Commit Graph

11 Commits

Author SHA1 Message Date
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
09ded63c4f fix(storage): re-read the realign decision under the lock; share _in_one_read with _display_set
From the final-head gate wave on b12ce8e275:

- Two openers that both saw the retired marker before rebuild admission each
  ran the full rebuild in turn (about 130 s on a 1.35M-row store), because
  the admitted callback did not re-check whether a peer had already
  aligned. align_locked now re-reads the layout and the marker under
  BEGIN IMMEDIATE and skips when there is nothing left to do. New test: the
  opener admitted second runs no rebuild; red on b12ce8e275
  (['second', 'first']).
- messages._display_set uses the shared sql_common._in_one_read instead of
  its own copy of the same BEGIN/ROLLBACK wrapper.
- Docstrings corrected where they no longer matched the code: the probe's
  IOERR may be persistent; _attribute_ranked_corruption raises it for a
  replay; _fts_match_read publishes the unattributed error after the retry
  budget; a writable write as well as a search detaches a damaged index;
  the skip decision is re-read under the lock.
2026-11-18 16:37:44 +05:30
kshitijk4poor
086b108734 refactor(storage): reuse _in_one_read for the ranked snapshot; guard the atomic realign in CI
From the gate wave on 529797fa7c and BearHuddleston's re-review:

- The rank-only MATCH pins its snapshot through the existing
  stored_reads._in_one_read instead of a local copy of the same
  BEGIN/ROLLBACK wrapper.
- _migrate_misaligned_fts_source: one locked helper owns the population
  recheck and the realign; the admitted callback is named instead of a
  lambda returning an ignored value.
- New test: a realign interrupted after its DDL leaves the old index hit and
  the retired marker in place, and the next open realigns. Red with the
  BEGIN IMMEDIATE removed.
- Reopens in the realign tests assert FTS stays enabled instead of skipping.
- _search_messages_stale docstring narrowed to the Latin retries (Bear's
  suggestion: a triggering CJK trigram failure still takes _search_cjk's
  any-term fallback, as on main). The empty-store test no longer names a
  savepoint.
2026-11-18 16:37:44 +05:30
kshitijk4poor
82fe239966 refactor(storage): one detached-search answer, one in-memory detach; honest read-only contract
From the gate wave and second-model review of 83d9fa65b3:

- A store whose FTS is detached now answers through one helper on the
  triggering request and every later one: LIKE on the exact terms, then on
  any term after a miss (CJK skipped, as the FTS OR-relaxed retry does). Before,
  the triggering OR-relaxed request found a row the next identical request
  did not. The primary-route detach returns that answer directly, which
  removes the detached_before_retries flag.
- _mark_fts_detached owns the three in-memory flag writes shared by
  writable fail-open, deferred admission, the cross-process stale refresh and
  the read-only detach.
- Read-only detach: the warning and docstring no longer promise that the next
  writable open repairs the index (nothing is persisted); they name the real
  paths, a writable search or `hermes sessions optimize-storage`. The test
  checks state_meta through a raw read-only connection instead of after a
  writer open.
- Realign: the marker check is inlined with its rationale, the rebuild timer
  starts inside do_align, and the warning states what is known (the marker
  only pre-v3 releases write) instead of asserting the history.
- The injected-error latch test is named for what it injects.
2026-11-18 16:37:44 +05:30
BearHuddleston
0316063447 fix(storage): make the FTS realign atomic and diagnose ranked corruption on the failing snapshot
From BearHuddleston's review of 8678b050ac (three inline patches):

- Realign: the unlocked message check only routes populated stores to
  rebuild admission; the skip-rebuild decision, the DDL, any rebuild and the
  marker removal now commit together under BEGIN IMMEDIATE. A peer insert
  between the empty check and the old savepoint was indexed and then lost;
  an interrupted rebuild now rolls back to the old index.
- Ranked MATCH: pin a read transaction for the rank-only route so the
  diagnostic bm25 probe sees the same index generation as the failed read
  (a peer rebuild in between otherwise let code 11 escape and latch a
  healthy store). An existing transaction is left alone; the read-only
  transaction is ended by ROLLBACK.
- Test: delete one cut tool row while the pre-v3 trigger is installed, so a
  repair that only swaps triggers and keeps the old postings fails.

[Salvage: ported onto 83d9fa65b3 by kshitijk4poor; the _schema.py hunk was
re-applied by hand around the post-rebuild realign warning.]
2026-11-18 16:37:44 +05:30
kshitijk4poor
86ba5a8a52 fix(storage): fail open on read-only search handles; log the marker realign once it ran
Read-only handles (dashboard and TUI cross-profile browsing) cannot write
the stale breadcrumb, so _enter_fts_fail_open refused and the newly
index-scoped error propagated instead of answering from canonical rows.
Search now detaches FTS for that handle's own lifetime and serves LIKE,
leaving the persistent detach and the rebuild to the next writable open.

The pre-v3-marker realign now logs after the rebuild has run, with its
duration (130 s on a 1.35M-row / 8.9 GB store clone), instead of claiming a
rebuild before admission decides. A deferred open logs only the existing
deferral line.
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
9f45375906 fix(persistence): heal reset rows carrying a stray delegate marker on open
A chat's /new continuation (session_key and _reset_from set) that picked up _delegate_from is hidden from every session list while the gateway keeps routing into it. The SQLite backend's schema open now strips the stray marker, as main's store does, and indexes the healed rows' messages into the trigram index under the same rebuild-window rule as the triggers.
2026-11-17 17:49:48 +01:00
yoniebans
1156b1e343 feat(persistence/sqlite): the state.db schema, DDL and migrations
_schema_ddl.py holds the state.db DDL and the FTS layout checks; _schema.py runs schema creation, column reconciliation, the data-migration ladder and the FTS setup on open; _dashboard_procs.py is the Desktop backend argv test the orphan holder reaper runs.
2026-11-17 17:49:46 +01:00