fix: address PR27 lifecycle, BOM and netlist review findings
Core regression / Python core, intervention UI and release configuration (push) Failing after 4m4s
Core regression / JavaScript syntax (push) Successful in 5s
Core regression / Python core, intervention UI and release configuration (pull_request) Failing after 4m20s
Core regression / JavaScript syntax (pull_request) Successful in 4s

This commit is contained in:
阿白叔 committed 2026-11-13 16:03:59 +08:00
1 parent 0ee83e77e2
commit f9d5e56bb8
58 files changed
+20646 -164

No files matched your search

+307
View File
@@ -0,0 +1,307 @@
"""Ordinary I/O failures close only their bound execution attempt."""
import json
import sqlite3
from threading import Event
import pytest
from dx_productivity.dsh.execution_runs import execute_confirmed_run, execute_incident_retry
from dx_productivity.dsh.run_journal import RunJournal
from dx_productivity.dsh.scheduling import ScheduleStore
from dx_productivity.dsh.task_lifecycle import preflight
from dx_productivity.trial_task_center import task_queue
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.task_queue import TaskQueueResult, TaskQueueEntry
from test_run_journal import project_service, checkpoint
from test_incident_rule_retry import rule_run
def fail(message):
raise OSError(message)
def test_resume_checkpoint_repair_failure_closes_durable_run(project_service, monkeypatch):
service, _, data, ids, hashes = project_service
run_id = 'a' * 32
journal = RunJournal(data)
journal.begin(run_id, ids, hashes)
checkpoint(data, run_id, ids, hashes)
prior = {'status': 'paused', 'tasks': [], 'entries': [
{'task_id': key, 'state': 'pending', 'message': ''} for key in ids]}
journal.finish(run_id, prior)
resume = journal.inspect(service, run_id)
monkeypatch.setattr(RunJournal, 'repair_retry_checkpoint', lambda *args: fail('repair failed'))
with pytest.raises(OSError, match='repair failed'):
execute_confirmed_run(service, data, ids, preflight(service, ids), Event(), run_id, resume=resume)
row = RunJournal(data).get(run_id)
assert row['status'] == 'interrupted'
assert row['result']['entries'] == prior['entries']
assert row['result']['tasks'] == prior['tasks']
@pytest.mark.parametrize('rebound', [False, True])
@pytest.mark.parametrize('boundary', ['inspect', 'bound'])
def test_scheduled_resume_inspection_failure_closes_only_bound_claim(project_service, monkeypatch, rebound, boundary):
service, _, data, ids, hashes = project_service
run_id = 'b' * 32
schedules = ScheduleStore(data)
schedule = schedules.save({'task_ids': ids, 'priority': 'normal',
'not_before': '2026-01-01T00:00:00+00:00'}, hashes)
schedules.claim(schedule['schedule_id'], run_id=run_id)
journal = RunJournal(data)
journal.begin(run_id, ids, hashes, schedule_id=schedule['schedule_id'])
checkpoint(data, run_id, ids, hashes)
journal.finish(run_id, {'status': 'paused', 'entries': []})
resume = journal.inspect(service, run_id)
if rebound:
with schedules._connect() as db:
db.execute('UPDATE schedules SET run_id=? WHERE schedule_id=?', ('c' * 32, schedule['schedule_id']))
if boundary == 'inspect':
monkeypatch.setattr(RunJournal, 'inspect', lambda *args: fail('inspection failed'))
else:
from dx_productivity.dsh import execution_runs
bound, calls = execution_runs._bound_schedule, []
def unavailable_once(*args):
calls.append(True)
if len(calls) == 1:
fail('binding read failed')
return bound(*args)
monkeypatch.setattr(execution_runs, '_bound_schedule', unavailable_once)
with pytest.raises(TaskCenterError if rebound else OSError):
execute_confirmed_run(service, data, ids, preflight(service, ids), Event(), run_id, resume=resume)
row = schedules.get(schedule['schedule_id'])
assert row['status'] == ('claimed' if rebound else 'interrupted')
assert row['run_id'] == ('c' * 32 if rebound else run_id)
@pytest.mark.parametrize('boundary', ['checkpoint_before', 'execute', 'checkpoint_after', 'finish'])
@pytest.mark.parametrize('scheduled', [False, True])
def test_retry_io_failure_preserves_bound_evidence_and_never_replays(rule_run, monkeypatch, boundary, scheduled):
case = rule_run(scheduled=scheduled)
service, task_id, run_id, root = (case[key] for key in ('service', 'task_id', 'run_id', 'root'))
selected = service.reserve_problem_retry(task_id, source='dsh')
service.prepare_failed_quick_run(task_id, operation_keys=selected)
prepared = service.task_context(task_id)
p = prepared.progress
expected_item = (str(p.next_project_path), p.next_old_part_number, p.next_new_part_number,
'part_label' if prepared.task.copy_part_number_to_value else 'preserve')
journal = RunJournal(root)
old = journal.get(run_id)['result']
save, finish = task_queue._save, RunJournal.finish
if boundary == 'execute':
monkeypatch.setattr(service, 'execute_quick_run_queue', lambda *args, **kwargs: fail('retry boundary'))
elif boundary.startswith('checkpoint'):
def broken_save(path, state):
expected = 'running' if boundary == 'checkpoint_before' else 'completed'
if state['entries'][task_id]['state'] == expected:
fail('retry boundary')
return save(path, state)
monkeypatch.setattr(task_queue, '_save', broken_save)
else:
def broken_finish(self, key, receipt):
if receipt.get('execution_status') == 'completed':
fail('retry boundary')
return finish(self, key, receipt)
monkeypatch.setattr(RunJournal, 'finish', broken_finish)
with pytest.raises(OSError, match='retry boundary'):
execute_incident_retry(service, root, task_id, run_id, expected_item=expected_item,
operation_keys=selected, stop_event=Event())
row = RunJournal(root).get(run_id)
assert row['status'] == 'interrupted'
assert row['task_ids'] == [task_id] and row['run_id'] == run_id
assert row['result']['retry']['operation_keys'] == sorted(selected)
assert row['result']['netlist_verification'] == old['netlist_verification']
assert row['result']['tasks'][0]['saved_items'] >= old['tasks'][0]['saved_items']
expected_calls = ['OLD-OK', 'OLD-BAD'] + (['OLD-BAD'] if boundary in {'checkpoint_after', 'finish'} else [])
assert case['calls'] == expected_calls
if boundary in {'checkpoint_after', 'finish'}:
assert row['result']['tasks'][0]['saved_items'] == 2
if scheduled:
schedule = ScheduleStore(root).get(case['schedule']['schedule_id'])
assert schedule['status'] == 'interrupted' and schedule['run_id'] == run_id
assert service.reserve_problem_retry(task_id, source='dsh') == ()
assert case['calls'] == expected_calls
if boundary in {'checkpoint_after', 'finish'}:
monkeypatch.setattr(task_queue, '_save', save)
monkeypatch.setattr(RunJournal, 'finish', finish)
resumed = execute_confirmed_run(service, root, [task_id],
preflight(service, [task_id], allow_completed=True), Event(), run_id,
resume=RunJournal(root).inspect(service, run_id))
assert resumed['status'] == 'completed'
assert case['calls'] == expected_calls, 'A saved retry may finalize but never dispatch again'
@pytest.mark.parametrize('failed_write', [1, 2])
@pytest.mark.parametrize('scheduled', [False, True])
def test_final_receipt_write_failure_is_durable_and_propagates(project_service, monkeypatch, failed_write, scheduled):
service, _, data, ids, hashes = project_service
run_id = 'd' * 32
schedule = ScheduleStore(data).save({'task_ids': ids, 'priority': 'normal',
'not_before': '2026-01-01T00:00:00+00:00'}, hashes) if scheduled else None
monkeypatch.setattr('dx_productivity.dsh.execution_runs.execute_task_queue', lambda *a, **kw:
TaskQueueResult(run_id, tuple(TaskQueueEntry(key, 'completed') for key in ids), False))
finish = RunJournal.finish
calls = 0
def broken_finish(self, key, receipt):
nonlocal calls
calls += 1
if calls == failed_write:
fail('receipt boundary')
return finish(self, key, receipt)
monkeypatch.setattr(RunJournal, 'finish', broken_finish)
with pytest.raises(OSError, match='receipt boundary'):
execute_confirmed_run(service, data, ids, preflight(service, ids), Event(), run_id, schedule=schedule)
row = RunJournal(data).get(run_id)
assert row['status'] == 'interrupted'
assert [entry['state'] for entry in row['result']['entries']] == ['completed'] * len(ids)
assert row['result']['code'] == 'receipt_write_error'
if scheduled:
after = ScheduleStore(data).get(schedule['schedule_id'])
assert after['status'] == 'interrupted' and after['run_id'] == run_id
@pytest.mark.parametrize('damage', ['scope', 'unknown'])
def test_saved_retry_with_changed_scope_or_unknown_proof_records_observation_without_replay(rule_run, monkeypatch, damage):
case = rule_run(scheduled=True)
service, task_id, run_id, root = (case[key] for key in ('service', 'task_id', 'run_id', 'root'))
selected = service.reserve_problem_retry(task_id, source='dsh')
service.prepare_failed_quick_run(task_id, operation_keys=selected)
prepared = service.task_context(task_id)
p = prepared.progress
expected = (str(p.next_project_path), p.next_old_part_number, p.next_new_part_number,
'part_label' if prepared.task.copy_part_number_to_value else 'preserve')
execute = service.execute_quick_run_queue
path = root / 'task-queues' / (run_id + '.json')
def damage_after_save(*args, **kwargs):
outcome = execute(*args, **kwargs)
assert service.task_context(task_id).progress.saved_items == 2
if damage == 'scope':
state = json.loads(path.read_text(encoding='utf-8'))
state['task_ids'] = ['f' * 32]
path.write_text(json.dumps(state), encoding='utf-8')
else:
case['store']._connection.execute('UPDATE execution_operations SET state=? WHERE operation_key=?',
('uncertain', selected[0]))
fail('saved outcome now uncertain')
return outcome
monkeypatch.setattr(service, 'execute_quick_run_queue', damage_after_save)
with pytest.raises((TaskCenterError, OSError)):
execute_incident_retry(service, root, task_id, run_id, expected_item=expected,
operation_keys=selected, stop_event=Event())
journal = RunJournal(root)
row = journal.get(run_id)
assert row['status'] == 'interrupted'
assert row['result']['tasks'][0]['saved_items'] == 1, 'Unsafe evidence cannot replace the authorized baseline'
if damage == 'scope':
assert row['result']['retry_observation']['saved_items'] == 2
assert row['result']['retry_observation']['task_id'] == task_id
inspected = journal.inspect(service, run_id)
assert not inspected['resume_ready']
with pytest.raises(TaskCenterError):
execute_confirmed_run(service, root, [task_id], preflight(service, [task_id], allow_completed=True),
Event(), run_id, resume=inspected)
assert case['calls'] == ['OLD-OK', 'OLD-BAD', 'OLD-BAD']
schedule = ScheduleStore(root).get(case['schedule']['schedule_id'])
assert schedule['status'] == 'interrupted' and schedule['run_id'] == run_id
def test_scheduled_resume_terminal_publication_failure_closes_claim(project_service, monkeypatch):
service, _, data, ids, hashes = project_service
run_id = 'e' * 32
schedules = ScheduleStore(data)
schedule = schedules.save({'task_ids': ids, 'priority': 'normal',
'not_before': '2026-01-01T00:00:00+00:00'}, hashes)
schedules.claim(schedule['schedule_id'], run_id=run_id)
journal = RunJournal(data)
journal.begin(run_id, ids, hashes, schedule_id=schedule['schedule_id'])
checkpoint(data, run_id, ids, hashes)
journal.finish(run_id, {'status': 'paused', 'entries': []})
resume = journal.inspect(service, run_id)
monkeypatch.setattr('dx_productivity.dsh.execution_runs.execute_task_queue', lambda *a, **kw:
TaskQueueResult(run_id, tuple(TaskQueueEntry(key, 'completed') for key in ids), False))
finish, calls = ScheduleStore.finish, []
def broken_once(self, *args, **kwargs):
calls.append(True)
if len(calls) == 1:
fail('schedule publication failed')
return finish(self, *args, **kwargs)
monkeypatch.setattr(ScheduleStore, 'finish', broken_once)
with pytest.raises(OSError, match='schedule publication failed'):
execute_confirmed_run(service, data, ids, preflight(service, ids), Event(), run_id, resume=resume)
after = schedules.get(schedule['schedule_id'])
assert after['status'] == 'interrupted' and after['run_id'] == run_id
assert journal.get(run_id)['status'] == 'completed', 'Known executor receipt stays durable'
@pytest.mark.parametrize('operation', ['begin', 'resume', 'finish'])
@pytest.mark.parametrize('error_type', [OSError, sqlite3.OperationalError])
def test_running_producer_returns_committed_record_without_fallible_tail_read(project_service, monkeypatch, operation, error_type):
_, _, data, ids, hashes = project_service
run_id = '1' * 32
journal = RunJournal(data)
if operation in {'resume', 'finish'}:
journal.begin(run_id, ids, hashes)
if operation == 'resume':
journal.finish(run_id, {'status': 'paused', 'entries': []})
read, failures = RunJournal.get, []
def unavailable_once(self, key):
row = read(self, key)
if row and row['status'] == ('completed' if operation == 'finish' else 'running') and not failures:
failures.append(True)
raise error_type('post-commit read unavailable')
return row
monkeypatch.setattr(RunJournal, 'get', unavailable_once)
returned = (journal.begin(run_id, ids, hashes) if operation == 'begin' else journal.resume(run_id)
if operation == 'resume' else journal.finish(run_id, {'status': 'completed', 'entries': []}))
assert returned == read(RunJournal(data), run_id)
assert returned['status'] == ('completed' if operation == 'finish' else 'running')
assert not failures, 'A committed mutation must not need a second connection/read to acknowledge it'
@pytest.mark.parametrize('error_type', [OSError, sqlite3.OperationalError])
def test_retry_producer_returns_real_intent_without_post_commit_read(rule_run, monkeypatch, error_type):
case = rule_run()
service, task_id, run_id, root = (case[key] for key in ('service', 'task_id', 'run_id', 'root'))
selected = service.reserve_problem_retry(task_id, source='dsh')
service.prepare_failed_quick_run(task_id, operation_keys=selected)
read, failures = RunJournal.get, []
def unavailable_once(self, key):
row = read(self, key)
if row and row['status'] == 'running' and not failures:
failures.append(True)
raise error_type('post-commit retry read unavailable')
return row
monkeypatch.setattr(RunJournal, 'get', unavailable_once)
returned = RunJournal(root).begin_retry(service, run_id, task_id, selected)
assert returned == read(RunJournal(root), run_id)
assert returned['status'] == 'running' and returned['result']['retry']['operation_keys'] == sorted(selected)
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
assert not failures
@pytest.mark.parametrize('error_type', [OSError, sqlite3.OperationalError])
def test_post_execution_read_failure_cannot_lose_known_outcome(project_service, monkeypatch, error_type):
service, _, data, ids, _ = project_service
run_id = '2' * 32
report = {ids[0]: {'status': 'verified', 'verified': True, 'report_path': 'known-save.json'}}
read, failures, executed = RunJournal.get, [], []
def executor(*args, **kwargs):
executed.append(True)
return TaskQueueResult(run_id, tuple(TaskQueueEntry(key, 'completed') for key in ids), False,
netlist_verification=report)
def unavailable_once(self, key):
if executed and not failures:
failures.append(True)
raise error_type('post-execution read unavailable')
return read(self, key)
monkeypatch.setattr('dx_productivity.dsh.execution_runs.execute_task_queue', executor)
monkeypatch.setattr(RunJournal, 'get', unavailable_once)
try:
receipt = execute_confirmed_run(service, data, ids, preflight(service, ids), Event(), run_id)
except (OSError, sqlite3.OperationalError):
receipt = read(RunJournal(data), run_id)['result']
row = read(RunJournal(data), run_id)
assert row['status'] in {'completed', 'interrupted'}
assert [entry['state'] for entry in row['result']['entries']] == ['completed'] * len(ids)
assert row['result']['netlist_verification'] == report
assert len(executed) == 1
+5 -4
View File
@@ -126,10 +126,11 @@ def test_receipt_enrichment_failure_does_not_erase_executor_result(ui, monkeypat
return original(self, run_id, receipt)
monkeypatch.setattr(RunJournal, 'finish', fail_enrichment)
ids = [ui.tasks[0].task_id]
receipt = execute_confirmed_run(ui.service, ui.data, ids, api.preflight(ui.service, ids), Event(), 'f' * 32)
assert receipt['status'] == 'completed'
assert receipt['reporting_errors'][0]['code'] == 'receipt_enrichment_unavailable'
assert RunJournal(ui.data).get('f' * 32)['result']['entries'][0]['state'] == 'completed'
with pytest.raises(OSError, match='controlled enrichment persistence failure'):
execute_confirmed_run(ui.service, ui.data, ids, api.preflight(ui.service, ids), Event(), 'f' * 32)
receipt = RunJournal(ui.data).get('f' * 32)['result']
assert receipt['status'] == receipt['execution_status'] == 'completed'
assert receipt['entries'][0]['state'] == 'completed'
def test_live_owner_and_saved_counts_do_not_follow_selected_task(ui, monkeypatch, qtbot):
@@ -0,0 +1,79 @@
"""A modal confirmation must not reserve a lane that another operation owns."""
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center.stop_control import StopControl
@pytest.mark.parametrize('batch', [False, True])
@pytest.mark.parametrize('change', ['worker', 'stop', 'closing', 'task', 'dirty', 'dialog'])
def test_confirmation_rechecks_admission_before_authorizing_or_replacing_controls(ui, monkeypatch, batch, change):
window = ui.window
ui.settle()
submitted = []
monkeypatch.setattr(window, '_run_async', lambda *args, **kwargs: submitted.append(args))
original_task = window._task_id
original_authorization = set(window._dsh_authorized_tasks)
original_dialog = window._dsh_operations.dialog
original_dirty = window.plan_panel.table.dirty
live_stop = StopControl()
live_worker = object()
live_run = {'active': True, 'run_id': 'already-running', 'task_id': 'other-owner'}
def confirm(*_):
if change in {'worker', 'stop'}:
window._batch_stop = live_stop
window._dsh_run_stop = live_stop
window._dsh_live_run = live_run
if change == 'worker':
window._workers.add(live_worker)
elif change == 'closing':
window._close_pending = True
elif change == 'task':
window._task_id = ui.tasks[1].task_id
elif change == 'dirty':
window.plan_panel.table.dirty = True
else:
window._dsh_operations.dialog = SimpleNamespace()
return True
window._quick_run_confirmer = confirm
try:
(window._execute_project_tasks if batch else window._prepare_quick_run)()
assert not submitted, 'stale confirmation must not submit another execution'
assert window._dsh_authorized_tasks == original_authorization
assert '未启动' in window.run_panel.operator_band.text()
if change in {'worker', 'stop'}:
assert window._batch_stop is live_stop
assert window._dsh_run_stop is live_stop
assert window._dsh_live_run is live_run
finally:
window._workers.discard(live_worker)
window._close_pending = False
window._task_id = original_task
window._dsh_operations.dialog = original_dialog
window.plan_panel.table.dirty = original_dirty
window._finish_run()
@pytest.mark.parametrize('batch', [False, True])
def test_idle_confirmation_still_starts_execution_while_read_query_is_busy(ui, monkeypatch, batch):
window = ui.window
ui.settle()
submitted = []
monkeypatch.setattr(window, '_run_async', lambda *args, **kwargs: submitted.append(args))
original_query = window._feedback_query
window._quick_run_confirmer = lambda *_: True
# A background read is not the mutation/execution lane.
window._feedback_query = SimpleNamespace(busy=True, invalidate=lambda: None)
try:
(window._execute_project_tasks if batch else window._prepare_quick_run)()
assert len(submitted) == 1
assert isinstance(window._batch_stop, StopControl)
assert ui.tasks[0].task_id in window._dsh_authorized_tasks
assert not ui.calls # The submitted executor is controlled, with no CAD.
finally:
window._finish_run()
window._feedback_query = original_query
+11 -2
View File
@@ -105,8 +105,17 @@ def test_bom_cli_inspection_does_not_create_cad_runtime(batch, tmp_path, runtime
def fail(*args, **kwargs):
raise TaskCenterError('inventory_cleanup', 'reader did not close')
service.for_project_task(tasks[0].task_id)._quick_run_preparer.collect_inventory = fail
report = inspect_batch(service, tasks[0].task_id,
write_bom_template(tmp_path / 'cleanup.xlsx', records_for(tasks, targets)))
path = write_bom_template(tmp_path / 'cleanup.xlsx', records_for(tasks, targets))
if read_error:
with pytest.raises(TaskCenterError) as caught:
inspect_batch(service, tasks[0].task_id, path)
assert caught.value.code == 'inventory_cleanup'
report = caught.value.bom_report
assert report.failed_rows == 1 and report.unchecked_rows == 1
assert report.passed_rows == 0 and report.preview is None
assert not scopes and not calls
return
report = inspect_batch(service, tasks[0].task_id, path)
assert report.total_rows == 2
assert report.failed_rows == (1 if read_error else 0)
assert report.passed_rows == (1 if read_error else 2)
+2 -1
View File
@@ -213,9 +213,10 @@ def test_already_target_bom_keeps_retained_enabled_targets_in_execution(batch, t
def test_native_read_failure_in_full_inspection_does_not_skip_other_projects(batch, tmp_path):
from dx_productivity.trial_task_center.bom_import_report import inspect_batch
from dx_productivity.trial_task_center.project_discovery import ReleasedProjectReadError
service, store, tasks, targets, calls = batch
def fail(*a, **k):
raise TaskCenterError('native_inventory_failed', 'native inventory unavailable')
raise ReleasedProjectReadError('native_inventory', 'native inventory unavailable')
service.for_project_task(tasks[0].task_id)._quick_run_preparer.collect_inventory = fail
report = inspect_batch(service, tasks[0].task_id,
write_bom_template(tmp_path / 'bom.xlsx', records_for(tasks, targets)))
+155
View File
@@ -0,0 +1,155 @@
"""A read failure must not hide resource uncertainty or bypass plan admission."""
from threading import Event
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.execution_problems import classify_execution_failure
@pytest.mark.parametrize('code', ['inventory_cleanup', 'quick_run_uncertain',
'mentor_release_required', 'batch_resources_pending'])
@pytest.mark.parametrize('phase', ['read', 'not_dispatched'])
def test_resource_uncertainty_never_becomes_safe_from_phase_name(code, phase):
policy = classify_execution_failure(code, 'failed', phase=phase)
assert policy['category'] == 'uncertain'
assert not policy['continue_allowed']
def test_resolution_retains_cleanup_code_identity_and_source_row(batch, tmp_path):
service, store, tasks, targets, calls = batch
task_id = tasks[0].task_id
source = write_bom_template(tmp_path / 'source.xlsx', records_for(tasks, targets))
service.import_bom_drafts(task_id, (source,))
pending = service.pending_bom(task_id)
def fail(*args, **kwargs):
raise TaskCenterError('inventory_cleanup', 'owned child has not exited', error_id='READ-CLEANUP-27')
service.for_project_task(task_id)._quick_run_preparer.collect_inventory = fail
with pytest.raises(TaskCenterError) as caught:
service.resolve_pending_bom(task_id)
assert caught.value.code == 'inventory_cleanup'
assert caught.value.error_id == 'READ-CLEANUP-27'
assert caught.value.bom_report.rows[0].source_file == str(source.resolve())
assert caught.value.bom_report.rows[0].source_row == 2
assert service.pending_bom(task_id) == pending
assert not store.list_target_plan(task_id)
def test_unreleased_native_read_blocks_next_project_without_an_uncertain_flag(batch, tmp_path, monkeypatch):
from dx_productivity.trial_task_center.task_queue import execute_task_queue
service, store, tasks, targets, calls = batch
source = write_bom_template(tmp_path / 'source.xlsx', records_for(tasks, targets))
service.import_bom_drafts(tasks[0].task_id, (source,))
attempted = []
for task in tasks:
def fail(*args, owner=task.task_id, **kwargs):
attempted.append(owner)
raise TaskCenterError('inventory_cleanup', 'child process exit is unconfirmed')
child = service.for_project_task(task.task_id)
monkeypatch.setattr(child._quick_run_preparer, 'collect_inventory', fail)
monkeypatch.setattr(child, 'execute_quick_run_queue', lambda *a, **k: pytest.fail('no CAD dispatch'))
result = execute_task_queue(service, tuple(task.task_id for task in tasks), stop_event=Event(),
runtime=SimpleNamespace(bind_logs=lambda *a: None), defer_problem_pass=True)
assert [entry.state for entry in result.entries] == ['blocked', 'pending']
assert result.paused and attempted == [tasks[0].task_id]
def test_legacy_inspection_does_not_treat_absent_runtime_as_release_proof(batch, tmp_path):
service, store, tasks, targets, calls = batch
def fail(*args, **kwargs):
raise TaskCenterError('inventory_cleanup', 'read process retained', error_id='LEGACY-27')
service.for_project_task(tasks[0].task_id)._quick_run_preparer.collect_inventory = fail
source = write_bom_template(tmp_path / 'source.xlsx', records_for(tasks, targets))
with pytest.raises(TaskCenterError) as caught:
inspect_batch(service, tasks[0].task_id, source)
assert caught.value.code == 'inventory_cleanup' and caught.value.error_id == 'LEGACY-27'
assert not calls
@pytest.mark.parametrize('action', ['import', 'resolve'])
def test_pending_plan_writes_obey_the_existing_quick_run_lease(batch, tmp_path, action):
from dx_productivity.trial_task_center.service import _quick_run_lease
service, store, tasks, targets, calls = batch
task_id = tasks[0].task_id
source = write_bom_template(tmp_path / 'source.xlsx', records_for(tasks, targets))
if action == 'resolve':
service.import_bom_drafts(task_id, (source,))
before = service.pending_bom(task_id)
with _quick_run_lease(service._logging.root):
with pytest.raises(TaskCenterError) as caught:
if action == 'import':
service.import_bom_drafts(task_id, (source,))
else:
service.resolve_pending_bom(task_id)
assert caught.value.code == 'quick_run_busy'
assert service.pending_bom(task_id) == before and not calls
@pytest.mark.parametrize('outcome', ['invalid_output', 'timeout', 'cleanup_failure'])
def test_native_reader_certifies_only_released_failures(tmp_path, outcome):
from test_native_inventory_reader import reader_fixture
from dx_productivity.trial_task_center.project_discovery import ReleasedProjectReadError
project, reader, stop, calls, released = reader_fixture(tmp_path,
corrupt=outcome == 'invalid_output', timeout=outcome == 'timeout',
fail_cleanup=outcome == 'cleanup_failure')
factory = reader.desktop_factory
closed = []
def owned(*args, **options):
scope = factory(*args, **options)
start = scope.start_process
def launch(*args, **options):
process = start(*args, **options)
process.close = lambda: closed.append(process.pid)
return process
scope.start_process = launch
return scope
reader.desktop_factory = owned
with pytest.raises(TaskCenterError) as caught:
reader.read(project, ('OLD',), stop_event=stop)
assert closed and released
assert isinstance(caught.value, ReleasedProjectReadError) == (outcome != 'cleanup_failure')
assert caught.value.code == ('inventory_cleanup' if outcome == 'cleanup_failure' else 'native_inventory')
def test_native_inventory_success_keeps_original_hashes_and_time(tmp_path):
import hashlib
import json
from datetime import datetime
from test_native_inventory_reader import reader_fixture
project, reader, stop, calls, released = reader_fixture(tmp_path)
expected = {str(p.resolve()): hashlib.sha256(p.read_bytes()).hexdigest()
for p in [project, project.parent / 'database/icdb.dat']}
reader.read(project, ('OLD',), stop_event=stop)
record = json.loads(next((tmp_path / 'evidence').rglob('native-inventory.json')).read_text(encoding='utf-8'))
assert record['source_hashes'] == expected
assert datetime.fromisoformat(record['finished_utc']) >= datetime.fromisoformat(record['started_utc'])
@pytest.mark.parametrize('diagnostic', ['copy', 'record'])
def test_cleanup_uncertainty_survives_diagnostic_io_failure(tmp_path, monkeypatch, diagnostic):
from pathlib import Path
from test_native_inventory_reader import reader_fixture
from dx_productivity.trial_task_center import native_inventory
project, reader, stop, calls, released = reader_fixture(tmp_path, fail_cleanup=True)
if diagnostic == 'copy':
def fail(*args, **kwargs):
raise OSError('diagnostic copy denied')
monkeypatch.setattr(native_inventory.shutil, 'copytree', fail)
else:
write = Path.write_text
def fail(path, *args, **kwargs):
if path.name == 'native-inventory.json':
raise OSError('diagnostic record denied')
return write(path, *args, **kwargs)
monkeypatch.setattr(Path, 'write_text', fail)
with pytest.raises(TaskCenterError) as caught:
reader.read(project, ('OLD',), stop_event=stop)
assert caught.value.code == 'inventory_cleanup'
assert isinstance(caught.value.diagnostic_error, OSError)
assert released
+267
View File
@@ -0,0 +1,267 @@
"""PR27: preserve completed evidence while rejecting unsupported task scope."""
import hashlib
import json
from pathlib import Path
import sys
from threading import Event
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import native_netlist
from dx_productivity.trial_task_center.batch_resources import write_record
from dx_productivity.trial_task_center.netlist_verification import NetlistVerification
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
@pytest.fixture
def saved_exports(tmp_path, monkeypatch):
"""Replace external native work with saved files; retain the real cache/comparator."""
exported = []
finished = Event()
cancelled = set()
def capture(source, directory):
directory.mkdir(parents=True)
saved = directory / 'saved.txt'
saved.write_bytes(source.read_bytes())
result = {'status': 'captured', 'project': str(source), 'root': str(directory),
'source_hashes': {str(source): hashlib.sha256(source.read_bytes()).hexdigest()},
'capture_hashes': {'saved.txt': hashlib.sha256(saved.read_bytes()).hexdigest()}}
write_record(directory / 'capture.json', result)
return result
def export(snapshot, directory, **controls):
directory.mkdir(parents=True, exist_ok=True)
part = (Path(snapshot['root']) / 'saved.txt').read_text()
exported.append(part)
result = {'status': 'cancelled' if part in cancelled else 'success',
'complete': part not in cancelled, 'capture': snapshot,
'outputs': {}, 'runs': []}
if part not in cancelled:
output = directory / 'effective.txt'
output.write_text(part)
result.update(outputs={'effective': str(output)},
runs=[{'command': [sys.executable],
'tool_sha256': hashlib.sha256(Path(sys.executable).read_bytes()).hexdigest()}],
graph={'components': {'u1': {'refdes': 'R1', 'attributes': {
'Part Number': part, 'Value': 'V'}}},
'nets': [{'name': 'GND', 'endpoints': [['u1', '1']]}]})
write_record(directory / 'netlist.json', result)
if part in {'NEW', 'UNEXPECTED'}:
finished.set()
return result
monkeypatch.setattr(native_netlist, 'capture_project', capture)
monkeypatch.setattr(native_netlist, 'export_netlist', export)
return SimpleNamespace(exported=exported, finished=finished, cancelled=cancelled)
def child_for(project):
row = TargetPlanRow(ComponentTarget(project, 'MAIN', '1', 'u1', 'R1', 'OLD', 'V'), True, 'NEW')
return SimpleNamespace(target_plan=lambda _: (row,), projects=lambda _: (SimpleNamespace(path=project, selected=True, available=True),),
get_task=lambda _: SimpleNamespace(copy_part_number_to_value=False))
@pytest.mark.parametrize('count', [0, 2])
@pytest.mark.parametrize('rule_mode', [False, True])
def test_non_single_project_task_is_rejected_before_any_capture(tmp_path, monkeypatch, count, rule_mode):
child = child_for(tmp_path / 'board.prj')
child.projects = lambda _: tuple(SimpleNamespace(path=tmp_path / f'{i}.prj') for i in range(count))
if rule_mode:
child.target_plan = lambda _: ()
child.rules = lambda _: (SimpleNamespace(enabled=True),)
child.get_task = lambda _: SimpleNamespace(copy_part_number_to_value=False, target_plan_mode=False)
def unexpected(*args, **kwargs):
pytest.fail('unsupported task must not capture, export, or compare a partial project')
monkeypatch.setattr(native_netlist, 'capture_project', unexpected)
monkeypatch.setattr(native_netlist, 'compare_netlists', unexpected)
with NetlistVerification(tmp_path / 'data', 'run', Event()) as checks:
checks.before_task(child, 'task')
checks.after_task('task', execution_summary={'saved_items': 0})
result = checks.finish()['task']
assert result['status'] == 'unavailable'
assert result['verified'] is False
assert '单工程' in result['reason']
def test_project_scope_change_is_rejected_before_after_capture(tmp_path, saved_exports):
project = tmp_path / 'board.prj'
project.write_text('OLD')
child = child_for(project)
with NetlistVerification(tmp_path / 'data', 'run', Event()) as checks:
checks.before_task(child, 'task')
checks.tasks['task']['before'].result(timeout=3)
child.projects = lambda _: (SimpleNamespace(path=project), SimpleNamespace(path=tmp_path / 'other.prj'))
checks.after_task('task')
result = checks.finish()['task']
assert result['status'] == 'unavailable'
assert '单工程' in result['reason']
assert result['after'] is None
assert saved_exports.exported == ['OLD']
def test_resumed_baseline_cannot_be_relabelled_as_another_project(tmp_path, saved_exports):
project = tmp_path / 'board.prj'
project.write_text('OLD')
root = tmp_path / 'data'
with NetlistVerification(root, 'run', Event()) as checks:
checks.before_task(child_for(project), 'task')
other = tmp_path / 'other.prj'
other.write_text('NEW')
with NetlistVerification(root, 'run', Event()) as checks:
checks.before_task(child_for(other), 'task')
checks.after_task('task')
result = checks.finish()['task']
assert result['status'] == 'unavailable' and result['verified'] is False
assert '基准不属于' in result['reason']
assert saved_exports.exported == ['OLD']
@pytest.mark.parametrize('state,saved,status', [('completed', 0, 'not_required'), ('failed', 0, 'unavailable'),
('completed', 1, 'unavailable')])
@pytest.mark.parametrize('change_scope', [False, True])
def test_rule_no_save_only_waives_export_after_valid_single_project_scope(tmp_path, monkeypatch, state, saved, status, change_scope):
project = tmp_path / 'board.prj'
child = child_for(project)
child.target_plan = lambda _: ()
child.rules = lambda _: (SimpleNamespace(enabled=True),)
child.get_task = lambda _: SimpleNamespace(copy_part_number_to_value=False, target_plan_mode=False)
monkeypatch.setattr(native_netlist, 'capture_project', lambda *a: (_ for _ in ()).throw(ValueError('missing RootBlock')))
with NetlistVerification(tmp_path / 'data', 'run', Event()) as checks:
checks.before_task(child, 'task')
if change_scope:
child.projects = lambda _: (SimpleNamespace(path=project), SimpleNamespace(path=tmp_path / 'other.prj'))
checks.after_task('task', execution_state=state, execution_summary={'saved_items': saved, 'no_match_items': 1})
result = checks.finish()['task']
assert result['status'] == ('unavailable' if change_scope else status) and result['verified'] is False
@pytest.mark.parametrize('damage', ['missing_plan', 'bad_capture_json', 'bad_plan_json', 'missing_capture'])
def test_rule_no_save_cannot_waive_unverifiable_existing_baseline(tmp_path, monkeypatch, damage):
project = tmp_path / 'board.prj'
directory = tmp_path / 'data/tasks/task/netlist-checks/run'
before = directory / 'before'
before.mkdir(parents=True)
manifest, plan = before / 'capture.json', directory / 'plan.json'
if damage != 'missing_capture':
manifest.write_text('not-json' if damage == 'bad_capture_json' else json.dumps({'project': str(project)}))
if damage != 'missing_plan':
plan.write_text('not-json' if damage == 'bad_plan_json' else json.dumps({'rows': [], 'copy_value': False}))
original = {path: path.read_bytes() for path in (manifest, plan) if path.is_file()}
child = child_for(project)
child.target_plan = lambda _: ()
child.rules = lambda _: (SimpleNamespace(enabled=True),)
child.get_task = lambda _: SimpleNamespace(copy_part_number_to_value=False, target_plan_mode=False)
monkeypatch.setattr(native_netlist, 'capture_project', lambda *a: pytest.fail('existing baseline cannot be recreated'))
with NetlistVerification(tmp_path / 'data', 'run', Event()) as checks:
checks.before_task(child, 'task')
checks.after_task('task', execution_summary={'saved_items': 0, 'no_match_items': 1})
result = checks.finish()['task']
assert result['status'] == 'unavailable' and result['verified'] is False
assert result['reason']
assert all(path.read_bytes() == data for path, data in original.items())
@pytest.mark.parametrize('saved_part,status', [('NEW', 'verified'), ('UNEXPECTED', 'different')])
def test_later_project_pause_preserves_completed_project_comparison(tmp_path, saved_exports, saved_part, status):
from test_task_queue import Service
from dx_productivity.trial_task_center.task_queue import execute_task_queue
projects = {name: tmp_path / f'{name}.prj' for name in ('A', 'B')}
for path in projects.values():
path.write_text('OLD')
def pause_b(stop):
assert saved_exports.finished.wait(3), 'A exports must finish before B is paused'
stop.set()
service = Service(tmp_path / 'data', {'A': lambda _: projects['A'].write_text(saved_part), 'B': pause_b})
original = service.for_project_task
def task_child(task_id):
child = original(task_id)
plan = child_for(projects[task_id])
child.projects, child.target_plan = plan.projects, plan.target_plan
return child
service.for_project_task = task_child
outcome = execute_task_queue(service, ('A', 'B'), stop_event=Event(),
runtime=SimpleNamespace(bind_logs=lambda *_: None))
assert outcome.paused
assert outcome.entries[0].state == 'completed'
assert outcome.netlist_verification['A']['status'] == status
assert outcome.netlist_verification['A']['verified'] is (status == 'verified')
assert outcome.netlist_verification['B']['status'] == 'cancelled'
def test_cancelled_export_is_never_promoted_to_verified(tmp_path, saved_exports):
project = tmp_path / 'board.prj'
project.write_text('OLD')
saved_exports.cancelled.add('NEW')
stop = Event()
with NetlistVerification(tmp_path / 'data', 'run', stop) as checks:
checks.before_task(child_for(project), 'task')
project.write_text('NEW')
checks.after_task('task')
checks.tasks['task']['after'].result(timeout=3)
stop.set()
result = checks.finish()['task']
assert result['status'] == 'cancelled'
assert result['verified'] is False
assert result['after']['complete'] is False
@pytest.mark.parametrize('state,summary,status', [
('failed', {'failed_items': 1}, 'not_completed'),
('completed', {'no_match_items': 1, 'saved_items': 0}, 'not_replaced'),
])
def test_pause_never_overrides_execution_failure_gate(tmp_path, saved_exports, state, summary, status):
project = tmp_path / 'board.prj'
project.write_text('OLD')
stop = Event()
with NetlistVerification(tmp_path / 'data', 'run', stop) as checks:
checks.before_task(child_for(project), 'task')
project.write_text('NEW')
checks.after_task('task', execution_state=state, execution_summary=summary)
checks.tasks['task']['after'].result(timeout=3)
stop.set()
result = checks.finish()['task']
assert result['status'] == status
assert result['verified'] is False
assert result['graph_comparison']['verified'] is True
@pytest.mark.parametrize('tamper', [False, True])
def test_report_binds_resumed_original_baseline_and_actual_exports(tmp_path, saved_exports, tamper):
project = tmp_path / 'board.prj'
project.write_text('OLD')
root = tmp_path / 'data'
directory = root / 'tasks/task/netlist-checks/run'
with NetlistVerification(root, 'run', Event()) as checks:
checks.before_task(child_for(project), 'task')
original_manifest = (directory / 'before/capture.json').read_bytes()
if tamper:
(directory / 'before-export/effective.txt').write_text('TAMPERED')
project.write_text('NEW')
with NetlistVerification(root, 'run', Event()) as checks:
checks.before_task(child_for(project), 'task')
checks.after_task('task')
result = checks.finish()['task']
assert result['verified'] is True
assert saved_exports.exported.count('OLD') == (2 if tamper else 1)
assert saved_exports.exported.count('NEW') == 1
assert (directory / 'before/capture.json').read_bytes() == original_manifest
report = json.loads(Path(result['report_path']).read_text(encoding='utf-8'))
assert report['schema_version'] == 1
assert report['run_id'] == 'run' and report['task_id'] == 'task'
assert Path(report['project_path']) == project
assert report['plan_sha256'] == hashlib.sha256((directory / 'plan.json').read_bytes()).hexdigest()
for phase, part in [('before', 'OLD'), ('after', 'NEW')]:
evidence = report[phase]
assert evidence['source_hashes'] == {str(project): hashlib.sha256(part.encode()).hexdigest()}
assert evidence['capture_hashes'] == {'saved.txt': hashlib.sha256(part.encode()).hexdigest()}
assert evidence['output_hashes']['effective'] == hashlib.sha256(part.encode()).hexdigest()
assert evidence['export_sha256'] == hashlib.sha256(Path(evidence['export_path']).read_bytes()).hexdigest()
@@ -0,0 +1,209 @@
"""A real unlaunched runtime producer must retire its exact journal claim."""
import json
import os
from pathlib import Path
import pytest
from test_nonblocking_items import component_case
from test_batch_runtime import Cad, Desktop, worker_runtime
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.quick_run import _run_process
from dx_productivity.trial_task_center.stop_control import StopControl
def execution(case):
service, store, tasks, calls, _ = case
task_id = tasks[0].task_id
child = service.for_project_task(task_id)
preparer = child._quick_run_preparer
projects, rules = child.projects(task_id), child._execution_rules(task_id)
session = preparer.begin_batch_session(task_id, projects, rules)
preparer._process_runner = _run_process
return task_id, child, preparer, projects, rules, session
def run_step(case, runtime):
task_id, child, preparer, projects, rules, session = case
with preparer.project_session_scope(runtime=runtime) as project_session:
return preparer.execute_step(task_id, projects, rules, batch_mode=True, batch_session=session,
project_session=project_session, runtime=runtime, stop_event=runtime.stop_event)
@pytest.mark.parametrize('boundary', ['cad_start', 'ready_checkpoint', pytest.param('create_rejected',
marks=pytest.mark.skipif(os.name != 'nt', reason='Windows process creation boundary'))])
def test_released_unlaunched_startup_failure_commits_failed_receipt(component_case, tmp_path, monkeypatch, boundary):
task_id = component_case[2][0].task_id
controlled_runner = component_case[0].for_project_task(task_id)._quick_run_preparer._process_runner
case = execution(component_case)
task_id, child, preparer, projects, rules, session = case
from dx_productivity.trial_task_center import worker_monitor
monitor_process = worker_monitor.run_monitored_process
runtime = worker_runtime(tmp_path, monkeypatch, lambda *a, **k: pytest.fail('worker must remain unlaunched'))
runtime.stop_event = StopControl()
runtime.cad_factory = lambda *a, stop_control=None, **k: Cad(*a, **k)
ensure = runtime._ensure_cad
if boundary == 'create_rejected':
import ctypes
import subprocess
from test_isolated_desktop import native_api
from dx_productivity.trial_task_center import isolated_desktop
api, events, _, _, job = native_api()
native_dll = ctypes.WinDLL
def reject(*args):
events.append(('CreateProcessW-rejected',))
ctypes.set_last_error(5)
return False
def kernel(*args, **kwargs):
native = native_dll(*args, **kwargs)
class Proxy:
def __getattr__(self, name):
return reject if name == 'CreateProcessW' else getattr(native, name)
return Proxy()
monkeypatch.setattr(isolated_desktop.ctypes, 'WinDLL', kernel)
# Exercise the real monitor's process-factory exception transport too.
monkeypatch.setattr(worker_monitor, 'run_monitored_process', monitor_process)
def fail(*args, **kwargs):
if boundary == 'cad_start':
raise OSError('controlled CAD bootstrap failure')
cad = ensure(*args, **kwargs)
if boundary == 'create_rejected':
cad.start_worker = lambda launch, **options: api.create_process(launch, None, None, None,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
cad.checkpoint = lambda *_: (_ for _ in ()).throw(OSError('controlled ready checkpoint failure'))
return cad
monkeypatch.setattr(runtime, '_ensure_cad', fail)
with runtime:
with pytest.raises((TaskCenterError, OSError)) as caught:
run_step(case, runtime)
assert getattr(caught.value, 'code', None) == 'quick_run_session'
assert not runtime.stop_event.is_set()
assert not runtime.record['retries'], 'the shared problem pass owns the single retry allowance'
rows = component_case[1]._connection.execute('SELECT * FROM execution_operations WHERE task_id=? ORDER BY rowid', (task_id,)).fetchall()
assert [row['state'] for row in rows] == ['failed', 'pending']
receipt = json.loads(rows[0]['receipt_json'])
assert receipt['code'] == 'cad_attachment_failed'
startup = receipt['proof']['unlaunched_worker_failure']
assert startup['worker_launch_attempted'] is (boundary == 'create_rejected')
if boundary == 'create_rejected':
assert startup['worker_creation_rejected'] is True
assert startup['failure']['type'] == 'ProcessNotStartedError' and startup['failure']['winerror'] == 5
assert job.closed and events.count(('CreateProcessW-rejected',)) == 1
else:
assert startup['failure']['type'] == 'OSError'
assert 'controlled' in startup['failure']['message']
command = read_command_rows(session.handoff.command_path)[0]
assert preparer.journal.failure_certified(task_id, command)
assert preparer.journal.independent_continuation_ready(task_id)
assert not child.has_interrupted_quick_run(task_id)
assert not component_case[3]
assert len(Desktop.created) == 1 and Desktop.created[0].released
# Complete the other UID, then spend the original failure's shared allowance.
preparer._process_runner = controlled_runner
next_session = preparer.begin_batch_session(task_id, projects, rules)
preparer.execute_step(task_id, projects, rules, batch_mode=True, batch_session=next_session)
assert component_case[3] == [(task_id, ('R2',))]
keys = child.reserve_problem_retry(task_id, source='dsh')
assert len(keys) == 1
assert child.reserve_problem_retry(task_id, source='problems') == ()
child.prepare_failed_quick_run(task_id, operation_keys=keys, runtime=runtime)
retry = preparer.begin_batch_session(task_id, child.projects(task_id), child._execution_rules(task_id))
preparer.execute_step(task_id, child.projects(task_id), child._execution_rules(task_id),
batch_mode=True, batch_session=retry)
assert component_case[3] == [(task_id, ('R2',)), (task_id, ('R1',))]
assert child.execution_problems(task_id)[0]['auto_retries'] == 1
@pytest.mark.parametrize('damage', ['source', 'status', 'command', 'attempt', 'release', 'launch'])
def test_unproven_startup_failure_keeps_prepared_claim_protected(component_case, tmp_path, monkeypatch, damage):
case = execution(component_case)
task_id, child, preparer, projects, rules, session = case
def monitor(command, timeout, *, process_factory, **kwargs):
process_factory(command)
raise OSError('failure after worker start was attempted')
runtime = worker_runtime(tmp_path, monkeypatch, monitor)
runtime.stop_event = StopControl()
runtime.cad_factory = lambda *a, stop_control=None, **k: Cad(*a, **k)
ensure = runtime._ensure_cad
root = session.handoff.command_path.parent
def fail(*args, **kwargs):
if damage == 'launch':
cad = ensure(*args, **kwargs)
cad.start_worker = lambda *a, **k: (_ for _ in ()).throw(OSError('process factory failed'))
return cad
if damage == 'source':
projects[0].path.write_text('source changed outside worker')
elif damage in {'status', 'command'}:
with (root / (damage + '.tsv')).open('a') as stream:
stream.write('foreign input\n')
elif damage == 'attempt':
from dx_productivity.trial_task_center.batch_attempt import _publish
path, expected = runtime._current_attempts[0]
_publish(path, dict(expected, state='mutation_possible'))
elif damage == 'release':
Desktop.fail_release = True
raise OSError('unlaunched startup failed with unproven cleanup')
monkeypatch.setattr(runtime, '_ensure_cad', fail)
try:
with pytest.raises((TaskCenterError, OSError)):
with runtime:
run_step(case, runtime)
row = component_case[1]._connection.execute("SELECT * FROM execution_operations WHERE task_id=? AND state='prepared'", (task_id,)).fetchone()
assert row is not None
assert not preparer.journal.independent_continuation_ready(task_id)
assert child.has_interrupted_quick_run(task_id)
assert not component_case[3]
assert not runtime.record['retries'], 'an attempted worker launch cannot earn an unproven inline replay'
finally:
Desktop.fail_release = False
try:
runtime.close(reason='manual_retry')
except TaskCenterError:
from dx_productivity.trial_task_center.batch_resources import LIVE_RESOURCES
LIVE_RESOURCES.pop(str(runtime.path), None)
@pytest.mark.parametrize('damage', ['job', 'generation', 'journal', 'certificate', 'late_source'])
def test_changed_real_producer_certificate_cannot_commit_failure(component_case, tmp_path, monkeypatch, damage):
case = execution(component_case)
task_id, child, preparer, projects, rules, session = case
runtime = worker_runtime(tmp_path, monkeypatch, lambda *a, **k: pytest.fail('worker launched'))
runtime.stop_event = StopControl()
monkeypatch.setattr(runtime, '_ensure_cad', lambda *a, **k: (_ for _ in ()).throw(OSError('bootstrap failed')))
run = runtime.run_worker
def corrupt(*args, **kwargs):
result = run(*args, **kwargs)
proof = result.unlaunched_worker_failure
if damage == 'job':
proof['job_id'] = 'foreign-job'
elif damage == 'generation':
proof['generation'] += 1
elif damage == 'journal':
proof['journal_attempt']['attempt_id'] = 'foreign-logical-attempt'
elif damage == 'certificate':
Path(proof['files'][0]['path']).write_text('{}')
else:
# Change only after the consumer's first certificate validation.
validate = preparer.journal.validate_before_dispatch
def mutate(*a, **k):
validate(*a, **k)
projects[0].path.write_text('external source mutation after admission')
monkeypatch.setattr(preparer.journal, 'validate_before_dispatch', mutate)
return result
monkeypatch.setattr(runtime, 'run_worker', corrupt)
with runtime:
with pytest.raises(TaskCenterError) as caught:
run_step(case, runtime)
assert caught.value.code == 'quick_run_uncertain'
assert component_case[1]._connection.execute("SELECT count(*) FROM execution_operations WHERE task_id=? AND state='prepared'", (task_id,)).fetchone()[0] == 1
assert child.has_interrupted_quick_run(task_id)
+157
View File
@@ -0,0 +1,157 @@
"""Only the process creation API can prove that a worker never started."""
import ctypes
from ctypes import wintypes
import gc
import os
import subprocess
import pytest
from dx_productivity.trial_task_center import isolated_desktop as module
from dx_productivity.trial_task_center.errors import TaskCenterError
from test_isolated_desktop import native_api
windows_only = pytest.mark.skipif(os.name != 'nt', reason='Windows process creation boundary')
def handle_count():
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
count = wintypes.DWORD()
get_count = kernel.GetProcessHandleCount
get_count.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]
get_count.restype = wintypes.BOOL
assert get_count(wintypes.HANDLE(-1), ctypes.byref(count))
return count.value
def assert_not_started(error):
assert isinstance(error, getattr(module, 'ProcessNotStartedError', ()))
assert isinstance(error.__cause__, OSError)
assert error.errno == error.__cause__.errno
assert error.winerror == error.__cause__.winerror
@windows_only
def test_missing_executable_is_certified_only_after_job_closes_without_handle_leak(tmp_path, monkeypatch):
api = module._Win32Api()
create_job = api.job.CreateJobObject
redirect = module._create_redirected_process
jobs, empty_jobs = [], []
def job(*args):
result = create_job(*args)
jobs.append(result)
return result
def launch(*args):
try:
return redirect(*args)
except OSError:
empty_jobs.append(api.job.QueryInformationJobObject(
jobs[-1], api.job.JobObjectBasicAccountingInformation)['ActiveProcesses'])
raise
monkeypatch.setattr(api.job, 'CreateJobObject', job)
monkeypatch.setattr(module, '_create_redirected_process', launch)
command = (str(tmp_path / 'never-existed-worker.exe'),)
# Warm up imports and inspect the same real Windows failure repeatedly.
with pytest.raises(OSError):
api.create_process(command, None, tmp_path, None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
gc.collect()
before = handle_count()
errors = []
for _ in range(8):
with pytest.raises(OSError) as caught:
api.create_process(command, None, tmp_path, None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
errors.append(caught.value)
assert empty_jobs == [0] * 9
assert all(int(job) == 0 for job in jobs)
assert api._pending_cleanup == []
for error in errors:
assert_not_started(error)
assert error.winerror == 2
error.__traceback__ = None
errors.clear()
del caught, error
gc.collect()
assert handle_count() == before
@pytest.mark.parametrize('stage', ['create', 'attributes', 'handles'])
@windows_only
def test_only_createprocess_false_gets_the_type(tmp_path, monkeypatch, stage):
native_dll = ctypes.WinDLL
calls = []
def fail(*args):
calls.append(stage)
ctypes.set_last_error(5)
return stage == 'handles' # Simulate creation without launching a process.
def kernel(*args, **kwargs):
real = native_dll(*args, **kwargs)
class Proxy:
def __getattr__(self, name):
if name == ('UpdateProcThreadAttribute' if stage == 'attributes' else 'CreateProcessW'):
return fail
return getattr(real, name)
return Proxy()
monkeypatch.setattr(module.ctypes, 'WinDLL', kernel)
if stage == 'handles':
import pywintypes
def invalid_handle(*_):
raise OSError('handle conversion failed after creation')
monkeypatch.setattr(pywintypes, 'HANDLE', invalid_handle)
with pytest.raises(OSError) as caught:
module._create_redirected_process(('unused.exe',), None, tmp_path, None, 0,
subprocess.PIPE, subprocess.PIPE)
assert calls == [stage]
if stage == 'create':
assert_not_started(caught.value)
assert caught.value.winerror == 5
else:
assert not isinstance(caught.value, getattr(module, 'ProcessNotStartedError', ()))
frame = caught.value.__traceback__
while frame.tb_frame.f_code.co_name != '_create_redirected_process':
frame = frame.tb_next
assert all(reader.closed for reader in frame.tb_frame.f_locals['readers'])
@windows_only
def test_job_cleanup_failure_must_remove_not_started_certification(tmp_path, monkeypatch):
api, _, _, _, job = native_api()
job.fail_once = True
missing = (str(tmp_path / 'missing-worker.exe'),)
with pytest.raises(TaskCenterError) as caught:
api.create_process(missing, None, tmp_path, None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
assert caught.value.code == 'private_desktop'
assert not isinstance(caught.value, getattr(module, 'ProcessNotStartedError', ()))
assert_not_started(caught.value.__cause__)
assert api._pending_cleanup == [job] and not job.closed
api.close_pending()
assert job.closed and not api._pending_cleanup
@pytest.mark.parametrize('stage', ['assign', 'resume', 'handle_conversion'])
def test_errors_after_process_creation_are_never_not_started(monkeypatch, stage):
api, _, state, handle, job = native_api()
api.process_ids = lambda _: (42,)
failure = OSError('late launch stage failed')
def fail(*_args, **_kwargs):
raise failure
if stage == 'assign':
api.job.AssignProcessToJobObject = fail
elif stage == 'resume':
api.process.ResumeThread = fail
else:
monkeypatch.setattr(module, '_Win32Process', fail)
with pytest.raises(OSError) as caught:
api.create_process(('fake-python.exe',), None, None, None)
assert caught.value is failure
assert not isinstance(caught.value, getattr(module, 'ProcessNotStartedError', ()))
assert job.closed
if stage != 'handle_conversion':
assert handle.closed and not state['running']
+77
View File
@@ -0,0 +1,77 @@
"""Watchdog grace follows business progress, never mere worker liveness."""
import pytest
from dx_productivity.trial_task_center.worker_monitor import ProgressWatch
def frame(sequence, *, stage='save_and_close', done=0, safe=0):
return f'DX_PROGRESS\ttoken\tjob\t{sequence}\t{stage}\t{done}\t100\t{safe}\n'.encode()
def native_frame(sequence, *, done=0, parent=1, safe=0):
return f'DX_NATIVE_PROGRESS\ttoken\tjob\t{parent}\tjob\t{sequence}\t{done}\t100\t{safe}\n'.encode()
@pytest.mark.parametrize('heartbeat', [False, True])
def test_stalled_unsafe_work_reaches_failure_cleanup_despite_liveness(heartbeat):
watch = ProgressWatch('token', 'job', 10, 0)
assert watch.accept(frame(1), 0)
assert watch.action(10) == 'request_stop'
assert watch.action(20) == 'await_safe_completion'
for sequence, now in enumerate((30, 49, 51, 60, 120, 1000), 2):
if heartbeat:
assert watch.accept(frame(sequence), now)
assert watch.action(now) == (None if now < 50 else 'failure_cleanup')
assert watch.snapshot(now=now)['waiting_for_safe_completion']
assert watch.last_business_progress == 0
assert watch.last_progress == (1000 if heartbeat else 0)
@pytest.mark.parametrize('source', ['stdout', 'native'])
def test_business_progress_restarts_grace_without_revoking_requested_pause(source):
watch = ProgressWatch('token', 'job', 10, 0)
stage = 'native_snapshot_read' if source == 'native' else 'save_and_close'
assert watch.accept(frame(1, stage=stage), 0)
assert watch.action(10) == 'request_stop'
assert watch.action(20) == 'await_safe_completion'
if source == 'native':
assert watch.accept_native(native_frame(1, done=1), 49)
else:
assert watch.accept(frame(2, stage=stage, done=1), 49)
assert not watch.snapshot(now=49)['waiting_for_safe_completion']
assert watch.stop_requested
assert watch.action(50) is None
assert watch.action(68.999) is None
assert watch.action(69) == 'await_safe_completion'
assert watch.action(98.999) is None
assert watch.action(99) == 'failure_cleanup'
def test_native_heartbeats_cannot_restart_stalled_business_grace():
watch = ProgressWatch('token', 'job', 10, 0)
assert watch.accept(frame(1, stage='native_snapshot_read'), 0)
assert watch.action(10) == 'request_stop'
assert watch.action(20) == 'await_safe_completion'
for sequence, now in enumerate((30, 49, 51), 1):
assert watch.accept_native(native_frame(sequence), now)
assert watch.action(now) == (None if now < 50 else 'failure_cleanup')
@pytest.mark.parametrize('line', [
native_frame(1, done=1, parent=2),
native_frame(1, done=1, safe=1),
native_frame(1, done=1).replace(b'token', b'other'),
native_frame(1, done=1).replace(b'\tjob\t1\tjob\t', b'\tjob\t1\tother\t'),
native_frame(1, done=1)[:-1],
])
def test_unbound_native_progress_cannot_clear_wait_or_grant_safety(line):
watch = ProgressWatch('token', 'job', 10, 0)
assert watch.accept(frame(1, stage='native_snapshot_read'), 0)
assert watch.action(10) == 'request_stop'
assert watch.action(20) == 'await_safe_completion'
assert not watch.accept_native(line, 49)
assert not watch.safe_stop
assert watch.action(51) == 'failure_cleanup'