12 Commits

Author SHA1 Message Date
yoniebans
6d3d757e5b fix(storage): a lagging owned store keeps its named refusal when its full-text index is also broken
The checked reader ran its full-text index probes before the declared-schema probe, so a store that lags the schema and also has a broken full-text index failed on the index first. A gateway-owned store then got the generic "schema unavailable" 503 instead of the missing column and the gateway restart command, as on main. The reader now runs the drift probe first on the same connection, the order main's separate admin check had; a store at the current schema with a broken index is unchanged.

Co-authored-by: Bear Huddleston <bear@bearhuddleston.dev>
2026-11-18 15:12:51 +01:00
yoniebans
68bb692467 fix(storage): a browse read checks schema drift on its own connection
Every Desktop and dashboard session read opened state.db twice: an admin handle ran the declared-schema probe on a fresh connection, then the reader the read uses opened another. The read-only SessionDB browse the storage interface replaced ran that probe on its one reader connection, so each open and page read became about a third slower at the median.

open_persistence_reader gains check_drift, passed through the backend to the read-only holder the way patience_s is. With it, the holder's open runs the probe on its own connection and raises the core DeclarativeDrift with the reason StoreAdmin.schema_drift_reason gives; both now share one helper, declared_schema_drift. The browse open binds its reader with the check, and on drift runs the existing one-time catch-up and opens again, so a store that lags the declared schema is still caught up or refused by name exactly as before. A browse open's failures are reported in its 503 only and no longer reach the process's last session-store init error; main's browse wrote it only when its reader failed after the separate probe had passed.
2026-11-18 15:12:51 +01:00
kshitijk4poor
a84e7f1847 refactor(storage): attribute ranked FTS corruption inside the search read, drop the holder hook
The gate wave on 764c751 found that the `rescope` keyword threaded through
StoreHolder._read_all/_read_retrying_ioerr put FTS policy on the shared read
boundary, and that the diagnostic probe ran on a second pooled reader, after
the failing read had released its snapshot.

Search now owns one MATCH read (_fts_match_read) that runs inside
_read_retrying_ioerr's callback. It attributes a bare SQLITE_CORRUPT on the
rank-only route on the SAME connection before the error reaches the
storage-health latch. _holder.py is back to main, and both ranked call sites
share the read.

The genuine-corruption test now drives search_messages instead of the private
closure.
2026-11-18 16:37:44 +05:30
kshitijk4poor
15ad970a27 fix(storage): address review on the FTS rank-corruption fix
- Empty realigned store: the marker realign of a store with no messages runs
  inside SAVEPOINT fts_align_empty; run its DDL through
  _execute_ddl_script_transactional so executescript's implicit COMMIT no
  longer ends the savepoint ("no such savepoint: fts_align_empty" on open).
- Trigram / OR-relaxed retry that detaches the indexes now answers the
  triggering request from canonical rows (exact terms, then any term)
  instead of returning an empty miss.
- _read_all passes rescope only when set, keeping the one-argument
  _read_retrying_ioerr call shape other callers and test spies rely on.
- Rank detection compares against the rank-only ORDER BY constant instead
  of a substring test on the SQL fragment.

Tests: empty-store reopen with the retired marker; trigram and OR-relaxed
retries return the stored row on the first request.
2026-11-18 16:37:44 +05:30
kshitijk4poor
2c0bde027b fix(storage): keep FTS index damage index-scoped on ranked search; realign stores a pre-v3 release reopened
A dashboard search could take a whole profile's session storage down until restart
although state.db was intact (PRAGMA quick_check: ok).

FTS5 evaluates `ORDER BY rank` in a nested sorter statement and SQLite masks that
statement's error to the primary code, so index damage bm25 reports as
SQLITE_CORRUPT_VTAB (e.g. a posting whose _docsize row is gone) reached the read path as
bare SQLITE_CORRUPT. _read_retrying_ioerr published it before the search's existing
fail-open could run, it classified as structural, and the process-wide latch refused
every session.create/resume with storage_unavailable.

- StoreHolder._read_all/_read_retrying_ioerr take an optional `rescope` applied before
  the storage-health latch. The ranked MATCH reads pass one that, only for bare
  SQLITE_CORRUPT on a rank-ordered statement, re-asks the index alone (unsorted bm25
  keeps the extended code). An index-scoped answer replaces the error, so the existing
  fail-open answers from canonical rows and the error, if raised, maps to
  SearchIndexCorrupt; anything else keeps the original and still fails closed.
- The zero-hit trigram retry now fails open like the other ranked routes.
- _migrate_misaligned_fts_source also realigns a store whose retired
  fts_tool_full_content_high_water marker is back. A release before FTS storage v3
  reopening a realigned store re-stamps it at MAX(id) and reinstalls id-gated triggers
  whose 'delete' sends full content for tool rows the v3 rebuild indexed as the bounded
  prefix; each such delete leaves the token cut at the boundary behind with no _docsize
  row, which is the damage above.

Wire error codes are unchanged.
2026-11-18 16:37:44 +05:30
yoniebans
be3d6affc8 refactor(state)!: remove the old session store
hermes_state.py becomes the stand-in plugins import, the rest of the legacy store and its test folder go, and the per-process modules the backend imported from main move under persistence/sqlite/_state/. The backend checks PID namespaces and lease holders through process_identity and its WAL setup through sqlite_support, and its error module takes the shared predicates and classification from storage_errors, so neither helper set has a second copy. The backend, sqlite_support.py and the tests that pin those modules reach their final imports, and the backend-import guard allows no file outside persistence/. The modules no caller imports any more go with it: the agent's onboarding rules (now in session_rules) and gateway/session_admission.py.

The stand-in's SessionDB releases its store on close() and, used again afterwards, opens it again with a warning, as the old class reopened its connection, unless the file at its path was replaced or the store is latched corrupt; a read-only one raises. A close during a call releases the store when the call returns. A named source wins over a source list in its session listing and count.

An agent given a writable stand-in SessionDB as session_db= and no persistence= takes the store handle that SessionDB forwards to as its persistence, so its turn flush, token counts, compression and session row writes go through the storage interface, as an agent given the old SessionDB wrote through it.

The backend-import guard also holds the backend's remaining reads of the process or task home, each with its reason, and refuses any other and any import of the stand-in inside persistence/sqlite/.

Plugin context engines get the agent's store as persistence= beside the deprecated session_db=, in each hook whose signature accepts that keyword, including the rebind after /new, /resume and /branch, and the context engine guide and the plugin guide's replacement table name it. A test fails once the running release reaches the stand-in's removal release, listing what goes with the stand-in.

release_unheld_media and collect_unheld_api_images take a store only: their SessionDB branches, which no caller reaches, go with the gateway's own copies of the admission and transcript queries.
2026-11-17 19:10:57 +01:00
yoniebans
af7f2f3806 fix(persistence): a read-only holder reads its application id without a header probe
The spillover reader behind session auto-prune opens a read-only StoreHolder. It already waits in connect_tracked while close_all_under closes the home's header probes, but the holder's identity record then read the application id through _pread_db_range, which opened and cached a new probe fd for the path the sweep had just released. That probe outlived the reader and stayed until the next sweep or exit.

A read-only holder never runs the write-path replacement checks that compare against the recorded id, so it now takes the id from its own connection (PRAGMA application_id) and leaves the probe cache alone. Writer holders keep the lock-safe raw header read.
2026-11-17 17:51:23 +01:00
yoniebans
499db5e413 fix(persistence): the SQLite holder fails closed on a symlinked state.db path
The holder's state.db hardening now raises OSError(ELOOP) on a symlinked state.db, -wal or -shm instead of skipping it, so sqlite3.connect() never follows a planted link; a state.db link the operator made to a store of their own still opens. Modes are tightened through _chmod_pinned_inode, which never re-resolves the path to a swapped-in link. The registry judges the link with refuse_planted_state_db_link before resolve() hides it.

Main's fail-closed cases run against the holder, the registry and the backend's open.
2026-11-17 17:49:49 +01:00
yoniebans
2450bffa31 feat(persistence): serve the prompt-cache clock from the SQLite usage repository
The holder keys prompt_cache_clock like a route field, so queued deltas carrying different cache events apply in order and are never merged. The usage delta passes its clock to the token update, which writes the column only when a clock is given, with main's statement. The usage repository gains prompt_cache_clock (one statement: the stored clock, the resume fallback only for sessions whose cache counters are non-zero, and the archived-row generation, after draining the queue) and prompt_cache_generation, and the session record carries the column.
2026-11-17 17:49:49 +01:00
yoniebans
c2100ebc39 fix(persistence): a holder read that falls back to the locked writer logs a rate-limited WARNING
When every pooled read permit is out, StoreHolder._get_read_conn hands the read to the writer connection under the write lock, where it waits behind every in-flight write. The holder now reports it through hermes_state_readpool.note_read_pool_exhausted: one WARNING per database per window, counting the reads that degraded since the previous one, never SQL or parameters.

Tests: test_read_pool_exhaustion_warning.py ports the SessionDB cases against the holder.
2026-11-17 17:49:48 +01:00
yoniebans
1a515b1766 fix(persistence): the holder's writer mutex honours write patience and queued usage survives a refusal
StoreHolder._execute_write takes the in-process writer mutex with writer_mutex_until from hermes_state_write: a write that cannot take it within its patience is refused before BEGIN with WriterMutexTimeout (SQLITE_BUSY, "in-process" wording), never replayed, and the refused waiter logs the holder's thread and call site once per window. The token writer puts a refused delta and everything after it back at the front of the queue; flush_token_counts reports the requeue and the close-time drain retries instead of dropping deltas.

Tests: test_writer_mutex_patience.py ports the SessionDB patience and patience-contract cases against the holder; the clean-close residual-poison lock double now offers acquire/release, since the mutex is taken with a timeout.
2026-11-17 17:49:48 +01:00
yoniebans
c9f3a2ffd4 feat(persistence/sqlite): one store holder per state.db, handed out by a registry
_holder.py owns the writer connection and its lock, BEGIN IMMEDIATE write transactions with jittered replay, the bounded read pool, WAL setup, file and WAL-generation guards, quarantine and close; _registry.py hands out one holder per state.db per process.
2026-11-17 17:49:46 +01:00