fix(delegate): a late resumable-record write never recreates a removed profile
Review finding: late durable write recreates a deleted profile. The record opener now goes through the ledger's own state.db opener (async_delegation.open_state_db: tombstone-aware mkdir, owner-only 0600 files), one shared helper instead of a bare open_db that materialized profiles/<removed>/state.db.
This commit is contained in:
77
tests/tools/test_delegate_resumable_pins.py
Normal file
77
tests/tools/test_delegate_resumable_pins.py
Normal file
@@ -0,0 +1,77 @@
|
||||
"""Durable resumable subagents, review round 2: a running continuation pins where it is now, a tree the child made
|
||||
stays pinned after it leaves that repository, a late record write never recreates a removed profile, and boot
|
||||
recovery names the continuable children on the ledger row that reports them (independent completions on or off).
|
||||
|
||||
Real SQLite, real git, real sweep, real dispatch and boot recovery against a temp HERMES_HOME; only the model is
|
||||
scripted.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import stat
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.tools.test_delegate_continue import _parent, _ScriptedModel
|
||||
from tests.tools.test_delegate_resumable import _git
|
||||
from tests.waiting import wait_until
|
||||
|
||||
_DEAD_PID = 2 ** 22 + 7
|
||||
|
||||
|
||||
def _repo(path):
|
||||
path.mkdir()
|
||||
_git("init", "-q", "-b", "main", cwd=path)
|
||||
(path / "a").write_text("a")
|
||||
_git("add", "a", cwd=path)
|
||||
_git("commit", "-qm", "base", cwd=path)
|
||||
return path
|
||||
|
||||
|
||||
def _run(parent, sid):
|
||||
child = SimpleNamespace(session_id="child", model="m", _parent_session_id=parent.session_id,
|
||||
_delegate_resume={"goal": "g", "route": SimpleNamespace(request={})})
|
||||
return SimpleNamespace(child=child, parent_agent=parent, subagent_id=sid, worktree_info=None, child_task_id="t")
|
||||
|
||||
|
||||
def _completions(delegation_ids):
|
||||
"""Wait for every listed unit's completion event (one drain: waiting per id would drop a sibling's event)."""
|
||||
from tools.process_registry import process_registry
|
||||
pending = set(delegation_ids)
|
||||
|
||||
def drained():
|
||||
while not process_registry.completion_queue.empty():
|
||||
evt = process_registry.completion_queue.get_nowait()
|
||||
if evt.get("type") == "async_delegation":
|
||||
pending.discard(evt.get("delegation_id"))
|
||||
return not pending
|
||||
wait_until(drained, timeout=20, what=f"completions of {sorted(pending)}")
|
||||
|
||||
|
||||
def _backdate(*paths):
|
||||
old = time.time() - 30 * 3600
|
||||
for p in paths:
|
||||
os.utime(p, (old, old))
|
||||
|
||||
|
||||
def test_a_late_record_write_never_recreates_a_removed_profile_and_stays_owner_only(tmp_path):
|
||||
from hermes_constants import get_hermes_home, profile_tombstone_path
|
||||
from tools import delegate_tool_resumable as r
|
||||
removed = get_hermes_home() / "profiles" / "removed"
|
||||
tomb = profile_tombstone_path(removed)
|
||||
tomb.parent.mkdir(parents=True, exist_ok=True)
|
||||
tomb.write_text("deleted")
|
||||
|
||||
r._write(removed / "state.db", lambda conn: conn.execute("SELECT 1").fetchone())
|
||||
assert not removed.exists()
|
||||
|
||||
live = get_hermes_home() / "state.db"
|
||||
r._write(live, lambda conn: conn.execute("SELECT 1").fetchone())
|
||||
if os.name != "nt":
|
||||
assert stat.S_IMODE(live.stat().st_mode) == 0o600
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import threading
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
from hermes_constants import get_hermes_home, hermes_home_key
|
||||
@@ -121,19 +122,20 @@ def _connect() -> sqlite3.Connection:
|
||||
from agent.runtime_session_store import WorkerPersistenceError, is_worker_process
|
||||
if is_worker_process():
|
||||
raise WorkerPersistenceError('worker_delegation_ledger_unavailable')
|
||||
return open_state_db(_db_path(), "state.db (async_delegation)")
|
||||
|
||||
|
||||
def open_state_db(path: Path, db_label: str) -> sqlite3.Connection:
|
||||
"""A short-lived writer connection to a profile's ``state.db`` that never resurrects a removed named profile
|
||||
(#123265) and keeps the file and its sidecars owner-only (0600, as ``hermes_state.SessionDB`` does)."""
|
||||
from hermes_cli.sqlite_util import open_db
|
||||
# Same state.db as hermes_state.SessionDB -- reuse its owner-only (0600)
|
||||
# hardening so this writer doesn't create/leave the file (and its WAL
|
||||
# sidecars) at the process umask. See hermes_state._secure_state_db_files.
|
||||
from hermes_constants import mkdir_under_hermes_home
|
||||
from hermes_state import _secure_state_db_files
|
||||
|
||||
path = _db_path()
|
||||
# A late replay or writer must not resurrect a removed named profile (#123265).
|
||||
mkdir_under_hermes_home(path.parent)
|
||||
_secure_state_db_files(path, create_main=True)
|
||||
# wal=False: SessionDB owns state.db's journal mode (_initialize_schema applies the barriers).
|
||||
conn = open_db(path, db_label="state.db (async_delegation)", busy_timeout_ms=10_000,
|
||||
conn = open_db(path, db_label=db_label, busy_timeout_ms=10_000,
|
||||
wal=False, row_factory=None, initialize=_initialize_schema)
|
||||
_secure_state_db_files(path)
|
||||
return conn
|
||||
|
||||
@@ -88,10 +88,9 @@ def _db_path_for(parent_agent: Any = None) -> Optional[Path]:
|
||||
|
||||
|
||||
def _connect(path: Path):
|
||||
from hermes_cli.sqlite_util import open_db, transaction
|
||||
from tools.async_delegation import _initialize_schema
|
||||
return transaction(open_db(path, db_label="state.db (resumable_subagents)", busy_timeout_ms=10_000, wal=False,
|
||||
row_factory=None, initialize=_initialize_schema))
|
||||
from hermes_cli.sqlite_util import transaction
|
||||
from tools.async_delegation import open_state_db
|
||||
return transaction(open_state_db(path, "state.db (resumable_subagents)"))
|
||||
|
||||
|
||||
def _write(path: Optional[Path], fn) -> Any:
|
||||
@@ -100,6 +99,9 @@ def _write(path: Optional[Path], fn) -> Any:
|
||||
try:
|
||||
with _connect(path) as conn:
|
||||
return fn(conn)
|
||||
except FileNotFoundError: # its profile was removed: a late write must not recreate it
|
||||
logger.debug("resumable subagent record skipped: %s is gone", path.parent)
|
||||
return None
|
||||
except Exception:
|
||||
logger.warning("resumable subagent record write failed (%s)", path, exc_info=True)
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user