"""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('cbb_refresh_verify.owner_probe.query_owners', lambda *_a, **_k: []) 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): from cbb_refresh_verify.maintenance_entry import assert_native_idle def query(names): assert 'icdb2ascii.exe' in [n.casefold() for n in names] and 'icdbnetserver.exe' in [n.casefold() for n in names] return [{'pid': 123456, 'name': 'icdb2ascii.exe', 'command': 'export'}] monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', 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()