fix(dsh): keep AI waits off task execution and adapt main capabilities
Core regression / Python 3.12 core, intervention UI and release configuration (push) Failing after 21s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python 3.12 core, intervention UI and release configuration (pull_request) Failing after 21s
Core regression / JavaScript syntax (pull_request) Successful in 3s
Core regression / Python 3.12 core, intervention UI and release configuration (push) Failing after 21s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python 3.12 core, intervention UI and release configuration (pull_request) Failing after 21s
Core regression / JavaScript syntax (pull_request) Successful in 3s
This commit is contained in:
1 parent
3ecb6fa276
commit
eba935e710
24 files changed
+929
-128
No files matched your search
@@ -42,6 +42,13 @@ def _limit(limit: object) -> int:
|
||||
def _policy(task, row) -> tuple[str, str | None]:
|
||||
if bool(getattr(row, "custom_value_enabled", False)):
|
||||
return "custom", str(getattr(row, "custom_value", ""))
|
||||
mode = getattr(row, "value_mode", "inherit")
|
||||
if mode == "custom":
|
||||
return "custom", str(getattr(row, "custom_value", ""))
|
||||
if mode == "part_number":
|
||||
return mode, row.new_part_number
|
||||
if mode in {"preserve", "part_label"}:
|
||||
return mode, None
|
||||
if bool(getattr(task, "copy_part_number_to_value", False)):
|
||||
# The library label is only known during the CAD execution read. It is
|
||||
# unsafe for a preview to present the replacement part number as Value.
|
||||
@@ -72,6 +79,7 @@ def _target_row(task, task_id: str, row) -> dict[str, Any]:
|
||||
"old_value": target.old_value,
|
||||
"proposed_value": proposed,
|
||||
"value_policy": value_policy,
|
||||
"value_mode": row.value_mode,
|
||||
"target_cell": target_cell,
|
||||
"target_cell_policy": target_cell,
|
||||
"sync_nc": sync_nc,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Durable automatic diagnosis, bounded repair, verification and escalation."""
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import nullcontext
|
||||
from hashlib import sha256
|
||||
from itertools import islice
|
||||
import json
|
||||
@@ -127,10 +128,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 = []
|
||||
@@ -215,6 +217,8 @@ class IncidentRunner:
|
||||
snapshot['trigger'] = trigger
|
||||
return snapshot, context
|
||||
snapshot, context = take_snapshot()
|
||||
# Keep the original immutable evidence across the asynchronous model wait.
|
||||
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')
|
||||
@@ -275,35 +279,42 @@ class IncidentRunner:
|
||||
update('cleaning_resources')
|
||||
cleanup = {}
|
||||
try:
|
||||
pending = tuple(self.service.pending_batch_resources())
|
||||
cleanup['resources_before'] = _bounded_details(pending)
|
||||
if cancel_event.is_set() or 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 cancel_event.is_set() or 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)
|
||||
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('cleanup_gate_changed')
|
||||
cleanup['returned_resources'] = _bounded_details(self.service.cleanup_batch_resources())
|
||||
with self.action_scope('cleanup_resources'):
|
||||
try:
|
||||
pending = tuple(self.service.pending_batch_resources())
|
||||
cleanup['resources_before'] = _bounded_details(pending)
|
||||
if cancel_event.is_set() or 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 cancel_event.is_set() or 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)
|
||||
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('cleanup_gate_changed')
|
||||
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]})
|
||||
if 'resources_before' not in cleanup:
|
||||
cleanup['resources_before_error'] = cleanup['error']
|
||||
evidence.event('cleanup_failed', **cleanup['error'])
|
||||
try:
|
||||
remaining = tuple(self.service.pending_batch_resources())
|
||||
cleanup['remaining_resources'] = _bounded_details(remaining)
|
||||
cleanup['remaining_resources_observed'] = True
|
||||
released = not remaining
|
||||
except Exception as error:
|
||||
cleanup['verification_error'] = scrub({'type': type(error).__name__, 'detail': str(error)[:1000]})
|
||||
cleanup['remaining_resources'], released = None, None
|
||||
cleanup['remaining_resources_observed'] = False
|
||||
evidence.event('cleanup_verification_unavailable', **cleanup['verification_error'])
|
||||
except Exception as error:
|
||||
cleanup['error'] = scrub({'type': type(error).__name__, 'code': getattr(error, 'code', ''), 'detail': str(error)[:1000]})
|
||||
if 'resources_before' not in cleanup:
|
||||
cleanup['resources_before_error'] = cleanup['error']
|
||||
evidence.event('cleanup_failed', **cleanup['error'])
|
||||
try:
|
||||
remaining = tuple(self.service.pending_batch_resources())
|
||||
cleanup['remaining_resources'] = _bounded_details(remaining)
|
||||
cleanup['remaining_resources_observed'] = True
|
||||
released = not remaining
|
||||
except Exception as error:
|
||||
cleanup['verification_error'] = scrub({'type': type(error).__name__, 'detail': str(error)[:1000]})
|
||||
cleanup['remaining_resources'], released = None, None
|
||||
cleanup['error'] = scrub({'type': type(error).__name__, 'detail': str(error)[:1000]})
|
||||
cleanup.setdefault('remaining_resources', None)
|
||||
cleanup['remaining_resources_observed'] = False
|
||||
evidence.event('cleanup_verification_unavailable', **cleanup['verification_error'])
|
||||
released = None
|
||||
incomplete = 'error' in cleanup or 'verification_error' in cleanup
|
||||
performed = record['action'] == 'cleanup_resources'
|
||||
verification_status = 'incomplete' if incomplete else ('observed_cleared' if released and not performed else 'complete')
|
||||
@@ -331,48 +342,48 @@ class IncidentRunner:
|
||||
if cancel_event.is_set():
|
||||
return cancelled()
|
||||
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() or cancel_event.is_set()
|
||||
or (execution_enabled is not None and not execution_enabled.is_set())):
|
||||
raise ValueError('retry_gate_changed')
|
||||
record['action'] = 'retry_failed'
|
||||
write_json(state_path, record)
|
||||
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)
|
||||
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()
|
||||
or (execution_enabled is not None and not execution_enabled.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'):
|
||||
# Re-read at the actual mutation boundary; the model never supplies parameters.
|
||||
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()
|
||||
or (execution_enabled is not None and not execution_enabled.is_set())):
|
||||
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())
|
||||
except FileExistsError:
|
||||
gates['retry_budget_available'] = False
|
||||
write_json(evidence.directory / 'gates.json', gates)
|
||||
raise ValueError('retry_budget_spent')
|
||||
update('retrying', attempts=1)
|
||||
record['action'] = 'retry_failed'
|
||||
write_json(state_path, record)
|
||||
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)
|
||||
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()
|
||||
or (execution_enabled is not None and not execution_enabled.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 cancel_event.is_set():
|
||||
return cancelled()
|
||||
if p.queue_complete and not p.failed_items and not current.interrupted and not outcome.paused:
|
||||
|
||||
@@ -27,6 +27,10 @@ def catalog(service, task_id=None):
|
||||
'rules': [asdict(rule) for rule in context.rules], 'targets_count': len(context.targets),
|
||||
'copy_part_number_to_value': context.task.copy_part_number_to_value,
|
||||
'interrupted': context.interrupted, 'phase': context.phase}
|
||||
if context.task.target_plan_mode:
|
||||
from .impact import execution_impact
|
||||
report = execution_impact(service, [task_id])
|
||||
result['detail'].update(targets=report['rows'], omitted_targets=report['omitted_row_count'])
|
||||
return result
|
||||
|
||||
|
||||
@@ -99,11 +103,13 @@ def preview(service, raw):
|
||||
if not isinstance(raw, dict) or set(raw) - {'operation', 'task_id', 'patch'}:
|
||||
raise TaskCenterError('assistant_fields', '任务操作包含不支持的字段。')
|
||||
op = raw.get('operation')
|
||||
if op not in {'select', 'copy', 'update', 'archive'}:
|
||||
if op not in {'select', 'copy', 'update', 'archive', 'import_bom'}:
|
||||
raise TaskCenterError('assistant_operation', '不支持此任务操作。')
|
||||
context = _context(service, raw.get('task_id'))
|
||||
if context.task.status is TaskStatus.DELETED:
|
||||
raise TaskCenterError('assistant_deleted', '任务已归档,请先在回收站恢复。')
|
||||
if op == 'import_bom':
|
||||
service._editable_rules(context.task.task_id, lambda: None)
|
||||
patch = raw.get('patch', {})
|
||||
if not isinstance(patch, dict) or set(patch) - {'name', 'note', 'copy_part_number_to_value', 'rules'} or (patch and op != 'update'):
|
||||
raise TaskCenterError('assistant_patch', '只支持修改名称、备注、Value 开关和已有料号规则。')
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from contextlib import contextmanager
|
||||
from collections import deque
|
||||
from copy import deepcopy
|
||||
from dataclasses import dataclass
|
||||
@@ -36,6 +37,7 @@ class DshAutomation(QObject):
|
||||
model_requested = Signal(object)
|
||||
state_changed = Signal(object)
|
||||
cancel_requested = Signal(str)
|
||||
action_requested = Signal(object)
|
||||
|
||||
def __init__(self, window):
|
||||
super().__init__(window)
|
||||
@@ -47,23 +49,23 @@ class DshAutomation(QObject):
|
||||
self.latest = {}
|
||||
self.waiters = {}
|
||||
self.worker = None
|
||||
self._pool = QThreadPool(self)
|
||||
self._pool = QThreadPool(QApplication.instance())
|
||||
self._pool.setMaxThreadCount(1)
|
||||
self.execution_enabled = Event()
|
||||
if window.auto_intervention_check.isChecked():
|
||||
self.execution_enabled.set()
|
||||
self._current_identity = None
|
||||
self.current_request = None
|
||||
self._owns_execution_lane = True
|
||||
self._owns_execution_lane = False
|
||||
self._uses_cad_controls = False
|
||||
self.cancel_event = Event()
|
||||
self._analysis_deadline = None
|
||||
self._previous_run_stop = None
|
||||
self._connected_view = None
|
||||
self._native_unavailable = False
|
||||
self.model_requested.connect(self._request_model)
|
||||
self.state_changed.connect(self._state_changed)
|
||||
self.cancel_requested.connect(self._cancel_model)
|
||||
self.action_requested.connect(self._admit_action)
|
||||
self._restore_pending()
|
||||
|
||||
def _restore_pending(self):
|
||||
@@ -90,6 +92,9 @@ class DshAutomation(QObject):
|
||||
for item in self.pending:
|
||||
self._forget((item.task_id, item.code, item.run_id))
|
||||
self.pending.clear()
|
||||
for identity in tuple(self.seen):
|
||||
if identity[2] == 'observation':
|
||||
self._forget(identity)
|
||||
|
||||
def cancel_pending(self, run_id):
|
||||
for item in list(self.pending):
|
||||
@@ -146,8 +151,10 @@ class DshAutomation(QObject):
|
||||
self.current_request = item
|
||||
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 and (item.authorized or item.cleanup_allowed)
|
||||
self._uses_cad_controls = self._owns_execution_lane and item.authorized
|
||||
self._owns_execution_lane = False
|
||||
self._uses_cad_controls = False
|
||||
self._admitted_action = None
|
||||
self._observed_run_id = w._dsh_run_id
|
||||
self.cancel_event = Event()
|
||||
# Start the shared model budget when the Harness session is ready;
|
||||
# startup/session creation must not consume diagnosis time.
|
||||
@@ -176,13 +183,10 @@ 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.
|
||||
if self._uses_cad_controls:
|
||||
w._batch_stop = stop
|
||||
w._active_quick_run_task_id = task_id or None
|
||||
self._action_stop = stop
|
||||
runner = IncidentRunner(self.root, w.service, self._analyze,
|
||||
GitIssuePublisher(self.root / 'dsh' / 'issue-config.json'), self.state_changed.emit)
|
||||
GitIssuePublisher(self.root / 'dsh' / 'issue-config.json'), self.state_changed.emit,
|
||||
action_scope=self._action_scope)
|
||||
allow_execution = authorized and not item.read_only and not w.plan_panel.has_unsaved_plans()
|
||||
permission = self.execution_enabled
|
||||
cancellation = self.cancel_event
|
||||
@@ -195,8 +199,6 @@ class DshAutomation(QObject):
|
||||
def _start_worker(self, worker):
|
||||
w = self.window
|
||||
self.worker = worker
|
||||
if self._owns_execution_lane:
|
||||
w._workers.add(worker)
|
||||
worker.signals.succeeded.connect(self._completed)
|
||||
worker.signals.failed.connect(self._failed)
|
||||
worker.signals.finished.connect(self._finished)
|
||||
@@ -204,6 +206,78 @@ class DshAutomation(QObject):
|
||||
self._publish_context()
|
||||
self._pool.start(worker)
|
||||
|
||||
@contextmanager
|
||||
def _action_scope(self, action):
|
||||
request = {'action': action, 'worker': self.worker, 'complete': Event(), 'holder': {}}
|
||||
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
|
||||
self.action_requested.emit(request)
|
||||
raise ValueError('ai_action_admission_timeout')
|
||||
if not request['holder'].get('admitted'):
|
||||
raise ValueError('ai_action_context_changed')
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
request['complete'].clear()
|
||||
request['holder']['release'] = True
|
||||
self.action_requested.emit(request)
|
||||
request['complete'].wait(5)
|
||||
|
||||
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:
|
||||
request['complete'].set()
|
||||
|
||||
def _release_action(self, request):
|
||||
if getattr(self, '_admitted_action', None) is not request:
|
||||
return
|
||||
w = self.window
|
||||
w._workers.discard(request['worker'])
|
||||
if self._uses_cad_controls and w._batch_stop is self._action_stop:
|
||||
w._batch_stop = None
|
||||
w._active_quick_run_task_id = None
|
||||
self._admitted_action = None
|
||||
self._owns_execution_lane = False
|
||||
self._uses_cad_controls = False
|
||||
if not w._closed:
|
||||
# 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)
|
||||
w._update_gates()
|
||||
|
||||
def _forget(self, identity):
|
||||
self.seen.discard(identity)
|
||||
try:
|
||||
@@ -362,23 +436,19 @@ class DshAutomation(QObject):
|
||||
|
||||
def _finished(self):
|
||||
w = self.window
|
||||
if getattr(self, '_admitted_action', None) is not None:
|
||||
self._release_action(self._admitted_action)
|
||||
w._workers.discard(self.worker)
|
||||
self.worker = None
|
||||
if self._current_identity:
|
||||
w._dsh_blockers.completed(self._current_identity[2])
|
||||
if self._current_identity[2] == 'observation' or self._current_identity[2].startswith('blocker-'):
|
||||
if self._current_identity[2].startswith('blocker-'):
|
||||
self._forget(self._current_identity)
|
||||
self._current_identity = None
|
||||
self.current_request = None
|
||||
self._publish_context()
|
||||
if w._closed:
|
||||
return
|
||||
if self._uses_cad_controls:
|
||||
w._finish_run()
|
||||
w._dsh_run_stop = self._previous_run_stop
|
||||
if self._owns_execution_lane:
|
||||
# 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:
|
||||
|
||||
@@ -72,6 +72,8 @@ class DshOperationsController(QObject):
|
||||
self.decisions = DecisionLog(self.root)
|
||||
self.dialog = None
|
||||
self.worker = None
|
||||
self._read_pool = QThreadPool(QApplication.instance())
|
||||
self._read_pool.setMaxThreadCount(1)
|
||||
self.request_id = None
|
||||
self._request_task_ids = ()
|
||||
self._read_failures = {}
|
||||
@@ -149,6 +151,12 @@ class DshOperationsController(QObject):
|
||||
code=getattr(error, 'code', 'operations_error'))
|
||||
|
||||
def _work(self, action, done, *, request_id=None, reserve_lane=True):
|
||||
if request_id and self.request_id != request_id:
|
||||
return
|
||||
if reserve_lane and (self.window._closed or self.window._workers or self.window._loading):
|
||||
if request_id:
|
||||
self._respond(request_id, status='busy', message='任务状态已变化,请在当前操作结束后重新确认。')
|
||||
return
|
||||
self._observed_execution = self._execution_state()
|
||||
worker = ServiceWorker(action)
|
||||
self.worker = worker
|
||||
@@ -177,6 +185,8 @@ class DshOperationsController(QObject):
|
||||
getattr(error, 'message', '托管记录暂不可读,请检查本地记录。'))
|
||||
self._state('unavailable', '监管记录暂不可用,已有执行不受影响。')
|
||||
def finished():
|
||||
if not isValid(self.window):
|
||||
return
|
||||
self.window._dsh_blockers.unwatch(worker)
|
||||
self.window._workers.discard(worker)
|
||||
if self.worker is worker:
|
||||
@@ -190,7 +200,7 @@ class DshOperationsController(QObject):
|
||||
worker.signals.succeeded.connect(succeeded); worker.signals.failed.connect(failed)
|
||||
worker.signals.finished.connect(finished)
|
||||
self.window._update_gates()
|
||||
QThreadPool.globalInstance().start(worker)
|
||||
(QThreadPool.globalInstance() if reserve_lane else self._read_pool).start(worker)
|
||||
|
||||
def _read_blockers(self, value):
|
||||
self._read_recovered('operations:read')
|
||||
@@ -333,7 +343,7 @@ class DshOperationsController(QObject):
|
||||
# Preserve the original native future-run authorization. This
|
||||
# is not a model-supplied confirmation flag.
|
||||
QTimer.singleShot(0, lambda: self._dispatch(candidate, automatic=True))
|
||||
self._work(lambda: self._read(synchronize_tickets=self._ticks % 20 == 0), ready)
|
||||
self._work(lambda: self._read(synchronize_tickets=self._ticks % 20 == 0), ready, reserve_lane=False)
|
||||
|
||||
def _dispatch(self, row, *, automatic, request_id=None):
|
||||
if not isValid(self.window) or self.window._closed:
|
||||
@@ -388,22 +398,22 @@ class DshOperationsController(QObject):
|
||||
def read(value):
|
||||
self.cache.update(value)
|
||||
self._respond(key, status='read', **value)
|
||||
self._work(self._read, read, request_id=key)
|
||||
self._work(self._read, read, request_id=key, reserve_lane=False)
|
||||
elif op == 'impact':
|
||||
def impact(report):
|
||||
self.cache['impact'] = report
|
||||
self._respond(key, status='impact', **report)
|
||||
self._work(lambda: execution_impact(self.window.service, spec.get('task_ids')), impact, request_id=key)
|
||||
self._work(lambda: execution_impact(self.window.service, spec.get('task_ids')), impact, request_id=key, reserve_lane=False)
|
||||
elif op == 'experience':
|
||||
def found(rows):
|
||||
self.cache['experiences'] = rows
|
||||
self._respond(key, status='experience', experiences=rows)
|
||||
self._work(lambda: self.experiences.search(spec.get('issue_code', '')), found, request_id=key)
|
||||
self._work(lambda: self.experiences.search(spec.get('issue_code', '')), found, request_id=key, reserve_lane=False)
|
||||
elif op == 'refresh_ticket':
|
||||
def synced(row):
|
||||
self.cache['tickets'] = self.tickets.list_tickets()[:20]
|
||||
self._respond(key, status='ticket', ticket=row)
|
||||
self._work(lambda: self.tickets.refresh(spec.get('incident_id')), synced, request_id=key)
|
||||
self._work(lambda: self.tickets.refresh(spec.get('incident_id')), synced, request_id=key, reserve_lane=False)
|
||||
elif op == 'open_incident':
|
||||
incident = spec.get('incident_id')
|
||||
if not isinstance(incident, str) or not re.fullmatch('[a-f0-9]{24}', incident):
|
||||
@@ -427,18 +437,21 @@ class DshOperationsController(QObject):
|
||||
draft = self.schedules.preview(raw, report['plan_hashes'])
|
||||
for dependency in draft['dependencies']:
|
||||
self.window.service.get_task(dependency)
|
||||
return draft, report
|
||||
self._work(prepare, lambda result: self._schedule_ready(key, *result), request_id=key)
|
||||
return draft, report, execution_impact(self.window.service, draft['task_ids'])
|
||||
self._work(prepare, lambda result: self._schedule_ready(key, *result), request_id=key, reserve_lane=False)
|
||||
elif op in {'cancel_schedule', 'run_schedule', 'reconcile_schedule'}:
|
||||
def loaded():
|
||||
row = self.schedules.get(spec.get('schedule_id'))
|
||||
if row is None:
|
||||
raise ValueError('schedule missing')
|
||||
return row
|
||||
self._work(loaded, lambda row: self._schedule_action(key, op, row), request_id=key)
|
||||
self._work(loaded, lambda row: self._schedule_action(key, op, row), request_id=key, reserve_lane=False)
|
||||
|
||||
def _schedule_ready(self, key, draft, report):
|
||||
self.cache['impact'] = execution_impact(self.window.service, draft['task_ids'])
|
||||
def _schedule_ready(self, key, draft, report, impact):
|
||||
if self.window._workers or self.window._closed:
|
||||
self._respond(key, status='busy', message='任务状态已变化,未打开排期确认。')
|
||||
return
|
||||
self.cache['impact'] = impact
|
||||
self.dialog = DshScheduleDialog(draft, report, self.window)
|
||||
dialog = self.dialog
|
||||
self._state('awaiting_confirmation', '请核对排期时间、依赖和自动执行授权。')
|
||||
@@ -464,6 +477,9 @@ 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:
|
||||
self._respond(key, status='busy', message='任务状态已变化,未提交排期操作。')
|
||||
return
|
||||
if op == 'run_schedule':
|
||||
self.request_id = None
|
||||
QTimer.singleShot(0, lambda: self._dispatch(row, automatic=False, request_id=key))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Non-blocking model readiness and visible automatic-intervention state."""
|
||||
from PySide6.QtCore import QObject, QPointF, QRectF, QSize, Qt, QTimer
|
||||
from PySide6.QtCore import QObject, QPointF, QRectF, QSize, Qt, QThreadPool, QTimer
|
||||
from PySide6.QtGui import QColor, QFontMetricsF, QPainter
|
||||
from PySide6.QtWidgets import QToolButton
|
||||
from PySide6.QtWidgets import QApplication, QToolButton
|
||||
|
||||
from ...dsh.availability import check_availability
|
||||
from ...dsh.evidence import scrub
|
||||
@@ -58,7 +58,9 @@ class DshStatusController(QObject):
|
||||
self.window = window
|
||||
self.availability = {'available': False, 'code': 'checking', 'message': '正在检查本地 AI 配置。'}
|
||||
self._runtime_error = ''
|
||||
self.query = LatestQuery(self)
|
||||
self._read_pool = QThreadPool(QApplication.instance())
|
||||
self._read_pool.setMaxThreadCount(1)
|
||||
self.query = LatestQuery(self, pool=self._read_pool)
|
||||
self.timer = QTimer(self)
|
||||
self.timer.setInterval(5000)
|
||||
self.timer.timeout.connect(self.refresh)
|
||||
|
||||
@@ -5,7 +5,8 @@ import re
|
||||
from uuid import uuid4
|
||||
|
||||
from PySide6.QtCore import QObject, QThreadPool, QTimer
|
||||
from PySide6.QtWidgets import QDialog, QDialogButtonBox, QLabel, QPlainTextEdit, QVBoxLayout
|
||||
from PySide6.QtWidgets import QApplication, QDialog, QDialogButtonBox, QLabel, QPlainTextEdit, QVBoxLayout
|
||||
from shiboken6 import isValid
|
||||
|
||||
from ...dsh import task_lifecycle as api
|
||||
from ..errors import TaskCenterError
|
||||
@@ -39,6 +40,8 @@ class DshTaskLifecycleController(QObject):
|
||||
self.dialog = None
|
||||
self.request_id = None
|
||||
self.worker = None
|
||||
self._read_pool = QThreadPool(QApplication.instance())
|
||||
self._read_pool.setMaxThreadCount(1)
|
||||
self.results = {}
|
||||
self.active_ids = ()
|
||||
self._request_task_ids = ()
|
||||
@@ -91,15 +94,16 @@ class DshTaskLifecycleController(QObject):
|
||||
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):
|
||||
def _work(self, operation, done, *, executing=False, reserve_lane=True):
|
||||
worker = ServiceWorker(operation)
|
||||
self.worker = worker
|
||||
self.window._workers.add(worker)
|
||||
if reserve_lane:
|
||||
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:
|
||||
if not isValid(self.window) or self.request_id != request_id or self.window._closed:
|
||||
return
|
||||
try:
|
||||
done(result)
|
||||
@@ -107,6 +111,8 @@ class DshTaskLifecycleController(QObject):
|
||||
failed(error)
|
||||
worker.signals.succeeded.connect(succeeded)
|
||||
def failed(error):
|
||||
if not isValid(self.window) or self.window._closed or self.request_id != request_id:
|
||||
return
|
||||
if executing:
|
||||
self.window._finish_run()
|
||||
self.active_ids = ()
|
||||
@@ -114,10 +120,14 @@ class DshTaskLifecycleController(QObject):
|
||||
self.window._metadata_changed(None)
|
||||
self._failed(request_id, error, report_blocker=not executing)
|
||||
def finished():
|
||||
if not isValid(self.window):
|
||||
return
|
||||
self.window._dsh_blockers.unwatch(worker)
|
||||
if self.worker is worker:
|
||||
self.worker = None
|
||||
self.window._workers.discard(worker)
|
||||
if self.window._closed:
|
||||
return
|
||||
self.window._bind_dsh_context()
|
||||
self.window._update_gates()
|
||||
if self.window._close_pending:
|
||||
@@ -125,7 +135,7 @@ class DshTaskLifecycleController(QObject):
|
||||
worker.signals.failed.connect(failed)
|
||||
worker.signals.finished.connect(finished)
|
||||
self.window._update_gates()
|
||||
QThreadPool.globalInstance().start(worker)
|
||||
(QThreadPool.globalInstance() if reserve_lane else self._read_pool).start(worker)
|
||||
|
||||
def request(self, value):
|
||||
request_id = value.get('request_id')
|
||||
@@ -172,11 +182,11 @@ class DshTaskLifecycleController(QObject):
|
||||
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)
|
||||
self._work(inspect, lambda pair: self._preflight_ready(request_id, capability, pair[0]['task_ids'], pair[1], resume=pair[0]))
|
||||
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'}:
|
||||
self._work(lambda: api.catalog(self.window.service, spec.get('task_id')),
|
||||
lambda result: self._respond(request_id, status='read', **result))
|
||||
lambda result: self._respond(request_id, status='read', **result), reserve_lane=False)
|
||||
elif capability in {'preflight', 'execute'}:
|
||||
if not isinstance(spec, dict) or set(spec) - ({'task_ids', 'operation'} if capability == 'execute' else {'task_ids'}) or (capability == 'execute' and spec.get('operation') != 'start'):
|
||||
self._failed(request_id, TaskCenterError('assistant_fields', '执行请求字段无效。')); return
|
||||
@@ -184,13 +194,26 @@ class DshTaskLifecycleController(QObject):
|
||||
if self.window.plan_panel.has_unsaved_plan(ids if isinstance(ids, list) else ()):
|
||||
self._failed(request_id, TaskCenterError('assistant_dirty', '所选任务有未保存位号计划,请先保存。')); return
|
||||
self._work(lambda: api.preflight(self.window.service, ids),
|
||||
lambda report: self._preflight_ready(request_id, capability, ids, report))
|
||||
lambda report: self._preflight_ready(request_id, capability, ids, report), reserve_lane=False)
|
||||
elif capability == 'manage':
|
||||
self._work(lambda: api.preview(self.window.service, spec), lambda plan: self._plan_ready(request_id, plan))
|
||||
self._work(lambda: api.preview(self.window.service, spec), lambda plan: self._plan_ready(request_id, plan), reserve_lane=False)
|
||||
else:
|
||||
self._failed(request_id, TaskCenterError('assistant_capability', '未开放此能力。'))
|
||||
|
||||
def _allow_transition(self, request_id):
|
||||
if not isValid(self.window) or self.window._closed or self.request_id != request_id:
|
||||
return False
|
||||
creation = self.window._dsh_task_creation
|
||||
if (self.window._workers or self.window._loading or self.window._batch_stop is not None
|
||||
or self.window._active_quick_run_task_id or self.window.history_panel._worker is not None
|
||||
or (creation and creation.request_id) or self.window._dsh_operations.busy):
|
||||
self._respond(request_id, status='busy', message='任务中心状态已变化,请等待当前操作收尾后重新请求。')
|
||||
return False
|
||||
return True
|
||||
|
||||
def _show(self, title, text, accepted):
|
||||
if not self._allow_transition(self.request_id):
|
||||
return
|
||||
self._state('awaiting_confirmation', title=title, preview=text)
|
||||
self.dialog = DshLifecycleDialog(title, text, self.window)
|
||||
dialog = self.dialog
|
||||
@@ -208,11 +231,38 @@ class DshTaskLifecycleController(QObject):
|
||||
dialog.open()
|
||||
|
||||
def _plan_ready(self, request_id, plan):
|
||||
if not self._allow_transition(request_id):
|
||||
return
|
||||
spec = plan['spec']; op = spec['operation']; task_id = spec['task_id']
|
||||
if op == 'select':
|
||||
self.window.open_task(task_id)
|
||||
self._respond(request_id, status='selected', task_id=task_id)
|
||||
return
|
||||
if op == 'import_bom':
|
||||
panel = self.window.plan_panel
|
||||
def eligible():
|
||||
return (self.window._task_id == task_id and panel.task_id == task_id
|
||||
and self.window._context is not None and not self.window._loading
|
||||
and not self.window._workers and panel.import_bom_button.isEnabled())
|
||||
if not eligible():
|
||||
self._failed(request_id, TaskCenterError('assistant_bom_scope', '请先选择并加载该任务,确认其 BOM 导入可用后重试。'))
|
||||
return
|
||||
text = ('打开该任务的原生 BOM 导入窗口,可多选 Excel 文件。\n'
|
||||
'文件选择后由任务中心校验并暂存预览;请在位号计划中核对报告后手动保存本批计划。\n'
|
||||
'本次确认只打开文件选择,不代表导入或保存成功,不执行 CAD。')
|
||||
def launch_import():
|
||||
if self.request_id != request_id:
|
||||
return
|
||||
if self.window._closed or not eligible():
|
||||
self._failed(request_id, TaskCenterError('assistant_bom_scope', '任务选择或导入状态已变化,请重新确认。'))
|
||||
return
|
||||
self.window.content_stack.setCurrentIndex(0)
|
||||
self.window.mapping_tabs.setCurrentWidget(panel)
|
||||
panel.import_bom()
|
||||
self._respond(request_id, status='handed_off', task_id=task_id, cad_execution_started=False,
|
||||
message='已交由原生 BOM 文件选择和校验流程;导入结果请核对位号计划中的报告,保存需另行确认。')
|
||||
self._show('导入 BOM', text, launch_import)
|
||||
return
|
||||
if op == 'copy':
|
||||
# Project scope and configuration preview use the existing creation controller.
|
||||
try:
|
||||
@@ -221,7 +271,7 @@ class DshTaskLifecycleController(QObject):
|
||||
self._failed(request_id, error); return
|
||||
self._state('awaiting_confirmation', title='复制任务:请选择新工程')
|
||||
def launch():
|
||||
if self.request_id != request_id:
|
||||
if not self._allow_transition(request_id):
|
||||
return
|
||||
creation = self.window._dsh_task_creation
|
||||
self.copy_requests.add(request_id)
|
||||
@@ -238,7 +288,7 @@ class DshTaskLifecycleController(QObject):
|
||||
else:
|
||||
text += '\n\n仅写入任务配置,不执行 CAD。同批规则变更会应用到以上全部任务。'
|
||||
def apply():
|
||||
if self.request_id != request_id:
|
||||
if not self._allow_transition(request_id):
|
||||
return
|
||||
if self.window._workers or self.window._closed or self.window.plan_panel.has_unsaved_plan([t['task_id'] for t in plan['affected_tasks']]):
|
||||
self._failed(request_id, TaskCenterError('assistant_busy', '任务正在处理或有未保存计划,请重新确认。')); return
|
||||
@@ -268,7 +318,7 @@ class DshTaskLifecycleController(QObject):
|
||||
raise TaskCenterError('schedule_blocked', '排期尚未满足时间、依赖或执行门禁。')
|
||||
return current, api.preflight(self.window.service, current['task_ids'])
|
||||
self._work(check, lambda pair: self._preflight_ready(request_id, 'execute', pair[0]['task_ids'], pair[1],
|
||||
schedule=pair[0], automatic=automatic))
|
||||
schedule=pair[0], automatic=automatic), reserve_lane=False)
|
||||
|
||||
def _preflight_ready(self, request_id, capability, ids, report, *, resume=None, schedule=None, automatic=False):
|
||||
self.window._dsh_operations.cache['impact'] = report.get('impact', {})
|
||||
@@ -300,6 +350,8 @@ class DshTaskLifecycleController(QObject):
|
||||
if self.worker is not None and not self.active_ids:
|
||||
QTimer.singleShot(100, start)
|
||||
return
|
||||
if not self._allow_transition(request_id):
|
||||
return
|
||||
if self.window._workers or self.window._closed or self.window.plan_panel.has_unsaved_plan(ids):
|
||||
self._failed(request_id, TaskCenterError('assistant_busy', '任务状态已变化,请重新预检。')); return
|
||||
run_id = resume['run_id'] if resume else uuid4().hex
|
||||
|
||||
@@ -346,7 +346,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
if self._close_saving:
|
||||
event.ignore()
|
||||
return
|
||||
if self._workers or self.history_panel._worker or (self._dsh_operations and self._dsh_operations.worker):
|
||||
if self._workers or self.history_panel._worker:
|
||||
self._close_pending = True
|
||||
if self._dsh_automation and getattr(self._dsh_automation, '_owns_execution_lane', False):
|
||||
self._cancel_dsh_diagnosis()
|
||||
|
||||
@@ -8,8 +8,9 @@ from .workers import ServiceWorker
|
||||
class LatestQuery(QObject):
|
||||
settled = Signal()
|
||||
|
||||
def __init__(self, parent=None):
|
||||
def __init__(self, parent=None, *, pool=None):
|
||||
super().__init__(parent)
|
||||
self._pool = pool if pool is not None else QThreadPool.globalInstance()
|
||||
self._generation = 0
|
||||
self._active = {}
|
||||
self._pending = None
|
||||
@@ -68,7 +69,7 @@ class LatestQuery(QObject):
|
||||
worker.signals.succeeded.connect(self._received)
|
||||
worker.signals.failed.connect(self._failed)
|
||||
worker.signals.finished.connect(self._finished)
|
||||
QThreadPool.globalInstance().start(worker)
|
||||
self._pool.start(worker)
|
||||
|
||||
def _current(self):
|
||||
entry = self._active.get(self.sender())
|
||||
|
||||
Reference in new issue
Block a user