fix: verify saved replacements through native netlist exports

This commit is contained in:
阿白叔 committed 2026-11-17 19:35:38 +08:00
1 parent d9cf6a07e9
commit d08a940afe
22 files changed
+1907 -177

No files matched your search

+14
View File
@@ -254,6 +254,20 @@ def test_hierarchy_has_no_arbitrary_depth_limit(tmp_path):
native_netlist._check_hierarchy_graph(path, {'components': {identity: {}}}, 'b0')
def test_root_port_name_with_slash_is_not_a_hierarchy_instance(tmp_path):
from dx_productivity.trial_task_center import native_netlist
effective = tmp_path / 'effective.txt'
effective.write_text(ascii_report() + ' Symbol LED2/RXDLY\tref des \tpage \n'
'\tPath \n\tSymbol name out.1 type \n')
components, nets = native_netlist._parse_ascii(effective)
hierarchy = tmp_path / 'hier.txt'
hierarchy.write_text(ascii_report().split('Config ')[0].replace('FLAT BLOCKS', 'HIER BLOCKS')
+ 'Block board \tRoot\n Symbol $1I1\tpage 1\n\tProp Ref Designator R1\n'
+ ' Symbol LED2/RXDLY\tpage 1\n\tSymbol name out.1 type \n')
native_netlist._check_hierarchy_graph(hierarchy, {'components': components, 'nets': nets}, 'board')
assert components['LED2/RXDLY']['source_page'] == '1'
def test_duplicate_nonidentity_attributes_are_preserved_and_require_declared_resolution(tmp_path):
from dx_productivity.trial_task_center import native_netlist
graph(tmp_path)
+47 -27
View File
@@ -1,4 +1,5 @@
"""Full selected C/A frames share a correlated read with untouched baselines."""
"""Selected writer snapshots and legacy correlated native capture frames."""
import re
import subprocess
import pytest
@@ -61,7 +62,7 @@ End If
''')
def test_generated_capture_uses_original_selected_snapshot_and_untouched_reader(tmp_path):
def test_legacy_generated_capture_uses_original_selected_snapshot_and_untouched_reader(tmp_path):
source=tmp_path/'source.vbs'
source.write_text(reader.MAIN.read_text(encoding='ascii')+'\n'+reader.ADAPTER.read_text(encoding='ascii'),encoding='ascii')
generated=tmp_path/'generated.vbs';result=tmp_path/'capture.tsv'
@@ -87,43 +88,62 @@ QPWriteUtf8 ''' + reader.quote(generated) + ''',Text
assert reader.PAIR in text and text.endswith('END\tnonce\t2\r\n')
@pytest.mark.parametrize('changed', ['', 'part', 'value', 'refdes'])
def test_capture_consumes_native_targets_without_external_pin_read_and_rechecks_scope(tmp_path, changed):
state = STATE.replace('\tOLD\t', '\tSAME\t') + 'A\tu1\tPart Number\tOLD\t\t0\t0\t1\t2\t3\t0\t1\r\n'
if changed == 'part':
state = state.replace('Part Number\tOLD', 'Part Number\tOTHER')
elif changed == 'value':
state = state.replace('Value\tSAME', 'Value\tCHANGED')
elif changed == 'refdes':
state = state.replace('C\tu1\tR1', 'C\tu1\tR9')
(tmp_path/'native-target.tsv').write_bytes(state.encode('ascii'))
@pytest.mark.parametrize('changed', ['', 'part', 'value', 'refdes', 'missing'])
def test_capture_reads_selected_com_attributes_without_native_or_fullpage_validation(tmp_path, changed):
fake=reader.NATIVE_FAKES.replace('Dim App,Comp', 'Dim App,Comp,Attr').replace(
'App.ActiveView.Components.Add Comp,True',
'Set Attr=New FullAttribute:Comp.Attributes.Add Attr,True\n'
' Set Attr=New FullAttribute:Attr.Name="Part Number":Attr.Value="OLD":Attr.InstanceValue="OLD":Comp.Attributes.Add Attr,True\n'
' App.ActiveView.Components.Add Comp,True',1)
def replace_native(code):
import re
code=re.sub(r'(?ms)^Function QPUseNativeSnapshot\([^\n]*\n.*?^End Function',
'Function QPUseNativeSnapshot()\n QPUseNativeSnapshot=True\nEnd Function',code)
return re.sub(r'(?ms)^Function QPNativeCapture\([^\n]*\n.*?^End Function', '''Function QPNativeCapture(ByRef Selected)
Dim Result,Targets
Set Result=CreateObject("Scripting.Dictionary"):Set Targets=CreateObject("Scripting.Dictionary")
Targets.Add "u1",QPReadUtf8(QP_Fso.BuildPath(QP_Root,"native-target.tsv"))
Result.Add "total",2:Result.Add "text","":Result.Add "selected",Targets
Set QPNativeCapture=Result
End Function''',code)
fake=fake.replace('Comp.UID="u2": Comp.Refdes="R2"',
'Comp.UID="u2": Comp.Refdes="R2":Comp.RaiseOnFind=True')
fake=fake.replace(' If Kind=128 Then Set Query=Components Else Set Query=Pins',
' If Kind<>128 Then Err.Raise 59000,"Forbidden","pin query"\n Set Query=Components')
if changed == 'part':
fake=fake.replace('Attr.Value="OLD":Attr.InstanceValue="OLD"',
'Attr.Value="OTHER":Attr.InstanceValue="OTHER"')
elif changed == 'value':
fake=fake.replace('Set Attr=New FullAttribute:Comp.Attributes.Add Attr,True',
'Set Attr=New FullAttribute:Attr.Value="CHANGED":Attr.InstanceValue="CHANGED":Comp.Attributes.Add Attr,True')
elif changed == 'refdes':
fake=fake.replace('Comp.UID="u1": Comp.Refdes="R1"','Comp.UID="u1": Comp.Refdes="R9"')
elif changed == 'missing':
fake=fake.replace('App.ActiveView.Components.Add Comp,True','',1)
def forbid_validation(code):
for name in ('QPUseNativeSnapshot', 'QPNativeCapture', 'QPNativeReadUntouched',
'QPCurrentSemanticState', 'QPVerifyUntouched', 'QPUntouchedComponent', 'QPComponentPins'):
pattern=rf'(?m)^(Function|Sub) {name}\([^\n]*\n[\s\S]*?^End \1'
def forbidden(match):
return match[0].split('\n',1)[0] + '\n Err.Raise 59000,"Forbidden","' + name + '"\nEnd ' + match[1]
code,count=re.subn(pattern,forbidden,code)
assert count==1,name
return code
output=reader.run_composed_fixture(tmp_path, '''
Dim Command,Failure
Dim Command,Failure,FailureSource
Set Command=CreateObject("Scripting.Dictionary")
Command.Add "project_path","c:\\board.prj":Command.Add "old_part_number","OLD":Command.Add "new_part_number","NEW"
Command.Add "job_id","job":Command.Add "value_mode","preserve":Command.Add "custom_value","":Command.Add "sync_nc","1"
Command.Add "target_scope","targets":Command.Add "target_selectors",QPEncode("u1" & Chr(31) & "R1" & Chr(31) & "SAME")
On Error Resume Next
QPCaptureAndSelect Command,QP_Fso.BuildPath(QP_Root,"snapshot.tsv")
Failure=Err.Number
Failure=Err.Number:FailureSource=Err.Source
Err.Clear
On Error GoTo 0
WScript.Echo CStr(Failure<>0)
WScript.Echo CStr(QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root,"snapshot.tsv")))
''',native_app=fake,routines_transform=replace_native)
assert output==(['True','False'] if changed else ['False','True'])
WScript.Echo CStr(FailureSource<>"Forbidden")
If Failure<>0 Then WScript.Echo FailureSource
''',native_app=fake,routines_transform=forbid_validation)
if changed:
assert output==['True','False','True','QuickPartReplace.Target']
return
assert output==['False','True','True']
rows=[line.split('\t') for line in (tmp_path/'snapshot.tsv').read_text(encoding='utf-8-sig').splitlines() if line]
assert [row for row in rows if row[0]=='X']==[['X','saved_netlist_v1']]
assert [row for row in rows if row[0]=='C']==[['C','u1','R1','0','0','0','1','NETLIST']]
assert not any(row[0] in {'U','G'} for row in rows)
attributes=[row for row in rows if row[0]=='A']
assert {row[1] for row in attributes}=={'u1'}
assert {row[2]:row[3:5] for row in attributes}=={'Part Number':['OLD','OLD'],'Value':['SAME','SAME']}
@@ -35,3 +35,63 @@ def test_native_closed_checkpoint_binds_project_marker_and_saved_source(tmp_path
assert validate_project_commit_source(proof, root)
marker.write_text('changed')
assert not validate_project_commit_source(proof, root)
@pytest.mark.parametrize('damage', [None, 'foreign_attempt', 'missing_native', 'bad_manifest', 'missing_expectations', 'old_snapshot'])
def test_saved_native_checkpoint_only_authorizes_export_validation(tmp_path, monkeypatch, damage):
from test_batch_runtime import command_for, worker_runtime
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
command, project = command_for(tmp_path)
root = Path(command[3])
token = 'a' * 32
(root / 'project-session.request').write_text(f'{token}\t{project}\tjob')
marker = root / ('project-commit-' + token + '.tsv')
def monitor(*args, **kwargs):
marker.write_text(f'{token}\t{project}\tproject_saved\njob\t' + ('saved_ok' if damage == 'bad_manifest' else 'pending_save') + '\n')
(root / 'snapshot-job.tsv').write_text('M\ttarget snapshot\n' + ('' if damage == 'old_snapshot' else 'X\tsaved_netlist_v1\n'))
if damage != 'missing_expectations':
(root / 'writer-expectations-job.tsv').write_text('bound target writer expectations')
if damage != 'missing_native':
expected = dict(runtime._current_attempts[0][1])
from dx_productivity.trial_task_center import batch_attempt
batch_attempt._publish(runtime._current_attempts[0][0], dict(expected, state='mutation_possible'))
if damage == 'foreign_attempt': expected['attempt_id'] = 'f' * 32
(root / 'snapshot-job.tsv.native.json').write_text(json.dumps({
'ok': True, 'stage': 'native_replace_applied', 'batch_attempt': expected}))
return subprocess.CompletedProcess(command, 0, '', '')
runtime = worker_runtime(tmp_path, monkeypatch, monitor)
monkeypatch.setattr(runtime, '_retain_uncertain', lambda *args: None)
with runtime:
if damage:
with pytest.raises((WorkerMonitorError, OSError)):
runtime.run_worker(command, 5)
return
runtime.run_worker(command, 5)
proof = json.loads((root / 'project-checkpoint.json').read_text(encoding='utf-8'))['project_commit_source']
assert proof['marker_state'] == 'project_saved' and proof['saved_only'] is True
assert proof['validation_required'] == 'saved_netlist_v1'
assert proof['outcomes'] == {'job': 'pending_save'}
assert proof['native_outcomes'] == {'job': 'pending_save'}
assert set(proof['readback_files']) == {'snapshot-job.tsv', 'snapshot-job.tsv.native.json', 'writer-expectations-job.tsv'}
assert not list(root.glob('post-state-*')) and not list(root.glob('value-readback-*'))
assert validate_project_commit_source(proof, root)
project.write_text('unexplained change after saved closure')
assert not validate_project_commit_source(proof, root)
def test_saved_native_no_match_checkpoint_requires_unmutated_attempt(tmp_path, monkeypatch):
from test_batch_runtime import command_for, worker_runtime
command, project = command_for(tmp_path)
root = Path(command[3])
token = 'a' * 32
(root / 'project-session.request').write_text(f'{token}\t{project}\tjob')
def monitor(*args, **kwargs):
(root / ('project-commit-' + token + '.tsv')).write_text(f'{token}\t{project}\tproject_saved\njob\tno_match\n')
return subprocess.CompletedProcess(command, 0, '', '')
runtime = worker_runtime(tmp_path, monkeypatch, monitor)
with runtime:
runtime.run_worker(command, 5)
proof = json.loads((root / 'project-checkpoint.json').read_text(encoding='utf-8'))['project_commit_source']
assert proof['saved_only'] is True and proof['outcomes'] == {'job': 'no_match'}
assert proof['validation_required'] == 'saved_netlist_v1' and proof['readback_files'] == {}
assert validate_project_commit_source(proof, root)
+24 -5
View File
@@ -377,11 +377,12 @@ def test_multiunit_value_evidence_covers_physical_selector_without_dropping_unit
def test_real_vbs_capture_records_all_units_of_one_physical_selector(tmp_path):
import test_accuracy_vbs_guards as guards
names=guards.UNTOUCHED_ROUTINES+['QPCaptureAndSelect','QPSnapshotComponent','QPCommandTargets',
names=['QPCaptureAndSelect','QPSnapshotComponent','QPCommandTargets','QPReadSnapshot','QPReadUtf8','QPWriteUtf8',
'QPSnapshotAttribute','QPSortSnapshotLines','QPOptionalAttributeField','QPFindCurrentAttribute','QPInvalidatePinIndex',
'QPBooleanText','QPLogField','QPTargetCell','QPRequireUniqueAttributeNames','QPAttributeObservations']
path=tmp_path/'units.tsv'
output=guards.run_vbs(tmp_path,names,'''
Dim A,B,Attr,Pin,Command,Records,Comp
Dim A,B,Attr,Command,Records,Comp
Set QP_App=New FakeApp
Set A=New FullComponent:A.UID="u1":A.Refdes="U1":A.X=0
Set B=New FullComponent:B.UID="u2":B.Refdes="U1":B.X=100
@@ -391,8 +392,6 @@ For Each Comp In Array(A,B)
Set Attr=New FullAttribute:Attr.Name="Value":Attr.Value="1K":Attr.InstanceValue="1K"
Comp.Attributes.Add Attr,True
QP_App.ActiveView.Components.Add Comp,True
Set Pin=New FakePin:Set Pin.Component=Comp:Pin.Number="1":Pin.X=Comp.X:Pin.Y=0
Set Pin.Connection=Nothing:QP_App.ActiveView.Pins.Add Pin,True
Next
Set Command=CreateObject("Scripting.Dictionary")
Command.Add "job_id","test":Command.Add "old_part_number","OLD":Command.Add "new_part_number","NEW"
@@ -403,9 +402,21 @@ Set Records=QPReadSnapshot("'''+str(path)+'''")
WScript.Echo Records("components").Count
WScript.Echo CapturedState
''',prelude=guards.LOG_STUB+guards.FULL_FAKE+'''
Dim CapturedState
Dim CapturedState,QP_SavedNetlistMode
Sub QPBuildComponentIndex(ByRef Components)
End Sub
Function QPComponentPins(ByVal Uid)
Err.Raise 59001,"Forbidden","pin query"
End Function
Function QPUseNativeSnapshot()
Err.Raise 59002,"Forbidden","native CAD read"
End Function
Function QPCurrentSemanticState()
Err.Raise 59003,"Forbidden","whole page"
End Function
Sub QPVerifyUntouched(ByRef Records)
Err.Raise 59004,"Forbidden","unselected validation"
End Sub
Function QPValueMode(ByRef Command)
QPValueMode="preserve"
End Function
@@ -420,6 +431,14 @@ Sub QPWriteStatus(ByVal Root,ByVal Job,ByVal State,ByVal Code,ByVal Message)
End Sub
''')
assert output.splitlines()==['2','awaiting_native_replace']
rows=[line.split('\t') for line in path.read_text(encoding='utf-8-sig').splitlines() if line]
assert [row for row in rows if row[0]=='X']==[['X','saved_netlist_v1']]
assert [row for row in rows if row[0]=='C']==[
['C','u1','U1','0','0','0','1','NETLIST'],
['C','u2','U1','100','0','0','1','NETLIST']]
assert {(row[1],row[2],row[3],row[4]) for row in rows if row[0]=='A'}=={
(uid,name,value,value) for uid in ('u1','u2') for name,value in (('Part Number','OLD'),('Value','1K'))}
assert not any(row[0] in {'U','G'} for row in rows)
def test_fresh_vbs_recovery_restores_interleaved_unselected_unit_aliases(tmp_path):
@@ -11,8 +11,9 @@ from dx_productivity.trial_task_center.stop_control import StopControl
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
@pytest.mark.parametrize('saved_native', [False, True])
@pytest.mark.parametrize('damage', [None, 'current_mutated', 'marker_missing', 'uncovered_prefix', 'source_unexplained', 'checkpoint'])
def test_prewrite_pause_certifies_only_current_job_and_hash_binds_committed_prefix(tmp_path, monkeypatch, damage):
def test_prewrite_pause_certifies_only_current_job_and_hash_binds_committed_prefix(tmp_path, monkeypatch, damage, saved_native):
from test_batch_runtime import command_for, worker_runtime, Cad
command, project = command_for(tmp_path)
root = Path(command[3])
@@ -34,9 +35,16 @@ def test_prewrite_pause_certifies_only_current_job_and_hash_binds_committed_pref
(root / ('project-pause-' + 'a'*32 + '.tsv')).write_text(f'{"a"*32}\t{project}\tnext\tprewrite_closed')
if damage != 'source_unexplained':
(root / ('project-commit-' + 'a'*32 + '.tsv')).write_text(
f'{"a"*32}\t{project}\tproject_verified\n' + ('foreign' if damage == 'uncovered_prefix' else 'job') + '\tsaved_ok\n')
for name in ('post-state-job.tsv', 'snapshot-job.tsv', 'snapshot-job.tsv.native.json', 'value-readback-job.tsv'):
(root / name).write_text('bound native prefix evidence')
f'{"a"*32}\t{project}\t' + ('project_saved' if saved_native else 'project_verified') + '\n'
+ ('foreign' if damage == 'uncovered_prefix' else 'job') + ('\tpending_save\n' if saved_native else '\tsaved_ok\n'))
if saved_native:
(root / 'snapshot-job.tsv').write_text('M\ttarget snapshot\nX\tsaved_netlist_v1\n')
(root / 'writer-expectations-job.tsv').write_text('bound target writer expectations')
(root / 'snapshot-job.tsv.native.json').write_text(__import__('json').dumps({
'ok': True, 'stage': 'native_replace_applied', 'batch_attempt': paths['job'][1]}))
else:
for name in ('post-state-job.tsv', 'snapshot-job.tsv', 'snapshot-job.tsv.native.json', 'value-readback-job.tsv'):
(root / name).write_text('bound native prefix evidence')
if damage == 'checkpoint':
runtime.cad.checkpoint = lambda *args: (_ for _ in ()).throw(WorkerMonitorError('project still open'))
result = subprocess.CompletedProcess(command, 75, '', '')
@@ -57,7 +65,9 @@ def test_prewrite_pause_certifies_only_current_job_and_hash_binds_committed_pref
assert proof['phase'] == 'before_native_dispatch' and proof['job_id'] == 'next'
assert len(proof['batch_attempts']) == 1
assert proof['batch_attempts'][0]['expected']['job_id'] == 'next'
assert proof['committed_prefix'] == {'job': 'saved_ok'}
assert proof['committed_prefix'] == {'job': 'pending_save' if saved_native else 'saved_ok'}
if saved_native:
assert proof['prefix_marker_state'] == 'project_saved' and proof['prefix_validation_required'] is True
assert proof['native_dispatch_not_started'] and proof['project_closed']
assert proof['files']
@@ -0,0 +1,80 @@
import hashlib
import json
from pathlib import Path
from threading import Event
from types import ModuleType, SimpleNamespace
import pytest
from test_execution_proof import proof_case
from dx_productivity.trial_task_center.native_helper import read_snapshot, transaction_binding
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
@pytest.mark.parametrize('actual,present', [('33R', True), ('', None)])
def test_applied_writer_receipt_uses_saved_native_proof_instead_of_cad_readback(proof_case, actual, present):
from dx_productivity.trial_task_center.netlist_verification import library_from_receipt
_, root, command = proof_case
snapshot = root / 'snapshot-job.tsv'
text = snapshot.read_text(encoding='utf-8').replace('\tpins\n', '\tNETLIST\n')
snapshot.write_text(text + 'X\tsaved_netlist_v1\n', encoding='utf-8')
metadata, records = read_snapshot(snapshot)
report_path = Path(str(snapshot) + '.native.json')
report = json.loads(report_path.read_text(encoding='utf-8'))
report.update(stage='native_replace_applied', transaction=transaction_binding(
snapshot, metadata, records, ['lib', 'NEW', 'sym', '', 'name', 'label'], 'sym'))
report_path.write_text(json.dumps(report), encoding='utf-8')
proof = {'files': [{'path': str(p), 'sha256': hashlib.sha256(p.read_bytes()).hexdigest()}
for p in (snapshot, report_path)],
'saved_netlist': {'status': 'verified'}}
receipt = {'native_state': 'saved_ok', 'job_id': 'job', 'proof': proof}
proof['value_readback'] = dict(value_readback_status='verified', value_readback_job_id='job',
project_path=command['project_path'], schematic_name=command['schematic_name'], sheet_number=command['sheet_number'],
value_readback=[dict(uid='uid', actual_part_number='NEW', actual_value=actual, actual_value_present=present,
value_presence_coverage='native_ascii_empty_presence_unknown')])
assert library_from_receipt(command, receipt)['uid']['attributes']['Part Number'] == 'NEW'
assert library_from_receipt(command, receipt)['uid']['preserved_value_present'] is present
proof.pop('saved_netlist')
with pytest.raises(ValueError):
library_from_receipt(command, receipt)
report['stage'] = 'native_replace_verified'
report_path.write_text(json.dumps(report), encoding='utf-8')
proof['files'][1]['sha256'] = hashlib.sha256(report_path.read_bytes()).hexdigest()
with pytest.raises(ValueError):
library_from_receipt(command, receipt)
def test_independent_comparison_reuses_verified_saved_export(tmp_path, monkeypatch):
import sys
from dx_productivity.trial_task_center import native_netlist
from dx_productivity.trial_task_center.netlist_verification import NetlistVerification
project = tmp_path / 'board.prj'
project.write_text('project', encoding='utf-8')
row = TargetPlanRow(ComponentTarget(project, 'MAIN', '1', 'u', 'R1', 'OLD', '33R'), True, 'NEW')
child = SimpleNamespace(target_plan=lambda _: (row,), projects=lambda _: (SimpleNamespace(path=project),),
get_task=lambda _: SimpleNamespace(copy_part_number_to_value=False),
_quick_run_preparer=SimpleNamespace(data_root=tmp_path / 'data/tasks/task'))
captures = []
def capture(source, destination):
captures.append(source)
destination.mkdir(parents=True)
return {'project': str(source), 'root': str(destination)}
def graph(part):
return {'components': {'u': {'refdes': 'R1', 'attributes': {'Part Number': part, 'Value': '33R'}}},
'nets': [{'name': 'N', 'endpoints': [['u', '1']]}]}
before = {'status': 'success', 'complete': True, 'graph': graph('OLD'), 'outputs': {}}
after = {'status': 'success', 'complete': True, 'graph': graph('NEW'), 'outputs': {}}
saved = {'status': 'verified', 'capture': {'project': str(project), 'root': str(tmp_path / 'saved')},
'result': after, 'export_path': str(tmp_path / 'saved-export/netlist.json')}
# The saved-source verifier is a separately exercised native I/O boundary.
module = ModuleType('dx_productivity.trial_task_center.saved_netlist_verification')
module.load_saved_export = lambda root, path: saved
monkeypatch.setitem(sys.modules, module.__name__, module)
monkeypatch.setattr(native_netlist, 'capture_project', capture)
monkeypatch.setattr(native_netlist, 'export_netlist', lambda *a, **kw: before)
with NetlistVerification(tmp_path / 'data', 'run', Event()) as checks:
checks.before_task(child, 'task')
checks.after_task('task', execution_summary={'saved_items': 1})
result = checks.finish()['task']
assert len(captures) == 1, 'already verified after-export must not be captured/exported again'
assert result['verified'] is True
+78
View File
@@ -0,0 +1,78 @@
import hashlib
import json
import pytest
from test_project_commit_journal import staged_case
from dx_productivity.trial_task_center.errors import TaskCenterError
def test_saved_proof_promotion_is_compare_and_swap_and_keeps_source_binding(staged_case, tmp_path):
store, journal, task, rows, proof = staged_case
token = 'a' * 32
attempt = journal.claim(task, rows[0])
journal.stage_project_result(attempt, rows[0], session_token=token, root=tmp_path, proof=proof)
source = dict(proof, session_token=token, project_path=rows[0]['project_path'], jobs=['job1'],
marker_state='project_saved', saved_only=True, validation_required='saved_netlist_v1',
native_outcomes={'job1': 'pending_save'}, outcomes={'job1': 'pending_save'})
journal.bind_project_commit_proof(task, token, source)
verified = dict(source, outcomes={'job1': 'saved_ok'}, saved_netlist={'status': 'verified'})
with pytest.raises(TaskCenterError):
journal.promote_project_commit_proof(task, token, dict(source, jobs=[]), verified)
with pytest.raises(TaskCenterError):
journal.promote_project_commit_proof(task, token, source, dict(verified, project_path='other.prj'))
journal.promote_project_commit_proof(task, token, source, verified)
journal.promote_project_commit_proof(task, token, source, verified)
stored, = journal.pending_project_commits(task)
assert json.loads(stored['proof_json']) == verified
def test_saved_project_requires_native_export_before_committing_receipts(staged_case, tmp_path):
store, journal, task, rows, old_proof = staged_case
proof = {'files': old_proof['files']}
for row in rows:
journal.stage_project_result(journal.claim(task, row), row,
session_token='a' * 32, root=tmp_path, proof=proof)
jobs = [row['job_id'] for row in rows]
commit = dict(proof, session_token='a' * 32, project_path=rows[0]['project_path'], jobs=jobs,
marker_state='project_saved', saved_only=True, validation_required='saved_netlist_v1',
native_outcomes={job: 'pending_save' for job in jobs},
outcomes={job: 'saved_ok' for job in jobs})
with pytest.raises(TaskCenterError):
journal.commit_project_results(task, 'a' * 32, dict.fromkeys(jobs, proof), commit)
assert [r[0] for r in store._connection.execute('SELECT state FROM execution_operations')] == ['pending_save'] * 2
def test_native_baseline_and_commit_references_do_not_duplicate_all_job_payloads(staged_case, tmp_path):
store, journal, task, rows, old_proof = staged_case
proof = {'files': old_proof['files']}
attempts = {}
for row in rows:
attempt = journal.claim(task, row)
attempts[row['job_id']] = [attempt.operation_key, attempt.attempt_id, attempt.generation]
journal.stage_project_result(attempt, row, session_token='a' * 32, root=tmp_path, proof=proof)
jobs = list(attempts)
exported = tmp_path / 'netlist.json'
exported.write_text('{"export":"saved native data"}', encoding='utf-8')
digest = hashlib.sha256(exported.read_bytes()).hexdigest()
saved = {'status': 'verified', 'export_path': str(exported), 'export_sha256': digest,
'files': [{'path': str(exported), 'sha256': digest}],
'jobs': {job: {'value_readback_status': 'verified'} for job in jobs}}
other_input = tmp_path / 'other-job-input.tsv'
other_input.write_text('another target snapshot', encoding='utf-8')
saved['files'].append({'path': str(other_input), 'sha256': hashlib.sha256(other_input.read_bytes()).hexdigest()})
commit = dict(proof, session_token='a' * 32, project_path=rows[0]['project_path'], jobs=jobs,
marker_state='project_saved', saved_only=True, validation_required='saved_netlist_v1',
native_outcomes={job: 'pending_save' for job in jobs}, outcomes={job: 'saved_ok' for job in jobs},
saved_netlist=saved, operation_attempts=attempts)
journal.commit_project_results(task, 'a' * 32, dict.fromkeys(jobs, proof), commit)
records = store._connection.execute('SELECT receipt_json FROM execution_operations').fetchall()
for record, job in zip(records, jobs):
bound = json.loads(record[0])['proof']['project_commit']
assert 'jobs' not in bound.get('saved_netlist', {}), 'per-job receipts must not repeat every target'
assert set(bound['operation_attempts']) == {job}
assert str(other_input) not in {item['path'] for item in json.loads(record[0])['proof']['files']}
baseline, = journal.expected_baselines(task, rows[0]['project_path'])
assert baseline['validation_mode'] == 'saved_netlist_v1'
assert baseline['state'] == 'N\tsaved_netlist_v1\t' + digest
assert journal.project_commit_attempts(task, 'a' * 32) == attempts
@@ -0,0 +1,405 @@
import json
from pathlib import Path
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.execution_proof import capture_project_commit
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _encode_vbs_field as enc, _run_process, _write_uncertain_flag
from dx_productivity.trial_task_center.native_helper import read_snapshot, transaction_binding
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.history_store import HistoryRepository
from dx_productivity.trial_task_center.models import TaskStatus
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
def test_saved_marker_is_pending_until_native_netlist_verifies(tmp_path):
root = tmp_path / 'quick-run'; root.mkdir()
project = tmp_path / 'board.prj'; project.write_text('saved')
token = 'a' * 32
(root / f'project-commit-{token}.tsv').write_text(
f'{token}\t{project}\tproject_saved\njob\tpending_save\n')
proof = capture_project_commit(tmp_path, root, dict(session_token=token,
project_path=str(project.resolve()).casefold(), jobs_json=json.dumps(['job'])))
assert proof['validation_required'] == 'saved_netlist_v1'
assert proof['marker_state'] == 'project_saved'
assert proof['outcomes'] == {'job': 'pending_save'}
assert 'saved_netlist' not in proof
@pytest.fixture
def saved_case(tmp_path, monkeypatch, request):
from dx_productivity.trial_task_center import native_netlist
from test_native_cli_netlist import project_fixture, ascii_report
monkeypatch.setattr('dx_productivity.trial_task_center.scanner._is_schematic_project', lambda _: True)
project = project_fixture(tmp_path)
project.write_text(project.read_text().replace('"board"', '"MAIN"'))
data = tmp_path / 'data'
preparer = QuickRunPreparer(data, process_runner=_run_process,
cscript_resolver=lambda: Path('cscript.exe'), sheet_discoverer=lambda _: (('MAIN', '1'),))
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(data), quick_run_preparer=preparer)
task = service.create_task('saved native netlist')
service.scan_projects(task.task_id, project.parent)
for selected in service.projects(task.task_id):service.set_project_selected(selected.project_id, True)
service.add_rule(task.task_id, 'OLD1', 'NEW1',target_cell='CELL'); service.add_rule(task.task_id, 'OLD2', 'NEW2',target_cell='CELL')
handoff = preparer.prepare(task.task_id, service.projects(task.task_id), service.rules(task.task_id),
sheet_targets={str(project.resolve()).casefold(): (('MAIN', '1'),)})
rows = list(preparer._bind_journal_handoff(task.task_id, handoff).values())
session = preparer.begin_batch_session(task.task_id,service.projects(task.task_id),service.rules(task.task_id))
root = data / 'quick-run'; token = 'a'*32
for index, row in enumerate(rows, 1):
job, uid, ref = row['job_id'], f'$1I{index}', f'R{index}'
path = root / f'snapshot-{job}.tsv'
path.write_text('\t'.join(map(enc, ['M', str(project), row['old_part'], row['new_part'], 'MAIN:1', 'preserve', '', '1'])) + '\n' +
f'L\tCELL\nX\tsaved_netlist_v1\nC\t{uid}\t{ref}\t0\t0\t0\t1\tNETLIST\nA\t{uid}\tValue\tOLD_VALUE\tOLD_VALUE\t0\t0\t0\t0\t1\t0\t1\n')
metadata, components = read_snapshot(path)
report = dict(ok=True, stage='native_replace_applied', transaction=transaction_binding(path, metadata, components,
['lib', row['new_part'], 'symbol', '', 'NAME'+str(index), 'LABEL'+str(index)], 'symbol'),
batch_attempt=dict(task_id=task.task_id,job_id=job,project_path=str(project),session_id='b'*32,attempt_id='c'*32,generation=1))
Path(str(path)+'.native.json').write_text(json.dumps(report))
expectation = [['W','1',task.task_id,job,str(project),'MAIN','1',path.read_bytes().decode()],
['C',uid,ref,'10K','1','NAME'+str(index),'LABEL'+str(index),row['new_part'],'CELL']]
(root / f'writer-expectations-{job}.tsv').write_text('\n'.join('\t'.join(map(enc, line)) for line in expectation)+'\n')
if getattr(request,'param',None) != 'execute':
attempt = preparer.journal.claim(task.task_id, row)
staged = preparer.result_proof(root, row, ('pending_save','session_staged','applied'))
preparer.journal.stage_project_result(attempt,row,session_token=token,root=root,proof=staged)
(root / f'project-commit-{token}.tsv').write_text(f'{token}\t{project}\tproject_saved\n'+
''.join(row['job_id']+'\tpending_save\n' for row in rows))
installation = tmp_path / 'installation'
for name in ('iCDB/win32/bin/icdb2ascii.exe','wv/win32/bin/KeyinNetlist.exe'):
executable = installation / name; executable.parent.mkdir(parents=True,exist_ok=True); executable.touch()
monkeypatch.setattr(native_netlist,'installation_root',lambda:installation)
control = {'calls':[], 'damage':None, 'session':session}
class Scope:
cleanup_record = {'workers_closed':True}
def __enter__(self):return self
def __exit__(self,*args):pass
def start_process(self,command,*,cwd,**kwargs):
control['calls'].append(command)
parts = []
for index in (1,2):
part = 'WRONG' if control['damage']=='part' and index==2 else 'NEW'+str(index)
value = 'WRONG' if control['damage']=='value' and index==2 else '10K'
base = ascii_report(part).replace('$1I1',f'$1I{index}').replace('R1',f'R{index}').replace('page \t','page 1\t')
base = base.replace('ref des '+f'R{index}'+'\tpage \n',f'ref des R{index}\tpage 1\n')
symbol = base[base.index(' Symbol '):].replace('Prop Value 10K','Prop Value '+value)
symbol += f'\tProp Part Name NAME{index}\n\tProp Part Label LABEL{index}\n'
symbol += '\tProp Cell Name '+('WRONG' if control['damage']=='cell' and index==2 else 'CELL')+'\n'
parts.append(symbol)
if '-h' in command:
text = ascii_report().split('Config default')[0].replace('FLAT BLOCKS','HIER BLOCKS')+'Block MAIN \tRoot\n'
for index in (1,2):
text += f' Symbol $1I{index}\tpage 1\n\tProp Ref Designator R{index}\n\tProp Part Number NEW{index}\n\tProp Value 10K\n'
if control['damage']=='partial':text += ' Symbol $1I3\tpage 1\n\tProp Part Number MISSING\n'
path = next(arg[6:] for arg in command if arg.startswith('-file='))
elif '-f' in command:
text = ascii_report().split('Config default')[0]+'Config default\tview none\n\tNet N1\n'
text += ''.join(f'\t\tConn $1I{i} pin A page 1\n\t\tPath root\n' for i in (1,2))+''.join(parts)
path = next(arg[6:] for arg in command if arg.startswith('-file='))
else:
text = ';; V4.1.0\n%net\n%page=MAIN\n\\N1\\ \\R1\\-\\1\\ \\R2\\-\\1\\\n%Part\n\\NEW1\\ \\R1\\\n\\NEW2\\ \\R2\\\n'
path = next(arg[5:] for arg in command if arg.startswith('-out='))
Path(path).write_text(text)
if control['damage']=='source':(project.parent/'database/icdb.dat').write_bytes(b'changed during export')
return type('Process',(),{'poll':lambda self:0})()
monkeypatch.setattr(native_netlist,'OwnedCliScope',Scope)
monkeypatch.setattr(TaskCenterService,'_owned_cad_operation',lambda *a,**k:pytest.fail('CAD fallback/replay'))
yield service,store,task.task_id,preparer,project,rows,control
store.close()
def test_saved_prefix_exports_once_and_commits_without_cad_readback(saved_case):
service,store,task,preparer,project,rows,control = saved_case
preparer._commit_staged_project(task,bind_source=True)
assert len(control['calls']) == 3
operations = store._connection.execute('SELECT state,receipt_json FROM execution_operations').fetchall()
assert [row['state'] for row in operations] == ['verified','verified']
for item in operations:
proof = json.loads(item['receipt_json'])['proof']
assert proof['saved_netlist']['status']=='verified'
assert proof['value_readback']['value_readback_status']=='verified'
assert proof['baseline']['validation_mode']=='saved_netlist_v1'
assert proof['baseline']['state'].startswith('N\tsaved_netlist_v1\t')
assert not list((preparer.data_root/'quick-run').glob('post-state-*'))
assert not list((preparer.data_root/'quick-run').glob('value-readback-*.tsv'))
preparer.write_expected_baselines(task,preparer.data_root/'quick-run',str(project))
assert (preparer.data_root/'quick-run'/'expected-baselines.tsv').read_text().splitlines() == [
'project_path\tschematic_name\tsheet_number\tsemantic_state']
from dx_productivity.trial_task_center.saved_netlist_verification import load_saved_export
pointer = preparer.data_root/'quick-run/saved-netlist-export.json'
cached = json.loads(pointer.read_text())
cached['result']['graph']['components']['$1I1']['attributes']['Value']='MUTABLE_WRONG'
cached['jobs'][rows[0]['job_id']]['value_readback'][0]['actual_value']='MUTABLE_WRONG'
pointer.write_text(json.dumps(cached))
loaded = load_saved_export(preparer.data_root/'quick-run',project)
assert loaded['result']['graph']['components']['$1I1']['attributes']['Value']=='10K'
assert loaded['jobs'][rows[0]['job_id']]['value_readback'][0]['actual_value']=='10K'
@pytest.mark.parametrize('damage',['part','value','cell','partial','source','unavailable','writer_evidence'])
def test_saved_prefix_export_failure_keeps_all_items_pending(saved_case,damage,monkeypatch):
service,store,task,preparer,project,rows,control = saved_case
control['damage']=damage
if damage=='unavailable':
from dx_productivity.trial_task_center import native_netlist
monkeypatch.setattr(native_netlist,'installation_root',lambda:preparer.data_root/'missing-installation')
elif damage=='writer_evidence':
path = preparer.data_root/'quick-run'/f'writer-expectations-{rows[0]["job_id"]}.tsv'
path.write_text(path.read_text().replace('10K','WRONG'))
with pytest.raises((TaskCenterError,ValueError)):preparer._commit_staged_project(task,bind_source=True)
assert all(row[0]=='pending_save' for row in store._connection.execute('SELECT state FROM execution_operations'))
def test_saved_export_recovers_real_service_after_history_failure_and_restart(saved_case,monkeypatch):
service,store,task,preparer,project,rows,control = saved_case
original = HistoryRepository.append
monkeypatch.setattr(HistoryRepository,'append',lambda *a,**k:(_ for _ in ()).throw(OSError('history disk full')))
with pytest.raises(OSError):preparer._commit_staged_project(task,bind_source=True)
monkeypatch.setattr(HistoryRepository,'append',original)
root = preparer.data_root/'quick-run'
_write_uncertain_flag(root/'uncertain.flag','receipt_commit_failed')
store.set_task_status(task,TaskStatus.BLOCKED)
reopened = TaskStore(store.path)
try:
worker = QuickRunPreparer(preparer.data_root,process_runner=_run_process)
resumed = TaskCenterService(reopened,configure_logging(preparer.data_root),quick_run_preparer=worker)
assert resumed.recover_quick_run(task,confirmed=True).progress.saved_items==2
assert reopened.get_task(task).status is TaskStatus.COMPLETED
assert len(control['calls'])==3
assert resumed.recover_quick_run(task,confirmed=True).state=='saved_ok'
assert len(control['calls'])==3
finally:reopened.close()
@pytest.mark.parametrize('damage',[None,'source','writer'])
def test_runtime_saved_checkpoint_recovers_before_sql_callback_after_restart(saved_case,damage):
from types import SimpleNamespace
from test_batch_runtime import Desktop
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
from dx_productivity.trial_task_center.batch_attempt import prepare_attempt, _publish
service,store,task,preparer,project,rows,control = saved_case
root = preparer.data_root/'quick-run'
runtime = BatchCadRuntime(preparer.data_root,'execution',desktop_factory=Desktop,session_id='b'*32)
runtime._ensure_desktop()
runtime.cad = SimpleNamespace(checkpoint=lambda _:None)
runtime.record['active_job'] = rows[0]['job_id']
for row in rows:
path = runtime.path.parent/'attempts'/f'{row["job_id"]}.json'
expected = prepare_attempt(path,session_id='b'*32,generation=1,task_id=task,
job_id=row['job_id'],project_path=str(project),attempt_id='c'*32)
_publish(path,dict(expected,state='mutation_possible'))
runtime._current_attempts.append((path,expected))
(root/'project-session.request').write_text('a'*32+'\t'+str(project)+'\t'+rows[0]['job_id'])
runtime._checkpoint(root,project,'c'*32)
runtime.desktop.close(); runtime.record['cleanup']=runtime.desktop.cleanup_record
runtime.desktop=runtime.cad=None; runtime._record_release()
assert preparer.journal.project_commit_records(task)[0]['proof_json'] is None
if damage=='source':(project.parent/'database/icdb.dat').write_bytes(b'changed after close')
elif damage=='writer':(root/f'writer-expectations-{rows[0]["job_id"]}.tsv').write_text('changed after close')
_write_uncertain_flag(root/'uncertain.flag','project_commit_unverified')
store.set_task_status(task,TaskStatus.BLOCKED)
reopened = TaskStore(store.path)
try:
worker = QuickRunPreparer(preparer.data_root,process_runner=_run_process)
resumed = TaskCenterService(reopened,configure_logging(preparer.data_root),quick_run_preparer=worker)
if damage:
with pytest.raises(TaskCenterError):resumed.recover_quick_run(task,confirmed=True)
assert (root/'uncertain.flag').is_file()
assert not control['calls']
else:
assert resumed.recover_quick_run(task,confirmed=True).progress.saved_items==2
assert reopened.get_task(task).status is TaskStatus.COMPLETED
assert len(control['calls'])==3
finally:reopened.close()
def test_mutable_export_pointer_cannot_override_immutable_native_graph(saved_case):
service,store,task,preparer,project,rows,control = saved_case
control['damage']='value'
with pytest.raises(ValueError):preparer._commit_staged_project(task,bind_source=True)
pointer = preparer.data_root/'quick-run/saved-netlist-export.json'
record = json.loads(pointer.read_text())
for component in record['result']['graph']['components'].values():component['attributes']['Value']='10K'
pointer.write_text(json.dumps(record))
with pytest.raises(ValueError):preparer._commit_staged_project(task)
assert all(row[0]=='pending_save' for row in store._connection.execute('SELECT state FROM execution_operations'))
def test_saved_prefix_mixed_applied_and_no_match_commits_after_one_export(saved_case):
service,store,task,preparer,project,rows,control = saved_case
root = preparer.data_root/'quick-run'; job = rows[1]['job_id']
record = store._connection.execute('SELECT operation_key,receipt_json FROM execution_operations ORDER BY rowid DESC LIMIT 1').fetchone()
receipt = json.loads(record['receipt_json']); receipt['proof']={'files':[]}; receipt['code']='session_staged_no_match'
store._connection.execute('UPDATE execution_operations SET receipt_json=? WHERE operation_key=?',(json.dumps(receipt),record['operation_key']))
for name in (f'snapshot-{job}.tsv',f'snapshot-{job}.tsv.native.json',f'writer-expectations-{job}.tsv'):(root/name).unlink()
marker = root/('project-commit-'+'a'*32+'.tsv')
marker.write_text(marker.read_text().replace(job+'\tpending_save',job+'\tno_match'))
preparer._commit_staged_project(task,bind_source=True)
records = store._connection.execute('SELECT state,receipt_json FROM execution_operations ORDER BY rowid').fetchall()
assert [row['state'] for row in records]==['verified','no_match']
assert json.loads(records[1]['receipt_json'])['proof']['files']
assert len(control['calls'])==3
def test_scoped_multiunit_preserve_checks_each_declared_library_default():
from dx_productivity.trial_task_center.saved_netlist_verification import _observations
row = dict(task_id='task',job_id='job',project_path='board.prj',old_part='OLD',new_part='NEW',schematic_name='MAIN',sheet_number='1')
attrs = {'Part Number':'NEW','Part Name':'NAME','Part Label':'LABEL'}
graph = {'components':{uid:dict(refdes='U1',source_page='1',source_schematic='MAIN',attributes=dict(attrs,Value=value))
for uid,value in (('native-a','10K'),('native-b','20K'))}}
expected = {uid:dict(refdes='U1',attributes=attrs,value=value,present=True,old_value='OLD',target_cell='')
for uid,value in (('original-a','10K'),('original-b','20K'))}
values = _observations(graph,row,expected,dict(target_symbol='symbol',slot_count=2))['value_readback']
assert [item['actual_value'] for item in values]==['10K','20K']
def test_native_commit_preserves_active_batch_status_identity_and_incremental_tail(saved_case):
from types import SimpleNamespace
service,store,task,preparer,project,rows,control = saved_case
session = control['session']
original_identity = session.status_identity
preparer._commit_staged_project(task,bind_source=True)
progress = preparer.complete_project_session(task,SimpleNamespace(worker=None),session,service.projects(task))
assert progress.saved_items==2 and progress.queue_complete
assert session.status_identity==original_identity
@pytest.mark.parametrize('saved_case',['execute'],indirect=True)
@pytest.mark.parametrize('entrypoint',['single','disabled_scope','retained_scope'])
def test_nonretained_entrypoint_commits_one_saved_native_prefix(saved_case,monkeypatch,entrypoint):
import subprocess
from contextlib import contextmanager
from types import SimpleNamespace
service,store,task,preparer,project,rows,control = saved_case
root = preparer.data_root/'quick-run'
monkeypatch.setattr('dx_productivity.trial_task_center.cell_catalog.preflight_command_target',lambda *a:None)
control['closes']=0
class Boundary:
enabled=True
worker=None
on_commit=None
def prepare(self,project):pass
def run_step(self,project,command,timeout):
assert self.enabled
self.job=command[-1]
if self.worker is None:self.jobs=[]
self.jobs.append(self.job)
self.worker=SimpleNamespace(root=root,token='e'*32)
with (root/'status.tsv').open('a') as stream:stream.write(self.job+'\tpending_save\tsession_staged\tstaged native write\n')
return subprocess.CompletedProcess(command,0,'','')
def close(self):
if self.worker is None:return
control['closes']+=1
(root/f'project-commit-{self.worker.token}.tsv').write_text(self.worker.token+'\t'+str(project)+'\tproject_saved\n'+
''.join(job+'\tpending_save\n' for job in self.jobs))
if self.on_commit:self.on_commit(self.worker)
self.worker=None
@contextmanager
def scope(**kwargs):
assert kwargs.get('enabled',True)
boundary=Boundary()
try:yield boundary
finally:boundary.close()
preparer.project_session_scope=scope
runtime=SimpleNamespace()
if entrypoint=='single':result=service.execute_quick_run(task,runtime=runtime)
elif entrypoint=='retained_scope':
with scope(enabled=True) as boundary:
staged=preparer.execute_step(task,service.projects(task),service.rules(task),batch_mode=True,
batch_session=control['session'],project_session=boundary,runtime=runtime)
assert staged.state=='pending_save' and control['closes']==0
result=preparer.execute_step(task,service.projects(task),service.rules(task),batch_mode=True,
batch_session=control['session'],project_session=boundary,runtime=runtime)
else:
disabled=SimpleNamespace(enabled=False,run_step=lambda *a:pytest.fail('disabled legacy native path used'))
result=preparer.execute_step(task,service.projects(task),service.rules(task),batch_mode=True,
batch_session=control['session'],project_session=disabled,runtime=runtime)
completed = 2 if entrypoint=='retained_scope' else 1
assert result.state=='saved_ok' and result.progress.saved_items==completed
assert result.progress.completed_items==completed and result.progress.queue_complete is (completed==2)
assert control['closes']==1 and len(control['calls'])==3
assert [row[0] for row in store._connection.execute('SELECT state FROM execution_operations ORDER BY rowid')]==(
['verified','verified'] if completed==2 else ['verified','pending'])
from dx_productivity.trial_task_center.value_readback import value_readback_details
assert value_readback_details(result)['value_readback']['value_readback_status']=='verified'
@pytest.mark.parametrize('saved_case',['execute'],indirect=True)
@pytest.mark.parametrize(('failure','damage'),[('history',None),('before_sql',None),('after_sql',None),
('history','historical_marker'),('history','historical_artifact'),('history','historical_attempt'),
('history','current_source'),('history','later_actual')])
def test_two_saved_prefixes_recover_latest_source_without_replaying_history(saved_case,monkeypatch,failure,damage):
from types import SimpleNamespace
from test_batch_runtime import Desktop
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
from dx_productivity.trial_task_center.batch_attempt import prepare_attempt, _publish
from dx_productivity.trial_task_center.batch_supervisor import _mark_interrupted
service,store,task,preparer,project,rows,control = saved_case
root=preparer.data_root/'quick-run'; first='a'*32; second='f'*32
attempt=preparer.journal.claim(task,rows[0])
proof=preparer.result_proof(root,rows[0],('pending_save','session_staged','first native prefix'))
preparer.journal.stage_project_result(attempt,rows[0],session_token=first,root=root,proof=proof)
(root/f'project-commit-{first}.tsv').write_text(f'{first}\t{project}\tproject_saved\n{rows[0]["job_id"]}\tpending_save\n')
preparer._commit_staged_project(task,session_token=first,bind_source=True)
first_attempt=tuple(store._connection.execute('SELECT attempt_id,generation FROM execution_operations ORDER BY rowid LIMIT 1').fetchone())
(project.parent/'database/icdb.dat').write_bytes(b'saved second prefix changes the live engineering database')
attempt=preparer.journal.claim(task,rows[1])
proof=preparer.result_proof(root,rows[1],('pending_save','session_staged','second native prefix'))
preparer.journal.stage_project_result(attempt,rows[1],session_token=second,root=root,proof=proof)
(root/f'project-commit-{second}.tsv').write_text(f'{second}\t{project}\tproject_saved\n{rows[1]["job_id"]}\tpending_save\n')
if failure=='before_sql':
runtime=BatchCadRuntime(preparer.data_root,'execution',desktop_factory=Desktop,session_id='b'*32)
runtime._ensure_desktop(); runtime.cad=SimpleNamespace(checkpoint=lambda _:None)
runtime.record.update(active_job=rows[1]['job_id'],active_task=task)
path=runtime.path.parent/'attempts'/f'{rows[1]["job_id"]}.json'
expected=prepare_attempt(path,session_id='b'*32,generation=1,task_id=task,
job_id=rows[1]['job_id'],project_path=str(project),attempt_id='c'*32)
_publish(path,dict(expected,state='mutation_possible'));runtime._current_attempts=[(path,expected)]
(root/'project-session.request').write_text(second+'\t'+str(project)+'\t'+rows[1]['job_id'])
runtime._checkpoint(root,project,'c'*32)
runtime.desktop.close();runtime.record['cleanup']=runtime.desktop.cleanup_record
runtime.desktop=runtime.cad=None;runtime._record_release()
_mark_interrupted(preparer.data_root,dict(batch_id=runtime.session_id,operation='execute_task_queue',
task_ids=[task],uncertainty_roots={task:str(preparer.data_root)}),'parent crashed before second SQL callback')
else:
original=HistoryRepository.append
if failure=='history':
monkeypatch.setattr(HistoryRepository,'append',lambda *a,**k:(_ for _ in ()).throw(OSError('second prefix history failure')))
with pytest.raises(OSError):preparer._commit_staged_project(task,session_token=second,bind_source=True)
monkeypatch.setattr(HistoryRepository,'append',original)
else:preparer._commit_staged_project(task,session_token=second,bind_source=True)
_write_uncertain_flag(root/'uncertain.flag','receipt_commit_failed')
store.set_task_status(task,TaskStatus.BLOCKED)
if damage=='historical_marker':(root/f'project-commit-{first}.tsv').write_text('changed historical marker')
elif damage=='historical_artifact':
original_proof=json.loads(next(item for item in preparer.journal.project_commit_records(task) if item['session_token']==first)['proof_json'])
Path(original_proof['saved_netlist']['verification_path']).write_text('{}')
elif damage=='historical_attempt':
store._connection.execute('UPDATE execution_operations SET generation=generation+1 WHERE operation_key=?',
(preparer.journal.project_commit_attempts(task,first)[rows[0]['job_id']][0],))
elif damage=='current_source':(project.parent/'database/icdb.dat').write_bytes(b'unexplained latest-source modification')
elif damage=='later_actual':
item=dict(store._connection.execute('SELECT * FROM execution_operations LIMIT 1').fetchone())
command=json.loads(item['command_json']);command['old_part']='LATER'
store._connection.execute('''INSERT INTO execution_operations(task_id,round_id,operation_key,command_json,state,attempt_id,generation)
VALUES (?,?,?,?,'prepared',?,1)''',(task,item['round_id'],'later-operation',json.dumps(command),'d'*32))
calls_before=len(control['calls'])
reopened=TaskStore(store.path)
try:
worker=QuickRunPreparer(preparer.data_root,process_runner=_run_process)
resumed=TaskCenterService(reopened,configure_logging(preparer.data_root),quick_run_preparer=worker)
if damage:
with pytest.raises(TaskCenterError):resumed.recover_quick_run(task,confirmed=True)
assert reopened.get_task(task).status is TaskStatus.BLOCKED
assert (root/'uncertain.flag').is_file() and len(control['calls'])==calls_before
return
assert resumed.recover_quick_run(task,confirmed=True).progress.saved_items==2
assert resumed.recover_quick_run(task,confirmed=True).progress.saved_items==2
assert reopened.get_task(task).status is TaskStatus.COMPLETED
assert tuple(reopened._connection.execute('SELECT attempt_id,generation FROM execution_operations ORDER BY rowid LIMIT 1').fetchone())==first_attempt
assert len([item for item in HistoryRepository(reopened).page().rows if item['operation']=='器件替换'])==2
assert len(control['calls'])==calls_before+(3 if failure=='before_sql' else 0)
finally:reopened.close()
+266
View File
@@ -0,0 +1,266 @@
from pathlib import Path
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import native_helper
import test_accuracy_vbs_guards as guards
def test_new_snapshot_mode_requires_exact_marker_and_selected_only(tmp_path):
path=tmp_path/'snapshot.tsv'
path.write_text('M\tboard\tOLD\tNEW\tMAIN:1\tpreserve\nX\tsaved_netlist_v1\nC\tu1\tR1\t0\t0\t0\t1\tNETLIST\n')
assert native_helper.saved_netlist_snapshot(path)
for extra in ('X\tuntouched_full_v1\n','X\tsaved_netlist_v1\n','U\tu2\tR2\tOLD\tv\tn\tl\n'):
path.write_text('M\tboard\tOLD\tNEW\tMAIN:1\nX\tsaved_netlist_v1\nC\tu1\tR1\t0\t0\t0\t1\tNETLIST\n'+extra)
with pytest.raises(ValueError):native_helper.saved_netlist_snapshot(path)
@pytest.mark.parametrize('extra', ['', 'X\tuntouched_full_v1\n', 'U\tu2\tR2\tOLD\tv\tn\tl\n',
'A\tu2\tValue\tv\tv\t0\t0\t1\t2\t3\t0\t1\n'])
def test_vbs_snapshot_reader_selects_new_protocol_strictly(tmp_path,extra):
snapshot=tmp_path/'snapshot.tsv'
snapshot.write_text('M\tboard.prj\tOLD\tNEW\tMAIN:1\tpreserve\n'
'X\tsaved_netlist_v1\nC\tu1\tR1\t0\t0\t0\t1\tNETLIST\n'
'A\tu1\tValue\tv\tv\t0\t0\t1\t2\t3\t0\t1\n'+extra)
output=guards.run_vbs(tmp_path,['QPReadSnapshot','QPReadUtf8'],'''
Dim Records,Code
On Error Resume Next
Set Records=QPReadSnapshot("'''+str(snapshot)+'''")
Code=Err.Number:Err.Clear
WScript.Echo CStr(Code=0)
If Code=0 Then WScript.Echo CStr(QP_SavedNetlistMode)
''', '''
Dim QP_SavedNetlistMode
''')
assert output.splitlines()==(['True','True'] if not extra else ['False'])
def test_capture_uses_selected_attributes_without_page_or_pin_validation(tmp_path):
path=tmp_path/'snapshot.tsv'
output=guards.run_vbs(tmp_path,['QPCaptureAndSelect','QPCommandTargets','QPSnapshotComponent',
'QPRequireUniqueAttributeNames','QPAttributeObservations','QPBooleanText','QPLogField','QPTargetCell',
'QPSnapshotAttribute','QPSortSnapshotLines','QPOptionalAttributeField','QPFindCurrentAttribute','QPWriteUtf8','QPReadUtf8','QPInvalidatePinIndex','QPInvalidateComponentIndex'],'''
Dim Comp,Other,Attr,Command,Text
Set QP_App=New FakeApp
Set Comp=New FullComponent:Comp.UID="u1":Comp.Refdes="R1"
Set Other=New FullComponent:Other.UID="u2":Other.Refdes="R2":Other.RaiseOnFind=True
Set Attr=New FullAttribute:Attr.Name="Part Number":Attr.Value="OLD":Attr.InstanceValue="OLD":Comp.Attributes.Add Attr,True
Set Attr=New FullAttribute:Attr.Name="Value":Attr.Value="1K":Attr.InstanceValue="1K":Comp.Attributes.Add Attr,True
QP_App.ActiveView.Components.Add Comp,True:QP_App.ActiveView.Components.Add Other,True
Set Command=CreateObject("Scripting.Dictionary")
Command.Add "job_id","job":Command.Add "old_part_number","OLD":Command.Add "new_part_number","NEW"
Command.Add "target_scope","targets":Command.Add "target_selectors",QPEncode("u1" & Chr(31) & "R1" & Chr(31) & "1K")
QPCaptureAndSelect Command,"'''+str(path)+'''"
Text=QPReadUtf8("'''+str(path)+'''")
WScript.Echo CStr(InStr(Text,"X" & vbTab & "saved_netlist_v1")>0)
WScript.Echo CStr(InStr(Text,"NETLIST")>0)
WScript.Echo CStr(InStr(Text,vbCrLf & "U" & vbTab)=0 And InStr(Text,vbCrLf & "G" & vbTab)=0)
''',prelude=guards.LOG_STUB+guards.FULL_FAKE+'''
Dim QP_SavedNetlistMode
Sub QPProgress(ByVal Stage,ByVal Done,ByVal Total)
End Sub
Function QPValueMode(ByRef Command)
QPValueMode="preserve"
End Function
Function QPCustomValue(ByRef Command)
QPCustomValue=""
End Function
Function QPSyncNc(ByRef Command)
QPSyncNc=False
End Function
Sub QPWriteStatus(ByVal Root,ByVal Job,ByVal State,ByVal Code,ByVal Message)
End Sub
Function QPComponentPins(ByVal Uid)
Err.Raise 59001,"Forbidden","pin query"
End Function
Function QPCurrentSemanticState()
Err.Raise 59002,"Forbidden","whole page"
End Function
Sub QPVerifyUntouched(ByRef Records)
Err.Raise 59003,"Forbidden","unselected validation"
End Sub
Function QPUseNativeSnapshot()
Err.Raise 59004,"Forbidden","native CAD read"
End Function
''')
assert output.splitlines()==['True','True','True']
def test_saved_commit_closes_once_and_leaves_applied_rows_pending(tmp_path):
output = guards.run_vbs(tmp_path, ['QPCommitSavedNetlistProject', 'QPWriteUtf8', 'QPReadUtf8'], '''
Dim Applied, Unchanged, Manifest
QP_Root="'''+str(tmp_path)+'''"
QP_SessionProject="board.prj":QP_SessionToken="session"
Set QP_SessionItems=CreateObject("Scripting.Dictionary")
Set QP_SessionDocuments=CreateObject("Scripting.Dictionary")
Set Applied=CreateObject("Scripting.Dictionary")
Applied.Add "saved_netlist",True:Applied.Add "final_state","restored_ok"
Set Unchanged=CreateObject("Scripting.Dictionary")
Unchanged.Add "saved_netlist",True:Unchanged.Add "final_state","no_match"
QP_SessionItems.Add "job1",Applied:QP_SessionItems.Add "job2",Unchanged
QPCommitSavedNetlistProject
Manifest=QPReadUtf8(QP_Fso.BuildPath(QP_Root,"project-commit-session.tsv"))
WScript.Echo CloseCount
WScript.Echo CStr(InStr(Manifest,"project_saved")>0 And InStr(Manifest,"job1" & vbTab & "pending_save")>0)
WScript.Echo CStr(InStr(Manifest,"job2" & vbTab & "no_match")>0 And InStr(Manifest,"saved_ok")=0)
''', guards.LOG_STUB+'''
Dim QP_SessionProject,QP_SessionToken,QP_SessionItems,QP_SessionDocuments,CloseCount
Sub QPCloseBatchProject(ByVal Path,ByVal Save)
If Not Save Then Err.Raise 59001,"Test","must save applied project"
CloseCount=CloseCount+1
End Sub
Sub QPWriteStatus(ByVal Root,ByVal Job,ByVal State,ByVal Code,ByVal Message)
End Sub
Function QPCurrentSemanticState()
Err.Raise 59002,"Forbidden","whole page"
End Function
Sub QPEnsureProject(ByRef App,ByVal Path)
Err.Raise 59003,"Forbidden","saved reopen"
End Sub
''')
assert output.splitlines()==['1','True','True']
def test_staging_reloads_command_without_recapturing_written_values(tmp_path):
output=guards.run_vbs(tmp_path,['QPStageSessionItem','QPWriteUtf8'],'''
QP_Root="'''+str(tmp_path)+'''"
Set QP_App=New StageView
Set QP_SessionItems=CreateObject("Scripting.Dictionary")
QP_BatchState="restored_ok":QP_CurrentJobId="job":QP_SavedNetlistMode=True
QPStageSessionItem
WScript.Echo CStr(QP_SessionItems("job")("saved_netlist"))
WScript.Echo CStr(QP_SessionItems("job")("snapshot_path")="snapshot-job.tsv")
''',guards.LOG_STUB+'''
Dim QP_App,QP_SessionItems,QP_BatchState,QP_CurrentJobId,QP_SavedNetlistMode,QP_SessionToken
Class StageView
Public Property Get ActiveView()
Set ActiveView=Me
End Property
Public Property Get Block()
Set Block=Me
End Property
Public Property Get SheetNum()
SheetNum="1"
End Property
Function GetName(ByVal Kind)
GetName="MAIN"
End Function
End Class
Function QPReadCommand(ByVal Path)
If QP_BatchState<>"" Then Err.Raise 59001,"Test","cached command state not cleared"
Set QPReadCommand=CreateObject("Scripting.Dictionary")
End Function
Function QPReadSnapshot(ByVal Path)
QP_SavedNetlistMode=True
Set QPReadSnapshot=CreateObject("Scripting.Dictionary")
End Function
Function QPJobSnapshotPath(ByVal Job)
QPJobSnapshotPath="snapshot-" & Job & ".tsv"
End Function
Sub QPRequireCommandSnapshot(ByRef Command,ByVal Path)
End Sub
Function QPCurrentSemanticState()
Err.Raise 59002,"Forbidden","whole page"
End Function
Sub QPVerifyUntouched(ByRef Records)
Err.Raise 59003,"Forbidden","unselected verification"
End Sub
Function QPCaptureValueState(ByRef Candidate)
Err.Raise 59004,"Forbidden","expected Value derived after writing"
End Function
Sub QPWriteStatus(ByVal Root,ByVal Job,ByVal State,ByVal Code,ByVal Message)
WScript.Echo State
End Sub
''')
assert output.splitlines()==['pending_save','True','True']
def test_native_target_completion_reads_no_unselected_attributes(monkeypatch):
target=SimpleNamespace(UID='u1',Refdes='R1')
other=SimpleNamespace(UID='u2',Refdes='R2')
def attribute(component,name,**kwargs):
assert component is target
assert name=='Part Number'
return 'NEW'
monkeypatch.setattr(native_helper,'attribute_value',attribute)
records=[['C','u1','R1','0','0','0','1','NETLIST']]
assert native_helper.applied_replacement_uids([other,target],records,'NEW')==['u1']
def test_native_pin_promotion_does_not_query_pins_in_saved_mode(monkeypatch):
target=SimpleNamespace(UID='u1',Refdes='R1')
monkeypatch.setattr(native_helper,'components_on_sheet',lambda app,api:[target])
monkeypatch.setattr(native_helper,'selection',lambda component,state:None)
slots=[]
class View:
Block=SimpleNamespace(PromoteSymbolNumbers=lambda kind,slot:slots.append(slot))
def Query(self,*args):
raise AssertionError('CAD pin validation forbidden')
assert native_helper.promote_pin_numbers(SimpleNamespace(ActiveView=View()),None,['u1'],2,verify_pins=False)==[]
assert slots==[1,2]
@pytest.mark.parametrize(('mode','present','nc','expected'), [
('preserve', True, False, 'library-value'),
('preserve', False, False, ''),
('custom', True, False, 'custom-value'),
('part_number', True, False, 'NEW'),
('part_label', True, False, 'library-label'),
('preserve', True, True, 'library-value/NC'),
])
def test_expectations_bind_snapshot_and_pre_restore_target_value(tmp_path,mode,present,nc,expected):
output=guards.run_vbs(tmp_path,['QPWriteWriterExpectations','QPWriteUtf8','QPReadUtf8','QPBooleanText','QPAppendNcMarker','QPValueHasNcMarker'],'''
Dim Command,Records,Components,Record,States,Before,Text,Rows,Fields
QP_Root="'''+str(tmp_path)+'''"
Set QP_App=New ExpectApp
Set Command=CreateObject("Scripting.Dictionary")
Command.Add "task_id","task":Command.Add "job_id","job":Command.Add "project_path","board.prj"
Command.Add "new_part_number","NEW"
Set Components=CreateObject("Scripting.Dictionary")
Set Record=CreateObject("Scripting.Dictionary"):Record.Add "uid","u1":Record.Add "refdes","R1"
Components.Add "0",Record
Set Records=CreateObject("Scripting.Dictionary"):Records.Add "components",Components
Set States=CreateObject("Scripting.Dictionary")
Set Before=CreateObject("Scripting.Dictionary")
Before.Add "value","'''+('library-value' if present else '')+'''":Before.Add "exists",'''+str(present)+'''
Before.Add "part_name","library-name":Before.Add "part_label","library-label"
Before.Add "nc_required",'''+str(nc)+''':States.Add "0",Before
QPWriteUtf8 QPJobSnapshotPath("job"),"original snapshot" & vbCrLf
QPWriteWriterExpectations Command,Records,States
Text=QPReadUtf8(QP_Fso.BuildPath(QP_Root,"writer-expectations-job.tsv"))
Rows=Split(Text,vbCrLf):Fields=Split(Rows(0),vbTab)
WScript.Echo CStr(QPDecode(Fields(7))=("original snapshot" & vbCrLf))
Fields=Split(Rows(1),vbTab)
WScript.Echo QPDecode(Fields(3))
WScript.Echo Fields(4)
''',guards.LOG_STUB+'''
Dim QP_App
Class ExpectApp
Public Property Get ActiveView()
Set ActiveView=Me
End Property
Public Property Get Block()
Set Block=Me
End Property
Public Property Get SheetNum()
SheetNum="1"
End Property
Function GetName(ByVal Kind)
GetName="MAIN"
End Function
End Class
Function QPJobSnapshotPath(ByVal Job)
QPJobSnapshotPath=QP_Fso.BuildPath(QP_Root,"snapshot-" & Job & ".tsv")
End Function
Function QPValueMode(ByRef Command)
QPValueMode="'''+mode+'''"
End Function
Function QPCustomValue(ByRef Command)
QPCustomValue="custom-value"
End Function
Function QPTargetCell(ByRef Command)
QPTargetCell="cell"
End Function
''')
assert output.splitlines()==['True',expected,'1' if present or mode!='preserve' or nc else '0']