feat(storage): neutral helpers and the store-handle seams callers share

The top-level helpers the switched callers share (session keys, process identity, storage limits, lineage adoption, session rescue) and the store-handle seams that open persistence beside the legacy store, with the test fixtures and fakes the caller tests use.
This commit is contained in:
yoniebans
2026-11-05 04:33:21 +00:00
parent 48536a9eac
commit e50375c995
13 changed files with 677 additions and 1 deletions

93
lineage_adoption.py Normal file
View File

@@ -0,0 +1,93 @@
"""Adoption of a session's compression lineage from another profile's store: the stranded-session heal for a profile bot whose rows accumulated in the default profile's store before session calls were routed by their target session."""
from __future__ import annotations
import logging
from typing import Any
from persistence.conversation.messages import TranscriptRead, TranscriptView
from persistence.conversation.sessions import END_REASON_ADOPTED
from persistence.housekeeping.maintenance import ImportResult, SessionExport
# caplog tests pin the "hermes_state" logger name.
logger = logging.getLogger("hermes_state")
_EVERY_ROW = TranscriptRead(view=TranscriptView.ALL)
def _row_count(store, session_id: str) -> int:
return len(store.messages.read_transcript(session_id, _EVERY_ROW))
def _import_entry(segment: SessionExport) -> dict[str, Any]:
return {**segment.session.as_dict(), "messages": [message.as_wire_row() for message in segment.messages]}
def _result_dict(result: ImportResult) -> dict[str, Any]:
"""The ``import_sessions`` dict: the id lists only on success."""
out: dict[str, Any] = {"ok": result.ok, "imported": result.imported, "skipped": result.skipped, "detached": result.detached}
if result.ok:
out.update(imported_ids=list(result.imported_ids), skipped_ids=list(result.skipped_ids))
out["errors"] = list(result.errors)
return out
def adopt_session_lineage(store, donor, session_id: str, *, retire_donor: bool = True) -> dict[str, Any]:
"""Adopt *session_id*'s full compression lineage from the *donor* store into *store*: the donor's lineage export with every row, imported here (runtime fields reset, already-present ids skipped, so it is idempotent). Every message row is carried with its archived state, so turns in-place compaction archived stay visible here and stay out of model context. With ``retire_donor`` and a complete adoption, donor rows are ARCHIVED (never deleted) with ``end_reason=END_REASON_ADOPTED``, deliberately not a recoverable reason, so resurrection cannot undo an adoption. Returns the ``import_sessions`` dict plus ``adopted`` and ``donor_retired`` (True only when EVERY segment retired)."""
# Every row, not just live ones: the retired donor is unrecoverable, so any turn left behind
# (compaction-archived history included) would be visible nowhere.
payload = donor.maintenance.export_session_lineage(session_id, include_inactive=True)
if payload is None:
return {"ok": False, "adopted": False, "donor_retired": False,
"error": f"session {session_id!r} not found in donor store"}
segments = payload.segments
# Divergence guard: a segment we will SKIP (already here) may have kept growing in
# the donor after a partial adoption; retiring it would strand those messages
# behind a non-recoverable archive. Still import, but refuse to retire.
donor_ahead = False
for segment in segments:
seg_id = segment.session.id
if store.sessions.get(seg_id) is None:
continue
donor_count = len(segment.messages)
local_count = _row_count(store, seg_id)
if donor_count > local_count:
donor_ahead = True
logger.warning("adoption divergence: donor segment %s has %d messages, "
"local copy has %d — donor will NOT be retired", seg_id, donor_count, local_count)
result = _result_dict(store.maintenance.import_sessions([_import_entry(segment) for segment in segments]))
imported = result["imported"]
skipped = result["skipped"]
adopted = result["ok"] and (imported + skipped) == len(segments)
if not adopted:
logger.warning("adoption of %s did not complete: imported=%s skipped=%s of %s segment(s); errors=%s",
session_id, imported, skipped, len(segments), result["errors"])
donor_retired = False
if adopted and retire_donor and not donor_ahead:
donor_retired = all(_retire_donor_segment(store, donor, segment.session.id) for segment in segments)
return {**result, "adopted": adopted, "donor_retired": donor_retired}
def _retire_donor_segment(store, donor, seg_id: str) -> bool:
"""Archive one adopted donor segment; False when skipped or failed. The divergence guard used export-time counts, so both stores are re-read right before stamping and donor growth never lands behind a non-recoverable archive (equal-count content divergence is accepted: the bytes stay in the donor either way). A retirement failure does not fail the adoption (a later resume retries idempotently), but never claims success it did not have."""
try:
donor_now = _row_count(donor, seg_id)
local_now = _row_count(store, seg_id)
if donor_now > local_now:
logger.warning(
"adoption divergence at retire time: donor segment %s grew to %d messages (local %d) — "
"leaving donor unretired", seg_id, donor_now, local_now,
)
return False
# The first end reason wins; reopen so the adoption boundary is stamped even on an ended segment.
donor.sessions.reopen(seg_id)
donor.sessions.end(seg_id, END_REASON_ADOPTED)
# The session lives on in the adopting profile: not a delete for plugins.
donor.sessions.set_archived(seg_id, True, notify=False)
return True
except Exception:
logger.warning("failed to retire donor segment %s after adoption", seg_id, exc_info=True)
return False

View File

@@ -1003,10 +1003,11 @@ def handle_function_call(
return _apply_transform_tool_result_hook(function_name, function_args, result, duration_ms, ids)
except Exception as e:
from storage_user_copy import error_type_name
error_msg = f"Error executing {function_name}: {e!s}"
logger.exception(error_msg)
return _emit(tool_error(_sanitize_tool_error(error_msg)), duration_ms=_elapsed_ms(start),
status="error", error_type=type(e).__name__, error_message=str(e))
status="error", error_type=error_type_name(e), error_message=str(e))
# =============================================================================

46
persistence_beside.py Normal file
View File

@@ -0,0 +1,46 @@
"""Storage interface handles held beside a legacy store handle.
A handle beside a store never changes what the store's path does: an open or close that fails logs at debug, the open
answers None, and the caller carries on with its store alone.
"""
from __future__ import annotations
import logging
from contextlib import ExitStack
from pathlib import Path
from typing import Any, Optional
logger = logging.getLogger(__name__)
def open_beside(home: Optional[Path] = None) -> Any:
"""A handle on the store of ``home`` (the current home when None), or None when it cannot open."""
try:
from persistence_assembly import open_persistence, profile_scope
return open_persistence(profile_scope(home=home))
except Exception: # health: allow BLE001 -- the store beside it decides the result; the handle stays absent
logger.debug("storage interface unavailable for %s", home or "the current home", exc_info=True)
return None
def open_reader_beside(target: Path, handles: ExitStack) -> Any:
"""A read-only handle over ``target``, closed with ``handles``, or None when it cannot open."""
try:
from persistence_assembly import open_persistence_reader
return handles.enter_context(open_persistence_reader(target))
except Exception: # health: allow BLE001 -- the store beside it decides the result; the handle stays absent
logger.debug("storage interface reader unavailable for %s", target, exc_info=True)
return None
def close_beside(handle: Any) -> None:
"""Close ``handle`` (a handle from ``open_beside`` or an ``ExitStack`` of readers); None does nothing."""
if handle is None:
return
try:
handle.close()
except Exception: # health: allow BLE001 -- the store beside it decides the result; a failed release is logged
logger.debug("storage interface close failed", exc_info=True)

172
process_identity.py Normal file
View File

@@ -0,0 +1,172 @@
"""Process identity of lock and lease holders.
A ``pid=<n>`` holder is relative to its writer's PID namespace; a reader in a
sibling namespace (two containers on one volume, systemd ``PrivatePIDs=``) sees
a live holder as absent and would reclaim its unexpired row. Holders are
stamped with ``pidns=<inode of /proc/self/ns/pid>`` and a foreign stamp is
never probed. Unstamped (pre-upgrade) records differ by policy:
* :func:`holder_pid_checkable` — STRICT, for TTL rows (compression locks,
turn leases): unstamped defers to its expiry (<= TTL; a false defer
self-heals, a false reclaim ends a live turn).
* :func:`persistent_record_pidns_checkable` — LEGACY, for no-expiry flock
records: unstamped keeps probing so orphaned-lock cleanup still works.
Platforms without PID namespaces (macOS, Windows) keep the plain pid probe; a
failed Linux lookup is not cached and makes every holder unverifiable.
:func:`holder_process_is_dead` is the reclaim probe a lease holder's row is
judged by; the Python option tables say which interpreter options take a
separate operand when an argv is read for the program it runs.
"""
from __future__ import annotations
import os
import re
import sys
from typing import NamedTuple, Optional
try: # Hard dependency, but tolerate scaffold-phase imports before pip install.
import psutil
except ImportError: # pragma: no cover - stripped/scaffold installs only
psutil = None # type: ignore[assignment]
_PYTHON_SHORT_OPTIONS_WITH_OPERANDS = frozenset({"Q", "W", "X"})
_PYTHON_LONG_OPTIONS_WITH_OPERANDS = frozenset(
{"--check-hash-based-pycs", "--jit"}
)
# ``pidns=`` token inside a structured holder string (``pid=123:pidns=4026533184:turn=…``).
_PIDNS_TOKEN_RE = re.compile(r"(?:^|:)pidns=(\d+)(?::|$)")
class LocalPidNamespace(NamedTuple):
"""What this process knows about its own PID namespace.
Three states, and the ``checkable`` predicates treat each differently:
``supported`` False — the platform has no namespace identity at all;
``supported`` True with an ``id`` — resolved; ``supported`` True with an
``id`` of None — resolution failed, see the module docstring.
"""
id: Optional[str]
supported: bool
_UNSUPPORTED = LocalPidNamespace(None, False)
# Cached once there is a definite answer: a process cannot move itself into
# another PID namespace (``setns`` applies to its future children), so a
# successful read never changes for us. A failed read is NOT cached — it may
# be transient, and while it lasts every structured holder is unverifiable.
_LOCAL_PID_NS: Optional[LocalPidNamespace] = None
def _resolve_local_pid_namespace() -> LocalPidNamespace:
if sys.platform != "linux":
return _UNSUPPORTED
try:
link = os.readlink("/proc/self/ns/pid")
except OSError:
return LocalPidNamespace(None, True)
match = re.search(r"\[(\d+)\]", link) # "pid:[4026532534]"
return LocalPidNamespace(match.group(1) if match else None, True)
def _local_pid_namespace() -> LocalPidNamespace:
"""This process' PID-namespace identity (see :class:`LocalPidNamespace`)."""
global _LOCAL_PID_NS
if _LOCAL_PID_NS is None:
local = _resolve_local_pid_namespace()
if local.id is not None or not local.supported:
_LOCAL_PID_NS = local
return local
return _LOCAL_PID_NS
def pid_namespace_id() -> Optional[str]:
"""What a holder records: the ``/proc/self/ns/pid`` inode on Linux, ``None``
where there is no namespace identity or the lookup failed. A holder never
asserts a namespace it cannot prove."""
return _local_pid_namespace().id
def holder_namespace_token() -> str:
"""The ``:pidns=<id>`` fragment to append to a new holder string, or ``""``.
Callers build ``f"pid={os.getpid()}{holder_namespace_token()}:turn=…"``.
"""
ns = pid_namespace_id()
return f":pidns={ns}" if ns else ""
def _recorded_namespace(holder: str) -> Optional[str]:
"""The ``pidns=`` stamp from a holder string, or None when it carries none."""
match = _PIDNS_TOKEN_RE.search(holder or "")
return match.group(1) if match else None
def _qualify(recorded: Optional[str], *, unstamped_checkable: bool) -> bool:
"""The shared matrix; *unstamped_checkable* is the policy for a record that
carries no namespace (see the module docstring for why there are two)."""
local = _local_pid_namespace()
if not local.supported:
return True # single-namespace platform: a pid is evidence on its own
if recorded is None:
return unstamped_checkable
if local.id is None:
return False # our own lookup failed: unknown authority is not authority
return recorded == local.id
def holder_pid_checkable(holder: str) -> bool:
"""STRICT: may a structured holder string's ``pid=`` be probed here?
The policy for TTL-bounded rows (compression locks, session turn leases):
a foreign-namespace or unstamped holder is never probed — it defers to the
row's own expiry instead (at most the remaining TTL; a false defer
self-heals, a false reclaim ends a live turn).
"""
return _qualify(_recorded_namespace(holder), unstamped_checkable=False)
def persistent_record_pidns_checkable(recorded: Optional[str]) -> bool:
"""LEGACY ROLLOUT: may a persistent record (no expiry) be probed here?
The policy for the flock holder records: a foreign-namespace record is
never probed, while an unstamped one keeps main's behavior — those records
never expire, so refusing to probe them would permanently disable
orphaned-lock cleanup (see the module docstring).
"""
return _qualify(recorded, unstamped_checkable=True)
def holder_process_is_dead(holder: str) -> bool:
"""True only when a ``pid=<n>`` lock holder's local PID is provably gone.
Reclaim on kernel proof only: unstructured/same-process holders (another
thread's live lease) and any probe doubt keep the lease until TTL expiry
(PID reuse must never steal a live lease; a wrongly-kept one self-heals).
Foreign/unstamped PID namespaces defer to TTL: see :func:`holder_pid_checkable`."""
match = re.search(r"(?:^|:)pid=(\d+)(?::|$)", holder or "")
pid = int(match.group(1)) if match else 0
if pid <= 0 or pid == os.getpid():
return False
if not holder_pid_checkable(holder):
return False # foreign / unknown namespace: defer to TTL
if psutil is not None:
try:
return not psutil.pid_exists(pid) # recycled PIDs read as alive (conservative)
except Exception: # health: allow BLE001 -- any probe doubt keeps the lease until its TTL
return False
# psutil-less fallback is POSIX-only: on Windows os.kill(pid, 0) maps sig=0 to
# CTRL_C_EVENT and can kill the target's console group.
if os.name == "nt":
return False
try:
os.kill(pid, 0) # windows-footgun: ok — nt early-returns just above
except ProcessLookupError:
return True
except (OSError, OverflowError): # PermissionError is an OSError: alive but foreign
return False
return False

15
session_keys.py Normal file
View File

@@ -0,0 +1,15 @@
"""The profile namespace of a gateway session key, for the gateway and the storage backend."""
from persistence.core.keys import profile_from_session_key_namespace
__all__ = ["profile_from_session_key", "profile_from_session_key_namespace"]
def profile_from_session_key(session_key):
"""Profile namespace encoded in an ``agent:<ns>:...`` gateway session key, else None."""
if not session_key:
return None
parts = str(session_key).split(":")
if len(parts) < 2 or parts[0] != "agent":
return None
return profile_from_session_key_namespace(parts[1] or "main")

23
session_rescue.py Normal file
View File

@@ -0,0 +1,23 @@
"""Transcript rescue for a store replaced under a live process: pending messages go to a JSONL file instead."""
import json
from pathlib import Path
from typing import Optional
from hermes_dir_acl import make_user_dir
def divert_session_transcript_jsonl(session_id: str, messages, *, sessions_dir: Path) -> Optional[Path]:
"""Append pending messages to ``<sessions_dir>/<id>.jsonl`` (state.db was replaced under a
live process). Returns the path, or None if nothing to write."""
sid = str(session_id or "").strip()
if not sid or not messages:
return None
make_user_dir(sessions_dir, parents=True, exist_ok=True)
path = sessions_dir / f"{sid}.jsonl"
with path.open("a", encoding="utf-8") as handle:
for msg in messages:
if msg is not None:
record = msg if isinstance(msg, dict) else {"content": str(msg)}
handle.write(json.dumps(record, ensure_ascii=False, default=str) + "\n")
return path

24
storage_limits.py Normal file
View File

@@ -0,0 +1,24 @@
"""The transcript size limits callers pass to the resume and export verbs."""
_MAX_SAFE_MESSAGES = 20_000 # resume/export guard default
def _configured_transcript_limit(key: str, fallback: int = _MAX_SAFE_MESSAGES) -> int:
"""``sessions.<key>`` from config.yaml (lazy import: circular at load), else *fallback*; 0 disables."""
try:
from hermes_cli.config import load_config_readonly
value = (load_config_readonly().get("sessions") or {}).get(key)
if value is None:
return fallback
limit = int(value)
return limit if limit >= 0 else fallback
except Exception: # health: allow BLE001 -- an unreadable config means the default limit
return fallback
def resolved_max_resume_messages() -> int:
return _configured_transcript_limit("max_resume_messages")
def resolved_max_export_messages() -> int:
return _configured_transcript_limit("max_export_messages")

83
tests/fixtures/gateway_owner.py vendored Normal file
View File

@@ -0,0 +1,83 @@
"""A profile's gateway owner in this process, for tests that drive the classic CLI's ``GatewaySessionStore``.
``GatewayOwner`` runs a real session authority (``initialize_session_authority``) on its own loop thread; each store
:meth:`GatewayOwner.client` hands out is a ``GatewaySessionStore`` on a real ``GatewayConnection`` whose requests run
through ``AuthorityConnection.dispatch`` on that loop, so the CLI's synchronous calls reach the owner as they do in
production. ``persistence`` is the owner's storage interface handle, for seeding and reading rows.
"""
import asyncio
import threading
from contextlib import asynccontextmanager
from types import SimpleNamespace
from hermes_cli.gateway_client import rpc_error
from hermes_cli.gateway_connection import GatewayConnection
from hermes_cli.gateway_session_store import GatewaySessionStore
class _Life:
"""One socket to the owner: each request runs on the owner's loop."""
def __init__(self, connection, loop):
self.connection, self.loop = connection, loop
self.events = asyncio.Queue()
async def rpc(self, method, *, _timeout=None, **params):
frame = {"id": 1, "method": method, "params": params}
reply = await asyncio.wrap_future(asyncio.run_coroutine_threadsafe(self.connection.dispatch(frame), self.loop))
if "error" in reply:
raise rpc_error(reply["error"])
return reply["result"]
class GatewayOwner:
"""The profile at *home*'s gateway; ``close`` stops it and every client it handed out."""
def __init__(self, home, monkeypatch):
from gateway import run
from gateway.config import GatewayConfig
from gateway.session import SessionStore
monkeypatch.setattr(run, "_load_gateway_config",
lambda *a, **k: {"platform_toolsets": {"cli": []}, "model": "m"})
self.loop = asyncio.new_event_loop()
self.thread = threading.Thread(target=self.loop.run_forever, daemon=True)
self.thread.start()
self.store = SessionStore(home / "sessions", GatewayConfig())
self.persistence = self.store.persistence
self.lives, self.clients = [], []
self.authority = self._run(self._boot(str(home)))
def _run(self, coro):
return asyncio.run_coroutine_threadsafe(coro, self.loop).result(30)
async def _boot(self, profile):
from gateway.session_authority import initialize_session_authority
runner = SimpleNamespace(session_store=self.store, _session_db=self.persistence, adapters={}, _draining=False,
_cached_agent_for=lambda route: None, _evict_cached_agent=lambda route: None)
runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)
runner._adapters_for_profile = lambda profile: runner.adapters # /new and /clear send command.observe
return await initialize_session_authority(runner, profile_id=profile, instance_id="owner")
async def _open(self):
from gateway.session_controls import AuthorityConnection
self.lives.append(_Life(AuthorityConnection(self.authority, object(), {"user_id": "owner"}), self.loop))
return self.lives[-1]
@asynccontextmanager
async def _dial(self):
yield await asyncio.wrap_future(asyncio.run_coroutine_threadsafe(self._open(), self.loop))
def client(self):
"""A classic CLI's session store on its own connection to this owner."""
self.clients.append(GatewaySessionStore(GatewayConnection(connect=self._dial)))
return self.clients[-1]
def close(self):
for client in self.clients:
client.connection.close()
client.close_reader()
for life in self.lives:
self._run(life.connection.close())
self.store.close_all_db_handles()
self.loop.call_soon_threadsafe(self.loop.stop)
self.thread.join(5)

65
tests/fixtures/test_storage_holder.py vendored Normal file
View File

@@ -0,0 +1,65 @@
"""The holder helper runs raw SQL on the store the interface handle reads."""
import importlib
import json
import sqlite3
import time
from tests.fixtures import storage_holder as h
from tests.fixtures.storage_holder import raw_holder
from tests.fixtures.storage_seed import seed_session
from tests.gateway.fixtures.storage_handles import close_storage_handles, storage_handle
def test_raw_holder_writes_and_reads_the_handles_store(tmp_path):
store = storage_handle(tmp_path)
seed_session(store, "s", "cli")
holder = raw_holder(store)
holder._execute_write(lambda conn: conn.execute("UPDATE sessions SET title = ? WHERE id = ?", ("raw", "s")))
with holder._read_ctx() as conn:
assert conn.execute("SELECT title FROM sessions WHERE id = ?", ("s",)).fetchone()[0] == "raw"
assert store.sessions.get("s").title == "raw"
def test_key_builders_prefix_their_suffix():
for build in (h.policy_key, h.api_binding_key, h.terminal_admission_key, h.admission_result_key,
h.retired_session_key, h.retired_route_key, h.history_binding_key, h.retired_media_key):
assert build("x") == build() + "x" and build().startswith("gateway.")
def test_result_codec_round_trips():
result = {"result": {"final_response": "ok", "messages": [{"role": "assistant", "content": "ok"}]}}
assert h.load_result(json.dumps(h.encode_result(result))) == result
assert h.result_decoder()(json.dumps(h.encode_result(result))) == result
def test_retirement_helpers_write_list_and_reclaim_markers(tmp_path):
store = storage_handle(tmp_path)
h.retire_routes(store, ["gone"], expiring=["gone"])
assert store.state_meta.get(h.retired_session_key("gone")) is not None
assert h.expiring_retirements(store, ["gone", "other"]) == {"gone"}
h.reclaim_expired(store, h.retired_session_key(), time.time() + 1)
assert store.state_meta.get(h.retired_session_key("gone")) is None
assert h.guarded_ids(store, ["gone"]) == set()
assert h.create_conflict(store, "fresh") is None
def test_browse_helpers_reach_the_names_the_browse_reads():
reconcile = importlib.import_module("persistence.sqlite.admin._reconcile")
assert h.browse_integrity_scan() is reconcile._integrity_problem
assert h.browse_budgets() == (reconcile.BROWSE_INTEGRITY_BUDGET_S, reconcile.BROWSE_RECONCILE_BUDGET_S)
reconcile._scan_too_slow["probe"] = (0, 0)
h.forget_slow_scans()
assert reconcile._scan_too_slow == {}
def test_recovery_orphan_cleanup_clears_a_dangling_parent(tmp_path):
store = storage_handle(tmp_path)
seed_session(store, "child", "cli")
conn = sqlite3.connect(str(tmp_path / "state.db"), isolation_level=None)
conn.row_factory = sqlite3.Row
try:
conn.execute("UPDATE sessions SET parent_session_id = 'gone' WHERE id = 'child'")
assert h.recovery_orphan_cleanup(conn)["sessions_parent_cleared"] == 1
assert conn.execute("SELECT parent_session_id FROM sessions WHERE id = 'child'").fetchone()[0] is None
finally:
conn.close()

40
tests/fixtures/test_storage_read.py vendored Normal file
View File

@@ -0,0 +1,40 @@
"""The read helpers return the session row, the stored message rows and the replay messages as dicts."""
from persistence.conversation.messages import ConversationRequest
from tests.fixtures.storage_read import conversation, session_row, transcript_rows
from tests.fixtures.storage_seed import seed_messages, seed_session
from tests.gateway.fixtures.storage_handles import close_storage_handles, storage_handle
TOOL_CALL = {"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{}"}}
MESSAGES = ({"role": "user", "content": "hi"}, {"role": "assistant", "content": "", "tool_calls": [TOOL_CALL]},
{"role": "tool", "content": "out", "tool_call_id": "c1", "tool_name": "f"})
def test_session_row_is_the_row_dict_or_none(tmp_path):
store = storage_handle(tmp_path)
seed_session(store, "s", "cli", model="m", title="T", end_reason="user_exit")
row = session_row(store, "s")
assert (row["id"], row["source"], row["model"], row["title"], row["title_source"], row["end_reason"]) == (
"s", "cli", "m", "T", "user", "user_exit")
assert (row["hidden"], row["archived"], row["pinned"]) == (0, 0, 0)
assert session_row(store, "missing") is None
def test_transcript_rows_are_the_stored_rows_in_order(tmp_path):
store = storage_handle(tmp_path)
seed_session(store, "s", "cli")
ids = seed_messages(store, "s", *MESSAGES)
rows = transcript_rows(store, "s")
assert [(row["id"], row["session_id"], row["role"], row["content"]) for row in rows] == [
(ids[0], "s", "user", "hi"), (ids[1], "s", "assistant", ""), (ids[2], "s", "tool", "out")]
assert (rows[1]["tool_calls"], rows[2]["tool_call_id"]) == ([TOOL_CALL], "c1")
assert {(row["active"], row["compacted"]) for row in rows} == {(1, 0)}
def test_conversation_is_the_openai_format_replay(tmp_path):
store = storage_handle(tmp_path)
seed_session(store, "s", "cli")
ids = seed_messages(store, "s", *MESSAGES)
messages = conversation(store, "s")
assert [(m["role"], m["content"]) for m in messages] == [("user", "hi"), ("assistant", ""), ("tool", "out")]
assert (messages[1]["tool_calls"], messages[2]["tool_call_id"], messages[2]["tool_name"]) == ([TOOL_CALL], "c1", "f")
assert [m["_row_id"] for m in conversation(store, "s", ConversationRequest(include_row_ids=True))] == ids

47
tests/fixtures/test_storage_seed.py vendored Normal file
View File

@@ -0,0 +1,47 @@
"""The seed helpers write sessions, transcripts and admission settlements through the storage interface."""
from tests.fixtures.storage_seed import seed_messages, seed_session, settle_claim
from tests.gateway.fixtures.storage_handles import close_storage_handles, storage_handle
TOOL_CALL = {"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{}"}}
def test_seed_session_creates_the_row_then_titles_flags_and_ends_it(tmp_path):
store = storage_handle(tmp_path)
assert seed_session(store, "s", "telegram", model="m", origin_json='{"platform": "telegram"}', title="Title",
pinned=True, archived=True, hidden=True, end_reason="user_exit") == "s"
record = store.sessions.get("s")
assert (record.source, record.model, dict(record.origin), record.title) == ("telegram", "m", {"platform": "telegram"}, "Title")
assert (record.pinned, record.archived, record.hidden, record.end_reason) == (True, True, True, "user_exit")
def test_seed_session_leaves_unset_columns_alone(tmp_path):
store = storage_handle(tmp_path)
seed_session(store, "s", "cli")
record = store.sessions.get("s")
assert (record.title, record.pinned, record.archived, record.hidden, record.ended_at) == (None, False, False, False, None)
def test_seed_messages_appends_each_dict_in_order(tmp_path):
store = storage_handle(tmp_path)
seed_session(store, "s", "cli")
ids = seed_messages(store, "s", {"role": "user", "content": "hi"},
{"role": "assistant", "content": "", "tool_calls": [TOOL_CALL]},
{"role": "tool", "content": "out", "tool_call_id": "c1", "tool_name": "f"},
{"role": "assistant", "content": "summary", "_compressed_summary": True})
rows = store.messages.read_transcript("s")
assert [row.id for row in rows] == ids
assert [(row.role, row.content) for row in rows] == [("user", "hi"), ("assistant", ""), ("tool", "out"), ("assistant", "summary")]
assert (rows[1].tool_calls, rows[2].tool_call_id, rows[2].tool_name, rows[3].compressed_summary) == ([TOOL_CALL], "c1", "f", True)
assert store.sessions.get("s").message_count == 4
def test_settle_claim_settles_the_claimed_admission(tmp_path):
store = storage_handle(tmp_path)
seed_session(store, "s", "cli")
epoch = store.runtime.begin_epoch(instance_id="test")
admitted, _ = store.admissions.admit(epoch=epoch, principal_id="owner", session_id="s", request_id="r1", payload={"text": "hi"})
claimed = store.admissions.claim(epoch=epoch, session_id="s")
assert claimed.admission_id == admitted.admission_id
settled = settle_claim(store, claimed)
assert (settled.admission_id, settled.status, settled.outcome) == (admitted.admission_id, "terminal", "completed")
assert store.admissions.get(admission_id=admitted.admission_id).outcome == "completed"

View File

@@ -0,0 +1,21 @@
"""Storage interface handles for fake authorities: opened on a profile home, closed after each test.
A test module activates the closing fixture by importing ``close_storage_handles`` beside
``storage_handle``."""
import pytest
_HANDLES = []
@pytest.fixture(autouse=True)
def close_storage_handles():
yield
while _HANDLES:
_HANDLES.pop().close()
def storage_handle(home):
"""A storage interface handle on *home*'s state.db, closed after the test."""
from persistence_assembly import open_persistence, profile_scope
_HANDLES.append(open_persistence(profile_scope(home=home)))
return _HANDLES[-1]

View File

@@ -0,0 +1,46 @@
"""A storage interface handle beside a store never changes what the store's path does."""
from contextlib import ExitStack
import pytest
import persistence_assembly
from persistence_beside import close_beside, open_beside, open_reader_beside
@pytest.fixture
def failing_opens(monkeypatch):
def fail(*args, **kwargs):
raise ValueError("unknown persistence provider 'nope'")
monkeypatch.setattr(persistence_assembly, "open_persistence", fail)
monkeypatch.setattr(persistence_assembly, "open_persistence_reader", fail)
def test_open_beside_opens_a_handle_on_the_named_home(tmp_path):
handle = open_beside(tmp_path)
try:
assert handle.scope.profile_dir == tmp_path.resolve()
finally:
close_beside(handle)
assert not (tmp_path / "state.db").exists()
def test_a_failed_open_answers_none(failing_opens, tmp_path):
assert open_beside() is None
handles = ExitStack()
assert open_reader_beside(tmp_path / "state.db", handles) is None
close_beside(handles)
def test_close_beside_keeps_a_failed_close_to_itself():
class Raising:
closed = 0
def close(self):
self.closed += 1
raise OSError("disk I/O error")
handle = Raising()
close_beside(handle)
close_beside(None)
assert handle.closed == 1