fix: keep resource checks responsive and retain import diagnostics

This commit is contained in:
阿白叔 committed 2026-10-30 10:12:31 +08:00
1 parent 7bdaaeb2ec
commit 656f43e2ff
20 files changed
+455 -48

No files matched your search

+1 -1
View File
@@ -36,7 +36,7 @@ def ui(qtbot, tmp_path):
def settle():
qtbot.waitUntil(lambda:not window._workers and not window._task_query.busy
and not window._context_query.busy and not window._feedback_query.busy
and not window._log_presenter.query.busy,timeout=5000)
and not window._log_presenter.query.busy and not window._resource_status.busy,timeout=5000)
def open_task(task):
window.open_task(task.task_id)
qtbot.waitUntil(lambda:not window._context_query.busy and not window._loading,timeout=5000)
@@ -23,6 +23,20 @@ def test_current_task_executes_only_after_confirmation_and_no_match_is_completed
assert w.run_panel.new_round_button.isEnabled()
def test_batch_execute_button_tracks_remaining_tasks(ui):
w = ui.window
w._quick_run_confirmer = lambda *_args: True
w._prepare_quick_run()
ui.settle()
# A completed selection must still allow execution of its pending sibling.
assert w.task_list.queue_button.isEnabled()
w.task_list.queue_button.click()
ui.settle()
assert len(ui.calls) == 2
assert not w.task_list.queue_button.isEnabled(), 'a completed batch must not offer a no-op execution button'
assert w.run_panel.new_round_button.isEnabled()
@pytest.mark.parametrize('value',[False,True])
def test_changed_value_policy_stops_stale_confirmation_before_worker(ui,value):
w=ui.window;task=ui.tasks[0]
@@ -1,4 +1,4 @@
"""Readable logs and execution feedback on the current project-task interface."""
"""UI log and feedback coverage, collectable alongside the service feedback tests."""
import json
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.ui.messages import (
+103
View File
@@ -0,0 +1,103 @@
"""Resource snapshots stay conservative during slow, failed and repeated reads."""
import os
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
from threading import Event
from dx_productivity.trial_task_center.ui.resource_status import ResourceStatus
def test_resource_read_failure_blocks_until_a_successful_recheck(qtbot):
outcome = [()]
def read():
if isinstance(outcome[0], Exception):
raise outcome[0]
return outcome[0]
status = ResourceStatus(read)
try:
assert status.blocked and not status.known
status.refresh()
qtbot.waitUntil(lambda: not status.busy)
assert status.known and not status.blocked
outcome[0] = OSError('resource directory unavailable')
status.refresh()
qtbot.waitUntil(lambda: not status.busy)
assert status.blocked and isinstance(status.error, OSError)
outcome[0] = ()
status.refresh()
qtbot.waitUntil(lambda: not status.busy)
assert not status.blocked and status.error is None
finally:
status.close()
def test_operation_completion_coalesces_recheck_and_ignores_the_stale_clear_snapshot(qtbot):
started, release = Event(), Event()
calls, states = [], []
def read():
calls.append(1)
if len(calls) == 1:
started.set()
assert release.wait(5)
return ()
return ({'state': 'blocked'},)
status = ResourceStatus(read)
status.changed.connect(lambda: states.append(status.blocked))
try:
status.refresh()
qtbot.waitUntil(started.is_set)
for _ in range(10):
status.refresh()
release.set()
qtbot.waitUntil(lambda: not status.busy)
assert len(calls) == 2
assert status.records == ({'state': 'blocked'},)
assert states == [True], 'a pre-operation snapshot must not briefly unlock CAD actions'
finally:
release.set()
status.close()
def test_polling_does_not_restart_a_slow_resource_read(qtbot):
started, release = Event(), Event()
calls = []
def read():
calls.append(1)
started.set()
assert release.wait(5)
return ()
status = ResourceStatus(read)
try:
status.refresh()
qtbot.waitUntil(started.is_set)
for _ in range(10):
status._poll()
release.set()
qtbot.waitUntil(lambda: not status.busy)
assert status.known and not status.blocked
assert len(calls) == 1
finally:
release.set()
status.close()
def test_close_cancels_polling_and_drops_late_resource_results(qtbot):
started, release = Event(), Event()
changes = []
def read():
started.set()
assert release.wait(5)
return ()
status = ResourceStatus(read)
status.changed.connect(lambda: changes.append(True))
try:
status.refresh()
qtbot.waitUntil(started.is_set)
status.close()
assert not status._timer.isActive()
release.set()
qtbot.waitUntil(lambda: not status.busy)
assert status.blocked and changes == []
finally:
release.set()
status.close()
+41 -19
View File
@@ -9,6 +9,21 @@ import pytest
from dx_productivity.trial_task_center.worker_monitor import ProgressWatch, run_monitored_process
@pytest.fixture
def started_worker_watch(monkeypatch):
"""Test phase timeouts after real child startup, with a bounded startup grace."""
stages = set()
action = ProgressWatch.action
def after_start(watch, now):
if not watch.sequence and now - watch.started < 5:
return None
if watch.sequence:
stages.add(watch.stage)
return action(watch, now)
monkeypatch.setattr(ProgressWatch, 'action', after_start)
return stages
def test_unsafe_save_timeout_waits_for_completion_and_recovers_on_progress():
watch = ProgressWatch('token', 'job', 10, 0)
assert watch.accept(b'DX_PROGRESS\ttoken\tjob\t1\tsave_and_close\t0\t1\t0\n', 0)
@@ -20,7 +35,7 @@ def test_unsafe_save_timeout_waits_for_completion_and_recovers_on_progress():
assert watch.snapshot(now=201)['waiting_for_safe_completion'] is False
def test_real_slow_save_is_not_killed_by_inactivity(tmp_path):
def test_real_slow_save_is_not_killed_by_inactivity(tmp_path, started_worker_watch):
script = tmp_path / 'save.py'
script.write_text('''import sys,time,pathlib
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
@@ -32,10 +47,11 @@ time.sleep(1.5)
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
result = run_monitored_process(command, .3)
assert result.returncode == 0
assert 'save_and_close' in started_worker_watch
assert (tmp_path / 'saved.txt').read_text() == 'saved and independently verified'
def test_readonly_native_wait_keeps_bounded_cancellation_without_force_ui(tmp_path):
def test_readonly_native_wait_keeps_bounded_cancellation_without_force_ui(tmp_path, started_worker_watch):
script = tmp_path / 'read.py'
script.write_text('''import sys,time,pathlib
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
@@ -46,9 +62,10 @@ time.sleep(1.5)
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
with pytest.raises(subprocess.TimeoutExpired):
run_monitored_process(command, .3, cooperative_abort=True)
assert 'native_snapshot_read' in started_worker_watch
def test_explicit_force_stops_unsafe_worker_with_protection(tmp_path):
def test_explicit_force_stops_unsafe_worker_with_protection(tmp_path, monkeypatch):
script = tmp_path / 'save.py'
script.write_text('''import sys,time,pathlib
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
@@ -59,22 +76,20 @@ time.sleep(30)
(root/'unexpected_completed').touch()
''', encoding='utf-8')
force = Event()
def request():
for _ in range(200):
if (tmp_path / 'started').exists():
force.set()
return
Event().wait(.01)
requester = Thread(target=request)
requester.start()
accept = ProgressWatch.accept
def force_after_unsafe_progress(watch, line, now):
accepted = accept(watch, line, now)
if accepted and watch.stage == 'save_and_close' and not watch.safe_stop:
force.set()
return accepted
monkeypatch.setattr(ProgressWatch, 'accept', force_after_unsafe_progress)
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
try:
with pytest.raises(Exception, match='forced'):
run_monitored_process(command, .3, force_event=force)
assert (tmp_path / 'uncertain.flag').exists()
assert not (tmp_path / 'unexpected_completed').exists()
finally:
requester.join(3)
# This checks force at an accepted unsafe boundary, not startup speed.
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
with pytest.raises(WorkerMonitorError, match='forced'):
run_monitored_process(command, 5, force_event=force)
assert (tmp_path / 'uncertain.flag').exists()
assert not (tmp_path / 'unexpected_completed').exists()
def test_abnormal_cad_shutdown_is_not_hidden_by_physical_release(tmp_path):
@@ -228,7 +243,14 @@ def test_failed_protection_fsync_is_retried_before_force_is_allowed(tmp_path, mo
Event().wait(.01)
assert control.control_error
control.request_force()
thread.join(.25)
# Initial progress publication can still be doing filesystem I/O.
# Observe the rejected force request instead of assuming it reaches
# the retry within a fixed quarter-second scheduling window.
for _ in range(300):
if control.control_error:
break
Event().wait(.01)
assert control.control_error
assert thread.is_alive(), 'a file left by failed fsync must not authorize force'
assert len(attempts) >= 2
monkeypatch.setattr(module.os, 'fsync', original)
+44
View File
@@ -21,3 +21,47 @@ def test_pending_cleanup_cannot_expose_bom_preview():
error=resource_pending_error('inspect_bom_batch',report,OSError('held desktop'))
assert error.completed_result.preview is None
assert error.bom_report.preview is None
@pytest.mark.parametrize('business_succeeded', [True, False])
def test_abnormal_shutdown_retains_bom_rows_without_an_executable_preview(tmp_path, business_succeeded):
from dx_productivity.trial_task_center.batch_resources import write_record
from dx_productivity.trial_task_center.batch_supervisor import _finish_response
from dx_productivity.trial_task_center.bom_batch import BomBatchPreview
from dx_productivity.trial_task_center.bom_import_report import BomImportReport, BomRowResult
from dx_productivity.trial_task_center.bom_import_state import BomImportMachine
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.supervisor_protocol import encode, encode_error
report = BomImportReport((BomRowResult(4, 'board.prj', 'Board', 'failed', 'R99 missing'),), (),
BomBatchPreview('task', (), ()) if business_succeeded else None)
primary = TaskCenterError('inventory_cleanup', 'inventory reader failed')
primary.bom_report = report
journal = {'operation': 'inspect_bom_batch', 'batch_id': 'a' * 32, 'state': 'blocked'}
write_record(tmp_path / 'batch-resources' / journal['batch_id'] / 'session.json', {
'version': 1, 'session_id': journal['batch_id'], 'kind': 'bom_import', 'state': 'released',
'generation': 1, 'desktop': 'dx-' + 'b' * 32, 'processes': [], 'cad_pid': None,
'cad_guid': None, 'checkpoints': {}, 'retries': {}, 'timings': [],
'cad_shutdown': {'clean': False, 'orderly_shutdown': False}})
response = {'business_succeeded': business_succeeded, 'status': 'error',
'error': encode_error(TaskCenterError('batch_resources_pending', 'Quit failed'))}
if business_succeeded:
response['result'] = encode(report)
else:
response['operation_error'] = encode_error(primary)
machine = BomImportMachine()
attempt = machine.start()
with pytest.raises(TaskCenterError) as caught:
_finish_response(tmp_path, journal, response, configure_logging(tmp_path))
failure = caught.value
assert failure.code == 'application_shutdown_failed'
machine.finish(attempt, error=failure)
assert machine.state.report is not None, 'shutdown errors must preserve Excel row diagnostics'
assert machine.state.report.rows[0].excel_row == 4
assert machine.state.report.rows[0].reason == 'R99 missing'
assert machine.state.report.preview is None
if business_succeeded:
assert failure.completed_result.preview is None
else:
assert failure.primary_error.code == 'inventory_cleanup'
+27
View File
@@ -265,6 +265,33 @@ def test_dialog_discards_choices_when_project_binding_changes_before_delivery(qt
assert '工程' in dialog.cell_status.text()
@pytest.mark.parametrize('reader_fails', [False, True])
def test_destroyed_mapping_dialog_ignores_pending_cell_reader(qtbot, reader_fails):
from PySide6.QtCore import QCoreApplication, QEvent, QThreadPool
from shiboken6 import isValid
release, started = Event(), Event()
def load(_part):
started.set()
assert release.wait(5)
if reader_fails:
raise OSError('late library failure')
return ('CellA',)
dialog = _MappingDialog(None, 'OLD', 'NEW', cell_loader=load)
dialog.cell_load_button.click()
try:
qtbot.waitUntil(started.is_set)
dialog.deleteLater()
QCoreApplication.sendPostedEvents(dialog, QEvent.Type.DeferredDelete)
assert not isValid(dialog)
finally:
release.set()
with qtbot.captureExceptions() as exceptions:
assert QThreadPool.globalInstance().waitForDone(5000)
QCoreApplication.processEvents()
assert not exceptions, 'completed readers must not access destroyed dialog widgets'
def test_update_rejects_non_text_cell_instead_of_clearing(batch):
app, store, tasks = batch
rule = app.add_rule(tasks[0].task_id, 'OLD', 'NEW', target_cell='Existing')
+3 -2
View File
@@ -20,13 +20,14 @@ def test_pending_batch_resources_block_new_work_and_cleanup_does_not_replace(win
pending.clear()
return ()
monkeypatch.setattr(window.service, 'cleanup_batch_resources', cleanup)
window._update_gates()
window._resource_status.refresh()
qtbot.waitUntil(lambda: not window._resource_status.busy)
assert not window.run_panel.quick_run_button.isEnabled()
assert not window.plan_panel.collect_button.isEnabled()
assert not window.plan_panel.import_bom_button.isEnabled()
assert window.run_panel.cleanup_resources_button.isEnabled()
window.run_panel.cleanup_resources_button.click()
qtbot.waitUntil(lambda: not window._workers)
qtbot.waitUntil(lambda: not window._workers and not window._resource_status.busy)
assert calls == ['cleanup']
assert not window.run_panel.cleanup_resources_button.isEnabled()
assert '已释放' in window.run_panel.operator_band.text()
+29
View File
@@ -40,6 +40,35 @@ def loaded(qtbot, window, task):
and window._context.task.task_id == task.task_id, timeout=3000)
def test_resource_scan_never_runs_in_gate_refresh_and_keeps_event_loop_responsive(browser, qtbot, monkeypatch):
window, service, (task, _) = browser
window.open_task(task.task_id)
loaded(qtbot, window, task)
entered, release = Event(), Event()
gui_thread = get_ident()
def slow_resources():
assert get_ident() != gui_thread, 'resource files must not be read on the GUI thread'
entered.set()
assert release.wait(5)
return ({'state': 'blocked'},)
monkeypatch.setattr(service, 'pending_batch_resources', slow_resources)
try:
window._update_gates()
window._resource_status.refresh()
qtbot.waitUntil(entered.is_set)
tick = []
QTimer.singleShot(0, lambda: tick.append(True))
window.task_list.search.setText('board')
window._update_gates()
qtbot.waitUntil(lambda: bool(tick))
assert not release.is_set()
finally:
release.set()
qtbot.waitUntil(lambda: not window._resource_status.busy)
assert window.run_panel.cleanup_resources_button.isEnabled()
assert not window.run_panel.quick_run_button.isEnabled()
def test_slow_task_read_is_background_and_stale_result_cannot_change_selection(browser, qtbot, monkeypatch):
window, service, (a, b) = browser
real = service.task_context