fix: address PR27 lifecycle, BOM and netlist review findings
Core regression / Python core, intervention UI and release configuration (push) Failing after 4m4s
Core regression / JavaScript syntax (push) Successful in 5s
Core regression / Python core, intervention UI and release configuration (pull_request) Failing after 4m20s
Core regression / JavaScript syntax (pull_request) Successful in 4s

This commit is contained in:
阿白叔 committed 2026-11-13 16:03:59 +08:00
1 parent 0ee83e77e2
commit f9d5e56bb8
58 files changed
+20646 -164

No files matched your search

+144 -91
View File
@@ -13,7 +13,7 @@ from ..trial_task_center.task_queue import execute_task_queue
def _failure_evidence(service, journal, run_id, baseline):
evidence = {key: baseline[key] for key in ('tasks', 'entries', 'retry') if key in baseline}
evidence = {key: baseline[key] for key in ('tasks', 'entries', 'retry', 'netlist_verification') if key in baseline}
if not baseline:
return evidence
try:
@@ -43,14 +43,22 @@ def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resu
if schedule_id:
schedules = ScheduleStore(root)
with schedules.execution_lease(schedule_id):
if resume:
_bound_schedule(schedules, prior)
receipt = _execute_confirmed_run(service, root, task_ids, report, stop, run_id,
resume=resume, schedule=schedule, automatic=automatic)
if resume:
schedules.finish(schedule_id, 'interrupted' if receipt['status'] in {'paused', 'blocked'} else receipt['status'],
repair_run_id=run_id, run_id=run_id, receipt=receipt)
return receipt
try:
if resume:
_bound_schedule(schedules, prior)
receipt = _execute_confirmed_run(service, root, task_ids, report, stop, run_id,
resume=resume, schedule=schedule, automatic=automatic)
if resume:
schedules.finish(schedule_id, 'interrupted' if receipt['status'] in {'paused', 'blocked'} else receipt['status'],
repair_run_id=run_id, run_id=run_id, receipt=receipt)
return receipt
except Exception:
original = prior or RunJournal(root).get(run_id)
if original:
if original['schedule_id'] != schedule_id:
raise TaskCenterError('schedule_run_conflict', '运行已不再绑定当前排期执行租约。')
_finish_failed_schedule(schedules, RunJournal(root), original)
raise
return _execute_confirmed_run(service, root, task_ids, report, stop, run_id, resume=resume)
@@ -74,6 +82,7 @@ def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, res
raise TaskCenterError('run_blocked', '原执行范围或证据已变化,请先核验。')
baseline = inspected.get('result') or {}
journal.resume(run_id)
initialized = True
journal.repair_retry_checkpoint(service, run_id)
else:
journal.begin(run_id, task_ids, report['plan_hashes'], schedule_id=schedule['schedule_id'] if schedule else None)
@@ -92,10 +101,10 @@ def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, res
schedules.finish(schedule['schedule_id'], 'interrupted', run_id=run_id, receipt=failure)
raise
return _finish_execution_run(service, root, task_ids, stop, run_id, result,
schedule=schedule if claimed else None)
baseline=baseline, schedule=schedule if claimed else None)
def _finish_execution_run(service, root, task_ids, stop, run_id, result, *, schedule=None):
def _finish_execution_run(service, root, task_ids, stop, run_id, result, *, baseline, schedule=None):
journal = RunJournal(root)
schedules = ScheduleStore(root) if schedule is not None else None
entries = [{'task_id': e.task_id, 'state': e.state, 'message': e.message} for e in result.entries]
@@ -112,7 +121,7 @@ def _finish_execution_run(service, root, task_ids, stop, run_id, result, *, sche
if result.netlist_verification:
receipt['netlist_verification'] = result.netlist_verification
# Persist the executor's known outcome before optional readback/enrichment.
journal.finish(run_id, receipt)
_persist_execution_receipt(service, journal, run_id, receipt, baseline)
try:
receipt['cad_verification'] = CadVerificationAdapter(service).after_run(task_ids,
netlist_verification=result.netlist_verification)
@@ -134,23 +143,42 @@ def _finish_execution_run(service, root, task_ids, stop, run_id, result, *, sche
if status == 'completed' and receipt['acceptance']['status'] in {'different', 'unavailable'}:
receipt['status'] = 'failed'
receipt['message'] = '替换执行已收尾,独立网表验收未通过;保留已保存回执,不重复替换。'
try:
journal.finish(run_id, receipt)
except Exception as error:
receipt['reporting_errors'].append({'code': 'receipt_enrichment_unavailable', 'error': type(error).__name__})
_persist_execution_receipt(service, journal, run_id, receipt, baseline)
if schedule is not None:
try:
schedules.finish(schedule['schedule_id'], 'interrupted' if receipt['status'] in {'paused', 'blocked'} else receipt['status'],
run_id=run_id, receipt=receipt)
except Exception as error:
receipt['reporting_errors'].append({'code': getattr(error, 'code', 'schedule_receipt_unavailable')})
try:
journal.finish(run_id, receipt)
except Exception:
receipt['reporting_errors'].append({'code': 'receipt_enrichment_unavailable'})
_persist_execution_receipt(service, journal, run_id, receipt, baseline)
raise
return receipt
def _persist_execution_receipt(service, journal, run_id, receipt, baseline):
try:
journal.finish(run_id, receipt)
except Exception as error:
evidence = _failure_evidence(service, journal, run_id, baseline)
failure = {**evidence, **receipt, 'status': 'interrupted', 'code': 'receipt_write_error',
'reporting_errors': [*receipt['reporting_errors'],
{'code': 'receipt_write_error', 'error': type(error).__name__}]}
if not receipt['tasks'] and 'tasks' in evidence:
failure['tasks'] = evidence['tasks']
journal.finish(run_id, failure)
raise
def _finish_failed_schedule(schedules, journal, original):
# The lease and both identities remain mandatory even on error paths.
_bound_schedule(schedules, original)
receipt = (journal.get(original['run_id']) or {}).get('result') or {}
failure = {**receipt, 'status': 'interrupted', 'run_id': original['run_id'],
'queue_id': original['queue_id'], 'code': receipt.get('code', 'execution_interrupted')}
schedules.finish(original['schedule_id'], 'interrupted', repair_run_id=original['run_id'],
run_id=original['run_id'], receipt=failure)
def _bound_schedule(schedules, run):
row = schedules.get(run['schedule_id'])
if (not row or row['run_id'] != run['run_id'] or row['task_ids'] != run['task_ids']
@@ -164,13 +192,17 @@ def execute_incident_retry(service, root, task_id, run_id, *, expected_item, sto
if original and original['schedule_id']:
schedules = ScheduleStore(root)
with schedules.execution_lease(original['schedule_id']):
_bound_schedule(schedules, original)
result = _execute_incident_retry(service, root, task_id, run_id,
expected_item=expected_item, stop_event=stop_event, operation_keys=operation_keys)
receipt = RunJournal(root).get(run_id)['result']
schedules.finish(original['schedule_id'], 'interrupted' if receipt['status'] in {'paused', 'blocked'} else receipt['status'],
repair_run_id=run_id, run_id=run_id, receipt=receipt)
return result
try:
_bound_schedule(schedules, original)
result = _execute_incident_retry(service, root, task_id, run_id,
expected_item=expected_item, stop_event=stop_event, operation_keys=operation_keys)
receipt = RunJournal(root).get(run_id)['result']
schedules.finish(original['schedule_id'], 'interrupted' if receipt['status'] in {'paused', 'blocked'} else receipt['status'],
repair_run_id=run_id, run_id=run_id, receipt=receipt)
return result
except Exception:
_finish_failed_schedule(schedules, RunJournal(root), original)
raise
return _execute_incident_retry(service, root, task_id, run_id,
expected_item=expected_item, stop_event=stop_event, operation_keys=operation_keys)
@@ -198,67 +230,88 @@ def _execute_incident_retry(service, root, task_id, run_id, *, expected_item, st
if (checkpoint.get('task_ids') != original['task_ids'] or checkpoint.get('plan_hashes') != original['plan_hashes']
or set(checkpoint['entries']) != set(original['task_ids'])):
raise TaskCenterError('run_scope', '原队列检查点身份或范围已变化;不执行重试。')
journal.begin_retry(service, run_id, task_id, operation_keys)
checkpoint['entries'][task_id].update(state='running', message='仅执行已预约的原失败项重试。')
_save(path, checkpoint)
token = original['run_id'] if original else sha256(str(run_id).encode('utf-8')).hexdigest()[:32]
with NetlistVerification(root, token, stop_event) as checks:
# Never capture a partially replaced project as a new "before".
checks.before_task(child, task_id, existing_only=True)
outcome = service.execute_quick_run_queue(task_id, expected_item=expected_item, stop_event=stop_event)
current = service.task_context(task_id)
p = current.progress
complete = p.queue_complete and not p.failed_items and not current.interrupted and not outcome.paused
summary = {key: getattr(p, key, 0) for key in ('saved_items', 'failed_items', 'no_match_items')}
if p.saved_items or 'rules' in checks.tasks.get(task_id, {}).get('plan', {}):
checks.after_task(task_id, execution_state='completed' if complete else 'failed',
execution_summary=summary, refresh=True)
reports = checks.finish()
if not p.saved_items:
reports = {key: report for key, report in reports.items() if report['status'] == 'not_required'}
if p.saved_items and task_id not in reports:
directory = root / 'tasks' / task_id / 'netlist-checks' / token
reports[task_id] = {'status': 'unavailable', 'verified': False,
'reason': '原授权执行缺少完整替换前基准,不能事后补造或仅凭保存计数宣称验收通过。',
'report_path': str(directory / 'verification.json')}
write_record(directory / 'verification.json', reports[task_id])
acceptance = verification_summary(reports, required_task_ids=(task_id,) if p.saved_items else ())
verification = {'queue_complete': p.queue_complete, 'failed_items': p.failed_items,
'saved_items': p.saved_items, 'completed_items': p.completed_items,
'interrupted': current.interrupted, 'paused': outcome.paused,
'acceptance': acceptance, 'netlist_verification': reports, 'run_receipt_updated': False}
if original:
# Preserve every other entry/report. This does not resume the parent
# queue or dispatch any other engineering task.
prior = original.get('result') or {}
entries = {row['task_id']: dict(row) for row in prior.get('entries', ())}
if set(entries) != set(original['task_ids']):
raise TaskCenterError('run_scope', '原执行回执范围不完整,保留本次真实结果等待核验。')
state = 'blocked' if current.interrupted else 'paused' if outcome.paused else 'completed' if complete else 'failed'
message = 'DSH 已按原失败项范围重试;保存结果与独立验收分别记录。'
entries[task_id].update(state=state, message=message)
merged = dict(prior.get('netlist_verification') or {})
merged.pop(task_id, None)
merged.update(reports)
candidates = [root / folder / (run_id + '.json') for folder in ('task-queues', 'workspace-queues')]
existing = [path for path in candidates if path.is_file()]
if len(existing) != 1:
raise TaskCenterError('run_scope', '原队列检查点缺失或有歧义;不接续其他任务。')
path = existing[0]
checkpoint = json.loads(path.read_text(encoding='utf-8'))
if (checkpoint.get('task_ids') != original['task_ids'] or checkpoint.get('plan_hashes') != original['plan_hashes']
or set(checkpoint['entries']) != set(original['task_ids'])):
raise TaskCenterError('run_scope', '原队列检查点身份或范围已变化;保留本次结果。')
checkpoint['entries'][task_id].update(state=state, message=message)
if path.parent.name == 'workspace-queues':
checkpoint['entries'][task_id].update(released=not bool(service.pending_batch_resources()), problems_done=True)
if reports:
checkpoint['entries'][task_id]['netlist_verification'] = reports[task_id]
elif reports:
checkpoint.setdefault('netlist_verification', {}).update(reports)
_save(path, checkpoint)
result = TaskQueueResult(original['queue_id'], tuple(TaskQueueEntry(**entries[key])
for key in original['task_ids']), outcome.paused, netlist_verification=merged)
receipt = _finish_execution_run(service, root, original['task_ids'], stop_event, run_id, result)
verification.update(run_receipt_updated=True, run_status=receipt['status'])
return outcome, current, verification
retry_run = journal.begin_retry(service, run_id, task_id, operation_keys)
baseline = (retry_run.get('result') or {}) if original else {}
try:
if original:
checkpoint['entries'][task_id].update(state='running', message='仅执行已预约的原失败项重试。')
_save(path, checkpoint)
token = original['run_id'] if original else sha256(str(run_id).encode('utf-8')).hexdigest()[:32]
with NetlistVerification(root, token, stop_event) as checks:
# Never capture a partially replaced project as a new "before".
checks.before_task(child, task_id, existing_only=True)
outcome = service.execute_quick_run_queue(task_id, expected_item=expected_item, stop_event=stop_event)
current = service.task_context(task_id)
p = current.progress
complete = p.queue_complete and not p.failed_items and not current.interrupted and not outcome.paused
summary = {key: getattr(p, key, 0) for key in ('saved_items', 'failed_items', 'no_match_items')}
if p.saved_items or 'rules' in checks.tasks.get(task_id, {}).get('plan', {}):
checks.after_task(task_id, execution_state='completed' if complete else 'failed',
execution_summary=summary, refresh=True)
reports = checks.finish()
if not p.saved_items:
reports = {key: report for key, report in reports.items() if report['status'] == 'not_required'}
if p.saved_items and task_id not in reports:
directory = root / 'tasks' / task_id / 'netlist-checks' / token
reports[task_id] = {'status': 'unavailable', 'verified': False,
'reason': '原授权执行缺少完整替换前基准,不能事后补造或仅凭保存计数宣称验收通过。',
'report_path': str(directory / 'verification.json')}
write_record(directory / 'verification.json', reports[task_id])
acceptance = verification_summary(reports, required_task_ids=(task_id,) if p.saved_items else ())
verification = {'queue_complete': p.queue_complete, 'failed_items': p.failed_items,
'saved_items': p.saved_items, 'completed_items': p.completed_items,
'interrupted': current.interrupted, 'paused': outcome.paused,
'acceptance': acceptance, 'netlist_verification': reports, 'run_receipt_updated': False}
if original:
# Preserve every other entry/report. This does not resume the parent
# queue or dispatch any other engineering task.
prior = original.get('result') or {}
entries = {row['task_id']: dict(row) for row in prior.get('entries', ())}
if set(entries) != set(original['task_ids']):
raise TaskCenterError('run_scope', '原执行回执范围不完整,保留本次真实结果等待核验。')
state = 'blocked' if current.interrupted else 'paused' if outcome.paused else 'completed' if complete else 'failed'
message = 'DSH 已按原失败项范围重试;保存结果与独立验收分别记录。'
entries[task_id].update(state=state, message=message)
merged = dict(prior.get('netlist_verification') or {})
merged.pop(task_id, None)
merged.update(reports)
candidates = [root / folder / (run_id + '.json') for folder in ('task-queues', 'workspace-queues')]
existing = [path for path in candidates if path.is_file()]
if len(existing) != 1:
raise TaskCenterError('run_scope', '原队列检查点缺失或有歧义;不接续其他任务。')
path = existing[0]
checkpoint = json.loads(path.read_text(encoding='utf-8'))
if (checkpoint.get('task_ids') != original['task_ids'] or checkpoint.get('plan_hashes') != original['plan_hashes']
or set(checkpoint['entries']) != set(original['task_ids'])):
raise TaskCenterError('run_scope', '原队列检查点身份或范围已变化;保留本次结果。')
checkpoint['entries'][task_id].update(state=state, message=message)
if path.parent.name == 'workspace-queues':
checkpoint['entries'][task_id].update(released=not bool(service.pending_batch_resources()), problems_done=True)
if reports:
checkpoint['entries'][task_id]['netlist_verification'] = reports[task_id]
elif reports:
checkpoint.setdefault('netlist_verification', {}).update(reports)
_save(path, checkpoint)
result = TaskQueueResult(original['queue_id'], tuple(TaskQueueEntry(**entries[key])
for key in original['task_ids']), outcome.paused, netlist_verification=merged)
receipt = _finish_execution_run(service, root, original['task_ids'], stop_event, run_id, result,
baseline=baseline)
verification.update(run_receipt_updated=True, run_status=receipt['status'])
return outcome, current, verification
except Exception as error:
if original and journal.get(run_id)['status'] == 'running':
failure = {**_failure_evidence(service, journal, run_id, baseline),
'status': 'interrupted', 'run_id': run_id, 'queue_id': original['queue_id'],
'code': getattr(error, 'code', 'execution_interrupted'),
'message': '原失败项重试未完成;保留已保存证据,按原范围核验后接续。'}
try:
observed = service.task_context(task_id)
# A raw readback must not replace the baseline after a scope/proof failure.
failure['retry_observation'] = dict(task_id=task_id, interrupted=observed.interrupted,
**{key: getattr(observed.progress, key) for key in
('saved_items', 'failed_items', 'no_match_items', 'queue_complete')})
except Exception as readback_error:
failure['reporting_errors'] = [{'code': 'context_unavailable',
'error': type(readback_error).__name__}]
journal.finish(run_id, failure)
raise
+9 -5
View File
@@ -98,8 +98,9 @@ class RunJournal:
started = _now()
db.execute("INSERT INTO run_journal VALUES (?, ?, ?, ?, ?, ?, ?, NULL, NULL)",
(run_id, run_id, json.dumps(ids), json.dumps(hashes, sort_keys=True), schedule_id, "running", started))
current = self._row(db.execute("SELECT * FROM run_journal WHERE run_id = ?", (run_id,)).fetchone())
db.execute("COMMIT")
return self.get(run_id)
return current
def finish(self, run_id, result):
if not isinstance(run_id, str) or not _ID.fullmatch(run_id):
@@ -123,21 +124,23 @@ class RunJournal:
(run_id, stamp, status, payload))
db.execute("UPDATE run_journal SET status = ?, finished_utc = ?, result = ? WHERE run_id = ?",
(status, stamp, payload, run_id))
current = self._row(db.execute("SELECT * FROM run_journal WHERE run_id = ?", (run_id,)).fetchone())
db.execute("COMMIT")
return self.get(run_id)
return current
def resume(self, run_id):
"""Mark a natively reconfirmed continuation; keep its last durable receipt."""
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT status FROM run_journal WHERE run_id = ?", (run_id,)).fetchone()
row = self._row(db.execute("SELECT * FROM run_journal WHERE run_id = ?", (run_id,)).fetchone())
if row is None:
raise TaskCenterError("run_missing", "run does not exist")
if row["status"] not in {"running", "paused", "blocked", "interrupted"}:
raise TaskCenterError("run_terminal", "this run has no resumable execution")
db.execute("UPDATE run_journal SET status = 'running', finished_utc = NULL WHERE run_id = ?", (run_id,))
row.update(status='running', finished_utc=None)
db.execute("COMMIT")
return self.get(run_id)
return row
def begin_retry(self, service, run_id, task_id, operation_keys):
"""Persist one reserved retry baseline before its first CAD dispatch."""
@@ -181,8 +184,9 @@ class RunJournal:
db.execute('INSERT INTO run_journal_receipts (run_id,finished_utc,status,result) VALUES (?,?,?,?)',
(run_id, stamp, 'running', payload))
db.execute("UPDATE run_journal SET status='running',finished_utc=NULL,result=? WHERE run_id=?", (payload, run_id))
row.update(status='running', finished_utc=None, result=value)
db.execute('COMMIT')
return self.get(run_id)
return row
@staticmethod
def _same_pending_retry(child, task_id, before, after):
@@ -1,6 +1,7 @@
"""One lazy private desktop/CAD owner per import or execution batch."""
from __future__ import annotations
from dataclasses import asdict
import hashlib
import json
from pathlib import Path
@@ -13,7 +14,7 @@ from .batch_resources import (BatchResourceCleanupError, LIVE_RESOURCES, cleanup
guard_pending_resources, pending_resources, process_identity, project_checkpoint_released, write_record)
from .errors import TaskCenterError
from .path_access import canonical_path, internal_path, legacy_path
from .isolated_desktop import PrivateDesktop
from .isolated_desktop import PrivateDesktop, ProcessNotStartedError
from .operation_control import check_cancelled
from .worker_monitor import WorkerMonitorError
@@ -408,12 +409,13 @@ class BatchCadRuntime:
'worker_closed': True, 'cad_pid': self.record['cad_pid'], 'cad_guid': self.record['cad_guid']})
self._active_attempts = []
def _pause_unlaunched_worker(self, root, project, command, attempt_id, expected, before, inputs):
"""Only the caller that has not invoked its process factory may certify this."""
def _certify_unlaunched_worker(self, root, project, command, attempt_id, expected, before, inputs, *, failure=None,
worker_creation_rejected=False):
"""Certify no worker was created, using exact launch and release provenance."""
from .batch_attempt import can_retry_attempt
from .discovery_cache import project_fingerprint
from .project_session_health import _source_parameters
self.close(reason='pause_before_worker_launch')
self.close(reason='failure_before_worker_launch' if failure is not None else 'pause_before_worker_launch')
absent = self.desktop is None and self.cad is None and self.generation == 0
if (not absent and (self.record['state'] != 'released' or not self.owned_processes_exited())
or before is None or before != project_fingerprint(project, self.root)
@@ -432,7 +434,13 @@ class BatchCadRuntime:
for name, key in (('command.tsv', 'command_sha256'), ('current-command.tsv', 'current_command_sha256'),
('status.tsv', 'status_sha256'), ('project-session.request', 'request_sha256')):
proof[key] = hashlib.sha256(inputs[name]).hexdigest() if inputs[name] is not None else None
proof_path = root / ('unlaunched-pause-' + attempt_id + '.json')
if failure is not None:
if worker_creation_rejected:
proof.update(worker_launch_attempted=True, worker_creation_rejected=True)
proof['journal_attempt'] = asdict(self._journal_attempt)
proof['failure'] = {'type': type(failure).__name__, 'module': type(failure).__module__,
'message': str(failure), **{key: getattr(failure, key, None) for key in ('code', 'error_id', 'errno', 'winerror')}}
proof_path = root / (('unlaunched-failure-' if failure is not None else 'unlaunched-pause-') + attempt_id + '.json')
write_record(proof_path, proof)
proof['files'] = [{'path': str(path), 'sha256': hashlib.sha256(internal_path(path).read_bytes()).hexdigest()}
for path in (proof_path, *(path for path, record in expected))]
@@ -484,6 +492,7 @@ class BatchCadRuntime:
started = time.monotonic()
failure = None
worker_launch_attempted = False
worker_creation_rejected = False
try:
check_cancelled(abort_event or self.stop_event)
self._ensure_desktop(abort_event)
@@ -494,9 +503,13 @@ class BatchCadRuntime:
environment = {'DXPART_ATTEMPT_FILE': str(directory), 'DXPART_ATTEMPT_ID': attempt_id,
'DXPART_BATCH_SESSION_ID': self.session_id, 'DXPART_BATCH_GENERATION': str(self.generation)}
def start_worker(launch, **options):
nonlocal worker_launch_attempted
nonlocal worker_launch_attempted, worker_creation_rejected
worker_launch_attempted = True
return cad.start_worker(launch, job_id=command[-1], extra_environment=environment, **options)
try:
return cad.start_worker(launch, job_id=command[-1], extra_environment=environment, **options)
except ProcessNotStartedError:
worker_creation_rejected = True
raise
result = run_monitored_process(command, timeout, abort_event=abort_event,
cooperative_abort=cooperative_abort, process_factory=start_worker,
**({'owner_loss_path': self.path.parent / 'owner-loss.json'} if self.read_only else {}),
@@ -546,10 +559,32 @@ class BatchCadRuntime:
except TaskCenterError as error:
if (error.code == 'operation_cancelled' and not self.read_only and not worker_launch_attempted
and not getattr(getattr(self.stop_event, 'force_event', None), 'is_set', lambda: False)()):
error.unlaunched_worker_pause = self._pause_unlaunched_worker(
error.unlaunched_worker_pause = self._certify_unlaunched_worker(
root, project, command, attempt_id, expected, before, inputs)
raise
except (PrivateCadStartupError, WorkerMonitorError, subprocess.TimeoutExpired, OSError) as error:
logical = getattr(self, '_journal_attempt', None)
bound = (logical is not None and logical.task_id == self.record['active_task']
and logical.job_id == command[-1] and not self.read_only)
from .worker_monitor import WorkerMonitorSafeTimeout
if (bound and worker_launch_attempted and not worker_creation_rejected and not (isinstance(error, WorkerMonitorSafeTimeout)
and error.prewrite_cleanup_confirmed and error.stage == 'open_project')):
from .quick_run import _write_uncertain_flag
_write_uncertain_flag(root / 'uncertain.flag', 'worker_launch_failure_requires_verification')
raise
if (bound and (not worker_launch_attempted or worker_creation_rejected) and not is_identity_conflict(error)
and not (abort_event is not None and abort_event.is_set())
and not (self.stop_event is not None and self.stop_event.is_set())):
try:
proof = self._certify_unlaunched_worker(root, project, command, attempt_id, expected,
before, inputs, failure=error, worker_creation_rejected=worker_creation_rejected)
except Exception:
from .quick_run import _write_uncertain_flag
_write_uncertain_flag(root / 'uncertain.flag', 'unproven_unlaunched_failure')
raise
result = subprocess.CompletedProcess(command, 2, '', str(error))
result.unlaunched_worker_failure, result.startup_error = proof, error
return result
failure = error
finally:
self._timing('project_worker', started, project=str(project), attempt_id=attempt_id,
@@ -27,6 +27,8 @@ class BomRowResult:
source_file: str = ''
source_row: int | None = None
duplicate_rows: tuple[int, ...] = ()
origin_code: str = ''
error_id: str = ''
@dataclass(frozen=True)
@@ -336,10 +338,11 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
raise
reason = f'工程采集失败:{error.message}(错误编号:{error.error_id})'
for index in indices:
rows[index] = replace(rows[index], status='failed', reason=reason)
# Native reads own no CAD session; explicit legacy runtimes
# still require positive session-release evidence.
if task_scope or runtime is None or isinstance(error, ReleasedProjectReadError):
rows[index] = replace(rows[index], status='failed', reason=reason,
origin_code=error.code, error_id=error.error_id)
from .execution_problems import classify_execution_failure
safe_read = classify_execution_failure(error.code, 'failed', phase='read')['continue_allowed']
if safe_read and (task_scope or isinstance(error, ReleasedProjectReadError)):
progress(f'「{task.name}」采集失败,已记录;继续核验其他工程')
continue
for index, row in enumerate(rows):
@@ -6,7 +6,7 @@ from tempfile import TemporaryDirectory
from uuid import uuid4
from .bom_batch import _scope, _assert_editable
from .bom_import_report import inspect_batch
from .bom_import_report import BomInspectionError, inspect_batch
from .bom_plan import BomRecord, read_bom_records, write_bom_template
from .errors import TaskCenterError
from .operation_control import check_cancelled
@@ -97,7 +97,7 @@ def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=Non
normalized.unlink(missing_ok=True)
failed_paths = {result.project_path for result in report.rows if result.status == 'failed'}
annotated = []
for result, source in zip(report.rows, rows):
for result, source in zip(report.rows, rows, strict=True):
reason = result.reason
if result.duplicate_rows:
locations = (f'{rows[number - 2].source.name} 第 {rows[number - 2].excel_row} 行'
@@ -108,14 +108,14 @@ def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=Non
annotated.append(replace(result, source_file=str(source.source), source_row=source.excel_row, reason=reason))
report = replace(report, rows=tuple(annotated), source_map_path=mapping)
if report.deferred:
accepted_sources = tuple(source for result, source in zip(report.rows, rows)
accepted_sources = tuple(source for result, source in zip(report.rows, rows, strict=True)
if result.project_path not in failed_paths)
with TemporaryDirectory(prefix='dx-bom-validate-') as directory:
accepted = write_routed_bom(Path(directory) / 'accepted.xlsx', accepted_sources, routes, project_names=names)
records = read_bom_records(accepted)
by_path = {str(project.path.resolve()).casefold(): task.task_id for task, project in scope}
grouped = {}
for record, source in zip(records, accepted_sources):
for record, source in zip(records, accepted_sources, strict=True):
owner = by_path[str(Path(record.project_path).resolve()).casefold()]
grouped.setdefault(owner, []).append(PendingBomRequest(record, str(source.source),
source.excel_row, source.source_sha256))
@@ -137,15 +137,25 @@ def resolve_pending(service, task_id, *, stop_event=None, on_progress=None, runt
check_cancelled(stop_event)
with TemporaryDirectory(prefix='dx-bom-resolve-') as directory:
path = write_bom_template(Path(directory) / 'bom.xlsx', tuple(_template_record(item.record) for item in pending))
report = inspect_batch(service, task_id, path, stop_event=stop_event, on_progress=on_progress,
runtime=runtime, task_scope=True, force_inventory=True)
failure = None
try:
report = inspect_batch(service, task_id, path, stop_event=stop_event, on_progress=on_progress,
runtime=runtime, task_scope=True, force_inventory=True)
except BomInspectionError as error:
report, failure = error.bom_report, error
report = replace(report, rows=tuple(replace(row, source_file=request.source_file,
source_row=request.source_row,
reason=row.reason + f';来源:{request.source_file} 第 {request.source_row} 行')
for row, request in zip(report.rows, pending)))
for row, request in zip(report.rows, pending, strict=True)))
if failure is not None:
failure.bom_report = report
raise failure
if report.preview is None:
message = '\n'.join((*report.errors, *(row.reason for row in report.rows if row.status == 'failed')))
error = TaskCenterError('bom_resolution', message or 'BOM 工程位号核验未通过,待核验清单已保留')
origin = next((row for row in report.rows if row.origin_code), None)
error = TaskCenterError(origin.origin_code if origin else 'bom_resolution',
message or 'BOM 工程位号核验未通过,待核验清单已保留',
error_id=origin.error_id if origin else None)
error.bom_report = report
raise error
project = report.preview.projects[0]
@@ -269,8 +269,8 @@ class ExecutionJournal:
with self.store.transaction():
self.store._connection.execute('UPDATE execution_rounds SET pause_requested=1 WHERE task_id=?',(task_id,))
def pause_before_dispatch(self, attempt, row, proof):
"""Return only this certified unstarted claim to the original pending plan."""
def validate_before_dispatch(self, attempt, row, proof):
"""Validate the existing affirmative no-dispatch certificate."""
from .execution_proof import proof_intact
from .batch_attempt import can_retry_attempt
from .project_session_health import _source_digest
@@ -278,16 +278,26 @@ class ExecutionJournal:
from .project_session_health import _intact_certificate
if not _intact_certificate(proof):
raise TaskCenterError('quick_run_uncertain', '启动前暂停证书与当前回执不符。')
if proof.get('failure'):
from dataclasses import asdict
if proof.get('journal_attempt') != asdict(attempt):
raise TaskCenterError('quick_run_uncertain', '启动失败证书不属于当前执行声明。')
if (proof.get('task_id') != attempt.task_id or proof.get('job_id') != attempt.job_id
or canonical_path(proof.get('project_path', '')) != canonical_path(row['project_path'])
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 proof.get('phase') == 'before_worker_launch' and (
proof.get('worker_launch_attempted') is not False or proof.get('resources_released') is not True)
not (proof.get('worker_launch_attempted') is False or proof.get('failure')
and proof.get('worker_launch_attempted') is True and proof.get('worker_creation_rejected') is True)
or proof.get('resources_released') is not True)
or _source_digest(proof) != proof.get('source_sha256') or not proof.get('source_sha256')
or not proof.get('batch_attempts') or not all(can_retry_attempt(item['path'], item['expected'])
for item in proof['batch_attempts'])):
raise TaskCenterError('quick_run_uncertain', '暂停缺少完整的未派发与关闭证明。')
def pause_before_dispatch(self, attempt, row, proof):
"""Return only this certified unstarted claim to the original pending plan."""
self.validate_before_dispatch(attempt, row, proof)
with self.store.transaction():
current = self._round(attempt.task_id)
record = self.store._connection.execute('''SELECT * FROM execution_operations
@@ -11,13 +11,15 @@ TRANSIENT_CODES = frozenset({'cad_attachment_failed', 'worker_timeout_before_wri
'worker_error', 'worker_timeout', 'timeout', 'quick_run_failed', 'execution_failed', 'native_failed'})
DETERMINISTIC_CODES = frozenset({'target_identity', 'probe_baseline_missing', 'task_not_retryable',
'assistant_stale', 'target_cell', 'invalid_target', 'target_not_found'})
RESOURCE_UNCERTAIN_CODES = frozenset({'inventory_cleanup', 'quick_run_uncertain',
'project_session_cleanup', 'mentor_release_required', 'batch_resources_pending'})
def classify_execution_failure(code, state, *, certified=False, phase='unknown',
interrupted=False, authorized=False):
"""One policy; certified means identity-bound, intact no-write/release evidence."""
code, state = str(code or '').casefold(), str(state or '').casefold()
if interrupted or state in {'uncertain', 'saved_unverified', 'prepared', 'batch_saved_unverified'} or (
if code in RESOURCE_UNCERTAIN_CODES or interrupted or state in {'uncertain', 'saved_unverified', 'prepared', 'batch_saved_unverified'} or (
phase in {'may_write', 'saved'} and not certified):
category = 'uncertain'
elif state == 'paused' or code in {'paused', 'user_pause'}:
@@ -27,6 +27,13 @@ DESKTOP_RELEASE_TIMEOUT_SECONDS = 5.0
DESCENDANT_EXIT_GRACE_SECONDS = 2.0
class ProcessNotStartedError(OSError):
"""CreateProcessW rejected the request without creating a process."""
def __init__(self, cause: OSError):
super().__init__(cause.errno, cause.strerror, cause.filename, cause.winerror)
def _native_handle(handle):
try:
return int(handle) if handle is not None else None
@@ -338,7 +345,8 @@ def _create_redirected_process(command, desktop, cwd, env, flags, stdout, stderr
if not create(str(command[0]), command_line, None, None, True,
flags | 0x80000 | 0x400, environment, str(cwd) if cwd else None,
ctypes.byref(startup), ctypes.byref(information)):
raise ctypes.WinError(ctypes.get_last_error())
error = ctypes.WinError(ctypes.get_last_error())
raise ProcessNotStartedError(error) from error
result = (pywintypes.HANDLE(information.hProcess), pywintypes.HANDLE(information.hThread),
information.dwProcessId, information.dwThreadId)
finally:
@@ -3,6 +3,7 @@ from __future__ import annotations
import hashlib
import json
from datetime import datetime, timezone
import os
from pathlib import Path
import re
@@ -17,6 +18,7 @@ from .path_access import canonical_path, internal_path, retry_sharing_violation
from .native_cli import OwnedCliScope
from .native_inventory_protocol import NativeInventoryUnsupported, read_ascii_discovery, read_native_text
from .operation_control import check_cancelled, report_progress
from .project_discovery import ReleasedProjectReadError
_NATIVE_CRASH_CODES = frozenset({0xC0000005, 0xC000001D, 0xC0000094,
@@ -88,7 +90,7 @@ class NativeInventoryReader:
text, block, snapshot, database = _project_options(project)
tools = self._tools()
except (NativeInventoryUnsupported, OSError, ImportError, UnicodeError, TaskCenterError) as error:
raise TaskCenterError('native_inventory', f'原生清单读取不可用:{str(error)[:160]}') from error
raise ReleasedProjectReadError('native_inventory', f'原生清单读取不可用:{str(error)[:160]}') from error
return self._read(project, text, block, snapshot, database, tools, old_part_numbers,
stop_event=stop_event, on_progress=on_progress)
@@ -102,7 +104,8 @@ class NativeInventoryReader:
workspace = Path(tempfile.mkdtemp(prefix='dx-cli-', dir=base)).resolve()
desktop = self.desktop_factory('dx-cli-' + token, enabled=True)
record = {'backend': 'native_cli', 'project': str(project), 'state': 'reading',
'workspace': str(workspace), 'tools': []}
'workspace': str(workspace), 'tools': [],
'started_utc': datetime.now(timezone.utc).isoformat()}
started = time.monotonic()
clean = False
result = None
@@ -159,7 +162,8 @@ class NativeInventoryReader:
check_cancelled(stop_event)
result = read_ascii_discovery(project, output / 'scope.txt', old_part_numbers,
expected_root=block, effective_report_path=output / 'effective.txt')
record.update(state='ready', components=len(result.components), source_hashes_unchanged=True)
record.update(state='ready', components=len(result.components), source_hashes_unchanged=True,
source_hashes={str(path): digest for path, digest in source_hashes.items()})
report_progress(on_progress, f'原生采集完成,已核对 {len(result.components)} 个目标位号及 UID。')
except (NativeInventoryUnsupported, OSError, UnicodeError) as error:
if record['state'] == 'uncertain':
@@ -168,7 +172,7 @@ class NativeInventoryReader:
record.update(source_hashes_unchanged=True,
source_hashes={str(path): digest for path, digest in source_hashes.items()})
record.update(state='failed', reason=str(error))
raise TaskCenterError('native_inventory', f'原生清单未能完整核对:{str(error)[:160]}') from error
raise ReleasedProjectReadError('native_inventory', f'原生清单未能完整核对:{str(error)[:160]}') from error
except TaskCenterError as error:
if record['state'] == 'uncertain':
try:
@@ -179,19 +183,27 @@ class NativeInventoryReader:
record.update(state='cancelled' if error.code == 'operation_cancelled' else 'failed', reason=error.message)
raise
finally:
primary_error = sys.exception()
record.update(seconds=time.monotonic() - started,
finished_utc=datetime.now(timezone.utc).isoformat(),
cleanup=getattr(desktop, 'cleanup_record', None))
# All diagnostics happen after process/desktop cleanup, never in
# between an exit request and the wait that confirms it.
try:
if (workspace / 'output').is_dir():
shutil.copytree(workspace / 'output', evidence / 'output')
finally:
if clean or not record['tools'] and record['state'] != 'uncertain':
if workspace.parent == base and workspace.resolve() == workspace:
shutil.rmtree(workspace)
(evidence / 'native-inventory.json').write_text(
json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
try:
if (workspace / 'output').is_dir():
shutil.copytree(workspace / 'output', evidence / 'output')
finally:
if clean or not record['tools'] and record['state'] != 'uncertain':
if workspace.parent == base and workspace.resolve() == workspace:
shutil.rmtree(workspace)
(evidence / 'native-inventory.json').write_text(
json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
except Exception as diagnostic_error:
if primary_error is None:
raise
primary_error.diagnostic_error = diagnostic_error
primary_error.add_note('Native inventory diagnostics failed: ' + str(diagnostic_error))
return result
def _run_tool(self, desktop, command, workspace, environment, output, record, stop_event):
@@ -9,6 +9,14 @@ from uuid import uuid4
from . import native_netlist
from .batch_resources import write_record
from .path_access import canonical_path
def _single_project(child, task_id):
projects = tuple(child.projects(task_id))
if len(projects) != 1:
raise ValueError('独立网表比对仅支持唯一单工程任务')
return canonical_path(projects[0].path)
def _export_saved_capture(capture, directory, *, stop_event):
@@ -223,15 +231,23 @@ class NetlistVerification:
'rule_mode': bool(rules)}
self.tasks[task_id] = record
try:
project = _single_project(child, task_id)
record['project_path'] = str(project)
record['scope_verified'] = True
before = directory / 'before'
manifest = before / 'capture.json'
plan_path = directory / 'plan.json'
if manifest.is_file() and not plan_path.is_file():
raise ValueError('原始网表基准缺少替换前冻结的计划,不能事后补造')
if manifest.exists() or plan_path.exists():
record['scope_verified'] = False
if not manifest.is_file() or not plan_path.is_file():
raise ValueError('原始网表基准缺少配套快照或冻结计划,不能事后补造')
# Resume always retains the original baseline, including a partially
# replaced project; never relabel the resumed input as "before".
capture = (json.loads(manifest.read_text(encoding='utf-8')) if manifest.is_file() else
native_netlist.capture_project(child.projects(task_id)[0].path, before))
native_netlist.capture_project(project, before))
if canonical_path(capture['project']) != project:
record['scope_verified'] = False
raise ValueError('原始网表基准不属于当前单工程任务')
if plan_path.is_file():
plan = json.loads(plan_path.read_text(encoding='utf-8'))
else:
@@ -247,9 +263,10 @@ class NetlistVerification:
'target_cell': rule.target_cell}))
plan.update(rules=frozen, project_path=capture['project'])
write_record(plan_path, plan)
record.update(plan=plan, before_capture=capture)
record.update(plan=plan, plan_sha256=native_netlist._hash(plan_path), before_capture=capture,
before_export=directory / 'before-export', scope_verified=True)
record['before'] = self.pool.submit(_export_saved_capture, capture,
directory / 'before-export', stop_event=self.stop)
record['before_export'], stop_event=self.stop)
except Exception as error:
record.update(status='unavailable', reason=str(error))
@@ -259,7 +276,15 @@ class NetlistVerification:
return
record['execution_state'] = execution_state
record['execution_summary'] = execution_summary or {}
if ((record.get('rule_mode') or 'rules' in record.get('plan', {}))
if not record.get('scope_verified'):
return
try:
if _single_project(record['child'], task_id) != canonical_path(record['project_path']):
raise ValueError('单工程任务的工程身份已变化')
except Exception as error:
record.update(status='unavailable', scope_verified=False, reason=str(error))
return
if (execution_state == 'completed' and (record.get('rule_mode') or 'rules' in record.get('plan', {}))
and record['execution_summary'].get('saved_items') == 0):
record['status'] = 'not_required'
return
@@ -274,8 +299,9 @@ class NetlistVerification:
capture = native_netlist.capture_project(Path(record['before_capture']['project']),
directory / ('after-' + attempt))
record['after_capture'] = capture
record['after_export'] = directory / ('after-export-' + attempt)
record['after'] = self.pool.submit(_export_saved_capture, capture,
directory / ('after-export-' + attempt), stop_event=self.stop)
record['after_export'], stop_event=self.stop)
except Exception as error:
record.update(status='unavailable', reason=str(error))
@@ -327,7 +353,9 @@ class NetlistVerification:
for task_id, record in self.tasks.items():
if task_id in self.results:
continue
result = {'status': record['status'], 'verified': False,
result = {'schema_version': 1, 'run_id': self.run_id, 'task_id': task_id,
'project_path': record.get('project_path'), 'plan_sha256': record.get('plan_sha256'),
'status': record['status'], 'verified': False,
'report_path': str(record['directory'] / 'verification.json')}
if record['status'] == 'not_required':
result['execution'] = dict(record.get('execution_summary', {}), state=record.get('execution_state'))
@@ -341,7 +369,9 @@ class NetlistVerification:
after = record['after'].result() if 'after' in record else None
if record.get('reason'):
result['reason'] = record['reason']
elif self.stop.is_set():
elif (any(export and export.get('status') == 'cancelled' for export in (before, after))
or (self.stop.is_set() and not all(export and export.get('status') == 'success'
and export.get('complete') is True for export in (before, after)))):
result.update(status='cancelled', reason='任务已暂停或取消;未宣称网表比对通过')
elif before is None or after is None:
result.update(status='not_completed', reason='工程尚未完整执行;保留替换前基准')
@@ -366,8 +396,18 @@ class NetlistVerification:
result.update(status='not_replaced', verified=False, graph_comparison=comparison,
reason='存在未命中项;网表一致不代表已执行替换')
result['execution'] = dict(record.get('execution_summary', {}), state=record.get('execution_state'))
result['before'] = before and {key: before.get(key) for key in ('status', 'complete', 'outputs', 'reason')}
result['after'] = after and {key: after.get(key) for key in ('status', 'complete', 'outputs', 'reason')}
for phase, export in (('before', before), ('after', after)):
evidence = export and {key: export.get(key) for key in ('status', 'complete', 'outputs', 'reason')}
if evidence:
capture = record[phase + '_capture']
evidence.update(source_hashes=capture.get('source_hashes', {}),
capture_hashes=capture.get('capture_hashes', {}))
manifest = record[phase + '_export'] / 'netlist.json'
if manifest.is_file():
evidence.update(export_path=str(manifest), export_sha256=native_netlist._hash(manifest))
evidence['output_hashes'] = {name: native_netlist._hash(Path(path))
for name, path in export.get('outputs', {}).items() if Path(path).is_file()}
result[phase] = evidence
except Exception as error:
result.update(status='unavailable', reason=str(error))
write_record(Path(result['report_path']), result)
@@ -16,7 +16,7 @@ from .operation_control import check_cancelled, report_progress
class ReleasedProjectReadError(TaskCenterError):
"""Project read failed, with positive evidence that its CAD session released."""
"""Project read failed before launch or after its owned processes released."""
def _read_failure(root, message):
@@ -503,6 +503,8 @@ class QuickRunPreparer:
row = (batch_session.journal_rows if batch_session is not None else journal_rows)[selected_command[1]]
self.write_expected_baselines(task_id,handoff.command_path.parent,selected_command[2])
journal_attempt = journal.claim(task_id, row)
if self._process_runner is _run_process and runtime is not None:
runtime._journal_attempt = journal_attempt
if self._process_runner is not _run_process:
from .discovery_cache import project_fingerprint
dispatch_fingerprint = project_fingerprint(Path(selected_command[2]), self._data_root)
@@ -667,11 +669,33 @@ class QuickRunPreparer:
if completed.returncode == 2 and after == before:
_append_log(handoff.log_path, "quick_run_attach_failure exit_code=2")
detail = completed.stderr.strip() or completed.stdout.strip() or "DxDesigner attachment failed"
unlaunched = getattr(completed, 'unlaunched_worker_failure', None)
if unlaunched is not None:
try:
if (runtime is None or journal_attempt is None
or unlaunched.get('phase') != 'before_worker_launch'
or not unlaunched.get('failure')
or unlaunched.get('session_id') != runtime.session_id
or unlaunched.get('generation') != runtime.generation
or unlaunched.get('attempt_id') != runtime.record.get('active_attempt')
or unlaunched.get('resource_record') != str(runtime.path)):
raise ValueError('unlaunched failure is not bound to the active runtime')
journal.validate_before_dispatch(journal_attempt, row, unlaunched)
for name, key in (('command.tsv', 'command_sha256'), ('current-command.tsv', 'current_command_sha256'),
('status.tsv', 'status_sha256'), ('project-session.request', 'request_sha256')):
path = _io_path(handoff.command_path.parent / name)
digest = hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else None
if digest != unlaunched.get(key):
raise ValueError('unlaunched failure inputs changed')
except Exception as proof_error:
_write_uncertain_flag(uncertain_path, 'unproven_unlaunched_failure')
raise TaskCenterError('quick_run_uncertain', '启动失败缺少完整的未派发与释放证明;保留保护并核验。') from proof_error
if journal_attempt is not None:
self._record_rejected_attempt(journal_attempt, handoff, selected_command, before,
projects, detail, code='cad_attachment_failed', row=row,
source_before=dispatch_fingerprint, runtime=runtime)
raise TaskCenterError("quick_run_session", _session_failure_message(detail))
source_before=dispatch_fingerprint, runtime=runtime,
unlaunched_proof=unlaunched)
raise TaskCenterError("quick_run_session", _session_failure_message(detail)) from getattr(completed, 'startup_error', None)
if completed.returncode == 3:
if after == before:
_append_log(handoff.log_path, "quick_run_pre_mutation_failure exit_code=3")
@@ -836,7 +860,7 @@ class QuickRunPreparer:
def _record_rejected_attempt(self, attempt, handoff, command, before, projects, message, *, code='pre_mutation_rejected',
row=None, source_before=None, runtime=None, dispatch_not_started=False,
synchronous_prewrite=False):
synchronous_prewrite=False, unlaunched_proof=None):
"""Known pre-mutation exit + unchanged status is a safe failure, not an unknown write."""
outcome=(command[1], BATCH_FAILED_STATE, code, message)
_write_status_details(handoff.status_path, (*before, outcome))
@@ -844,16 +868,22 @@ class QuickRunPreparer:
_read_commands(handoff.command_path), (*before,outcome), _read_command_sheet_targets(handoff.command_path))
try:
proof = None
if row is not None and (self._process_runner is not _run_process or dispatch_not_started or synchronous_prewrite):
if row is not None and (self._process_runner is not _run_process or dispatch_not_started or synchronous_prewrite or unlaunched_proof):
from .project_session_health import synchronous_completion
if dispatch_not_started:
if dispatch_not_started or unlaunched_proof:
from .discovery_cache import project_fingerprint
source_before = project_fingerprint(Path(command[2]), self._data_root)
if runtime is not None and runtime.cad is not None:
if unlaunched_proof and hashlib.sha256(repr(source_before).encode()).hexdigest() != unlaunched_proof['source_sha256']:
raise TaskCenterError('quick_run_uncertain', '未派发失败证书校验后工程源文件已变化,保留保护。')
if not unlaunched_proof and runtime is not None and runtime.cad is not None:
runtime.reset_project_after_safe_failure(Path(runtime.record['active_project']), runtime._active_evidence,
job_id=runtime.record.get('active_job'))
completion = synchronous_completion(self._data_root, row, attempt, outcome[1:], source_before, runtime=runtime)
completion = synchronous_completion(self._data_root, row, attempt, outcome[1:], source_before,
runtime=None if unlaunched_proof else runtime)
proof = {'files': completion['files'], 'failure_health': completion}
if unlaunched_proof:
proof['files'].extend(unlaunched_proof['files'])
proof['unlaunched_worker_failure'] = unlaunched_proof
elif row is not None and runtime is not None:
from .project_session_health import runtime_dispatch_binding
binding = runtime_dispatch_binding(self._data_root, row, attempt, runtime)
@@ -207,13 +207,14 @@ class TaskCenterService:
def import_bom_drafts(self, task_id, sources, *, stop_event=None, on_progress=None, on_phase=None, allow_partial=False):
from .bom_pending import import_drafts
return self._operation('import_bom_drafts', task_id, lambda: import_drafts(self, task_id, sources,
stop_event=stop_event, on_progress=on_progress, on_phase=on_phase, allow_partial=allow_partial))
return self._idle_quick_run_operation('import_bom_drafts', task_id, lambda: import_drafts(self, task_id, sources,
stop_event=stop_event, on_progress=on_progress, on_phase=on_phase, allow_partial=allow_partial),
capture_history=False)
def resolve_pending_bom(self, task_id, *, stop_event=None, on_progress=None, runtime=None):
from .bom_pending import resolve_pending
return self._operation('resolve_pending_bom', task_id, lambda: resolve_pending(self, task_id,
stop_event=stop_event, on_progress=on_progress, runtime=runtime))
return self._idle_quick_run_operation('resolve_pending_bom', task_id, lambda: resolve_pending(self, task_id,
stop_event=stop_event, on_progress=on_progress, runtime=runtime), capture_history=False)
def preview_bom_sources(self, task_id: str, sources, *, stop_event=None, on_progress=None,
on_phase=None, runtime=None, allow_partial=False):
@@ -769,6 +769,27 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._set_operator_message('当前范围无法执行:' + ';'.join(reasons), 'warning')
return False
def _confirmed_execution_allowed(self, task_id, task_ids, button):
# Confirmation runs a nested event loop; admit the run only after it returns.
if (self._closed or self._close_pending or self._close_saving
or task_id != self._task_id or self._context is None
or self._context.task.task_id != task_id):
reason = '窗口正在关闭或当前任务已变化,请重新选择任务并确认。'
elif self._workers or self._batch_stop is not None or self._loading:
reason = '当前操作尚未结束,请等待安全收尾后重新确认。'
elif self.plan_panel.has_unsaved_plan(task_ids) or self.plan_panel._active_bom_batch():
reason = '计划有未保存编辑,请先保存或放弃编辑后重新确认。'
elif any(controller is not None and controller.dialog is not None for controller in
(self._dsh_task_creation, self._dsh_lifecycle, self._dsh_operations)):
reason = '任务操作窗口尚未结束,请关闭后重新确认。'
else:
self._update_gates()
if button.isEnabled():
return True
reason = '当前执行条件已变化,请核对任务和后台资源后重新确认。'
self._set_operator_message('未启动执行:' + reason, 'warning')
return False
def _prepare_quick_run(self):
if not self.run_panel.quick_run_button.isEnabled():
return
@@ -793,6 +814,9 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._dsh_confirmation_impact = report.get('impact', {})
if not self._quick_run_confirmer('current', 1, enabled):
return
if not self._confirmed_execution_allowed(context.task.task_id, (context.task.task_id,),
self.run_panel.quick_run_button):
return
self._dsh_authorized_tasks.add(context.task.task_id)
p = context.progress
expected = (str(p.next_project_path), p.next_old_part_number, p.next_new_part_number,
@@ -830,6 +854,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
def _execute_project_tasks(self):
if not self.task_list.queue_button.isEnabled():
return
owner_task_id = self._context.task.task_id
group = self._context.task.group_id
tasks = pending_batch_tasks(self._tasks, group)
if not tasks:
@@ -854,6 +879,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
enabled = report.get('impact', {}).get('enabled_scope', 0)
if not self._quick_run_confirmer('batch', len(ids), enabled):
return
if not self._confirmed_execution_allowed(owner_task_id, ids, self.task_list.queue_button):
return
self._dsh_authorized_tasks.update(ids)
self._begin_run(ids[0])
self._dsh_live_run['task_ids'] = list(ids)
@@ -158,6 +158,7 @@ class ProgressWatch:
if ((current_job, fields[4], done, total, bool(safe)) !=
(self.current_job_id, self.stage, self.done, self.total, self.safe_stop)):
self.last_business_progress = now
self.waiting_for_safe_completion = False
if current_job != self.current_job_id:
self.current_job_id = current_job
self.stage_seconds = {}
@@ -172,7 +173,6 @@ class ProgressWatch:
self.last_progress = now
self.stage, self.done, self.total, self.safe_stop = fields[4], done, total, bool(safe)
self.unsafe_seen = self.unsafe_seen or not bool(safe)
self.waiting_for_safe_completion = False
return True
def accept_native(self, line: bytes, now: float) -> bool:
@@ -201,6 +201,7 @@ class ProgressWatch:
self.last_progress = now
if (done, total) != (self.done, self.total):
self.last_business_progress = now
self.waiting_for_safe_completion = False
self.done, self.total = done, total
return True