fix: keep cold Cell reads outside native mutation deadline

This commit is contained in:
阿白叔 committed 2026-10-19 15:28:31 +08:00
1 parent 4d1b825e4a
commit ec75445f44
7 files changed
+179 -13

No files matched your search

+18 -2
View File
@@ -36,9 +36,13 @@ def interrupted(tmp_path, monkeypatch):
library.write_text('library fixture')
catalog = SimpleNamespace(library_path=library, part_partition='library', part_number='NEW',
cells=(SimpleNamespace(partition='RES', name='CELL'),), source_fingerprint='source-proof')
catalog_reads = []
def read_catalog(*args, **kwargs):
catalog_reads.append(kwargs)
return catalog
monkeypatch.setitem(sys.modules, 'dx_productivity.trial_task_center.cell_catalog', SimpleNamespace(
project_library_path=lambda project: library,
read_library_cell_catalog=lambda *args, **kwargs: catalog))
read_library_cell_catalog=read_catalog))
project = tmp_path / 'project' / 'one.prj'
project.parent.mkdir()
project.write_text('project')
@@ -62,7 +66,8 @@ def interrupted(tmp_path, monkeypatch):
lock = handoff.command_path.parent / 'uncertain.flag'
lock.write_text('old timeout')
return SimpleNamespace(preparer=preparer, root=root, projects=projects, rules=rules, snapshot=snapshot,
job=job, handoff=handoff, lock=lock, report=report, catalog=catalog, cell_proof=cell_proof)
job=job, handoff=handoff, lock=lock, report=report, catalog=catalog, cell_proof=cell_proof,
catalog_reads=catalog_reads)
def invoke(fixture, **kwargs):
@@ -313,3 +318,14 @@ def test_cell_catalog_drift_blocks_recovery_before_worker(interrupted,fault):
assert calls==[]
assert interrupted.lock.exists()
assert interrupted.handoff.status_path.read_bytes()==before
def test_standalone_recovery_allows_cold_catalog_preflight_before_worker(interrupted):
interrupted.catalog_reads.clear()
run_worker = worker_result(interrupted)
def run(command, timeout):
assert interrupted.catalog_reads == [{'allow_cold_read': True}]
assert interrupted.lock.exists()
return run_worker(command, timeout)
interrupted.preparer._process_runner = run
assert invoke(interrupted).state == 'restored_ok'
+63
View File
@@ -92,6 +92,69 @@ def test_tampered_cache_evidence_is_rejected(library, tmp_path, reader):
assert second.evidence_path != first.evidence_path
@pytest.mark.parametrize('fault', ['absent', 'source_changed', 'digest', 'cleanup', 'malformed'])
def test_cache_only_read_rejects_unusable_proof_without_cold_work(library, tmp_path, reader, monkeypatch, fault):
root = tmp_path / 'out'
if fault != 'absent':
first = catalog.read_library_cell_catalog(library, 'PN', root)
if fault == 'source_changed':
(library.parent / 'CellDBLibs/RES.cel').write_bytes(b'changed')
elif fault == 'digest':
first.evidence_path.write_text('{}', encoding='utf-8')
else:
evidence = json.loads(first.evidence_path.read_text(encoding='utf-8'))
if fault == 'cleanup':
evidence['result']['cleanup']['processes'][0]['job_active_processes'] = 1
else:
evidence['result'] = []
catalog._write_json(first.evidence_path, evidence)
cache_path = next((root / 'cache').glob('*.json'))
cache = json.loads(cache_path.read_text(encoding='utf-8'))
cache['sha256'] = catalog._hash(first.evidence_path)
catalog._write_json(cache_path, cache)
reader.clear()
cold_calls = []
def forbid_clone(*args):
cold_calls.append(args)
raise AssertionError('cache-only validation must not clone or launch a reader')
monkeypatch.setattr(catalog, '_clone_library', forbid_clone)
reads_before = set(root.glob('reads/*'))
with pytest.raises(ValueError, match='请在料号规则中重新读取目标封装'):
catalog.read_library_cell_catalog(library, 'PN', root, allow_cold_read=False)
assert not reader and not cold_calls
assert set(root.glob('reads/*')) == reads_before
def test_cache_only_read_reuses_valid_proof_and_rehashes_source_twice(library, tmp_path, reader, monkeypatch):
root = tmp_path / 'out'
first = catalog.read_library_cell_catalog(library, 'PN', root, partition='RES')
original_manifest = catalog._library_manifest
sources = []
def manifest(path):
sources.append(path)
return original_manifest(path)
monkeypatch.setattr(catalog, '_library_manifest', manifest)
assert catalog.read_library_cell_catalog(library, 'PN', root, partition='RES', allow_cold_read=False) == first
assert sources == [library.resolve(), library.resolve()]
assert len(reader) == 1
def test_cache_only_read_rejects_source_change_during_final_rehash(library, tmp_path, reader, monkeypatch):
root = tmp_path / 'out'
catalog.read_library_cell_catalog(library, 'PN', root)
original_manifest = catalog._library_manifest
calls = []
def manifest(path):
calls.append(path)
if len(calls) == 2:
(library.parent / 'CentLib.prp').write_bytes(b'changed')
return original_manifest(path)
monkeypatch.setattr(catalog, '_library_manifest', manifest)
with pytest.raises(ValueError, match='请在料号规则中重新读取目标封装'):
catalog.read_library_cell_catalog(library, 'PN', root, allow_cold_read=False)
assert len(calls) == 2 and len(reader) == 1
@pytest.mark.parametrize('cells', [[], [{'partition':'A','name':'same'}, {'partition':'B','name':'same'}]])
def test_zero_or_ambiguous_cells_are_not_authoritative(library, tmp_path, monkeypatch, cells):
def run(clone, part, partition, root):
+75 -2
View File
@@ -99,7 +99,7 @@ def test_actual_project_library_catalog_controls_choice(tmp_path,monkeypatch,cho
app=SimpleNamespace(GetProjectData=lambda:SimpleNamespace(CentralLibraryPath=str(library)))
captured=[]
def read(path,part,evidence_root,**kwargs):
captured.append((path,part))
captured.append((path,part,kwargs))
return SimpleNamespace(library_path=library,part_partition='RESISTOR',part_number='NEW',
cells=(SimpleNamespace(partition='RES',name='CELL_OK'),),source_fingerprint='fingerprint',evidence_path=tmp_path/'proof.json')
monkeypatch.setitem(sys.modules,'dx_productivity.trial_task_center.cell_catalog',SimpleNamespace(read_library_cell_catalog=read))
@@ -110,7 +110,80 @@ def test_actual_project_library_catalog_controls_choice(tmp_path,monkeypatch,cho
proof=native_helper.target_cell_catalog(app,tmp_path/'snapshot.tsv',['M','project','OLD','NEW','sheet'],choice)
assert proof['selected']=='CELL_OK' and proof['source_fingerprint']=='fingerprint'
assert proof['library_path']==str(library.resolve())
assert captured==[(library,'NEW')]
assert captured==[(library,'NEW',{'allow_cold_read':False})]
@pytest.mark.parametrize('fail_at', [1, 2])
def test_native_catalog_checks_cannot_cold_read_or_submit_on_miss(tmp_path, monkeypatch, fail_at):
import ctypes
import sys
snapshot = tmp_path / 'snapshot.tsv'
snapshot.write_text('M\tproject\tOLD\tNEW\tsheet\tpreserve\nL\tCELL_OK\nC\tuid\tR1\t0\t0\t0\t1\tpins\n')
library = tmp_path / 'lib.lmc'
app = SimpleNamespace(ActiveViewHandle=1, GetProjectData=lambda: SimpleNamespace(
CentralLibraryPath=str(library), GetSlotsCount=lambda *args: 1))
components = [SimpleNamespace(UID='uid', Refdes='R1')]
reads, submits = [], []
def read(path, part, evidence_root, **kwargs):
reads.append((path, part, kwargs))
if len(reads) == fail_at:
raise ValueError('请在料号规则中重新读取目标封装')
return SimpleNamespace(library_path=library, part_partition='RESISTOR', part_number='NEW',
cells=(SimpleNamespace(partition='RES', name='CELL_OK'),), source_fingerprint='fingerprint')
monkeypatch.setitem(sys.modules, 'dx_productivity.trial_task_center.cell_catalog',
SimpleNamespace(read_library_cell_catalog=read))
constants = SimpleNamespace(WM_COMMAND=0x111, WM_GETTEXT=0xD, WM_SETTEXT=0xC,
WM_LBUTTONDOWN=0x201, WM_LBUTTONUP=0x202, WM_LBUTTONDBLCLK=0x203, SMTO_ABORTIFHUNG=2)
opened = []
def post_message(handle, code, *args):
if code == constants.WM_COMMAND:
opened.append(True)
def enum_windows(callback, _):
for handle in ([1, 2, 3, 4] if opened else [1]):
callback(handle, None)
def message(handle, code, wparam, lparam, *args):
if code == constants.WM_GETTEXT:
value = {1001: 'NEW', 1701: 'RES:symbol'}.get(handle, 'option')
buffer = ctypes.create_unicode_buffer(value)
ctypes.memmove(lparam, buffer, ctypes.sizeof(buffer))
elif code == 0xF5 and handle == 1695:
submits.append(handle)
gui = SimpleNamespace(error=RuntimeError, GetAncestor=lambda *args: 1, EnumWindows=enum_windows,
EnumChildWindows=lambda *args: None, IsWindowVisible=lambda handle: True,
GetClassName=lambda handle: {2: '#32770', 3: 'SysListView32', 4: 'Edit'}.get(handle, 'Main'),
GetDlgItem=lambda handle, identifier: identifier, IsWindowEnabled=lambda handle: True,
GetDlgCtrlID=lambda handle: {3: 4000, 4: 4006}.get(handle, 0),
SendMessage=lambda *args: 1, SendMessageTimeout=message, PostMessage=post_message,
GetWindowRect=lambda handle: (0, 0, 500, 500), ScreenToClient=lambda handle, point: point,
IsWindow=lambda handle: True)
row = SimpleNamespace(children=lambda **kwargs: [SimpleNamespace(window_text=lambda value=value: value)
for value in ['RESISTOR', 'NEW', 'RES:symbol', '', 'part', 'label']],
rectangle=lambda: SimpleNamespace(left=0, right=200, top=10, bottom=20, height=lambda: 10))
monkeypatch.setitem(sys.modules, 'win32api', SimpleNamespace(
OpenProcess=lambda *args: SimpleNamespace(Close=lambda: None)))
monkeypatch.setitem(sys.modules, 'win32con', constants)
monkeypatch.setitem(sys.modules, 'win32gui', gui)
monkeypatch.setitem(sys.modules, 'win32process', SimpleNamespace(
GetWindowThreadProcessId=lambda handle: (1, 2), GetModuleFileNameEx=lambda *args: 'viewdraw.exe'))
monkeypatch.setitem(sys.modules, 'pywinauto', SimpleNamespace(Desktop=lambda **kwargs: SimpleNamespace(
window=lambda **kwargs: SimpleNamespace(descendants=lambda **kwargs: [row]))))
monkeypatch.setattr(native_helper, 'attach', lambda: (app, object()))
monkeypatch.setattr(native_helper, 'check_active_context', lambda *args: None)
for name in ('components_on_sheet', 'select_snapshot_batch', 'check_context'):
monkeypatch.setattr(native_helper, name, lambda *args, **kwargs: components)
monkeypatch.setattr(native_helper, 'attribute_value', lambda *args: 'OLD')
monkeypatch.setattr(native_helper, 'selection', lambda *args: None)
monkeypatch.setattr(native_helper, 'replacement_command_from_resources', lambda *args: 33977)
monkeypatch.setattr(native_helper, 'wait_for', lambda callback, *args, **kwargs: callback())
monkeypatch.setattr(native_helper, 'wait_for_library_rows', lambda callback, *args: callback())
monkeypatch.setattr(native_helper, 'wait_for_native_target', lambda callback, *args: callback())
report = {}
with pytest.raises(ValueError, match='重新读取目标封装'):
native_helper.run_native(snapshot, report)
assert reads == [(library, 'NEW', {'allow_cold_read': False})] * fail_at
assert not submits
assert 'transaction' not in report and 'stage' not in report
def test_legacy_recovery_evidence_cannot_upgrade_without_explicit_cell(tmp_path):