test: cover shared retry budgets and supervisor process crashes

This commit is contained in:
阿白叔 committed 2026-10-23 16:11:22 +08:00
1 parent 9837ca581b
commit 62f143fe9f
3 files changed
+165

No files matched your search

@@ -0,0 +1,13 @@
# Supervisor safety regression evidence boundaries
These automated tests do not open CAD or certify schematic property writes.
| Test | Real behavior exercised | Replaced behavior |
| --- | --- | --- |
| `test_mock_native_read_recovery_spends_same_project_worker_retry_budget` | Durable source hashes and attempt proof, runtime rebuild decision, shared native/worker project budget | Desktop/CAD ownership and worker failure |
| `test_mock_different_projects_each_get_one_retry_without_accumulating_budget` | Two project identities, one rebuild per project, successful execution cannot replenish a spent budget | Desktop/CAD ownership and monitored worker execution |
| `test_real_supervisor_process_crash_reconciles_without_replaying_mock_business` | Separate Python child, production admission and one-shot claim, process creation identity, hard `os._exit`, durable saved-result fallback, uncertainty protection at legacy/project-task evidence roots, separate cleanup child | Business replacement writes a durable witness instead of using CAD; no private desktop or CAD resources are acquired |
The process test covers both an unknown outcome before publication and a completed business result published before a crash. Cleanup must neither execute the witness operation again nor alter an earlier completed result. Unknown outcomes retain their original protection marker after reconciliation; proven completed outcomes do not acquire an uncertainty marker.
Remaining physical acceptance: inject failures in the frozen executable before and after the actual first CAD mutation, prove marker/helper durability failure prevents every production write/save path, and confirm actual CAD/desktop release and independent schematic readback. The tests above do not provide that evidence.
+63
View File
@@ -367,6 +367,69 @@ def test_native_rebuild_requires_strict_source_and_worker_proof(tmp_path):
assert len(Desktop.created) == 2
def test_mock_native_read_recovery_spends_same_project_worker_retry_budget(tmp_path, monkeypatch):
"""Real durable proof/runtime logic; desktop, CAD and worker failure are fakes."""
import hashlib
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
command, project = command_for(tmp_path)
database = project.parent / 'database.dat'
database.write_bytes(b'unchanged database')
evidence = Path(command[3]) / 'native'
evidence.mkdir()
calls = []
def fail_worker(*args, **kwargs):
calls.append(1)
raise WorkerMonitorError('prewrite failure after native recovery')
runtime = worker_runtime(tmp_path, monkeypatch, fail_worker)
with runtime:
with runtime.native_scope(evidence) as scope:
pass
proof = {'version': 1, 'native_read_only': True, 'workers_closed': True,
'binding': scope.identity, 'project_path': str(project.resolve()),
'evidence_root': str(evidence.resolve()),
'source_hashes': {str(path.resolve()): hashlib.sha256(path.read_bytes()).hexdigest()
for path in (project, database)}}
(evidence / 'native-retry-proof.json').write_text(json.dumps(proof))
assert runtime.recover_native_failure(project, evidence, 'read timeout')
assert len(Desktop.created) == 2 and Desktop.created[0].released
with pytest.raises(WorkerMonitorError, match='after native recovery'):
runtime.run_worker(command, 5)
assert calls == [1]
assert len(Desktop.created) == 2
assert not runtime.recover_native_failure(project, evidence, 'another read timeout')
assert all(desktop.released for desktop in Desktop.created)
assert runtime.record['retries'][str(project.resolve()).casefold()]['count'] == 1
def test_mock_different_projects_each_get_one_retry_without_accumulating_budget(tmp_path, monkeypatch):
"""Real per-project accounting; fake CAD/desktop and unchanged prewrite failures."""
import subprocess
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
one, project_one = command_for(tmp_path)
two, project_two = command_for(tmp_path, 'two')
calls = {one[3]: 0, two[3]: 0}
def monitor(command, *args, **kwargs):
calls[command[3]] += 1
if calls[command[3]] == 2:
return subprocess.CompletedProcess(command, 0, '', '')
raise WorkerMonitorError('unchanged prewrite failure')
runtime = worker_runtime(tmp_path, monkeypatch, monitor)
with runtime:
runtime.run_worker(one, 5)
assert len(Desktop.created) == 2
runtime.run_worker(two, 5)
assert len(Desktop.created) == 3 # Each project gets its own single rebuild.
for command in (one, two):
with pytest.raises(WorkerMonitorError, match='prewrite failure'):
runtime.run_worker(command, 5)
assert len(Desktop.created) == 3 # Success cannot replenish either budget.
assert calls == {one[3]: 3, two[3]: 3}
assert set(runtime.record['retries']) == {
str(project_one.resolve()).casefold(), str(project_two.resolve()).casefold()}
assert all(value['count'] == 1 for value in runtime.record['retries'].values())
assert all(desktop.released for desktop in Desktop.created)
def test_release_publication_failure_can_be_reconciled_without_replaying(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import batch_runtime
runtime = batch_runtime.BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop)
+89
View File
@@ -159,3 +159,92 @@ def test_parent_job_cleanup_failure_preserves_result_and_can_retry_resources_onl
assert not service.pending_batch_resources()
finally:
store.close()
@pytest.mark.parametrize('bound_task', [False, True], ids=['legacy-root', 'project-task-root'])
@pytest.mark.parametrize('saved_success', [False, True], ids=['unknown-write', 'saved-business-success'])
def test_real_supervisor_process_crash_reconciles_without_replaying_mock_business(
tmp_path, monkeypatch, bound_task, saved_success):
"""Real child admission, hard exit, result proof and cleanup; no CAD/desktop.
Only the child business method is replaced with a durable witness write.
This tests process-crash orchestration, not actual schematic write safety.
"""
import sys
import textwrap
from dx_productivity.trial_task_center import batch_supervisor as supervisor
from dx_productivity.trial_task_center.errors import TaskCenterError
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 / 'task-center.db')
try:
service = TaskCenterService(store, configure_logging(tmp_path), supervised=True)
task = store.create_task('crash fixture')
if bound_task:
project_path = tmp_path / 'fixture.prj'
project_path.write_text('placeholder; never opened in CAD')
project = store.sync_projects(task.task_id, tmp_path, (project_path,))[0]
store.bind_project_task(task.task_id, project.project_id, 'crash-fixture', 0)
evidence = service._project_task_service(task.task_id)._quick_run_preparer.data_root
witness = evidence / 'quick-run/crash-business-witness.txt'
previous = supervisor.run_supervised(service, 'probe', {})
previous_files = {path: path.read_bytes() for path in
(tmp_path / 'batch-resources').glob('*/*result.json')}
original_command = supervisor._command
bootstrap = textwrap.dedent('''
import os, sys
from pathlib import Path
from dx_productivity.trial_task_center import batch_worker, batch_resources
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.quick_run_protocol import QuickRunStepResult
saved_success = sys.argv[2] == 'yes'
def business(self, task_id, **kwargs):
root = self._project_task_service(task_id)._quick_run_preparer.data_root / 'quick-run'
root.mkdir(parents=True, exist_ok=True)
with (root / 'crash-business-witness.txt').open('a', encoding='utf-8') as stream:
stream.write(str(os.getpid()) + '\\n')
stream.flush()
os.fsync(stream.fileno())
if not saved_success:
os._exit(73)
return QuickRunStepResult(root/'worker.vbs', root/'command.tsv', root/'status.tsv',
root/'events.log', 'restored_ok', 'mock business completed')
TaskCenterService.execute_quick_run = business
original_write = batch_resources.write_record
def write_then_crash(path, value):
original_write(path, value)
if Path(path).name == 'business-result.json':
os._exit(74)
batch_resources.write_record = write_then_crash
batch_worker.run(Path(sys.argv[1]))
''')
def command(request):
if json.loads(request.read_text(encoding='utf-8'))['operation'] == 'execute_quick_run':
return (sys.executable, '-c', bootstrap, str(request), 'yes' if saved_success else 'no')
return original_command(request)
monkeypatch.setattr(supervisor, '_command', command)
if saved_success:
result = supervisor.run_supervised(service, 'execute_quick_run', {'task_id': task.task_id})
assert result.state == 'restored_ok'
else:
with pytest.raises(TaskCenterError) as caught:
supervisor.run_supervised(service, 'execute_quick_run', {'task_id': task.task_id})
assert caught.value.code == 'supervisor_interrupted'
executions = witness.read_text().splitlines()
assert len(executions) == 1 and int(executions[0]) not in {os.getpid(), previous['pid']}
marker = evidence / 'quick-run/uncertain.flag'
assert marker.exists() is (not saved_success)
other_root = tmp_path if bound_task else tmp_path / 'tasks' / task.task_id
assert not (other_root / 'quick-run/uncertain.flag').exists()
protection = marker.read_bytes() if marker.exists() else None
assert not list((tmp_path / 'batch-resources').glob('*/session.json'))
# A new real cleanup supervisor performs resource reconciliation only.
assert service.cleanup_batch_resources() == ()
assert not service.pending_batch_resources()
assert witness.read_text().splitlines() == executions
assert (marker.read_bytes() if marker.exists() else None) == protection
assert all(path.read_bytes() == value for path, value in previous_files.items())
finally:
store.close()