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

+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()