fix(snapshot): validate evidence generations and bound unstable reads

This commit is contained in:
阿白叔 committed 2026-10-15 10:10:29 +08:00
1 parent e3b0f8940c
commit e265ca515d
2 files changed
+140 -2

No files matched your search

@@ -1,6 +1,6 @@
"""Read-only execution view reconstructed from one cached set of handoff files."""
from __future__ import annotations
from dataclasses import dataclass
from dataclasses import dataclass, replace
from pathlib import Path
from .errors import TaskCenterError
from .quick_run_protocol import QuickRunProgress
@@ -19,11 +19,39 @@ class _ReadFiles:
def __init__(self, control):
self.control = control
self.texts = {}
self.roots = {}
def checkpoint(self):
if self.control is not None:
self.control.checkpoint()
def _manifest(self, root):
self.checkpoint()
def stamp(path):
self.checkpoint()
try:
stat = path.stat()
return (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns)
except OSError:
return None
root_stamp = stamp(root)
try:
# Include sidecar evidence used by hard-failure recovery as well as
# command/status and flags; creation/removal changes the root stamp.
entries = tuple(root.iterdir())
except OSError:
entries = ()
result = {path.name: stamp(path) for path in entries}
self.checkpoint()
return root_stamp, result
def track_root(self, root):
if root not in self.roots:
self.roots[root] = self._manifest(root)
def stable(self):
return all(self._manifest(root) == before for root, before in self.roots.items())
def path(self, path):
return _CachedPath(Path(path), self)
@@ -61,9 +89,23 @@ class _CachedPath:
def read_snapshot(preparer, task_id, projects, rules, *, copy_part_number_to_value=False,
read_control=None, project_path=None):
for _ in range(3):
files = _ReadFiles(read_control)
snapshot = _read_snapshot_once(preparer, task_id, projects, rules,
copy_part_number_to_value=copy_part_number_to_value, project_path=project_path, files=files)
if files.stable():
return snapshot
# Never publish executable continuation coordinates from a changing set.
progress = replace(snapshot.progress, next_project_path=None, next_old_part_number=None,
next_new_part_number=None, next_schematic_name=None, next_sheet_number=None)
files.checkpoint()
return replace(snapshot, progress=progress, interrupted=True)
def _read_snapshot_once(preparer, task_id, projects, rules, *, copy_part_number_to_value=False,
project_path=None, files):
# Import lazily to preserve the historical quick_run private parser boundaries.
from . import quick_run as api
files = _ReadFiles(read_control)
files.checkpoint()
selected = api._selected_projects(projects)
queued = api._queue_projects(projects)
@@ -83,6 +125,7 @@ def read_snapshot(preparer, task_id, projects, rules, *, copy_part_number_to_val
yield from sorted((path for path in history.glob('obsolete-*') if path.is_dir()), reverse=True)
for candidate in candidates():
files.checkpoint()
files.track_root(candidate)
command = candidate / 'command.tsv'
if not command.is_file() or not (candidate / 'status.tsv').is_file():
continue
@@ -83,3 +83,98 @@ def test_legacy_phase_wrapper_keeps_terminal_phase_while_snapshot_exposes_retry(
handoff.status_path.write_text(f'job_id\tstate\tcode\tmessage\n{job}\tbatch_failed\t\tfailed\n', encoding='utf-8')
assert preparer.read_snapshot('task', (project,), (rule,)).phase == 'retry'
assert preparer.current_phase('task', (project,), (rule,)) == 'complete'
def test_snapshot_retries_when_uncertain_flag_is_created_during_status_read(tmp_path, monkeypatch):
preparer, project, rule, handoff, job = fixture_queue(tmp_path)
original = Path.open
injected = False
def racing_open(path, *args, **kwargs):
nonlocal injected
if path == handoff.status_path and args and args[0] == 'r' and not injected:
injected = True
(path.parent / 'uncertain.flag').write_text('uncertain', encoding='utf-8')
return original(path, *args, **kwargs)
monkeypatch.setattr(Path, 'open', racing_open)
snapshot = preparer.read_snapshot('task', (project,), (rule,))
assert snapshot.interrupted
assert snapshot.has_evidence
def test_snapshot_retries_command_and_status_as_one_generation(tmp_path, monkeypatch):
preparer, project, rule, handoff, job = fixture_queue(tmp_path)
original = Path.open
command = handoff.command_path.read_text(encoding='utf-8')
injected = False
def racing_open(path, *args, **kwargs):
nonlocal injected
if path == handoff.status_path and args and args[0] == 'r' and not injected:
injected = True
handoff.command_path.write_text(command.replace(job, 'new-generation'), encoding='utf-8')
handoff.status_path.write_text('job_id\tstate\tcode\tmessage\nnew-generation\tno_match\t\tno match\n', encoding='utf-8')
return original(path, *args, **kwargs)
monkeypatch.setattr(Path, 'open', racing_open)
snapshot = preparer.read_snapshot('task', (project,), (rule,))
assert snapshot.progress.completed_items == 1
assert snapshot.progress.queue_complete
assert snapshot.progress.no_match_items == 1
def test_snapshot_continuous_changes_block_continuation_after_bounded_retries(tmp_path, monkeypatch):
preparer, project, rule, handoff, job = fixture_queue(tmp_path)
original = Path.open
reads = 0
def racing_open(path, *args, **kwargs):
nonlocal reads
if path == handoff.status_path and args and args[0] == 'r':
reads += 1
(path.parent / 'changing.txt').write_text('x' * reads, encoding='utf-8')
return original(path, *args, **kwargs)
monkeypatch.setattr(Path, 'open', racing_open)
snapshot = preparer.read_snapshot('task', (project,), (rule,))
assert reads == 3
assert snapshot.interrupted
assert snapshot.progress.next_project_path is None
assert snapshot.progress.next_old_part_number is None
def test_context_resolves_facade_from_bundle_without_another_database_read(tmp_path, monkeypatch):
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')
task = store.create_task('bound')
project = store.sync_projects(task.task_id, tmp_path, (tmp_path / 'one.prj',))[0]
store.bind_project_task(task.task_id, project.project_id, 'group', 0)
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
original = store.read_task_bundle
def bundle_then_block_rereads(*args, **kwargs):
bundle = original(*args, **kwargs)
def unexpected(*args, **kwargs):
raise AssertionError('context reread task after its database snapshot')
for name in ('get_task', 'list_tasks', 'list_projects', 'pending_migration_recoveries',
'acknowledge_migration_recoveries', 'recover_interrupted_work'):
monkeypatch.setattr(store, name, unexpected)
return bundle
monkeypatch.setattr(store, 'read_task_bundle', bundle_then_block_rereads)
context = service.task_context(task.task_id)
assert context.task.primary_project_id == project.project_id
assert context.project.project_id == project.project_id
def test_snapshot_cancellation_during_generation_validation_is_not_suppressed(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import quick_run_snapshot as module
from dx_productivity.trial_task_center.read_control import QueryCancelled, QueryControl
preparer, project, rule, handoff, job = fixture_queue(tmp_path)
control = QueryControl()
original = module._ReadFiles._manifest
calls = 0
def validating(files, root):
nonlocal calls
calls += 1
if calls == 2:
control.cancel()
return original(files, root)
monkeypatch.setattr(module._ReadFiles, '_manifest', validating)
with pytest.raises(QueryCancelled):
preparer.read_snapshot('task', (project,), (rule,), read_control=control)