fix: isolate component failures and recover owned CAD resources

This commit is contained in:
阿白叔 committed 2026-11-06 14:56:53 +08:00
1 parent a8da30aad2
commit 4db5f05531
87 files changed
+6688 -301

No files matched your search

+96
View File
@@ -0,0 +1,96 @@
from contextlib import contextmanager
from test_incidents import Service, analyze, make_runner
def test_rejected_admission_does_not_mutate_or_spend_budget(tmp_path):
@contextmanager
def scope(_action):
raise ValueError('execution_lane_changed')
yield
service = Service()
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.glob('dsh/retry-budget/*.json'))
def test_model_wait_changed_context_cannot_retry(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.glob('dsh/retry-budget/*.json'))
def test_retry_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 scoped_execute(*args, **kwargs):
assert active == ['retry_failed']
return execute(*args, **kwargs)
service.execute_quick_run_queue = scoped_execute
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_cancellation_during_model_wait_retains_evidence_without_publication(tmp_path):
from threading import Event
cancelled = Event()
def model(*_args):
cancelled.set()
return analyze()
service, published = Service(), []
runner = make_runner(tmp_path, service, model, lambda *_args: published.append(True))
result = runner.run('t', 'worker_error', 'failure', execution_authorized=True, cancel_event=cancelled)
assert not service.calls and not published
assert result['status'] == 'pending_issue'
assert (tmp_path / 'dsh/incidents' / result['incident_id'] / 'incident.json').is_file()
def test_shared_retry_reservation_denial_never_uses_legacy_budget(tmp_path):
service = Service()
service.reserve_problem_retry = lambda *args, **kwargs: ()
result = make_runner(tmp_path, service).run('t', 'worker_error', 'failure', execution_authorized=True)
assert not service.calls
assert result['attempts'] == 0
assert result['gates']['retry_budget_available'] is False
assert not list(tmp_path.glob('dsh/retry-budget/*.json'))
def test_shared_reservation_limits_preparation_to_reserved_operation_keys(tmp_path):
service, reserved, prepared_keys = Service(), ('uid-operation',), []
service.reserve_problem_retry = lambda *args, **kwargs: reserved
prepare = service.prepare_failed_quick_run
def prepare_reserved(task_id, *, operation_keys=None):
prepared_keys.append(operation_keys)
prepare(task_id)
service.prepare_failed_quick_run = prepare_reserved
result = make_runner(tmp_path, service).run('t', 'worker_error', 'failure', execution_authorized=True)
assert prepared_keys == [reserved]
assert result['status'] == 'resolved'
assert not list(tmp_path.glob('dsh/retry-budget/*.json'))
+60
View File
@@ -81,6 +81,66 @@ def test_failed_queue_receipt_does_not_claim_success(project_service):
assert journal.finish('a' * 32, result)['status'] == 'failed'
def test_inspect_accepts_frozen_workspace_checkpoint(project_service):
service, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('b' * 32, ids, hashes)
path = data / 'workspace-queues' / ('b' * 32 + '.json')
path.parent.mkdir(parents=True)
path.write_text(json.dumps({'version': 1, 'task_ids': ids, 'plan_hashes': hashes,
'phase': 'primary', 'entries': {key: {'state': 'pending', 'message': '',
'released': False, 'problems_done': False, 'checkpoint_id': str(index) * 32}
for index, key in enumerate(ids, 1)}}))
result = journal.inspect(service, 'b' * 32)
assert result['queue_available'] and result['resume_ready']
assert result['remaining_task_ids'] == ids
@pytest.mark.parametrize('isolated', [True, False])
def test_released_isolated_project_does_not_block_resume_of_other_projects(project_service, isolated):
from dx_productivity.dsh.run_journal import resume_preflight
service, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('d' * 32, ids, hashes)
evidence(service, ids[0], state='batch_saved_unverified' if isolated else 'batch_failed')
entries = {key: {'state': ('blocked' if isolated else 'failed') if index == 0 else 'pending', 'message': 'problem' if index == 0 else '',
'released': index == 0, 'problems_done': False, 'checkpoint_id': str(index + 1) * 32}
for index, key in enumerate(ids)}
entries[ids[0]]['supervisor_batch_id'] = 'e' * 32
path = data / 'workspace-queues' / ('d' * 32 + '.json')
path.parent.mkdir(parents=True)
path.write_text(json.dumps({'version': 1, 'task_ids': ids, 'plan_hashes': hashes,
'phase': 'primary' if isolated else 'problems', 'entries': entries}))
result = journal.inspect(service, 'd' * 32)
assert result['queue_available'] and result['resume_ready'], result['blockers']
assert result['remaining_task_ids'] == (ids[1:] if isolated else ids)
assert result['isolated_task_ids'] == ([ids[0]] if isolated else [])
assert result['tasks'][0]['interrupted'] == isolated
report = resume_preflight(service, result)
assert report['ready']
assert report['tasks'][0]['isolated'] == isolated
def test_unpaused_blocked_project_is_not_a_completed_run(project_service):
_, _, data, ids, hashes = project_service
journal = RunJournal(data)
journal.begin('b' * 32, ids, hashes)
result = TaskQueueResult('b' * 32, (TaskQueueEntry(ids[0], 'blocked'),), False)
assert journal.finish('b' * 32, result)['status'] == 'blocked'
def test_confirmed_run_reports_isolated_blocked_project_as_issue(project_service, monkeypatch):
from threading import Event
from dx_productivity.dsh.execution_runs import execute_confirmed_run
from dx_productivity.dsh.task_lifecycle import preflight
service, _, data, ids, _ = project_service
monkeypatch.setattr('dx_productivity.dsh.execution_runs.execute_task_queue', lambda *_args, **_kwargs:
TaskQueueResult('c' * 32, tuple(TaskQueueEntry(task_id, 'blocked' if index == 0 else 'completed')
for index, task_id in enumerate(ids)), False))
result = execute_confirmed_run(service, data, ids, preflight(service, ids), Event(), 'c' * 32)
assert result['status'] == 'blocked'
def test_native_confirmed_resume_marks_running_and_retains_last_receipt(project_service):
_, _, data, ids, hashes = project_service
journal = RunJournal(data)
@@ -15,7 +15,7 @@ def frame(sequence, stage='capture', done=1, total=18, safe=1, token='token', jo
def test_progress_allows_total_runtime_to_exceed_idle_limit():
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
for sequence, now in enumerate(range(100, 1001, 100), 1):
assert watch.accept(frame(sequence), now)
assert watch.accept(frame(sequence, done=sequence), now)
assert watch.action(now) is None
assert not watch.stop_requested
@@ -33,7 +33,7 @@ def test_progress_during_drain_prevents_emergency_kill():
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
assert watch.action(150) == 'request_stop'
for sequence, now in enumerate((200, 350, 490, 630), 1):
assert watch.accept(frame(sequence, safe=0), now)
assert watch.accept(frame(sequence, done=sequence, safe=0), now)
assert watch.action(now) is None
assert watch.stop_requested
@@ -57,7 +57,7 @@ def test_replayed_sequence_does_not_extend_deadline():
def native_frame(sequence=1, *, parent=1, current='job', safe=1):
return f'DX_NATIVE_PROGRESS\ttoken\tjob\t{parent}\t{current}\t{sequence}\t1\t57\t{safe}\r\n'.encode()
return f'DX_NATIVE_PROGRESS\ttoken\tjob\t{parent}\t{current}\t{sequence}\t{sequence}\t57\t{safe}\r\n'.encode()
def test_native_progress_extends_only_its_live_read_without_changing_stdout_sequence():
@@ -67,7 +67,7 @@ def test_native_progress_extends_only_its_live_read_without_changing_stdout_sequ
assert watch.accept_native(native_frame(n), now)
assert watch.action(now) is None
assert watch.sequence == 1
assert watch.snapshot(now=301)['done'] == 1
assert watch.snapshot(now=301)['done'] == 3
assert watch.accept(frame(2, stage='verify'), 302)
assert not watch.accept_native(native_frame(4), 450)
assert watch.action(452) == 'request_stop'
+240
View File
@@ -0,0 +1,240 @@
"""Model and supervision waits must not own execution admission or capacity."""
from threading import Event
import pytest
from PySide6.QtCore import QThreadPool, Signal
from dx_productivity.trial_task_center.ui.dsh_automation import DshAutomation
from dx_productivity.trial_task_center.ui.workers import ServiceWorker
from .test_dsh_native_menu import HarnessView
from .test_dsh_operations import setup_view
@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', 'refresh_ticket'])
def test_supervision_wait_leaves_execution_lane_and_thread_available(
ui, monkeypatch, qtbot, single_execution_thread, source):
setup_view(ui, monkeypatch)
operations = ui.window._dsh_operations
started, release, executed = Event(), Event(), Event()
def read(*_args, **_kwargs):
started.set()
assert release.wait(5)
return {'schedules': []}
monkeypatch.setattr(operations, '_read', read)
monkeypatch.setattr(operations.tickets, 'refresh', read)
if source == 'timer':
operations.tick()
else:
spec = {'operation': source}
if source == 'refresh_ticket':
spec['incident_id'] = 'a' * 24
operations.request({'request_id': 'a' * 32, 'spec': spec})
try:
qtbot.waitUntil(started.is_set)
assert operations.worker not in ui.window._workers
assert not operations.busy
ui.window._run_async(executed.set, lambda _: None)
qtbot.waitUntil(executed.is_set, timeout=1000)
assert not release.is_set()
finally:
release.set()
qtbot.waitUntil(lambda: operations.worker is None and not ui.window._workers)
class DiagnosisView(HarnessView):
diagnosis_event = Signal(object)
is_running = True
def __init__(self, parent):
super().__init__(parent)
self.requests = []
def request_diagnosis(self, request):
self.requests.append(request)
def shutdown(self):
self.is_running = False
self.stopped.emit()
@pytest.fixture
def diagnosis(ui, monkeypatch, qtbot):
from dx_productivity.trial_task_center.ui import dsh_automation as module
ui.settle()
monkeypatch.setattr(type(ui.window), '_create_dsh_view', lambda self: DiagnosisView(self))
published = []
monkeypatch.setattr(module, 'GitIssuePublisher', lambda _path: lambda *_args: published.append(True) or {'status': 'unavailable'})
automation = DshAutomation(ui.window)
ui.window._dsh_automation = automation
# Bypass only offscreen enqueue suppression; exercise the real incident runner.
automation.pending.append((ui.tasks[0].task_id, 'worker_error', 'controlled failure', True, 'old-run', None))
automation._drain()
qtbot.waitUntil(lambda: bool(ui.window._dsh_view.requests))
yield automation, ui.window._dsh_view, published
automation._native_unavailable = True
automation._runtime_stopped()
if hasattr(automation, 'close'):
automation.close()
qtbot.waitUntil(lambda: automation.worker is None)
def test_model_wait_does_not_own_controls_or_starve_execution(single_execution_thread, diagnosis, ui, qtbot):
automation, _view, _ = diagnosis
executed = Event()
try:
assert automation.worker not in ui.window._workers
assert ui.window._batch_stop is None
assert ui.window._active_quick_run_task_id is None
worker = ServiceWorker(executed.set)
single_execution_thread.start(worker)
qtbot.waitUntil(executed.is_set, timeout=1000)
finally:
automation.close()
qtbot.waitUntil(lambda: automation.worker is None)
def test_old_diagnosis_finishing_preserves_new_manual_run(diagnosis, ui, qtbot):
automation, _, _ = diagnosis
ui.window._begin_run(ui.tasks[1].task_id)
manual_stop, run_id = ui.window._batch_stop, ui.window._dsh_run_id
try:
automation._runtime_stopped()
qtbot.waitUntil(lambda: automation.worker is None)
assert ui.window._batch_stop is manual_stop
assert ui.window._dsh_run_id == run_id
assert ui.window._dsh_live_run['active']
assert not manual_stop.is_set()
finally:
ui.window._finish_run()
def test_close_wakes_model_wait_and_suppresses_ticket_submission(diagnosis, ui, qtbot):
automation, _, published = diagnosis
ui.window.close()
qtbot.waitUntil(lambda: automation.worker is None, timeout=2000)
assert not published
def test_cancelled_close_keeps_idle_automation_available(ui, monkeypatch):
ui.settle()
ui.window.archive_on_close_check.setChecked(False)
automation = DshAutomation(ui.window)
ui.window._dsh_automation = automation
monkeypatch.setattr(ui.window.plan_panel, 'has_unsaved_plans', lambda: True)
monkeypatch.setattr(ui.window, '_close_plan_confirmer', lambda: 'cancel')
ui.window.close()
assert not ui.window._closed
assert not automation._closing
def test_cancelled_close_after_model_cancellation_keeps_automation_available(diagnosis, ui, monkeypatch, qtbot):
automation, _, published = diagnosis
ui.window.archive_on_close_check.setChecked(False)
monkeypatch.setattr(ui.window.plan_panel, 'has_unsaved_plans', lambda: True)
monkeypatch.setattr(ui.window, '_close_plan_confirmer', lambda: 'cancel')
ui.window.close()
qtbot.waitUntil(lambda: automation.worker is None)
ui.settle()
assert not ui.window._closed and not automation._closing
assert not published
def test_mutation_admission_owns_lane_only_until_actual_action_finishes(ui, qtbot):
from dx_productivity.trial_task_center.stop_control import StopControl
ui.settle()
automation = DshAutomation(ui.window)
ui.window._dsh_automation = automation
automation._observed_run_id = ui.window._dsh_run_id
automation._action_task_id = ui.tasks[0].task_id
automation._action_stop = StopControl()
entered, release, reflected = Event(), Event(), Event()
def action():
with automation._action_scope('retry_failed'):
entered.set()
assert release.wait(5)
reflected.set()
assert automation.worker not in ui.window._workers
return {'status': 'pending_issue'}
automation._start_worker(ServiceWorker(action))
try:
qtbot.waitUntil(entered.is_set)
assert automation.worker in ui.window._workers
assert ui.window._batch_stop is automation._action_stop
assert ui.window._active_quick_run_task_id == ui.tasks[0].task_id
finally:
release.set()
qtbot.waitUntil(lambda: automation.worker is None)
assert reflected.is_set()
assert not ui.window._workers
assert ui.window._batch_stop is None
def test_new_manual_run_denies_old_admission_without_touching_controls(ui, qtbot):
from dx_productivity.trial_task_center.stop_control import StopControl
ui.settle()
automation = DshAutomation(ui.window)
ui.window._dsh_automation = automation
automation._observed_run_id = ui.window._dsh_run_id
automation._action_task_id = ui.tasks[0].task_id
automation._action_stop = StopControl()
ui.window._begin_run(ui.tasks[1].task_id)
manual_stop = ui.window._batch_stop
rejected, mutated = Event(), Event()
def action():
try:
with automation._action_scope('retry_failed'):
mutated.set()
except ValueError:
rejected.set()
return {'status': 'pending_issue'}
try:
automation._start_worker(ServiceWorker(action))
qtbot.waitUntil(lambda: automation.worker is None)
assert rejected.is_set() and not mutated.is_set()
assert ui.window._batch_stop is manual_stop
assert ui.window._active_quick_run_task_id == ui.tasks[1].task_id
assert not manual_stop.is_set()
finally:
ui.window._finish_run()
def test_reflection_waits_for_gui_to_confirm_lane_release(ui, qtbot):
from dx_productivity.trial_task_center.stop_control import StopControl
ui.settle()
automation = DshAutomation(ui.window)
ui.window._dsh_automation = automation
automation._observed_run_id = ui.window._dsh_run_id
automation._action_task_id = ui.tasks[0].task_id
automation._action_stop = StopControl()
releases, reflected = [], Event()
automation.action_requested.disconnect(automation._admit_action)
def gui(request):
if request['release']:
releases.append(request)
else:
automation._admit_action(request)
automation.action_requested.connect(gui)
def action():
with automation._action_scope('retry_failed'):
pass
reflected.set()
return {'status': 'pending_issue'}
automation._start_worker(ServiceWorker(action))
try:
qtbot.waitUntil(lambda: bool(releases))
qtbot.wait(5100)
assert not reflected.is_set(), 'Model work started before GUI acknowledged release'
finally:
automation._admit_action(releases[0])
qtbot.waitUntil(lambda: automation.worker is None)
+4 -3
View File
@@ -139,7 +139,7 @@ def test_last_execution_receipt_survives_later_catalog_reads(ui, monkeypatch, qt
assert view.operations['last_execution']['tasks'][0]['no_match_items'] == 2
def test_history_read_busy_state_is_published_and_rejection_is_visible(ui, monkeypatch, qtbot):
def test_history_read_busy_state_is_published_without_blocking_execution_confirmation(ui, monkeypatch, qtbot):
from threading import Event
view=setup_view(ui,monkeypatch); operations=ui.window._dsh_operations
started,release=Event(),Event()
@@ -152,8 +152,9 @@ def test_history_read_busy_state_is_published_and_rejection_is_visible(ui, monke
assert view.operations['busy'] is True
ui.window._dsh_lifecycle.request({'request_id':'b'*32,'capability':'execute',
'spec':{'operation':'start','task_ids':[ui.tasks[0].task_id]}})
assert view.lifecycle_results[-1]['status']=='busy'
assert view.operations['activity']['message']
qtbot.waitUntil(lambda: ui.window._dsh_lifecycle.dialog is not None)
ui.window._dsh_lifecycle.dialog.reject()
assert view.lifecycle_results[-1]['status']=='cancelled'
assert not ui.calls
finally:
release.set()
+38
View File
@@ -0,0 +1,38 @@
def test_owned_modal_can_be_handled_while_execution_worker_is_busy(ui, monkeypatch):
window = ui.window
ui.settle()
worker = object()
invoked = []
monkeypatch.setattr('dx_productivity.trial_task_center.ui.cad_dialog_operations.show_cad_dialogs',
lambda current: invoked.append(current))
window.service._supervisor_dialog_state = {'supervision': {'blocked': True}}
window._workers.add(worker)
try:
window._update_gates()
button = window.run_panel.cleanup_resources_button
assert not button.isHidden() and button.isEnabled()
button.click()
assert invoked == [window]
finally:
window._workers.discard(worker)
window.service._supervisor_dialog_state = None
window._update_gates()
def test_retained_resource_force_requires_explicit_operator_choice(ui, monkeypatch):
from PySide6.QtWidgets import QMessageBox
window = ui.window
ui.settle()
forced = []
monkeypatch.setattr(window.service, 'cleanup_batch_resources', lambda: ({'state': 'blocked'},))
monkeypatch.setattr(window.service, 'force_pending_owned_resources',
lambda *, confirmed=False: forced.append(confirmed) or ())
monkeypatch.setattr(window, '_run_async', lambda action, done, *_a, **_k: done(action()))
monkeypatch.setattr(QMessageBox, 'question', lambda *_a, **_k: QMessageBox.StandardButton.No)
window.run_panel.cleanup_resources_button.setEnabled(True)
window._cleanup_batch_resources()
assert forced == []
monkeypatch.setattr(QMessageBox, 'question', lambda *_a, **_k: QMessageBox.StandardButton.Yes)
window.run_panel.cleanup_resources_button.setEnabled(True)
window._cleanup_batch_resources()
assert forced == [True]
+9 -2
View File
@@ -35,9 +35,12 @@ def run_vbs(tmp_path, names, body, prelude=''):
LOG_STUB = '''
Dim QP_Root
Dim QP_Root, QP_Fso
Set QP_Fso=CreateObject("Scripting.FileSystemObject")
Sub QPLog(ByVal Root, ByVal Level, ByVal Message)
End Sub
Sub QPAppendAscii(ByVal Path, ByVal Text)
End Sub
'''
@@ -377,6 +380,8 @@ Sub QPVerifyRestoredPlans(ByRef Command, ByRef Records, ByRef Plans, ByRef State
End Sub
Sub QPWriteStatus(ByVal Root, ByVal Job, ByVal State, ByVal Code, ByVal Message)
End Sub
Sub QPWriteValueReadback(ByRef Command, ByRef Records, ByRef Plans, ByVal State)
End Sub
''')
assert output == expected
@@ -727,7 +732,9 @@ WScript.Echo CStr(InStr(Text, "G" & vbTab & "note" & vbTab) > 0)
def test_capture_protects_unselected_and_does_not_hide_target_pn_error(tmp_path, read_failure, exact_scope):
snapshot = str(tmp_path / 'captured.tsv')
output = run_vbs(tmp_path, UNTOUCHED_ROUTINES + ['QPCaptureAndSelect', 'QPSnapshotComponent',
'QPCommandTargets', 'QPBooleanText', 'QPLogField', 'QPTargetCell'], '''
'QPCommandTargets', 'QPBooleanText', 'QPLogField', 'QPTargetCell',
'QPRequireUniqueAttributeNames', 'QPAttributeObservations', 'QPRequireAlreadyTargetPolicy',
'QPValueHasNcMarker', 'QPAppendNcMarker'], '''
Dim Comp, Other, Attr, Pin, Command, Records
Set QP_App = New FakeApp
Set Comp = New FullComponent: Comp.UID = "u1": Comp.Refdes = "R1"
+13 -8
View File
@@ -149,7 +149,7 @@ def worker_runtime(tmp_path, monkeypatch, monitor):
return BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=Desktop, cad_factory=Cad)
def test_two_projects_reuse_cad_and_produce_distinct_close_checkpoints(tmp_path, monkeypatch):
def test_same_project_reuses_cad_then_next_project_starts_a_fresh_session(tmp_path, monkeypatch):
import subprocess
from dx_productivity.trial_task_center.batch_resources import project_checkpoint_released
one, _ = command_for(tmp_path)
@@ -159,10 +159,15 @@ def test_two_projects_reuse_cad_and_produce_distinct_close_checkpoints(tmp_path,
with runtime:
runtime.run_worker(one, 5)
assert project_checkpoint_released(Path(one[3]))
first = runtime.cad
runtime.run_worker(one, 5)
assert runtime.cad is first
runtime.run_worker(two, 5)
assert project_checkpoint_released(Path(two[3]))
assert len(Cad.created) == len(Desktop.created) == 1
assert Cad.created[0].closed and Desktop.created[0].released
assert first.closed and Desktop.created[0].released
assert len(Cad.created) == len(Desktop.created) == 2
assert all(cad.closed for cad in Cad.created)
assert all(desktop.released for desktop in Desktop.created)
def test_completed_project_does_not_hold_resolution_wait_for_next_project_failure(tmp_path, monkeypatch):
@@ -410,7 +415,7 @@ def test_native_rebuild_requires_strict_source_and_worker_proof(tmp_path):
for path in (project, database)}}
path = evidence / 'native-retry-proof.json'
path.write_text(json.dumps(proof))
with BatchCadRuntime(tmp_path / 'data', 'bom_import', desktop_factory=Desktop) as runtime:
with BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=Desktop) as runtime:
with runtime.native_scope(evidence) as scope:
pass
proof['binding'] = scope.identity
@@ -475,17 +480,17 @@ def test_mock_different_projects_each_get_one_retry_without_accumulating_budget(
calls[command[3]] += 1
if calls[command[3]] == 2:
return subprocess.CompletedProcess(command, 0, '', '')
raise WorkerMonitorError('unchanged prewrite failure')
return subprocess.CompletedProcess(command, 2, '', 'unchanged prewrite failure')
runtime = worker_runtime(tmp_path, monkeypatch, monitor)
with runtime:
runtime.run_worker(one, 5)
assert len(Desktop.created) == 2
runtime.run_worker(two, 5)
assert len(Desktop.created) == 3 # Each project gets its own single rebuild.
for command in (one, two):
assert len(Desktop.created) == 4 # Separate project startup plus its single rebuild.
for expected_sessions, command in enumerate((one, two), 5):
with pytest.raises(WorkerMonitorError, match='prewrite failure'):
runtime.run_worker(command, 5)
assert len(Desktop.created) == 3 # Success cannot replenish either budget.
assert len(Desktop.created) == expected_sessions # Switching projects is not another retry.
assert calls == {one[3]: 3, two[3]: 3}
assert set(runtime.record['retries']) == {
str(project_one.resolve()).casefold(), str(project_two.resolve()).casefold()}
+145
View File
@@ -0,0 +1,145 @@
from dataclasses import replace
from types import SimpleNamespace
import pytest
from test_bom_batch import batch, records_for
from dx_productivity.trial_task_center.bom_import_report import inspect_batch
from dx_productivity.trial_task_center.bom_plan import write_bom_template
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.inventory import HEADER, read_component_inventory
from dx_productivity.trial_task_center.store import TaskStore
def test_inventory_accepts_effective_metadata_and_legacy_unknown(tmp_path):
path = tmp_path / 'components.tsv'
project = tmp_path / 'board.prj'
row = f'{project}\tMAIN\t1\tu1\tR1\tNEW\t10nF'
path.write_text('\t'.join(HEADER) + '\n' + row + '\n')
legacy = read_component_inventory(path, project, (('MAIN', '1'),))[0]
assert legacy.actual_part_label is None and legacy.actual_cell is None
path.write_text('\t'.join((*HEADER, 'actual_part_label', 'actual_cell')) + '\n' + row + '\t10nF\tCELL\n')
actual = read_component_inventory(path, project, (('MAIN', '1'),))[0]
assert actual.actual_part_label == '10nF' and actual.actual_cell == 'CELL'
@pytest.mark.parametrize('mode,value,label,cell,expected', [
('custom', '10nF', 'LABEL', 'CELL', True), ('part_number', 'NEW-0', 'LABEL', 'CELL', True),
('preserve', 'current', 'LABEL', 'CELL', True), ('part_label', 'LABEL', 'LABEL', 'CELL', True),
('part_label', 'wrong', 'LABEL', 'CELL', False), ('part_label', 'LABEL', 'LABEL', 'WRONG', False),
('part_label', '', '', 'CELL', False),
])
def test_bom_already_target_verifies_effective_label_and_cell(batch, tmp_path, mode, value, label, cell, expected):
service, store, tasks, targets, calls = batch
target = replace(targets[tasks[0].task_id][0], old_part_number='NEW-0', old_value=value,
actual_part_label=label, actual_cell=cell)
targets[tasks[0].task_id] = (target,)
service.rules = lambda _task: (SimpleNamespace(old_part_number='OLD', new_part_number='NEW-0',
target_cell='CELL', enabled=True),)
record = dict(records_for(tasks, targets)[0], value_mode=mode, custom_value='10nF' if mode == 'custom' else '')
report = inspect_batch(service, tasks[0].task_id, write_bom_template(tmp_path / 'actual.xlsx', (record,)),
runtime=SimpleNamespace(bind_logs=lambda *_: None))
assert bool(report.preview) is expected
if expected:
preview = report.preview
service.save_bom_batch(preview, {p.task_id: p.rows for p in preview.projects})
assert not store.list_target_plan(tasks[0].task_id)[0].enabled
assert store.list_target_plan(tasks[0].task_id)[0].target.actual_cell == cell
else:
assert report.failed_rows == 1 and ('Value' in report.rows[0].reason or 'Cell' in report.rows[0].reason)
def test_bom_refreshes_unknown_effective_metadata_and_persists_without_changing_edits(batch, tmp_path):
service, store, tasks, targets, calls = batch
target = replace(targets[tasks[0].task_id][0], old_part_number='NEW-0', old_value='LABEL')
store.record_target_inventory(tasks[0].task_id, (target,))
targets[tasks[0].task_id] = (replace(target, actual_part_label='LABEL', actual_cell='CELL'),)
record = dict(records_for(tasks, targets)[0], value_mode='part_label')
path = write_bom_template(tmp_path / 'refresh.xlsx', (record,))
report = inspect_batch(service, tasks[0].task_id, path, runtime=SimpleNamespace(bind_logs=lambda *_: None))
assert report.preview and len(calls) == 1
assert store.list_target_plan(tasks[0].task_id)[0].target.actual_part_label is None
service.save_bom_batch(report.preview, {p.task_id: p.rows for p in report.preview.projects})
assert store.list_target_plan(tasks[0].task_id)[0].target.actual_part_label == 'LABEL'
database = store._database_path if hasattr(store, '_database_path') else tmp_path / 'tasks.db'
reopened = TaskStore(database)
try:
assert reopened.list_target_plan(tasks[0].task_id)[0].target.actual_part_label == 'LABEL'
finally:
reopened.close()
def test_known_metadata_change_cannot_replace_inventory(batch):
service, store, tasks, targets, _ = batch
target = replace(targets[tasks[0].task_id][0], actual_part_label='A', actual_cell='CELL')
store.record_target_inventory(tasks[0].task_id, (target,))
with pytest.raises(TaskCenterError, match='identity'):
store.record_target_inventory(tasks[0].task_id, (replace(target, actual_cell='FOREIGN'),))
def test_official_effective_report_supplies_label_and_cell_without_claiming_layer(tmp_path):
from test_native_ascii_inventory import report, effective_report
from dx_productivity.trial_task_center.native_inventory_protocol import read_ascii_discovery
flat = effective_report(tmp_path)
flat.write_text(flat.read_text().replace('\tProp Value 0R/NC\n',
'\tProp Value 0R/NC\n\tProp Part Label 0R/NC\n\tProp Cell Name CELL\n'))
target = read_ascii_discovery(tmp_path / 'board.prj', report(tmp_path), ('NEW',),
effective_report_path=flat).components[0]
assert (target.actual_part_label, target.actual_cell) == ('0R/NC', 'CELL')
def test_legacy_database_migration_keeps_effective_fields_unknown(batch, tmp_path):
service, store, tasks, targets, _ = batch
store.record_target_inventory(tasks[0].task_id, (targets[tasks[0].task_id][0],))
with store.transaction():
store._connection.execute('ALTER TABLE target_plan DROP COLUMN actual_part_label')
store._connection.execute('ALTER TABLE target_plan DROP COLUMN actual_cell')
reopened = TaskStore(tmp_path / 'tasks.db')
try:
target = reopened.list_target_plan(tasks[0].task_id)[0].target
assert target.uid == 'u1' and target.actual_part_label is None and target.actual_cell is None
finally:
reopened.close()
def test_frozen_inventory_rejects_changed_or_missing_effective_evidence(batch):
from dx_productivity.trial_task_center.inventory import validate_target_inventory
service, store, tasks, targets, _ = batch
target = replace(targets[tasks[0].task_id][0], actual_cell='CELL')
rule = SimpleNamespace(targets=(target,))
for cell in ('FOREIGN', None):
with pytest.raises(TaskCenterError):
validate_target_inventory(target.project_path, (rule,), (replace(target, actual_cell=cell),))
@pytest.mark.parametrize('current', ['matches', 'changed_label', 'changed_cell', 'changed_value',
'unknown_label', 'unknown_cell'])
def test_already_target_database_inventory_requires_current_source_evidence(batch, tmp_path, current):
service, store, tasks, targets, calls = batch
task_id = tasks[0].task_id
target = replace(targets[task_id][0], old_part_number='NEW-0', old_value='LABEL',
actual_part_label='LABEL', actual_cell='CELL')
store.record_target_inventory(task_id, (target,))
service.rules = lambda _task: (SimpleNamespace(old_part_number='OLD', new_part_number='NEW-0',
target_cell='CELL', enabled=True),)
# The persisted database still matches the requested target while the actual
# source content may have changed since that observation was collected.
with target.project_path.open('a') as stream:
stream.write(f'\nCURRENT_SOURCE_STATE {current}\n')
def collect(project, parts, **controls):
calls.append((task_id, parts))
source = project.read_text()
return (replace(target,
actual_part_label=None if 'unknown_label' in source else 'WRONG' if 'changed_label' in source else 'LABEL',
actual_cell=None if 'unknown_cell' in source else 'WRONG' if 'changed_cell' in source else 'CELL',
old_value='WRONG' if 'changed_value' in source else 'LABEL'),)
service.for_project_task(task_id)._quick_run_preparer.collect_inventory = collect
path = write_bom_template(tmp_path / 'stale-inventory.xlsx',
(dict(records_for(tasks, targets)[0], value_mode='part_label'),))
report = inspect_batch(service, task_id, path, runtime=SimpleNamespace(bind_logs=lambda *_: None))
assert len(calls) == 1
if current == 'matches':
assert report.preview and not report.preview.projects[0].rows[0].enabled
else:
assert report.preview is None and report.passed_preview is None and report.failed_rows == 1
assert store.list_target_plan(task_id)[0].target == target
+26
View File
@@ -0,0 +1,26 @@
"""Manual controls expose real prompt text and send only explicit selections."""
from types import SimpleNamespace
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QPlainTextEdit
def test_dialog_buttons_send_current_bound_manual_choice(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.ui import cad_dialog_operations
app = QApplication.instance() or QApplication([])
window = QWidget()
row = {'pid': 20, 'hwnd': 30, 'title': 'Save?', 'text': 'Save changes to board?', 'complete': True,
'buttons': [{'hwnd': 40, 'id': 6, 'text': 'Yes', 'enabled': True}]}
binding = {'batch_id': 'a' * 32, 'attempt_id': 'b' * 32, 'generation': 1, 'session_token': 'token'}
window.service = SimpleNamespace(_logging=SimpleNamespace(root=tmp_path), _supervisor_dialog_state={
'project': 'board.prj', 'binding': binding, 'supervision': {'blocked': True, 'current_dialogs': [row]}})
sent = []
monkeypatch.setattr(cad_dialog_operations, 'request_manual_dialog_action',
lambda *args: sent.append(args) or 'request')
dialog = cad_dialog_operations.CadDialogOperations(window)
assert sent == []
assert 'Save changes to board?' in dialog.findChild(QPlainTextEdit).toPlainText()
button = next(button for button in dialog.findChildren(QPushButton) if button.text() == 'Yes')
button.click()
assert sent == [(tmp_path, binding, row, 40)]
dialog.close()
window.close()
+254
View File
@@ -0,0 +1,254 @@
"""Freeze raw all-match rules into actual component identities before mutation."""
import csv
from dataclasses import replace
from pathlib import Path
import subprocess
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.execution_journal import read_command_rows
from dx_productivity.trial_task_center.models import ProjectRecord, ProjectStatus, RuleRecord
from dx_productivity.trial_task_center.quick_run import (
ProjectDiscovery, QuickRunPreparer, _path_key, _queue_matches_inputs, _read_commands,
)
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetRule
@pytest.fixture
def scope_case(tmp_path, monkeypatch):
project = tmp_path / 'projects' / 'Board' / 'board.prj'
project.parent.mkdir(parents=True)
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
source = tmp_path / 'runtime.vbs'
source.write_text("' controlled runtime")
selected = ProjectRecord('p', 't', 'Board', project, project.parent, True, True, ProjectStatus.PENDING, 0)
rules = (RuleRecord('r', 't', 0, 'OLD', 'NEW', True),)
components = tuple(ComponentTarget(project, 'MAIN', '1', f'uid-{i}', f'R{i}', 'OLD', '10K') for i in (1, 2))
calls, requested = [], []
def worker(command, timeout):
root = Path(command[3])
row = read_command_rows(root / 'current-command.tsv')[0]
assert row['target_selectors'], 'An empty inventory marker must never reach a mutating worker'
calls.append(row)
with (root / 'status.tsv').open('a', encoding='utf8') as stream:
stream.write(f'{command[-1]}\tawaiting_native_replace\t\tcaptured\n')
stream.write(f'{command[-1]}\tsaved_ok\tbatch_closed\tcontrolled save\n')
return subprocess.CompletedProcess(command, 0, '', '')
preparer = QuickRunPreparer(tmp_path / 'data', script_source=source,
process_runner=worker, cscript_resolver=lambda: Path('controlled-cscript'), run_token_factory=lambda: 'scope')
def discover(path, parts, *, collect_components=False, **kwargs):
requested.append(collect_components)
return ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): frozenset({'old'})}, components)
monkeypatch.setattr(preparer, 'discover_project', discover)
return preparer, selected, rules, components, requested, calls
def test_new_raw_rule_freezes_two_equal_value_targets_as_separate_uids(scope_case):
preparer, project, rules, _, requested, _ = scope_case
handoff = preparer.ensure_batch_handoff('t', (project,), rules)
rows = read_command_rows(handoff.command_path)
assert requested == [True]
assert len(rows) == 2
assert [row['target_selectors'] for row in rows] == ['uid-1\x1fR1\x1f10K', 'uid-2\x1fR2\x1f10K']
assert all(row['target_scope'] == 'targets' and row['execution_unit'] == 'component' for row in rows)
assert handoff.command_path.with_name('component-scope.json').is_file()
assert _queue_matches_inputs(handoff.command_path, _read_commands(handoff.command_path), (project,), rules)
@pytest.mark.parametrize('change', [{'custom_value_enabled': True, 'custom_value': 'changed'}, {'sync_nc': False}, {'target_cell': 'QFN'}])
def test_original_source_rule_option_changes_cannot_resume_frozen_scope(scope_case, change):
preparer, project, rules, *_ = scope_case
handoff = preparer.ensure_batch_handoff('t', (project,), rules)
changed = (replace(rules[0], **change),)
with pytest.raises(TaskCenterError, match='source|scope|来源|冻结'):
preparer.ensure_batch_handoff('t', (project,), changed)
def test_snapshot_and_resume_use_frozen_uids_without_rediscovering_changed_parts(scope_case, monkeypatch):
preparer, project, rules, *_ = scope_case
handoff = preparer.ensure_batch_handoff('t', (project,), rules)
rows = read_command_rows(handoff.command_path)
with handoff.status_path.open('a', encoding='utf8') as stream:
stream.write(f"{rows[0]['job_id']}\tsaved_ok\tbatch_closed\talready saved\n")
def forbidden(*args, **kwargs):
raise AssertionError('Completed targets now have new Part Numbers; do not rediscover them')
monkeypatch.setattr(preparer, 'discover_project', forbidden)
before = handoff.command_path.read_bytes()
assert preparer.ensure_batch_handoff('t', (project,), rules).command_path.read_bytes() == before
snapshot = preparer.read_snapshot('t', (project,), rules)
assert not snapshot.interrupted
assert snapshot.progress.total_items == 2 and snapshot.progress.completed_items == 1
assert snapshot.progress.next_old_part_number == 'OLD'
def test_mixed_no_match_is_preterminal_and_other_uid_commands_remain_dispatchable(scope_case):
preparer, project, rules, _, _, calls = scope_case
missing = RuleRecord('missing', 't', 0, 'ABSENT', 'DEST', True)
session = preparer.begin_batch_session('t', (project,), (missing, *rules))
rows = read_command_rows(session.handoff.command_path)
empty = rows[0]
assert empty['execution_unit'] == 'inventory_empty'
assert empty['target_scope'] == 'targets' and empty['target_selectors'] == ''
assert session.latest[empty['job_id']] == ('batch_skipped', 'inventory_empty')
assert session.commands[session.next_index][1] == rows[1]['job_id']
# Without a journal the normal batch gate conservatively blocks after any
# failure; dispatch the pending current command to verify its actual scope.
from dx_productivity.trial_task_center.quick_run import _write_current_command
_write_current_command(session, session.commands[session.next_index])
preparer._process_runner(('controlled', '', '', str(session.handoff.command_path.parent), rows[1]['job_id']), 10)
assert len(calls) == 1 and calls[0]['target_selectors'].startswith('uid-1\x1f')
progress = preparer.read_snapshot('t', (project,), (missing, *rules)).progress
assert progress.failed_items == 1 and progress.saved_items == 1
def test_legacy_page_all_match_queue_resumes_without_new_expansion(scope_case, monkeypatch):
preparer, project, rules, *_ = scope_case
handoff = preparer.prepare('t', (project,), rules, sheet_targets={_path_key(project.path): (('MAIN', '1'),)})
before = handoff.command_path.read_bytes()
monkeypatch.setattr(preparer, 'discover_project', lambda *args, **kwargs: pytest.fail('Legacy queue must keep its original shape'))
assert preparer.ensure_batch_handoff('t', (project,), rules).command_path.read_bytes() == before
assert 'target_scope' not in read_command_rows(handoff.command_path)[0]
assert not handoff.command_path.with_name('component-scope.json').exists()
def test_retry_preparation_inherits_frozen_scope_without_new_inventory(scope_case):
preparer, project, rules, *_ = scope_case
handoff = preparer.ensure_batch_handoff('t', (project,), rules)
staged = preparer.for_data_root(preparer.data_root / 'retry-stage')
retried = staged.prepare('t', (project,), rules,
sheet_targets={_path_key(project.path): (('MAIN', '1'),)}, component_scope_from=handoff.command_path.parent)
assert read_command_rows(retried.command_path) == read_command_rows(handoff.command_path)
assert retried.command_path.with_name('component-scope.json').read_bytes() == handoff.command_path.with_name('component-scope.json').read_bytes()
def test_incomplete_component_manifest_fails_closed_instead_of_all_match(scope_case, monkeypatch):
preparer, project, rules, *_ = scope_case
monkeypatch.setattr(preparer, 'discover_project', lambda *args, **kwargs:
ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): frozenset({'old'})}))
with pytest.raises(TaskCenterError) as error:
preparer.ensure_batch_handoff('t', (project,), rules)
assert error.value.code == 'component_scope'
assert not (preparer.data_root / 'quick-run/command.tsv').exists()
def test_missing_terminal_marker_never_dispatches_empty_target_selectors(scope_case):
preparer, project, rules, _, _, calls = scope_case
missing = RuleRecord('missing', 't', 0, 'ABSENT', 'DEST', True)
handoff = preparer.ensure_batch_handoff('t', (project,), (missing, *rules))
handoff.status_path.write_text('job_id\tstate\tcode\tmessage\n')
session = preparer.begin_batch_session('t', (project,), (missing, *rules))
with pytest.raises(TaskCenterError) as error:
preparer.execute_step('t', (project,), (missing, *rules), batch_mode=True, batch_session=session)
assert error.value.code == 'component_scope'
assert not calls
def test_empty_command_proof_requires_the_exact_full_frozen_queue(scope_case):
import json
from dx_productivity.trial_task_center.component_scope import validate_empty_command
preparer, project, rules, *_ = scope_case
missing = RuleRecord('missing', 't', 0, 'ABSENT', 'DEST', True)
handoff = preparer.ensure_batch_handoff('t', (project,), (missing, *rules))
empty = read_command_rows(handoff.command_path)[0]
assert validate_empty_command(handoff.command_path.parent, empty)
scope_path = handoff.command_path.with_name('component-scope.json')
scope = json.loads(scope_path.read_text())
scope['projects'][0]['components'].pop()
scope_path.write_text(json.dumps(scope))
assert not validate_empty_command(handoff.command_path.parent, empty)
def test_real_journal_keeps_empty_rule_manual_and_executes_other_exact_uids(scope_case, tmp_path, monkeypatch):
from threading import Event
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.task_queue import execute_task_queue
preparer, project, _, _, _, calls = scope_case
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(preparer.data_root), quick_run_preparer=preparer)
try:
task = service.create_project_tasks(project.path.parent)[0]
service.add_rule(task.task_id, 'ABSENT', 'DEST')
service.add_rule(task.task_id, 'OLD', 'NEW')
child = service.for_project_task(task.task_id)
monkeypatch.setattr(child._quick_run_preparer, 'discover_project', preparer.discover_project)
result = execute_task_queue(service, (task.task_id,), stop_event=Event())
assert not result.paused and result.entries[0].state == 'failed'
assert [row['target_selectors'] for row in calls] == ['uid-1\x1fR1\x1f10K', 'uid-2\x1fR2\x1f10K']
progress = service.quick_run_progress(task.task_id)
assert progress.queue_complete and progress.failed_items == 1 and progress.saved_items == 2
issues = service.execution_problems(task.task_id)
assert len(issues) == 1 and issues[0]['code'] == 'inventory_empty' and issues[0]['classification'] == 'manual'
assert service.reserve_problem_retry(task.task_id, source='dsh') == ()
execute_task_queue(service, (task.task_id,), stop_event=Event(), queue_id=result.queue_id)
assert len(calls) == 2
finally:
store.close()
def test_real_raw_retry_inherits_original_uids_and_does_not_repeat_success(scope_case, tmp_path, monkeypatch):
from threading import Event
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.task_queue import execute_task_queue
preparer, project, _, _, _, calls = scope_case
original_worker = preparer._process_runner
failed = False
def worker(command, timeout):
nonlocal failed
root = Path(command[3])
row = read_command_rows(root / 'current-command.tsv')[0]
if row['target_selectors'].startswith('uid-1\x1f') and not failed:
failed = True
calls.append(row)
with (root / 'status.tsv').open('a', encoding='utf8') as stream:
stream.write(f'{command[-1]}\tbatch_failed\tcad_attachment_failed\tcontrolled prewrite failure\n')
return subprocess.CompletedProcess(command, 0, '', '')
return original_worker(command, timeout)
preparer._process_runner = worker
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(preparer.data_root), quick_run_preparer=preparer)
try:
task = service.create_project_tasks(project.path.parent)[0]
service.add_rule(task.task_id, 'OLD', 'NEW')
child = service.for_project_task(task.task_id)
monkeypatch.setattr(child._quick_run_preparer, 'discover_project', preparer.discover_project)
result = execute_task_queue(service, (task.task_id,), stop_event=Event(), defer_problem_pass=True)
assert not result.paused and len(calls) == 2
original_scope = (child._quick_run_preparer.data_root / 'quick-run/component-scope.json').read_bytes()
monkeypatch.setattr(child._quick_run_preparer, 'discover_project', lambda *args, **kwargs: pytest.fail('Retry must inherit frozen inventory'))
reserved = service.reserve_problem_retry(task.task_id, source='dsh')
assert len(reserved) == 1
service.prepare_failed_quick_run(task.task_id, operation_keys=reserved)
assert (child._quick_run_preparer.data_root / 'quick-run/component-scope.json').read_bytes() == original_scope
retried = execute_task_queue(service, (task.task_id,), stop_event=Event())
assert not retried.paused and retried.entries[0].state == 'completed'
assert [row['target_selectors'].split('\x1f')[0] for row in calls] == ['uid-1', 'uid-2', 'uid-1']
finally:
store.close()
def test_retry_inherits_legacy_grouped_target_shape(scope_case):
preparer, project, _, components, *_ = scope_case
rules = (TargetRule('OLD', 'NEW', components),)
sheets = {_path_key(project.path): (('MAIN', '1'),)}
original = preparer.prepare('t', (project,), rules, sheet_targets=sheets, split_targets=False)
staged = preparer.for_data_root(preparer.data_root / 'retry-stage')
retried = staged.prepare('t', (project,), rules, sheet_targets=sheets, component_scope_from=original.command_path.parent)
assert read_command_rows(retried.command_path) == read_command_rows(original.command_path)
assert len(read_command_rows(retried.command_path)) == 1
def test_retry_missing_frozen_sidecar_cannot_become_an_all_match_queue(scope_case):
preparer, project, rules, *_ = scope_case
original = preparer.ensure_batch_handoff('t', (project,), rules)
original.command_path.with_name('component-scope.json').unlink()
staged = preparer.for_data_root(preparer.data_root / 'retry-stage')
with pytest.raises(TaskCenterError) as error:
staged.prepare('t', (project,), rules, sheet_targets={_path_key(project.path): (('MAIN', '1'),)},
component_scope_from=original.command_path.parent)
assert error.value.code == 'component_scope'
assert not (staged.data_root / 'quick-run/command.tsv').exists()
+93
View File
@@ -0,0 +1,93 @@
from threading import Event
import pytest
from test_nonblocking_items import component_case
from dx_productivity.trial_task_center.task_queue import execute_task_queue
def test_primary_all_projects_precedes_single_failed_uid_retry(component_case):
service, store, tasks, calls, outcomes = component_case
ids = tuple(task.task_id for task in tasks)
outcomes[(ids[0], ('R1',))] = ['attach_failed', 'saved_ok']
result = execute_task_queue(service, ids, stop_event=Event())
assert not result.paused
assert calls == [(ids[0], ('R1',)), (ids[0], ('R2',)),
(ids[1], ('R1',)), (ids[1], ('R2',)), (ids[0], ('R1',))]
assert [entry.state for entry in result.entries] == ['completed', 'completed']
assert service.execution_problems(ids[0])[0]['auto_retries'] == 1
assert service.execution_problems(ids[0])[0]['state'] == 'resolved'
def test_permanent_transient_failure_only_retries_once_across_queue_restart(component_case):
service, _, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
outcomes[(task_id, ('R1',))] = 'attach_failed'
result = execute_task_queue(service, (task_id,), stop_event=Event())
execute_task_queue(service, (task_id,), stop_event=Event(), queue_id=result.queue_id)
assert calls == [(task_id, ('R1',)), (task_id, ('R2',)), (task_id, ('R1',))]
assert service.reserve_problem_retry(task_id, source='dsh') == ()
def test_stop_on_last_primary_item_defers_problem_pass_until_resume(component_case):
service, _, tasks, calls, outcomes = component_case
ids = tuple(task.task_id for task in tasks)
stop = Event()
outcomes[(ids[0], ('R1',))] = ['attach_failed', 'saved_ok']
outcomes['after_call'] = lambda count: stop.set() if count == 4 else None
result = execute_task_queue(service, ids, stop_event=stop)
assert len(calls) == 4
assert service.execution_problems(ids[0])[0]['auto_retries'] == 0
execute_task_queue(service, ids, stop_event=Event(), queue_id=result.queue_id)
assert len(calls) == 5 and calls[-1] == (ids[0], ('R1',))
def test_dsh_and_problem_pass_cannot_each_reserve_one_replay(component_case):
service, _, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
outcomes[(task_id, ('R1',))] = 'attach_failed'
execute_task_queue(service, (task_id,), stop_event=Event(), defer_problem_pass=True)
keys = service.reserve_problem_retry(task_id, source='dsh')
assert len(keys) == 1
assert service.reserve_problem_retry(task_id, source='problems') == ()
assert service.reserve_problem_retry(task_id, operation_keys=keys, source='dsh') == ()
def test_crash_after_reservation_resumes_same_allowance_without_success_replay(component_case, monkeypatch):
service, store, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
outcomes[(task_id, ('R1',))] = ['attach_failed', 'saved_ok']
result = 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:
patch.setattr(child, 'prepare_failed_quick_run', lambda *_a, **_k: (_ for _ in ()).throw(OSError('controlled crash before preparation')))
with pytest.raises(OSError):
execute_task_queue(service, (task_id,), stop_event=Event(), queue_id=result.queue_id)
assert service.execution_problems(task_id)[0]['auto_retries'] == 1
execute_task_queue(service, (task_id,), stop_event=Event(), queue_id=result.queue_id)
assert calls == [(task_id, ('R1',)), (task_id, ('R2',)), (task_id, ('R1',))]
assert service.execution_problems(task_id)[0]['auto_retries'] == 1
def test_two_independent_connections_cannot_both_spend_same_uid_allowance(component_case, tmp_path):
from concurrent.futures import ThreadPoolExecutor
from threading import Barrier
from dx_productivity.trial_task_center.execution_problems import ExecutionProblems
from dx_productivity.trial_task_center.store import TaskStore
service, _, tasks, _, outcomes = component_case
task_id = tasks[0].task_id
outcomes[(task_id, ('R1',))] = 'attach_failed'
execute_task_queue(service, (task_id,), stop_event=Event(), defer_problem_pass=True)
barrier = Barrier(2)
def reserve(source):
connection = TaskStore(tmp_path / 'tasks.db')
try:
barrier.wait(timeout=10)
return ExecutionProblems(connection).reserve(task_id, source=source)
finally:
connection.close()
with ThreadPoolExecutor(max_workers=2) as pool:
futures = [pool.submit(reserve, source) for source in ('dsh', 'problems')]
reservations = [future.result(timeout=15) for future in futures]
assert sorted(map(len, reservations)) == [0, 1]
assert service.execution_problems(task_id)[0]['auto_retries'] == 1
+25
View File
@@ -7,6 +7,31 @@ import pytest
from dx_productivity.trial_task_center import diagnostics_bundle as bundle
def test_nonblocking_queue_and_owner_loss_evidence_are_exported_without_scope_inputs(tmp_path):
root = tmp_path / 'data'
queue = root / 'workspace-queues'
queue.mkdir(parents=True)
(queue / ('a' * 32 + '.json')).write_text(json.dumps({'phase': 'problems'}))
owner = root / 'batch-resources' / ('b' * 32)
owner.mkdir(parents=True)
(owner / 'owner-loss.json').write_text(json.dumps({'reason': 'parent_exited', 'token': 'private'}))
(owner / 'force-request.json').write_text(json.dumps({'confirmed': True}))
evidence = root / 'tasks' / 't' / 'quick-run'
evidence.mkdir(parents=True)
(evidence / 'project-read-release.json').write_text(json.dumps({'released': True}))
(evidence / ('retained-worker-' + 'c' * 32 + '.json')).write_text(json.dumps({'state': 'blocked'}))
(evidence / 'component-scope.json').write_text('private component inventory')
output = bundle.export_diagnostic_bundle(root, tmp_path / 'support.zip')
with zipfile.ZipFile(output) as archive:
assert 'workspace-queues/' + 'a' * 32 + '.json' in archive.namelist()
assert 'batch-resources/' + 'b' * 32 + '/owner-loss.json' in archive.namelist()
assert 'batch-resources/' + 'b' * 32 + '/force-request.json' in archive.namelist()
assert 'tasks/t/quick-run/retained-worker-' + 'c' * 32 + '.json' in archive.namelist()
assert 'tasks/t/quick-run/project-read-release.json' in archive.namelist()
assert 'tasks/t/quick-run/component-scope.json' not in archive.namelist()
assert b'private' not in archive.read('batch-resources/' + 'b' * 32 + '/owner-loss.json')
def test_bundle_allowlist_redacts_secrets_and_home_and_omits_inputs(tmp_path):
root = tmp_path / 'data'
session = root / 'batch-resources' / 'batch1'
+1 -1
View File
@@ -64,7 +64,7 @@ def test_bom_extension_stages_union_preserves_edits_and_saves(batch, tmp_path):
service, store, tasks, targets, calls = batch
before, path = extension_preview(batch, tmp_path)
preview = preview_batch(service, tasks[0].task_id, path)
assert all(set(parts) == {'OLD', 'EXTRA'} for _, parts in calls)
assert all(set(parts) == {'OLD', 'EXTRA', 'NEW'} for _, parts in calls)
assert len(calls) == 2
for project in preview.projects:
assert store.list_target_plan(project.task_id) == before[project.task_id]
+33
View File
@@ -0,0 +1,33 @@
"""A disposable native popup, without CAD or input-desktop switching."""
import os
import subprocess
import sys
import time
from uuid import uuid4
import pytest
@pytest.mark.skipif(os.name != 'nt', reason='Windows owned native dialog')
def test_explicit_no_button_closes_owned_unknown_popup_and_releases(tmp_path):
from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard
from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop
code = 'import ctypes; print(ctypes.windll.user32.MessageBoxW(None,"Save changes to sample?","Save Changes",4),flush=True)'
with PrivateDesktop('dx-' + uuid4().hex, enabled=True) as desktop:
process = desktop.start_process((sys.executable, '-c', code), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
guard = CadDialogGuard(desktop, process, tmp_path / 'cad-dialogs.json', 'manual-native-sample')
deadline = time.monotonic() + 10
while not guard.summary()['blocked'] and time.monotonic() < deadline:
guard.poll('manual_sample')
time.sleep(.03)
dialogs = guard.summary()['current_dialogs']
assert len(dialogs) == 1 and process.poll() is None
dialog = dialogs[0]
button = next(button for button in dialog['buttons'] if button['id'] == 7)
assert guard.records[-1]['action'] == 'manual_required'
guard.manual_action(dialog, button['hwnd'])
assert process.wait(timeout=5) == 0
assert process.stdout.read().decode().strip() == '7'
assert guard.records[-1]['action'] == 'user_selected_button'
assert desktop.cleanup_record['desktop_confirmation']['released']
assert not any(row.get('forced_termination') for row in desktop.cleanup_record.get('processes', ()))
+23 -8
View File
@@ -16,7 +16,8 @@ from test_accuracy_vbs_guards import run_vbs
def test_inventory_accepts_missing_uid_only_with_unique_refdes(tmp_path, uid, refdes, duplicate, expected, broken_value):
(tmp_path / 'component-inventory.request').touch()
output = run_vbs(tmp_path, ['QPDiscoverInventory', 'QPFindCurrentAttribute',
'QPEffectiveComponentAttribute'], f'''
'QPEffectiveComponentAttribute', 'QPRequireUniqueAttributeNames',
'QPAttributeObservations'], f'''
Dim Documents, Comp, Other, Failure
QP_Root="{tmp_path}"
BrokenValue={str(broken_value)}
@@ -47,6 +48,8 @@ Const VDM_COMP=128
Const VD_ALL=0
Sub QPLog(ByVal Root,ByVal Level,ByVal Message)
End Sub
Sub QPAppendAscii(ByVal FilePath,ByVal Text)
End Sub
Sub QPProgress(ByVal Stage,ByVal Done,ByVal Total)
End Sub
Function QPReadInventoryRequest()
@@ -112,18 +115,28 @@ Class FakeDocument
End Sub
End Class
Class FakeComponent
Public UID,Refdes
Public UID,Refdes,Attributes
Private Sub Class_Initialize()
Dim Attr,Name
Set Attributes=CreateObject("Scripting.Dictionary")
For Each Name In Array("Part Number","Part Label","Cell Name")
Set Attr=New FakeAttribute:Attr.Name=Name
If Name="Part Label" Then Attr.Value="LABEL"
If Name="Cell Name" Then Attr.Value="CELL"
Attributes.Add Attr,True
Next
End Sub
Function FindAttribute(ByVal Name)
Dim Attr
If Name="Value" And BrokenValue Then Err.Raise 1234,"FakeCOM","optional value unavailable"
If Name="Part Number" Then
Set FindAttribute=New FakeAttribute
Else
Set FindAttribute=Nothing
End If
Set FindAttribute=Nothing
For Each Attr In Attributes
If Attr.Name=Name Then Set FindAttribute=Attr
Next
End Function
End Class
Class FakeAttribute
Public Value,InstanceValue
Public Name,Value,InstanceValue
Private Sub Class_Initialize
Value="OLD":InstanceValue=""
End Sub
@@ -133,3 +146,5 @@ End Class
if expected == 'OK':
identity = uid or '@REFDES|' + refdes
assert output.splitlines()[-1].split('\t')[3:6] == [identity, refdes, 'OLD']
assert output.splitlines()[1].split('\t')[7:] == ['actual_part_label', 'actual_cell']
assert output.splitlines()[-1].split('\t')[7:] == ['LABEL', 'CELL']
+1 -1
View File
@@ -25,7 +25,7 @@ def run(tmp_path, body, *, prelude=''):
source = ADAPTER.read_text(encoding='ascii')
common = '\n'.join(guards.routine(n) for n in ('QPEncode', 'QPDecode', 'QPUntouchedIdentity', 'QPReadUtf8', 'QPWriteUtf8'))
script = tmp_path / 'native-reader-test.vbs'
script.write_text(prelude + '\n' + common + '\n' + source + '\n' + body, encoding='ascii')
script.write_text('Dim QP_Fso\nSet QP_Fso=CreateObject("Scripting.FileSystemObject")\n' + prelude + '\n' + common + '\n' + source + '\n' + body, encoding='ascii')
result = subprocess.run(['cscript.exe', '//nologo', str(script)], capture_output=True, text=True, timeout=15)
assert result.returncode == 0, result.stdout + result.stderr
return result.stdout.strip()
+80
View File
@@ -0,0 +1,80 @@
"""Full real scheduler/journal acceptance with a controlled native executor."""
import csv
import subprocess
from collections import Counter
from pathlib import Path
from threading import Event
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _decode_vbs_field
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
from dx_productivity.trial_task_center.task_queue import execute_task_queue
def test_hundred_uid_mixed_batch_finishes_93_safe_items_without_replay(tmp_path):
calls = []
outcomes = {}
def worker(command, timeout):
root = Path(command[3])
with (root / 'current-command.tsv').open(encoding='utf-8-sig') as stream:
row = {key: _decode_vbs_field(value) for key, value in
next(csv.DictReader(stream, delimiter='\t')).items()}
uid, refdes, _ = row['target_selectors'].split('\x1f')
assert '\x1e' not in row['target_selectors']
key = row['task_id'], uid
calls.append(key)
state = outcomes.get(key, 'saved_ok')
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
if state == 'saved_ok':
stream.write(f'{command[-1]}\tawaiting_native_replace\t\tcaptured\n')
stream.write(f'{command[-1]}\t{state}\tbatch_closed\tControlled {refdes}\n')
return subprocess.CompletedProcess(command, 0, '', '')
for name in ('A', 'B', 'C', 'D'):
project = tmp_path / 'projects' / name / 'board.prj'
project.parent.mkdir(parents=True)
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
data = tmp_path / 'data'
database = tmp_path / 'tasks.db'
store = TaskStore(database)
preparer = QuickRunPreparer(data, process_runner=worker,
cscript_resolver=lambda: Path('controlled-native'), sheet_discoverer=lambda _: (('MAIN', '1'),))
engine = TaskCenterService(store, configure_logging(data), quick_run_preparer=preparer)
tasks = engine.create_project_tasks(tmp_path / 'projects')
counts = (48, 50, 1, 1)
for index, (task, count) in enumerate(zip(tasks, counts)):
project = engine.projects(task.task_id)[0].path
targets = tuple(ComponentTarget(project, 'MAIN', '1', f'u{i}', f'R{i}', 'OLD', '10K')
for i in range(1, count + 1))
store.record_target_inventory(task.task_id, targets)
store.replace_target_plan(task.task_id, tuple(TargetPlanRow(target, True, 'NEW') for target in targets))
if index == 0:
outcomes.update({(task.task_id, f'u{i}'): 'batch_failed' for i in range(1, 6)})
elif index in (2, 3):
outcomes[(task.task_id, 'u1')] = 'batch_saved_unverified'
gui = TaskCenterService(store, configure_logging(data), supervised=True, quick_run_preparer=preparer)
# Only the process transport/native CAD are substituted. Each child executes
# the production queue, receipts, backups, issue pass and runtime cleanup.
def supervise(operation, arguments, *, stop_event):
assert operation == 'execute_task_queue'
return execute_task_queue(engine, stop_event=stop_event, **arguments)
gui._supervise = supervise
ids = tuple(task.task_id for task in tasks)
try:
result = execute_task_queue(gui, ids, stop_event=Event())
assert not result.paused
assert [entry.state for entry in result.entries] == ['failed', 'completed', 'blocked', 'blocked']
assert len(calls) == 100 and set(Counter(calls).values()) == {1}
records = dict(store._connection.execute('SELECT state,count(*) FROM execution_operations GROUP BY state'))
assert records == {'verified': 93, 'failed': 5, 'uncertain': 2}
execute_task_queue(gui, ids, stop_event=Event(), queue_id=result.queue_id)
assert len(calls) == 100
finally:
store.close()
reopened = TaskStore(database)
try:
assert reopened._connection.execute("SELECT count(*) FROM execution_operations WHERE state='verified'").fetchone()[0] == 93
assert reopened._connection.execute('SELECT sum(auto_retries) FROM execution_problems').fetchone()[0] == 0
finally:
reopened.close()
+184
View File
@@ -0,0 +1,184 @@
from dataclasses import replace
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center.bom_plan import write_bom_template
from dx_productivity.trial_task_center.errors import TaskCenterError
from test_bom_batch import batch, records_for
def test_target_library_preflight_reads_target_even_when_cell_unspecified(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import cell_catalog
project = tmp_path / 'board.prj'
project.write_text('KEY CentralLibrary "library/lib.lmc"\n')
reads = []
def read(library, part, evidence_root, **options):
reads.append((library, part, options))
return SimpleNamespace(cells=(cell_catalog.CellChoice('RES', 'CELL'),), source_fingerprint='proof')
monkeypatch.setattr(cell_catalog, 'read_library_cell_catalog', read)
rules = (SimpleNamespace(new_part_number='NEW', target_cell='', enabled=True),)
result = cell_catalog.preflight_target_libraries((project,), rules, tmp_path / 'proof')
assert reads[0][1] == 'NEW' and result
with pytest.raises(TaskCenterError, match='Cell'):
cell_catalog.preflight_target_libraries((project,),
(SimpleNamespace(new_part_number='NEW', target_cell='WRONG', enabled=True),), tmp_path / 'proof')
def test_execution_preflight_separates_safe_target_failure_from_unreleased_reader(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import cell_catalog
row = {'project_path': str(tmp_path / 'board.prj'), 'new_part': 'NEW'}
def missing(*args, **kwargs):
raise TaskCenterError('cell_catalog', 'target part missing')
monkeypatch.setattr(cell_catalog, 'preflight_target_libraries', missing)
with pytest.raises(TaskCenterError) as failure:
cell_catalog.preflight_command_target(row, tmp_path / 'evidence')
assert failure.value.code == 'target_cell_catalog'
def retained(*args, **kwargs):
raise TaskCenterError('batch_resources_pending', 'private desktop not released')
monkeypatch.setattr(cell_catalog, 'preflight_target_libraries', retained)
with pytest.raises(TaskCenterError) as failure:
cell_catalog.preflight_command_target(row, tmp_path / 'evidence')
assert failure.value.code == 'batch_resources_pending'
def test_partial_import_requires_explicit_selection_and_keeps_failed_project(batch, tmp_path):
from dx_productivity.trial_task_center.bom_import_report import inspect_batch, select_passed_projects
service, store, tasks, targets, calls = batch
records = list(records_for(tasks, targets))
records[1]['new_part_number'] = ''
path = write_bom_template(tmp_path / 'partial.xlsx', records)
runtime = SimpleNamespace(bind_logs=lambda *_: None)
atomic = inspect_batch(service, tasks[0].task_id, path, runtime=runtime)
assert atomic.preview is None and not calls
report = inspect_batch(service, tasks[0].task_id, path, runtime=runtime, allow_partial=True)
assert report.preview is None and report.failed_rows == 1 and report.passed_rows == 1
assert not store.list_target_plan(tasks[0].task_id)
with pytest.raises(TaskCenterError):
select_passed_projects(report, (tasks[1].task_id,))
preview = select_passed_projects(report, (tasks[0].task_id,))
service.save_bom_batch(preview, {p.task_id: p.rows for p in preview.projects})
assert store.list_target_plan(tasks[0].task_id)[0].enabled
assert not store.list_target_plan(tasks[1].task_id)
def test_partial_selection_rejects_changed_source_and_edited_rows(batch, tmp_path):
from dx_productivity.trial_task_center.bom_import_report import inspect_batch, select_passed_projects
service, store, tasks, targets, _ = batch
records = list(records_for(tasks, targets))
records[1]['refdes'] = 'R999'
path = write_bom_template(tmp_path / 'partial.xlsx', records)
report = inspect_batch(service, tasks[0].task_id, path,
runtime=SimpleNamespace(bind_logs=lambda *_: None), allow_partial=True)
preview = select_passed_projects(report, (tasks[0].task_id,))
project = preview.projects[0]
edited = (replace(project.rows[0], new_part_number='FOREIGN'), *project.rows[1:])
with pytest.raises(TaskCenterError, match='预览'):
service.save_bom_batch(preview, {project.task_id: edited})
path.write_bytes(path.read_bytes() + b'changed')
with pytest.raises(TaskCenterError, match='来源'):
service.save_bom_batch(preview, {project.task_id: project.rows})
assert all(not store.list_target_plan(task.task_id) for task in tasks)
def test_partial_ui_stages_only_user_selected_passed_projects(batch, tmp_path, qtbot):
from dx_productivity.trial_task_center.bom_import_report import inspect_batch
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service, store, tasks, targets, _ = batch
records = list(records_for(tasks, targets))
records[1]['refdes'] = 'R999'
report = inspect_batch(service, tasks[0].task_id, write_bom_template(tmp_path / 'ui.xlsx', records),
runtime=SimpleNamespace(bind_logs=lambda *_: None), allow_partial=True)
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.open_task(tasks[0].task_id)
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
panel = window.plan_panel
panel._received_bom_report(report)
assert not panel._bom_batches
panel.accept_passed_projects((tasks[0].task_id,))
assert panel._drafts[tasks[0].task_id][0].enabled
assert tasks[1].task_id not in panel._drafts
assert panel.last_bom_report.failed_rows == 1
assert not store.list_target_plan(tasks[0].task_id)
panel.discard_all()
qtbot.waitUntil(lambda: not window._workers and not window._context_query.busy)
window.close()
@pytest.mark.parametrize('mode,value,passed', [('custom', '10nF', True), ('custom', 'wrong', False),
('part_number', 'NEW-0', True), ('part_label', '10nF', False)])
def test_bom_recognizes_actual_target_pn_only_when_value_policy_proven(batch, tmp_path, mode, value, passed):
from dx_productivity.trial_task_center.bom_import_report import inspect_batch
service, store, tasks, targets, calls = batch
target = replace(targets[tasks[0].task_id][0], old_part_number='NEW-0', old_value=value)
targets[tasks[0].task_id] = (target,)
record = dict(records_for(tasks, targets)[0], value_mode=mode, custom_value='10nF' if mode == 'custom' else '')
report = inspect_batch(service, tasks[0].task_id, write_bom_template(tmp_path / 'target.xlsx', (record,)),
runtime=SimpleNamespace(bind_logs=lambda *_: None))
if passed:
assert report.preview and report.passed_rows == 1
assert not report.preview.projects[0].rows[0].enabled
assert '目标料号' in report.rows[0].reason
else:
assert report.failed_rows == 1 and report.preview is None
assert 'Value' in report.rows[0].reason
assert 'NEW-0' in calls[0][1]
def test_partial_migrated_source_binding_survives_normalized_copy_removal(batch, tmp_path):
from dx_productivity.trial_task_center.bom_import_report import select_passed_projects
service, store, tasks, targets, _ = batch
records = list(records_for(tasks, targets))
records[1]['refdes'] = 'R999'
sources = tuple(write_bom_template(tmp_path / f'source-{i}.xlsx', (record,)) for i, record in enumerate(records))
report = service.preview_bom_sources(tasks[0].task_id, sources,
runtime=SimpleNamespace(bind_logs=lambda *_: None), allow_partial=True)
assert not report.source_map_path.with_name('normalized-bom.xlsx').exists()
assert [row.source_row for row in report.rows] == [2, 2]
preview = select_passed_projects(report, (tasks[0].task_id,))
assert set(path for path, _ in preview.projects[0].source_hashes) == {
*(str(path) for path in sources), str(report.source_map_path)}
service.save_bom_batch(preview, {p.task_id: p.rows for p in preview.projects})
assert store.list_target_plan(tasks[0].task_id)[0].enabled
assert not store.list_target_plan(tasks[1].task_id)
def test_already_target_bom_does_not_treat_planned_cell_as_actual_evidence(batch, tmp_path):
from dx_productivity.trial_task_center.bom_import_report import inspect_batch
service, store, tasks, targets, _ = batch
target = replace(targets[tasks[0].task_id][0], old_part_number='NEW-0', old_value='10nF')
targets[tasks[0].task_id] = (target,)
store.record_target_inventory(tasks[0].task_id, (target,))
original = store.list_target_plan(tasks[0].task_id)[0]
store.replace_target_plan(tasks[0].task_id, (replace(original, new_part_number='NEW-0', target_cell='CELL'),))
record = dict(records_for(tasks, targets)[0], value_mode='custom', custom_value='10nF')
report = inspect_batch(service, tasks[0].task_id, write_bom_template(tmp_path / 'target-cell.xlsx', (record,)),
runtime=SimpleNamespace(bind_logs=lambda *_: None))
assert report.preview is None and report.failed_rows == 1
assert '实际 Cell' in report.rows[0].reason
@pytest.mark.parametrize('fault', ['formula', 'numeric_pn', 'value_mode', 'extra_formula'])
def test_explicit_partial_source_import_keeps_invalid_project_rows_in_report(batch, tmp_path, fault):
from openpyxl import load_workbook
from dx_productivity.trial_task_center.bom_import_report import select_passed_projects
service, store, tasks, targets, calls = batch
records = list(records_for(tasks, targets))
paths = tuple(write_bom_template(tmp_path / f'input-{i}.xlsx', (record,), include_value_mode=True)
for i, record in enumerate(records))
book = load_workbook(paths[1])
book.active[{'formula': 'D2', 'numeric_pn': 'D2', 'value_mode': 'L2', 'extra_formula': 'M2'}[fault]] = {
'formula': '=1+1', 'numeric_pn': 123, 'value_mode': 'invalid', 'extra_formula': '=1+1'}[fault]
book.save(paths[1])
book.close()
runtime = SimpleNamespace(bind_logs=lambda *_: None)
with pytest.raises(TaskCenterError):
service.preview_bom_sources(tasks[0].task_id, paths, runtime=runtime)
assert not calls
report = service.preview_bom_sources(tasks[0].task_id, paths, runtime=runtime, allow_partial=True)
assert report.preview is None and report.failed_rows == 1 and report.passed_rows == 1
assert report.rows[1].source_file == str(paths[1]) and report.rows[1].source_row == 2
preview = select_passed_projects(report, (tasks[0].task_id,))
service.save_bom_batch(preview, {p.task_id: p.rows for p in preview.projects})
assert not store.list_target_plan(tasks[1].task_id)
+145
View File
@@ -0,0 +1,145 @@
"""Actual command, journal and queue behavior at a controlled native boundary."""
import csv
import subprocess
from dataclasses import replace
from pathlib import Path
from threading import Event
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.execution_journal import read_command_rows
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _decode_vbs_field
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
from dx_productivity.trial_task_center.task_queue import execute_task_queue
@pytest.fixture
def component_case(tmp_path):
calls = []
outcomes = {}
def worker(command, timeout):
root = Path(command[3])
with (root / 'current-command.tsv').open(encoding='utf-8-sig') as stream:
row = {key: _decode_vbs_field(value) for key, value in
next(csv.DictReader(stream, delimiter='\t')).items()}
selectors = row['target_selectors'].split('\x1e')
refdes = tuple(selector.split('\x1f')[1] for selector in selectors)
calls.append((row['task_id'], refdes))
result = outcomes.get((row['task_id'], refdes), 'saved_ok')
if isinstance(result, list):
result = result.pop(0) if len(result) > 1 else result[0]
if result == 'attach_failed':
return subprocess.CompletedProcess(command, 2, '', 'controlled attachment failure')
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
if result == 'saved_ok':
stream.write(f'{command[-1]}\tawaiting_native_replace\t\tcaptured\n')
stream.write(f'{command[-1]}\t{result}\tbatch_closed\tControlled {result}\n')
if outcomes.get('after_call'):
outcomes['after_call'](len(calls))
return subprocess.CompletedProcess(command, 0, '', '')
for name in ('A', 'B'):
project = tmp_path / 'projects' / name / 'board.prj'
project.parent.mkdir(parents=True)
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'),
quick_run_preparer=QuickRunPreparer(tmp_path / 'data', process_runner=worker,
cscript_resolver=lambda: Path('controlled-cscript'),
sheet_discoverer=lambda _: (('MAIN', '1'),)))
tasks = service.create_project_tasks(tmp_path / 'projects')
for task in tasks:
project = service.projects(task.task_id)[0].path
targets = tuple(ComponentTarget(project, 'MAIN', '1', f'u{i}', f'R{i}', 'OLD', '10K')
for i in (1, 2))
store.record_target_inventory(task.task_id, targets)
store.replace_target_plan(task.task_id, tuple(TargetPlanRow(t, True, 'NEW') for t in targets))
yield service, store, tasks, calls, outcomes
store.close()
def test_same_rule_same_value_produces_distinct_single_uid_commands(component_case):
service, _, tasks, calls, _ = component_case
result = execute_task_queue(service, (tasks[0].task_id,), stop_event=Event())
assert not result.paused
assert [refs for _, refs in calls] == [('R1',), ('R2',)]
rows = read_command_rows(service.for_project_task(tasks[0].task_id)._quick_run_preparer.data_root /
'quick-run' / 'command.tsv')
assert [row['execution_unit'] for row in rows] == ['component', 'component']
def test_safe_component_failure_continues_independent_component_and_project(component_case):
service, store, tasks, calls, outcomes = component_case
ids = tuple(t.task_id for t in tasks)
outcomes[(ids[0], ('R1',))] = 'batch_failed'
result = execute_task_queue(service, ids, stop_event=Event())
assert not result.paused
assert [entry.state for entry in result.entries] == ['failed', 'completed']
assert calls == [(ids[0], ('R1',)), (ids[0], ('R2',)), (ids[1], ('R1',)), (ids[1], ('R2',))]
execute_task_queue(service, ids, stop_event=Event(), queue_id=result.queue_id)
assert len(calls) == 4
assert store._connection.execute("SELECT count(*) FROM execution_operations WHERE state='verified'").fetchone()[0] == 3
def test_uncertain_component_never_runs_same_project_remainder(component_case):
service, _, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
outcomes[(task_id, ('R1',))] = 'batch_saved_unverified'
result = execute_task_queue(service, (task_id,), stop_event=Event())
assert result.paused
assert calls == [(task_id, ('R1',))]
def test_problem_retry_budget_survives_rebinding_and_is_shared(component_case):
service, _, tasks, _, outcomes = component_case
task_id = tasks[0].task_id
outcomes[(task_id, ('R1',))] = 'batch_failed'
execute_task_queue(service, (task_id,), stop_event=Event())
# Unknown native failures are visible but cannot obtain automatic replay.
assert service.reserve_problem_retry(task_id, source='dsh') == ()
issues = service.execution_problems(task_id)
assert len(issues) == 1 and issues[0]['classification'] == 'manual'
def test_old_group_receipt_cannot_be_split_into_new_work(component_case):
service, _, tasks, _, _ = component_case
child = service.for_project_task(tasks[0].task_id)
task = tasks[0]
preparer = child._quick_run_preparer
handoff = preparer.prepare(task.task_id, child.projects(task.task_id), child._execution_rules(task.task_id),
sheet_targets={str(child.projects(task.task_id)[0].path).casefold(): (('MAIN', '1'),)},
split_targets=False)
rows = read_command_rows(handoff.command_path)
journal = preparer.journal
journal.bind(task.task_id, rows, {})
journal.finish(journal.claim(task.task_id, rows[0]), 'saved_ok', 'batch_closed', 'legacy group')
split = dict(rows[0], target_selectors='u1\x1fR1\x1f10K', execution_unit='component')
with pytest.raises(TaskCenterError):
journal.bind(task.task_id, (split,), {})
def test_unresolved_attempt_blocks_another_uid_before_any_failure(component_case):
service, _, tasks, _, _ = component_case
child = service.for_project_task(tasks[0].task_id)
handoff = child._quick_run_preparer.ensure_batch_handoff(tasks[0].task_id,
child.projects(tasks[0].task_id), child._execution_rules(tasks[0].task_id))
rows = read_command_rows(handoff.command_path)
journal = child._quick_run_preparer.journal
journal.bind(tasks[0].task_id, rows, {})
journal.claim(tasks[0].task_id, rows[0])
with pytest.raises(TaskCenterError, match='quick_run_uncertain'):
journal.claim(tasks[0].task_id, rows[1])
def test_overlapping_component_commands_rejected_before_first_dispatch(component_case):
service, _, tasks, _, _ = component_case
child = service.for_project_task(tasks[0].task_id)
handoff = child._quick_run_preparer.ensure_batch_handoff(tasks[0].task_id,
child.projects(tasks[0].task_id), child._execution_rules(tasks[0].task_id))
first = read_command_rows(handoff.command_path)[0]
overlap = dict(first, job_id='overlap', new_part='OTHER')
with pytest.raises(TaskCenterError, match='quick_run_uncertain'):
child._quick_run_preparer.journal.bind(tasks[0].task_id, (first, overlap), {})
+574
View File
@@ -0,0 +1,574 @@
"""Resource release proof, never elapsed time, admits later project work."""
import json
import os
from pathlib import Path
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import batch_resources, batch_runtime
from dx_productivity.trial_task_center.errors import TaskCenterError
def record_at(root, **values):
session = 'a' * 32
path = root / 'batch-resources' / session / 'session.json'
record = dict(version=1, session_id=session, kind='execution', generation=1,
desktop='dx-' + 'b' * 32, state='blocked', processes=[],
cad_pid=500, cad_guid='owned', checkpoints={}, retries={}, timings=[])
record.update(values)
batch_resources.write_record(path, record)
return path
def test_restart_reconciliation_checks_cad_identity_even_if_worker_list_empty(tmp_path, monkeypatch):
path = record_at(tmp_path, cad_process={'pid': 500, 'creation_time': 'original'})
seen = []
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: seen.append(item) or False)
from dx_productivity.trial_task_center import isolated_desktop
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: SimpleNamespace(confirm_desktop_released=lambda _: None))
assert batch_resources.cleanup_pending_resources(tmp_path)
assert seen == [{'pid': 500, 'creation_time': 'original'}]
assert json.loads(path.read_text())['state'] != 'released'
def test_legacy_cad_record_without_process_identity_cannot_be_released(tmp_path, monkeypatch):
record_at(tmp_path)
from dx_productivity.trial_task_center import isolated_desktop
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: SimpleNamespace(confirm_desktop_released=lambda _: None))
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: True)
assert batch_resources.cleanup_pending_resources(tmp_path)
def test_released_record_without_release_evidence_stays_pending(tmp_path):
record_at(tmp_path, state='released')
assert batch_resources.pending_resources(tmp_path)
def test_metadata_only_change_reuses_inventory_but_content_edit_does_not(tmp_path):
from dx_productivity.trial_task_center.discovery_cache import DiscoveryCache
from dx_productivity.trial_task_center.quick_run_protocol import ProjectDiscovery
project = tmp_path / 'project' / 'test.prj'
project.parent.mkdir()
project.write_text('project')
calls = []
def load():
calls.append(1)
return ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): frozenset({'old'})})
cache = DiscoveryCache(tmp_path / 'data')
cache.discover(project, ('old',), False, load)
info = project.stat()
os.utime(project, ns=(info.st_atime_ns, info.st_mtime_ns + 1000000000))
cache.discover(project, ('old',), False, load)
assert len(calls) == 1
project.write_text('changed')
cache.discover(project, ('old',), False, load)
assert len(calls) == 2
def test_runtime_uncertainty_wait_has_owned_exit_observer(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import stop_control, batch_attempt
runtime = batch_runtime.BatchCadRuntime(tmp_path, 'execution', stop_control.StopControl())
process = SimpleNamespace(poll=lambda: 0)
runtime.desktop = SimpleNamespace(processes=[process])
runtime.cad = SimpleNamespace(cad=process)
monkeypatch.setattr(batch_attempt, 'can_retry_attempt', lambda *args: False)
captured = {}
monkeypatch.setattr(stop_control, 'wait_for_resolution', lambda *args, **kw: captured.update(kw))
runtime._retain_uncertain(tmp_path, None, [('attempt', {})], RuntimeError('lost write'))
assert captured.get('resolved') is not None
assert captured['resolved']() is True
process.poll = lambda: None
assert captured['resolved']() is False
def test_supervisor_heartbeats_do_not_reset_business_stall_clock():
from dx_productivity.trial_task_center.batch_supervisor import BusinessProgressWatch
watch = BusinessProgressWatch(0, idle_timeout=10)
watch.observe('state', {'phase': 'ready', 'queue': None, 'batch': None}, 1)
for now in range(2, 12):
watch.observe('heartbeat', None, now)
watch.observe('state', {'phase': 'ready', 'queue': None, 'batch': None}, now)
assert watch.stalled(11)
watch.observe('progress', 'R2 verified', 12)
assert not watch.stalled(12)
def test_runtime_read_only_policy_comes_from_operation_provenance(tmp_path):
assert batch_runtime.BatchCadRuntime(tmp_path, 'bom_import').read_only
assert batch_runtime.BatchCadRuntime(tmp_path, 'collect_target_inventory').read_only
assert not batch_runtime.BatchCadRuntime(tmp_path, 'execute_quick_run').read_only
def test_safe_failure_reset_refuses_absent_checkpoint(tmp_path):
runtime = batch_runtime.BatchCadRuntime(tmp_path, 'execution')
runtime.desktop = SimpleNamespace(close=lambda: pytest.fail('no release without proof'))
runtime.cad = object()
with pytest.raises(TaskCenterError, match='checkpoint|检查点|证明'):
runtime.reset_project_after_safe_failure(tmp_path / 'board.prj', tmp_path / 'evidence')
def test_unknown_dialog_manual_action_revalidates_full_fingerprint(monkeypatch):
from dx_productivity.trial_task_center import cad_dialogs
row = {'pid': 20, 'hwnd': 30, 'class': '#32770', 'title': 'Save?', 'text': 'Save changes?',
'complete': True, 'buttons': [{'hwnd': 40, 'id': 6, 'text': 'Yes', 'enabled': True}]}
actions = []
import win32gui
monkeypatch.setattr(win32gui, 'PostMessage', lambda *args: actions.append(args))
monkeypatch.setattr(cad_dialogs, 'inspect_owned_dialogs', lambda *args: (dict(row, text='Other prompt'),))
with pytest.raises(OSError):
cad_dialogs.manually_act_on_owned_dialog(None, 'dx-owned', 20, row, 40)
assert actions == []
monkeypatch.setattr(cad_dialogs, 'inspect_owned_dialogs', lambda *args: (row,))
cad_dialogs.manually_act_on_owned_dialog(None, 'dx-owned', 20, row, 40)
assert actions == [(40, 0x00F5, 0, 0)]
def test_read_only_cad_cleanup_releases_owned_handles_without_write_uncertainty(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.isolated_cad import IsolatedCadSession
from dx_productivity.trial_task_center.stop_control import StopControl
process = SimpleNamespace(pid=50, poll=lambda: None)
def close():
process.poll = lambda: 1
desktop = SimpleNamespace(name='dx-owned', close=close, cleanup_record={
'desktop_handle_closed': True, 'desktop_confirmation': {'released': True}, 'errors': []})
session = IsolatedCadSession(tmp_path, desktop=desktop, read_only=True, stop_control=StopControl())
session.cad = process
session.binding = SimpleNamespace(environment=lambda: {})
desktop.start_process = lambda *a, **k: (_ for _ in ()).throw(RuntimeError('read still has a project open'))
session.__exit__(None, None, None)
assert process.poll() is not None
assert session.record['read_only_released'] is True
assert not (tmp_path / 'uncertain.flag').exists()
def test_read_only_worker_failure_releases_entire_generation_once(tmp_path, monkeypatch):
import subprocess
from test_batch_runtime import Cad, Desktop, command_for
from dx_productivity.trial_task_center import worker_monitor
from dx_productivity.trial_task_center.project_discovery import ReleasedProjectReadError
command, _ = command_for(tmp_path)
calls = []
def monitor(*args, **kwargs):
calls.append(kwargs)
raise subprocess.TimeoutExpired('read', 1)
monkeypatch.setattr(worker_monitor, 'run_monitored_process', monitor)
runtime = batch_runtime.BatchCadRuntime(tmp_path / 'data', 'bom_import', desktop_factory=Desktop,
cad_factory=lambda *args, read_only=False, **kwargs: Cad(*args, **kwargs))
with runtime:
with pytest.raises(ReleasedProjectReadError):
runtime.run_worker(command, 1)
assert runtime.desktop is runtime.cad is None
assert runtime.record['state'] == 'released'
assert len(calls) == 1 and calls[0]['cooperative_abort']
assert json.loads((Path(command[3]) / 'project-read-release.json').read_text())['resources_released']
def test_new_project_closes_previous_cad_before_starting_next(tmp_path, monkeypatch):
import subprocess
from test_batch_runtime import Cad, Desktop, command_for, worker_runtime
first, _ = command_for(tmp_path)
second, _ = command_for(tmp_path, 'two')
runtime = worker_runtime(tmp_path, monkeypatch, lambda cmd, *a, **kw: subprocess.CompletedProcess(cmd, 0, '', ''))
with runtime:
runtime.run_worker(first, 1)
previous = runtime.cad
runtime.run_worker(second, 1)
assert previous.closed
assert runtime.cad is not previous
assert runtime.generation == 2
def test_owner_loss_requires_bound_parent_identity_and_records_read_policy(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.read_recovery import check_owner_loss
owner = {'pid': 40, 'creation_time': 'parent-created'}
binding = {'batch_id': 'a' * 32, 'attempt_id': 'b' * 32, 'parent_process': owner}
seen = []
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: seen.append(item) or True)
assert check_owner_loss(tmp_path, binding, read_only=True)
proof = json.loads((tmp_path / 'owner-loss.json').read_text())
assert proof['parent_process'] == owner and proof['read_only'] is True
assert seen == [owner]
with pytest.raises(ValueError):
check_owner_loss(tmp_path, dict(binding, parent_process={'pid': 40}), read_only=True)
def test_unsafe_worker_exception_wait_resolves_when_owned_worker_exits(tmp_path, monkeypatch):
import io
import subprocess
from dx_productivity.trial_task_center import worker_monitor, stop_control
from dx_productivity.trial_task_center.stop_control import StopControl
process = SimpleNamespace(pid=123, stdout=io.BytesIO(), stderr=io.BytesIO(), returncode=None,
poll=lambda: None, close=lambda: None)
class Owned:
def __init__(self, *args): pass
def close(self): pass
def stop_workers(self, _): return []
monkeypatch.setattr(worker_monitor, '_OwnedWorkers', Owned)
real_atomic = worker_monitor._atomic_text
def fail_ready(path, text):
if path.suffix == '.ready':
# An actual launched worker can already be inside an unsafe stage.
raise OSError('ready evidence locked')
return real_atomic(path, text)
monkeypatch.setattr(worker_monitor, '_atomic_text', fail_ready)
original = worker_monitor.ProgressWatch
class UnsafeWatch(original):
def __init__(self, *args):
super().__init__(*args)
self.safe_stop = False
monkeypatch.setattr(worker_monitor, 'ProgressWatch', UnsafeWatch)
captured = {}
def resolve(control, root, error, **options):
captured.update(options)
process.poll = lambda: 1
process.returncode = 1
assert options['resolved']()
monkeypatch.setattr(stop_control, 'wait_for_resolution', resolve)
process.wait = lambda **options: 1
with pytest.raises(worker_monitor.WorkerMonitorError):
worker_monitor.run_monitored_process(('cscript', '', '', str(tmp_path), 'python', 'job'), 1,
process_factory=lambda *a, **kw: process, force_control=StopControl())
assert captured.get('resolved') is not None
def test_manual_dialog_transport_is_generation_bound_and_one_shot(tmp_path):
from dx_productivity.trial_task_center.batch_worker import consume_manual_dialog_actions
binding = {'batch_id': 'a' * 32, 'attempt_id': 'b' * 32, 'generation': 2, 'session_token': 'token'}
calls = []
runtime = SimpleNamespace(generation=2, cad=SimpleNamespace(token='token'),
manual_dialog_action=lambda dialog, button: calls.append((dialog, button)))
request = dict(binding, version=1, request_id='c' * 32, dialog={'pid': 1}, button_hwnd=2)
batch_resources.write_record(tmp_path / ('manual-dialog-' + request['request_id'] + '.json'), request)
consume_manual_dialog_actions(tmp_path, runtime, binding['batch_id'], binding['attempt_id'])
consume_manual_dialog_actions(tmp_path, runtime, binding['batch_id'], binding['attempt_id'])
assert calls == [({'pid': 1}, 2)]
stale = dict(request, generation=1, request_id='d' * 32)
batch_resources.write_record(tmp_path / ('manual-dialog-' + stale['request_id'] + '.json'), stale)
consume_manual_dialog_actions(tmp_path, runtime, binding['batch_id'], binding['attempt_id'])
assert calls == [({'pid': 1}, 2)]
def test_cache_hashes_after_verified_reader_release(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import discovery_cache
from dx_productivity.trial_task_center.quick_run_protocol import ProjectDiscovery
project = tmp_path / 'board.prj'
project.write_text('project')
calls, locked = [], [False]
real_fingerprint = discovery_cache.project_fingerprint
def fingerprint(*args, **kwargs):
assert not locked[0], 'fingerprint attempted before read generation release'
return real_fingerprint(*args, **kwargs)
def load():
calls.append('load')
locked[0] = True
return ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): frozenset({'old'})})
def release():
calls.append('release')
locked[0] = False
monkeypatch.setattr(discovery_cache, 'project_fingerprint', fingerprint)
cache = discovery_cache.DiscoveryCache(tmp_path / 'data')
cache.discover(project, ('old',), False, load, release_idle=release)
cache.discover(project, ('old',), False, load, release_idle=release)
assert calls == ['load', 'release']
def test_cleanup_error_never_drops_live_write_cad_or_closes_its_desktop(tmp_path):
from test_batch_runtime import Desktop
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
runtime = batch_runtime.BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop)
runtime._ensure_desktop()
process = SimpleNamespace(poll=lambda: None)
def refuse(*args):
raise WorkerMonitorError('CAD still saving; evidence write failed')
cad = SimpleNamespace(cad=process, __exit__=refuse, record={})
runtime.cad = cad
with pytest.raises(TaskCenterError):
runtime.close()
assert runtime.cad is cad
assert not runtime.desktop.released
# Leave no retained live registry state in the test process.
batch_resources.LIVE_RESOURCES.pop(str(runtime.path), None)
def test_owned_exit_observer_waits_for_job_descendants(tmp_path):
runtime = batch_runtime.BatchCadRuntime(tmp_path, 'execution')
process = SimpleNamespace(poll=lambda: 0, tree_exited=lambda: False)
runtime.desktop = SimpleNamespace(processes=[process])
assert not runtime.owned_processes_exited()
process.tree_exited = lambda: True
assert runtime.owned_processes_exited()
def test_startup_dialog_owner_is_published_before_guid_binding(tmp_path):
from test_batch_runtime import Desktop
runtime = batch_runtime.BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop)
with runtime:
with runtime.native_scope(tmp_path / 'startup') as lease:
process = lease.start_process(('viewdraw.exe',))
lease.register_cad_process(process, 'session-token')
record = json.loads(runtime.path.read_text())
assert record['cad_pid'] == process.pid
assert record['cad_process']['pid'] == process.pid
assert record['cad_token'] == 'session-token'
assert record['cad_guid'] is None
def test_native_read_failure_releases_without_repeating_project(tmp_path):
import hashlib
from test_batch_runtime import Desktop
from dx_productivity.trial_task_center.project_discovery import ReleasedProjectReadError
project, database = tmp_path / 'board.prj', tmp_path / 'database.dat'
project.write_text('project')
database.write_text('database')
evidence = tmp_path / 'native'
runtime = batch_runtime.BatchCadRuntime(tmp_path / 'data', 'bom_import', desktop_factory=Desktop)
with runtime:
with runtime.native_scope(evidence) as scope:
pass
batch_resources.write_record(evidence / 'native-retry-proof.json', {'version': 1,
'native_read_only': True, 'workers_closed': True, 'binding': scope.identity,
'project_path': str(project), 'evidence_root': str(evidence),
'source_hashes': {str(item): hashlib.sha256(item.read_bytes()).hexdigest() for item in (project, database)}})
with pytest.raises(ReleasedProjectReadError):
runtime.recover_native_failure(project, evidence, 'read timed out')
assert runtime.generation == 1 and runtime.record['state'] == 'released'
assert runtime.desktop is runtime.cad is None
assert runtime.record['retries'] == {}
@pytest.mark.parametrize('native', [False, True])
def test_repeated_live_frames_cannot_hide_business_stall(native):
from dx_productivity.trial_task_center.worker_monitor import ProgressWatch
watch = ProgressWatch('token', 'job', 10, 0)
stage = 'native_snapshot_read' if native else 'native_replace'
assert watch.accept(f'DX_PROGRESS\ttoken\tjob\t1\t{stage}\t0\t10\t0\n'.encode(), 1)
for sequence in range(2, 12):
if native:
assert watch.accept_native(f'DX_NATIVE_PROGRESS\ttoken\tjob\t1\tjob\t{sequence}\t0\t10\t0\n'.encode(), sequence)
else:
assert watch.accept(f'DX_PROGRESS\ttoken\tjob\t{sequence}\t{stage}\t0\t10\t0\n'.encode(), sequence)
assert watch.action(11) == 'request_stop'
assert watch.action(21) == 'await_safe_completion'
assert watch.action(100) is None # Elapsed time cannot authorize killing a possible write.
def test_finished_supervisor_label_does_not_hide_a_live_original_process(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.batch_supervisor import pending_supervisors
batch_id = 'a' * 32
batch_resources.write_record(tmp_path / 'batch-resources' / batch_id / 'supervisor.json', {
'version': 1, 'batch_id': batch_id, 'attempt_id': 'b' * 32,
'operation': 'execute_task_queue', 'state': 'finished', 'task_ids': ['A'],
'process': {'pid': 20, 'creation_time': 'worker'},
'parent_process': {'pid': 10, 'creation_time': 'parent'}, 'request_sha256': 'f' * 64})
monkeypatch.setattr(batch_resources, '_process_gone', lambda identity: False)
assert pending_supervisors(tmp_path)
def test_crashed_write_supervisor_does_not_kill_its_still_running_descendant(tmp_path, monkeypatch):
import sys
from dx_productivity.trial_task_center import batch_supervisor
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.stop_control import StopControl
monkeypatch.setattr(batch_supervisor, '_command', lambda request: (sys.executable, '-c',
'import subprocess,sys; subprocess.Popen([sys.executable,"-c","import time;time.sleep(6)"], '
'stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)'))
store = TaskStore(tmp_path / 'tasks.db')
try:
service = TaskCenterService(store, configure_logging(tmp_path))
task = store.create_task('harmless owned process probe')
with pytest.raises(TaskCenterError) as caught:
batch_supervisor.run_supervised(service, 'execute_quick_run', {'task_id': task.task_id},
stop_event=StopControl())
record = json.loads(next((tmp_path / 'batch-resources').glob('*/process.json')).read_text())
assert record['cleanup']['forced_termination'] is False
assert caught.value.resources_released
assert list(tmp_path.rglob('uncertain.flag'))
finally:
store.close()
def test_no_control_write_session_retains_harmless_owned_process(tmp_path, monkeypatch):
import sys
from uuid import uuid4
from dx_productivity.trial_task_center import isolated_cad
from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop
desktop = PrivateDesktop('dx-' + uuid4().hex, enabled=True)
desktop.__enter__()
process = desktop.start_process((sys.executable, '-c', 'import time;time.sleep(60)'))
session = isolated_cad.IsolatedCadSession(tmp_path, desktop=desktop)
session.cad = process
session.binding = SimpleNamespace(environment=lambda: {})
session._record(cad_pid=process.pid, cad_process=batch_resources.process_identity(process))
monkeypatch.setattr(isolated_cad, '_helper_command', lambda *args: (sys.executable, '-c', 'raise SystemExit(1)'))
try:
with pytest.raises(isolated_cad.WorkerMonitorError):
session.__exit__(None, None, None)
assert process.poll() is None
assert isolated_cad.RETAINED_CAD_SESSIONS[str(session.root)] is session
assert (tmp_path / 'uncertain.flag').exists()
assert batch_resources.pending_resources(tmp_path)[0]['kind'] == 'retained_cad'
assert batch_resources.force_pending_owned_resources(tmp_path, confirmed=True) == ()
assert process.poll() is not None
assert str(session.root) not in isolated_cad.RETAINED_CAD_SESSIONS
finally:
process.terminate(reason='explicit harmless test cleanup')
desktop.close()
getattr(isolated_cad, 'RETAINED_CAD_SESSIONS', {}).pop(str(session.root), None)
def test_force_pending_owned_job_requires_confirmation_identity_and_durable_protection(tmp_path, monkeypatch):
import os
import sys
from uuid import uuid4
import win32api
from dx_productivity.trial_task_center import batch_supervisor
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api
from dx_productivity.trial_task_center.batch_resources import force_pending_owned_resources
api = _Win32Api()
process = api.create_process((sys.executable, '-c', 'import time;time.sleep(60)'), None, None, None)
batch_id = uuid4().hex
path = tmp_path / 'batch-resources' / batch_id / 'supervisor.json'
parent = SimpleNamespace(pid=os.getpid(), handle=win32api.GetCurrentProcess())
journal = {'version': 1, 'batch_id': batch_id, 'attempt_id': uuid4().hex,
'operation': 'execute_quick_run', 'state': 'blocked', 'task_ids': ['A'],
'process': batch_resources.process_identity(process), 'parent_process': batch_resources.process_identity(parent),
'request_sha256': 'f' * 64}
batch_resources.write_record(path, journal)
batch_supervisor._LIVE_SUPERVISORS[path] = (api, process)
try:
with pytest.raises(TaskCenterError):
force_pending_owned_resources(tmp_path)
assert process.poll() is None and not list(tmp_path.rglob('uncertain.flag'))
corrupt = dict(journal, process=dict(journal['process'], creation_time='reused PID'))
batch_resources.write_record(path, corrupt)
with pytest.raises(TaskCenterError):
force_pending_owned_resources(tmp_path, confirmed=True)
assert process.poll() is None
batch_resources.write_record(path, journal)
mark = batch_supervisor._mark_interrupted
monkeypatch.setattr(batch_supervisor, '_mark_interrupted', lambda *args: (_ for _ in ()).throw(PermissionError('protection denied')))
with pytest.raises(PermissionError):
force_pending_owned_resources(tmp_path, confirmed=True)
assert process.poll() is None
monkeypatch.setattr(batch_supervisor, '_mark_interrupted', mark)
assert force_pending_owned_resources(tmp_path, confirmed=True) == ()
assert process.poll() is not None
assert list(tmp_path.rglob('uncertain.flag'))
finally:
process.terminate(reason='explicit harmless test cleanup')
process.close()
api.close_pending()
batch_supervisor._LIVE_SUPERVISORS.pop(path, None)
def test_safe_failure_reset_returns_bound_prewrite_source_and_release_proof(tmp_path, monkeypatch):
import hashlib
import subprocess
from test_batch_runtime import command_for, worker_runtime
command, project = command_for(tmp_path)
runtime = worker_runtime(tmp_path, monkeypatch, lambda cmd, *a, **kw: subprocess.CompletedProcess(cmd, 0, '', ''))
with runtime:
runtime.run_worker(command, 1)
proof = runtime.reset_project_after_safe_failure(project, Path(command[3]))
assert proof['no_mutation'] is True and proof['source_unchanged'] is True
assert proof['resources_released'] is True and proof['project_closed'] is True
assert proof['job_id'] == 'job' and proof['attempt_id'] == runtime.record['active_attempt']
assert proof['session_id'] == runtime.session_id and proof['generation'] == 1
assert proof['project_path'] == str(project.resolve())
assert proof['attempt_record_sha256'] == hashlib.sha256(Path(proof['attempt_record_path']).read_bytes()).hexdigest()
assert json.loads(Path(proof['proof_path']).read_text()) == proof
def test_discovery_identity_preserves_actual_metadata_unknown_vs_empty():
from dx_productivity.trial_task_center.discovery_cache import _discovery_identity
row = SimpleNamespace(key='uid', refdes='R1', old_part_number='old', old_value='value',
actual_part_label=None, actual_cell=None)
discovery = SimpleNamespace(sheets=(('MAIN', '1'),), matched_old_parts={('MAIN', '1'): frozenset({'old'})}, components=(row,))
before = _discovery_identity(discovery)
row.actual_part_label = ''
assert _discovery_identity(discovery) != before
def test_force_pending_runtime_uses_live_handles_and_preserves_write_uncertainty(tmp_path):
import sys
from dx_productivity.trial_task_center.isolated_cad import IsolatedCadSession
runtime = batch_runtime.BatchCadRuntime(tmp_path, 'execution')
scope = runtime.native_scope(tmp_path / 'quick-run')
scope.__enter__()
process = scope.start_process((sys.executable, '-c', 'import time;time.sleep(60)'))
session = IsolatedCadSession(tmp_path / 'cad', desktop=scope)
session.cad = process
session._record(cad_pid=process.pid, cad_process=batch_resources.process_identity(process))
runtime.cad = session
runtime._active_evidence = tmp_path / 'quick-run'
runtime._save(cad_pid=process.pid, cad_guid='owned', cad_process=batch_resources.process_identity(process))
try:
assert batch_resources.force_pending_owned_resources(tmp_path, confirmed=True) == ()
assert process.poll() is not None
assert runtime.record['state'] == 'released'
assert (tmp_path / 'quick-run' / 'uncertain.flag').exists()
assert runtime.record['force_confirmed'] is True
finally:
process.terminate(reason='explicit harmless test cleanup')
runtime.cad = None
runtime.close(reason='manual_retry')
def test_raw_retained_session_reconciles_after_all_owned_processes_exit(tmp_path, monkeypatch):
import sys
import time
from uuid import uuid4
from dx_productivity.trial_task_center import isolated_cad
from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop
desktop = PrivateDesktop('dx-' + uuid4().hex, enabled=True)
desktop.__enter__()
process = desktop.start_process((sys.executable, '-c', 'import time;time.sleep(1.5)'))
session = isolated_cad.IsolatedCadSession(tmp_path, desktop=desktop)
session.cad = process
session.binding = SimpleNamespace(environment=lambda: {})
session._record(cad_pid=process.pid, cad_process=batch_resources.process_identity(process))
monkeypatch.setattr(isolated_cad, '_helper_command', lambda *args: (sys.executable, '-c', 'raise SystemExit(1)'))
try:
with pytest.raises(isolated_cad.WorkerMonitorError):
session.__exit__(None, None, None)
assert process.wait(timeout=4) == 0
deadline = time.monotonic() + 2
while not all(item.tree_exited() for item in session._retained_processes):
assert time.monotonic() < deadline
time.sleep(.01)
assert batch_resources.cleanup_pending_resources(tmp_path) == ()
assert (tmp_path / 'uncertain.flag').exists()
assert process.cleanup_record['forced_termination'] is False
finally:
process.terminate(reason='explicit harmless test cleanup')
desktop.close()
isolated_cad.RETAINED_CAD_SESSIONS.pop(str(session.root), None)
def test_no_control_retains_cad_job_when_root_exited_but_descendants_remain(tmp_path):
from dx_productivity.trial_task_center import isolated_cad
process = SimpleNamespace(pid=30, poll=lambda: 0, tree_exited=lambda: False)
desktop = SimpleNamespace(name='dx-owned', _processes=[process],
close=lambda: pytest.fail('root exit cannot authorize descendant termination'))
session = isolated_cad.IsolatedCadSession(tmp_path, desktop=desktop)
session.cad = process
try:
with pytest.raises(isolated_cad.WorkerMonitorError):
session.__exit__(None, None, None)
assert isolated_cad.RETAINED_CAD_SESSIONS[str(session.root)] is session
finally:
isolated_cad.RETAINED_CAD_SESSIONS.pop(str(session.root), None)
def test_repeat_explicit_force_checks_whole_job_not_only_completed_root(tmp_path):
from dx_productivity.trial_task_center.batch_supervisor import _force_owned_supervisor
calls = []
process = SimpleNamespace(poll=lambda: 0, tree_exited=lambda: False,
terminate=lambda: calls.append('force-job'))
journal = {'version': 1, 'batch_id': 'a' * 32, 'attempt_id': 'b' * 32,
'operation': 'execute_quick_run', 'task_ids': ['A'], 'force_state': 'termination_requested'}
_force_owned_supervisor(tmp_path, journal, process)
assert calls == ['force-job']
+73
View File
@@ -0,0 +1,73 @@
from threading import Event
from test_nonblocking_items import component_case
from dx_productivity.dsh.execution_runs import execute_confirmed_run
from dx_productivity.dsh.run_journal import RunJournal, resume_preflight
from dx_productivity.dsh.task_lifecycle import preflight
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
from dx_productivity.trial_task_center.task_queue import execute_task_queue
def supervised_boundary(engine, store):
gui = TaskCenterService(store, engine._logging, supervised=True,
quick_run_preparer=engine._quick_run_preparer)
gui._supervise = lambda operation, arguments, *, stop_event: execute_task_queue(
engine, stop_event=stop_event, **arguments)
return gui
def test_safe_failed_uid_pause_can_resume_independent_uid_through_dsh(component_case):
service, _, tasks, calls, outcomes = component_case
ids = [tasks[0].task_id]
stop = Event()
outcomes[(ids[0], ('R1',))] = 'batch_failed'
outcomes['after_call'] = lambda count: stop.set() if count == 1 else None
root = service._logging.root
result = execute_confirmed_run(service, root, ids, preflight(service, ids), stop, '4' * 32)
assert result['status'] == 'paused'
inspected = RunJournal(root).inspect(service, '4' * 32)
assert inspected['resume_ready'], inspected['blockers']
report = resume_preflight(service, inspected)
assert report['ready']
execute_confirmed_run(service, root, ids, report, Event(), '4' * 32, resume=inspected)
assert calls == [(ids[0], ('R1',)), (ids[0], ('R2',))]
def test_last_primary_pause_keeps_deferred_pass_visible_to_dsh(component_case):
engine, store, tasks, calls, outcomes = component_case
gui = supervised_boundary(engine, store)
ids = [task.task_id for task in tasks]
stop = Event()
outcomes[(ids[0], ('R1',))] = ['attach_failed', 'saved_ok']
outcomes['after_call'] = lambda count: stop.set() if count == 4 else None
root = engine._logging.root
result = execute_confirmed_run(gui, root, ids, preflight(gui, ids), stop, '5' * 32)
assert result['status'] == 'paused' and len(calls) == 4
inspected = RunJournal(root).inspect(gui, '5' * 32)
assert inspected['remaining_task_ids'], 'deferred work must remain accessible after the last primary item'
assert inspected['resume_ready'], inspected['blockers']
execute_confirmed_run(gui, root, ids, resume_preflight(gui, inspected), Event(), '5' * 32, resume=inspected)
assert calls[-1] == (ids[0], ('R1',)) and len(calls) == 5
def test_paused_problem_pass_with_manual_failure_resumes_reserved_uid(component_case):
engine, store, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
project = engine.projects(task_id)[0].path
targets = tuple(ComponentTarget(project, 'MAIN', '1', f'u{i}', f'R{i}', 'OLD', '10K') for i in (1, 2, 3))
store.record_target_inventory(task_id, targets)
store.replace_target_plan(task_id, tuple(TargetPlanRow(target, True, 'NEW') for target in targets))
gui = supervised_boundary(engine, store)
stop = Event()
outcomes[(task_id, ('R1',))] = 'batch_failed'
outcomes[(task_id, ('R2',))] = ['attach_failed', 'saved_ok']
outcomes[(task_id, ('R3',))] = ['attach_failed', 'saved_ok']
outcomes['after_call'] = lambda count: stop.set() if count == 4 else None
root = engine._logging.root
result = execute_confirmed_run(gui, root, [task_id], preflight(gui, [task_id]), stop, '6' * 32)
assert result['status'] == 'paused' and len(calls) == 4
inspected = RunJournal(root).inspect(gui, '6' * 32)
assert inspected['resume_ready'], inspected['blockers']
execute_confirmed_run(gui, root, [task_id], resume_preflight(gui, inspected), Event(), '6' * 32, resume=inspected)
assert [refs for _, refs in calls] == [('R1',), ('R2',), ('R3',), ('R2',), ('R3',)]
+170
View File
@@ -0,0 +1,170 @@
import pytest
import test_accuracy_vbs_guards as guards
def test_already_target_requires_value_and_cell_policy(tmp_path):
output = guards.run_vbs(tmp_path, ['QPRequireAlreadyTargetPolicy', 'QPTargetCell', 'QPValueMode',
'QPCustomValue', 'QPSyncNc', 'QPValueHasNcMarker', 'QPAppendNcMarker', 'QPDecode'], '''
Dim Command,Comp,Selector,Failure
Set Command=CreateObject("Scripting.Dictionary")
Command.Add "new_part_number","NEW":Command.Add "value_mode","custom"
Command.Add "custom_value","10nF":Command.Add "target_cell","CELL":Command.Add "sync_nc","1"
Set Comp=New FakeComponent
Selector=Array("R1","10nF")
QPRequireAlreadyTargetPolicy Comp,Command,Selector
Comp.CurrentValue="wrong"
On Error Resume Next
QPRequireAlreadyTargetPolicy Comp,Command,Selector
Failure=Err.Number:Err.Clear
If Failure=0 Then WScript.Quit 9
Comp.CurrentValue="10nF":Comp.Cell="WRONG"
QPRequireAlreadyTargetPolicy Comp,Command,Selector
If Err.Number=0 Then WScript.Quit 10
WScript.Echo "Value and Cell mismatch blocked"
''', prelude='''
Class FakeComponent
Public Refdes,CurrentValue,Cell
Private Sub Class_Initialize()
Refdes="R1":CurrentValue="10nF":Cell="CELL"
End Sub
End Class
Function QPEffectiveComponentAttribute(ByRef Comp,ByVal Name)
Select Case Name
Case "Value":QPEffectiveComponentAttribute=Comp.CurrentValue
Case "Cell Name":QPEffectiveComponentAttribute=Comp.Cell
Case "Part Label":QPEffectiveComponentAttribute="LABEL"
Case "Part Number":QPEffectiveComponentAttribute="NEW"
End Select
End Function
''')
assert output == 'Value and Cell mismatch blocked'
def test_duplicate_attribute_names_preserve_equal_text_before_blocking(tmp_path):
output = guards.run_vbs(tmp_path, ['QPAttributeObservations', 'QPRequireUniqueAttributeNames', 'QPEncode'], '''
Dim Comp,Attr,Evidence,Failure
Set Comp=New FakeComponent
Set Attr=New FakeAttribute:Attr.Name="Value":Attr.Value="same":Attr.InstanceValue="same"
Comp.Attributes.Add Attr,True
Set Attr=New FakeAttribute:Attr.Name="Value":Attr.Value="same":Attr.InstanceValue="same"
Comp.Attributes.Add Attr,True
Evidence=QPAttributeObservations(Comp)
If UBound(Split(Evidence,vbCrLf))<>2 Then WScript.Quit 8
If InStr(Evidence,"unknown")=0 Then WScript.Quit 9
On Error Resume Next
QPRequireUniqueAttributeNames Comp
Failure=Err.Number
If Failure=0 Then WScript.Quit 10
WScript.Echo "both occurrences retained; ambiguous write blocked"
''', prelude='''
Dim QP_Root,QP_CurrentJobId,QP_Fso
QP_Root=".":QP_CurrentJobId="job":Set QP_Fso=CreateObject("Scripting.FileSystemObject")
Sub QPAppendAscii(ByVal Path,ByVal Text)
End Sub
Class FakeComponent
Public Attributes,UID,Refdes
Private Sub Class_Initialize()
UID="u1":Refdes="R1":Set Attributes=CreateObject("Scripting.Dictionary")
End Sub
End Class
Class FakeAttribute
Public Name,Value,InstanceValue
End Class
''')
assert output == 'both occurrences retained; ambiguous write blocked'
def test_native_value_report_is_readable_and_bound_to_current_snapshot(tmp_path):
from test_value_readback import case
from dx_productivity.trial_task_center.value_readback import capture_value_readback
row, raw = case(tmp_path)
raw.unlink()
fields = dict(row, old_part_number='OLD', new_part_number='NEW')
assignments = '\n'.join('Command.Add "' + key + '","' + value.replace('"', '""') + '"'
for key, value in fields.items() if key != 'target_selectors')
body = '''
Dim Command,Records,Plans,Comp
Set Command=CreateObject("Scripting.Dictionary")
''' + assignments + '''
Command.Add "target_selectors","u1%001FR1%001F10nF"
Set Records=CreateObject("Scripting.Dictionary")
Set Plans=CreateObject("Scripting.Dictionary")
Set Comp=New FakeComponent:Plans.Add "0",Comp
QPWriteValueReadback Command,Records,Plans,"saved_ok"
WScript.Echo "report persisted"
'''
prelude = '''
Dim QP_Root,QP_Fso
QP_Root="''' + str(tmp_path).replace('"', '""') + '''":Set QP_Fso=CreateObject("Scripting.FileSystemObject")
Class FakeAttribute
Public Name,Value,InstanceValue
End Class
Class FakeComponent
Public Attributes,UID,Refdes
Private Sub Class_Initialize()
Dim Attr
UID="u1":Refdes="R1":Set Attributes=CreateObject("Scripting.Dictionary")
Set Attr=New FakeAttribute:Attr.Name="Value":Attr.Value="10nF":Attr.InstanceValue="10nF"
Attributes.Add Attr,True
End Sub
Function FindAttribute(ByVal Name)
Dim Attr
Set FindAttribute=Nothing
For Each Attr In Attributes
If Attr.Name=Name Then Set FindAttribute=Attr
Next
End Function
End Class
Function QPEffectiveComponentAttribute(ByRef Comp,ByVal Name)
If Name="Part Number" Then QPEffectiveComponentAttribute="NEW"
If Name="Value" Then QPEffectiveComponentAttribute="10nF"
If Name="Cell Name" Then QPEffectiveComponentAttribute="CELL"
End Function
'''
assert guards.run_vbs(tmp_path, ['QPWriteValueReadback', 'QPAttributeObservations', 'QPFindCurrentAttribute',
'QPReadUtf8', 'QPWriteUtf8', 'QPEncode', 'QPDecode', 'QPJobSnapshotPath', 'QPValueMode', 'QPCustomValue',
'QPSyncNc', 'QPBooleanText', 'QPTargetCell'], body, prelude=prelude) == 'report persisted'
assert capture_value_readback(tmp_path, row, ('saved_ok', 'batch_closed', 'verified'))['value_readback_status'] == 'verified'
@pytest.mark.parametrize('fault', ['', 'value', 'cell', 'duplicate'])
def test_real_capture_pipeline_skips_only_verified_already_target(tmp_path, fault):
names = ['QPCaptureAndSelect', 'QPCommandTargets', 'QPRequireUniqueAttributeNames', 'QPAttributeObservations',
'QPRequireAlreadyTargetPolicy', 'QPFindCurrentAttribute', 'QPEffectiveComponentAttribute', 'QPValueMode',
'QPCustomValue', 'QPSyncNc', 'QPTargetCell', 'QPEncode', 'QPDecode', 'QPValueHasNcMarker',
'QPAppendNcMarker', 'QPInvalidatePinIndex']
body = '''
Dim Command,Comp,Attr,Index,Names,Values,Failure
Set QP_App=New FakeApp
Set Comp=New FullComponent:Comp.UID="u1":Comp.Refdes="R1"
Names=Array("Part Number","Value","Cell Name")
Values=Array("NEW","''' + ('WRONG' if fault == 'value' else '10nF') + '''","''' + ('WRONG' if fault == 'cell' else 'CELL') + '''")
For Index=0 To 2
Set Attr=New FullAttribute:Attr.Name=Names(Index):Attr.Value=Values(Index):Attr.InstanceValue=Values(Index)
Comp.Attributes.Add Attr,True
Next
''' + ('''Set Attr=New FullAttribute:Attr.Name="Value":Attr.Value="10nF":Attr.InstanceValue="10nF"
Comp.Attributes.Add Attr,True
''' if fault == 'duplicate' else '') + '''
QP_App.ActiveView.Components.Add Comp,True
Set Command=CreateObject("Scripting.Dictionary")
Command.Add "job_id","job":Command.Add "old_part_number","OLD":Command.Add "new_part_number","NEW"
Command.Add "value_mode","custom":Command.Add "custom_value","10nF":Command.Add "sync_nc","1"
Command.Add "target_cell","CELL":Command.Add "target_scope","targets"
Command.Add "target_selectors",QPEncode("u1" & Chr(31) & "R1" & Chr(31) & "10nF")
On Error Resume Next
QPCaptureAndSelect Command,"unused"
Failure=Err.Number
On Error GoTo 0
WScript.Echo CStr(Failure<>0)
WScript.Echo CapturedState & ":" & CapturedCode
'''
prelude = guards.LOG_STUB + guards.FULL_FAKE + '''
Dim QP_CurrentJobId,CapturedState,CapturedCode
QP_CurrentJobId="job"
Sub QPWriteStatus(ByVal Root,ByVal Job,ByVal State,ByVal Code,ByVal Message)
CapturedState=State:CapturedCode=Code
End Sub
'''
output = guards.run_vbs(tmp_path, names, body, prelude=prelude)
assert output.splitlines() == (['False', 'no_match:already_target'] if not fault else ['True', ':'])
+271
View File
@@ -0,0 +1,271 @@
"""A failed receipt authorizes another UID only through affirmative health."""
import json
from pathlib import Path
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.execution_journal import read_command_rows
from dx_productivity.trial_task_center.task_queue import execute_task_queue
def prepared(case):
service, store, tasks, calls, outcomes = case
task_id = tasks[0].task_id
child = service.for_project_task(task_id)
handoff = child._quick_run_preparer.ensure_batch_handoff(task_id, child.projects(task_id), child._execution_rules(task_id))
rows = read_command_rows(handoff.command_path)
journal = child._quick_run_preparer.journal
journal.bind(task_id, rows, {})
return task_id, child, handoff, rows, journal
def native_failed_receipt(journal, task_id, row, runtime, child):
from dx_productivity.trial_task_center.project_session_health import runtime_dispatch_binding
attempt = journal.claim(task_id, row)
binding = runtime_dispatch_binding(child._quick_run_preparer.data_root, row, attempt, runtime)
journal.finish(attempt, 'batch_failed', 'batch_closed', 'current prewrite rejection',
proof={'files': binding['files'], 'native_dispatch': binding})
def test_bare_failed_receipt_cannot_admit_another_uid(component_case):
task_id, child, handoff, rows, journal = prepared(component_case)
journal.finish(journal.claim(task_id, rows[0]), 'batch_failed', 'batch_closed', 'no health evidence')
with pytest.raises(TaskCenterError):
journal.claim(task_id, rows[1])
assert journal.independent_continuation_ready(task_id) is False
def test_empty_proof_does_not_count_as_affirmative_failure_health():
from dx_productivity.trial_task_center.project_session_health import affirmative
assert not affirmative({}, {})
assert not affirmative({'files': []}, {})
def test_changed_project_after_controlled_failure_blocks_remaining_uid(component_case):
service, store, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
project = service.projects(task_id)[0].path
outcomes[(task_id, ('R1',))] = 'batch_failed'
outcomes['after_call'] = lambda count: project.write_text('unexpected source mutation') if count == 1 else None
result = execute_task_queue(service, (task_id,), stop_event=Event())
assert result.paused
assert calls == [(task_id, ('R1',))]
def test_tampered_failure_health_denies_resume(component_case):
service, store, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
outcomes[(task_id, ('R1',))] = 'batch_failed'
stop = Event()
outcomes['after_call'] = lambda count: stop.set() if count == 1 else None
first = execute_task_queue(service, (task_id,), stop_event=stop)
journal = service.for_project_task(task_id)._quick_run_preparer.journal
assert journal.independent_continuation_ready(task_id) is True
receipt = json.loads(store._connection.execute("SELECT receipt_json FROM execution_operations WHERE task_id=? AND state='failed'", (task_id,)).fetchone()[0])
proof = receipt['proof']['failure_health']
Path(proof['files'][0]['path']).write_text('tampered')
assert journal.independent_continuation_ready(task_id) is False
outcomes.pop('after_call')
resumed = execute_task_queue(service, (task_id,), stop_event=Event(), queue_id=first.queue_id)
assert calls == [(task_id, ('R1',))]
_, _, _, rows, journal = prepared(component_case)
with pytest.raises(TaskCenterError):
journal.claim(task_id, rows[1])
def test_native_reset_health_binds_current_failed_job_before_next_claim(component_case, monkeypatch):
import subprocess
from test_batch_runtime import Cad, Desktop
from dx_productivity.trial_task_center import worker_monitor
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
task_id, child, handoff, rows, journal = prepared(component_case)
monkeypatch.setattr(worker_monitor, 'run_monitored_process', lambda cmd, *a, **kw: subprocess.CompletedProcess(cmd, 0, '', ''))
root = handoff.command_path.parent
with BatchCadRuntime(child._quick_run_preparer.data_root, 'execution', desktop_factory=Desktop, cad_factory=Cad) as runtime:
runtime.run_worker(('cscript', '', '', str(root), 'python', rows[0]['job_id']), 1)
native_failed_receipt(journal, task_id, rows[0], runtime, child)
health = runtime.reset_project_after_safe_failure(Path(rows[0]['project_path']), root, job_id=rows[0]['job_id'])
release_path = Path(health['resource_record'])
release_bytes = release_path.read_bytes()
proof_path = Path(health['proof_path'])
proof_bytes = proof_path.read_bytes()
release = json.loads(release_bytes)
release['generation_releases'] = []
release_path.write_text(json.dumps(release), encoding='utf-8')
import hashlib
bad = dict(health, resource_record_sha256=hashlib.sha256(release_path.read_bytes()).hexdigest())
proof_path.write_text(json.dumps(bad), encoding='utf-8')
with pytest.raises(TaskCenterError):
journal.certify_safe_failure(task_id, rows[0], bad)
release_path.write_bytes(release_bytes)
proof_path.write_bytes(proof_bytes)
journal.certify_safe_failure(task_id, rows[0], health)
assert journal.failure_certified(task_id, rows[0])
assert journal.claim(task_id, rows[1]).job_id == rows[1]['job_id']
def test_stale_native_attempt_or_mutated_source_health_cannot_certify(component_case, monkeypatch):
import subprocess
from test_batch_runtime import Cad, Desktop
from dx_productivity.trial_task_center import worker_monitor
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
task_id, child, handoff, rows, journal = prepared(component_case)
monkeypatch.setattr(worker_monitor, 'run_monitored_process', lambda cmd, *a, **kw: subprocess.CompletedProcess(cmd, 0, '', ''))
root = handoff.command_path.parent
with BatchCadRuntime(child._quick_run_preparer.data_root, 'execution', desktop_factory=Desktop, cad_factory=Cad) as runtime:
runtime.run_worker(('cscript', '', '', str(root), 'python', rows[0]['job_id']), 1)
native_failed_receipt(journal, task_id, rows[0], runtime, child)
Path(rows[0]['project_path']).write_text('source changed outside this failed job')
health = runtime.reset_project_after_safe_failure(Path(rows[0]['project_path']), root, job_id=rows[0]['job_id'])
assert health['source_unchanged'] is False
with pytest.raises(TaskCenterError):
journal.certify_safe_failure(task_id, rows[0], health)
with pytest.raises(TaskCenterError):
journal.certify_safe_failure(task_id, rows[0], dict(health, job_id=rows[1]['job_id']))
with pytest.raises(TaskCenterError):
journal.claim(task_id, rows[1])
def test_intact_last_verified_same_sheet_baseline_permits_current_prewrite_failure(component_case, monkeypatch):
import subprocess
import hashlib
from test_batch_runtime import Cad, Desktop
from dx_productivity.trial_task_center import worker_monitor
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
task_id, child, handoff, rows, journal = prepared(component_case)
baseline_file = child._quick_run_preparer.data_root / 'verified-sheet.json'
baseline_file.write_text('verified semantic sheet evidence')
baseline = {'project_path': str(Path(rows[1]['project_path']).resolve()).casefold(),
'schematic_name': rows[1]['schematic_name'], 'sheet_number': rows[1]['sheet_number'],
'state': 'S\tfull_sheet_v1\r\nverified R2'}
journal.finish(journal.claim(task_id, rows[1]), 'saved_ok', 'batch_closed', 'R2 verified', proof={
'baseline': baseline, 'files': [{'path': str(baseline_file), 'sha256': hashlib.sha256(baseline_file.read_bytes()).hexdigest()}]})
monkeypatch.setattr(worker_monitor, 'run_monitored_process', lambda cmd, *a, **kw: subprocess.CompletedProcess(cmd, 0, '', ''))
root = handoff.command_path.parent
with BatchCadRuntime(child._quick_run_preparer.data_root, 'execution', desktop_factory=Desktop, cad_factory=Cad) as runtime:
runtime.run_worker(('cscript', '', '', str(root), 'python', rows[0]['job_id']), 1)
native_failed_receipt(journal, task_id, rows[0], runtime, child)
Path(rows[0]['project_path']).write_text('legal last verified sheet serialization')
health = runtime.reset_project_after_safe_failure(Path(rows[0]['project_path']), root, job_id=rows[0]['job_id'])
journal.certify_safe_failure(task_id, rows[0], health)
assert journal.failure_certified(task_id, rows[0])
baseline_file.write_text('tampered prior sheet')
assert not journal.failure_certified(task_id, rows[0])
def test_old_native_health_cannot_certify_a_new_journal_dispatch(component_case, monkeypatch):
import subprocess
from test_batch_runtime import Cad, Desktop
from dx_productivity.trial_task_center import worker_monitor
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
from dx_productivity.trial_task_center.project_session_health import runtime_dispatch_binding
task_id, child, handoff, rows, journal = prepared(component_case)
monkeypatch.setattr(worker_monitor, 'run_monitored_process', lambda cmd, *a, **kw: subprocess.CompletedProcess(cmd, 0, '', ''))
old = None
for generation in (1, 2):
if generation == 2:
journal.authorize_retry(task_id)
journal.bind(task_id, rows, {})
attempt = journal.claim(task_id, rows[0])
root = handoff.command_path.parent
with BatchCadRuntime(child._quick_run_preparer.data_root, 'execution', desktop_factory=Desktop, cad_factory=Cad) as runtime:
runtime.run_worker(('cscript', '', '', str(root), 'python', rows[0]['job_id']), 1)
binding = runtime_dispatch_binding(child._quick_run_preparer.data_root, rows[0], attempt, runtime)
journal.finish(attempt, 'batch_failed', 'batch_closed', 'failed', proof={
'files': binding['files'], 'native_dispatch': binding})
health = runtime.reset_project_after_safe_failure(Path(rows[0]['project_path']), root, job_id=rows[0]['job_id'])
if old is not None:
with pytest.raises(TaskCenterError):
journal.certify_safe_failure(task_id, rows[0], old)
journal.certify_safe_failure(task_id, rows[0], health)
old = health
def test_source_edit_after_safe_failure_pause_revokes_ready_and_claim(component_case):
service, store, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
outcomes[(task_id, ('R1',))] = 'batch_failed'
stop = Event()
outcomes['after_call'] = lambda count: stop.set() if count == 1 else None
execute_task_queue(service, (task_id,), stop_event=stop)
child = service.for_project_task(task_id)
journal = child._quick_run_preparer.journal
assert journal.independent_continuation_ready(task_id)
project = child.projects(task_id)[0].path
(project.parent / 'unrelated-component.sch').write_text('external CAD edit after certificate')
assert journal.independent_continuation_ready(task_id) is False
rows = read_command_rows(child._quick_run_preparer.data_root / 'quick-run' / 'command.tsv')
with pytest.raises(TaskCenterError):
journal.claim(task_id, rows[1])
assert calls == [(task_id, ('R1',))]
@pytest.mark.parametrize('external_edit_after_success', [False, True])
def test_new_verified_same_sheet_baseline_advances_source_checkpoint(component_case, external_edit_after_success):
import csv
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
from dx_productivity.trial_task_center.quick_run import _encode_vbs_field
service, store, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
project = service.projects(task_id)[0].path
targets = tuple(ComponentTarget(project, 'MAIN', '1', f'u{i}', f'R{i}', 'OLD', '10K') for i in (1, 2, 3))
store.record_target_inventory(task_id, targets)
store.replace_target_plan(task_id, tuple(TargetPlanRow(target, True, 'NEW') for target in targets))
outcomes[(task_id, ('R1',))] = 'batch_failed'
stop = Event()
def saved(count):
if count != 2:return
child = service.for_project_task(task_id)
root = child._quick_run_preparer.data_root / 'quick-run'
with (root / 'current-command.tsv').open(encoding='utf-8-sig') as stream:
row = next(csv.DictReader(stream, delimiter='\t'))
project.write_text('legally verified R2 save')
columns = ('job_id', 'project_path', 'schematic_name', 'sheet_number', 'semantic_state')
values = (row['job_id'], str(project), 'MAIN', '1', 'S\tfull_sheet_v1\r\nR2 verified save')
(root / ('post-state-' + row['job_id'] + '.tsv')).write_text('\t'.join(columns) + '\n' +
'\t'.join(_encode_vbs_field(value) for value in values) + '\n', encoding='utf-8')
stop.set()
outcomes['after_call'] = saved
first = execute_task_queue(service, (task_id,), stop_event=stop)
assert calls == [(task_id, ('R1',)), (task_id, ('R2',))]
child = service.for_project_task(task_id)
journal = child._quick_run_preparer.journal
assert journal.independent_continuation_ready(task_id)
if external_edit_after_success:
(project.parent / 'OTHER.sch').write_text('unrelated external edit after successful checkpoint')
assert journal.independent_continuation_ready(task_id) is False
else:
outcomes.pop('after_call')
resumed = execute_task_queue(service, (task_id,), stop_event=Event(), queue_id=first.queue_id)
assert not resumed.paused and calls[-1] == (task_id, ('R3',))
def test_verified_native_release_source_is_reused_without_hashing_locked_files(component_case, monkeypatch):
import subprocess
import hashlib
from test_batch_runtime import Cad, Desktop
from dx_productivity.trial_task_center import worker_monitor, discovery_cache
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
from dx_productivity.trial_task_center.project_session_health import verified_source_checkpoint
task_id, child, handoff, rows, journal = prepared(component_case)
monkeypatch.setattr(worker_monitor, 'run_monitored_process', lambda cmd, *a, **kw: subprocess.CompletedProcess(cmd, 0, '', ''))
root = handoff.command_path.parent
attempt = journal.claim(task_id, rows[0])
with BatchCadRuntime(child._quick_run_preparer.data_root, 'execution', desktop_factory=Desktop, cad_factory=Cad) as runtime:
runtime.run_worker(('cscript', '', '', str(root), 'python', rows[0]['job_id']), 1)
health = runtime.reset_project_after_safe_failure(Path(rows[0]['project_path']), root, job_id=rows[0]['job_id'])
semantic = root / 'verified-sheet.txt'
semantic.write_text('S\tfull_sheet_v1\r\nverified current native sheet')
proof = {'files': [{'path': str(semantic), 'sha256': hashlib.sha256(semantic.read_bytes()).hexdigest()}],
'baseline': {'project_path': str(Path(rows[0]['project_path'])).casefold(),
'schematic_name': rows[0]['schematic_name'], 'sheet_number': rows[0]['sheet_number'],
'state': 'S\tfull_sheet_v1\r\nverified current native sheet'},
'native_attempt': {key: health[key] for key in ('session_id', 'attempt_id', 'generation')}}
monkeypatch.setattr(discovery_cache, 'project_fingerprint', lambda *a, **kw: pytest.fail('verified native source must not be hashed twice'))
checkpoint = verified_source_checkpoint(child._quick_run_preparer.data_root, rows[0], attempt, proof,
[{'identity': {'failed': 'prior'}, 'certificate_sha256': 'a' * 64}],
excluded_root=child._quick_run_preparer.data_root, native_source=health)
assert checkpoint['source_sha256'] == health['source_sha256']
+332
View File
@@ -0,0 +1,332 @@
import io
import json
import sys
import textwrap
import time
import threading
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import batch_resources, batch_supervisor, isolated_cad, worker_monitor
from dx_productivity.trial_task_center.errors import TaskCenterError
def test_successful_quit_retains_live_cad_descendants(tmp_path, monkeypatch):
from test_isolated_cad import fake_desktop
events, cad = fake_desktop(monkeypatch, tmp_path)
cad.tree_exited = lambda: False
session = isolated_cad.IsolatedCadSession(tmp_path)
session.__enter__()
start = session.desktop.start_process
def start_with_identity(*args, **options):
process = start(*args, **options)
process.pid = 124
return process
session.desktop.start_process = start_with_identity
try:
with pytest.raises(worker_monitor.WorkerMonitorError):
session.__exit__(None, None, None)
assert not any(isinstance(event, tuple) and event[0] == 'release' for event in events)
assert isolated_cad.RETAINED_CAD_SESSIONS[str(session.root)] is session
assert (tmp_path / 'uncertain.flag').exists()
finally:
isolated_cad.RETAINED_CAD_SESSIONS.pop(str(session.root), None)
def test_runtime_retains_quit_helper_after_cad_tree_exited(tmp_path):
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
cad_process = SimpleNamespace(poll=lambda: 0, tree_exited=lambda: True)
helper = SimpleNamespace(poll=lambda: None, tree_exited=lambda: False)
def failed_close(*args):
raise worker_monitor.WorkerMonitorError('Quit helper retained')
cad = SimpleNamespace(cad=cad_process, _retained_processes=[cad_process, helper],
__exit__=failed_close, record={})
closed = []
runtime = BatchCadRuntime(tmp_path, 'execute_quick_run')
runtime.generation = 1
runtime.cad = cad
runtime.desktop = SimpleNamespace(_processes=[cad_process, helper], close=lambda: closed.append(True))
try:
with pytest.raises(batch_resources.BatchResourceCleanupError):
runtime.close()
assert not closed
assert runtime.cad is cad
finally:
batch_resources.LIVE_RESOURCES.pop(str(runtime.path), None)
@pytest.mark.parametrize('root_finished,control_error', [(False, False), (True, False), (False, True)])
def test_monitor_retains_possible_write_without_control(tmp_path, monkeypatch, root_finished, control_error):
calls = []
process = SimpleNamespace(pid=123, stdout=io.BytesIO(), stderr=io.BytesIO(),
returncode=0 if root_finished else None, poll=lambda: 0 if root_finished else None,
tree_exited=lambda: False, wait=lambda **options: 0,
close=lambda: calls.append('process_close'))
class Owned:
def __init__(self, *args): pass
def close(self): calls.append('owned_close')
def stop_workers(self, process):
calls.append('terminate')
return []
monkeypatch.setattr(worker_monitor, '_OwnedWorkers', Owned)
options = {}
if control_error:
from dx_productivity.trial_task_center import stop_control
options['force_control'] = stop_control.StopControl()
monkeypatch.setattr(stop_control, 'wait_for_resolution',
lambda *args, **kwargs: (_ for _ in ()).throw(OSError('resolution observer unavailable')))
if not root_finished:
original = worker_monitor.ProgressWatch
class UnsafeWatch(original):
def __init__(self, *args):
super().__init__(*args)
self.safe_stop = False
monkeypatch.setattr(worker_monitor, 'ProgressWatch', UnsafeWatch)
atomic = worker_monitor._atomic_text
def locked_ready(path, text):
if path.suffix == '.ready':
raise OSError('ready locked')
atomic(path, text)
monkeypatch.setattr(worker_monitor, '_atomic_text', locked_ready)
try:
with pytest.raises((worker_monitor.WorkerMonitorError, OSError)):
worker_monitor.run_monitored_process(('cscript', '', '', str(tmp_path), 'python', 'job'), 1,
process_factory=lambda *args, **options: process, **options)
assert not calls
assert batch_resources.pending_resources(tmp_path)
assert (tmp_path / 'uncertain.flag').exists()
finally:
for key, entry in tuple(getattr(worker_monitor, 'RETAINED_WORKERS', {}).items()):
if entry['root'] == tmp_path:
worker_monitor.RETAINED_WORKERS.pop(key)
@pytest.mark.parametrize('state', ['blocked', 'finished'])
@pytest.mark.parametrize('active', [False, True])
def test_reconcile_does_not_hide_retained_supervisor_descendants(tmp_path, monkeypatch, state, active):
token = 'a' * 32
path = tmp_path / 'batch-resources' / token / 'supervisor.json'
batch_resources.write_record(path, {'version': 1, 'batch_id': token, 'attempt_id': 'b' * 32,
'operation': 'execute_task_queue', 'state': state, 'task_ids': ['A'], 'outcome': 'interrupted',
'process': {'pid': 20, 'creation_time': 'worker'},
'parent_process': {'pid': 10, 'creation_time': 'parent'}, 'request_sha256': 'f' * 64})
process = SimpleNamespace(poll=lambda: 0, tree_exited=lambda: False)
registry = batch_supervisor._ACTIVE_SUPERVISORS if active else batch_supervisor._LIVE_SUPERVISORS
registry[path] = (object(), process, SimpleNamespace(waiting_for_resolution=True)) if active else (object(), process)
monkeypatch.setattr(batch_resources, '_process_gone', lambda identity: True)
try:
assert batch_supervisor.pending_supervisors(tmp_path)
assert batch_supervisor.reconcile_supervisors(tmp_path)
finally:
registry.pop(path, None)
@pytest.mark.parametrize('force', [False, True])
def test_noninteractive_worker_keeps_retained_job_alive_until_natural_exit(tmp_path, monkeypatch, force):
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
launcher = textwrap.dedent('''
import sys, json
from pathlib import Path
from dx_productivity.trial_task_center import batch_runtime, batch_worker
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.stop_control import StopControl
from dx_productivity.trial_task_center.batch_resources import BatchResourceCleanupError
class Retained(batch_runtime.BatchCadRuntime):
def __exit__(self, *args):
raise BatchResourceCleanupError('injected retained write owner')
batch_runtime.BatchCadRuntime = Retained
def run(self, task_id, runtime=None):
(runtime.root / 'control.json').write_text(json.dumps(isinstance(runtime.stop_event, StopControl)))
child_code = 'import time; from pathlib import Path; time.sleep(1.2); Path(' + repr(str(runtime.root / 'child-finished')) + ').write_text("finished")'
process = runtime._ensure_desktop().start_process((sys.executable, '-c', child_code))
runtime._track(process)
raise BatchResourceCleanupError('injected possible write failure')
TaskCenterService.execute_quick_run = run
batch_worker.run(Path(sys.argv[1]))
''')
if force:
launcher = launcher.replace('time.sleep(1.2)', 'time.sleep(60)')
monkeypatch.setattr(batch_supervisor, '_command', lambda request: (sys.executable, '-c', launcher, str(request)))
store = TaskStore(tmp_path / 'tasks.db')
try:
service = TaskCenterService(store, configure_logging(tmp_path))
task = store.create_task('harmless retained child')
if force:
failures = []
def supervise():
try:
batch_supervisor.run_supervised(service, 'execute_quick_run', {'task_id': task.task_id})
except TaskCenterError as error:
failures.append(error)
thread = threading.Thread(target=supervise)
thread.start()
deadline = time.monotonic() + 15
while not any(control.waiting_for_resolution for path, (_, _, control)
in tuple(batch_supervisor._ACTIVE_SUPERVISORS.items()) if path.is_relative_to(tmp_path)):
assert thread.is_alive() and time.monotonic() < deadline
time.sleep(.02)
service.force_pending_owned_resources(confirmed=True)
thread.join(15)
assert not thread.is_alive()
assert failures and failures[0].code == 'user_forced_stop'
assert list(tmp_path.rglob('uncertain.flag'))
else:
with pytest.raises(TaskCenterError):
batch_supervisor.run_supervised(service, 'execute_quick_run', {'task_id': task.task_id})
assert json.loads((tmp_path / 'control.json').read_text()) is True
assert (tmp_path / 'child-finished').is_file() is not force
finally:
for path, (_, process, _) in tuple(batch_supervisor._ACTIVE_SUPERVISORS.items()):
if path.is_relative_to(tmp_path):
process.terminate(reason='explicit harmless test cleanup')
if force and 'thread' in locals():
thread.join(15)
store.close()
def test_explicit_force_can_signal_an_active_protected_supervisor(tmp_path):
from dx_productivity.trial_task_center.stop_control import StopControl
token = 'c' * 32
path = tmp_path / 'batch-resources' / token / 'supervisor.json'
control = StopControl()
control.waiting_for_resolution = True
process = SimpleNamespace(pid=123, poll=lambda: None)
registry = getattr(batch_supervisor, '_ACTIVE_SUPERVISORS', {})
registry[path] = (object(), process, control)
try:
with pytest.raises(TaskCenterError):
batch_resources.force_pending_owned_resources(tmp_path)
assert not control.force_event.is_set()
# Unknown ownership cannot grant force, even for an active waiter.
with pytest.raises((TaskCenterError, OSError)):
batch_resources.force_pending_owned_resources(tmp_path, confirmed=True)
assert not control.force_event.is_set()
finally:
registry.pop(path, None)
def test_worker_exit_does_not_wait_for_already_released_empty_desktop(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import batch_worker, stop_control
runtime = SimpleNamespace(read_only=False, root=tmp_path, path=tmp_path / 'session.json',
record={'state': 'released'}, desktop=SimpleNamespace(_processes=[]), cad=None,
owned_processes_exited=lambda: False, close=lambda **options: None)
monkeypatch.setattr(stop_control, 'wait_for_resolution', lambda *args, **options: pytest.fail('released owner waited'))
batch_worker._wait_for_owned_writes(runtime, stop_control.StopControl())
@pytest.mark.parametrize('force', [False, True])
def test_retained_native_worker_is_reachable_for_exit_or_explicit_force(tmp_path, monkeypatch, force):
from uuid import uuid4
from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop
desktop = PrivateDesktop('dx-' + uuid4().hex, enabled=True)
desktop.__enter__()
process = desktop.start_process((sys.executable, '-c', 'import time;time.sleep(60)' if force else 'pass'))
owned = worker_monitor._OwnedWorkers(uuid4().hex, {sys.executable})
token = uuid4().hex
try:
worker_monitor._retain_worker(tmp_path, token, 'job', process, owned, True, 'unsafe worker')
if force:
assert batch_resources.cleanup_pending_resources(tmp_path)
assert process.poll() is None
with pytest.raises(TaskCenterError):
batch_resources.force_pending_owned_resources(tmp_path)
assert process.poll() is None
assert batch_resources.force_pending_owned_resources(tmp_path, confirmed=True) == ()
else:
process.wait(timeout=10)
deadline = time.monotonic() + 5
while not process.tree_exited():
assert time.monotonic() < deadline
time.sleep(.01)
assert batch_resources.cleanup_pending_resources(tmp_path) == ()
assert not process.cleanup_record['forced_termination']
assert (tmp_path / 'uncertain.flag').exists()
finally:
worker_monitor.RETAINED_WORKERS.pop(str(tmp_path / ('retained-worker-' + token + '.json')), None)
process.terminate(reason='explicit harmless test cleanup')
desktop.close()
def test_active_force_request_requires_creation_identity_and_durable_protection(tmp_path, monkeypatch):
from uuid import uuid4
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api
from dx_productivity.trial_task_center.stop_control import StopControl
from dx_productivity.trial_task_center import stop_control
api = _Win32Api()
process = api.create_process((sys.executable, '-c', 'import time;time.sleep(60)'), None, str(tmp_path), None)
token = uuid4().hex
path = tmp_path / 'batch-resources' / token / 'supervisor.json'
identity = batch_resources.process_identity(process)
journal = {'version': 1, 'batch_id': token, 'attempt_id': uuid4().hex, 'state': 'running',
'operation': 'execute_quick_run', 'task_ids': ['A'], 'process': identity,
'parent_process': identity, 'request_sha256': 'f' * 64}
control = StopControl()
control.waiting_for_resolution = True
batch_supervisor._ACTIVE_SUPERVISORS[path] = (api, process, control)
try:
batch_resources.write_record(path, dict(journal, process=dict(identity, creation_time='foreign')))
with pytest.raises(TaskCenterError):
batch_resources.force_pending_owned_resources(tmp_path, confirmed=True)
assert not control.force_event.is_set()
batch_resources.write_record(path, journal)
protect = stop_control.protect_interruption
monkeypatch.setattr(stop_control, 'protect_interruption', lambda *args: (_ for _ in ()).throw(OSError('denied')))
with pytest.raises(OSError):
batch_resources.force_pending_owned_resources(tmp_path, confirmed=True)
assert not control.force_event.is_set()
monkeypatch.setattr(stop_control, 'protect_interruption', protect)
assert batch_resources.force_pending_owned_resources(tmp_path, confirmed=True)
assert control.force_event.is_set()
assert process.poll() is None # Only the owning loop performs termination.
assert (path.parent / 'force-request.json').exists()
finally:
batch_supervisor._ACTIVE_SUPERVISORS.pop(path, None)
process.terminate(reason='explicit harmless test cleanup')
process.close()
api.close_pending()
def test_retained_worker_record_blocks_after_owner_registry_is_lost(tmp_path):
token = 'd' * 32
path = tmp_path / 'tasks' / 'A' / 'quick-run' / ('retained-worker-' + token + '.json')
batch_resources.write_record(path, {'version': 1, 'state': 'blocked', 'token': token,
'job_id': 'job', 'process': {'pid': 10, 'creation_time': 'original'}})
pending = batch_resources.pending_resources(tmp_path)
assert len(pending) == 1 and pending[0]['kind'] == 'retained_worker'
assert batch_resources.cleanup_pending_resources(tmp_path)
def test_unsafe_stall_without_controller_returns_a_reachable_retained_owner(tmp_path, monkeypatch):
process = SimpleNamespace(pid=123, stdout=io.BytesIO(), stderr=io.BytesIO(), returncode=None, polls=0,
close=lambda: None)
def poll():
process.polls += 1
if process.polls >= 8:
process.returncode = 0
return process.returncode
process.poll = poll
process.tree_exited = lambda: process.returncode is not None
class Owned:
def __init__(self, *args): pass
def close(self): pass
def stop_workers(self, process): return []
class StalledWatch(worker_monitor.ProgressWatch):
def __init__(self, *args):
super().__init__(*args)
self.safe_stop = False
def action(self, now): return 'await_safe_completion'
monkeypatch.setattr(worker_monitor, '_OwnedWorkers', Owned)
monkeypatch.setattr(worker_monitor, 'ProgressWatch', StalledWatch)
try:
with pytest.raises(worker_monitor.WorkerMonitorError):
worker_monitor.run_monitored_process(('cscript', '', '', str(tmp_path), 'python', 'job'), 1,
process_factory=lambda *args, **options: process)
assert process.returncode is None
assert batch_resources.pending_resources(tmp_path)
finally:
for key, entry in tuple(worker_monitor.RETAINED_WORKERS.items()):
if entry['root'] == tmp_path:
worker_monitor.RETAINED_WORKERS.pop(key)
+12
View File
@@ -53,6 +53,18 @@ def test_pending_cleanup_cannot_expose_bom_preview():
assert error.bom_report.preview is None
@pytest.mark.parametrize('shutdown', [False, True])
def test_failed_release_also_revokes_explicit_partial_import(shutdown):
from dx_productivity.trial_task_center.bom_import_report import BomImportReport
from dx_productivity.trial_task_center.supervisor_result import resource_pending_error, application_shutdown_error
report = BomImportReport((), (), preview='atomic', passed_preview='partial')
failure = (application_shutdown_error(report, OSError('held application')) if shutdown else
resource_pending_error('inspect_bom_batch', report, OSError('held desktop')))
assert failure.bom_report.preview is None
assert failure.bom_report.passed_preview is None
assert failure.completed_result.passed_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
+87
View File
@@ -0,0 +1,87 @@
from pathlib import Path
import pytest
from dx_productivity.trial_task_center.quick_run_protocol import _encode_vbs_field as enc
def case(tmp_path):
row = dict(task_id='task', job_id='job', project_path=str(tmp_path / 'board.prj'), schematic_name='MAIN',
sheet_number='1', old_part='OLD', new_part='NEW', value_mode='custom', custom_value='10nF',
sync_nc='1', target_cell='CELL', target_scope='targets', target_selectors='u1\x1fR1\x1f10nF')
snapshot = 'C\tu1\tR1\t0\t0\t0\t1\tNO_PINS\r\nA\tu1\tValue\t10nF\t10nF\t0\t0\t0\t0\t10\t0\t1\r\n'
(tmp_path / 'snapshot-job.tsv').write_bytes(snapshot.encode())
header = ['V', '2', 'task', 'job', 'saved_ok', row['project_path'], 'MAIN', '1', 'OLD', 'NEW',
'custom', '10nF', '1', 'CELL', row['target_selectors'], snapshot]
records = [header, ['C', 'u1', 'R1', 'NEW', '10nF', '1', 'CELL'],
['E', 'u1', '0', 'Value', '10nF', '10nF', 'unknown']]
raw = tmp_path / 'value-readback-job.tsv'
raw.write_text('\n'.join('\t'.join(map(enc, record)) for record in records) + '\n', encoding='utf-8')
(tmp_path / 'status.tsv').write_text('job_id\tstate\tcode\tmessage\njob\tsaved_ok\tbatch_closed\tverified\n')
return row, raw
def test_persists_actual_values_and_rejects_later_terminal_job(tmp_path):
from dx_productivity.trial_task_center.value_readback import capture_value_readback, load_value_readback
row, _ = case(tmp_path)
outcome = ('saved_ok', 'batch_closed', 'verified')
details = capture_value_readback(tmp_path, row, outcome)
assert details['value_readback'][0]['actual_value'] == '10nF'
assert details['value_readback'][0]['uid'] == 'u1'
assert details['attribute_observations'][0]['layer'] == 'unknown'
assert load_value_readback(tmp_path, row, outcome) == details
with (tmp_path / 'status.tsv').open('a') as stream:
stream.write('other\tsaved_ok\tbatch_closed\tverified\n')
assert load_value_readback(tmp_path, row, outcome)['value_readback_status'] == 'rejected'
@pytest.mark.parametrize('fault', ['uid', 'policy', 'snapshot', 'foreign_job', 'version', 'cell', 'pn', 'value'])
def test_readback_rejects_foreign_or_stale_report(tmp_path, fault):
from dx_productivity.trial_task_center.value_readback import capture_value_readback
row, raw = case(tmp_path)
text = raw.read_text(encoding='utf-8')
if fault == 'uid':
text = text.replace('C\tu1\t', 'C\tu2\t')
elif fault == 'policy':
row['custom_value'] = '100nF'
elif fault == 'snapshot':
(tmp_path / 'snapshot-job.tsv').write_text('changed')
elif fault == 'foreign_job':
text = text.replace('V\t2\ttask\tjob\t', 'V\t2\ttask\tforeign\t')
elif fault == 'version':
text = text.replace('V\t2\t', 'V\t1\t')
elif fault == 'cell':
text = text.replace('C\tu1\tR1\tNEW\t10nF\t1\tCELL', 'C\tu1\tR1\tNEW\t10nF\t1\tWRONG')
elif fault == 'value':
text = text.replace('C\tu1\tR1\tNEW\t10nF\t', 'C\tu1\tR1\tNEW\twrong\t')
else:
text = text.replace('C\tu1\tR1\tNEW\t', 'C\tu1\tR1\tOLD\t')
raw.write_text(text, encoding='utf-8')
assert capture_value_readback(tmp_path, row, ('saved_ok', 'batch_closed', 'verified'))['value_readback_status'] == 'rejected'
def test_equal_raw_attribute_text_keeps_every_occurrence(tmp_path):
from dx_productivity.trial_task_center.value_readback import capture_value_readback
row, raw = case(tmp_path)
with raw.open('a', encoding='utf-8') as stream:
stream.write('E\tu1\t1\tValue\t10nF\t10nF\tunknown\n')
details = capture_value_readback(tmp_path, row, ('saved_ok', 'batch_closed', 'verified'))
assert len(details['attribute_observations']) == 2
assert details['attribute_ambiguities'] == [{'uid': 'u1', 'name': 'value', 'ordinals': [0, 1]}]
def test_visible_report_uses_actual_values_and_explicitly_marks_missing_value():
import json
from dx_productivity.trial_task_center.ui.messages import replacement_result_rows
event = dict(operation='quick_run_executed', message='Replacements: R1 OLD -> NEW', details={
'state': 'saved_ok', 'value_readback': {'value_readback_status': 'verified',
'schematic_name': 'MAIN', 'sheet_number': '1', 'value_readback_job_id': 'job', 'value_readback': [
dict(uid='u1', refdes='R1', old_part_number='OLD', actual_part_number='NEW',
old_value='planned old', actual_value='actual readback', actual_value_present=True)]}})
rows = replacement_result_rows((json.dumps(event),))
assert rows[0][4:6] == ('planned old', 'actual readback')
assert len(rows[0]) == 7
event['details']['value_readback'] = {'value_readback_status': 'rejected'}
rows = replacement_result_rows((json.dumps(event),))
assert rows[0][5] == '回读证据被拒绝'
assert 'actual readback' not in str(rows)
+159
View File
@@ -0,0 +1,159 @@
"""Frozen parent queue survives one isolated project supervisor failure."""
import json
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.task_queue import TaskQueueEntry, TaskQueueResult
def service_for(tmp_path, monkeypatch, outcomes):
from dx_productivity.trial_task_center import task_queue
monkeypatch.setattr(task_queue, '_plan_hash', lambda child, task_id: 'hash-' + task_id)
children = {name: SimpleNamespace(projects=lambda _, n=name: (
SimpleNamespace(path=tmp_path / n / 'board.prj'),)) for name in ('A', 'B')}
calls = []
def supervise(operation, arguments, **controls):
name = arguments['task_ids'][0]
calls.append((operation, arguments, controls))
outcome = outcomes[name]
if isinstance(outcome, Exception):
raise outcome
return TaskQueueResult(arguments.get('checkpoint_id') or arguments['queue_id'],
(TaskQueueEntry(name, outcome),), False)
return SimpleNamespace(_logging=SimpleNamespace(root=tmp_path),
for_project_task=lambda name: children[name], _supervise=supervise), calls
def test_released_uncertain_A_isolated_from_B_and_parent_order_retained(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
failure = TaskCenterError('quick_run_uncertain', 'A write uncertain')
failure.resources_released = True
service, calls = service_for(tmp_path, monkeypatch, {'A': failure, 'B': 'completed'})
stop = Event()
result = execute_workspace_projects(service, ('A', 'B'), stop_event=stop,
expected_plan_hashes={'A': 'hash-A', 'B': 'hash-B'}, checkpoint_id='a' * 32)
assert [(entry.task_id, entry.state) for entry in result.entries] == [('A', 'blocked'), ('B', 'completed')]
assert result.queue_id == 'a' * 32 and not result.paused
assert [call[1]['task_ids'] for call in calls] == [('A',), ('B',)]
assert calls[0][1]['checkpoint_id'] != calls[1][1]['checkpoint_id']
assert not stop.is_set()
assert json.loads((tmp_path / 'workspace-queues' / (result.queue_id + '.json')).read_text())['task_ids'] == ['A', 'B']
def test_missing_release_proof_prevents_B(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
failure = TaskCenterError('quick_run_uncertain', 'owner still alive')
service, calls = service_for(tmp_path, monkeypatch, {'A': failure, 'B': 'completed'})
result = execute_workspace_projects(service, ('A', 'B'), stop_event=Event())
assert result.paused and result.current_task_id == 'A'
assert [entry.state for entry in result.entries] == ['blocked', 'pending']
assert len(calls) == 1
def test_resume_skips_terminal_and_blocked_tasks_without_replaying_A(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
service, calls = service_for(tmp_path, monkeypatch, {'A': 'failed', 'B': 'completed'})
first = execute_workspace_projects(service, ('A', 'B'), stop_event=Event())
calls.clear()
resumed = execute_workspace_projects(service, ('A', 'B'), stop_event=Event(), queue_id=first.queue_id)
assert resumed == first
assert calls == []
def test_changed_frozen_hash_or_order_rejects_resume(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
service, calls = service_for(tmp_path, monkeypatch, {'A': 'completed', 'B': 'completed'})
first = execute_workspace_projects(service, ('A', 'B'), stop_event=Event())
with pytest.raises(TaskCenterError):
execute_workspace_projects(service, ('B', 'A'), stop_event=Event(), queue_id=first.queue_id)
calls.clear()
with pytest.raises(TaskCenterError):
execute_workspace_projects(service, ('A', 'B'), stop_event=Event(),
expected_plan_hashes={'A': 'changed', 'B': 'hash-B'})
assert calls == []
def test_pause_keeps_one_child_checkpoint_for_exact_resume(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
service, calls = service_for(tmp_path, monkeypatch, {'A': 'paused', 'B': 'completed'})
original = service._supervise
def paused(operation, arguments, **controls):
result = original(operation, arguments, **controls)
return TaskQueueResult(result.queue_id, result.entries, True, 'A')
service._supervise = paused
first = execute_workspace_projects(service, ('A', 'B'), stop_event=Event())
assert first.paused and len(calls) == 1
child = calls[0][1]['checkpoint_id']
path = tmp_path / 'task-queues' / (child + '.json')
path.parent.mkdir()
path.write_text('{}')
service._supervise = original
resumed = execute_workspace_projects(service, ('A', 'B'), stop_event=Event(), queue_id=first.queue_id)
assert calls[1][1]['queue_id'] == child and calls[1][1]['checkpoint_id'] is None
def test_all_primary_projects_precede_deferred_problem_pass(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
service, calls = service_for(tmp_path, monkeypatch, {'A': 'failed', 'B': 'completed'})
original = service._supervise
def engine(operation, arguments, **controls):
outcome = original(operation, arguments, **controls)
path = tmp_path / 'task-queues' / (outcome.queue_id + '.json')
path.parent.mkdir(exist_ok=True)
path.write_text('{}')
return outcome
service._supervise = engine
result = execute_workspace_projects(service, ('A', 'B'), stop_event=Event())
assert [call[1]['task_ids'][0] for call in calls] == ['A', 'B', 'A', 'B']
assert [call[1]['defer_problem_pass'] for call in calls] == [True, True, False, False]
assert calls[2][1]['queue_id'] == calls[0][1]['checkpoint_id']
assert calls[3][1]['queue_id'] == calls[1][1]['checkpoint_id']
assert json.loads((tmp_path / 'workspace-queues' / (result.queue_id + '.json')).read_text())['phase'] == 'finished'
def test_resume_after_manual_resource_release_skips_uncertain_A_and_runs_B(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
from dx_productivity.trial_task_center import batch_resources
failure = TaskCenterError('quick_run_uncertain', 'A still owned')
service, calls = service_for(tmp_path, monkeypatch, {'A': failure, 'B': 'completed'})
batch_id = 'd' * 32
service._last_supervisor_batch_id = batch_id
first = execute_workspace_projects(service, ('A', 'B'), stop_event=Event())
assert first.paused
journal = {'version': 1, 'batch_id': batch_id, 'attempt_id': 'e' * 32,
'operation': 'execute_task_queue', 'state': 'finished', 'task_ids': ['A'],
'process': {'pid': 20, 'creation_time': 'worker'},
'parent_process': {'pid': 10, 'creation_time': 'parent'}, 'request_sha256': 'f' * 64}
batch_resources.write_record(tmp_path / 'batch-resources' / batch_id / 'supervisor.json', journal)
monkeypatch.setattr(batch_resources, '_process_gone', lambda identity: True)
resumed = execute_workspace_projects(service, ('A', 'B'), stop_event=Event(), queue_id=first.queue_id)
assert not resumed.paused
assert [call[1]['task_ids'][0] for call in calls] == ['A', 'B']
assert [entry.state for entry in resumed.entries] == ['blocked', 'completed']
def test_paused_problem_pass_resumes_same_child_in_problems_phase(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
service, calls = service_for(tmp_path, monkeypatch, {'A': 'failed', 'B': 'completed'})
original = service._supervise
problem_attempts = []
def engine(operation, arguments, **controls):
outcome = original(operation, arguments, **controls)
path = tmp_path / 'task-queues' / (outcome.queue_id + '.json')
path.parent.mkdir(exist_ok=True)
path.write_text('{}')
if not arguments['defer_problem_pass'] and arguments['task_ids'] == ('A',):
problem_attempts.append(arguments['queue_id'])
return TaskQueueResult(outcome.queue_id, (TaskQueueEntry('A', 'paused' if len(problem_attempts) == 1 else 'completed'),),
len(problem_attempts) == 1, 'A' if len(problem_attempts) == 1 else None)
return outcome
service._supervise = engine
first = execute_workspace_projects(service, ('A', 'B'), stop_event=Event())
assert first.paused and first.entries[0].state == 'paused'
resumed = execute_workspace_projects(service, ('A', 'B'), stop_event=Event(), queue_id=first.queue_id)
assert not resumed.paused and resumed.entries[0].state == 'completed'
assert len(problem_attempts) == 2 and problem_attempts[0] == problem_attempts[1]