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

@@ -430,7 +430,8 @@ class BatchCadRuntime:
from .execution_proof import capture_project_commit, bind_project_commit_source
from .quick_run import _decode_vbs_field
rows = [line.split('\t') for line in marker.read_text(encoding='utf-8-sig').splitlines() if line]
if (not rows or len(rows[0]) != 3 or rows[0][0] != request[0] or rows[0][2] != 'project_verified'
if (not rows or len(rows[0]) != 3 or rows[0][0] != request[0]
or rows[0][2] not in {'project_verified', 'project_saved'}
or canonical_path(_decode_vbs_field(rows[0][1])) != project
or any(len(row) != 2 for row in rows[1:])):
raise WorkerMonitorError('native project commit marker is not bound to the closed project')
@@ -439,6 +440,10 @@ class BatchCadRuntime:
expected_jobs = expected_jobs[expected_jobs.index(self.record['active_job']):]
if not jobs or len(set(jobs)) != len(jobs) or jobs != expected_jobs[:len(jobs)]:
raise WorkerMonitorError('native project commit marker does not cover an authorized prefix')
saved_only = rows[0][2] == 'project_saved'
allowed_outcomes = {'pending_save', 'no_match'} if saved_only else {'saved_ok', 'no_match'}
if any(row[1] not in allowed_outcomes for row in rows[1:]):
raise WorkerMonitorError('native project commit marker has an invalid outcome')
proof = capture_project_commit(self.root, root, {'session_token': request[0],
'project_path': str(project).casefold(), 'jobs_json': json.dumps(jobs)})
proof = bind_project_commit_source(proof, self.root, root, project)
@@ -446,14 +451,49 @@ class BatchCadRuntime:
proof['files'].append({'path': str(canonical_path(marker)), 'sha256': proof['marker_sha256']})
readback_names = []
for job, outcome in proof['outcomes'].items():
readback_names.append('post-state-' + job + '.tsv')
if outcome == 'saved_ok':
if saved_only:
from .batch_attempt import read_attempt
path, expected = next((path, expected) for path, expected in self._current_attempts
if expected['job_id'] == job)
actual = read_attempt(path)
if any(actual.get(name) != value for name, value in expected.items() if name != 'state'):
raise WorkerMonitorError('saved project attempt identity changed')
if outcome == 'no_match' and actual['state'] != 'prepared':
raise WorkerMonitorError('saved project no-match outcome has a possible native write')
snapshot = internal_path(root / ('snapshot-' + job + '.tsv'))
report_path = internal_path(str(snapshot) + '.native.json')
if snapshot.exists():
if b'X\tsaved_netlist_v1' not in snapshot.read_bytes().splitlines():
raise WorkerMonitorError('saved project snapshot does not authorize native export validation')
readback_names.append(snapshot.name)
if outcome in {'saved_ok', 'pending_save'} or report_path.exists():
report = json.loads(report_path.read_text(encoding='utf-8'))
native = report.get('batch_attempt', {})
if (report.get('ok') is not True
or outcome in {'saved_ok', 'pending_save'} and report.get('stage') != 'native_replace_applied'
or any(native.get(name) != expected[name] for name in
('session_id', 'generation', 'attempt_id', 'task_id', 'job_id'))
or canonical_path(native.get('project_path', '')) != project):
raise WorkerMonitorError('saved project native write attempt is not bound')
readback_names.append(report_path.name)
if outcome in {'saved_ok', 'pending_save'}:
if not snapshot.is_file() or actual['state'] != 'mutation_possible':
raise WorkerMonitorError('saved project applied write lacks its original mutation attempt')
readback_names.append('writer-expectations-' + job + '.tsv')
proof.setdefault('batch_attempts', []).append({'path': str(path), 'expected': expected})
proof['files'].append({'path': str(path), 'sha256': hashlib.sha256(internal_path(path).read_bytes()).hexdigest()})
else:
readback_names.append('post-state-' + job + '.tsv')
if not saved_only and outcome == 'saved_ok':
readback_names.extend(('snapshot-' + job + '.tsv', 'snapshot-' + job + '.tsv.native.json',
'value-readback-' + job + '.tsv'))
proof['readback_files'] = {name: hashlib.sha256(internal_path(root / name).read_bytes()).hexdigest()
for name in readback_names}
proof['native_attempt'] = {'session_id': self.session_id, 'generation': self.generation,
'attempt_id': attempt_id}
if saved_only:
proof.update(marker_state='project_saved', saved_only=True, validation_required='saved_netlist_v1',
native_outcomes=dict(rows[1:]), outcomes=dict(rows[1:]))
checkpoint['project_commit_source'] = proof
write_record(root / 'project-checkpoint.json', checkpoint)
self._active_attempts = []
@@ -737,15 +777,19 @@ class BatchCadRuntime:
raise ValueError('prewrite project closure marker is missing or stale')
manifest_path = root / ('project-commit-' + request[0] + '.tsv')
committed = {}
prefix_marker_state = None
files = [marker_path, *(path for path, _ in expected)]
if internal_path(manifest_path).exists():
rows = [line.split('\t') for line in internal_path(manifest_path).read_text(encoding='utf-8-sig').splitlines()]
if (not rows or len(rows[0]) != 3 or rows[0][0] != request[0]
or canonical_path(_decode_vbs_field(rows[0][1])) != project or rows[0][2] != 'project_verified'):
or canonical_path(_decode_vbs_field(rows[0][1])) != project
or rows[0][2] not in {'project_verified', 'project_saved'}):
raise ValueError('committed prefix manifest is not bound')
prefix_marker_state = rows[0][2]
allowed_outcomes = {'pending_save', 'no_match'} if prefix_marker_state == 'project_saved' else {'saved_ok', 'no_match'}
for row in rows[1:]:
if (len(row) != 2 or row[0] not in prefix_jobs or row[0] in committed
or row[1] not in {'saved_ok', 'no_match'}):
or row[1] not in allowed_outcomes):
raise ValueError('committed prefix manifest contains an unrelated result')
committed[row[0]] = row[1]
files.append(manifest_path)
@@ -761,6 +805,7 @@ class BatchCadRuntime:
session_id=self.session_id, generation=self.generation, attempt_id=attempt_id,
resource_record=str(self.path), project_closed=True, native_dispatch_not_started=True,
source_sha256=hashlib.sha256(repr(after).encode()).hexdigest(), committed_prefix=committed,
prefix_marker_state=prefix_marker_state, prefix_validation_required=prefix_marker_state == 'project_saved',
pause_marker_path=str(marker_path),
pause_marker_sha256=hashlib.sha256(internal_path(marker_path).read_bytes()).hexdigest(),
commit_manifest_path=str(manifest_path) if committed else None,
@@ -634,6 +634,28 @@ class ExecutionJournal:
WHERE task_id=? AND round_id=? AND session_token=? AND state='pending_save' AND proof_json IS NULL''',
(_json(proof), task_id, current['round_id'], session_token))
def promote_project_commit_proof(self, task_id, session_token, expected_proof, verified_proof):
"""Attach native verification to the same saved attempt without replacing its source binding."""
from .execution_proof import proof_intact
with self.store.transaction():
current = self._round(task_id)
record = self.store._connection.execute('''SELECT * FROM execution_project_commits
WHERE task_id=? AND round_id=? AND session_token=?''',
(task_id, current['round_id'], session_token)).fetchone() if current else None
original = {key: value for key, value in expected_proof.items() if key not in {'files', 'outcomes', 'saved_netlist'}}
if (record is None or record['state'] != 'pending_save'
or expected_proof.get('session_token') != session_token
or expected_proof.get('validation_required') != 'saved_netlist_v1'
or verified_proof.get('saved_netlist', {}).get('status') != 'verified'
or any(verified_proof.get(key) != value for key, value in original.items())
or any(item not in verified_proof.get('files', []) for item in expected_proof.get('files', []))
or not proof_intact(verified_proof)
or json.loads(record['proof_json'] or 'null') not in (expected_proof, verified_proof)):
raise TaskCenterError('quick_run_uncertain', '原工程保存证明发生变化,不能覆盖核验结果。')
self.store._connection.execute('''UPDATE execution_project_commits SET proof_json=?
WHERE task_id=? AND round_id=? AND session_token=?''',
(_json(verified_proof), task_id, current['round_id'], session_token))
def staged_project_rows(self, task_id, session_token):
with self.store._lock:
current = self._round(task_id)
@@ -661,6 +683,16 @@ class ExecutionJournal:
or not commit_proof.get('files') or not proof_intact(commit_proof)
or any(not proof.get('files') or not proof_intact(proof) for proof in proofs.values())):
raise TaskCenterError('quick_run_uncertain', '工程保存回读证明未覆盖全部暂存项。')
saved_protocol = commit_proof.get('marker_state') == 'project_saved' or commit_proof.get('validation_required') == 'saved_netlist_v1'
saved = commit_proof.get('saved_netlist', {})
if saved_protocol and (commit_proof.get('validation_required') != 'saved_netlist_v1'
or saved.get('status') != 'verified' or set(saved.get('jobs', {})) != set(jobs)
or set(commit_proof.get('native_outcomes', {})) != set(jobs)
or any(state not in {'pending_save', 'no_match'} for state in commit_proof['native_outcomes'].values())
or commit_proof.get('outcomes') != {job: 'saved_ok' if state == 'pending_save' else state
for job, state in commit_proof['native_outcomes'].items()}
or not saved.get('files') or not proof_intact(saved)):
raise TaskCenterError('quick_run_uncertain', '工程已保存,尚未完成原生数据核验。')
records = connection.execute('''SELECT * FROM execution_operations
WHERE task_id=? AND round_id=? AND state='pending_save' ''', (task_id, current['round_id'])).fetchall()
records = [record for record in records if json.loads(record['receipt_json']).get('session_token') == session_token]
@@ -672,14 +704,29 @@ class ExecutionJournal:
proof = dict(proofs[job])
if proof.get('native_attempt') != receipt.get('proof', {}).get('native_attempt'):
raise TaskCenterError('quick_run_uncertain', '保存回读与原暂存原生尝试不一致。')
proof['project_commit'] = commit_proof
proof['files'] = list(proof['files']) + list(commit_proof['files'])
if saved_protocol:
proof['project_commit'] = dict(session_token=session_token, project_path=commit_proof['project_path'],
validation_required='saved_netlist_v1',
operation_attempts={job: [record['operation_key'], record['attempt_id'], record['generation']]},
saved_netlist={key: saved[key] for key in ('status', 'export_path', 'export_sha256')})
command = json.loads(record['command_json'])
proof['baseline'] = dict(project_path=command['project_path'], schematic_name=command['schematic_name'],
sheet_number=command['sheet_number'], validation_mode='saved_netlist_v1',
state='N\tsaved_netlist_v1\t' + saved['export_sha256'])
shared = [{'path': saved['export_path'], 'sha256': saved['export_sha256']}]
if saved.get('verification_path'):
shared.append({'path': saved['verification_path'], 'sha256': saved['verification_sha256']})
proof['files'] = list(proof['files']) + [item for item in shared if item not in proof['files']]
else:
proof['project_commit'] = commit_proof
proof['files'] = list(proof['files']) + list(commit_proof['files'])
attempt = JournalAttempt(task_id, current['round_id'], record['operation_key'],
record['attempt_id'], record['generation'], job)
connection.execute('''UPDATE execution_operations SET state='prepared'
WHERE task_id=? AND round_id=? AND operation_key=?''', (task_id, current['round_id'], record['operation_key']))
native_state = commit_proof.get('outcomes', {}).get(job, 'saved_ok')
self.finish(attempt, native_state, 'project_committed', '工程统一保存、关闭重开及回读校验通过。', proof=proof)
message = '工程统一保存,原生数据核验通过。' if saved_protocol else '工程统一保存、关闭重开及回读校验通过。'
self.finish(attempt, native_state, 'project_committed', message, proof=proof)
connection.execute('''UPDATE execution_project_commits SET state='verified',proof_json=?
WHERE task_id=? AND round_id=? AND session_token=?''', (_json(commit_proof), task_id, current['round_id'], session_token))
@@ -17,14 +17,35 @@ def proof_intact(proof):
except (OSError,ValueError,KeyError,TypeError):return False
def capture_result(data_root,root,row,outcome,*,strict=False,persist=True):
def capture_result(data_root,root,row,outcome,*,strict=False,persist=True,project_commit=None):
from .quick_run import _decode_vbs_field, _safe_run_token
from .native_helper import read_snapshot, require_resumable_transaction, snapshot_target_cell
from .native_helper import read_snapshot, require_resumable_transaction, snapshot_target_cell, saved_netlist_snapshot
state,code,_=outcome
proof={'files':[]}
paths=[]
try:
_safe_run_token(row['job_id'])
snapshot = internal_path(root/f'snapshot-{row["job_id"]}.tsv')
saved_protocol = ((snapshot.is_file() and saved_netlist_snapshot(snapshot))
or bool(project_commit and project_commit.get('validation_required') == 'saved_netlist_v1'))
if saved_protocol:
proof['validation_required'] = 'saved_netlist_v1'
if state in {'saved_ok', 'no_match'}:
saved = (project_commit or {}).get('saved_netlist', {})
if saved.get('status') != 'verified' or row['job_id'] not in saved.get('jobs', {}):
raise ValueError('saved native netlist proof is required')
proof['saved_netlist'] = {key:saved[key] for key in ('status','export_path','export_sha256')}
proof['value_readback'] = saved['jobs'][row['job_id']]
if state == 'no_match' and persist:
destination = internal_path(data_root/'execution-proof'/uuid4().hex)
destination.mkdir(parents=True,exist_ok=False)
target = destination/f'no-match-{row["job_id"]}.json'
reference = dict(command=dict(row),session_token=project_commit['session_token'],
**{key:saved[key] for key in ('export_path','export_sha256','verification_path','verification_sha256')})
data = json.dumps(reference,ensure_ascii=False,sort_keys=True).encode('utf-8')
with target.open('xb') as stream:
stream.write(data);stream.flush();os.fsync(stream.fileno())
proof['files'].append({'path':str(canonical_path(target)),'sha256':hashlib.sha256(data).hexdigest()})
if row.get('execution_unit') == 'inventory_empty':
from .component_scope import validate_empty_command
if state != 'batch_skipped' or not validate_empty_command(root, row):
@@ -39,7 +60,7 @@ def capture_result(data_root,root,row,outcome,*,strict=False,persist=True):
if row.get('execution_unit') == 'inventory_empty':
checked[manifest] = checked_manifest
baseline=internal_path(root/f'post-state-{row["job_id"]}.tsv')
if baseline.is_file():
if baseline.is_file() and not saved_protocol:
checked[baseline]=baseline.read_bytes()
with baseline.open(encoding='utf-8-sig',newline='') as stream:
rows=list(csv.DictReader(stream,delimiter='\t'))
@@ -53,7 +74,7 @@ def capture_result(data_root,root,row,outcome,*,strict=False,persist=True):
proof['baseline']={'project_path':str(canonical_path(row['project_path'])).casefold(),
'schematic_name':actual['schematic_name'],'sheet_number':actual['sheet_number'],'state':actual['semantic_state']}
paths.append(baseline)
elif strict and state in {'saved_ok','no_match','restored_ok','recovery_readback'}:
elif strict and not saved_protocol and state in {'saved_ok','no_match','restored_ok','recovery_readback'}:
raise ValueError('missing verified semantic state')
if state=='saved_ok' or (state=='pending_save' and code == 'session_staged') or (state=='restored_ok' and code in {'recovery_verified','recovery_saved_verified'}):
snapshot=internal_path(root/f'snapshot-{row["job_id"]}.tsv')
@@ -74,7 +95,8 @@ def capture_result(data_root,root,row,outcome,*,strict=False,persist=True):
raise ValueError('snapshot command changed')
attempt=report.get('batch_attempt')
if strict:
if report.get('stage')!='native_replace_verified' or report.get('ok') is not True:
required_stage = 'native_replace_applied' if saved_protocol else 'native_replace_verified'
if report.get('stage')!=required_stage or report.get('ok') is not True:
raise ValueError('native result is not verified')
if (not isinstance(attempt,dict) or attempt.get('job_id')!=row['job_id'] or
attempt.get('task_id')!=row['task_id'] or
@@ -84,6 +106,10 @@ def capture_result(data_root,root,row,outcome,*,strict=False,persist=True):
raise ValueError('native attempt differs from this job')
proof['native_attempt']=attempt
paths.extend((snapshot,report_path))
if saved_protocol:
writer = internal_path(root/f'writer-expectations-{row["job_id"]}.tsv')
checked[writer] = writer.read_bytes()
paths.append(writer)
if any(path.read_bytes()!=data for path,data in checked.items()):
raise ValueError('execution evidence changed during receipt binding')
if persist and paths:
@@ -111,10 +137,12 @@ def capture_project_commit(data_root, root, commit):
token, project, state = lines[0].split('\t')
outcomes = [line.split('\t') for line in lines[1:] if line]
jobs = json.loads(commit['jobs_json'])
if (token != commit['session_token'] or state != 'project_verified'
saved_only = state == 'project_saved'
allowed = {'pending_save', 'no_match'} if saved_only else {'saved_ok', 'no_match'}
if (token != commit['session_token'] or state not in {'project_verified', 'project_saved'}
or str(canonical_path(_decode_vbs_field(project))).casefold() != commit['project_path']
or [outcome[0] for outcome in outcomes] != jobs
or any(len(outcome) != 2 or outcome[1] not in {'saved_ok', 'no_match'} for outcome in outcomes)):
or any(len(outcome) != 2 or outcome[1] not in allowed for outcome in outcomes)):
raise ValueError('project commit does not cover staged prefix')
destination = internal_path(data_root / 'execution-proof' / uuid4().hex)
destination.mkdir(parents=True, exist_ok=False)
@@ -123,8 +151,11 @@ def capture_project_commit(data_root, root, commit):
stream.write(data); stream.flush(); os.fsync(stream.fileno())
if path.read_bytes() != data:
raise ValueError('project marker changed during binding')
return dict(session_token=token, project_path=commit['project_path'], jobs=jobs,
proof = dict(session_token=token, project_path=commit['project_path'], jobs=jobs,
outcomes=dict(outcomes), files=[dict(path=str(canonical_path(target)), sha256=hashlib.sha256(data).hexdigest())])
if saved_only:
proof.update(marker_state=state, saved_only=True, validation_required='saved_netlist_v1', native_outcomes=dict(outcomes))
return proof
except (OSError, UnicodeError, ValueError, KeyError, TypeError, IndexError) as error:
raise TaskCenterError('quick_run_uncertain', '工程统一保存或回读尚未得到完整证明,保留全部暂存项待核验。') from error
@@ -142,6 +142,22 @@ def read_snapshot(path):
return metadata[0], components
def saved_netlist_snapshot(snapshot):
rows = [line.split('\t') for line in Path(snapshot).read_text(encoding='utf-8-sig').splitlines() if line]
markers = [row for row in rows if row[0] == 'X']
if ['X', 'saved_netlist_v1'] not in markers:
return False
if (markers != [['X', 'saved_netlist_v1']] or any(row[0] not in {'M', 'C', 'A', 'X', 'L'} for row in rows)
or not any(row[0] == 'C' for row in rows)
or any(len(row) != 8 or row[7] != 'NETLIST' for row in rows if row[0] == 'C')):
raise ValueError('Invalid saved native data snapshot scope')
_, components = read_snapshot(snapshot)
selected = {row[1] for row in components}
if any(len(row) != 12 or decode(row[1]) not in selected for row in rows if row[0] == 'A'):
raise ValueError('Invalid saved native data snapshot attributes')
return True
def snapshot_value_mode(metadata):
return metadata[5] if len(metadata) >= 6 else "part_label"
@@ -496,7 +512,8 @@ def check_context(app, api, metadata, records, require_selection=True):
or attribute_value(component, "Value") != old_value for component in candidates)):
raise ValueError("Selected target changed since inventory")
else:
actual = {_component_uid(component) for component in components if attribute_value(component, "Part Number", required=True).casefold() == metadata[2].casefold()}
scope = [component for component in components if _component_uid(component) in wanted] if all(row[7] == "NETLIST" for row in records) else components
actual = {_component_uid(component) for component in scope if attribute_value(component, "Part Number", required=True).casefold() == metadata[2].casefold()}
if actual != wanted:
raise ValueError(f"Source batch changed since snapshot: expected={sorted(wanted)!r} actual={sorted(actual)!r}")
if require_selection:
@@ -612,6 +629,21 @@ def select_snapshot_batch(app, api, metadata, records):
return components
def applied_replacement_uids(components, records, target):
"""Associate just the written targets while the native operation completes."""
wanted = {row[1] for row in records}
targets = {_component_uid(component): component for component in components
if _component_uid(component) in wanted}
if len(targets) != len(records):
return None
for record in records:
component = targets[record[1]]
if (str(component.Refdes).strip().casefold() != record[2].strip().casefold()
or attribute_value(component, 'Part Number', required=True).casefold() != target.casefold()):
return None
return [record[1] for record in records]
def existing_replacement_uids(components, records, target, binding, require_part_label=True):
matches = replacement_matches(components, records, target, require_part_label,
library_row=binding['library_row'])
@@ -620,7 +652,7 @@ def existing_replacement_uids(components, records, target, binding, require_part
return matches
def promote_pin_numbers(app, api, replacement_uids, slot_count=1, on_progress=None):
def promote_pin_numbers(app, api, replacement_uids, slot_count=1, on_progress=None, *, verify_pins=True):
def progress(phase):
if on_progress:
on_progress(phase)
@@ -634,6 +666,8 @@ def promote_pin_numbers(app, api, replacement_uids, slot_count=1, on_progress=No
for slot in range(1, int(slot_count) + 1):
progress(f'promote_slot_{slot}')
app.ActiveView.Block.PromoteSymbolNumbers(1, slot)
if not verify_pins:
return []
progress('query_promoted_pins')
promoted = []
for item in app.ActiveView.Query(4096, 0):
@@ -733,6 +767,7 @@ def run_native(snapshot, report):
from pywinauto import Desktop
metadata, records = read_snapshot(snapshot)
native_mode = saved_netlist_snapshot(snapshot)
target_cell = snapshot_target_cell(snapshot, required=False)
require_part_label = snapshot_value_mode(metadata) == "part_label"
app, api = attach()
@@ -740,7 +775,7 @@ def run_native(snapshot, report):
cell_proof = target_cell_catalog(app, snapshot, metadata, target_cell) if target_cell is not None else None
components = components_on_sheet(app, api)
wanted = {row[1] for row in records}
if len(metadata) == 10:
if len(metadata) == 10 and not native_mode:
verify_unselected_snapshot(snapshot, components, wanted, api=api)
source_uids = {
_component_uid(component)
@@ -751,6 +786,11 @@ def run_native(snapshot, report):
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")
if native_mode:
if report.get("stage") == "native_replace_applied" and report.get("pin_promotion_phase") == "promotion_complete":
report["already_replaced"] = True
return
raise ValueError("Native replacement may already have been applied; verify saved native data before continuing")
report["replaced_uids"] = existing_replacement_uids(
components, records, metadata[3], binding, require_part_label=require_part_label
)
@@ -770,7 +810,7 @@ def run_native(snapshot, report):
return
components = select_snapshot_batch(app, api, metadata, records)
before_uids = {_component_uid(component) for component in components}
untouched = None if len(metadata) == 10 else {_component_uid(component): (
untouched = None if native_mode or len(metadata) == 10 else {_component_uid(component): (
str(component.Refdes),
*(attribute_value(component, name) for name in ("Part Number", "Value", "Part Name", "Part Label"))
) for component in components if _component_uid(component) not in wanted}
@@ -937,6 +977,8 @@ def run_native(snapshot, report):
def selected_replaced():
nonlocal replacement_poll_count
replacement_poll_count += 1
if native_mode:
return applied_replacement_uids(components_on_sheet(app, api), records, metadata[3])
selected = [api.IVdComp(component._oleobj_) for component in app.ActiveView.Query(128, 1)]
if len(selected) == len(records):
matches = replacement_matches(selected, records, metadata[3], require_part_label, library_row=columns)
@@ -956,7 +998,7 @@ def run_native(snapshot, report):
# Preserve the last observed identities without retrying a mutation.
report['replacement_timeout'] = {'polls': replacement_poll_count}
try:
current = components_on_sheet(app, api)
current = [] if native_mode else components_on_sheet(app, api)
refs = {record[2] for record in records}
report['replacement_timeout'].update(
component_count=len(current),
@@ -971,16 +1013,17 @@ def run_native(snapshot, report):
except Exception as error:
report['replacement_timeout']['target_control_error'] = str(error)
raise
current = components_on_sheet(app, api)
verify_replacement_readback(snapshot, current, metadata, records, before_uids,
untouched, require_part_label, columns, report['replaced_uids'], api=api)
if not native_mode:
current = components_on_sheet(app, api)
verify_replacement_readback(snapshot, current, metadata, records, before_uids,
untouched, require_part_label, columns, report['replaced_uids'], api=api)
report["stage"] = "native_replace_applied"
save_report(snapshot, report)
report["stage"] = "pin_promotion_started"
save_report(snapshot, report)
report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count,
lambda phase: _promotion_phase(snapshot, report, phase))
report["stage"] = "native_replace_verified"
lambda phase: _promotion_phase(snapshot, report, phase), verify_pins=not native_mode)
report["stage"] = "native_replace_applied" if native_mode else "native_replace_verified"
finally:
if dialog and win32gui.IsWindow(dialog):
close_button = dlg_item(dialog, 1696)
@@ -185,6 +185,8 @@ def _parse_ascii(path, *, hierarchy_boundaries=(), require_connections=True):
symbol['refdes'] = attrs.get('Ref Designator', '')
elif attrs.get('Ref Designator') and attrs['Ref Designator'] != symbol['refdes']:
symbol['source_refdes'], symbol['refdes'] = symbol['refdes'], attrs['Ref Designator']
# Port names can contain '/', so retain the reported path even at the root.
symbol['instance_path'] = '' if paths[0] == 'root' else paths[0]
if _is_pcb(symbol) and (not symbol['refdes'] or attrs.get('Ref Designator') != symbol['refdes']):
raise ValueError(f'PCB component identity is ambiguous: {uid!r} / {symbol["refdes"]!r}')
raw_identity = uid
@@ -1,5 +1,5 @@
"""Overlap native exports with replacement, keeping each saved input immutable."""
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import Future, ThreadPoolExecutor
from dataclasses import asdict
import json
import hashlib
@@ -54,7 +54,7 @@ def library_from_receipt(command, receipt):
if receipt.get('native_state') not in {'saved_ok', 'restored_ok'}:
return {}
from .execution_proof import proof_intact
from .native_helper import read_snapshot, require_resumable_transaction
from .native_helper import read_snapshot, require_resumable_transaction, saved_netlist_snapshot
from .path_access import canonical_path, internal_path
proof = receipt.get('proof', {})
native_files = [Path(item['path']) for item in proof.get('files', ())
@@ -70,7 +70,11 @@ def library_from_receipt(command, receipt):
if str(snapshot) not in paths:
raise ValueError('原生库件证据缺少配套快照')
report = json.loads(internal_path(path).read_text(encoding='utf-8'))
if report.get('ok') is not True or report.get('stage') != 'native_replace_verified':
saved_native = saved_netlist_snapshot(snapshot)
if saved_native and proof.get('saved_netlist', proof.get('project_commit', {}).get('saved_netlist', {})).get('status') != 'verified':
raise ValueError('已保存的原生数据尚未核验,不能使用写入回执声明成功')
stage = 'native_replace_applied' if saved_native else 'native_replace_verified'
if report.get('ok') is not True or report.get('stage') != stage:
raise ValueError('原生库件回执未通过实际替换核验')
metadata, records = read_snapshot(snapshot)
binding = require_resumable_transaction(snapshot, report, metadata, records)
@@ -101,9 +105,11 @@ def library_from_receipt(command, receipt):
'schematic_name': command.get('schematic_name',''), 'sheet_number': command.get('sheet_number','')}
if uid in values:
value = values[uid]
native_empty = (saved_native and value['actual_value'] == '' and value['actual_value_present'] is None
and value.get('value_presence_coverage') == 'native_ascii_empty_presence_unknown')
if (value['actual_part_number'].casefold() != row[1].casefold()
or not isinstance(value['actual_value'], str)
or type(value['actual_value_present']) is not bool):
or (type(value['actual_value_present']) is not bool and not native_empty)):
raise ValueError('Value 回读证据与目标库件不符')
identity.update(preserved_value=value['actual_value'],
preserved_value_present=value['actual_value_present'])
@@ -360,6 +366,18 @@ class NetlistVerification:
return
try:
record['library'] = _library_expectations(record['child'], task_id)
preparer = getattr(record['child'], '_quick_run_preparer', None)
if preparer is not None:
from .saved_netlist_verification import load_saved_export
saved = load_saved_export(preparer.data_root / 'quick-run',
Path(record['before_capture']['project']))
if saved is not None:
exported = Future()
exported.set_result(saved['result'])
record.update(after_capture=saved['capture'],
after_export=Path(saved['export_path']).parent,
after=exported)
return
directory = record['directory']
attempt = uuid4().hex
capture = native_netlist.capture_project(Path(record['before_capture']['project']),
@@ -353,7 +353,7 @@ class QuickRunPreparer:
journal_rows,
)
def _bind_journal_handoff(self, task_id, handoff):
def _bind_journal_handoff(self, task_id, handoff, *, append_only=False):
journal = getattr(self, 'journal', None)
if journal is None:
return {}
@@ -365,7 +365,8 @@ class QuickRunPreparer:
proof_reader=lambda row,outcome:self.result_proof(handoff.command_path.parent,row,outcome))
additional = tuple((job, *outcome) for job, outcome in restored.items() if latest.get(job) != outcome)
if additional:
_write_status_details(handoff.status_path, (*details, *additional))
if append_only:_append_status_details(handoff.status_path,additional)
else:_write_status_details(handoff.status_path, (*details, *additional))
return {row['job_id']: row for row in rows}
def reconcile_terminal_receipts(self, task_id):
@@ -383,10 +384,10 @@ class QuickRunPreparer:
_write_uncertain_flag(root/'uncertain.flag','uncommitted_receipt_requires_verification')
raise
def result_proof(self, root, row, outcome, *, persist=True):
def result_proof(self, root, row, outcome, *, persist=True, project_commit=None):
from .execution_proof import capture_result
return capture_result(self._data_root,root,row,outcome,
strict=self._process_runner is _run_process,persist=persist)
strict=self._process_runner is _run_process,persist=persist,project_commit=project_commit)
def _commit_staged_project(self, task_id, *, session_token=None, bind_source=False):
journal = getattr(self, 'journal', None)
@@ -410,16 +411,34 @@ class QuickRunPreparer:
from .execution_proof import bind_project_commit_source
commit_proof = bind_project_commit_source(commit_proof, self._data_root, root, commit['project_path'])
commit_proof['operation_attempts'] = journal.project_commit_attempts(task_id, commit['session_token'])
staged = journal.staged_project_rows(task_id, commit['session_token'])
saved_protocol = commit_proof.get('validation_required') == 'saved_netlist_v1'
if saved_protocol:
from .saved_netlist_verification import verify_saved_project
for receipt in staged:
for item in receipt['proof'].get('files', ()):
name = Path(item['path']).name
if hashlib.sha256(_io_path(root/name).read_bytes()).hexdigest() != item['sha256']:
raise ValueError('staged native target evidence changed before saved export')
if not commit_proof.get('readback_files'):
names = [name for job, state in commit_proof['native_outcomes'].items() if state == 'pending_save'
for name in (f'snapshot-{job}.tsv', f'snapshot-{job}.tsv.native.json', f'writer-expectations-{job}.tsv')]
commit_proof['readback_files'] = {name:hashlib.sha256(_io_path(root/name).read_bytes()).hexdigest() for name in names}
journal.bind_project_commit_proof(task_id, commit['session_token'], commit_proof)
before_validation = commit_proof
commit_proof = verify_saved_project(self._data_root, root, commit_proof, [receipt['row'] for receipt in staged])
journal.promote_project_commit_proof(task_id, commit['session_token'], before_validation, commit_proof)
proofs = {}
for receipt in journal.staged_project_rows(task_id, commit['session_token']):
for receipt in staged:
row = receipt['row']
outcome = (commit_proof['outcomes'][row['job_id']], 'project_committed', '工程保存回读校验通过。')
proof = self.result_proof(root, row, outcome)
outcome = (commit_proof['outcomes'][row['job_id']], 'project_committed',
'工程统一保存,原生数据核验通过。' if saved_protocol else '工程保存回读校验通过。')
proof = self.result_proof(root, row, outcome, project_commit=commit_proof) if saved_protocol else self.result_proof(root,row,outcome)
if outcome[0] == 'saved_ok':
from .value_readback import capture_value_readback
proof['value_readback'] = capture_value_readback(root, row, outcome, project_commit=commit_proof)
proofs[row['job_id']] = proof
if bind_source and not commit.get('proof_json'):
if bind_source and not commit.get('proof_json') and not saved_protocol:
commit_proof['readback_files'] = {Path(item['path']).name: item['sha256']
for proof in proofs.values() for item in proof.get('files', ())}
for job, outcome in commit_proof['outcomes'].items():
@@ -428,6 +447,10 @@ class QuickRunPreparer:
if value_path.is_file():commit_proof['readback_files'][value_path.name] = hashlib.sha256(value_path.read_bytes()).hexdigest()
journal.bind_project_commit_proof(task_id, commit['session_token'], commit_proof)
journal.commit_project_results(task_id, commit['session_token'], proofs, commit_proof)
if saved_protocol:
handoff = QuickRunResult(root/'QuickPartReplace.vbs',root/'command.tsv',root/'status.tsv',
root/'quick-part-replace.log',self.vbs_root_compatible)
self._bind_journal_handoff(task_id,handoff,append_only=True)
record_operation(root, 'readback_proof', 'return', item_id=commit['session_token'])
for job in commit_proof['jobs']:
record_operation(root, 'item', 'return', item_id=job)
@@ -461,7 +484,7 @@ class QuickRunPreparer:
elif protection not in allowed and interrupted is None:return None
if not confirmed:
raise TaskCenterError('quick_run_recovery_confirmation', '工程提交回执核验需要明确确认。')
from .execution_proof import capture_project_commit, validate_project_commit_source
from .execution_proof import capture_project_commit, validate_project_commit_source, proof_intact
from .execution_journal import read_command_rows, command_identity, _hash
from .batch_resources import write_record
try:
@@ -470,14 +493,40 @@ class QuickRunPreparer:
current = journal._round(task_id)
if json.loads(current['plan_json']) != [_hash(command_identity(row)) for row in rows]:
raise ValueError('frozen command plan changed')
positions = {row['job_id']:index for index,row in enumerate(rows)}
markers = {commit['session_token']:capture_project_commit(self._data_root,root,commit) for commit in commits}
ends = {token:max(positions[job] for job in marker['jobs']) for token,marker in markers.items()}
latest = {}
for commit in commits:
token = commit['session_token']
if markers[token].get('validation_required') == 'saved_netlist_v1':
latest[commit['project_path']] = max(latest.get(commit['project_path'],-1),ends[token])
historical = set()
def historical_intact(proof):
saved = proof['saved_netlist']
verified = json.loads(_io_path(saved['verification_path']).read_text(encoding='utf-8'))
context = {key:proof[key] for key in ('session_token','project_path','saved_sources','command_sha256')}
context['marker_sha256'] = proof['files'][0]['sha256']
return (proof_intact(proof) and saved.get('status') == 'verified'
and proof['command_sha256'] == hashlib.sha256(_io_path(root/'command.tsv').read_bytes()).hexdigest()
and hashlib.sha256(_io_path(saved['verification_path']).read_bytes()).hexdigest() == saved['verification_sha256']
and hashlib.sha256(_io_path(saved['export_path']).read_bytes()).hexdigest() == saved['export_sha256']
and verified.get('status') == 'verified' and verified.get('context') == context
and verified.get('export_path') == saved['export_path'] and verified.get('export_sha256') == saved['export_sha256']
and verified.get('jobs') == saved.get('jobs') and set(saved['jobs']) == set(proof['jobs'])
and proof['outcomes'] == {job:'saved_ok' if state == 'pending_save' else state
for job,state in proof['native_outcomes'].items()})
covered = set()
covered_attempts = []
for commit in commits:
if Path(commit['evidence_root']).resolve() != root.resolve():raise ValueError('foreign commit root')
proof = json.loads(commit['proof_json'] or '{}')
prior = (commit['state'] == 'verified' and proof.get('validation_required') == 'saved_netlist_v1'
and ends[commit['session_token']] < latest.get(commit['project_path'],-1))
if prior:historical.add(commit['session_token'])
if proof and proof.get('operation_attempts') != journal.project_commit_attempts(task_id, commit['session_token']):
raise ValueError('original project attempts changed')
if not proof or interrupted is not None:
if not proof or interrupted is not None and not prior:
from .batch_resources import _valid_record
checkpoint = json.loads(_io_path(root / 'project-checkpoint.json').read_text(encoding='utf-8'))
owner_path = Path(checkpoint['resource_record'])
@@ -500,25 +549,28 @@ class QuickRunPreparer:
or task_id not in supervisor.get('protected_task_ids', ())):
raise ValueError('supervisor interruption is not bound to the closed native worker')
proof = dict(proof, operation_attempts=journal.project_commit_attempts(task_id, commit['session_token']))
if (not validate_project_commit_source(proof, root)
if (not (historical_intact(proof) if prior else validate_project_commit_source(proof, root))
or proof.get('operation_attempts') != journal.project_commit_attempts(task_id, commit['session_token'])):
raise ValueError('saved source or original attempts changed')
marker = capture_project_commit(self._data_root, root, commit)
if (marker['jobs'] != proof.get('jobs') or marker['outcomes'] != proof.get('outcomes')
marker = markers[commit['session_token']]
if (marker['jobs'] != proof.get('jobs') or marker['outcomes'] != proof.get('native_outcomes',proof.get('outcomes'))
or marker['files'][0]['sha256'] != proof['files'][0]['sha256']):
raise ValueError('native project marker changed')
covered.update(proof['jobs'])
covered_attempts.extend(proof['operation_attempts'].values())
for row in rows:
if row['job_id'] not in proof['jobs']:continue
outcome = (proof['outcomes'][row['job_id']], 'project_committed', '工程保存回读校验通过。')
saved_protocol = proof.get('validation_required') == 'saved_netlist_v1'
state = proof.get('native_outcomes',proof['outcomes'])[row['job_id']] if saved_protocol else proof['outcomes'][row['job_id']]
if saved_protocol and state == 'no_match':continue
outcome = (state, 'session_staged' if saved_protocol else 'project_committed', '工程保存回读校验通过。')
result = self.result_proof(root, row, outcome)
if proof.get('native_attempt') and outcome[0] == 'saved_ok' and any(
if proof.get('native_attempt') and outcome[0] in {'saved_ok','pending_save'} and any(
result.get('native_attempt', {}).get(key) != value for key, value in proof['native_attempt'].items()):
raise ValueError('native result differs from the exited project worker')
if any(proof.get('readback_files', {}).get(Path(item['path']).name) != item['sha256'] for item in result.get('files', ())):
raise ValueError('saved native readback evidence changed')
if outcome[0] == 'saved_ok':
if outcome[0] == 'saved_ok' and not saved_protocol:
from .value_readback import capture_value_readback
if capture_value_readback(root, row, outcome, project_commit=proof).get('value_readback_status') != 'verified':
raise ValueError('saved target Value readback is incomplete')
@@ -535,7 +587,8 @@ class QuickRunPreparer:
self._commit_staged_project(task_id)
for commit in commits:
proof = json.loads(commit['proof_json'])
if not validate_project_commit_source(proof, root):raise ValueError('saved source changed during recovery')
if not (historical_intact(proof) if commit['session_token'] in historical else validate_project_commit_source(proof, root)):
raise ValueError('saved source or historical proof changed during recovery')
handoff = QuickRunResult(root/'QuickPartReplace.vbs', root/'command.tsv', root/'status.tsv', root/'quick-part-replace.log', self.vbs_root_compatible)
self._bind_journal_handoff(task_id, handoff)
if protection is not None:
@@ -579,7 +632,8 @@ class QuickRunPreparer:
def write_expected_baselines(self, task_id, root, project_path):
journal=getattr(self,'journal',None)
if journal is None:return
rows=journal.expected_baselines(task_id,project_path)
rows=tuple(row for row in journal.expected_baselines(task_id,project_path)
if row.get('validation_mode') != 'saved_netlist_v1')
text='project_path\tschematic_name\tsheet_number\tsemantic_state\r\n'
text+=''.join('\t'.join(_encode_vbs_field(row[key]) for key in
('project_path','schematic_name','sheet_number','state'))+'\r\n' for row in rows)
@@ -618,6 +672,31 @@ class QuickRunPreparer:
uncertain_path = self._data_root / "quick-run" / "uncertain.flag"
if _io_path(uncertain_path).exists():
raise TaskCenterError("quick_run_uncertain", "a previous quick-run worker timed out or returned an uncorrelated status; reconcile the project before retrying")
if (self._process_runner is _run_process and getattr(self,'journal',None) is not None
and (project_session is None or not project_session.enabled)):
if not batch_mode:
from .single_step import prepare_private_single_step
prepare_private_single_step(self,task_id,projects,rules,copy_part_number_to_value,
**({'runtime':runtime} if runtime is not None else {}))
session = batch_session or self.begin_batch_session(task_id,projects,rules,
copy_part_number_to_value=copy_part_number_to_value,runtime=runtime)
if session.next_index >= len(session.commands):
raise TaskCenterError('quick_run_complete','all replacement rules in this queue are complete')
job = session.commands[session.next_index][1]
# A standalone or explicitly nonretained call still needs one closed,
# saved native prefix. The scope is held for this invocation only.
with self.project_session_scope(enabled=True,runtime=runtime) as scope:
result = self.execute_step(task_id,projects,rules,copy_part_number_to_value=copy_part_number_to_value,
expected_item=expected_item,batch_mode=True,batch_session=session,project_session=scope,
runtime=runtime,stop_event=stop_event)
if result.state == 'pending_save':
self.complete_project_session(task_id,scope,session,projects)
if result.state not in DONE_STATES | {'pending_save'}:return result
terminal = next(entry for entry in reversed(session.statuses) if entry[0] == job)
progress = session.progress
return QuickRunStepResult(result.script_path,result.command_path,result.status_path,result.log_path,
terminal[1],terminal[3],progress.next_project_path,progress.next_old_part_number,
progress.next_new_part_number,progress.next_schematic_name,progress.next_sheet_number,progress)
if self._process_runner is _run_process and not batch_mode:
from .single_step import prepare_private_single_step
prepare_private_single_step(self, task_id, projects, rules, copy_part_number_to_value,
@@ -1036,7 +1115,8 @@ class QuickRunPreparer:
or (stop_event is not None and stop_event.is_set())):
progress = self.complete_project_session(task_id, project_session, batch_session, projects)
state = 'no_match' if code == 'session_staged_no_match' else 'saved_ok'
message = '工程统一保存、关闭重开及回读校验通过。'
message = ('工程统一保存,原生数据核验通过。' if proof.get('validation_required') == 'saved_netlist_v1'
else '工程统一保存、关闭重开及回读校验通过。')
next_command = commands[batch_session.next_index] if batch_session is not None and batch_session.next_index < len(commands) else None
next_sheet = batch_session.sheets.get(next_command[1], (None, None)) if batch_session is not None and next_command is not None and batch_session.sheets is not None else (None, None)
return QuickRunStepResult(handoff.script_path, handoff.command_path, handoff.status_path, handoff.log_path,
@@ -1763,6 +1843,22 @@ def _recover_pre_mutation_hard_failures(
)
def _append_status_details(path: Path, statuses: tuple[tuple[str, str, str, str], ...]) -> None:
"""Publish closed-project receipts without replacing an active batch stream."""
payload = ''.join('\t'.join(_encode_vbs_field(field) for field in entry)+'\r\n' for entry in statuses).encode('utf-8')
try:
with _io_path(path).open('r+b') as stream:
stream.seek(0,os.SEEK_END)
end = stream.tell()
if end:
stream.seek(-1,os.SEEK_END)
if stream.read(1) != b'\n':raise ValueError('cannot append to an incomplete status stream')
stream.seek(0,os.SEEK_END)
stream.write(payload);stream.flush();os.fsync(stream.fileno())
except (OSError,ValueError) as error:
raise TaskCenterError('quick_run_status','cannot publish saved project status') from error
def _write_status_details(path: Path, statuses: tuple[tuple[str, str, str, str], ...]) -> None:
temporary = path.with_name(f".{path.name}.{uuid4().hex}.tmp")
text = "job_id\tstate\tcode\tmessage\r\n"
@@ -0,0 +1,273 @@
"""Validate a closed project's applied targets through one saved native export."""
import hashlib
import json
import re
from collections import Counter
from pathlib import Path
from . import native_netlist
from .batch_resources import write_record
from .execution_proof import proof_intact, validate_project_commit_source
from .path_access import canonical_path, internal_path
from .quick_run_protocol import _decode_vbs_field
def _hash(path):
return hashlib.sha256(internal_path(path).read_bytes()).hexdigest()
def _fields(line):
return [_decode_vbs_field(value) for value in line.split('\t')]
def _context(proof):
return {key: proof[key] for key in ('session_token', 'project_path', 'saved_sources', 'command_sha256')}
def _intact(record):
return (record.get('files') and proof_intact(record)
and all(_hash(path) == digest for path, digest in record['context']['saved_sources'].items())
and _hash(record['export_path']) == record['export_sha256'])
def _authoritative_export(record):
"""The mutable lookup record cannot supply graph data or captured inputs."""
result = json.loads(internal_path(record['export_path']).read_text(encoding='utf-8'))
capture = result['capture']
source_hashes = {str(canonical_path(path)).casefold():digest for path,digest in capture['source_hashes'].items()}
if (result.get('status') != 'success' or result.get('complete') is not True
or canonical_path(capture['project']) != canonical_path(record['context']['project_path'])
or any(source_hashes.get(str(canonical_path(path)).casefold()) != digest
for path,digest in record['context']['saved_sources'].items())
or set(result['outputs'].values()) != set(record['output_hashes'])
or any(_hash(path) != record['output_hashes'][path] for path in result['outputs'].values())):
raise ValueError('immutable saved native export differs from its original source binding')
native_netlist._check_capture(capture)
return result
def load_saved_export(root, project):
"""Return a verified intact shared export for the current saved source, or None."""
try:
record = json.loads(internal_path(Path(root) / 'saved-netlist-export.json').read_text(encoding='utf-8'))
if (record.get('status') == 'verified'
and canonical_path(record['context']['project_path']) == canonical_path(project)
and record['context']['command_sha256'] == _hash(Path(root) / 'command.tsv')
and record['context']['marker_sha256'] == _hash(Path(root) / ('project-commit-' + record['context']['session_token'] + '.tsv'))
and _intact(record)):
if _hash(record['verification_path']) != record['verification_sha256']:
raise ValueError('immutable saved target verification changed')
verified = json.loads(internal_path(record['verification_path']).read_text(encoding='utf-8'))
if any(verified.get(key) != record[key] for key in ('status','context','export_path','export_sha256')):
raise ValueError('saved target lookup differs from its immutable verification')
record['jobs'] = verified['jobs']
record['result'] = _authoritative_export(record)
record['capture'] = record['result']['capture']
return record
except (OSError, ValueError, KeyError, TypeError):pass
return None
def compact_saved_netlist(record, *, include_jobs=True):
result = {key: record[key] for key in ('status', 'export_path', 'export_sha256')}
result.update(verification_path=record['verification_path'], verification_sha256=record['verification_sha256'])
if include_jobs:
result.update(context=record['context'], jobs=record['jobs'], files=record['files'])
return result
def _expectations(root, row):
from .execution_proof import capture_result
from .native_helper import read_snapshot, require_resumable_transaction, saved_netlist_snapshot
snapshot = internal_path(root / f'snapshot-{row["job_id"]}.tsv')
if not saved_netlist_snapshot(snapshot):raise ValueError('saved netlist target snapshot protocol required')
# This validates the command, selected original target set and native attempt.
capture_result(root.parent, root, row, ('pending_save', 'session_staged', ''), strict=True, persist=False)
metadata, components = read_snapshot(snapshot)
report_path = Path(str(snapshot) + '.native.json')
report = json.loads(report_path.read_text(encoding='utf-8'))
binding = require_resumable_transaction(snapshot, report, metadata, components)
library = binding['library_row']
if library[1].casefold() != row['new_part'].casefold():raise ValueError('native library target changed')
writer = internal_path(root / f'writer-expectations-{row["job_id"]}.tsv')
records = [_fields(line) for line in writer.read_text(encoding='utf-8-sig').splitlines() if line]
header = ['W', '1', row['task_id'], row['job_id'], row['project_path'],
row.get('schematic_name',''), row.get('sheet_number',''), snapshot.read_bytes().decode('utf-8-sig')]
if not records or records[0] != header:raise ValueError('writer expectations are not bound to the original snapshot and command')
original = {item[1]: item[2] for item in components}
if row.get('target_scope') == 'targets':
selectors = [value.split('\x1f') for value in row.get('target_selectors','').split('\x1e')]
if (not selectors or any(len(value) != 3 or not value[1].strip() for value in selectors)
or {value[1].strip().casefold() for value in selectors} != {ref.strip().casefold() for ref in original.values()}):
raise ValueError('native snapshot reference set differs from the frozen target selectors')
old_values = {}
for line in snapshot.read_text(encoding='utf-8-sig').splitlines():
fields = _fields(line)
if fields[0] == 'A' and len(fields) == 12 and fields[2].casefold() == 'value':
if fields[1] in old_values:raise ValueError('original Value is ambiguous')
old_values[fields[1]] = fields[4] or fields[3]
has_nc = lambda text: '/' in text and any(part.strip().casefold() == 'nc' for part in text.split('/'))
expected = {}
for fields in records[1:]:
if len(fields) != 9 or fields[0] != 'C':raise ValueError('malformed writer target expectation')
_, uid, ref, value, present, name, label, part, cell = fields
if (uid not in original or uid in expected or ref != original[uid] or present not in {'0','1'}
or name != library[4] or label != library[5] or part.casefold() != row['new_part'].casefold()
or cell != row.get('target_cell','')):
raise ValueError('writer target expectation differs from native library/command')
mode = row['value_mode']
if mode != 'preserve':
policy_value = {'custom': row.get('custom_value',''), 'part_number': row['new_part'], 'part_label': library[5]}[mode]
if row.get('sync_nc','1') == '1' and has_nc(old_values.get(uid,'')) and not has_nc(policy_value):
policy_value = policy_value.rstrip(' ') + ('NC' if policy_value.rstrip(' ').endswith('/') else '/NC')
if present != '1' or value != policy_value:raise ValueError('writer Value contradicts the frozen write policy')
if row.get('sync_nc','1') == '1' and has_nc(old_values.get(uid,'')) and not has_nc(value):
raise ValueError('required original NC marker was not retained')
expected[uid] = dict(refdes=ref, value=value, present=present == '1', old_value=old_values.get(uid),
attributes={'Part Number': part, 'Part Name': name, 'Part Label': label}, target_cell=cell)
if set(expected) != set(original):raise ValueError('writer target set is incomplete')
return expected, binding, [snapshot, report_path, writer]
def _scope(component, row):
return all(not row.get(key) or component.get(field) == row[key]
for key, field in (('schematic_name','source_schematic'), ('sheet_number','source_page')))
def _observations(graph, row, expected, binding):
observations = []
counts = Counter(item['refdes'].strip().casefold() for item in expected.values())
remaining = {}
for uid, item in expected.items():
ref = item['refdes'].strip().casefold()
if ref not in remaining:
keys = native_netlist.reference_targets(graph, item['refdes'],
sheet=row.get('sheet_number',''), schematic=row.get('schematic_name',''))
if len(keys) != counts[ref] or not keys:
raise ValueError('saved native target units are missing or ambiguous')
if any(not _scope(graph['components'][key],row) or graph['components'][key].get('ambiguous_attributes') for key in keys):
raise ValueError('saved native target sheet or attributes are ambiguous')
remaining[ref] = list(keys)
# Match the declared multiset within one physical reference. Native UIDs
# may change; no expected property is inferred from the exported graph.
matches = []
for key in remaining[ref]:
attrs = graph['components'][key]['attributes']
if (all(attrs.get(name) is not None and
(attrs[name].casefold() == value.casefold() if name == 'Part Number' else attrs[name] == value)
for name,value in item['attributes'].items())
and (not item['target_cell'] or attrs.get('Cell Name') == item['target_cell'])
and attrs.get('Value','') == item['value']):
matches.append(key)
if not matches:raise ValueError('saved native target library attributes, Cell or Value differ from the write policy')
key = matches[0]
remaining[ref].remove(key)
symbol = graph['components'][key].get('symbol','')
if symbol:
target = re.fullmatch(r'(?:[^:\s]+:)?([^:\s]+?)(?:\.(\d+))?', binding['target_symbol'])
actual = re.match(r'([^\s]+?)\.(\d+) type ', symbol)
if (not target or not actual or target[1] != actual[1]
or target[2] is not None and target[2] != actual[2]
or not 1 <= int(actual[2]) <= binding['slot_count']):
raise ValueError('saved native target symbol differs from the selected library')
actual = graph['components'][key]['attributes']
observations.append(dict(uid=uid, refdes=item['refdes'], old_part_number=row['old_part'],
actual_part_number=actual['Part Number'], old_value=item['old_value'], actual_value=actual.get('Value',''),
old_value_present=item['old_value'] is not None,
actual_value_present=True if actual.get('Value') else None,
value_presence_coverage='native_ascii_empty_presence_unknown', actual_cell=actual.get('Cell Name','')))
return dict(value_readback_status='verified', value_readback=observations, value_readback_job_id=row['job_id'],
project_path=row['project_path'], schematic_name=row.get('schematic_name',''), sheet_number=row.get('sheet_number',''),
coverage_limits=['Native ASCII empty Value does not prove attribute presence; CAD display/layout is not checked.'])
def verify_saved_project(data_root, root, proof, rows, *, stop_event=None):
"""Export once, validate all applied targets, and return the verified commit proof."""
from .netlist_verification import _export_saved_capture
root, data_root = Path(root), Path(data_root)
if proof.get('validation_required') != 'saved_netlist_v1' or not validate_project_commit_source(proof, root):
raise ValueError('saved source-bound project proof is required')
def readbacks_intact():
return all(Path(name).name == name and _hash(root/name) == digest
for name,digest in proof.get('readback_files',{}).items())
if not readbacks_intact():raise ValueError('native writer evidence changed before saved export')
rows = {row['job_id']: row for row in rows}
if not set(proof['jobs']) <= rows.keys():raise ValueError('saved prefix is outside the frozen command plan')
context = _context(proof)
context['marker_sha256'] = proof['files'][0]['sha256']
evidence, inputs = {}, []
for job in proof['jobs']:
if proof.get('native_outcomes', proof['outcomes'])[job] == 'pending_save':
evidence[job] = _expectations(root, rows[job])
inputs.extend(evidence[job][2])
pointer = root / 'saved-netlist-export.json'
record = None
try:
candidate = json.loads(internal_path(pointer).read_text(encoding='utf-8'))
if candidate['context'] == context and _intact(candidate):record = candidate
except (OSError, ValueError, KeyError, TypeError):pass
if record is None:
directory = data_root / 'execution-proof' / ('saved-netlist-' + proof['session_token'])
capture_path = directory / 'capture/capture.json'
if capture_path.is_file():
capture = json.loads(capture_path.read_text(encoding='utf-8'))
native_netlist._check_capture(capture)
source_hashes = {str(canonical_path(path)).casefold():digest for path,digest in capture['source_hashes'].items()}
if (canonical_path(capture['project']) != canonical_path(proof['project_path'])
or any(source_hashes.get(str(canonical_path(path)).casefold()) != digest for path,digest in proof['saved_sources'].items())):
raise ValueError('saved native capture belongs to a different original source')
else:
capture = native_netlist.capture_project(Path(proof['project_path']), directory / 'capture')
if not validate_project_commit_source(proof, root):raise ValueError('saved source changed while capturing the native database')
result = _export_saved_capture(capture, directory / 'export', stop_event=stop_event)
if result.get('status') != 'success' or result.get('complete') is not True:
raise ValueError('complete native saved export unavailable: ' + str(result.get('reason','')))
manifest = directory / 'export/netlist.json'
paths = [Path(capture['manifest_path']), manifest, *map(Path,result['outputs'].values()),
*(Path(capture['root']) / name for name in capture['capture_hashes'])]
for path in inputs:
target = internal_path(directory / 'inputs' / path.name)
target.parent.mkdir(parents=True,exist_ok=True)
data = internal_path(path).read_bytes(); target.write_bytes(data)
if internal_path(path).read_bytes() != data:raise ValueError('native target evidence changed during capture')
paths.append(target)
files = [{'path':str(canonical_path(path)), 'sha256':_hash(path)} for path in dict.fromkeys(paths)]
record = dict(status='exported', context=context, capture=capture, result=result,
export_path=str(canonical_path(manifest)), export_sha256=_hash(manifest),
output_hashes={str(canonical_path(path)):_hash(path) for path in result['outputs'].values()}, files=files)
write_record(pointer, record)
record['result'] = _authoritative_export(record)
record['capture'] = record['result']['capture']
graph, jobs = record['result']['graph'], {}
for job in proof['jobs']:
row = rows[job]
if job in evidence:
expected, binding, _ = evidence[job]
jobs[job] = _observations(graph, row, expected, binding)
else:
candidates = [item for item in graph['components'].values() if _scope(item,row)]
if row.get('target_scope') == 'targets':
refs = {item.split('\x1f')[1].strip().casefold() for item in row['target_selectors'].split('\x1e')}
candidates = [item for item in candidates if item.get('refdes','').strip().casefold() in refs]
if any(item['attributes'].get('Part Number','').casefold() == row['old_part'].casefold() for item in candidates):
raise ValueError('native no-match claim still has original targets in the saved scope')
jobs[job] = dict(value_readback_status='verified',value_readback=[],value_readback_job_id=job,
project_path=row['project_path'],schematic_name=row.get('schematic_name',''),sheet_number=row.get('sheet_number',''))
if not validate_project_commit_source(proof,root) or not _intact(record) or not readbacks_intact():
raise ValueError('saved source/export or writer evidence changed during target validation')
record.update(status='verified',jobs=jobs)
verification = Path(record['export_path']).parent / 'verification.json'
verification_value = {key:record[key] for key in ('status','context','export_path','export_sha256','jobs')}
if verification.is_file():
if json.loads(verification.read_text(encoding='utf-8')) != verification_value:
raise ValueError('saved native target verification changed on resume')
else:write_record(verification,verification_value)
record.update(verification_path=str(canonical_path(verification)),verification_sha256=_hash(verification))
if not any(item['path'] == str(canonical_path(verification)) for item in record['files']):
record['files'].append({'path':str(canonical_path(verification)),'sha256':_hash(verification)})
write_record(pointer,record)
result = dict(proof, saved_netlist=compact_saved_netlist(record))
result['native_outcomes'] = proof.get('native_outcomes',proof['outcomes'])
result['outcomes'] = {job:'saved_ok' if state == 'pending_save' else state for job,state in result['native_outcomes'].items()}
result['files'] = list({(item['path'],item['sha256']):item for item in [*proof['files'],*record['files']]}.values())
return result
@@ -142,6 +142,18 @@ def _validated(root, row, outcome, *, project_commit=None):
def capture_value_readback(root, row, outcome, *, project_commit=None):
try:
if project_commit and project_commit.get('validation_required') == 'saved_netlist_v1':
saved = project_commit['saved_netlist']
details = saved['jobs'][row['job_id']]
binding = dict(command=dict(row),terminal=[row['job_id'],*outcome],
verification_path=saved['verification_path'], verification_sha256=saved['verification_sha256'],
export_path=saved['export_path'], export_sha256=saved['export_sha256'])
if (saved.get('status') != 'verified' or details.get('value_readback_status') != 'verified'
or details.get('value_readback_job_id') != row['job_id'] or outcome[0] != 'saved_ok'):
raise ValueError('saved native target Value proof differs')
_, path, _ = _paths(root,row)
write_record(path,dict(schema=3,binding=binding,details=details))
return details
details, binding = _validated(root, row, outcome, project_commit=project_commit)
_, saved, _ = _paths(root, row)
write_record(saved, dict(schema=2, binding=binding, details=details))
@@ -152,10 +164,26 @@ def capture_value_readback(root, row, outcome, *, project_commit=None):
return {'value_readback_status': 'rejected', 'value_readback_reason': str(error)}
def _load_saved_netlist_value(binding,row,outcome):
if (binding['command'] != dict(row) or binding['terminal'] != [row['job_id'],*outcome]
or _digest(_read(internal_path(binding['verification_path']))) != binding['verification_sha256']
or _digest(_read(internal_path(binding['export_path']))) != binding['export_sha256']):
raise ValueError('saved native Value evidence binding changed')
verified = json.loads(_read(internal_path(binding['verification_path'])))
if (verified['status'] != 'verified' or verified['export_path'] != binding['export_path']
or verified['export_sha256'] != binding['export_sha256']):
raise ValueError('saved native target verification is incomplete')
return verified['jobs'][row['job_id']]
def load_value_readback(root, row, outcome):
try:
_, saved, _ = _paths(root, row)
persisted = json.loads(_read(saved))
if persisted.get('schema') == 3:
details = _load_saved_netlist_value(persisted['binding'],row,outcome)
if details != persisted['details']:raise ValueError('persisted native Value observation changed')
return details
details, binding = _validated(root, row, outcome,
project_commit=persisted.get('binding',{}).get('project_commit'))
if persisted != dict(schema=2, binding=binding, details=details):