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
|
||||
@@ -11,6 +11,62 @@ def setup_view(ui, monkeypatch):
|
||||
return ui.window._dsh_view
|
||||
|
||||
|
||||
@pytest.mark.parametrize('missing', [False, True])
|
||||
def test_terminal_history_sums_persisted_counts_and_preserves_unknown(ui, monkeypatch, qtbot, missing):
|
||||
from dx_productivity.dsh.task_lifecycle import preflight
|
||||
view = setup_view(ui, monkeypatch)
|
||||
ctl = ui.window._dsh_operations
|
||||
ids = [task.task_id for task in ui.tasks]
|
||||
ctl.runs.begin('e' * 32, ids, preflight(ui.service, ids)['plan_hashes'])
|
||||
tasks = [{'task_id': ids[0], 'saved_items': 2, 'failed_items': 0, 'no_match_items': 1},
|
||||
{'task_id': ids[1], 'saved_items': None if missing else 3, 'failed_items': 1, 'no_match_items': 0}]
|
||||
ctl.runs.finish('e' * 32, {'status': 'failed', 'tasks': tasks})
|
||||
ctl.refresh()
|
||||
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
|
||||
row = view.operations['runs'][0]
|
||||
assert row['counters'] == {'saved_items': None if missing else 5, 'failed_items': 1, 'no_match_items': 1}
|
||||
assert row['tasks'] == tasks
|
||||
|
||||
|
||||
def test_orphan_schedule_reconciliation_waits_for_native_confirmation(ui, monkeypatch, qtbot):
|
||||
from dx_productivity.dsh.task_lifecycle import preflight
|
||||
from PySide6.QtWidgets import QDialogButtonBox
|
||||
view = setup_view(ui, monkeypatch)
|
||||
ctl = ui.window._dsh_operations
|
||||
ids = [ui.tasks[0].task_id]
|
||||
row = ctl.schedules.save({'task_ids': ids, 'not_before': '2026-10-30T12:00:00Z'}, preflight(ui.service, ids)['plan_hashes'])
|
||||
ctl.schedules.claim(row['schedule_id'], run_id='9' * 32)
|
||||
for key, accept in [('1', False), ('2', True)]:
|
||||
ctl.request({'request_id': key * 32, 'spec': {'operation': 'reconcile_schedule', 'schedule_id': row['schedule_id']}})
|
||||
qtbot.waitUntil(lambda: ctl.dialog is not None, timeout=5000)
|
||||
assert ctl.schedules.get(row['schedule_id'])['status'] == 'claimed'
|
||||
button = QDialogButtonBox.StandardButton.Ok if accept else QDialogButtonBox.StandardButton.Cancel
|
||||
qtbot.mouseClick(ctl.dialog.buttons.button(button), Qt.MouseButton.LeftButton)
|
||||
qtbot.waitUntil(lambda: len(view.lifecycle_results) == int(key), timeout=5000)
|
||||
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
|
||||
assert ctl.schedules.get(row['schedule_id'])['status'] == ('interrupted' if accept else 'claimed')
|
||||
assert view.lifecycle_results[-1]['status'] == 'schedule_reconciled'
|
||||
assert view.operations['schedule_events'][0]['payload']['reconciled'] is True
|
||||
assert not ui.calls
|
||||
|
||||
|
||||
def test_missing_schedule_archive_degrades_its_section_without_hiding_history(ui, monkeypatch, qtbot):
|
||||
view = setup_view(ui, monkeypatch)
|
||||
ctl = ui.window._dsh_operations
|
||||
with ctl.schedules._connect() as db:
|
||||
for _ in range(4):
|
||||
ctl.schedules._event(db, 'a' * 32, '2026-10-31T12:00:00Z', 'result', None, {'status': 'completed'})
|
||||
ctl.schedules.archive_events(keep=2)
|
||||
next((ui.data / 'dsh/schedule-audit').glob('*.jsonl')).unlink()
|
||||
ctl.refresh()
|
||||
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
|
||||
assert view.operations['schedule_audit']['status'] == 'unavailable'
|
||||
assert view.operations['section_errors'] == [{'section': 'schedule_audit', 'code': 'section_unavailable'}]
|
||||
assert view.operations['health']['status'] == 'degraded'
|
||||
assert len(view.operations['schedule_events']) == 2
|
||||
assert isinstance(view.operations['runs'], list)
|
||||
|
||||
|
||||
def test_live_snapshot_reports_running_and_pause_request_without_claiming_paused(ui, monkeypatch):
|
||||
view = setup_view(ui, monkeypatch)
|
||||
window = ui.window
|
||||
@@ -199,13 +255,14 @@ def test_audit_read_error_does_not_hide_health_or_leak_error_text(ui, monkeypatc
|
||||
assert 'private-test-value' not in json.dumps(view.operations)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('section', ['experiences', 'schedule_events'])
|
||||
@pytest.mark.parametrize('section', ['experiences', 'schedule_events', 'schedule_audit'])
|
||||
def test_independent_section_failure_keeps_schedules_and_health_visible(ui, monkeypatch, qtbot, section):
|
||||
view = setup_view(ui, monkeypatch)
|
||||
ctl = ui.window._dsh_operations
|
||||
def unavailable(*_args, **_kwargs):
|
||||
raise OSError('Authorization: Bearer private-test-value')
|
||||
target, method = (ctl.experiences, 'refresh') if section == 'experiences' else (ctl.schedules, 'events')
|
||||
target, method = (ctl.experiences, 'refresh') if section == 'experiences' else (
|
||||
ctl.schedules, 'events' if section == 'schedule_events' else 'audit_status')
|
||||
monkeypatch.setattr(target, method, unavailable)
|
||||
ctl.refresh()
|
||||
qtbot.waitUntil(lambda: ctl.worker is None, timeout=5000)
|
||||
|
||||
Reference in new issue
Block a user