feat(dsh): intervene on blocking states and verify resource recovery
Core regression / Python core and release configuration (push) Successful in 18s
Core regression / JavaScript syntax (push) Successful in 2s
Core regression / Python core and release configuration (pull_request) Successful in 16s
Core regression / JavaScript syntax (pull_request) Successful in 3s

This commit is contained in:
阿白叔 committed 2026-11-04 23:39:33 +08:00
1 parent 389fc917b9
commit de9cb2908d
21 files changed
+1557 -46

No files matched your search

+109 -9
View File
@@ -15,6 +15,43 @@ from .rules import RETRYABLE_CODES
from .snapshot import TaskSnapshot
_RUN_LOCK = Lock()
_RESOURCE_CODES = {'batch_resources_pending', 'resource_cleanup_pending'}
def _bounded_details(value):
remaining = 16000
def bound(item, depth=0):
nonlocal remaining
if remaining <= 0 or depth > 5:
return '<truncated>'
remaining -= 32
if remaining <= 0:
return '<truncated>'
if isinstance(item, dict):
result = {}
for key, part in list(item.items())[:40]:
if remaining <= 0:
result['_truncated'] = True
break
key = str(key)[:80]
remaining -= len(key)
result[key] = bound(part, depth + 1)
return result
if isinstance(item, (list, tuple)):
result = []
for part in item[:20]:
if remaining <= 0:
break
result.append(bound(part, depth + 1))
return result
if isinstance(item, str):
item = item[:min(1000, remaining)]
remaining -= len(item)
elif not isinstance(item, (int, float, bool, type(None))):
item = str(item)[:min(1000, remaining)]
remaining -= len(item)
return item
return scrub(bound(value))
def decision(reply):
@@ -28,7 +65,7 @@ def decision(reply):
value.setdefault('summary', narrative[:1800])
else:
value = json.loads(text)
if not isinstance(value, dict) or not isinstance(value.get('summary'), str) or value.get('action') not in {'retry_failed', 'none'}:
if not isinstance(value, dict) or not isinstance(value.get('summary'), str) or value.get('action') not in {'retry_failed', 'cleanup_resources', 'none'}:
raise ValueError('invalid_diagnostic_decision')
return value
@@ -43,13 +80,13 @@ class IncidentRunner:
refs = []
for path in sorted(evidence.directory.iterdir()):
if path.is_file() and path.name in {'snapshot.json', 'snapshot-after.json', 'gates.json',
'actions.json', 'verification.json', 'diagnose.json', 'reflect.json', 'evidence.zip'}:
'actions.json', 'verification.json', 'diagnose.json', 'reflect.json', 'evidence.zip', 'trigger.json', 'cleanup.json'}:
refs.append(path.relative_to(self.data_root).as_posix())
try:
value = self.decisions.append({
'incident_id': record['incident_id'], 'trigger': record.get('issue_code', ''),
'evidence_refs': refs, 'gates': record.get('gates', {}),
'candidate_action': 'retry_failed' if record.get('attempts') else 'none',
'candidate_action': record.get('action', 'retry_failed' if record.get('attempts') else 'none'),
'authorized_scope': {'task_id': record.get('task_id'), 'run_id': record.get('run_id')},
'outcome': outcome, 'human_takeover': human_takeover})
record['decision_sequence'] = value['sequence']
@@ -61,13 +98,15 @@ class IncidentRunner:
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,
execution_enabled=None):
execution_enabled=None, trigger=None, snapshot_override=None, cleanup_allowed=False):
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_enabled=execution_enabled)
execution_enabled=execution_enabled, trigger=trigger,
snapshot_override=snapshot_override, cleanup_allowed=cleanup_allowed)
def _run(self, task_id, issue_code, message, *, run_id, execution_authorized, stop_event, execution_enabled):
def _run(self, task_id, issue_code, message, *, run_id, execution_authorized, stop_event, execution_enabled,
trigger, snapshot_override, cleanup_allowed):
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'
@@ -89,7 +128,20 @@ class IncidentRunner:
evidence.event(status, **values)
self.notify(dict(record))
update('collecting')
snapshot, context = self._snapshot(task_id, issue_code, message)
trigger = _bounded_details(trigger) if trigger is not None else None
if trigger is not None:
write_json(evidence.directory / 'trigger.json', trigger)
def take_snapshot():
if snapshot_override is not None:
# A stalled operation may hold the service lock; cached evidence never reads it.
snapshot, context = _bounded_details(snapshot_override), None
snapshot.update(task_id=str(task_id)[:128], issue_code=str(issue_code)[:80], issue=scrub(str(message)[:500]))
else:
snapshot, context = self._snapshot(task_id, issue_code, message)
if trigger is not None:
snapshot['trigger'] = trigger
return snapshot, context
snapshot, context = take_snapshot()
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')
@@ -97,6 +149,8 @@ class IncidentRunner:
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,
'cleanup_allowed': bool(cleanup_allowed and issue_code in _RESOURCE_CODES),
'cleanup_scope': 'Owned resources only; requires idle queue, lease and PID identity checks; never resumes CAD.',
'business_status_is_not_worker_liveness': True,
'mutation_admission': 'Coordinator serializes execution; service independently checks leases and uncertainty before each action.'}
write_json(evidence.directory / 'snapshot.json', snapshot)
@@ -128,6 +182,51 @@ class IncidentRunner:
record['gates'] = gates
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']
cleanup_gates = {'cleanup_allowed': bool(cleanup_allowed), 'resource_issue': issue_code in _RESOURCE_CODES,
'model_requested_cleanup': bool(suggestion and suggestion['action'] == 'cleanup_resources'),
'not_stopped': not stop_event.is_set(),
'auto_intervention_enabled': execution_enabled is None or execution_enabled.is_set()}
gates['cleanup'] = cleanup_gates
write_json(evidence.directory / 'gates.json', gates)
if all(cleanup_gates.values()):
update('cleaning_resources')
cleanup = {}
try:
pending = tuple(self.service.pending_batch_resources())
cleanup['resources_before'] = _bounded_details(pending)
if stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()):
raise ValueError('cleanup_gate_changed')
if pending:
update('cleaning_resources', cleanup_attempts=1)
if stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()):
raise ValueError('cleanup_gate_changed')
record['action'] = 'cleanup_resources'
write_json(state_path, record)
cleanup['returned_resources'] = _bounded_details(self.service.cleanup_batch_resources())
except Exception as error:
cleanup['error'] = scrub({'type': type(error).__name__, 'code': getattr(error, 'code', ''), 'detail': str(error)[:1000]})
evidence.event('cleanup_failed', **cleanup['error'])
try:
remaining = tuple(self.service.pending_batch_resources())
cleanup['remaining_resources'] = _bounded_details(remaining)
released = not remaining and 'error' not in cleanup
except Exception as error:
cleanup['verification_error'] = scrub({'type': type(error).__name__, 'detail': str(error)[:1000]})
cleanup['remaining_resources'], released = None, False
evidence.event('cleanup_verification_unavailable', **cleanup['verification_error'])
record['verification'] = {'resources_released': released, 'remaining_resources': cleanup['remaining_resources']}
record['cleanup'] = cleanup
write_json(evidence.directory / 'cleanup.json', cleanup)
write_json(evidence.directory / 'verification.json', record['verification'])
write_json(evidence.directory / 'actions.json', {'action': record.get('action', 'none'),
'cleanup_attempts': record.get('cleanup_attempts', 0), 'cleanup': cleanup, 'verification': record['verification']})
if released:
update('resolved')
evidence.capture('diagnostics-after')
self._record_decision(record, evidence, outcome='resources_released')
write_json(state_path, record)
evidence.pack(record)
return record
if safe:
# Consume before entering a service mutation. A crash or changed error
# code must never buy another replay of the same authorized run.
@@ -142,7 +241,7 @@ class IncidentRunner:
gates['retry_budget_available'] = False
write_json(evidence.directory / 'gates.json', gates)
if safe:
update('retrying', attempts=1)
update('retrying', attempts=1, action='retry_failed')
try:
# Re-read at the actual mutation boundary; the model never supplies parameters.
current = self.service.task_context(task_id)
@@ -178,13 +277,14 @@ 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.'
snapshot, _ = self._snapshot(task_id, issue_code, message)
snapshot, _ = take_snapshot()
snapshot['intervention'] = {'retry_attempts': record['attempts'], 'gates': gates,
'verification': record.get('verification')}
write_json(evidence.directory / 'snapshot-after.json', snapshot)
evidence.capture('diagnostics-after')
# Reflection gets original evidence plus the actual attempted actions and verification.
write_json(evidence.directory / 'actions.json', {'attempts': record['attempts'],
'action': record.get('action', 'none'), 'cleanup_attempts': record.get('cleanup_attempts', 0), 'cleanup': record.get('cleanup'),
'verification': record.get('verification'), 'retry_error': record.get('retry_error'), 'retry_skipped': record.get('retry_skipped')})
if suggestion is not None:
original_excerpt = evidence.excerpt