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
|
||||
|
||||
Reference in new issue
Block a user