fix(dsh): address intervention cancellation and verification review
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:
阿白叔 committed 2026-11-05 11:58:32 +08:00
1 parent de9cb2908d
commit 775bc23dc3
26 files changed
+1280 -119

No files matched your search

+43 -1
View File
@@ -12,6 +12,7 @@ def blockers(ui, monkeypatch):
events = []
spy = SimpleNamespace(
watched={}, check_stalled=lambda: None,
completed=lambda *args: None,
report=lambda *args, **kwargs: events.append(('report', args, kwargs)),
clear=lambda *args, **kwargs: events.append(('clear', args, kwargs)),
watch=lambda *args, **kwargs: events.append(('watch', args, kwargs)),
@@ -117,8 +118,11 @@ def test_operations_read_error_reports_on_ui_thread_and_clears_on_recovery(ui, b
monkeypatch.setattr(ctl.schedules, 'events', lambda: (_ for _ in ()).throw(OSError('unreadable')))
ctl.refresh()
qtbot.waitUntil(lambda: ctl.worker is None)
assert not reports(blockers)
qtbot.waitUntil(lambda: bool(reports(blockers)), timeout=3000)
event = next(row for row in reports(blockers) if row[1][2] == 'section_unavailable')
assert event[1][4]['section'] == 'schedule_events'
assert event[1][4]['consecutive_failures'] == 2
assert event[2].get('read_only') is True
monkeypatch.setattr(ctl.schedules, 'events', original)
ctl.refresh()
@@ -161,11 +165,15 @@ def test_bom_operational_report_and_progress_keep_import_owner_after_selection_c
panel = ui.window.plan_panel
owner = panel.task_id
scope = panel._report_scope(owner)
worker = object()
monkeypatch.setattr(ui.window, '_operation_worker', worker, raising=False)
monkeypatch.setattr(panel, '_dispatch', lambda *args, **kwargs: None)
panel._dispatch_cancellable(lambda *args: None, lambda _: None, panel.import_bom_button, bom_scope=scope)
ui.open(ui.tasks[1])
panel._operation_phase(BomImportPhase.VALIDATING, 'Validating imported rows')
assert ('progress', ('Validating imported rows',), {}) in blockers
assert any(event[0] == 'progress' and event[1][0] == 'Validating imported rows'
and (event[1][1] if len(event[1]) > 1 else event[2].get('worker')) is worker
for event in blockers)
error = TaskCenterError('bom_read_failed', 'Project inventory unavailable')
error.bom_report = BomImportReport((BomRowResult(2, '', '', 'failed', 'inventory unavailable'),), ())
panel.finish_operation(error=error)
@@ -231,3 +239,37 @@ def test_creation_worker_failure_reports_and_success_clears_source(ui, blockers,
qtbot.waitUntil(lambda: ctl.worker is None)
assert ('clear', ('task-creation',), {}) in blockers
assert not ui.calls
def test_transient_background_section_failure_recovers_on_quick_reread_without_ai(ui, blockers, monkeypatch, qtbot):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
original = ctl.schedules.events
calls = []
def read():
calls.append(True)
if len(calls) == 1:
raise OSError('temporary read sharing violation')
return original()
monkeypatch.setattr(ctl.schedules, 'events', read)
ctl.refresh()
qtbot.waitUntil(lambda: len(calls) >= 2 and ctl.worker is None, timeout=3000)
assert not reports(blockers)
@pytest.mark.parametrize('scope', ['whole_read', 'decision_audit'])
def test_transient_background_read_failures_are_confirmed_by_actual_reads(ui, blockers, monkeypatch, qtbot, scope):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
owner, method = (ctl, '_read') if scope == 'whole_read' else (ctl.decisions, 'list')
original = getattr(owner, method)
calls = []
def read(*args, **kwargs):
calls.append(True)
if len(calls) == 1:
raise OSError('temporary read unavailable')
return original(*args, **kwargs)
monkeypatch.setattr(owner, method, read)
ctl.refresh()
qtbot.waitUntil(lambda: len(calls) >= 2 and ctl.worker is None, timeout=3000)
assert not reports(blockers)
+63 -5
View File
@@ -66,7 +66,7 @@ def test_operation_progress_does_not_hide_stuck_query_and_recovery_starts_new_ep
operation, query = object(), object()
coordinator.watch(operation, '导入 BOM', 'task-1', 'bom', now=0)
coordinator.watch(query, '读取资源', '', area, now=0)
coordinator.progress('row 2', now=100)
coordinator.progress('row 2', operation, now=100)
coordinator.check_stalled(now=121)
assert len(events) == 1 and events[0]['task_id'] == ''
coordinator.progress('resource reply received', query, now=130)
@@ -90,8 +90,9 @@ def test_resource_states_enter_ai_once_and_recover(ui):
assert events[0]['cleanup_allowed'] is True
window._resource_status.records = ()
window._observe_dsh_resource_blockers()
window._resource_status.error = OSError('resource query failed')
window._observe_dsh_resource_blockers()
window._resource_status._failed(OSError('resource query failed'))
assert len(events) == 1
window._resource_status._failed(OSError('resource query failed'))
assert events[-1]['issue_code'] == 'resource_inspection_failed'
assert len(events) == 2
window._resource_status.error = None
@@ -126,7 +127,8 @@ def test_ai_retry_healthy_resources_are_not_release_failures(ui, monkeypatch):
window._dsh_blockers.enqueue = lambda **value: events.append(value) or True
active = object()
monkeypatch.setattr(window, '_dsh_automation', SimpleNamespace(worker=active, _owns_execution_lane=True,
latest={'status': 'retrying'}, cancel_pending=lambda value: None))
latest={'status': 'retrying'}, cancel_pending=lambda value: None,
can_cancel=False, cancel=lambda: None))
window._workers.add(active)
window._resource_status.known = True
window._resource_status.records = ({'state': 'ready', 'session_id': 'auto-owned-session'},)
@@ -206,11 +208,67 @@ def test_resource_diagnosis_keeps_previous_cad_stop_intent(ui, monkeypatch, qtbo
assert window._dsh_run_stop.is_set()
@pytest.mark.parametrize('complete_while_disabled', [False, True])
def test_completed_blocker_restarts_only_after_explicit_switch_cycle(complete_while_disabled):
events = []
state = {'enabled': True}
window = SimpleNamespace(auto_intervention_check=SimpleNamespace(isChecked=lambda: state['enabled']))
coordinator = DshBlockerCoordinator(window, lambda **value: events.append(dict(value)) or True)
coordinator.report('bom', 'task-1', 'bom_validation_failed', 'bad row')
original_run = events[0]['run_id']
if not complete_while_disabled:
coordinator.completed(original_run)
for _ in range(3):
coordinator.report('bom', 'task-1', 'bom_validation_failed', 'bad row')
coordinator.replay_pending()
assert len(events) == 1
state['enabled'] = False
coordinator.set_enabled(False)
if complete_while_disabled:
coordinator.completed(original_run)
state['enabled'] = True
coordinator.set_enabled(True)
assert len(events) == 2 and events[-1]['run_id'] != original_run
coordinator.report('bom', 'task-1', 'bom_validation_failed', 'bad row')
assert len(events) == 2
def test_completed_while_disabled_restarts_once_but_healthy_clear_cancels():
events, cancelled = [], []
state = {'enabled': True}
window = SimpleNamespace(auto_intervention_check=SimpleNamespace(isChecked=lambda: state['enabled']))
coordinator = DshBlockerCoordinator(window, lambda **value: events.append(dict(value)) or True, cancelled.append)
coordinator.report('resources', '', 'batch_resources_pending', 'held')
run_id = events[0]['run_id']
state['enabled'] = False
coordinator.set_enabled(False)
coordinator.completed(run_id)
coordinator.clear('resources')
state['enabled'] = True
coordinator.set_enabled(True)
assert len(events) == 1 and cancelled == [run_id]
def test_progress_only_resets_actual_worker_even_in_same_area():
events = []
window = SimpleNamespace(auto_intervention_check=SimpleNamespace(isChecked=lambda: True))
coordinator = DshBlockerCoordinator(window, lambda **value: events.append(dict(value)) or True)
first, second = object(), object()
coordinator.watch(first, 'first BOM', 'task-1', 'bom', now=0)
coordinator.watch(second, 'second BOM', 'task-2', 'bom', now=0)
coordinator.progress('row 2', first, now=100)
coordinator.check_stalled(now=121)
assert [event['task_id'] for event in events] == ['task-2']
with pytest.raises(TypeError):
coordinator.progress('unscoped progress', now=130)
def test_global_resource_evidence_actions_work_with_a_task_selected(ui, monkeypatch):
window = ui.window
calls = []
monkeypatch.setattr(window, '_dsh_view', SimpleNamespace(context={'revision': 'r'}, shutdown=lambda: None))
monkeypatch.setattr(window, '_dsh_automation', SimpleNamespace(
latest={'task_id': '', 'incident_id': 'a' * 24}, resubmit=lambda value: calls.append(value)))
latest={'task_id': '', 'incident_id': 'a' * 24}, resubmit=lambda value: calls.append(value),
can_cancel=False, cancel=lambda: None))
window._handle_dsh_action({'task_id': window._task_id, 'revision': 'r', 'action': 'retry_issue'})
assert calls == ['a' * 24]
+141
View File
@@ -0,0 +1,141 @@
import json
from types import SimpleNamespace
import pytest
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QApplication
from dx_productivity.trial_task_center.ui import dsh_automation as module
from .test_dsh_native_menu import HarnessView
class SlowHarness(HarnessView):
diagnosis_event = Signal(object)
def __init__(self, parent):
super().__init__(parent)
self.requests, self.cancellations = [], []
self.is_running = True
def request_diagnosis(self, request):
self.requests.append(request)
def cancel_diagnosis(self, request_id):
self.cancellations.append(request_id)
def shutdown(self):
self.is_running = False
self.stopped.emit()
@pytest.fixture
def slow_diagnosis(ui, qtbot, monkeypatch):
ui.settle()
window = ui.window
published = []
monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows')
monkeypatch.setattr(window, '_create_dsh_view', lambda: SlowHarness(window))
monkeypatch.setattr(module, 'GitIssuePublisher', lambda path: lambda *args: published.append(args) or {'status': 'unavailable'})
automation = module.DshAutomation(window)
window._dsh_automation = automation
def start(*, read_only=True, cleanup=False):
automation.enqueue('', 'batch_resources_pending' if cleanup else 'operation_stalled', 'controlled slow diagnosis',
read_only=read_only, cleanup_allowed=cleanup, snapshot_override={'task_id': '', 'status': 'unknown'})
automation._drain()
qtbot.waitUntil(lambda: bool(window._dsh_view.requests), timeout=5000)
return window._dsh_view
yield window, automation, published, start
if automation.worker is not None:
if hasattr(automation, 'cancel'):
automation.cancel()
else:
for request_id in list(automation.waiters):
automation._diagnosis_event({'request_id': request_id, 'status': 'failed', 'error': 'test_cleanup'})
qtbot.waitUntil(lambda: automation.worker is None, timeout=5000)
if not window._closed:
ui.settle()
def test_readonly_diagnosis_keeps_task_controls_usable_and_can_be_cancelled(slow_diagnosis, qtbot, ui):
window, automation, published, start = slow_diagnosis
view = start()
assert automation.worker not in window._workers
assert window.task_list.list.isEnabled()
assert window.task_list.new_button.isEnabled()
assert window.cancel_diagnosis_button.isVisible()
qtbot.mouseClick(window.cancel_diagnosis_button, Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: automation.worker is None, timeout=5000)
assert view.cancellations
assert automation.latest['status'] == 'cancelled'
assert not published
assert not window.cancel_diagnosis_button.isVisible()
ui.settle()
def test_readonly_diagnosis_does_not_prevent_window_close(slow_diagnosis, qtbot):
window, automation, published, start = slow_diagnosis
start()
window.close()
qtbot.waitUntil(lambda: window._closed and automation.worker is None, timeout=5000)
assert not window._close_pending
assert not published
def test_resource_diagnosis_has_no_cad_pause_or_force_controls(slow_diagnosis, qtbot, ui):
window, automation, published, start = slow_diagnosis
view = start(read_only=False, cleanup=True)
assert automation.worker in window._workers
assert window._batch_stop is None
assert not window.run_panel.stop_queue_button.isVisible()
assert not window.run_panel.force_stop_button.isVisible()
qtbot.mouseClick(window.cancel_diagnosis_button, Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: automation.worker is None, timeout=5000)
assert view.cancellations and not published
ui.settle()
def test_model_wait_is_limited_by_remaining_total_budget(slow_diagnosis, monkeypatch, ui):
window, automation, _, _ = slow_diagnosis
window._open_dsh()
waits = []
class Complete:
def wait(self, timeout):
waits.append(timeout)
return False
monkeypatch.setattr(module, 'Event', Complete)
monkeypatch.setattr(module, 'monotonic', lambda: 100.0)
automation._analysis_deadline = 100.1
with pytest.raises(TimeoutError):
automation._analyze('a' * 24, {'task_id': ''}, 'evidence', 'reflect')
assert 0 < waits[0] <= 0.1
ui.settle()
def test_native_cancel_removes_queued_request_and_sends_only_target_id():
from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView
sent = []
native = SimpleNamespace(_diagnosis_queue=[{'request_id': 'cancel'}, {'request_id': 'keep'}],
_started=False, is_running=True, process=SimpleNamespace(write=sent.append))
NativeHarnessView.cancel_diagnosis(native, 'cancel')
assert native._diagnosis_queue == [{'request_id': 'keep'}]
assert not sent
native._started = True
NativeHarnessView.cancel_diagnosis(native, 'active')
assert json.loads(sent[0]) == {'type': 'diagnose_cancel', 'request_id': 'active'}
def test_completed_incident_removes_embedded_cancel_action(slow_diagnosis, qtbot, ui):
from dx_productivity.trial_task_center.ui.workers import ServiceWorker
window, automation, _, _ = slow_diagnosis
window._open_dsh()
automation._current_identity = ('', 'operation_stalled', 'blocker-completed')
automation._owns_execution_lane = False
automation._start_worker(ServiceWorker(lambda: {'status': 'observed_cleared', 'task_id': ''}))
qtbot.waitUntil(lambda: automation.worker is None)
assert window._dsh_view.automation['can_cancel'] is False
assert not window.cancel_diagnosis_button.isVisible()
ui.settle()
+7 -7
View File
@@ -80,7 +80,7 @@ def test_cross_task_harness_action_never_reaches_task_service(ui, monkeypatch):
def test_error_entry_queues_automatic_ai_without_running_synchronous_retry(ui, monkeypatch):
window = ui.window
events, retried = [], []
window._dsh_automation = SimpleNamespace(enqueue=lambda *args, **kwargs: events.append((args, kwargs)) or True)
window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *args, **kwargs: events.append((args, kwargs)) or True)
window._dsh.action_handler = lambda proposal: retried.append(proposal)
window._show_error(TaskCenterError('worker_error', 'controlled error'))
assert len(events) == 1 and events[0][0][:2] == (window._task_id, 'worker_error')
@@ -90,7 +90,7 @@ def test_error_entry_queues_automatic_ai_without_running_synchronous_retry(ui, m
def test_failed_result_queues_ai_even_when_no_exception_is_raised(ui, monkeypatch):
window = ui.window
events = []
window._dsh_automation = SimpleNamespace(enqueue=lambda *args, **kwargs: events.append((args, kwargs)) or True)
window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *args, **kwargs: events.append((args, kwargs)) or True)
monkeypatch.setattr(window, '_metadata_changed', lambda _: None)
window._active_quick_run_task_id = window._task_id
window._show_batch_result(SimpleNamespace(paused=False,
@@ -101,7 +101,7 @@ def test_failed_result_queues_ai_even_when_no_exception_is_raised(ui, monkeypatc
def test_cancelled_operation_does_not_start_ai(ui):
window = ui.window
events = []
window._dsh_automation = SimpleNamespace(enqueue=lambda *args, **kwargs: events.append(args))
window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *args, **kwargs: events.append(args))
window._show_error(TaskCenterError('operation_cancelled', 'cancelled'))
assert not events
@@ -129,7 +129,7 @@ def test_auto_intervention_toggle_persists_and_disabled_errors_do_not_enqueue(ui
window = ui.window
events = []
assert window.auto_intervention_check.isChecked()
window._dsh_automation = SimpleNamespace(enqueue=lambda *a, **kw: events.append(a),
window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *a, **kw: events.append(a),
set_enabled=lambda enabled: None)
qtbot.mouseClick(window.auto_intervention_check, Qt.MouseButton.LeftButton)
window._show_error(TaskCenterError('worker_error', 'disabled error'))
@@ -166,7 +166,7 @@ def test_taskless_error_automatically_queues_diagnosis(ui):
window._task_id = None
window._dsh_run_id = 'previous-cad-run'
events = []
window._dsh_automation = SimpleNamespace(enqueue=lambda *a, **kw: events.append((a, kw)) or True)
window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *a, **kw: events.append((a, kw)) or True)
window._show_error(TaskCenterError('worker_error', 'taskless error'))
assert len(events) == 1
assert events[0][0][:2] == ('', 'worker_error')
@@ -177,7 +177,7 @@ def test_taskless_error_automatically_queues_diagnosis(ui):
def test_native_startup_failure_never_enqueues_itself(ui):
events = []
ui.window._dsh_automation = SimpleNamespace(enqueue=lambda *a, **kw: events.append(a))
ui.window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *a, **kw: events.append(a))
ui.window._show_error(TaskCenterError('dsh_startup', 'native unavailable'))
assert not events
@@ -242,7 +242,7 @@ def test_taskless_incident_actions_allow_outbox_and_evidence_but_reject_other_ta
monkeypatch.setattr(window, '_task_id', None)
monkeypatch.setattr(window, '_dsh_view', SimpleNamespace(context={'revision': 'r'}, shutdown=lambda: None))
monkeypatch.setattr(window, '_dsh_automation', SimpleNamespace(
latest={'task_id': '', 'incident_id': 'a' * 24}, resubmit=lambda value: calls.append(value)))
can_cancel=False, cancel=lambda: None, latest={'task_id': '', 'incident_id': 'a' * 24}, resubmit=lambda value: calls.append(value)))
monkeypatch.setattr(QDesktopServices, 'openUrl', lambda url: calls.append(url.toLocalFile()))
window._handle_dsh_action({'task_id': '', 'revision': 'r', 'action': 'retry_issue'})
window._handle_dsh_action({'task_id': '', 'revision': 'r', 'action': 'open_evidence'})
+54
View File
@@ -0,0 +1,54 @@
from threading import Event
from dx_productivity.trial_task_center.ui.queries import LatestQuery
from dx_productivity.trial_task_center.ui.resource_status import ResourceStatus
def test_active_workers_excludes_cancelled_old_selection_and_is_immutable(qtbot):
query = LatestQuery()
first_started, second_started, release = Event(), Event(), Event()
def read(started):
started.set()
assert release.wait(5)
return ()
try:
query.request(lambda: read(first_started), lambda _: None, lambda _: None)
qtbot.waitUntil(first_started.is_set)
first = query.active_workers
assert isinstance(first, tuple) and len(first) == 1
query.request(lambda: read(second_started), lambda _: None, lambda _: None)
qtbot.waitUntil(second_started.is_set)
current = query.active_workers
assert len(current) == 1 and current[0] is not first[0]
query.invalidate()
assert query.active_workers == () and len(first) == 1
finally:
release.set()
qtbot.waitUntil(lambda: not query.busy)
query.close()
def test_resource_failures_count_actual_callbacks_and_success_resets(qtbot):
state = {'fail': True, 'calls': 0}
def read():
state['calls'] += 1
if state['fail']:
raise OSError('temporary local file failure')
return ()
status = ResourceStatus(read)
try:
assert status.consecutive_failures == 0
status.refresh()
qtbot.waitUntil(lambda: not status.busy)
assert status.consecutive_failures == 1
status.changed.emit()
assert status.consecutive_failures == 1
status.refresh()
qtbot.waitUntil(lambda: not status.busy)
assert status.consecutive_failures == 2
state['fail'] = False
status.refresh()
qtbot.waitUntil(lambda: not status.busy)
assert status.consecutive_failures == 0 and state['calls'] == 3
finally:
status.close()