fix: isolate component failures and recover owned CAD resources

This commit is contained in:
阿白叔 committed 2026-11-06 14:56:53 +08:00
1 parent a8da30aad2
commit 4db5f05531
87 files changed
+6688 -301

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()),
+64 -39
View File
@@ -1,6 +1,7 @@
"""Durable automatic diagnosis, bounded repair, verification and escalation."""
from __future__ import annotations
from contextlib import nullcontext
from hashlib import sha256
import json
import os
@@ -34,10 +35,11 @@ def decision(reply):
class IncidentRunner:
def __init__(self, data_root, service, analyze, publish, notify=lambda row: None):
def __init__(self, data_root, service, analyze, publish, notify=lambda row: None, *, action_scope=None):
self.data_root, self.service = Path(data_root), service
self.analyze, self.publish, self.notify = analyze, publish, notify
self.decisions = DecisionLog(self.data_root)
self.action_scope = action_scope or (lambda _action: nullcontext())
def _record_decision(self, record, evidence, *, outcome, human_takeover=False):
refs = []
@@ -60,12 +62,13 @@ class IncidentRunner:
record['decision_log_status'] = 'unavailable'
evidence.event('decision_log_unavailable', error=type(error).__name__)
def run(self, task_id, issue_code, message, *, run_id='observation', execution_authorized=False, stop_event=None):
def run(self, task_id, issue_code, message, *, run_id='observation', execution_authorized=False, stop_event=None, cancel_event=None):
with _RUN_LOCK:
return self._run(task_id, issue_code, message, run_id=run_id,
execution_authorized=execution_authorized, stop_event=stop_event or Event())
execution_authorized=execution_authorized, stop_event=stop_event or Event(),
cancel_event=cancel_event or Event())
def _run(self, task_id, issue_code, message, *, run_id, execution_authorized, stop_event):
def _run(self, task_id, issue_code, message, *, run_id, execution_authorized, stop_event, cancel_event):
incident_id = sha256(f'{task_id}:{run_id}:{issue_code}'.encode()).hexdigest()[:24]
evidence = IncidentEvidence(self.data_root, incident_id)
state_path = evidence.directory / 'incident.json'
@@ -88,10 +91,12 @@ class IncidentRunner:
self.notify(dict(record))
update('collecting')
snapshot, context = self._snapshot(task_id, issue_code, message)
context_fingerprint = repr(context)
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,
@@ -112,7 +117,16 @@ class IncidentRunner:
write_json(evidence.directory / (phase + '.json'), failure)
evidence.event('analysis_unavailable', **failure)
return None
def cancelled():
update('pending_issue', cancellation='Automatic intervention cancelled; no further action or publication was started.')
self._draft(record, evidence)
evidence.pack(record)
return record
if cancel_event.is_set():
return cancelled()
suggestion = analyze('diagnose')
if cancel_event.is_set():
return cancelled()
policy = classify_failure(issue_code, getattr(context.task.status, 'value', '') if context is not None else 'unknown',
interrupted=context is None or bool(getattr(context, 'interrupted', True)),
authorized=bool(execution_authorized))
@@ -126,41 +140,48 @@ class IncidentRunner:
write_json(evidence.directory / 'gates.json', gates)
safe = all(value is True for key, value in gates.items() if key != 'failure_policy') and policy['retry_allowed']
if safe:
# 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())
except FileExistsError:
safe = False
gates['retry_budget_available'] = False
write_json(evidence.directory / 'gates.json', gates)
if safe:
update('retrying', attempts=1)
try:
# Re-read at the actual mutation boundary; the model never supplies parameters.
current = self.service.task_context(task_id)
if current.interrupted or current.phase != 'retry' or stop_event.is_set():
raise ValueError('retry_gate_changed')
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,
'part_label' if prepared.task.copy_part_number_to_value else 'preserve')
if prepared.interrupted or not p.next_project_path or stop_event.is_set():
raise ValueError('retry_execution_gate_changed')
outcome = self.service.execute_quick_run_queue(task_id, expected_item=expected, stop_event=stop_event)
update('verifying')
current = self.service.task_context(task_id)
p = current.progress
verification = {'queue_complete': p.queue_complete, 'failed_items': p.failed_items,
'saved_items': p.saved_items, 'completed_items': p.completed_items,
'interrupted': current.interrupted, 'paused': outcome.paused}
write_json(evidence.directory / 'verification.json', verification)
record['verification'] = verification
with self.action_scope('retry_failed'):
# Compare immutable evidence after the model wait and GUI admission.
current = self.service.task_context(task_id)
if (repr(current) != context_fingerprint or current.interrupted or current.phase != 'retry'
or stop_event.is_set() or cancel_event.is_set()):
raise ValueError('retry_gate_changed')
if reserve_retry is not None:
reserved = reserve_retry(task_id, source='dsh')
if not reserved:
gates['retry_budget_available'] = False
write_json(evidence.directory / 'gates.json', gates)
raise ValueError('retry_budget_spent')
else:
# Legacy service adapters use the original exclusive durable budget.
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())
update('retrying', attempts=1)
if stop_event.is_set() or cancel_event.is_set():
raise ValueError('retry_gate_changed')
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,
'part_label' if prepared.task.copy_part_number_to_value else 'preserve')
if prepared.interrupted or not p.next_project_path or stop_event.is_set() or cancel_event.is_set():
raise ValueError('retry_execution_gate_changed')
outcome = self.service.execute_quick_run_queue(task_id, expected_item=expected, stop_event=stop_event)
update('verifying')
current = self.service.task_context(task_id)
p = current.progress
verification = {'queue_complete': p.queue_complete, 'failed_items': p.failed_items,
'saved_items': p.saved_items, 'completed_items': p.completed_items,
'interrupted': current.interrupted, 'paused': outcome.paused}
write_json(evidence.directory / 'verification.json', verification)
record['verification'] = verification
if p.queue_complete and not p.failed_items and not current.interrupted and not outcome.paused:
update('resolved')
evidence.capture('diagnostics-after')
@@ -173,6 +194,8 @@ class IncidentRunner:
record['retry_error'] = scrub({'type': type(error).__name__, 'code': getattr(error, 'code', ''), 'detail': str(error)[:1000]})
else:
record['retry_skipped'] = 'Policy, execution authorization, current evidence or model recommendation did not admit replay.'
if cancel_event.is_set():
return cancelled()
snapshot, _ = self._snapshot(task_id, issue_code, message)
snapshot['intervention'] = {'retry_attempts': record['attempts'], 'gates': gates,
'verification': record.get('verification')}
@@ -185,6 +208,8 @@ class IncidentRunner:
original_excerpt = evidence.excerpt
evidence.excerpt = lambda: original_excerpt() + '\nGATES:\n' + json.dumps(gates) + '\nACTIONS:\n' + (evidence.directory / 'actions.json').read_text(encoding='utf8')
analyze('reflect')
if cancel_event.is_set():
return cancelled()
update('pending_issue')
self._draft(record, evidence)
archive = evidence.pack(record)
+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