merge(main): resolve PR19 review conflicts and run intervention regressions in CI
Core regression / Python core, intervention UI and release configuration (push) Failing after 2m42s
Core regression / JavaScript syntax (push) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) Canceled after 1m17s
Core regression / JavaScript syntax (pull_request) Canceled after 0s

This commit is contained in:
阿白叔 committed 2026-11-09 11:35:29 +08:00
commit f8f07d30d2
127 files changed
+9390 -386

No files matched your search

+1 -1
View File
@@ -81,7 +81,7 @@ 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
entries = [{'task_id': e.task_id, 'state': e.state, 'message': e.message} for e in result.entries]
status = ('blocked' if result.paused and any(e['state'] == 'blocked' for e in entries)
status = ('blocked' if any(e['state'] == 'blocked' for e in entries)
else 'paused' if result.paused else 'failed' if any(e['state'] == 'failed' for e in entries) else 'completed')
receipt = {'status': status, 'run_id': run_id, 'queue_id': result.queue_id, 'paused': result.paused,
'user_pause_requested': bool(stop.is_set()), 'awaiting_user_resume': bool(result.paused and stop.is_set()),
+18 -7
View File
@@ -222,7 +222,8 @@ class IncidentRunner:
record['task_name'] = snapshot.get('task_name', task_id)
budget_id = sha256(f'{task_id}:{run_id}'.encode()).hexdigest()[:24]
budget_path = self.data_root / 'dsh' / 'retry-budget' / (budget_id + '.json')
budget_available = not budget_path.exists()
reserve_retry = getattr(self.service, 'reserve_problem_retry', None)
budget_available = reserve_retry is not None or not budget_path.exists()
snapshot['intervention'] = {'original_execution_authorized': bool(execution_authorized), 'retry_attempts': 0 if budget_available else 1,
'phase': getattr(context, 'phase', 'unknown'), 'interrupted': getattr(context, 'interrupted', True),
'known_retryable_error': issue_code in RETRYABLE_CODES,
@@ -251,6 +252,8 @@ class IncidentRunner:
write_json(evidence.directory / (phase + '.json'), failure)
evidence.event('analysis_unavailable', **failure)
return None
if cancel_event.is_set():
return cancelled()
suggestion = analyze('diagnose')
if cancel_event.is_set():
return cancelled()
@@ -351,12 +354,17 @@ class IncidentRunner:
raise ValueError('retry_gate_changed')
# Consume before entering a service mutation. A crash or changed error
# code must never buy another replay of the same authorized run.
budget_path.parent.mkdir(parents=True, exist_ok=True)
try:
with budget_path.open('x', encoding='utf8') as stream:
json.dump({'incident_id': incident_id, 'task_id': task_id, 'run_id': run_id, 'attempts': 1}, stream)
stream.flush()
os.fsync(stream.fileno())
if reserve_retry is not None:
reserved = reserve_retry(task_id, source='dsh')
if not reserved:
raise FileExistsError('retry_budget_spent')
else:
budget_path.parent.mkdir(parents=True, exist_ok=True)
with budget_path.open('x', encoding='utf8') as stream:
json.dump({'incident_id': incident_id, 'task_id': task_id, 'run_id': run_id, 'attempts': 1}, stream)
stream.flush()
os.fsync(stream.fileno())
except FileExistsError:
gates['retry_budget_available'] = False
write_json(evidence.directory / 'gates.json', gates)
@@ -367,7 +375,10 @@ class IncidentRunner:
if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()):
record['action'] = 'none'
raise ValueError('retry_gate_changed')
self.service.prepare_failed_quick_run(task_id)
if reserve_retry is not None:
self.service.prepare_failed_quick_run(task_id, operation_keys=reserved)
else:
self.service.prepare_failed_quick_run(task_id)
prepared = self.service.task_context(task_id)
p = prepared.progress
expected = (str(p.next_project_path), p.next_old_part_number, p.next_new_part_number,
+2 -1
View File
@@ -9,12 +9,13 @@ def resume_diff(service, inspected_run, *, current_plan_hashes=None):
current = {} if current_plan_hashes is None else dict(current_plan_hashes)
blockers = list(inspected_run.get('blockers') or [])
contexts = {}
isolated = set(inspected_run.get('isolated_task_ids') or ())
for task_id in ids:
try:
contexts[task_id] = service.task_context(task_id)
if current_plan_hashes is None:
current[task_id] = _plan_hash(service.for_project_task(task_id), task_id)
if contexts[task_id].interrupted:
if contexts[task_id].interrupted and task_id not in isolated:
blockers.append('interrupted')
except Exception:
blockers.append('task_unavailable')
+58 -6
View File
@@ -156,18 +156,34 @@ class RunJournal:
raise TaskCenterError("run_missing", "run does not exist")
blockers: list[str] = []
checkpoint = self.data_root / "task-queues" / f"{run_id}.json"
workspace_checkpoint = self.data_root / "workspace-queues" / f"{run_id}.json"
workspace = workspace_checkpoint.is_file()
conflicting = workspace and checkpoint.is_file()
if workspace:
checkpoint = workspace_checkpoint
queue = None
try:
queue = json.loads(checkpoint.read_text(encoding="utf-8"))
if conflicting:
raise ValueError('ambiguous checkpoint ownership')
if queue.get("version") != 1 or queue.get("task_ids") != row["task_ids"] or queue.get("plan_hashes") != row["plan_hashes"]:
raise ValueError
entries = queue["entries"]
if set(entries) != set(row["task_ids"]) or any(
not isinstance(entry, dict) or set(entry) != {"state", "message"} or
not isinstance(entry, dict) or (not {"state", "message", "released", "problems_done", "checkpoint_id"} <= set(entry)
or set(entry) - {"state", "message", "released", "problems_done", "checkpoint_id", "supervisor_batch_id"}
if workspace else set(entry) != {"state", "message"}) or
entry["state"] not in {"pending", "running", "paused", "blocked", "completed", "failed", "skipped"} or
not isinstance(entry["message"], str) for entry in entries.values()
):
raise ValueError
if workspace and (queue.get('phase') not in {'primary', 'problems', 'finished'} or any(
type(entry['released']) is not bool or type(entry['problems_done']) is not bool
or not isinstance(entry['checkpoint_id'], str) or not _ID.fullmatch(entry['checkpoint_id'])
or 'supervisor_batch_id' in entry and (not isinstance(entry['supervisor_batch_id'], str)
or not _ID.fullmatch(entry['supervisor_batch_id']))
for entry in entries.values())):
raise ValueError('invalid workspace checkpoint')
except (OSError, ValueError, TypeError, KeyError, json.JSONDecodeError):
queue = None
blockers.append("queue_missing" if not checkpoint.exists() else "queue_invalid")
@@ -175,10 +191,17 @@ class RunJournal:
tasks = []
has_evidence = False
current_hashes = {}
released_primary = {key for key, entry in (queue['entries'].items() if workspace and queue else ())
if entry['released'] and entry['state'] in {'completed', 'failed', 'skipped', 'blocked'}}
isolated = {key for key in released_primary if queue['entries'][key]['state'] == 'blocked'}
safe_continuations = set()
for task_id in row["task_ids"]:
item = {"task_id": task_id, "status": "unknown", "saved_items": 0, "failed_items": 0, "no_match_items": 0}
try:
context = service.task_context(task_id)
if (queue and queue['entries'][task_id]['state'] in {'paused', 'running'}
and not context.interrupted and service.independent_continuation_ready(task_id)):
safe_continuations.add(task_id)
has_evidence = has_evidence or context.has_evidence
progress = context.progress
item.update({"status": context.task.status.value, "interrupted": bool(context.interrupted),
@@ -189,9 +212,9 @@ class RunJournal:
for key in ("saved_items", "failed_items", "no_match_items"):
counters[key] += item[key]
counters["total"] += item["total_items"]
if context.interrupted:
if context.interrupted and task_id not in isolated:
blockers.append("interrupted")
if getattr(progress, "failed_items", 0):
if getattr(progress, "failed_items", 0) and task_id not in released_primary | safe_continuations:
blockers.append("failed_items")
if queue and queue['entries'][task_id]['state'] == 'completed' and not (
context.has_evidence and progress.queue_complete is True
@@ -208,21 +231,31 @@ class RunJournal:
if queue:
counters["completed"] = sum(queue["entries"][task_id]["state"] in {"completed", "failed", "skipped"} for task_id in row["task_ids"])
remaining = [task_id for task_id in row["task_ids"] if not queue or queue["entries"][task_id]["state"] not in {"completed", "failed", "skipped"}]
if workspace and queue:
primary_exhausted = all(entry['state'] in {'completed', 'failed', 'skipped', 'blocked'} for entry in queue['entries'].values())
remaining = [key for key in row['task_ids'] if key not in isolated and (
queue['entries'][key]['state'] not in {'completed', 'failed', 'skipped'} or
(queue['phase'] == 'problems' or queue['phase'] == 'primary' and primary_exhausted)
and not queue['entries'][key]['problems_done'])]
if "queue_missing" in blockers and not has_evidence:
# The receipt may have committed before the executor created its checkpoint.
# A native reconfirmation can safely create the original queue; no auto replay.
blockers.remove("queue_missing")
if remaining:
runnable_remaining = [key for key in remaining if key not in released_primary]
if runnable_remaining:
try:
from .task_lifecycle import preflight
if not preflight(service, remaining, allow_completed=True)["ready"]:
if not preflight(service, runnable_remaining, allow_completed=True)["ready"]:
blockers.append("preflight_blocked")
except Exception:
blockers.append("preflight_unavailable")
elif service.pending_batch_resources():
if service.pending_batch_resources():
blockers.append("resources_pending")
blockers = list(dict.fromkeys(blockers))
value = {**row, "queue_available": queue is not None, "tasks": tasks, "counters": counters,
'isolated_task_ids': [key for key in row['task_ids'] if key in isolated],
'released_primary_task_ids': [key for key in row['task_ids'] if key in released_primary],
'safe_continuation_task_ids': [key for key in row['task_ids'] if key in safe_continuations],
"checkpoint_states": {key: entry['state'] for key, entry in queue['entries'].items()} if queue else {},
"remaining_task_ids": remaining, "blockers": blockers, "resume_ready": not blockers,
"requires_confirmation": True,
@@ -233,3 +266,22 @@ class RunJournal:
value['blockers'] = value['diff']['blockers']
value['resume_ready'] = False
return value
def resume_preflight(service, inspected_run):
"""Retain the original scope while displaying tasks held out of this resume."""
from .task_lifecycle import preflight
if not inspected_run.get('resume_ready') or not inspected_run.get('diff', {}).get('safe'):
raise TaskCenterError('run_blocked', '原队列范围或证据尚未通过恢复准入。')
report = preflight(service, inspected_run['task_ids'], allow_completed=True)
if report['plan_hashes'] != inspected_run['plan_hashes']:
raise TaskCenterError('assistant_stale', '原执行计划已变化,请重新核对。')
held = set(inspected_run.get('released_primary_task_ids') or ())
isolated = set(inspected_run.get('isolated_task_ids') or ())
for task in report['tasks']:
if task['task_id'] in held:
task['blockers'] = []
task['isolated'] = task['task_id'] in isolated
report['ready'] = all(not task['blockers'] for task in report['tasks'])
report['resume_scope'] = list(inspected_run['remaining_task_ids'])
return report
@@ -164,6 +164,7 @@ def main(argv: Sequence[str] | None = None) -> int:
logging_context = configure_logging(data_root)
install_exception_hooks(logging_context)
store: TaskStore | None = None
window = None
try:
database_path = data_root / "task-center.db"
_log_startup(logging_context, data_root, database_path)
@@ -190,6 +191,11 @@ def main(argv: Sequence[str] | None = None) -> int:
# The window invalidates queued UI results on close. Finish the
# remaining read before releasing the shared SQLite connection.
QThreadPool.globalInstance().waitForDone()
for name in ('_dsh_status', '_dsh_operations', '_dsh_lifecycle', '_dsh_automation'):
controller = getattr(window, name, None)
pool = getattr(controller, '_read_pool', None) or getattr(controller, '_pool', None)
if pool is not None:
pool.waitForDone()
store.close()
+47 -2
View File
@@ -22,6 +22,7 @@ from .retention import maintain_quick_run_storage
from .schematic_backup import create_schematic_backup
from .execution_metrics import measure_phase
from .batch_backup import BatchBackupCoordinator, _write_backup_state
from .value_readback import value_readback_details
@dataclass(frozen=True)
@@ -46,7 +47,8 @@ def execute_batch(
) -> BatchRunResult:
preparer = service._quick_run_preparer
journal = getattr(preparer, 'journal', None)
if (journal is not None and journal.requires_retry(task_id)) or service._retryable_quick_run(task_id):
if ((journal is not None and journal.requires_retry(task_id)) or service._retryable_quick_run(task_id)) and not (
journal is not None and journal.has_pending_components(task_id)):
raise TaskCenterError('quick_run_retry_required', '本工程有失败项,普通继续不会重试;请准备失败项重试。')
retention = maintain_quick_run_storage(preparer.data_root)
if retention.removed_entries or retention.skipped_entries:
@@ -144,11 +146,35 @@ def execute_batch(
new_part_number=expected[2], job_id=session.commands[session.next_index][1]) as metric:
try:
last_result = preparer.execute_step(task_id, projects, rules, copy_part_number_to_value=task.copy_part_number_to_value,
expected_item=expected, batch_mode=True, batch_session=session,
expected_item=expected, batch_mode=True, batch_session=session, stop_event=stop_event,
**({'project_session': project_session} if project_session.enabled else {}),
**({'runtime': runtime} if runtime is not None else {}))
metric['state'] = last_result.state
metric['completed_units'] = int(last_result.state in {'saved_ok', 'restored_ok', 'no_match'})
except TaskCenterError as error:
current_row = session.journal_rows.get(metric['job_id'], {})
if error.code not in {'quick_run_session', 'target_cell_catalog'} or current_row.get('execution_unit') != 'component':
raise
# Only an already committed safe failure may be consumed here.
issues = service.execution_problems(task_id)
from .execution_journal import command_identity, _hash
key = _hash(command_identity(current_row))
if not any(issue['operation_key'] == key and issue['classification'] != 'uncertain' for issue in issues):
raise
candidate = preparer.progress(task_id, projects, rules,
copy_part_number_to_value=task.copy_part_number_to_value)
if candidate.queue_complete:
session.progress = candidate
else:
session = preparer.begin_batch_session(task_id, projects, rules,
copy_part_number_to_value=task.copy_part_number_to_value,
**({'runtime': runtime} if runtime is not None else {}))
candidate = session.progress
last_result = QuickRunStepResult(session.handoff.script_path, session.handoff.command_path,
session.handoff.status_path, session.handoff.log_path, BATCH_FAILED_STATE, error.message,
candidate.next_project_path, candidate.next_old_part_number, candidate.next_new_part_number,
candidate.next_schematic_name, candidate.next_sheet_number, candidate)
metric['state'] = BATCH_FAILED_STATE
finally:
worker_progress = session.handoff.command_path.parent / 'worker-progress.json'
try:
@@ -190,6 +216,7 @@ def execute_batch(
append_task_event(service._logging, level=event_level,
task_id=task_id, project_id=project_id, operation='quick_run_executed', message=last_result.message,
details={'state': last_result.state, 'continue_queue': not updated.queue_complete,
**value_readback_details(last_result),
'timing': metric,
'project_path': str(current),
'schematic_name': progress.next_schematic_name,
@@ -201,6 +228,24 @@ def execute_batch(
task_id, last_result.state, updated.completed_items, updated.total_items)
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
from .quick_run import _run_process
if journal is None:
raise TaskCenterError('quick_run_uncertain', '缺少失败回执及工程健康证明,暂缓剩余位号。')
if not journal.failure_certified(task_id, row):
if preparer._process_runner is not _run_process or runtime is None:
raise TaskCenterError('quick_run_uncertain', '失败后缺少明确的未写入与资源释放证明,暂缓剩余位号。')
health = runtime.reset_project_after_safe_failure(current,
session.handoff.command_path.parent, job_id=metric['job_id'])
journal.certify_safe_failure(task_id, row, health)
service._batch_feedback = (task_id, progress, '问题位号已记录,继续独立位号。')
continue
# execute_step has already rejected possible unverified native
# mutation. Leave this engineering task's remaining work held,
# but permit the outer serial queue to run the next project.
@@ -72,13 +72,59 @@ def pending_resources(root):
record = json.loads(internal_path(path).read_text(encoding='utf-8'))
if not _valid_record(record, path):
raise ValueError('invalid resource ownership record')
if record.get('state') != 'released':
if record.get('state') != 'released' or not _released_evidence(record):
pending.append(dict(record, record_path=str(path)))
except (OSError, ValueError, TypeError) as error:
pending.append({'state': 'blocked', 'record_path': str(path), 'error': str(error)})
import sys
sessions = getattr(sys.modules.get(__package__ + '.isolated_cad'), 'RETAINED_CAD_SESSIONS', {})
for session in sessions.values():
if session.root.is_relative_to(canonical_path(root)):
pending.append({'state': 'blocked', 'kind': 'retained_cad', 'cad_pid': session.cad.pid,
'desktop': session.desktop.name, 'record_path': str(session.root / 'private-desktop.json')})
workers = getattr(sys.modules.get(__package__ + '.worker_monitor'), 'RETAINED_WORKERS', {})
worker_paths = set()
for entry in tuple(workers.values()):
if entry['root'].is_relative_to(canonical_path(root)):
worker_paths.add(canonical_path(entry['path']))
pending.append({'state': 'blocked', 'kind': 'retained_worker',
'record_path': str(entry['path']), 'worker_pid': entry['process'].pid, 'force_available': True})
for path in internal_path(canonical_path(root)).rglob('retained-worker-*.json'):
if canonical_path(path) in worker_paths:
continue
try:
record = json.loads(path.read_text(encoding='utf-8'))
from .retained_worker_recovery import boot_release_proven
if (record.get('version') == 1 and record.get('state') == 'released'
and record.get('processes_exited') is True
and path.name == 'retained-worker-' + record.get('token', '') + '.json'
and ('release_proof' not in record or boot_release_proven(record, path))):
continue
except (OSError, ValueError, TypeError, AttributeError):
pass
# After restart there is no live Job handle to prove descendant exit.
from .retained_worker_recovery import RESTART_HINT
pending.append({'state': 'blocked', 'kind': 'retained_worker', 'record_path': str(canonical_path(path)),
'resolution_hint': RESTART_HINT, 'force_available': False})
return tuple(pending)
def _released_evidence(record):
"""A state label alone must never reopen the physical resource gate."""
proof = record.get('release_proof', {})
if (isinstance(proof, dict) and proof.get('generation') == record['generation']
and proof.get('desktop_released') is True and proof.get('processes_exited') is True):
return True
releases = record.get('generation_releases', ())
if not isinstance(releases, list) or not releases:
return False
last = releases[-1]
cleanup = last.get('cleanup') or {}
return (last.get('generation') == record['generation'] and last.get('desktop') == record['desktop']
and cleanup.get('desktop_handle_closed') is True and not cleanup.get('errors')
and (cleanup.get('desktop_confirmation') or {}).get('released') is True)
def guard_pending_resources(root):
if pending_resources(root):
raise BatchResourceCleanupError('上一批资源尚未确认释放;请先重试释放资源,再开始新批次。')
@@ -86,7 +132,7 @@ def guard_pending_resources(root):
def process_identity(process):
result = {'pid': process.pid, 'creation_time': None}
handle = getattr(process, 'handle', None)
handle = getattr(process, 'handle', getattr(process, '_handle', None))
if handle is not None:
import win32process
result['creation_time'] = str(win32process.GetProcessTimes(handle)['CreationTime'])
@@ -117,8 +163,33 @@ def _process_gone(identity):
def cleanup_pending_resources(root, *, logging_context=None):
from .isolated_desktop import _Win32Api
from .batch_release_log import write_release_event
from .isolated_cad import RETAINED_CAD_SESSIONS
from .read_recovery import process_tree_exited
from .worker_monitor import cleanup_retained_workers, RETAINED_WORKERS
cleanup_retained_workers(root)
for session in tuple(RETAINED_CAD_SESSIONS.values()):
if (session.root.is_relative_to(canonical_path(root))
and all(process_tree_exited(process) for process in session._retained_processes)):
try:
session.__exit__(None, None, None)
except Exception:
pass # Business uncertainty remains; only confirmed handle release removes the owner.
for record in pending_resources(root):
path = Path(record['record_path'])
if record.get('kind') == 'retained_worker':
if str(canonical_path(path)) in RETAINED_WORKERS:
continue # Live process-tree handles remain the only release authority.
from .retained_worker_recovery import reconcile_worker
try:
reconciled = reconcile_worker(path)
write_release_event(root, path, reconciled,
'succeeded' if reconciled['state'] == 'released' else 'failed',
context=logging_context, reason='restart_recheck',
error='' if reconciled['state'] == 'released' else record['resolution_hint'])
except (OSError, ValueError, TypeError) as error:
write_release_event(root, path, record, 'failed', context=logging_context,
reason='restart_recheck', error=str(error))
continue
live = LIVE_RESOURCES.get(str(path))
if live is not None:
try:
@@ -145,16 +216,27 @@ def cleanup_pending_resources(root, *, logging_context=None):
if not record.get('session_id'):
continue # Corrupt evidence cannot authorize resource actions.
log('started')
identities = list(record.get('processes', ()))
cad_identity = record.get('cad_process')
if record.get('cad_pid') is not None:
if (not isinstance(cad_identity, dict) or cad_identity.get('pid') != record['cad_pid']
or not cad_identity.get('creation_time')):
log('failed', 'CAD 进程身份缺失,不能仅凭桌面消失解除资源保护')
continue
if cad_identity not in identities:
identities.append(cad_identity)
if not all(_process_gone(item) for item in identities):
log('failed', '记录中的进程仍未确认退出')
continue
desktop = record.get('desktop')
if desktop:
_Win32Api().confirm_desktop_released(desktop)
if not all(_process_gone(item) for item in record.get('processes', ())):
log('failed', '记录中的进程仍未确认退出')
continue
# After restart only confirm disappearance. Never attach to COM,
# close a project, or terminate a PID whose handles we no longer own.
record.pop('record_path', None)
record = dict(record, state='released', reconciled=True, released_at=time.time())
record = dict(record, state='released', reconciled=True, released_at=time.time(),
release_proof={'generation': record['generation'], 'desktop_released': True,
'processes_exited': True, 'processes': identities, 'method': 'restart_observation'})
write_record(path, record)
log('succeeded')
except Exception as error:
@@ -188,3 +270,111 @@ def project_checkpoint_released(root):
and record['checkpoints'][key] == checkpoint['attempt_id'])
except (OSError, ValueError, TypeError, KeyError):
return False
def _verify_retained_handles(processes, recorded):
from .read_recovery import process_tree_exited
for process in processes:
if process_tree_exited(process):
continue
identity = process_identity(process)
if not identity.get('creation_time') or identity not in recorded:
raise TaskCenterError('target_identity', '保留进程的创建身份与证据不符,拒绝强制结束。')
def force_pending_owned_resources(root, *, confirmed=False):
"""Explicit GUI action: protect first, terminate only exact retained handles."""
if confirmed is not True:
raise TaskCenterError('force_confirmation_required', '必须明确确认强制结束可能写入的进程。')
from . import batch_supervisor, isolated_cad
from .read_recovery import process_tree_exited
from .stop_control import StopControl, protect_interruption
root = canonical_path(root)
active = [(path, process, control) for path, (_, process, control)
in tuple(batch_supervisor._ACTIVE_SUPERVISORS.items())
if canonical_path(path).parent.parent == root / 'batch-resources'
and control.waiting_for_resolution]
if active:
# Signal the owning supervision loop; never race its process/Job close.
for path, process, control in active:
journal = json.loads(internal_path(path).read_text(encoding='utf-8'))
identity = process_identity(process)
if (not batch_supervisor.valid_journal(journal, path.parent.name)
or not identity.get('creation_time') or identity != journal.get('process')):
raise TaskCenterError('target_identity', '活动监督进程身份不符,拒绝强制结束。')
protect_interruption(path.parent, 'user_confirmed_force_pending_owned_resources')
write_record(path.parent / 'force-request.json', {'version': 1, 'batch_id': journal['batch_id'],
'attempt_id': journal['attempt_id'], 'process': identity, 'confirmed': True})
control.request_force()
return tuple({'state': 'blocked', 'record_path': str(path), 'force_requested': True}
for path, _, _ in active)
with batch_supervisor.supervisor_lease(root):
for path, (api, process) in tuple(batch_supervisor._LIVE_SUPERVISORS.items()):
if canonical_path(path).parent.parent != root / 'batch-resources':
continue
journal = json.loads(internal_path(path).read_text(encoding='utf-8'))
if (not batch_supervisor.valid_journal(journal, path.parent.name)
or process_identity(process) != journal.get('process')):
raise TaskCenterError('target_identity', '监督进程身份已变化,拒绝强制结束。')
batch_supervisor._force_owned_supervisor(root, journal, process)
process.close()
api.close_pending()
batch_supervisor._LIVE_SUPERVISORS.pop(path, None)
for path, runtime in tuple(LIVE_RESOURCES.items()):
if canonical_path(path).parent.parent != root / 'batch-resources':
continue
record = json.loads(internal_path(path).read_text(encoding='utf-8'))
if (not _valid_record(record, Path(path)) or record['session_id'] != runtime.session_id
or record['generation'] != runtime.generation
or record['desktop'] != getattr(runtime.desktop, 'name', None)):
raise TaskCenterError('target_identity', '批次资源会话身份已变化,拒绝强制结束。')
processes = list(getattr(runtime.desktop, '_processes', getattr(runtime.desktop, 'processes', ())))
recorded = list(record['processes'])
if record.get('cad_process'):
recorded.append(record['cad_process'])
_verify_retained_handles(processes, recorded)
evidence = runtime._active_evidence or runtime.path.parent
protect_interruption(evidence, 'user_confirmed_force_pending_owned_resources')
runtime._save(force_state='requested', force_confirmed=True, force_requested_at=time.time())
control = StopControl()
control.request_force()
runtime.stop_event = control
if runtime.cad is not None:
runtime.cad.stop_control = control
for process in processes:
if not process_tree_exited(process):
process.terminate(reason='user_confirmed_pending_resource_force')
try:
runtime.close(reason='manual_retry')
except Exception as error:
runtime.record['force_cleanup_error'] = str(error)
runtime._save()
for key, session in tuple(isolated_cad.RETAINED_CAD_SESSIONS.items()):
if not session.root.is_relative_to(root):
continue
record = json.loads(internal_path(session.root / 'private-desktop.json').read_text(encoding='utf-8'))
processes = session._retained_processes
if (record.get('token') != session.token or record.get('desktop') != session.desktop.name
or record.get('cad_pid') != session.cad.pid or not record.get('retained_for_manual')):
raise TaskCenterError('target_identity', '保留 CAD 会话身份已变化,拒绝强制结束。')
_verify_retained_handles(processes, record.get('retained_processes', ()))
protect_interruption(session.root, 'user_confirmed_force_pending_owned_resources')
session._record(force_state='requested', force_confirmed=True, force_requested_at=time.time())
control = StopControl()
control.request_force()
session.stop_control = control
for process in processes:
if not process_tree_exited(process):
process.terminate(reason='user_confirmed_pending_resource_force')
try:
session.__exit__(None, None, None)
except Exception:
if not all(process_tree_exited(process) for process in processes):
raise
from .worker_monitor import cleanup_retained_workers
cleanup_retained_workers(root, force=True)
pending = cleanup_pending_resources(root)
supervisors = batch_supervisor.reconcile_supervisors(root)
retained = tuple({'state': 'blocked', 'record_path': str(session.root / 'private-desktop.json')}
for session in isolated_cad.RETAINED_CAD_SESSIONS.values() if session.root.is_relative_to(root))
return (*pending, *supervisors, *retained)
@@ -61,6 +61,31 @@ class _DesktopLease:
self.owner._track(process)
return process
def inspect_dialogs(self, pid):
if self.desktop is None or self.generation != self.owner.generation:
return ()
inspect = getattr(self.desktop, 'inspect_dialogs', None)
if inspect is None or not any(process.pid == pid and process.poll() is None for process in self.processes):
return ()
return inspect(pid)
def acknowledge_dialog(self, dialog):
if (self.desktop is None or self.generation != self.owner.generation or
not any(process.pid == dialog['pid'] and process.poll() is None for process in self.processes)):
raise WorkerMonitorError('stale or unavailable batch dialog owner')
self.desktop.acknowledge_dialog(dialog)
def manual_dialog_action(self, dialog, button_hwnd):
if (self.desktop is None or self.generation != self.owner.generation or
not any(process.pid == dialog['pid'] and process.poll() is None for process in self.processes)):
raise WorkerMonitorError('stale or unavailable batch dialog owner')
self.desktop.manual_dialog_action(dialog, button_hwnd)
def register_cad_process(self, process, token):
if self.generation != self.owner.generation or not any(item is process for item in self.processes):
raise WorkerMonitorError('CAD startup process does not belong to this desktop lease')
self.owner._save(cad_pid=process.pid, cad_process=process_identity(process), cad_token=token)
def close(self):
errors, remaining, records = [], [], []
for process in reversed(self.processes):
@@ -87,6 +112,7 @@ class BatchCadRuntime:
def __init__(self, root, kind, stop_event=None, *, desktop_factory=None, cad_factory=None, session_id=None):
self.root = canonical_path(root)
self.kind, self.stop_event = kind, stop_event
self.read_only = kind in {'bom_import', 'collect_target_inventory'}
self.session_id = uuid4().hex if session_id is None else UUID(str(session_id)).hex
self.path = self.root / 'batch-resources' / self.session_id / 'session.json'
self.desktop_factory = desktop_factory or PrivateDesktop
@@ -95,6 +121,7 @@ class BatchCadRuntime:
self.generation = 0
self.result = None
self.record = {'version': 1, 'session_id': self.session_id, 'kind': kind, 'state': 'new',
'read_only': self.read_only,
'generation': 0, 'desktop': None, 'cad_pid': None, 'cad_guid': None,
'processes': [], 'checkpoints': {}, 'retries': {}, 'timings': [], 'native_operations': {}}
self._retry_counts = {}
@@ -102,6 +129,8 @@ class BatchCadRuntime:
self._logging = None
self._active_evidence = None
self._active_attempts = []
self._current_attempts = []
self._attempt_sources = {}
self._close_failure = None
self._close_failure_rebuild = False
@@ -168,7 +197,7 @@ class BatchCadRuntime:
name = 'dx-' + uuid4().hex
self._save(state='starting', generation=self.generation, desktop=name,
processes=[], cad_pid=None, cad_guid=None, checkpoints={}, native_operations={},
cad_shutdown=None, cad_start_requested=False, cleanup=None)
cad_process=None, cad_token=None, cad_shutdown=None, cad_start_requested=False, cleanup=None)
LIVE_RESOURCES[str(self.path)] = self
self.desktop = self.desktop_factory(name, enabled=True)
started = time.monotonic()
@@ -198,6 +227,96 @@ class BatchCadRuntime:
def native_scope(self, evidence):
return _DesktopLease(self, evidence, native=True)
def owned_processes_exited(self):
"""Observe exact retained handles, never infer exit from a timeout."""
processes = list(getattr(self.desktop, '_processes', getattr(self.desktop, 'processes', ())))
cad_process = getattr(self.cad, 'cad', None)
if cad_process is not None and cad_process not in processes:
processes.append(cad_process)
try:
from .read_recovery import process_tree_exited
return bool(processes) and all(process_tree_exited(process) for process in processes)
except Exception:
return False
def reset_project_after_safe_failure(self, project, evidence_root, *, job_id=None):
"""Discard a checkpointed project session before another admitted item."""
root = canonical_path(evidence_root)
try:
checkpoint = json.loads(internal_path(root / 'project-checkpoint.json').read_text(encoding='utf-8'))
safe = (self.record['state'] == 'ready' and self.cad is not None
and canonical_path(checkpoint['project_path']) == canonical_path(project)
and canonical_path(checkpoint['resource_record']) == canonical_path(self.path)
and checkpoint['generation'] == self.generation and project_checkpoint_released(root))
except (OSError, ValueError, TypeError, KeyError):
safe = False
if not safe:
raise BatchResourceCleanupError('缺少当前工程关闭检查点证明,不能继续执行。')
from .batch_attempt import can_retry_attempt
from .discovery_cache import project_fingerprint
attempt_id = checkpoint['attempt_id']
job_id = self.record.get('active_job') if job_id is None else job_id
selected = [(path, expected) for path, expected in self._current_attempts
if expected.get('attempt_id') == attempt_id and expected.get('job_id') == job_id
and expected.get('session_id') == self.session_id and expected.get('generation') == self.generation
and canonical_path(expected['project_path']) == canonical_path(project)]
attempt_path = selected[0][0] if len(selected) == 1 else None
no_mutation = bool(len(selected) == 1 and can_retry_attempt(*selected[0]))
before = self._attempt_sources.get(attempt_id)
checkpoint_digest = hashlib.sha256(internal_path(root / 'project-checkpoint.json').read_bytes()).hexdigest()
self.close(rebuilding=True, reason='safe_project_failure')
self.desktop = self.cad = None
self._active_evidence = None
self._active_attempts = []
after = project_fingerprint(canonical_path(project), self.root)
if after is None:
raise BatchResourceCleanupError('资源已释放,但无法核对工程源文件,不能证明安全继续。')
release_path = self.path.parent / ('generation-release-' + attempt_id + '.json')
write_record(release_path, self.record)
job_token = hashlib.sha256(str(job_id).encode()).hexdigest()[:12]
proof_path = root / ('project-health-' + attempt_id + '-' + job_token + '.json')
proof = {'version': 1, 'session_id': self.session_id, 'generation': self.generation,
'project_path': str(canonical_path(project)), 'job_id': job_id, 'attempt_id': attempt_id,
'project_closed': True, 'resources_released': True, 'no_mutation': no_mutation,
'attempt_record_path': str(attempt_path) if attempt_path is not None else None,
'attempt_record_sha256': hashlib.sha256(internal_path(attempt_path).read_bytes()).hexdigest() if attempt_path else None,
'source_sha256': hashlib.sha256(repr(after).encode()).hexdigest(),
'source_unchanged': before is not None and before == after,
'resource_record': str(release_path), 'resource_record_sha256': hashlib.sha256(internal_path(release_path).read_bytes()).hexdigest(),
'session_record': str(self.path),
'checkpoint_sha256': checkpoint_digest, 'proof_path': str(proof_path)}
write_record(proof_path, proof)
return proof
def release_idle_for_fingerprint(self, project):
if not self.read_only or self.cad is None or self._active_evidence is None:
return False
if canonical_path(self.record.get('active_project', '')) != canonical_path(project):
return False
self.reset_project_after_safe_failure(project, self._active_evidence)
return True
def dialog_state(self):
guard = getattr(self.cad, '_dialogs', None)
return guard.summary() if guard is not None else None
def business_progress(self):
if self._active_evidence is None:
return None
try:
path = internal_path(self._active_evidence / 'worker-progress.json')
value = json.loads(path.read_text(encoding='utf-8'))
if not isinstance(value, dict):
return None
return {key: value.get(key) for key in ('job_id', 'stage', 'done', 'total', 'safe_stop')}
except (OSError, ValueError, TypeError):
return None
def manual_dialog_action(self, dialog, button_hwnd):
if self.cad is None or self.cad.cad.poll() is not None:
raise WorkerMonitorError('owned CAD dialog session is unavailable')
self.cad._dialogs.manual_action(dialog, button_hwnd)
def _ensure_cad(self, abort_event=None):
if self.cad is None:
from .isolated_cad import IsolatedCadSession
@@ -207,6 +326,7 @@ class BatchCadRuntime:
self._save(cad_start_requested=True)
cad = factory(self.path.parent / f'generation-{self.generation + (self.desktop is None)}',
abort_event=abort_event, desktop=lease,
**({'read_only': True} if self.read_only else {}),
**({'stop_control': self.stop_event} if hasattr(self.stop_event, 'force_event') else {}))
self.cad = cad # Retain cleanup ownership even if startup fails.
try:
@@ -219,7 +339,8 @@ class BatchCadRuntime:
self.cad = None
raise
self._timing('cad_start', started)
self._save(state='ready', cad_pid=cad.binding.pid, cad_guid=cad.binding.guid)
self._save(state='ready', cad_pid=cad.binding.pid, cad_guid=cad.binding.guid,
cad_process=process_identity(cad.cad) if getattr(cad, 'cad', None) is not None else None)
return self.cad
def _prepare_attempts(self, root, command, attempt_id, generation):
@@ -241,6 +362,7 @@ class BatchCadRuntime:
task_id=row[0], job_id=row[1], project_path=str(project), attempt_id=attempt_id)
expected.append((path, record))
self._project_attempts.setdefault(str(project).casefold(), []).extend(expected)
self._current_attempts = list(expected)
return project, legacy_path(directory), expected
def _can_retry(self, project, expected):
@@ -264,7 +386,19 @@ class BatchCadRuntime:
from .discovery_cache import project_fingerprint
from .isolated_cad import PrivateCadStartupError, is_identity_conflict
from .worker_monitor import run_monitored_process
cooperative_abort = cooperative_abort or self.read_only
if self.read_only and abort_event is None:
abort_event = self.stop_event
root = canonical_path(command[3])
if self.cad is not None and self.record.get('active_project'):
from .quick_run import _read_commands
selected = [row for row in _read_commands(internal_path(root / 'command.tsv')) if row[1] == command[-1]]
if len(selected) != 1:
raise TaskCenterError('target_identity', '批次工作命令身份缺失或重复,已停止。')
if canonical_path(selected[0][2]) != canonical_path(self.record['active_project']):
if self._active_evidence is None:
raise BatchResourceCleanupError('缺少上一工程关闭检查点,不能启动下一工程。')
self.reset_project_after_safe_failure(self.record['active_project'], self._active_evidence)
self._active_evidence = root
while True:
check_cancelled(abort_event or self.stop_event)
@@ -284,6 +418,7 @@ class BatchCadRuntime:
# this task rather than a stale completed task from session.json.
self._save(active_task=self.record['active_task'], active_attempt=attempt_id)
before = project_fingerprint(project, self.root)
self._attempt_sources[attempt_id] = before
status = internal_path(root / 'status.tsv')
status_before = status.read_bytes() if status.exists() else None
started = time.monotonic()
@@ -297,7 +432,10 @@ class BatchCadRuntime:
return cad.start_worker(launch, extra_environment=environment, **options)
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 {}),
**({'force_control': self.stop_event} if hasattr(self.stop_event, 'force_event') else {}))
if result.returncode and self.read_only:
raise WorkerMonitorError(result.stderr or 'read-only worker failed')
if result.returncode:
self._retain_uncertain(root, project, expected,
WorkerMonitorError(result.stderr or 'worker failed after possible mutation'))
@@ -310,10 +448,41 @@ class BatchCadRuntime:
finally:
self._timing('project_worker', started, project=str(project), attempt_id=attempt_id,
task_id=self.record['active_task'], job_id=self.record['active_job'])
if self.read_only:
self.close(reason='read_failure')
write_record(root / 'project-read-release.json', {'version': 1,
'session_id': self.session_id, 'generation': self.generation,
'project_path': str(project), 'resource_record': str(self.path),
'resources_released': True, 'error': str(failure)})
self.desktop = self.cad = None
self._active_evidence = None
self._active_attempts = []
check_cancelled(abort_event or self.stop_event)
from .project_discovery import ReleasedProjectReadError
raise ReleasedProjectReadError('quick_run_sheet_discovery',
f'工程读取失败,读取会话已释放,可继续其他工程:{project.name};{failure}') from failure
# Missing proof, changed inputs/status, cancellation or a previous
# write anywhere in this project can never authorize replay.
after = project_fingerprint(project, self.root)
status_after = status.read_bytes() if status.exists() else None
from .worker_monitor import WorkerMonitorSafeTimeout
from .batch_attempt import can_retry_attempt
if (isinstance(failure, WorkerMonitorSafeTimeout) and failure.prewrite_cleanup_confirmed
and failure.stage == 'open_project' and before is not None and before == after
and status_before == status_after and expected
and all(can_retry_attempt(path, record) for path, record in
self._project_attempts.get(str(project).casefold(), ()))
and not internal_path(root / 'recovery.request').exists()
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())):
# The deferred problem pass owns replay; do not spend another
# inline runtime retry before the remaining primary items run.
self.close(rebuilding=True, reason='safe_project_failure')
self.desktop = self.cad = None
self._active_evidence = None
self._active_attempts = []
failure.prewrite_source_before = before
raise failure
# Runtime database changes require separate identity evidence. Until
# available for a failed read, use the stricter full fingerprint.
safe = (not is_identity_conflict(failure) and before is not None and before == after
@@ -332,11 +501,13 @@ class BatchCadRuntime:
self.desktop = self.cad = None
def _retain_uncertain(self, root, project, expected, error):
if self.read_only:
return
from .batch_attempt import can_retry_attempt
from .stop_control import wait_for_resolution
attempts = self._project_attempts.get(str(project).casefold(), expected)
if attempts and not all(can_retry_attempt(path, record) for path, record in attempts):
wait_for_resolution(self.stop_event, root, error)
wait_for_resolution(self.stop_event, root, error, resolved=self.owned_processes_exited)
def recover_native_failure(self, project, evidence, reason):
"""One read-only recovery, based on durable source and worker proof."""
@@ -365,6 +536,17 @@ class BatchCadRuntime:
return False
except (OSError, ValueError, KeyError, TypeError):
return False
if self.read_only:
self.close(reason='read_failure')
write_record(evidence / 'project-read-release.json', {'version': 1,
'session_id': self.session_id, 'generation': self.generation,
'project_path': str(project), 'resource_record': str(self.path),
'resources_released': True, 'error': str(reason)})
self.desktop = self.cad = None
self._active_evidence = None
from .project_discovery import ReleasedProjectReadError
raise ReleasedProjectReadError('quick_run_sheet_discovery',
f'原生工程读取失败,读取会话已释放,可继续其他工程:{project.name};{reason}')
self._retry_counts[key] = 1
self.record['retries'][key] = {'count': 1, 'reason': str(reason), 'backend': 'native_cli'}
self._save(state='recycling')
@@ -414,14 +596,16 @@ class BatchCadRuntime:
def _close_resources(self, *, rebuilding=False):
started = time.monotonic()
errors = []
retained_cad = False
try:
self._save(state='closing')
except Exception as error:
errors.append('resource journal: ' + str(error))
if self.cad is not None:
cad, self.cad = self.cad, None
cad = self.cad
try:
cad.__exit__(None, None, None)
self.cad = None
except Exception as error:
if rebuilding:
self.record['shutdown_warning'] = str(error)
@@ -429,14 +613,24 @@ class BatchCadRuntime:
# an unconfirmed shutdown. Keep the warning for diagnostics,
# but retain the failure in the resource gate as well.
errors.append(str(error))
from .read_recovery import process_tree_exited
process = getattr(cad, 'cad', None)
processes = [*getattr(cad, '_retained_processes', ()),
*getattr(self.desktop, '_processes', getattr(self.desktop, 'processes', ()))]
if process is not None:
processes.append(process)
retained_cad = not processes or not all(process_tree_exited(item) for item in processes)
if not retained_cad:
self.cad = None
finally:
cad_record = getattr(cad, 'record', {})
cad_record = cad_record if isinstance(cad_record, dict) else {}
self.record['cad_shutdown'] = {key: cad_record[key] for key in (
'state', 'clean', 'cad_exit_code', 'quit_helper_exit_code', 'cleanup_errors',
'shutdown_seconds', 'orderly_shutdown', 'diagnostic_errors', 'forced_termination',
'forced_root_termination', 'forced_descendant_pids', 'termination_reason') if key in cad_record}
if self.desktop is not None:
'forced_root_termination', 'forced_descendant_pids', 'termination_reason',
'dialog_supervision', 'read_only_released') if key in cad_record}
if self.desktop is not None and not retained_cad:
try:
self.desktop.close()
except Exception as error:
@@ -21,9 +21,56 @@ from .supervisor_protocol import VERSION, MessageGate, valid_journal, encode, de
_WORKER_ROOT = None
_LAUNCH_LOCK = threading.Lock()
_LIVE_SUPERVISORS = {}
_ACTIVE_SUPERVISORS = {}
_WRITE_OPERATIONS = frozenset({'execute_task_queue', 'execute_quick_run_queue', 'execute_quick_run', 'recover_quick_run'})
class BusinessProgressWatch:
"""Control-channel liveness cannot certify forward business progress."""
def __init__(self, started, idle_timeout=150):
self.last_progress = started
self.idle_timeout = idle_timeout
self.signatures = {}
def observe(self, kind, payload, now):
if kind == 'heartbeat':
return
if kind == 'state':
payload = {key: payload.get(key) for key in ('phase', 'queue', 'batch', 'business_progress', 'active_project')}
if kind not in {'state', 'progress', 'phase'}:
return
signature = json.dumps([kind, payload], ensure_ascii=True, sort_keys=True, default=str)
if signature != self.signatures.get(kind):
self.last_progress = now
self.signatures[kind] = signature
def stalled(self, now):
return now - self.last_progress >= self.idle_timeout
def request_manual_dialog_action(root, binding, dialog, button_hwnd):
"""Publish one explicit UI choice for the current supervisor generation."""
from .batch_resources import write_record, _valid_record, _process_gone
from uuid import UUID
batch_id, attempt_id = binding['batch_id'], binding['attempt_id']
if UUID(batch_id).hex != batch_id or UUID(attempt_id).hex != attempt_id:
raise TaskCenterError('target_identity', '弹窗监督进程身份无效。')
directory = canonical_path(root) / 'batch-resources' / batch_id
journal = json.loads(internal_path(directory / 'supervisor.json').read_text(encoding='utf-8'))
resource = json.loads(internal_path(directory / 'session.json').read_text(encoding='utf-8'))
if (not valid_journal(journal, batch_id) or journal['attempt_id'] != attempt_id
or journal['state'] not in {'running', 'blocked'} or not journal.get('process')
or _process_gone(journal['process']) or not _valid_record(resource, directory / 'session.json')
or binding.get('generation') != resource['generation'] or not binding.get('session_token')
or binding['session_token'] != resource.get('cad_token')
or dialog.get('pid') != resource.get('cad_pid') or type(button_hwnd) is not int):
raise TaskCenterError('target_identity', '弹窗或工程会话已变化,请刷新后重新处理。')
request_id = uuid4().hex
write_record(directory / ('manual-dialog-' + request_id + '.json'), dict(binding,
version=VERSION, request_id=request_id, dialog=dialog, button_hwnd=button_hwnd))
return request_id
def _decode_process_output(value):
if not isinstance(value, bytes):
return str(value)
@@ -70,9 +117,10 @@ def _worker_context(root):
def _force_owned_supervisor(root, journal, process):
"""Persist uncertainty before terminating the exact process/Job we own."""
from .batch_resources import write_record
from .read_recovery import process_tree_exited
path = Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json'
if (journal.get('force_state') in {'termination_requested', 'confirmed'}
and process.poll() is not None):
and process_tree_exited(process)):
return
journal['stop_mode'] = 'forced'
journal.setdefault('force_requested_at', time.time())
@@ -138,7 +186,11 @@ def _retain_supervisor_after_control_error(root, journal, process, control, erro
return True
try:
process.wait(timeout=.2)
return False
from .read_recovery import process_tree_exited
if process_tree_exited(process):
control.waiting_for_resolution = False
return False
threading.Event().wait(.2)
except subprocess.TimeoutExpired:
pass
except Exception as failure:
@@ -196,15 +248,24 @@ def mutation_lease(root):
def pending_supervisors(root):
from .batch_resources import _process_gone
from .read_recovery import process_tree_exited
pending = []
for path in (internal_path(root) / 'batch-resources').glob('*/supervisor.json'):
try:
value = json.loads(path.read_text(encoding='utf-8'))
if not valid_journal(value, path.parent.name):
raise ValueError('invalid supervisor ownership record')
if value.get('state') == 'finished':
owner = (_LIVE_SUPERVISORS.get(canonical_path(path))
or _ACTIVE_SUPERVISORS.get(canonical_path(path)))
if owner is not None and not process_tree_exited(owner[1]):
pending.append(dict(value, record_path=str(canonical_path(path)), state='blocked'))
continue
identity = value.get('process') or value.get('parent_process')
if value.get('state') == 'finished':
if value.get('process') is None or _process_gone(value['process']):
continue
pending.append(dict(value, record_path=str(canonical_path(path)), state='blocked'))
continue
if (value.get('state') in {'starting', 'running'} and identity and not _process_gone(identity)
and value.get('parent_process') and not _process_gone(value['parent_process'])):
continue
@@ -217,8 +278,13 @@ def pending_supervisors(root):
def reconcile_supervisors(root):
"""Recheck orphan ownership only; this never launches or replays a job."""
from .batch_resources import _process_gone, pending_resources, write_record
from .read_recovery import process_tree_exited
physical = pending_resources(root)
for record in pending_supervisors(root):
owner = (_LIVE_SUPERVISORS.get(canonical_path(record['record_path']))
or _ACTIVE_SUPERVISORS.get(canonical_path(record['record_path'])))
if owner is not None and not process_tree_exited(owner[1]):
continue
identity = record.get('process')
if not record.get('batch_id') or (identity and not _process_gone(identity)):
continue
@@ -263,6 +329,9 @@ def _finish_response(root, journal, response, context):
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
if related:
raise resource_pending_error(journal['operation'], result, error, primary)
for failure in (error, primary):
if failure is not None:
failure.resources_released = True
resource_path = internal_path(Path(root) / 'batch-resources' / journal['batch_id'] / 'session.json')
def preserve_shutdown_failure(detail):
try:
@@ -271,6 +340,10 @@ def _finish_response(root, journal, response, context):
context.logger.error('supervisor_shutdown_record_failed batch_id=%s error=%s',
journal['batch_id'], record_error)
journal['shutdown_record_error'] = str(record_error)
def shutdown_failure():
failure = application_shutdown_error(result, error, primary)
failure.resources_released = True
return failure
try:
resource = json.loads(resource_path.read_text(encoding='utf-8'))
except FileNotFoundError:
@@ -278,7 +351,7 @@ def _finish_response(root, journal, response, context):
except (OSError, ValueError, TypeError) as failure:
journal.update(state='blocked', shutdown_record_error=str(failure))
preserve_shutdown_failure(failure)
raise application_shutdown_error(result, error, primary) from failure
raise shutdown_failure() from failure
shutdown = resource.get('cad_shutdown') if isinstance(resource, dict) else None
if shutdown is None and isinstance(resource, dict):
shutdown = {}
@@ -287,11 +360,11 @@ def _finish_response(root, journal, response, context):
or any(not isinstance(item, dict) for item in shutdown.get('cleanup_errors', ()))):
journal.update(state='blocked', shutdown_record_error='invalid shutdown record shape')
preserve_shutdown_failure('invalid shutdown record shape')
raise application_shutdown_error(result, error, primary)
raise shutdown_failure()
if (shutdown.get('orderly_shutdown') is False or shutdown.get('forced_termination')
or shutdown.get('diagnostic_errors')
or any(item.get('stage') != 'desktop_release' for item in shutdown.get('cleanup_errors', ()))):
raise application_shutdown_error(result, error, primary)
raise shutdown_failure()
if response.get('business_succeeded'):
if response.get('error'):
context.logger.info('supervisor_resource_recovery_passed batch_id=%s business_replayed=false', journal['batch_id'])
@@ -310,18 +383,25 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
from .isolated_desktop import _Win32Api
from .stop_control import StopControl
root = canonical_path(service._logging.root)
force_control = stop_event if isinstance(stop_event, StopControl) else StopControl()
if stop_event is not None and stop_event.is_set():
raise TaskCenterError('operation_cancelled', '本批操作已取消,未启动监督进程。')
with supervisor_lease(root):
if operation == 'cleanup_batch_resources':
for key, (owned_api, owned_process) in tuple(_LIVE_SUPERVISORS.items()):
if key.parent.parent == root / 'batch-resources':
from .read_recovery import process_tree_exited
retained = json.loads(internal_path(key).read_text(encoding='utf-8'))
if retained.get('operation') in _WRITE_OPERATIONS and not process_tree_exited(owned_process):
raise TaskCenterError('batch_resources_pending',
'保留的写入进程尚未全部退出;普通资源清理不能强制结束,请先人工处理或明确强制结束。')
owned_process.close()
owned_api.close_pending()
_LIVE_SUPERVISORS.pop(key)
if operation != 'cleanup_batch_resources' and pending_supervisors(root):
raise TaskCenterError('batch_resources_pending', '上一监督进程尚未完成资源复核,请先重新清理资源。')
batch_id, attempt_id = uuid4().hex, uuid4().hex
service._last_supervisor_batch_id = batch_id
directory = root / 'batch-resources' / batch_id
request = directory / 'request.json'
journal = {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id,
@@ -351,6 +431,8 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
stderr_reader = None
stdout_tail, stderr_tail = deque(maxlen=65536), deque(maxlen=65536)
sent_cancel, last_heartbeat = False, time.monotonic()
business_watch = BusinessProgressWatch(last_heartbeat)
stall_reported = False
transport_error = None
ownership_cleanup_error = None
force_accepted = False
@@ -388,18 +470,27 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
_environment(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
journal.update(state='running', process=process_identity(process))
write_record(directory / 'supervisor.json', journal)
_ACTIVE_SUPERVISORS[directory / 'supervisor.json'] = (api, process, force_control)
reader = threading.Thread(target=receive, daemon=True)
reader.start()
stderr_reader = threading.Thread(target=receive_stderr, daemon=True)
stderr_reader.start()
while process.poll() is None or not messages.empty():
force = getattr(stop_event, 'force_event', None)
stalled = business_watch.stalled(time.monotonic())
if stalled and not stall_reported:
journal['business_stalled'] = True
journal['business_stalled_at'] = time.time()
write_record(directory / 'supervisor.json', journal)
service._logging.logger.warning('supervisor_business_stalled batch_id=%s; owned processes retained', batch_id)
stall_reported = True
service._supervisor_business_stalled = stalled
force = force_control.force_event
if force is not None and force.is_set() and process.poll() is None:
try:
_force_owned_supervisor(root, journal, process)
except Exception as error:
force.clear()
stop_event.control_error = '强制结束未执行或未确认;请保留窗口和诊断:' + str(error)
force_control.control_error = '强制结束未执行或未确认;请保留窗口和诊断:' + str(error)
service._logging.logger.error('force_stop_failed batch_id=%s error=%s', batch_id, error)
else:
force_accepted = True
@@ -425,16 +516,24 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
continue
last_message = value
last_heartbeat = time.monotonic()
if value['type'] == 'progress' and on_progress is not None:
on_progress(value['payload'])
elif value['type'] == 'phase' and on_phase is not None:
if value['type'] == 'progress':
business_watch.observe('progress', value['payload'], time.monotonic())
if on_progress is not None:
on_progress(value['payload'])
elif value['type'] == 'phase':
payload = decode(value['payload'])
on_phase(*payload)
business_watch.observe('phase', payload, time.monotonic())
if on_phase is not None:
on_phase(*payload)
elif value['type'] == 'state':
state = decode(value['payload'])
service._task_queue_feedback = state['queue']
business_watch.observe('state', state, time.monotonic())
service._task_queue_feedback = getattr(service, '_workspace_queue_context', None) or state['queue']
service._batch_feedback = state['batch']
service._supervisor_waiting = bool(state.get('waiting_for_resolution'))
service._supervisor_waiting = bool(state.get('waiting_for_resolution')) or stalled
force_control.waiting_for_resolution = service._supervisor_waiting
service._supervisor_dialog_state = {'project': state.get('active_project'),
'binding': state.get('dialog_binding'), 'supervision': state.get('dialog_supervision')}
if on_phase is not None and state['phase'] in {'recycling', 'closing'}:
from .bom_import_state import BomImportPhase
on_phase(BomImportPhase.RECOVERING if state['phase'] == 'recycling' else BomImportPhase.RELEASING,
@@ -442,14 +541,23 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
process.wait(timeout=15)
except Exception as error:
transport_error = error
if process is not None and isinstance(stop_event, StopControl):
force_accepted = _retain_supervisor_after_control_error(root, journal, process, stop_event, error)
if process is not None and operation in _WRITE_OPERATIONS:
force_accepted = _retain_supervisor_after_control_error(root, journal, process, force_control, error)
finally:
service._task_queue_feedback = None
service._batch_feedback = None
service._supervisor_waiting = False
service._supervisor_business_stalled = False
service._supervisor_dialog_state = None
try:
if process is not None:
from .read_recovery import process_tree_exited
if (operation in _WRITE_OPERATIONS and not force_accepted
and not process_tree_exited(process)):
retained_error = TaskCenterError('supervisor_interrupted',
'监督进程已结束但所属进程仍在运行;保留可能写入,等待人工处理。')
force_accepted = _retain_supervisor_after_control_error(
root, journal, process, force_control, retained_error)
process.close() # Waits, and confines termination to the owned Job.
api.close_pending()
except Exception as error:
@@ -458,6 +566,8 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
_LIVE_SUPERVISORS[directory / 'supervisor.json'] = (api, process)
transport_error = error if transport_error is None else TaskCenterError(
'batch_resources_pending', f'监督进程错误:{transport_error};收尾错误:{error}')
finally:
_ACTIVE_SUPERVISORS.pop(directory / 'supervisor.json', None)
if reader is not None:
reader.join(3)
if stderr_reader is not None:
@@ -543,11 +653,14 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
# Recheck physical resources even when final business results are
# missing; this never authorizes repeating the interrupted job.
from .batch_resources import cleanup_pending_resources
cleanup_pending_resources(root, logging_context=service._logging)
outstanding = cleanup_pending_resources(root, logging_context=service._logging)
failure = cause if isinstance(cause, TaskCenterError) else TaskCenterError(
'supervisor_interrupted', '批次监督进程未留下可信结果;保留保护记录,不自动重试。' +
(f' 首发原因:{transport_error}' if transport_error else ''))
failure.primary_error = transport_error or error
from .read_recovery import process_tree_exited
failure.resources_released = (not outstanding and ownership_cleanup_error is None
and (process is None or process_tree_exited(process)))
raise failure from (transport_error or error)
if transport_error is not None:
if response['payload']['business_succeeded']:
@@ -555,5 +668,10 @@ def run_supervised(service, operation, arguments, *, stop_event=None, on_progres
write_record(directory / 'supervisor.json', journal)
else:
_mark_interrupted(root, journal, transport_error)
raise resource_pending_error(operation, decoded_result, transport_error, decoded_primary)
failure = resource_pending_error(operation, decoded_result, transport_error, decoded_primary)
from .batch_resources import pending_resources
from .read_recovery import process_tree_exited
failure.resources_released = (ownership_cleanup_error is None and not pending_resources(root)
and process is not None and process_tree_exited(process))
raise failure
return _finish_response(root, journal, response['payload'], service._logging)
@@ -59,6 +59,57 @@ def _admit_request(directory, request, request_bytes):
'process': own}, stream)
stream.flush()
os.fsync(stream.fileno())
return journal
def consume_manual_dialog_actions(directory, runtime, batch_id, attempt_id):
from .batch_resources import write_record
for path in list(internal_path(directory).glob('manual-dialog-*.json'))[:8]:
claimed = path.with_suffix('.claimed')
try:
path.replace(claimed) # Claim before executing; never replay after a crash.
except FileNotFoundError:
continue
result = {'request_file': path.name, 'succeeded': False}
try:
request = json.loads(claimed.read_text(encoding='utf-8'))
if (request.get('version') != VERSION or request.get('batch_id') != batch_id
or request.get('attempt_id') != attempt_id or type(request.get('generation')) is not int
or request['generation'] != runtime.generation
or request.get('session_token') != getattr(runtime.cad, 'token', None)
or path.name != 'manual-dialog-' + UUID(request['request_id']).hex + '.json'):
raise ValueError('manual dialog request belongs to a different owned session')
runtime.manual_dialog_action(request['dialog'], request['button_hwnd'])
result['succeeded'] = True
except Exception as error:
result['error'] = str(error)
write_record(claimed.with_suffix('.result'), result)
def _wait_for_owned_writes(runtime, control):
"""Process exit would close kill-on-close Jobs, so it is also a write boundary."""
if runtime.read_only:
return
from .isolated_cad import RETAINED_CAD_SESSIONS
from .read_recovery import process_tree_exited
from .worker_monitor import RETAINED_WORKERS, _worker_tree_exited, cleanup_retained_workers
from .stop_control import wait_for_resolution
def exited():
if (runtime.record['state'] != 'released' and (runtime.desktop is not None or runtime.cad is not None)
and not runtime.owned_processes_exited()):
return False
if any(session.root.is_relative_to(runtime.root)
and not all(process_tree_exited(process) for process in session._owned_processes())
for session in tuple(RETAINED_CAD_SESSIONS.values())):
return False
return all(_worker_tree_exited(entry['process'], entry['owned'])
for entry in tuple(RETAINED_WORKERS.values()) if entry['root'].is_relative_to(runtime.root))
if not exited():
wait_for_resolution(control, runtime.path.parent,
'supervisor retains possible-write Jobs until all owned processes exit', resolved=exited)
cleanup_retained_workers(runtime.root)
if runtime.desktop is not None or runtime.cad is not None:
runtime.close(reason='manual_retry')
def run(request_path):
@@ -78,7 +129,7 @@ def run(request_path):
evidence = LifecycleEvidence(directory)
if request_path != directory / 'request.json':
raise ValueError('Supervisor request ownership path mismatch')
_admit_request(directory, request, request_bytes)
admission = _admit_request(directory, request, request_bytes)
evidence.try_append('worker_started', pid=os.getpid())
from .batch_runtime import BatchCadRuntime
from .batch_supervisor import _worker_context
@@ -87,7 +138,7 @@ def run(request_path):
from .store import TaskStore
_worker_context(root)
from .stop_control import StopControl
stop = StopControl() if request.get('interactive_stop', False) else threading.Event()
stop = StopControl()
finished, output_lock = threading.Event(), threading.Lock()
kind = {'inspect_bom_batch': 'bom_import', 'preview_bom_batch': 'bom_import', 'preview_bom_sources': 'bom_import',
'execute_task_queue': 'task_queue', 'execute_quick_run_queue': 'quick_run_queue'}.get(request['operation'], request['operation'])
@@ -110,15 +161,24 @@ def run(request_path):
def monitor():
while not finished.is_set():
try:
from .read_recovery import check_owner_loss
if check_owner_loss(directory, admission, read_only=runtime.read_only):
stop.set()
cancel = internal_path(directory / 'cancel.json')
if cancel.is_file():
value = json.loads(cancel.read_text(encoding='utf-8'))
if value == {'version': VERSION, 'batch_id': batch_id, 'attempt_id': attempt_id}:
stop.set()
consume_manual_dialog_actions(directory, runtime, batch_id, attempt_id)
emit('heartbeat')
feedback = getattr(service, '_task_queue_feedback', None)
emit('state', encode({'phase': runtime.record['state'], 'queue': feedback,
'batch': service.batch_feedback(),
'active_project': runtime.record.get('active_project'),
'business_progress': runtime.business_progress(),
'dialog_supervision': runtime.dialog_state(),
'dialog_binding': {'batch_id': batch_id, 'attempt_id': attempt_id,
'generation': runtime.generation, 'session_token': getattr(runtime.cad, 'token', None)},
'waiting_for_resolution': getattr(stop, 'waiting_for_resolution', False),
'resolution_error': getattr(stop, 'resolution_error', '')}))
except Exception:
@@ -187,6 +247,7 @@ def run(request_path):
context.report_exception('batch_supervisor', error)
response.update(status='error', error=encode_error(error))
finally:
_wait_for_owned_writes(runtime, stop)
evidence.try_append('worker_closing', status=response.get('status'), business_succeeded=response.get('business_succeeded'))
finished.set()
thread.join(3)
@@ -1,5 +1,6 @@
"""Project routing, staged previews and atomic confirmation for a batch BOM."""
from dataclasses import dataclass
import hashlib
from pathlib import Path
from .bom_plan import write_bom_template
@@ -14,6 +15,8 @@ class BomProjectPreview:
baseline: tuple
inventory: tuple
rows: tuple
source_hashes: tuple[tuple[str, str], ...] = ()
strict_rows: bool = False
@dataclass(frozen=True)
@@ -80,6 +83,15 @@ def save_batch(service, preview, rows_by_task):
raise TaskCenterError('project_binding', '本批工程范围已改变,请重新导入 BOM')
for project in preview.projects:
_assert_editable(service, project.task_id)
if project.strict_rows and tuple(rows_by_task[project.task_id]) != project.rows:
raise TaskCenterError('bom_import', '部分导入必须使用原预览行,请重新导入后确认')
for source, digest in project.source_hashes:
try:
actual = hashlib.sha256(Path(source).read_bytes()).hexdigest()
except OSError as error:
raise TaskCenterError('bom_import', 'BOM 来源已不可读,请重新导入') from error
if actual != digest:
raise TaskCenterError('bom_import', 'BOM 来源在预览后已改变,请重新导入')
if tuple(store.list_target_plan(project.task_id)) != project.baseline:
raise TaskCenterError('target_identity', '工程位号计划在 BOM 预览后已改变,请重新导入')
for project in preview.projects:
@@ -1,5 +1,6 @@
"""Read-only, exhaustive BOM validation with an all-or-nothing preview."""
import inspect
import hashlib
from dataclasses import dataclass, replace
from pathlib import Path
@@ -43,6 +44,7 @@ class BomImportReport:
preview: BomBatchPreview | None = None
errors: tuple[str, ...] = ()
source_map_path: Path | None = None
passed_preview: BomBatchPreview | None = None
@property
def total_rows(self):
@@ -128,7 +130,29 @@ def _check_record_conflicts(rows, records, indices):
duplicate_rows=tuple(rows[item].excel_row for item in dict.fromkeys(claimed)))
def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None, on_phase=None, runtime=None):
def select_passed_projects(report, task_ids):
"""Explicitly accept whole passed projects from this immutable inspection."""
task_ids = tuple(task_ids)
preview = report.passed_preview
if (preview is None or report.errors or not task_ids or len(task_ids) != len(set(task_ids))
or not set(task_ids) <= {p.task_id for p in preview.projects}):
raise TaskCenterError('bom_import', '只能选择本次预览中校验通过的工程')
return replace(preview, projects=tuple(replace(p, strict_rows=True) for p in preview.projects
if p.task_id in task_ids))
def bind_source_report(report, source_hashes, source_map_path):
"""Replace temporary normalized input binding with original workbook proof."""
bindings = tuple(source_hashes) + ((str(source_map_path), hashlib.sha256(
Path(source_map_path).read_bytes()).hexdigest()),)
def bind(preview):
return None if preview is None else replace(preview, projects=tuple(
replace(p, source_hashes=bindings) for p in preview.projects))
return replace(report, preview=bind(report.preview), passed_preview=bind(report.passed_preview))
def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None, on_phase=None, runtime=None,
allow_partial=False):
"""Validate all independent rows; never persist inventory or return partial plans.
Operational failures (including cancellation and native cleanup) propagate so
@@ -141,16 +165,16 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
with BatchCadRuntime(service._logging.root, 'bom_import', stop_event) as owned_runtime:
try:
report = inspect_batch(service, task_id, path, stop_event=stop_event,
on_progress=on_progress, on_phase=on_phase, runtime=owned_runtime)
on_progress=on_progress, on_phase=on_phase, runtime=owned_runtime, allow_partial=allow_partial)
except BomInspectionError as error:
report = error.bom_report
raise
owned_runtime.result = report
return report
except BatchResourceCleanupError as error:
error.bom_report = replace(report, preview=None) if report is not None else None
error.bom_report = replace(report, preview=None, passed_preview=None) if report is not None else None
if isinstance(error.completed_result, BomImportReport):
error.completed_result = replace(error.completed_result, preview=None)
error.completed_result = replace(error.completed_result, preview=None, passed_preview=None)
raise
def check_cancelled():
if stop_event is not None and stop_event.is_set():
@@ -171,6 +195,7 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
if len(owners) != len(scope):
raise TaskCenterError('project_binding', '同批任务存在重复工程')
rows, records, grouped = [], {}, {}
source_hash = hashlib.sha256(Path(path).read_bytes()).hexdigest() if Path(path).is_file() else ''
workbook = None
try:
workbook = load_workbook(Path(path), read_only=True, data_only=False)
@@ -251,26 +276,52 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
except TaskCenterError as error:
for index in indices:
rows[index] = replace(rows[index], status='failed', reason=error.message)
if any(row.status == 'failed' for row in rows):
if any(row.status == 'failed' for row in rows) and not allow_partial:
return _report(rows)
notify(f'BOM 表格校验通过,共 {len(rows)} 行、涉及 {len(grouped)} 个工程;开始核验工程位号。')
previews = []
for position, (key, indices) in enumerate(grouped.items(), 1):
check_cancelled()
task, project = owners[key]
# One invalid row rejects its whole project, including parsed rows which
# were excluded from grouped because they failed Excel validation.
if any(row.status == 'failed' and row.project_path == str(project.path) for row in rows):
continue
task_default_value_mode = 'part_label' if task.copy_part_number_to_value else 'preserve'
def progress(message, phase=None):
notify(f'工程 {position}/{len(grouped)} · {message}', phase)
progress(f'正在核验「{task.name}」的位号库存…', BomImportPhase.INVENTORY)
baseline = tuple(service._store.list_target_plan(task.task_id))
requested = tuple(dict.fromkeys(records[index].old for index in indices))
requested = tuple(dict.fromkeys(part for index in indices
for part in (records[index].old, records[index].new)))
known = tuple(dict.fromkeys(row.target.old_part_number for row in baseline))
if baseline and {part.casefold() for part in requested} <= {part.casefold() for part in known}:
known_parts = {part.casefold() for part in known}
project_rules = service.rules(task.task_id)
defaults = {(rule.old_part_number.casefold(), rule.new_part_number): rule.target_cell
for rule in project_rules if rule.enabled}
missing_metadata = False
already_target_inventory = False
for index in indices:
record = records[index]
mode = task_default_value_mode if record.value_mode == 'inherit' else record.value_mode
for row in baseline:
if (record.enabled and row.target.old_part_number.casefold() == record.new.casefold()
and row.target.refdes.casefold() in {ref.casefold() for ref in record.refs}):
already_target_inventory = True
cell = (row.target_cell if row.new_part_number == record.new else '') or defaults.get(
(record.old.casefold(), record.new), '')
missing_metadata |= ((mode == 'part_label' and row.target.actual_part_label is None)
or (bool(cell) and row.target.actual_cell is None))
if baseline and all(records[index].old.casefold() in known_parts or records[index].new.casefold() in known_parts
for index in indices) and not already_target_inventory:
progress(f'「{task.name}」复用已有位号库存,无需启动 CAD')
inventory = tuple(row.target for row in baseline)
else:
progress(f'「{task.name}」正在获取位号库存,仅采集本表涉及的旧料号及已有计划料号')
collector = service.for_project_task(task.task_id)._quick_run_preparer.collect_inventory
preparer = service.for_project_task(task.task_id)._quick_run_preparer
if missing_metadata:
preparer.invalidate_discovery(project.path)
collector = preparer.collect_inventory
controls = ({'runtime': runtime} if any(
parameter.name == 'runtime' or parameter.kind is inspect.Parameter.VAR_KEYWORD
for parameter in inspect.signature(collector).parameters.values()) else {})
@@ -300,9 +351,17 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
raise BomInspectionError(error, report) from error
check_cancelled()
progress(f'「{task.name}」正在匹配 {len(indices)} 行 BOM 与工程位号…', BomImportPhase.MATCHING)
merged = merge_target_inventory(baseline, inventory)
try:
merged = merge_target_inventory(baseline, inventory)
except TaskCenterError as error:
if not already_target_inventory:
raise
for index in indices:
rows[index] = replace(rows[index], status='failed', reason=error.message)
continue
matched_rows, touched = {}, {}
matcher = BomMatcher(merged, service.rules(task.task_id)) if merged else None
matcher = BomMatcher(merged, project_rules, default_value_mode=task_default_value_mode,
current_inventory=inventory) if merged else None
for index in indices:
check_cancelled()
try:
@@ -314,7 +373,12 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
for target_key, row in matched.items():
touched.setdefault(target_key, []).append(index)
matched_rows[target_key] = row
rows[index] = replace(rows[index], status='passed', reason='校验通过')
already = tuple(row.target.refdes for row in matched.values()
if records[index].enabled and
row.target.old_part_number.casefold() == records[index].new.casefold())
reason = ('校验通过;已是目标料号且实际 Value/Cell 满足策略,跳过位号:' + ', '.join(already)
if already else '校验通过')
rows[index] = replace(rows[index], status='passed', reason=reason)
except TaskCenterError as error:
rows[index] = replace(rows[index], status='failed', reason=error.message)
for target, indices_for_target in touched.items():
@@ -330,9 +394,14 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
for index in indices:
if rows[index].status == 'passed':
rows[index] = replace(rows[index], status='failed', reason=error.message)
previews.append(BomProjectPreview(task.task_id, project.path, baseline, inventory, combined))
if all(rows[index].status == 'passed' for index in indices):
previews.append(BomProjectPreview(task.task_id, project.path, baseline, inventory, combined,
((str(Path(path).resolve()), source_hash),)))
progress(f'「{task.name}」校验完成')
check_cancelled()
preview = None if any(row.status != 'passed' for row in rows) else BomBatchPreview(
task_id, _identity(scope), tuple(previews))
return _report(rows, preview)
if hashlib.sha256(Path(path).read_bytes()).hexdigest() != source_hash:
return _report(rows, errors=('BOM 来源在校验期间已改变,请重新导入',))
passed = BomBatchPreview(task_id, _identity(scope), tuple(previews)) if allow_partial and previews else None
return replace(_report(rows, preview), passed_preview=passed)
@@ -115,6 +115,8 @@ class BomImportMachine:
def release_preview(self, *, saved: bool) -> None:
report = self.state.report
if report is not None and report.preview is not None:
self.state = replace(self.state, report=replace(report, preview=None), notice=
'校验通过,位号计划已保存。' if saved else '本次导入预览已放弃,校验报告保留。')
if report is not None and (report.preview is not None or report.passed_preview is not None):
notice = ('校验通过,位号计划已保存。' if report.preview is not None else
'已保存选择的通过工程;失败和未检查行的报告保留。')
self.state = replace(self.state, report=replace(report, preview=None, passed_preview=None), notice=
notice if saved else '本次导入预览已放弃,校验报告保留。')
@@ -178,15 +178,18 @@ def parse_bom_row(cells, positions):
class BomMatcher:
"""Index one immutable inventory once, then match independent Excel rows."""
def __init__(self, baseline, rules=()):
def __init__(self, baseline, rules=(), *, default_value_mode='preserve', current_inventory=None):
if not baseline:
raise TaskCenterError('target_inventory', '未采集到可匹配的工程位号')
self.by_key = {}
self.projects = set()
self.by_identity = {}
self.default_value_mode = default_value_mode
self.cell_defaults = {(rule.old_part_number.casefold(), rule.new_part_number): rule.target_cell
for rule in rules if rule.enabled}
self.identities = ProjectIdentityResolver()
self.current_inventory = (None if current_inventory is None else
{self.identities.target(target): target for target in current_inventory})
for row in baseline:
target = row.target
key = self.identities.target(target)
@@ -201,25 +204,47 @@ class BomMatcher:
raise TaskCenterError('bom_import', 'BOM 工程与当前任务不一致')
matched = {}
for refdes in record.refs:
candidates = [(key, target) for key, target in self.by_identity.get((record.old.casefold(), refdes.casefold()), ())
if (not record.schematic or target.schematic_name.casefold() == record.schematic.casefold())
identities = ((record.old.casefold(), refdes.casefold()), (record.new.casefold(), refdes.casefold()))
candidates = [(key, target) for identity in dict.fromkeys(identities)
for key, target in self.by_identity.get(identity, ())
if (not record.project_path or self.identities.project(record.project_path) == key[0])
and (not record.schematic or target.schematic_name.casefold() == record.schematic.casefold())
and (not record.sheet or target.sheet_number.casefold() == record.sheet.casefold())
and (not record.uid or target.uid == record.uid)]
if len(candidates) != 1:
raise TaskCenterError('bom_import', f'位号 {refdes} 无法唯一匹配当前采集清单')
key, target = candidates[0]
if record.project_path and self.identities.project(record.project_path) != key[0]:
raise TaskCenterError('bom_import', f'位号 {refdes} 不属于本行工程')
if key in matched:
raise TaskCenterError('bom_import', f'位号 {refdes} 在 BOM 中重复')
matched[key] = TargetPlanRow(target, record.enabled, record.new,
cell = ((self.by_key[key].target_cell if self.by_key[key].new_part_number == record.new else '')
or self.cell_defaults.get((record.old.casefold(), record.new), ''))
already_target = target.old_part_number.casefold() == record.new.casefold()
if already_target and record.enabled:
current = target if self.current_inventory is None else self.current_inventory.get(key)
if current is None:
raise TaskCenterError('bom_import', f'位号 {refdes} 缺少本轮只读观察,不能确认已到目标')
mode = self.default_value_mode if record.value_mode == 'inherit' else record.value_mode
expected = {'preserve': current.old_value, 'custom': record.custom, 'part_number': current.old_part_number,
'part_label': current.actual_part_label}.get(mode)
has_nc = lambda value: any(part.strip().casefold() == 'nc' for part in value.split('/')[1:])
if expected is not None and record.sync_nc and has_nc(current.old_value) and not has_nc(expected):
expected = expected.rstrip() + ('NC' if expected.rstrip().endswith('/') else '/NC')
if expected is None or (mode == 'part_label' and not expected) or current.old_value != expected:
raise TaskCenterError('bom_import', f'位号 {refdes} 已是目标料号,但实际 Value 不符合策略或缺少 Part Label 证据;请核验后处理')
if cell and current.actual_cell != cell:
reason = '库存没有实际 Cell 回读证据' if current.actual_cell is None else '实际 Cell 不符合指定封装'
raise TaskCenterError('bom_import', f'位号 {refdes} 已是目标料号,但{reason},不能确认跳过')
matched[key] = TargetPlanRow(target, record.enabled and not already_target, record.new,
record.value_mode == 'custom', record.custom, record.sync_nc,
(self.by_key[key].target_cell if self.by_key[key].new_part_number == record.new else '')
or self.cell_defaults.get((target.old_part_number.casefold(), record.new), ''),
cell,
record.value_mode)
return matched
def match_bom_records(baseline, records, rules=()) -> tuple[TargetPlanRow, ...]:
matcher = BomMatcher(baseline, rules)
def match_bom_records(baseline, records, rules=(), *, default_value_mode='preserve') -> tuple[TargetPlanRow, ...]:
matcher = BomMatcher(baseline, rules, default_value_mode=default_value_mode)
matched = {}
for record in records:
incoming = matcher.match_record(record)
@@ -227,14 +252,15 @@ def match_bom_records(baseline, records, rules=()) -> tuple[TargetPlanRow, ...]:
raise TaskCenterError('bom_import', '位号在 BOM 中重复')
matched.update(incoming)
result = tuple(matched.get(key, TargetPlanRow(row.target)) for key, row in matcher.by_key.items())
compile_target_rules(result)
compile_target_rules(result, default_value_mode=default_value_mode)
return result
def read_bom_plan(store, task_id: str, path: Path) -> tuple[TargetPlanRow, ...]:
from .batch_rules import batch_rule_view
return match_bom_records(store.list_target_plan(task_id), read_bom_records(path),
batch_rule_view(store, task_id, strict=True))
batch_rule_view(store, task_id, strict=True), default_value_mode=
'part_label' if store.get_task(task_id).copy_part_number_to_value else 'preserve')
def _normal_headers(values):
@@ -0,0 +1,155 @@
"""Bounded, COM-independent observations of modal dialogs on an owned desktop."""
import ctypes
from ctypes import wintypes
import json
import time
from threading import RLock
from .batch_resources import write_record
def _text(handle):
user = ctypes.WinDLL('user32', use_last_error=True)
send = user.SendMessageTimeoutW
send.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM,
wintypes.UINT, wintypes.UINT, ctypes.POINTER(ctypes.c_size_t)]
send.restype = wintypes.LPARAM
buffer, result = ctypes.create_unicode_buffer(2048), ctypes.c_size_t()
if not send(handle, 0x000D, len(buffer), ctypes.addressof(buffer), 0x0002, 50, ctypes.byref(result)):
raise OSError('dialog text unavailable or unresponsive')
if result.value >= len(buffer) - 1:
raise OSError('dialog text exceeds observation limit')
return buffer.value
def inspect_owned_dialogs(api, desktop_name, pid):
import win32gui
import win32process
result = []
deadline = time.monotonic() + .5
for window in api._desktop_windows(desktop_name):
if window['pid'] != pid or window['class'] != '#32770' or not win32gui.IsWindowVisible(window['hwnd']):
continue
handle = window['hwnd']
row = dict(window, title='', text='', buttons=[], complete=True)
labels, children = [], []
try:
row['title'] = _text(handle)
win32gui.EnumChildWindows(handle, lambda child, _: children.append(child), None)
for child in children:
if time.monotonic() >= deadline or len(children) > 64:
row['complete'] = False
break
if not win32gui.IsWindowVisible(child):
continue
if win32process.GetWindowThreadProcessId(child)[1] != pid:
row['complete'] = False
continue
text = _text(child)
if win32gui.GetClassName(child).casefold() == 'button':
row['buttons'].append({'hwnd': int(child), 'id': win32gui.GetDlgCtrlID(child),
'text': text, 'enabled': bool(win32gui.IsWindowEnabled(child))})
elif text:
labels.append(text)
except Exception as error:
row.update(complete=False, read_error=str(error))
row['text'] = '\n'.join(labels)[:8192]
result.append(row)
if len(result) >= 8 or time.monotonic() >= deadline:
break
return tuple(result)
def acknowledge_owned_dialog(api, desktop_name, pid, expected):
import win32gui
# Re-enumerate the private desktop and compare the complete fingerprint;
# a recycled HWND or changed prompt cannot inherit the earlier decision.
current = next((row for row in inspect_owned_dialogs(api, desktop_name, pid)
if row == expected), None)
if current is None or not _script_error(current):
raise OSError('dialog changed before acknowledgement')
win32gui.PostMessage(current['buttons'][0]['hwnd'], 0x00F5, 0, 0) # BM_CLICK, no global input
def manually_act_on_owned_dialog(api, desktop_name, pid, expected, button_hwnd):
"""Execute one explicit user choice only while the full prompt still matches."""
import win32gui
current = next((row for row in inspect_owned_dialogs(api, desktop_name, pid)
if row == expected and row['pid'] == pid), None)
if current is None or current.get('complete') is not True or type(button_hwnd) is not int:
raise OSError('dialog changed before the manual action')
button = next((row for row in current['buttons']
if row['hwnd'] == button_hwnd and row['enabled']), None)
if button is None:
raise OSError('manual dialog button is no longer available')
win32gui.PostMessage(button_hwnd, 0x00F5, 0, 0)
def _script_error(row):
title = row['title'].strip().casefold()
body = row['text'].casefold()
buttons = row['buttons']
return (row.get('complete') is True and title in {'script error', 'microsoft vbscript', 'dxdesigner', '脚本错误'}
and any(marker in body for marker in ('microsoft vbscript compilation error', 'microsoft vbscript 编译器错误'))
and len(buttons) == 1 and buttons[0]['id'] in {1, 2} and buttons[0]['enabled']
and buttons[0]['text'].replace('&', '').strip().casefold() in {'ok', '确定', '确定(o)'})
class CadDialogGuard:
def __init__(self, desktop, process, evidence_path, token):
self.desktop, self.process = desktop, process
self.evidence_path, self.token = evidence_path, token
self.records, self.seen = [], set()
self.blocking = []
self.current = []
self.failure = ''
self._lock = RLock()
def poll(self, phase):
with self._lock:
self._poll(phase)
def _poll(self, phase):
inspect = getattr(self.desktop, 'inspect_dialogs', None)
if inspect is None or self.process.poll() is not None:
self.blocking = []
return
rows = [row for row in inspect(self.process.pid)
if row['pid'] == self.process.pid and row['class'] == '#32770']
self.current = rows
self.blocking = [row['title'] or '未命名弹窗' for row in rows]
for row in rows:
key = json.dumps(row, ensure_ascii=False, sort_keys=True)
action = 'acknowledge_script_error' if _script_error(row) else 'manual_required'
if action == 'acknowledge_script_error':
self.failure = 'CAD script error: ' + row['text'][:1000]
if key in self.seen or len(self.records) >= 100:
continue
record = dict(row, phase=phase, action=action, observed_at=time.time())
self.records.append(record)
self._save() # No automatic button action without durable evidence.
self.seen.add(key)
if action == 'acknowledge_script_error':
self.desktop.acknowledge_dialog(row)
def _save(self):
write_record(self.evidence_path, {'version': 1, 'session_token': self.token,
'cad_pid': self.process.pid, 'dialogs': self.records})
def summary(self):
with self._lock:
return {'evidence_path': str(self.evidence_path), 'dialogs_seen': len(self.records),
'blocked': bool(self.blocking), 'blocking_titles': list(self.blocking),
'current_dialogs': list(self.current), 'error': self.failure}
def manual_action(self, dialog, button_hwnd):
with self._lock:
self._poll('manual_review')
if dialog not in self.current:
raise OSError('manual dialog is no longer current')
self.records.append(dict(dialog, action='user_selected_button', button_hwnd=button_hwnd,
observed_at=time.time()))
self._save()
self.desktop.manual_dialog_action(dialog, button_hwnd)
@@ -153,13 +153,15 @@ def _catalog_from_evidence(evidence, library, part, partition, fingerprint, path
def _require_cleanup(cleanup):
def pending(message):
raise TaskCenterError('batch_resources_pending', message)
if not isinstance(cleanup, dict) or cleanup.get('errors') or not cleanup.get('desktop_handle_closed') or not cleanup.get('desktop_confirmation', {}).get('released'):
_fail('catalog private desktop cleanup was not proven')
pending('catalog private desktop cleanup was not proven')
if not cleanup.get('processes'):
_fail('catalog owned process cleanup is missing')
pending('catalog owned process cleanup is missing')
for process in cleanup['processes']:
if process.get('errors') or process.get('job_active_processes') != 0 or not process.get('process_handle_closed') or not process.get('job_handle_closed') or process.get('unconfirmed_descendant_handles', 0):
_fail('catalog owned Job process cleanup was not proven')
pending('catalog owned Job process cleanup was not proven')
def _dispose_clone(root):
@@ -208,6 +210,7 @@ def read_library_cell_catalog(library_path: Path, part_number: str, evidence_roo
root.mkdir(parents=True)
evidence_path = root / 'catalog.json'
reader_started = False
result = None
try:
clone = _clone_library(library, root, manifest)
_write_json(root / 'source-before.json', manifest)
@@ -235,9 +238,16 @@ def read_library_cell_catalog(library_path: Path, part_number: str, evidence_roo
cleanup_path = root / 'desktop-cleanup.json'
if not reader_started:
_dispose_clone(root)
elif result is not None:
_require_cleanup(result.get('cleanup'))
_dispose_clone(root)
elif cleanup_path.is_file():
_require_cleanup(json.loads(cleanup_path.read_text(encoding='utf-8')))
_dispose_clone(root)
elif getattr(error, 'catalog_resources_released', False):
_dispose_clone(root)
else:
raise TaskCenterError('batch_resources_pending', 'catalog reader cleanup/release evidence is missing') from error
raise
@@ -271,6 +281,41 @@ def read_project_cell_choices(project_paths: tuple[Path, ...], part_number: str,
return tuple(sorted(choices))
def preflight_target_libraries(project_paths, rules, evidence_root, *, allow_cold_read=True):
"""Prove each requested target PN and Cell using the isolated readonly reader.
An empty Cell choice still requires an authoritative associated cell list;
missing parts and ambiguous partitions are rejected by the reader itself.
"""
projects = tuple(project_paths)
if not projects:
_fail('no project libraries are available for target preflight')
requests = tuple(dict.fromkeys((rule.new_part_number, getattr(rule, 'target_cell', ''))
for rule in rules if getattr(rule, 'enabled', True)))
proof = []
for library in dict.fromkeys(project_library_path(project) for project in projects):
for part, cell in requests:
catalog = read_library_cell_catalog(library, part, evidence_root,
allow_cold_read=allow_cold_read)
if cell and cell not in {choice.name for choice in catalog.cells}:
_fail(f'target Cell is not associated with requested Part Number: {part} / {cell}')
proof.append(catalog)
return tuple(proof)
def preflight_command_target(command, evidence_root, *, allow_cold_read=True):
"""Execution adapter for one frozen command, before journal claim or CAD writes."""
from types import SimpleNamespace
try:
return preflight_target_libraries((Path(command['project_path']),),
(SimpleNamespace(new_part_number=command['new_part'], target_cell=command.get('target_cell', '')),),
evidence_root, allow_cold_read=allow_cold_read)
except TaskCenterError as error:
if error.code != 'cell_catalog':
raise
raise TaskCenterError('target_cell_catalog', error.message) from error
def _worker_command(request):
if getattr(sys, 'frozen', False):
return (sys.executable, '--cell-catalog-worker', str(request))
@@ -359,7 +404,11 @@ def _catalog_launch_lock():
def _run_isolated_reader(clone, part, partition, root):
with _catalog_launch_lock():
_require_no_existing_manager()
try:
_require_no_existing_manager()
except TaskCenterError as error:
error.catalog_resources_released = True
raise
return _run_owned_reader(clone, part, partition, root)
@@ -0,0 +1,167 @@
"""Frozen read-only UID expansion for newly created all-match queues."""
from dataclasses import dataclass
import csv
from hashlib import sha256
from io import StringIO
import json
from pathlib import Path
from types import SimpleNamespace
from .errors import TaskCenterError
from .target_plan import ComponentTarget, TargetRule
@dataclass(frozen=True)
class InventoryEmptyRule:
old_part_number: str
new_part_number: str
inventory_empty_sheet: tuple[str, str, str]
custom_value_enabled: bool = False
custom_value: str = ''
sync_nc: bool = True
target_cell: str = ''
value_mode: str = 'preserve'
enabled: bool = True
scope: str = 'targets'
targets: tuple = ()
def _error(detail):
return TaskCenterError('component_scope', 'Frozen component scope is invalid: ' + detail)
def _digest(value):
return sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf8')).hexdigest()
def _sources(rules, base_mode):
if any(getattr(rule, 'scope', 'all') != 'all' for rule in rules):
raise _error('source rules are not all-match rules')
return [{name: getattr(rule, name, default) for name, default in (
('rule_id', ''), ('task_id', ''), ('position', 0), ('old_part_number', ''),
('new_part_number', ''), ('enabled', True), ('custom_value_enabled', False),
('custom_value', ''), ('sync_nc', True), ('target_cell', ''), ('value_mode', base_mode))}
for rule in rules]
def freeze(projects, rules, sheets, discoveries, failures, base_mode):
"""The discovery boundary certifies parser validation and reader release."""
from .quick_run import _path_key
sources = _sources(rules, base_mode)
requested = {rule.old_part_number.casefold() for rule in rules}
inventories = []
for project in projects:
key = _path_key(project.path)
if key not in sheets:
raise _error('missing project sheet manifest')
discovery = discoveries.get(key)
components = []
if key not in failures:
if discovery is None or set(discovery.sheets) != set(discovery.matched_old_parts):
raise _error('missing validated read-only component manifest')
seen, actual = set(), {sheet: set() for sheet in sheets[key]}
for target in discovery.components:
sheet = target.schematic_name, target.sheet_number
if _path_key(target.project_path) != key or sheet not in actual or target.key in seen:
raise _error('component inventory identity is not unique within the frozen sheet scope')
seen.add(target.key)
if target.old_part_number.casefold() in requested:
actual[sheet].add(target.old_part_number.casefold())
components.append({
'schematic_name': target.schematic_name, 'sheet_number': target.sheet_number,
'uid': target.uid, 'refdes': target.refdes,
'old_part_number': target.old_part_number, 'old_value': target.old_value,
'actual_part_label': target.actual_part_label, 'actual_cell': target.actual_cell})
expected = {sheet: {part.casefold() for part in discovery.matched_old_parts[sheet]} & requested
for sheet in sheets[key]}
if actual != expected:
raise _error('Part Number inventory has no matching component identity manifest')
inventories.append({'project_path': str(project.path), 'sheets': [list(sheet) for sheet in sheets[key]],
'components': components, 'observation': 'project_missing' if key in failures else 'validated_readonly_inventory'})
return {'version': 1, 'base_value_mode': base_mode, 'source_rules': sources,
'source_signature': _digest(sources), 'projects': inventories}
def load(path):
try:
record = json.loads(path.read_text(encoding='utf-8-sig'))
if (record['version'] != 1 or record['base_value_mode'] not in {'preserve', 'part_label', 'part_number'}
or not isinstance(record['source_rules'], list) or not record['source_rules']
or record['source_signature'] != _digest(record['source_rules'])
or not isinstance(record['projects'], list) or not record['projects']):
raise ValueError('source signature or schema changed')
return record
except (OSError, UnicodeError, ValueError, KeyError, TypeError) as error:
raise _error('source signature, schema or inventory sidecar is missing or changed') from error
def expand(record, projects, rules, base_mode, sheets):
"""Reconstruct exact commands from original rules, without querying changed CAD."""
from .quick_run import _path_key, _rule_command_options
if record['base_value_mode'] != base_mode or record['source_rules'] != _sources(rules, base_mode):
raise _error('source rule options differ from the frozen source signature')
try:
inventories = {_path_key(item['project_path']): item for item in record['projects']}
if len(inventories) != len(record['projects']):
raise ValueError('duplicate project')
current, empty = [], []
for project in projects:
key = _path_key(project.path)
item = inventories[key]
available = tuple(tuple(sheet) for sheet in item['sheets'])
if (available != sheets[key] or not available or len(set(available)) != len(available)
or any(len(sheet) != 2 or not all(isinstance(value, str) and value for value in sheet) for sheet in available)
or item['observation'] not in {'validated_readonly_inventory', 'project_missing'}):
raise ValueError('sheet scope or provenance changed')
components = tuple(ComponentTarget(Path(project.path), **target) for target in item['components'])
if (len({target.key for target in components}) != len(components)
or any((target.schematic_name, target.sheet_number) not in available for target in components)
or any(not isinstance(target.old_value, str) for target in components)
or (item['observation'] == 'project_missing' and components)):
raise ValueError('component inventory changed')
current.extend(components)
for rule in rules:
if not any(target.old_part_number.casefold() == rule.old_part_number.casefold() for target in components):
mode, custom, sync, _ = _rule_command_options(rule, base_mode)
empty.append(InventoryEmptyRule(rule.old_part_number, rule.new_part_number,
(key, *available[0]), mode == 'custom', custom, sync,
str(getattr(rule, 'target_cell', '')), mode))
expanded = []
for rule in rules:
targets = tuple(target for target in current if target.old_part_number.casefold() == rule.old_part_number.casefold())
mode, custom, sync, _ = _rule_command_options(rule, base_mode)
if targets:
expanded.append(TargetRule(rule.old_part_number, rule.new_part_number, targets,
custom_value_enabled=mode == 'custom', custom_value=custom, sync_nc=sync,
target_cell=str(getattr(rule, 'target_cell', '')), value_mode=mode))
expanded.extend(item for item in empty if (item.old_part_number, item.new_part_number)
== (rule.old_part_number, rule.new_part_number))
return tuple(expanded)
except (ValueError, KeyError, TypeError) as error:
raise _error('frozen component identities, provenance or sheet scope changed') from error
def validate_empty_command(root, row):
"""Bind a non-dispatchable no-match row to the frozen read-only inventory."""
from .execution_journal import read_command_rows
from .path_access import internal_path
from .quick_run import _command_text, _decode_vbs_field, _path_key
try:
if row.get('execution_unit') != 'inventory_empty' or row.get('target_selectors') != '':
return False
scope = load(internal_path(root / 'component-scope.json'))
actual_rows = read_command_rows(root / 'command.tsv')
active = {_path_key(item['project_path']) for item in actual_rows}
selected = tuple(item for item in scope['projects'] if _path_key(item['project_path']) in active)
projects = tuple(SimpleNamespace(path=Path(item['project_path'])) for item in selected)
sheets = {_path_key(item.path): tuple(tuple(sheet) for sheet in saved['sheets'])
for item, saved in zip(projects, selected)}
rules = tuple(SimpleNamespace(**source) for source in scope['source_rules'])
expanded = expand(scope, projects, rules, scope['base_value_mode'], sheets)
expected = _command_text('expected', 'expected', projects, expanded, scope['base_value_mode'], sheet_targets=sheets)
expected_rows = tuple({key: _decode_vbs_field(value) for key, value in item.items()}
for item in csv.DictReader(StringIO(expected), delimiter='\t'))
identity = lambda item: {key: value for key, value in item.items() if key not in {'task_id', 'job_id'}}
return row in actual_rows and tuple(map(identity, actual_rows)) == tuple(map(identity, expected_rows))
except (OSError, UnicodeError, ValueError, KeyError, TypeError, TaskCenterError):
return False
@@ -15,10 +15,10 @@ MAX_BUNDLE_BYTES = 32 * 1024 * 1024
MAX_FILES = 512
_BATCH_NAMES = {'session.json', 'supervisor.json', 'request.json', 'result.json',
'business-result.json', 'supervisor.log', 'resource-release.log', 'cancel.json',
'process.json', 'lifecycle.jsonl'}
'process.json', 'lifecycle.jsonl', 'owner-loss.json', 'claim.json', 'force-request.json'}
_QUICK_NAMES = {'private-desktop.json', 'checkpoint.json', 'status.json',
'uncertain.flag', 'resolved-uncertain.flag', 'protection.json', 'cleanup.json',
'project-session.json', 'project-checkpoint.json', 'status.tsv'}
'project-session.json', 'project-checkpoint.json', 'project-read-release.json', 'status.tsv'}
_SECRET_KEY = re.compile(r'(?:password|passwd|(?:client[_-]?)?secret|credentials?|authorization|api[_-]?key|access[_-]?token|refresh[_-]?token|token)', re.I)
_USER_KEY = re.compile(r'(?:user(?:[_-]?name)?|login[_-]?name)', re.I)
_SECRET_TEXT = re.compile(r'''(?ix)(\b(?:password|passwd|(?:client[_-]?)?secret|credentials?|authorization|api[_-]?key|access[_-]?token|refresh[_-]?token|token)\b["']?\s*[=:]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;}]+)''')
@@ -52,23 +52,26 @@ def _scrub_json(value):
def _allowed(parts):
if re.fullmatch(r'cad-dialogs-[a-f0-9]{32}\.json', parts[-1]):
return ((len(parts) == 4 and parts[0] == 'batch-resources' and re.fullmatch(r'generation-\d+', parts[2])) or
any(value in parts for value in ('quick-run', 'quickrun', 'quick-run-history')))
if (len(parts) == 5 and parts[0] == 'tasks' and parts[2] == 'quick-run-history'
and re.fullmatch(r'bom-import-[A-Za-z0-9-]+', parts[3])):
return parts[-1] == 'source-map.json'
if len(parts) == 2 and parts[0] == 'logs':
return bool(re.fullmatch(r'[^/]+\.log(?:\.\d+)?', parts[-1]))
if len(parts) == 3 and parts[0] == 'batch-resources':
return parts[-1] in _BATCH_NAMES
return parts[-1] in _BATCH_NAMES or bool(re.fullmatch(r'manual-dialog-[a-f0-9]{32}\.json', parts[-1]))
if len(parts) >= 5 and parts[0] == 'batch-resources' and parts[2] == 'attempts':
return parts[-1].endswith('.json')
if len(parts) >= 2 and parts[0] == 'attempts':
return parts[-1].endswith('.json')
if len(parts) == 3 and parts[0] == 'tasks':
return bool(re.fullmatch(r'events\.jsonl(?:\.\d+)?', parts[-1]))
if len(parts) >= 2 and parts[0] in {'queue', 'queues', 'task-queues'}:
if len(parts) >= 2 and parts[0] in {'queue', 'queues', 'task-queues', 'workspace-queues'}:
return parts[-1].endswith('.json')
if len(parts) >= 2 and any(value in parts for value in ('quick-run', 'quickrun', 'quick-run-history')):
return parts[-1] in _QUICK_NAMES
return parts[-1] in _QUICK_NAMES or bool(re.fullmatch(r'retained-worker-[a-f0-9]{32}\.json', parts[-1]))
return False
@@ -98,7 +101,7 @@ def export_diagnostic_bundle(data_root, destination: Path) -> Path:
info = entry.lstat()
if stat.S_ISLNK(info.st_mode) or getattr(info, 'st_file_attributes', 0) & 0x400:
manifest['omissions'].append({'path': _scrub_text(relative), 'reason': 'link_or_reparse_point'})
elif base == physical and name not in {'logs', 'batch-resources', 'attempts', 'tasks', 'queue', 'queues', 'task-queues', 'quick-run', 'quick-run-history'}:
elif base == physical and name not in {'logs', 'batch-resources', 'attempts', 'tasks', 'queue', 'queues', 'task-queues', 'workspace-queues', 'quick-run', 'quick-run-history'}:
manifest['omissions'].append({'path': _scrub_text(relative), 'reason': 'outside_allowlist'})
else:
safe_folders.append(name)
@@ -109,6 +109,14 @@ def _only_database_changed(before, after):
return design is not None and before != after and design == _without_runtime_database(after)
def _content_fingerprint(stamp):
if stamp is None:
return None
# Hash every byte on each lookup. Metadata changes can be refreshed, but
# file replacement still invalidates identity even when bytes are equal.
return stamp[0], tuple((row[0], row[1], row[2], row[3], row[-1]) for row in stamp[1])
def _discovery_identity(discovery):
sheets = discovery.sheets
components = getattr(discovery, 'components', ())
@@ -116,7 +124,8 @@ def _discovery_identity(discovery):
raise TaskCenterError('target_identity', '原生采集返回重复图页或位号身份,请核对工程')
return (tuple(sorted(sheets)),
tuple(sorted((sheet, tuple(sorted(parts))) for sheet, parts in discovery.matched_old_parts.items())),
tuple(sorted((row.key, row.refdes, row.old_part_number, row.old_value) for row in components)))
tuple(sorted((row.key, row.refdes, row.old_part_number, row.old_value,
getattr(row, 'actual_part_label', None), getattr(row, 'actual_cell', None)) for row in components)))
class DiscoveryCache:
@@ -158,7 +167,7 @@ class DiscoveryCache:
payload = json.dumps(record['discovery'], ensure_ascii=True, sort_keys=True).encode('utf-8')
if record['payload_sha256'] != hashlib.sha256(payload).hexdigest():
raise ValueError('invalid discovery cache')
if record['project'] != _key(project) or record['fingerprint'] != hashlib.sha256(repr(stamp).encode()).hexdigest():
if record['project'] != _key(project) or record['fingerprint'] != hashlib.sha256(repr(_content_fingerprint(stamp)).encode()).hexdigest():
return None
discovery = decode(record['discovery'])
from .quick_run_protocol import ProjectDiscovery
@@ -180,7 +189,7 @@ class DiscoveryCache:
try:
payload = encode(discovery)
record = {'version': 2, 'project': _key(project),
'fingerprint': hashlib.sha256(repr(stamp).encode()).hexdigest(), 'parts': sorted(requested),
'fingerprint': hashlib.sha256(repr(_content_fingerprint(stamp)).encode()).hexdigest(), 'parts': sorted(requested),
'collect_components': components, 'discovery': payload,
'payload_sha256': hashlib.sha256(json.dumps(payload, ensure_ascii=True, sort_keys=True).encode()).hexdigest()}
record['record_sha256'] = hashlib.sha256(json.dumps(record, ensure_ascii=True, sort_keys=True).encode()).hexdigest()
@@ -191,7 +200,7 @@ class DiscoveryCache:
except (OSError, ValueError, TypeError):
pass # Cache persistence is optional, unlike execution write-ahead proof.
def discover(self, project, parts, collect_components, loader, *, stop_event=None):
def discover(self, project, parts, collect_components, loader, *, stop_event=None, release_idle=None):
with self.lock:
check_cancelled(stop_event)
def fingerprint():
@@ -203,10 +212,10 @@ class DiscoveryCache:
entry = self._entries.pop(key, None) or self._disk_entry(project, before)
if entry is not None:
stamp, covered, has_components, discovery = entry
if (before is not None and before == stamp and requested <= covered
if (before is not None and _content_fingerprint(before) == _content_fingerprint(stamp) and requested <= covered
and (not collect_components or has_components)
and (collect_components or getattr(discovery, 'complete_sheet_manifest', True))):
self._entries[key] = entry
self._entries[key] = (before, covered, has_components, discovery)
check_cancelled(stop_event)
return deepcopy(discovery)
# Fingerprinting is an optimization: an initially unverifiable
@@ -214,6 +223,8 @@ class DiscoveryCache:
if before is None:
discovery = loader()
check_cancelled(stop_event)
if release_idle is not None:
release_idle()
_discovery_identity(discovery)
return discovery
# Native opens may update database session metadata on every read.
@@ -229,6 +240,8 @@ class DiscoveryCache:
check_cancelled(stop_event)
discovery = loader()
check_cancelled(stop_event)
if release_idle is not None:
release_idle()
identity = _discovery_identity(discovery)
after = fingerprint()
if before is not None and before == after:
@@ -14,6 +14,8 @@ _TERMINAL={'saved_ok','no_match','restored_ok','batch_failed','batch_saved_unver
def create_execution_schema(connection):
from .execution_problems import create_problem_schema
create_problem_schema(connection)
connection.execute('''CREATE TABLE IF NOT EXISTS execution_transitions (
transition_id TEXT PRIMARY KEY, task_id TEXT NOT NULL)''')
connection.execute('''CREATE TABLE IF NOT EXISTS execution_baselines (
@@ -72,6 +74,7 @@ class JournalAttempt:
operation_key: str
attempt_id: str
generation: int
job_id: str | None = None
class ExecutionJournal:
@@ -99,7 +102,7 @@ class ExecutionJournal:
ON CONFLICT(task_id) DO UPDATE SET round_id=excluded.round_id,plan_json='[]',
retry_authorized=0,pause_requested=0''',(task_id,round_id))
def authorize_retry(self,task_id):
def authorize_retry(self,task_id,*,operation_keys=None):
with self.store.transaction():
current=self._round(task_id)
if current:
@@ -107,8 +110,131 @@ class ExecutionJournal:
WHERE task_id=? AND round_id=? AND state IN ('prepared','uncertain') LIMIT 1''',
(task_id,current['round_id'])).fetchone()
if unsafe:raise TaskCenterError('quick_run_uncertain','原执行项尚待核验,不能准备重试。')
self.store._connection.execute('DELETE FROM execution_retry_selections WHERE task_id=?',(task_id,))
if operation_keys is not None:
selected=tuple(operation_keys)
if not selected:raise TaskCenterError('problem_retry_scope','重试范围不能为空。')
valid={row[0] for row in self.store._connection.execute("SELECT operation_key FROM execution_operations WHERE task_id=? AND round_id=? AND state='failed'",(task_id,current['round_id']))}
if not set(selected)<=valid:raise TaskCenterError('problem_retry_scope','重试范围不属于原失败项。')
self.store._connection.execute('INSERT INTO execution_retry_selections VALUES (?,?,?)',(task_id,current['round_id'],_json(selected)))
self.store._connection.execute('UPDATE execution_rounds SET retry_authorized=1 WHERE task_id=?',(task_id,))
def has_pending_components(self,task_id):
with self.store._lock:
current=self._round(task_id)
if current is None:return False
rows=self.store._connection.execute("SELECT command_json FROM execution_operations WHERE task_id=? AND round_id=? AND state='pending'",(task_id,current['round_id']))
return any(json.loads(row[0]).get('execution_unit')=='component' for row in rows)
def independent_continuation_ready(self, task_id):
"""Inspect the first pending frozen item; never select a later UID."""
with self.store._lock:
try:
current = self._round(task_id)
if current is None:return False
records = {row['operation_key']: row for row in self.store._connection.execute(
'SELECT operation_key,state,command_json FROM execution_operations WHERE task_id=? AND round_id=?',
(task_id, current['round_id']))}
for key in json.loads(current['plan_json']):
record = records.get(key)
if record is None or record['state'] in {'prepared', 'uncertain'}:return False
if record['state'] == 'pending':
command = json.loads(record['command_json'])
return bool(self.can_continue_component(task_id, command))
return False
except (OSError, ValueError, KeyError, TypeError, AttributeError, TaskCenterError):
return False
def can_continue_component(self,task_id,command):
from .execution_proof import proof_intact
if command.get('execution_unit')!='component' or len(_targets(command))!=1:return False
current=self._round(task_id)
if current is None:return False
baselines = self.expected_baselines(task_id, command['project_path'])
for row in self.store._connection.execute('SELECT * FROM execution_operations WHERE task_id=? AND round_id=?',(task_id,current['round_id'])):
prior=json.loads(row['command_json'])
if prior['project_path']!=command['project_path']:continue
if row['state'] in {'prepared','uncertain'}:return False
if row['state']=='failed':
receipt=json.loads(row['receipt_json'])
proof=receipt.get('proof',{})
if not isinstance(proof, dict):return False
if prior.get('execution_unit')=='inventory_empty' and proof.get('inventory_empty') is True and proof.get('files') and proof_intact(proof):
continue
if prior.get('execution_unit')!='component' or set(_targets(prior))&set(_targets(command)):return False
from .project_session_health import affirmative
identity = {'task_id': task_id, 'round_id': current['round_id'],
'operation_key': row['operation_key'], 'job_id': receipt.get('job_id'),
'project_path': prior['project_path'], 'attempt_id': row['attempt_id'],
'generation': row['generation']}
if not proof_intact(proof) or not affirmative(proof.get('failure_health', {}), identity, baselines=baselines):return False
return True
def _failed_healths(self, task_id, project_path):
from .project_session_health import health_reference
current = self._round(task_id)
if current is None:return ()
key = str(canonical_path(project_path)).casefold()
values = []
for record in self.store._connection.execute('''SELECT command_json,receipt_json FROM execution_operations
WHERE task_id=? AND round_id=? AND state='failed' ''', (task_id, current['round_id'])):
command = json.loads(record['command_json'])
if command['project_path'] != key:continue
health = json.loads(record['receipt_json']).get('proof', {}).get('failure_health', {})
if health_reference(health):values.append(health)
return tuple(values)
def failure_health_references(self, task_id, project_path):
from .project_session_health import health_reference
with self.store._lock:
return tuple(health_reference(value) for value in self._failed_healths(task_id, project_path))
def certify_safe_failure(self, task_id, row, health):
from pathlib import Path
from .project_session_health import native_completion
key = _hash(command_identity(row))
with self.store.transaction():
current = self._round(task_id)
record = self.store._connection.execute('''SELECT * FROM execution_operations
WHERE task_id=? AND round_id=? AND operation_key=?''', (task_id, current['round_id'], key)).fetchone() if current else None
if record is None or record['state'] != 'failed' or row['task_id'] != task_id:
raise TaskCenterError('quick_run_uncertain', '健康证明只能绑定当前轮次已失败的原执行项。')
receipt = json.loads(record['receipt_json'])
if receipt.get('job_id') != row['job_id']:
raise TaskCenterError('quick_run_uncertain', '健康证明任务与原失败回执不一致。')
attempt = JournalAttempt(task_id, current['round_id'], key, record['attempt_id'], record['generation'])
bound = native_completion(Path(self.store.path).parent / 'task-evidence' / task_id,
row, attempt, health, self.expected_baselines(task_id, row['project_path']),
receipt.get('proof', {}).get('native_dispatch', {}))
proof = receipt.setdefault('proof', {'files': []})
proof['failure_health'] = bound
proof.setdefault('files', []).extend(bound['files'])
self.store._connection.execute('''UPDATE execution_operations SET receipt_json=?
WHERE task_id=? AND round_id=? AND operation_key=?''', (_json(receipt), task_id, current['round_id'], key))
def failure_certified(self, task_id, row):
from .project_session_health import affirmative
from .execution_proof import proof_intact
with self.store._lock:
current = self._round(task_id)
if current is None:return False
key = _hash(command_identity(row))
record = self.store._connection.execute('''SELECT * FROM execution_operations
WHERE task_id=? AND round_id=? AND operation_key=?''', (task_id, current['round_id'], key)).fetchone()
if record is None or record['state'] != 'failed':return False
receipt = json.loads(record['receipt_json'])
proof = receipt.get('proof', {})
if not isinstance(proof, dict):return False
identity = {'task_id': task_id, 'round_id': current['round_id'], 'operation_key': key,
'job_id': receipt.get('job_id'), 'project_path': command_identity(row)['project_path'],
'attempt_id': record['attempt_id'], 'generation': record['generation']}
try:
baselines = self.expected_baselines(task_id, row['project_path'])
except TaskCenterError:
return False
return receipt.get('job_id') == row['job_id'] and proof_intact(proof) and affirmative(
proof.get('failure_health', {}), identity, baselines=baselines)
def pause(self,task_id):
with self.store.transaction():
self.store._connection.execute('UPDATE execution_rounds SET pause_requested=1 WHERE task_id=?',(task_id,))
@@ -153,10 +279,20 @@ class ExecutionJournal:
keys=[_hash(identity) for identity in identities]
if not keys or len(keys)!=len(set(keys)):
raise TaskCenterError('quick_run_uncertain','执行计划包含重复或空的逻辑项。')
component_targets=set()
for identity in identities:
if identity.get('execution_unit')!='component':continue
fields=identity.get('target_selectors','').split('\x1f')
targets=_targets(identity)
if len(targets)!=1 or len(fields)!=3 or not all(fields[:2]) or component_targets.intersection(targets):
raise TaskCenterError('quick_run_uncertain','逐位号执行范围重复或身份不完整。')
component_targets.update(targets)
with self.store.transaction():
current=self._round(task_id,create=True)
round_id=current['round_id'];connection=self.store._connection
prior=json.loads(current['plan_json']); retry=bool(current['retry_authorized'])
selection=connection.execute('SELECT keys_json FROM execution_retry_selections WHERE task_id=? AND round_id=?',(task_id,round_id)).fetchone()
retry_keys=set(json.loads(selection[0])) if selection else None
if prior and prior!=keys and not retry:
raise TaskCenterError('quick_run_uncertain','执行计划与本轮已保存回执不一致,请核验原范围。')
restored={}
@@ -187,8 +323,14 @@ class ExecutionJournal:
restored[row['job_id']]=tuple(json.loads(record['receipt_json'])[name] for name in ('native_state','code','message'))
continue
elif record['state']=='failed' and retry:
if retry_keys is not None and key not in retry_keys:
restored[row['job_id']]=tuple(json.loads(record['receipt_json'])[name] for name in ('native_state','code','message'))
continue
connection.execute("UPDATE execution_operations SET state='pending',attempt_id=NULL WHERE task_id=? AND round_id=? AND operation_key=?",(task_id,round_id,key))
continue # The old failed TSV must not cancel explicit retry.
elif record['state']=='failed':
restored[row['job_id']]=tuple(json.loads(record['receipt_json'])[name] for name in ('native_state','code','message'))
continue
outcome=latest.get(row['job_id'])
if outcome and outcome[0] in _TERMINAL:
record=connection.execute('''SELECT * FROM execution_operations
@@ -216,13 +358,16 @@ class ExecutionJournal:
# The current UI owns one CBB per bound task. Legacy unbound
# multi-project API queues retain their existing failure policy.
hold_project=bool(self.store.get_task(task_id).primary_project_id)
if record['state']=='failed' or (hold_project and not importing and self.requires_retry(task_id)):
if record['state']=='failed' or (hold_project and not importing and self.requires_retry(task_id)
and not self.can_continue_component(task_id,command_identity(row))):
raise TaskCenterError('quick_run_retry_required','本工程有失败项,请准备失败项重试;不会重新执行成功项。')
if record['state']!='pending':raise TaskCenterError('quick_run_uncertain','上次尝试尚未核验,禁止再次派发。')
if not importing and row.get('execution_unit')=='component' and not self.can_continue_component(task_id,command_identity(row)):
raise TaskCenterError('quick_run_uncertain','工程有未决尝试或健康证明不足,暂缓独立位号。')
identifier=uuid4().hex;generation=record['generation']+1
self.store._connection.execute('''UPDATE execution_operations SET state='prepared',attempt_id=?,generation=?
WHERE task_id=? AND round_id=? AND operation_key=?''',(identifier,generation,task_id,current['round_id'],key))
return JournalAttempt(task_id,current['round_id'],key,identifier,generation)
return JournalAttempt(task_id,current['round_id'],key,identifier,generation,row['job_id'])
def finish(self,attempt,native_state,code,message,*,progress=None,proof=None):
if native_state not in _TERMINAL:raise TaskCenterError('quick_run_uncertain','不能提交未知的执行结果。')
@@ -240,18 +385,51 @@ class ExecutionJournal:
raise TaskCenterError('quick_run_uncertain','旧尝试的结果不能覆盖当前执行回执。')
command=json.loads(record['command_json'])
receipt={'native_state':native_state,'code':code,'message':message}
# job_id is outside command_identity and must be retained separately
# to bind failure health to this exact dispatch, including rebinding.
health_identity = (proof or {}).get('failure_health', {}).get('identity', {})
if health_identity:
receipt['job_id'] = health_identity.get('job_id')
else:
receipt['job_id'] = getattr(attempt, 'job_id', None)
if proof is not None:
from .execution_proof import proof_intact
if not proof_intact(proof):raise TaskCenterError('quick_run_uncertain','执行证明不完整,不能提交回执。')
receipt['proof']=proof
if not proof_intact(proof):
if state != 'failed' or proof.get('files'):
raise TaskCenterError('quick_run_uncertain','执行证明不完整,不能提交回执。')
else:
receipt['proof']=proof
source_checkpoint = None
if state in _SUCCESS and proof and proof.get('baseline'):
healths = self._failed_healths(attempt.task_id, command['project_path'])
if healths:
from pathlib import Path
from .project_session_health import verified_source_checkpoint, health_reference
project = next((project.path for project in self.store.list_projects(attempt.task_id)
if str(canonical_path(project.path)).casefold() == command['project_path']), None)
if project is None:
raise TaskCenterError('quick_run_uncertain', '已核验源文件检查点缺少绑定的原工程路径。')
# Folded journal identities are comparison keys. Filesystem
# reads must retain the bound project's actual spelling.
source_row = dict(command, task_id=attempt.task_id, job_id=attempt.job_id, project_path=str(project))
source_checkpoint = verified_source_checkpoint(Path(self.store.path).parent / 'task-evidence' / attempt.task_id,
source_row, attempt, proof,
[health_reference(value) for value in healths], excluded_root=healths[0]['source_excluded_root'],
native_source=proof.get('verified_source_health'))
if source_checkpoint:
proof['files'].extend(source_checkpoint['files'])
proof['source_checkpoint'] = source_checkpoint
connection.execute('''UPDATE execution_operations SET state=?,receipt_json=?
WHERE task_id=? AND round_id=? AND operation_key=?''',
(state,_json(receipt),attempt.task_id,attempt.round_id,attempt.operation_key))
from .execution_problems import ExecutionProblems
ExecutionProblems(self.store).record(attempt,command,state,code,message)
if state in _SUCCESS:
if proof and proof.get('baseline'):
baseline=dict(proof['baseline'])
baseline['project_path']=command['project_path']
baseline['files']=proof.get('files',[])
if source_checkpoint:baseline['source_checkpoint'] = source_checkpoint
connection.execute('''INSERT INTO execution_baselines VALUES (?,?,?,?,?,?)
ON CONFLICT(task_id,round_id,project_path,schematic_name,sheet_number)
DO UPDATE SET baseline_json=excluded.baseline_json''',
@@ -264,6 +442,8 @@ class ExecutionJournal:
history_receipt={key:value for key,value in receipt.items() if key!='proof'}
if proof:
history_receipt['proof_file_count']=len(proof.get('files',()))
if 'value_readback' in proof:
history_receipt['value_readback']=proof['value_readback']
HistoryRepository(self.store).append(task_id=attempt.task_id,task_name=task.name,
project_path=command['project_path'],operation='器件替换',state=state,summary=message,
details={**command,**history_receipt,'round_id':attempt.round_id,'attempt_id':attempt.attempt_id,
@@ -0,0 +1,153 @@
"""Durable per-target issues and a single automatic replay allowance."""
import hashlib
import json
from .errors import TaskCenterError
RULE_VERSION = 'safe-prewrite-v1'
RETRYABLE_CODES = frozenset({'cad_attachment_failed', 'worker_timeout_before_write'})
def create_problem_schema(connection):
connection.execute('''CREATE TABLE IF NOT EXISTS execution_problems (
task_id TEXT NOT NULL, round_id TEXT NOT NULL, problem_key TEXT NOT NULL,
operation_key TEXT NOT NULL, classification TEXT NOT NULL, state TEXT NOT NULL,
code TEXT NOT NULL, message TEXT NOT NULL, auto_retries INTEGER NOT NULL DEFAULT 0,
reservation_source TEXT, rule_version TEXT NOT NULL,
PRIMARY KEY(task_id,round_id,problem_key))''')
connection.execute('''CREATE TABLE IF NOT EXISTS execution_retry_selections (
task_id TEXT PRIMARY KEY, round_id TEXT NOT NULL, keys_json TEXT NOT NULL)''')
connection.execute('''CREATE TABLE IF NOT EXISTS execution_problem_passes (
queue_id TEXT NOT NULL, task_id TEXT NOT NULL, round_id TEXT NOT NULL,
generations_json TEXT NOT NULL, state TEXT NOT NULL,
PRIMARY KEY(queue_id,task_id))''')
def problem_key(command):
# Policy/part revisions of the same original target never earn a new budget.
targets = sorted(selector.split('\x1f')[0] for selector in
command.get('target_selectors', '').split('\x1e') if selector)
scope = [command.get(name, '') for name in ('project_path', 'schematic_name', 'sheet_number')]
scope.append(targets or ['all', command.get('old_part', '')])
return hashlib.sha256(json.dumps(scope, ensure_ascii=False).encode('utf-8')).hexdigest()
class ExecutionProblems:
def __init__(self, store):
self.store = store
def record(self, attempt, command, state, code, message):
key = problem_key(command)
if state in {'verified', 'restored', 'no_match'}:
self.store._connection.execute('''UPDATE execution_problems SET state='resolved'
WHERE task_id=? AND round_id=? AND problem_key=?''',
(attempt.task_id, attempt.round_id, key))
return
category = ('uncertain' if state == 'uncertain' else
'retryable' if code in RETRYABLE_CODES else 'manual')
self.store._connection.execute('''INSERT INTO execution_problems
(task_id,round_id,problem_key,operation_key,classification,state,code,message,rule_version)
VALUES (?,?,?,?,?,'open',?,?,?)
ON CONFLICT(task_id,round_id,problem_key) DO UPDATE SET
operation_key=excluded.operation_key,classification=excluded.classification,
state='open',code=excluded.code,message=excluded.message''',
(attempt.task_id, attempt.round_id, key, attempt.operation_key, category, code, message, RULE_VERSION))
def list(self, task_id):
with self.store._lock:
return tuple(dict(row) for row in self.store._connection.execute('''SELECT p.*
FROM execution_problems p JOIN execution_rounds r
ON p.task_id=r.task_id AND p.round_id=r.round_id WHERE p.task_id=? ORDER BY p.rowid''', (task_id,)))
def overview(self, task_id):
"""Project the current frozen plan, including items with no attempt yet."""
with self.store._lock:
current = self.store._connection.execute(
'SELECT round_id FROM execution_rounds WHERE task_id=?', (task_id,)).fetchone()
rows = self.store._connection.execute('''SELECT o.*,p.problem_key,p.classification,
p.state AS problem_state,p.code,p.message,p.auto_retries,p.rule_version
FROM execution_operations o LEFT JOIN execution_problems p
ON p.task_id=o.task_id AND p.round_id=o.round_id AND p.operation_key=o.operation_key
WHERE o.task_id=? AND o.round_id=? ORDER BY o.rowid''',
(task_id, current[0])).fetchall() if current else ()
blocked = any(row['state'] in {'pending', 'prepared', 'uncertain'} for row in rows)
items = []
for row in rows:
if row['state'] == 'superseded' or (not row['problem_key'] and row['state'] not in
{'pending', 'prepared', 'uncertain', 'failed'}):
continue
command = json.loads(row['command_json'])
targets = [selector.split('\x1f') for selector in
command.get('target_selectors', '').split('\x1e') if selector]
item = {key: row[key] for key in ('operation_key', 'generation', 'state', 'classification',
'problem_state', 'code', 'message', 'rule_version')}
item.update({key: command.get(key, '') for key in
('project_path', 'schematic_name', 'sheet_number', 'old_part', 'new_part')})
item.update(uid=', '.join(target[0] for target in targets),
refdes=', '.join(target[1] for target in targets if len(target) > 1),
can_retry=row['state'] == 'failed' and not blocked,
auto_retries_remaining=int(row['classification'] == 'retryable' and
row['state'] == 'failed' and not row['auto_retries']))
items.append(item)
return dict(round_id=current[0] if current else None, items=tuple(items),
failed=sum(item['state'] == 'failed' for item in items),
held=sum(item['state'] == 'pending' for item in items),
uncertain=sum(item['state'] in {'prepared', 'uncertain'} for item in items),
resolved=sum(item['problem_state'] == 'resolved' for item in items))
def validate_selection(self, task_id, keys, round_id, generations):
# Caller holds the preparation transaction, so validation and reset are atomic.
overview = self.overview(task_id)
selected = set(keys or ())
allowed = {item['operation_key']: item['generation'] for item in overview['items'] if item['can_retry']}
if (overview['round_id'] != round_id or not selected or not selected <= allowed.keys()
or generations != {key: allowed[key] for key in selected}):
raise TaskCenterError('problem_retry_scope',
'所选问题的轮次、状态或尝试代次已变化,或仍有待执行/待核验项;请刷新问题列表。')
def reserve(self, task_id, *, operation_keys=None, source='problems'):
if source not in {'problems', 'dsh'}:
raise TaskCenterError('problem_retry_scope', '未知自动重试来源。')
with self.store.transaction():
current = self.store._connection.execute('SELECT round_id FROM execution_rounds WHERE task_id=?', (task_id,)).fetchone()
if current is None:
return ()
round_id = current[0]
# Finish the primary pass first. A retained unknown write cannot be retried.
unfinished = self.store._connection.execute('''SELECT 1 FROM execution_operations
WHERE task_id=? AND round_id=? AND state IN ('pending','prepared','uncertain') LIMIT 1''', (task_id, round_id)).fetchone()
if unfinished:
return ()
requested = set(operation_keys) if operation_keys is not None else None
selection = self.store._connection.execute('''SELECT keys_json FROM execution_retry_selections
WHERE task_id=? AND round_id=?''', (task_id, round_id)).fetchone()
if selection is not None:
frozen = set(json.loads(selection[0]))
# An explicit manual scope also bounds the later automatic pass
# and DSH. Otherwise they could replay unselected old failures.
requested = frozen if requested is None else requested & frozen
rows = self.store._connection.execute('''SELECT p.problem_key,p.operation_key,o.command_json
FROM execution_problems p JOIN execution_operations o
ON p.task_id=o.task_id AND p.round_id=o.round_id AND p.operation_key=o.operation_key
WHERE p.task_id=? AND p.round_id=? AND p.classification='retryable'
AND p.state='open' AND p.auto_retries=0 AND o.state='failed' ORDER BY p.rowid''', (task_id, round_id)).fetchall()
keys = []
for row in rows:
if json.loads(row['command_json']).get('execution_unit') != 'component':
continue
if requested is not None and row['operation_key'] not in requested:
continue
self.store._connection.execute('''UPDATE execution_problems SET auto_retries=1,
reservation_source=? WHERE task_id=? AND round_id=? AND problem_key=? AND auto_retries=0''',
(source, task_id, round_id, row['problem_key']))
keys.append(row['operation_key'])
return tuple(keys)
def problem_projection(problems):
issues = tuple(row for row in problems if row['state'] != 'resolved')
return {'status': 'completed_with_issues' if issues else 'completed',
'failed': sum(row['classification'] != 'uncertain' for row in issues),
'uncertain': sum(row['classification'] == 'uncertain' for row in issues),
'resolved': sum(row['state'] == 'resolved' for row in problems), 'items': issues}
@@ -25,9 +25,19 @@ def capture_result(data_root,root,row,outcome,*,strict=False,persist=True):
paths=[]
try:
_safe_run_token(row['job_id'])
if row.get('execution_unit') == 'inventory_empty':
from .component_scope import validate_empty_command
if state != 'batch_skipped' or not validate_empty_command(root, row):
raise ValueError('empty inventory command is not certified')
manifest = internal_path(root / 'component-scope.json')
checked_manifest = manifest.read_bytes()
paths.append(manifest)
proof['inventory_empty'] = True
if strict and state in {'saved_ok','no_match'} and code not in {'batch_closed','session_verified'}:
raise ValueError('save/close was not verified')
checked={}
if row.get('execution_unit') == 'inventory_empty':
checked[manifest] = checked_manifest
baseline=internal_path(root/f'post-state-{row["job_id"]}.tsv')
if baseline.is_file():
checked[baseline]=baseline.read_bytes()
@@ -11,6 +11,7 @@ from .target_plan import ComponentTarget, ProjectIdentityResolver
HEADER = ("project_path", "schematic_name", "sheet_number", "uid", "refdes",
"old_part", "old_value")
EFFECTIVE_HEADER = HEADER + ('actual_part_label', 'actual_cell')
def validate_target_inventory(project_path, rules, components):
@@ -25,7 +26,9 @@ def validate_target_inventory(project_path, rules, components):
actual = current.get(identities.target(target))
if (actual is None or actual.refdes != target.refdes
or actual.old_part_number.casefold() != target.old_part_number.casefold()
or actual.old_value != target.old_value):
or actual.old_value != target.old_value
or any(getattr(target, name) is not None and getattr(actual, name) != getattr(target, name)
for name in ('actual_part_label', 'actual_cell'))):
raise TaskCenterError('target_identity',
f'位号计划与当前工程不一致,请重新采集:{target.refdes}(UID={target.uid})')
@@ -36,7 +39,8 @@ def read_component_inventory(path: Path, project_path: Path,
try:
lines = Path(path).read_text(encoding="utf-8-sig").splitlines()
if not lines or tuple(lines[0].split("\t")) != HEADER:
header = tuple(lines[0].split('\t')) if lines else ()
if header not in {HEADER, EFFECTIVE_HEADER}:
raise ValueError("component inventory header changed")
result: list[ComponentTarget] = []
seen: set[tuple[str, str, str]] = set()
@@ -44,15 +48,15 @@ def read_component_inventory(path: Path, project_path: Path,
if not line:
continue
fields = tuple(_decode_vbs_field(field) for field in line.split("\t"))
if len(fields) != len(HEADER):
if len(fields) != len(header):
raise ValueError("component inventory row is malformed")
project, schematic, sheet, uid, refdes, old_part, old_value = fields
project, schematic, sheet, uid, refdes, old_part, old_value = fields[:7]
if (_path_key(project) != _path_key(project_path) or (schematic, sheet) not in sheets or
not all((uid, refdes, old_part)) or (schematic, sheet, uid) in seen):
raise ValueError("component inventory identity is invalid")
seen.add((schematic, sheet, uid))
result.append(ComponentTarget(Path(project_path), schematic, sheet, uid, refdes,
old_part, old_value))
old_part, old_value, *fields[7:]))
return tuple(result)
except (OSError, UnicodeError, ValueError) as error:
raise TaskCenterError("target_inventory", str(error)) from error
@@ -7,12 +7,16 @@ import subprocess
import sys
import time
from traceback import clear_frames
from threading import Event, Thread
from uuid import uuid4
from .cad_identity import CadBinding, current_desktop_name, verify_application, project_file_path
from .isolated_desktop import PrivateDesktop
from .worker_monitor import WorkerMonitorError
from .path_access import internal_path, canonical_path, retry_sharing_violation
from .cad_dialogs import CadDialogGuard
RETAINED_CAD_SESSIONS = {}
class PrivateCadStartupError(WorkerMonitorError):
@@ -87,7 +91,7 @@ def _designer_executable():
class IsolatedCadSession:
"""The supervisor never attaches to COM on the user's input desktop."""
def __init__(self, root, *, abort_event=None, desktop=None, stop_control=None):
def __init__(self, root, *, abort_event=None, desktop=None, stop_control=None, read_only=False):
self.root = canonical_path(root)
self.token = uuid4().hex
self.borrowed_desktop = desktop is not None
@@ -97,7 +101,13 @@ class IsolatedCadSession:
self.started = time.monotonic()
self.abort_event = abort_event
self.stop_control = stop_control
self.record = {'desktop': self.desktop.name, 'token': self.token, 'state': 'starting'}
self.read_only = read_only
self.record = {'desktop': self.desktop.name, 'token': self.token, 'state': 'starting',
'read_only': read_only}
self._dialogs = None
self._dialog_monitor_error = ''
self._dialog_stop = Event()
self._dialog_thread = None
def _record(self, **values):
self.record.update(values)
@@ -114,11 +124,19 @@ class IsolatedCadSession:
_replace_record(pending, archived)
def __enter__(self):
if RETAINED_CAD_SESSIONS:
raise WorkerMonitorError('an owned CAD session is retained for manual reconciliation')
try:
self._check_abort()
self.desktop.__enter__()
self.cad = self.desktop.start_process((str(_designer_executable()),))
self._record(cad_pid=self.cad.pid)
publish = getattr(self.desktop, 'register_cad_process', None)
if publish is not None:
publish(self.cad, self.token)
self._dialogs = CadDialogGuard(self.desktop, self.cad,
self.root / ('cad-dialogs-' + self.token + '.json'), self.token)
from .batch_resources import process_identity
self._record(cad_pid=self.cad.pid, cad_process=process_identity(self.cad))
bootstrap = self.root / ('cad-binding-' + self.token + '.json')
environment = dict(os.environ, DXPART_DESKTOP=self.desktop.name,
DXPART_CAD_PID=str(self.cad.pid), DXPART_SESSION_TOKEN=self.token)
@@ -129,16 +147,18 @@ class IsolatedCadSession:
deadline = time.monotonic() + 120
while probe.poll() is None:
self._check_abort()
self._poll_dialogs('startup')
cad_exit = self.cad.poll()
if cad_exit is not None:
raise WorkerMonitorError(f'owned private CAD exited during startup: exit code {cad_exit}')
if time.monotonic() >= deadline:
raise WorkerMonitorError('private CAD bootstrap timed out')
raise WorkerMonitorError('private CAD bootstrap timed out' + self._dialog_description())
time.sleep(0.05)
code = probe.poll()
if code:
failure_type = CadIdentityConflict if code == PRIVATE_CAD_IDENTITY_EXIT_CODE else WorkerMonitorError
raise failure_type('private CAD startup failed: ' + probe.stderr.read().decode('utf-8', errors='replace'))
self._poll_dialogs('startup')
finally:
probe.close()
try:
@@ -151,8 +171,10 @@ class IsolatedCadSession:
raise CadIdentityConflict('private CAD bootstrap identity evidence is invalid: ' + str(failure)) from failure
self.binding = binding
self._record(state='ready', guid=self.binding.guid, startup_seconds=time.monotonic() - self.started)
self._start_dialog_monitor()
return self
except Exception as error:
self._stop_dialog_monitor()
try:
self.desktop.close()
except Exception as failure:
@@ -167,6 +189,54 @@ class IsolatedCadSession:
if self.abort_event is not None and self.abort_event.is_set():
raise WorkerMonitorError('private CAD startup was cancelled before execution')
def _start_dialog_monitor(self):
if getattr(self.desktop, 'inspect_dialogs', None) is None:
return
def monitor():
while not self._dialog_stop.wait(.2):
self._poll_dialogs('running')
self._dialog_thread = Thread(target=monitor, name='owned-cad-dialogs', daemon=True)
self._dialog_thread.start()
def _stop_dialog_monitor(self):
self._dialog_stop.set()
if self._dialog_thread is not None:
self._dialog_thread.join(3)
if self._dialog_thread.is_alive():
self._dialog_monitor_error = 'CAD dialog monitor did not stop within its budget'
def _poll_dialogs(self, phase):
if self._dialogs is None:
return
try:
self._dialogs.poll(phase)
except Exception as error:
self._dialog_monitor_error = str(error)
self.record['dialog_supervision'] = dict(self._dialogs.summary(), monitor_error=self._dialog_monitor_error)
if phase in {'startup', 'checkpoint'} and self._dialogs.failure:
raise WorkerMonitorError(self._dialogs.failure + self._dialog_description())
def _dialog_description(self):
if self._dialogs is None or not self._dialogs.records:
return ''
summary = self._dialogs.summary()
titles = ' / '.join(summary['blocking_titles']) or '已记录弹窗'
return f';CAD 弹窗:{titles};详情:{summary["evidence_path"]}'
def _wait_process(self, process, timeout, phase):
if getattr(self.desktop, 'inspect_dialogs', None) is None:
return process.wait(timeout=timeout)
deadline = time.monotonic() + timeout
while True:
self._poll_dialogs(phase)
remaining = deadline - time.monotonic()
if remaining <= 0:
raise subprocess.TimeoutExpired(getattr(process, 'args', phase), timeout)
try:
return process.wait(timeout=min(.25, remaining))
except subprocess.TimeoutExpired:
pass
def start_worker(self, command, *, extra_environment=None, **options):
if self.binding is None or self.cad.poll() is not None:
raise WorkerMonitorError('owned private CAD is unavailable')
@@ -187,7 +257,7 @@ class IsolatedCadSession:
process = self.start_worker(_helper_command('checkpoint', evidence, self.cad.pid),
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
code = process.wait(timeout=20)
code = self._wait_process(process, 20, 'checkpoint')
if code:
failure_type = CadIdentityConflict if code == PRIVATE_CAD_IDENTITY_EXIT_CODE else WorkerMonitorError
raise failure_type('project close checkpoint failed: ' +
@@ -206,6 +276,9 @@ class IsolatedCadSession:
return result
def __exit__(self, error_type, error, traceback):
if self.read_only:
return self._close_read_only()
self._stop_dialog_monitor()
closing_started = time.monotonic()
cleanup_errors = []
diagnostic_errors = []
@@ -250,37 +323,56 @@ class IsolatedCadSession:
if self.cad is not None and self.cad.poll() is not None:
raise WorkerMonitorError('owned CAD exited before the authorized quit request')
if self.cad is not None and self.binding is not None:
self._poll_dialogs('closing')
closing = self.desktop.start_process(_helper_command('quit', self.root / 'private-desktop.json', self.cad.pid),
env=_child_environment(self.binding.environment()), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
quit_code = closing.wait(timeout=20)
quit_code = self._wait_process(closing, 20, 'closing')
exit_codes['quit_helper_exit_code'] = quit_code
if quit_code:
raise WorkerMonitorError('owned CAD refused orderly exit: ' + closing.stderr.read().decode('utf-8', errors='replace'))
cad_code = self.cad.wait(timeout=15)
cad_code = self._wait_process(self.cad, 15, 'closing')
exit_codes['cad_exit_code'] = cad_code
if cad_code != 0:
raise WorkerMonitorError('owned CAD returned a nonzero exit code after quit')
self.record['orderly_shutdown'] = True
except Exception as failure:
remember('orderly_shutdown', failure)
remember('orderly_shutdown', WorkerMonitorError(str(failure) + self._dialog_description())
if self._dialog_description() else failure)
finally:
if self._dialogs is not None and (self._dialogs.failure or self._dialog_monitor_error):
remember('cad_dialog', WorkerMonitorError(
(self._dialogs.failure or self._dialog_monitor_error) + self._dialog_description()))
if error is not None or failures:
# Evidence failure must never prevent the identity-checked Quit
# above or release of the handles we own below.
persist_uncertain()
if self.stop_control is not None and cleanup_errors and self.cad is not None:
if self.cad is not None:
cad_running = True
try:
cad_running = self.cad.poll() is None
from .read_recovery import process_tree_exited
cad_running = not all(process_tree_exited(process)
for process in self._owned_processes(closing))
except Exception as failure:
remember('cad_exit_check', failure)
if cad_running:
if not cleanup_errors:
remember('owned_tree_active', WorkerMonitorError('owned processes remain after orderly Quit'))
persist_uncertain()
from .stop_control import StopControl
if not isinstance(self.stop_control, StopControl):
self._retain_for_manual(closing)
raise WorkerMonitorError('owned CAD is still running; handles retained until explicit force or exit')
# A refused/timed-out Quit may still be saving or closing.
# Keep both CAD and its helper owned and alive until the
# interactive caller confirms force, including ordinary stop.
# caller confirms force or both retained processes exit.
from .stop_control import wait_for_resolution
def owned_processes_exited():
self._poll_dialogs('closing')
from .read_recovery import process_tree_exited
return all(process_tree_exited(process) for process in self._owned_processes(closing))
try:
wait_for_resolution(self.stop_control, self.root, failure_message())
wait_for_resolution(self.stop_control, self.root, failure_message(),
resolved=owned_processes_exited)
except WorkerMonitorError as failure:
force_event = getattr(self.stop_control, 'force_event', None)
if force_event is None or not force_event.is_set():
@@ -293,6 +385,7 @@ class IsolatedCadSession:
remember('quit_helper_release', failure)
try:
self.desktop.close()
RETAINED_CAD_SESSIONS.pop(str(self.root), None)
except Exception as failure:
remember('desktop_release', failure)
desktop_cleanup = getattr(self.desktop, 'cleanup_record', None) or {}
@@ -317,6 +410,40 @@ class IsolatedCadSession:
if failures:
raise WorkerMonitorError('private CAD cleanup requires reconciliation: ' + failure_message()) from failures[0]
def _owned_processes(self, closing=None):
processes = list(getattr(self.desktop, '_processes', getattr(self.desktop, 'processes', ())))
for process in (*getattr(self, '_retained_processes', ()), self.cad, closing):
if process is not None and not any(item is process for item in processes):
processes.append(process)
return processes
def _retain_for_manual(self, closing):
from .batch_resources import process_identity
processes = self._owned_processes(closing)
self._retained_processes = processes
if getattr(self.desktop, 'owner', None) is None:
RETAINED_CAD_SESSIONS[str(self.root)] = self
self._record(state='uncertain', retained_for_manual=True,
retained_processes=[process_identity(process) for process in processes])
def _close_read_only(self):
"""Whole-generation cleanup is allowed only by admitted read provenance."""
self._stop_dialog_monitor()
started = time.monotonic()
# Record the authority and exact ownership before any terminate-capable
# handle close. A failed evidence write retains the session for retry.
self._record(state='read_only_releasing', read_only_cleanup_authorized=True,
cad_pid=getattr(self.cad, 'pid', None))
try:
self.desktop.close()
except Exception as error:
self._record(state='read_only_release_pending', clean=False, cleanup_error=str(error))
raise WorkerMonitorError('read-only generation release was not confirmed: ' + str(error)) from error
self._record(state='session_closed' if self.borrowed_desktop else 'released',
clean=True, read_only_released=True, desktop_retained_by_batch=self.borrowed_desktop,
shutdown_seconds=time.monotonic() - started,
desktop_cleanup=getattr(self.desktop, 'cleanup_record', None))
def _uncertain(self, message, **details):
from .quick_run import _write_uncertain_flag
_write_uncertain_flag(self.root / 'uncertain.flag', 'private_desktop: ' + message)
@@ -329,7 +456,7 @@ def run_isolated_process(command, timeout, *, abort_event=None, cooperative_abor
return runtime.run_worker(command, timeout, abort_event=abort_event,
cooperative_abort=cooperative_abort)
try:
with IsolatedCadSession(Path(command[3]), abort_event=abort_event) as session:
with IsolatedCadSession(Path(command[3]), abort_event=abort_event, read_only=cooperative_abort) as session:
return run_monitored_process(command, timeout, abort_event=abort_event, process_factory=session.start_worker,
**({'cooperative_abort': True} if cooperative_abort else {}))
except CadIdentityConflict:
@@ -345,6 +345,17 @@ class _Win32Process:
self.returncode = self._process_api.GetExitCodeProcess(self.handle)
return self.returncode
def tree_exited(self):
if self.poll() is None:
return False
if self.job is not None and self.job_assigned:
active = self._job_api.QueryInformationJobObject(
self.job, self._job_api.JobObjectBasicAccountingInformation)['ActiveProcesses']
if active:
return False
return all(self._event_api.WaitForSingleObject(handle, 0) == 0
for handle in self._descendant_handles)
def wait(self, timeout=None):
if self.returncode is not None:
return self.returncode
@@ -536,6 +547,26 @@ class PrivateDesktop:
def __exit__(self, *_exc: object) -> None:
self.close()
def inspect_dialogs(self, pid):
from .cad_dialogs import inspect_owned_dialogs
if self._handle is None or not any(process.pid == pid and process.poll() is None for process in self._processes):
return ()
return inspect_owned_dialogs(self._api, self.name, pid)
def acknowledge_dialog(self, dialog):
from .cad_dialogs import acknowledge_owned_dialog
pid = dialog['pid']
if self._handle is None or not any(process.pid == pid and process.poll() is None for process in self._processes):
raise TaskCenterError('private_desktop', 'dialog process is no longer owned and alive')
acknowledge_owned_dialog(self._api, self.name, pid, dialog)
def manual_dialog_action(self, dialog, button_hwnd):
from .cad_dialogs import manually_act_on_owned_dialog
pid = dialog['pid']
if self._handle is None or not any(process.pid == pid and process.poll() is None for process in self._processes):
raise TaskCenterError('private_desktop', 'dialog process is no longer owned and alive')
manually_act_on_owned_dialog(self._api, self.name, pid, dialog, button_hwnd)
def _create(self) -> None:
if os.name != "nt" and self._api is None:
return
@@ -14,7 +14,7 @@ class NativeInventoryUnsupported(ValueError):
_UID = re.compile(r'^\$\d+I\d+$')
_PROPERTY = re.compile(r'\tProp (Ref Designator|Part Number|Value)(?: (.*))?')
_PROPERTY = re.compile(r'\tProp (Ref Designator|Part Number|Value|Part Label|Cell Name)(?: (.*))?')
def read_native_text(path: Path) -> str:
@@ -109,7 +109,8 @@ def _parse_scope(text, requested, effective, inconsistent_refs):
ref, part = values.get('Ref Designator', ''), values['Part Number']
if not ref or 'Ref Designator' not in attributes:
raise NativeInventoryUnsupported('全工程报告中的请求物料缺少位号')
target = block, sheet, uid, ref, part, values.get('Value', '')
target = (block, sheet, uid, ref, part, values.get('Value', ''),
values.get('Part Label'), values.get('Cell Name'))
if target in targets:
raise NativeInventoryUnsupported('全工程报告含重复器件身份')
targets.add(target)
@@ -0,0 +1,91 @@
"""Run only reserved safe issues, after all runnable primary items finish."""
from dataclasses import dataclass
import json
from .errors import TaskCenterError
@dataclass(frozen=True)
class ProblemPassResult:
results: dict
blocked_task_id: str | None = None
error_code: str = ''
message: str = ''
def run_problem_pass(service, task_ids, queue_id, *, stop_event, runtime):
results = {}
for task_id in task_ids:
if stop_event.is_set():
break
try:
result = _run_project_problems(service, task_id, queue_id, stop_event=stop_event, runtime=runtime)
except TaskCenterError as error:
if error.code not in {'problem_retry_scope', 'quick_run_uncertain'}:
raise # Resource and storage failures retain their existing escalation.
return ProblemPassResult(results, task_id, error.code, error.message)
if result is not None:
results[task_id] = result
if result.paused:
break
return ProblemPassResult(results)
def _run_project_problems(service, task_id, queue_id, *, stop_event, runtime):
store = service._store
child = service.for_project_task(task_id)
if child.has_interrupted_quick_run(task_id):
raise TaskCenterError('quick_run_uncertain', '问题项上次尝试尚未核验,禁止自动重放。')
with store.transaction():
record = store._connection.execute('SELECT * FROM execution_problem_passes WHERE queue_id=? AND task_id=?',
(queue_id, task_id)).fetchone()
current = store._connection.execute('SELECT round_id FROM execution_rounds WHERE task_id=?', (task_id,)).fetchone()
if record is None:
keys = child.reserve_problem_retry(task_id, source='problems')
if not keys:
return None
generations = {row['operation_key']: row['generation'] for row in store._connection.execute(
'SELECT operation_key,generation FROM execution_operations WHERE task_id=? AND round_id=?',
(task_id, current[0])) if row['operation_key'] in keys}
store._connection.execute('INSERT INTO execution_problem_passes VALUES (?,?,?,?,?)',
(queue_id, task_id, current[0], json.dumps(generations, sort_keys=True), 'reserved'))
record = store._connection.execute('SELECT * FROM execution_problem_passes WHERE queue_id=? AND task_id=?',
(queue_id, task_id)).fetchone()
if current is None or current[0] != record['round_id']:
raise TaskCenterError('problem_retry_scope', '问题轮次与原执行轮次不一致。')
if record['state'] == 'finished':
return None
original = json.loads(record['generations_json'])
selection = store._connection.execute('''SELECT keys_json FROM execution_retry_selections
WHERE task_id=? AND round_id=?''', (task_id, current[0])).fetchone()
if selection is not None:
# A resumed reservation can predate a newer manual selection.
# Consuming it must obey the same scope as a fresh reservation.
allowed = set(json.loads(selection[0]))
original = {key: generation for key, generation in original.items() if key in allowed}
states = {row['operation_key']: row for row in store._connection.execute(
'SELECT operation_key,generation,state FROM execution_operations WHERE task_id=? AND round_id=?',
(task_id, current[0])) if row['operation_key'] in original}
if set(states) != set(original):
raise TaskCenterError('problem_retry_scope', '原问题项已变化,不能扩大自动重试范围。')
if any(row['state'] in {'prepared', 'uncertain'} for row in states.values()):
raise TaskCenterError('quick_run_uncertain', '问题项上次尝试尚未核验,禁止自动重放。')
prepare_keys = tuple(key for key, row in states.items()
if row['state'] == 'failed' and row['generation'] == original[key])
if prepare_keys:
child.prepare_failed_quick_run(task_id, runtime=runtime, operation_keys=prepare_keys)
pending = bool(prepare_keys) or any(row['state'] == 'pending' for row in states.values())
result = None
if pending and not stop_event.is_set():
progress = child.quick_run_progress(task_id)
task = child.get_task(task_id)
expected = (str(progress.next_project_path), progress.next_old_part_number,
progress.next_new_part_number, 'part_label' if task.copy_part_number_to_value else 'preserve')
result = child.execute_quick_run_queue(task_id, expected_item=expected,
stop_event=stop_event, runtime=runtime)
if result.paused:
return result
if not stop_event.is_set():
with store.transaction():
store._connection.execute("UPDATE execution_problem_passes SET state='finished' WHERE queue_id=? AND task_id=?", (queue_id, task_id))
return result
@@ -86,11 +86,19 @@ class ProjectSessionWorker:
while True:
if self._done.is_set():
if self._error is not None:
from .worker_monitor import WorkerMonitorSafeTimeout
if isinstance(self._error, WorkerMonitorSafeTimeout) and self._error.prewrite_cleanup_confirmed:
self._failure_delivered = True
raise self._error
if self._result.returncode == 0:
raise WorkerMonitorError('project session exited before authorized closing')
self._failure_delivered = True
return self._result
stop_control = getattr(self.runtime, 'stop_event', None)
if stop_control is not None and stop_control.is_set() and not self._abort.is_set():
# A step cannot return to the queue's stop check before its checkpoint.
# The owned monitor still decides whether the current stage can stop.
self._abort.set()
try:
fields = (self.root / 'project-session-result.tsv').read_text(encoding='utf-8-sig').strip().split('\t')
except (FileNotFoundError, PermissionError):
@@ -136,8 +144,11 @@ class ProjectSessionWorker:
raise WorkerMonitorError('owned project did not acknowledge session closing')
self._closed = True
if self._error is not None:
raise self._error
if self._result.returncode != 0 and not self._failure_delivered:
from .worker_monitor import WorkerMonitorSafeTimeout
if not (self._failure_delivered and isinstance(self._error, WorkerMonitorSafeTimeout)
and self._error.prewrite_cleanup_confirmed):
raise self._error
if not self._failure_delivered and self._result.returncode != 0:
raise WorkerMonitorError('owned project session did not close cleanly: ' + self._result.stderr)
finally:
if self._done.is_set():
@@ -0,0 +1,235 @@
"""Affirmative, immutable failure health bound to one journal attempt."""
import hashlib
import json
from pathlib import Path
from uuid import uuid4
from .batch_resources import write_record
from .errors import TaskCenterError
from .path_access import canonical_path, internal_path
SOURCE_DIGEST_ALGORITHM = 'sha256-project-fingerprint-repr-v1'
def _source_digest(value):
from .discovery_cache import project_fingerprint
if value.get('source_digest_algorithm') != SOURCE_DIGEST_ALGORITHM:
return None
if not all(Path(value[key]).is_absolute() for key in ('source_project_path', 'source_excluded_root')):
return None
project, root = canonical_path(value['source_project_path']), canonical_path(value['source_excluded_root'])
stamp = project_fingerprint(project, root)
return hashlib.sha256(repr(stamp).encode()).hexdigest() if stamp is not None else None
def _source_parameters(project, root):
return {'source_project_path': str(canonical_path(project)),
'source_excluded_root': str(canonical_path(root)), 'source_digest_algorithm': SOURCE_DIGEST_ALGORITHM}
def _intact_certificate(value):
from .execution_proof import proof_intact
return (isinstance(value, dict) and isinstance(value.get('files'), list) and bool(value['files']) and proof_intact(value)
and json.loads(internal_path(value['files'][0]['path']).read_text(encoding='utf-8')) ==
{key: item for key, item in value.items() if key != 'files'})
def health_reference(health):
try:
return {'identity': health['identity'], 'certificate_sha256': health['files'][0]['sha256']} if _intact_certificate(health) else None
except (OSError, ValueError, KeyError, TypeError):
return None
def _identity(row, attempt):
from .execution_journal import command_identity, _hash
return {'task_id': row['task_id'], 'round_id': attempt.round_id,
'operation_key': _hash(command_identity(row)), 'job_id': row['job_id'],
'project_path': str(canonical_path(row['project_path'])).casefold(),
'attempt_id': attempt.attempt_id, 'generation': attempt.generation}
def _persist(data_root, value, evidence=()):
destination = internal_path(Path(data_root) / 'execution-proof' / uuid4().hex)
files = []
for number, (path, digest) in enumerate(evidence):
data = internal_path(path).read_bytes()
if hashlib.sha256(data).hexdigest() != digest:
raise TaskCenterError('quick_run_uncertain', '工程健康证明文件已变化。')
target = destination / (str(number) + '-' + Path(path).name)
target.parent.mkdir(parents=True, exist_ok=True)
with target.open('xb') as stream:
import os
stream.write(data); stream.flush(); os.fsync(stream.fileno())
files.append({'path': str(canonical_path(target)), 'sha256': digest})
certificate = destination / 'completion.json'
write_record(certificate, value)
files.insert(0, {'path': str(canonical_path(certificate)),
'sha256': hashlib.sha256(certificate.read_bytes()).hexdigest()})
return dict(value, files=files)
def synchronous_completion(data_root, row, attempt, outcome, before, *, runtime=None):
from .discovery_cache import project_fingerprint
from .batch_resources import LIVE_RESOURCES
from .isolated_cad import RETAINED_CAD_SESSIONS
from .execution_journal import command_identity
absent = runtime is None or (hasattr(runtime, 'desktop') and hasattr(runtime, 'cad')
and runtime.desktop is None and runtime.cad is None)
root = canonical_path(data_root)
def related(path):
return path.is_relative_to(root) or root.is_relative_to(path)
absent = absent and not any(related(session.root) for session in RETAINED_CAD_SESSIONS.values()) and not any(
owner.desktop is not None or owner.cad is not None for owner in LIVE_RESOURCES.values() if related(owner.root))
value = {'version': 1, 'identity': _identity(row, attempt), 'command': command_identity(row), 'outcome': list(outcome),
'kind': 'synchronous_completion', 'resources_released': absent,
'project_closed': absent, 'no_mutation': False, 'source_unchanged': False}
if outcome[0] == 'batch_failed':
after = project_fingerprint(canonical_path(row['project_path']), canonical_path(data_root))
if before is None or after is None or before != after or not absent:
raise TaskCenterError('quick_run_uncertain', '失败后无法证明工程源文件未变化且执行会话已释放。')
value.update(no_mutation=True, source_unchanged=True,
source_sha256=hashlib.sha256(repr(after).encode()).hexdigest())
value.update(_source_parameters(row['project_path'], data_root))
return _persist(data_root, value)
def runtime_dispatch_binding(data_root, row, attempt, runtime):
from .batch_attempt import read_attempt
from .execution_journal import command_identity
selected = [(path, expected) for path, expected in runtime._current_attempts
if expected.get('job_id') == row['job_id'] and expected.get('task_id') == row['task_id']
and expected.get('attempt_id') == runtime.record.get('active_attempt')
and expected.get('session_id') == runtime.session_id and expected.get('generation') == runtime.generation]
if len(selected) != 1:
raise TaskCenterError('quick_run_uncertain', '当前原生派发身份无法与执行回执绑定。')
path, expected = selected[0]
actual = read_attempt(path)
if any(actual.get(key) != expected.get(key) for key in ('job_id', 'task_id', 'project_path', 'session_id', 'attempt_id', 'generation')):
raise TaskCenterError('quick_run_uncertain', '原生派发身份发生变化。')
return _persist(data_root, {'version': 1, 'kind': 'native_dispatch', 'identity': _identity(row, attempt), 'command': command_identity(row),
'native_identity': {key: actual[key] for key in ('session_id', 'attempt_id', 'generation')}},
[(path, hashlib.sha256(internal_path(path).read_bytes()).hexdigest())])
def native_completion(data_root, row, attempt, health, baselines, dispatch):
from .execution_proof import proof_intact
from .execution_journal import command_identity
from .batch_resources import _valid_record, _released_evidence
try:
if (not dispatch.get('files') or not proof_intact(dispatch)
or dispatch.get('identity') != _identity(row, attempt)
or dispatch.get('native_identity') != {key: health.get(key) for key in ('session_id', 'attempt_id', 'generation')}
or json.loads(internal_path(dispatch['files'][0]['path']).read_text(encoding='utf-8')) !=
{key: value for key, value in dispatch.items() if key != 'files'}):
raise ValueError('health belongs to another logical or native dispatch')
if (health.get('version') != 1 or health.get('job_id') != row['job_id']
or canonical_path(health['project_path']) != canonical_path(row['project_path'])
or not all(health.get(key) is True for key in ('no_mutation', 'resources_released', 'project_closed'))
or not isinstance(health.get('source_sha256'), str) or len(health['source_sha256']) != 64):
raise ValueError('non-affirmative project health')
native_path = internal_path(health['proof_path'])
if json.loads(native_path.read_text(encoding='utf-8')) != health:
raise ValueError('health record changed')
release_path = canonical_path(health['resource_record'])
release = json.loads(internal_path(release_path).read_text(encoding='utf-8'))
checkpoint_path = native_path.parent / 'project-checkpoint.json'
checkpoint = json.loads(checkpoint_path.read_text(encoding='utf-8'))
if (not _valid_record(release, release_path) or release.get('state') != 'released'
or not _released_evidence(release)
or any(release.get(key) != health.get(key) for key in ('session_id', 'generation'))
or checkpoint.get('project_closed') is not True or checkpoint.get('worker_closed') is not True
or canonical_path(checkpoint['project_path']) != canonical_path(row['project_path'])
or any(checkpoint.get(key) != health.get(key) for key in ('session_id', 'generation', 'attempt_id'))
or (checkpoint.get('cad_pid'), checkpoint.get('cad_guid')) != (release['cad_pid'], release['cad_guid'])):
raise ValueError('physical generation release is not certified')
native = json.loads(internal_path(health['attempt_record_path']).read_text(encoding='utf-8'))
if (native.get('state') != 'prepared' or native.get('job_id') != row['job_id']
or native.get('task_id') != row['task_id']
or canonical_path(native['project_path']) != canonical_path(row['project_path'])
or any(native.get(key) != health.get(key) for key in ('session_id', 'attempt_id', 'generation'))):
raise ValueError('native attempt does not bind the failed job')
evidence = [(health['proof_path'], hashlib.sha256(native_path.read_bytes()).hexdigest()),
(health['attempt_record_path'], health['attempt_record_sha256']),
(health['resource_record'], health['resource_record_sha256']),
(checkpoint_path, health['checkpoint_sha256'])]
evidence.extend((item['path'], item['sha256']) for item in dispatch['files'])
baseline = None
if health.get('source_unchanged') is not True:
baseline = next((value for value in baselines
if value.get('project_path') == str(canonical_path(row['project_path'])).casefold()
and (value.get('schematic_name'), value.get('sheet_number')) == (row.get('schematic_name'), row.get('sheet_number'))
and value.get('state', '').startswith('S\tfull_sheet_v1\r\n') and proof_intact(value)), None)
if baseline is None:
raise ValueError('no intact last verified baseline for the failed sheet')
evidence.extend((item['path'], item['sha256']) for item in baseline['files'])
return _persist(data_root, {'version': 1, 'identity': _identity(row, attempt), 'command': command_identity(row),
'kind': 'native_failure_health', 'resources_released': True, 'project_closed': True,
'no_mutation': True, 'source_unchanged': health.get('source_unchanged') is True,
'source_sha256': health['source_sha256'], 'verified_baseline': baseline,
**_source_parameters(health['project_path'], canonical_path(health['session_record']).parents[2]),
'native_identity': {key: health[key] for key in ('session_id', 'attempt_id', 'generation')}}, evidence)
except (OSError, ValueError, KeyError, TypeError) as error:
raise TaskCenterError('quick_run_uncertain', '当前失败位号没有完整且匹配的工程健康证明。') from error
def verified_source_checkpoint(data_root, row, attempt, proof, references, *, excluded_root, native_source=None):
from .execution_proof import proof_intact
if not references or not proof.get('baseline') or not proof.get('files') or not proof_intact(proof):
return None
value = {'version': 1, 'kind': 'verified_source_checkpoint', 'identity': _identity(row, attempt),
'baseline': proof['baseline'], 'supersedes_failure_health': references,
**_source_parameters(row['project_path'], excluded_root)}
evidence = [(item['path'], item['sha256']) for item in proof['files']]
if native_source is not None:
from .batch_resources import _valid_record, _released_evidence
health_path = internal_path(native_source['proof_path'])
release_path = canonical_path(native_source['resource_record'])
release = json.loads(internal_path(release_path).read_text(encoding='utf-8'))
if (json.loads(health_path.read_text(encoding='utf-8')) != native_source
or native_source.get('job_id') != row['job_id']
or canonical_path(native_source['project_path']) != canonical_path(row['project_path'])
or any(native_source.get(key) is not True for key in ('resources_released', 'project_closed'))
or any(native_source.get(key) != proof.get('native_attempt', {}).get(key)
for key in ('session_id', 'attempt_id', 'generation'))
or not _valid_record(release, release_path) or release.get('state') != 'released'
or not _released_evidence(release)
or any(release.get(key) != native_source.get(key) for key in ('session_id', 'generation'))):
raise TaskCenterError('quick_run_uncertain', '已保存步骤的资源释放证明无法与原生回执绑定。')
value.update(_source_parameters(native_source['project_path'], canonical_path(native_source['session_record']).parents[2]))
digest = native_source['source_sha256']
evidence.extend(((health_path, hashlib.sha256(health_path.read_bytes()).hexdigest()),
(release_path, native_source['resource_record_sha256'])))
else:
digest = _source_digest(value)
if not isinstance(digest, str) or len(digest) != 64 or any(char not in '0123456789abcdef' for char in digest):
raise TaskCenterError('quick_run_uncertain', '已保存步骤的工程源文件无法核对,不能放行后续位号。')
value['source_sha256'] = digest
return _persist(data_root, value, evidence)
def affirmative(health, identity, *, baselines=()):
from .execution_proof import proof_intact
try:
if not _intact_certificate(health) or health.get('identity') != identity:
return False
valid = (all(health.get(key) is True for key in ('no_mutation', 'resources_released', 'project_closed'))
and (health.get('source_unchanged') is True or health.get('kind') == 'native_failure_health'
and health.get('verified_baseline') and proof_intact(health['verified_baseline'])))
if not valid:return False
if _source_digest(health) == health.get('source_sha256') and health.get('source_sha256'):
return True
command = health['command']
for baseline in baselines:
checkpoint = baseline.get('source_checkpoint', {})
if ((baseline.get('project_path'), baseline.get('schematic_name'), baseline.get('sheet_number')) !=
(command['project_path'], command.get('schematic_name'), command.get('sheet_number'))
or not baseline.get('files') or not proof_intact(baseline) or not _intact_certificate(checkpoint)
or checkpoint.get('baseline') != {key: baseline[key] for key in checkpoint.get('baseline', {})}
or health_reference(health) not in checkpoint.get('supersedes_failure_health', ())):
continue
if _source_digest(checkpoint) == checkpoint.get('source_sha256') and checkpoint.get('source_sha256'):
return True
return False
except (OSError, ValueError, KeyError, TypeError):
return False
@@ -103,6 +103,9 @@ class QuickRunPreparer:
sheet_targets: dict[str, tuple[tuple[str, str], ...]] | None = None,
discovery_matches: dict[str, dict[tuple[str, str], frozenset[str]]] | None = None,
discovery_failures: dict[str, str] | None = None,
split_targets: bool = True,
component_scope: dict | None = None,
component_scope_from: Path | None = None,
) -> QuickRunResult:
from .handoff_guard import assert_handoff_intact
# Preserve the public preparation errors (and diagnostic entries) for
@@ -118,6 +121,22 @@ class QuickRunPreparer:
raise TaskCenterError("selected_project_required", "at least one available project must be selected")
if not enabled_rules:
raise TaskCenterError("enabled_rule_required", "at least one replacement rule must be enabled")
if component_scope_from is not None:
original = _io_path(component_scope_from)
original_header = (original / 'command.tsv').read_text(encoding='utf-8-sig').splitlines()[0].split('\t')
split_targets = 'execution_unit' in original_header
scope_path = original / 'component-scope.json'
if scope_path.exists():
from .component_scope import load
component_scope = load(scope_path)
elif 'target_scope' in original_header and all(getattr(rule, 'scope', 'all') == 'all' for rule in enabled_rules):
raise TaskCenterError('component_scope', 'Frozen component scope sidecar is missing; refusing an all-match retry')
if component_scope is not None:
from .component_scope import expand
if sheet_targets is None:
raise TaskCenterError('component_scope', 'Frozen component scope requires its original sheet manifest')
enabled_rules = expand(component_scope, selected_projects, enabled_rules,
_value_mode(copy_part_number_to_value), sheet_targets)
source = self._required_script_source()
self._validate_fields(selected_projects, enabled_rules)
_validate_target_scope(selected_projects, enabled_rules, sheet_targets)
@@ -137,6 +156,11 @@ class QuickRunPreparer:
_io_path(manifest_path).write_text(_sheet_manifest_text(selected_projects, sheet_targets), encoding="utf-8", newline="")
else:
(_io_path(root / "sheets.tsv")).unlink(missing_ok=True)
scope_path = _io_path(root / 'component-scope.json')
if component_scope is not None:
scope_path.write_text(json.dumps(component_scope, ensure_ascii=False, sort_keys=True), encoding='utf8')
else:
scope_path.unlink(missing_ok=True)
_io_path(command_path).write_text(
_command_text(
task_id,
@@ -145,6 +169,7 @@ class QuickRunPreparer:
enabled_rules,
_value_mode(copy_part_number_to_value),
sheet_targets=sheet_targets,
split_targets=split_targets,
),
encoding="utf-8",
newline="",
@@ -207,6 +232,7 @@ class QuickRunPreparer:
{} if self._sheet_discoverer is None else None
)
discovery_failures: dict[str, str] = {}
component_discoveries = {}
targeted = all(getattr(rule, 'scope', 'all') == 'targets' for rule in enabled_rules)
old_part_numbers = tuple(rule.old_part_number for rule in enabled_rules)
for project in selected_projects:
@@ -215,12 +241,13 @@ class QuickRunPreparer:
before_sheet_discovery(project.path)
if self._sheet_discoverer is None:
discovery = self.discover_project(project.path, old_part_numbers,
**({'collect_components': True} if targeted else {}),
collect_components=True,
**({'runtime': runtime} if runtime is not None else {}))
if targeted:
from .inventory import validate_target_inventory
validate_target_inventory(project.path, enabled_rules, discovery.components)
targets = discovery.sheets
component_discoveries[_path_key(project.path)] = discovery
assert discovery_matches is not None
discovery_matches[_path_key(project.path)] = discovery.matched_old_parts
else:
@@ -241,6 +268,11 @@ class QuickRunPreparer:
discovery_matches[project_key] = {_MISSING_PROJECT_SHEET: frozenset()}
_validate_sheet_targets(project.path, targets)
sheet_targets[_path_key(project.path)] = targets
component_scope = None
if self._sheet_discoverer is None and not targeted:
from .component_scope import freeze
component_scope = freeze(selected_projects, enabled_rules, sheet_targets,
component_discoveries, discovery_failures, value_mode)
return self.prepare(
task_id,
projects,
@@ -249,6 +281,7 @@ class QuickRunPreparer:
sheet_targets=sheet_targets,
discovery_matches=discovery_matches,
discovery_failures=discovery_failures,
component_scope=component_scope,
)
def begin_batch_session(
@@ -388,6 +421,7 @@ class QuickRunPreparer:
batch_session: QuickRunBatchSession | None = None,
project_session=None,
runtime=None,
stop_event=None,
) -> QuickRunStepResult:
"""Prepare or resume a queue, then execute one replacement rule end to end."""
uncertain_path = self._data_root / "quick-run" / "uncertain.flag"
@@ -446,6 +480,7 @@ class QuickRunPreparer:
selected_command = _next_unfinished_command(commands, before)
if selected_command is None:
raise TaskCenterError("quick_run_complete", "all replacement rules in this queue are complete")
_assert_dispatchable_component(handoff.command_path, selected_command[1], batch_session)
actual_item = (*selected_command[2:], value_mode)
if expected_item is not None and actual_item != expected_item:
raise TaskCenterError("quick_run_selection_changed", "confirmed queue item or Value policy changed; confirm again")
@@ -462,10 +497,26 @@ class QuickRunPreparer:
batch_request = handoff.script_path.parent / "batch.request"
journal = getattr(self, 'journal', None)
journal_attempt = None
dispatch_fingerprint = None
if journal is not None:
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 not _run_process:
from .discovery_cache import project_fingerprint
dispatch_fingerprint = project_fingerprint(Path(selected_command[2]), self._data_root)
if self._process_runner is _run_process:
try:
from .cell_catalog import preflight_command_target
preflight_command_target(row, self._data_root / 'cell-catalog')
except TaskCenterError as error:
if error.code == 'target_cell_catalog':
self._record_rejected_attempt(journal_attempt, handoff, selected_command, before,
projects, error.message, code='target_library_rejected',
row=row, runtime=runtime, dispatch_not_started=True)
raise
from .value_readback import clear_value_readback
clear_value_readback(handoff.command_path.parent, row)
current_command_stamp = None
if batch_mode:
if batch_session is not None:
@@ -473,7 +524,7 @@ class QuickRunPreparer:
_io_path(batch_request).write_text(selected_command[1], encoding="ascii")
else:
_io_path(batch_request).unlink(missing_ok=True)
from .worker_monitor import WorkerMonitorError
from .worker_monitor import WorkerMonitorError, WorkerMonitorSafeTimeout
self.invalidate_discovery(Path(selected_command[2]))
try:
@@ -487,6 +538,28 @@ class QuickRunPreparer:
_write_uncertain_flag(uncertain_path, "worker_timeout")
_append_log(handoff.log_path, "quick_run_uncertain worker_timeout")
raise TaskCenterError("quick_run_uncertain", "执行器持续无有效进度,安全停止请求后仍未响应;结果待核验。请保留当前工程,不要清锁或重复替换。") from error
except WorkerMonitorSafeTimeout as error:
safe = (error.prewrite_cleanup_confirmed and error.stage == 'open_project'
and journal_attempt is not None and not (stop_event is not None and stop_event.is_set())
and not (getattr(runtime, 'stop_event', None) is not None and runtime.stop_event.is_set()))
try:
safe = safe and _read_status_details(handoff.status_path) == before
if safe and current_command_stamp is not None:
safe = _file_stamp(handoff.command_path.with_name('current-command.tsv')) == current_command_stamp
if safe:
self._record_rejected_attempt(journal_attempt, handoff, selected_command, before,
projects, str(error), code='worker_timeout_before_write', row=row,
source_before=dispatch_fingerprint if dispatch_fingerprint is not None else
getattr(error, 'prewrite_source_before', None), runtime=runtime,
synchronous_prewrite=True)
except Exception as proof_error:
_write_uncertain_flag(uncertain_path, 'safe_timeout_proof_failed')
raise TaskCenterError('quick_run_uncertain', '打开工程超时后无法确认未写入且会话已释放,请先核验恢复。') from proof_error
if not safe:
_write_uncertain_flag(uncertain_path, 'unproven_prewrite_timeout')
raise TaskCenterError('quick_run_uncertain', '超时缺少完整的未写入与释放证明,结果待核验。') from error
_append_log(handoff.log_path, 'quick_run_safe_timeout code=worker_timeout_before_write')
raise TaskCenterError('quick_run_session', '打开工程超时,已确认未写入且资源释放;记录问题项后继续独立位号。') from error
except WorkerMonitorError as error:
_write_uncertain_flag(uncertain_path, f"monitor_failure: {error}")
_append_log(handoff.log_path, f"quick_run_uncertain monitor_failure error={_log_text(str(error))}")
@@ -530,7 +603,8 @@ class QuickRunPreparer:
detail = completed.stderr.strip() or completed.stdout.strip() or "DxDesigner attachment failed"
if journal_attempt is not None:
self._record_rejected_attempt(journal_attempt, handoff, selected_command, before,
projects, detail)
projects, detail, code='cad_attachment_failed', row=row,
source_before=dispatch_fingerprint, runtime=runtime)
raise TaskCenterError("quick_run_session", _session_failure_message(detail))
if completed.returncode == 3:
if after == before:
@@ -538,7 +612,8 @@ class QuickRunPreparer:
detail = completed.stderr.strip() or completed.stdout.strip() or "DxDesigner pre-mutation validation failed"
if journal_attempt is not None:
self._record_rejected_attempt(journal_attempt, handoff, selected_command, before,
projects, detail)
projects, detail, row=row,
source_before=dispatch_fingerprint, runtime=runtime)
raise TaskCenterError("quick_run_session", detail)
_write_uncertain_flag(uncertain_path, "contradictory_pre_mutation_status")
_append_log(handoff.log_path, "quick_run_uncertain pre_mutation_exit_status_changed exit_code=3")
@@ -639,7 +714,35 @@ class QuickRunPreparer:
progress = _progress_from_queue(tuple(project for project in projects if project.selected and project.available),
commands, after, _read_command_sheet_targets(handoff.command_path))
try:
verified_source_health = None
if (state in {'saved_ok', 'restored_ok', 'no_match'} and self._process_runner is _run_process
and journal.failure_health_references(task_id, row['project_path'])):
# A prior failure makes the next source checkpoint an
# admission boundary; finish the retained owner before hashing.
if project_session is not None and project_session.worker is not None:
project_session.worker.close()
project_session.worker = None
if runtime is not None and runtime.cad is not None:
verified_source_health = runtime.reset_project_after_safe_failure(
Path(row['project_path']), handoff.command_path.parent, job_id=row['job_id'])
proof=self.result_proof(handoff.command_path.parent,row,(state,code,message))
if verified_source_health is not None:
proof['verified_source_health'] = verified_source_health
if self._process_runner is not _run_process:
from .project_session_health import synchronous_completion
completion = synchronous_completion(self._data_root, row, journal_attempt,
(state, code, message), dispatch_fingerprint, runtime=runtime)
proof.setdefault('files', []).extend(completion['files'])
if state == BATCH_FAILED_STATE:
proof['failure_health'] = completion
elif state == BATCH_FAILED_STATE and runtime is not None:
from .project_session_health import runtime_dispatch_binding
binding = runtime_dispatch_binding(self._data_root, row, journal_attempt, runtime)
proof.setdefault('files', []).extend(binding['files'])
proof['native_dispatch'] = binding
if state in {'saved_ok', 'restored_ok'}:
from .value_readback import capture_value_readback
proof['value_readback'] = capture_value_readback(handoff.command_path.parent,row,(state,code,message))
journal.finish(journal_attempt, state, code, message, progress=progress,proof=proof)
except Exception:
_write_uncertain_flag(uncertain_path, 'receipt_commit_failed')
@@ -665,14 +768,31 @@ class QuickRunPreparer:
return read_snapshot(self, task_id, projects, rules,
copy_part_number_to_value=copy_part_number_to_value, read_control=read_control)
def _record_rejected_attempt(self, attempt, handoff, command, before, projects, message):
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):
"""Known pre-mutation exit + unchanged status is a safe failure, not an unknown write."""
outcome=(command[1], BATCH_FAILED_STATE, 'pre_mutation_rejected', message)
outcome=(command[1], BATCH_FAILED_STATE, code, message)
_write_status_details(handoff.status_path, (*before, outcome))
progress=_progress_from_queue(tuple(project for project in projects if project.selected and project.available),
_read_commands(handoff.command_path), (*before,outcome), _read_command_sheet_targets(handoff.command_path))
try:
self.journal.finish(attempt, *outcome[1:], progress=progress)
proof = None
if row is not None and (self._process_runner is not _run_process or dispatch_not_started or synchronous_prewrite):
from .project_session_health import synchronous_completion
if dispatch_not_started:
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:
runtime.reset_project_after_safe_failure(Path(command[2]), runtime._active_evidence,
job_id=runtime.record.get('active_job'))
completion = synchronous_completion(self._data_root, row, attempt, outcome[1:], source_before, runtime=runtime)
proof = {'files': completion['files'], 'failure_health': completion}
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)
proof = {'files': binding['files'], 'native_dispatch': binding}
self.journal.finish(attempt, *outcome[1:], progress=progress, proof=proof)
except Exception:
_write_uncertain_flag(handoff.command_path.parent/'uncertain.flag', 'rejection_receipt_commit_failed')
raise
@@ -806,6 +926,8 @@ class QuickRunPreparer:
return self._discover_project_sheets(project_path, old_part_numbers, **controls)
return self._discovery_cache.discover(
Path(project_path), old_part_numbers, collect_components, load,
**({'release_idle': lambda: runtime.release_idle_for_fingerprint(project_path)}
if callable(getattr(runtime, 'release_idle_for_fingerprint', None)) else {}),
**({'stop_event': stop_event} if stop_event is not None else {}))
def collect_inventory(self, project_path: Path, old_part_numbers: tuple[str, ...], *, stop_event=None, on_progress=None, runtime=None) -> tuple:
@@ -1468,10 +1590,28 @@ def _initial_discovery_status(
discovery_failures: dict[str, str] | None = None,
) -> str:
rows = ["job_id\tstate\tcode\tmessage"]
lines = _io_path(command_path).read_text(encoding='utf-8-sig').splitlines()
header = lines[0].split('\t')
empty_jobs = set()
if 'execution_unit' in header:
for line in lines[1:]:
fields = dict(zip(header, line.split('\t')))
if fields.get('execution_unit') != 'inventory_empty':
continue
job = fields['job_id']
empty_jobs.add(job)
failure = (discovery_failures or {}).get(_path_key(fields['project_path']))
message = failure or ('Read-only component inventory found no matching UID for the source rule; '
'manual review required. No replacement was dispatched. '
f"Project={fields['project_path']}; old_part={fields['old_part']}")
rows.append('\t'.join(_encode_vbs_field(value) for value in
(job, BATCH_SKIPPED_STATE, 'project_missing' if failure else 'inventory_empty', message)))
if discovery_matches is None:
if discovery_failures:
commands = _read_commands(command_path)
for _, job_id, project_path, _, _ in commands:
if job_id in empty_jobs:
continue
failure = discovery_failures.get(_path_key(project_path))
if failure is None:
continue
@@ -1480,7 +1620,7 @@ def _initial_discovery_status(
for field in (job_id, BATCH_SKIPPED_STATE, "project_missing", failure)
))
return "\r\n".join(rows) + "\r\n"
return rows[0] + "\r\n"
return '\r\n'.join(rows) + "\r\n"
commands = _read_commands(command_path)
sheets = _read_command_sheet_targets(command_path)
targeted = "target_scope" in _io_path(command_path).read_text(encoding="utf-8-sig").splitlines()[0].split("\t")
@@ -1488,6 +1628,8 @@ def _initial_discovery_status(
raise TaskCenterError("quick_run_sheet_discovery", "discovery inventory requires page-addressed commands")
possible_by_sheet: dict[tuple[str, str, str], set[str]] = {}
for _, job_id, project_path, old_part, new_part in commands:
if job_id in empty_jobs:
continue
project_key = _path_key(project_path)
sheet = sheets[job_id]
failure = (discovery_failures or {}).get(project_key)
@@ -1524,6 +1666,12 @@ def _queue_matches_inputs(
rules: tuple[RuleRecord, ...],
) -> bool:
base_mode = _queue_value_mode(command_path)
header = _io_path(command_path).read_text(encoding='utf-8-sig').splitlines()[0].split('\t')
if 'target_scope' in header and all(getattr(rule, 'scope', 'all') == 'all' for rule in rules):
from .component_scope import expand, load
scope = load(_io_path(command_path.with_name('component-scope.json')))
sheets = _read_sheet_manifest(command_path.with_name('sheets.tsv'), projects)
rules = expand(scope, projects, rules, base_mode, sheets)
cells = _read_command_cells(command_path)
actual_cells = {cells.get(command[1], "") for command in commands}
expected_cells = {str(getattr(rule, "target_cell", "")) for rule in rules}
@@ -1532,9 +1680,10 @@ def _queue_matches_inputs(
if "target_scope" in _io_path(command_path).read_text(encoding="utf-8-sig").splitlines()[0].split("\t"):
sheets = _read_command_sheet_targets(command_path)
manifest = _read_sheet_manifest(command_path.with_name("sheets.tsv"), projects) if sheets is not None else None
expected = _command_text("expected", "expected", projects, rules, base_mode,
sheet_targets=manifest).splitlines()
actual = _io_path(command_path).read_text(encoding="utf-8-sig").splitlines()
expected = _command_text("expected", "expected", projects, rules, base_mode,
sheet_targets=manifest,
split_targets='execution_unit' in actual[0].split('\t')).splitlines()
return (expected[0] == actual[0] and len(expected) == len(actual) and
all(expected_row.split("\t")[2:] == actual_row.split("\t")[2:]
for expected_row, actual_row in zip(expected[1:], actual[1:])))
@@ -1672,6 +1821,22 @@ def _assert_batch_files_unchanged(session: QuickRunBatchSession) -> None:
raise TaskCenterError("quick_run_selection_changed", "batch sheet queue changed during execution")
def _assert_dispatchable_component(command_path, job_id, session=None):
if session is not None:
text = session.target_command_rows.get(job_id)
if text is None:
return
header = session.command_header.split('\t')
else:
lines = _io_path(command_path).read_text(encoding='utf-8-sig').splitlines()
header = lines[0].split('\t')
text = next(line for line in lines[1:] if line.split('\t')[header.index('job_id')] == job_id)
row = dict(zip(header, text.split('\t')))
if (row.get('execution_unit') == 'inventory_empty'
or (row.get('target_scope') == 'targets' and not row.get('target_selectors'))):
raise TaskCenterError('component_scope', 'An inventory-empty record cannot be dispatched; retain its read-only evidence for manual review')
def _write_current_command(
session: QuickRunBatchSession,
command: tuple[str, str, str, str, str],
@@ -1770,7 +1935,8 @@ def _write_atomic_queue_text(path: Path, text: str, code: str, message: str) ->
def _path_key(path: str | Path) -> str:
return os.path.normcase(os.path.abspath(str(path)))
# CAD project identities remain case-insensitive on portable test hosts too.
return os.path.normcase(os.path.abspath(str(path))).casefold()
def _selected_projects(projects: tuple[ProjectRecord, ...]) -> tuple[ProjectRecord, ...]:
@@ -2013,6 +2179,7 @@ def _command_text(
value_mode: str,
*,
sheet_targets: dict[str, tuple[tuple[str, str], ...]] | None = None,
split_targets: bool = True,
) -> str:
_validate_target_scope(projects, rules, sheet_targets)
targeted = any(getattr(rule, "scope", "all") == "targets" for rule in rules)
@@ -2022,6 +2189,8 @@ def _command_text(
has_cell = any(getattr(rule, "target_cell", "") for rule in rules)
if has_cell:
suffix += "\ttarget_cell"
if targeted and split_targets:
suffix += "\texecution_unit"
if sheet_targets is None:
rows = ["task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode" + suffix]
else:
@@ -2033,27 +2202,37 @@ def _command_text(
for rule in rules:
scope = getattr(rule, "scope", "all")
if scope == "targets":
targets_for_sheet = tuple(target for target in rule.targets
if _path_key(target.project_path) == _path_key(project.path)
and (target.schematic_name, target.sheet_number) == (schematic_name, sheet_number))
if not targets_for_sheet:
continue
selectors = _encode_vbs_field("\x1e".join(
"\x1f".join((target.uid, target.refdes, target.old_value))
for target in targets_for_sheet))
empty_sheet = getattr(rule, 'inventory_empty_sheet', None)
if empty_sheet is not None:
if empty_sheet != (_path_key(project.path), schematic_name, sheet_number):
continue
targets_for_sheet = ()
else:
targets_for_sheet = tuple(target for target in rule.targets
if _path_key(target.project_path) == _path_key(project.path)
and (target.schematic_name, target.sheet_number) == (schematic_name, sheet_number))
if not targets_for_sheet:
continue
selector_groups = (((),) if empty_sheet is not None else tuple((target,) for target in targets_for_sheet)
if split_targets else (targets_for_sheet,))
else:
selectors = ""
job_id = f"{run_token}_{job_index}"
sheet_fields = "" if schematic_name is None else f"\t{schematic_name}\t{sheet_number}"
rule_mode, custom_value, sync_nc, base_mode = _rule_command_options(rule, value_mode)
rows.append(
f"{task_id}\t{job_id}\t{project.path}{sheet_fields}\t"
f"{rule.old_part_number}\t{rule.new_part_number}\t{rule_mode}\t{custom_value}\t"
f"{'1' if sync_nc else '0'}\t{base_mode}"
+ (f"\t{scope}\t{selectors}" if targeted else "")
+ ("\t" + _encode_vbs_field(str(getattr(rule, "target_cell", ""))) if has_cell else "")
)
job_index += 1
selector_groups = ((),)
for group in selector_groups:
selectors = _encode_vbs_field("\x1e".join(
"\x1f".join((target.uid, target.refdes, target.old_value)) for target in group))
job_id = f"{run_token}_{job_index}"
sheet_fields = "" if schematic_name is None else f"\t{schematic_name}\t{sheet_number}"
rule_mode, custom_value, sync_nc, base_mode = _rule_command_options(rule, value_mode)
rows.append(
f"{task_id}\t{job_id}\t{project.path}{sheet_fields}\t"
f"{rule.old_part_number}\t{rule.new_part_number}\t{rule_mode}\t{custom_value}\t"
f"{'1' if sync_nc else '0'}\t{base_mode}"
+ (f"\t{scope}\t{selectors}" if targeted else "")
+ ("\t" + _encode_vbs_field(str(getattr(rule, "target_cell", ""))) if has_cell else "")
+ (('\tinventory_empty' if getattr(rule, 'inventory_empty_sheet', None) is not None else '\tcomponent')
if targeted and split_targets else '')
)
job_index += 1
return "\r\n".join(rows) + "\r\n"
@@ -2070,6 +2249,9 @@ def _validate_target_scope(projects, rules, sheet_targets) -> None:
for schematic, sheet in sheet_targets.get(_path_key(project.path), ())}
for rule in rules:
if not rule.targets:
from .component_scope import InventoryEmptyRule
if isinstance(rule, InventoryEmptyRule) and rule.inventory_empty_sheet in available:
continue
raise TaskCenterError("empty_target_scope", "target rule has no components")
for target in rule.targets:
if (_path_key(target.project_path), target.schematic_name, target.sheet_number) not in available:
@@ -0,0 +1,33 @@
"""Owner loss observations; only admitted reads may automatically clean up."""
import re
import time
from .batch_resources import write_record
def check_owner_loss(directory, binding, *, read_only):
from .batch_resources import _process_gone
parent = binding.get('parent_process')
if (not isinstance(parent, dict) or type(parent.get('pid')) is not int or parent['pid'] <= 0
or not isinstance(parent.get('creation_time'), str) or not parent['creation_time']
or any(not isinstance(binding.get(key), str) or not re.fullmatch('[0-9a-f]{32}', binding[key])
for key in ('batch_id', 'attempt_id'))):
raise ValueError('owner loss requires the admitted parent process identity')
if not _process_gone(parent):
return False
path = directory / 'owner-loss.json'
if not path.exists():
write_record(path, {'version': 1, 'batch_id': binding['batch_id'],
'attempt_id': binding['attempt_id'], 'parent_process': parent,
'read_only': read_only, 'observed_at': time.time(),
'policy': 'release_owned_read_generation' if read_only else 'retain_possible_write'})
return True
def process_tree_exited(process):
"""Native handles also cover descendants; simple adapters expose poll only."""
try:
observe = getattr(process, 'tree_exited', None)
return observe() if observe is not None else process.poll() is not None
except Exception:
return False
@@ -0,0 +1,83 @@
"""Reconcile lost worker handles using a positive kernel restart observation."""
import ctypes
import json
import re
import time
from uuid import UUID
from .batch_resources import write_record
from .path_access import internal_path
RESTART_HINT = ('工作进程的原句柄已丢失,无法确认整个进程树退出。请先保存其他工作,'
'重启 Windows 后再次点击“重试释放资源”;仅重启本应用不能提供退出证明。工程结果仍须核验。')
def _boot_id(value):
try:
return isinstance(value, str) and str(UUID(value)) == value and UUID(value).int != 0
except ValueError:
return False
def boot_identity():
"""Boot GUID survives clock changes and sleep; failures never authorize release."""
try:
buffer = ctypes.create_string_buffer(32)
returned = ctypes.c_ulong()
query = ctypes.WinDLL('ntdll').NtQuerySystemInformation
query.argtypes = [ctypes.c_ulong, ctypes.c_void_p, ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong)]
query.restype = ctypes.c_long
if query(90, buffer, len(buffer), ctypes.byref(returned)) != 0 or returned.value != len(buffer):
return None
value = str(UUID(bytes_le=buffer.raw[:16]))
return value if _boot_id(value) else None
except (OSError, AttributeError, ValueError):
return None
def _valid_worker(record, path):
if not isinstance(record, dict):
return False
process = record.get('process')
token = record.get('token')
return (type(record.get('version')) is int and record['version'] == 1
and isinstance(token, str) and re.fullmatch('[0-9a-f]{32}', token) is not None
and path.name == 'retained-worker-' + token + '.json'
and record.get('state') in {'blocked', 'released'}
and isinstance(record.get('job_id'), str) and bool(record['job_id'])
and isinstance(process, dict) and type(process.get('pid')) is int and process['pid'] > 0
and isinstance(process.get('creation_time'), str) and bool(process['creation_time']))
def boot_release_proven(record, path):
proof = record.get('release_proof')
if not _valid_worker(record, path) or not isinstance(proof, dict):
return False
before, after = proof.get('previous_boot_id'), proof.get('current_boot_id')
return (record.get('state') == 'released' and record.get('processes_exited') is True
and proof.get('method') == 'kernel_boot_changed' and _boot_id(before) and _boot_id(after)
and before != after and before == record.get('retained_boot_id', record.get('first_observed_boot_id')))
def reconcile_worker(path):
"""No PID actions: a kernel restart proves all older descendants are gone."""
record = json.loads(internal_path(path).read_text(encoding='utf-8'))
if not _valid_worker(record, path):
raise ValueError('保留工作进程证据不完整,请保留诊断记录。')
if record['state'] != 'blocked':
raise ValueError('工作进程释放声明缺少有效证明,请保留诊断记录。')
current = boot_identity()
if not _boot_id(current):
raise ValueError('无法读取 Windows 启动身份,不能解除工作进程保护。')
before = record.get('retained_boot_id', record.get('first_observed_boot_id'))
if before is None:
# Legacy evidence is first observed now. Only a *later* boot can clear it.
record.update(first_observed_boot_id=current, first_observed_at=time.time())
elif not _boot_id(before):
raise ValueError('记录的 Windows 启动身份无效,不能解除工作进程保护。')
elif before != current:
record.update(state='released', processes_exited=True, reconciled=True, released_at=time.time(),
release_proof=dict(method='kernel_boot_changed', previous_boot_id=before, current_boot_id=current))
write_record(path, record)
return record
@@ -2,6 +2,8 @@
from __future__ import annotations
from .value_readback import value_readback_details
from collections.abc import Callable
from contextlib import contextmanager, ExitStack
from datetime import datetime
@@ -196,14 +198,15 @@ class TaskCenterService:
**({'runtime': runtime} if runtime is not None else {})))
def preview_bom_sources(self, task_id: str, sources, *, stop_event=None, on_progress=None,
on_phase=None, runtime=None):
on_phase=None, runtime=None, allow_partial=False):
"""Normalize several BOM files and exact-name migrated project paths before CAD reads."""
sources = tuple(Path(source) for source in sources)
if runtime is None and self._supervised:
return self._supervise('preview_bom_sources', {'task_id': task_id, 'sources': sources},
return self._supervise('preview_bom_sources', {'task_id': task_id, 'sources': sources,
**({'allow_partial': True} if allow_partial else {})},
stop_event=stop_event, on_progress=on_progress, on_phase=on_phase)
from .bom_batch import _scope
from .bom_import_report import BomImportReport, inspect_batch
from .bom_import_report import BomImportReport, inspect_batch, bind_source_report
from .bom_import_state import BomImportPhase
from .retention import maintain_quick_run_storage
from .workspace_bom import load_sources, route_sources, write_routed_bom
@@ -215,7 +218,8 @@ class TaskCenterService:
on_phase(BomImportPhase.READING, message)
if on_progress is not None:
on_progress(message)
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress)
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress,
**({'allow_partial': True} if allow_partial else {}))
scope = _scope(self._store, task_id)
paths = tuple(project.path for _, project in scope)
names = {project.path: task.name for task, project in scope}
@@ -247,7 +251,9 @@ class TaskCenterService:
reason = '位号在 BOM 中重复(' + ';'.join(locations) + ')'
annotated.append(replace(row, source_file=str(source.source), source_row=source.excel_row,
reason=reason + f';来源:{source.source} 第 {source.excel_row} 行'))
return replace(report, rows=tuple(annotated), source_map_path=mapping)
annotated_report = replace(report, rows=tuple(annotated), source_map_path=mapping)
return bind_source_report(annotated_report,
tuple(dict.fromkeys((str(row.source), row.source_sha256) for row in rows)), mapping)
def inspection_phase(phase, message):
if on_phase is not None and phase is not BomImportPhase.READING:
@@ -259,7 +265,8 @@ class TaskCenterService:
operation='preview_bom_sources', message='BOM 导入来源记录已保存',
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows})})
report = inspect_batch(self, task_id, normalized, stop_event=stop_event,
on_progress=on_progress, on_phase=inspection_phase, runtime=runtime)
on_progress=on_progress, on_phase=inspection_phase, runtime=runtime,
**({'allow_partial': True} if allow_partial else {}))
return annotate(report)
except TaskCenterError as error:
if getattr(error, 'bom_report', None) is not None:
@@ -383,7 +390,7 @@ class TaskCenterService:
interrupted = snapshot.interrupted
has_evidence = snapshot.has_evidence
phase = snapshot.phase
if facade._quick_run_preparer.journal.requires_retry(task_id) and not interrupted:
if facade._quick_run_preparer.journal.requires_retry(task_id) and not interrupted and not facade._quick_run_preparer.journal.has_pending_components(task_id):
phase = 'retry'
elif (not interrupted and task.summary == 'current-sheet quick-run queue completed with retryable failures'
and any(project.status is ProjectStatus.FAILED for project in projects)):
@@ -825,7 +832,8 @@ class TaskCenterService:
task_id=task_id,
operation="quick_run_executed",
message=result.message,
details={"state": result.state, "status_path": str(result.status_path), "log_path": str(result.log_path)},
details={"state": result.state, "status_path": str(result.status_path), "log_path": str(result.log_path),
**value_readback_details(result)},
)
self._logging.logger.info("quick_run_executed task_id=%s state=%s", task_id, result.state)
return result
@@ -903,16 +911,39 @@ class TaskCenterService:
finally:
self._batch_feedback = None
def prepare_failed_quick_run(self, task_id: str, *, runtime=None) -> QuickRunProgress:
def execution_problems(self, task_id: str):
from .execution_problems import ExecutionProblems
return ExecutionProblems(self._store).list(task_id)
def execution_problem_overview(self, task_id: str):
from .execution_problems import ExecutionProblems
return ExecutionProblems(self._store).overview(task_id)
def independent_continuation_ready(self, task_id: str):
child = self._project_task_service(task_id)
return child._quick_run_preparer.journal.independent_continuation_ready(task_id)
def reserve_problem_retry(self, task_id: str, *, operation_keys=None, source='dsh'):
from .execution_problems import ExecutionProblems
child = self._project_task_service(task_id)
if child.has_interrupted_quick_run(task_id):
return ()
return ExecutionProblems(self._store).reserve(task_id, operation_keys=operation_keys, source=source)
def prepare_failed_quick_run(self, task_id: str, *, runtime=None, operation_keys=None,
expected_round_id=None, expected_generations=None) -> QuickRunProgress:
"""Reset only failed projects and discard the finished queue handoff."""
if runtime is None and self._supervised:
return self._supervise('prepare_failed_quick_run', {'task_id': task_id})
return self._supervise('prepare_failed_quick_run', {'task_id': task_id, 'operation_keys': operation_keys,
'expected_round_id': expected_round_id, 'expected_generations': expected_generations})
if runtime is None:
return self._owned_cad_operation('prepare_failed_quick_run', lambda owned:
self.prepare_failed_quick_run(task_id, runtime=owned), task_id=task_id)
self.prepare_failed_quick_run(task_id, runtime=owned, operation_keys=operation_keys,
expected_round_id=expected_round_id, expected_generations=expected_generations), task_id=task_id)
delegated = self._project_task_service(task_id)
if delegated is not self:
return delegated.prepare_failed_quick_run(task_id, runtime=runtime)
return delegated.prepare_failed_quick_run(task_id, runtime=runtime, operation_keys=operation_keys,
expected_round_id=expected_round_id, expected_generations=expected_generations)
def prepare_retry() -> QuickRunProgress:
from .retry_preparation import recover_publication
recover_publication(self._quick_run_preparer, self._store, task_id)
@@ -946,7 +977,11 @@ class TaskCenterService:
from .retry_preparation import stage_publication, recover_publication
try:
with self._store.transaction():
self._quick_run_preparer.journal.authorize_retry(task_id)
if expected_round_id is not None or expected_generations is not None:
from .execution_problems import ExecutionProblems
ExecutionProblems(self._store).validate_selection(task_id, operation_keys,
expected_round_id, expected_generations)
self._quick_run_preparer.journal.authorize_retry(task_id, operation_keys=operation_keys)
with stage_publication(self._quick_run_preparer, self._store, task_id) as (staged, original):
# Use the frozen sheet scope. Successful exact targets
# now have new parts and must never be rediscovered as old.
@@ -961,6 +996,8 @@ class TaskCenterService:
sheets={key:value for key,value in sheets.items() if key in eligible}
handoff = staged.prepare(task_id, self._store.list_projects(task_id),
self._execution_rules(task_id), sheet_targets=sheets,
component_scope_from=original,
split_targets='execution_unit' in (original/'command.tsv').read_text(encoding='utf-8-sig').splitlines()[0].split('\t'),
copy_part_number_to_value=task.copy_part_number_to_value)
inherit_backup_for_retry(original, handoff.command_path.parent, task_id)
staged._bind_journal_handoff(task_id, handoff)
@@ -1008,6 +1045,12 @@ class TaskCenterService:
return self._operation('export_diagnostics', None,
lambda: export_diagnostic_bundle(self._logging.root, destination))
def force_pending_owned_resources(self, *, confirmed=False):
"""Explicit local action: retained process handles belong to this GUI."""
from .batch_resources import force_pending_owned_resources
return self._operation('force_pending_owned_resources', None,
lambda: force_pending_owned_resources(self._logging.root, confirmed=confirmed))
def cleanup_batch_resources(self):
"""Retry owned-resource release without opening or changing any project."""
if self._supervised:
@@ -1346,7 +1389,7 @@ class TaskCenterService:
)
if self._supervised:
return progress # Only the batch process persists live execution state.
by_path = {os.path.normcase(os.path.abspath(str(project.path))): project.project_id for project in projects}
by_path = {_path_key(project.path): project.project_id for project in projects}
project_by_id = {project.project_id: project for project in projects}
summary_by_id = {
by_path[_path_key(path)]: summary
@@ -1364,7 +1407,7 @@ class TaskCenterService:
completed_project_ids = tuple(
by_path[path_key]
for path in progress.completed_project_paths
if (path_key := os.path.normcase(os.path.abspath(str(path)))) in by_path
if (path_key := _path_key(path)) in by_path
and by_path[path_key] not in failed_project_ids
)
changed_project_ids = tuple(
@@ -42,11 +42,12 @@ def protect_interruption(root, reason):
os.fsync(stream.fileno())
def wait_for_resolution(control, root, error):
"""Interactive owners retain a possibly changed project until explicit force.
def wait_for_resolution(control, root, error, *, resolved=None):
"""Retain uncertain work until explicit force or an owned-exit proof.
The GUI-side supervisor can also terminate its own Job after durable force
evidence. Ordinary cancellation never releases this wait.
evidence. Ordinary cancellation never releases this wait; an optional
observer may prove all retained processes exited without clearing uncertainty.
"""
if not isinstance(control, StopControl):
return
@@ -71,6 +72,9 @@ def wait_for_resolution(control, root, error):
resolution_error=str(error), stop_requested=True, safe_stop=False)
_publish_progress(root / 'worker-progress.json', record)
while True:
if resolved is not None and resolved():
control.waiting_for_resolution = False
return
if control.force_event.wait(.1):
try:
protect()
@@ -81,7 +81,8 @@ def read_task_bundle(store, task_id: str, read_control=None) -> TaskBundle:
def target_record(row):
return TargetPlanRow(
ComponentTarget(Path(row['project_path']), row['schematic_name'], row['sheet_number'],
row['uid'], row['refdes'], row['old_part_number'], row['old_value']),
row['uid'], row['refdes'], row['old_part_number'], row['old_value'],
row['actual_part_label'], row['actual_cell']),
bool(row['enabled']), row['new_part_number'], bool(row['custom_value_enabled']),
row['custom_value'], bool(row['sync_nc']),
row['target_cell'], value_mode=row['value_mode'],
@@ -240,6 +240,9 @@ class StoreSchema:
self._store._connection.execute("ALTER TABLE target_plan ADD COLUMN target_cell TEXT NOT NULL DEFAULT ''")
if 'value_mode' not in columns:
self._store._connection.execute("ALTER TABLE target_plan ADD COLUMN value_mode TEXT NOT NULL DEFAULT 'inherit'")
for name in ('actual_part_label', 'actual_cell'):
if name not in columns:
self._store._connection.execute(f'ALTER TABLE target_plan ADD COLUMN {name} TEXT')
def _ensure_rule_columns(self) -> None:
columns = {row["name"] for row in self._store._connection.execute("PRAGMA table_info(rules)")}
@@ -2,12 +2,14 @@
from __future__ import annotations
from pathlib import Path
from dataclasses import replace
from .errors import TaskCenterError
from .models import TaskRecord, TaskStatus
from .target_plan import ProjectIdentityResolver
def _target_baseline(target, identities) -> tuple:
return (identities.target(target), target.refdes, target.old_part_number, target.old_value)
return (identities.target(target), target.refdes, target.old_part_number, target.old_value,
target.actual_part_label, target.actual_cell)
def merge_target_inventory(existing, targets) -> tuple:
@@ -18,12 +20,19 @@ def merge_target_inventory(existing, targets) -> tuple:
incoming = {identities.target(target): target for target in targets}
if len(incoming) != len(targets):
raise TaskCenterError("target_identity", "component inventory contains duplicate UID")
if any(identities.target(row.target) not in incoming or
_target_baseline(row.target, identities) != _target_baseline(incoming[identities.target(row.target)], identities)
for row in existing):
raise TaskCenterError("target_identity", "component inventory identity changed")
for row in existing:
actual = incoming.get(identities.target(row.target))
if (actual is None or _target_baseline(row.target, identities)[:4] != _target_baseline(actual, identities)[:4]
or any(getattr(row.target, name) is not None and getattr(actual, name) is not None
and getattr(row.target, name) != getattr(actual, name)
for name in ('actual_part_label', 'actual_cell'))):
raise TaskCenterError("target_identity", "component inventory identity changed")
known = {identities.target(row.target) for row in existing}
return existing + tuple(TargetPlanRow(target) for key, target in incoming.items() if key not in known)
enriched = tuple(replace(row, target=replace(row.target, **{
name: getattr(incoming[identities.target(row.target)], name)
if getattr(incoming[identities.target(row.target)], name) is not None else getattr(row.target, name)
for name in ('actual_part_label', 'actual_cell')})) for row in existing)
return enriched + tuple(TargetPlanRow(target) for key, target in incoming.items() if key not in known)
class TargetPlanRepository:
@@ -86,11 +95,11 @@ class TargetPlanRepository:
self._store._connection.execute("DELETE FROM target_plan WHERE task_id = ?", (task_id,))
for row in rows:
target = row.target
self._store._connection.execute("""INSERT INTO target_plan VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
self._store._connection.execute("""INSERT INTO target_plan VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(task_id, identities.project(target.project_path), target.schematic_name,
target.sheet_number, target.uid, target.refdes, target.old_part_number, target.old_value,
int(row.enabled), row.new_part_number, int(row.custom_value_enabled), row.custom_value,
int(row.sync_nc), row.target_cell, row.value_mode))
int(row.sync_nc), row.target_cell, row.value_mode, target.actual_part_label, target.actual_cell))
self._store._connection.execute("UPDATE tasks SET target_plan_mode = 1 WHERE task_id = ?", (task_id,))
return self._store.list_target_plan(task_id)
@@ -107,6 +116,12 @@ class TargetPlanRepository:
return ()
existing = self._store.list_target_plan(task_id)
merged = merge_target_inventory(existing, targets)
for row in merged[:len(existing)]:
target = row.target
self._store._connection.execute('''UPDATE target_plan SET actual_part_label=?,actual_cell=?
WHERE task_id=? AND project_path=? AND schematic_name=? AND sheet_number=? AND uid=?''',
(target.actual_part_label, target.actual_cell, task_id, str(target.project_path.resolve()).casefold(),
target.schematic_name, target.sheet_number, target.uid))
rows = merged[len(existing):]
identities = ProjectIdentityResolver()
projects = self._store.list_projects(task_id)
@@ -115,9 +130,10 @@ class TargetPlanRepository:
raise TaskCenterError("target_identity", "inventory project is not in task")
for row in rows:
target = row.target
self._store._connection.execute("""INSERT INTO target_plan VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, '', 0, '', 1, '', 'inherit')""",
self._store._connection.execute("""INSERT INTO target_plan VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, '', 0, '', 1, '', 'inherit', ?, ?)""",
(task_id, identities.project(target.project_path), target.schematic_name,
target.sheet_number, target.uid, target.refdes, target.old_part_number, target.old_value))
target.sheet_number, target.uid, target.refdes, target.old_part_number, target.old_value,
target.actual_part_label, target.actual_cell))
self._store._connection.execute("UPDATE tasks SET target_plan_mode = 1 WHERE task_id = ?", (task_id,))
return self._store.list_target_plan(task_id)
@@ -128,7 +144,8 @@ class TargetPlanRepository:
rows = self._store._connection.execute("SELECT * FROM target_plan WHERE task_id = ? ORDER BY project_path, schematic_name, sheet_number, refdes, uid", (task_id,)).fetchall()
return tuple(TargetPlanRow(
ComponentTarget(Path(row["project_path"]), row["schematic_name"], row["sheet_number"],
row["uid"], row["refdes"], row["old_part_number"], row["old_value"]),
row["uid"], row["refdes"], row["old_part_number"], row["old_value"],
row['actual_part_label'], row['actual_cell']),
bool(row["enabled"]), row["new_part_number"], bool(row["custom_value_enabled"]),
row["custom_value"], bool(row["sync_nc"]), row['target_cell'], row['value_mode']) for row in rows)
@@ -41,13 +41,13 @@ def resource_pending_error(operation, result, error, primary_error=None):
from .batch_resources import BatchResourceCleanupError
from .bom_import_report import BomImportReport
if isinstance(result, BomImportReport):
result = replace(result, preview=None)
result = replace(result, preview=None, passed_preview=None)
failure = BatchResourceCleanupError('后台资源仍待清理;报告和已保存核验结果保留。' + (str(error) if error else ''),
completed_result=result, primary_error=primary_error, cleanup_error=error)
for candidate in (result, getattr(error, 'bom_report', None),
getattr(primary_error, 'bom_report', None)):
if isinstance(candidate, BomImportReport):
failure.bom_report = replace(candidate, preview=None)
failure.bom_report = replace(candidate, preview=None, passed_preview=None)
break
return failure
@@ -59,7 +59,7 @@ def application_shutdown_error(result, error, primary_error=None):
from .errors import TaskCenterError
if isinstance(result, BomImportReport):
result = replace(result, preview=None)
result = replace(result, preview=None, passed_preview=None)
failure = TaskCenterError('application_shutdown_failed',
'应用未正常收尾,已有报告和核验结果保留;请查看退出诊断。')
failure.completed_result = result
@@ -68,6 +68,6 @@ def application_shutdown_error(result, error, primary_error=None):
for candidate in (result, getattr(error, 'bom_report', None),
getattr(primary_error, 'bom_report', None)):
if isinstance(candidate, BomImportReport):
failure.bom_report = replace(candidate, preview=None)
failure.bom_report = replace(candidate, preview=None, passed_preview=None)
break
return failure
@@ -32,8 +32,13 @@ class ComponentTarget:
refdes: str
old_part_number: str
old_value: str
actual_part_label: str | None = None
actual_cell: str | None = None
def __post_init__(self) -> None:
if any(value is not None and not isinstance(value, str)
for value in (self.actual_part_label, self.actual_cell)):
raise TaskCenterError('target_inventory', 'effective Part Label and Cell must be text or unknown')
fields = (self.schematic_name, self.sheet_number, self.uid, self.refdes, self.old_part_number)
if any(not isinstance(value, str) or not value for value in fields):
raise TaskCenterError("target_identity", "component identity is incomplete")
@@ -130,17 +130,20 @@ def _save(path: Path, state: dict) -> None:
def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
queue_id: str | None = None, runtime=None, expected_plan_hashes=None, checkpoint_id=None) -> TaskQueueResult:
queue_id: str | None = None, runtime=None, expected_plan_hashes=None, checkpoint_id=None,
defer_problem_pass=False) -> TaskQueueResult:
"""Execute the frozen order; uncertain state stops before the next project."""
if runtime is None and getattr(service, '_supervised', False):
return service._supervise('execute_task_queue', {'task_ids': task_ids, 'queue_id': queue_id,
'expected_plan_hashes': expected_plan_hashes, 'checkpoint_id': checkpoint_id}, stop_event=stop_event)
from .workspace_execution import execute_workspace_projects
return execute_workspace_projects(service, task_ids, queue_id=queue_id, stop_event=stop_event,
expected_plan_hashes=expected_plan_hashes, checkpoint_id=checkpoint_id,
defer_problem_pass=defer_problem_pass)
if runtime is None:
from .batch_runtime import BatchCadRuntime
with BatchCadRuntime(service._logging.root, 'task_queue', stop_event) as owned_runtime:
result = execute_task_queue(service, task_ids, stop_event=stop_event,
queue_id=queue_id, runtime=owned_runtime, expected_plan_hashes=expected_plan_hashes,
checkpoint_id=checkpoint_id)
checkpoint_id=checkpoint_id, defer_problem_pass=defer_problem_pass)
owned_runtime.result = result
return result
ids = tuple(task_ids)
@@ -184,7 +187,7 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
except (OSError, ValueError, KeyError, TypeError) as error:
raise TaskCenterError('task_queue_state', '任务顺序或计划已变化,不能恢复原队列。') from error
else:
state = {'version': 1, 'task_ids': list(ids), 'plan_hashes': hashes,
state = {'version': 1, 'task_ids': list(ids), 'plan_hashes': hashes, 'phase': 'primary',
'entries': {task_id: {'state': 'pending', 'message': ''} for task_id in ids}}
_save(path, state)
paused = False
@@ -249,6 +252,23 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
_save(path, state)
if paused:
break
if not paused and not defer_problem_pass and not stop_event.is_set() and state.get('phase') != 'finished' and hasattr(service, 'reserve_problem_retry'):
state['phase'] = 'problems'
_save(path, state)
from .problem_pass import run_problem_pass
retried = run_problem_pass(service, ids, token, stop_event=stop_event, runtime=runtime)
for task_id, result in retried.results.items():
state['entries'][task_id] = {'state': 'paused' if result.paused else 'failed' if result.progress.failed_items else 'completed',
'message': '问题轮次暂停。' if result.paused else '问题轮次已收尾,保留所有真实回执。'}
if result.paused:
paused, current = True, task_id
if retried.blocked_task_id is not None:
paused, current = True, retried.blocked_task_id
state['entries'][current] = {'state': 'blocked',
'message': f'{retried.error_code}: {retried.message}'}
if not paused and not stop_event.is_set():
state['phase'] = 'finished'
_save(path, state)
return TaskQueueResult(token, tuple(TaskQueueEntry(task_id, **state['entries'][task_id])
for task_id in ids), paused, current if paused else None)
finally:
@@ -1,5 +1,11 @@
"""PySide6 task-center presentation layer."""
from .main_window import TrialTaskCenterWindow
__all__ = ["TrialTaskCenterWindow"]
def __getattr__(name):
# Core projections live in this package too; importing them needs no Qt.
if name == 'TrialTaskCenterWindow':
from .main_window import TrialTaskCenterWindow
return TrialTaskCenterWindow
raise AttributeError(name)
@@ -0,0 +1,82 @@
"""Explicit, session-bound handling of the owned CAD's unknown modal prompts."""
import json
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import (QDialog, QDialogButtonBox, QGroupBox, QHBoxLayout,
QLabel, QMessageBox, QPlainTextEdit, QPushButton, QVBoxLayout, QWidget)
from ..batch_supervisor import request_manual_dialog_action
class CadDialogOperations(QDialog):
def __init__(self, window):
super().__init__(window)
self.service = window.service
self.setWindowTitle('人工处理 CAD 弹窗')
self.resize(640, 480)
self.layout_box = QVBoxLayout(self)
self.project = QLabel()
self.project.setWordWrap(True)
self.layout_box.addWidget(self.project)
self.prompt = QWidget()
self.prompt_box = QVBoxLayout(self.prompt)
self.layout_box.addWidget(self.prompt)
self.status = QLabel('请选择弹窗中的原始按钮。保存、放弃或许可操作由你决定。')
self.status.setWordWrap(True)
self.layout_box.addWidget(self.status)
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
buttons.rejected.connect(self.reject)
self.layout_box.addWidget(buttons)
self.signature = None
self.timer = QTimer(self)
self.timer.setInterval(500)
self.timer.timeout.connect(self.refresh)
self.timer.start()
self.refresh()
def refresh(self):
state = getattr(self.service, '_supervisor_dialog_state', None) or {}
signature = json.dumps(state, sort_keys=True, default=str)
if signature == self.signature:
return
self.signature = signature
self.project.setText('当前工程:' + str(state.get('project') or '尚无工程身份'))
while self.prompt_box.count():
widget = self.prompt_box.takeAt(0).widget()
if widget is not None:
widget.setParent(None)
widget.deleteLater()
binding = state.get('binding') or {}
rows = (state.get('supervision') or {}).get('current_dialogs') or ()
if not rows:
self.prompt_box.addWidget(QLabel('当前没有可处理的 CAD 弹窗。'))
for row in rows:
group = QGroupBox(row.get('title') or '未命名弹窗')
box = QVBoxLayout(group)
text = QPlainTextEdit()
text.setReadOnly(True)
text.setPlainText(row.get('text', ''))
box.addWidget(text)
choices = QHBoxLayout()
for button in row.get('buttons', ()):
choice = QPushButton(button['text'])
choice.setEnabled(bool(button['enabled']) and row.get('complete') is True)
choice.clicked.connect(lambda _checked=False, d=row, b=button['hwnd'], s=binding, c=choice:
self.choose(s, d, b, c))
choices.addWidget(choice)
box.addLayout(choices)
self.prompt_box.addWidget(group)
def choose(self, binding, dialog, button_hwnd, button):
try:
request_manual_dialog_action(self.service._logging.root, binding, dialog, button_hwnd)
except Exception as error:
QMessageBox.warning(self, '弹窗操作未发送', str(error))
return
button.setEnabled(False)
self.status.setText('已发送人工选择,正在等待 CAD 响应。弹窗变化后将刷新。')
def show_cad_dialogs(window):
dialog = CadDialogOperations(window)
dialog.exec()
@@ -6,7 +6,7 @@ from PySide6.QtWidgets import (QAbstractItemView, QDialog, QHBoxLayout, QLabel,
class ResultTableModel(QAbstractTableModel):
headers = ('图页', '位号', '旧料号', '回读料号', '核验状态')
headers = ('图页', '位号', '旧料号', '回读料号', '原 Value', '实际 Value', '核验状态')
def __init__(self, parent=None):
super().__init__(parent)
@@ -85,7 +85,7 @@ class TaskLogDialog(QDialog):
self.result_view.setModel(ResultTableModel(self.result_view))
self.result_view.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.result_view.setAlternatingRowColors(True)
for column, width in enumerate((140, 75, 195, 195, 165)):
for column, width in enumerate((110, 65, 145, 145, 160, 160, 150)):
self.result_view.setColumnWidth(column, width)
self._pages[0].addWidget(self.result_summary)
self._pages[0].addWidget(self.result_view, 1)
@@ -6,7 +6,7 @@ from contextlib import contextmanager
from collections import deque
from copy import deepcopy
from dataclasses import dataclass
from threading import Event
from threading import Event, Lock
from time import monotonic
from uuid import uuid4
@@ -60,6 +60,8 @@ class DshAutomation(QObject):
self._uses_cad_controls = False
self.cancel_event = Event()
self._analysis_deadline = None
self._admitted_action = None
self._closing = False
self._connected_view = None
self._native_unavailable = False
self.model_requested.connect(self._request_model)
@@ -115,9 +117,6 @@ class DshAutomation(QObject):
status = getattr(self.window, '_dsh_status', None)
if status is not None and not status.available:
return False
# Offscreen UI unit tests have no Chromium surface or local provider.
if QApplication.platformName().casefold() == 'offscreen':
return False
if not self.window.auto_intervention_check.isChecked() or issue_code in {'operation_cancelled', 'dsh_startup'}:
return False
item = IncidentRequest(task_id, issue_code, message, execution_authorized, run_id, stop_event,
@@ -139,7 +138,7 @@ class DshAutomation(QObject):
w = self.window
if w._dsh_status is not None and not w._dsh_status.available:
return
if w._closed or not w.auto_intervention_check.isChecked() or self.worker is not None or not self.pending:
if w._closed or w._close_pending or self._closing or not w.auto_intervention_check.isChecked() or self.worker is not None or not self.pending:
return
busy = (w._workers or w._loading or (w._dsh_lifecycle and w._dsh_lifecycle.dialog)
or (w._dsh_task_creation and w._dsh_task_creation.dialog) or w._dsh_operations.busy)
@@ -209,57 +208,57 @@ class DshAutomation(QObject):
@contextmanager
def _action_scope(self, action):
request = {'action': action, 'worker': self.worker, 'complete': Event(), 'holder': {}}
request = {'action': action, 'worker': self.worker, 'complete': Event(),
'released': Event(), 'lock': Lock(), 'abandoned': False, 'admitted': False, 'release': False}
self.action_requested.emit(request)
# Admission runs on the GUI thread; a timed-out request cannot acquire later.
if not request['complete'].wait(5):
request['holder']['abandoned'] = True
request['holder']['release'] = True
with request['lock']:
request['abandoned'] = True
request['release'] = True
self.action_requested.emit(request)
if request['admitted']:
request['released'].wait()
raise ValueError('ai_action_admission_timeout')
if not request['holder'].get('admitted'):
if not request['admitted']:
raise ValueError('ai_action_context_changed')
try:
yield
finally:
request['complete'].clear()
request['holder']['release'] = True
request['release'] = True
self.action_requested.emit(request)
request['complete'].wait(5)
# Never begin reflection while the GUI still owns our mutation gate.
request['released'].wait()
def _admit_action(self, request):
if request['holder'].get('release'):
self._release_action(request)
request['complete'].set()
return
w = self.window
try:
item = self.current_request
if (request['holder'].get('abandoned') or w._closed or self.cancel_event.is_set()
or not self.execution_enabled.is_set() or not w.auto_intervention_check.isChecked()
or item is None or item.read_only or request['worker'] is not self.worker
or w._workers or w._loading or w._batch_stop is not None
or w._dsh_run_id != self._observed_run_id
or w.plan_panel.has_unsaved_plans()
or (w._dsh_lifecycle and (w._dsh_lifecycle.worker or w._dsh_lifecycle.dialog))
or (w._dsh_task_creation and (w._dsh_task_creation.worker or w._dsh_task_creation.dialog))
or w._dsh_operations.dialog):
return
if request['action'] == 'retry_failed':
if not item.authorized or self._action_stop.is_set():
return
elif request['action'] != 'cleanup_resources' or not item.cleanup_allowed:
return
self._admitted_action = request
self._owns_execution_lane = True
self._uses_cad_controls = request['action'] == 'retry_failed'
if self._uses_cad_controls:
w._batch_stop = self._action_stop
w._active_quick_run_task_id = item.task_id
w._workers.add(self.worker)
request['holder']['admitted'] = True
w._update_gates()
finally:
with request['lock']:
if request['release']:
self._release_action(request)
request['released'].set()
else:
w = self.window
item = self.current_request
if (not request['abandoned'] and not self._closing and not w._closed and not w._close_pending
and item is not None and not item.read_only
and self.execution_enabled.is_set() and w.auto_intervention_check.isChecked()
and ((request['action'] == 'retry_failed' and item.authorized)
or (request['action'] == 'cleanup_resources' and item.cleanup_allowed))
and not self.cancel_event.is_set() and not self._action_stop.is_set()
and request['worker'] is self.worker and not w._workers and not w._loading
and not w._dsh_live_run.get('active') and w._batch_stop is None
and w._dsh_run_id == self._observed_run_id
and not w.plan_panel.has_unsaved_plans()
and not (w._dsh_lifecycle and w._dsh_lifecycle.dialog)
and not (w._dsh_task_creation and w._dsh_task_creation.dialog)
and not w._dsh_operations.busy):
self._admitted_action = request
request['admitted'] = True
w._workers.add(self.worker)
self._owns_execution_lane = True
self._uses_cad_controls = request['action'] == 'retry_failed'
if self._uses_cad_controls:
w._batch_stop = self._action_stop
w._active_quick_run_task_id = item.task_id
w._update_gates()
request['complete'].set()
def _release_action(self, request):
@@ -273,7 +272,7 @@ class DshAutomation(QObject):
self._admitted_action = None
self._owns_execution_lane = False
self._uses_cad_controls = False
if not w._closed:
if not w._closed and not w._close_pending and not self._closing:
# Refresh only this task's visible evidence; never finish a newer run.
if self.current_request and w._task_id == self.current_request.task_id:
w._load_task_data(auto_intervene=False)
@@ -353,7 +352,7 @@ class DshAutomation(QObject):
self.waiters.pop(request_id, None)
def _request_model(self, request):
if self.window._closed or self.cancel_event.is_set():
if self.window._closed or self._closing or self.cancel_event.is_set():
self._diagnosis_event({'request_id': request['request_id'], 'status': 'cancelled', 'error': 'diagnosis_cancelled'})
return
status = self.window._dsh_status
@@ -371,6 +370,7 @@ class DshAutomation(QObject):
view.request_diagnosis(request)
def _runtime_stopped(self):
self._native_unavailable = True
for complete, holder in list(self.waiters.values()):
holder.update(status='failed', error='native_harness_stopped')
if holder.get('_ready') is not None:
@@ -442,8 +442,10 @@ class DshAutomation(QObject):
w = self.window
if getattr(self, '_admitted_action', None) is not None:
self._release_action(self._admitted_action)
refresh_task = self.current_request.task_id if self.current_request else (self._current_identity[0] if self._current_identity else None)
w._workers.discard(self.worker)
self.worker = None
self._closing = False
if self._current_identity:
w._dsh_blockers.completed(self._current_identity[2])
if self._current_identity[2].startswith('blocker-'):
@@ -453,7 +455,12 @@ class DshAutomation(QObject):
self._publish_context()
if w._closed:
return
w._resource_status.refresh()
if (refresh_task and w._task_id == refresh_task and not w._workers and not w._loading
and not w._close_pending and not w._dsh_live_run.get('active')
and getattr(self, '_observed_run_id', w._dsh_run_id) == w._dsh_run_id):
w._load_task_data(auto_intervene=False)
if not w._close_pending:
w._resource_status.refresh()
w._update_gates()
if w._close_pending:
QTimer.singleShot(0, w.close)
@@ -461,10 +468,20 @@ class DshAutomation(QObject):
QTimer.singleShot(0, self._drain)
def resubmit(self, incident_id):
if self.worker is not None or self.window._workers:
if self.worker is not None or self.window._closed or self._closing:
return
runner = IncidentRunner(self.root, self.window.service, self._analyze,
GitIssuePublisher(self.root / 'dsh' / 'issue-config.json'), self.state_changed.emit)
self._owns_execution_lane = False
self._uses_cad_controls = False
self._start_worker(ServiceWorker(lambda: runner.publish_pending(incident_id)))
def close(self):
self._closing = True
self.cancel()
self.pending.clear()
self.execution_enabled.clear()
self.cancel_event.set()
if self._admitted_action is not None:
self._action_stop.set()
self._runtime_stopped()
@@ -72,6 +72,7 @@ class DshOperationsController(QObject):
self.decisions = DecisionLog(self.root)
self.dialog = None
self.worker = None
self._reserves_lane = False
self._read_pool = QThreadPool(QApplication.instance())
self._read_pool.setMaxThreadCount(1)
self.request_id = None
@@ -97,13 +98,13 @@ class DshOperationsController(QObject):
@property
def busy(self):
return bool(self.worker or self.dialog or self.request_id)
return bool((self.worker and self._reserves_lane) or self.dialog)
def attach(self, view):
view.stopped.connect(self.runtime_stopped)
def context(self):
value = {**self.cache, 'busy': bool(self.busy or self.window._workers or self._other_dialog())}
value = {**self.cache, 'busy': bool(self.worker or self.request_id or self.busy or self.window._workers or self._other_dialog())}
health = self.cache.get('health', {})
if health.get('checks'):
checks = [execution_check(self._execution_state()) if row['name'] == 'execution' else dict(row)
@@ -163,6 +164,7 @@ class DshOperationsController(QObject):
owner = self._request_task_ids[0] if request_id and self._request_task_ids else ''
self.window._dsh_blockers.watch(worker,
'DSH operations request' if request_id else '读取 DSH 监管记录', owner, area='operations')
self._reserves_lane = reserve_lane
if reserve_lane:
self.window._workers.add(worker)
def succeeded(value):
@@ -191,6 +193,7 @@ class DshOperationsController(QObject):
self.window._workers.discard(worker)
if self.worker is worker:
self.worker = None
self._reserves_lane = False
if not isValid(self.window) or self.window._closed:
return
self.window._bind_dsh_context()
@@ -237,7 +240,7 @@ class DshOperationsController(QObject):
def _retry_failed_read(self):
if self.window._closed or not self._read_failures:
return
if self.busy or self.window._workers or self._other_dialog():
if self.worker or self.request_id or self.busy or self.window._workers or self._other_dialog():
self._read_recheck.start()
else:
self.refresh()
@@ -319,7 +322,7 @@ class DshOperationsController(QObject):
'health': health, 'decisions': decisions, 'decision_audit': audit}
def refresh(self, *, synchronize_tickets=False):
if self.window._closed or self.window._workers or self.busy or self._other_dialog():
if self.window._closed or self.window._workers or self.worker or self.request_id or self.busy or self._other_dialog():
return
def done(value):
self.cache.update(value)
@@ -332,7 +335,7 @@ class DshOperationsController(QObject):
return bool((lifecycle and lifecycle.request_id) or (creation and creation.request_id))
def tick(self):
if self.window._closed or self.window._workers or self.busy or self._other_dialog():
if self.window._closed or self.window._workers or self.worker or self.request_id or self.busy or self._other_dialog():
return
self._ticks += 1
def ready(value):
@@ -380,7 +383,7 @@ class DshOperationsController(QObject):
self.window._dsh_lifecycle.request({'request_id': key, 'capability': 'execute',
'spec': {'operation': 'resume', 'run_id': spec['run_id']}})
return
if self.busy or self.window._workers or self._other_dialog() or self.window._closed:
if self.worker or self.request_id or self.busy or self.window._workers or self._other_dialog() or self.window._closed:
self._respond(key, status='busy', message='请等待当前操作或确认窗口收尾。'); return
self.request_id = key
ids = spec.get('task_ids', ())
@@ -448,7 +451,7 @@ class DshOperationsController(QObject):
self._work(loaded, lambda row: self._schedule_action(key, op, row), request_id=key, reserve_lane=False)
def _schedule_ready(self, key, draft, report, impact):
if self.window._workers or self.window._closed:
if self.window._workers or self.window._closed or self._other_dialog():
self._respond(key, status='busy', message='任务状态已变化,未打开排期确认。')
return
self.cache['impact'] = impact
@@ -477,7 +480,7 @@ class DshOperationsController(QObject):
dialog.accepted.connect(accept); dialog.rejected.connect(reject); dialog.open()
def _schedule_action(self, key, op, row):
if self.window._workers or self.window._closed:
if self.window._workers or self.window._closed or self._other_dialog():
self._respond(key, status='busy', message='任务状态已变化,未提交排期操作。')
return
if op == 'run_schedule':
@@ -181,7 +181,8 @@ class DshTaskLifecycleController(QObject):
record = self.window._dsh_operations.runs.inspect(self.window.service, spec['run_id'])
if not record['resume_ready'] or not record['remaining_task_ids'] or not record.get('diff', {}).get('safe', False):
raise TaskCenterError('run_blocked', '原执行不可直接接续:' + ', '.join(record['blockers']))
return record, api.preflight(self.window.service, record['task_ids'], allow_completed=True)
from ...dsh.run_journal import resume_preflight
return record, resume_preflight(self.window.service, record)
self._work(inspect, lambda pair: self._preflight_ready(request_id, capability, pair[0]['task_ids'], pair[1], resume=pair[0]), reserve_lane=False)
return
if capability == 'catalog' and isinstance(spec, dict) and not set(spec) - {'task_id'}:
@@ -109,6 +109,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._quick_run_confirmer = quick_run_confirmer or self._confirm_quick_run
self._task_id = None
self._context = None
self._problem_dialog = None
self._tasks = ()
self._known_task_groups = {}
self._workers = set()
@@ -165,6 +166,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self.run_panel.stop_queue_button.clicked.connect(self._pause_queue)
self.run_panel.force_stop_button.clicked.connect(self._force_batch_stop)
self.run_panel.retry_button.clicked.connect(self._retry_failed)
self.run_panel.problems_button.clicked.connect(self._open_execution_problems)
self.run_panel.recover_button.clicked.connect(self._recover_quick_run)
self.run_panel.cleanup_resources_button.clicked.connect(self._cleanup_batch_resources)
self.run_panel.diagnostics_button.clicked.connect(self._export_diagnostics)
@@ -381,6 +383,12 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._close_saving = True
self._run_async(lambda: archive_completed_session(self.service), self._session_archived)
return
automation = self._dsh_automation
if automation and getattr(automation, 'worker', None) and callable(getattr(automation, 'close', None)):
self._close_pending = True
automation.close()
event.ignore()
return
if self._dsh_view is not None and getattr(self._dsh_view, 'is_running', False):
# All confirmation/retention branches have passed; the remaining
# asynchronous shutdown is part of an accepted close request.
@@ -499,9 +507,12 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._dsh_status.update()
busy = bool(self._workers) or self._loading or self.history_panel._worker is not None
resources_pending = self._resource_status.blocked
dialog_state = getattr(self.service, '_supervisor_dialog_state', None) or {}
modal_pending = bool((dialog_state.get('supervision') or {}).get('blocked'))
self.history_panel.set_mutations_enabled(not busy and not resources_pending and self._batch_stop is None)
self.run_panel.cleanup_resources_button.setVisible(resources_pending and self._resource_status.known)
self.run_panel.cleanup_resources_button.setEnabled(resources_pending and self._resource_status.known and not busy)
self.run_panel.cleanup_resources_button.setText('处理阻塞弹窗' if modal_pending else '重试释放资源')
self.run_panel.cleanup_resources_button.setVisible(modal_pending or resources_pending and self._resource_status.known)
self.run_panel.cleanup_resources_button.setEnabled(modal_pending or resources_pending and self._resource_status.known and not busy)
state = execution_state(self._context, busy=busy,
dirty=self.plan_panel.table.dirty or self.plan_panel.table.has_pending_editor())
group_unsaved = self._group_has_unsaved_plans() if state.editable or state.new_round else False
@@ -510,6 +521,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self.run_panel.quick_run_button.setEnabled(state.execute and not resources_pending)
self.run_panel.retry_button.setVisible(bool(context and context.phase == 'retry'))
self.run_panel.retry_button.setEnabled(state.retry and not resources_pending)
self.run_panel.problems_button.setEnabled(bool(context and not busy))
self.run_panel.recover_button.setVisible(bool(context and context.interrupted))
self.run_panel.recover_button.setEnabled(state.recover and not resources_pending)
self.run_panel.new_round_button.setVisible(bool(context and context.task.status is TaskStatus.COMPLETED))
@@ -780,7 +792,11 @@ class TrialTaskCenterWindow(MaterialMainWindow):
if len(ids) <= 20:
from ...dsh import task_lifecycle as lifecycle
try:
report = lifecycle.preflight(self.service, list(ids), allow_completed=True)
if token:
from ...dsh.run_journal import resume_preflight
report = resume_preflight(self.service, self._dsh_operations.runs.inspect(self.service, token))
else:
report = lifecycle.preflight(self.service, list(ids), allow_completed=True)
except Exception as error:
self._show_error(error, owner_task_id=ids[0])
return
@@ -911,9 +927,35 @@ class TrialTaskCenterWindow(MaterialMainWindow):
def _cleanup_batch_resources(self):
if not self.run_panel.cleanup_resources_button.isEnabled():
return
state = getattr(self.service, '_supervisor_dialog_state', None) or {}
if (state.get('supervision') or {}).get('blocked'):
from .cad_dialog_operations import show_cad_dialogs
show_cad_dialogs(self)
self._update_gates()
return
force_confirmed = False
cleanup_finished = False
force_started = False
def start_force_if_ready():
nonlocal force_started
if force_confirmed and cleanup_finished and not force_started and not self._close_pending:
force_started = True
self._run_async(lambda: self.service.force_pending_owned_resources(confirmed=True),
forced, self.run_panel.cleanup_resources_button)
def after_cleanup():
nonlocal cleanup_finished
cleanup_finished = True
start_force_if_ready()
def forced(remaining):
self._resource_status.refresh()
self._set_operator_message('仍有资源未能确认释放,请保留诊断。' if remaining else
'自有残留资源已释放;相关工程仍须核验后恢复。', 'warning')
self._update_gates()
def done(pending):
nonlocal force_confirmed
hints = tuple(dict.fromkeys(row['resolution_hint'] for row in pending if row.get('resolution_hint')))
self._set_operator_message(
'后台资源仍待清理,请保留诊断记录后重试。' if pending else '后台资源已释放,可以继续。',
'\n'.join(hints) if hints else '后台资源仍待清理,请保留诊断记录后重试。' if pending else '后台资源已释放,可以继续。',
'warning' if pending else 'success')
if pending:
self._dsh_blockers.report('resource-release', '', 'batch_resources_pending',
@@ -921,8 +963,18 @@ class TrialTaskCenterWindow(MaterialMainWindow):
else:
self._dsh_blockers.clear('resource-release')
self._update_gates()
if pending and not any(row.get('force_available', True) for row in pending):
return
if pending and QMessageBox.question(self, '强制结束自有残留进程',
'安全释放尚未完成。是否强制结束本程序仍持有且能证明归属的残留进程?\n\n'
'可能存在未保存或部分保存的结果。中断证据会保留,相关工程必须先核验,不能直接再次替换。',
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No) == QMessageBox.StandardButton.Yes:
force_confirmed = True
# A modal question can deliver finished before returning Yes.
start_force_if_ready()
self._run_async(self.service.cleanup_batch_resources, done,
self.run_panel.cleanup_resources_button, operation_area='resources')
self.run_panel.cleanup_resources_button, operation_area='resources', on_finished=after_cleanup)
def _startup_resource_recheck(self):
if self._closed:
@@ -964,6 +1016,39 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._update_gates()
QThreadPool.globalInstance().start(worker)
def _open_execution_problems(self):
if not self._task_id or not self.run_panel.problems_button.isEnabled():
return
from .problem_items import ProblemItemsDialog
task_id = self._task_id
def loaded(overview):
if self._problem_dialog is not None:
self._problem_dialog.close()
dialog = ProblemItemsDialog(overview, allow_retry=bool(self._context and
self._context.phase == 'retry' and not self._context.interrupted
and not self._resource_status.blocked), parent=self)
self._problem_dialog = dialog
dialog.retry_requested.connect(lambda selection: self._prepare_selected_problem_retry(task_id, selection))
dialog.refresh_requested.connect(self._open_execution_problems)
def closed(_):
if self._problem_dialog is dialog:
self._problem_dialog = None
dialog.finished.connect(closed)
dialog.show()
self._run_async(lambda: self.service.execution_problem_overview(task_id), loaded,
self.run_panel.problems_button, expected_task_id=task_id)
def _prepare_selected_problem_retry(self, task_id, selection):
if task_id != self._task_id or not self.run_panel.retry_button.isEnabled():
self._set_operator_message('任务或执行状态已变化,请刷新问题列表后重试。', 'warning')
return
group_id = self._context.task.group_id
def prepared(_):
self._project_queues.pop(group_id, None)
self._load_task_data()
self._run_async(lambda: self.service.prepare_failed_quick_run(task_id, **selection),
prepared, self.run_panel.retry_button, expected_task_id=task_id)
def _retry_failed(self):
if self.run_panel.retry_button.isEnabled():
task_id = self._task_id
@@ -1043,6 +1128,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
QMessageBox.StandardButton.No) == QMessageBox.StandardButton.Yes
def _update_quick_run_elapsed(self):
self._update_gates()
if self._batch_stop is not None and not self._feedback_query.busy:
task_id, started = self._active_quick_run_task_id, self._run_started_at
run_id = self._dsh_run_id
@@ -1237,7 +1323,12 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._set_operator_message(state.message)
def _run_async(self, operation, callback, button=None, *, expected_task_id=None,
retain_result=False, operation_area='', **_unused):
retain_result=False, operation_area='', on_finished=None, **_unused):
"""Call on_finished after releasing the worker lane, including failures.
A modal result callback can receive finished before that callback returns.
Closing windows suppress the continuation.
"""
if (self._workers or self._closed or (self._dsh_task_creation is not None and self._dsh_task_creation.dialog is not None)
or (self._dsh_lifecycle is not None and self._dsh_lifecycle.dialog is not None)
or (self._dsh_operations is not None and self._dsh_operations.dialog is not None)):
@@ -1306,12 +1397,17 @@ class TrialTaskCenterWindow(MaterialMainWindow):
QTimer.singleShot(0, self.close)
if not self._closed:
self._update_gates()
if on_finished is not None and not self._close_pending:
on_finished()
worker.signals.succeeded.connect(succeeded)
worker.signals.failed.connect(failed)
worker.signals.finished.connect(finished)
self._update_gates()
QThreadPool.globalInstance().start(worker)
def _ai_ready(self):
return bool(self._dsh_status is not None and self._dsh_status.available)
def _show_error(self, error, *, owner_task_id=None, auto_intervene=True, operation_area='', **_unused):
stable = error if isinstance(error, TaskCenterError) else self.service.report_ui_error(error)
message = format_operation_error(stable)
@@ -1339,8 +1435,10 @@ class TrialTaskCenterWindow(MaterialMainWindow):
if owner_task_id is None or owner_task_id == self._task_id:
self._append_log(message)
self._update_gates()
ai_unavailable = self.auto_intervention_check.isChecked() and not self._dsh_status.available
if auto_intervene and not managed and not ai_unavailable and self.isVisible() and QApplication.platformName().casefold() != 'offscreen':
configuration = getattr(self._dsh_status, 'availability', {})
ai_unconfigured = self.auto_intervention_check.isChecked() and configuration.get('code') in {
'missing_configuration', 'missing_credential'}
if auto_intervene and not managed and not ai_unconfigured and self.isVisible():
QMessageBox.warning(self, '操作未完成', message)
def _cancel_dsh_diagnosis(self):
@@ -1352,11 +1450,12 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._layout_settings.setValue('dsh/auto_intervention', enabled)
self._layout_settings.sync()
if self._dsh_automation is not None:
self._dsh_automation.set_enabled(enabled and self._dsh_status.available)
self._dsh_automation.set_enabled(enabled and self._ai_ready())
if enabled:
self._observe_dsh_resource_blockers()
self._dsh_blockers.set_enabled(enabled)
self._dsh_status.update()
if self._dsh_status is not None:
self._dsh_status.update()
def _observe_dsh_resource_blockers(self):
status = self._resource_status
@@ -1412,7 +1511,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
def _enqueue_dsh_blocker(self, *, source, task_id, issue_code, run_id, message, details,
read_only, cleanup_allowed, snapshot):
if self._closed or not self.auto_intervention_check.isChecked() or not self._dsh_status.available:
if self._closed or not self.auto_intervention_check.isChecked() or not self._ai_ready():
return False
from ...dsh.evidence import scrub
if self._dsh_automation is None:
@@ -1433,7 +1532,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
read_only=read_only or not cleanup_allowed, cleanup_allowed=cleanup_allowed)
def _queue_dsh_incident(self, task_id, issue_code, message):
if not self.auto_intervention_check.isChecked() or not self._dsh_status.available:
if not self.auto_intervention_check.isChecked() or not self._ai_ready():
return False
if self._dsh_automation is None:
from .dsh_automation import DshAutomation
@@ -139,7 +139,20 @@ def replacement_result_rows(lines):
state = details.get('state')
location = ':'.join(str(details.get(key) or '') for key in ('schematic_name', 'sheet_number'))
verification = '已保存并核验' if state == 'saved_ok' else '已回读,保存待确认'
rows.extend((location, refdes, old, new, verification)
observation = details.get('value_readback')
if state in {'saved_ok', 'restored_ok'} and isinstance(observation, dict):
if observation.get('value_readback_status') == 'verified':
location = ':'.join(str(observation.get(key) or '') for key in ('schematic_name', 'sheet_number'))
for record in observation.get('value_readback', ()):
rows.append((location, record['refdes'], record['old_part_number'], record['actual_part_number'],
record.get('old_value') if record.get('old_value') is not None else '原值证据不明确',
record['actual_value'] if record['actual_value_present'] else '属性不存在', verification))
continue
actual_value = {'rejected': '回读证据被拒绝', 'ambiguous': '属性来源不明确'}.get(
observation.get('value_readback_status'), '未提供实际回读')
else:
actual_value = '未提供实际回读'
rows.extend((location, refdes, old, new, '未提供', actual_value, verification)
for refdes, old, new in _replacement_parts(str(event.get('message') or ''), state))
return tuple(rows)
@@ -0,0 +1,85 @@
"""Current-round issues, independent of paged and truncated execution logs."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (QAbstractItemView, QDialog, QHBoxLayout, QLabel, QMessageBox,
QPushButton, QTableWidget, QTableWidgetItem, QVBoxLayout)
class ProblemItemsDialog(QDialog):
retry_requested = Signal(object)
refresh_requested = Signal()
def __init__(self, overview, *, allow_retry=False, parent=None):
super().__init__(parent)
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
self.setWindowTitle('当前任务 · 问题项与定向重试')
self.resize(1120, 480)
self.overview = overview
self.summary = QLabel(f"失败 {overview['failed']} · 尚未执行 {overview['held']} · "
f"待核验 {overview['uncertain']} · 已解决 {overview['resolved']}")
self.notice = QLabel('仅可选择已失败项;成功项不会重放。待核验项须先核验并恢复。'
'尚有未执行项时,请先继续原队列,或使用工程级“重试失败项”准备失败及暂缓项。')
self.notice.setWordWrap(True)
headers = ('选择', '状态', '工程', '图页', '位号', 'UID', '原因', '可执行操作', '自动重试剩余')
self.table = QTableWidget(len(overview['items']), len(headers), objectName='problemItems')
self.table.setHorizontalHeaderLabels(headers)
self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.table.setAlternatingRowColors(True)
states = {'failed': '失败', 'pending': '尚未执行', 'prepared': '待核验', 'uncertain': '待核验',
'verified': '已解决', 'restored': '已解决', 'no_match': '已解决'}
for index, row in enumerate(overview['items']):
can_retry = allow_retry and row['can_retry']
action = ('可勾选手动重试' if can_retry else '先核验并恢复' if row['state'] in {'prepared', 'uncertain'}
else '继续原队列/工程级重试' if row['state'] in {'pending', 'failed'} else '无需操作')
values = ('', states.get(row['state'], row['state']), row['project_path'],
f"{row['schematic_name']} / {row['sheet_number']}", row['refdes'], row['uid'],
'\n'.join(value for value in (row['code'], row['message']) if value), action,
str(row['auto_retries_remaining']))
for column, value in enumerate(values):
item = QTableWidgetItem(value)
item.setToolTip(value)
item.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable)
if column == 0 and can_retry:
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable)
item.setCheckState(Qt.CheckState.Unchecked)
self.table.setItem(index, column, item)
for column, width in enumerate((45, 90, 200, 110, 70, 120, 260, 160, 95)):
self.table.setColumnWidth(column, width)
self.retry_button = QPushButton('准备所选失败项重试', objectName='retrySelectedProblems')
self.retry_button.setEnabled(False)
self.retry_button.clicked.connect(self._retry)
self.table.itemChanged.connect(lambda _: self.retry_button.setEnabled(bool(self.selected_items())))
refresh = QPushButton('刷新列表')
refresh.clicked.connect(self.refresh_requested)
close = QPushButton('关闭')
close.clicked.connect(self.reject)
actions = QHBoxLayout()
actions.addWidget(refresh)
actions.addStretch()
actions.addWidget(self.retry_button)
actions.addWidget(close)
layout = QVBoxLayout(self)
layout.addWidget(self.summary)
layout.addWidget(self.notice)
layout.addWidget(self.table, 1)
layout.addLayout(actions)
def selected_items(self):
return tuple(row for index, row in enumerate(self.overview['items'])
if self.table.item(index, 0).flags() & Qt.ItemFlag.ItemIsUserCheckable
and self.table.item(index, 0).checkState() == Qt.CheckState.Checked)
def _retry(self):
selected = self.selected_items()
if not selected:
return
scope = '\n'.join(f"{row['schematic_name']} / {row['sheet_number']} · {row['refdes']} · UID {row['uid']}"
for row in selected)
if QMessageBox.question(self, '确认定向重试',
f'仅准备以下 {len(selected)} 个失败项:\n{scope}\n\n保留原料号和 Value 策略。准备完成后需继续确认执行。',
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes:
return
self.retry_requested.emit(dict(operation_keys=tuple(row['operation_key'] for row in selected),
expected_round_id=self.overview['round_id'],
expected_generations={row['operation_key']: row['generation'] for row in selected}))
self.accept()
@@ -7,7 +7,7 @@ from time import monotonic
from PySide6.QtCore import Qt, QThreadPool, QObject, Signal, QSignalBlocker
from PySide6.QtGui import QAction,QKeySequence
from PySide6.QtWidgets import (QDialog, QDialogButtonBox, QFileDialog, QHBoxLayout, QLabel,
from PySide6.QtWidgets import (QCheckBox, QDialog, QDialogButtonBox, QFileDialog, QHBoxLayout, QLabel,
QLineEdit, QListWidget, QListWidgetItem, QMessageBox, QPushButton,
QVBoxLayout, QWidget, QToolButton, QMenu)
from shiboken6 import isValid
@@ -222,6 +222,11 @@ class ProjectPlanPanel(QWidget):
self.report_toggle.hide()
self.report_toggle.toggled.connect(self._toggle_report)
self.last_bom_report = None
self.partial_bom = QCheckBox('允许部分导入通过工程', objectName='allowPartialBom')
self.partial_bom.setToolTip('仅核验前置检查通过的工程;报告返回后仍需选择工程并确认。')
self.partial_bom_button = QPushButton('选择通过工程…', objectName='selectPassedBomProjects')
self.partial_bom_button.hide()
self.partial_bom_button.clicked.connect(self._choose_passed_projects)
toolbar=QWidget(objectName='planToolbar')
actions=QHBoxLayout(toolbar)
actions.setContentsMargins(0,3,0,3);actions.setSpacing(8)
@@ -264,6 +269,8 @@ class ProjectPlanPanel(QWidget):
self.find_result.hide()
layout.addLayout(summary_row)
layout.addWidget(self.report_toggle)
layout.addWidget(self.partial_bom)
layout.addWidget(self.partial_bom_button)
layout.addWidget(self.table, 1)
layout.addLayout(selection)
self.collect_button.clicked.connect(self.collect)
@@ -428,7 +435,7 @@ class ProjectPlanPanel(QWidget):
def _release_bom_previews(self, saved=None):
for machine in self._bom_imports.values():
report = machine.state.report
preview = report.preview if report is not None else None
preview = (report.preview or report.passed_preview) if report is not None else None
if preview is not None and (saved is None or all(p.task_id in saved for p in preview.projects)):
machine.release_preview(saved=saved is not None)
self._restore_bom_report(self._report_scope(self.task_id))
@@ -655,8 +662,9 @@ class ProjectPlanPanel(QWidget):
if paths:
task_id = self.task_id
scope = self._report_scope(task_id)
partial = {'allow_partial': True} if self.partial_bom.isChecked() else {}
self._dispatch_cancellable(lambda stop, progress, phase: self.window.service.preview_bom_sources(
task_id, tuple(Path(path) for path in paths), stop_event=stop, on_progress=progress, on_phase=phase),
task_id, tuple(Path(path) for path in paths), stop_event=stop, on_progress=progress, on_phase=phase, **partial),
lambda report: self._received_bom_report(report, scope=scope, owner_task_id=task_id), self.import_bom_button,
bom_scope=scope)
@@ -699,6 +707,8 @@ class ProjectPlanPanel(QWidget):
_, self.report_text, title = self._format_bom_report(state)
self.report_toggle.setText(title)
self.report_toggle.setVisible(state.report is not None)
self.partial_bom_button.setVisible(state.report is not None and state.report.preview is None
and state.report.passed_preview is not None and not state.notice and not state.busy)
if state.report is None:
self.report_toggle.setChecked(False)
if self.report_dialog is not None:
@@ -726,6 +736,8 @@ class ProjectPlanPanel(QWidget):
details.append(state.notice)
elif report.preview is None:
details.append('本次未暂存或保存新计划,原有预览和编辑保留;请修正后重新导入。')
if report.passed_preview is not None:
details.append('可点击“选择通过工程…”确认部分导入;失败行及其来源记录保留。')
else:
details.append('校验通过,已暂存预览;请确认后保存本批位号计划。')
title = f'本批 BOM {outcome} · 通过 {report.passed_rows} / 失败 {report.failed_rows} / 未检查 {report.unchecked_rows} 行 · 详情'
@@ -776,6 +788,43 @@ class ProjectPlanPanel(QWidget):
return next((batch for batch in (*self._bom_batches.values(), *self._orphaned_bom_batches.values())
if any(project.task_id == self.task_id for project in batch.projects)), None)
def _choose_passed_projects(self):
report = self.last_bom_report
if report is None or report.passed_preview is None:
return
dialog = QDialog(self)
dialog.setWindowTitle('确认部分导入工程')
layout = QVBoxLayout(dialog)
layout.addWidget(QLabel('仅导入勾选工程的原预览行;失败工程保留原计划。'))
choices = QListWidget()
for project in report.passed_preview.projects:
item = QListWidgetItem(str(project.project_path))
item.setData(Qt.ItemDataRole.UserRole, project.task_id)
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable)
item.setCheckState(Qt.CheckState.Unchecked)
choices.addItem(item)
layout.addWidget(choices)
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
buttons.accepted.connect(dialog.accept)
buttons.rejected.connect(dialog.reject)
layout.addWidget(buttons)
if dialog.exec() == QDialog.DialogCode.Accepted:
selected = tuple(choices.item(i).data(Qt.ItemDataRole.UserRole) for i in range(choices.count())
if choices.item(i).checkState() == Qt.CheckState.Checked)
if selected:
self.accept_passed_projects(selected)
def accept_passed_projects(self, task_ids):
from ..bom_import_report import select_passed_projects
machine = self._bom_imports.get(self._report_scope(self.task_id))
if machine is None or machine.state.busy:
return
preview = select_passed_projects(machine.state.report, task_ids)
self._preview_bom(preview)
machine.state = replace(machine.state, report=replace(machine.state.report, passed_preview=preview),
notice=f'已明确选择 {len(preview.projects)} 个通过工程,待保存原预览行。')
self._restore_bom_report(self._report_scope(self.task_id))
def _preview_bom(self, batch):
if self.task_id and self.table.dirty:
self._drafts[self.task_id] = self.table.rows()
@@ -30,6 +30,8 @@ class RunPanel(QWidget):
self.force_stop_button = QPushButton('强制结束…', objectName='forceStopButton')
self.force_stop_button.setToolTip('异常情况下使用;会中断当前操作,结果必须重新核验。')
self.retry_button = QPushButton('重试失败项', objectName='retryTaskItems')
self.retry_button.setToolTip('准备本工程失败及暂缓项。也可从“更多操作”的问题项列表定向选择。')
self.problems_button = QPushButton('问题项 / 定向重试', objectName='executionProblems')
self.recover_button = QPushButton('核验并恢复', objectName='recoverQuickRunButton')
self.cleanup_resources_button = QPushButton('重新清理资源', objectName='cleanupBatchResources')
self.cleanup_resources_button.setToolTip('只释放本程序拥有的后台资源,不执行工程替换。')
@@ -47,7 +49,7 @@ class RunPanel(QWidget):
self.log_dialog = None
self.toggle_log_button.toggled.connect(self._toggle_log)
self.more_menu=CommandMenu(self)
for button in (self.diagnostics_button,self.cleanup_resources_button,self.history_button,self.reset_layout_button):
for button in (self.problems_button,self.diagnostics_button,self.cleanup_resources_button,self.history_button,self.reset_layout_button):
self.more_menu.add_button(button)
self.more_button=QToolButton(objectName='executionMoreMenu')
self.more_button.setText('更多操作')
@@ -0,0 +1,166 @@
"""Persist observed values; command and terminal proof remain the authority."""
import hashlib
import json
import re
from .batch_resources import write_record
from .path_access import internal_path
from .quick_run_protocol import _decode_vbs_field
def _paths(root, row):
job = row['job_id']
if not re.fullmatch(r'[A-Za-z0-9_-]+', job):
raise ValueError('invalid Value report job identity')
root = internal_path(root)
return root / f'value-readback-{job}.tsv', root / f'value-readback-{job}.json', root / f'snapshot-{job}.tsv'
def clear_value_readback(root, row):
"""Discard prior observation before dispatch, so a retry cannot reuse it."""
raw, saved, _ = _paths(root, row)
raw.unlink(missing_ok=True)
saved.unlink(missing_ok=True)
def _digest(data):
return hashlib.sha256(data).hexdigest()
def _read(path):
if path.stat().st_size > 16 * 1024 * 1024:
raise ValueError('Value evidence exceeds size limit')
return path.read_bytes()
def _fields(line):
return tuple(_decode_vbs_field(field) for field in line.split('\t'))
def _validated(root, row, outcome):
raw, _, snapshot_path = _paths(root, row)
state, code, message = outcome
if state not in {'saved_ok', 'restored_ok'}:
raise ValueError('Value report requires a verified replacement terminal state')
status_bytes = _read(internal_path(root) / 'status.tsv')
terminal = _fields(status_bytes.decode('utf-8-sig').splitlines()[-1])
if terminal != (row['job_id'], state, code, message):
raise ValueError('Value report does not belong to the current terminal job')
raw_bytes, snapshot_bytes = _read(raw), _read(snapshot_path)
snapshot = snapshot_bytes.decode('utf-8-sig')
lines = raw_bytes.decode('utf-8-sig').splitlines()
header = _fields(lines[0])
expected = ('V', '2', row['task_id'], row['job_id'], state, row['project_path'],
row.get('schematic_name', ''), row.get('sheet_number', ''), row['old_part'], row['new_part'],
row['value_mode'], row.get('custom_value', ''), row.get('sync_nc', '1'), row.get('target_cell', ''),
row.get('target_selectors', ''), snapshot)
if header != expected:
raise ValueError('Value report version, command or current snapshot differs')
components, old_values, source_nc = {}, {}, set()
def has_nc(value):
return any(part.strip().casefold() == 'nc' for part in value.split('/')[1:])
for line in snapshot.splitlines():
fields = _fields(line)
if fields[0] == 'C':
if len(fields) != 8 or not fields[1] or fields[1] in components:
raise ValueError('snapshot component identity is invalid')
components[fields[1]] = fields[2]
elif fields[0] == 'A' and len(fields) == 12 and fields[2].casefold() == 'value':
old_values.setdefault(fields[1], []).append(fields[4] or fields[3])
if (fields[0] == 'A' and len(fields) == 12 and fields[2].casefold() == 'value'
and has_nc(fields[4] or fields[3])):
source_nc.add(fields[1])
selectors = row.get('target_selectors', '')
if row.get('target_scope') == 'targets':
selected = {parts[0]: parts[1] for selector in selectors.split('\x1e')
if len(parts := selector.split('\x1f')) == 3}
if components != selected:
raise ValueError('Value snapshot UID set differs from frozen command')
values, observations, seen, ordinals = [], [], set(), set()
names = {}
for line in lines[1:]:
fields = _fields(line)
if fields[0] == 'C' and len(fields) == 7:
_, uid, ref, part, value, present, cell = fields
if (uid not in components or uid in seen or components[uid] != ref or present not in {'0', '1'}
or part.casefold() != row['new_part'].casefold()
or (row.get('target_cell') and cell != row['target_cell'])):
raise ValueError('foreign, duplicate or inconsistent Value identity/Part Number/Cell')
seen.add(uid)
expected = {'custom': row.get('custom_value', ''), 'part_number': part}.get(row['value_mode'])
if expected is not None:
if row.get('sync_nc', '1') == '1' and uid in source_nc and not has_nc(expected):
expected = expected.rstrip() + ('NC' if expected.rstrip().endswith('/') else '/NC')
if present != '1' or value != expected:
raise ValueError('actual Value contradicts verified command policy')
before = old_values.get(uid, [])
values.append(dict(uid=uid, refdes=ref, old_part_number=row['old_part'], actual_part_number=part,
old_value=before[0] if len(before) == 1 else None, actual_value=value,
old_value_present=bool(before), actual_value_present=present == '1', actual_cell=cell))
elif fields[0] == 'E' and len(fields) == 7:
_, uid, ordinal, name, raw_value, instance, layer = fields
if uid not in components or not ordinal.isdigit() or layer != 'unknown' or (uid, ordinal) in ordinals:
raise ValueError('invalid attribute observation identity')
ordinals.add((uid, ordinal))
names.setdefault((uid, name.casefold()), []).append(int(ordinal))
observations.append(dict(uid=uid, ordinal=int(ordinal), name=name, raw_value=raw_value,
instance_value=instance, layer='unknown'))
else:
raise ValueError('invalid Value report record')
if not components or seen != set(components):
raise ValueError('Value report UID set is incomplete')
if (_read(internal_path(root) / 'status.tsv') != status_bytes or _read(raw) != raw_bytes
or _read(snapshot_path) != snapshot_bytes):
raise ValueError('Value evidence changed during validation')
ambiguities = [dict(uid=uid, name=name, ordinals=indices) for (uid, name), indices in names.items() if len(indices) > 1]
details = dict(value_readback_status='ambiguous' if ambiguities else 'verified', value_readback=values,
value_readback_job_id=row['job_id'], project_path=row['project_path'],
schematic_name=row.get('schematic_name', ''), sheet_number=row.get('sheet_number', ''),
attribute_observations=observations, attribute_ambiguities=ambiguities)
binding = dict(command=dict(row), terminal=list(terminal), status_sha256=_digest(status_bytes),
snapshot_sha256=_digest(snapshot_bytes), report_sha256=_digest(raw_bytes))
return details, binding
def capture_value_readback(root, row, outcome):
try:
details, binding = _validated(root, row, outcome)
_, saved, _ = _paths(root, row)
write_record(saved, dict(schema=2, binding=binding, details=details))
return details
except FileNotFoundError:
return {'value_readback_status': 'unavailable'}
except (OSError, UnicodeError, ValueError, KeyError, IndexError, TypeError) as error:
return {'value_readback_status': 'rejected', 'value_readback_reason': str(error)}
def load_value_readback(root, row, outcome):
try:
details, binding = _validated(root, row, outcome)
_, saved, _ = _paths(root, row)
persisted = json.loads(_read(saved))
if persisted != dict(schema=2, binding=binding, details=details):
raise ValueError('persisted Value evidence binding changed')
return details
except FileNotFoundError:
return {'value_readback_status': 'unavailable'}
except (OSError, UnicodeError, ValueError, KeyError, IndexError, TypeError) as error:
return {'value_readback_status': 'rejected', 'value_readback_reason': str(error)}
def value_readback_details(result):
"""Read only the verified persisted observation for this returned terminal."""
if result.state not in {'saved_ok', 'restored_ok'}:
return {}
try:
from .execution_journal import read_command_rows
terminal = _fields(_read(internal_path(result.status_path)).decode('utf-8-sig').splitlines()[-1])
if len(terminal) != 4 or terminal[1] != result.state or terminal[3] != result.message:
raise ValueError('returned result differs from current terminal job')
rows = tuple(row for row in read_command_rows(result.command_path) if row['job_id'] == terminal[0])
if len(rows) != 1:
raise ValueError('terminal job is not uniquely bound to current command')
details = load_value_readback(result.status_path.parent, rows[0], terminal[1:])
except (OSError, UnicodeError, ValueError, KeyError, IndexError, TypeError) as error:
details = {'value_readback_status': 'rejected', 'value_readback_reason': str(error)}
return {'value_readback': details}
@@ -13,12 +13,107 @@ import time
import threading
from uuid import uuid4
PROJECT_OPEN_IDLE_TIMEOUT_SECONDS = 45
READ_ONLY_CANCEL_GRACE_SECONDS = 5
READ_ONLY_IDLE_TIMEOUT_SECONDS = 45
class WorkerMonitorError(subprocess.SubprocessError):
pass
class WorkerMonitorCancelled(WorkerMonitorError):
"""An owned worker was stopped at an admitted cancellation boundary."""
def __init__(self, message, *, stage):
super().__init__(message)
self.stage = stage
self.cleanup_notes = ()
class WorkerMonitorSafeTimeout(WorkerMonitorError):
"""A project-open stage timed out before any possible mutation."""
def __init__(self, message, *, stage):
super().__init__(message)
self.stage = stage
self.cleanup_notes = ()
self.prewrite_cleanup_confirmed = False
_PROGRESS_FAILURE_LOGGED: dict[str, float] = {}
RETAINED_WORKERS = {}
def _worker_tree_exited(process, owned):
from .read_recovery import process_tree_exited
try:
observe = getattr(owned, 'tree_exited', None)
return process_tree_exited(process) and (observe is None or observe())
except Exception:
return False
def _wait_worker_tree_exit(process, owned, deadline):
while not _worker_tree_exited(process, owned) and time.monotonic() < deadline:
time.sleep(.01)
return _worker_tree_exited(process, owned)
def _retain_worker(root, token, job_id, process, owned, close_process, error):
from .batch_resources import process_identity, write_record
from .stop_control import protect_interruption
from .retained_worker_recovery import boot_identity
path = root / ('retained-worker-' + token + '.json')
entry = dict(root=root, path=path, token=token, job_id=job_id, process=process,
owned=owned, close_process=close_process)
# Keep the handles even if writing the protection/ownership proof fails.
RETAINED_WORKERS[str(path)] = entry
protect_interruption(root, 'worker_retained: ' + str(error))
identity = process_identity(process)
entry['identity'] = identity
boot = boot_identity()
write_record(path, dict(version=1, state='blocked', token=token, job_id=job_id,
process=identity, error=str(error), **({'retained_boot_id': boot} if boot else {})))
def cleanup_retained_workers(root, *, force=False):
from .batch_resources import process_identity, write_record
from .errors import TaskCenterError
from .path_access import canonical_path, internal_path
from .stop_control import protect_interruption
for key, entry in tuple(RETAINED_WORKERS.items()):
if not entry['root'].is_relative_to(canonical_path(root)):
continue
process, owned = entry['process'], entry['owned']
if not entry.get('resources_released') and not _worker_tree_exited(process, owned):
if not force:
continue
record = json.loads(internal_path(entry['path']).read_text(encoding='utf-8'))
identity = process_identity(process)
if (not identity.get('creation_time') or identity != entry.get('identity')
or record.get('process') != identity or record.get('version') != 1
or record.get('token') != entry['token'] or record.get('job_id') != entry['job_id']):
raise TaskCenterError('target_identity', '保留工作进程身份与证据不符,拒绝强制结束。')
protect_interruption(entry['root'], 'user_confirmed_force_pending_owned_resources')
write_record(entry['path'], dict(record, force_state='requested', force_confirmed=True))
if entry['close_process']:
process.terminate()
else:
owned.terminate()
process.wait(timeout=10)
deadline = time.monotonic() + 10
while not _worker_tree_exited(process, owned) and time.monotonic() < deadline:
time.sleep(.01)
if not entry.get('resources_released') and not _worker_tree_exited(process, owned):
continue
if not entry.get('resources_released'):
if entry['close_process']:
process.close()
owned.close()
entry['resources_released'] = True
# Physical release never clears the durable business uncertainty.
write_record(entry['path'], dict(version=1, state='released', token=entry['token'],
job_id=entry['job_id'], process=entry.get('identity'), processes_exited=True))
RETAINED_WORKERS.pop(key)
class ProgressWatch:
@@ -30,6 +125,7 @@ class ProgressWatch:
self.current_job_id = job_id
self.idle_timeout = idle_timeout
self.last_progress = started
self.last_business_progress = started
self.sequence = 0
self.native_sequence = 0
self.native_progress_frames = 0
@@ -38,6 +134,7 @@ class ProgressWatch:
self.done = 0
self.total = 0
self.safe_stop = True
self.unsafe_seen = False
self.waiting_for_safe_completion = False
self.started = started
self.stage_started = started
@@ -58,6 +155,9 @@ class ProgressWatch:
return False
except (ValueError, UnicodeError):
return False
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
if current_job != self.current_job_id:
self.current_job_id = current_job
self.stage_seconds = {}
@@ -71,6 +171,7 @@ class ProgressWatch:
self.native_sequence = 0
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
@@ -98,15 +199,20 @@ class ProgressWatch:
self.native_sequence = sequence
self.native_progress_frames += 1
self.last_progress = now
if (done, total) != (self.done, self.total):
self.last_business_progress = now
self.done, self.total = done, total
return True
def action(self, now: float) -> str | None:
idle = now - self.last_progress
if not self.stop_requested and idle >= self.idle_timeout:
idle = now - self.last_business_progress
idle_timeout = self.idle_timeout
if self.stage == 'open_project' and self.safe_stop:
idle_timeout = min(idle_timeout, PROJECT_OPEN_IDLE_TIMEOUT_SECONDS)
if not self.stop_requested and idle >= idle_timeout:
self.stop_requested = True
return 'request_stop'
if self.stop_requested and idle >= self.idle_timeout * 2:
if self.stop_requested and idle >= idle_timeout * 2:
if not self.safe_stop:
if not self.waiting_for_safe_completion:
self.waiting_for_safe_completion = True
@@ -122,6 +228,8 @@ class ProgressWatch:
return {name: getattr(self, name) for name in ('token', 'sequence', 'stage', 'done', 'total', 'safe_stop', 'stop_requested', 'waiting_for_safe_completion')} | {
'job_id': self.current_job_id,
'native_progress_frames': self.native_progress_frames,
'business_idle_seconds': max(0.0, now - self.last_business_progress),
'heartbeat_idle_seconds': max(0.0, now - self.last_progress),
'elapsed_seconds': max(0.0, now - self.started), 'stage_seconds': stages}
@@ -159,12 +267,22 @@ class _OwnedWorkers:
self.job = win32job.CreateJobObject(None, 'DxPartReplace-monitor-' + token)
self.allowed = {os.path.normcase(os.path.abspath(value)) for value in allowed}
def tree_exited(self):
import win32job
return not win32job.QueryInformationJobObject(self.job,
win32job.JobObjectBasicAccountingInformation)['ActiveProcesses']
def terminate(self):
import win32job
win32job.TerminateJobObject(self.job, 1)
def assign(self, process: subprocess.Popen) -> None:
import win32job
win32job.AssignProcessToJobObject(self.job, process._handle)
def stop_workers(self, process: subprocess.Popen) -> list[str]:
import pywintypes
import win32api
import win32job
@@ -190,7 +308,10 @@ class _OwnedWorkers:
else:
failures.append(f'preserved_non_worker pid={process_id}')
except Exception as error:
failures.append(f'child_cleanup pid={process_id} error={error}')
vanished = (handle is None and isinstance(error, (OSError, pywintypes.error))
and getattr(error, 'winerror', None) == 87)
if not vanished: # OpenProcess may observe an already exited PID.
failures.append(f'child_cleanup pid={process_id} error={error}')
finally:
if handle is not None:
handle.Close()
@@ -206,7 +327,8 @@ class _OwnedWorkers:
def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abort_event=None,
process_factory=None, cooperative_abort=False, force_event=None, force_control=None) -> subprocess.CompletedProcess[str]:
process_factory=None, cooperative_abort=False, force_event=None, force_control=None,
owner_loss_path=None) -> subprocess.CompletedProcess[str]:
root = Path(command[3]).resolve()
job_id = command[-1]
token = uuid4().hex
@@ -215,12 +337,19 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
progress_path = root / 'worker-progress.json'
native_progress_path = root / f'monitor-{token}.native-progress'
root.mkdir(parents=True, exist_ok=True)
watch = ProgressWatch(token, job_id, idle_timeout, time.monotonic())
watch = ProgressWatch(token, job_id,
min(idle_timeout, READ_ONLY_IDLE_TIMEOUT_SECONDS) if cooperative_abort else idle_timeout,
time.monotonic())
if force_control is not None:
force_event = force_control.force_event
owned = _OwnedWorkers(token, {command[0], command[4]})
process = None
retained = False
durable_force_accepted = False
read_cancel_started = None
read_idle_stop_started = None
stop_write_pending = False
stop_warning = ''
threads = []
messages = queue.Queue(maxsize=1024)
stop_readers = threading.Event()
@@ -247,6 +376,25 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
elif len(output[channel]) < 1024 * 1024:
output[channel].extend(line[:1024 * 1024 - len(output[channel])])
def request_stop():
nonlocal stop_write_pending, stop_warning
try:
_atomic_text(stop, token)
except OSError as error:
stop_write_pending = True
warning = '暂停请求尚未写入,保留进程并重试:' + str(error)
if warning != stop_warning:
import logging
logging.getLogger(__name__).warning('%s', warning)
stop_warning = warning
if force_control is not None:
force_control.control_error = warning
else:
stop_write_pending = False
if force_control is not None and force_control.control_error == stop_warning:
force_control.control_error = ''
stop_warning = ''
try:
if process_factory is None:
process = subprocess.Popen((*command, token), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
@@ -263,6 +411,16 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
_publish_progress(progress_path, watch.snapshot())
_atomic_text(ready, token)
while process.poll() is None:
if cooperative_abort and owner_loss_path is not None and Path(owner_loss_path).is_file():
# The admitted read owner was lost. This only stops this exact
# read worker; its runtime releases the complete generation.
if read_cancel_started is None:
read_cancel_started = time.monotonic()
if not watch.stop_requested:
watch.stop_requested = True
request_stop()
if time.monotonic() - read_cancel_started >= READ_ONLY_CANCEL_GRACE_SECONDS:
raise WorkerMonitorCancelled('read owner exited before the read completed', stage=watch.stage)
if force_event is not None and force_event.is_set():
from .stop_control import protect_interruption
try:
@@ -276,20 +434,26 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
else:
durable_force_accepted = True
raise WorkerMonitorError('user forced stop; execution requires reconciliation')
if stop_write_pending:
request_stop()
if abort_event is not None and abort_event.is_set():
if not cooperative_abort and watch.safe_stop:
raise WorkerMonitorError('project session supervisor requested worker cleanup')
if cooperative_abort and read_cancel_started is None:
read_cancel_started = time.monotonic()
if (read_cancel_started is not None and
time.monotonic() - read_cancel_started >= READ_ONLY_CANCEL_GRACE_SECONDS):
raise WorkerMonitorCancelled(
'read-only worker did not acknowledge cancellation within its grace period', stage=watch.stage)
if not watch.stop_requested:
# Read-only callers request the VBS safe boundary first.
# The existing idle watchdog still bounds a stalled COM call.
# Request a worker boundary; queued unsafe progress may not
# have reached watch yet, so ordinary pause cannot kill here.
watch.stop_requested = True
watch.last_progress = time.monotonic()
try:
_atomic_text(stop, token)
except OSError:
if watch.safe_stop:
raise
watch.last_business_progress = watch.last_progress
request_stop()
_publish_progress(progress_path, watch.snapshot())
if (read_idle_stop_started is not None and time.monotonic() - read_idle_stop_started >=
min(READ_ONLY_CANCEL_GRACE_SECONDS, watch.idle_timeout)):
raise subprocess.TimeoutExpired(command, watch.idle_timeout)
try:
receive(*messages.get(timeout=min(0.1, idle_timeout / 10)))
for pending in range(128):
@@ -309,20 +473,29 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
break
action = watch.action(time.monotonic())
if action == 'request_stop':
try:
_atomic_text(stop, token)
except OSError:
if watch.safe_stop:
raise
if cooperative_abort:
read_idle_stop_started = time.monotonic()
request_stop()
_publish_progress(progress_path, watch.snapshot())
elif action == 'await_safe_completion':
if cooperative_abort:
# This entry point is explicitly read-only. A blocked COM
# read has no write to finish and retains its bounded cancel.
raise subprocess.TimeoutExpired(command, idle_timeout * 2)
from .stop_control import StopControl
if not isinstance(force_control, StopControl):
raise WorkerMonitorError('unsafe worker stalled without an interactive controller')
_publish_progress(progress_path, watch.snapshot())
elif action == 'unresponsive':
if stop_write_pending and not cooperative_abort:
watch.waiting_for_safe_completion = True
_publish_progress(progress_path, watch.snapshot())
continue
if watch.safe_stop and not watch.unsafe_seen and watch.stage == 'open_project':
raise WorkerMonitorSafeTimeout('project open made no progress; safe stop was requested',
stage=watch.stage)
raise subprocess.TimeoutExpired(command, idle_timeout * 2)
exit_deadline = time.monotonic() + 10
drain_deadline = time.monotonic() + 5
while (any(thread.is_alive() for thread in threads) or not messages.empty()) and time.monotonic() < drain_deadline:
try:
@@ -330,27 +503,53 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
except queue.Empty:
pass
_publish_progress(progress_path, watch.snapshot())
# A root can exit before Job accounting confirms its descendants exited.
if not cooperative_abort and not _wait_worker_tree_exit(process, owned, exit_deadline):
raise WorkerMonitorError('worker root exited while owned descendants remain; reconciliation required')
return subprocess.CompletedProcess(command, process.returncode, _decode(output[0]), _decode(output[1]))
except Exception as error:
if process is not None:
if (not watch.safe_stop and not cooperative_abort and force_control is not None
and not durable_force_accepted):
from .stop_control import wait_for_resolution
if (not cooperative_abort and not durable_force_accepted
and (not watch.safe_stop or process.poll() is not None)
and not _worker_tree_exited(process, owned)):
from .stop_control import StopControl, wait_for_resolution
if not isinstance(force_control, StopControl):
retained = True
_retain_worker(root, token, job_id, process, owned, process_factory is not None, error)
raise WorkerMonitorError('owned worker retained for explicit force or confirmed exit: ' + str(error)) from error
try:
wait_for_resolution(force_control, root, error)
wait_for_resolution(force_control, root, error,
resolved=lambda: _worker_tree_exited(process, owned))
except WorkerMonitorError:
if not force_event.is_set():
raise
durable_force_accepted = True
cleanup_deadline = time.monotonic() + 10
failures = owned.stop_workers(process)
process.wait(timeout=10)
for thread in threads:
thread.join(2)
if (isinstance(error, WorkerMonitorSafeTimeout) and not watch.unsafe_seen
and all(note.startswith('preserved_non_worker ') for note in failures)):
# Root exit and Job accounting need not become observable in
# the same tick. Confirm naturally exiting descendants within
# the existing worker-cleanup budget; never force unknown ones.
_wait_worker_tree_exit(process, owned, cleanup_deadline)
diagnostic = watch.snapshot() | {'monitor_error': str(error), 'worker_cleanup_notes': failures}
try:
_atomic_text(progress_path, json.dumps(diagnostic, ensure_ascii=False))
except OSError:
pass
if (isinstance(error, WorkerMonitorSafeTimeout) and not watch.unsafe_seen
and _worker_tree_exited(process, owned)
and all(note.startswith('preserved_non_worker ') for note in failures)):
# A console host may exit naturally after its worker. Never kill
# it or trust the root PID alone; the empty owned tree is proof.
error.cleanup_notes = tuple(failures)
error.prewrite_cleanup_confirmed = True
raise error
if isinstance(error, WorkerMonitorCancelled) and not failures:
raise error
if isinstance(error, subprocess.TimeoutExpired):
raise
raise WorkerMonitorError(f'Worker monitoring failed after launch; execution requires reconciliation: {error}') from error
@@ -359,6 +558,13 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
stop_readers.set()
for thread in threads:
thread.join(0.2)
owned.close()
if process_factory is not None and process is not None:
process.close()
if (not retained and process is not None and not cooperative_abort and not durable_force_accepted
and not _worker_tree_exited(process, owned)
and (not watch.safe_stop or process.poll() is not None)):
retained = True
_retain_worker(root, token, job_id, process, owned, process_factory is not None,
'worker monitor cleanup did not prove the owned tree exited')
if not retained:
owned.close()
if process_factory is not None and process is not None:
process.close()
@@ -1,6 +1,7 @@
"""Safe multi-file BOM loading and project routing for workspace imports."""
from dataclasses import dataclass
import hashlib
from pathlib import Path, PureWindowsPath
from openpyxl import load_workbook
@@ -24,6 +25,7 @@ class SourceRow:
excel_row: int
values: tuple
value_mode: str = 'inherit'
source_sha256: str = ''
@property
def project_name(self):
@@ -53,7 +55,7 @@ def _selected_xlsx(sources):
return tuple(sorted(paths, key=lambda path: str(path).casefold()))
def load_sources(sources, *, stop_event=None, on_progress=None):
def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=False):
"""Read every selected workbook before any CAD operation starts."""
from .operation_control import check_cancelled
@@ -67,6 +69,7 @@ def load_sources(sources, *, stop_event=None, on_progress=None):
on_progress(f'正在读取 BOM {number}/{len(paths)}:{path.name}')
workbook = None
try:
source_sha256 = hashlib.sha256(path.read_bytes()).hexdigest()
workbook = load_workbook(path, read_only=True, data_only=False)
if len(workbook.worksheets) != 1:
raise ValueError('BOM 只能包含一个工作表')
@@ -84,13 +87,18 @@ def load_sources(sources, *, stop_event=None, on_progress=None):
positions = {name: index for index, name in enumerate(headers) if name}
for excel_row, cells in enumerate(rows, 2):
check_cancelled(stop_event)
if any(cell.data_type == 'f' for cell in cells):
formula = any(cell.data_type == 'f' for cell in cells)
if formula and not allow_partial:
raise ValueError(f'Excel 第 {excel_row} 行不接受公式')
values = tuple(
cells[positions[name]].value if name in positions and positions[name] < len(cells) else ''
for name in BOM_HEADERS
)
if not any(values[index] not in (None, '') for index in (2, 3, 4, 9)):
if formula and allow_partial:
# Even a formula in an unmapped extra column rejects its
# original row; keep a formula marker for the strict parser.
values = (*values[:8], '=INVALID_SOURCE_FORMULA()', *values[9:])
if not any(values[index] not in (None, '') for index in (2, 3, 4, 9)) and not formula:
continue
project_path = str(values[1] or '').strip()
if project_path and not (Path(project_path).is_absolute() or PureWindowsPath(project_path).is_absolute()):
@@ -99,12 +107,15 @@ def load_sources(sources, *, stop_event=None, on_progress=None):
_part_number_text(cells, positions, 'old_part_number', '旧料号')
_part_number_text(cells, positions, 'new_part_number', '新料号')
except ValueError as error:
raise ValueError(f'Excel 第 {excel_row} 行:{error}') from error
if not allow_partial:
raise ValueError(f'Excel 第 {excel_row} 行:{error}') from error
default_mode = 'custom' if str(values[9] or '').strip() else 'inherit'
value_mode = str(cells[positions['value_mode']].value or default_mode).strip() if 'value_mode' in positions else default_mode
if value_mode not in {'inherit', 'preserve', 'part_label', 'part_number', 'custom'}:
if value_mode not in {'inherit', 'preserve', 'part_label', 'part_number', 'custom'} and not allow_partial:
raise ValueError(f'Excel 第 {excel_row} 行 Value 来源无效')
result.append(SourceRow(path, excel_row, values, value_mode))
result.append(SourceRow(path, excel_row, values, value_mode, source_sha256))
if hashlib.sha256(path.read_bytes()).hexdigest() != source_sha256:
raise ValueError('BOM 来源在读取期间已改变,请重新导入')
except TaskCenterError:
raise
except Exception as error:
@@ -192,6 +203,7 @@ def write_routed_bom(destination, rows, routes, *, project_names=None):
else:
reason = 'single_project'
source_map.append({'source_file': str(row.source), 'source_row': row.excel_row,
'source_sha256': row.source_sha256,
'original_project_path': row.project_path,
'project_name': row.project_name,
'matched_project_path': str(Path(target).resolve()),
@@ -0,0 +1,202 @@
"""Frozen parent queue, with one resource-owning supervisor per project."""
from contextlib import contextmanager
import hashlib
import json
from pathlib import Path
from threading import Lock
from uuid import uuid4
from .batch_resources import write_record
from .errors import TaskCenterError
from .path_access import canonical_path, internal_path
from .stop_control import StopControl, protect_interruption
_LOCK = Lock()
_TERMINAL = {'completed', 'failed', 'skipped', 'blocked'}
class _ProjectControl(StopControl):
def __init__(self, parent):
super().__init__()
self.parent = parent
if hasattr(parent, 'force_event'):
self.force_event = parent.force_event
def is_set(self):
return super().is_set() or self.parent.is_set()
@contextmanager
def _lease(root):
from .task_queue import _os_lock
if not _LOCK.acquire(blocking=False):
raise TaskCenterError('quick_run_busy', '工程队列正在执行。')
handle, acquired = None, False
try:
path = internal_path(root / '.workspace-queue.execution.lock')
path.parent.mkdir(parents=True, exist_ok=True)
handle = path.open('a+b')
if handle.seek(0, 2) == 0:
handle.write(b'\0')
handle.flush()
try:
_os_lock(handle, True)
acquired = True
except OSError as error:
raise TaskCenterError('quick_run_busy', '另一窗口的工程队列正在执行。') from error
yield
finally:
if handle is not None:
if acquired:
_os_lock(handle, False)
handle.close()
_LOCK.release()
def _token(value):
return isinstance(value, str) and len(value) == 32 and all(char in '0123456789abcdef' for char in value)
def _released_after_recheck(root, task_id, row):
from .batch_resources import _process_gone, pending_resources
from .batch_supervisor import pending_supervisors
from .supervisor_protocol import valid_journal
batch_id = row.get('supervisor_batch_id')
if not _token(batch_id):
return False
try:
journal = json.loads(internal_path(root / 'batch-resources' / batch_id / 'supervisor.json').read_text(encoding='utf-8'))
return (valid_journal(journal, batch_id) and journal['task_ids'] == [task_id]
and journal['state'] == 'finished' and journal.get('process')
and _process_gone(journal['process']) and not pending_resources(root) and not pending_supervisors(root))
except (OSError, ValueError, KeyError, TypeError):
return False
def execute_workspace_projects(service, task_ids, *, stop_event, queue_id=None,
expected_plan_hashes=None, checkpoint_id=None, defer_problem_pass=False):
from .task_queue import _plan_hash, TaskQueueEntry, TaskQueueResult
ids = tuple(task_ids)
if not ids or len(set(ids)) != len(ids) or any(not isinstance(item, str) or not item or Path(item).name != item
or item in {'.', '..'} for item in ids):
raise TaskCenterError('task_queue_selection', '请选择不同的单工程任务。')
root = canonical_path(service._logging.root)
with _lease(root):
children = {item: service.for_project_task(item) for item in ids}
projects = [children[item].projects(item) for item in ids]
if any(len(rows) != 1 for rows in projects) or len({str(canonical_path(rows[0].path)).casefold()
for rows in projects}) != len(ids):
raise TaskCenterError('project_binding', '每个任务必须对应不同的单个工程。')
hashes = {item: _plan_hash(children[item], item) for item in ids}
if expected_plan_hashes is not None and hashes != expected_plan_hashes:
raise TaskCenterError('assistant_stale', '执行计划已变化,请重新预检。')
token = queue_id or checkpoint_id or uuid4().hex
if not _token(token) or queue_id and checkpoint_id:
raise TaskCenterError('task_queue_state', '工程队列编号无效。')
path = internal_path(root / 'workspace-queues' / (token + '.json'))
if queue_id:
try:
state = json.loads(path.read_text(encoding='utf-8'))
if (state['version'] != 1 or state['task_ids'] != list(ids) or state['plan_hashes'] != hashes
or set(state['entries']) != set(ids) or state['phase'] not in {'primary', 'problems', 'finished'}
or any(not _token(row['checkpoint_id']) or row['state'] not in
{'pending', 'running', 'paused', *_TERMINAL} or type(row['released']) is not bool
or type(row['problems_done']) is not bool or not isinstance(row['message'], str)
for row in state['entries'].values())):
raise ValueError('workspace queue inputs changed')
except (OSError, ValueError, TypeError, KeyError) as error:
raise TaskCenterError('task_queue_state', '工程顺序或计划已变化,不能恢复原队列。') from error
else:
if path.exists():
raise TaskCenterError('task_queue_state', '工程队列检查点已存在,请恢复原队列。')
state = {'version': 1, 'task_ids': list(ids), 'plan_hashes': hashes, 'phase': 'primary',
'entries': {item: {'state': 'pending', 'message': '', 'released': False, 'problems_done': False,
'checkpoint_id': hashlib.sha256((token + '\0' + item).encode()).hexdigest()[:32]}
for item in ids}}
write_record(path, state)
def result(paused=False, current=None):
return TaskQueueResult(token, tuple(TaskQueueEntry(item, state['entries'][item]['state'],
state['entries'][item]['message']) for item in ids), paused, current)
def run_project(item, *, problems=False):
row = state['entries'][item]
previous = row['state']
row['state'] = 'running'
write_record(path, state)
child_id = row['checkpoint_id']
resume = problems or internal_path(root / 'task-queues' / (child_id + '.json')).is_file()
control = _ProjectControl(stop_event)
service._task_queue_feedback = (token, item, ids.index(item) + 1, len(ids))
service._workspace_queue_context = service._task_queue_feedback
try:
outcome = service._supervise('execute_task_queue', {'task_ids': (item,),
'expected_plan_hashes': {item: hashes[item]},
'queue_id': child_id if resume else None, 'checkpoint_id': None if resume else child_id,
'defer_problem_pass': not problems}, stop_event=control)
if (outcome.queue_id != child_id or len(outcome.entries) != 1 or outcome.entries[0].task_id != item
or outcome.entries[0].state not in {'pending', 'running', 'paused', *_TERMINAL}):
raise TaskCenterError('task_queue_state', '工程监督进程返回了不同的队列身份。')
row.update(state=outcome.entries[0].state, message=outcome.entries[0].message, released=True)
write_record(path, state)
return outcome.paused and row['state'] != 'blocked'
except TaskCenterError as error:
released = getattr(error, 'resources_released', False) is True
row.update(state='blocked', message=error.message, released=released)
row['supervisor_batch_id'] = getattr(service, '_last_supervisor_batch_id', None)
evidence = getattr(getattr(children[item], '_quick_run_preparer', None), 'data_root', root / 'tasks' / item)
protect_interruption(Path(evidence) / 'quick-run', 'project_supervisor_failed: ' + error.message)
if released:
from .batch_supervisor import reconcile_supervisors
try:
row['released'] = not bool(reconcile_supervisors(root))
except Exception:
row['released'] = False
write_record(path, state)
return not row['released']
except BaseException:
row['state'] = previous if previous in _TERMINAL else 'blocked'
write_record(path, state)
raise
try:
if state['phase'] == 'primary':
for item in ids:
row = state['entries'][item]
if row['state'] in _TERMINAL:
if row['state'] == 'blocked' and not row['released']:
if not _released_after_recheck(root, item, row):
return result(True, item)
row['released'] = True
write_record(path, state)
continue
if stop_event.is_set():
return result(True, item)
if run_project(item):
return result(True, item)
if stop_event.is_set():
return result(True, item)
state['phase'] = 'problems'
write_record(path, state)
if defer_problem_pass:
return result()
if state['phase'] == 'problems':
for item in ids:
row = state['entries'][item]
if row['problems_done'] or row['state'] not in {'completed', 'failed', 'paused', 'running'}:
continue
if stop_event.is_set():
return result(True, item)
# A project that never created its engine checkpoint has
# no admitted deferred work to revisit.
if internal_path(root / 'task-queues' / (row['checkpoint_id'] + '.json')).is_file():
if run_project(item, problems=True):
return result(True, item)
row['problems_done'] = True
write_record(path, state)
state['phase'] = 'finished'
write_record(path, state)
return result()
finally:
service._task_queue_feedback = None
service._workspace_queue_context = None