From ec75445f449b0121cd47ea409c9b65408ff6000c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Mon, 19 Oct 2026 15:28:31 +0800 Subject: [PATCH] fix: keep cold Cell reads outside native mutation deadline --- docs/user/target-cell-selection.md | 6 +- .../trial_task_center/cell_catalog.py | 13 +++- .../trial_task_center/native_helper.py | 7 +- .../trial_task_center/recovery.py | 6 +- tests/trial_task_center/test_recovery.py | 20 ++++- tests/v1_1/test_cell_catalog.py | 63 +++++++++++++++ tests/v1_1/test_target_cell_execution.py | 77 ++++++++++++++++++- 7 files changed, 179 insertions(+), 13 deletions(-) diff --git a/docs/user/target-cell-selection.md b/docs/user/target-cell-selection.md index 3b41f2a..61f0edb 100644 --- a/docs/user/target-cell-selection.md +++ b/docs/user/target-cell-selection.md @@ -8,7 +8,7 @@ 1. 创建工程任务,打开顶部 **本批料号规则**,添加或编辑旧、新料号。 2. 点击 **读取封装**,等待后台读取中央库。在 **目标封装** 下拉框中明确选择一项;只有一个候选时也需要选择。 -3. 保存规则。直接采集位号或导入 BOM,检查位号计划的 **目标封装**,再保存计划并执行。 +3. 保存规则,在 **本批料号规则** 中核对对应旧、新料号的 **目标封装**。直接采集位号或导入 BOM,保存计划后执行。 也可以先导入并保存 BOM,再添加与计划中旧、新料号一致的规则并选择封装。相同映射中尚未选择封装的计划行会补齐;已有独立选择、自定义 Value、NC 和位号勾选会保留。手动修改计划的新料号后,原封装选择会清空,需要在对应规则中重新配置。 @@ -18,8 +18,10 @@ 读取期间可以继续操作界面。更换新料号、改变工程范围或关闭弹窗后,旧请求返回的结果不会覆盖新选择。失败后可以再次点击 **读取封装**。已有 Library Manager 正在运行时,请关闭它后重试候选读取。 -工具通过中央库副本读取关联,不打开原库进行编辑。首次读取可能较慢;本机样例冷读取约 84 秒,缓存命中约 2~4 秒,其他机器和库不保证相同时间。执行前仍会核对实际工程的当前库,候选或库发生变化时会停止。 +工具通过中央库副本读取关联,不打开原库进行编辑。首次读取可能较慢;本机样例冷读取约 84 秒,缓存命中约 2~4 秒,其他机器和库不保证相同时间。执行前和原生替换提交前都只复用已核验缓存,并重新核对实际工程的完整源库指纹与所选候选。缓存缺失、损坏或源库变化时,会在替换提交前停止,提示 **请在料号规则中重新读取目标封装**;重新读取并核对选择后再执行。 替换后显式写入选定的 Cell Name,并在保存前和磁盘重开后检查有效值。成功日志包含 `Target Cell verified` 及所选封装。属性写入、保存或回读不符合要求时,不会给出已保存成功结果。 有中断或状态不确定的旧轮次时,先使用原版本完成核验恢复再升级。旧记录没有显式封装证据时,新流程不会把它自动认定为封装核验成功。 + +当前版本的中断任务仍保持保护时,规则编辑可能被锁定。使用 **核验恢复** 后,工具会在启动恢复 CAD 前独立预检封装;缓存被删除或失效时,可通过库副本重新读取,沿用读取器的互斥等待和工作进程超时限制。预检必须与原事务的源库、指纹、料号、分区、完整候选及封装选择完全一致;不一致或读取失败时保留保护,不启动恢复 CAD。原生替换过程仍只允许复用已核验缓存。 diff --git a/src/dx_productivity/trial_task_center/cell_catalog.py b/src/dx_productivity/trial_task_center/cell_catalog.py index 2ced45c..64dcb87 100644 --- a/src/dx_productivity/trial_task_center/cell_catalog.py +++ b/src/dx_productivity/trial_task_center/cell_catalog.py @@ -172,7 +172,8 @@ def _dispose_clone(root): _write_json(root / 'clone-cleanup.json', {'path': str(target), 'removed': not target.exists()}) -def read_library_cell_catalog(library_path: Path, part_number: str, evidence_root: Path, *, partition: str | None = None) -> CellCatalog: +def read_library_cell_catalog(library_path: Path, part_number: str, evidence_root: Path, *, + partition: str | None = None, allow_cold_read: bool = True) -> CellCatalog: library = Path(library_path).resolve() if not isinstance(part_number, str) or not part_number.strip() or (partition is not None and not partition): _fail('part number and optional partition must be nonempty') @@ -191,12 +192,18 @@ def read_library_cell_catalog(library_path: Path, part_number: str, evidence_roo if _hash(path) != cache['sha256']: raise ValueError('evidence digest changed') value = _catalog_from_evidence(json.loads(path.read_text(encoding='utf-8')), library, part_number, partition, fingerprint, path) - except (ValueError, KeyError, OSError, TypeError): - pass # Re-read through an owned clone; never return damaged proof. + except (ValueError, KeyError, OSError, TypeError, AttributeError): + pass # Only an explicitly permitted cold read may replace damaged proof. else: if _library_manifest(library) != manifest: + if not allow_cold_read: + _fail('源库在缓存核验期间发生变化,请在料号规则中重新读取目标封装后再执行。') _fail('source library changed during cache validation') return value + if not allow_cold_read: + # Native mutation has its own hard deadline: never wait for the reader + # mutex or create a clone/process inside that budget. + _fail('目标封装缓存缺失或已失效,请在料号规则中重新读取目标封装后再执行。') root = evidence_root / 'reads' / uuid.uuid4().hex root.mkdir(parents=True) evidence_path = root / 'catalog.json' diff --git a/src/dx_productivity/trial_task_center/native_helper.py b/src/dx_productivity/trial_task_center/native_helper.py index 3cd22aa..d01e5f0 100644 --- a/src/dx_productivity/trial_task_center/native_helper.py +++ b/src/dx_productivity/trial_task_center/native_helper.py @@ -86,13 +86,14 @@ def target_cell_catalog(app, snapshot, metadata, selected): library = Path(raw_path) if not raw_path.strip() or not library.is_absolute(): raise ValueError("Active project has no absolute central library path for Cell validation") - return cell_catalog_binding(library, metadata[3], selected, cell_catalog_evidence_root(snapshot)) + return cell_catalog_binding(library, metadata[3], selected, cell_catalog_evidence_root(snapshot), + allow_cold_read=False) -def cell_catalog_binding(library, part_number, selected, evidence_root): +def cell_catalog_binding(library, part_number, selected, evidence_root, *, allow_cold_read=False): from .cell_catalog import read_library_cell_catalog - catalog = read_library_cell_catalog(library, part_number, evidence_root) + catalog = read_library_cell_catalog(library, part_number, evidence_root, allow_cold_read=allow_cold_read) if catalog.library_path.resolve() != library.resolve() or catalog.part_number != part_number: raise ValueError("Cell catalog does not match the active project and target part") names = [cell.name for cell in catalog.cells] diff --git a/src/dx_productivity/trial_task_center/recovery.py b/src/dx_productivity/trial_task_center/recovery.py index e8e97c8..e0e10d4 100644 --- a/src/dx_productivity/trial_task_center/recovery.py +++ b/src/dx_productivity/trial_task_center/recovery.py @@ -91,7 +91,11 @@ def require_current_cell_binding(snapshot, binding, project, metadata): raise ValueError('Recovery has no bound target Cell catalog') from .cell_catalog import project_library_path library = project_library_path(project) - current = cell_catalog_binding(library, metadata[3], cell, cell_catalog_evidence_root(snapshot)) + # Standalone preflight runs before the recovery CAD worker and outside the + # native helper deadline. Rebuild lost cache while interruption protection + # still locks the rule editor, then require the original exact binding. + current = cell_catalog_binding(library, metadata[3], cell, cell_catalog_evidence_root(snapshot), + allow_cold_read=True) if current != binding['cell_catalog']: raise ValueError('Recovery target Cell catalog has changed') return current diff --git a/tests/trial_task_center/test_recovery.py b/tests/trial_task_center/test_recovery.py index 7514b54..e2013f3 100644 --- a/tests/trial_task_center/test_recovery.py +++ b/tests/trial_task_center/test_recovery.py @@ -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' diff --git a/tests/v1_1/test_cell_catalog.py b/tests/v1_1/test_cell_catalog.py index 0430e9b..f85ccee 100644 --- a/tests/v1_1/test_cell_catalog.py +++ b/tests/v1_1/test_cell_catalog.py @@ -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): diff --git a/tests/v1_1/test_target_cell_execution.py b/tests/v1_1/test_target_cell_execution.py index 0183c10..e22fc2e 100644 --- a/tests/v1_1/test_target_cell_execution.py +++ b/tests/v1_1/test_target_cell_execution.py @@ -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):