From bb506a355080d25ed3a2f5d843622300d6530890 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 14:50:32 +0800 Subject: [PATCH] fix(execution): bind explicit target cells to native save and recovery --- .../dxdesigner795/QuickPartReplace.vbs | 54 +++++++ .../trial_task_center/native_helper.py | 65 +++++++- .../trial_task_center/quick_run.py | 45 +++++- .../trial_task_center/recovery.py | 23 ++- .../test_execution_safety.py | 2 + tests/trial_task_center/test_recovery.py | 47 ++++-- tests/v1_1/test_target_cell_execution.py | 140 ++++++++++++++++++ 7 files changed, 356 insertions(+), 20 deletions(-) create mode 100644 tests/v1_1/test_target_cell_execution.py diff --git a/integration/dxdesigner795/QuickPartReplace.vbs b/integration/dxdesigner795/QuickPartReplace.vbs index f09b45a..403ee6d 100644 --- a/integration/dxdesigner795/QuickPartReplace.vbs +++ b/integration/dxdesigner795/QuickPartReplace.vbs @@ -1174,6 +1174,8 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath) If Not Selectors Is Nothing Then _ Snapshot = Snapshot & vbTab & QPEncode("targets") & vbTab & CStr(Command("target_selectors")) Snapshot = Snapshot & vbCrLf + If Len(QPTargetCell(Command)) > 0 Then _ + Snapshot = Snapshot & "L" & vbTab & QPEncode(QPTargetCell(Command)) & vbCrLf Set MatchedUids = CreateObject("Scripting.Dictionary") For Index = 0 To Matches.Count - 1 Set Comp = Matches.Item(CStr(Index)) @@ -1632,6 +1634,8 @@ Sub QPRestoreAfterOperatorReplace(ByRef Command, ByVal SnapshotPath) CStr(Command("new_part_number"))) SuccessMessage = "Native replacement and parameter readback passed on current sheet. Replacements: " & _ ReplacementSummary & " " & QPDisplayVerificationSummary(Records) + If Len(QPTargetCell(Command)) > 0 Then SuccessMessage = SuccessMessage & _ + " Target Cell verified: " & QPTargetCell(Command) & "." If Len(QP_NcSyncSummary) > 0 Then SuccessMessage = SuccessMessage & _ " NC synced: " & QP_NcSyncSummary QPWriteStatus QP_Root, CStr(Command("job_id")), "restored_ok", "", SuccessMessage @@ -1665,6 +1669,7 @@ Sub QPRestorePlans(ByRef Command, ByRef Records, ByRef Plans) ValueStates.Item(CStr(Index)).Add "custom_value", QPCustomValue(Command) QPRestoreComponent Candidate, ComponentRecord, Records.Item("attributes"), _ QPValueMode(Command), QPCustomValue(Command), QPSyncNc(Command) + QPSetTargetCell Candidate, Command QPProgress "restore_attributes", Index + 1, Plans.Count Next QPVerifyRestoredPlans Command, Records, Plans, ValueStates @@ -1677,6 +1682,7 @@ Sub QPVerifyRestoredPlans(ByRef Command, ByRef Records, ByRef Plans, ByRef Value For Index = 0 To Plans.Count - 1 Set ComponentRecord = Records.Item("components").Item(CStr(Index)) Set Candidate = Plans.Item(CStr(Index)) + QPVerifyTargetCell Candidate, Command ' Captured only after native library identity validation (or recovery ' command validation), before restoration/save; never derive this expected ' identity from the reopened result or from its current Value. @@ -1713,6 +1719,13 @@ Sub QPRecoverSavedJob(ByRef Command, ByVal SnapshotPath) Dim Records, Plans, Used, ValueStates, Index, Record, Candidate, PartNumber Dim OldCount, NewCount, ErrorNumber, ErrorDescription, RecoveryDocuments, RecoveryDocument, RecoveryProjectData QPRequireCommandSnapshot Command, SnapshotPath + If Len(QPTargetCell(Command)) > 0 Then + If Not Command.Exists("recovery_library_path") Then _ + Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "recovery Cell library proof missing" + If QPCanonicalPath(CStr(QP_App.GetProjectData().CentralLibraryPath)) <> _ + QPCanonicalPath(QPDecode(CStr(Command("recovery_library_path")))) Then _ + Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "recovery active library changed" + End If Set Records = QPReadSnapshot(SnapshotPath) QPVerifyUntouched Records Set Plans = CreateObject("Scripting.Dictionary") @@ -2200,6 +2213,8 @@ Sub QPRequireCommandSnapshot(ByRef Command, ByVal SnapshotPath) Err.Raise vbObjectError + 830, "QuickPartReplace", "snapshot rule mismatch" If QPValueMode(Meta) <> QPValueMode(Command) Then _ Err.Raise vbObjectError + 842, "QuickPartReplace", "snapshot Value policy mismatch" + If QPTargetCell(Meta) <> QPTargetCell(Command) Then _ + Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "target Cell changed since snapshot" If QPCustomValue(Meta) <> QPCustomValue(Command) Or _ QPSyncNc(Meta) <> QPSyncNc(Command) Then _ Err.Raise vbObjectError + 842, "QuickPartReplace", "snapshot Value or NC option mismatch" @@ -2218,6 +2233,39 @@ Sub QPRequireCommandSnapshot(ByRef Command, ByVal SnapshotPath) End If End Sub +Function QPTargetCell(ByRef Record) + Dim Value, Index + QPTargetCell = "" + If Not Record.Exists("target_cell") Then Exit Function + Value = QPDecode(CStr(Record("target_cell"))) + If Len(Value) = 0 Or Trim(Value) <> Value Then _ + Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "target Cell selection is empty or invalid" + For Index = 1 To Len(Value) + If AscW(Mid(Value, Index, 1)) >= 0 And AscW(Mid(Value, Index, 1)) < 32 Then _ + Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "invalid control character in target Cell" + Next + QPTargetCell = Value +End Function + +Sub QPSetTargetCell(ByRef Comp, ByRef Command) + Dim Value, Attr + Value = QPTargetCell(Command) + If Len(Value) = 0 Then Exit Sub + Set Attr = QPFindCurrentAttribute(Comp, "Cell Name") + If Attr Is Nothing Then Err.Raise vbObjectError + 878, _ + "QuickPartReplace.Cell", "replaced target has no Cell Name attribute" + Attr.InstanceValue = Value + QPVerifyTargetCell Comp, Command +End Sub + +Sub QPVerifyTargetCell(ByRef Comp, ByRef Command) + Dim Value + Value = QPTargetCell(Command) + If Len(Value) = 0 Then Exit Sub + If QPRequiredAttributeValue(Comp, "Cell Name") <> Value Then _ + Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "effective target Cell does not match explicit selection" +End Sub + Function QPValueMode(ByRef Record) QPValueMode = "legacy_part_label" If Not Record.Exists("value_mode") Then Exit Function @@ -2871,6 +2919,12 @@ Function QPReadSnapshot(ByVal Path) Meta.Add "target_selectors", CStr(Fields(9)) End If Result.Add "meta", Meta + Case "L" + If UBound(Fields) <> 1 Or Not Result.Exists("meta") Then _ + Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "invalid target Cell snapshot" + Result.Item("meta").Add "target_cell", CStr(Fields(1)) + If Len(QPTargetCell(Result.Item("meta"))) = 0 Then _ + Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "missing target Cell snapshot" Case "C" If UBound(Fields) <> 7 Then Err.Raise vbObjectError + 813, _ "QuickPartReplace", "invalid snapshot component" diff --git a/src/dx_productivity/trial_task_center/native_helper.py b/src/dx_productivity/trial_task_center/native_helper.py index e98a2a2..d87c164 100644 --- a/src/dx_productivity/trial_task_center/native_helper.py +++ b/src/dx_productivity/trial_task_center/native_helper.py @@ -61,13 +61,53 @@ def snapshot_sha256(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() -def transaction_binding(snapshot, metadata, records, library_row, symbol, slot_count=1): +def snapshot_target_cell(path, *, required=True): + rows = [line.split("\t") for line in Path(path).read_text(encoding="utf-8-sig").splitlines() + if line.split("\t", 1)[0] == "L"] + if not rows and not required: + return None + if len(rows) != 1 or len(rows[0]) != 2: + raise ValueError("Snapshot requires one explicit target Cell selection") + value = decode(rows[0][1]) + if not value or value != value.strip() or any(ord(c) < 32 for c in value): + raise ValueError("Snapshot target Cell selection is empty or invalid") + return value + + +def target_cell_catalog(app, snapshot, metadata, selected): + raw_path = str(app.GetProjectData().CentralLibraryPath) + 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, Path(snapshot).parent.parent / "cell-catalog") + + +def cell_catalog_binding(library, part_number, selected, evidence_root): + from .cell_catalog import read_library_cell_catalog + + catalog = read_library_cell_catalog(library, part_number, evidence_root) + 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] + if len(names) != len(set(names)) or names.count(selected) != 1: + raise ValueError("Selected target Cell is unavailable or ambiguous in the actual project library") + return { + "library_path": str(library.resolve()), + "source_fingerprint": catalog.source_fingerprint, + "part_partition": catalog.part_partition, + "part_number": catalog.part_number, + "cells": sorted([[cell.partition, cell.name] for cell in catalog.cells]), + "selected": selected, + } + + +def transaction_binding(snapshot, metadata, records, library_row, symbol, slot_count=1, *, cell_catalog=None): if len(library_row) < 6 or not str(library_row[4]).strip() or not str(library_row[5]).strip(): raise ValueError("Library target has incomplete identity fields") slots = int(slot_count) if slots < 1: raise ValueError("Library target has no valid slots") - return { + result = { "snapshot_sha256": snapshot_sha256(snapshot), "project_path": os.path.normcase(os.path.abspath(metadata[1])), "sheet_identity": metadata[4], @@ -79,6 +119,14 @@ def transaction_binding(snapshot, metadata, records, library_row, symbol, slot_c "target_symbol": str(symbol), "slot_count": slots, } + cell = snapshot_target_cell(snapshot, required=False) + if cell is not None: + result["target_cell"] = cell + if cell_catalog is not None: + if cell_catalog.get("selected") != cell or cell_catalog.get("part_partition") != str(library_row[0]): + raise ValueError("Native library row differs from authoritative Cell catalog") + result["cell_catalog"] = cell_catalog + return result def require_resumable_transaction(snapshot, report, metadata, records): @@ -99,6 +147,9 @@ def require_resumable_transaction(snapshot, report, metadata, records): "source_uids": sorted(row[1] for row in records), "target_selectors": metadata[9] if len(metadata) == 10 else None, } + cell = snapshot_target_cell(snapshot, required=False) + if cell is not None: + expected["target_cell"] = cell if not isinstance(binding, dict) or any(binding.get(key) != value for key, value in expected.items()): raise ValueError("Native replacement evidence does not match this snapshot") library_row = binding.get("library_row") @@ -452,9 +503,11 @@ def run_native(snapshot, report): from pywinauto import Desktop metadata, records = read_snapshot(snapshot) + target_cell = snapshot_target_cell(snapshot) require_part_label = snapshot_value_mode(metadata) == "part_label" app, api = attach() check_active_context(app, metadata) + cell_proof = target_cell_catalog(app, snapshot, metadata, target_cell) components = components_on_sheet(app, api) wanted = {row[1] for row in records} if len(metadata) == 10: @@ -466,6 +519,8 @@ def run_native(snapshot, report): } if source_uids != wanted: binding = require_resumable_transaction(snapshot, report, metadata, records) + if binding.get("cell_catalog") != cell_proof: + raise ValueError("Current Cell catalog differs from recorded native transaction") report["replaced_uids"] = existing_replacement_uids( components, records, metadata[3], binding, require_part_label=require_part_label ) @@ -634,7 +689,11 @@ def run_native(snapshot, report): if read_target() != ready: raise ValueError('Native target changed during final context verification') symbol = ready[1] - report["transaction"] = transaction_binding(snapshot, metadata, records, columns, symbol, slot_count) + current_cell_proof = target_cell_catalog(app, snapshot, metadata, target_cell) + if current_cell_proof != cell_proof: + raise ValueError("Cell catalog changed before native replacement; no replacement submitted") + report["transaction"] = transaction_binding(snapshot, metadata, records, columns, symbol, slot_count, + cell_catalog=cell_proof) report["stage"] = "native_replace_started" save_report(snapshot, report) click(dlg_item(dialog, 1695)) diff --git a/src/dx_productivity/trial_task_center/quick_run.py b/src/dx_productivity/trial_task_center/quick_run.py index 195fd18..d602933 100644 --- a/src/dx_productivity/trial_task_center/quick_run.py +++ b/src/dx_productivity/trial_task_center/quick_run.py @@ -275,7 +275,7 @@ class QuickRunPreparer: command_lines = handoff.command_path.read_text(encoding='utf-8-sig').splitlines() job_column = command_lines[0].split('\t').index('job_id') target_command_rows = ({line.split('\t')[job_column]: line for line in command_lines[1:] if line} - if 'target_scope' in command_lines[0].split('\t') else {}) + if {'target_scope', 'target_cell'} & set(command_lines[0].split('\t')) else {}) return QuickRunBatchSession( task_id, _value_mode(copy_part_number_to_value), @@ -765,6 +765,7 @@ class QuickRunPreparer: for rule in rules: _validate_field(rule.old_part_number, "old part number") _validate_field(rule.new_part_number, "new part number") + _validate_field(str(getattr(rule, "target_cell", "")), "target Cell") if bool(getattr(rule, "custom_value_enabled", False)): custom_value = str(getattr(rule, "custom_value", "")) _validate_field(custom_value, "custom Value") @@ -1410,6 +1411,11 @@ def _queue_matches_inputs( rules: tuple[RuleRecord, ...], ) -> bool: base_mode = _queue_value_mode(command_path) + cells = _read_command_cells(command_path) + actual_cells = {cells.get(command[1], "") for command in commands} + expected_cells = {str(getattr(rule, "target_cell", "")) for rule in rules} + if actual_cells != expected_cells: + return False if "target_scope" in command_path.read_text(encoding="utf-8-sig").splitlines()[0].split("\t"): sheets = _read_command_sheet_targets(command_path) manifest = _read_sheet_manifest(command_path.with_name("sheets.tsv"), projects) if sheets is not None else None @@ -1425,26 +1431,26 @@ def _queue_matches_inputs( expected = tuple( ( str(project.path), rule.old_part_number, rule.new_part_number, - *_rule_command_options(rule, base_mode)[:3], + *_rule_command_options(rule, base_mode)[:3], str(getattr(rule, "target_cell", "")), ) for project in projects for rule in rules ) - return tuple((*command[2:], *options[command[1]][:3]) for command in commands) == expected + return tuple((*command[2:], *options[command[1]][:3], cells.get(command[1], "")) for command in commands) == expected if set(sheets) != {command[1] for command in commands} or len(commands) != len(sheets): return False manifest = _read_sheet_manifest(command_path.with_name("sheets.tsv"), projects) expected = tuple( ( str(project.path), schematic_name, sheet_number, rule.old_part_number, rule.new_part_number, - *_rule_command_options(rule, base_mode)[:3], + *_rule_command_options(rule, base_mode)[:3], str(getattr(rule, "target_cell", "")), ) for project in projects for schematic_name, sheet_number in manifest[_path_key(project.path)] for rule in rules ) actual = tuple( - (command[2], *sheets[command[1]], command[3], command[4], *options[command[1]][:3]) + (command[2], *sheets[command[1]], command[3], command[4], *options[command[1]][:3], cells.get(command[1], "")) for command in commands ) return actual == expected @@ -1808,6 +1814,31 @@ def _queue_value_mode(path: Path) -> str: raise TaskCenterError("quick_run_command", "queue Value policy is invalid") from error +def _read_command_cells(path: Path) -> dict[str, str]: + try: + lines = path.read_text(encoding="utf-8-sig").splitlines() + header = lines[0].split("\t") + if "target_cell" not in header: + return {} + if header.count("target_cell") != 1 or header.count("job_id") != 1: + raise ValueError("duplicate Cell header") + result = {} + for line in lines[1:]: + if not line: + continue + fields = line.split("\t") + if len(fields) != len(header): + raise ValueError("Cell field count") + job = fields[header.index("job_id")] + cell = _decode_vbs_field(fields[header.index("target_cell")]) + if not job or job in result or cell != cell.strip() or any(ord(c) < 32 for c in cell): + raise ValueError("invalid Cell option") + result[job] = cell + return result + except (OSError, UnicodeError, IndexError, ValueError) as error: + raise TaskCenterError("quick_run_command", "queue target Cell options are invalid") from error + + def _read_command_options(path: Path) -> dict[str, tuple[str, str, bool, str]]: try: lines = path.read_text(encoding="utf-8-sig").splitlines() @@ -1871,6 +1902,9 @@ def _command_text( if targeted and sheet_targets is None: raise TaskCenterError("target_scope", "target execution requires sheet-addressed commands") suffix = "\ttarget_scope\ttarget_selectors" if targeted else "" + has_cell = any(getattr(rule, "target_cell", "") for rule in rules) + if has_cell: + suffix += "\ttarget_cell" if sheet_targets is None: rows = ["task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode" + suffix] else: @@ -1900,6 +1934,7 @@ def _command_text( f"{rule.old_part_number}\t{rule.new_part_number}\t{rule_mode}\t{custom_value}\t" f"{'1' if sync_nc else '0'}\t{base_mode}" + (f"\t{scope}\t{selectors}" if targeted else "") + + ("\t" + _encode_vbs_field(str(getattr(rule, "target_cell", ""))) if has_cell else "") ) job_index += 1 return "\r\n".join(rows) + "\r\n" diff --git a/src/dx_productivity/trial_task_center/recovery.py b/src/dx_productivity/trial_task_center/recovery.py index 82d72bb..3d6912d 100644 --- a/src/dx_productivity/trial_task_center/recovery.py +++ b/src/dx_productivity/trial_task_center/recovery.py @@ -12,13 +12,14 @@ import subprocess from uuid import uuid4 from .errors import TaskCenterError -from .native_helper import read_snapshot, require_resumable_transaction +from .native_helper import read_snapshot, require_resumable_transaction, snapshot_target_cell, cell_catalog_binding from .quick_run import ( TERMINAL_STATES, IDLE_PROGRESS_TIMEOUT_SECONDS, QuickRunStepResult, _native_helper_launch_arguments, _next_unfinished_command, _path_key, _queue_matches_inputs, _queue_value_mode, _read_command_sheet_targets, _read_command_options, _read_commands, _read_status_details, _safe_run_token, _value_mode_matches_option, _write_status_details, _write_uncertain_flag, _decode_vbs_field, + _read_command_cells, _encode_vbs_field, ) from .retention import maintain_quick_run_storage from .schematic_backup import create_schematic_backup @@ -83,6 +84,18 @@ def _recovery_copytree(source: Path, destination: Path) -> None: ) from error +def require_current_cell_binding(snapshot, binding, project, metadata): + cell = snapshot_target_cell(snapshot) + if binding.get('target_cell') != cell or not isinstance(binding.get('cell_catalog'), dict): + 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, snapshot.parent.parent / 'cell-catalog') + if current != binding['cell_catalog']: + raise ValueError('Recovery target Cell catalog has changed') + return current + + def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=False, confirmed=False): if not confirmed: raise TaskCenterError('quick_run_recovery_confirmation', '核验恢复需要明确确认,不能作为自动重试执行。') @@ -142,10 +155,14 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal raise ValueError('snapshot target scope missing from command') report = json.loads(snapshot.with_suffix('.tsv.native.json').read_text(encoding='utf-8')) binding = require_resumable_transaction(snapshot, report, metadata, components) + selected_cell = _read_command_cells(root / 'command.tsv').get(job_id) + if selected_cell != snapshot_target_cell(snapshot): + raise ValueError('snapshot target Cell mismatch') + cell_proof = require_current_cell_binding(snapshot, binding, Path(selected[2]), metadata) identity = binding['library_row'][4:6] if any(not value or any(character in value for character in '\t\r\n') for value in identity): raise ValueError('invalid library identity') - except (OSError, ValueError, KeyError, TypeError) as error: + except (OSError, ValueError, KeyError, TypeError, TaskCenterError) as error: raise TaskCenterError('quick_run_recovery', '快照或原生替换证据无法与此任务绑定,保护状态保持不变。') from error if not uncertain.is_file(): _write_uncertain_flag(uncertain, 'recovery_in_progress') @@ -191,6 +208,8 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal if len(metadata) == 10: header += '\ttarget_scope\ttarget_selectors' row = (*row, 'targets', selectors) + header += '\ttarget_cell\trecovery_library_path' + row = (*row, _encode_vbs_field(selected_cell), _encode_vbs_field(cell_proof['library_path'])) (worker / 'command.tsv').write_text(header + '\n' + '\t'.join(row) + '\n', encoding='utf-8') _write_status_details(worker / 'status.tsv', ()) from .quick_run import _vbs_worker_paths diff --git a/tests/trial_task_center/test_execution_safety.py b/tests/trial_task_center/test_execution_safety.py index c0375d4..06cbb24 100644 --- a/tests/trial_task_center/test_execution_safety.py +++ b/tests/trial_task_center/test_execution_safety.py @@ -79,6 +79,8 @@ def test_invalid_transaction_evidence_never_promotes_pins(monkeypatch, tmp_path) from types import SimpleNamespace components = [SimpleNamespace(UID='outside-snapshot')] + (tmp_path / 'snapshot.tsv').write_text('L\tCELL\n') + monkeypatch.setattr(native_helper, 'target_cell_catalog', lambda *args: {}) monkeypatch.setattr(native_helper, 'read_snapshot', lambda path: (['M', 'project', 'OLD', 'NEW', 'sheet'], [['C', 'recorded', 'R1', '0', '0', '0', '1', 'net']])) monkeypatch.setattr(native_helper, 'attach', lambda: (object(), object())) diff --git a/tests/trial_task_center/test_recovery.py b/tests/trial_task_center/test_recovery.py index 0355c0b..7514b54 100644 --- a/tests/trial_task_center/test_recovery.py +++ b/tests/trial_task_center/test_recovery.py @@ -6,7 +6,7 @@ from types import SimpleNamespace import pytest from dx_productivity.trial_task_center.errors import TaskCenterError -from dx_productivity.trial_task_center.native_helper import read_snapshot, transaction_binding +from dx_productivity.trial_task_center.native_helper import read_snapshot, transaction_binding, cell_catalog_binding from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _read_commands, _read_status_details from dx_productivity.trial_task_center.recovery import _is_link_or_reparse, _recovery_hashes, recover @@ -30,7 +30,15 @@ def test_locked_recovery_files_return_stable_recovery_error(tmp_path, monkeypatc @pytest.fixture -def interrupted(tmp_path): +def interrupted(tmp_path, monkeypatch): + import sys + library = tmp_path / 'library.lmc' + 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') + 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)) project = tmp_path / 'project' / 'one.prj' project.parent.mkdir() project.write_text('project') @@ -40,20 +48,21 @@ def interrupted(tmp_path): preparer = QuickRunPreparer(root, script_source=script, run_token_factory=lambda: 'first', cscript_resolver=lambda: Path('cscript.exe')) projects = (SimpleNamespace(path=project, selected=True, available=True),) - rules = (SimpleNamespace(old_part_number='OLD', new_part_number='NEW', enabled=True),) + rules = (SimpleNamespace(old_part_number='OLD', new_part_number='NEW', enabled=True, target_cell='CELL'),) handoff = preparer.prepare('task', projects, rules, copy_part_number_to_value=True) job = _read_commands(handoff.command_path)[0][1] snapshot = handoff.command_path.parent / f'snapshot-{job}.tsv' - snapshot.write_text(f'M\t{project}\tOLD\tNEW\tA:1\tpart_label\nC\tuid\tR1\t0\t0\t0\t1\tpins\n', encoding='utf-8') + snapshot.write_text(f'M\t{project}\tOLD\tNEW\tA:1\tpart_label\nL\tCELL\nC\tuid\tR1\t0\t0\t0\t1\tpins\n', encoding='utf-8') metadata, components = read_snapshot(snapshot) + cell_proof = cell_catalog_binding(library, 'NEW', 'CELL', snapshot.parent / 'cell-catalog') report = {'stage': 'native_replace_verified', 'transaction': transaction_binding( - snapshot, metadata, components, ['library', 'NEW', 'symbol', '', 'cap', 'label'], 'symbol')} + snapshot, metadata, components, ['library', 'NEW', 'symbol', '', 'cap', 'label'], 'symbol', cell_catalog=cell_proof)} snapshot.with_suffix('.tsv.native.json').write_text(json.dumps(report), encoding='utf-8') handoff.status_path.write_text('job_id\tstate\tcode\tmessage\n' + job + '\tawaiting_native_replace\t\tstarted\n', encoding='utf-8') 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) + job=job, handoff=handoff, lock=lock, report=report, catalog=catalog, cell_proof=cell_proof) def invoke(fixture, **kwargs): @@ -134,7 +143,7 @@ def test_r12_part_number_queue_keeps_recorded_policy_during_recovery(interrupted metadata, components = read_snapshot(interrupted.snapshot) report = {'stage': 'native_replace_verified', 'transaction': transaction_binding( interrupted.snapshot, metadata, components, - ['library', 'NEW', 'symbol', '', 'cap', 'label'], 'symbol')} + ['library', 'NEW', 'symbol', '', 'cap', 'label'], 'symbol', cell_catalog=interrupted.cell_proof)} interrupted.snapshot.with_suffix('.tsv.native.json').write_text(json.dumps(report), encoding='utf-8') def worker(command, timeout): @@ -154,8 +163,8 @@ def test_r12_part_number_queue_keeps_recorded_policy_during_recovery(interrupted def test_page_addressed_recovery_keeps_the_original_sheet_binding(interrupted): project = interrupted.projects[0].path interrupted.handoff.command_path.write_text( - 'task_id\tjob_id\tproject_path\tschematic_name\tsheet_number\told_part\tnew_part\tvalue_mode\n' - f'task\t{interrupted.job}\t{project}\tA\t1\tOLD\tNEW\tpart_label\n', + 'task_id\tjob_id\tproject_path\tschematic_name\tsheet_number\told_part\tnew_part\tvalue_mode\ttarget_cell\n' + f'task\t{interrupted.job}\t{project}\tA\t1\tOLD\tNEW\tpart_label\tCELL\n', encoding='utf-8', ) (interrupted.handoff.command_path.parent / 'sheets.tsv').write_text( @@ -270,7 +279,7 @@ def test_service_recovery_updates_queue_and_database(interrupted, initial): service.set_copy_part_number_to_value(task.task_id, True) projects = service.scan_projects(task.task_id, interrupted.projects[0].path.parent) service.set_project_selected(projects[0].project_id, True) - service.add_rule(task.task_id, 'OLD', 'NEW') + service.add_rule(task.task_id, 'OLD', 'NEW', target_cell='CELL') command_path = interrupted.handoff.command_path command_path.write_text(command_path.read_text().replace('task\t', task.task_id + '\t'), encoding='utf-8') if store.get_task(task.task_id).status is TaskStatus.DRAFT: @@ -286,3 +295,21 @@ def test_service_recovery_updates_queue_and_database(interrupted, initial): assert store.get_task(task.task_id).status is TaskStatus.COMPLETED assert service.quick_run_progress(task.task_id).queue_complete assert not service.has_interrupted_quick_run(task.task_id) + +@pytest.mark.parametrize('fault',['source_changed','choice_removed','proof_missing']) +def test_cell_catalog_drift_blocks_recovery_before_worker(interrupted,fault): + calls=[] + interrupted.preparer._process_runner=lambda *args:calls.append(args) + if fault=='source_changed': + interrupted.catalog.source_fingerprint='changed' + elif fault=='choice_removed': + interrupted.catalog.cells=() + else: + interrupted.report['transaction'].pop('cell_catalog') + interrupted.snapshot.with_suffix('.tsv.native.json').write_text(json.dumps(interrupted.report),encoding='utf8') + before=interrupted.handoff.status_path.read_bytes() + with pytest.raises(TaskCenterError,match='quick_run_recovery'): + invoke(interrupted) + assert calls==[] + assert interrupted.lock.exists() + assert interrupted.handoff.status_path.read_bytes()==before diff --git a/tests/v1_1/test_target_cell_execution.py b/tests/v1_1/test_target_cell_execution.py new file mode 100644 index 0000000..d0ad7e7 --- /dev/null +++ b/tests/v1_1/test_target_cell_execution.py @@ -0,0 +1,140 @@ +"""Explicit target Cell binding across queue, snapshot and recovery evidence.""" +from dataclasses import replace +from pathlib import Path +from types import SimpleNamespace +import pytest +from dx_productivity.trial_task_center import native_helper, quick_run + + +def rule(cell): + return SimpleNamespace(old_part_number='OLD',new_part_number='NEW',enabled=True,target_cell=cell) + + +def test_queue_cell_selection_is_preserved_and_change_invalidates_queue(tmp_path): + project=SimpleNamespace(path=tmp_path/'one.prj') + path=tmp_path/'command.tsv' + path.write_text(quick_run._command_text('task','token',(project,),(rule('CELL_A'),),'preserve'),encoding='utf8',newline='') + rows=path.read_text().splitlines();header=rows[0].split('\t');fields=rows[1].split('\t') + assert fields[header.index('target_cell')]=='CELL_A' + commands=quick_run._read_commands(path) + assert quick_run._queue_matches_inputs(path,commands,(project,),(rule('CELL_A'),)) + assert not quick_run._queue_matches_inputs(path,commands,(project,),(rule('CELL_B'),)) + assert not quick_run._queue_matches_inputs(path,commands,(project,),(rule(''),)) + + +@pytest.mark.parametrize('rows', ['', 'L\t\n', 'L\tCELL\textra\n','L\tCELL\nL\tCELL\n']) +def test_native_snapshot_requires_one_nonempty_cell_choice(tmp_path,rows): + snapshot=tmp_path/'snapshot.tsv';snapshot.write_text(rows) + with pytest.raises(ValueError,match='Cell'): + native_helper.snapshot_target_cell(snapshot) + + +def test_native_binding_binds_cell_and_rejects_changed_selection(tmp_path): + snapshot=tmp_path/'snapshot.tsv';snapshot.write_text('L\tCELL_A\n') + meta=['M','project','OLD','NEW','sheet'];records=[['C','uid','R1','0','0','0','1','pins']] + binding=native_helper.transaction_binding(snapshot,meta,records,['lib','NEW','sym','','part','label'],'sym') + assert binding['target_cell']=='CELL_A' + report={'stage':'native_replace_verified','transaction':binding} + assert native_helper.require_resumable_transaction(snapshot,report,meta,records)==binding + report['transaction']['target_cell']='CELL_B' + with pytest.raises(ValueError,match='snapshot'): + native_helper.require_resumable_transaction(snapshot,report,meta,records) + + +def test_native_missing_cell_stops_before_attaching_to_cad(tmp_path,monkeypatch): + snapshot=tmp_path/'snapshot.tsv';snapshot.write_text('M\tproject\tOLD\tNEW\tsheet\nC\tuid\tR1\t0\t0\t0\t1\tpins\n') + calls=[];monkeypatch.setattr(native_helper,'attach',lambda:calls.append('attach')) + with pytest.raises(ValueError,match='Cell'): + native_helper.run_native(snapshot,{}) + assert calls==[] + +@pytest.mark.parametrize('mode',['ok','missing','readonly']) +def test_cell_instance_write_is_explicit_and_verified(tmp_path,mode): + import test_accuracy_vbs_guards as guards + output=guards.run_vbs(tmp_path,['QPSetTargetCell','QPVerifyTargetCell','QPTargetCell','QPDecode','QPFindCurrentAttribute','QPEffectiveAttributeValue','QPRequiredAttributeValue'],''' +Dim Comp,Command,Failure +Set Comp=New CellComponent:Set Command=CreateObject("Scripting.Dictionary") +Command.Add "target_cell","NEW_CELL" +On Error Resume Next +QPSetTargetCell Comp,Command +Failure=Err.Number +On Error GoTo 0 +WScript.Echo CStr(Failure<>0) +If Failure=0 Then + WScript.Echo Comp.Attr.InstanceValue + Comp.Attr.InstanceValue="WRONG" + On Error Resume Next + QPVerifyTargetCell Comp,Command + Failure=Err.Number + On Error GoTo 0 + WScript.Echo CStr(Failure<>0) +End If +''',prelude=''' +Class CellComponent + Public Attr + Private Sub Class_Initialize() + Set Attr=New CellAttribute + End Sub + Function FindAttribute(ByVal Name) + Set FindAttribute='''+('Nothing' if mode=='missing' else 'Attr')+''' + End Function +End Class +Class CellAttribute + Public Value + Private Stored + Public Property Get InstanceValue() + InstanceValue=Stored + End Property + Public Property Let InstanceValue(ByVal NewValue) + '''+('Err.Raise 1234,"Fake","write rejected"' if mode=='readonly' else 'Stored=NewValue')+''' + End Property +End Class +''') + assert output.splitlines()==(['False','NEW_CELL','True'] if mode=='ok' else ['True']) + +@pytest.mark.parametrize('choice',['CELL_OK','INVALID']) +def test_actual_project_library_catalog_controls_choice(tmp_path,monkeypatch,choice): + import sys + library=tmp_path/'lib.lmc' + app=SimpleNamespace(GetProjectData=lambda:SimpleNamespace(CentralLibraryPath=str(library))) + captured=[] + def read(path,part,evidence_root,**kwargs): + captured.append((path,part)) + 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)) + if choice=='INVALID': + with pytest.raises(ValueError,match='Cell'): + native_helper.target_cell_catalog(app,tmp_path/'snapshot.tsv',['M','project','OLD','NEW','sheet'],choice) + else: + 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')] + + +def test_legacy_recovery_evidence_cannot_upgrade_without_explicit_cell(tmp_path): + from dx_productivity.trial_task_center import recovery + snapshot=tmp_path/'snapshot.tsv';snapshot.write_text('M\tproject\tOLD\tNEW\tsheet\n') + with pytest.raises(ValueError,match='Cell'): + recovery.require_current_cell_binding(snapshot,{},tmp_path/'project.prj',['M','project','OLD','NEW','sheet']) + +@pytest.mark.parametrize('fault',['','duplicate','empty','extra']) +def test_vbs_cell_snapshot_roundtrip_rejects_malformed_selection(tmp_path,fault): + import test_accuracy_vbs_guards as guards + cell='L\tCELL_A\n' + if fault=='duplicate':cell+=cell + if fault=='empty':cell='L\t\n' + if fault=='extra':cell='L\tCELL_A\tOTHER\n' + path=tmp_path/'snapshot.tsv';path.write_text('M\tc:\\board.prj\tOLD\tNEW\tMAIN:1\n'+cell+'C\tu1\tR1\t0\t0\t0\t1\tpins\nA\tu1\tCell Name\t\tOLD_CELL\t0\t0\t1\t1\t1\t0\t1\n') + output=guards.run_vbs(tmp_path,['QPReadSnapshot','QPReadUtf8','QPDecode','QPTargetCell'],''' +Dim QP_Fso,Result,Failure +Set QP_Fso=CreateObject("Scripting.FileSystemObject") +On Error Resume Next +Set Result=QPReadSnapshot("'''+str(path).replace('"','""')+'''") +Failure=Err.Number +On Error GoTo 0 +WScript.Echo CStr(Failure<>0) +If Failure=0 Then WScript.Echo QPTargetCell(Result("meta")) +''') + assert output.splitlines()==(['True'] if fault else ['False','CELL_A'])