Core regression / Python core, intervention UI and release configuration (push) Successful in 3m52s
Core regression / JavaScript syntax (push) Successful in 5s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 4m13s
Core regression / JavaScript syntax (pull_request) Successful in 9s
462 lines
27 KiB
Python
462 lines
27 KiB
Python
"""Real rule commands, bound proof files, SQLite budget and independent graphs.
|
|
|
|
Only native execution/export boundaries are controlled; no CAD process starts.
|
|
"""
|
|
import copy
|
|
import csv
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
from threading import Event
|
|
|
|
import pytest
|
|
|
|
from dx_productivity.dsh.execution_runs import execute_confirmed_run
|
|
from dx_productivity.dsh.incidents import IncidentRunner
|
|
from dx_productivity.dsh.run_journal import RunJournal
|
|
from dx_productivity.dsh.task_lifecycle import preflight
|
|
from dx_productivity.trial_task_center import native_netlist
|
|
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
|
from dx_productivity.trial_task_center.native_helper import read_snapshot, transaction_binding
|
|
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _decode_vbs_field, _encode_vbs_field
|
|
from dx_productivity.trial_task_center.service import TaskCenterService
|
|
from dx_productivity.trial_task_center.store import TaskStore
|
|
|
|
|
|
@pytest.fixture
|
|
def rule_run(tmp_path, monkeypatch, request):
|
|
def create(*, initial_saved=True, retry_saved=True, scheduled=False):
|
|
project = tmp_path / 'projects' / 'board' / 'board.prj'
|
|
project.parent.mkdir(parents=True)
|
|
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
|
|
graph = {'components': {
|
|
uid: {'refdes': ref, 'attributes': {'Part Number': part, 'Value': 'OLD VALUE'},
|
|
'symbol': 'old.1 type Primitive Frozen ForwardPCB ', 'pins': {'1': {'number': '1', 'nets': ['GND']}}}
|
|
for uid, ref, part in [('u-ok', 'R1', 'OLD-OK'), ('u-bad', 'R2', 'OLD-BAD'),
|
|
('u-outside-sheet', 'R3', 'OLD-BAD')]},
|
|
'nets': [{'name': 'GND', 'endpoints': [['u-ok', '1'], ['u-bad', '1'], ['u-outside-sheet', '1']]}]}
|
|
calls, captures = [], []
|
|
control = {'acceptance': 'verified'}
|
|
def capture(source, directory):
|
|
directory.mkdir(parents=True, exist_ok=True)
|
|
value = {'project': str(source), 'root': str(directory), 'graph': copy.deepcopy(graph)}
|
|
(directory / 'capture.json').write_text(json.dumps(value), encoding='utf-8')
|
|
captures.append(str(directory))
|
|
return value
|
|
def export(saved, directory, **controls):
|
|
directory.mkdir(parents=True, exist_ok=True)
|
|
value = copy.deepcopy(saved['graph'])
|
|
if value['components']['u-bad']['attributes']['Part Number'] == 'NEW-BAD':
|
|
if control['acceptance'] == 'unavailable':
|
|
raise OSError('controlled after export unavailable')
|
|
if control['acceptance'] == 'different':
|
|
value['nets'][0]['name'] = 'UNDECLARED-NET-CHANGE'
|
|
return {'status': 'success', 'complete': True, 'graph': value}
|
|
monkeypatch.setattr(native_netlist, 'capture_project', capture)
|
|
monkeypatch.setattr(native_netlist, 'export_netlist', export)
|
|
def worker(command, timeout):
|
|
root, job = Path(command[3]), command[-1]
|
|
with (root / 'current-command.tsv').open(encoding='utf-8-sig') as stream:
|
|
row = {key: _decode_vbs_field(value) for key, value in
|
|
next(csv.DictReader(stream, delimiter='\t')).items()}
|
|
calls.append(row['old_part'])
|
|
if row['old_part'] == 'OLD-BAD' and calls.count('OLD-BAD') == 1:
|
|
return subprocess.CompletedProcess(command, 2, '', 'controlled attachment failure')
|
|
saved = initial_saved if row['old_part'] == 'OLD-OK' else retry_saved
|
|
state = 'saved_ok' if saved else 'no_match'
|
|
if saved:
|
|
uid = 'u-ok' if row['old_part'] == 'OLD-OK' else 'u-bad'
|
|
node = graph['components'][uid]
|
|
snapshot = root / f'snapshot-{job}.tsv'
|
|
fields = ['M', str(project), row['old_part'], row['new_part'],
|
|
f"{row['schematic_name']}:{row['sheet_number']}", row['value_mode'],
|
|
row.get('custom_value', ''), row.get('sync_nc', '1')]
|
|
snapshot.write_text('\t'.join(fields) + f'\nC\t{uid}\t{node["refdes"]}\t0\t0\t0\t1\tpins\n', encoding='utf-8')
|
|
metadata, components = read_snapshot(snapshot)
|
|
report = {'ok': True, 'stage': 'native_replace_verified', 'transaction': transaction_binding(
|
|
snapshot, metadata, components, ['lib', row['new_part'], 'sym', '', 'name', 'VALUE'], 'sym')}
|
|
Path(str(snapshot) + '.native.json').write_text(json.dumps(report), encoding='utf-8')
|
|
node['attributes'].update({'Part Number': row['new_part'], 'Part Name': 'name',
|
|
'Part Label': 'VALUE', 'Value': 'VALUE'})
|
|
node['symbol'] = 'sym.1 type Primitive Frozen ForwardPCB '
|
|
semantic = root / f'post-state-{job}.tsv'
|
|
semantic.write_text('job_id\tproject_path\tschematic_name\tsheet_number\tsemantic_state\n' +
|
|
'\t'.join(_encode_vbs_field(row[key]) for key in
|
|
('job_id', 'project_path', 'schematic_name', 'sheet_number')) +
|
|
'\t' + _encode_vbs_field('S\tfull_sheet_v1\r\ncontrolled verified sheet\r\n') + '\n', encoding='utf-8')
|
|
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
|
|
if saved:
|
|
stream.write(f'{job}\tawaiting_native_replace\t\tcaptured\n')
|
|
stream.write(f'{job}\t{state}\tbatch_closed\tcontrolled result\n')
|
|
return subprocess.CompletedProcess(command, 0, '', '')
|
|
data = tmp_path / 'data'
|
|
store = TaskStore(tmp_path / 'tasks.db')
|
|
request.addfinalizer(store.close)
|
|
service = TaskCenterService(store, configure_logging(data), quick_run_preparer=QuickRunPreparer(
|
|
data, process_runner=worker, cscript_resolver=lambda: Path('controlled-native'),
|
|
sheet_discoverer=lambda _: (('MAIN', '1'),)))
|
|
task = service.create_project_tasks(tmp_path / 'projects')[0]
|
|
service.add_rule(task.task_id, 'OLD-OK', 'NEW-OK')
|
|
service.add_rule(task.task_id, 'OLD-BAD', 'NEW-BAD')
|
|
service.set_copy_part_number_to_value(task.task_id, True)
|
|
run_id = '9' * 32
|
|
report = preflight(service, [task.task_id])
|
|
schedule = None
|
|
if scheduled:
|
|
from dx_productivity.dsh.scheduling import ScheduleStore
|
|
schedule = ScheduleStore(data).save({'task_ids': [task.task_id], 'priority': 'normal',
|
|
'not_before': '2026-01-01T00:00:00+00:00'}, report['plan_hashes'])
|
|
initial = execute_confirmed_run(service, data, [task.task_id], report, Event(), run_id, schedule=schedule)
|
|
assert initial['execution_status'] == 'failed'
|
|
context = service.task_context(task.task_id)
|
|
assert context.task.target_plan_mode is False and context.phase == 'retry' and not context.interrupted
|
|
assert calls == ['OLD-OK', 'OLD-BAD']
|
|
return {'service': service, 'store': store, 'task_id': task.task_id, 'root': data,
|
|
'run_id': run_id, 'calls': calls, 'captures': captures, 'control': control, 'schedule': schedule}
|
|
return create
|
|
|
|
|
|
def incident(case):
|
|
return IncidentRunner(case['root'], case['service'],
|
|
lambda *args: {'reply': '{"summary":"receipt checked","action":"none"}'},
|
|
lambda *args: {'status': 'unavailable'}).run(case['task_id'], 'execution_failed', 'failed rule',
|
|
run_id=case['run_id'], execution_authorized=True)
|
|
|
|
|
|
@pytest.mark.parametrize('damage', ['delete', 'tamper'])
|
|
def test_rule_retry_rechecks_failure_proof_without_spending_or_dispatching(rule_run, damage):
|
|
case = rule_run()
|
|
receipt = json.loads(case['store']._connection.execute(
|
|
"SELECT receipt_json FROM execution_operations WHERE task_id=? AND state='failed'", (case['task_id'],)).fetchone()[0])
|
|
proof = Path(receipt['proof']['failure_health']['files'][0]['path'])
|
|
if damage == 'delete':
|
|
proof.unlink()
|
|
else:
|
|
proof.write_text('tampered current health proof')
|
|
assert case['service'].execution_problem_overview(case['task_id'])['items'][0]['auto_retries_remaining'] == 1
|
|
prepared = []
|
|
original = case['service'].prepare_failed_quick_run
|
|
case['service'].prepare_failed_quick_run = lambda *args, **kwargs: (prepared.append(True), original(*args, **kwargs))[1]
|
|
result = incident(case)
|
|
assert not prepared and case['calls'] == ['OLD-OK', 'OLD-BAD']
|
|
assert result['attempts'] == 0 and result['status'] != 'resolved'
|
|
assert case['service'].execution_problems(case['task_id'])[0]['auto_retries'] == 0
|
|
|
|
|
|
def test_rule_reserves_same_operation_bound_allowance_and_no_saved_needs_no_netlist(rule_run):
|
|
case = rule_run(initial_saved=False, retry_saved=False)
|
|
result = incident(case)
|
|
assert case['calls'] == ['OLD-OK', 'OLD-BAD', 'OLD-BAD']
|
|
assert result['status'] == 'resolved'
|
|
assert case['service'].execution_problems(case['task_id'])[0]['auto_retries'] == 1
|
|
assert case['service'].reserve_problem_retry(case['task_id'], source='dsh') == ()
|
|
receipt = RunJournal(case['root']).get(case['run_id'])['result']
|
|
assert receipt['execution_status'] == 'completed' and receipt['acceptance']['status'] == 'not_required'
|
|
|
|
|
|
@pytest.mark.parametrize('acceptance', ['verified', 'different', 'unavailable'])
|
|
def test_rule_saved_retry_refreshes_original_capture_and_run_receipt(rule_run, acceptance):
|
|
case = rule_run()
|
|
before = case['root'] / 'tasks' / case['task_id'] / 'netlist-checks' / case['run_id'] / 'before' / 'capture.json'
|
|
assert before.is_file(), 'New rule-mode runs need their original full before capture'
|
|
original_before = before.read_bytes()
|
|
case['control']['acceptance'] = acceptance
|
|
result = incident(case)
|
|
assert case['calls'] == ['OLD-OK', 'OLD-BAD', 'OLD-BAD'], 'Saved first rule must never replay'
|
|
assert before.read_bytes() == original_before
|
|
assert sum(Path(path).name.startswith('after-') for path in case['captures']) >= 2
|
|
receipt = RunJournal(case['root']).get(case['run_id'])['result']
|
|
assert receipt['execution_status'] == 'completed'
|
|
assert receipt['acceptance']['status'] == acceptance
|
|
report = receipt['netlist_verification'][case['task_id']]
|
|
if acceptance == 'verified':
|
|
assert set(report['expected_changes']) == {'u-ok', 'u-bad'}
|
|
assert 'u-outside-sheet' not in report['expected_changes'], 'Same Part Number cannot invent a sheet/UID scope'
|
|
assert Path(report['report_path']).is_file()
|
|
assert (result['status'] == 'resolved') is (acceptance == 'verified')
|
|
assert receipt['status'] == ('completed' if acceptance == 'verified' else 'failed')
|
|
|
|
|
|
def test_legacy_rule_retry_cannot_create_a_replacement_before_baseline(rule_run):
|
|
import shutil
|
|
case = rule_run()
|
|
directory = case['root'] / 'tasks' / case['task_id'] / 'netlist-checks' / case['run_id']
|
|
if directory.exists():
|
|
shutil.rmtree(directory)
|
|
before_count = sum(Path(path).name == 'before' for path in case['captures'])
|
|
result = incident(case)
|
|
assert case['calls'] == ['OLD-OK', 'OLD-BAD', 'OLD-BAD']
|
|
assert result['status'] != 'resolved'
|
|
assert sum(Path(path).name == 'before' for path in case['captures']) == before_count
|
|
receipt = RunJournal(case['root']).get(case['run_id'])['result']
|
|
assert receipt['execution_status'] == 'completed' and receipt['acceptance']['status'] == 'unavailable'
|
|
|
|
|
|
def test_retry_receipt_refresh_preserves_other_task_without_dispatch(tmp_path, monkeypatch):
|
|
from types import SimpleNamespace as NS
|
|
from dx_productivity.dsh.execution_runs import execute_incident_retry
|
|
from dx_productivity.trial_task_center import netlist_verification, task_queue
|
|
selected, other, run_id = 'a' * 32, 'b' * 32, 'c' * 32
|
|
hashes = {selected: 'd' * 64, other: 'e' * 64}
|
|
monkeypatch.setattr(task_queue, '_plan_hash', lambda child, key: hashes[key])
|
|
monkeypatch.setattr(RunJournal, 'begin_retry', lambda journal, *args: journal.get(run_id))
|
|
dispatch = []
|
|
context = lambda key: NS(task=NS(name=key), interrupted=False, progress=NS(
|
|
saved_items=1, failed_items=0, no_match_items=0, completed_items=1, queue_complete=True))
|
|
def execute(key, **options):
|
|
dispatch.append(key)
|
|
return NS(paused=False)
|
|
service = NS(for_project_task=lambda key: service, task_context=context, execute_quick_run_queue=execute)
|
|
class Checks:
|
|
def __init__(self, *args): self.tasks = {}
|
|
def __enter__(self): return self
|
|
def __exit__(self, *args): pass
|
|
def before_task(self, child, key, *, existing_only): assert existing_only
|
|
def after_task(self, key, **options): assert key == selected
|
|
def finish(self): return {selected: {'status': 'verified', 'verified': True, 'report_path': 'new.json'}}
|
|
monkeypatch.setattr(netlist_verification, 'NetlistVerification', Checks)
|
|
journal = RunJournal(tmp_path)
|
|
journal.begin(run_id, [selected, other], hashes)
|
|
old_other = {'task_id': other, 'state': 'completed', 'message': 'original saved result'}
|
|
old_report = {'status': 'verified', 'verified': True, 'report_path': 'original.json'}
|
|
journal.finish(run_id, {'status': 'failed', 'entries': [
|
|
{'task_id': selected, 'state': 'failed', 'message': 'safe failure'}, old_other],
|
|
'netlist_verification': {other: old_report}})
|
|
checkpoint = tmp_path / 'task-queues' / (run_id + '.json')
|
|
checkpoint.parent.mkdir()
|
|
checkpoint.write_text(json.dumps({'version': 1, 'phase': 'finished', 'task_ids': [selected, other],
|
|
'plan_hashes': hashes, 'entries': {selected: {'state': 'failed', 'message': 'safe failure'},
|
|
other: {'state': 'completed', 'message': 'original saved result'}}}))
|
|
_, _, verification = execute_incident_retry(service, tmp_path, selected, run_id,
|
|
expected_item=('board.prj', 'OLD', 'NEW', 'preserve'), stop_event=Event())
|
|
assert dispatch == [selected] and verification['run_receipt_updated']
|
|
receipt = journal.get(run_id)['result']
|
|
assert next(row for row in receipt['entries'] if row['task_id'] == other) == old_other
|
|
assert receipt['netlist_verification'][other] == old_report
|
|
assert json.loads(checkpoint.read_text())['entries'][other] == {'state': 'completed', 'message': 'original saved result'}
|
|
|
|
|
|
@pytest.mark.parametrize('scheduled', [False, True])
|
|
def test_saved_retry_survives_fatal_first_receipt_commit_without_replay(rule_run, monkeypatch, scheduled):
|
|
case = rule_run(scheduled=scheduled)
|
|
class FatalExit(BaseException):
|
|
pass
|
|
original_finish = RunJournal.finish
|
|
def fatal_finish(journal, run_id, result):
|
|
if result.get('execution_status') == 'completed':
|
|
checkpoint = json.loads((case['root'] / 'task-queues' / (run_id + '.json')).read_text())
|
|
assert checkpoint['entries'][case['task_id']]['state'] == 'completed'
|
|
raise FatalExit('saved retry checkpoint precedes first final receipt')
|
|
return original_finish(journal, run_id, result)
|
|
with monkeypatch.context() as patch:
|
|
patch.setattr(RunJournal, 'finish', fatal_finish)
|
|
with pytest.raises(FatalExit):
|
|
incident(case)
|
|
assert case['calls'] == ['OLD-OK', 'OLD-BAD', 'OLD-BAD']
|
|
journal = RunJournal(case['root'])
|
|
restarted = journal.inspect(case['service'], case['run_id'])
|
|
assert restarted['status'] == 'running'
|
|
assert restarted['resume_ready'] and restarted['diff']['safe'], restarted['blockers']
|
|
resumed = execute_confirmed_run(case['service'], case['root'], [case['task_id']],
|
|
preflight(case['service'], [case['task_id']], allow_completed=True), Event(), case['run_id'], resume=restarted)
|
|
assert resumed['status'] == 'completed'
|
|
assert case['calls'] == ['OLD-OK', 'OLD-BAD', 'OLD-BAD'], 'Saved retry must not dispatch after receipt I/O recovery'
|
|
if scheduled:
|
|
from dx_productivity.dsh.scheduling import ScheduleStore
|
|
row = ScheduleStore(case['root']).get(case['schedule']['schedule_id'])
|
|
assert row['status'] == 'completed' and row['run_id'] == case['run_id']
|
|
|
|
|
|
@pytest.mark.parametrize('rebound', [False, True])
|
|
def test_scheduled_rule_repair_refreshes_only_the_same_bound_run(rule_run, rebound):
|
|
from dx_productivity.dsh.scheduling import ScheduleStore
|
|
case = rule_run(scheduled=True)
|
|
schedules = ScheduleStore(case['root'])
|
|
schedule_id = case['schedule']['schedule_id']
|
|
assert schedules.get(schedule_id)['status'] == 'failed'
|
|
if rebound:
|
|
with schedules._connect() as db:
|
|
db.execute("UPDATE schedules SET run_id=?,status='claimed' WHERE schedule_id=?", ('8' * 32, schedule_id))
|
|
result = incident(case)
|
|
after = schedules.get(schedule_id)
|
|
if rebound:
|
|
assert after['run_id'] == '8' * 32 and after['status'] == 'claimed'
|
|
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
|
|
assert result['status'] != 'resolved'
|
|
else:
|
|
assert result['status'] == 'resolved'
|
|
assert after['run_id'] == case['run_id'] and after['status'] == 'completed'
|
|
|
|
|
|
@pytest.mark.parametrize('damage', ['failed', 'uncertain', 'generation', 'source', 'proof_removed', 'prior_saved_proof'])
|
|
def test_retry_recovery_rejects_anything_except_bound_verified_progress(rule_run, monkeypatch, damage):
|
|
case = rule_run()
|
|
class FatalExit(BaseException): pass
|
|
original = RunJournal.finish
|
|
def fatal(journal, run_id, result):
|
|
if result.get('execution_status') == 'completed':
|
|
raise FatalExit()
|
|
return original(journal, run_id, result)
|
|
with monkeypatch.context() as patch:
|
|
patch.setattr(RunJournal, 'finish', fatal)
|
|
with pytest.raises(FatalExit):
|
|
incident(case)
|
|
journal = RunJournal(case['root'])
|
|
retry = journal.get(case['run_id'])['result']['retry']
|
|
selected, = retry['operation_keys']
|
|
store = case['store']
|
|
row = dict(store._connection.execute('SELECT * FROM execution_operations WHERE operation_key=?', (selected,)).fetchone())
|
|
if damage in {'failed', 'uncertain'}:
|
|
store._connection.execute('UPDATE execution_operations SET state=? WHERE operation_key=?', (damage, selected))
|
|
elif damage == 'generation':
|
|
store._connection.execute('UPDATE execution_operations SET generation=generation+1 WHERE operation_key=?', (selected,))
|
|
elif damage == 'source':
|
|
command = json.loads(row['command_json'])
|
|
command['project_path'] = str(Path(command['project_path']).with_name('foreign.prj'))
|
|
store._connection.execute('UPDATE execution_operations SET command_json=? WHERE operation_key=?', (json.dumps(command), selected))
|
|
elif damage == 'proof_removed':
|
|
receipt = json.loads(row['receipt_json'])
|
|
receipt['proof'] = {}
|
|
store._connection.execute('UPDATE execution_operations SET receipt_json=? WHERE operation_key=?', (json.dumps(receipt), selected))
|
|
else:
|
|
old = next(value for key, value in retry['operations'].items() if key != selected and value['state'] == 'verified')
|
|
receipt = json.loads(old['receipt_json'])
|
|
Path(receipt['proof']['files'][0]['path']).write_text('old saved proof changed')
|
|
inspected = journal.inspect(case['service'], case['run_id'])
|
|
assert not inspected['resume_ready']
|
|
assert 'retry_evidence_changed' in inspected['blockers']
|
|
assert case['calls'] == ['OLD-OK', 'OLD-BAD', 'OLD-BAD']
|
|
|
|
|
|
@pytest.mark.parametrize('unit', [None, 'inventory_empty'])
|
|
def test_dsh_rule_allowance_does_not_expand_legacy_grouped_target_modes(rule_run, monkeypatch, unit):
|
|
from dx_productivity.trial_task_center.execution_journal import ExecutionJournal
|
|
case = rule_run(initial_saved=False, retry_saved=False)
|
|
store = case['store']
|
|
row = dict(store._connection.execute("SELECT * FROM execution_operations WHERE state='failed'").fetchone())
|
|
command = json.loads(row['command_json'])
|
|
command.update(target_scope='targets', target_selectors='u-bad\x1fR2\x1fOLD VALUE')
|
|
if unit:
|
|
command['execution_unit'] = unit
|
|
store._connection.execute('UPDATE execution_operations SET command_json=? WHERE operation_key=?',
|
|
(json.dumps(command), row['operation_key']))
|
|
# Isolate the execution-unit/scope gate; live-proof behavior is exercised
|
|
# by the actual native-snapshot tests above.
|
|
monkeypatch.setattr(ExecutionJournal, 'failure_certified', lambda *args: True)
|
|
assert case['service'].reserve_problem_retry(case['task_id'], source='dsh') == ()
|
|
assert case['service'].execution_problems(case['task_id'])[0]['auto_retries'] == 0
|
|
|
|
|
|
def test_retry_intent_before_checkpoint_failure_resumes_only_pending_selection(rule_run, monkeypatch):
|
|
from dx_productivity.trial_task_center import task_queue
|
|
case = rule_run()
|
|
before = case['root'] / 'tasks' / case['task_id'] / 'netlist-checks' / case['run_id'] / 'before' / 'capture.json'
|
|
before_bytes = before.read_bytes()
|
|
class FatalExit(BaseException): pass
|
|
save = task_queue._save
|
|
def fatal_save(path, state):
|
|
if state['entries'][case['task_id']]['state'] == 'running':
|
|
assert RunJournal(case['root']).get(case['run_id'])['result']['retry']
|
|
raise FatalExit('retry intent committed; first checkpoint write failed')
|
|
return save(path, state)
|
|
with monkeypatch.context() as patch:
|
|
patch.setattr(task_queue, '_save', fatal_save)
|
|
with pytest.raises(FatalExit):
|
|
incident(case)
|
|
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
|
|
inspected = RunJournal(case['root']).inspect(case['service'], case['run_id'])
|
|
assert inspected['resume_ready'] and inspected['diff']['safe'], inspected['blockers']
|
|
assert case['task_id'] in inspected['remaining_task_ids']
|
|
resumed = execute_confirmed_run(case['service'], case['root'], [case['task_id']],
|
|
preflight(case['service'], [case['task_id']], allow_completed=True), Event(), case['run_id'], resume=inspected)
|
|
assert resumed['status'] == 'completed'
|
|
assert case['calls'] == ['OLD-OK', 'OLD-BAD', 'OLD-BAD']
|
|
assert before.read_bytes() == before_bytes
|
|
|
|
|
|
@pytest.mark.parametrize('scheduled', [False, True])
|
|
@pytest.mark.parametrize('damage', [None, 'proof_removed', 'generation'])
|
|
def test_certified_startup_pause_during_dsh_retry_survives_exit_and_resumes(rule_run, monkeypatch, tmp_path, scheduled, damage):
|
|
"""Real handlers/journals; only the native worker/COM boundary is controlled."""
|
|
monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[1] / 'v1_1'))
|
|
from test_batch_runtime import worker_runtime, Cad
|
|
from dx_productivity.trial_task_center.stop_control import StopControl
|
|
from dx_productivity.trial_task_center.errors import TaskCenterError
|
|
case = rule_run(scheduled=scheduled)
|
|
service, task_id = case['service'], case['task_id']
|
|
child = service.for_project_task(task_id)
|
|
preparer = child._quick_run_preparer
|
|
original_worker = preparer._process_runner
|
|
original_queue = service.execute_quick_run_queue
|
|
before = case['root'] / 'tasks' / task_id / 'netlist-checks' / case['run_id'] / 'before' / 'capture.json'
|
|
before_bytes = before.read_bytes()
|
|
current = {}
|
|
|
|
class FatalExit(BaseException):
|
|
pass
|
|
|
|
def monitor(command, *args, **options):
|
|
current['runtime'].stop_event.set()
|
|
result = subprocess.CompletedProcess(command, 74, '', '')
|
|
request = (Path(command[3]) / 'project-session.request').read_text(encoding='utf-8').split('\t')
|
|
result.startup_pause = dict(monitor_token='b' * 32, session_token=request[0], job_id=command[-1],
|
|
project_path=request[1], sequence=1, worker_tree_exited=True)
|
|
return result
|
|
|
|
def worker(command, timeout):
|
|
root = Path(command[3])
|
|
with (root / 'current-command.tsv').open(encoding='utf-8-sig') as stream:
|
|
row = {key: _decode_vbs_field(value) for key, value in next(csv.DictReader(stream, delimiter='\t')).items()}
|
|
(root / 'project-session.request').write_text(
|
|
f'{"a" * 32}\t{row["project_path"]}\t{command[-1]}', encoding='utf-8')
|
|
return current['runtime'].run_worker(command, timeout)
|
|
|
|
def queue_with_startup_pause(key, **options):
|
|
runtime = worker_runtime(tmp_path, monkeypatch, monitor)
|
|
runtime.cad_factory = lambda *args, stop_control=None, **kwargs: Cad(*args, **kwargs)
|
|
runtime.stop_event = StopControl()
|
|
current['runtime'] = runtime
|
|
with runtime:
|
|
try:
|
|
original_queue(key, **dict(options, runtime=runtime, stop_event=runtime.stop_event))
|
|
except TaskCenterError as error:
|
|
assert error.code == 'operation_cancelled'
|
|
assert not child.task_context(key).interrupted
|
|
assert any(json.loads(row[0]).get('startup_pause') for row in case['store']._connection.execute(
|
|
"SELECT receipt_json FROM execution_operations WHERE task_id=? AND state='pending'", (key,)))
|
|
raise FatalExit('certified pending committed; final retry run receipt not yet committed')
|
|
|
|
with monkeypatch.context() as patch:
|
|
patch.setattr(preparer, '_process_runner', worker)
|
|
patch.setattr(service, 'execute_quick_run_queue', queue_with_startup_pause)
|
|
with pytest.raises(FatalExit):
|
|
incident(case)
|
|
assert case['calls'] == ['OLD-OK', 'OLD-BAD'], 'Startup pause dispatched no replacement'
|
|
assert not list(case['root'].rglob('uncertain.flag'))
|
|
journal = RunJournal(case['root'])
|
|
if damage:
|
|
row = case['store']._connection.execute(
|
|
"SELECT * FROM execution_operations WHERE task_id=? AND state='pending'", (task_id,)).fetchone()
|
|
if damage == 'generation':
|
|
case['store']._connection.execute('UPDATE execution_operations SET generation=generation+1 WHERE operation_key=?',
|
|
(row['operation_key'],))
|
|
else:
|
|
proof = json.loads(row['receipt_json'])['startup_pause']
|
|
Path(proof['files'][0]['path']).unlink()
|
|
inspected = journal.inspect(service, case['run_id'])
|
|
assert not inspected['resume_ready'] and 'retry_evidence_changed' in inspected['blockers']
|
|
assert case['calls'] == ['OLD-OK', 'OLD-BAD']
|
|
return
|
|
inspected = journal.inspect(service, case['run_id'])
|
|
assert inspected['resume_ready'] and inspected['diff']['safe'], inspected['blockers']
|
|
assert inspected['remaining_task_ids'] == [task_id]
|
|
assert preparer._process_runner == original_worker
|
|
resumed = execute_confirmed_run(service, case['root'], [task_id],
|
|
preflight(service, [task_id], allow_completed=True), Event(), case['run_id'], resume=inspected)
|
|
assert resumed['status'] == 'completed' and resumed['run_id'] == case['run_id']
|
|
assert resumed['acceptance']['status'] == 'verified'
|
|
assert case['calls'] == ['OLD-OK', 'OLD-BAD', 'OLD-BAD']
|
|
assert before.read_bytes() == before_bytes
|
|
assert service.execution_problems(task_id)[0]['auto_retries'] == 1
|
|
assert service.reserve_problem_retry(task_id, source='dsh') == ()
|