fix: preserve unknown assets and retained export-copy ownership

This commit is contained in:
阿白叔 committed 2026-11-03 12:24:54 +08:00
1 parent 55a82fdc5f
commit f21781f170
8 files changed
+312 -10

No files matched your search

+4
View File
@@ -17,3 +17,7 @@ The subsequent `mentor795-native-content-v1` contract requires pinned native hie
The real management engine now captures a source baseline before any removal. Native Add requires a prepared transaction binding the verified full backup, staged source, baseline proof, exact target/name/partition, supervisor and exclusive lease. After normal native release, it corrects imported PRJ/PCB library references using the existing documented text helpers, reopens the exact native catalog and compares a target-only identity. Update remains remove plus Add; failures retain the recovery snapshot and checkpoint. The UI action is explicitly labeled “用工程替换已选 CBB…(原生重新导入)”; backup Work restoration is unchanged.
Coordinator-native source/registered capture matched all three exports and primary assets after correcting the observed imported PCB reference; original source manifests were unchanged. Implementation verification remains file-only: 114 focused tests passed before the final bootstrap/lease refinement. `create_owned_fixture` and `run_owned_fixture_management` provide a token-bound empty-library/real-engine route for the coordinator's actual CRUD cycle. Production Add/Update remain disabled until that separate acceptance and promotion step.
The coordinator's native engine cycle subsequently passed empty-library creation, Add A, duplicate refusal, same-name replacement by B (with a different verified layout hash), removal with strict absence, and reimport from a complete backup. Every operation reported safe native release and both original source manifests stayed unchanged; evidence is under `diagnostics/issue2-native-crud-20261103/engine-e2e`.
Final safety review narrowed the additional iCDB runtime exclusions to known log directories, exact events files and the observed dated GUID log filenames. Unknown `cdbsvr` content remains primary, including unknown events/plog files, and a registered unknown-file change now requires recovery. Export capture binds its analysis copy to the existing library checkpoint before launch. That binding survives retention/restart and cannot be cleared by release or maintenance adoption until recorded processes/child handles have exited, known exporter/server processes are absent, copied addresses are absent and copied database files can be held exclusively. Missing/malformed ownership evidence remains blocked. The final focused safety/engine suite passed 167 tests; no native operations or full-suite run were performed by the implementation agent. Production promotion remains a separate reviewed change.
+15 -4
View File
@@ -66,8 +66,11 @@ def has_blocker(library):
def _persist_blocker(library, status='OWNER_RELEASE_UNCONFIRMED', *, lease_id):
path = blocker_path(library)
pending = path.with_suffix('.pending')
previous = checkpoint_record(path)
export_record = ({'export_analysis': previous['export_analysis']}
if previous and previous['lease_id'] == lease_id and 'export_analysis' in previous else {})
with pending.open('w', encoding='utf-8') as stream:
json.dump({'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
json.dump({**export_record, 'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
'lease_id': lease_id, 'library': str(library), 'status': status,
'pid': os.getpid(), 'time': datetime.now(timezone.utc).isoformat()}, stream)
stream.flush(); os.fsync(stream.fileno())
@@ -159,6 +162,9 @@ class LibraryLock:
if not self.entered:
return
owner = _owners[self.key]
checkpoint = checkpoint_record(blocker_path(self.library))
if checkpoint is not None and 'export_analysis' in checkpoint:
owner['retained'] = True
if self.safe_to_release is not None:
try:
safe = self.safe_to_release() is True
@@ -237,7 +243,8 @@ def _enter_maintenance(lease):
0, None, win32con.OPEN_ALWAYS, win32con.FILE_ATTRIBUTE_NORMAL, None)
# All target/process/address/exclusive-file checks finish BEFORE
# any old checkpoint replacement. Keep the exact sidecar open.
with lease.maintenance_guard() as proof:
from .native_export_guard import prove_export_copies_released
with prove_export_copies_released(lease.library), lease.maintenance_guard() as proof:
if (marker.read_bytes() if marker.exists() else None) != old:
raise LibraryBusy('维护检查期间检查点变化')
if old is not None:
@@ -284,6 +291,9 @@ def _prove_library_released(library):
import pythoncom, win32com.client, win32con, win32file
from .scoped_manifest import scan_tree
from .native_management import _retained_workers
from .native_export_guard import assert_retained_exports_idle, prove_export_copies_released
from .native_engineering_identity import _OWNER_NAMES
assert_retained_exports_idle()
if any(worker.poll() is None for worker in _retained_workers):
raise LibraryBusy('原生管理工作进程尚未返回,不能解除协调阻止。')
from .com_runtime import initialize_com, uninitialize_com
@@ -291,7 +301,7 @@ def _prove_library_released(library):
try:
service = win32com.client.GetObject('winmgmts:')
names = ('LibraryManager.exe', 'ExpeditionPCB.exe', 'viewdraw.exe',
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe')
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe', *sorted(_OWNER_NAMES))
query = 'SELECT ProcessId, Name FROM Win32_Process WHERE ' + ' OR '.join(
f"Name='{name}'" for name in names)
owners = [{'pid': int(item.ProcessId), 'name': str(item.Name)} for item in service.ExecQuery(query)]
@@ -307,11 +317,12 @@ def _prove_library_released(library):
if Path(library).resolve() not in native:
raise LibraryBusy('目标库身份缺失,不能解除协调阻止。')
with ExitStack() as stack:
export_copies = stack.enter_context(prove_export_copies_released(library))
for path in native:
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
yield {'native_owners': owners, 'addresses': addresses,
yield {'native_owners': owners, 'addresses': addresses, 'export_copies': export_copies,
'exclusive_files': [str(path) for path in native]}
finally:
uninitialize_com(initialized)
+4 -1
View File
@@ -15,11 +15,14 @@ from uuid import uuid4
def assert_native_idle():
import win32com.client
from .native_management import _retained_workers
from .native_export_guard import assert_retained_exports_idle
from .native_engineering_identity import _OWNER_NAMES
assert_retained_exports_idle()
if any(worker.poll() is None for worker in _retained_workers):
raise ValueError('MAINTENANCE_OWNER_ACTIVE: 管理工作进程尚未返回')
names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'viewdraw.exe', 'iCDBProjectBackup.exe',
'ReuseBlockImporter.exe', 'CleanWGLib.exe', 'cscript.exe', 'wscript.exe',
'python.exe', 'pythonw.exe', 'CbbRefreshVerify.exe')
'python.exe', 'pythonw.exe', 'CbbRefreshVerify.exe', *sorted(_OWNER_NAMES))
service = win32com.client.GetObject('winmgmts:')
query = 'SELECT ProcessId, Name, CommandLine FROM Win32_Process WHERE ' + ' OR '.join(
f"Name='{name}'" for name in names)
@@ -203,7 +203,17 @@ def asset_identity(source, expected_library):
assets = {}
for relative, record in files.items():
path = root/relative
if path == main_database/'icdb.dat' or any(path.is_relative_to(p) for p in runtime):
known_runtime = False
for server_root in runtime:
if not path.is_relative_to(server_root): continue
parts = path.relative_to(server_root).parts
folded = tuple(p.casefold() for p in parts)
known_runtime = (len(parts) > 1 and folded[0] in ('log', 'dbcheck', 'dbrestore', 'dbupgrade', 'pimlog')
or folded in (('events', 'events.dat'), ('events', 'events.idx'))
or len(parts) == 2 and folded[0] == 'plog'
and re.fullmatch(r'\d{4}\.\d{2}\.\d{2}\.guid\.\d+\.txt', parts[1]) is not None)
break
if path == main_database/'icdb.dat' or known_runtime:
continue
if path in projects:
data = _normalized_project(path, expected_library)
@@ -273,6 +283,7 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
"""Observe exact exporter/descendant handles; never kill a database owner."""
import win32api, win32con, win32event, pywintypes
root = Path(root)
_write_json(root/'export-launch.json', {'started': False})
before = _process_snapshot()
if any(p['name'].casefold() in _OWNER_NAMES for p in before):
return {'success': False, 'safe_to_continue': False, 'detail': 'An existing iCDB owner prevents isolated identity export.'}
@@ -300,6 +311,7 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
try:
deadline = time.monotonic()+float(timeout_seconds)
with (root/(kind+'-stdout.txt')).open('wb') as output:
_write_json(root/'export-launch.json', {'started': True})
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW)
record['pid'] = process.pid
@@ -348,6 +360,7 @@ def capture_identity(source, evidence_root, *, expected_library, owner_library,
from .backup_recovery import _align_library
from .library_lock import LibraryLock, owned_snapshot
from .scoped_manifest import copy_verified
from .native_export_guard import begin_export_analysis, finish_export_analysis
import win32event, win32con
source, pcb, top = source_project(source)
root = Path(evidence_root).absolute()
@@ -375,10 +388,13 @@ def capture_identity(source, evidence_root, *, expected_library, owner_library,
_align_library(clone, clone_pcb, Path(expected_library))
if any((root/'project').rglob('sAddress.adr')):
raise ValueError('Analysis source contains an unresolved database address.')
export_token = begin_export_analysis(library, root, clone)
owner_safe = False
native = _run_exports(clone, root, mentor_home, timeout_seconds)
owner_safe = native.get('safe_to_continue') is True
_write_json(root/'native-outcome.json', native)
if native.get('safe_to_continue') is True:
finish_export_analysis(library, export_token)
owner_safe = True
if not owner_safe or not native.get('success'):
outcome = IdentityOutcome(None, owner_safe, native.get('detail', 'Native export failed.'), root)
else:
@@ -0,0 +1,117 @@
"""Export-copy ownership bound to the existing per-library lease checkpoint."""
from contextlib import contextmanager, ExitStack
import json
from pathlib import Path
from uuid import uuid4
from .management import _write_json
def assert_retained_exports_idle():
import win32con, win32event
from .native_engineering_identity import _retained_exports
from .library_lock import LibraryBusy
for process, handles in _retained_exports:
if process.poll() is None or any(win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_OBJECT_0
for handle in handles.values()):
raise LibraryBusy('Native identity exporter or descendant has not released.')
def begin_export_analysis(library, root, project):
from .library_lock import _guard, blocker_path, checkpoint_record, LibraryBusy
from .management_transaction import current_lease
library, root, project = Path(library).resolve(), Path(root).resolve(), Path(project).resolve()
owner = current_lease(library)
if (project.parent != root/'project' or not project.is_file()
or root.is_relative_to(library.parent) or library.parent.is_relative_to(root)):
raise LibraryBusy('Export-copy ownership paths are not independent and exact.')
record = {'protocol': 'cbb-native-export-analysis', 'version': 1, 'token': uuid4().hex,
'library': str(library), 'lease_id': owner['lease_id'], 'supervisor_pid': owner['supervisor_pid'],
'analysis_root': str(root), 'project': str(project)}
with _guard:
marker = blocker_path(library)
checkpoint = checkpoint_record(marker)
if (checkpoint is None or checkpoint['lease_id'] != owner['lease_id']
or 'export_analysis' in checkpoint):
raise LibraryBusy('A prior export analysis is unresolved or the lease changed.')
_write_json(root/'export-owner.json', record)
_write_json(marker, {**checkpoint, 'export_analysis': [record]})
return record['token']
@contextmanager
def prove_export_copies_released(library):
"""Fresh process and exclusive-copy proof, including after interpreter exit."""
import win32file, win32con, pywintypes
from .library_lock import blocker_path, checkpoint_record, _supervisor_alive, LibraryBusy
from .native_engineering_identity import _process_snapshot, _OWNER_NAMES
from .scoped_manifest import scan_tree
assert_retained_exports_idle()
library = Path(library).resolve()
marker = blocker_path(library)
checkpoint = checkpoint_record(marker)
if marker.exists() and checkpoint is None:
raise LibraryBusy('Invalid library checkpoint cannot release export ownership.')
if checkpoint is None or 'export_analysis' not in checkpoint:
yield []
return
records = checkpoint['export_analysis']
if not isinstance(records, list) or not records:
raise LibraryBusy('Invalid export-analysis ownership record.')
owners = [p for p in _process_snapshot() if p['name'].casefold() in _OWNER_NAMES]
if owners: raise LibraryBusy(f'Native identity owners remain active: {owners}')
copies = []
with ExitStack() as stack:
for record in records:
try:
root, project = Path(record['analysis_root']), Path(record['project'])
if (record.get('protocol') != 'cbb-native-export-analysis' or record.get('version') != 1
or not record.get('token') or record['lease_id'] != checkpoint['lease_id']
or record['supervisor_pid'] != checkpoint['pid']
or Path(record['library']).resolve() != library
or not root.is_absolute() or not project.is_absolute() or root.resolve() != root
or project.parent != root/'project' or not project.is_file()
or root.resolve().is_relative_to(library.parent)
or library.parent.is_relative_to(root.resolve())
or json.loads((root/'export-owner.json').read_text(encoding='utf-8')) != record):
raise ValueError('Export record does not match the exact library, lease and copy.')
processes = [root/(kind+'-process.json') for kind in ('ascii', 'csv', 'edif')
if (root/(kind+'-process.json')).exists()]
if not processes:
launch = json.loads((root/'export-launch.json').read_text(encoding='utf-8'))
if launch != {'started': False}:
raise ValueError('Export launch has no confirmed process record.')
for path in processes:
process = json.loads(path.read_text(encoding='utf-8'))
pids = process.get('observed_pids', []) + [process['pid']]
if any(not isinstance(pid, int) or pid <= 0 for pid in pids):
raise ValueError('Invalid export process identity.')
if any(_supervisor_alive(pid) for pid in pids):
raise LibraryBusy('A recorded export process or descendant remains alive.')
entries = scan_tree(root/'project')
if any(path.name.casefold() == 'saddress.adr' for path in entries):
raise LibraryBusy('The retained analysis copy still has a database address.')
databases = [path for path in entries if path.is_file()
and path.name.casefold() in ('icdb.dat', 'layoutdb.lyt')]
if not any(path.name.casefold() == 'icdb.dat' for path in databases):
raise ValueError('The recorded analysis database is missing.')
for path in databases:
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
stack.callback(handle.Close)
copies.append(str(root/'project'))
except (KeyError, TypeError, ValueError, OSError, pywintypes.error) as error:
raise LibraryBusy(f'Export analysis release is not proven: {error}') from error
yield copies
def finish_export_analysis(library, token):
from .library_lock import _guard, blocker_path, checkpoint_record, LibraryBusy
with _guard, prove_export_copies_released(library):
marker = blocker_path(library)
checkpoint = checkpoint_record(marker)
records = checkpoint.get('export_analysis', []) if checkpoint else []
if len(records) != 1 or records[0].get('token') != token:
raise LibraryBusy('Export ownership changed before confirmed cleanup.')
del checkpoint['export_analysis']
_write_json(marker, checkpoint)
+7 -3
View File
@@ -56,7 +56,10 @@ def transaction(tmp_path, monkeypatch):
text = pcb_project.read_text()
import re
pcb_project.write_text(re.sub(r'KEY CentralLibrary "[^"]*"', 'KEY CentralLibrary "wrong-relative.lmc"', text))
if state['corrupt']: (work/'PCB/Layout/LayoutDB.lyt').write_bytes(b'wrong physical design')
if state['corrupt'] == 'unknown_cdbsvr':
unknown = work/'database/cdbsvr/persistent.dat'; unknown.parent.mkdir(parents=True, exist_ok=True)
unknown.write_bytes(b'unexpected engineering content')
elif state['corrupt']: (work/'PCB/Layout/LayoutDB.lyt').write_bytes(b'wrong physical design')
state['entries'] = [{'name': job['name'], 'partition': job['partition'],
'engineering_identity': engineering_identity(work/staged.name)}]
return {'success': True, 'safe_to_continue': True, 'identity_matches': False}
@@ -99,9 +102,10 @@ def test_owned_fixture_engine_add_conflict_update_remove_and_identity(transactio
assert request.source.read_bytes() == original
def test_native_registered_but_asset_mismatch_retains_recovery(transaction):
@pytest.mark.parametrize('corrupt', [True, 'unknown_cdbsvr'])
def test_native_registered_but_asset_mismatch_retains_recovery(transaction, corrupt):
root, request, state = transaction
state['corrupt'] = True
state['corrupt'] = corrupt
result = execute(root, request)
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
+29
View File
@@ -72,6 +72,33 @@ def test_assets_require_correct_library_references_and_unknown_bytes(project):
asset_identity(source, library)
@pytest.mark.parametrize('relative', ['database/cdbsvr/persistent.dat',
'database/cdbsvr/new-engineering/config.bin', 'database/cdbsvr/events/custom.dat',
'database/cdbsvr/plog/unknown-engineering.bin'])
def test_unknown_cdbsvr_assets_remain_part_of_identity(project, relative):
from cbb_refresh_verify.native_engineering_identity import asset_identity
source, library = project
baseline = asset_identity(source, library)
unknown = source.parent/relative; unknown.parent.mkdir(parents=True, exist_ok=True)
unknown.write_bytes(b'first engineering content')
added = asset_identity(source, library)
assert added != baseline
unknown.write_bytes(b'changed engineering content')
assert asset_identity(source, library) != added
unknown.unlink()
assert asset_identity(source, library) == baseline
def test_observed_guid_and_events_runtime_does_not_change_identity(project):
from cbb_refresh_verify.native_engineering_identity import asset_identity
source, library = project
baseline = asset_identity(source, library)
for relative in ['database/cdbsvr/plog/2026.11.03.guid.48432.txt',
'database/cdbsvr/events/events.dat', 'database/cdbsvr/events/events.idx']:
path = source.parent/relative; path.parent.mkdir(parents=True, exist_ok=True); path.write_bytes(b'runtime')
assert asset_identity(source, library) == baseline
@pytest.mark.parametrize('failure', ['empty', 'missing_completion', 'error', 'exit'])
def test_export_evidence_requires_successful_complete_native_output(tmp_path, failure):
from cbb_refresh_verify.native_engineering_identity import validate_export_output
@@ -94,11 +121,13 @@ def test_capture_only_exports_fresh_copy_and_leaves_source_unchanged(project, tm
source, library = project
original = build_manifest(source.parent)
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
def exports(clone, root, *_):
assert clone.parent == root/'project' and clone != source
(clone.parent/'database/icdb.dat').write_bytes(b'export changed disposable copy')
(root/'design.rpt').write_bytes(ascii_report())
(root/'design.edf').write_bytes(edif_report())
(root/'export-launch.json').write_text('{"started": false}')
return {'success': True, 'safe_to_continue': True, 'detail': ''}
monkeypatch.setattr(identity, '_run_exports', exports)
monkeypatch.setattr(identity, 'csv_identity', lambda _: {'work/identity': 'csv proof'})
+118
View File
@@ -0,0 +1,118 @@
"""Fresh release/adoption proof for retained export copies; no native launch."""
from contextlib import contextmanager
import json
import os
from types import SimpleNamespace
import pytest
@pytest.fixture
def export_case(tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.native_engineering_identity as identity
import win32com.client
monkeypatch.setattr(win32com.client, 'GetObject', lambda *_: SimpleNamespace(ExecQuery=lambda *_: []))
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
monkeypatch.setattr(identity, '_retained_exports', [])
monkeypatch.setattr(locks, '_supervisor_alive', lambda _: False)
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.write_bytes(b'original library')
root = tmp_path/'analysis'; (root/'project/database').mkdir(parents=True)
source = root/'project/Source.prj'; source.write_bytes(b'copied project')
(root/'project/database/icdb.dat').write_bytes(b'copied database')
lease = locks.LibraryLock(library, safe_to_release=lambda: False)
with lease:
from cbb_refresh_verify.native_export_guard import begin_export_analysis
token = begin_export_analysis(library, root, source)
(root/'ascii-process.json').write_text(json.dumps({'pid': 123456, 'observed_pids': [123456],
'command': ['icdb2ascii.exe'], 'safe_to_continue': False}))
yield library, root, token, lease
with locks._guard:
owner = locks._owners.pop(lease.key, None)
if owner: owner['handle'].Close()
locks.blocker_path(library).unlink(missing_ok=True)
@pytest.mark.parametrize('action', ['release', 'maintenance'])
@pytest.mark.parametrize('obstacle', ['active_exporter', 'active_child', 'copy_address', 'copy_exclusive', 'invalid_record', 'missing_copy'])
def test_release_and_takeover_cannot_bypass_export_copy(export_case, monkeypatch, tmp_path, action, obstacle):
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.native_engineering_identity as identity
import win32api, win32con, win32file
library, root, token, lease = export_case
handle = None
if obstacle == 'active_exporter':
# Restart case: no in-memory exporter, but a known native owner remains.
monkeypatch.setattr(identity, '_process_snapshot', lambda: [
{'pid': 123456, 'name': 'iCDBNetServer.exe', 'parent': 0, 'executable': 'native'}])
if obstacle == 'active_child':
handle = win32api.OpenProcess(win32con.SYNCHRONIZE, False, os.getpid())
monkeypatch.setattr(identity, '_retained_exports', [(SimpleNamespace(poll=lambda: 0), {os.getpid(): handle})])
if obstacle == 'copy_address':
address = root/'project/database/cdbsvr/sAddress.adr'; address.parent.mkdir(); address.write_bytes(b'copy owner')
if obstacle == 'copy_exclusive':
handle = win32file.CreateFile(str(root/'project/database/icdb.dat'), win32con.GENERIC_READ,
0, None, win32con.OPEN_EXISTING, 0, None)
if obstacle == 'invalid_record': (root/'export-owner.json').write_text('{invalid')
if obstacle == 'missing_copy': (root/'project/database/icdb.dat').unlink()
@contextmanager
def target_guard(): yield {'target': 'file-only maintenance proof'}
try:
marker = locks.blocker_path(library); before = marker.read_bytes()
with pytest.raises((ValueError, OSError)):
if action == 'release': locks.release_retained_library(library, tmp_path/'release')
else:
with locks.LibraryLock.for_maintenance(library, tmp_path/'takeover', target_guard,
safe_to_release=lambda: True): pass
assert marker.read_bytes() == before
assert lease.path.exists()
finally:
if handle: handle.Close()
@pytest.mark.parametrize('action', ['release', 'maintenance'])
def test_restarted_export_copy_can_release_only_after_fresh_proof(export_case, tmp_path, action):
import cbb_refresh_verify.library_lock as locks
library, root, token, lease = export_case
# Simulate interpreter exit: all process-local registries/lease handles lost.
with locks._guard: locks._owners.pop(lease.key)['handle'].Close()
@contextmanager
def target_guard(): yield {'target': 'file-only maintenance proof'}
if action == 'release':
assert locks.release_retained_library(library, tmp_path/'release')['status'] == 'RELEASE_CONFIRMED'
else:
with locks.LibraryLock.for_maintenance(library, tmp_path/'takeover', target_guard,
safe_to_release=lambda: True): pass
assert not locks.blocker_path(library).exists()
assert (root/'project/database/icdb.dat').read_bytes() == b'copied database'
def test_maintenance_idle_guard_recognizes_new_exporter_names(monkeypatch):
import win32com.client
from cbb_refresh_verify.maintenance_entry import assert_native_idle
def query(sql):
assert 'icdb2ascii.exe' in sql.casefold() and 'icdbnetserver.exe' in sql.casefold()
return [SimpleNamespace(ProcessId=123456, Name='icdb2ascii.exe', CommandLine='export')]
monkeypatch.setattr(win32com.client, 'GetObject', lambda *_: SimpleNamespace(ExecQuery=query))
with pytest.raises(ValueError, match='MAINTENANCE_OWNER_ACTIVE'): assert_native_idle()
def test_successful_export_clears_only_its_bound_guard_after_fresh_copy_proof(tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.native_engineering_identity as identity
from cbb_refresh_verify.native_export_guard import begin_export_analysis, finish_export_analysis
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
monkeypatch.setattr(identity, '_retained_exports', [])
monkeypatch.setattr(locks, '_supervisor_alive', lambda _: False)
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
root = tmp_path/'analysis'; (root/'project/database').mkdir(parents=True)
project = root/'project/Source.prj'; project.touch()
(project.parent/'database/icdb.dat').write_bytes(b'copied db')
with locks.LibraryLock(library):
token = begin_export_analysis(library, root, project)
marker = locks.blocker_path(library)
assert json.loads(marker.read_text())['export_analysis'][0]['token'] == token
(root/'export-launch.json').write_text('{"started": false}')
finish_export_analysis(library, token)
assert 'export_analysis' not in json.loads(marker.read_text())
assert not marker.exists()