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

This commit is contained in:
阿白叔 committed 2026-11-05 17:15:29 +08:00
1 parent 3ecb6fa276
commit eba935e710
24 files changed
+929 -128

No files matched your search

+31
View File
@@ -157,3 +157,34 @@ def test_saved_plan_hash_errors_are_not_replaced_with_synthetic_hashes(setup, mo
with pytest.raises(TaskCenterError) as caught:
execution_impact(service, [tasks[0].task_id])
assert caught.value.code == 'controlled_read_error'
@pytest.mark.parametrize('task_default', [False, True])
@pytest.mark.parametrize('mode', ['inherit', 'preserve', 'part_label', 'part_number', 'custom'])
def test_per_item_value_policy_matches_saved_execution_mode(setup, task_default, mode):
service, store, tasks, _ = setup
task_id = tasks[0].task_id
rows = store.list_target_plan(task_id)
item = replace(rows[0], value_mode=mode, custom_value_enabled=False, custom_value='CUSTOM')
store.replace_target_plan(task_id, (item, *rows[1:]))
store.set_copy_part_number_to_value(task_id, task_default)
result = execution_impact(service, [task_id])['rows'][0]
effective = ('part_label' if task_default else 'preserve') if mode == 'inherit' else mode
assert result['value_mode'] == mode
assert result['value_policy'] == effective
assert result['proposed_value'] == {'preserve': 'V1', 'part_label': None, 'part_number': 'NEW', 'custom': 'CUSTOM'}[effective]
def test_catalog_exposes_bounded_saved_item_value_policies(setup):
from dx_productivity.dsh.task_lifecycle import catalog
service, store, tasks, paths = setup
task_id = tasks[1].task_id
targets = tuple(ComponentTarget(paths[1], 'MAIN', '1', f'uid{i}', f'R{i}', 'OLD', 'ORIGINAL') for i in range(105))
store.record_target_inventory(task_id, targets)
store.replace_target_plan(task_id, tuple(TargetPlanRow(target, True, 'NEW', value_mode='part_number') for target in targets))
detail = catalog(service, task_id)['detail']
assert detail['targets_count'] == 105
assert len(detail['targets']) == 100 and detail['omitted_targets'] == 5
assert detail['targets'][0]['value_mode'] == 'part_number'
assert detail['targets'][0]['proposed_value'] == 'NEW'
assert detail['targets'][0]['uid'] == 'uid0'
+73
View File
@@ -0,0 +1,73 @@
from contextlib import contextmanager
from pathlib import Path
from test_incidents import Service, ResourceService, analyze, cleanup_model, make_runner
def test_rejected_admission_never_mutates_or_spends_retry_budget(tmp_path):
service = Service()
@contextmanager
def scope(action):
raise ValueError('execution_lane_changed')
yield
runner = make_runner(tmp_path, service)
runner.action_scope = scope
result = runner.run('t', 'worker_error', 'failure', execution_authorized=True)
assert service.calls == []
assert result['attempts'] == 0
assert not list((tmp_path / 'dsh/retry-budget').glob('*.json'))
def test_changed_task_after_model_wait_never_retries(tmp_path):
service = Service()
def model(*args):
service.progress.saved_items += 1
return analyze()
result = make_runner(tmp_path, service, model).run('t', 'worker_error', 'failure', execution_authorized=True)
assert not service.calls
assert result['attempts'] == 0
assert not list((tmp_path / 'dsh/retry-budget').glob('*.json'))
def test_action_scope_released_before_reflection_and_publication(tmp_path):
active, phases = [], []
@contextmanager
def scope(action):
active.append(action)
try:
yield
finally:
active.pop()
service = Service(fixed=False)
execute = service.execute_quick_run_queue
def execute_scoped(*args, **kwargs):
assert active == ['retry_failed']
return execute(*args, **kwargs)
service.execute_quick_run_queue = execute_scoped
def model(*args):
assert not active
phases.append(args[-1])
return analyze()
def publish(*args):
assert not active
return {'status': 'unavailable'}
runner = make_runner(tmp_path, service, model, publish)
runner.action_scope = scope
runner.run('t', 'worker_error', 'failure', execution_authorized=True)
assert phases == ['diagnose', 'reflect']
assert service.calls == ['prepare', 'execute']
assert not active
def test_cleanup_rejected_admission_does_not_release_resources(tmp_path):
service = ResourceService()
@contextmanager
def scope(action):
raise ValueError('execution_lane_changed')
yield
runner = make_runner(tmp_path, service, cleanup_model)
runner.action_scope = scope
result = runner.run('t', 'batch_resources_pending', 'failure', cleanup_allowed=True)
assert not service.calls
assert result['cleanup_attempts'] == 0
assert result['status'] != 'resolved'
+274
View File
@@ -0,0 +1,274 @@
"""AI observation must leave the desktop execution lane available."""
from threading import Event
from types import SimpleNamespace
import pytest
from PySide6.QtCore import QThreadPool
from dx_productivity.trial_task_center.ui.workers import ServiceWorker
from .test_dsh_diagnosis_lifecycle import slow_diagnosis
from .test_dsh_operations import setup_view
pytestmark = pytest.mark.usefixtures('ai_ready')
@pytest.fixture
def single_execution_thread(ui, qtbot):
ui.settle()
pool = QThreadPool.globalInstance()
previous = pool.maxThreadCount()
pool.setMaxThreadCount(1)
yield pool
qtbot.waitUntil(lambda: pool.activeThreadCount() == 0, timeout=5000)
pool.setMaxThreadCount(previous)
@pytest.mark.parametrize('source', ['timer', 'history'])
def test_operations_observation_never_reserves_or_starves_task_execution(
ui, monkeypatch, qtbot, single_execution_thread, source):
window = ui.window
view = setup_view(ui, monkeypatch)
operations = window._dsh_operations
started, release, executed = Event(), Event(), Event()
def read(**_kwargs):
started.set()
assert release.wait(5), 'Controlled operations read was not released'
return {'schedules': []}
monkeypatch.setattr(operations, '_read', read)
if source == 'timer':
operations.tick()
else:
operations.request({'request_id': 'a' * 32, 'spec': {'operation': 'history'}})
try:
qtbot.waitUntil(started.is_set, timeout=5000)
assert operations.worker not in window._workers
assert window.task_list.new_button.isEnabled()
window._run_async(executed.set, lambda _: None)
qtbot.waitUntil(executed.is_set, timeout=1000)
assert not release.is_set(), 'Task work must start before the AI read finishes'
finally:
release.set()
qtbot.waitUntil(lambda: operations.worker is None and not window._workers, timeout=5000)
if source == 'history':
assert view.lifecycle_results[-1]['status'] == 'read'
def test_availability_check_cannot_starve_task_worker(
ui, monkeypatch, qtbot, single_execution_thread):
from dx_productivity.trial_task_center.ui import dsh_status
status = ui.window._dsh_status
status.timer.stop()
qtbot.waitUntil(lambda: not status.query.busy, timeout=5000)
started, release, executed = Event(), Event(), Event()
def check(_root):
started.set()
assert release.wait(5), 'Controlled availability check was not released'
return {'available': True, 'code': 'available', 'message': 'Controlled readiness'}
monkeypatch.setattr(dsh_status, 'check_availability', check)
status.refresh()
worker = ServiceWorker(executed.set)
try:
qtbot.waitUntil(started.is_set, timeout=5000)
single_execution_thread.start(worker)
qtbot.waitUntil(executed.is_set, timeout=1000)
assert not release.is_set()
finally:
release.set()
qtbot.waitUntil(lambda: not status.query.busy, timeout=5000)
@pytest.mark.parametrize('kind', ['authorized_retry', 'resource_cleanup'])
def test_model_wait_never_owns_task_controls(slow_diagnosis, qtbot, kind):
window, automation, _, start = slow_diagnosis
if kind == 'resource_cleanup':
start(read_only=False, cleanup=True)
else:
automation.enqueue(window._task_id, 'execution_failed', 'Controlled authorized failure',
execution_authorized=True, run_id='b' * 32)
automation._drain()
qtbot.waitUntil(lambda: bool(window._dsh_view.requests), timeout=5000)
try:
assert automation.worker not in window._workers
assert window._batch_stop is None
assert window._active_quick_run_task_id is None
assert window.task_list.new_button.isEnabled()
finally:
automation.cancel()
qtbot.waitUntil(lambda: automation.worker is None, timeout=5000)
def test_finishing_old_diagnosis_preserves_new_manual_run(slow_diagnosis, ui, qtbot):
window, automation, _, _ = slow_diagnosis
automation.enqueue(window._task_id, 'execution_failed', 'Controlled old failure',
execution_authorized=True, run_id='c' * 32)
automation._drain()
qtbot.waitUntil(lambda: bool(window._dsh_view.requests), timeout=5000)
owner = ui.tasks[1].task_id
window._begin_run(owner)
manual_stop = window._batch_stop
manual_run = window._dsh_run_id
try:
automation.cancel()
qtbot.waitUntil(lambda: automation.worker is None, timeout=5000)
assert window._batch_stop is manual_stop
assert window._active_quick_run_task_id == owner
assert window._dsh_run_id == manual_run
assert window._dsh_live_run['active']
assert not manual_stop.is_set()
finally:
window._finish_run()
def reply_to_model(view, action='none'):
request = view.requests[-1]
view.diagnosis_event.emit({'status': 'started', 'request_id': request['request_id'],
'session_id': 'controlled-session'})
view.diagnosis_event.emit({'status': 'completed', 'request_id': request['request_id'],
'session_id': 'controlled-session',
'reply': '{"summary":"Controlled diagnosis","action":"' + action + '"}'})
def test_cleanup_reserves_lane_only_during_service_action(
slow_diagnosis, monkeypatch, qtbot):
from dx_productivity.trial_task_center.ui import dsh_automation
window, automation, _, start = slow_diagnosis
started, release = Event(), Event()
pending = [{'state': 'blocked', 'kind': 'controlled_test_resource'}]
publications = []
def cleanup():
started.set()
assert release.wait(5), 'Controlled cleanup was not released'
return tuple(pending)
def publish(*_args):
publications.append(automation.worker in window._workers)
return {'status': 'unavailable'}
monkeypatch.setattr(window.service, 'pending_batch_resources', lambda: tuple(pending))
monkeypatch.setattr(window.service, 'cleanup_batch_resources', cleanup)
monkeypatch.setattr(dsh_automation, 'GitIssuePublisher', lambda _path: publish)
view = start(read_only=False, cleanup=True)
reply_to_model(view, 'cleanup_resources')
try:
qtbot.waitUntil(started.is_set, timeout=5000)
assert automation.worker in window._workers
assert automation._owns_execution_lane
assert window._batch_stop is None
finally:
release.set()
qtbot.waitUntil(lambda: len(view.requests) == 2, timeout=5000)
assert view.requests[-1]['phase'] == 'reflect'
assert automation.worker not in window._workers
assert not automation._owns_execution_lane
assert window.task_list.new_button.isEnabled()
pending.clear()
reply_to_model(view)
qtbot.waitUntil(lambda: automation.worker is None, timeout=5000)
assert publications == [False]
@pytest.mark.parametrize('action', ['cleanup_resources', 'retry_failed'])
def test_new_manual_run_denies_old_ai_mutation_without_touching_controls(
slow_diagnosis, ui, monkeypatch, qtbot, action):
from dx_productivity.trial_task_center.ui import dsh_automation
window, automation, published, start = slow_diagnosis
mutations = []
monkeypatch.setattr(window.service, 'cleanup_batch_resources', lambda: mutations.append('cleanup'))
monkeypatch.setattr(window.service, 'prepare_failed_quick_run', lambda _task: mutations.append('prepare'))
if action == 'cleanup_resources':
view = start(read_only=False, cleanup=True)
else:
context = SimpleNamespace(task=SimpleNamespace(status=SimpleNamespace(value='running')),
interrupted=False, phase='retry')
monkeypatch.setattr(dsh_automation.IncidentRunner, '_snapshot',
lambda _self, task_id, _code, _message: ({'task_id': task_id, 'status': 'running'}, context))
automation.enqueue(window._task_id, 'execution_failed', 'Controlled retryable failure',
execution_authorized=True, run_id='d' * 32)
automation._drain()
qtbot.waitUntil(lambda: bool(window._dsh_view.requests), timeout=5000)
view = window._dsh_view
window._begin_run(ui.tasks[1].task_id)
manual_stop = window._batch_stop
owner = window._active_quick_run_task_id
try:
reply_to_model(view, action)
qtbot.waitUntil(lambda: len(view.requests) == 2, timeout=5000)
assert not mutations
assert automation.worker not in window._workers
assert window._batch_stop is manual_stop
assert window._active_quick_run_task_id == owner
assert not manual_stop.is_set()
assert 'ai_action_context_changed' in str(automation.latest)
assert not list(ui.data.glob('dsh/retry-budget/*.json'))
reply_to_model(view)
qtbot.waitUntil(lambda: automation.worker is None, timeout=5000)
assert window._batch_stop is manual_stop
assert window._active_quick_run_task_id == owner
assert len(published) == 1
finally:
window._finish_run()
def test_completed_taskless_observation_does_not_start_another_model_run(
slow_diagnosis, qtbot):
window, automation, published, start = slow_diagnosis
view = start()
reply_to_model(view)
qtbot.waitUntil(lambda: len(view.requests) == 2, timeout=5000)
reply_to_model(view)
qtbot.waitUntil(lambda: automation.worker is None, timeout=5000)
assert ('', 'operation_stalled', 'observation') in automation.seen
assert automation.enqueue('', 'operation_stalled', 'same persistent global error', read_only=True)
automation._drain()
qtbot.wait(20)
assert len(view.requests) == 2
assert automation.worker is None
assert not automation.pending
assert len(published) == 1
automation.set_enabled(False)
automation.set_enabled(True)
assert automation.enqueue('', 'operation_stalled', 'explicit new episode', read_only=True)
automation._drain()
qtbot.waitUntil(lambda: len(view.requests) == 3, timeout=5000)
automation.cancel()
qtbot.waitUntil(lambda: automation.worker is None, timeout=5000)
def test_admission_timeout_releases_even_if_gui_just_admitted(ui, monkeypatch):
from dx_productivity.trial_task_center.ui import dsh_automation as module
from dx_productivity.trial_task_center.stop_control import StopControl
ui.settle()
window = ui.window
automation = module.DshAutomation(window)
automation.worker = object()
automation.current_request = module.IncidentRequest('', 'batch_resources_pending', '',
False, 'observation', cleanup_allowed=True)
automation._observed_run_id = window._dsh_run_id
automation._action_stop = StopControl()
class ExpiringEvent:
def set(self):
pass
def wait(self, _timeout):
return False
monkeypatch.setattr(module, 'Event', ExpiringEvent)
try:
with pytest.raises(ValueError, match='admission_timeout'):
with automation._action_scope('cleanup_resources'):
pytest.fail('Timed-out admission must not mutate')
assert not automation._owns_execution_lane
assert automation.worker not in window._workers
assert automation._admitted_action is None
finally:
automation.worker = None
+1 -1
View File
@@ -106,7 +106,7 @@ def test_cancelled_close_confirmation_keeps_diagnosis_running(slow_diagnosis, qt
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 automation.worker not 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()
+17
View File
@@ -11,6 +11,23 @@ def setup_view(ui, monkeypatch):
return ui.window._dsh_view
def test_confirmed_operation_rechecks_lane_after_read_preview(ui, monkeypatch):
view = setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
ctl.request_id = '7' * 32
other_worker = object()
ui.window._workers.add(other_worker)
called = []
try:
ctl._work(lambda: called.append('mutation'), lambda _: None, request_id='7' * 32)
assert ctl.worker is None
assert ui.window._workers == {other_worker}
assert view.lifecycle_results[-1]['status'] == 'busy'
assert not called
finally:
ui.window._workers.discard(other_worker)
@pytest.mark.parametrize('missing', [False, True])
def test_terminal_history_sums_persisted_counts_and_preserves_unknown(ui, monkeypatch, qtbot, missing):
from dx_productivity.dsh.task_lifecycle import preflight
+172
View File
@@ -212,3 +212,175 @@ def test_pause_uses_active_stop_control_and_refuses_other_scope(ui, monkeypatch)
assert ui.window._batch_stop.is_set() and not ui.window._batch_stop.force_event.is_set()
assert view.lifecycle_results[-1]['status'] == 'pause_requested'
ui.window._finish_run()
def test_bom_handoff_requires_native_confirmation_and_never_claims_import(ui, monkeypatch, qtbot):
ctl, view = controller(ui, monkeypatch)
opened = []
monkeypatch.setattr(ui.window.plan_panel, 'import_bom', lambda: opened.append(ui.window.plan_panel.task_id))
ctl.request(request(ui, 'import_bom'))
qtbot.waitUntil(lambda: ctl.dialog is not None or bool(view.lifecycle_results), timeout=5000)
assert ctl.dialog is not None
assert '多选' in ctl.dialog.preview.toPlainText()
assert not opened and not ui.calls
qtbot.mouseClick(ctl.dialog.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: bool(view.lifecycle_results), timeout=5000)
assert opened == [ui.tasks[0].task_id]
assert view.lifecycle_results[-1]['status'] == 'handed_off'
assert view.lifecycle_results[-1]['cad_execution_started'] is False
ctl.request(request(ui, 'import_bom'))
assert len(opened) == 1
assert not ui.calls
ui.settle()
def test_bom_handoff_rechecks_selected_task_after_confirmation(ui, monkeypatch, qtbot):
ctl, view = controller(ui, monkeypatch)
opened = []
monkeypatch.setattr(ui.window.plan_panel, 'import_bom', lambda: opened.append(True))
ctl.request(request(ui, 'import_bom'))
qtbot.waitUntil(lambda: ctl.dialog is not None or bool(view.lifecycle_results), timeout=5000)
assert ctl.dialog is not None
ui.open(ui.tasks[1])
qtbot.mouseClick(ctl.dialog.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: bool(view.lifecycle_results), timeout=5000)
assert view.lifecycle_results[-1]['status'] == 'rejected'
assert not opened
ui.settle()
@pytest.mark.parametrize('capability', ['catalog', 'preflight', 'manage'])
def test_lifecycle_reads_do_not_reserve_ordinary_task_lane(ui, monkeypatch, qtbot, capability):
from threading import Event
ctl, view = controller(ui, monkeypatch)
ui.settle()
entered, release = Event(), Event()
api = lifecycle()
function = {'catalog': 'catalog', 'preflight': 'preflight', 'manage': 'preview'}[capability]
original = getattr(api, function)
def slow(*args, **kwargs):
entered.set()
assert release.wait(5)
return original(*args, **kwargs)
monkeypatch.setattr(api, function, slow)
spec = ({'task_id': ui.tasks[0].task_id} if capability == 'catalog' else
{'task_ids': [ui.tasks[0].task_id]} if capability == 'preflight' else
{'operation': 'update', 'task_id': ui.tasks[0].task_id, 'patch': {'name': 'Preview'}})
ctl.request({'request_id': 'f' * 32, 'capability': capability, 'spec': spec})
try:
qtbot.waitUntil(entered.is_set, timeout=5000)
lane_reserved = bool(ui.window._workers)
ordinary_execution_enabled = ui.window.run_panel.quick_run_button.isEnabled()
finally:
release.set()
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
if ctl.dialog is not None:
ctl.dialog.reject()
ui.settle()
assert not lane_reserved
assert ordinary_execution_enabled
def test_select_does_not_claim_success_if_ordinary_mutation_starts_during_read(ui, monkeypatch, qtbot):
from threading import Event
ctl, view = controller(ui, monkeypatch)
ui.settle()
entered, release = Event(), Event()
api = lifecycle()
original = api.preview
def slow(*args):
entered.set()
assert release.wait(5)
return original(*args)
monkeypatch.setattr(api, 'preview', slow)
ctl.request({'request_id': '3' * 32, 'capability': 'manage',
'spec': {'operation': 'select', 'task_id': ui.tasks[1].task_id}})
busy = object()
try:
qtbot.waitUntil(entered.is_set, timeout=5000)
ui.window._workers.add(busy)
release.set()
qtbot.waitUntil(lambda: bool(view.lifecycle_results), timeout=5000)
result = view.lifecycle_results[-1]
selected = ui.window._task_id
finally:
release.set()
ui.window._workers.discard(busy)
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
ui.settle()
assert result['status'] == 'busy'
assert selected == ui.tasks[0].task_id
@pytest.mark.parametrize('operation', ['update', 'archive', 'copy', 'execute'])
@pytest.mark.parametrize('busy_kind', ['worker', 'run', 'loading'])
def test_delayed_preview_does_not_open_modal_after_manual_activity(ui, monkeypatch, qtbot, operation, busy_kind):
from threading import Event
from dx_productivity.trial_task_center.stop_control import StopControl
from dx_productivity.trial_task_center.ui.operation_state import ContextReadPhase
ctl, view = controller(ui, monkeypatch)
ui.settle()
entered, release = Event(), Event()
api = lifecycle()
function = 'preflight' if operation == 'execute' else 'preview'
original = getattr(api, function)
def slow(*args, **kwargs):
value = original(*args, **kwargs)
entered.set()
assert release.wait(5)
return value
monkeypatch.setattr(api, function, slow)
value = ({'request_id': '4' * 32, 'capability': 'execute',
'spec': {'operation': 'start', 'task_ids': [ui.tasks[0].task_id]}} if operation == 'execute' else
request(ui, operation, **({'patch': {'name': 'Uncommitted'}} if operation == 'update' else {})))
ctl.request(value)
busy = object()
previous_phase = ui.window._context_phase
try:
qtbot.waitUntil(entered.is_set, timeout=5000)
if busy_kind == 'worker':
ui.window._workers.add(busy)
elif busy_kind == 'run':
ui.window._batch_stop = StopControl()
else:
ui.window._context_phase = ContextReadPhase.LOADING
release.set()
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
qtbot.waitUntil(lambda: ctl.dialog is not None or ui.window._dsh_task_creation.dialog is not None
or bool(view.lifecycle_results), timeout=5000)
modal_opened = ctl.dialog is not None or ui.window._dsh_task_creation.dialog is not None
result = view.lifecycle_results[-1] if view.lifecycle_results else {}
finally:
release.set()
ui.window._workers.discard(busy)
ui.window._batch_stop = None
ui.window._context_phase = previous_phase
if ctl.dialog is not None:
ctl.dialog.reject()
if ui.window._dsh_task_creation.dialog is not None:
ui.window._dsh_task_creation.dialog.reject()
ui.settle()
assert not modal_opened
assert result['status'] == 'busy'
assert not ui.calls
def test_cancelled_read_failure_does_not_replace_cancellation(ui, monkeypatch, qtbot):
from threading import Event
ctl, view = controller(ui, monkeypatch)
entered, release = Event(), Event()
def slow(*args):
entered.set()
assert release.wait(5)
raise TaskCenterError('controlled_read_failure', 'Read failed after cancellation')
monkeypatch.setattr(lifecycle(), 'catalog', slow)
value = {'request_id': '5' * 32, 'capability': 'catalog', 'spec': {}}
ctl.request(value)
try:
qtbot.waitUntil(entered.is_set, timeout=5000)
ctl.cancel(value)
finally:
release.set()
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
ui.settle()
assert [result['status'] for result in view.lifecycle_results] == ['cancelled']