fix: reconcile batch scope, resource safety and durable receipts (#44)
Core regression / Python core, intervention UI and release configuration (push) Failing after 9m5s
Core regression / JavaScript syntax (push) Successful in 7s
Core regression / Python core, intervention UI and release configuration (pull_request) Failing after 8m0s
Core regression / JavaScript syntax (pull_request) Successful in 7s

This commit is contained in:
阿白叔 committed 2026-11-27 12:26:19 +08:00
1 parent 0b7f3e5c4a
commit 392ae365da
45 files changed
+2855 -305

No files matched your search

+133
View File
@@ -123,6 +123,139 @@ def incident(case):
run_id=case['run_id'], execution_authorized=True)
@pytest.fixture
def confirmed_incident_batch(rule_run, monkeypatch):
from dataclasses import replace
from dx_productivity.trial_task_center import batch_admission, batch_resources
from dx_productivity.trial_task_center.project_isolation import write_sources
case = rule_run(initial_saved=False, retry_saved=False)
service, task_id, run_id, root = (case[key] for key in ('service', 'task_id', 'run_id', 'root'))
task, = service.tasks()
sibling_id = 'f' * 32
sibling = replace(task, task_id=sibling_id, group_position=task.group_position + 1)
monkeypatch.setattr(service, 'tasks', lambda: (task, sibling))
original_interrupted = service.has_interrupted_quick_run
held = {'value': True}
monkeypatch.setattr(service, 'has_interrupted_quick_run',
lambda item: held['value'] if item == sibling_id else original_interrupted(item))
run = RunJournal(root).get(run_id)
project = service.task_context(task_id).project.path
manifest = {'schema_version': 1, 'policy_version': batch_admission.POLICY_VERSION, 'scope_kind': 'selected',
'group_id': task.group_id, 'candidate_task_ids': [task_id], 'runnable_task_ids': [task_id],
'plan_hashes': run['plan_hashes'], 'decisions': [{'task_id': task_id,
'classification': 'executable', 'project': str(project), 'write_sources': sorted(write_sources(project, strict=True))}]}
batch_resources.write_record(root / 'batch-runs' / run_id / 'manifest.json',
dict(manifest, run_id=run_id, manifest_digest=batch_admission._digest(manifest)))
return case, held
def test_uncertain_batch_sibling_blocks_incident_before_retry_reservation(confirmed_incident_batch):
case, _ = confirmed_incident_batch
result = incident(case)
assert result['attempts'] == 0
assert result['retry_error']['code'] == 'quick_run_uncertain'
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
assert case['service'].execution_problems(case['task_id'])[0]['auto_retries'] == 0
def test_cleared_sibling_does_not_reopen_a_batch_paused_for_verification(confirmed_incident_batch):
case, held = confirmed_incident_batch
held['value'] = False
journal = RunJournal(case['root'])
run = journal.get(case['run_id'])
journal.finish(case['run_id'], dict(run['result'], status='blocked', paused=True))
result = incident(case)
assert result['attempts'] == 0
assert result['retry_error']['code'] == 'quick_run_uncertain'
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
def test_missing_confirmed_manifest_cannot_fall_back_to_legacy_retry(confirmed_incident_batch):
case, held = confirmed_incident_batch
held['value'] = False
root, run_id = case['root'], case['run_id']
folder = root / 'batch-runs' / run_id
manifest = json.loads((folder / 'manifest.json').read_bytes())
checkpoint = root / 'task-queues' / (run_id + '.json')
state = json.loads(checkpoint.read_bytes())
checkpoint.write_text(json.dumps(dict(state, manifest_digest=manifest['manifest_digest'])), encoding='utf-8')
folder.rename(folder.with_name('copied-evidence'))
result = incident(case)
assert result['attempts'] == 0
assert result['retry_error']['code'] == 'batch_manifest'
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
def test_incident_dispatch_failure_exports_original_batch_revision(confirmed_incident_batch, monkeypatch):
from dx_productivity.dsh.execution_runs import _republish_incident_batch_summary
from dx_productivity.trial_task_center.errors import TaskCenterError
case, held = confirmed_incident_batch
held['value'] = False
service, task_id, run_id, root = (case[key] for key in ('service', 'task_id', 'run_id', 'root'))
journal = RunJournal(root)
checkpoint = root / 'task-queues' / (run_id + '.json')
folder = root / 'batch-runs' / run_id
path = folder / 'batch-receipt.json'
manifest = json.loads((folder / 'manifest.json').read_bytes())
state = json.loads(checkpoint.read_bytes())
checkpoint.write_text(json.dumps(dict(state, manifest_digest=manifest['manifest_digest'])), encoding='utf-8')
_republish_incident_batch_summary(service, root, run_id, journal.get(run_id)['result'])
previous = json.loads(path.read_bytes())
batch_id = '8' * 32
dispatched = []
def failed_dispatch(item, **controls):
controls['revalidate']()
dispatched.append(item)
service._last_supervisor_batch_id = batch_id
raise TaskCenterError('supervisor_interrupted', 'worker ended without a durable result')
monkeypatch.setattr(service, 'execute_quick_run_queue', failed_dispatch)
result = incident(case)
assert result['retry_error']['code'] == 'supervisor_interrupted'
assert dispatched == [task_id]
summary = json.loads(path.read_bytes())
assert summary['revision'] == previous['revision'] + 1
assert summary['stop_reason'] == 'supervisor_interrupted'
assert batch_id in summary['resource_batch_ids']
def test_uncertain_batch_sibling_blocks_direct_retry_intent(confirmed_incident_batch):
from dx_productivity.trial_task_center.errors import TaskCenterError
case, _ = confirmed_incident_batch
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)
journal = RunJournal(root)
before = journal.get(run_id)
with pytest.raises(TaskCenterError) as caught:
journal.begin_retry(service, run_id, task_id, selected)
assert caught.value.code == 'quick_run_uncertain'
assert journal.get(run_id) == before
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
def test_incident_rechecks_sibling_under_dispatch_lease(confirmed_incident_batch, monkeypatch):
from dx_productivity.trial_task_center.netlist_verification import NetlistVerification
case, held = confirmed_incident_batch
held['value'] = False
before_task = NetlistVerification.before_task
def expose_interruption(self, *args, **kwargs):
result = before_task(self, *args, **kwargs)
held['value'] = True
return result
monkeypatch.setattr(NetlistVerification, 'before_task', expose_interruption)
result = incident(case)
assert result['retry_error']['code'] == 'quick_run_uncertain'
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
@pytest.mark.parametrize('damage', ['delete', 'tamper'])
def test_rule_retry_rechecks_failure_proof_without_spending_or_dispatching(rule_run, damage):
case = rule_run()
+385
View File
@@ -0,0 +1,385 @@
import json
from pathlib import Path
from threading import Event
import pytest
from dx_productivity.dsh import execution_runs
from dx_productivity.dsh.run_journal import RunJournal
from dx_productivity.trial_task_center import batch_resources
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.task_queue import TaskQueueEntry, TaskQueueResult
RUN_ID = '1' * 32
BATCH_ID = '2' * 32
TASK_ID = 'a' * 32
SKIPPED_ID = 'b' * 32
PLAN_HASHES = {TASK_ID: 'a' * 64}
def test_known_manifest_run_cannot_resume_through_legacy_path_when_manifest_is_missing(batch):
service, child, data, report, admission = batch
journal = RunJournal(data)
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
batch_resources.write_record(data / 'task-queues' / (RUN_ID + '.json'),
{'manifest_digest': admission['manifest_digest']})
with pytest.raises(TaskCenterError) as caught:
execution_runs.execute_confirmed_run(service, data, [TASK_ID], report, Event(), RUN_ID,
resume={'run_id': RUN_ID})
assert caught.value.code == 'batch_manifest'
@pytest.fixture
def batch(tmp_path, monkeypatch):
report = {'fingerprint': 'frozen', 'plan_hashes': PLAN_HASHES}
admission = {'candidate_task_ids': [SKIPPED_ID, TASK_ID],
'runnable_task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES,
'execution_report': report, 'manifest_digest': 'd' * 64, 'policy_version': 1,
'candidate_fingerprint': 'f' * 64, 'decisions': [
{'task_id': SKIPPED_ID, 'classification': 'skipped', 'message': 'no plan'},
{'task_id': TASK_ID, 'classification': 'executable'}]}
data = tmp_path / 'data'
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(data))
child_db = tmp_path / 'child.db'
child = TaskStore(child_db)
service.for_project_task = lambda key: type('Child', (), {'_store': child})()
service.task_context = lambda key: type('Context', (), {
'task': type('Task', (), {'name': key}), 'progress': type('Progress', (), {
'saved_items': 1, 'failed_items': 0, 'no_match_items': 0, 'queue_complete': True}),
'interrupted': False})()
monkeypatch.setattr(execution_runs.tasks, 'fingerprint', lambda *_: 'frozen')
monkeypatch.setattr(execution_runs, 'validate_batch_admission', lambda *_: report)
try:
yield service, child, data, report, admission
finally:
child.close()
store.close()
@pytest.mark.parametrize('resource_state, outcome', [('released', 'completed'), ('isolated', 'paused')])
def test_bound_receipt_preserves_verified_result_and_checks_resource_state(batch, monkeypatch, resource_state, outcome):
service, child, data, report, admission = batch
directory = data / 'batch-runs' / RUN_ID
dispatches = []
def dispatch(current_service, scope, **kwargs):
assert json.loads((directory / 'manifest.json').read_bytes())['candidate_task_ids'] == [SKIPPED_ID, TASK_ID]
kwargs['revalidate']()
dispatches.append(scope)
assert RunJournal(data).get(RUN_ID)['task_ids'] == [TASK_ID]
with child.transaction():
child._connection.execute('INSERT INTO execution_rounds (task_id,round_id) VALUES (?,?)', (TASK_ID, 'round'))
child._connection.execute('INSERT INTO execution_operations VALUES (?,?,?,?,?,?,?,?)',
(TASK_ID, 'round', 'key', json.dumps({'target_scope': 'targets',
'project_path': 'board.prj', 'schematic_name': 'MAIN', 'sheet_number': '1',
'target_selectors': 'uid1\x1fR1'}), 'verified', 'a', 1, '{}'))
current_service._last_supervisor_batch_id = BATCH_ID
record = {'version': 1, 'session_id': BATCH_ID, 'kind': 'task_queue',
'generation': 1, 'desktop': 'dx-' + BATCH_ID, 'state': resource_state, 'processes': [],
'cad_pid': None, 'cad_guid': None, 'checkpoints': {}, 'retries': {}, 'timings': [],
'release_proof': {'generation': 1, 'desktop_not_acquired': True},
'cleanup': {'desktop_not_acquired': True, 'desktop_handle_closed': True,
'owned_cleanup_complete': True}}
batch_resources.write_record(data / 'batch-resources' / BATCH_ID / 'session.json', record)
from dx_productivity.trial_task_center.supervisor_protocol import VERSION
batch_resources.write_record(data / 'batch-resources' / BATCH_ID / 'supervisor.json',
{'version': VERSION, 'batch_id': BATCH_ID, 'state': 'finished', 'outcome': 'ok',
'operation': 'execute_task_queue', 'task_ids': [TASK_ID], 'attempt_id': '3' * 32,
'request_sha256': '0' * 64, 'parent_process': {'pid': 1, 'creation_time': 'test'}})
return TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed'),), False,
netlist_verification={TASK_ID: {'status': 'verified', 'verified': True}})
monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch)
receipt = execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(),
RUN_ID, admission=admission)
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
assert dispatches == [(TASK_ID,)]
assert receipt['summary'] == summary
assert summary['manifest_digest'] == admission['manifest_digest']
assert summary['operation_counts']['saved'] == 1
assert summary['task_counts']['skipped'] == 1
assert summary['execution_status'] == 'completed'
assert summary['acceptance_status'] == 'verified'
assert summary['resource_state'] == resource_state
assert summary['status'] == RunJournal(data).get(RUN_ID)['result']['status'] == outcome
if resource_state == 'isolated':
session = data / 'batch-resources' / BATCH_ID / 'session.json'
record = json.loads(session.read_bytes())
batch_resources.write_record(session, dict(record, state='released'))
execution_runs.recover_batch_receipts(service, data)
reconciled = json.loads((directory / 'batch-receipt.json').read_bytes())
assert dispatches == [(TASK_ID,)]
assert reconciled['revision'] == summary['revision'] + 1
assert reconciled['operation_counts'] == summary['operation_counts']
assert reconciled['resource_state'] == 'released'
assert reconciled['status'] == 'completed'
def test_interrupted_receipt_recovery_after_export_failure_dispatches_once(batch, monkeypatch):
service, _, data, report, admission = batch
dispatches = []
directory = data / 'batch-runs' / RUN_ID
atomic_write = batch_resources.write_record
def dispatch(*args, **kwargs):
kwargs['revalidate']()
dispatches.append(True)
checkpoint = data / 'task-queues' / (RUN_ID + '.json')
atomic_write(checkpoint, {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES,
'entries': {TASK_ID: {'state': 'blocked', 'message': 'needs save verification'}}})
raise TaskCenterError('supervisor_interrupted', 'owner exited')
def write_failure(path, value):
if Path(path).name == 'batch-receipt.json':
raise OSError('fixture unavailable')
atomic_write(path, value)
monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch)
monkeypatch.setattr(batch_resources, 'write_record', write_failure)
with pytest.raises(TaskCenterError, match='owner exited'):
execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(),
RUN_ID, admission=admission)
assert not (directory / 'batch-receipt.json').exists()
durable = RunJournal(data).batch_summary(RUN_ID)
assert durable['reporting_errors'][-1]['code'] == 'batch_receipt_export_unavailable'
monkeypatch.setattr(batch_resources, 'write_record', atomic_write)
execution_runs.recover_batch_receipts(service, data)
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
assert dispatches == [True]
assert summary == RunJournal(data).batch_summary(RUN_ID)
assert summary['task_counts']['blocked'] == 1
assert summary['stop_reason'] == 'supervisor_interrupted'
def test_confirmed_scope_change_keeps_manifest_and_records_zero_dispatch(batch, monkeypatch):
service, _, data, report, admission = batch
directory = data / 'batch-runs' / RUN_ID
dispatches = []
def validate(current_service, frozen):
assert json.loads((directory / 'manifest.json').read_bytes())['manifest_digest'] == frozen['manifest_digest']
raise TaskCenterError('assistant_stale', 'scope changed')
def dispatch(*args, **kwargs):
kwargs['revalidate']()
dispatches.append(True)
monkeypatch.setattr(execution_runs, 'validate_batch_admission', validate)
monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch)
with pytest.raises(TaskCenterError, match='scope changed'):
execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(),
RUN_ID, admission=admission)
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
assert not dispatches
assert RunJournal(data).get(RUN_ID) is None
assert summary['status'] == 'rejected'
assert summary['dispatch_count'] == 0 and summary['queue_id'] is None
def test_restart_rebuilds_summary_after_sqlite_publish_error(batch, monkeypatch):
service, _, data, report, admission = batch
directory = data / 'batch-runs' / RUN_ID
dispatches = []
save_summary = RunJournal.save_batch_summary
def dispatch(*args, **kwargs):
kwargs['revalidate']()
dispatches.append(True)
checkpoint = data / 'task-queues' / (RUN_ID + '.json')
batch_resources.write_record(checkpoint, {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES,
'entries': {TASK_ID: {'state': 'failed', 'message': 'failed safely'}}})
return TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'failed'),), False)
def fail_summary(*args, **kwargs):
raise OSError('fixture unavailable')
monkeypatch.setattr(RunJournal, 'save_batch_summary', fail_summary)
monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch)
receipt = execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(),
RUN_ID, admission=admission)
assert receipt['reporting_errors'][-1]['code'] == 'batch_summary_unavailable'
assert RunJournal(data).get(RUN_ID)['result']['reporting_errors'] == receipt['reporting_errors']
assert not (directory / 'batch-receipt.json').exists()
monkeypatch.setattr(RunJournal, 'save_batch_summary', save_summary)
execution_runs.recover_batch_receipts(service, data)
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
assert dispatches == [True]
assert summary['task_counts']['failed'] == 1 and summary['status'] == 'failed'
assert summary['reporting_errors'][-1]['code'] == 'batch_summary_unavailable'
def _durable_supervisor_result(data, result, *, stopping_reason=None, batch_id=BATCH_ID, resumed=False):
from hashlib import sha256
from dx_productivity.trial_task_center.supervisor_protocol import VERSION, encode
directory = data / 'batch-resources' / batch_id
attempt_id = '3' * 32
request_path = directory / 'request.json'
batch_resources.write_record(request_path, {'version': VERSION, 'batch_id': batch_id,
'attempt_id': attempt_id, 'root': str(data), 'operation': 'execute_task_queue',
'task_ids': [TASK_ID], 'arguments': encode({'task_ids': (TASK_ID,),
('queue_id' if resumed else 'checkpoint_id'): RUN_ID,
'expected_plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64})})
batch_resources.write_record(directory / 'supervisor.json',
{'version': VERSION, 'batch_id': batch_id, 'state': 'finished', 'outcome': 'ok',
'operation': 'execute_task_queue', 'task_ids': [TASK_ID], 'attempt_id': attempt_id,
'started_at': 2 if resumed else 1,
'stopping_reason': stopping_reason, 'business_idle_timeout_seconds': 150,
'request_sha256': sha256(request_path.read_bytes()).hexdigest(),
'parent_process': {'pid': 1, 'creation_time': 'test'}})
batch_resources.write_record(directory / 'result.json', {'version': VERSION, 'batch_id': batch_id,
'attempt_id': attempt_id, 'generation': 1, 'sequence': 1, 'type': 'result',
'payload': {'status': 'ok', 'business_succeeded': True, 'result': encode(result)}})
batch_resources.write_record(directory / 'session.json', {'version': 1, 'session_id': batch_id,
'kind': 'task_queue', 'generation': 1, 'desktop': 'dx-' + batch_id, 'state': 'released', 'processes': [],
'cad_pid': None, 'cad_guid': None, 'checkpoints': {}, 'retries': {}, 'timings': [],
'release_proof': {'generation': 1, 'desktop_not_acquired': True},
'cleanup': {'desktop_not_acquired': True, 'desktop_handle_closed': True, 'owned_cleanup_complete': True}})
def test_restart_recovers_business_and_netlist_before_first_journal_finish(batch, monkeypatch):
service, _, data, _, admission = batch
checkpoint = {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64,
'entries': {TASK_ID: {'state': 'completed', 'message': 'saved'}}}
directory = data / 'batch-runs' / RUN_ID
batch_resources.write_record(directory / 'manifest.json', dict(admission, run_id=RUN_ID))
batch_resources.write_record(data / 'task-queues' / (RUN_ID + '.json'), checkpoint)
journal = RunJournal(data)
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
result = TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed', 'saved'),), False,
netlist_verification={TASK_ID: {'status': 'verified', 'verified': True}})
_durable_supervisor_result(data, result)
monkeypatch.setattr(execution_runs, 'execute_task_queue',
lambda *args, **kwargs: pytest.fail('receipt recovery dispatched CAD'))
execution_runs.recover_batch_receipts(service, data)
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
assert summary['status'] == 'completed'
assert summary['execution_status'] == 'completed'
assert summary['acceptance_status'] == 'verified'
assert journal.get(RUN_ID)['result']['netlist_verification'] == result.netlist_verification
def test_cleanup_only_stop_reason_resolves_without_replay(batch, monkeypatch):
service, _, data, report, admission = batch
directory = data / 'batch-runs' / RUN_ID
def dispatch(*args, **kwargs):
kwargs['revalidate']()
result = TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed', 'saved'),), False,
netlist_verification={TASK_ID: {'status': 'verified', 'verified': True}})
_durable_supervisor_result(data, result)
session = data / 'batch-resources' / BATCH_ID / 'session.json'
batch_resources.write_record(session, dict(json.loads(session.read_bytes()), state='isolated'))
raise batch_resources.BatchResourceCleanupError('resources held', completed_result=result)
monkeypatch.setattr(execution_runs, 'execute_task_queue', dispatch)
with pytest.raises(batch_resources.BatchResourceCleanupError):
execution_runs.execute_confirmed_run(service, data, (TASK_ID,), report, Event(),
RUN_ID, admission=admission)
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
assert summary['stop_reason'] == 'resource_pending'
assert summary['status'] == 'paused'
session = data / 'batch-resources' / BATCH_ID / 'session.json'
batch_resources.write_record(session, dict(json.loads(session.read_bytes()), state='released'))
execution_runs.recover_batch_receipts(service, data)
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
assert summary['stop_reason'] is None and summary['status'] == 'completed'
def test_bound_incident_retry_refreshes_original_receipt(batch):
service, _, data, _, admission = batch
directory = data / 'batch-runs' / RUN_ID
batch_resources.write_record(directory / 'manifest.json', dict(admission, run_id=RUN_ID))
journal = RunJournal(data)
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
receipt = {'status': 'failed', 'execution_status': 'failed', 'queue_id': RUN_ID,
'entries': [{'task_id': TASK_ID, 'state': 'failed', 'message': 'retry failed safely'}]}
journal.finish(RUN_ID, receipt)
execution_runs._republish_incident_batch_summary(service, data, RUN_ID, receipt)
readback = json.loads((directory / 'batch-receipt.json').read_bytes())
assert readback['manifest_digest'] == 'd' * 64
assert readback['task_counts']['failed'] == readback['task_counts']['skipped'] == 1
def test_current_lookup_problem_codes_are_exported(batch):
service, child, data, _, admission = batch
directory = data / 'batch-runs' / RUN_ID
batch_resources.write_record(directory / 'manifest.json', dict(admission, run_id=RUN_ID))
journal = RunJournal(data)
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
with child.transaction():
child._connection.execute('INSERT INTO execution_rounds (task_id,round_id) VALUES (?,?)', (TASK_ID, 'r'))
for index, code in enumerate(('target_not_found', 'lookup_unavailable')):
key = str(index)
child._connection.execute('INSERT INTO execution_operations VALUES (?,?,?,?,?,?,?,?)',
(TASK_ID, 'r', key, '{"target_scope":"all"}', 'failed', 'a', 1, '{}'))
child._connection.execute('''INSERT INTO execution_problems
(task_id,round_id,problem_key,operation_key,classification,state,code,message,rule_version)
VALUES (?,?,?,?,?,?,?,?,?)''', (TASK_ID, 'r', key, key, 'action_required', 'open',
code, 'Native lookup report', 'test'))
journal.finish(RUN_ID, {'status': 'failed', 'entries': [{'task_id': TASK_ID, 'state': 'failed'}]})
execution_runs.recover_batch_receipts(service, data)
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
assert summary['failure_code_counts'] == {'target_not_found': 1, 'lookup_unavailable': 1}
assert {item['code'] for item in summary['operation_failures']} == {'target_not_found', 'lookup_unavailable'}
assert all(item['message'] == 'Native lookup report' and item['round_id'] == 'r'
for item in summary['operation_failures'])
@pytest.mark.parametrize('reason', ['user_pause', 'inactivity'])
def test_restart_keeps_supervisor_stop_cause(batch, reason):
service, _, data, _, admission = batch
checkpoint = {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64,
'entries': {TASK_ID: {'state': 'paused', 'message': 'paused'}}}
directory = data / 'batch-runs' / RUN_ID
batch_resources.write_record(directory / 'manifest.json', dict(admission, run_id=RUN_ID))
batch_resources.write_record(data / 'task-queues' / (RUN_ID + '.json'), checkpoint)
journal = RunJournal(data)
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
result = TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'paused', 'paused'),), True)
_durable_supervisor_result(data, result, stopping_reason=reason)
execution_runs.recover_batch_receipts(service, data)
summary = json.loads((directory / 'batch-receipt.json').read_bytes())
assert summary['stop_reason'] == reason
assert journal.get(RUN_ID)['result']['user_pause_requested'] is (reason == 'user_pause')
assert summary['resource']['generations'][0]['business_idle_timeout_seconds'] == 150
def test_restart_recovers_new_supervisor_result_after_resumed_run(batch, monkeypatch):
service, _, data, _, admission = batch
directory = data / 'batch-runs' / RUN_ID
checkpoint_path = data / 'task-queues' / (RUN_ID + '.json')
checkpoint = {'task_ids': [TASK_ID], 'plan_hashes': PLAN_HASHES, 'manifest_digest': 'd' * 64,
'entries': {TASK_ID: {'state': 'paused', 'message': 'first attempt paused'}}}
batch_resources.write_record(directory / 'manifest.json', dict(admission, run_id=RUN_ID))
batch_resources.write_record(checkpoint_path, checkpoint)
journal = RunJournal(data)
journal.begin(RUN_ID, [TASK_ID], PLAN_HASHES)
_durable_supervisor_result(data, TaskQueueResult(RUN_ID,
(TaskQueueEntry(TASK_ID, 'paused', 'first attempt paused'),), True), stopping_reason='user_pause')
monkeypatch.setattr(execution_runs, 'execute_task_queue',
lambda *args, **kwargs: pytest.fail('receipt recovery dispatched CAD'))
execution_runs.recover_batch_receipts(service, data)
previous = journal.batch_summary(RUN_ID)
assert previous['status'] == 'paused'
assert journal.resume(RUN_ID)['result']['summary'] == previous
new_result = TaskQueueResult(RUN_ID, (TaskQueueEntry(TASK_ID, 'completed', 'resumed and saved'),), False,
netlist_verification={TASK_ID: {'status': 'verified', 'verified': True}})
_durable_supervisor_result(data, new_result, batch_id='4' * 32, resumed=True)
checkpoint.update(entries={TASK_ID: {'state': 'completed', 'message': 'resumed and saved'}},
netlist_verification=new_result.netlist_verification)
batch_resources.write_record(checkpoint_path, checkpoint)
execution_runs.recover_batch_receipts(service, data)
summary = journal.batch_summary(RUN_ID)
assert summary['revision'] == previous['revision'] + 1
assert summary['status'] == 'completed' and summary['acceptance_status'] == 'verified'
assert summary['stop_reason'] is None
assert summary == json.loads((directory / 'batch-receipt.json').read_bytes())
assert journal.get(RUN_ID)['result']['netlist_verification'] == new_result.netlist_verification
+33 -16
View File
@@ -96,27 +96,44 @@ def test_inspect_accepts_frozen_workspace_checkpoint(project_service):
assert result['remaining_task_ids'] == ids
def test_inspect_restores_a_legacy_resource_pause_only_from_its_original_batch(project_service, monkeypatch):
from dx_productivity.trial_task_center import task_queue
def test_inspect_restores_a_determined_resource_pause_only_from_its_original_batch(project_service, monkeypatch):
import hashlib
from dx_productivity.trial_task_center import batch_resources
from dx_productivity.trial_task_center.supervisor_protocol import encode
service, _, data, ids, hashes = project_service
journal = RunJournal(data)
token, batch_id = 'a' * 32, 'b' * 32
token, batch_id, attempt = 'a' * 32, 'b' * 32, 'c' * 32
journal.begin(token, ids, hashes)
checkpoint(data, token, ids, hashes, {ids[0]: 'blocked'})
evidence(service, ids[0])
checkpoint(data, token, ids, hashes, {ids[0]: 'completed'})
path = data / 'task-queues' / (token + '.json')
state = json.loads(path.read_bytes())
path.write_text(json.dumps(dict(state, phase='primary')), encoding='utf-8')
journal.finish(token, {'status': 'blocked', 'paused': True, 'user_pause_requested': False})
archive = data / 'batch-resources' / batch_id / 'result.json'
archive.parent.mkdir(parents=True)
archive.touch()
monkeypatch.setattr(task_queue, 'resource_pause_admitted', lambda root, owner, tasks, plan:
TaskQueueResult(token, (), True, ids[0]) if owner == batch_id and tuple(ids) == tasks and hashes == plan else False)
result = journal.inspect(service, token)
assert result['resource_batch_id'] == batch_id
assert result['isolated_task_ids'] == ids[:1]
assert result['remaining_task_ids'] == ids[1:]
journal.finish(token, {'status': 'blocked', 'paused': True, 'user_pause_requested': True})
directory = data / 'batch-resources' / batch_id
identity = {'pid': 17, 'creation_time': 'worker'}
binding = {'version': 1, 'batch_id': batch_id, 'attempt_id': attempt}
request = dict(binding, operation='execute_task_queue', root=str(data),
arguments=encode({'task_ids': tuple(ids), 'queue_id': None, 'checkpoint_id': token,
'expected_plan_hashes': hashes, 'manifest_digest': 'e' * 64}))
batch_resources.write_record(directory / 'request.json', request)
request_digest = hashlib.sha256((directory / 'request.json').read_bytes()).hexdigest()
batch_resources.write_record(directory / 'supervisor.json', dict(binding,
operation='execute_task_queue', task_ids=ids, state='finished', process=identity,
parent_process=identity, request_sha256=request_digest))
paused = TaskQueueResult(token, tuple(TaskQueueEntry(item, row['state'])
for item, row in state['entries'].items()), True, ids[0])
batch_resources.write_record(directory / 'result.json', dict(binding, generation=1, sequence=1, type='result',
payload={'business_succeeded': True, 'status': 'ok', 'result': encode(paused)}))
state.update(phase='primary', manifest_digest='e' * 64, resource_pause={'task_id': ids[0], 'batch_id': batch_id,
'business_determined': True, 'manifest_digest': 'e' * 64, 'sources': {item: [item] for item in ids}})
batch_resources.write_record(path, state)
monkeypatch.setattr(batch_resources, 'observe_process_identity', lambda _: {'state': 'gone'})
journal.finish(token, {'status': 'paused', 'paused': True, 'user_pause_requested': False})
inspected = journal.inspect(service, token)
assert inspected['resource_batch_id'] == batch_id
assert inspected['isolated_task_ids'] == []
assert inspected['remaining_task_ids'] == ids[1:]
journal.finish(token, {'status': 'paused', 'paused': True, 'user_pause_requested': True})
assert journal.inspect(service, token)['resource_batch_id'] is None
@@ -798,6 +798,50 @@ Require QP_App.UndoCount=0,"launch failure invoked undo"
''', routines_transform=replace_shell)
@pytest.mark.parametrize('exit_code,may_write,expected_code', [
(4, False, 'lookup_unavailable'),
(1, False, '-2147220665'),
(4, True, '-2147220665'),
])
def test_native_lookup_timeout_code_reaches_status_tsv(tmp_path, exit_code, may_write, expected_code):
def replace_native_shell(routines):
start = routines.index('Sub QPNativeReplace(')
end = routines.index('End Sub', start)
return (routines[:start] + routines[start:end].replace(
'Set Shell = CreateObject("WScript.Shell")', 'Set Shell = New NativeResultShell')
+ routines[end:] + f'''
Class NativeResultShell
Public Function Run(ByVal CommandLine, ByVal WindowStyle, ByVal Wait)
Run={exit_code}
End Function
End Class
''')
if may_write:
(tmp_path / 'snapshot-value-job.tsv.native.json').write_text(
'{"stage": "native_replace_started"}', encoding='utf-8')
mutation_possible = 'True' if may_write else 'False'
run_vbs(tmp_path, 'part_number', f'''
Dim FailureSource, FailureDetail, StatusPath
QP_HelperExecutable=WScript.FullName
QP_HelperScript=""
QP_BatchMode=True
On Error Resume Next
QPAutomaticReplaceAndRestore Command,SnapshotPath
Failure=Err.Number: FailureSource=Err.Source: FailureDetail=Err.Description
Err.Clear
On Error GoTo 0
Require Failure<>0,"native failure did not reach status writer"
Require QP_NativeMutationPossible={mutation_possible},"native mutation evidence was lost or invented"
Require QP_App.UndoCount=0,"batch failure invoked undo"
QPFail QP_Root,"batch_failed",Failure,FailureSource,FailureDetail
StatusPath=QP_Fso.BuildPath(QP_Root,"status.tsv")
Require QPReadState(StatusPath,"value-job")="batch_failed","failure state was lost"
''', routines_transform=replace_native_shell)
rows = (tmp_path / 'status.tsv').read_text(encoding='utf-8-sig').splitlines()
assert rows[-1].split('\t')[:3] == ['value-job', 'batch_failed', expected_code]
def test_main_continues_after_zero_match_without_calling_native_helper(tmp_path):
run_vbs(tmp_path, 'preserve', r'''
QP_Fso.DeleteFile SnapshotPath
+248
View File
@@ -0,0 +1,248 @@
"""Incremental scope acceptance through the real task service and Qt controls."""
from dataclasses import replace
import importlib
import json
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.models import TaskStatus
def admission_module():
try:
return importlib.import_module('dx_productivity.trial_task_center.batch_admission')
except ModuleNotFoundError:
pytest.fail('The eligible batch admission path is missing')
def test_selected_scope_uses_saved_order_and_rejects_cross_group(ui):
module = admission_module()
a, b = ui.tasks
assert module.resolve_batch_task_ids(tuple(reversed(ui.tasks)), a.group_id,
selected_ids=(b.task_id, a.task_id)) == (a.task_id, b.task_id)
with pytest.raises(TaskCenterError):
module.resolve_batch_task_ids((a, replace(b, group_id='other')), a.group_id,
selected_ids=(a.task_id, b.task_id))
def test_missing_plan_is_listed_without_rejecting_eligible_task(ui):
module = admission_module()
a, b = ui.tasks
ui.store.record_target_inventory(b.task_id, ())
report = module.build_batch_admission(ui.service, (a.task_id, b.task_id), scope_kind='batch')
assert report['ready']
assert report['runnable_task_ids'] == [a.task_id]
assert [(d['task_id'], d['classification']) for d in report['decisions']] == [
(a.task_id, 'executable'), (b.task_id, 'skipped')]
assert report['decisions'][1]['message']
assert report['execution_report']['plan_hashes'].keys() == {a.task_id}
assert module.validate_batch_admission(ui.service, report)['ready']
def test_confirmation_does_not_silently_admit_a_newly_eligible_task(ui):
module = admission_module()
a, b = ui.tasks
path = ui.service.projects(b.task_id)[0].path
backup = path.with_suffix('.prj.saved')
path.rename(backup)
report = module.build_batch_admission(ui.service, (a.task_id, b.task_id), scope_kind='batch')
backup.rename(path)
with pytest.raises(TaskCenterError, match='确认|变化'):
module.validate_batch_admission(ui.service, report)
assert not ui.calls
def test_uncertain_member_stops_entire_batch_even_if_other_member_is_ready(ui):
module = admission_module()
a, b = ui.tasks
ui.store.set_task_status(b.task_id, TaskStatus.BLOCKED, summary='saved but unverified')
report = module.build_batch_admission(ui.service, (a.task_id, b.task_id), scope_kind='batch')
assert not report['ready']
assert report['global_blockers']
assert report['decisions'][1]['classification'] == 'held'
assert not ui.calls
def test_cancelled_batch_leaves_zero_dispatch_receipt(ui, qtbot):
seen = []
ui.window._quick_run_confirmer = lambda *args: seen.append(args) or False
ui.window.task_list.queue_button.click()
qtbot.waitUntil(lambda: bool(seen), timeout=5000)
ui.settle()
receipts = list((ui.data / 'batch-runs').glob('*/batch-receipt.json'))
assert receipts, 'Cancelled confirmations must retain their actual candidate scope'
value = json.loads(receipts[-1].read_text(encoding='utf-8'))
assert value['status'] == 'cancelled'
assert value['dispatch_count'] == 0
assert not ui.calls
def test_selected_action_and_confirmation_show_only_explicit_selection(ui, qtbot):
action = getattr(ui.window.task_list, 'selected_queue_button', None)
assert action is not None, 'Explicit selected-project execution is missing'
ui.window.task_list.list.selectAll()
ui.settle()
seen = []
ui.window._quick_run_confirmer = lambda *args: seen.append(
(args, ui.window._batch_confirmation_admission)) or False
action.click()
qtbot.waitUntil(lambda: bool(seen), timeout=5000)
assert seen[0][0][1] == 2
assert seen[0][1]['scope_kind'] == 'selected'
assert seen[0][1]['candidate_task_ids'] == [t.task_id for t in ui.tasks]
assert not ui.calls
def test_mixed_eight_projects_dispatch_only_the_confirmed_five(ui, qtbot, tmp_path):
from dx_productivity.dsh.run_journal import RunJournal
root = tmp_path / 'mixed-eight'
for i in range(8):
project = root / f'Board-{i}' / 'board.prj'
project.parent.mkdir(parents=True)
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
tasks = ui.service.create_project_tasks(root)
ui.service.add_rule(tasks[0].task_id, 'OLD', 'NEW')
ui.store.record_target_inventory(tasks[5].task_id, ())
ui.store.record_target_inventory(tasks[6].task_id, ())
ui.service.projects(tasks[7].task_id)[0].path.unlink()
ui.window._project_tasks_created(tasks)
ui.settle()
confirmed = []
def confirm(*args):
confirmed.append(ui.window._batch_confirmation_admission)
return True
ui.window._quick_run_confirmer = confirm
ui.window.task_list.queue_button.click()
qtbot.waitUntil(lambda: len(ui.calls) == 5 or '错误' in ui.window.run_panel.operator_band.text(), timeout=10000)
ui.settle()
assert len(ui.calls) == 5, ui.window.run_panel.operator_band.text()
run = RunJournal(ui.data).list_runs()[0]
assert run['task_ids'] == [task.task_id for task in tasks[:5]]
assert [d['classification'] for d in confirmed[0]['decisions']] == ['executable'] * 5 + ['skipped'] * 3
assert all(ui.service.get_task(task.task_id).status is not TaskStatus.RUNNING for task in tasks)
receipt = json.loads((ui.data / 'batch-runs' / run['run_id'] / 'batch-receipt.json').read_text(encoding='utf-8'))
assert receipt['task_counts']['skipped'] == 3
assert receipt['task_counts']['completed'] == 5
assert receipt == ui.window._dsh_last_execution['summary']
assert '跳过 3' in ui.window.run_panel.operator_band.text()
def test_plan_change_in_modal_confirmation_produces_no_dispatch(ui, qtbot):
def confirm(*_):
ui.service.set_copy_part_number_to_value(ui.tasks[0].task_id, True)
return True
ui.window._quick_run_confirmer = confirm
ui.window.task_list.queue_button.click()
qtbot.waitUntil(lambda: bool(list((ui.data / 'batch-runs').glob('*/batch-receipt.json'))), timeout=5000)
ui.settle()
assert not ui.calls
assert '变化' in ui.window.run_panel.operator_band.text()
def test_missing_batch_json_is_repaired_on_window_startup_without_dispatch(ui, qtbot):
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
ui.window._quick_run_confirmer = lambda *_: True
ui.window.task_list.queue_button.click()
qtbot.waitUntil(lambda: len(ui.calls) == 2, timeout=5000)
ui.settle()
path = next((ui.data / 'batch-runs').glob('*/batch-receipt.json'))
path.unlink()
ui.window.close()
ui.settle()
ui.service._supervised = True
second = TrialTaskCenterWindow(ui.service)
qtbot.addWidget(second)
second.show()
try:
qtbot.waitUntil(path.is_file, timeout=5000)
assert len(ui.calls) == 2, 'Repairing a report must not dispatch replacements'
assert json.loads(path.read_text(encoding='utf-8'))['task_counts']['completed'] == 2
finally:
qtbot.waitUntil(lambda: not second._workers and not second._loading, timeout=5000)
second.close()
ui.service._supervised = False
def test_changing_explicit_selection_during_confirmation_does_not_dispatch_old_scope(ui, qtbot):
ui.window.task_list.list.selectAll()
def confirm(*_):
item = next(ui.window.task_list.list.item(i) for i in range(ui.window.task_list.list.count())
if ui.window.task_list.list.item(i).data(256) == ui.tasks[1].task_id)
item.setSelected(False)
return True
ui.window._quick_run_confirmer = confirm
ui.window.task_list.selected_queue_button.click()
qtbot.waitUntil(lambda: bool(list((ui.data / 'batch-runs').glob('*/batch-receipt.json'))), timeout=5000)
ui.settle()
assert not ui.calls
assert '范围' in ui.window.run_panel.operator_band.text()
def test_resume_validates_declared_database_source_without_comparing_progress(ui):
module = admission_module()
ids = tuple(t.task_id for t in ui.tasks)
admission = module.build_batch_admission(ui.service, ids, scope_kind='batch')
ui.store.set_task_status(ids[0], TaskStatus.RUNNING, summary='legitimate progress')
module.validate_batch_resume(ui.service, admission)
path = ui.service.projects(ids[1])[0].path
path.write_text(path.read_text().replace('"database"', '"different-database"'))
with pytest.raises(TaskCenterError, match='写入源'):
module.validate_batch_resume(ui.service, admission)
assert not ui.calls
def test_resume_of_selected_member_cannot_bypass_uncertain_unselected_sibling(ui):
module = admission_module()
a, b = ui.tasks
admission = module.build_batch_admission(ui.service, (a.task_id,), scope_kind='selected')
ui.store.set_task_status(b.task_id, TaskStatus.BLOCKED, summary='saved but unverified')
with pytest.raises(TaskCenterError, match='待核验'):
module.validate_batch_resume(ui.service, admission)
def test_manual_queue_resume_rejects_a_changed_database_before_second_dispatch(ui, monkeypatch):
child = ui.service.for_project_task(ui.tasks[0].task_id)
worker = child._quick_run_preparer._process_runner
def pause_after_first(command, timeout):
completed = worker(command, timeout)
ui.window._batch_stop.set()
return completed
monkeypatch.setattr(child._quick_run_preparer, '_process_runner', pause_after_first)
ui.window._quick_run_confirmer = lambda *_: True
ui.window.task_list.queue_button.click()
ui.settle()
assert len(ui.calls) == 1
assert ui.window._project_queues
path = ui.service.projects(ui.tasks[1].task_id)[0].path
path.write_text(path.read_text().replace('"database"', '"different-database"'))
ui.window.task_list.queue_button.click()
ui.settle()
assert len(ui.calls) == 1, 'Resuming must not write a different database under the old authorization'
assert '写入源' in ui.window.run_panel.operator_band.text()
def test_selected_execution_uses_saved_order_when_list_display_is_reversed(ui):
from dx_productivity.dsh.run_journal import RunJournal
ui.window.task_list.sort.setCurrentIndex(ui.window.task_list.sort.findData('name_desc'))
ui.window.task_list.list.selectAll()
ui.settle()
ui.window._quick_run_confirmer = lambda *_: True
ui.window.task_list.selected_queue_button.click()
ui.settle()
assert len(ui.calls) == 2, ui.window.run_panel.operator_band.text()
assert RunJournal(ui.data).list_runs()[0]['task_ids'] == [task.task_id for task in ui.tasks]
def test_visible_confirmation_never_names_unselected_sibling_as_execution_scope(ui, monkeypatch):
from PySide6.QtWidgets import QMessageBox
a, b = ui.tasks
module = admission_module()
admission = module.build_batch_admission(ui.service, (a.task_id,), scope_kind='selected')
ui.window._batch_confirmation_admission = admission
ui.window._dsh_confirmation_impact = admission['execution_report']['impact']
seen = []
monkeypatch.setattr(QMessageBox, 'question', lambda *args: seen.append(args[2]) or QMessageBox.StandardButton.No)
assert not ui.window._confirm_quick_run('batch', 1, 1)
assert a.name in seen[0]
assert b.name not in seen[0]
+20 -4
View File
@@ -9,11 +9,16 @@ 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):
def test_confirmation_rechecks_admission_before_authorizing_or_replacing_controls(ui, monkeypatch, qtbot, batch, change):
window = ui.window
ui.settle()
submitted = []
monkeypatch.setattr(window, '_run_async', lambda *args, **kwargs: submitted.append(args))
original_run_async = window._run_async
def dispatch(*args, **kwargs):
if kwargs.get('operation_area') == 'batch_preflight':
return original_run_async(*args, **kwargs)
submitted.append(args)
monkeypatch.setattr(window, '_run_async', dispatch)
original_task = window._task_id
original_authorization = set(window._dsh_authorized_tasks)
original_dialog = window._dsh_operations.dialog
@@ -22,7 +27,9 @@ def test_confirmation_rechecks_admission_before_authorizing_or_replacing_control
live_worker = object()
live_run = {'active': True, 'run_id': 'already-running', 'task_id': 'other-owner'}
confirmation_seen = []
def confirm(*_):
confirmation_seen.append(True)
if change in {'worker', 'stop'}:
window._batch_stop = live_stop
window._dsh_run_stop = live_stop
@@ -42,6 +49,8 @@ def test_confirmation_rechecks_admission_before_authorizing_or_replacing_control
window._quick_run_confirmer = confirm
try:
(window._execute_project_tasks if batch else window._prepare_quick_run)()
if batch:
qtbot.waitUntil(lambda: bool(confirmation_seen), timeout=5000)
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()
@@ -59,17 +68,24 @@ def test_confirmation_rechecks_admission_before_authorizing_or_replacing_control
@pytest.mark.parametrize('batch', [False, True])
def test_idle_confirmation_still_starts_execution_while_read_query_is_busy(ui, monkeypatch, batch):
def test_idle_confirmation_still_starts_execution_while_read_query_is_busy(ui, monkeypatch, qtbot, batch):
window = ui.window
ui.settle()
submitted = []
monkeypatch.setattr(window, '_run_async', lambda *args, **kwargs: submitted.append(args))
original_run_async = window._run_async
def dispatch(*args, **kwargs):
if kwargs.get('operation_area') == 'batch_preflight':
return original_run_async(*args, **kwargs)
submitted.append(args)
monkeypatch.setattr(window, '_run_async', dispatch)
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)()
if batch:
qtbot.waitUntil(lambda: window._batch_stop is not None, timeout=5000)
assert len(submitted) == 1
assert isinstance(window._batch_stop, StopControl)
assert ui.tasks[0].task_id in window._dsh_authorized_tasks
@@ -20,6 +20,7 @@ def test_native_preflight_error_is_visible_and_does_not_start_execution(ui, monk
window._prepare_quick_run()
else:
window._execute_project_tasks()
ui.settle()
assert '受控预检异常' in window.run_panel.operator_band.text()
assert not ui.calls and not window._dsh_authorized_tasks
+2 -1
View File
@@ -76,7 +76,8 @@ def test_external_reference_preserves_completed_result_until_resource_only_clean
assert json.loads(runtime.path.read_text())['state'] == 'isolated'
log = runtime.path.with_name('resource-release.log').read_text(encoding='utf-8')
assert 'isolated' in log
guard_pending_resources(tmp_path)
with pytest.raises(BatchResourceCleanupError):
guard_pending_resources(tmp_path)
assert not list(Path(tmp_path).rglob('uncertain.flag'))
assert current_desktop_name() == before
finally:
+22
View File
@@ -0,0 +1,22 @@
import json
import zipfile
from dx_productivity.trial_task_center.diagnostics_bundle import export_diagnostic_bundle
def test_batch_evidence_uses_existing_redaction_and_allowlist(tmp_path):
data = tmp_path / 'data'
relative = 'batch-runs/' + 'a' * 32
directory = data / relative
directory.mkdir(parents=True)
(directory / 'manifest.json').write_text(json.dumps({'token': 'private-scope-credential'}))
(directory / 'batch-receipt.json').write_text(json.dumps({'manifest_digest': 'bound'}))
(directory / 'project.prj').write_text('private CAD')
(directory / 'old-receipt.json').write_text('{}')
output = export_diagnostic_bundle(data, tmp_path / 'support.zip')
with zipfile.ZipFile(output) as bundle:
assert b'private-scope-credential' not in bundle.read(f'{relative}/manifest.json')
assert json.loads(bundle.read(f'{relative}/batch-receipt.json'))['manifest_digest'] == 'bound'
omissions = json.loads(bundle.read('manifest.json'))['omissions']
for filename in ('project.prj', 'old-receipt.json'):
assert {'path': f'{relative}/{filename}', 'reason': 'outside_allowlist'} in omissions
+88
View File
@@ -0,0 +1,88 @@
def test_pending_save_is_counted_by_target_and_keeps_batch_blocked():
from dx_productivity.trial_task_center.batch_summary import summarize_batch
manifest = {'candidate_task_ids': ['A'], 'decisions': [
{'task_id': 'A', 'classification': 'executable'}]}
queue = {'entries': {'A': {'state': 'blocked', 'message': 'save unverified'}}}
rows = [dict(task_id='A', round_id='r', operation_key='job', generation=1,
state='pending_save', target_keys=[f'uid:{i}' for i in range(23)],
current_round=True)]
summary = summarize_batch(manifest, queue, rows, {'state': 'released'}, elapsed_seconds=301)
assert summary['operation_counts']['pending_save'] == 23
assert summary['operation_counts']['saved'] == 0
assert summary['operation_job_count'] == 1
assert summary['task_counts']['blocked'] == 1
assert summary['status'] == 'blocked'
def test_summary_counts_only_effective_targets_and_conserves_candidate_entries():
from dx_productivity.trial_task_center.batch_summary import summarize_batch
candidates = list('ABCDEFGH')
manifest = {'candidate_task_ids': candidates, 'decisions': [
{'task_id': key, 'classification': 'executable' if index < 5 else 'skipped',
'target_count': 2 if key == 'A' else 0}
for index, key in enumerate(candidates)]}
queue = {'entries': {key: {'state': 'completed'} for key in candidates[:5]}}
rows = [
dict(task_id='A', round_id='old', operation_key='old', generation=1,
state='verified', target_keys=['historical'], current_round=False),
dict(task_id='A', round_id='r', operation_key='gone', generation=1,
state='superseded', target_keys=['superseded']),
dict(task_id='A', round_id='r', operation_key='job', generation=1,
state='failed', target_keys=['ref1', 'ref2']),
dict(task_id='A', round_id='r', operation_key='job', generation=2,
state='verified', target_keys=['ref1', 'ref2', 'ref2']),
dict(task_id='F', round_id='r', operation_key='unrelated', generation=1,
state='verified', target_keys=['skipped']),
]
summary = summarize_batch(manifest, queue, rows,
{'state': 'isolated', 'supervisor_status': 'ok'}, elapsed_seconds=18)
assert summary['candidate_count'] == sum(summary['task_counts'].values()) == 8
assert (summary['task_counts']['completed'], summary['task_counts']['skipped']) == (5, 3)
assert summary['operation_counts']['saved'] == 2
assert summary['operation_counts']['failed'] == 0
assert summary['operation_total'] == 2
assert summary['execution_status'] == 'completed'
assert summary['status'] == 'paused'
def test_rule_scope_without_native_targets_has_unknown_total():
from dx_productivity.trial_task_center.batch_summary import summarize_batch
manifest = {'candidate_task_ids': ['A'], 'decisions': [
{'task_id': 'A', 'classification': 'executable'}]}
row = dict(task_id='A', round_id='r', operation_key='rule', generation=1,
state='pending', target_keys=None)
summary = summarize_batch(manifest, {}, [row], {'state': 'unknown'}, elapsed_seconds=0)
assert summary['operation_total'] is None
assert summary['operation_job_count'] == 1
assert summary['task_counts']['pending'] == 1
def test_native_bom_zero_replacements_is_counted_as_skipped():
from dx_productivity.trial_task_center.batch_summary import summarize_batch
manifest = {'candidate_task_ids': ['A'], 'decisions': [
{'task_id': 'A', 'classification': 'executable'}]}
queue = {'entries': {'A': {'state': 'skipped', 'message': 'BOM matches'}}}
summary = summarize_batch(manifest, queue, [], {'state': 'released'}, elapsed_seconds=1)
assert summary['task_counts']['skipped'] == 1
assert summary['operation_total'] == 0
assert summary['status'] == 'completed'
def test_unresolved_sibling_blocks_every_retry_selection():
from dx_productivity.trial_task_center.batch_summary import summarize_batch
manifest = {'candidate_task_ids': ['A', 'B'], 'decisions': [
{'task_id': key, 'classification': 'executable'} for key in ('A', 'B')]}
queue = {'entries': {'A': {'state': 'failed'}, 'B': {'state': 'blocked'}}}
rows = [
dict(task_id='A', round_id='a', operation_key='failed', generation=1,
state='failed', target_keys=['A1'], can_retry=True),
dict(task_id='B', round_id='b', operation_key='pending', generation=1,
state='pending_save', target_keys=['B1']),
]
summary = summarize_batch(manifest, queue, rows, {'state': 'released'}, elapsed_seconds=1)
assert summary['retry_selection'] == []
+57
View File
@@ -0,0 +1,57 @@
import json
from types import SimpleNamespace
from dx_productivity.trial_task_center import native_helper as native
from dx_productivity.trial_task_center.batch_attempt import prepare_attempt, read_attempt
from dx_productivity.trial_task_center.execution_problems import classify_execution_failure
def test_empty_databook_timeout_reports_lookup_unavailable_before_writing(tmp_path, monkeypatch):
project = tmp_path / 'board.prj'
snapshot = tmp_path / 'snapshot-job.tsv'
snapshot.write_text(f'M\t{project}\tOLD\tMISSING\tMAIN:1\nC\tuid\tR1\t0\t0\t0\t1\t\n', encoding='utf-8')
(tmp_path / 'command.tsv').write_text(
f'job_id\ttask_id\tproject_path\njob\ttask\t{project}\n', encoding='utf-8')
attempt_path = tmp_path / 'attempt.json'
attempt = prepare_attempt(attempt_path, session_id='session', generation=1,
job_id='job', task_id='task', project_path=project)
for name, value in {
'DXPART_DESKTOP': 'dx-test',
'DXPART_ATTEMPT_FILE': attempt_path,
'DXPART_ATTEMPT_ID': attempt['attempt_id'],
'DXPART_BATCH_GENERATION': attempt['generation'],
'DXPART_BATCH_SESSION_ID': attempt['session_id'],
}.items():
monkeypatch.setenv(name, str(value))
now = [0.0]
monkeypatch.setattr(native, 'time', SimpleNamespace(
monotonic=lambda: now[0], sleep=lambda seconds: now.__setitem__(0, now[0] + seconds)))
def lookup(path, report):
native.load_databook_target(path, report, 'MISSING',
controls=lambda: (10, 11), browse=lambda: None, filter_part=lambda handle: None,
list_rows=lambda handle: [], dialogs=lambda: (), close_dialog=lambda row: None)
monkeypatch.setattr(native, 'run_native', lookup)
assert native.run(snapshot) == 4
report_path = snapshot.with_suffix('.tsv.native.json')
report = json.loads(report_path.read_bytes())
assert (report['ok'], report['stage'], report['code']) == (False, 'preflight', 'lookup_unavailable')
assert [load['retry'] for load in report['databook']['loads']] == [True, False]
assert report['batch_attempt']['attempt_id'] == attempt['attempt_id']
assert read_attempt(attempt_path)['state'] == 'prepared'
assert 'MISSING' in snapshot.with_suffix('.tsv.native.error.txt').read_text(encoding='utf-8')
def unrelated_timeout(path, report):
raise TimeoutError('CAD dialog did not open')
monkeypatch.setattr(native, 'run_native', unrelated_timeout)
assert native.run(snapshot) == 1
assert 'code' not in json.loads(report_path.read_bytes())
def test_lookup_failure_needs_existing_certification_for_batch_retry():
unavailable = classify_execution_failure('lookup_unavailable', 'failed', authorized=True)
assert unavailable['retry_allowed'] is False
certified = classify_execution_failure('lookup_unavailable', 'failed', certified=True, authorized=True)
assert certified['retry_allowed'] is True
@@ -0,0 +1,85 @@
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import batch_resources, batch_supervisor
def test_legacy_nonblocking_isolation_blocks_write(tmp_path, monkeypatch):
from test_nonblocking_resources import record_at
record_at(tmp_path, state='isolated', blocking=False)
monkeypatch.setattr(batch_resources, '_isolation_evidence', lambda _: True)
with pytest.raises(batch_resources.BatchResourceCleanupError):
batch_resources.guard_pending_resources(tmp_path)
record = {'state': 'isolated', 'blocking': False}
assert batch_resources.resource_blockers((record,)) == (record,)
@pytest.mark.parametrize(('winerror', 'state'), [(5, 'unknown'), (87, 'gone')])
def test_process_open_failure_distinguishes_unknown_from_gone(monkeypatch, winerror, state):
import pywintypes
import win32api
def open_process(access, inherit, pid):
assert (access, inherit, pid) == (0x101000, False, 123)
raise pywintypes.error(winerror, 'OpenProcess', 'injected')
monkeypatch.setattr(win32api, 'OpenProcess', open_process)
identity = {'pid': 123, 'creation_time': 'original'}
result = batch_resources.observe_process_identity(identity)
assert (result['state'], result['error_code']) == (state, winerror)
assert batch_resources._process_gone(identity) is (state == 'gone')
@pytest.mark.parametrize(('created', 'wait_result', 'state'), [
('original', 258, 'alive'), ('new', 258, 'gone'), ('original', 0, 'gone'), ('original', 9, 'unknown'),
])
def test_queried_identity_and_liveness_close_handle_once(monkeypatch, created, wait_result, state):
import win32api
import win32event
import win32process
closed = []
handle = SimpleNamespace(Close=lambda: closed.append(True))
monkeypatch.setattr(win32api, 'OpenProcess', lambda *args: handle)
monkeypatch.setattr(win32process, 'GetProcessTimes', lambda value: {'CreationTime': created})
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda value, timeout: wait_result)
observation = batch_resources.observe_process_identity({'pid': 123, 'creation_time': 'original'})
assert observation['state'] == state
assert closed == [True]
def test_unauthorized_historical_supervisor_is_diagnosable_and_stays_blocked(tmp_path, monkeypatch):
import pywintypes
import win32api
def open_process(*args):
raise pywintypes.error(5, 'OpenProcess', 'injected')
monkeypatch.setattr(win32api, 'OpenProcess', open_process)
batch = 'b' * 32
identity = {'pid': 123, 'creation_time': 'original'}
path = tmp_path / 'batch-resources' / batch / 'supervisor.json'
batch_resources.write_record(path, {'version': 1, 'batch_id': batch, 'attempt_id': 'a' * 32,
'state': 'finished', 'operation': 'probe', 'task_ids': [], 'process': identity,
'parent_process': identity, 'request_sha256': 'f' * 64})
before = path.read_bytes()
pending, = batch_supervisor.reconcile_supervisors(tmp_path)
assert pending['state'] == 'blocked'
assert pending['process_observation']['state'] == 'unknown'
assert pending['process_observation']['error_code'] == 5
assert path.read_bytes() == before
def test_live_generation_exempts_only_its_own_healthy_record(tmp_path):
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
from test_batch_runtime import Desktop
from test_nonblocking_resources import record_at
with BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop) as runtime:
desktop = runtime._ensure_desktop()
assert runtime._ensure_desktop() is desktop
record_at(tmp_path, state='isolated', blocking=False)
with pytest.raises(batch_resources.BatchResourceCleanupError):
runtime._ensure_desktop()
+148
View File
@@ -0,0 +1,148 @@
from threading import Event
import pytest
from dx_productivity.trial_task_center.batch_supervisor import BusinessProgressWatch
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.task_queue import execute_task_queue
from test_project_isolation_queue import ReleasedRuntime
from test_task_queue import Service
def test_repeated_state_requests_stop_once_and_real_progress_moves_deadline():
watch = BusinessProgressWatch(0)
requests = []
frame = {'phase': 'ready', 'business_progress': {'job_id': 'one', 'stage': 'save', 'done': 3, 'total': 5}}
watch.observe('state', frame, 1)
watch.observe('heartbeat', {}, 145)
watch.observe('state', {**frame, 'elapsed_seconds': 145}, 145)
assert not watch.request_cooperative_stop(150, requests.append)
progressed = {**frame, 'business_progress': {**frame['business_progress'], 'done': 4}}
watch.observe('state', progressed, 150)
watch.observe('state', {**progressed, 'elapsed_seconds': 298}, 298)
assert watch.request_cooperative_stop(300, requests.append)
assert not watch.request_cooperative_stop(600, requests.append)
assert requests == ['inactivity']
def test_outer_watch_respects_worker_stop_already_in_flight():
watch = BusinessProgressWatch(0)
requests = []
watch.observe('state', {'business_progress': {'job_id': 'one', 'stage': 'save',
'done': 3, 'total': 5, 'stop_requested': True}}, 10)
assert not watch.request_cooperative_stop(200, requests.append)
assert requests == []
def test_worker_timeout_publishes_inactivity_without_user_intent():
from dx_productivity.trial_task_center.worker_monitor import ProgressWatch
watch = ProgressWatch('worker', 'job', 150, 0)
assert watch.action(150) == 'request_stop'
progress = watch.snapshot(now=150)
assert progress['stopping_reason'] == 'inactivity'
assert progress['idle_timeout_seconds'] == 150
def test_supervisor_delivers_inactivity_stop_without_setting_parent_pause(tmp_path, monkeypatch):
import json
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.stop_control import StopControl
from dx_productivity.trial_task_center.store import TaskStore
probe = tmp_path / 'stall-probe.py'
probe.write_text("""
import json
import sys
import time
from pathlib import Path
from dx_productivity.trial_task_center.supervisor_protocol import encode
request = Path(sys.argv[1])
binding = json.loads(request.read_bytes())
envelope = {key: binding[key] for key in ('version', 'batch_id', 'attempt_id')}
cancel = request.with_name('cancel.json')
deadline = time.monotonic() + 8
sequence = 0
while not cancel.exists() and time.monotonic() < deadline:
sequence += 1
print(json.dumps(dict(envelope, type='heartbeat', generation=1, sequence=sequence, payload=None)), flush=True)
time.sleep(.02)
intent = json.loads(cancel.read_bytes())
result = dict(envelope, type='result', generation=1, sequence=sequence + 1,
payload={'status': 'ok', 'business_succeeded': True, 'result': encode({'reason': intent['reason']})})
request.with_name('result.json').write_text(json.dumps(result), encoding='utf-8')
""", encoding='utf-8')
monkeypatch.setattr(batch_supervisor, 'BusinessProgressWatch',
lambda started: BusinessProgressWatch(started, idle_timeout=.25))
monkeypatch.setattr(batch_supervisor, '_command', lambda request: (sys.executable, str(probe), str(request)))
store = TaskStore(tmp_path / 'tasks.db')
try:
service = TaskCenterService(store, configure_logging(tmp_path))
stop = StopControl()
assert batch_supervisor.run_supervised(service, 'probe', {}, stop_event=stop) == {'reason': 'inactivity'}
assert not stop.is_set() and not stop.force_event.is_set()
journal = next((tmp_path / 'batch-resources').glob('*/supervisor.json'))
recorded = json.loads(journal.read_bytes())
assert recorded['stopping_reason'] == 'inactivity'
assert recorded['business_idle_timeout_seconds'] == .25
finally:
store.close()
def test_regressing_worker_counters_do_not_extend_supervisor_deadline():
watch = BusinessProgressWatch(0)
requests = []
for now, done in ((1, 4), (100, 3), (149, 4)):
watch.observe('state', {'business_progress': {'job_id': 'one', 'stage': 'save', 'done': done}}, now)
assert watch.request_cooperative_stop(151, requests.append)
assert requests == ['inactivity']
@pytest.mark.parametrize('release_succeeded', [True, False])
def test_unknown_save_stops_batch_even_after_resource_release(tmp_path, release_succeeded):
service = Service(tmp_path, {'B': TaskCenterError('quick_run_uncertain', 'save outcome unavailable')})
runtime = ReleasedRuntime(tmp_path, release_succeeded)
result = execute_task_queue(service, ('A', 'B', 'C'), stop_event=Event(), runtime=runtime)
assert result.paused and result.current_task_id == 'B'
assert [entry.state for entry in result.entries] == ['completed', 'blocked', 'pending']
assert service.calls == [('start', 'A'), ('end', 'A'), ('start', 'B')]
assert runtime.release_calls == ['quick_run_uncertain']
def test_unknown_write_is_protected_before_cleanup_and_resume_cannot_dispatch(tmp_path):
service = Service(tmp_path, {'B': TaskCenterError('quick_run_uncertain', 'save outcome unavailable')})
runtime = ReleasedRuntime(tmp_path)
release = runtime.release_failed_project
def guarded_release(error, evidence_root):
assert (evidence_root / 'uncertain.flag').read_text(encoding='utf-8')
return release(error, evidence_root)
runtime.release_failed_project = guarded_release
result = execute_task_queue(service, ('A', 'B', 'C'), stop_event=Event(), runtime=runtime)
assert runtime.release_calls == ['quick_run_uncertain']
service.calls.clear()
resumed = execute_task_queue(service, ('A', 'B', 'C'), stop_event=Event(), runtime=runtime,
queue_id=result.queue_id)
assert resumed.paused and resumed.current_task_id == 'B'
assert service.calls == []
def test_failed_protection_write_never_runs_owned_cleanup_or_next_project(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import stop_control
def failed_write(*args):
raise OSError('disk failure')
monkeypatch.setattr(stop_control, 'protect_interruption', failed_write)
service = Service(tmp_path, {'B': TaskCenterError('quick_run_uncertain', 'save outcome unavailable')})
runtime = ReleasedRuntime(tmp_path)
with pytest.raises(OSError, match='disk failure'):
execute_task_queue(service, ('A', 'B', 'C'), stop_event=Event(), runtime=runtime)
assert runtime.release_calls == []
assert service.calls == [('start', 'A'), ('end', 'A'), ('start', 'B')]
+4 -4
View File
@@ -102,7 +102,7 @@ def test_mutex_release_error_preserves_the_durably_returned_lease(tmp_path):
pass
record = batch_resources.pending_resources(runtime.root)[0]
assert record['state'] == 'isolated' and record['blocking'] is False
assert record['state'] == 'isolated' and record['blocking'] is True
assert record['cleanup']['desktop_lease']['returned'] is True
assert 'mutex release failed' in record['isolation_warning']
@@ -166,7 +166,7 @@ def test_resource_recheck_never_queries_a_reused_desktop_for_a_returned_lease(tm
def forbidden(*args): pytest.fail('old batch queried the currently leased desktop')
monkeypatch.setattr(isolated_desktop, '_Win32Api', forbidden)
warnings = batch_resources.cleanup_pending_resources(runtime.root)
assert warnings and warnings[0]['blocking'] is False
assert warnings and warnings[0]['blocking'] is True
next_owner.release(desktop_disappeared=False)
@@ -193,8 +193,8 @@ def test_transient_return_proof_read_failure_can_be_rechecked_without_permanent_
monkeypatch.setattr(desktop_slot, 'returned_lease_intact', lambda *args: False)
assert batch_resources.cleanup_pending_resources(runtime.root)[0]['blocking'] is True
monkeypatch.setattr(desktop_slot, 'returned_lease_intact', original)
assert batch_resources.cleanup_pending_resources(runtime.root)[0]['blocking'] is False
assert not batch_resources.blocking_resources(runtime.root)
assert batch_resources.cleanup_pending_resources(runtime.root)[0]['blocking'] is True
assert batch_resources.blocking_resources(runtime.root)
def test_native_job_creation_failure_is_certified_before_process_creation():
+1 -1
View File
@@ -361,7 +361,7 @@ def test_finished_supervisor_label_does_not_hide_a_live_original_process(tmp_pat
'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)
monkeypatch.setattr(batch_resources, 'observe_process_identity', lambda identity: {'state': 'alive'})
assert pending_supervisors(tmp_path)
+3 -3
View File
@@ -24,13 +24,13 @@ class ReleasedRuntime:
@pytest.mark.parametrize('released',[False,True])
def test_uncertain_project_only_holds_independent_tasks_until_writers_exit(tmp_path,released):
def test_uncertain_project_holds_independent_tasks_regardless_of_writer_exit(tmp_path,released):
service=Service(tmp_path,{'A':TaskCenterError('quick_run_uncertain','unknown saved result')})
runtime=ReleasedRuntime(tmp_path,released)
result=execute_task_queue(service,('A','B'),stop_event=Event(),runtime=runtime)
assert result.entries[0].state=='blocked'
assert result.paused is (not released)
assert service.calls==([('start','A'),('start','B'),('end','B')] if released else [('start','A')])
assert result.paused
assert service.calls==[('start','A')]
assert runtime.release_calls==['quick_run_uncertain']
+1 -1
View File
@@ -131,7 +131,7 @@ def test_closed_desktop_rechecks_only_observe_until_external_reference_disappear
assert runtime.record['state'] == 'isolated'
for _ in range(3):
assert cleanup_pending_resources(tmp_path)
assert not batch_resources.blocking_resources(tmp_path)
assert batch_resources.blocking_resources(tmp_path)
assert calls.count('close') == 1
api.present = False
assert cleanup_pending_resources(tmp_path) == ()
+17 -12
View File
@@ -32,13 +32,13 @@ def runtime_with_residual(tmp_path, monkeypatch, *, confirmation=False):
@pytest.mark.parametrize('confirmation', [False, None])
def test_residual_desktop_is_warning_admits_fresh_batch_and_never_repeats_close(tmp_path, monkeypatch, confirmation):
def test_residual_desktop_blocks_fresh_batch_and_never_repeats_close(tmp_path, monkeypatch, confirmation):
runtime, calls = runtime_with_residual(tmp_path, monkeypatch, confirmation=confirmation)
runtime.close()
assert runtime.record['state'] == 'isolated'
assert runtime.record['blocking'] is False
assert runtime.record['blocking'] is True
assert runtime.record['release_results']['desktop_released'] is False
assert batch_resources.blocking_resources(tmp_path) == ()
assert batch_resources.blocking_resources(tmp_path)
assert batch_resources.pending_resources(tmp_path)[0]['state'] == 'isolated'
with pytest.raises(batch_resources.BatchResourceCleanupError):
runtime._ensure_desktop()
@@ -47,8 +47,9 @@ def test_residual_desktop_is_warning_admits_fresh_batch_and_never_repeats_close(
confirm_desktop_released=lambda name: (_ for _ in ()).throw(OSError('foreign reference'))))
batch_resources.cleanup_pending_resources(tmp_path)
assert calls == ['close']
with batch_runtime.BatchCadRuntime(tmp_path, 'next') as admitted:
assert admitted.generation == 0
with pytest.raises(batch_resources.BatchResourceCleanupError):
with batch_runtime.BatchCadRuntime(tmp_path, 'next'):
pytest.fail('an isolated desktop admitted a fresh batch')
assert runtime.result == {'completed': True}
@@ -61,7 +62,7 @@ def test_isolation_proof_is_revalidated_after_restart_and_does_not_trust_label(t
proof = runtime.record['isolation_proof']
assert proof['processes'] == [identity]
assert proof['session_id'] == runtime.session_id and proof['generation'] == 1
assert batch_resources.blocking_resources(tmp_path) == ()
assert batch_resources.blocking_resources(tmp_path)
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: False)
assert batch_resources.blocking_resources(tmp_path)
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: SimpleNamespace(confirm_desktop_released=lambda _: None))
@@ -108,7 +109,7 @@ def test_passive_disappearance_confirmation_updates_both_release_state_and_resul
assert calls == ['close']
def test_supervisor_preserves_success_and_business_failure_with_nonfatal_desktop_warning(tmp_path, monkeypatch):
def test_supervisor_preserves_business_evidence_while_desktop_blocks_admission(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.batch_supervisor import _finish_response
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.supervisor_protocol import encode, encode_error
@@ -120,25 +121,29 @@ def test_supervisor_preserves_success_and_business_failure_with_nonfatal_desktop
journal = {'operation': 'probe', 'batch_id': runtime.session_id}
result = {'verified': True}
response = {'business_succeeded': True, 'status': 'ok', 'result': encode(result)}
assert _finish_response(tmp_path, journal, response, configure_logging(tmp_path)) == result
assert journal['state'] == 'finished'
with pytest.raises(TaskCenterError) as pending:
_finish_response(tmp_path, journal, response, configure_logging(tmp_path))
assert pending.value.code == 'batch_resources_pending'
assert pending.value.completed_result == result
assert journal['state'] == 'blocked'
assert journal['resource_recheck']['desktop_released'] is False
response = {'business_succeeded': False, 'status': 'error',
'error': encode_error(TaskCenterError('replacement_uncertain', 'requires verification'))}
with pytest.raises(TaskCenterError) as caught:
_finish_response(tmp_path, journal, response, configure_logging(tmp_path))
assert caught.value.code == 'replacement_uncertain'
assert caught.value.code == 'batch_resources_pending'
assert caught.value.primary_error.code == 'replacement_uncertain'
assert caught.value.resources_released is False and caught.value.owned_writers_exited is True
def test_resource_status_displays_isolation_warning_without_blocking(qtbot):
def test_resource_status_displays_isolation_as_blocking(qtbot):
from dx_productivity.trial_task_center.ui.resource_status import ResourceStatus
warning = {'state': 'isolated', 'blocking': False, 'desktop_released': False}
status = ResourceStatus(lambda: (warning,))
try:
status.refresh()
qtbot.waitUntil(lambda: not status.busy)
assert status.records == (warning,) and not status.blocked
assert status.records == (warning,) and status.blocked
status._received((warning, {'state': 'blocked'}))
assert status.blocked
finally:
+42 -6
View File
@@ -16,7 +16,7 @@ def test_normal_supervised_queue_reuses_original_queue_after_resource_pause(tmp_
ids = ('A', 'B', 'C')
token = 'a' * 32
hashes = dict.fromkeys(ids, 'f' * 64)
result = TaskQueueResult(token, (TaskQueueEntry('A', 'completed'), TaskQueueEntry('B', 'blocked'),
result = TaskQueueResult(token, (TaskQueueEntry('A', 'completed'), TaskQueueEntry('B', 'completed'),
TaskQueueEntry('C', 'pending')), True, 'B')
done = TaskQueueResult(token, (result.entries[0], result.entries[1], TaskQueueEntry('C', 'completed')), False)
calls = []
@@ -42,18 +42,47 @@ def test_normal_supervised_queue_reuses_original_queue_after_resource_pause(tmp_
assert calls[-1]['expected_plan_hashes'] == hashes
@pytest.mark.parametrize('reason', [None, 'unknown_writer', 'cancel', 'consumed', 'unknown_pause'])
def test_automatic_resource_continuation_revalidates_before_later_dispatch(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.errors import TaskCenterError
ids = ('A', 'B')
queue_id = 'a' * 32
paused = TaskQueueResult(queue_id, (TaskQueueEntry('A', 'completed'), TaskQueueEntry('B', 'pending')), True, 'A')
dispatched, validations = [], []
def supervise(operation, arguments, **controls):
validate = controls.get('revalidate')
if validate is not None:
validate()
dispatched.append(arguments)
return paused
def continuation():
validations.append('continuation')
raise TaskCenterError('quick_run_uncertain', 'another member now needs verification')
service = SimpleNamespace(_supervised=True, _logging=SimpleNamespace(root=tmp_path),
_supervise=supervise, _last_supervisor_batch_id='b' * 32)
monkeypatch.setattr(task_queue, 'resource_pause_admitted', lambda *args, **kwargs: True)
with pytest.raises(TaskCenterError, match='quick_run_uncertain'):
task_queue.execute_task_queue(service, ids, stop_event=Event(), checkpoint_id=queue_id,
revalidate=lambda: validations.append('initial'), continuation_revalidate=continuation)
assert validations == ['initial', 'continuation']
assert len(dispatched) == 1 and dispatched[0]['checkpoint_id'] == queue_id
@pytest.mark.parametrize('reason', [None, 'unknown_writer', 'cancel', 'consumed', 'unknown_pause', 'uncertain'])
def test_original_receipt_must_prove_resource_pause_and_cannot_be_consumed_again(tmp_path, monkeypatch, reason):
from dx_productivity.trial_task_center import batch_resources
batch_id, attempt, queue = 'b' * 32, 'c' * 32, 'a' * 32
ids, hashes = ('A', 'B'), {'A': '01', 'B': '02'}
entries = (TaskQueueEntry('A', 'blocked'), TaskQueueEntry('B', 'pending'))
entries = (TaskQueueEntry('A', 'completed'), TaskQueueEntry('B', 'pending'))
result = TaskQueueResult(queue, entries, True, 'A')
folder = tmp_path / 'batch-resources' / batch_id
request = {'batch_id': batch_id, 'attempt_id': attempt, 'operation': 'execute_task_queue', 'root': str(tmp_path),
'arguments': encode({'task_ids': ids, 'queue_id': None, 'checkpoint_id': queue,
'expected_plan_hashes': hashes})}
'expected_plan_hashes': hashes, 'manifest_digest': 'm' * 64})}
batch_resources.write_record(folder / 'request.json', request)
digest = hashlib.sha256((folder / 'request.json').read_bytes()).hexdigest()
process = {'pid': 17, 'creation_time': 'worker'}
@@ -61,18 +90,25 @@ def test_original_receipt_must_prove_resource_pause_and_cannot_be_consumed_again
'operation': 'execute_task_queue', 'task_ids': list(ids), 'parent_process': process,
'process': process, 'state': 'finished', 'request_sha256': digest})
payload = {'business_succeeded': True, 'status': 'ok', 'result': encode(result)}
if reason != 'unknown_pause':
payload['resource_warning'] = {'state': 'isolated', 'owned_writers_exited': True}
payload['resource_warning'] = {'state': 'isolated', 'owned_writers_exited': True}
batch_resources.write_record(folder / 'result.json', {'version': 1, 'batch_id': batch_id, 'attempt_id': attempt,
'generation': 1, 'sequence': 1, 'type': 'result', 'payload': payload})
state = {'version': 1, 'task_ids': list(ids), 'plan_hashes': hashes, 'phase': 'primary',
'manifest_digest': 'm' * 64,
'entries': {entry.task_id: {'state': entry.state, 'message': entry.message} for entry in entries}}
if reason != 'unknown_pause':
state['resource_pause'] = {'task_id': 'A', 'batch_id': batch_id, 'business_determined': True,
'manifest_digest': 'm' * 64, 'sources': {'A': ['a.prj'], 'B': ['b.prj']}}
if reason == 'consumed':
state['consumed_resource_pauses'] = {batch_id: 'A'}
if reason == 'cancel':
(folder / 'cancel.json').write_text(json.dumps({'batch_id': batch_id}))
if reason == 'uncertain':
from dx_productivity.trial_task_center.stop_control import protect_interruption
protect_interruption(tmp_path / 'tasks' / 'A' / 'quick-run', 'unknown result')
batch_resources.write_record(tmp_path / 'task-queues' / (queue + '.json'), state)
monkeypatch.setattr(batch_resources, '_process_gone', lambda _: reason != 'unknown_writer')
monkeypatch.setattr(batch_resources, 'observe_process_identity', lambda _: {'state': 'gone'})
assert task_queue.resource_pause_admitted(tmp_path, batch_id, ids, hashes) == (False if reason else result)
+6 -6
View File
@@ -70,11 +70,11 @@ def test_changed_confirmed_plan_is_rejected_before_any_executor(tmp_path):
assert not service.calls
def test_dispatched_error_isolates_the_project_after_its_owned_resources_exit(tmp_path):
def test_dispatched_error_with_no_no_write_proof_pauses_the_batch(tmp_path):
service = Service(tmp_path, {'A': TaskCenterError('quick_run_preflight', 'target absent')})
result = execute_task_queue(service, ('A', 'B'), stop_event=Event())
assert not result.paused and result.entries[0].state == 'blocked'
assert service.calls == [('start', 'A'), ('start', 'B'), ('end', 'B')]
assert result.paused and result.entries[0].state == 'blocked'
assert service.calls == [('start', 'A')]
def test_actual_read_phase_failure_allows_next_project(tmp_path):
@@ -93,12 +93,12 @@ def test_actual_read_phase_failure_allows_next_project(tmp_path):
assert service.calls == [('start', 'B'), ('end', 'B')]
def test_uncertain_result_is_quarantined_without_replaying_before_next_independent_task(tmp_path):
def test_uncertain_result_pauses_before_next_independent_task(tmp_path):
service = Service(tmp_path, {'A': TaskCenterError('quick_run_uncertain', 'unknown')})
result = execute_task_queue(service, ('A', 'B'), stop_event=Event())
assert not result.paused
assert result.paused
assert result.entries[0].state == 'blocked'
assert service.calls == [('start', 'A'), ('start', 'B'), ('end', 'B')]
assert service.calls == [('start', 'A')]
def test_pause_finishes_current_item_and_does_not_start_next_task(tmp_path):
+1
View File
@@ -40,6 +40,7 @@ def test_large_manual_batch_uses_full_lifecycle_confirmation(window, qtbot, tmp_
return False
window._quick_run_confirmer = confirm
window.task_list.queue_button.click()
qtbot.waitUntil(lambda: bool(confirmations), timeout=5000)
assert len(confirmations) == 1
assert confirmations[0][0] == ('batch', 21, 21)
assert confirmations[0][1]['enabled_scope'] == 21
+33 -7
View File
@@ -1,4 +1,4 @@
"""Frozen parent queue survives one isolated project supervisor failure."""
"""Keep legacy workspace checkpoints and enforce batch-wide uncertainty."""
import json
from pathlib import Path
from threading import Event
@@ -28,7 +28,7 @@ def service_for(tmp_path, monkeypatch, outcomes):
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):
def test_released_uncertain_A_pauses_before_B_and_retains_parent_order(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
@@ -36,10 +36,9 @@ def test_released_uncertain_A_isolated_from_B_and_parent_order_retained(tmp_path
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 [(entry.task_id, entry.state) for entry in result.entries] == [('A', 'blocked'), ('B', 'pending')]
assert result.queue_id == 'a' * 32 and result.paused
assert [call[1]['task_ids'] for call in calls] == [('A',)]
assert not stop.is_set()
assert json.loads((tmp_path / 'workspace-queues' / (result.queue_id + '.json')).read_text())['task_ids'] == ['A', 'B']
@@ -70,6 +69,29 @@ def test_missing_release_proof_prevents_B(tmp_path, monkeypatch):
assert len(calls) == 1
def test_legacy_workspace_retains_netlist_for_completed_child_with_pending_resources(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'})
supervise = service._supervise
report = {'status': 'verified', 'verified': True}
def pending(operation, arguments, **controls):
child = supervise(operation, arguments, **controls)
failure = TaskCenterError('batch_resources_pending', 'desktop still held')
failure.completed_result = TaskQueueResult(child.queue_id, child.entries, False,
netlist_verification={'A': report})
raise failure
service._supervise = pending
result = execute_workspace_projects(service, ('A', 'B'), stop_event=Event())
assert result.paused and len(calls) == 1
assert result.entries[0].state == 'completed'
assert result.netlist_verification == {'A': report}
path = tmp_path / 'workspace-queues' / (result.queue_id + '.json')
assert json.loads(path.read_text(encoding='utf-8'))['entries']['A']['netlist_verification'] == report
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'})
@@ -130,7 +152,7 @@ def test_all_primary_projects_precede_deferred_problem_pass(tmp_path, monkeypatc
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):
def test_resume_after_manual_resource_release_waits_for_reconciliation(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')
@@ -146,6 +168,10 @@ def test_resume_after_manual_resource_release_skips_uncertain_A_and_runs_B(tmp_p
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 resumed.paused and resumed.current_task_id == 'A'
assert [call[1]['task_ids'][0] for call in calls] == ['A']
(tmp_path / 'tasks' / 'A' / 'quick-run' / 'uncertain.flag').unlink()
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']