fix(dsh): reconcile orphan schedules and preserve audit evidence
This commit is contained in:
1 parent
4aaebcb65a
commit
282252a5fb
16 files changed
+578
-27
No files matched your search
@@ -9,6 +9,7 @@ from dx_productivity.dsh.execution_runs import execute_confirmed_run
|
||||
from dx_productivity.dsh.run_journal import RunJournal
|
||||
from dx_productivity.dsh.task_lifecycle import preflight
|
||||
from test_run_journal import project_service
|
||||
from test_run_journal import checkpoint, evidence
|
||||
|
||||
|
||||
def test_second_resume_after_fatal_exit_preserves_verified_progress_and_runs_each_task_once(project_service, monkeypatch):
|
||||
@@ -51,3 +52,28 @@ def test_second_resume_after_fatal_exit_preserves_verified_progress_and_runs_eac
|
||||
assert last['status'] == 'completed' and last['queue_id'] == run_id
|
||||
assert calls == ids
|
||||
assert all(task['saved_items'] == 0 and task['no_match_items'] == 1 for task in last['tasks'])
|
||||
|
||||
|
||||
def test_resume_soft_failure_retains_the_last_evidence_baseline(project_service, monkeypatch):
|
||||
service, _, data, ids, hashes = project_service
|
||||
journal = RunJournal(data)
|
||||
run_id = 'e' * 32
|
||||
journal.begin(run_id, ids, hashes)
|
||||
checkpoint(data, run_id, ids, hashes)
|
||||
prior = {'status': 'paused', 'tasks': [{'task_id': ids[0], 'saved_items': 0, 'failed_items': 0,
|
||||
'no_match_items': 0, 'queue_complete': False, 'interrupted': False}],
|
||||
'entries': [{'task_id': key, 'state': 'paused' if key == ids[0] else 'pending'} for key in ids]}
|
||||
journal.finish(run_id, prior)
|
||||
resume = journal.inspect(service, run_id)
|
||||
def unavailable(*args, **kwargs):
|
||||
raise OSError('controlled queue failure before progress')
|
||||
monkeypatch.setattr('dx_productivity.dsh.execution_runs.execute_task_queue', unavailable)
|
||||
with pytest.raises(OSError):
|
||||
execute_confirmed_run(service, data, ids, preflight(service, ids), Event(), run_id, resume=resume)
|
||||
result = journal.get(run_id)['result']
|
||||
assert result['status'] == 'interrupted'
|
||||
assert result['tasks'] == prior['tasks'] and result['entries'] == prior['entries']
|
||||
evidence(service, ids[0])
|
||||
inspected = journal.inspect(service, run_id)
|
||||
assert inspected['diff']['evidence_baseline_available']
|
||||
assert 'evidence_changed' in inspected['blockers']
|
||||
@@ -0,0 +1,86 @@
|
||||
import hashlib
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.dsh.scheduling import ScheduleStore
|
||||
|
||||
|
||||
def populate(root, count=6):
|
||||
store = ScheduleStore(root)
|
||||
with store._connect() as db:
|
||||
for index in range(count):
|
||||
store._event(db, 'a' * 32, '2026-10-31T12:00:00Z', 'result', 'b' * 32,
|
||||
{'status': 'completed', 'index': index})
|
||||
return store
|
||||
|
||||
|
||||
def test_archive_bounds_hot_events_without_losing_original_records(tmp_path):
|
||||
store = populate(tmp_path)
|
||||
before = store.events()
|
||||
first = store.archive_events(keep=2, batch=2)
|
||||
assert first['archived'] == 2
|
||||
assert len(store.events()) == 4
|
||||
store.archive_events(keep=2, batch=2)
|
||||
summary = ScheduleStore(tmp_path).audit_status(keep=2)
|
||||
assert summary['live_events'] == 2 and summary['archived_events'] == 4
|
||||
archived = []
|
||||
for path in sorted((tmp_path / 'dsh/schedule-audit').glob('*.jsonl')):
|
||||
raw = path.read_bytes()
|
||||
assert path.stem.endswith(hashlib.sha256(raw).hexdigest())
|
||||
archived.extend(json.loads(line) for line in raw.splitlines())
|
||||
assert sorted(archived + store.events(), key=lambda row: row['sequence']) == list(reversed(before))
|
||||
assert store.archive_events(keep=2)['archived'] == 0
|
||||
|
||||
|
||||
def test_failed_archive_export_never_deletes_audit_events(tmp_path, monkeypatch):
|
||||
from dx_productivity.dsh import schedule_audit
|
||||
store = populate(tmp_path)
|
||||
before = store.events()
|
||||
def unavailable(*args):
|
||||
raise OSError('controlled export failure')
|
||||
monkeypatch.setattr(schedule_audit, '_write_archive', unavailable)
|
||||
with pytest.raises(OSError):
|
||||
store.archive_events(keep=2)
|
||||
assert store.events() == before
|
||||
|
||||
|
||||
def test_database_failure_after_archive_is_safe_and_retryable(tmp_path):
|
||||
store = populate(tmp_path)
|
||||
before = store.events()
|
||||
with sqlite3.connect(store.path) as db:
|
||||
db.execute("CREATE TRIGGER reject_trim BEFORE DELETE ON schedule_events BEGIN SELECT RAISE(ABORT, 'controlled fault'); END")
|
||||
with pytest.raises(sqlite3.IntegrityError):
|
||||
store.archive_events(keep=2)
|
||||
assert store.events() == before
|
||||
files = list((tmp_path / 'dsh/schedule-audit').glob('*.jsonl'))
|
||||
assert len(files) == 1
|
||||
raw = files[0].read_bytes()
|
||||
with sqlite3.connect(store.path) as db:
|
||||
db.execute('DROP TRIGGER reject_trim')
|
||||
store.archive_events(keep=2)
|
||||
assert files[0].read_bytes() == raw
|
||||
assert store.audit_status(keep=2)['archived_events'] == 4
|
||||
|
||||
|
||||
@pytest.mark.parametrize('damage', ['missing', 'changed'])
|
||||
def test_missing_or_changed_committed_archive_is_never_reported_healthy(tmp_path, damage):
|
||||
store = populate(tmp_path)
|
||||
store.audit_status(keep=2)
|
||||
archive = next((tmp_path / 'dsh/schedule-audit').glob('*.jsonl'))
|
||||
if damage == 'missing':
|
||||
archive.unlink()
|
||||
else:
|
||||
archive.write_bytes(b'corrupted evidence\n')
|
||||
with pytest.raises(OSError):
|
||||
store.audit_status(keep=2)
|
||||
|
||||
|
||||
def test_automatic_rotation_batches_overflow_instead_of_creating_one_file_per_event(tmp_path):
|
||||
store = populate(tmp_path, count=3)
|
||||
assert store.audit_status(keep=2)['archived_events'] == 0
|
||||
with store._connect() as db:
|
||||
store._event(db, 'a' * 32, '2026-10-31T12:00:00Z', 'result', None, {'status': 'completed'})
|
||||
status = store.audit_status(keep=2)
|
||||
assert status['live_events'] == 2 and status['archived_events'] == 2
|
||||
@@ -186,3 +186,98 @@ def test_cancel_is_durable_and_cannot_cancel_an_owned_claim(project_service):
|
||||
schedules.claim(claimed['schedule_id'])
|
||||
with pytest.raises(TaskCenterError):
|
||||
schedules.cancel(claimed['schedule_id'])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('run_state', [None, 'running', 'completed', 'paused', 'failed'])
|
||||
def test_reconcile_orphan_claim_preserves_original_run_and_never_replays(project_service, run_state):
|
||||
from dx_productivity.dsh.run_journal import RunJournal
|
||||
service, _, data, ids, hashes = project_service
|
||||
schedules = ScheduleStore(data)
|
||||
row = schedules.save(spec(ids, auto_start=True), hashes)
|
||||
run_id = 'c' * 32
|
||||
schedules.claim(row['schedule_id'], run_id=run_id, automatic=True)
|
||||
journal = RunJournal(data)
|
||||
if run_state:
|
||||
journal.begin(run_id, ids, hashes, schedule_id=row['schedule_id'])
|
||||
if run_state != 'running':
|
||||
journal.finish(run_id, {'status': run_state, 'tasks': [], 'entries': []})
|
||||
before = journal.get(run_id)
|
||||
reopened = ScheduleStore(data)
|
||||
result = reopened.reconcile_claim(service, row['schedule_id'])
|
||||
expected = run_state if run_state in {'completed', 'failed'} else 'interrupted'
|
||||
assert result['status'] == expected and result['run_id'] == run_id
|
||||
assert journal.get(run_id) == before
|
||||
assert result['result']['reconciled'] is True
|
||||
assert reopened.events()[0]['event'] == 'result'
|
||||
assert reopened.events()[0]['payload']['reconciled'] is True
|
||||
assert not reopened.evaluate(service, now=NOW)[0]['dispatchable']
|
||||
assert not list(data.rglob('command.tsv'))
|
||||
|
||||
|
||||
def test_reconcile_refuses_active_owner_and_pending_resources(project_service, monkeypatch):
|
||||
service, _, data, ids, hashes = project_service
|
||||
schedules = ScheduleStore(data)
|
||||
row = schedules.save(spec(ids), hashes)
|
||||
schedules.claim(row['schedule_id'], run_id='d' * 32)
|
||||
with schedules.execution_lease(row['schedule_id']):
|
||||
with pytest.raises(TaskCenterError, match='schedule_busy'):
|
||||
ScheduleStore(data).reconcile_claim(service, row['schedule_id'])
|
||||
monkeypatch.setattr(service, 'pending_batch_resources', lambda: [object()])
|
||||
with pytest.raises(TaskCenterError, match='schedule_busy'):
|
||||
schedules.reconcile_claim(service, row['schedule_id'])
|
||||
assert schedules.get(row['schedule_id'])['status'] == 'claimed'
|
||||
assert len(schedules.events()) == 1
|
||||
|
||||
|
||||
def test_reconcile_audit_failure_leaves_claim_unchanged(project_service):
|
||||
import sqlite3
|
||||
service, _, data, ids, hashes = project_service
|
||||
schedules = ScheduleStore(data)
|
||||
row = schedules.save(spec(ids), hashes)
|
||||
schedules.claim(row['schedule_id'])
|
||||
with sqlite3.connect(schedules.path) as db:
|
||||
db.execute("CREATE TRIGGER reject_result BEFORE INSERT ON schedule_events BEGIN SELECT RAISE(ABORT, 'controlled fault'); END")
|
||||
with pytest.raises(sqlite3.IntegrityError):
|
||||
schedules.reconcile_claim(service, row['schedule_id'])
|
||||
assert schedules.get(row['schedule_id'])['status'] == 'claimed'
|
||||
|
||||
|
||||
def test_hard_process_exit_releases_schedule_lease_for_native_reconciliation(project_service):
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
service, _, data, ids, hashes = project_service
|
||||
schedules = ScheduleStore(data)
|
||||
row = schedules.save(spec(ids, auto_start=True), hashes)
|
||||
child = subprocess.run([sys.executable, '-c',
|
||||
"import os,sys; sys.path.insert(0, 'src'); from dx_productivity.dsh.scheduling import ScheduleStore; "
|
||||
"s=ScheduleStore(sys.argv[1]); lease=s.execution_lease(sys.argv[2]); lease.__enter__(); "
|
||||
"s.claim(sys.argv[2],run_id='e'*32,automatic=True); os._exit(19)", str(data), row['schedule_id']],
|
||||
cwd=Path(__file__).resolve().parents[2], capture_output=True, timeout=20)
|
||||
assert child.returncode == 19, child.stderr.decode('utf8', 'replace')
|
||||
assert ScheduleStore(data).get(row['schedule_id'])['status'] == 'claimed'
|
||||
result = ScheduleStore(data).reconcile_claim(service, row['schedule_id'])
|
||||
assert result['status'] == 'interrupted' and result['run_id'] == 'e' * 32
|
||||
|
||||
|
||||
def test_active_claim_in_another_process_cannot_be_reconciled(project_service):
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
service, _, data, ids, hashes = project_service
|
||||
schedules = ScheduleStore(data)
|
||||
row = schedules.save(spec(ids, auto_start=True), hashes)
|
||||
child = subprocess.Popen([sys.executable, '-c',
|
||||
"import sys; sys.path.insert(0,'src'); from dx_productivity.dsh.scheduling import ScheduleStore; "
|
||||
"s=ScheduleStore(sys.argv[1]); lease=s.execution_lease(sys.argv[2]); lease.__enter__(); "
|
||||
"s.claim(sys.argv[2],run_id='f'*32,automatic=True); print('ready',flush=True); "
|
||||
"sys.stdin.buffer.read(1); lease.__exit__(None,None,None)", str(data), row['schedule_id']],
|
||||
cwd=Path(__file__).resolve().parents[2], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
assert child.stdout.readline().strip() == b'ready'
|
||||
with pytest.raises(TaskCenterError, match='schedule_busy'):
|
||||
schedules.reconcile_claim(service, row['schedule_id'])
|
||||
assert schedules.get(row['schedule_id'])['status'] == 'claimed'
|
||||
finally:
|
||||
child.communicate(input=b'q', timeout=10)
|
||||
assert child.returncode == 0
|
||||
Reference in new issue
Block a user