"""Recovery of incomplete evidence does not repeat engineering work.""" import json 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, batch_summary, task_queue from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime, BatchResourceCleanupError from dx_productivity.trial_task_center.errors import TaskCenterError from test_issue44_batch_receipt import BATCH_ID, RUN_ID, TASK_ID, batch from test_pr47_audit_receipts import _start, _supervised_complete from test_run_journal import project_service def _verified_batch(case): service, child, root, _, admission = case with child.transaction(): child._connection.execute('INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)', (TASK_ID, 'round')) command = {'target_scope': 'targets', 'project_path': 'board.prj', 'schematic_name': 'MAIN', 'sheet_number': '1', 'target_selectors': 'uid1\x1fR1'} child._connection.execute('INSERT INTO execution_operations VALUES (?,?,?,?,?,?,?,?)', (TASK_ID, 'round', 'key', json.dumps(command), 'verified', 'attempt', 1, '{}')) journal = _start(root, admission) journal.finish(RUN_ID, dict(_supervised_complete(root), elapsed_seconds=28.125)) checkpoint = root / 'task-queues' / (RUN_ID + '.json') batch_resources.write_record(checkpoint, dict(json.loads(checkpoint.read_bytes()), round_ids={TASK_ID: 'round'})) return service, root, journal def test_same_revision_rebuilds_missing_evidence_without_version_churn(batch, monkeypatch): service, root, journal = _verified_batch(batch) read_sources = batch_summary._operation_sources unavailable = True def evidence(*args): if unavailable: return [], {TASK_ID: {'state': 'unknown'}}, [TASK_ID] return read_sources(*args) monkeypatch.setattr(batch_summary, '_operation_sources', evidence) monkeypatch.setattr(execution_runs, 'execute_task_queue', lambda *_args, **_kwargs: pytest.fail('receipt recovery dispatched engineering work')) execution_runs.recover_batch_receipts(service, root) first = journal.batch_summary(RUN_ID) assert first['operation_evidence_missing'] == [TASK_ID] assert first['status'] == 'paused' and first['resource_state'] == 'released' execution_runs.recover_batch_receipts(service, root) assert journal.batch_summary(RUN_ID) == first exported = root / 'batch-runs' / RUN_ID / 'batch-receipt.json' exported.write_text('{incomplete export', encoding='utf-8') execution_runs.recover_batch_receipts(service, root) assert journal.batch_summary(RUN_ID) == first assert json.loads(exported.read_bytes()) == first unavailable = False execution_runs.recover_batch_receipts(service, root) recovered = journal.batch_summary(RUN_ID) assert recovered['revision'] == first['revision'] + 1 assert recovered['operation_evidence_missing'] == [] assert recovered['operation_counts']['verified'] == 1 assert recovered['status'] == recovered['execution_status'] == 'completed' assert recovered['acceptance'] == first['acceptance'] assert recovered['elapsed_seconds'] == first['elapsed_seconds'] == 28.125 assert recovered['resource_batch_ids'] == first['resource_batch_ids'] == [BATCH_ID] assert recovered['netlist_verification'] == first['netlist_verification'] execution_runs.recover_batch_receipts(service, root) assert journal.batch_summary(RUN_ID) == recovered assert json.loads((root / 'batch-runs' / RUN_ID / 'batch-receipt.json').read_bytes()) == recovered def test_same_revision_rechecks_unknown_round_even_without_missing_field(batch, monkeypatch): service, root, journal = _verified_batch(batch) execution_runs.recover_batch_receipts(service, root) previous = journal.batch_summary(RUN_ID) previous.update(status='paused', source_versions={**previous['source_versions'], 'rounds': {TASK_ID: {'state': 'unknown'}}}) journal.save_batch_summary(RUN_ID, previous, journal.get(RUN_ID)['result'], revision=previous['revision']) monkeypatch.setattr(execution_runs, 'execute_task_queue', lambda *_args, **_kwargs: pytest.fail('unknown-round recovery dispatched engineering work')) execution_runs.recover_batch_receipts(service, root) repaired = journal.batch_summary(RUN_ID) assert repaired['status'] == 'completed' assert repaired['source_versions']['rounds'][TASK_ID]['round_id'] == 'round' assert repaired['operation_counts']['verified'] == 1 assert repaired['revision'] == previous['revision'] + 1 @pytest.mark.parametrize('bound', [True, False]) def test_first_publication_never_lends_a_new_round_to_an_old_report(batch, bound): service, root, journal = _verified_batch(batch) with batch[1].transaction(): batch[1]._connection.execute('UPDATE execution_rounds SET round_id=? WHERE task_id=?', ('round-2', TASK_ID)) if not bound: checkpoint = root / 'task-queues' / (RUN_ID + '.json') state = json.loads(checkpoint.read_bytes()) state.pop('round_ids') batch_resources.write_record(checkpoint, state) manifest = json.loads((root / 'batch-runs' / RUN_ID / 'manifest.json').read_bytes()) execution_runs._finish_batch_summary(service, root, journal, manifest, journal.get(RUN_ID)['result'], 28.125) summary = journal.batch_summary(RUN_ID) version = summary['source_versions']['rounds'][TASK_ID] if bound: assert version['round_id'] == 'round' assert summary['operation_counts']['verified'] == 1 else: assert version['state'] == 'unknown' and 'round_id' not in version assert summary['status'] == 'paused' and summary['operation_evidence_missing'] == [TASK_ID] @pytest.mark.parametrize('binding', ['checkpoint', 'summary', 'missing', 'conflict']) def test_recovery_never_lends_a_new_round_to_an_old_netlist_report(batch, monkeypatch, binding): service, root, journal = _verified_batch(batch) if binding == 'summary': execution_runs.recover_batch_receipts(service, root) previous = journal.batch_summary(RUN_ID) previous.update(status='paused', operation_evidence_missing=[TASK_ID]) journal.save_batch_summary(RUN_ID, previous, journal.get(RUN_ID)['result'], revision=previous['revision']) else: with monkeypatch.context() as unavailable: unavailable.setattr(batch_summary, '_operation_sources', lambda *_args: ([], {TASK_ID: {'state': 'unknown'}}, [TASK_ID])) execution_runs.recover_batch_receipts(service, root) first = journal.batch_summary(RUN_ID) checkpoint = root / 'task-queues' / (RUN_ID + '.json') state = json.loads(checkpoint.read_bytes()) if binding in {'missing', 'summary'}: state.pop('round_ids') elif binding == 'conflict': previous = journal.batch_summary(RUN_ID) previous['source_versions']['rounds'][TASK_ID] = {'round_id': 'foreign-round'} journal.save_batch_summary(RUN_ID, previous, journal.get(RUN_ID)['result'], revision=previous['revision']) batch_resources.write_record(checkpoint, state) child = batch[1] with child.transaction(): child._connection.execute('UPDATE execution_rounds SET round_id=? WHERE task_id=?', ('round-2', TASK_ID)) command = json.loads(child._connection.execute( 'SELECT command_json FROM execution_operations WHERE task_id=?', (TASK_ID,)).fetchone()[0]) for i in range(2): child._connection.execute('INSERT INTO execution_operations VALUES (?,?,?,?,?,?,?,?)', (TASK_ID, 'round-2', 'new-key-' + str(i), json.dumps(command), 'verified', 'new-attempt', 1, '{}')) execution_runs.recover_batch_receipts(service, root) repaired = journal.batch_summary(RUN_ID) version = repaired['source_versions']['rounds'][TASK_ID] assert version.get('round_id') != 'round-2' assert repaired['netlist_verification'] == first['netlist_verification'] if binding in {'checkpoint', 'summary'}: assert version['round_id'] == 'round' assert repaired['operation_counts']['verified'] == 1 else: assert version['state'] == 'unknown' and repaired['status'] == 'paused' assert repaired['operation_evidence_missing'] == [TASK_ID] execution_runs.recover_batch_receipts(service, root) assert journal.batch_summary(RUN_ID)['source_versions']['rounds'][TASK_ID] == version class FatalExit(BaseException): pass @pytest.mark.parametrize('failure', ['ordinary', 'fatal', 'cleanup', 'revalidation']) def test_local_queue_zero_generation_finalizes_only_after_orderly_close(project_service, monkeypatch, failure): service, _, root, ids, hashes = project_service task_id = ids[0] child = service.for_project_task(task_id) validations = [] def revalidate(): validations.append(True) if failure == 'revalidation': raise TaskCenterError('preflight_changed', 'scope changed before binding') def fail_before_any_cad(*args): if failure == 'fatal': raise FatalExit('simulated hard boundary interruption') raise TaskCenterError('preflight_changed', 'scope changed after binding') monkeypatch.setattr(child, 'get_task', fail_before_any_cad) if failure == 'cleanup': def cannot_close(*args): raise OSError('cleanup was not confirmed') monkeypatch.setattr(BatchCadRuntime, 'close', cannot_close) expected_error = FatalExit if failure == 'fatal' else ( BatchResourceCleanupError if failure == 'cleanup' else TaskCenterError) with pytest.raises(expected_error): task_queue.execute_task_queue(service, (task_id,), stop_event=Event(), checkpoint_id=RUN_ID, expected_plan_hashes={task_id: hashes[task_id]}, manifest_digest='d' * 64, revalidate=revalidate) links = list((root / 'batch-runs' / RUN_ID).glob('local-resource-*.json')) assert bool(validations) assert not list((root / 'batch-resources').glob('*/session.json')) if failure == 'revalidation': assert links == [] else: assert len(links) == 1 binding = json.loads(links[0].read_bytes()) assert binding['never_acquired'] is (failure == 'ordinary') assert binding['task_ids'] == [task_id]