fix: reconcile saved database locks without replaying replacements
Core regression / Python core, intervention UI and release configuration (push) Successful in 4m44s
Core regression / JavaScript syntax (push) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 3m57s
Core regression / JavaScript syntax (pull_request) Successful in 6s

This commit is contained in:
阿白叔 committed 2026-11-18 18:24:50 +08:00
1 parent cdbc92fab8
commit e63a82b695
10 files changed
+748 -15

No files matched your search

+300
View File
@@ -0,0 +1,300 @@
import json
from pathlib import Path
from threading import Event
import pytest
def locked(code=32):
error = PermissionError('database is busy')
error.winerror = code
return error
def inputs(tmp_path):
project = tmp_path / 'project/test.prj'
project.parent.mkdir()
project.write_text('KEY iCDBDir "database"\n')
database = project.parent / 'database/icdb.dat'
database.parent.mkdir()
database.write_bytes(b'saved database')
root = tmp_path / 'data/quick-run'
root.mkdir(parents=True)
(root / 'command.tsv').write_text('frozen command')
return project, database, root
def test_transient_sharing_conflict_retries_reads_and_preserves_saved_marker(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import saved_source
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
project, database, root = inputs(tmp_path)
original = saved_source.source_hash
failures = []
def read(path):
if Path(path).name == 'icdb.dat' and not failures:
failures.append(True)
raise locked()
return original(path)
monkeypatch.setattr(saved_source, 'source_hash', read)
monkeypatch.setattr(saved_source.time, 'sleep', lambda _: None)
proof = bind_project_commit_source({'session_token': 'a'*32}, root.parent, root, project)
assert len(proof['saved_sources']) == 2
status = json.loads((root / 'saved-source-status.json').read_text(encoding='utf-8'))
assert status['state'] == 'bound' and status['session_token'] == 'a'*32
assert status['first_error']['winerror'] == 32
assert status['replacement_replayed'] is False
@pytest.mark.parametrize('code', [5, 2])
def test_non_lock_errors_fail_immediately_with_exact_native_code(tmp_path, monkeypatch, code):
from dx_productivity.trial_task_center import saved_source
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
project, database, root = inputs(tmp_path)
calls = []
def denied(path):
calls.append(path)
raise locked(code)
monkeypatch.setattr(saved_source, 'source_hash', denied)
monkeypatch.setattr(saved_source.time, 'sleep', lambda _: pytest.fail('non-lock error retried'))
with pytest.raises(saved_source.SavedSourceReadError) as caught:
bind_project_commit_source({}, root.parent, root, project)
assert caught.value.winerror == code and not caught.value.retryable
assert len(calls) == 1
def test_pause_during_lock_wait_keeps_pending_save_without_fallback(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import saved_source
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
project, database, root = inputs(tmp_path)
stop = Event()
monkeypatch.setattr(saved_source, 'source_hash', lambda _: (_ for _ in ()).throw(locked()))
monkeypatch.setattr(saved_source.time, 'sleep', lambda _: stop.set())
with pytest.raises(saved_source.SavedSourceReadError) as caught:
bind_project_commit_source({}, root.parent, root, project, stop_event=stop)
assert caught.value.code == 'saved_source_pending' and caught.value.interrupted
status = json.loads((root / 'saved-source-status.json').read_text(encoding='utf-8'))
assert status['state'] == 'pending' and status['replacement_replayed'] is False
@pytest.mark.parametrize('next_project', [False, True])
def test_persistent_lock_recycles_only_after_closed_checkpoint_then_binds_without_replay(tmp_path, monkeypatch, next_project):
from dx_productivity.trial_task_center import saved_source
from dx_productivity.trial_task_center.execution_proof import validate_project_commit_source
from test_batch_runtime import command_for, worker_runtime
import subprocess
command, project = command_for(tmp_path)
root = Path(command[3])
token = 'a'*32
(root / 'project-session.request').write_text(f'{token}\t{project}\tjob')
calls = []
def monitor(launch, *args, **kwargs):
calls.append('replace')
if Path(launch[3]) == root:
(root / f'project-commit-{token}.tsv').write_text(f'{token}\t{project}\tproject_saved\njob\tno_match\n')
return subprocess.CompletedProcess(launch, 0, '', '')
runtime = worker_runtime(tmp_path, monkeypatch, monitor)
original = saved_source.source_hash
def read(path):
if runtime.cad is not None:
raise locked()
return original(path)
monkeypatch.setattr(saved_source, 'source_hash', read)
monkeypatch.setattr(saved_source, 'LOCK_WAIT_SECONDS', 0)
with runtime:
runtime.run_worker(command, 5)
proof = json.loads((root / 'project-checkpoint.json').read_text(encoding='utf-8'))['project_commit_source']
assert validate_project_commit_source(proof, root)
assert runtime.cad is None and runtime.desktop is None
if next_project:
next_command, _ = command_for(tmp_path, 'two')
runtime.run_worker(next_command, 5)
assert runtime.generation == 2 and runtime.cad is not None
assert calls == ['replace'] * (2 if next_project else 1)
status = json.loads((root / 'saved-source-status.json').read_text(encoding='utf-8'))
assert status['state'] == 'bound' and status['mentor_released_for_read'] is True
@pytest.mark.parametrize('nested', [False, True])
def test_cleanup_message_keeps_primary_saved_read_failure_visible(nested):
from dx_productivity.trial_task_center.batch_resources import BatchResourceCleanupError
from dx_productivity.trial_task_center.errors import TaskCenterError
primary = TaskCenterError('saved_source_pending', '已保存,数据库持续占用,等待核验')
if nested: primary = BatchResourceCleanupError('第一次释放异常', primary_error=primary)
error = BatchResourceCleanupError('释放仍有异常', primary_error=primary)
assert '已保存,数据库持续占用,等待核验' in error.message and '释放仍有异常' in error.message
def test_sources_changing_during_binding_remain_unverified(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import saved_source
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
from dx_productivity.trial_task_center.errors import TaskCenterError
project, database, root = inputs(tmp_path)
original = saved_source.source_hash
def read(path):
digest = original(path)
if Path(path).name == 'icdb.dat': database.write_bytes(b'changed while reading')
return digest
monkeypatch.setattr(saved_source, 'source_hash', read)
with pytest.raises(TaskCenterError, match='saved_source_changed'):
bind_project_commit_source({}, root.parent, root, project)
status = json.loads((root / 'saved-source-status.json').read_text(encoding='utf-8'))
assert status['state'] == 'pending'
assert 'saved_source_changed' in status['last_error']['message']
@pytest.mark.parametrize('code', [5, 32])
def test_diagnostic_write_failure_never_replaces_original_read_error(tmp_path, monkeypatch, code):
from dx_productivity.trial_task_center import saved_source, batch_resources
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
project, database, root = inputs(tmp_path)
monkeypatch.setattr(saved_source, 'source_hash', lambda _: (_ for _ in ()).throw(locked(code)))
monkeypatch.setattr(batch_resources, 'write_record', lambda *a: (_ for _ in ()).throw(OSError('disk full')))
with pytest.raises(saved_source.SavedSourceReadError) as caught:
bind_project_commit_source({}, root.parent, root, project)
assert caught.value.winerror == code
@pytest.mark.skipif(__import__('os').name != 'nt', reason='Windows delete sharing')
def test_native_hash_uses_same_sharing_as_later_source_validation(tmp_path):
import win32file
from dx_productivity.trial_task_center.saved_source import source_hash
project, database, root = inputs(tmp_path)
handle = win32file.CreateFile(str(database), 0x10000, 7, None, 3, 0, None)
try:
with pytest.raises(OSError) as caught:
source_hash(database)
assert caught.value.winerror == 32
finally:
handle.Close()
assert source_hash(database)
def test_lock_released_during_diagnostics_is_rechecked_before_recycling(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import saved_source
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
project, database, root = inputs(tmp_path)
original = saved_source.source_hash
released = []
def read(path):
if not released: raise locked()
return original(path)
def observe(path):
released.append(True)
return {'processes': [], 'complete': True}
monkeypatch.setattr(saved_source, 'source_hash', read)
monkeypatch.setattr(saved_source, 'locking_processes', observe)
monkeypatch.setattr(saved_source, 'LOCK_WAIT_SECONDS', 0)
bind_project_commit_source({}, root.parent, root, project,
release_mentor=lambda _: pytest.fail('recycled CAD using stale lock observation'))
def test_pause_arriving_during_diagnostics_keeps_saved_result_pending(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import saved_source
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
project, database, root = inputs(tmp_path)
original = saved_source.source_hash
stop = Event()
def read(path):
if not stop.is_set(): raise locked()
return original(path)
def observe(path):
stop.set()
return {'processes': [], 'complete': True}
monkeypatch.setattr(saved_source, 'source_hash', read)
monkeypatch.setattr(saved_source, 'locking_processes', observe)
with pytest.raises(saved_source.SavedSourceReadError) as caught:
bind_project_commit_source({}, root.parent, root, project, stop_event=stop,
release_mentor=lambda _: pytest.fail('pause recycled CAD'))
assert caught.value.interrupted
def test_journal_failure_during_owner_release_preserves_both_errors(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.saved_source import SavedSourceReadError
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
from dx_productivity.trial_task_center.batch_resources import BatchResourceCleanupError
runtime = BatchCadRuntime(tmp_path / 'data', 'execution')
primary = SavedSourceReadError(locked(), 'icdb.dat')
cleanup = BatchResourceCleanupError('quit uncertain')
monkeypatch.setattr(runtime, 'close', lambda **k: (_ for _ in ()).throw(cleanup))
monkeypatch.setattr(runtime, '_save', lambda **k: (_ for _ in ()).throw(OSError('journal full')))
with pytest.raises(BatchResourceCleanupError) as caught:
runtime._release_saved_source_owner(primary)
assert caught.value.primary_error is primary and caught.value.cleanup_error is cleanup
@pytest.mark.parametrize('progress', [[], {'sequence': 'partial'}])
def test_bad_optional_progress_does_not_block_saved_source_binding(tmp_path, progress):
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
project, database, root = inputs(tmp_path)
(root / 'worker-progress.json').write_text(json.dumps(progress), encoding='utf-8')
assert bind_project_commit_source({}, root.parent, root, project)['saved_sources']
def test_pause_after_release_notice_never_starts_cad_recycling(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import saved_source, batch_resources
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
project, database, root = inputs(tmp_path)
stop = Event()
original = batch_resources.write_record
def write(path, record):
original(path, record)
if record.get('state') == 'releasing_mentor': stop.set()
monkeypatch.setattr(batch_resources, 'write_record', write)
monkeypatch.setattr(saved_source, 'source_hash', lambda _: (_ for _ in ()).throw(locked()))
monkeypatch.setattr(saved_source, 'locking_processes', lambda _: {'processes': []})
monkeypatch.setattr(saved_source, 'LOCK_WAIT_SECONDS', 0)
with pytest.raises(saved_source.SavedSourceReadError) as caught:
bind_project_commit_source({}, root.parent, root, project, stop_event=stop,
release_mentor=lambda _: pytest.fail('pause recycled CAD after release notice'))
assert caught.value.interrupted
def test_rebinding_same_saved_prefix_preserves_first_handoff_diagnostics(tmp_path):
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
project, database, root = inputs(tmp_path)
prior = dict(session_token='c'*32, project_path=str(project).upper(),
first_error={'winerror': 32, 'message': 'original lock'},
mentor_released_for_read=True, lock_observation={'processes': [{'pid': 123}]})
(root / 'saved-source-status.json').write_text(json.dumps(prior), encoding='utf-8')
bind_project_commit_source({'session_token': 'c'*32}, root.parent, root, project)
status = json.loads((root / 'saved-source-status.json').read_text(encoding='utf-8'))
assert status['state'] == 'bound' and status['mentor_released_for_read'] is True
assert status['first_error'] == prior['first_error']
assert status['lock_observation'] == prior['lock_observation']
bind_project_commit_source({'session_token': 'd'*32}, root.parent, root, project)
status = json.loads((root / 'saved-source-status.json').read_text(encoding='utf-8'))
assert 'first_error' not in status and status['mentor_released_for_read'] is False
@pytest.mark.parametrize('forced', [False, True])
def test_owner_exit_failure_or_external_lock_never_replays_or_publishes_checkpoint(tmp_path, monkeypatch, forced):
from dx_productivity.trial_task_center import saved_source
from dx_productivity.trial_task_center.batch_resources import BatchResourceCleanupError
from test_batch_runtime import command_for, worker_runtime
import subprocess
command, project = command_for(tmp_path)
root = Path(command[3]); token = 'b'*32
(root / 'project-session.request').write_text(f'{token}\t{project}\tjob')
calls = []
def monitor(*a, **k):
calls.append('replace')
(root / f'project-commit-{token}.tsv').write_text(f'{token}\t{project}\tproject_saved\njob\tno_match\n')
return subprocess.CompletedProcess(command, 0, '', '')
runtime = worker_runtime(tmp_path, monkeypatch, monitor)
monkeypatch.setattr(saved_source, 'source_hash', lambda _: (_ for _ in ()).throw(locked()))
monkeypatch.setattr(saved_source, 'LOCK_WAIT_SECONDS', 0)
if forced:
original_close = runtime.close
def close(**options):
original_close(**options)
raise BatchResourceCleanupError('forced termination was required')
monkeypatch.setattr(runtime, 'close', close)
try:
runtime.run_worker(command, 5)
pytest.fail('persistent lock or forced cleanup admitted verification')
except (saved_source.SavedSourceReadError, BatchResourceCleanupError):
assert not (root / 'project-checkpoint.json').exists()
pending = json.loads((root / 'project-save-pending.json').read_text(encoding='utf-8'))
assert pending['project_commit_pending']['jobs'] == ['job']
assert json.loads((root / 'saved-source-status.json').read_text(encoding='utf-8'))['state'] == 'pending'
assert calls == ['replace']