import json from pathlib import Path import subprocess import sys import pytest from dx_productivity.trial_task_center import batch_resources, batch_worker, operation_diagnostics from dx_productivity.trial_task_center.project_session import ProjectSessionWorker from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError from test_project_session import toy_worker def events(root): path = root / 'operation-events.jsonl' return [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()] if path.exists() else [] def test_native_step_and_commit_enter_events_precede_real_worker_dispatch(tmp_path): command = toy_worker(tmp_path) script = Path(command[2]) source = script.read_text(encoding='utf-8').replace('job=initial; sequence=0', '''job=initial; sequence=0 events=[json.loads(line) for line in (root/'operation-events.jsonl').read_text().splitlines()] assert any(e['operation']=='native_step' and e['event']=='enter' and e['item_id']==job for e in events)''') source = source.replace("if job=='close':break", '''if job=='close': events=[json.loads(line) for line in (root/'operation-events.jsonl').read_text().splitlines()] assert any(e['operation']=='close_project' and e['event']=='enter' for e in events) break''') script.write_text(source, encoding='utf-8') worker = ProjectSessionWorker(tmp_path / 'board.prj', tmp_path) try: assert worker.run_step(command, 3).returncode == 0 assert [(e['operation'], e['event']) for e in events(tmp_path)] == [('native_step', 'enter'), ('native_step', 'return')] assert not (tmp_path / 'closed.txt').exists() finally: worker.close() assert [(e['operation'], e['event']) for e in events(tmp_path)] == [ ('native_step', 'enter'), ('native_step', 'return'), ('close_project', 'enter'), ('close_project', 'return')] assert not any(e['operation'] in {'item', 'readback'} for e in events(tmp_path)) @pytest.mark.parametrize('diagnostic_failure', [False, True]) def test_native_failure_keeps_primary_error_even_when_diagnostics_fail(tmp_path, monkeypatch, diagnostic_failure): command = toy_worker(tmp_path) script = Path(command[2]) script.write_text(script.read_text(encoding='utf-8').replace('saved_ok', 'invalid_checkpoint'), encoding='utf-8') if diagnostic_failure: monkeypatch.setattr(operation_diagnostics, 'record_operation', lambda *args, **kwargs: (_ for _ in ()).throw(OSError('diagnostic disk failure'))) worker = ProjectSessionWorker(tmp_path / 'board.prj', tmp_path) try: with pytest.raises(WorkerMonitorError, match='invalid checkpoint'): worker.run_step(command, 3) finally: worker.close() if not diagnostic_failure: records = [row for row in events(tmp_path) if row['operation'] == 'native_step'] assert [row['event'] for row in records] == ['enter', 'error'] assert 'invalid checkpoint' in records[-1]['error'] def test_diagnostic_failure_does_not_block_worker_success_or_native_close(tmp_path, monkeypatch): monkeypatch.setattr(operation_diagnostics, 'record_operation', lambda *args, **kwargs: (_ for _ in ()).throw(OSError('diagnostic disk failure'))) worker = ProjectSessionWorker(tmp_path / 'board.prj', tmp_path) try: assert worker.run_step(toy_worker(tmp_path), 3).returncode == 0 finally: worker.close() assert (tmp_path / 'closed.txt').exists() def test_native_close_failure_logs_error_and_never_a_successful_close(tmp_path): command = toy_worker(tmp_path) script = Path(command[2]) script.write_text(script.read_text(encoding='utf-8') + '\nsys.exit(7)\n', encoding='utf-8') worker = ProjectSessionWorker(tmp_path / 'board.prj', tmp_path) assert worker.run_step(command, 3).returncode == 0 with pytest.raises(WorkerMonitorError, match='did not close cleanly'): worker.close() closing = [row for row in events(tmp_path) if row['operation'] == 'close_project'] assert [row['event'] for row in closing] == ['enter', 'error'] worker.close() assert [row for row in events(tmp_path) if row['operation'] == 'close_project'] == closing def test_result_persistence_enter_is_durable_before_actual_result_write(tmp_path, monkeypatch): original = batch_resources.write_record def observe(path, value): assert [(e['operation'], e['event']) for e in events(tmp_path)] == [('result_persistence', 'enter')] assert not path.exists() original(path, value) monkeypatch.setattr(batch_resources, 'write_record', observe) result = {'attempt_id': 'attempt', 'payload': {'status': 'ok'}} batch_worker._persist_result(tmp_path, result) assert json.loads((tmp_path / 'result.json').read_text(encoding='utf-8')) == result assert [(e['operation'], e['event']) for e in events(tmp_path)] == [('result_persistence', 'enter'), ('result_persistence', 'return')] @pytest.mark.parametrize('diagnostic_failure', [False, True]) def test_result_write_failure_remains_original_exception_and_never_logs_success(tmp_path, monkeypatch, diagnostic_failure): failure = OSError('result storage failed') monkeypatch.setattr(batch_resources, 'write_record', lambda *args: (_ for _ in ()).throw(failure)) if diagnostic_failure: monkeypatch.setattr(operation_diagnostics, 'record_operation', lambda *args, **kwargs: (_ for _ in ()).throw(OSError('diagnostic disk failure'))) with pytest.raises(OSError) as caught: batch_worker._persist_result(tmp_path, {'attempt_id': 'attempt'}) assert caught.value is failure assert not (tmp_path / 'result.json').exists() if not diagnostic_failure: assert [e['event'] for e in events(tmp_path)] == ['enter', 'error'] assert events(tmp_path)[-1]['error'] == 'result storage failed' def test_diagnostic_failure_does_not_block_actual_result_persistence(tmp_path, monkeypatch): monkeypatch.setattr(operation_diagnostics, 'record_operation', lambda *args, **kwargs: (_ for _ in ()).throw(OSError('diagnostic disk failure'))) batch_worker._persist_result(tmp_path, {'attempt_id': 'attempt', 'payload': 'completed'}) assert json.loads((tmp_path / 'result.json').read_text(encoding='utf-8'))['payload'] == 'completed' def test_real_supervisor_result_write_uses_structured_persistence_boundary(tmp_path): from dx_productivity.trial_task_center.batch_supervisor import run_supervised 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 store = TaskStore(tmp_path / 'tasks.db') try: service = TaskCenterService(store, configure_logging(tmp_path)) result = run_supervised(service, 'probe', {}) assert result['resource_state'] == 'not_acquired' directory = next((tmp_path / 'batch-resources').iterdir()) assert [row['event'] for row in events(directory) if row['operation'] == 'result_persistence'] == ['enter', 'return'] assert (directory / 'result.json').exists() finally: store.close() def test_result_write_process_crash_leaves_durable_incomplete_boundary(tmp_path): source = Path(__file__).resolve().parents[2] / 'src' script = '''import os,sys from pathlib import Path sys.path.insert(0,sys.argv[1]) from dx_productivity.trial_task_center import batch_resources,batch_worker batch_resources.write_record=lambda *args: os._exit(23) batch_worker._persist_result(Path(sys.argv[2]),{'attempt_id':'attempt'}) ''' result = subprocess.run((sys.executable, '-c', script, str(source), str(tmp_path)), capture_output=True, timeout=10) assert result.returncode == 23, result.stderr summary = operation_diagnostics.summarize_operations(events(tmp_path)) assert [(e['operation'], e['item_id']) for e in summary['incomplete_operations']] == [('result_persistence', 'attempt')] assert not (tmp_path / 'result.json').exists() def test_incomplete_actual_operation_can_be_reported_before_return(tmp_path): with operation_diagnostics.operation_span(tmp_path, 'native_step', item_id='job'): summary = operation_diagnostics.summarize_operations(events(tmp_path)) assert [(e['operation'], e['item_id']) for e in summary['incomplete_operations']] == [('native_step', 'job')] assert summary['last_successful_item'] is None assert operation_diagnostics.summarize_operations(events(tmp_path))['incomplete_operations'] == [] def test_diagnostic_serialization_failure_is_nonblocking(tmp_path): assert operation_diagnostics.record_operation(tmp_path, 'native_step', 'enter', item_id=object()) is False