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

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

No files matched your search

+233
View File
@@ -0,0 +1,233 @@
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center.bom_import_report import BomImportReport, BomRowResult
from dx_productivity.trial_task_center.errors import TaskCenterError
from .test_dsh_operations import setup_view
@pytest.fixture
def blockers(ui, monkeypatch):
events = []
spy = SimpleNamespace(
watched={}, check_stalled=lambda: 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)),
unwatch=lambda *args, **kwargs: events.append(('unwatch', args, kwargs)),
progress=lambda *args, **kwargs: events.append(('progress', args, kwargs)))
monkeypatch.setattr(ui.window, '_dsh_blockers', spy, raising=False)
return events
def reports(events):
return [event for event in events if event[0] == 'report']
def test_bom_validation_reports_original_owner_and_bounded_evidence(ui, blockers, monkeypatch):
from PySide6.QtWidgets import QFileDialog
panel = ui.window.plan_panel
owner = ui.tasks[0].task_id
pending = []
monkeypatch.setattr(QFileDialog, 'getOpenFileName', lambda *args: ('bad.xlsx', ''))
monkeypatch.setattr(panel, '_dispatch_cancellable', lambda operation, callback, button, **kwargs: pending.append(callback))
panel.import_bom()
ui.open(ui.tasks[1])
report = BomImportReport(tuple(BomRowResult(i, 'board.prj', 'Board', 'failed', 'R9 missing')
for i in range(2, 152)), (), errors=('bad header',) * 150)
pending[0](report)
event, args, options = reports(blockers)[-1]
assert args[1:3] == (owner, 'bom_validation_failed')
assert args[4]['total_rows'] == args[4]['failed_rows'] == 150
assert args[4]['rows'][0]['reason'] == 'R9 missing'
assert len(args[4]['rows']) <= 100 and len(args[4]['errors']) <= 100
assert options.get('read_only') is True
assert not ui.calls
def test_bom_new_attempt_clears_scope_but_cancelled_file_dialog_does_not(ui, blockers, monkeypatch):
from PySide6.QtWidgets import QFileDialog
panel = ui.window.plan_panel
scope = panel._report_scope(panel.task_id)
report = BomImportReport((BomRowResult(2, '', '', 'failed', 'invalid row'),), ())
panel._received_bom_report(report, scope=scope)
source = reports(blockers)[-1][1][0]
blockers.clear()
monkeypatch.setattr(QFileDialog, 'getOpenFileName', lambda *args: ('', ''))
panel.import_bom()
assert not blockers
monkeypatch.setattr(QFileDialog, 'getOpenFileName', lambda *args: ('new.xlsx', ''))
monkeypatch.setattr(panel, '_dispatch', lambda *args, **kwargs: None)
panel.import_bom()
assert ('clear', (source,), {}) in blockers
panel.finish_operation()
def test_preflight_blockers_include_exact_task_evidence_and_clear_when_ready(ui, blockers, monkeypatch):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_lifecycle
ids = [ui.tasks[0].task_id, ui.tasks[1].task_id]
report = {'ready': False, 'tasks': [
{'task_id': ids[0], 'blockers': ['saved plan invalid']},
{'task_id': ids[1], 'blockers': ['project missing']}],
'impact': {'component_count': 3}, 'message': 'checked'}
ctl._preflight_ready('a' * 32, 'preflight', ids, report)
args = reports(blockers)[-1][1]
assert args[1:3] == (ids[0], 'preflight_blocked')
assert args[4]['tasks'] == report['tasks'] and args[4]['impact'] == report['impact']
assert 'saved plan invalid' in args[3] and 'project missing' in args[3]
ctl._preflight_ready('b' * 32, 'preflight', list(reversed(ids)), {**report, 'ready': True})
assert ('clear', (args[0],), {}) in blockers
assert not ui.calls
@pytest.mark.parametrize('kind', ['lifecycle', 'operations'])
def test_assistant_operation_failure_preserves_requested_task_owner(ui, blockers, monkeypatch, qtbot, kind):
setup_view(ui, monkeypatch)
ctl = getattr(ui.window, '_dsh_' + kind)
captured = []
monkeypatch.setattr(ctl, '_work', lambda *args, **kwargs: captured.append(args))
owner = ui.tasks[0].task_id
request = {'request_id': 'c' * 32, 'spec': {'task_ids': [owner]}}
if kind == 'lifecycle':
request['capability'] = 'preflight'
else:
request['spec']['operation'] = 'impact'
ctl.request(request)
ui.open(ui.tasks[1])
ctl._failed('c' * 32, TaskCenterError('plan_unavailable', 'Saved plan cannot be read'))
args = reports(blockers)[-1][1]
assert args[1:4] == (owner, 'plan_unavailable', 'Saved plan cannot be read')
assert not ui.calls
@pytest.mark.parametrize('code', ['operation_cancelled', 'schedule_blocked'])
def test_expected_cancellation_and_schedule_waiting_do_not_report(ui, blockers, monkeypatch, code):
setup_view(ui, monkeypatch)
ui.window._dsh_lifecycle._failed('d' * 32, TaskCenterError(code, 'Waiting or cancelled'))
ui.window._dsh_operations._failed('e' * 32, TaskCenterError(code, 'Waiting or cancelled'))
assert not reports(blockers)
def test_operations_read_error_reports_on_ui_thread_and_clears_on_recovery(ui, blockers, monkeypatch, qtbot):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
original = ctl.schedules.events
monkeypatch.setattr(ctl.schedules, 'events', lambda: (_ for _ in ()).throw(OSError('unreadable')))
ctl.refresh()
qtbot.waitUntil(lambda: ctl.worker is None)
event = next(row for row in reports(blockers) if row[1][2] == 'section_unavailable')
assert event[1][4]['section'] == 'schedule_events'
assert event[2].get('read_only') is True
monkeypatch.setattr(ctl.schedules, 'events', original)
ctl.refresh()
qtbot.waitUntil(lambda: ctl.worker is None)
assert ('clear', (event[1][0],), {}) in blockers
@pytest.mark.parametrize('kind', ['lifecycle', 'operations'])
def test_successful_assistant_request_clears_previous_scoped_error(ui, blockers, monkeypatch, kind):
setup_view(ui, monkeypatch)
ctl = getattr(ui.window, '_dsh_' + kind)
ctl.request_id = 'f' * 32
ctl._request_task_ids = (ui.tasks[0].task_id,)
ctl._failed('f' * 32, TaskCenterError('plan_unavailable', 'cannot read plan'))
source = reports(blockers)[-1][1][0]
ctl.request_id = 'a' * 32
ctl._respond('a' * 32, status='read')
assert ('clear', (source,), {}) in blockers
def test_schedule_plan_failure_is_reported_but_future_schedule_wait_is_not(ui, blockers, monkeypatch, qtbot):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_lifecycle
row = {'schedule_id': 'a' * 32, 'task_ids': [ui.tasks[0].task_id], 'ready': False,
'dispatchable': False, 'blockers': ['plan_changed']}
monkeypatch.setattr(ui.window._dsh_operations.schedules, 'evaluate', lambda _: [row])
ctl.start_schedule(row)
qtbot.waitUntil(lambda: ctl.worker is None)
args = reports(blockers)[-1][1]
assert args[2] == 'schedule_plan_blocked' and 'plan_changed' in args[3]
blockers.clear()
row['blockers'] = ['not_due']
ctl.start_schedule(row)
qtbot.waitUntil(lambda: ctl.worker is None)
assert not reports(blockers) and not ui.calls
def test_bom_operational_report_and_progress_keep_import_owner_after_selection_changes(ui, blockers, monkeypatch):
from dx_productivity.trial_task_center.bom_import_state import BomImportPhase
panel = ui.window.plan_panel
owner = panel.task_id
scope = panel._report_scope(owner)
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
error = TaskCenterError('bom_read_failed', 'Project inventory unavailable')
error.bom_report = BomImportReport((BomRowResult(2, '', '', 'failed', 'inventory unavailable'),), ())
panel.finish_operation(error=error)
args = reports(blockers)[-1][1]
assert args[1] == owner and args[4]['failed_rows'] == 1
assert not ui.calls
def test_lifecycle_direct_rejection_is_reported_once(ui, blockers, monkeypatch):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_lifecycle
ctl._respond('c' * 32, status='rejected', message='No matching active execution')
assert len(reports(blockers)) == 1
assert reports(blockers)[0][1][3] == 'No matching active execution'
blockers.clear()
ctl._respond('d' * 32, status='failed', queue_id='e' * 32, tasks=[])
assert not reports(blockers) # Execution receipts already report each failed task.
def test_background_operations_read_worker_is_watched_until_finished(ui, blockers, monkeypatch, qtbot):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
ctl.refresh()
worker = ctl.worker
assert any(event[0] == 'watch' and event[1][0] is worker for event in blockers)
qtbot.waitUntil(lambda: ctl.worker is None)
assert any(event[0] == 'unwatch' and event[1][0] is worker for event in blockers)
def test_creation_validation_failure_reports_bounded_summary_without_watching_dialog(ui, blockers, monkeypatch):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_task_creation
ctl.request({'request_id': 'a' * 32, 'spec': {'name': 'A' * 1000, 'rules': []}})
args = reports(blockers)[-1][1]
assert args[0:2] == ('task-creation', '')
assert args[4]['phase'] == 'validation' and len(args[4]['name']) <= 120
assert not any(event[0] == 'watch' for event in blockers)
def test_creation_worker_failure_reports_and_success_clears_source(ui, blockers, monkeypatch, qtbot):
from .test_dsh_task_creation import request
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_task_creation
original = ui.service.create_assistant_project_tasks
root = ui.data.parent / 'projects'
paths = (root / 'Board-A' / 'board.prj',)
monkeypatch.setattr(ui.service, 'create_assistant_project_tasks',
lambda *args: (_ for _ in ()).throw(TaskCenterError('creation_locked', 'Storage is locked')))
ctl.request(request('b'))
monkeypatch.setattr(ctl.dialog, 'values', lambda: (root, paths))
ctl._accepted('b' * 32, ctl.dialog.spec)
worker = ctl.worker
qtbot.waitUntil(lambda: ctl.worker is None)
args = reports(blockers)[-1][1]
assert args[0:4] == ('task-creation', '', 'creation_locked', 'Storage is locked')
assert args[4]['phase'] == 'creation' and args[4]['rule_count'] == 1
assert any(event[0] == 'watch' and event[1][0] is worker for event in blockers)
assert any(event[0] == 'unwatch' and event[1][0] is worker for event in blockers)
monkeypatch.setattr(ui.service, 'create_assistant_project_tasks', original)
ctl.request(request('c'))
monkeypatch.setattr(ctl.dialog, 'values', lambda: (root, paths))
ctl._accepted('c' * 32, ctl.dialog.spec)
qtbot.waitUntil(lambda: ctl.worker is None)
assert ('clear', ('task-creation',), {}) in blockers
assert not ui.calls
+216
View File
@@ -0,0 +1,216 @@
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center.ui.dsh_blockers import DshBlockerCoordinator
def test_blocker_report_is_deduplicated_until_cleared():
events = []
window = SimpleNamespace(auto_intervention_check=SimpleNamespace(isChecked=lambda: True))
coordinator = DshBlockerCoordinator(window, lambda **value: events.append(value) or True)
assert coordinator.report('bom', 'task-1', 'bom_validation_failed', 'bad row', {'failed_rows': 1})
assert not coordinator.report('bom', 'task-1', 'bom_validation_failed', 'bad row', {'failed_rows': 1})
assert len(events) == 1
coordinator.clear('bom', 'task-1')
assert coordinator.report('bom', 'task-1', 'bom_validation_failed', 'bad row', {'failed_rows': 1})
assert len(events) == 2
def test_disabled_switch_keeps_blocker_until_enabled():
events = []
state = {'enabled': False}
window = SimpleNamespace(auto_intervention_check=SimpleNamespace(isChecked=lambda: state['enabled']))
coordinator = DshBlockerCoordinator(window, lambda **value: events.append(value) or True)
assert not coordinator.report('resources', '', 'batch_resources_pending', 'still held')
assert not events
state['enabled'] = True
coordinator.replay_pending()
assert len(events) == 1
assert events[0]['issue_code'] == 'batch_resources_pending'
def test_different_blockers_and_tasks_get_separate_events():
events = []
window = SimpleNamespace(auto_intervention_check=SimpleNamespace(isChecked=lambda: True))
coordinator = DshBlockerCoordinator(window, lambda **value: events.append(value) or True)
coordinator.report('preflight', 'task-1', 'preflight_blocked', 'missing plan')
coordinator.report('preflight', 'task-2', 'preflight_blocked', 'missing plan')
coordinator.report('resources', '', 'batch_resources_pending', 'held')
assert [(e['source'], e['task_id']) for e in events] == [
('preflight', 'task-1'), ('preflight', 'task-2'), ('resources', '')]
def test_progress_prevents_stall_but_stuck_worker_reports_once():
events = []
window = SimpleNamespace(auto_intervention_check=SimpleNamespace(isChecked=lambda: True))
coordinator = DshBlockerCoordinator(window, lambda **value: events.append(value) or True)
worker = object()
coordinator.watch(worker, '导入 BOM', 'task-1', 'bom', now=0)
coordinator.progress('reading row 1', worker, now=100)
coordinator.check_stalled(now=121)
assert not events
coordinator.check_stalled(now=221)
coordinator.check_stalled(now=230)
assert len(events) == 1
assert events[0]['read_only'] is True
assert events[0]['details']['area'] == 'bom'
coordinator.unwatch(worker)
assert not coordinator.active
@pytest.mark.parametrize('area', ['query', 'operations', 'task-creation'])
def test_operation_progress_does_not_hide_stuck_query_and_recovery_starts_new_episode(area):
events = []
window = SimpleNamespace(auto_intervention_check=SimpleNamespace(isChecked=lambda: True))
coordinator = DshBlockerCoordinator(window, lambda **value: events.append(value) or True)
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.check_stalled(now=121)
assert len(events) == 1 and events[0]['task_id'] == ''
coordinator.progress('resource reply received', query, now=130)
assert not coordinator.active
coordinator.progress('row 3', operation, now=230)
coordinator.check_stalled(now=251)
assert len(events) == 2
assert events[0]['run_id'] != events[1]['run_id']
def test_resource_states_enter_ai_once_and_recover(ui):
window = ui.window
events = []
window._dsh_blockers.enqueue = lambda **value: events.append(value) or True
window._resource_status.known = True
window._resource_status.records = ({'batch_id': 'owned-batch', 'pid': 123},)
window._observe_dsh_resource_blockers()
window._observe_dsh_resource_blockers()
assert len(events) == 1
assert events[0]['issue_code'] == 'batch_resources_pending'
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()
assert events[-1]['issue_code'] == 'resource_inspection_failed'
assert len(events) == 2
window._resource_status.error = None
window._observe_dsh_resource_blockers()
assert not window._dsh_blockers.active
def test_resources_owned_by_running_operation_are_not_release_failures(ui):
from dx_productivity.trial_task_center.ui.operation_state import OperationState
window = ui.window
events = []
window._dsh_blockers.enqueue = lambda **value: events.append(value) or True
active = object()
window._workers.add(active)
window.operation_state = OperationState.start('导入 BOM', window._task_id, 'bom')
window._resource_status.known = True
window._resource_status.records = ({'state': 'ready', 'session_id': 'active-owned-session'},)
try:
window._observe_dsh_resource_blockers()
assert not events
window._resource_status.records = ({'state': 'blocked', 'session_id': 'active-owned-session'},)
window._observe_dsh_resource_blockers()
assert len(events) == 1
finally:
window._workers.discard(active)
window._resource_status.records = ()
def test_ai_retry_healthy_resources_are_not_release_failures(ui, monkeypatch):
window = ui.window
events = []
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))
window._workers.add(active)
window._resource_status.known = True
window._resource_status.records = ({'state': 'ready', 'session_id': 'auto-owned-session'},)
try:
window._observe_dsh_resource_blockers()
assert not events
finally:
window._workers.discard(active)
window._resource_status.records = ()
def test_clear_removes_queued_blocker_and_disabled_replay_retains_episode():
events, cancelled = [], []
window = SimpleNamespace(auto_intervention_check=SimpleNamespace(isChecked=lambda: True))
coordinator = DshBlockerCoordinator(window, lambda **value: events.append(value) or True, cancelled.append)
coordinator.report('resources', '', 'batch_resources_pending', 'held')
run_id = events[0]['run_id']
coordinator.set_enabled(False)
coordinator.set_enabled(True)
assert events[-1]['run_id'] == run_id
coordinator.clear('resources')
assert cancelled == [run_id]
def test_readonly_diagnosis_starts_while_worker_is_stuck_and_keeps_controls(ui, monkeypatch, qtbot):
from PySide6.QtWidgets import QApplication
from dx_productivity.trial_task_center.stop_control import StopControl
from dx_productivity.trial_task_center.ui import dsh_automation as module
ui.settle()
window = ui.window
original = object()
stop = StopControl()
window._workers.add(original)
window._batch_stop = stop
window._active_quick_run_task_id = window._task_id
monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows')
monkeypatch.setattr(window, '_open_dsh', lambda: None)
monkeypatch.setattr(module, 'GitIssuePublisher', lambda path: lambda *args: {'status': 'unavailable'})
automation = module.DshAutomation(window)
window._dsh_automation = automation
try:
assert automation.enqueue(window._task_id, 'operation_stalled', 'stuck',
read_only=True, snapshot_override={'task_id': window._task_id, 'status': 'running',
'issue_code': 'operation_stalled', 'issue': 'stuck'})
automation._drain()
assert automation.worker is not None
qtbot.waitUntil(lambda: automation.worker is None, timeout=10000)
assert window._workers == {original}
assert window._batch_stop is stop
assert window._active_quick_run_task_id == window._task_id
assert not stop.is_set()
finally:
window._workers.discard(original)
window._batch_stop = None
window._active_quick_run_task_id = None
def test_resource_diagnosis_keeps_previous_cad_stop_intent(ui, monkeypatch, qtbot):
from PySide6.QtWidgets import QApplication
from dx_productivity.trial_task_center.stop_control import StopControl
from dx_productivity.trial_task_center.ui import dsh_automation as module
ui.settle()
window = ui.window
previous_stop = StopControl()
previous_stop.set()
window._dsh_run_stop = previous_stop
monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows')
monkeypatch.setattr(window, '_open_dsh', lambda: None)
monkeypatch.setattr(module, 'GitIssuePublisher', lambda path: lambda *args: {'status': 'unavailable'})
automation = module.DshAutomation(window)
window._dsh_automation = automation
assert automation.enqueue('', 'batch_resources_pending', 'held', snapshot_override={
'task_id': '', 'status': 'blocked'}, cleanup_allowed=True)
automation._drain()
qtbot.waitUntil(lambda: automation.worker is None, timeout=10000)
assert window._dsh_run_stop is previous_stop
assert window._dsh_run_stop.is_set()
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)))
window._handle_dsh_action({'task_id': window._task_id, 'revision': 'r', 'action': 'retry_issue'})
assert calls == ['a' * 24]