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
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:
1 parent
389fc917b9
commit
de9cb2908d
21 files changed
+1557
-46
No files matched your search
@@ -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
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from threading import Event
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -14,6 +15,20 @@ from ..stop_control import StopControl
|
||||
from .workers import ServiceWorker
|
||||
|
||||
|
||||
@dataclass
|
||||
class IncidentRequest:
|
||||
task_id: str
|
||||
code: str
|
||||
message: str
|
||||
authorized: bool
|
||||
run_id: str
|
||||
stop: object = None
|
||||
trigger: dict | None = None
|
||||
snapshot: dict | None = None
|
||||
read_only: bool = False
|
||||
cleanup_allowed: bool = False
|
||||
|
||||
|
||||
class DshAutomation(QObject):
|
||||
model_requested = Signal(object)
|
||||
state_changed = Signal(object)
|
||||
@@ -27,10 +42,14 @@ class DshAutomation(QObject):
|
||||
self.latest = {}
|
||||
self.waiters = {}
|
||||
self.worker = None
|
||||
self._pool = QThreadPool(self)
|
||||
self._pool.setMaxThreadCount(1)
|
||||
self.execution_enabled = Event()
|
||||
if window.auto_intervention_check.isChecked():
|
||||
self.execution_enabled.set()
|
||||
self._current_identity = None
|
||||
self._owns_execution_lane = True
|
||||
self._previous_run_stop = None
|
||||
self._connected_view = None
|
||||
self._native_unavailable = False
|
||||
self.model_requested.connect(self._request_model)
|
||||
@@ -58,17 +77,25 @@ class DshAutomation(QObject):
|
||||
self.execution_enabled = Event()
|
||||
self.execution_enabled.set()
|
||||
else:
|
||||
for task_id, code, _message, _authorized, run_id, _stop in self.pending:
|
||||
self.seen.discard((task_id, code, run_id))
|
||||
for item in self.pending:
|
||||
self.seen.discard((item.task_id, item.code, item.run_id))
|
||||
self.pending.clear()
|
||||
|
||||
def enqueue(self, task_id, issue_code, message, *, execution_authorized=False, run_id='observation', stop_event=None):
|
||||
def cancel_pending(self, run_id):
|
||||
for item in list(self.pending):
|
||||
if item.run_id == run_id:
|
||||
self.seen.discard((item.task_id, item.code, item.run_id))
|
||||
self.pending.remove(item)
|
||||
|
||||
def enqueue(self, task_id, issue_code, message, *, execution_authorized=False, run_id='observation', stop_event=None,
|
||||
trigger=None, snapshot_override=None, read_only=False, cleanup_allowed=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 = (task_id, issue_code, message, execution_authorized, run_id, stop_event)
|
||||
item = IncidentRequest(task_id, issue_code, message, execution_authorized, run_id, stop_event,
|
||||
trigger, snapshot_override, read_only, cleanup_allowed)
|
||||
identity = (task_id, issue_code, run_id)
|
||||
if identity in self.seen:
|
||||
return True
|
||||
@@ -81,11 +108,16 @@ class DshAutomation(QObject):
|
||||
w = self.window
|
||||
if w._closed or not w.auto_intervention_check.isChecked() or self.worker is not None or not self.pending:
|
||||
return
|
||||
if (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):
|
||||
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)
|
||||
index = next((i for i, item in enumerate(self.pending) if item.read_only), None) if busy else 0
|
||||
if index is None:
|
||||
QTimer.singleShot(200, self._drain)
|
||||
return
|
||||
task_id, code, message, authorized, run_id, original_stop = self.pending.pop(0)
|
||||
item = self.pending.pop(index)
|
||||
task_id, code, message, authorized, run_id, original_stop = (
|
||||
item.task_id, item.code, item.message, item.authorized, item.run_id, item.stop)
|
||||
self._owns_execution_lane = not item.read_only
|
||||
self._current_identity = (task_id, code, run_id)
|
||||
if run_id == 'observation':
|
||||
run_id = uuid4().hex
|
||||
@@ -104,15 +136,18 @@ class DshAutomation(QObject):
|
||||
# Carry the original run's stop/force intent through the asynchronous
|
||||
# handoff, including pauses requested after enqueue but before drain.
|
||||
stop = original_stop if original_stop is not None else StopControl()
|
||||
self._previous_run_stop = original_stop if original_stop is not None else w._dsh_run_stop
|
||||
# The same worker gate reserves the mutation lane throughout diagnosis.
|
||||
w._batch_stop = stop
|
||||
w._active_quick_run_task_id = task_id or None
|
||||
if self._owns_execution_lane:
|
||||
w._batch_stop = stop
|
||||
w._active_quick_run_task_id = task_id or None
|
||||
runner = IncidentRunner(self.root, w.service, self._analyze,
|
||||
GitIssuePublisher(self.root / 'dsh' / 'issue-config.json'), self.state_changed.emit)
|
||||
allow_execution = authorized and not w.plan_panel.has_unsaved_plans()
|
||||
allow_execution = authorized and not item.read_only and not w.plan_panel.has_unsaved_plans()
|
||||
permission = self.execution_enabled
|
||||
worker = ServiceWorker(lambda: runner.run(task_id, code, message, run_id=run_id,
|
||||
execution_authorized=allow_execution, stop_event=stop, execution_enabled=permission))
|
||||
execution_authorized=allow_execution, stop_event=stop, execution_enabled=permission,
|
||||
trigger=item.trigger, snapshot_override=item.snapshot, cleanup_allowed=item.cleanup_allowed and not item.read_only))
|
||||
self._start_worker(worker)
|
||||
|
||||
def _start_worker(self, worker):
|
||||
@@ -123,7 +158,7 @@ class DshAutomation(QObject):
|
||||
worker.signals.failed.connect(self._failed)
|
||||
worker.signals.finished.connect(self._finished)
|
||||
w._update_gates()
|
||||
QThreadPool.globalInstance().start(worker)
|
||||
self._pool.start(worker)
|
||||
|
||||
def _analyze(self, incident_id, snapshot, evidence, phase):
|
||||
from ...dsh.experience import ExperienceStore
|
||||
@@ -192,7 +227,8 @@ class DshAutomation(QObject):
|
||||
continue
|
||||
w._dsh_view.automation = {key: row.get(key, '') for key in
|
||||
('incident_id', 'task_id', 'task_name', 'issue_code', 'status', 'session_id', 'evidence_dir', 'attempts')}
|
||||
w._dsh_view.automation.update(summary=summary, ticket=row.get('ticket', {}))
|
||||
w._dsh_view.automation.update(summary=summary, ticket=row.get('ticket', {}),
|
||||
cleanup_attempts=row.get('cleanup_attempts', 0), verification=row.get('verification'))
|
||||
w._bind_dsh_context()
|
||||
|
||||
def _completed(self, row):
|
||||
@@ -214,9 +250,12 @@ class DshAutomation(QObject):
|
||||
if self._current_identity and self._current_identity[2] == 'observation':
|
||||
self.seen.discard(self._current_identity)
|
||||
self._current_identity = None
|
||||
w._finish_run()
|
||||
# A passive refresh must not create an incident about this diagnosis.
|
||||
w._load_task_data(auto_intervene=False)
|
||||
if self._owns_execution_lane:
|
||||
w._finish_run()
|
||||
w._dsh_run_stop = self._previous_run_stop
|
||||
# A passive refresh must not create an incident about this diagnosis.
|
||||
w._load_task_data(auto_intervene=False)
|
||||
w._resource_status.refresh()
|
||||
w._update_gates()
|
||||
if w._close_pending:
|
||||
QTimer.singleShot(0, w.close)
|
||||
@@ -228,4 +267,5 @@ class DshAutomation(QObject):
|
||||
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._start_worker(ServiceWorker(lambda: runner.publish_pending(incident_id)))
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Deduplicate persistent blockers and observe actual background progress."""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
class DshBlockerCoordinator:
|
||||
def __init__(self, window, enqueue, cancel=None):
|
||||
self.window, self.enqueue, self.cancel = window, enqueue, cancel
|
||||
self.active, self.pending, self.watched = {}, {}, {}
|
||||
|
||||
def _submit(self, identity, value):
|
||||
if self.window.auto_intervention_check.isChecked() and self.enqueue(**value):
|
||||
self.active[identity] = value
|
||||
self.pending.pop(identity, None)
|
||||
return True
|
||||
self.pending[identity] = value
|
||||
return False
|
||||
|
||||
def report(self, source, task_id, code, message, details=None, *, read_only=False,
|
||||
cleanup_allowed=False, snapshot=None):
|
||||
identity = (str(source), str(task_id or ''), str(code))
|
||||
if identity in self.active:
|
||||
return False
|
||||
value = self.pending.get(identity) or {
|
||||
'source': identity[0], 'task_id': identity[1], 'issue_code': identity[2],
|
||||
'run_id': 'blocker-' + uuid4().hex}
|
||||
value.update(message=str(message)[:2000], details=details or {},
|
||||
read_only=bool(read_only), cleanup_allowed=bool(cleanup_allowed), snapshot=snapshot)
|
||||
return self._submit(identity, value)
|
||||
|
||||
def clear(self, source, task_id=None, issue_code=None):
|
||||
for identity in set(self.active) | set(self.pending):
|
||||
if (identity[0] == str(source) and (task_id is None or identity[1] == str(task_id or ''))
|
||||
and (issue_code is None or identity[2] == issue_code)):
|
||||
value = self.active.pop(identity, None) or self.pending.get(identity)
|
||||
self.pending.pop(identity, None)
|
||||
if self.cancel and value:
|
||||
self.cancel(value['run_id'])
|
||||
|
||||
def set_enabled(self, enabled):
|
||||
if not enabled:
|
||||
self.pending.update(self.active)
|
||||
self.active.clear()
|
||||
else:
|
||||
self.replay_pending()
|
||||
|
||||
def replay_pending(self):
|
||||
if self.window.auto_intervention_check.isChecked():
|
||||
for identity, value in list(self.pending.items()):
|
||||
self._submit(identity, value)
|
||||
|
||||
def watch(self, worker, label, task_id='', area='', *, now=None):
|
||||
self.watched[worker] = {'label': label, 'task_id': task_id or '', 'area': area,
|
||||
'last_progress': time.monotonic() if now is None else now, 'signature': None}
|
||||
|
||||
def progress(self, signature, worker=None, *, now=None):
|
||||
for key, row in self.watched.items():
|
||||
if worker is None and row['area'] in {'query', 'operations', 'task-creation'}:
|
||||
continue
|
||||
if (worker is None or key is worker) and row['signature'] != signature:
|
||||
row.update(signature=signature, last_progress=time.monotonic() if now is None else now)
|
||||
self.clear('worker:' + str(id(key)), row['task_id'])
|
||||
|
||||
def unwatch(self, worker):
|
||||
row = self.watched.pop(worker, None)
|
||||
if row:
|
||||
self.clear('worker:' + str(id(worker)), row['task_id'])
|
||||
|
||||
def check_stalled(self, *, now=None, threshold=120):
|
||||
current = time.monotonic() if now is None else now
|
||||
for worker, row in list(self.watched.items()):
|
||||
age = current - row['last_progress']
|
||||
if age >= threshold:
|
||||
self.report('worker:' + str(id(worker)), row['task_id'], 'operation_stalled',
|
||||
f"{row['label']}已有 {int(age)} 秒未观察到进展,后台操作仍在运行。",
|
||||
{'operation': row['label'], 'area': row['area'], 'no_progress_seconds': int(age),
|
||||
'last_progress': row['signature'], 'worker_still_running': True}, read_only=True)
|
||||
@@ -73,6 +73,7 @@ class DshOperationsController(QObject):
|
||||
self.dialog = None
|
||||
self.worker = None
|
||||
self.request_id = None
|
||||
self._request_task_ids = ()
|
||||
self._observed_execution = None
|
||||
self.results = {}
|
||||
self.cache = {'runs': [], 'schedules': [], 'schedule_events': [], 'schedule_audit': {}, 'section_errors': [],
|
||||
@@ -123,6 +124,8 @@ class DshOperationsController(QObject):
|
||||
if len(self.results) > 100:
|
||||
self.results.pop(next(iter(self.results)))
|
||||
if self.request_id == request_id:
|
||||
if result['status'] not in {'rejected', 'failed', 'blocked', 'busy', 'cancelled'}:
|
||||
self.window._dsh_blockers.clear('assistant:operations:' + ','.join(sorted(self._request_task_ids)))
|
||||
self.request_id = None
|
||||
self._state(result['status'], result.get('message', ''))
|
||||
if self.window._dsh_view:
|
||||
@@ -131,6 +134,12 @@ class DshOperationsController(QObject):
|
||||
def _failed(self, request_id, error):
|
||||
if not isinstance(error, (TaskCenterError, ValueError)):
|
||||
self.window.service.report_ui_error(error)
|
||||
code = getattr(error, 'code', 'operations_error')
|
||||
if code not in {'operation_cancelled', 'schedule_blocked'}:
|
||||
ids = self._request_task_ids if self.request_id == request_id else ()
|
||||
self.window._dsh_blockers.report('assistant:operations:' + ','.join(sorted(ids)),
|
||||
ids[0] if ids else '', code, getattr(error, 'message', str(error)),
|
||||
{'task_ids': list(ids)}, read_only=True)
|
||||
self._respond(request_id, status='rejected', message=getattr(error, 'message', '操作未完成,请核对输入或保留日志。'),
|
||||
code=getattr(error, 'code', 'operations_error'))
|
||||
|
||||
@@ -138,12 +147,17 @@ class DshOperationsController(QObject):
|
||||
self._observed_execution = self._execution_state()
|
||||
worker = ServiceWorker(action)
|
||||
self.worker = worker
|
||||
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')
|
||||
if reserve_lane:
|
||||
self.window._workers.add(worker)
|
||||
def succeeded(value):
|
||||
if not isValid(self.window) or self.window._closed or (request_id and self.request_id != request_id):
|
||||
return
|
||||
try:
|
||||
if isinstance(value, dict) and 'section_errors' in value:
|
||||
self._read_blockers(value)
|
||||
done(value)
|
||||
except Exception as error:
|
||||
self._failed(request_id or uuid4().hex, error)
|
||||
@@ -153,8 +167,12 @@ class DshOperationsController(QObject):
|
||||
if request_id:
|
||||
self._failed(request_id, error)
|
||||
else:
|
||||
self.window._dsh_blockers.report('operations:read', '',
|
||||
getattr(error, 'code', 'operations_read_failed'),
|
||||
getattr(error, 'message', '托管记录暂不可读,请检查本地记录。'), read_only=True)
|
||||
self._state('unavailable', '监管记录暂不可用,已有执行不受影响。')
|
||||
def finished():
|
||||
self.window._dsh_blockers.unwatch(worker)
|
||||
self.window._workers.discard(worker)
|
||||
if self.worker is worker:
|
||||
self.worker = None
|
||||
@@ -169,6 +187,24 @@ class DshOperationsController(QObject):
|
||||
self.window._update_gates()
|
||||
QThreadPool.globalInstance().start(worker)
|
||||
|
||||
def _read_blockers(self, value):
|
||||
self.window._dsh_blockers.clear('operations:read')
|
||||
errors = {row['section']: row for row in value['section_errors']}
|
||||
for section in ('runs', 'schedules', 'schedule_events', 'schedule_audit', 'experiences', 'tickets', 'health'):
|
||||
source = 'operations:section:' + section
|
||||
error = errors.get(section)
|
||||
if error:
|
||||
self.window._dsh_blockers.report(source, '', error['code'],
|
||||
'托管记录不可读:' + section, error, read_only=True)
|
||||
else:
|
||||
self.window._dsh_blockers.clear(source)
|
||||
audit = value.get('decision_audit', {})
|
||||
if audit.get('status') in {'corrupt', 'unavailable'}:
|
||||
self.window._dsh_blockers.report('operations:decision_audit', '', audit['code'],
|
||||
audit['message'], audit, read_only=True)
|
||||
elif audit.get('status') == 'ok':
|
||||
self.window._dsh_blockers.clear('operations:decision_audit')
|
||||
|
||||
def _read_decisions(self):
|
||||
# A corrupt audit chain must fail closed for append/verification without
|
||||
# making independent history, tickets, health or scheduling unreadable.
|
||||
@@ -310,6 +346,9 @@ class DshOperationsController(QObject):
|
||||
if 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', ())
|
||||
self._request_task_ids = tuple(task_id for task_id in ids if isinstance(task_id, str) and task_id
|
||||
) if isinstance(ids, (list, tuple)) else ()
|
||||
self._state('checking')
|
||||
allowed = {
|
||||
'refresh': set(), 'history': set(), 'health': set(), 'decisions': set(), 'impact': {'task_ids'}, 'experience': {'issue_code'}, 'tickets': set(),
|
||||
|
||||
@@ -63,6 +63,18 @@ class DshTaskCreationController(QObject):
|
||||
self.results.pop(next(iter(self.results)))
|
||||
self.request_id = None
|
||||
|
||||
def _report_failure(self, error, phase, spec, *, project_count=None):
|
||||
if getattr(error, 'code', '') == 'operation_cancelled':
|
||||
return
|
||||
spec = spec if isinstance(spec, dict) else {}
|
||||
name, rules = spec.get('name'), spec.get('rules')
|
||||
details = {'phase': phase, 'name': name[:120] if isinstance(name, str) else '',
|
||||
'rule_count': len(rules) if isinstance(rules, (list, tuple)) else 0}
|
||||
if project_count is not None:
|
||||
details['project_count'] = project_count
|
||||
self.window._dsh_blockers.report('task-creation', '', getattr(error, 'code', 'task_creation_failed'),
|
||||
getattr(error, 'message', '任务创建未完成,请检查本地日志。'), details, read_only=True)
|
||||
|
||||
def request(self, value):
|
||||
request_id = value.get('request_id')
|
||||
if not isinstance(request_id, str) or not re.fullmatch(r'[a-f0-9]{32}', request_id):
|
||||
@@ -81,6 +93,7 @@ class DshTaskCreationController(QObject):
|
||||
try:
|
||||
spec = validate_creation_spec(value.get('spec'))
|
||||
except TaskCenterError as error:
|
||||
self._report_failure(error, 'validation', value.get('spec'))
|
||||
self.view.complete_task_creation({'request_id': request_id, 'status': 'rejected', 'message': error.message})
|
||||
return
|
||||
self.request_id = request_id
|
||||
@@ -115,7 +128,9 @@ class DshTaskCreationController(QObject):
|
||||
worker = ServiceWorker(lambda: self.window.service.create_assistant_project_tasks(request_id, spec, root, paths))
|
||||
self.worker = worker
|
||||
self.window._workers.add(worker)
|
||||
self.window._dsh_blockers.watch(worker, '创建 DSH 任务', '', area='task-creation')
|
||||
def created(result):
|
||||
self.window._dsh_blockers.clear('task-creation')
|
||||
self._respond({'request_id': request_id, **result})
|
||||
self.window.task_list.recycle_button.setChecked(False)
|
||||
if result['task_ids']:
|
||||
@@ -126,9 +141,11 @@ class DshTaskCreationController(QObject):
|
||||
def failed(error):
|
||||
if not isinstance(error, TaskCenterError):
|
||||
self.window.service.report_ui_error(error)
|
||||
self._report_failure(error, 'creation', spec, project_count=len(paths))
|
||||
self._respond({'request_id': request_id, 'status': 'failed',
|
||||
'message': getattr(error, 'message', '任务创建未完成,已有配置未改变。'), 'task_ids': []})
|
||||
def finished():
|
||||
self.window._dsh_blockers.unwatch(worker)
|
||||
self.window._workers.discard(worker)
|
||||
self.worker = None
|
||||
self.window._bind_dsh_context()
|
||||
|
||||
@@ -41,6 +41,7 @@ class DshTaskLifecycleController(QObject):
|
||||
self.worker = None
|
||||
self.results = {}
|
||||
self.active_ids = ()
|
||||
self._request_task_ids = ()
|
||||
self.copy_requests = set()
|
||||
view.lifecycle_requested.connect(self.request)
|
||||
view.lifecycle_cancelled.connect(self.cancel)
|
||||
@@ -59,14 +60,22 @@ class DshTaskLifecycleController(QObject):
|
||||
self.view.lifecycle = {'request_id': self.request_id, 'status': status, **values}
|
||||
self.window._bind_dsh_context()
|
||||
|
||||
def _respond(self, request_id, **result):
|
||||
def _respond(self, request_id, *, report_blocker=True, **result):
|
||||
result = {'request_id': request_id, **result}
|
||||
code = result.get('code', 'assistant_error')
|
||||
if (report_blocker and 'queue_id' not in result and result['status'] in {'rejected', 'failed'}
|
||||
and code not in {'operation_cancelled', 'schedule_blocked'}):
|
||||
ids = self._request_task_ids if self.request_id == request_id else ()
|
||||
self.window._dsh_blockers.report('assistant:lifecycle:' + ','.join(sorted(ids)),
|
||||
ids[0] if ids else '', code, result.get('message', ''), {'task_ids': list(ids)}, read_only=True)
|
||||
if 'queue_id' in result:
|
||||
self.window._dsh_last_execution = dict(result)
|
||||
self.results[request_id] = result
|
||||
if len(self.results) > 100:
|
||||
self.results.pop(next(iter(self.results)))
|
||||
if self.request_id == request_id:
|
||||
if result['status'] not in {'rejected', 'failed', 'blocked', 'busy', 'cancelled'}:
|
||||
self.window._dsh_blockers.clear('assistant:lifecycle:' + ','.join(sorted(self._request_task_ids)))
|
||||
self._state(result['status'], result=result)
|
||||
self.request_id = None
|
||||
elif result['status'] in {'busy', 'rejected'}:
|
||||
@@ -75,10 +84,11 @@ class DshTaskLifecycleController(QObject):
|
||||
self.window._bind_dsh_context()
|
||||
self.view.complete_lifecycle(result)
|
||||
|
||||
def _failed(self, request_id, error):
|
||||
def _failed(self, request_id, error, *, report_blocker=True):
|
||||
if not isinstance(error, TaskCenterError):
|
||||
self.window.service.report_ui_error(error)
|
||||
self._respond(request_id, status='rejected' if isinstance(error, TaskCenterError) else 'failed',
|
||||
self._respond(request_id, report_blocker=report_blocker,
|
||||
status='rejected' if isinstance(error, TaskCenterError) else 'failed',
|
||||
message=getattr(error, 'message', '操作未完成,请核对任务中心日志。'), code=getattr(error, 'code', 'assistant_error'))
|
||||
|
||||
def _work(self, operation, done, *, executing=False):
|
||||
@@ -86,6 +96,8 @@ class DshTaskLifecycleController(QObject):
|
||||
self.worker = worker
|
||||
self.window._workers.add(worker)
|
||||
request_id = self.request_id
|
||||
owner = self._request_task_ids[0] if self._request_task_ids else ''
|
||||
self.window._dsh_blockers.watch(worker, 'DSH task operation', owner, area='lifecycle')
|
||||
def succeeded(result):
|
||||
if self.request_id != request_id or self.window._closed:
|
||||
return
|
||||
@@ -100,8 +112,9 @@ class DshTaskLifecycleController(QObject):
|
||||
self.active_ids = ()
|
||||
self.window._show_error(error, owner_task_id=self._execution_owner)
|
||||
self.window._metadata_changed(None)
|
||||
self._failed(request_id, error)
|
||||
self._failed(request_id, error, report_blocker=not executing)
|
||||
def finished():
|
||||
self.window._dsh_blockers.unwatch(worker)
|
||||
if self.worker is worker:
|
||||
self.worker = None
|
||||
self.window._workers.discard(worker)
|
||||
@@ -147,6 +160,9 @@ class DshTaskLifecycleController(QObject):
|
||||
or (creation and creation.request_id) or self.window._dsh_operations.busy):
|
||||
self._respond(request_id, status='busy', message='请等待当前操作或确认窗口收尾。'); return
|
||||
self.request_id = request_id
|
||||
requested_ids = spec.get('task_ids', [spec.get('task_id')]) if isinstance(spec, dict) else ()
|
||||
self._request_task_ids = tuple(task_id for task_id in requested_ids if isinstance(task_id, str) and task_id
|
||||
) if isinstance(requested_ids, (list, tuple)) else ()
|
||||
self._state('checking')
|
||||
if capability == 'execute' and isinstance(spec, dict) and spec.get('operation') == 'resume':
|
||||
if set(spec) != {'operation', 'run_id'}:
|
||||
@@ -238,10 +254,16 @@ class DshTaskLifecycleController(QObject):
|
||||
return
|
||||
request_id = request_id or uuid4().hex
|
||||
self.request_id = request_id
|
||||
self._request_task_ids = tuple(row['task_ids'])
|
||||
self._state('checking')
|
||||
def check():
|
||||
current = next((r for r in self.window._dsh_operations.schedules.evaluate(self.window.service)
|
||||
if r['schedule_id'] == row['schedule_id']), None)
|
||||
if current:
|
||||
failures = set(current.get('blockers', ())) - {'not_due', 'worker_busy', 'task_paused',
|
||||
'dependency_incomplete', 'already_claimed', 'finished'}
|
||||
if failures:
|
||||
raise TaskCenterError('schedule_plan_blocked', ', '.join(sorted(failures)))
|
||||
if not current or not current['ready'] or (automatic and not current['dispatchable']):
|
||||
raise TaskCenterError('schedule_blocked', '排期尚未满足时间、依赖或执行门禁。')
|
||||
return current, api.preflight(self.window.service, current['task_ids'])
|
||||
@@ -250,6 +272,15 @@ class DshTaskLifecycleController(QObject):
|
||||
|
||||
def _preflight_ready(self, request_id, capability, ids, report, *, resume=None, schedule=None, automatic=False):
|
||||
self.window._dsh_operations.cache['impact'] = report.get('impact', {})
|
||||
self._request_task_ids = tuple(ids)
|
||||
source = 'preflight:' + ','.join(sorted(ids))
|
||||
if report['ready']:
|
||||
self.window._dsh_blockers.clear(source)
|
||||
else:
|
||||
message = '\n'.join(f"{task['task_id']}: {blocker}" for task in report['tasks']
|
||||
for blocker in task['blockers'])
|
||||
self.window._dsh_blockers.report(source, ids[0], 'preflight_blocked', message,
|
||||
{'task_ids': list(ids), 'tasks': report['tasks'], 'impact': report.get('impact', {})}, read_only=True)
|
||||
if capability == 'preflight' or not report['ready']:
|
||||
self._respond(request_id, status='preflight' if capability == 'preflight' else 'blocked', **report)
|
||||
return
|
||||
|
||||
@@ -188,7 +188,15 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
widget.restoreState(saved)
|
||||
from .dsh_operations import DshOperationsController
|
||||
self._dsh_operations = DshOperationsController(self)
|
||||
from .dsh_blockers import DshBlockerCoordinator
|
||||
self._dsh_blockers = DshBlockerCoordinator(self, self._enqueue_dsh_blocker,
|
||||
lambda run_id: self._dsh_automation.cancel_pending(run_id) if self._dsh_automation else None)
|
||||
self._dsh_stall_timer = QTimer(self)
|
||||
self._dsh_stall_timer.setInterval(5000)
|
||||
self._dsh_stall_timer.timeout.connect(self._check_dsh_stalls)
|
||||
self._dsh_stall_timer.start()
|
||||
self._resource_status.changed.connect(self._update_gates)
|
||||
self._resource_status.changed.connect(self._observe_dsh_resource_blockers)
|
||||
self._resource_status.refresh()
|
||||
self._refresh_task_list()
|
||||
self._update_gates()
|
||||
@@ -370,6 +378,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._layout_settings.setValue(f'single_project/{name}', widget.saveState())
|
||||
self._layout_settings.setValue('tasks/sort', self.task_list.sort.currentData())
|
||||
self._closed = True
|
||||
self._dsh_stall_timer.stop()
|
||||
self.history_panel.shutdown()
|
||||
if self._dsh_operations:
|
||||
self._dsh_operations.close()
|
||||
@@ -882,9 +891,14 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._set_operator_message(
|
||||
'后台资源仍待清理,请保留诊断记录后重试。' if pending else '后台资源已释放,可以继续。',
|
||||
'warning' if pending else 'success')
|
||||
if pending:
|
||||
self._dsh_blockers.report('resource-release', '', 'batch_resources_pending',
|
||||
'后台资源清理完成后仍有资源未确认释放。', {'resources': list(pending)[:20]}, cleanup_allowed=True)
|
||||
else:
|
||||
self._dsh_blockers.clear('resource-release')
|
||||
self._update_gates()
|
||||
self._run_async(self.service.cleanup_batch_resources, done,
|
||||
self.run_panel.cleanup_resources_button)
|
||||
self.run_panel.cleanup_resources_button, operation_area='resources')
|
||||
|
||||
def _startup_resource_recheck(self):
|
||||
if self._closed:
|
||||
@@ -1028,6 +1042,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
bool(self._batch_stop and self._batch_stop.is_set())))
|
||||
live['message'] = self.run_panel.execution_status.text()
|
||||
self._dsh_live_run = live
|
||||
self._dsh_blockers.progress(tuple(str(live.get(key, '')) for key in
|
||||
('task_id', 'stage', 'saved_items', 'failed_items', 'completed_items', 'no_match_items')))
|
||||
self._bind_dsh_context()
|
||||
if self._batch_stop and self._batch_stop.control_error:
|
||||
self._set_operator_message(self._batch_stop.control_error, 'warning')
|
||||
@@ -1137,7 +1153,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
action = request.get('action')
|
||||
if action in {'retry_issue', 'open_evidence'} and self._dsh_automation:
|
||||
incident = self._dsh_automation.latest
|
||||
if incident.get('task_id') != (self._task_id or ''):
|
||||
if incident.get('task_id') not in {'', self._task_id or ''}:
|
||||
return
|
||||
if action == 'retry_issue':
|
||||
self._dsh_automation.resubmit(incident['incident_id'])
|
||||
@@ -1179,6 +1195,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._set_operator_message(self.operation_state.message)
|
||||
|
||||
def _operation_progress(self, message):
|
||||
self._dsh_blockers.progress(str(message))
|
||||
state = self.operation_state.progress(message)
|
||||
if state is not self.operation_state:
|
||||
self.operation_state = state
|
||||
@@ -1197,6 +1214,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
execution = self._batch_stop is not None
|
||||
owner = expected_task_id or self._active_quick_run_task_id
|
||||
label = button.text() if button is not None else '操作'
|
||||
self._dsh_blockers.watch(worker, label, owner or expected_task_id or self._task_id, operation_area)
|
||||
self.operation_state = OperationState.start(label, owner, operation_area)
|
||||
self._set_operator_message(self.operation_state.message)
|
||||
self.plan_panel._summary()
|
||||
@@ -1238,6 +1256,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._load_task_data()
|
||||
self._show_error(error, owner_task_id=owner)
|
||||
def finished():
|
||||
self._dsh_blockers.unwatch(worker)
|
||||
self._workers.discard(worker)
|
||||
if not isValid(self) or self._closed:
|
||||
return
|
||||
@@ -1271,7 +1290,11 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
# DSH must never hide or replace the original operation error.
|
||||
pass
|
||||
self._bind_dsh_context()
|
||||
managed = auto_intervene and self._queue_dsh_incident(task_id or '', issue_code, message)
|
||||
if getattr(error, 'bom_report', None) is not None and self.plan_panel._active_bom_import is not None:
|
||||
# The BOM completion callback owns the detailed report and its initiating task.
|
||||
managed = auto_intervene and self.auto_intervention_check.isChecked()
|
||||
else:
|
||||
managed = auto_intervene and self._queue_dsh_incident(task_id or '', issue_code, message)
|
||||
else:
|
||||
managed = False
|
||||
if owner_task_id is None or owner_task_id == self._task_id:
|
||||
@@ -1285,6 +1308,81 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._layout_settings.sync()
|
||||
if self._dsh_automation is not None:
|
||||
self._dsh_automation.set_enabled(enabled)
|
||||
if enabled:
|
||||
self._observe_dsh_resource_blockers()
|
||||
self._dsh_blockers.set_enabled(enabled)
|
||||
|
||||
def _observe_dsh_resource_blockers(self):
|
||||
status = self._resource_status
|
||||
if not status.known or self._closed:
|
||||
return
|
||||
if status.error is not None:
|
||||
self._dsh_blockers.report('resource-inspection', '', 'resource_inspection_failed',
|
||||
'无法确认后台资源释放状态。', {'error': type(status.error).__name__,
|
||||
'message': str(status.error)[:1000]}, read_only=True)
|
||||
else:
|
||||
self._dsh_blockers.clear('resource-inspection')
|
||||
records = status.records
|
||||
automation_worker = getattr(self._dsh_automation, 'worker', None)
|
||||
external_workers = self._workers - {automation_worker}
|
||||
automatic_mutation = bool(automation_worker and getattr(self._dsh_automation, '_owns_execution_lane', False)
|
||||
and getattr(self._dsh_automation, 'latest', {}).get('status') in
|
||||
{'retrying', 'verifying', 'cleaning_resources'})
|
||||
if automatic_mutation or (external_workers and (self._dsh_live_run.get('active') or
|
||||
self.operation_state.phase is OperationPhase.RUNNING)):
|
||||
# Healthy resources are expected while their current operation owns them.
|
||||
records = tuple(row for row in records if row.get('state') == 'blocked' or
|
||||
row.get('outcome') in {'completed_resources_pending', 'interrupted'})
|
||||
if status.records and not records:
|
||||
return
|
||||
if records:
|
||||
self._dsh_blockers.report('resource-release', '', 'batch_resources_pending',
|
||||
'后台资源未确认释放,已阻止继续导入或执行。',
|
||||
{'resources': list(records)[:20]}, cleanup_allowed=True)
|
||||
else:
|
||||
self._dsh_blockers.clear('resource-release')
|
||||
|
||||
def _check_dsh_stalls(self):
|
||||
if self._closed:
|
||||
return
|
||||
current = set()
|
||||
for query, label, owner in (
|
||||
(self._context_query, '读取任务上下文', self._task_id),
|
||||
(self._task_query, '读取任务列表', ''),
|
||||
(self._resource_status._query, '检查后台资源释放状态', ''),
|
||||
(self._feedback_query, '读取执行进度', self._active_quick_run_task_id)):
|
||||
for worker, request in query._active.values():
|
||||
if request[0] != query._generation or request[4].cancelled:
|
||||
continue
|
||||
current.add(worker)
|
||||
if worker not in self._dsh_blockers.watched:
|
||||
self._dsh_blockers.watch(worker, label, owner, 'query')
|
||||
for worker, row in list(self._dsh_blockers.watched.items()):
|
||||
if row['area'] == 'query' and worker not in current:
|
||||
self._dsh_blockers.unwatch(worker)
|
||||
self._dsh_blockers.check_stalled()
|
||||
|
||||
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():
|
||||
return False
|
||||
from ...dsh.evidence import scrub
|
||||
if self._dsh_automation is None:
|
||||
from .dsh_automation import DshAutomation
|
||||
self._dsh_automation = DshAutomation(self)
|
||||
context = self._context if self._task_id == task_id else None
|
||||
progress = getattr(context, 'progress', None)
|
||||
observed_status = getattr(getattr(getattr(context, 'task', None), 'status', None), 'value', 'unknown')
|
||||
cached = TaskSnapshot(task_id, observed_status,
|
||||
progress={key: getattr(progress, name, 0) for key, name in
|
||||
(('completed', 'completed_items'), ('total', 'total_items'),
|
||||
('failed_items', 'failed_items'), ('saved_items', 'saved_items'))},
|
||||
issue=message, issue_code=issue_code, rules_count=len(getattr(context, 'rules', ()))).safe_dict()
|
||||
cached.update(task_name=getattr(getattr(context, 'task', None), 'name', ''),
|
||||
snapshot_source='cached_at_blocker_detection')
|
||||
return self._dsh_automation.enqueue(task_id, issue_code, message, run_id=run_id,
|
||||
trigger=scrub({'source': source, 'details': details}), snapshot_override=snapshot or cached,
|
||||
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():
|
||||
|
||||
@@ -182,6 +182,7 @@ class ProjectPlanPanel(QWidget):
|
||||
self._orphaned_bom_batches = {}
|
||||
self._bom_imports = {}
|
||||
self._active_bom_import = None
|
||||
self._active_bom_import_owner = None
|
||||
self._editable = False
|
||||
self._operation_stop = None
|
||||
self._operation_progress = None
|
||||
@@ -457,9 +458,12 @@ class ProjectPlanPanel(QWidget):
|
||||
def finish_operation(self, *, error=None):
|
||||
cancellable = self._operation_stop is not None
|
||||
active, self._active_bom_import = self._active_bom_import, None
|
||||
owner, self._active_bom_import_owner = self._active_bom_import_owner, None
|
||||
if active is not None:
|
||||
scope, machine, attempt = active
|
||||
machine.finish(attempt, error=error)
|
||||
if error is not None and machine.state.phase is BomImportPhase.FAILED and machine.state.report is not None:
|
||||
self._report_bom_blocker(machine.state.report, scope, owner, error=error)
|
||||
if scope == self._report_scope(self.task_id):
|
||||
self._restore_bom_report(scope)
|
||||
if machine.state.message:
|
||||
@@ -485,7 +489,9 @@ class ProjectPlanPanel(QWidget):
|
||||
if bom_scope is not None:
|
||||
machine = self._bom_imports.setdefault(bom_scope, BomImportMachine())
|
||||
attempt = machine.start()
|
||||
self.window._dsh_blockers.clear(self._bom_blocker_source(bom_scope))
|
||||
self._active_bom_import = (bom_scope, machine, attempt)
|
||||
self._active_bom_import_owner = self.task_id
|
||||
self._restore_bom_report(self._report_scope(self.task_id))
|
||||
self._summary()
|
||||
self.window._set_operator_message('正在导入 BOM,请查看位号计划中的进度。')
|
||||
@@ -511,8 +517,10 @@ class ProjectPlanPanel(QWidget):
|
||||
def _operation_phase(self, phase, message):
|
||||
if self._active_bom_import is not None:
|
||||
scope, machine, attempt = self._active_bom_import
|
||||
if machine.progress(attempt, phase, message) and scope == self._report_scope(self.task_id):
|
||||
self._summary()
|
||||
if machine.progress(attempt, phase, message):
|
||||
self.window._dsh_blockers.progress(message)
|
||||
if scope == self._report_scope(self.task_id):
|
||||
self._summary()
|
||||
|
||||
def _operation_message(self, message):
|
||||
if self._operation_stop is not None and not self._operation_stop.is_set():
|
||||
@@ -643,7 +651,7 @@ class ProjectPlanPanel(QWidget):
|
||||
scope = self._report_scope(task_id)
|
||||
self._dispatch_cancellable(lambda stop, progress, phase: self.window.service.inspect_bom_batch(
|
||||
task_id, Path(path), stop_event=stop, on_progress=progress, on_phase=phase),
|
||||
lambda report: self._received_bom_report(report, scope=scope), self.import_bom_button,
|
||||
lambda report: self._received_bom_report(report, scope=scope, owner_task_id=task_id), self.import_bom_button,
|
||||
bom_scope=scope)
|
||||
|
||||
def _report_scope(self, task_id):
|
||||
@@ -652,6 +660,10 @@ class ProjectPlanPanel(QWidget):
|
||||
groups = getattr(self.window, '_known_task_groups', {})
|
||||
return ('batch', groups[task_id]) if groups.get(task_id) else ('task', task_id)
|
||||
|
||||
@staticmethod
|
||||
def _bom_blocker_source(scope):
|
||||
return 'bom:' + ':'.join(scope)
|
||||
|
||||
def _toggle_report(self, visible):
|
||||
if visible:
|
||||
if self.report_dialog is None:
|
||||
@@ -710,7 +722,7 @@ class ProjectPlanPanel(QWidget):
|
||||
title = f'本批 BOM {outcome} · 通过 {report.passed_rows} / 失败 {report.failed_rows} / 未检查 {report.unchecked_rows} 行 · 详情'
|
||||
return summary, '\n'.join(details), title
|
||||
|
||||
def _received_bom_report(self, report, *, scope=None):
|
||||
def _received_bom_report(self, report, *, scope=None, owner_task_id=None):
|
||||
scope = scope or self._report_scope(self.task_id)
|
||||
machine = self._bom_imports.setdefault(scope, BomImportMachine())
|
||||
# Direct report presentation (e.g. restoring a stored result) uses the same transitions.
|
||||
@@ -720,6 +732,7 @@ class ProjectPlanPanel(QWidget):
|
||||
attempt = machine.start()
|
||||
machine.receive(attempt, report)
|
||||
machine.finish(attempt)
|
||||
self._report_bom_blocker(report, scope, owner_task_id)
|
||||
if scope == self._report_scope(self.task_id):
|
||||
if hasattr(self.window, '_set_operator_message'):
|
||||
summary, _, _ = self._format_bom_report(machine.state)
|
||||
@@ -731,6 +744,25 @@ class ProjectPlanPanel(QWidget):
|
||||
self._summary()
|
||||
self.window._update_gates()
|
||||
|
||||
def _report_bom_blocker(self, report, scope, owner_task_id, *, error=None):
|
||||
source = self._bom_blocker_source(scope)
|
||||
if report.preview is None:
|
||||
summary, _, _ = self._format_bom_report(self._bom_imports[scope].state)
|
||||
details = {name: getattr(report, name) for name in (
|
||||
'total_rows', 'passed_rows', 'failed_rows', 'unchecked_rows',
|
||||
'total_projects', 'passed_projects', 'failed_projects', 'unchecked_projects')}
|
||||
details.update(scope=list(scope), errors=[str(error)[:1000] for error in report.errors[:100]],
|
||||
rows=[{'excel_row': row.excel_row, 'project_path': row.project_path,
|
||||
'project_name': row.project_name, 'status': row.status, 'reason': row.reason[:1000]}
|
||||
for row in report.rows if row.status == 'failed'][:100])
|
||||
owner = owner_task_id or (scope[1] if scope[0] == 'task' else self.task_id)
|
||||
code = getattr(error, 'code', 'bom_validation_failed')
|
||||
if error is not None:
|
||||
summary = getattr(error, 'message', str(error)) + '\n' + summary
|
||||
self.window._dsh_blockers.report(source, owner, code, summary, details, read_only=True)
|
||||
else:
|
||||
self.window._dsh_blockers.clear(source)
|
||||
|
||||
def _active_bom_batch(self):
|
||||
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)
|
||||
|
||||
Reference in new issue
Block a user