fix: preserve batch receipts and resource recovery after review
Core regression / Python core, intervention UI and release configuration (push) Successful in 18m39s
Core regression / JavaScript syntax (push) Successful in 7s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 11m51s
Core regression / JavaScript syntax (pull_request) Successful in 7s
Core regression / Python core, intervention UI and release configuration (push) Successful in 18m39s
Core regression / JavaScript syntax (push) Successful in 7s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 11m51s
Core regression / JavaScript syntax (pull_request) Successful in 7s
This commit is contained in:
1 parent
e63a82b695
commit
4a438e027b
25 files changed
+748
-138
No files matched your search
@@ -1,6 +1,6 @@
|
||||
"""Serial, confirmed queue execution with safe between-item pausing."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, replace
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
@@ -200,7 +200,13 @@ def execute_batch(
|
||||
item_messages.append(last_result.message)
|
||||
if last_result.progress is None:
|
||||
raise TaskCenterError('quick_run_queue_progress', '批量执行器未返回增量进度,队列已停止。')
|
||||
failed_component = (task.primary_project_id and last_result.state in {BATCH_FAILED_STATE, 'batch_skipped'}
|
||||
and session.journal_rows.get(metric['job_id'], {}).get('execution_unit') == 'component')
|
||||
candidate = last_result.progress
|
||||
if failed_component and project_session.worker is not None:
|
||||
# Verify the retained prefix before admitting another component.
|
||||
candidate = preparer.complete_project_session(task_id, project_session, session, projects)
|
||||
last_result = replace(last_result, progress=candidate)
|
||||
project_completed = candidate.completed_project_paths != progress.completed_project_paths
|
||||
synchronize = (
|
||||
(progress.completed_items == 0 and last_result.state != 'pending_save')
|
||||
@@ -240,12 +246,7 @@ def execute_batch(
|
||||
progress = updated
|
||||
if task.primary_project_id and last_result.state in {BATCH_FAILED_STATE, 'batch_skipped'}:
|
||||
row = session.journal_rows.get(metric['job_id'], {})
|
||||
if row.get('execution_unit') == 'component':
|
||||
# A failed component is terminal; rebuild its session before
|
||||
# admitting another UID against the last verified baseline.
|
||||
if project_session.worker is not None:
|
||||
project_session.worker.close()
|
||||
project_session.worker = None
|
||||
if failed_component:
|
||||
from .quick_run import _run_process
|
||||
if journal is None:
|
||||
raise TaskCenterError('quick_run_uncertain', '缺少失败回执及工程健康证明,暂缓剩余位号。')
|
||||
|
||||
@@ -148,6 +148,8 @@ def writer_identities(record):
|
||||
def isolation_proof(record):
|
||||
"""Certify handle closure and exact writer exit, never a desktop disappearance."""
|
||||
cleanup = record.get('cleanup') or {}
|
||||
if cleanup.get('desktop_lease_pending') is True:
|
||||
raise ValueError('Managed desktop lease is still held')
|
||||
if cleanup.get('desktop_lease'):
|
||||
from .desktop_slot import returned_lease_intact
|
||||
if not returned_lease_intact(cleanup['desktop_lease'], record['desktop']):
|
||||
|
||||
@@ -193,7 +193,9 @@ class BatchCadRuntime:
|
||||
|
||||
def _save(self, **values):
|
||||
record = dict(self.record, **values)
|
||||
write_record(self.path, record)
|
||||
# Prelaunch retries can change runtime state before it owns resources.
|
||||
if record['generation']:
|
||||
write_record(self.path, record)
|
||||
self.record = record
|
||||
|
||||
def _timing(self, phase, started, **details):
|
||||
@@ -209,17 +211,20 @@ class BatchCadRuntime:
|
||||
write_record(self.path.parent / f'isolated-generation-{self.generation}.json', self.record)
|
||||
if self.desktop is None:
|
||||
check_cancelled(self.stop_event if abort_event is None else abort_event)
|
||||
self.generation += 1
|
||||
generation = self.generation + 1
|
||||
name = 'dx-' + uuid4().hex
|
||||
self.desktop = (self.desktop_factory(name, enabled=True, managed=True)
|
||||
desktop = (self.desktop_factory(name, enabled=True, managed=True)
|
||||
if self.desktop_factory is PrivateDesktop else self.desktop_factory(name, enabled=True))
|
||||
name = self.desktop.name
|
||||
self._save(state='starting', generation=self.generation, desktop=name,
|
||||
# The factory does not acquire a desktop. Commit the starting
|
||||
# record before assigning cleanup ownership or entering it.
|
||||
self._save(state='starting', generation=generation, desktop=desktop.name,
|
||||
processes=[], writer_identities=[], cad_pid=None, cad_guid=None, checkpoints={}, native_operations={},
|
||||
blocking=True, isolation_proof=None,
|
||||
stopping_reason='', wait_reason='', primary_error=None,
|
||||
cad_process=None, cad_token=None, cad_shutdown=None, cad_start_requested=False, cleanup=None,
|
||||
release_state={'mentor': 'not_started', 'desktop': 'pending'})
|
||||
self.generation = generation
|
||||
self.desktop = desktop
|
||||
LIVE_RESOURCES[str(self.path)] = self
|
||||
started = time.monotonic()
|
||||
try:
|
||||
@@ -980,7 +985,7 @@ class BatchCadRuntime:
|
||||
completed_result=self.result, cleanup_error=self._close_failure)
|
||||
cleanup = self.desktop.cleanup_record or {}
|
||||
self.record['cleanup'] = cleanup
|
||||
if cleanup.get('desktop_confirmation', {}).get('released') is True:
|
||||
if (cleanup.get('desktop_confirmation') or {}).get('released') is True:
|
||||
self.record['release_results'] = {'mentor_released': True, 'desktop_released': True}
|
||||
self.record['release_state'] = {'mentor': 'released', 'desktop': 'released'}
|
||||
self._release_log('started', reason=reason)
|
||||
@@ -1083,7 +1088,7 @@ class BatchCadRuntime:
|
||||
self.record['release_results'] = {
|
||||
'mentor_released': not retained_cad,
|
||||
'desktop_released': cleanup.get('desktop_handle_closed') is True
|
||||
and cleanup.get('desktop_confirmation', {}).get('released') is True}
|
||||
and (cleanup.get('desktop_confirmation') or {}).get('released') is True}
|
||||
phases['desktop'] = ('waiting_for_mentor' if retained_cad else
|
||||
'released' if self.record['release_results']['desktop_released'] else 'failed')
|
||||
self.record['release_state'] = phases
|
||||
|
||||
@@ -159,7 +159,7 @@ def _require_cleanup(cleanup):
|
||||
from .desktop_slot import returned_lease_intact
|
||||
returned = isinstance(cleanup, dict) and returned_lease_intact(cleanup.get('desktop_lease', {}), cleanup.get('desktop'))
|
||||
if (not isinstance(cleanup, dict) or cleanup.get('errors') or not cleanup.get('desktop_handle_closed')
|
||||
or not (cleanup.get('desktop_confirmation', {}).get('released') or returned)):
|
||||
or not ((cleanup.get('desktop_confirmation') or {}).get('released') or returned)):
|
||||
pending('catalog private desktop cleanup was not proven')
|
||||
if not cleanup.get('processes'):
|
||||
pending('catalog owned process cleanup is missing')
|
||||
|
||||
@@ -70,9 +70,14 @@ class _Windows:
|
||||
def unlock(self, value):
|
||||
handle, name, release, thread, result = value
|
||||
release.set(); thread.join()
|
||||
if 'error' in result: raise result['error']
|
||||
handle.Close()
|
||||
_held.discard(name)
|
||||
try:
|
||||
if 'error' in result:
|
||||
raise result['error']
|
||||
finally:
|
||||
try:
|
||||
handle.Close()
|
||||
finally:
|
||||
_held.discard(name)
|
||||
|
||||
def desktop_exists(self, name):
|
||||
import win32service
|
||||
@@ -185,7 +190,8 @@ class DesktopSlot:
|
||||
self._save(dict(version=1, context=self.context, name=self.name, scope=self.scope,
|
||||
lease_id=self.lease_id, owner=self.backend.current_process(), state='leased', launches=[]))
|
||||
except Exception as error:
|
||||
self.backend.unlock(self.handle); self.handle = None
|
||||
handle, self.handle = self.handle, None
|
||||
self.backend.unlock(handle)
|
||||
if isinstance(error, TaskCenterError): raise
|
||||
raise TaskCenterError('desktop_slot_busy', '桌面租用记录无法核对,未创建新桌面。') from error
|
||||
return self
|
||||
@@ -218,7 +224,7 @@ class DesktopSlot:
|
||||
receipt = dict(returned=True, name=self.name, scope=self.scope, lease_id=self.lease_id,
|
||||
desktop_disappeared=desktop_disappeared, path=str(self.return_path),
|
||||
sha256=hashlib.sha256(internal_path(self.return_path).read_bytes()).hexdigest())
|
||||
self.backend.unlock(self.handle)
|
||||
self.handle = None
|
||||
handle, self.handle = self.handle, None
|
||||
self.receipt = receipt
|
||||
self.backend.unlock(handle)
|
||||
return receipt
|
||||
@@ -397,13 +397,18 @@ class ExecutionJournal:
|
||||
if record is None or not self.certified_startup_pause(task_id, record):
|
||||
return
|
||||
proof = json.loads(record['receipt_json'] or '{}').get('startup_pause', {})
|
||||
status = internal_path(root / 'status.tsv').read_bytes()
|
||||
status_size = proof.get('status_size')
|
||||
if proof.get('phase') == 'before_native_dispatch' and type(status_size) is int and 0 < status_size <= len(status):
|
||||
# A delayed marker retirement can follow appends to the certified stream.
|
||||
status = status[:status_size]
|
||||
if (proof.get('task_id') != task_id or proof.get('job_id') != row['job_id']
|
||||
or proof.get('native_dispatch_not_started') is not True
|
||||
or proof.get('project_closed') is not True or proof.get('worker_tree_exited') is not True
|
||||
or not proof.get('files') or not proof_intact(proof)
|
||||
or _source_digest(proof) != proof.get('source_sha256')
|
||||
or hashlib.sha256(marker.read_bytes()).hexdigest() != proof.get('current_command_sha256')
|
||||
or hashlib.sha256(internal_path(root / 'status.tsv').read_bytes()).hexdigest() != proof.get('status_sha256')
|
||||
or hashlib.sha256(status).hexdigest() != proof.get('status_sha256')
|
||||
# Scope cleanup removes this request after the durable pause;
|
||||
# a surviving request must still match the certified one.
|
||||
or internal_path(root / 'project-session.request').exists() and hashlib.sha256(
|
||||
@@ -600,7 +605,7 @@ class ExecutionJournal:
|
||||
return tuple(dict(row) for row in self.store._connection.execute('''SELECT * FROM execution_project_commits
|
||||
WHERE task_id=? AND round_id=?''', (task_id, current['round_id']))) if current else ()
|
||||
|
||||
def project_commit_attempts(self, task_id, session_token):
|
||||
def project_commit_attempts(self, task_id, session_token, *, require_recorded=False):
|
||||
with self.store._lock:
|
||||
current = self._round(task_id)
|
||||
if not current:return {}
|
||||
@@ -612,7 +617,7 @@ class ExecutionJournal:
|
||||
if token == session_token:
|
||||
actual = [row['operation_key'], row['attempt_id'], row['generation']]
|
||||
original = receipt.get('operation_attempt') or receipt.get('proof', {}).get('project_commit', {}).get('operation_attempts', {}).get(receipt['job_id'])
|
||||
if original is not None and original != actual:
|
||||
if original != actual and (require_recorded or original is not None):
|
||||
raise TaskCenterError('quick_run_uncertain', '原工程暂存尝试与当前执行记录不同。')
|
||||
result[receipt['job_id']] = actual
|
||||
return result
|
||||
@@ -668,6 +673,7 @@ class ExecutionJournal:
|
||||
def commit_project_results(self, task_id, session_token, proofs, commit_proof):
|
||||
"""Commit a whole staged prefix and its history in one SQL transaction."""
|
||||
from .execution_proof import proof_intact
|
||||
statuses = []
|
||||
with self.store.transaction():
|
||||
connection = self.store._connection
|
||||
current = self._round(task_id)
|
||||
@@ -675,7 +681,7 @@ class ExecutionJournal:
|
||||
WHERE task_id=? AND round_id=? AND session_token=?''', (task_id, current['round_id'], session_token)).fetchone() if current else None
|
||||
if commit is None:
|
||||
raise TaskCenterError('quick_run_uncertain', '缺少原工程暂存提交记录。')
|
||||
if commit['state'] == 'verified':return
|
||||
if commit['state'] == 'verified':return ()
|
||||
jobs = json.loads(commit['jobs_json'])
|
||||
if (commit_proof.get('session_token') != session_token
|
||||
or str(canonical_path(commit_proof.get('project_path', ''))).casefold() != commit['project_path']
|
||||
@@ -727,8 +733,10 @@ class ExecutionJournal:
|
||||
native_state = commit_proof.get('outcomes', {}).get(job, 'saved_ok')
|
||||
message = '工程统一保存,原生数据核验通过。' if saved_protocol else '工程统一保存、关闭重开及回读校验通过。'
|
||||
self.finish(attempt, native_state, 'project_committed', message, proof=proof)
|
||||
statuses.append((job, native_state, 'project_committed', message))
|
||||
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))
|
||||
return tuple(statuses)
|
||||
|
||||
def finish(self,attempt,native_state,code,message,*,progress=None,proof=None):
|
||||
if native_state not in _TERMINAL:raise TaskCenterError('quick_run_uncertain','不能提交未知的执行结果。')
|
||||
|
||||
@@ -779,29 +779,34 @@ class PrivateDesktop:
|
||||
event['error'] = str(error)
|
||||
self._desktop_handle_history.append(event)
|
||||
confirm = getattr(self._api, 'confirm_desktop_released', None)
|
||||
confirmation = None
|
||||
if self._slot is not None and self._handle is None and not errors:
|
||||
try:
|
||||
disappeared = not self._slot.backend.desktop_exists(self.name)
|
||||
self.cleanup_record['desktop_lease'] = self._slot.release(desktop_disappeared=disappeared)
|
||||
self._api.desktop_release_check = dict(desktop=self.name, released=disappeared,
|
||||
self._slot.release(desktop_disappeared=disappeared)
|
||||
confirmation = dict(desktop=self.name, released=disappeared,
|
||||
method='managed_lease_return', elapsed_seconds=0.0)
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
if self._slot.receipt is not None:
|
||||
self.cleanup_record['desktop_lease'] = self._slot.receipt
|
||||
elif confirm and self._handle is None:
|
||||
try:
|
||||
confirm(self.name)
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
confirmation = getattr(self._api, 'desktop_release_check', None)
|
||||
self.cleanup_record.update(desktop_handle_closed=self._handle is None,
|
||||
desktop_release_state='failed' if errors else 'released',
|
||||
desktop_confirmation=getattr(self._api, 'desktop_release_check', None),
|
||||
desktop_confirmation=confirmation,
|
||||
desktop_lease_pending=self._slot is not None and self._slot.receipt is None,
|
||||
desktop_handle_history=deepcopy(self._desktop_handle_history),
|
||||
process_history=deepcopy(self._process_history),
|
||||
diagnostic_scope={'external_handle_holders': 'unknown',
|
||||
'thread_desktops': 'unknown unless observed through residual windows; no exhaustive holder scan',
|
||||
'empty_windows_prove_no_holders': False},
|
||||
errors=[str(error) for error in errors])
|
||||
if not errors and self._slot is not None and not self._api.desktop_release_check['released']:
|
||||
if confirmation and self._slot is not None and not confirmation['released']:
|
||||
self.cleanup_record['desktop_release_state'] = 'reusable'
|
||||
if errors:
|
||||
self.cleanup_record['owned_resource_diagnostics'] = self._owned_resource_diagnostics()
|
||||
|
||||
@@ -375,7 +375,7 @@ def _check_hierarchy_graph(path, graph, root_block, *, include_rows=False):
|
||||
symbol['symbol'] = line[len('\tSymbol name '):]
|
||||
if roots != [root_block]:
|
||||
raise ValueError('Native hierarchy root differs from captured project')
|
||||
identities, boundaries, expanded = Counter(), set(), []
|
||||
identities, boundaries, expanded, source_sheets = Counter(), set(), [], set()
|
||||
|
||||
pending = [(root_block, '', set())]
|
||||
while pending:
|
||||
@@ -386,6 +386,7 @@ def _check_hierarchy_graph(path, graph, root_block, *, include_rows=False):
|
||||
identities.update({_instance_identity(uid, path): count for uid, count in row['symbols'].items()
|
||||
if uid not in row['children']})
|
||||
for item in row['rows']:
|
||||
source_sheets.add((name, item['source_page']))
|
||||
if item['source_uid'] in row['children'] and not _is_pcb(item):
|
||||
continue
|
||||
expanded.append(dict(item, instance_path=path, source_schematic=name))
|
||||
@@ -428,6 +429,8 @@ def _check_hierarchy_graph(path, graph, root_block, *, include_rows=False):
|
||||
consumed.add(index)
|
||||
if len(consumed) != len(remaining):
|
||||
raise ValueError('Hierarchical/effective instance coverage differs')
|
||||
# A page may contain only a child block absent from the flat component graph.
|
||||
graph['source_sheets'] = [list(sheet) for sheet in sorted(source_sheets)]
|
||||
return (identities, boundaries, expanded) if include_rows else (identities, boundaries)
|
||||
|
||||
|
||||
|
||||
@@ -242,24 +242,28 @@ def _reference_keys(graph, identity):
|
||||
def _reference_plan(plan, before, library):
|
||||
from copy import deepcopy
|
||||
result, rebound = deepcopy(plan), {}
|
||||
components = before['graph']['components']
|
||||
rows = []
|
||||
graph = before['graph']
|
||||
rows, plan_keys = [], {}
|
||||
for row in result['rows']:
|
||||
target = row['target']
|
||||
keys = _reference_keys(before['graph'], target)
|
||||
keys = _reference_keys(graph, target)
|
||||
if not keys and row['enabled']:
|
||||
raise ValueError('独立网表无法定位计划中的位号')
|
||||
plan_keys[target['uid']] = keys
|
||||
for key in keys:
|
||||
item = deepcopy(row)
|
||||
item['target']['uid'] = key
|
||||
rows.append(item)
|
||||
if target['uid'] in library:
|
||||
rebound[key] = library[target['uid']]
|
||||
for uid, identity in library.items():
|
||||
keys = _reference_keys(before['graph'], dict(identity, uid=uid))
|
||||
keys = _reference_keys(graph, dict(identity, uid=uid))
|
||||
if not keys and not identity.get('refdes'):
|
||||
keys = plan_keys.get(uid, ())
|
||||
if not keys:
|
||||
raise ValueError('独立网表无法定位回执中的位号或图页')
|
||||
for key in keys:
|
||||
exact = tuple(key for key in keys if key == uid or graph['components'][key].get('source_uid') == uid)
|
||||
for key in exact or keys:
|
||||
if key in rebound and rebound[key] != identity:
|
||||
raise ValueError('独立网表无法区分同一位号的原生单元回执')
|
||||
rebound[key] = identity
|
||||
result['rows'] = rows
|
||||
return result, rebound
|
||||
|
||||
@@ -102,8 +102,9 @@ def _validate_dependency(service, task_id, block):
|
||||
queue_bound = False
|
||||
store = getattr(child, '_store', None)
|
||||
with store._lock:
|
||||
dispatched = store._connection.execute('''SELECT 1 FROM execution_operations
|
||||
WHERE task_id=? AND (attempt_id IS NOT NULL OR generation>0 OR state NOT IN ('pending')) LIMIT 1''',
|
||||
dispatched = store._connection.execute('''SELECT 1 FROM execution_operations o
|
||||
JOIN execution_rounds r ON r.task_id=o.task_id AND r.round_id=o.round_id
|
||||
WHERE o.task_id=? AND (o.attempt_id IS NOT NULL OR o.generation>0 OR o.state!='pending') LIMIT 1''',
|
||||
(task_id,)).fetchone()
|
||||
evidence = child._quick_run_preparer.data_root / 'quick-run'
|
||||
absent_attempt = not dispatched and not any(internal_path(evidence).glob('snapshot-*'))
|
||||
|
||||
@@ -353,7 +353,7 @@ class QuickRunPreparer:
|
||||
journal_rows,
|
||||
)
|
||||
|
||||
def _bind_journal_handoff(self, task_id, handoff, *, append_only=False):
|
||||
def _bind_journal_handoff(self, task_id, handoff):
|
||||
journal = getattr(self, 'journal', None)
|
||||
if journal is None:
|
||||
return {}
|
||||
@@ -365,8 +365,7 @@ 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:
|
||||
if append_only:_append_status_details(handoff.status_path,additional)
|
||||
else:_write_status_details(handoff.status_path, (*details, *additional))
|
||||
_write_status_details(handoff.status_path, (*details, *additional))
|
||||
return {row['job_id']: row for row in rows}
|
||||
|
||||
def reconcile_terminal_receipts(self, task_id):
|
||||
@@ -374,15 +373,20 @@ class QuickRunPreparer:
|
||||
if journal is None or not journal.needs_reconciliation(task_id):
|
||||
return
|
||||
root = self._data_root/'quick-run'
|
||||
flag = root/'uncertain.flag'
|
||||
if _io_path(flag).exists():
|
||||
raise TaskCenterError('quick_run_uncertain', '工程已保留待核验保护,请先核验原执行证据。')
|
||||
from .handoff_guard import assert_handoff_intact
|
||||
assert_handoff_intact(root, task_id)
|
||||
try:
|
||||
self._commit_staged_project(task_id)
|
||||
self._bind_journal_handoff(task_id, QuickRunResult(root/'QuickPartReplace.vbs',
|
||||
root/'command.tsv', root/'status.tsv', root/'quick-part-replace.log', self.vbs_root_compatible))
|
||||
except TaskCenterError:
|
||||
_write_uncertain_flag(root/'uncertain.flag','uncommitted_receipt_requires_verification')
|
||||
raise
|
||||
except (OSError, ValueError, KeyError, TypeError) as error:
|
||||
_write_uncertain_flag(flag, 'uncommitted_receipt_requires_verification')
|
||||
if isinstance(error, TaskCenterError):
|
||||
raise
|
||||
raise TaskCenterError('quick_run_uncertain', '无法核验原工程提交回执;请保留执行证据。') from error
|
||||
|
||||
def result_proof(self, root, row, outcome, *, persist=True, project_commit=None):
|
||||
from .execution_proof import capture_result
|
||||
@@ -392,27 +396,38 @@ class QuickRunPreparer:
|
||||
def _commit_staged_project(self, task_id, *, session_token=None, bind_source=False):
|
||||
journal = getattr(self, 'journal', None)
|
||||
if journal is None:return
|
||||
from .execution_proof import capture_project_commit
|
||||
from .execution_proof import capture_project_commit, validate_project_commit_source
|
||||
from .operation_diagnostics import record_operation
|
||||
for commit in journal.pending_project_commits(task_id):
|
||||
if session_token is not None and commit['session_token'] != session_token:continue
|
||||
root = Path(commit['evidence_root'])
|
||||
record_operation(root, 'readback_proof', 'enter', item_id=commit['session_token'])
|
||||
try:
|
||||
commit_proof = capture_project_commit(self._data_root, root, commit)
|
||||
if commit.get('proof_json'):
|
||||
commit_proof = json.loads(commit['proof_json'])
|
||||
if commit_proof.get('saved_sources'):
|
||||
from .execution_proof import validate_project_commit_source
|
||||
if (not validate_project_commit_source(commit_proof, root)
|
||||
or capture_project_commit(self._data_root, root, commit)['files'][0]['sha256'] != commit_proof['files'][0]['sha256']):
|
||||
raise ValueError('saved project proof changed before receipt commit')
|
||||
marker = capture_project_commit(self._data_root, root, commit)
|
||||
saved_protocol = marker.get('validation_required') == 'saved_netlist_v1'
|
||||
persisted = json.loads(commit['proof_json']) if commit.get('proof_json') else None
|
||||
commit_proof = dict(persisted or marker)
|
||||
if persisted:
|
||||
if ((saved_protocol or commit_proof.get('saved_sources'))
|
||||
and not validate_project_commit_source(commit_proof, root)
|
||||
or marker['files'][0]['sha256'] != commit_proof['files'][0]['sha256']):
|
||||
raise ValueError('saved project proof changed before receipt commit')
|
||||
elif saved_protocol and not bind_source:
|
||||
commit_proof, _ = self._closed_project_commit_proof(root, commit)
|
||||
if (not validate_project_commit_source(commit_proof, root)
|
||||
or marker['files'][0]['sha256'] != commit_proof['files'][0]['sha256']
|
||||
or commit_proof.get('native_outcomes') != marker['native_outcomes']):
|
||||
raise ValueError('saved project proof changed after native closure')
|
||||
elif bind_source:
|
||||
if _io_path(root/'uncertain.flag').exists():
|
||||
raise TaskCenterError('quick_run_uncertain', '工程已保留待核验保护,不能重新绑定保存源。')
|
||||
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'])
|
||||
attempts = journal.project_commit_attempts(task_id, commit['session_token'])
|
||||
if commit_proof.get('operation_attempts', attempts) != attempts:
|
||||
raise ValueError('original project attempts changed')
|
||||
commit_proof['operation_attempts'] = attempts
|
||||
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:
|
||||
@@ -420,12 +435,12 @@ class QuickRunPreparer:
|
||||
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'):
|
||||
if bind_source and not persisted:
|
||||
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
|
||||
before_validation = persisted or 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 = {}
|
||||
@@ -446,11 +461,9 @@ class QuickRunPreparer:
|
||||
value_path = _io_path(root / f'value-readback-{job}.tsv')
|
||||
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)
|
||||
statuses = journal.commit_project_results(task_id, commit['session_token'], proofs, commit_proof)
|
||||
if saved_protocol and statuses:
|
||||
_append_status_details(root/'status.tsv', statuses)
|
||||
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)
|
||||
@@ -458,6 +471,25 @@ class QuickRunPreparer:
|
||||
record_operation(root, 'readback_proof', 'error', item_id=commit['session_token'], error=str(error))
|
||||
raise
|
||||
|
||||
def _closed_project_commit_proof(self, root, commit):
|
||||
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'])
|
||||
owner = json.loads(_io_path(owner_path).read_text(encoding='utf-8'))
|
||||
proof = checkpoint['project_commit_source']
|
||||
native = {key: checkpoint[key] for key in ('session_id', 'generation', 'attempt_id')}
|
||||
if (not _valid_record(owner, owner_path) or checkpoint.get('worker_closed') is not True
|
||||
or checkpoint.get('project_closed') is not True
|
||||
or Path(checkpoint['evidence_root']).resolve() != root.resolve()
|
||||
or _path_key(checkpoint['project_path']) != _path_key(commit['project_path'])
|
||||
or owner['session_id'] != native['session_id'] or owner['generation'] != native['generation']
|
||||
or owner['checkpoints'].get(str(root.resolve()).casefold()) != native['attempt_id']
|
||||
or proof.get('native_attempt') != native or proof.get('session_token') != commit['session_token']
|
||||
or proof.get('jobs') != json.loads(commit['jobs_json'])):
|
||||
raise ValueError('native close checkpoint is not bound to this project commit')
|
||||
return proof, owner_path
|
||||
|
||||
def recover_project_commit(self, task_id, *, confirmed=False):
|
||||
"""Reconcile an already closed/saved project without acquiring CAD."""
|
||||
journal = getattr(self, 'journal', None)
|
||||
@@ -524,27 +556,17 @@ class QuickRunPreparer:
|
||||
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 proof:
|
||||
attempts = journal.project_commit_attempts(task_id, commit['session_token'], require_recorded=True)
|
||||
if (proof.get('operation_attempts', attempts) != attempts
|
||||
or set(attempts) != set(proof['jobs'])):
|
||||
raise ValueError('original project attempts changed')
|
||||
proof.setdefault('operation_attempts', attempts)
|
||||
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'])
|
||||
owner = json.loads(_io_path(owner_path).read_text(encoding='utf-8'))
|
||||
proof = checkpoint['project_commit_source']
|
||||
native = {key: checkpoint[key] for key in ('session_id', 'generation', 'attempt_id')}
|
||||
if (not _valid_record(owner, owner_path) or checkpoint.get('worker_closed') is not True
|
||||
or checkpoint.get('project_closed') is not True
|
||||
or Path(checkpoint['evidence_root']).resolve() != root.resolve()
|
||||
or _path_key(checkpoint['project_path']) != _path_key(commit['project_path'])
|
||||
or owner['session_id'] != native['session_id'] or owner['generation'] != native['generation']
|
||||
or owner['checkpoints'].get(str(root.resolve()).casefold()) != native['attempt_id']
|
||||
or proof.get('native_attempt') != native or proof.get('session_token') != commit['session_token']
|
||||
or proof.get('jobs') != json.loads(commit['jobs_json'])):
|
||||
raise ValueError('native close checkpoint is not bound to this project commit')
|
||||
proof, owner_path = self._closed_project_commit_proof(root, commit)
|
||||
if interrupted is not None:
|
||||
supervisor = json.loads(_io_path(owner_path.parent / 'supervisor.json').read_text(encoding='utf-8'))
|
||||
if (native['session_id'] != interrupted or supervisor.get('batch_id') != interrupted
|
||||
if (proof['native_attempt']['session_id'] != interrupted or supervisor.get('batch_id') != interrupted
|
||||
or supervisor.get('state') != 'blocked' or supervisor.get('business_uncertain') is not True
|
||||
or task_id not in supervisor.get('protected_task_ids', ())):
|
||||
raise ValueError('supervisor interruption is not bound to the closed native worker')
|
||||
@@ -579,7 +601,7 @@ class QuickRunPreparer:
|
||||
raise ValueError('native/readback files changed since project closure')
|
||||
if not commit.get('proof_json'):
|
||||
journal.bind_project_commit_proof(task_id, commit['session_token'], proof)
|
||||
commit['proof_json'] = json.dumps(proof)
|
||||
commit['proof_json'] = json.dumps(proof)
|
||||
if (not set(journal.unresolved_jobs(task_id, rows)) <= covered
|
||||
or any(attempt not in covered_attempts for attempt in journal.project_commit_recovery_attempts(task_id))):
|
||||
raise ValueError('another native attempt is unresolved')
|
||||
@@ -906,11 +928,17 @@ class QuickRunPreparer:
|
||||
_append_log(handoff.log_path, "quick_run_uncertain malformed_status_after_worker")
|
||||
raise TaskCenterError("quick_run_uncertain", "quick-run worker left an unreadable status; reconcile the project before retrying") from error
|
||||
if completed.returncode == 75:
|
||||
if project_session is not None:
|
||||
project_session.on_commit = None
|
||||
if _io_path(uncertain_path).exists():
|
||||
raise TaskCenterError('quick_run_uncertain', '工程已保留待核验保护,请先核验原执行证据。')
|
||||
prefix_commit_pending = False
|
||||
try:
|
||||
proof = getattr(completed, 'prewrite_pause', {})
|
||||
pause_token = proof.get('session_token', '')
|
||||
marker = _io_path(handoff.command_path.parent / f'project-pause-{pause_token}.tsv')
|
||||
fields = marker.read_text(encoding='utf-8-sig').strip().split('\t')
|
||||
status_bytes = _io_path(handoff.status_path).read_bytes()
|
||||
if (runtime is None or journal_attempt is None or project_session is None
|
||||
or project_session.worker is None or pause_token != project_session.worker.token
|
||||
or proof.get('phase') != 'before_native_dispatch'
|
||||
@@ -923,17 +951,29 @@ class QuickRunPreparer:
|
||||
_io_path(handoff.command_path.with_name('project-session.request')).read_bytes()).hexdigest()
|
||||
or proof.get('current_command_sha256') != hashlib.sha256(
|
||||
_io_path(handoff.command_path.with_name('current-command.tsv')).read_bytes()).hexdigest()
|
||||
or proof.get('status_sha256') != hashlib.sha256(status_bytes).hexdigest()
|
||||
or any(entry[0] == row['job_id'] and entry[1] in TERMINAL_STATES for entry in after)
|
||||
or not ((stop_event is not None and stop_event.is_set())
|
||||
or (runtime.stop_event is not None and runtime.stop_event.is_set()))):
|
||||
raise ValueError('prewrite pause is not bound to the retained owner')
|
||||
self._commit_staged_project(task_id, session_token=pause_token)
|
||||
journal.pause_before_dispatch(journal_attempt, row, proof)
|
||||
journal.pause_before_dispatch(journal_attempt, row, dict(proof, status_size=len(status_bytes)))
|
||||
journal.finalize_startup_pause(task_id, handoff.command_path.parent)
|
||||
_write_status_details(handoff.status_path, (*after,
|
||||
(row['job_id'], 'pending', 'prewrite_paused', '工程安全关闭;当前项确认未替换,保留待执行。')))
|
||||
_append_status_details(handoff.status_path, (
|
||||
(row['job_id'], 'pending', 'prewrite_paused', '工程安全关闭;当前项确认未替换,保留待执行。'),))
|
||||
if proof.get('committed_prefix'):
|
||||
# Confirmed recovery can publish the prefix if the process
|
||||
# stops after committing SQL but before appending status.
|
||||
_write_uncertain_flag(uncertain_path, 'project_commit_unverified')
|
||||
prefix_commit_pending = True
|
||||
self._commit_staged_project(task_id, session_token=pause_token)
|
||||
if not any(commit['session_token'] == pause_token and commit['state'] == 'verified'
|
||||
and set(json.loads(commit['jobs_json'])) == set(proof['committed_prefix'])
|
||||
for commit in journal.project_commit_records(task_id)):
|
||||
raise ValueError('certified prewrite prefix has no matching verified receipt')
|
||||
_io_path(uncertain_path).unlink()
|
||||
except Exception as error:
|
||||
_write_uncertain_flag(uncertain_path, 'unproven_prewrite_pause')
|
||||
if not prefix_commit_pending:
|
||||
_write_uncertain_flag(uncertain_path, 'unproven_prewrite_pause')
|
||||
raise TaskCenterError('quick_run_uncertain', '暂停缺少完整的未写入与工程关闭证明;保留保护并核验。') from error
|
||||
_append_log(handoff.log_path, 'quick_run_paused prewrite_closed')
|
||||
raise TaskCenterError('operation_cancelled', '工程已安全关闭,已暂存前缀完成保存回读;当前项保留待执行。')
|
||||
|
||||
@@ -26,10 +26,24 @@ def _context(proof):
|
||||
|
||||
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 _saved_sources_intact(record['context']['saved_sources'])
|
||||
and _hash(record['export_path']) == record['export_sha256'])
|
||||
|
||||
|
||||
def _saved_sources_intact(sources):
|
||||
return bool(sources) and all(_hash(path) == digest for path, digest in sources.items())
|
||||
|
||||
|
||||
def _read_export_pointer(root):
|
||||
try:
|
||||
record = json.loads(internal_path(root / 'saved-netlist-export.json').read_text(encoding='utf-8'))
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
if not isinstance(record, dict) or record.get('status') not in {'exported', 'verified'}:
|
||||
raise ValueError('invalid saved native export lookup')
|
||||
return record
|
||||
|
||||
|
||||
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'))
|
||||
@@ -48,24 +62,33 @@ def _authoritative_export(record):
|
||||
|
||||
def load_saved_export(root, project):
|
||||
"""Return a verified intact shared export for the current saved source, or None."""
|
||||
root = Path(root)
|
||||
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
|
||||
record = _read_export_pointer(root)
|
||||
if record is None or record['status'] == 'exported':
|
||||
return None
|
||||
context = record['context']
|
||||
if (canonical_path(context['project_path']) != canonical_path(project)
|
||||
or context['command_sha256'] != _hash(root / 'command.tsv')):
|
||||
return None
|
||||
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[key] != record[key] for key in ('status', 'context', 'export_path', 'export_sha256')):
|
||||
raise ValueError('saved target lookup differs from its immutable verification')
|
||||
if not context['saved_sources']:
|
||||
raise ValueError('saved source hashes are missing')
|
||||
if not _saved_sources_intact(context['saved_sources']):
|
||||
return None
|
||||
marker = root / f'project-commit-{context["session_token"]}.tsv'
|
||||
if _hash(marker) != context['marker_sha256'] or not _intact(record):
|
||||
raise ValueError('saved marker or export artifacts changed')
|
||||
record['jobs'] = verified['jobs']
|
||||
record['result'] = _authoritative_export(record)
|
||||
record['capture'] = record['result']['capture']
|
||||
return record
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
|
||||
raise ValueError(f'saved native export integrity check failed: {error}') from error
|
||||
|
||||
|
||||
def compact_saved_netlist(record, *, include_jobs=True):
|
||||
@@ -134,6 +157,30 @@ def _scope(component, row):
|
||||
for key, field in (('schematic_name','source_schematic'), ('sheet_number','source_page')))
|
||||
|
||||
|
||||
def _verify_no_match(graph, row):
|
||||
components = graph['components']
|
||||
if row.get('target_scope') == 'targets':
|
||||
selectors = [item.split('\x1f') for item in row.get('target_selectors', '').split('\x1e')]
|
||||
if any(len(item) != 3 or not item[1].strip() for item in selectors):
|
||||
raise ValueError('saved native no-match coverage lacks valid frozen target selectors')
|
||||
for _, ref, _ in selectors:
|
||||
keys = native_netlist.reference_targets(graph, ref, sheet=row.get('sheet_number', ''),
|
||||
schematic=row.get('schematic_name', ''))
|
||||
if not keys or any(not _scope(components[key], row) for key in keys):
|
||||
raise ValueError(f'saved native no-match coverage lacks selected reference {ref}')
|
||||
# A frozen selector can return no_match only through already_target in the writer.
|
||||
if any(components[key]['attributes'].get('Part Number', '').casefold() != row['new_part'].casefold()
|
||||
for key in keys):
|
||||
raise ValueError(f'saved native no-match Part Number differs from the target for {ref}')
|
||||
return
|
||||
candidates = [item for component in components.values()
|
||||
for item in component.get('annotation_instances', [component]) if _scope(item, row)]
|
||||
if not candidates and [row['schematic_name'], row['sheet_number']] not in graph.get('source_sheets', ()):
|
||||
raise ValueError('saved native no-match coverage lacks the frozen schematic or sheet')
|
||||
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')
|
||||
|
||||
|
||||
def _observations(graph, row, expected, binding):
|
||||
observations = []
|
||||
counts = Counter(item['refdes'].strip().casefold() for item in expected.values())
|
||||
@@ -187,9 +234,16 @@ def verify_saved_project(data_root, root, proof, rows, *, stop_event=None):
|
||||
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')
|
||||
outcomes = proof.get('native_outcomes', proof['outcomes'])
|
||||
readbacks = proof.get('readback_files')
|
||||
required = {name for job, state in outcomes.items() if state == 'pending_save'
|
||||
for name in (f'snapshot-{job}.tsv', f'snapshot-{job}.tsv.native.json', f'writer-expectations-{job}.tsv')}
|
||||
|
||||
def readbacks_intact():
|
||||
return all(Path(name).name == name and _hash(root/name) == digest
|
||||
for name,digest in proof.get('readback_files',{}).items())
|
||||
return (isinstance(readbacks, dict) and required <= readbacks.keys()
|
||||
and all(Path(name).name == name and _hash(root / name) == digest
|
||||
for name, digest in readbacks.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')
|
||||
@@ -197,15 +251,18 @@ def verify_saved_project(data_root, root, proof, rows, *, stop_event=None):
|
||||
context['marker_sha256'] = proof['files'][0]['sha256']
|
||||
evidence, inputs = {}, []
|
||||
for job in proof['jobs']:
|
||||
if proof.get('native_outcomes', proof['outcomes'])[job] == 'pending_save':
|
||||
if outcomes[job] == 'pending_save':
|
||||
evidence[job] = _expectations(root, rows[job])
|
||||
inputs.extend(evidence[job][2])
|
||||
elif not rows[job].get('schematic_name') or not rows[job].get('sheet_number'):
|
||||
raise ValueError('saved native no-match coverage requires a frozen schematic and sheet')
|
||||
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
|
||||
candidate = _read_export_pointer(root)
|
||||
if candidate is not None and candidate['context'] == context:
|
||||
if not _intact(candidate):
|
||||
raise ValueError('saved native export changed before target validation')
|
||||
record = candidate
|
||||
if record is None:
|
||||
directory = data_root / 'execution-proof' / ('saved-netlist-' + proof['session_token'])
|
||||
capture_path = directory / 'capture/capture.json'
|
||||
@@ -228,7 +285,10 @@ def verify_saved_project(data_root, root, proof, rows, *, stop_event=None):
|
||||
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)
|
||||
data = internal_path(path).read_bytes()
|
||||
if hashlib.sha256(data).hexdigest() != readbacks[path.name]:
|
||||
raise ValueError('native target evidence changed during capture')
|
||||
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)]
|
||||
@@ -245,12 +305,7 @@ def verify_saved_project(data_root, root, proof, rows, *, stop_event=None):
|
||||
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')
|
||||
_verify_no_match(graph, row)
|
||||
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():
|
||||
@@ -267,7 +322,7 @@ def verify_saved_project(data_root, root, proof, rows, *, stop_event=None):
|
||||
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['native_outcomes'] = 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
|
||||
@@ -116,12 +116,6 @@ def bind_sources(proof, data_root, root, project, *, stop_event=None, release_me
|
||||
hashes[path] = source_hash(path)
|
||||
if not before or before != _source_digest(parameters):
|
||||
raise TaskCenterError('saved_source_changed', '保存后的源文件仍在变化,结果待核验;不会重复替换。')
|
||||
value = dict(proof, **parameters, source_sha256=before, saved_sources=hashes,
|
||||
command_sha256=hashlib.sha256(internal_path(root / 'command.tsv').read_bytes()).hexdigest())
|
||||
check_paused()
|
||||
publish('bound')
|
||||
record_operation(root, 'saved_source_bind', 'return', item_id=proof.get('session_token', ''))
|
||||
return value
|
||||
except OSError as failure:
|
||||
error = SavedSourceReadError(failure, path)
|
||||
stopped = stop_event is not None and stop_event.is_set()
|
||||
@@ -147,6 +141,16 @@ def bind_sources(proof, data_root, root, project, *, stop_event=None, release_me
|
||||
else:
|
||||
if status.get('state') != 'waiting': publish_read('waiting', error)
|
||||
time.sleep(.05)
|
||||
continue
|
||||
|
||||
command_hash = hashlib.sha256(internal_path(root / 'command.tsv').read_bytes()).hexdigest()
|
||||
check_paused()
|
||||
try:
|
||||
publish('bound')
|
||||
except OSError as diagnostic:
|
||||
record_operation(root, 'saved_source_diagnostic', 'error', error=str(diagnostic))
|
||||
record_operation(root, 'saved_source_bind', 'return', item_id=proof.get('session_token', ''))
|
||||
return dict(proof, **parameters, source_sha256=before, saved_sources=hashes, command_sha256=command_hash)
|
||||
except Exception as error:
|
||||
record_operation(root, 'saved_source_bind', 'error', item_id=proof.get('session_token', ''), error=str(error))
|
||||
try:
|
||||
|
||||
@@ -1188,10 +1188,13 @@ class TaskCenterService:
|
||||
raise TaskCenterError("quick_run_recovery", "请先恢复已删除的任务记录,再核验其中断步骤。")
|
||||
from .project_isolation import dependency_block, recover_dependency
|
||||
dependency = dependency_block(self._logging.root, task_id)
|
||||
with self._store._lock:
|
||||
dispatched = self._store._connection.execute('''SELECT 1 FROM execution_operations
|
||||
WHERE task_id=? AND (attempt_id IS NOT NULL OR generation>0) LIMIT 1''', (task_id,)).fetchone()
|
||||
if dependency is not None and not (dependency['state'] in {'readmission_prepared', 'readmitted'} and dispatched):
|
||||
dispatched = None
|
||||
if dependency is not None and dependency['state'] in {'readmission_prepared', 'readmitted'}:
|
||||
with self._store._lock:
|
||||
dispatched = self._store._connection.execute('''SELECT 1 FROM execution_operations o
|
||||
JOIN execution_rounds r ON r.task_id=o.task_id AND r.round_id=o.round_id
|
||||
WHERE o.task_id=? AND (o.attempt_id IS NOT NULL OR o.generation>0) LIMIT 1''', (task_id,)).fetchone()
|
||||
if dependency is not None and not dispatched:
|
||||
if stop_event is not None and stop_event.is_set():
|
||||
raise TaskCenterError('operation_cancelled', '共享数据源依赖核验已取消。')
|
||||
from .task_queue import assert_task_queue_idle
|
||||
|
||||
@@ -57,6 +57,36 @@ def test_cache_only_batch_does_not_create_desktop_or_cad(tmp_path):
|
||||
assert not Desktop.created
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['factory', 'first_write'])
|
||||
def test_desktop_startup_before_acquisition_does_not_block_later_batches(tmp_path, monkeypatch, failure):
|
||||
from dx_productivity.trial_task_center import batch_runtime
|
||||
|
||||
def fail_startup(*args, **options):
|
||||
raise OSError('desktop startup unavailable')
|
||||
|
||||
runtime = batch_runtime.BatchCadRuntime(
|
||||
tmp_path, 'execution', desktop_factory=fail_startup if failure == 'factory' else Desktop)
|
||||
if failure == 'first_write':
|
||||
write_record = batch_runtime.write_record
|
||||
|
||||
def fail_first_write(path, record):
|
||||
if record['state'] == 'starting':
|
||||
fail_startup()
|
||||
write_record(path, record)
|
||||
|
||||
monkeypatch.setattr(batch_runtime, 'write_record', fail_first_write)
|
||||
|
||||
with pytest.raises(OSError, match='desktop startup unavailable'):
|
||||
with runtime:
|
||||
with runtime.native_scope(tmp_path / 'startup'):
|
||||
pytest.fail('startup must fail before the desktop is acquired')
|
||||
|
||||
assert not Desktop.created
|
||||
assert batch_runtime.pending_resources(tmp_path) == ()
|
||||
with batch_runtime.BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop):
|
||||
pass
|
||||
|
||||
|
||||
def test_batch_forwards_business_failure_to_owned_cad_close(tmp_path):
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
runtime = BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop)
|
||||
@@ -182,6 +212,28 @@ def command_for(tmp_path, name='one'):
|
||||
return ('cscript', '//nologo', 'worker.vbs', str(root), 'python', 'job'), project
|
||||
|
||||
|
||||
def test_unlaunched_worker_retry_leaves_no_ownership_record(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import batch_runtime, worker_monitor
|
||||
|
||||
def fail_startup(*args, **options):
|
||||
raise OSError('desktop factory unavailable')
|
||||
|
||||
def unexpected_worker(*args, **options):
|
||||
pytest.fail('no worker may launch after the desktop factory fails')
|
||||
|
||||
monkeypatch.setattr(worker_monitor, 'run_monitored_process', unexpected_worker)
|
||||
command, _ = command_for(tmp_path)
|
||||
runtime = batch_runtime.BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=fail_startup)
|
||||
with pytest.raises(OSError, match='desktop factory unavailable'):
|
||||
with runtime:
|
||||
runtime.run_worker(command, 5)
|
||||
|
||||
assert runtime.record['retries']
|
||||
assert batch_runtime.pending_resources(runtime.root) == ()
|
||||
with batch_runtime.BatchCadRuntime(runtime.root, 'execution', desktop_factory=Desktop):
|
||||
pass
|
||||
|
||||
|
||||
def worker_runtime(tmp_path, monkeypatch, monitor):
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
from dx_productivity.trial_task_center import worker_monitor
|
||||
|
||||
@@ -21,3 +21,24 @@ def test_slot_can_be_returned_by_the_worker_monitor_thread():
|
||||
assert not thread.is_alive() and not errors
|
||||
again = backend.lock(name)
|
||||
backend.unlock(again)
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Windows mutex thread ownership')
|
||||
def test_release_error_closes_mutex_handle_and_allows_its_next_owner(monkeypatch):
|
||||
import win32event
|
||||
from dx_productivity.trial_task_center.desktop_slot import _Windows
|
||||
|
||||
def fail_release(handle):
|
||||
raise OSError('ReleaseMutex failed')
|
||||
|
||||
backend = _Windows()
|
||||
name = 'Local\\DxPartReplace-Release-Error-Test-' + uuid4().hex
|
||||
mutex = backend.lock(name)
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(win32event, 'ReleaseMutex', fail_release)
|
||||
with pytest.raises(OSError, match='ReleaseMutex failed'):
|
||||
backend.unlock(mutex)
|
||||
|
||||
assert not int(mutex[0])
|
||||
next_mutex = backend.lock(name)
|
||||
backend.unlock(next_mutex)
|
||||
@@ -105,7 +105,8 @@ def test_public_recovery_tries_verified_project_commit_before_cad(failed_native,
|
||||
|
||||
@pytest.mark.parametrize('publication_failure', [None, 'sql', 'marker'])
|
||||
@pytest.mark.parametrize('queue_directory', ['task-queues', 'workspace-queues'])
|
||||
def test_dependency_recovery_needs_confirmation_clear_source_and_never_opens_cad(tmp_path, monkeypatch, publication_failure, queue_directory):
|
||||
@pytest.mark.parametrize('previous_round', [False, True])
|
||||
def test_dependency_recovery_needs_confirmation_clear_source_and_never_opens_cad(tmp_path, monkeypatch, publication_failure, queue_directory, previous_round):
|
||||
import json
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
@@ -130,6 +131,13 @@ def test_dependency_recovery_needs_confirmation_clear_source_and_never_opens_cad
|
||||
store.set_task_status(task_id, TaskStatus.BLOCKED, summary='dependency')
|
||||
dependency, follower = tasks
|
||||
child = service.for_project_task(follower[0])
|
||||
if previous_round:
|
||||
with store.transaction():
|
||||
store._connection.execute('INSERT INTO execution_rounds(task_id, round_id) VALUES (?, ?)',
|
||||
(follower[0], 'current-round'))
|
||||
store._connection.execute('''INSERT INTO execution_operations
|
||||
(task_id, round_id, operation_key, command_json, state, attempt_id, generation)
|
||||
VALUES (?, 'old-round', 'old-operation', '{}', 'verified', 'old-attempt', 1)''', (follower[0],))
|
||||
marker = service._logging.root / 'dependency-blocks' / (follower[0] + '.json')
|
||||
marker.parent.mkdir()
|
||||
marker.write_text(json.dumps({'version': 1, 'task_id': follower[0], 'dependency_task_id': dependency[0],
|
||||
|
||||
@@ -68,18 +68,76 @@ def test_runtime_publishes_actual_managed_name_before_starting_a_worker(tmp_path
|
||||
runtime.close()
|
||||
|
||||
|
||||
def test_catalog_accepts_intact_return_without_claiming_desktop_disappearance(tmp_path):
|
||||
@pytest.mark.parametrize('confirmation', [{'released': False}, None])
|
||||
def test_catalog_accepts_intact_return_without_claiming_desktop_disappearance(tmp_path, confirmation):
|
||||
from dx_productivity.trial_task_center.cell_catalog import _require_cleanup
|
||||
backend = Backend(); current = slot(tmp_path, backend).acquire()
|
||||
receipt = current.release(desktop_disappeared=False)
|
||||
cleanup = dict(desktop=current.name, desktop_handle_closed=True, owned_cleanup_complete=True, errors=[],
|
||||
desktop_confirmation={'released': False}, desktop_lease=receipt,
|
||||
desktop_confirmation=confirmation, desktop_lease=receipt,
|
||||
processes=[dict(errors=[], job_active_processes=0, process_handle_closed=True, job_handle_closed=True)])
|
||||
_require_cleanup(cleanup)
|
||||
cleanup['desktop_lease'] = dict(receipt, lease_id='forged')
|
||||
with pytest.raises(TaskCenterError): _require_cleanup(cleanup)
|
||||
|
||||
|
||||
def test_mutex_release_error_preserves_the_durably_returned_lease(tmp_path):
|
||||
from dx_productivity.trial_task_center import batch_resources
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
|
||||
class ReleaseErrorBackend(Backend):
|
||||
def unlock(self, handle):
|
||||
super().unlock(handle)
|
||||
raise OSError('mutex release failed')
|
||||
|
||||
backend = ReleaseErrorBackend()
|
||||
api = Api(backend)
|
||||
|
||||
def factory(name, **options):
|
||||
return PrivateDesktop(name, **options, api=api, slot=slot(tmp_path / 'slot', backend))
|
||||
|
||||
runtime = BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=factory)
|
||||
with runtime:
|
||||
with runtime.native_scope(tmp_path / 'operation'):
|
||||
pass
|
||||
|
||||
record = batch_resources.pending_resources(runtime.root)[0]
|
||||
assert record['state'] == 'isolated' and record['blocking'] is False
|
||||
assert record['cleanup']['desktop_lease']['returned'] is True
|
||||
assert 'mutex release failed' in record['isolation_warning']
|
||||
|
||||
next_owner = slot(tmp_path / 'slot', backend).acquire()
|
||||
with pytest.raises(OSError, match='mutex release failed'):
|
||||
next_owner.release(desktop_disappeared=False)
|
||||
assert next_owner.handle is None
|
||||
|
||||
|
||||
def test_failed_lease_return_stays_blocking_until_the_slot_can_be_returned(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import batch_resources
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
|
||||
backend = Backend()
|
||||
api = Api(backend)
|
||||
|
||||
def factory(name, **options):
|
||||
return PrivateDesktop(name, **options, api=api, slot=slot(tmp_path / 'slot', backend))
|
||||
|
||||
def fail_return(*args):
|
||||
raise OSError('desktop observation unavailable')
|
||||
|
||||
runtime = BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=factory)
|
||||
with pytest.raises(TaskCenterError, match='desktop observation unavailable'):
|
||||
with runtime:
|
||||
with runtime.native_scope(tmp_path / 'operation'):
|
||||
monkeypatch.setattr(backend, 'desktop_exists', fail_return)
|
||||
|
||||
assert backend.locked and batch_resources.blocking_resources(runtime.root)
|
||||
monkeypatch.undo()
|
||||
batch_resources.cleanup_pending_resources(runtime.root, retry_failed=True)
|
||||
assert not backend.locked
|
||||
assert batch_resources.blocking_resources(runtime.root) == ()
|
||||
|
||||
|
||||
def test_failed_owned_handle_cleanup_keeps_slot_until_cleanup_succeeds(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import batch_resources
|
||||
backend = Backend(); api = Api(backend)
|
||||
|
||||
@@ -230,6 +230,7 @@ def test_hierarchy_expansion_repeated_blocks_requires_every_instance(tmp_path):
|
||||
path.write_text(text)
|
||||
graph = {'components': {uid: {} for uid in ('$9I2/$1I1', '$9I3/$1I1')}}
|
||||
native_netlist._check_hierarchy_graph(path, graph, 'board')
|
||||
assert graph['source_sheets'] == [['board', '1'], ['child', '1']]
|
||||
graph['components'].pop('$9I3/$1I1')
|
||||
with pytest.raises(ValueError, match='coverage'):
|
||||
native_netlist._check_hierarchy_graph(path, graph, 'board')
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from threading import Event
|
||||
@@ -10,6 +11,8 @@ from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _encode_vbs_field
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from test_nonblocking_items import component_case
|
||||
from test_saved_netlist_verification import saved_case
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pause_after_first', [False, True])
|
||||
@@ -169,3 +172,212 @@ def test_runtime_prewrite_pause_commits_prefix_and_retires_only_current_claim(tm
|
||||
assert service.quick_run_progress(task.task_id).completed_items == 1
|
||||
assert not preparer.has_interrupted(task.task_id)
|
||||
service._store.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('saved_case', ['execute'], indirect=True)
|
||||
@pytest.mark.parametrize('failure', [None, 'publication', 'marker_locked'])
|
||||
def test_saved_prewrite_pause_preserves_verified_prefix_and_retired_claim(
|
||||
saved_case, tmp_path, monkeypatch, failure):
|
||||
from dx_productivity.trial_task_center import quick_run
|
||||
from dx_productivity.trial_task_center.batch_attempt import _publish
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.quick_run import _file_identity, _read_status_details
|
||||
from dx_productivity.trial_task_center.stop_control import StopControl
|
||||
from test_batch_runtime import Cad, worker_runtime
|
||||
|
||||
service, store, task, preparer, project, rows, control = saved_case
|
||||
root = preparer.data_root / 'quick-run'
|
||||
prefix, paused = [row['job_id'] for row in rows]
|
||||
token = 'a' * 32
|
||||
stop = StopControl()
|
||||
(root / f'project-commit-{token}.tsv').unlink()
|
||||
monkeypatch.setattr('dx_productivity.trial_task_center.cell_catalog.preflight_command_target', lambda *args: None)
|
||||
marker_locked = failure == 'marker_locked'
|
||||
if marker_locked:
|
||||
unlink = Path.unlink
|
||||
|
||||
def lock_marker(path, *args, **kwargs):
|
||||
if marker_locked and path.name == 'current-command.tsv':
|
||||
raise PermissionError('current-command.tsv is locked')
|
||||
return unlink(path, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(Path, 'unlink', lock_marker)
|
||||
if failure == 'publication':
|
||||
append = quick_run._append_status_details
|
||||
|
||||
def fail_prefix_publication(path, statuses):
|
||||
if any(state == 'saved_ok' for _, state, _, _ in statuses):
|
||||
raise OSError('status append interrupted after SQL commit')
|
||||
return append(path, statuses)
|
||||
|
||||
monkeypatch.setattr(quick_run, '_append_status_details', fail_prefix_publication)
|
||||
|
||||
def native_monitor(command, *args, **kwargs):
|
||||
stop.set()
|
||||
path, expected = runtime._current_attempts[0]
|
||||
_publish(path, dict(expected, state='mutation_possible'))
|
||||
(root / f'project-commit-{token}.tsv').write_text(f'{token}\t{project}\tproject_saved\n{prefix}\tpending_save\n')
|
||||
(root / f'project-pause-{token}.tsv').write_text(f'{token}\t{project}\t{paused}\tprewrite_closed')
|
||||
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{paused}\tawaiting_native_replace\t\tsnapshot before pause\n')
|
||||
result = subprocess.CompletedProcess(command, 75, '', '')
|
||||
result.prewrite_pause = dict(session_token=token, job_id=paused, project_path=str(project),
|
||||
sequence=7, worker_tree_exited=True)
|
||||
return result
|
||||
|
||||
runtime = worker_runtime(tmp_path, monkeypatch, native_monitor)
|
||||
runtime.stop_event = stop
|
||||
runtime.cad_factory = lambda *args, stop_control=None, **options: Cad(*args, **options)
|
||||
runtime_attempt = 'c' * 32
|
||||
from dx_productivity.trial_task_center import batch_runtime
|
||||
monkeypatch.setattr(batch_runtime, 'uuid4', lambda: SimpleNamespace(hex=runtime_attempt))
|
||||
report_path = root / f'snapshot-{prefix}.tsv.native.json'
|
||||
report = json.loads(report_path.read_text())
|
||||
report['batch_attempt'].update(session_id=runtime.session_id, attempt_id=runtime_attempt)
|
||||
report_path.write_text(json.dumps(report))
|
||||
|
||||
class RetainedNative:
|
||||
enabled = True
|
||||
worker = SimpleNamespace(token=token, root=root)
|
||||
on_commit = None
|
||||
|
||||
def prepare(self, project): pass
|
||||
|
||||
def run_step(self, project, command, timeout):
|
||||
(root / 'project-session.request').write_text(f'{token}\t{project}\t{command[-1]}')
|
||||
if command[-1] == prefix:
|
||||
self.initial_command = command
|
||||
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{prefix}\tpending_save\tsession_staged\tapplied\n')
|
||||
return subprocess.CompletedProcess(command, 0, '', '')
|
||||
return runtime.run_worker(self.initial_command, timeout)
|
||||
|
||||
def close(self):
|
||||
if self.on_commit:
|
||||
self.on_commit(self.worker)
|
||||
self.worker = None
|
||||
|
||||
identity = _file_identity((root / 'status.tsv').stat())
|
||||
boundary = RetainedNative()
|
||||
def execute():
|
||||
return preparer.execute_step(task, service.projects(task), service.rules(task), batch_mode=True,
|
||||
batch_session=control['session'], project_session=boundary, stop_event=stop, runtime=runtime)
|
||||
with runtime:
|
||||
assert execute().state == 'pending_save'
|
||||
with pytest.raises(TaskCenterError) as raised:
|
||||
execute()
|
||||
if raised.value.code == 'operation_cancelled':
|
||||
boundary.close()
|
||||
assert _file_identity((root / 'status.tsv').stat()) == identity
|
||||
if marker_locked:
|
||||
assert (root / 'current-command.tsv').is_file()
|
||||
marker_locked = False
|
||||
assert not service.has_interrupted_quick_run(task)
|
||||
assert not (root / 'current-command.tsv').exists()
|
||||
record = store._connection.execute("SELECT * FROM execution_operations WHERE state='pending'").fetchone()
|
||||
assert preparer.journal.certified_startup_pause(task, record)
|
||||
proof = json.loads(preparer.journal.project_commit_records(task)[0]['proof_json'])
|
||||
assert proof['operation_attempts'] == preparer.journal.project_commit_attempts(task, token)
|
||||
assert proof['native_attempt']['attempt_id'] == runtime_attempt
|
||||
if failure == 'publication':
|
||||
assert raised.value.code == 'quick_run_uncertain'
|
||||
assert service.has_interrupted_quick_run(task)
|
||||
assert 'project_commit_unverified' in (root / 'uncertain.flag').read_text()
|
||||
# Older project proofs can recover from the independently bound per-job receipt.
|
||||
del proof['operation_attempts']
|
||||
store._connection.execute('UPDATE execution_project_commits SET proof_json=?', (json.dumps(proof),))
|
||||
assert service.recover_quick_run(task, confirmed=True).progress.saved_items == 1
|
||||
else:
|
||||
assert raised.value.code == 'operation_cancelled', raised.value.__cause__
|
||||
assert {job: (state, code) for job, state, code, _ in _read_status_details(root / 'status.tsv')} == {
|
||||
prefix: ('saved_ok', 'project_committed'), paused: ('pending', 'prewrite_paused')}
|
||||
assert not (root / 'uncertain.flag').exists()
|
||||
assert service.quick_run_progress(task).saved_items == 1
|
||||
assert not service.has_interrupted_quick_run(task)
|
||||
assert len(control['calls']) == 3
|
||||
|
||||
|
||||
def test_component_failure_closes_retained_prefix_with_commit_callback(component_case, monkeypatch):
|
||||
from dx_productivity.trial_task_center.project_session import ProjectSessionScope
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
|
||||
|
||||
service, store, tasks, calls, outcomes = component_case
|
||||
task = tasks[0].task_id
|
||||
child = service.for_project_task(task)
|
||||
preparer = child._quick_run_preparer
|
||||
project = child.projects(task)[0].path
|
||||
database = project.parent / 'database'
|
||||
database.mkdir()
|
||||
(database / 'icdb.dat').write_bytes(b'database')
|
||||
root = preparer.data_root / 'quick-run'
|
||||
targets = tuple(ComponentTarget(project, 'MAIN', '1', f'u{i}', f'R{i}', 'OLD', '10K') for i in (1, 2, 3))
|
||||
store.record_target_inventory(task, targets)
|
||||
store.replace_target_plan(task, tuple(TargetPlanRow(target, True, 'NEW') for target in targets))
|
||||
dispatched = []
|
||||
|
||||
class RetainedWorker:
|
||||
def __init__(self, project, root, **kwargs):
|
||||
self.project, self.root = project, root
|
||||
self.token = ('a' if not dispatched else 'b') * 32
|
||||
self._done = Event()
|
||||
self._abort = Event()
|
||||
self.staged = []
|
||||
|
||||
def run_step(self, command, timeout):
|
||||
job = command[-1]
|
||||
dispatched.append(job)
|
||||
if len(dispatched) == 2:
|
||||
outcomes[(task, ('R2',))] = 'batch_failed'
|
||||
return preparer._process_runner(command, timeout)
|
||||
if len(dispatched) == 3:
|
||||
assert preparer.journal.project_commit_records(task)[0]['state'] == 'verified'
|
||||
self.staged.append(job)
|
||||
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{job}\tpending_save\tsession_staged_no_match\tstaged\n')
|
||||
return subprocess.CompletedProcess(command, 0, '', '')
|
||||
|
||||
def close(self):
|
||||
if self._done.is_set():
|
||||
return
|
||||
marker = f'{self.token}\t{project}\tproject_verified\n'
|
||||
for job in self.staged:
|
||||
fields = (job, str(project), 'MAIN', '1', 'S\tfull_sheet_v1\r\nverified final state')
|
||||
(root / f'post-state-{job}.tsv').write_text(
|
||||
'job_id\tproject_path\tschematic_name\tsheet_number\tsemantic_state\n' +
|
||||
'\t'.join(_encode_vbs_field(value) for value in fields) + '\n', encoding='utf-8')
|
||||
marker += f'{job}\tno_match\n'
|
||||
(root / f'project-commit-{self.token}.tsv').write_text(marker, encoding='utf-8')
|
||||
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
|
||||
for job in self.staged:
|
||||
stream.write(f'{job}\tno_match\tproject_committed\tclosed\n')
|
||||
self._done.set()
|
||||
|
||||
monkeypatch.setattr('dx_productivity.trial_task_center.project_session.ProjectSessionWorker', RetainedWorker)
|
||||
preparer.project_session_scope = lambda **kwargs: ProjectSessionScope(preparer._process_runner, enabled=True)
|
||||
progress = child.quick_run_progress(task)
|
||||
result = child.execute_quick_run_queue(task, expected_item=(str(project), progress.next_old_part_number,
|
||||
progress.next_new_part_number, 'preserve'), stop_event=Event())
|
||||
assert len(dispatched) == 3
|
||||
assert result.progress.queue_complete
|
||||
assert (result.progress.no_match_items, result.progress.failed_items) == (2, 1)
|
||||
assert [row[0] for row in store._connection.execute('SELECT state FROM execution_operations ORDER BY rowid')] == [
|
||||
'no_match', 'failed', 'no_match']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('error_type', [ValueError, OSError])
|
||||
def test_reconciliation_marks_verification_errors_uncertain(saved_case, monkeypatch, error_type):
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
|
||||
_, _, task, preparer, _, _, _ = saved_case
|
||||
failure = error_type('saved database verification failed')
|
||||
|
||||
def fail(*args):
|
||||
raise failure
|
||||
|
||||
monkeypatch.setattr(preparer, '_commit_staged_project', fail)
|
||||
with pytest.raises(TaskCenterError) as raised:
|
||||
preparer.reconcile_terminal_receipts(task)
|
||||
assert raised.value.code == 'quick_run_uncertain'
|
||||
assert raised.value.__cause__ is failure
|
||||
assert (preparer.data_root / 'quick-run/uncertain.flag').read_text().startswith(
|
||||
'reason=uncommitted_receipt_requires_verification;')
|
||||
@@ -84,7 +84,9 @@ def test_partial_pause_commits_only_staged_prefix_and_rejects_incomplete_readbac
|
||||
assert record['state'] == 'verified'
|
||||
|
||||
|
||||
def test_crash_reconciliation_commits_native_marker_without_replaying_any_worker(staged_case, tmp_path):
|
||||
@pytest.mark.parametrize('persist_legacy_marker', [False, True])
|
||||
def test_crash_reconciliation_commits_native_marker_without_replaying_any_worker(staged_case, tmp_path, persist_legacy_marker):
|
||||
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
|
||||
store, journal, task, rows, proof = staged_case
|
||||
attempt = journal.claim(task, rows[0])
|
||||
@@ -102,7 +104,13 @@ def test_crash_reconciliation_commits_native_marker_without_replaying_any_worker
|
||||
'\t'.join(_encode_vbs_field(value) for value in fields) + '\n', encoding='utf-8')
|
||||
(tmp_path / ('project-commit-' + 'a' * 32 + '.tsv')).write_text(
|
||||
'a' * 32 + '\t' + rows[0]['project_path'] + '\tproject_verified\n' + job + '\tno_match\n', encoding='utf-8')
|
||||
if persist_legacy_marker:
|
||||
commit = journal.pending_project_commits(task)[0]
|
||||
marker_proof = capture_project_commit(tmp_path, tmp_path, commit)
|
||||
journal.bind_project_commit_proof(task, commit['session_token'], marker_proof)
|
||||
preparer._commit_staged_project(task)
|
||||
preparer._commit_staged_project(task)
|
||||
assert store._connection.execute('SELECT state FROM execution_operations WHERE attempt_id=?', (attempt.attempt_id,)).fetchone()[0] == 'no_match'
|
||||
assert len(HistoryRepository(store).page().rows) == 1
|
||||
commit_proof = json.loads(journal.project_commit_records(task)[0]['proof_json'])
|
||||
assert commit_proof['operation_attempts'] == {job: [attempt.operation_key, attempt.attempt_id, attempt.generation]}
|
||||
@@ -134,6 +134,27 @@ def test_reused_uid_cannot_override_a_known_reference_mismatch():
|
||||
_reference_plan(plan,graph('$1I1'),{})
|
||||
|
||||
|
||||
def test_multiunit_reference_plan_keeps_each_saved_value_with_its_source_unit():
|
||||
from dx_productivity.trial_task_center.netlist_verification import NetlistVerification, _reference_plan
|
||||
before = graph('$1I1')
|
||||
components = before['graph']['components']
|
||||
components['rebound-unit-2'] = deepcopy(components['$1I1'])
|
||||
components['rebound-unit-2'].update(source_uid='$1I2', symbol='res.2 type Primitive ForwardPCB')
|
||||
components['rebound-unit-2']['pins']['p1']['number'] = '2'
|
||||
before['graph']['nets'][0]['endpoints'].append(['rebound-unit-2', 'p1'])
|
||||
target = dict(uid='@REFDES|R1', refdes='R1', old_value='')
|
||||
plan = {'copy_value': False, 'rows': [dict(enabled=True, target=target,
|
||||
new_part_number='NEW', custom_value_enabled=False, sync_nc=False)]}
|
||||
library = {uid: dict(refdes='R1', attributes={'Part Number': 'NEW'}, preserved_value=value)
|
||||
for uid, value in [('$1I1', '10K'), ('$1I2', '20K')]}
|
||||
after = deepcopy(before)
|
||||
for uid, value in [('$1I1', '10K'), ('rebound-unit-2', '20K')]:
|
||||
after['graph']['components'][uid]['attributes'] = {'Part Number': 'NEW', 'Value': value}
|
||||
rows, rebound = _reference_plan(plan, before, library)
|
||||
expected = NetlistVerification._expected(rows, after, rebound)
|
||||
assert native_netlist.compare_netlists(before, after, expected_changes=expected)['verified'] is True
|
||||
|
||||
|
||||
def test_vbs_unselected_duplicate_uids_get_distinct_reference_keys(tmp_path):
|
||||
import test_accuracy_vbs_guards as guards
|
||||
output=guards.run_vbs(tmp_path,['QPComponentIdentityKey','QPBindSheetReferences'],'''
|
||||
|
||||
@@ -6,7 +6,7 @@ import pytest
|
||||
from dx_productivity.trial_task_center import batch_resources, batch_runtime, isolated_desktop
|
||||
|
||||
|
||||
def runtime_with_residual(tmp_path, monkeypatch):
|
||||
def runtime_with_residual(tmp_path, monkeypatch, *, confirmation=False):
|
||||
calls = []
|
||||
class Desktop:
|
||||
def __init__(self, name, **options):
|
||||
@@ -18,7 +18,8 @@ def runtime_with_residual(tmp_path, monkeypatch):
|
||||
calls.append('close')
|
||||
self.cleanup_record = {'desktop_handle_closed': True,
|
||||
'owned_cleanup_complete': True,
|
||||
'desktop_confirmation': {'released': False}, 'errors': ['foreign reference']}
|
||||
'desktop_confirmation': None if confirmation is None else {'released': confirmation},
|
||||
'errors': ['foreign reference']}
|
||||
raise OSError('foreign reference')
|
||||
def release_desktop(self):
|
||||
calls.append('observe')
|
||||
@@ -30,8 +31,9 @@ def runtime_with_residual(tmp_path, monkeypatch):
|
||||
return runtime, calls
|
||||
|
||||
|
||||
def test_residual_desktop_is_warning_admits_fresh_batch_and_never_repeats_close(tmp_path, monkeypatch):
|
||||
runtime, calls = runtime_with_residual(tmp_path, monkeypatch)
|
||||
@pytest.mark.parametrize('confirmation', [False, None])
|
||||
def test_residual_desktop_is_warning_admits_fresh_batch_and_never_repeats_close(tmp_path, monkeypatch, confirmation):
|
||||
runtime, calls = runtime_with_residual(tmp_path, monkeypatch, confirmation=confirmation)
|
||||
runtime.close()
|
||||
assert runtime.record['state'] == 'isolated'
|
||||
assert runtime.record['blocking'] is False
|
||||
|
||||
@@ -102,6 +102,8 @@ def saved_case(tmp_path, monkeypatch, request):
|
||||
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='))
|
||||
if control['damage'] == 'wrong_page':
|
||||
text = text.replace('page 1', 'page 2').replace('page 1', 'page 2')
|
||||
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})()
|
||||
@@ -244,6 +246,79 @@ def test_saved_prefix_mixed_applied_and_no_match_commits_after_one_export(saved_
|
||||
assert len(control['calls'])==3
|
||||
|
||||
|
||||
@pytest.mark.parametrize(('ref', 'damage', 'error'), [
|
||||
(None, 'wrong_page', 'coverage'), ('R2', 'wrong_page', 'coverage'), ('R3', None, 'coverage'),
|
||||
('R2', 'part', 'Part Number'), ('R2', None, None), (None, None, None),
|
||||
(None, 'unscoped', 'coverage'),
|
||||
])
|
||||
def test_saved_no_match_requires_exported_sheet_and_every_selected_part(saved_case, ref, damage, error):
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
from dx_productivity.trial_task_center.saved_netlist_verification import verify_saved_project
|
||||
_, _, _, preparer, project, rows, control = saved_case
|
||||
root = preparer.data_root / 'quick-run'
|
||||
token = 'a' * 32
|
||||
row = rows[1].copy()
|
||||
job = row['job_id']
|
||||
if ref is not None:
|
||||
row.update(target_scope='targets', target_selectors=f'@REFDES|{ref}\x1f{ref}\x1f10K')
|
||||
if damage == 'unscoped':
|
||||
row['sheet_number'] = ''
|
||||
control['damage'] = damage
|
||||
(root / f'project-commit-{token}.tsv').write_text(f'{token}\t{project}\tproject_saved\n{job}\tno_match\n')
|
||||
proof = capture_project_commit(preparer.data_root, root, dict(session_token=token,
|
||||
project_path=str(project.resolve()).casefold(), jobs_json=json.dumps([job])))
|
||||
proof = bind_project_commit_source(dict(proof, readback_files={}), preparer.data_root, root, project)
|
||||
if error:
|
||||
with pytest.raises(ValueError, match=error):
|
||||
verify_saved_project(preparer.data_root, root, proof, [row])
|
||||
else:
|
||||
verified = verify_saved_project(preparer.data_root, root, proof, [row])
|
||||
assert verified['outcomes'] == {job: 'no_match'}
|
||||
assert verified['saved_netlist']['status'] == 'verified'
|
||||
assert len(control['calls']) == (0 if damage == 'unscoped' else 3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('readbacks', [None, {}, {'unrelated.tsv': 'value'}])
|
||||
def test_saved_applied_write_requires_bound_writer_files_before_export(saved_case, readbacks):
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
from dx_productivity.trial_task_center.saved_netlist_verification import verify_saved_project
|
||||
_, _, _, preparer, project, rows, control = saved_case
|
||||
root = preparer.data_root / 'quick-run'
|
||||
proof = capture_project_commit(preparer.data_root, root, dict(session_token='a' * 32,
|
||||
project_path=str(project.resolve()).casefold(), jobs_json=json.dumps([row['job_id'] for row in rows])))
|
||||
if readbacks is not None:
|
||||
proof['readback_files'] = readbacks
|
||||
proof = bind_project_commit_source(proof, preparer.data_root, root, project)
|
||||
with pytest.raises(ValueError, match='writer evidence'):
|
||||
verify_saved_project(preparer.data_root, root, proof, rows)
|
||||
assert control['calls'] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('damage', ['pointer', 'marker', 'verification', 'manifest', 'output'])
|
||||
def test_same_source_saved_export_integrity_failure_is_visible(saved_case, damage):
|
||||
from dx_productivity.trial_task_center.saved_netlist_verification import load_saved_export
|
||||
_, _, task, preparer, project, _, _ = saved_case
|
||||
root = preparer.data_root / 'quick-run'
|
||||
preparer._commit_staged_project(task, bind_source=True)
|
||||
pointer = root / 'saved-netlist-export.json'
|
||||
record = json.loads(pointer.read_text(encoding='utf-8'))
|
||||
paths = {'pointer': pointer, 'marker': root / f'project-commit-{record["context"]["session_token"]}.tsv',
|
||||
'verification': Path(record['verification_path']), 'manifest': Path(record['export_path']),
|
||||
'output': Path(record['result']['outputs']['hier'])}
|
||||
paths[damage].write_text('corrupt', encoding='utf-8')
|
||||
with pytest.raises(ValueError, match='saved native export'):
|
||||
load_saved_export(root, project)
|
||||
|
||||
|
||||
def test_later_source_is_a_saved_export_cache_miss(saved_case):
|
||||
from dx_productivity.trial_task_center.saved_netlist_verification import load_saved_export
|
||||
_, _, task, preparer, project, _, _ = saved_case
|
||||
root = preparer.data_root / 'quick-run'
|
||||
preparer._commit_staged_project(task, bind_source=True)
|
||||
(project.parent / 'database/icdb.dat').write_bytes(b'later source revision')
|
||||
assert load_saved_export(root, project) is None
|
||||
|
||||
|
||||
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')
|
||||
|
||||
@@ -230,6 +230,21 @@ def test_bad_optional_progress_does_not_block_saved_source_binding(tmp_path, pro
|
||||
assert bind_project_commit_source({}, root.parent, root, project)['saved_sources']
|
||||
|
||||
|
||||
def test_status_file_sharing_conflict_does_not_recycle_mentor(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import saved_source, batch_resources
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
project, database, root = inputs(tmp_path)
|
||||
write_record = batch_resources.write_record
|
||||
def write(path, record):
|
||||
if path.name == 'saved-source-status.json':
|
||||
raise locked()
|
||||
return write_record(path, record)
|
||||
monkeypatch.setattr(batch_resources, 'write_record', write)
|
||||
monkeypatch.setattr(saved_source, 'LOCK_WAIT_SECONDS', 0)
|
||||
assert bind_project_commit_source({}, root.parent, root, project,
|
||||
release_mentor=lambda _: pytest.fail('diagnostic file lock recycled Mentor'))['saved_sources']
|
||||
|
||||
|
||||
def test_pause_after_release_notice_never_starts_cad_recycling(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import saved_source, batch_resources
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
|
||||
Reference in new issue
Block a user