fix: complete scoped problem retries and retained worker recovery

This commit is contained in:
阿白叔 committed 2026-11-06 14:56:54 +08:00
1 parent 4db5f05531
commit 096072926b
20 files changed
+845 -21

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
import os
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
from threading import Event
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QMessageBox
from shiboken6 import isValid
from test_nonblocking_items import component_case
from dx_productivity.trial_task_center.task_queue import execute_task_queue
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
def test_problem_dialog_disables_uncertain_and_pending_rows(qtbot):
from dx_productivity.trial_task_center.ui.problem_items import ProblemItemsDialog
overview = dict(round_id='round', failed=1, held=1, uncertain=1, resolved=0, items=tuple(
dict(state=state, can_retry=False, operation_key=state, generation=1, refdes=ref, uid=uid,
project_path='board.prj', schematic_name='MAIN', sheet_number='1', code='', message='',
auto_retries_remaining=0) for state, ref, uid in
[('failed', 'R1', 'u1'), ('uncertain', 'R2', 'u2'), ('pending', 'R3', 'u3')]))
dialog = ProblemItemsDialog(overview, allow_retry=True)
qtbot.addWidget(dialog)
assert dialog.table.rowCount() == 3
assert all(not dialog.table.item(i, 0).flags() & Qt.ItemFlag.ItemIsUserCheckable for i in range(3))
assert not dialog.retry_button.isEnabled()
def test_ui_selected_retry_reaches_real_preparation_and_dispatch(component_case, qtbot, monkeypatch):
service, _, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
for ref in ('R1', 'R2'):
outcomes[(task_id, (ref,))] = 'attach_failed'
execute_task_queue(service, (task_id,), stop_event=Event(), defer_problem_pass=True)
window = TrialTaskCenterWindow(service, close_plan_confirmer=lambda: 'discard')
qtbot.addWidget(window)
def settled():
return not window._workers and not window._task_query.busy and not window._context_query.busy
try:
qtbot.waitUntil(settled)
window.open_task(task_id)
qtbot.waitUntil(settled)
window.run_panel.problems_button.click()
qtbot.waitUntil(lambda: window._problem_dialog is not None and settled())
dialog = window._problem_dialog
assert '失败 2' in dialog.summary.text()
assert dialog.table.item(1, 4).text() == 'R2'
dialog.table.item(1, 0).setCheckState(Qt.CheckState.Checked)
assert dialog.retry_button.isEnabled()
monkeypatch.setattr(QMessageBox, 'question', lambda *_a, **_k: QMessageBox.StandardButton.Yes)
dialog.retry_button.click()
qtbot.waitUntil(settled)
outcomes[(task_id, ('R2',))] = 'saved_ok'
execute_task_queue(service, (task_id,), stop_event=Event())
assert calls == [(task_id, ('R1',)), (task_id, ('R2',)), (task_id, ('R2',))]
finally:
if isValid(window):
qtbot.waitUntil(settled)
window.close()
qtbot.waitUntil(lambda: not window._context_query.busy)
+106
View File
@@ -0,0 +1,106 @@
"""Problem selection uses real frozen commands, SQLite and retry preparation."""
from threading import Event
import pytest
from test_nonblocking_items import component_case
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.task_queue import execute_task_queue
def fail_primary(case, refs=('R1', 'R2')):
service, store, tasks, calls, outcomes = case
task_id = tasks[0].task_id
for ref in refs:
outcomes[(task_id, (ref,))] = 'attach_failed'
execute_task_queue(service, (task_id,), stop_event=Event(), defer_problem_pass=True)
return service, task_id, service.execution_problem_overview(task_id)
def selection(overview, item):
return dict(operation_keys=(item['operation_key'],), expected_round_id=overview['round_id'],
expected_generations={item['operation_key']: item['generation']})
def test_problem_overview_exposes_uid_scope_and_shared_budget(component_case):
service, task_id, overview = fail_primary(component_case, ('R1',))
assert overview['failed'] == 1 and overview['held'] == overview['uncertain'] == 0
item, = overview['items']
assert (item['uid'], item['refdes'], item['schematic_name'], item['sheet_number']) == ('u1', 'R1', 'MAIN', '1')
assert item['can_retry'] and item['auto_retries_remaining'] == 1
service.reserve_problem_retry(task_id)
assert service.execution_problem_overview(task_id)['items'][0]['auto_retries_remaining'] == 0
def test_selected_retry_dispatches_only_selected_failed_uid(component_case):
service, task_id, overview = fail_primary(component_case)
item = overview['items'][1]
service.prepare_failed_quick_run(task_id, **selection(overview, item))
component_case[-1][(task_id, ('R2',))] = 'saved_ok'
execute_task_queue(service, (task_id,), stop_event=Event())
assert component_case[3] == [(task_id, ('R1',)), (task_id, ('R2',)), (task_id, ('R2',))]
after = service.execution_problem_overview(task_id)
assert after['failed'] == after['resolved'] == 1
assert service.reserve_problem_retry(task_id,
operation_keys=(overview['items'][0]['operation_key'],), source='dsh') == ()
@pytest.mark.parametrize('stale', ['round', 'generation'])
def test_stale_selection_cannot_reset_current_receipts(component_case, stale):
service, task_id, overview = fail_primary(component_case)
args = selection(overview, overview['items'][0])
if stale == 'round':
args['expected_round_id'] = 'old-round'
else:
args['expected_generations'] = {overview['items'][0]['operation_key']: -1}
with pytest.raises(TaskCenterError, match='problem_retry_scope'):
service.prepare_failed_quick_run(task_id, **args)
assert service.execution_problem_overview(task_id)['failed'] == 2
def test_uncertain_and_unattempted_items_are_visible_but_not_selectable(component_case):
service, store, tasks, _, outcomes = component_case
task_id = tasks[0].task_id
outcomes[(task_id, ('R1',))] = 'batch_saved_unverified'
execute_task_queue(service, (task_id,), stop_event=Event(), defer_problem_pass=True)
overview = service.execution_problem_overview(task_id)
assert overview['uncertain'] == overview['held'] == 1
assert {item['state'] for item in overview['items']} == {'uncertain', 'pending'}
assert not any(item['can_retry'] for item in overview['items'])
def test_targeted_retry_does_not_silently_include_pending_work(component_case):
service, store, tasks, _, outcomes = component_case
task_id = tasks[0].task_id
stop = Event()
outcomes[(task_id, ('R1',))] = 'batch_failed'
outcomes['after_call'] = lambda _: stop.set()
execute_task_queue(service, (task_id,), stop_event=stop, defer_problem_pass=True)
overview = service.execution_problem_overview(task_id)
assert overview['held'] == 1
item = next(item for item in overview['items'] if item['state'] == 'failed')
assert not item['can_retry']
with pytest.raises(TaskCenterError, match='problem_retry_scope'):
service.prepare_failed_quick_run(task_id, **selection(overview, item))
def test_old_crashed_problem_pass_cannot_replay_items_outside_new_selection(component_case, monkeypatch):
service, _, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
for ref in ('R1', 'R2'):
outcomes[(task_id, (ref,))] = 'attach_failed'
original = execute_task_queue(service, (task_id,), stop_event=Event(), defer_problem_pass=True)
child = service.for_project_task(task_id)
with monkeypatch.context() as patch:
def crash(*_a, **_k):
raise OSError('crash after original R1/R2 reservation')
patch.setattr(child, 'prepare_failed_quick_run', crash)
with pytest.raises(OSError):
execute_task_queue(service, (task_id,), stop_event=Event(), queue_id=original.queue_id)
overview = service.execution_problem_overview(task_id)
service.prepare_failed_quick_run(task_id, **selection(overview, overview['items'][1]))
outcomes[(task_id, ('R2',))] = 'saved_ok'
execute_task_queue(service, (task_id,), stop_event=Event())
assert calls == [(task_id, ('R1',)), (task_id, ('R2',)), (task_id, ('R2',))]
execute_task_queue(service, (task_id,), stop_event=Event(), queue_id=original.queue_id)
assert calls == [(task_id, ('R1',)), (task_id, ('R2',)), (task_id, ('R2',))]
@@ -0,0 +1,39 @@
from PySide6.QtWidgets import QMessageBox
from test_ui_remediation import window
def test_confirmed_force_runs_after_cleanup_worker_finishes(window, qtbot, monkeypatch):
qtbot.waitUntil(lambda: not window._workers and not window._resource_status.busy)
pending = ({'state': 'blocked', 'kind': 'retained_worker', 'force_available': True},)
monkeypatch.setattr(window.service, 'pending_batch_resources', lambda: pending)
monkeypatch.setattr(window.service, 'cleanup_batch_resources', lambda: pending)
calls = []
def force(*, confirmed):
calls.append(confirmed)
return ()
monkeypatch.setattr(window.service, 'force_pending_owned_resources', force)
monkeypatch.setattr(QMessageBox, 'question', lambda *_a, **_k: QMessageBox.StandardButton.Yes)
window._resource_status.records = pending
window._resource_status.known = True
window._update_gates()
window.run_panel.cleanup_resources_button.click()
qtbot.waitUntil(lambda: calls == [True] and not window._workers)
def test_lost_handles_show_restart_hint_without_unusable_force_prompt(window, qtbot, monkeypatch):
qtbot.waitUntil(lambda: not window._workers and not window._resource_status.busy)
hint = '请先保存工作,重启 Windows 后重新清理,结果仍须核验。'
pending = ({'state': 'blocked', 'kind': 'retained_worker', 'force_available': False,
'resolution_hint': hint},)
monkeypatch.setattr(window.service, 'pending_batch_resources', lambda: pending)
monkeypatch.setattr(window.service, 'cleanup_batch_resources', lambda: pending)
questions = []
monkeypatch.setattr(QMessageBox, 'question', lambda *_a, **_k: questions.append(1))
window._resource_status.records = pending
window._resource_status.known = True
window._update_gates()
window.run_panel.cleanup_resources_button.click()
qtbot.waitUntil(lambda: not window._workers)
assert questions == []
assert hint in window.run_panel.operator_band.text()
@@ -0,0 +1,70 @@
import json
from uuid import uuid4
import pytest
from dx_productivity.trial_task_center import batch_resources
def orphan(root, **extra):
token = uuid4().hex
path = root / 'quick-run' / ('retained-worker-' + token + '.json')
record = dict(version=1, state='blocked', token=token, job_id='job',
process={'pid': 123, 'creation_time': 'original'}, **extra)
batch_resources.write_record(path, record)
flag = path.parent / 'uncertain.flag'
flag.write_text('business result still requires verification')
return path, flag
def test_new_worker_reconciles_only_after_verified_kernel_boot_change(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import retained_worker_recovery as recovery
before, after = str(uuid4()), str(uuid4())
path, flag = orphan(tmp_path, retained_boot_id=before)
monkeypatch.setattr(recovery, 'boot_identity', lambda: before)
assert batch_resources.cleanup_pending_resources(tmp_path)
monkeypatch.setattr(recovery, 'boot_identity', lambda: after)
assert not batch_resources.cleanup_pending_resources(tmp_path)
record = json.loads(path.read_text(encoding='utf-8'))
assert record['release_proof']['method'] == 'kernel_boot_changed'
assert record['release_proof']['previous_boot_id'] == before
assert record['release_proof']['current_boot_id'] == after
assert flag.read_text() == 'business result still requires verification'
def test_legacy_worker_is_stamped_and_requires_subsequent_boot(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import retained_worker_recovery as recovery
before = str(uuid4())
path, _ = orphan(tmp_path)
monkeypatch.setattr(recovery, 'boot_identity', lambda: before)
pending = batch_resources.cleanup_pending_resources(tmp_path)
assert pending and 'Windows' in pending[0]['resolution_hint']
record = json.loads(path.read_text(encoding='utf-8'))
assert record['first_observed_boot_id'] == before
assert batch_resources.cleanup_pending_resources(tmp_path)
monkeypatch.setattr(recovery, 'boot_identity', lambda: str(uuid4()))
assert not batch_resources.cleanup_pending_resources(tmp_path)
@pytest.mark.parametrize('invalid', ['identity_missing', 'wrong_token', 'invalid_boot', 'boot_unavailable'])
def test_incomplete_evidence_never_unlocks_resource_gate(tmp_path, monkeypatch, invalid):
from dx_productivity.trial_task_center import retained_worker_recovery as recovery
path, _ = orphan(tmp_path, retained_boot_id=str(uuid4()))
record = json.loads(path.read_text(encoding='utf-8'))
if invalid == 'identity_missing':
record.pop('process')
elif invalid == 'wrong_token':
record['token'] = uuid4().hex
elif invalid == 'invalid_boot':
record['retained_boot_id'] = 'corrupt'
batch_resources.write_record(path, record)
monkeypatch.setattr(recovery, 'boot_identity', lambda: None if invalid == 'boot_unavailable' else str(uuid4()))
assert batch_resources.cleanup_pending_resources(tmp_path)
assert json.loads(path.read_text(encoding='utf-8'))['state'] == 'blocked'
def test_native_boot_observation_is_stable_and_nonzero():
from dx_productivity.trial_task_center.retained_worker_recovery import boot_identity
from uuid import UUID
first = boot_identity()
assert UUID(first).int and boot_identity() == first
+128
View File
@@ -0,0 +1,128 @@
import json
from pathlib import Path
import subprocess
import sys
from threading import Event
import pytest
from test_nonblocking_items import component_case
from test_batch_runtime import command_for, worker_runtime, Desktop
from dx_productivity.trial_task_center import worker_monitor
from dx_productivity.trial_task_center.task_queue import execute_task_queue
def confirmed_timeout():
error = worker_monitor.WorkerMonitorSafeTimeout('controlled open timeout', stage='open_project')
error.prewrite_cleanup_confirmed = True
return error
def test_real_monitor_certifies_open_timeout_only_after_worker_exit(tmp_path):
script = tmp_path / 'open_timeout.py'
script.write_text("import sys,time\nprint('DX_PROGRESS\\t'+sys.argv[-1]+'\\t'+sys.argv[-2]+'\\t1\\topen_project\\t0\\t1\\t1',flush=True)\ntime.sleep(30)\n")
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, 'job')
with pytest.raises(worker_monitor.WorkerMonitorSafeTimeout) as caught:
worker_monitor.run_monitored_process(command, 1)
assert caught.value.prewrite_cleanup_confirmed
assert not worker_monitor.RETAINED_WORKERS
def test_runtime_releases_safe_timeout_without_inline_replay(tmp_path, monkeypatch):
command, _ = command_for(tmp_path)
calls = []
def monitor(*_a, **_k):
calls.append(1)
raise confirmed_timeout()
runtime = worker_runtime(tmp_path, monkeypatch, monitor)
with runtime:
with pytest.raises(worker_monitor.WorkerMonitorSafeTimeout):
runtime.run_worker(command, 5)
assert runtime.desktop is runtime.cad is None
assert len(calls) == 1 and len(Desktop.created) == 1
assert json.loads(runtime.path.read_text())['state'] == 'released'
def test_safe_timeout_runs_independent_uid_then_one_problem_retry(component_case):
service, _, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
preparer = service.for_project_task(task_id)._quick_run_preparer
original = preparer._process_runner
attempts = []
def worker(command, timeout):
attempts.append(command[-1])
if len(attempts) == 1:
raise confirmed_timeout()
return original(command, timeout)
preparer._process_runner = worker
result = execute_task_queue(service, (task_id,), stop_event=Event())
assert not result.paused
assert len(attempts) == 3
assert calls == [(task_id, ('R2',)), (task_id, ('R1',))]
issue, = service.execution_problems(task_id)
assert issue['state'] == 'resolved' and issue['auto_retries'] == 1
assert issue['code'] == 'worker_timeout_before_write'
@pytest.mark.parametrize('unsafe', ['unconfirmed', 'changed_status', 'changed_source', 'changed_command', 'wrong_stage', 'cancelled'])
def test_timeout_without_complete_proof_stays_uncertain(component_case, unsafe):
service, _, tasks, calls, _ = component_case
task_id = tasks[0].task_id
preparer = service.for_project_task(task_id)._quick_run_preparer
stop = Event()
def worker(command, timeout):
error = confirmed_timeout()
if unsafe == 'unconfirmed':
error.prewrite_cleanup_confirmed = False
elif unsafe == 'wrong_stage':
error.stage = 'native_replace'
elif unsafe == 'changed_status':
with (Path(command[3]) / 'status.tsv').open('a', encoding='utf-8') as stream:
stream.write(f'{command[-1]}\tawaiting_native_replace\t\twrite possible\n')
elif unsafe == 'changed_source':
service.projects(task_id)[0].path.write_text('changed while worker was running')
elif unsafe == 'changed_command':
with (Path(command[3]) / 'current-command.tsv').open('a', encoding='utf-8') as stream:
stream.write('changed command scope')
elif unsafe == 'cancelled':
stop.set()
raise error
preparer._process_runner = worker
result = execute_task_queue(service, (task_id,), stop_event=stop)
assert result.paused
assert calls == []
assert service.reserve_problem_retry(task_id) == ()
assert preparer.has_interrupted(task_id)
assert not any(issue['classification'] == 'retryable' for issue in service.execution_problems(task_id))
def test_repeated_safe_timeout_spends_only_one_shared_retry(component_case):
service, _, tasks, calls, _ = component_case
task_id = tasks[0].task_id
preparer = service.for_project_task(task_id)._quick_run_preparer
attempts = []
def worker(command, timeout):
attempts.append(command[-1])
raise confirmed_timeout()
preparer._process_runner = worker
result = execute_task_queue(service, (task_id,), stop_event=Event())
assert not result.paused and len(attempts) == 4
assert [issue['auto_retries'] for issue in service.execution_problems(task_id)] == [1, 1]
assert service.reserve_problem_retry(task_id, source='dsh') == ()
execute_task_queue(service, (task_id,), stop_event=Event(), queue_id=result.queue_id)
assert len(attempts) == 4
def test_delivered_safe_timeout_allows_session_scope_to_prepare_next_worker(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import project_session
def monitor(*_a, **_k):
raise confirmed_timeout()
monkeypatch.setattr(project_session, 'run_monitored_process', monitor)
command = ('cscript', '', '', str(tmp_path), 'python', 'job')
project = tmp_path / 'board.prj'
with project_session.ProjectSessionScope(None, enabled=True) as scope:
with pytest.raises(worker_monitor.WorkerMonitorSafeTimeout):
scope.run_step(project, command, 1)
assert scope.worker._failure_delivered
scope.prepare(project)
assert scope.worker is None