41 Commits

Author SHA1 Message Date
kshitijk4poor
8f239226bc fix(plugins): plugin writes refuse a deleted or renamed profile home
A session still bound to profile b survives `hermes profile delete b` and
`hermes profile rename b c`. Its next plugin write recreated profiles/b
through a raw mkdir, and nothing raised.

Seven plugin state writers now create their directories through
mkdir_under_hermes_home, which refuses a missing or tombstoned named home
with its existing FileNotFoundError: plugin_data_dir (and the
hermes-achievements fallback that duplicates it), the CLI plugins dir,
the update-check markers, disk-cleanup state, the Discord recovery ledger,
the Weixin account dir and the A2A audit log.

Callers that already catch keep skipping the write (Discord recovery,
the update-check writers, the disk-cleanup session-end hook and audit log,
the A2A audit). The disk-cleanup slash commands reply that the profile no
longer exists instead of raising. plugin_data_dir documents the refusal.
2026-11-22 02:17:23 +05:30
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
5b6696a012 fix(storage): carry the unattributed corruption on the probe's IOERR, not via __context__
Second-model review of e468bba3ce: an exception's __context__ is not proof
that it came from the rank probe. A plain ranked-read IOERR raised while the
caller was handling an unrelated DatabaseError was treated as an exhausted
probe and latched that ambient error. The probe now raises _RankProbeIoerr,
an OperationalError (still retried by _read_retrying_ioerr) that carries the
corruption it was diagnosing, and only that type is restored after the
budget is spent.

Test: a plain ranked-read IOERR inside a handler for an unrelated corruption
error answers [] and latches nothing. Red on e468bba3ce.
2026-11-18 16:37:44 +05:30
kshitijk4poor
8bd953b770 fix(storage): only a transient IOERR from the rank probe is retried; an inconclusive probe fails closed
The delta review of 6410cd3ca1 showed the probe re-raised every
OperationalError. "database is locked", "interrupted" or "no such function"
then replaced the bare SQLITE_CORRUPT, and the primary search route turned
it into an empty answer with nothing latched, where 5046fe2946 failed
closed. The probe now re-raises only disk I/O errors and keeps the original
error otherwise. An IOERR that outlasts the read retry budget restores the
unattributed corruption the probe was diagnosing (latched and raised)
instead of surfacing as the IOERR the search maps to [].

Test: a locked probe and a probe whose IOERR persists both leave
SQLITE_CORRUPT raised and latched, and only the IOERR case replays the read.
Both cases are red on 6410cd3ca1. The transient-IOERR test now asserts
exactly one failed probe.
2026-11-18 16:37:44 +05:30
kshitijk4poor
018d1f9c27 fix(storage): a transient IOERR in the rank probe replays the read instead of latching
Second-model review of 5046fe2946: the attribution probe caught every
DatabaseError, including a transient "disk I/O error" OperationalError, and
then returned the original bare SQLITE_CORRUPT. _read_retrying_ioerr retries
only IOERR, so it published the unattributed error to the storage-health
latch: the bug this PR fixes, reachable when index damage and the WAL
transition window coincide. The probe now re-raises OperationalError so the
holder replays the whole read.

Also from the gate wave:
- _in_one_read moves unchanged from stored_reads to sql_common, so search no
  longer imports a private helper from the transcript module.
- The interrupted-realign test raises only after the FTS DDL, not after any
  script the executor runs.

New test: a disk I/O error on the first probe replays the read, answers from
canonical rows and leaves storage ok. Red with the re-raise removed.
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
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
d1829b9f72 F31: the network-filesystem detection cases run on Linux under platforms("linux") instead of faking the platform
Main's network-filesystem detection reads /proc/self/mountinfo on Linux only and answers False elsewhere; tests/AGENTS.md ("Don't fake the host OS") says such a case runs on its host under @pytest.mark.platforms("linux") and never patches sys.platform.

The removal commit's copies of test_network_fs_wal_warn.py and test_network_fs_journal_default.py added a `_linux` fixture that set sqlite_support.sys.platform to "linux", so the Linux-only detection cases ran on every host over a faked platform.

The fixture is gone and the three cases that used it (16 parametrised runs) carry @pytest.mark.platforms("linux"). The other cases, host-independent, stay unmarked.

Proof: before, on darwin, both files passed 26 with the fake (19 + 7) and grep finds the two `monkeypatch.setattr(sqlite_support.sys, "platform", "linux")` lines; after, on darwin, 10 passed and 16 skipped with "platforms(linux); host is darwin" (4 passed, 15 skipped; 6 passed, 1 skipped), and no sys.platform patch is left. The 16 cases read only the mountinfo file they are given, so on Linux they run as they ran under the fake; the main Linux CI lane runs them. ruff clean.

Reported-by: greptile-apps[bot]
2026-11-17 19:10:58 +01:00
yoniebans
01e3ae05f2 test(persistence): pin a rename through an ended compression segment on the SQLite backend
Six cases drive the backend through the storage interface: the lineage is published as a compression child and each rename is a runtime sidebar mutation. A rename addressed to the ended segment lands on the live tip and is what the listing shows, a name the ancestor holds moves to the tip, an older copy of any segment is stale after a tip rename, a clear through the segment clears the listed name, a name taken from an abandoned chat advances that chat's revision, and a clear never empties the canonical Bot Chat ancestor.
2026-11-17 19:10:58 +01:00
yoniebans
0edf4be2b3 refactor(state): the backend and the backup share one zeroed-file detector in sqlite_support
The removal gave the backend's dbfile module its own copy of hermes_cli.backup.is_zeroed_sqlite_file, because the backend does not import hermes_cli.backup, and the test that kept the copy equal to backup's went with the old store's parity tests. So the detector existed twice, plus the header probe is_zeroed_state_db falls back on, and a fix to the live-connection guard or the header test had to land in both copies. The function now lives once in sqlite_support, the neutral SQLite helper module both sides already import, moved from hermes_cli/backup.py unchanged; backup.py and the backend import it from there, and the backend's copy goes. is_zeroed_state_db keeps main's fallback probe for the case where the detector raises.

The new case checks that the backend, the backup and sqlite_support name the same function; it fails before this commit. Greptile raised the duplicate in review.
2026-11-17 19:10:58 +01:00
yoniebans
bd36de5d41 test(state): operand-taking interpreter options are read past to the program they precede
The case that compared process_identity's two option tables with copies of their contents is replaced by cases through the readers that use such tables. Each operand-taking option (-Q, -W, -X, --check-hash-based-pycs, --jit), with its operand as the next token or attached, goes in front of a program: gateway.status_inline_source must still find the -c behind it and must not report inline source for a -m module, and the SQLite backend's holder reader must still name the -m module or the script. Dropping any one option from either table turns its cases red.
2026-11-17 19:10:58 +01:00
yoniebans
1e0fda4744 test(persistence/sqlite): reach the backend holder through raw_holder
The append batch, automatic ended stamp and FTS fail-open cases fetch the SQLite holder of their store handle through tests/fixtures/storage_holder.raw_holder, the one test helper that names the backend, instead of calling the handle's holder() themselves.
2026-11-17 19:10:58 +01:00
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
f1cd9b0703 fix(storage): callers identify a store by its profile scope, not by its file
store_location() answers None for a provider whose store is not a file, but callers used the file as the store's identity: the delivery and async-delegation ledgers rebuilt their scope from the file's parent, the session authority keyed its epoch fence and checked ownership on the resolved file, and handle caches, the media sweep, the subagent roster and the group controls compared or keyed stores by path. With no file each of those raised or skipped its work.

Those callers now carry the profile scope: the ledgers open their scope directly (the tests that redirected the ledgers' file now redirect the scope), keys and comparisons use the scope's home key, and the gateway's ownership check keeps main's resolved-file test when the store has a file. persistence_assembly gains store_exists(scope), answered by the store's readiness probe, which replaces the .exists() and .is_file() checks that asked whether a profile has a store before a reader opens it; readers open the profile home rather than its file.

Identity that is written down and read back keeps main's format for a file store and names the profile home otherwise: the Kanban owner receipt and the -w worktree lock, whose readers open either. The standalone hosted-rooms import has no legacy file beside a store without one, so it moves nothing. Features that work on the file itself (session repair, journal mode, the dashboard sidebar's file cache) refuse and say they need a file-backed store.
2026-11-17 17:51:22 +01:00
yoniebans
ebcc56e80a test(persistence/sqlite): backend and contract cases that drive the switched callers
These cases exercise the backend through callers that now use the interface, so they land after them. The legacy tests/hermes_state copies of the same cases go with them.
2026-11-17 17:51:21 +01:00
yoniebans
b29699077f refactor(state): serve SessionDB through the backend's store holder and registry
SessionDB keeps its methods and opens no connection of its own: it takes its writer, read pool and write transactions from the SQLite backend's holder, handed out by the backend's registry, so a process holds one writer per state.db whichever door a caller uses. The legacy tests that reached the old connection fields follow the new owner, and the mixed-caller cases pin one writer, one VACUUM gate and one profile release for a process that uses both doors.

A SessionDB built without a holder takes its own reference on the registry's holder for its file, as the backend's stores do, and returns it once: at close, or when the handle is collected unclosed. When that close is the last release and the holder could not close (a lost WAL generation whose capture failed keeps it open), close() raises the holder's error as the legacy close did; a handle collected unclosed only logs it. A read-only one opens a read-only holder, as the read-only backend does. Tests that stand for a second writer in the process open it on a holder of their own.

Tests that patched names this change moves follow them: the registry's holder open, the read lock wait, the clock the store stamps rows with, and the token writer's seam, whose loop-thread read case runs on the backend's holder.

The desktop source-backend fixture copies persistence and session_rules into its test install, since hermes_state imports persistence.
2026-11-17 17:50:50 +01:00
yoniebans
55dc43ef57 F24: the SQLite store answers serves_same_store by holder identity
Two SQLite handles serve one store while they share one holder: the registry hands every handle on a profile the same holder for the file's current generation, and a handle opened after state.db was replaced takes a new one while the older handle keeps the generation it held, as main's registry identity check compares its objects. SQLiteStore.serves_same_store compares holders, and the assembly's Persistence forwards it between the stores the two handles are bound to. A handle opened after the file was replaced reads the replacement and does not serve the same store as the owner; red without the method (the case raises AttributeError), green with it.

Reported-by: Greptile
Reported-by: BearHuddleston
2026-11-17 17:50:49 +01:00
yoniebans
efeff2acec F41: one boundary case per typed store error the backend maps
The boundary case pinned five of _store_error's mappings, so the transient I/O, FTS corruption, malformed schema and generic corruption branches could each be removed without a failure: the error then fell through to a wider class. The case gains one row per branch and asserts the exact class, not a parent. Removing each branch in turn fails exactly its row (four mutants, 8 passed and 1 failed each); the code is unchanged.

Reported-by: unsupportedpastels
2026-11-17 17:49:49 +01:00
yoniebans
d2ad2e6eb3 test(persistence/sqlite): the ledger-opening write in the journal-mode and schema cases is a delivery claim
The delegation ledger has no delivered-acknowledgement call any more; these cases need only a write that opens the ledger's store, and a delivery claim is that write.
2026-11-17 17:49:49 +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
ac7459e9b3 fix(sqlite_support): carry the network-filesystem journal-mode policy
A new store on an nfs/cifs/smb/sshfs mount starts in DELETE unless database.journal_mode is set explicitly, with one WARNING naming the override; an existing WAL store there keeps WAL (never live-downgraded) and gets one WARNING with the offline remedy, on both already-WAL paths. Stores opening through sqlite_support.open_db, including the hosted-room shared-state.db, follow the same policy as hermes_state_wal.

Tests: tests/persistence_sqlite/core/test_sqlite_support_network_fs.py and test_sqlite_support_network_fs_store_coverage.py.
2026-11-17 17:49:49 +01:00
yoniebans
6fe267fea2 fix(persistence): the delete hook dispatch binds the store's profile, as the old store did
The on_session_delete dispatch keeps main's legacy profile setter: under a bound local scope it binds the store's whole profile for the hook, so that profile's plugins run with its own secrets and terminal policy, and in a hosted scope it refuses as main's does. push_state(home=...) would have moved only the home and left a plugin of one profile reading another profile's secrets. The store open keeps push_state, binding only the home for its configuration read. The line carries the health waiver for the setter main itself uses at this point.
2026-11-17 17:49:49 +01:00
yoniebans
07bc10c39f fix(persistence): bind only the store's home with push_state when opening and dispatching
The store open's _home_bound and the on_session_delete dispatch in session_retention bound the store's profile home through the legacy set_hermes_home_override, which under a bound scope moves the whole scope (secrets and terminal policy with it) or refuses in a hosted one. Both now push the home alone with hermes_scope.push_state(home=...), keeping the bind condition and resetting the token afterwards, so the caller's scope stays its own.
2026-11-17 17:49:49 +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
7a21a2d1f8 fix(persistence): the holder registry releases header-probe fds when close_all_under sweeps a home
hermes_state_dbfile caches one O_RDONLY fd per state.db so the on-write header probe never closes a descriptor SQLite has locked, and nothing evicted those entries: a multiplexed gateway kept one fd for every profile it had unserved. close_all_under in persistence/sqlite/_registry.py now releases the probe fds under the swept home, never while another descriptor in the process holds the probe's inode: one descriptor scan per sweep under the paths' lifecycle locks, then an inode rescan inside offline_file_access before each close, so a tracked open through another pathname (a hard link) after the first scan keeps the probe. _path_is_under is hermes_state_common.path_is_under.

Tests: test_header_probe_release.py ports the SessionDB registry cases against the holder registry.
2026-11-17 17:49:48 +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
891473d2d4 fix(persistence/sqlite): a store in a folder with no settings of its own opens without setting the folder up as a home
Binding the store's folder as the Hermes home while it opens makes the configuration read run under that folder, and reading the configuration sets the bound home up first: sessions/, cron/, logs/, memories/, skills/, SOUL.md and the rest appear in any folder a store is opened on, where main creates them only for the current home. A folder without a config.yaml has no database settings to read, so the backend now binds it only when it holds one; a profile with its own settings still opens with them. A backend case opens a store in a folder without a config.yaml and checks none of the home's folders appear.
2026-11-17 17:49:48 +01:00
yoniebans
6ca27d12f1 fix(persistence/sqlite): a store opens with its own profile's database settings
The connection helpers read database.* (synchronous, cache_size and the rest) through load_config_readonly(), so they follow the Hermes home bound when the connection opens. Main's gateway acquires a served profile's state.db at once, under that profile's bound scope, so its writer takes that profile's settings. A store handle here opens its file on first use, and a store is named by its profile, so a handle opened under the served profile's scope but first used after the scope was reset, or a profile's store named from another profile, opened with the settings of whichever profile the caller ran as: a caller with synchronous OFF could open another profile's writer with OFF.

The backend now binds the store's own home while it acquires the holder, so the writer, the read-only holder's connection and the schema setup at open read that profile's configuration, as main's open under the served profile's scope does. Read connections the holder opens later from another thread take the settings of the home bound on that thread, as main's pooled readers do. A backend case writes different database settings for the caller's home and the store's profile and checks that the writer and a read-only holder open with the profile's.
2026-11-17 17:49:48 +01:00
yoniebans
855591dc56 fix(persistence/sqlite): a handle opened after its file is replaced uses the new file
Every handle on a profile shares one backend, and the backend kept the holder it first acquired for as long as any handle stayed open. Once state.db was replaced (a snapshot restore, a recovery swap), a handle opened afterwards was given that fenced holder: its writes raised StoreReplaced and its reads answered the old file until every handle had closed. On main a new acquire after the replace gets the registry's new generation, and only the instance opened before it stays fenced.

Each store handle now keeps the holder it first used. A handle without one asks the registry for the current generation; when that is a new one, the backend serves it to new handles and keeps the superseded holder for the handles that opened it, so they stay fenced, and releases both at close. A sweep and the read-only backend behave as before. A backend case replaces the file under an open handle and checks that a new handle writes the replacement, the old handle's write raises StoreReplaced, and close releases every generation.
2026-11-17 17:49:48 +01:00
yoniebans
dbb47c5fe0 fix(persistence): forward only the storage interface's names from a handle
A Persistence handle forwarded every public attribute of the SQLite store it binds, so a caller could reach the SQLite-only holder (and through it a live sqlite3 connection), the store's file path and its executor, none of which a second backend would have. The handle now forwards the names PersistenceStore declares and ready; any other name raises AttributeError whether the handle is open or closed, so a getattr(handle, name, None) probe keeps answering None. A protocol name read after close still raises the closed-handle RuntimeError.

The test fixture's raw_holder and hosted_upload reach a handle's bound store directly, so the tests that read raw SQL through a handle keep working, and the two backend tests that called holder() on a handle use raw_holder.
2026-11-17 17:49:47 +01:00
yoniebans
ffed216232 fix(persistence/sqlite): pin the float spelling and chat id refusals in the SQLite backend's own tests
The shared contract asks every backend only for neutral properties of float content and unbindable chat ids, so the exact behaviour main has, and the SQLite backend keeps, is pinned here instead. Float content reads back as the text a SQLite TEXT column stores for it, for the eight values whose spelling differs between SQLite builds. A chat id outside SQLite's 64-bit range raises the driver's own OverflowError ("Python int too large to convert to SQLite INTEGER") with no cause; a list or dict raises PermanentStoreError chained to the driver's ProgrammingError ("Error binding parameter 6: ..."). Each refusal leaves no session row and no routing entry.

The removed case compared the reference backend's float spelling with the installed SQLite, which the reference now asks for that spelling, so it compared the library with itself and tested no backend.
2026-11-17 17:49:47 +01:00
yoniebans
5ad33d226e fix(persistence): refuse a closed handle while another holds the backend
A Persistence handle checked for close only before its first bind, so a handle closed while another handle on the same profile kept the shared backend open still answered every attribute and wrote through it. Every attribute read now raises "persistence handle used after close" once the handle is closed, whatever else holds the backend.
2026-11-17 17:49:47 +01:00
yoniebans
b651abfa32 test(persistence/sqlite): conversation cases
The SQLite backend's conversation cases.
2026-11-17 17:49:47 +01:00
yoniebans
713dccf891 test(persistence/sqlite): holder, registry, schema and file cases
The SQLite backend's cases for the holder, the registry, the schema and the store files.
2026-11-17 17:49:47 +01:00