"""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() def test_unrelated_same_name_server_does_not_prevent_copy_release(export_case, monkeypatch): import cbb_refresh_verify.native_engineering_identity as identity from cbb_refresh_verify.native_export_guard import prove_export_copies_released library, root, *_ = export_case monkeypatch.setattr(identity, '_process_snapshot', lambda: [ {'pid': 777777, 'name': 'iCDBNetServer.exe', 'parent': 0, 'executable': 'native', 'command': 'iCDBNetServer.exe C:\\other\\database'}]) with prove_export_copies_released(library) as copies: assert copies == [str(root/'project')] def test_retained_export_registry_is_scoped_to_its_library(tmp_path, monkeypatch): import cbb_refresh_verify.native_engineering_identity as identity from cbb_refresh_verify.native_export_guard import assert_retained_exports_idle from cbb_refresh_verify.library_lock import LibraryBusy library_a, library_b = tmp_path/'a.lmc', tmp_path/'b.lmc' monkeypatch.setattr(identity, '_retained_exports', [ (SimpleNamespace(poll=lambda: None), {}, {'library': str(library_a.resolve())})]) assert_retained_exports_idle(library_b) with pytest.raises(LibraryBusy): assert_retained_exports_idle(library_a) @pytest.mark.parametrize('created,blocked', [('20261113120000.000000+480', False), ('20261112120000.000000+480', True)]) def test_recorded_export_pid_reuse_requires_matching_creation_identity(export_case, monkeypatch, created, blocked): import cbb_refresh_verify.native_engineering_identity as identity import cbb_refresh_verify.library_lock as locks from cbb_refresh_verify.native_export_guard import prove_export_copies_released library, root, *_ = export_case path = root/'ascii-process.json' record = json.loads(path.read_text('utf-8')) record['process_identities'] = [{'pid': 123456, 'created': '20261112120000.000000+480', 'executable': 'native'}] path.write_text(json.dumps(record), encoding='utf-8') monkeypatch.setattr(locks, '_supervisor_alive', lambda _: True) monkeypatch.setattr(identity, '_process_snapshot', lambda: [ {'pid': 123456, 'name': 'unrelated.exe', 'parent': 0, 'executable': 'native', 'created': created, 'command': ''}]) if blocked: with pytest.raises(locks.LibraryBusy): with prove_export_copies_released(library): pass else: with prove_export_copies_released(library): pass @pytest.mark.parametrize('in_memory', [False, True]) def test_preexisting_process_misrecorded_as_descendant_does_not_retain_copy(export_case, monkeypatch, in_memory): import win32api, win32con from cbb_refresh_verify import native_engineering_identity as identity from cbb_refresh_verify.native_export_guard import prove_export_copies_released library, root, *_ = export_case record = dict(pid=123456, observed_pids=[123456, os.getpid()], process_identities=[ dict(pid=123456, created='20261112120000.000000+480', executable='native'), dict(pid=os.getpid(), created='20261111120000.000000+480', executable='other')]) (root/'ascii-process.json').write_text(json.dumps(record),'utf-8') monkeypatch.setattr(identity, '_process_snapshot', lambda: [dict(pid=os.getpid(), name='other.exe', parent=123456, created='20261111120000.000000+480', executable='other', command='')]) handle = win32api.OpenProcess(win32con.SYNCHRONIZE, False, os.getpid()) try: if in_memory: monkeypatch.setattr(identity, '_retained_exports', [(SimpleNamespace(pid=123456,poll=lambda: 0), {os.getpid(): handle}, dict(library=str(library),analysis_root=str(root)))]) with prove_export_copies_released(library) as copies: assert copies == [str(root/'project')] finally: handle.Close() @pytest.mark.parametrize('active', [False, True]) def test_unknown_checkpoint_requires_explicit_full_proof_and_no_native_export_owner(tmp_path, monkeypatch, active): import cbb_refresh_verify.native_engineering_identity as identity import cbb_refresh_verify.library_lock as locks from cbb_refresh_verify.native_export_guard import prove_export_copies_released library = tmp_path/'lib.lmc'; library.touch() locks.blocker_path(library).write_text('{torn metadata') monkeypatch.setattr(identity, '_retained_exports', []) monkeypatch.setattr(identity, '_process_snapshot', lambda: [ {'pid': 12345, 'name': 'iCDBNetServer.exe', 'parent': 0}] if active else []) with pytest.raises(locks.LibraryBusy): with prove_export_copies_released(library): pass if active: with pytest.raises(locks.LibraryBusy): with prove_export_copies_released(library, allow_unknown_checkpoint=True): pass else: with prove_export_copies_released(library, allow_unknown_checkpoint=True) as copies: assert copies == [] assert locks.blocker_path(library).read_text() == '{torn metadata' @pytest.mark.parametrize('no_start_proven', [False, True]) def test_missing_pid_requires_bound_no_start_evidence(export_case, no_start_proven): from cbb_refresh_verify.native_export_guard import prove_export_copies_released from cbb_refresh_verify.library_lock import LibraryBusy library, root, *_ = export_case record = {'success': False, 'safe_to_continue': True} if no_start_proven: record['native_started'] = False (root/'ascii-process.json').write_text(json.dumps(record), encoding='utf-8') (root/'export-launch.json').write_text(json.dumps({'started': not no_start_proven}), encoding='utf-8') if no_start_proven: with prove_export_copies_released(library): pass else: with pytest.raises(LibraryBusy): with prove_export_copies_released(library): pass