merge(main): resolve PR19 review conflicts and run intervention regressions in CI
Core regression / Python core, intervention UI and release configuration (push) Failing after 2m42s
Core regression / JavaScript syntax (push) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) Canceled after 1m17s
Core regression / JavaScript syntax (pull_request) Canceled after 0s

This commit is contained in:
阿白叔 committed 2026-11-09 11:35:29 +08:00
commit f8f07d30d2
127 files changed
+9390 -386

No files matched your search

+1
View File
@@ -78,6 +78,7 @@ def test_native_only_credential_store_is_checked_without_profile_patch(tmp_path,
assert availability.check_availability(tmp_path)['source'] == 'native'
@pytest.mark.skipif(sys.platform != 'win32', reason='Windows DPAPI credential protection')
def test_dpapi_host_configuration_is_available_without_writes(tmp_path):
from dx_productivity.dsh.provider_config import save_provider
directory = tmp_path / 'dsh'
+93
View File
@@ -71,3 +71,96 @@ def test_cleanup_rejected_admission_does_not_release_resources(tmp_path):
assert not service.calls
assert result['cleanup_attempts'] == 0
assert result['status'] != 'resolved'
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'] == 'cancelled'
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'))
+2
View File
@@ -1,4 +1,5 @@
import json
import sys
import pytest
from dx_productivity.dsh.native_runtime import launch_environment, write_context
from dx_productivity.dsh.snapshot import TaskSnapshot
@@ -48,6 +49,7 @@ def test_invalid_native_credential_reference_does_not_expand_environment_allowli
assert 'FIXTURE_UNRELATED_API_KEY' not in env
@pytest.mark.skipif(sys.platform != 'win32', reason='Windows file sharing lock')
def test_context_publication_survives_a_real_windows_reader_lock(tmp_path):
import ctypes
from ctypes import wintypes
+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'
+16
View File
@@ -13,6 +13,12 @@ from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
@pytest.fixture(autouse=True)
def controlled_error_dialogs(monkeypatch):
from PySide6.QtWidgets import QMessageBox
monkeypatch.setattr(QMessageBox, 'warning', lambda *args, **kwargs: QMessageBox.StandardButton.Ok)
@pytest.fixture
def ai_ready(monkeypatch):
"""AI flow tests supply readiness explicitly; normal fixtures remain unconfigured."""
@@ -43,6 +49,8 @@ def ui(qtbot, tmp_path):
window=TrialTaskCenterWindow(service)
qtbot.addWidget(window);window.show()
def settle():
if not isValid(window) or window._closed:
return
qtbot.waitUntil(lambda:not window._workers and not window._task_query.busy
and not window._context_query.busy and not window._feedback_query.busy
and not window._log_presenter.query.busy and not window._resource_status.busy
@@ -59,4 +67,12 @@ def ui(qtbot, tmp_path):
if isValid(window):
window.plan_panel.discard_all()
window.close()
qtbot.waitUntil(lambda: not isValid(window) or window._closed, timeout=5000)
from PySide6.QtCore import QThreadPool
QThreadPool.globalInstance().waitForDone(5000)
for name in ('_dsh_status', '_dsh_operations', '_dsh_lifecycle', '_dsh_automation'):
controller = getattr(window, name, None)
pool = getattr(controller, '_read_pool', None) or getattr(controller, '_pool', None)
if pool is not None:
assert pool.waitForDone(5000), 'Controlled AI reads must finish before closing the fixture store'
store.close()
+7 -3
View File
@@ -84,7 +84,7 @@ def test_availability_check_cannot_starve_task_worker(
@pytest.mark.parametrize('kind', ['authorized_retry', 'resource_cleanup'])
def test_model_wait_never_owns_task_controls(slow_diagnosis, qtbot, kind):
def test_model_wait_never_owns_task_controls(slow_diagnosis, ui, qtbot, kind):
window, automation, _, start = slow_diagnosis
if kind == 'resource_cleanup':
start(read_only=False, cleanup=True)
@@ -101,6 +101,7 @@ def test_model_wait_never_owns_task_controls(slow_diagnosis, qtbot, kind):
finally:
automation.cancel()
qtbot.waitUntil(lambda: automation.worker is None, timeout=5000)
ui.settle()
def test_finishing_old_diagnosis_preserves_new_manual_run(slow_diagnosis, ui, qtbot):
@@ -123,6 +124,7 @@ def test_finishing_old_diagnosis_preserves_new_manual_run(slow_diagnosis, ui, qt
assert not manual_stop.is_set()
finally:
window._finish_run()
ui.settle()
def reply_to_model(view, action='none'):
@@ -216,10 +218,11 @@ def test_new_manual_run_denies_old_ai_mutation_without_touching_controls(
assert len(published) == 1
finally:
window._finish_run()
ui.settle()
def test_completed_taskless_observation_does_not_start_another_model_run(
slow_diagnosis, qtbot):
slow_diagnosis, ui, qtbot):
window, automation, published, start = slow_diagnosis
view = start()
reply_to_model(view)
@@ -241,6 +244,7 @@ def test_completed_taskless_observation_does_not_start_another_model_run(
qtbot.waitUntil(lambda: len(view.requests) == 3, timeout=5000)
automation.cancel()
qtbot.waitUntil(lambda: automation.worker is None, timeout=5000)
ui.settle()
def test_admission_timeout_releases_even_if_gui_just_admitted(ui, monkeypatch):
@@ -259,7 +263,7 @@ def test_admission_timeout_releases_even_if_gui_just_admitted(ui, monkeypatch):
class ExpiringEvent:
def set(self):
pass
def wait(self, _timeout):
def wait(self, _timeout=None):
return False
monkeypatch.setattr(module, 'Event', ExpiringEvent)
+252
View File
@@ -0,0 +1,252 @@
"""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, IncidentRequest
from dx_productivity.trial_task_center.ui.workers import ServiceWorker
from .test_dsh_native_menu import HarnessView
from .test_dsh_operations import setup_view
pytestmark = pytest.mark.usefixtures('ai_ready')
@pytest.fixture
def single_execution_thread(ui, qtbot):
ui.settle()
pool = QThreadPool.globalInstance()
previous = pool.maxThreadCount()
pool.setMaxThreadCount(1)
yield pool
qtbot.waitUntil(lambda: pool.activeThreadCount() == 0, timeout=5000)
pool.setMaxThreadCount(previous)
@pytest.mark.parametrize('source', ['timer', 'history', '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
assert automation.enqueue(ui.tasks[0].task_id, 'worker_error', 'controlled failure',
execution_authorized=True, run_id='old-run')
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')
worker = automation.worker
ui.window.close()
assert automation.worker is worker
assert not automation.cancel_event.is_set()
assert not ui.window._closed and not automation._closing
assert not published
automation.cancel()
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.current_request = IncidentRequest(ui.tasks[0].task_id, 'worker_error',
'controlled failure', True, 'old-run')
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.current_request = IncidentRequest(ui.tasks[0].task_id, 'worker_error',
'controlled failure', True, 'old-run')
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.current_request = IncidentRequest(ui.tasks[0].task_id, 'worker_error',
'controlled failure', True, 'old-run')
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
View File
@@ -155,7 +155,6 @@ def test_clear_removes_queued_blocker_and_disabled_replay_retains_episode():
def test_readonly_diagnosis_starts_while_worker_is_stuck_and_keeps_controls(ui, monkeypatch, qtbot):
from PySide6.QtWidgets import QApplication
from dx_productivity.trial_task_center.stop_control import StopControl
from dx_productivity.trial_task_center.ui import dsh_automation as module
ui.settle()
@@ -165,7 +164,6 @@ def test_readonly_diagnosis_starts_while_worker_is_stuck_and_keeps_controls(ui,
window._workers.add(original)
window._batch_stop = stop
window._active_quick_run_task_id = window._task_id
monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows')
monkeypatch.setattr(window, '_open_dsh', lambda: None)
monkeypatch.setattr(module, 'GitIssuePublisher', lambda path: lambda *args: {'status': 'unavailable'})
automation = module.DshAutomation(window)
@@ -188,7 +186,6 @@ def test_readonly_diagnosis_starts_while_worker_is_stuck_and_keeps_controls(ui,
def test_resource_diagnosis_keeps_previous_cad_stop_intent(ui, monkeypatch, qtbot):
from PySide6.QtWidgets import QApplication
from dx_productivity.trial_task_center.stop_control import StopControl
from dx_productivity.trial_task_center.ui import dsh_automation as module
ui.settle()
@@ -196,7 +193,6 @@ def test_resource_diagnosis_keeps_previous_cad_stop_intent(ui, monkeypatch, qtbo
previous_stop = StopControl()
previous_stop.set()
window._dsh_run_stop = previous_stop
monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows')
monkeypatch.setattr(window, '_open_dsh', lambda: None)
monkeypatch.setattr(module, 'GitIssuePublisher', lambda path: lambda *args: {'status': 'unavailable'})
automation = module.DshAutomation(window)
-2
View File
@@ -3,7 +3,6 @@ from types import SimpleNamespace
import pytest
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QApplication
from dx_productivity.trial_task_center.ui import dsh_automation as module
from .test_dsh_native_menu import HarnessView
@@ -34,7 +33,6 @@ def slow_diagnosis(ui, qtbot, monkeypatch):
ui.settle()
window = ui.window
published = []
monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows')
monkeypatch.setattr(window, '_create_dsh_view', lambda: SlowHarness(window))
monkeypatch.setattr(module, 'GitIssuePublisher', lambda path: lambda *args: published.append(args) or {'status': 'unavailable'})
automation = module.DshAutomation(window)
-2
View File
@@ -188,7 +188,6 @@ def test_native_startup_failure_never_enqueues_itself(ui):
def test_disabling_clears_pending_without_stopping_original_execution(ui, monkeypatch):
from PySide6.QtWidgets import QApplication
from dx_productivity.trial_task_center.ui.dsh_automation import DshAutomation
monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows')
automation = DshAutomation(ui.window)
ui.window._dsh_automation = automation
from dx_productivity.trial_task_center.stop_control import StopControl
@@ -212,7 +211,6 @@ def test_disabling_clears_pending_without_stopping_original_execution(ui, monkey
def test_duplicate_errors_share_pending_incident_but_new_runs_do_not(ui, monkeypatch):
from PySide6.QtWidgets import QApplication
from dx_productivity.trial_task_center.ui.dsh_automation import DshAutomation
monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows')
automation = DshAutomation(ui.window)
monkeypatch.setattr(automation, '_drain', lambda: None)
for run in ('first', 'first', 'second'):
+4 -3
View File
@@ -156,7 +156,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()
@@ -169,8 +169,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()
+26 -4
View File
@@ -2,7 +2,7 @@ from types import SimpleNamespace
import pytest
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication, QMessageBox
from PySide6.QtWidgets import QMessageBox
from dx_productivity.trial_task_center.errors import TaskCenterError
@@ -18,7 +18,6 @@ def test_fresh_install_without_key_is_red_and_task_error_never_starts_ai(no_mode
window = ui.window
ui.settle()
warnings = []
monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows')
monkeypatch.setattr(QMessageBox, 'warning', lambda *args: warnings.append(args))
monkeypatch.setattr(DshAutomation, '_drain', lambda self: None)
window._show_error(TaskCenterError('worker_error', 'Controlled task failure'))
@@ -44,6 +43,31 @@ def test_switch_off_shows_grey_silent_even_without_key(no_model, ui, qtbot):
assert '已关闭' in window.ai_status_indicator.toolTip()
@pytest.mark.parametrize('code', ['checking', 'runtime_unavailable', 'invalid_configuration', None])
def test_unknown_ai_readiness_preserves_original_error_feedback(no_model, ui, monkeypatch, code):
window = ui.window
ui.settle()
warnings = []
original = window._dsh_status
monkeypatch.setattr(QMessageBox, 'warning', lambda *args: warnings.append(args))
try:
if code is None:
window._dsh_status = None
else:
original._received({'available': False, 'code': code, 'message': 'Controlled uncertainty'})
window._show_error(TaskCenterError('worker_error', 'original failure'))
assert len(warnings) == 1
assert 'original failure' in warnings[0][-1]
assert window._dsh_automation is None
if code is None:
assert not window._queue_dsh_incident(window._task_id, 'worker_error', 'original failure')
assert not window._enqueue_dsh_blocker(source='controlled', task_id=window._task_id,
issue_code='worker_error', run_id='controlled', message='original failure', details={},
read_only=True, cleanup_allowed=False, snapshot={})
finally:
window._dsh_status = original
def test_indicator_tooltip_explains_live_intervention_reason_and_stage(no_model, ui, monkeypatch):
window = ui.window
assert hasattr(window, 'ai_status_indicator'), 'The old cancel button does not explain intervention'
@@ -161,7 +185,6 @@ def test_actual_incident_sends_one_diagnosis_and_one_reflection_despite_readines
window._dsh_status.query.close()
ready = {'available': True, 'code': 'available', 'message': 'Controlled configured model'}
window._dsh_status._received(ready)
monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows')
monkeypatch.setattr(window, '_create_dsh_view', lambda: ControlledHarness(window))
publications = []
monkeypatch.setattr(dsh_automation, 'GitIssuePublisher', lambda path:
@@ -239,7 +262,6 @@ def test_failed_runtime_start_keeps_unstarted_request_identity_for_recovery(no_m
window._dsh_status.timer.stop()
window._dsh_status.query.close()
window._dsh_status._received({'available': True, 'code': 'available', 'message': 'Configured'})
monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows')
automation = dsh_automation.DshAutomation(window)
monkeypatch.setattr(window, '_dsh_automation', automation)
monkeypatch.setattr(window, '_open_dsh', lambda: window._dsh_status.runtime_failed('Controlled startup failure'))
+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]
+40 -9
View File
@@ -24,7 +24,17 @@ def test_project_plan_discard_is_safe_after_qt_reclaims_report_control(ui, qtbot
@pytest.mark.parametrize('stop_kind',['none','pause','force','pause_then_reauthorize'])
def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monkeypatch,scope,stop_kind):
from dx_productivity.trial_task_center.ui import dsh_automation
from dx_productivity.trial_task_center import task_queue
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
from dx_productivity.dsh import execution_runs
ui.settle()
window=ui.window;task=ui.tasks[0]
project = ui.service.projects(task.task_id)[0].path
target = ComponentTarget(project, 'MAIN', '1', 'controlled-uid', 'R1', 'OLD', '10K')
ui.store.record_target_inventory(task.task_id, (target,))
ui.store.replace_target_plan(task.task_id, (TargetPlanRow(target, True, 'NEW'),))
ui.open(task)
ui.settle()
window._tasks=(task,)
window._quick_run_confirmer=lambda *args:True
window._update_gates()
@@ -36,10 +46,18 @@ def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monk
if stop_kind in {'pause','pause_then_reauthorize'}:window._pause_queue()
elif stop_kind=='force':window._force_batch_stop()
failure_count=2 if stop_kind=='pause_then_reauthorize'else 1
state='batch_failed'if len(calls)<=failure_count else'no_match'
if len(calls)<=failure_count:
return subprocess.CompletedProcess(command,2,'','Controlled prewrite attachment failure')
with (Path(command[3])/'status.tsv').open('a',encoding='utf8')as stream:
stream.write(f'{command[-1]}\t{state}\tbatch_closed\tControlled result\n')
stream.write(f'{command[-1]}\tno_match\tbatch_closed\tControlled result\n')
return subprocess.CompletedProcess(command,0,'','')
execute_queue = task_queue.execute_task_queue
def primary_pass(*args, **kwargs):
# Leave the one safe component replay to DSH so this tests its stop handoff.
kwargs['defer_problem_pass'] = True
return execute_queue(*args, **kwargs)
monkeypatch.setattr(task_queue, 'execute_task_queue', primary_pass)
monkeypatch.setattr(execution_runs, 'execute_task_queue', primary_pass)
# Keep the real service, queue, persistence, IncidentRunner and Qt handoff;
# replace only external CAD/model/issue transports and background dispatch.
monkeypatch.setattr(ui.service.for_project_task(task.task_id)._quick_run_preparer,'_process_runner',executor)
@@ -50,8 +68,23 @@ def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monk
monkeypatch.setattr(window,'_open_dsh',lambda:None)
automation=dsh_automation.DshAutomation(window)
window._dsh_automation=automation
monkeypatch.setattr(dsh_automation.QApplication,'platformName',lambda:'review-test')
monkeypatch.setattr(automation,'_analyze',lambda *args:{'reply':json.dumps({'summary':'Retry suggestion','action':'retry_failed'})})
analyzed = Event()
def analyze(*args):
analyzed.set()
return {'reply':json.dumps({'summary':'Retry suggestion','action':'retry_failed'})}
monkeypatch.setattr(automation,'_analyze',analyze)
def wait_for_diagnosis(previous_run=None):
def finished():
record = automation.latest
assert (analyzed.is_set() and automation.worker is None and
record.get('status') in {'resolved','pending_issue','escalated'} and
(previous_run is None or record.get('run_id') != previous_run and
record.get('status') == 'resolved')), (
f'{scope}/{stop_kind}: worker={automation.worker!r}, pending={automation.pending!r}, '
f'latest={record!r}, loading={window._loading}, workers={window._workers!r}, '
f'context_busy={window._context_query.busy}, operations_busy={window._dsh_operations.busy}, '
f'readiness={window._dsh_status.availability!r}')
qtbot.waitUntil(finished,timeout=10000)
monkeypatch.setattr(dsh_automation,'GitIssuePublisher',lambda *args:lambda *args:{'status':'unavailable'})
if scope=='single':window._prepare_quick_run()
else:window._execute_project_tasks()
@@ -62,8 +95,7 @@ def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monk
# grouped runs. Observe the real result without replacing its executor.
result = outcomes[0][0] if isinstance(outcomes[0], tuple) else outcomes[0]
assert (result['paused'] if isinstance(result, dict) else result.paused) is False
qtbot.waitUntil(lambda:automation.worker is None and
automation.latest.get('status')in {'resolved','pending_issue','escalated'},timeout=10000)
wait_for_diagnosis()
ui.settle()
record=automation.latest
assert len(calls)==(2 if stop_kind=='none'else 1)
@@ -75,14 +107,13 @@ def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monk
assert not list((ui.data/'dsh/retry-budget').glob('*.json'))
if stop_kind=='pause_then_reauthorize':
original_run=record['run_id']
analyzed.clear()
window._retry_failed();ui.settle()
window._tasks=(ui.service.get_task(task.task_id),)
window._update_gates()
if scope=='single':window._prepare_quick_run()
else:window._execute_project_tasks()
qtbot.waitUntil(lambda:automation.worker is None and
automation.latest.get('run_id')!=original_run and
automation.latest.get('status')=='resolved',timeout=10000)
wait_for_diagnosis(original_run)
ui.settle()
assert len(calls)==3
assert automation.latest['gates']['not_stopped']
+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"
+15 -8
View File
@@ -145,11 +145,13 @@ def worker_runtime(tmp_path, monkeypatch, monitor):
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
from dx_productivity.trial_task_center import worker_monitor
monkeypatch.setattr(worker_monitor, 'run_monitored_process', monitor)
Desktop.created = []
Desktop.fail_release = False
Cad.created = []
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 +161,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 +417,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 +482,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()
+292
View File
@@ -0,0 +1,292 @@
"""Owned modal-dialog samples; no CAD, project modifications, or PCB."""
import json
import os
import subprocess
from types import SimpleNamespace
import pytest
def script_dialog(**changes):
row = {'hwnd': 10, 'pid': 123, 'class': '#32770', 'title': 'Script Error',
'text': 'Microsoft VBScript compilation error\nName redefined: VdFoo', 'complete': True,
'buttons': [{'hwnd': 11, 'id': 1, 'text': 'OK', 'enabled': True}]}
return dict(row, **changes)
def test_known_script_error_is_recorded_before_acknowledgement_and_remains_failure(tmp_path):
from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard
path = tmp_path / 'cad-dialogs.json'
rows, acknowledged = [script_dialog()], []
def acknowledge(row):
assert json.loads(path.read_text(encoding='utf-8'))['dialogs'][0]['action'] == 'acknowledge_script_error'
acknowledged.append(row['hwnd'])
rows.clear()
desktop = SimpleNamespace(inspect_dialogs=lambda pid: tuple(rows), acknowledge_dialog=acknowledge)
guard = CadDialogGuard(desktop, SimpleNamespace(pid=123, poll=lambda: None), path, 'session')
guard.poll('closing')
guard.poll('closing')
assert acknowledged == [10]
assert 'compilation error' in guard.failure
assert guard.summary()['evidence_path'] == str(path)
@pytest.mark.parametrize('row', [
script_dialog(pid=999),
script_dialog(title='Save Changes', text='Save changes to Board.prj?'),
script_dialog(title='License Error', text='License unavailable'),
script_dialog(title='DxDesigner', text='Unknown warning'),
script_dialog(complete=False),
script_dialog(buttons=[{'hwnd': 11, 'id': 1, 'text': 'OK', 'enabled': True},
{'hwnd': 12, 'id': 2, 'text': 'Cancel', 'enabled': True}]),
])
def test_other_prompts_and_foreign_windows_are_never_automatically_clicked(tmp_path, row):
from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard
path = tmp_path / 'cad-dialogs.json'
desktop = SimpleNamespace(inspect_dialogs=lambda pid: (row,),
acknowledge_dialog=lambda _: pytest.fail('unsafe/foreign prompt clicked'))
guard = CadDialogGuard(desktop, SimpleNamespace(pid=123, poll=lambda: None), path, 'session')
guard.poll('startup')
if row['pid'] == 123:
assert guard.summary()['blocked']
assert json.loads(path.read_text(encoding='utf-8'))['dialogs'][0]['action'] == 'manual_required'
else:
assert not path.exists()
def test_evidence_failure_prevents_automatic_acknowledgement(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import cad_dialogs
desktop = SimpleNamespace(inspect_dialogs=lambda pid: (script_dialog(),),
acknowledge_dialog=lambda _: pytest.fail('unrecorded prompt clicked'))
guard = cad_dialogs.CadDialogGuard(desktop, SimpleNamespace(pid=123, poll=lambda: None),
tmp_path / 'cad-dialogs.json', 'session')
monkeypatch.setattr(cad_dialogs, 'write_record', lambda *_: (_ for _ in ()).throw(OSError('disk unavailable')))
with pytest.raises(OSError, match='disk unavailable'):
guard.poll('closing')
def test_dialogs_are_not_repeatedly_clicked_when_they_do_not_close(tmp_path):
from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard
acknowledged = []
desktop = SimpleNamespace(inspect_dialogs=lambda pid: (script_dialog(),),
acknowledge_dialog=lambda row: acknowledged.append(row['hwnd']))
guard = CadDialogGuard(desktop, SimpleNamespace(pid=123, poll=lambda: None),
tmp_path / 'cad-dialogs.json', 'session')
for _ in range(5):
guard.poll('closing')
assert acknowledged == [10]
assert guard.summary()['blocked']
def test_guard_ignores_a_completed_process(tmp_path):
from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard
desktop = SimpleNamespace(inspect_dialogs=lambda pid: pytest.fail('exited PID inspected'))
guard = CadDialogGuard(desktop, SimpleNamespace(pid=123, poll=lambda: 0),
tmp_path / 'cad-dialogs.json', 'session')
guard.poll('closing')
def test_evidence_limit_still_latches_fatal_error_without_unrecorded_click(tmp_path):
from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard
rows = [script_dialog(title='Unknown', text='initial')]
desktop = SimpleNamespace(inspect_dialogs=lambda pid: tuple(rows),
acknowledge_dialog=lambda row: pytest.fail('evidence limit cannot authorize another click'))
guard = CadDialogGuard(desktop, SimpleNamespace(pid=123, poll=lambda: None),
tmp_path / 'cad-dialogs.json', 'session')
for number in range(100):
rows[0] = script_dialog(title='Unknown', text=str(number))
guard.poll('running')
rows[0] = script_dialog()
guard.poll('closing')
assert guard.failure and len(guard.records) == 100
def test_batch_desktop_lease_delegates_dialogs_only_for_its_current_owned_process(tmp_path):
from dx_productivity.trial_task_center.batch_runtime import _DesktopLease
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
calls = []
desktop = SimpleNamespace(inspect_dialogs=lambda pid: calls.append(pid) or (script_dialog(),),
acknowledge_dialog=lambda row: calls.append('ack'))
owner = SimpleNamespace(generation=1)
lease = _DesktopLease(owner, tmp_path)
lease.desktop, lease.generation = desktop, 1
lease.processes = [SimpleNamespace(pid=123, poll=lambda: None)]
assert lease.inspect_dialogs(123) == (script_dialog(),)
lease.acknowledge_dialog(script_dialog())
assert not lease.inspect_dialogs(999)
owner.generation = 2
assert not lease.inspect_dialogs(123)
with pytest.raises(WorkerMonitorError, match='stale'):
lease.acknowledge_dialog(script_dialog())
assert calls == [123, 'ack']
def test_session_acknowledges_known_error_then_quits_without_claiming_success(tmp_path, monkeypatch):
from test_isolated_cad import fake_desktop
from dx_productivity.trial_task_center import isolated_cad as runtime
events, cad = fake_desktop(monkeypatch, tmp_path)
session = runtime.IsolatedCadSession(tmp_path)
session.__enter__()
rows = [script_dialog()]
session.desktop.inspect_dialogs = lambda pid: tuple(rows)
session.desktop.acknowledge_dialog = lambda row: rows.clear()
with pytest.raises(runtime.WorkerMonitorError, match='script error'):
session.__exit__(None, None, None)
assert not rows and events.count('quit') == 1
assert cad.poll() == 0 and session.record['orderly_shutdown']
assert session.record['clean'] is False
assert (tmp_path / 'uncertain.flag').exists()
def test_startup_script_error_is_acknowledged_and_cannot_enter_project_work(tmp_path, monkeypatch):
from test_isolated_cad import fake_desktop
from dx_productivity.trial_task_center import isolated_cad as runtime
events, cad = fake_desktop(monkeypatch, tmp_path)
rows = [script_dialog()]
monkeypatch.setattr(runtime.PrivateDesktop, 'inspect_dialogs', lambda self, pid: tuple(rows), raising=False)
monkeypatch.setattr(runtime.PrivateDesktop, 'acknowledge_dialog', lambda self, row: rows.clear(), raising=False)
with pytest.raises(runtime.PrivateCadStartupError, match='compilation error'):
with runtime.IsolatedCadSession(tmp_path):
pytest.fail('acknowledging a fatal popup must not authorize project work')
assert not rows and cad.poll() is not None
assert ('release', False) in events
@pytest.mark.skipif(os.name != 'nt', reason='Win32 action boundary')
def test_changed_prompt_or_recycled_window_handle_is_not_acknowledged(tmp_path, monkeypatch):
import win32gui
from dx_productivity.trial_task_center import cad_dialogs
expected = script_dialog()
monkeypatch.setattr(cad_dialogs, 'inspect_owned_dialogs',
lambda *_: (script_dialog(title='Save Changes', text='Save changes?'),))
monkeypatch.setattr(win32gui, 'PostMessage', lambda *_: pytest.fail('changed HWND clicked'))
with pytest.raises(OSError, match='changed'):
cad_dialogs.acknowledge_owned_dialog(None, 'dx-owned', 123, expected)
def test_protected_wait_finishes_when_user_dismisses_dialog_and_owned_processes_exit(tmp_path, monkeypatch):
from threading import Event, Thread
from test_isolated_cad import fake_desktop
from dx_productivity.trial_task_center import isolated_cad as runtime
from dx_productivity.trial_task_center.stop_control import StopControl
from dx_productivity.trial_task_center import worker_monitor
events, cad = fake_desktop(monkeypatch, tmp_path, cad_exit_code=None)
control = StopControl()
session = runtime.IsolatedCadSession(tmp_path, stop_control=control)
session.__enter__()
rows = [script_dialog(title='Save Changes', text='Save changes to Board.prj?')]
session.desktop.inspect_dialogs = lambda pid: tuple(rows)
session.desktop.acknowledge_dialog = lambda row: pytest.fail('save prompt clicked')
start = session.desktop.start_process
def start_quit(command, **kwargs):
process = start(command, **kwargs)
if command[0] == 'quit':
process.wait = lambda timeout: (_ for _ in ()).throw(subprocess.TimeoutExpired('quit', timeout))
process.poll = lambda: None if rows else 0
return process
session.desktop.start_process = start_quit
# Exercise timeout recovery without waiting for the normal 20 second budget.
clock = [0.0]
monkeypatch.setattr(runtime.time, 'monotonic', lambda: clock[0])
session.desktop.inspect_dialogs = lambda pid: (clock.__setitem__(0, clock[0] + 21) or tuple(rows))
waiting, finished = Event(), Event()
publish = worker_monitor._publish_progress
def observe(path, snapshot):
publish(path, snapshot)
if snapshot.get('stage') == 'awaiting_reconciliation':
waiting.set()
monkeypatch.setattr(worker_monitor, '_publish_progress', observe)
errors = []
def close():
try:
session.__exit__(None, None, None)
except Exception as error:
errors.append(error)
finally:
finished.set()
thread = Thread(target=close)
thread.start()
try:
assert waiting.wait(2)
assert not finished.is_set() and cad.poll() is None
rows.clear() # The operator handled the unknown prompt.
cad.returncode = 0
assert finished.wait(2), 'completed owned processes must release without requiring force'
assert not control.force_event.is_set()
assert errors and session.record['clean'] is False
assert events.count('quit') == 1 and (tmp_path / 'uncertain.flag').exists()
finally:
control.request_force()
thread.join(3)
@pytest.mark.skipif(os.name != 'nt', reason='Native owned private-desktop MessageBox samples')
@pytest.mark.parametrize('known', [True, False])
def test_real_private_desktop_messagebox_is_handled_without_touching_input_desktop(tmp_path, known):
import sys
import time
from uuid import uuid4
from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard
from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop
text = 'Microsoft VBScript compilation error\nName redefined: VdFoo' if known else 'Save changes to Board.prj?'
title = 'Script Error' if known else 'Save Changes'
code = 'import ctypes; ctypes.windll.user32.MessageBoxW(None, ' + repr(text) + ', ' + repr(title) + ', 0)'
with PrivateDesktop('dx-' + uuid4().hex, enabled=True) as desktop:
process = desktop.start_process((sys.executable, '-c', code))
guard = CadDialogGuard(desktop, process, tmp_path / 'cad-dialogs.json', 'sample')
deadline = time.monotonic() + 10
while not (guard.failure if known else guard.summary()['dialogs_seen']) and time.monotonic() < deadline:
guard.poll('closing')
time.sleep(.05)
assert guard.summary()['dialogs_seen'] >= 1
if known:
assert guard.records[-1]['action'] == 'acknowledge_script_error', guard.records
assert process.wait(timeout=3) == 0
assert guard.failure
else:
assert process.poll() is None
assert guard.summary()['blocked']
# Explicitly dismiss our disposable sample after proving no automatic click.
dialog, = guard.summary()['current_dialogs']
guard.manual_action(dialog, dialog['buttons'][0]['hwnd'])
assert process.wait(timeout=3) == 0
assert desktop.cleanup_record['desktop_confirmation']['released']
assert not any(row.get('forced_termination') for row in desktop.cleanup_record['processes'])
@pytest.mark.parametrize('directory', ['tasks/task/quick-run', 'batch-resources/batch/generation-1'])
def test_dialog_evidence_is_in_diagnostic_bundle_and_scrubbed(tmp_path, directory):
import zipfile
from dx_productivity.trial_task_center.diagnostics_bundle import export_diagnostic_bundle
path = tmp_path / 'data' / directory / ('cad-dialogs-' + 'a' * 32 + '.json')
path.parent.mkdir(parents=True)
path.write_text(json.dumps({'text': 'C:/Users/Alice/Board/script.vbs'}), encoding='utf-8')
bundle = export_diagnostic_bundle(tmp_path / 'data', tmp_path / 'diagnostics.zip')
with zipfile.ZipFile(bundle) as archive:
content = archive.read(path.relative_to(tmp_path / 'data').as_posix()).decode()
assert 'Alice' not in content and '<USER_HOME>' in content
@pytest.mark.skipif(os.name != 'nt', reason='Native modal dialog while the business thread waits')
def test_dialog_is_serviced_while_business_thread_is_blocked(tmp_path):
import sys
from dx_productivity.trial_task_center import isolated_cad as runtime
from dx_productivity.trial_task_center.cad_dialogs import CadDialogGuard
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime, _DesktopLease
code = "import ctypes; ctypes.windll.user32.MessageBoxW(None, 'Microsoft VBScript compilation error', 'Script Error', 0)"
with BatchCadRuntime(tmp_path / 'runtime', 'dialog-sample') as batch:
lease = _DesktopLease(batch, tmp_path)
lease.__enter__()
process = lease.start_process((sys.executable, '-c', code))
session = runtime.IsolatedCadSession(tmp_path, desktop=lease)
session.cad = process
session._dialogs = CadDialogGuard(lease, process, tmp_path / 'cad-dialogs.json', session.token)
session._start_dialog_monitor()
try:
assert process.wait(timeout=5) == 0 # No polling from this blocked thread.
assert session._dialogs.failure
finally:
session._stop_dialog_monitor()
lease.close()
assert not session._dialog_thread.is_alive()
assert batch.desktop.cleanup_record['desktop_confirmation']['released']
+265
View File
@@ -0,0 +1,265 @@
"""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('read_failed', [False, True])
def test_missing_project_sheet_manifest_is_a_controlled_scope_error(scope_case, read_failed):
from dx_productivity.trial_task_center.component_scope import freeze
preparer, project, rules, *_ = scope_case
key = _path_key(project.path)
discovery = preparer.discover_project(project.path, ('OLD',), collect_components=True)
with pytest.raises(TaskCenterError, match='component_scope'):
freeze((project,), rules, {}, {key: discovery}, {key} if read_failed else set(), 'preserve')
assert not (preparer.data_root / 'quick-run/command.tsv').exists()
@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()
+14 -2
View File
@@ -77,6 +77,7 @@ def test_deep_quick_run_prepare_publish_read_archive_keeps_canonical_results(dee
def test_deep_native_recovery_keeps_canonical_proof_and_release_logs(deep_root):
import hashlib
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
from dx_productivity.trial_task_center.project_discovery import ReleasedProjectReadError
from test_batch_runtime import Desktop
Desktop.created = []
Desktop.fail_release = False
@@ -95,8 +96,19 @@ def test_deep_native_recovery_keeps_canonical_proof_and_release_logs(deep_root):
'source_hashes': {str(path): hashlib.sha256(internal_path(path).read_bytes()).hexdigest()
for path in (project, database)}}
internal_path(evidence / 'native-retry-proof.json').write_text(json.dumps(proof), encoding='utf-8')
assert owner.recover_native_failure(project, evidence, 'timeout')
assert not owner.recover_native_failure(project, evidence, 'second timeout')
with pytest.raises(ReleasedProjectReadError) as caught:
owner.recover_native_failure(project, evidence, 'timeout')
assert caught.value.code == 'quick_run_sheet_discovery'
assert owner.desktop is owner.cad is None
assert not owner.record['retries']
release_record = json.loads(internal_path(evidence / 'project-read-release.json').read_text(encoding='utf-8'))
assert release_record['project_path'] == str(project)
assert release_record['resource_record'] == str(owner.path)
assert release_record['resources_released'] is True
assert json.loads(internal_path(evidence / 'native-retry-proof.json').read_text(encoding='utf-8')) == proof
assert proof['project_path'] == str(project) and proof['evidence_root'] == str(evidence)
assert proof['source_hashes'] == {str(path): hashlib.sha256(internal_path(path).read_bytes()).hexdigest()
for path in (project, database)}
assert all(desktop.released for desktop in Desktop.created)
assert not owner.record.get('release_log_errors')
release = owner.path.with_name('resource-release.log')
+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'
+11 -2
View File
@@ -2,6 +2,7 @@ import os
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
from dx_productivity.trial_task_center.logging_setup import append_task_event
from PySide6.QtCore import Qt
from test_ui_remediation import window
@@ -10,7 +11,8 @@ def test_results_use_executed_readback_and_clear_when_switching_tasks(window, qt
for state, ref in [('saved_ok', 'R1'), ('batch_failed', 'R2'), ('no_match', 'R3')]:
append_task_event(window.service._logging, level='INFO', task_id=task.task_id,
operation='quick_run_executed', message=f'Replacements: {ref} OLD -> ACTUAL Saved, reopened',
details={'state': state, 'schematic_name': 'MAIN', 'sheet_number': '1'})
details={'state': state, 'schematic_name': 'MAIN', 'sheet_number': '1',
'custom_value': 'PLANNED-ONLY', 'copy_part_number_to_value': True})
window.open_task(task.task_id)
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
window._show_task_log()
@@ -19,7 +21,14 @@ def test_results_use_executed_readback_and_clear_when_switching_tasks(window, qt
assert results.rowCount() == 1
assert results.index(0, 1).data() == 'R1'
assert results.index(0, 3).data() == 'ACTUAL'
assert '已保存并核验' in results.index(0, 4).data()
headers = [results.headerData(column, Qt.Orientation.Horizontal)
for column in range(results.columnCount())]
assert headers == ['图页', '位号', '旧料号', '回读料号', '原 Value', '实际 Value', '核验状态']
assert '已保存并核验' in results.index(0, headers.index('核验状态')).data()
assert results.index(0, headers.index('原 Value')).data() == '未提供'
assert results.index(0, headers.index('实际 Value')).data() == '未提供实际回读'
assert all(results.index(0, column).data() != 'PLANNED-ONLY'
for column in range(results.columnCount()))
other = window.service.create_task('Unexecuted')
window.open_task(other.task_id)
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
+81
View File
@@ -0,0 +1,81 @@
"""Portable core reads must not depend on a Qt installation or host casing."""
import os
from pathlib import Path
import subprocess
import sys
from types import SimpleNamespace
from threading import Event
from test_nonblocking_items import component_case
def test_windows_project_keys_remain_case_insensitive_on_portable_host(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import quick_run
monkeypatch.setattr(quick_run.os.path, 'normcase', lambda path: path)
project = tmp_path / 'Board-A' / 'BOARD.prj'
target = SimpleNamespace(project_path=Path(str(project).casefold()), schematic_name='MAIN', sheet_number='1')
rule = SimpleNamespace(scope='targets', targets=(target,))
quick_run._validate_target_scope((SimpleNamespace(path=project),), (rule,),
{quick_run._path_key(project): (('MAIN', '1'),)})
def test_core_ui_projections_can_import_without_qt():
source = Path(__file__).resolve().parents[2] / 'src'
script = '''import importlib.abc,sys
class NoQt(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path=None, target=None):
if fullname.split('.')[0] in {'PySide6', 'shiboken6'}:
raise ImportError('Qt must not be loaded by a pure core projection')
sys.meta_path.insert(0, NoQt())
from dx_productivity.trial_task_center.ui.execution_state import execution_state
from dx_productivity.trial_task_center.ui.messages import replacement_result_rows
assert execution_state(None).editable is False
assert not any(name.startswith(('PySide6', 'shiboken6')) for name in sys.modules)
'''
result = subprocess.run([sys.executable, '-c', script], capture_output=True, text=True,
env=os.environ | {'PYTHONPATH': str(source)}, timeout=15)
assert result.returncode == 0, result.stderr
def test_progress_uses_same_project_keys_as_the_execution_queue(component_case, monkeypatch):
from dx_productivity.trial_task_center import quick_run
from dx_productivity.trial_task_center.task_queue import execute_task_queue
monkeypatch.setattr(quick_run.os.path, 'normcase', lambda path: path)
service, _, tasks, _, outcomes = component_case
task_id = tasks[0].task_id
outcomes[(task_id, ('R1',))] = 'batch_failed'
result = execute_task_queue(service, (task_id,), stop_event=Event())
assert not result.paused
progress = service.quick_run_progress(task_id)
assert progress.queue_complete and progress.failed_items == progress.saved_items == 1
def test_source_checkpoint_reads_the_original_project_spelling(component_case, monkeypatch):
from dx_productivity.trial_task_center import project_session_health
from dx_productivity.trial_task_center.task_queue import execute_task_queue
service, _, tasks, _, outcomes = component_case
task_id = tasks[0].task_id
project = str(service.projects(task_id)[0].path)
assert project != project.casefold()
original = project_session_health.verified_source_checkpoint
reads = []
def checkpoint(data_root, row, *args, **kwargs):
reads.append(row['project_path'])
assert str(row['project_path']) == project
return original(data_root, row, *args, **kwargs)
monkeypatch.setattr(project_session_health, 'verified_source_checkpoint', checkpoint)
outcomes[(task_id, ('R1',))] = 'batch_failed'
def saved(count):
if count != 2:
return
from dx_productivity.trial_task_center.execution_journal import read_command_rows
from dx_productivity.trial_task_center.quick_run import _encode_vbs_field
root = service.for_project_task(task_id)._quick_run_preparer.data_root / 'quick-run'
row = read_command_rows(root / 'current-command.tsv')[0]
fields = ('job_id', 'project_path', 'schematic_name', 'sheet_number', 'semantic_state')
values = (row['job_id'], project, 'MAIN', '1', 'S\tfull_sheet_v1\r\nverified R2')
(root / ('post-state-' + row['job_id'] + '.tsv')).write_text('\t'.join(fields) + '\n' +
'\t'.join(_encode_vbs_field(value) for value in values) + '\n', encoding='utf-8')
outcomes['after_call'] = saved
result = execute_task_queue(service, (task_id,), stop_event=Event())
assert not result.paused and reads == [project]
+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]
+140
View File
@@ -0,0 +1,140 @@
"""Selected lxb nonblocking contracts; disposable workers only, no CAD."""
import subprocess
import os
import sys
import threading
import time
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import worker_monitor
from dx_productivity.trial_task_center.stop_control import StopControl
@pytest.mark.skipif(os.name != 'nt', reason='Windows owned Job and read cancellation sample')
def test_cancel_blocked_read_has_deadline_even_when_progress_keeps_arriving(tmp_path, monkeypatch):
"""A huge ordinary idle limit must not delay an explicit import cancel."""
script = tmp_path / 'reader.py'
script.write_text('''import pathlib,sys,time
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
while not (root/f'monitor-{token}.ready').exists(): time.sleep(.01)
(root/'reading').touch()
for n in range(1,500):
print(f'DX_PROGRESS\\t{token}\\t{job}\\t{n}\\tnative_snapshot_read\\t0\\t1\\t0',flush=True)
time.sleep(.02)
''')
monkeypatch.setattr(worker_monitor, 'READ_ONLY_CANCEL_GRACE_SECONDS', .15, raising=False)
control = StopControl()
def cancel():
while not (tmp_path / 'reading').exists():
time.sleep(.01)
control.set()
thread = threading.Thread(target=cancel, daemon=True)
thread.start()
started = time.monotonic()
command = (sys._base_executable, '-u', str(script), str(tmp_path), sys._base_executable, '', 'job')
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api
api = _Win32Api()
def start(launch, **options):
return api.create_process(launch, None, tmp_path, None, **options)
try:
with pytest.raises(worker_monitor.WorkerMonitorCancelled):
worker_monitor.run_monitored_process(command, 150, abort_event=control,
cooperative_abort=True, force_control=control, process_factory=start)
assert time.monotonic() - started < 3
assert not control.waiting_for_resolution
assert not (tmp_path / 'uncertain.flag').exists()
finally:
control.set()
thread.join(1)
api.close_pending()
@pytest.mark.skipif(os.name != 'nt', reason='Windows owned worker watchdog sample')
def test_frozen_read_uses_short_read_watchdog_instead_of_execution_idle_limit(tmp_path, monkeypatch):
script = tmp_path / 'frozen.py'
script.write_text('import time; time.sleep(1.5)')
monkeypatch.setattr(worker_monitor, 'READ_ONLY_IDLE_TIMEOUT_SECONDS', .15, raising=False)
command = (sys._base_executable, '-u', str(script), str(tmp_path), sys._base_executable, '', 'job')
started = time.monotonic()
with pytest.raises(subprocess.TimeoutExpired):
worker_monitor.run_monitored_process(command, 150, cooperative_abort=True)
assert time.monotonic() - started < 1.3
def test_project_open_has_short_watchdog_only_at_a_safe_boundary():
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
assert watch.accept(b'DX_PROGRESS\ttoken\tjob\t1\topen_project\t0\t1\t1\n', 0)
assert watch.action(45) == 'request_stop'
assert watch.action(90) == 'unresponsive'
unsafe = worker_monitor.ProgressWatch('token', 'job', 150, 0)
assert unsafe.accept(b'DX_PROGRESS\ttoken\tjob\t1\topen_project\t0\t1\t0\n', 0)
assert unsafe.action(90) is None
def test_project_step_forwards_pause_to_its_worker_before_checkpoint(tmp_path):
from dx_productivity.trial_task_center.project_session import ProjectSessionWorker
control = StopControl()
control.set()
requested = []
def worker(command, timeout, *, abort_event, **_controls):
requested.append(abort_event.wait(.5))
return subprocess.CompletedProcess(command, 2, '', 'stopped at safe boundary')
runtime = SimpleNamespace(stop_event=control, run_worker=worker)
session = ProjectSessionWorker(tmp_path / 'board.prj', tmp_path, runtime=runtime)
command = (sys.executable, '-u', 'sample', str(tmp_path), sys.executable, '', 'job')
try:
assert session.run_step(command, 150).returncode == 2
assert requested == [True]
assert not control.force_event.is_set()
finally:
session.close()
@pytest.mark.skipif(os.name != 'nt', reason='Windows Job with a real unsafe worker')
@pytest.mark.parametrize('deny_stop', [False, True])
def test_ordinary_pause_cannot_kill_write_before_queued_unsafe_progress_is_read(tmp_path, monkeypatch, deny_stop):
script = tmp_path / 'writing.py'
script.write_text('''import pathlib,sys,time
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
while not (root/f'monitor-{token}.ready').exists(): time.sleep(.005)
print(f'DX_PROGRESS\\t{token}\\t{job}\\t1\\tnative_replace\\t0\\t1\\t0',flush=True)
(root/'writing').touch()
while not (root/f'monitor-{token}.stop').exists(): time.sleep(.005)
(root/'pause-seen').touch()
while not (root/'finish-write').exists(): time.sleep(.005)
(root/'saved').touch()
''', encoding='utf-8')
control = StopControl()
atomic = worker_monitor._atomic_text
stop_attempts = []
def publish(path, value):
if path.suffix == '.stop':
stop_attempts.append(path)
if deny_stop and len(stop_attempts) == 1:
raise PermissionError('controlled stop token sharing violation')
atomic(path, value)
if path.suffix == '.ready':
deadline = time.monotonic() + 3
while not (tmp_path / 'writing').exists() and time.monotonic() < deadline:
time.sleep(.005)
assert (tmp_path / 'writing').exists()
control.set() # unsafe progress is queued, but watch still says starting/safe.
monkeypatch.setattr(worker_monitor, '_atomic_text', publish)
observed = []
def complete_write():
deadline = time.monotonic() + 3
while not (tmp_path / 'pause-seen').exists() and time.monotonic() < deadline:
time.sleep(.005)
observed.append((tmp_path / 'pause-seen').exists())
(tmp_path / 'finish-write').touch()
driver = threading.Thread(target=complete_write, daemon=True)
driver.start()
command = (sys._base_executable, '-u', str(script), str(tmp_path), sys._base_executable, '', 'job')
try:
result = worker_monitor.run_monitored_process(command, 10, abort_event=control, force_control=control)
assert result.returncode == 0 and (tmp_path / 'saved').exists()
assert not control.force_event.is_set() and not (tmp_path / 'uncertain.flag').exists()
finally:
(tmp_path / 'finish-write').touch()
driver.join(4)
assert observed == [True]
assert len(stop_attempts) >= (2 if deny_stop else 1)
+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']
+54 -4
View File
@@ -1,17 +1,67 @@
import csv
import importlib.util
import json
from pathlib import Path
import sqlite3
import pytest
@pytest.mark.parametrize('behavior', ['success', 'failure_continue', 'uncertain_stop', 'pause_resume'])
def test_multiple_projects_preserve_task_order_scope_results_and_measurements(tmp_path, behavior):
@pytest.mark.parametrize('behavior, steps, changed, states', [
('success', 24, 24, ['completed', 'completed', 'completed']),
('failure_continue', 24, 23, ['failed', 'completed', 'completed']),
('uncertain_stop', 1, 0, ['blocked', 'pending', 'pending']),
('pause_resume', 24, 24, ['completed', 'completed', 'completed']),
])
def test_multiple_projects_preserve_task_order_scope_results_and_measurements(tmp_path, behavior, steps, changed, states):
path = Path(__file__).resolve().parents[2] / 'tools/measure_task_queue.py'
spec = importlib.util.spec_from_file_location('measure_task_queue', path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
report = module.run_scenario(tmp_path / behavior, projects=3, sheets=2, rules=2, behavior=behavior)
output = tmp_path / behavior
report = module.run_scenario(output, projects=3, sheets=2, rules=2, behavior=behavior)
assert report['checks'] == 'passed'
assert report['executed_steps'] == steps
assert report['changed_components'] == changed
assert report['unselected_components_preserved'] == 12
assert report['result']['paused'] == (behavior == 'uncertain_stop')
assert [entry['state'] for entry in report['result']['entries']] == states
calls = report['calls']
assert len(calls) == steps
assert all(len(call['refdes']) == 1 for call in calls)
assert len({(call['project'], call['sheet'], call['refdes'][0]) for call in calls}) == steps
assert sum(call['state'] == 'saved_ok' for call in calls) == changed
assert [call['project'] for call in calls] == (['board-000'] if behavior == 'uncertain_stop' else
['board-000'] * 8 + ['board-001'] * 8 + ['board-002'] * 8)
assert calls[0]['state'] == {'failure_continue': 'batch_failed', 'uncertain_stop': 'batch_saved_unverified'}.get(behavior, 'saved_ok')
with sqlite3.connect(output / 'tasks.db') as connection:
rows = connection.execute('SELECT state,command_json,receipt_json FROM execution_operations').fetchall()
receipts = [json.loads(receipt) for _, _, receipt in rows if receipt]
assert len(receipts) == steps
assert {receipt['job_id']: receipt['native_state'] for receipt in receipts} == {
call['job_id']: call['state'] for call in calls}
assert sum(state == 'verified' for state, _, _ in rows) == changed
assert sum(state == 'failed' for state, _, _ in rows) == (behavior == 'failure_continue')
assert sum(state == 'uncertain' for state, _, _ in rows) == (behavior == 'uncertain_stop')
assert sum(state == 'pending' for state, _, _ in rows) == (7 if behavior == 'uncertain_stop' else 0)
for _, command, receipt in rows:
selector = json.loads(command)['target_selectors'].split('\x1e')
assert len(selector) == 1
uid, refdes, value = selector[0].split('\x1f')
assert uid.endswith(('-1', '-2'))
assert value in {'10K/NC', '10K'}
if receipt:
call = next(call for call in calls if call['job_id'] == json.loads(receipt)['job_id'])
assert call['refdes'] == [refdes]
events = [json.loads(line) for path in (output / 'data' / 'tasks').glob('*/events.jsonl')
for line in path.read_text(encoding='utf-8').splitlines()]
executed = [event for event in events if event['operation'] == 'quick_run_executed']
assert len(executed) == steps
assert all(event['details']['timing']['phase'] == 'execute_step' for event in executed)
assert {event['details']['timing']['job_id'] for event in executed} == {call['job_id'] for call in calls}
timings = report['timings']
assert len([row for row in timings if row['phase'] == 'execute_step']) == report['executed_steps']
assert len([row for row in timings if row['phase'] == 'execute_step']) == steps
assert all(row['elapsed_seconds'] >= 0 for row in timings)
with (output / 'timings.csv').open(encoding='utf-8-sig', newline='') as stream:
assert len([row for row in csv.DictReader(stream) if row['phase'] == 'execute_step']) == steps
assert json.loads((output / 'report.json').read_text(encoding='utf-8'))['executed_steps'] == steps
+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()
+187
View File
@@ -0,0 +1,187 @@
from dataclasses import replace
from importlib.util import find_spec
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)
@pytest.mark.skipif(find_spec('PySide6') is None or find_spec('pytestqt') is None,
reason='Qt dialog acceptance runs on the Windows UI host')
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', ':'])
+60
View File
@@ -0,0 +1,60 @@
import os
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
from threading import Event
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QMessageBox
from shiboken6 import isValid
from test_nonblocking_items import component_case
from dx_productivity.trial_task_center.task_queue import execute_task_queue
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
def test_problem_dialog_disables_uncertain_and_pending_rows(qtbot):
from dx_productivity.trial_task_center.ui.problem_items import ProblemItemsDialog
overview = dict(round_id='round', failed=1, held=1, uncertain=1, resolved=0, items=tuple(
dict(state=state, can_retry=False, operation_key=state, generation=1, refdes=ref, uid=uid,
project_path='board.prj', schematic_name='MAIN', sheet_number='1', code='', message='',
auto_retries_remaining=0) for state, ref, uid in
[('failed', 'R1', 'u1'), ('uncertain', 'R2', 'u2'), ('pending', 'R3', 'u3')]))
dialog = ProblemItemsDialog(overview, allow_retry=True)
qtbot.addWidget(dialog)
assert dialog.table.rowCount() == 3
assert all(not dialog.table.item(i, 0).flags() & Qt.ItemFlag.ItemIsUserCheckable for i in range(3))
assert not dialog.retry_button.isEnabled()
def test_ui_selected_retry_reaches_real_preparation_and_dispatch(component_case, qtbot, monkeypatch):
service, _, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
for ref in ('R1', 'R2'):
outcomes[(task_id, (ref,))] = 'attach_failed'
execute_task_queue(service, (task_id,), stop_event=Event(), defer_problem_pass=True)
window = TrialTaskCenterWindow(service, close_plan_confirmer=lambda: 'discard')
qtbot.addWidget(window)
def settled():
return not window._workers and not window._task_query.busy and not window._context_query.busy
try:
qtbot.waitUntil(settled)
window.open_task(task_id)
qtbot.waitUntil(settled)
window.run_panel.problems_button.click()
qtbot.waitUntil(lambda: window._problem_dialog is not None and settled())
dialog = window._problem_dialog
assert '失败 2' in dialog.summary.text()
assert dialog.table.item(1, 4).text() == 'R2'
dialog.table.item(1, 0).setCheckState(Qt.CheckState.Checked)
assert dialog.retry_button.isEnabled()
monkeypatch.setattr(QMessageBox, 'question', lambda *_a, **_k: QMessageBox.StandardButton.Yes)
dialog.retry_button.click()
qtbot.waitUntil(settled)
outcomes[(task_id, ('R2',))] = 'saved_ok'
execute_task_queue(service, (task_id,), stop_event=Event())
assert calls == [(task_id, ('R1',)), (task_id, ('R2',)), (task_id, ('R2',))]
finally:
if isValid(window):
qtbot.waitUntil(settled)
window.close()
qtbot.waitUntil(lambda: not window._context_query.busy)
+73
View File
@@ -0,0 +1,73 @@
"""Problem-pass safety rejections are durable paused outcomes, not lost results."""
import json
from threading import Event
import pytest
from test_nonblocking_items import component_case
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.task_queue import execute_task_queue
@pytest.mark.parametrize('code', ['quick_run_uncertain', 'problem_retry_scope'])
def test_problem_rejection_preserves_completed_project_and_resumes_original_budget(component_case, monkeypatch, code):
service, store, tasks, calls, outcomes = component_case
ids = tuple(task.task_id for task in tasks)
for task_id in ids:
outcomes[(task_id, ('R1',))] = ['attach_failed', 'saved_ok']
original = execute_task_queue(service, ids, stop_event=Event(), defer_problem_pass=True)
child = service.for_project_task(ids[1])
with monkeypatch.context() as patch:
def reject(*_a, **_k):
raise TaskCenterError(code, 'controlled problem safety rejection')
patch.setattr(child, 'prepare_failed_quick_run', reject)
result = execute_task_queue(service, ids, queue_id=original.queue_id, stop_event=Event())
assert result.paused and result.current_task_id == ids[1]
assert [entry.state for entry in result.entries] == ['completed', 'blocked']
assert code in result.entries[1].message
assert calls == [(ids[0], ('R1',)), (ids[0], ('R2',)), (ids[1], ('R1',)),
(ids[1], ('R2',)), (ids[0], ('R1',))]
path = service._logging.root / 'task-queues' / (original.queue_id + '.json')
state = json.loads(path.read_text(encoding='utf-8'))
assert state['phase'] == 'problems' and state['entries'][ids[1]]['state'] == 'blocked'
assert service.execution_problems(ids[0])[0]['state'] == 'resolved'
assert service.execution_problems(ids[1])[0]['auto_retries'] == 1
resumed = execute_task_queue(service, ids, queue_id=original.queue_id, stop_event=Event())
assert not resumed.paused and [entry.state for entry in resumed.entries] == ['completed', 'completed']
assert calls[-1] == (ids[1], ('R1',)) and len(calls) == 6
assert service.execution_problems(ids[1])[0]['auto_retries'] == 1
def reserve_then_crash(case, monkeypatch):
service, _, tasks, _, outcomes = case
task_id = tasks[0].task_id
outcomes[(task_id, ('R1',))] = ['attach_failed', 'saved_ok']
original = execute_task_queue(service, (task_id,), stop_event=Event(), defer_problem_pass=True)
with monkeypatch.context() as patch:
def crash(*_a, **_k):
raise OSError('crash after reservation')
patch.setattr(service.for_project_task(task_id), 'prepare_failed_quick_run', crash)
with pytest.raises(OSError):
execute_task_queue(service, (task_id,), queue_id=original.queue_id, stop_event=Event())
return service, task_id, original.queue_id
@pytest.mark.parametrize('reason', ['uncertain', 'round_changed', 'scope_changed'])
def test_old_problem_reservation_cannot_finish_or_dispatch_after_safety_evidence_changes(component_case, monkeypatch, reason):
service, task_id, queue_id = reserve_then_crash(component_case, monkeypatch)
_, store, _, calls, _ = component_case
if reason == 'uncertain':
root = service.for_project_task(task_id)._quick_run_preparer.data_root / 'quick-run'
(root / 'uncertain.flag').write_text('unverified write; do not replay')
else:
with store.transaction():
column, value = ('round_id', 'other-round') if reason == 'round_changed' else ('generations_json', '{"missing-operation": 1}')
store._connection.execute('UPDATE execution_problem_passes SET ' + column + '=? WHERE queue_id=? AND task_id=?',
(value, queue_id, task_id))
result = execute_task_queue(service, (task_id,), queue_id=queue_id, stop_event=Event())
assert result.paused and result.current_task_id == task_id
assert result.entries[0].state == 'blocked'
assert len(calls) == 2 and service.execution_problems(task_id)[0]['auto_retries'] == 1
state = json.loads((service._logging.root / 'task-queues' / (queue_id + '.json')).read_text(encoding='utf-8'))
assert state['phase'] == 'problems' and state['entries'][task_id]['state'] == 'blocked'
assert store._connection.execute('SELECT state FROM execution_problem_passes WHERE queue_id=?', (queue_id,)).fetchone()[0] == 'reserved'
+106
View File
@@ -0,0 +1,106 @@
"""Problem selection uses real frozen commands, SQLite and retry preparation."""
from threading import Event
import pytest
from test_nonblocking_items import component_case
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.task_queue import execute_task_queue
def fail_primary(case, refs=('R1', 'R2')):
service, store, tasks, calls, outcomes = case
task_id = tasks[0].task_id
for ref in refs:
outcomes[(task_id, (ref,))] = 'attach_failed'
execute_task_queue(service, (task_id,), stop_event=Event(), defer_problem_pass=True)
return service, task_id, service.execution_problem_overview(task_id)
def selection(overview, item):
return dict(operation_keys=(item['operation_key'],), expected_round_id=overview['round_id'],
expected_generations={item['operation_key']: item['generation']})
def test_problem_overview_exposes_uid_scope_and_shared_budget(component_case):
service, task_id, overview = fail_primary(component_case, ('R1',))
assert overview['failed'] == 1 and overview['held'] == overview['uncertain'] == 0
item, = overview['items']
assert (item['uid'], item['refdes'], item['schematic_name'], item['sheet_number']) == ('u1', 'R1', 'MAIN', '1')
assert item['can_retry'] and item['auto_retries_remaining'] == 1
service.reserve_problem_retry(task_id)
assert service.execution_problem_overview(task_id)['items'][0]['auto_retries_remaining'] == 0
def test_selected_retry_dispatches_only_selected_failed_uid(component_case):
service, task_id, overview = fail_primary(component_case)
item = overview['items'][1]
service.prepare_failed_quick_run(task_id, **selection(overview, item))
component_case[-1][(task_id, ('R2',))] = 'saved_ok'
execute_task_queue(service, (task_id,), stop_event=Event())
assert component_case[3] == [(task_id, ('R1',)), (task_id, ('R2',)), (task_id, ('R2',))]
after = service.execution_problem_overview(task_id)
assert after['failed'] == after['resolved'] == 1
assert service.reserve_problem_retry(task_id,
operation_keys=(overview['items'][0]['operation_key'],), source='dsh') == ()
@pytest.mark.parametrize('stale', ['round', 'generation'])
def test_stale_selection_cannot_reset_current_receipts(component_case, stale):
service, task_id, overview = fail_primary(component_case)
args = selection(overview, overview['items'][0])
if stale == 'round':
args['expected_round_id'] = 'old-round'
else:
args['expected_generations'] = {overview['items'][0]['operation_key']: -1}
with pytest.raises(TaskCenterError, match='problem_retry_scope'):
service.prepare_failed_quick_run(task_id, **args)
assert service.execution_problem_overview(task_id)['failed'] == 2
def test_uncertain_and_unattempted_items_are_visible_but_not_selectable(component_case):
service, store, tasks, _, outcomes = component_case
task_id = tasks[0].task_id
outcomes[(task_id, ('R1',))] = 'batch_saved_unverified'
execute_task_queue(service, (task_id,), stop_event=Event(), defer_problem_pass=True)
overview = service.execution_problem_overview(task_id)
assert overview['uncertain'] == overview['held'] == 1
assert {item['state'] for item in overview['items']} == {'uncertain', 'pending'}
assert not any(item['can_retry'] for item in overview['items'])
def test_targeted_retry_does_not_silently_include_pending_work(component_case):
service, store, tasks, _, outcomes = component_case
task_id = tasks[0].task_id
stop = Event()
outcomes[(task_id, ('R1',))] = 'batch_failed'
outcomes['after_call'] = lambda _: stop.set()
execute_task_queue(service, (task_id,), stop_event=stop, defer_problem_pass=True)
overview = service.execution_problem_overview(task_id)
assert overview['held'] == 1
item = next(item for item in overview['items'] if item['state'] == 'failed')
assert not item['can_retry']
with pytest.raises(TaskCenterError, match='problem_retry_scope'):
service.prepare_failed_quick_run(task_id, **selection(overview, item))
def test_old_crashed_problem_pass_cannot_replay_items_outside_new_selection(component_case, monkeypatch):
service, _, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
for ref in ('R1', 'R2'):
outcomes[(task_id, (ref,))] = 'attach_failed'
original = execute_task_queue(service, (task_id,), stop_event=Event(), defer_problem_pass=True)
child = service.for_project_task(task_id)
with monkeypatch.context() as patch:
def crash(*_a, **_k):
raise OSError('crash after original R1/R2 reservation')
patch.setattr(child, 'prepare_failed_quick_run', crash)
with pytest.raises(OSError):
execute_task_queue(service, (task_id,), stop_event=Event(), queue_id=original.queue_id)
overview = service.execution_problem_overview(task_id)
service.prepare_failed_quick_run(task_id, **selection(overview, overview['items'][1]))
outcomes[(task_id, ('R2',))] = 'saved_ok'
execute_task_queue(service, (task_id,), stop_event=Event())
assert calls == [(task_id, ('R1',)), (task_id, ('R2',)), (task_id, ('R2',))]
execute_task_queue(service, (task_id,), stop_event=Event(), queue_id=original.queue_id)
assert calls == [(task_id, ('R1',)), (task_id, ('R2',)), (task_id, ('R2',))]
+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']
@@ -0,0 +1,76 @@
from PySide6.QtWidgets import QMessageBox
from PySide6.QtCore import QTimer
from threading import Event
import pytest
from test_ui_remediation import window
@pytest.mark.parametrize('finish_order', ['normal', 'after_confirmation', 'during_confirmation'])
@pytest.mark.parametrize('confirmed', [False, True])
def test_confirmed_force_runs_after_cleanup_worker_finishes(window, qtbot, monkeypatch, finish_order, confirmed):
qtbot.waitUntil(lambda: not window._workers and not window._resource_status.busy)
pending = ({'state': 'blocked', 'kind': 'retained_worker', 'force_available': True},)
monkeypatch.setattr(window.service, 'pending_batch_resources', lambda: pending)
monkeypatch.setattr(window.service, 'cleanup_batch_resources', lambda: pending)
from dx_productivity.trial_task_center.ui.workers import ServiceWorker
release, prompted, event_turn = Event(), Event(), Event()
original_run = ServiceWorker.run
def gated_run(worker):
if finish_order != 'normal' and worker.action is window.service.cleanup_batch_resources:
try:
worker.signals.succeeded.emit(worker.action())
assert release.wait(5)
finally:
worker.signals.finished.emit()
else:
original_run(worker)
monkeypatch.setattr(ServiceWorker, 'run', gated_run)
calls = []
def force(*, confirmed):
calls.append(confirmed)
return ()
monkeypatch.setattr(window.service, 'force_pending_owned_resources', force)
def confirm(*_a, **_k):
prompted.set()
if finish_order == 'during_confirmation':
release.set()
qtbot.waitUntil(lambda: not window._workers)
assert calls == []
QTimer.singleShot(0, event_turn.set)
return QMessageBox.StandardButton.Yes if confirmed else QMessageBox.StandardButton.No
monkeypatch.setattr(QMessageBox, 'question', confirm)
window._resource_status.records = pending
window._resource_status.known = True
window._update_gates()
try:
window.run_panel.cleanup_resources_button.click()
qtbot.waitUntil(lambda: prompted.is_set() and event_turn.is_set())
if finish_order == 'after_confirmation':
assert calls == []
assert window._workers
release.set()
qtbot.waitUntil(lambda: not window._workers)
assert calls == ([True] if confirmed else [])
finally:
release.set()
qtbot.waitUntil(lambda: not window._workers)
def test_lost_handles_show_restart_hint_without_unusable_force_prompt(window, qtbot, monkeypatch):
qtbot.waitUntil(lambda: not window._workers and not window._resource_status.busy)
hint = '请先保存工作,重启 Windows 后重新清理,结果仍须核验。'
pending = ({'state': 'blocked', 'kind': 'retained_worker', 'force_available': False,
'resolution_hint': hint},)
monkeypatch.setattr(window.service, 'pending_batch_resources', lambda: pending)
monkeypatch.setattr(window.service, 'cleanup_batch_resources', lambda: pending)
questions = []
monkeypatch.setattr(QMessageBox, 'question', lambda *_a, **_k: questions.append(1))
window._resource_status.records = pending
window._resource_status.known = True
window._update_gates()
window.run_panel.cleanup_resources_button.click()
qtbot.waitUntil(lambda: not window._workers)
assert questions == []
assert hint in window.run_panel.operator_band.text()
@@ -0,0 +1,70 @@
import json
from uuid import uuid4
import pytest
from dx_productivity.trial_task_center import batch_resources
def orphan(root, **extra):
token = uuid4().hex
path = root / 'quick-run' / ('retained-worker-' + token + '.json')
record = dict(version=1, state='blocked', token=token, job_id='job',
process={'pid': 123, 'creation_time': 'original'}, **extra)
batch_resources.write_record(path, record)
flag = path.parent / 'uncertain.flag'
flag.write_text('business result still requires verification')
return path, flag
def test_new_worker_reconciles_only_after_verified_kernel_boot_change(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import retained_worker_recovery as recovery
before, after = str(uuid4()), str(uuid4())
path, flag = orphan(tmp_path, retained_boot_id=before)
monkeypatch.setattr(recovery, 'boot_identity', lambda: before)
assert batch_resources.cleanup_pending_resources(tmp_path)
monkeypatch.setattr(recovery, 'boot_identity', lambda: after)
assert not batch_resources.cleanup_pending_resources(tmp_path)
record = json.loads(path.read_text(encoding='utf-8'))
assert record['release_proof']['method'] == 'kernel_boot_changed'
assert record['release_proof']['previous_boot_id'] == before
assert record['release_proof']['current_boot_id'] == after
assert flag.read_text() == 'business result still requires verification'
def test_legacy_worker_is_stamped_and_requires_subsequent_boot(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import retained_worker_recovery as recovery
before = str(uuid4())
path, _ = orphan(tmp_path)
monkeypatch.setattr(recovery, 'boot_identity', lambda: before)
pending = batch_resources.cleanup_pending_resources(tmp_path)
assert pending and 'Windows' in pending[0]['resolution_hint']
record = json.loads(path.read_text(encoding='utf-8'))
assert record['first_observed_boot_id'] == before
assert batch_resources.cleanup_pending_resources(tmp_path)
monkeypatch.setattr(recovery, 'boot_identity', lambda: str(uuid4()))
assert not batch_resources.cleanup_pending_resources(tmp_path)
@pytest.mark.parametrize('invalid', ['identity_missing', 'wrong_token', 'invalid_boot', 'boot_unavailable'])
def test_incomplete_evidence_never_unlocks_resource_gate(tmp_path, monkeypatch, invalid):
from dx_productivity.trial_task_center import retained_worker_recovery as recovery
path, _ = orphan(tmp_path, retained_boot_id=str(uuid4()))
record = json.loads(path.read_text(encoding='utf-8'))
if invalid == 'identity_missing':
record.pop('process')
elif invalid == 'wrong_token':
record['token'] = uuid4().hex
elif invalid == 'invalid_boot':
record['retained_boot_id'] = 'corrupt'
batch_resources.write_record(path, record)
monkeypatch.setattr(recovery, 'boot_identity', lambda: None if invalid == 'boot_unavailable' else str(uuid4()))
assert batch_resources.cleanup_pending_resources(tmp_path)
assert json.loads(path.read_text(encoding='utf-8'))['state'] == 'blocked'
def test_native_boot_observation_is_stable_and_nonzero():
from dx_productivity.trial_task_center.retained_worker_recovery import boot_identity
from uuid import UUID
first = boot_identity()
assert UUID(first).int and boot_identity() == first
+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)
+128
View File
@@ -0,0 +1,128 @@
import json
from pathlib import Path
import subprocess
import sys
from threading import Event
import pytest
from test_nonblocking_items import component_case
from test_batch_runtime import command_for, worker_runtime, Desktop
from dx_productivity.trial_task_center import worker_monitor
from dx_productivity.trial_task_center.task_queue import execute_task_queue
def confirmed_timeout():
error = worker_monitor.WorkerMonitorSafeTimeout('controlled open timeout', stage='open_project')
error.prewrite_cleanup_confirmed = True
return error
def test_real_monitor_certifies_open_timeout_only_after_worker_exit(tmp_path):
script = tmp_path / 'open_timeout.py'
script.write_text("import sys,time\nprint('DX_PROGRESS\\t'+sys.argv[-1]+'\\t'+sys.argv[-2]+'\\t1\\topen_project\\t0\\t1\\t1',flush=True)\ntime.sleep(30)\n")
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, 'job')
with pytest.raises(worker_monitor.WorkerMonitorSafeTimeout) as caught:
worker_monitor.run_monitored_process(command, 1)
assert caught.value.prewrite_cleanup_confirmed
assert not worker_monitor.RETAINED_WORKERS
def test_runtime_releases_safe_timeout_without_inline_replay(tmp_path, monkeypatch):
command, _ = command_for(tmp_path)
calls = []
def monitor(*_a, **_k):
calls.append(1)
raise confirmed_timeout()
runtime = worker_runtime(tmp_path, monkeypatch, monitor)
with runtime:
with pytest.raises(worker_monitor.WorkerMonitorSafeTimeout):
runtime.run_worker(command, 5)
assert runtime.desktop is runtime.cad is None
assert len(calls) == 1 and len(Desktop.created) == 1
assert json.loads(runtime.path.read_text())['state'] == 'released'
def test_safe_timeout_runs_independent_uid_then_one_problem_retry(component_case):
service, _, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
preparer = service.for_project_task(task_id)._quick_run_preparer
original = preparer._process_runner
attempts = []
def worker(command, timeout):
attempts.append(command[-1])
if len(attempts) == 1:
raise confirmed_timeout()
return original(command, timeout)
preparer._process_runner = worker
result = execute_task_queue(service, (task_id,), stop_event=Event())
assert not result.paused
assert len(attempts) == 3
assert calls == [(task_id, ('R2',)), (task_id, ('R1',))]
issue, = service.execution_problems(task_id)
assert issue['state'] == 'resolved' and issue['auto_retries'] == 1
assert issue['code'] == 'worker_timeout_before_write'
@pytest.mark.parametrize('unsafe', ['unconfirmed', 'changed_status', 'changed_source', 'changed_command', 'wrong_stage', 'cancelled'])
def test_timeout_without_complete_proof_stays_uncertain(component_case, unsafe):
service, _, tasks, calls, _ = component_case
task_id = tasks[0].task_id
preparer = service.for_project_task(task_id)._quick_run_preparer
stop = Event()
def worker(command, timeout):
error = confirmed_timeout()
if unsafe == 'unconfirmed':
error.prewrite_cleanup_confirmed = False
elif unsafe == 'wrong_stage':
error.stage = 'native_replace'
elif unsafe == 'changed_status':
with (Path(command[3]) / 'status.tsv').open('a', encoding='utf-8') as stream:
stream.write(f'{command[-1]}\tawaiting_native_replace\t\twrite possible\n')
elif unsafe == 'changed_source':
service.projects(task_id)[0].path.write_text('changed while worker was running')
elif unsafe == 'changed_command':
with (Path(command[3]) / 'current-command.tsv').open('a', encoding='utf-8') as stream:
stream.write('changed command scope')
elif unsafe == 'cancelled':
stop.set()
raise error
preparer._process_runner = worker
result = execute_task_queue(service, (task_id,), stop_event=stop)
assert result.paused
assert calls == []
assert service.reserve_problem_retry(task_id) == ()
assert preparer.has_interrupted(task_id)
assert not any(issue['classification'] == 'retryable' for issue in service.execution_problems(task_id))
def test_repeated_safe_timeout_spends_only_one_shared_retry(component_case):
service, _, tasks, calls, _ = component_case
task_id = tasks[0].task_id
preparer = service.for_project_task(task_id)._quick_run_preparer
attempts = []
def worker(command, timeout):
attempts.append(command[-1])
raise confirmed_timeout()
preparer._process_runner = worker
result = execute_task_queue(service, (task_id,), stop_event=Event())
assert not result.paused and len(attempts) == 4
assert [issue['auto_retries'] for issue in service.execution_problems(task_id)] == [1, 1]
assert service.reserve_problem_retry(task_id, source='dsh') == ()
execute_task_queue(service, (task_id,), stop_event=Event(), queue_id=result.queue_id)
assert len(attempts) == 4
def test_delivered_safe_timeout_allows_session_scope_to_prepare_next_worker(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import project_session
def monitor(*_a, **_k):
raise confirmed_timeout()
monkeypatch.setattr(project_session, 'run_monitored_process', monitor)
command = ('cscript', '', '', str(tmp_path), 'python', 'job')
project = tmp_path / 'board.prj'
with project_session.ProjectSessionScope(None, enabled=True) as scope:
with pytest.raises(worker_monitor.WorkerMonitorSafeTimeout):
scope.run_step(project, command, 1)
assert scope.worker._failure_delivered
scope.prepare(project)
assert scope.worker is None
+73 -10
View File
@@ -36,6 +36,7 @@ def test_unsafe_save_timeout_waits_for_completion_and_recovers_on_progress():
def test_real_slow_save_is_not_killed_by_inactivity(tmp_path, started_worker_watch):
from dx_productivity.trial_task_center.stop_control import StopControl
script = tmp_path / 'save.py'
script.write_text('''import sys,time,pathlib
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
@@ -45,12 +46,63 @@ time.sleep(1.5)
(root/'saved.txt').write_text('saved and independently verified')
''', encoding='utf-8')
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
result = run_monitored_process(command, .3)
result = run_monitored_process(command, .3, force_control=StopControl())
assert result.returncode == 0
assert 'save_and_close' in started_worker_watch
assert (tmp_path / 'saved.txt').read_text() == 'saved and independently verified'
def test_noninteractive_unsafe_save_retains_owner_until_natural_exit(tmp_path, monkeypatch, started_worker_watch):
import time
from uuid import uuid4
from dx_productivity.trial_task_center import batch_resources, worker_monitor
from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop
script = tmp_path / 'save.py'
script.write_text('''import sys,time,pathlib
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
while not (root/f'monitor-{token}.ready').exists():time.sleep(.01)
print(f'DX_PROGRESS\\t{token}\\t{job}\\t1\\tsave_and_close\\t0\\t1\\t0',flush=True)
while not (root/'allow-exit').exists():time.sleep(.01)
(root/'saved.txt').write_text('naturally completed')
''', encoding='utf-8')
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
processes = []
with PrivateDesktop('dx-' + uuid4().hex, enabled=True) as desktop:
def launch(command, **options):
process = desktop.start_process(command, **options)
processes.append(process)
return process
monkeypatch.setattr(worker_monitor._OwnedWorkers, 'stop_workers',
lambda *_: pytest.fail('unsafe save must not be killed'))
try:
with pytest.raises(worker_monitor.WorkerMonitorError, match='owned worker retained'):
run_monitored_process(command, .3, process_factory=launch)
assert len(processes) == 1 and processes[0].poll() is None
assert 'save_and_close' in started_worker_watch
retained = next(tmp_path.glob('retained-worker-*.json'))
assert json.loads(retained.read_text())['state'] == 'blocked'
assert (tmp_path / 'uncertain.flag').exists()
assert batch_resources.cleanup_pending_resources(tmp_path)
assert processes[0].poll() is None and len(processes) == 1
(tmp_path / 'allow-exit').touch()
assert processes[0].wait(timeout=5) == 0
deadline = time.monotonic() + 5
while not processes[0].tree_exited():
assert time.monotonic() < deadline
time.sleep(.01)
assert batch_resources.cleanup_pending_resources(tmp_path) == ()
assert json.loads(retained.read_text())['state'] == 'released'
assert not processes[0].cleanup_record['forced_termination']
assert (tmp_path / 'saved.txt').read_text() == 'naturally completed'
assert (tmp_path / 'uncertain.flag').exists() and len(processes) == 1
finally:
(tmp_path / 'allow-exit').touch()
for process in processes:
process.wait(timeout=5)
worker_monitor.cleanup_retained_workers(tmp_path)
assert desktop.cleanup_record['desktop_confirmation']['released']
def test_readonly_native_wait_keeps_bounded_cancellation_without_force_ui(tmp_path, started_worker_watch):
script = tmp_path / 'read.py'
script.write_text('''import sys,time,pathlib
@@ -196,7 +248,7 @@ def test_interruption_targets_active_project_without_invalidating_previous_tasks
@pytest.mark.parametrize('interactive', [False, True])
def test_supervisor_only_holds_for_resolution_when_caller_has_force_control(tmp_path, monkeypatch, interactive):
def test_supervisor_preserves_caller_interactivity_and_always_owns_stop_control(tmp_path, monkeypatch, interactive):
import textwrap
from dx_productivity.trial_task_center import batch_supervisor as module
from dx_productivity.trial_task_center.stop_control import StopControl
@@ -211,7 +263,10 @@ def test_supervisor_only_holds_for_resolution_when_caller_has_force_control(tmp_
original=batch_runtime.BatchCadRuntime
def runtime(*args,**kwargs):
result=original(*args,**kwargs)
Path(sys.argv[1]).with_name('interactive-witness.json').write_text(json.dumps(isinstance(result.stop_event,StopControl)))
request = json.loads(Path(sys.argv[1]).read_text())
Path(sys.argv[1]).with_name('interactive-witness.json').write_text(json.dumps({
'request_interactive_stop': request['interactive_stop'],
'internal_stop_control': isinstance(result.stop_event,StopControl)}))
return result
batch_runtime.BatchCadRuntime=runtime
batch_worker.run(Path(sys.argv[1]))
@@ -222,7 +277,9 @@ def test_supervisor_only_holds_for_resolution_when_caller_has_force_control(tmp_
service = TaskCenterService(store, configure_logging(tmp_path))
module.run_supervised(service, 'probe', {}, stop_event=StopControl() if interactive else Event())
witness = next((tmp_path / 'batch-resources').glob('*/interactive-witness.json'))
assert json.loads(witness.read_text()) is interactive
observed = json.loads(witness.read_text())
assert observed['request_interactive_stop'] is interactive
assert observed['internal_stop_control'] is True
finally:
store.close()
@@ -300,11 +357,12 @@ def test_failed_protection_fsync_is_retried_before_force_is_allowed(tmp_path, mo
thread.join(3)
@pytest.mark.parametrize('deny_first,transport_failure,cleanup_failure,late_write_failure', [
(False, False, False, False), (True, False, False, False), (False, True, False, False),
(False, False, True, False), (False, False, False, True), (False, False, True, True)])
@pytest.mark.parametrize('deny_first,transport_failure,cleanup_failure,late_write_failure,slow_witness', [
(False, False, False, False, False), (True, False, False, False, False), (False, True, False, False, False),
(False, False, True, False, False), (False, False, False, True, False), (False, False, True, True, False),
(False, False, False, False, True)])
def test_real_supervisor_force_preserves_protection_and_never_replays(
tmp_path, monkeypatch, deny_first, transport_failure, cleanup_failure, late_write_failure):
tmp_path, monkeypatch, deny_first, transport_failure, cleanup_failure, late_write_failure, slow_witness):
import os
import textwrap
import time
@@ -329,7 +387,11 @@ def test_real_supervisor_force_preserves_protection_and_never_replays(
def business(self, task_id, **kwargs):
root=self._project_task_service(task_id)._quick_run_preparer.data_root/'quick-run'
root.mkdir(parents=True,exist_ok=True)
(root/'started').write_text(str(os.getpid()))
with (root/'started.tmp').open('w') as stream:
if sys.argv[2] == 'slow':
time.sleep(.2)
stream.write(str(os.getpid()))
(root/'started.tmp').replace(root/'started')
request=json.loads(Path(sys.argv[1]).read_text(encoding='utf-8'))
print(json.dumps({'version':1,'batch_id':request['batch_id'],'attempt_id':request['attempt_id'],
'generation':1,'sequence':100,'type':'progress','payload':'fixture executing'}),flush=True)
@@ -340,7 +402,7 @@ def test_real_supervisor_force_preserves_protection_and_never_replays(
''')
original_command = module._command
monkeypatch.setattr(module, '_command', lambda request:
(sys.executable, '-c', bootstrap, str(request))
(sys.executable, '-c', bootstrap, str(request), 'slow' if slow_witness else 'normal')
if json.loads(request.read_text())['operation'] == 'execute_quick_run' else original_command(request))
original_mark = module._mark_interrupted
denied = []
@@ -402,6 +464,7 @@ def test_real_supervisor_force_preserves_protection_and_never_replays(
control.request_force()
except Exception as error:
driver_errors.append(error)
control.request_force()
thread = Thread(target=request)
thread.start()
try:
+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)
@@ -0,0 +1,168 @@
"""An exited root is insufficient; use the existing cleanup budget for its tree."""
import io
import os
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import worker_monitor
@pytest.mark.parametrize('exit_after', [0, .03, None])
@pytest.mark.parametrize('returncode', [0, 7])
@pytest.mark.parametrize('tree_witness', ['monitor', 'native_adapter'])
def test_normal_completion_waits_for_tree_exit_without_killing_or_replaying(tmp_path, monkeypatch, exit_after, returncode, tree_witness):
clock = SimpleNamespace(now=0.0)
monkeypatch.setattr(worker_monitor, 'time', SimpleNamespace(monotonic=lambda: clock.now,
sleep=lambda delay: setattr(clock, 'now', clock.now + delay)))
process = SimpleNamespace(pid=123, returncode=returncode, stdout=io.BytesIO(b'real receipt\n'),
stderr=io.BytesIO(), closed=False)
process.poll = lambda: process.returncode
process.close = lambda: setattr(process, 'closed', True)
def tree_confirmed():
return owners[0].allow_exit or exit_after is not None and clock.now >= exit_after
process.tree_exited = tree_confirmed if tree_witness == 'native_adapter' else lambda: True
class Owned:
def __init__(self, *_args):
self.closed = self.allow_exit = False
owners.append(self)
def tree_exited(self):
return tree_confirmed() if tree_witness == 'monitor' else True
def stop_workers(self, _process):
pytest.fail('observing a normal exit must not terminate a worker')
def close(self):
self.closed = True
owners, launches = [], []
def launch(*_args, **_kwargs):
launches.append(1)
return process
monkeypatch.setattr(worker_monitor, '_OwnedWorkers', Owned)
try:
if exit_after is None:
with pytest.raises(worker_monitor.WorkerMonitorError, match='owned worker retained'):
worker_monitor.run_monitored_process(('worker', '', '', str(tmp_path), 'python', 'job'), 1,
process_factory=launch)
assert 10 <= clock.now <= 10.02
assert not owners[0].closed and not process.closed
assert (tmp_path / 'uncertain.flag').exists()
assert any(entry['process'] is process for entry in worker_monitor.RETAINED_WORKERS.values())
else:
result = worker_monitor.run_monitored_process(('worker', '', '', str(tmp_path), 'python', 'job'), 1,
process_factory=launch)
assert result.returncode == returncode and result.stdout == 'real receipt\n'
assert exit_after <= clock.now <= exit_after + .02
assert owners[0].closed and process.closed
assert not (tmp_path / 'uncertain.flag').exists()
assert launches == [1]
finally:
owners[0].allow_exit = True
worker_monitor.cleanup_retained_workers(tmp_path)
assert not any(entry['process'] is process for entry in worker_monitor.RETAINED_WORKERS.values())
@pytest.mark.parametrize('descendants_exit', [True, False])
def test_safe_timeout_waits_for_positive_tree_exit_without_extending_cleanup_budget(tmp_path, monkeypatch, descendants_exit):
clock = SimpleNamespace(now=0.0)
def monotonic():
clock.now += .01
return clock.now
monkeypatch.setattr(worker_monitor, 'time', SimpleNamespace(monotonic=monotonic,
sleep=lambda delay: setattr(clock, 'now', clock.now + delay)))
process = SimpleNamespace(pid=123, returncode=None, stdout=io.BytesIO(), stderr=io.BytesIO(), closed=False)
process.poll = lambda: process.returncode
process.close = lambda: setattr(process, 'closed', True)
process.wait = lambda timeout: process.returncode
class Owned:
def __init__(self, *_args):
self.closed, self.observations, self.cleanup_started, self.exited = False, 0, None, False
owners.append(self)
def tree_exited(self):
self.observations += 1
return self.exited or descendants_exit and self.observations >= 4
def stop_workers(self, _process):
self.cleanup_started = clock.now
process.returncode = 1
return ['preserved_non_worker pid=456']
def close(self):
self.closed = True
class StalledOpen(worker_monitor.ProgressWatch):
def __init__(self, *args):
super().__init__(*args)
self.stage = 'open_project'
def action(self, _now):
return 'unresponsive'
owners = []
monkeypatch.setattr(worker_monitor, '_OwnedWorkers', Owned)
monkeypatch.setattr(worker_monitor, 'ProgressWatch', StalledOpen)
try:
expected = worker_monitor.WorkerMonitorSafeTimeout if descendants_exit else worker_monitor.WorkerMonitorError
with pytest.raises(expected) as caught:
worker_monitor.run_monitored_process(('worker', '', '', str(tmp_path), 'python', 'job'), 1,
process_factory=lambda *_a, **_k: process)
if descendants_exit:
assert caught.value.prewrite_cleanup_confirmed
assert owners[0].observations >= 4 and owners[0].closed and process.closed
else:
assert not getattr(caught.value, 'prewrite_cleanup_confirmed', False)
assert any(entry['process'] is process for entry in worker_monitor.RETAINED_WORKERS.values())
assert not owners[0].closed and not process.closed
assert clock.now - owners[0].cleanup_started <= 10.2
finally:
owners[0].exited = True
worker_monitor.cleanup_retained_workers(tmp_path)
@pytest.mark.skipif(os.name != 'nt', reason='Win32 vanished PID observation')
def test_child_that_exits_during_job_enumeration_is_not_a_cleanup_failure(monkeypatch):
import pywintypes
import win32api
import win32job
owned = worker_monitor._OwnedWorkers.__new__(worker_monitor._OwnedWorkers)
owned.job, owned.allowed = object(), set()
monkeypatch.setattr(win32job, 'QueryInformationJobObject', lambda *_: (1, 2))
def vanished(*_args):
raise pywintypes.error(87, 'OpenProcess', 'process already exited')
monkeypatch.setattr(win32api, 'OpenProcess', vanished)
process = SimpleNamespace(pid=1, poll=lambda: 0)
assert owned.stop_workers(process) == []
@pytest.mark.skipif(os.name != 'nt', reason='Win32 pre-handle exception classification')
@pytest.mark.parametrize('error', [ValueError(87), OSError(87, 'not a Windows error'),
OSError(5, 'denied')])
def test_non_windows_error_87_is_not_mistaken_for_a_vanished_pid(monkeypatch, error):
import win32api
import win32job
owned = worker_monitor._OwnedWorkers.__new__(worker_monitor._OwnedWorkers)
owned.job, owned.allowed = object(), set()
monkeypatch.setattr(win32job, 'QueryInformationJobObject', lambda *_: (1, 2))
def failed(*_args):
raise error
monkeypatch.setattr(win32api, 'OpenProcess', failed)
notes = owned.stop_workers(SimpleNamespace(pid=1, poll=lambda: 0))
assert len(notes) == 1 and notes[0].startswith('child_cleanup pid=2')
@pytest.mark.skipif(os.name != 'nt', reason='Win32 post-open cleanup error')
def test_error_87_after_opening_child_remains_a_cleanup_failure(monkeypatch):
import ctypes
import win32api
import win32job
owned = worker_monitor._OwnedWorkers.__new__(worker_monitor._OwnedWorkers)
owned.job, owned.allowed = object(), set()
monkeypatch.setattr(win32job, 'QueryInformationJobObject', lambda *_: (1, 2))
closed = []
class Handle:
def __int__(self):
return 2
def Close(self):
closed.append(True)
monkeypatch.setattr(win32api, 'OpenProcess', lambda *_: Handle())
def failed_image_query(*_args):
ctypes.set_last_error(87)
return 0
monkeypatch.setattr(worker_monitor.ctypes, 'WinDLL', lambda *_a, **_k:
SimpleNamespace(QueryFullProcessImageNameW=failed_image_query))
notes = owned.stop_workers(SimpleNamespace(pid=1, poll=lambda: 0))
assert len(notes) == 1 and notes[0].startswith('child_cleanup pid=2')
assert closed == [True]
+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]