fix(execution): bind explicit target cells to native save and recovery

This commit is contained in:
阿白叔 committed 2026-10-19 14:50:32 +08:00
1 parent 976a72d572
commit bb506a3550
7 files changed
+356 -20

No files matched your search

@@ -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()))
+37 -10
View File
@@ -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
+140
View File
@@ -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'])