Repository navigation
feat(session)!: store sessions in SQLite - #729
Merged
Merged
Conversation
This was referenced Oct 28, 2026
hakula139
force-pushed
the
feat/session-sqlite-store
branch
from
October 28, 2026 14:06
9f356c0 to
9f0c06d
Compare
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
hakula139
force-pushed
the
feat/session-sqlite-store
branch
2 times, most recently
from
October 28, 2026 17:05
65a2532 to
b1615e5
Compare
This was referenced Oct 28, 2026
hakula139
force-pushed
the
feat/session-sqlite-store
branch
2 times, most recently
from
October 28, 2026 18:31
5dc8ab9 to
181fb88
Compare
…ctors Session liveness locks need a shared lock held while a process has a session open, and delete needs an exclusive lock that fails at once while any process holds one. open_private_lock becomes open_private_file, since the store also opens its database through it.
One bundled-SQLite database holds every session: a sessions row with the head pointer, immutable message rows keyed by session and ID, and per-request usage rows. Commits run under BEGIN IMMEDIATE and fork lazily when the stored head moved since this process last looked. The store also lists sessions by keyset pages, loads a chain with a recursive CTE, and exports and imports sessions as JSONL, landing an import by ancestry.
SessionState builds each commit from the actor's batch, and the handle tracks the live session ID and artifact directory so they follow a lazy fork. Each ack carries a WriteReport with the first failure and the fork the batch made, a failed commit stops persistence for the rest of the session, and the engine emits Event::SessionForked. The resolver imports an export path before resuming, and saved-session operations go through the store.
The store replaces the entry types, the chain builder, and the session path layout, along with the snapshots of the JSONL format.
The TUI notes a fork in chat and moves its status bar to the fork's ID, the stdio drivers print the notice to stderr, and the headless result reports the session the run continued in. Listings label a fork with the session it came from. ox export prints a session as JSONL, which ox -r <file> imports. The live harness and the leak check read sessions through the store, and the dev shell provides the sqlite3 shell for the leak check.
The persistence design covers the schema, versioning, write path, liveness locks, lazy fork, and export and import. The sessions guide covers where sessions live, backups, the local-filesystem requirement, forks, and moving a session between machines, and the release procedure copies the SQL dump and export fixtures.
hakula139
force-pushed
the
feat/session-sqlite-store
branch
from
October 28, 2026 19:15
181fb88 to
110e80f
Compare
This was referenced Oct 28, 2026
hakula139
added a commit
that referenced
this pull request
Oct 29, 2026
… config rules in ox-core (#737) ## Summary The `client.auth` shape rules in `ox-core/src/config/schema.rs` ("client.auth requires exactly one of value or file", "client.auth type login takes no other keys", "invalid client.auth.file: expected an absolute or `~/` path") and the user-layer redaction of private config values in `config/load.rs` had no `ox-core` test. Their only pins were the 19-case `INVALID_AUTH_CONFIGS` table and a relative-path test in `crates/ox/tests/cli.rs`, which spawned `ox config check` once per case, so a broken rule failed far from the code that owns it. Those rules now have unit tests next to their code, and the 1,674-line `tests/cli.rs` becomes one test binary with a file per area. - **Schema rules:** `config::schema` tests `LoginAuth` and `AuthValue` parsing through `toml::from_str::<FileConfig>` and `inline_secret` directly, asserting exact messages. They cover an inline value, absolute and `~/` files (with the home directory pinned), neither or both sources, an empty value, keys beside `type = 'login'`, and a header-unsafe value. The file check is the shared `expand_absolute`, whose own tests now hold its path cases. - **Bare `~` (user-visible):** `expand_absolute`, which `client.auth.file`, `client.extra_ca_certs`, and `permission.extra_roots` share, accepted `~` and `~/` because they expand to the absolute home directory. `client.auth.file = "~"` then passed `ox config check` and Home Manager's `checkConfig` and failed only when `ox` read the token, on Windows with a misleading "Access is denied". No caller can use the home directory itself: the credential file and the CA bundle name files, and an extra root already rejects `$HOME` as too broad. The helper now rejects both spellings with "expected an absolute or `~/` path", so the rule the authentication, configuration, and permissions guides state holds. Its tests pin `~`, `~/`, `~alice/...`, a relative path, and `~/ca.pem` under a relative home directory. The extra-root test pins the too-broad message with the home directory's absolute spelling. - **No raw path in expansion errors:** `expand_user`'s missing-home error no longer quotes the raw path and uses the spelling `rule.rs` already has ("failed to expand `~`: no home directory"). Every caller that shows the path already names it in its own context, so "errors never quote `raw`" now holds by construction, and `expand_absolute` needs no remap. The missing-home message stays untested, as on `main`, since no environment variable can force `home_dir()` to return nothing. - **Redaction:** `config::load::read_layer` gains a 16-case table of malformed private values in a user file, covering type errors, an unknown type, unknown fields, header errors, each custom message prefix that `safe_message` passes through, and a TOML syntax error. Each error must start with `invalid config at <path>: `, name the expected shape, and contain none of the private sentinels. Before this, only a project-layer case pinned redaction in `ox-core`. - **End-to-end privacy:** `config_check::rejects_a_malformed_credential_without_echoing_it` keeps two cases, a type error and a syntax error, to show that `ox config check` prints the headline after `Error:` and that neither stderr nor any file the run writes contains the value. - **CLI test layout:** `crates/ox/tests/cli/main.rs` holds the shared helpers (`ox`, `config_check`, `write_user_config`, `tree`, `assert_private_auth_run`, `request_header`) and declares `startup`, `config_check`, `native_auth`, `headless`, `repl`, `sessions`, and `signals` modules, the last gated once on `cfg(unix)`. Each module starts with `use super::*;`, and its test names drop the area's prefix, as in `config_check::rejects_an_unknown_key_with_its_file`. Test bodies are unchanged apart from the moved auth cases. - **Docs:** the testing conventions describe the area layout in Placement and Grouping and Naming, stating that every end-to-end test except the live tests in `tests/live.rs` builds as the one `tests/cli/` binary, and the Home Manager module's comment points at `tests/cli/config_check.rs`. Design decisions: - **Redaction tests in `load.rs`, rule tests in `schema.rs`.** The design review proposed moving the table into `schema.rs`, but most of its expected messages (`in \`client.auth\`: expected a string`, the custom-prefix pass-through, the TOML syntax error) are composed by `read_layer`'s redaction, so the table tests `read_layer`. The rules themselves (`LoginAuth`, `AuthValue`, `inline_secret`) are tested where they are defined, so each case lives in the module whose behavior it asserts. - **One test binary with area modules over several test binaries.** Each file under `tests/` is its own crate and link step, while a `tests/cli/main.rs` with modules links once and keeps the shared helpers in one place, as Codex's `exec/tests/all.rs` does. ## Test plan - The verification block passed at the first commit (`cargo fmt --check`, `cargo build`, both `cargo clippy` runs, `cargo doc --no-deps`, `cargo llvm-cov`, `pnpm format`, `pnpm lint`, `pnpm spellcheck`). After a test-helper fix in the final commit, `cargo fmt`, `cargo clippy --all-targets`, and `cargo llvm-cov` passed again: 1,924 `ox-core`, 1,461 `ox-tui`, 129 `ox` unit, and 40 CLI tests. - `cargo test --test cli` lists every test under its area module (40 before the rebase, 42 after #729 added two). - Patch coverage from the local lcov over the changed lines is 155/155. - CI run 40742080894 passed every job on the previous head b1d7d22, with codecov/patch at 100% of the diff. After the second review's fixes, the verification block passed again at 3791724, and CI passed on that head. After the rebase onto main, which ports #729's `tests/cli.rs` changes (the `saved_sessions` / `exported` helpers, the export-based resume tests, and the store-backed assertions) into `main.rs`, `sessions.rs`, `headless.rs`, and `native_auth.rs`, the verification block passed at 7b5e455 with 42 CLI tests. - The two moved shape rows without a private value (`{ type = 'bearer' }` and `value = ''`) are now parse-level `schema.rs` cases, and the `login` + `file` row is covered by `login_auth::try_from::rejects_any_other_key`.
hakula139
added a commit
that referenced
this pull request
Oct 29, 2026
…753) ## Summary Since #729, a failed compaction boundary write stops session persistence like any failed write, while the summary still replaces the transcript in memory and the failure is reported after `SessionCompacted`. Only a session writer that is gone, which takes a panic, discards the summary and leaves the transcript unchanged. Four places still described the pre-#729 contract, where a failed write discarded the summary and held the prompt, and the listing docs still described JSONL files. - **Compaction:** `docs/design/compaction.md` describes the current failure paths, names the `Auto-compaction was not saved` message a gone writer still produces, and says "summarizer failure" in both places, since the too-short refusal sends no request. The `replace_with_summary` and `run_compaction` docstrings say the same. `CompactFailure::NotSaved` is renamed `WriterGone` for the only case it covers, and the tests that run on a gone writer are named for it. - **Order test:** `reports_a_failed_write_after_the_compaction_event` records a message, fails every later write, and compacts. It asserts the summary replaces the transcript and the events are `[SessionCompacted, Error("Session write failed: ...disk full")]`, so moving the write report above the compaction event, which the TUI's chat clear would wipe, now fails a test. - **Resume design:** decision 12 describes one query per page on a worker thread. Decision 13, retitled "Keyset pages through `SessionWalk`", says pages never overlap while a session written between pages may show twice or not at all, that only current-project pages have an index serving their order, and that a prefix lookup searches the current project through `sessions_by_project` before it widens. Out of Scope no longer calls the picker an mtime list. - **Picker:** the `live_session_id` doc gives the real reason for the filter: resume, archive, and delete all refuse the live session. - **Slash commands:** `/archive` and `/delete` describe the archive time and the session's rows in place of entries and files. - **Guides:** the backup commands use `${XDG_DATA_HOME:-$HOME/.local/share}`, as the recovery block does, and the uninstall `rm -rf` commands quote their paths. ## Test plan - [x] `cargo fmt --check`, `cargo build`, `cargo clippy --all-targets`, `cargo clippy`, and `cargo doc --no-deps` pass - [x] `cargo llvm-cov`: 1971 tests pass - [x] `cargo deny check` passes - [x] `pnpm format`, `pnpm lint`, and `pnpm spellcheck` pass
hakula139
added a commit
that referenced
this pull request
Oct 29, 2026
…behave (#735) ## Summary The system prompt described Claude Code's harness, so the model misread its own. Nothing named oxide-code, so a model asked to stop `ox` from prompting before `cargo test` would edit `.claude/settings.json`, which `ox` never reads. The environment reported the user's `$SHELL`, often zsh, while every `bash` call runs a fresh `bash -c`, so zsh syntax failed and a `cd` in one call silently did not carry into the next. Nothing explained the permission modes, and a `plan` denial told the model to ask the user to adjust permissions, so it asked the user to leave `plan`. The model now learns where it runs, how its commands run, and what each mode means. - **Harness:** the introduction says the model runs in oxide-code, names `~/.config/ox/config.toml`, a project's `.ox/config.toml`, and the `AGENTS.md` / `CLAUDE.md` instruction files, says a project's config cannot add allow rules or change credentials, the endpoint, or TLS trust, says Claude Code's settings, hooks, skills, slash commands, and MCP servers have no effect, and points usage questions to `/help` and the user guides. This replaces the `If the user asks for help` bullet, a remnant of Claude Code's `/help` pointer. The `You are Claude Code, Anthropic's official CLI for Claude.` block is unchanged, since OAuth needs it byte-identical. - **Permissions and compaction:** the System section describes `manual`, `plan`, and `yolo`, explains that each command of a chain is checked on its own while syntax the check cannot analyze, such as `$(( ))` arithmetic or a `[[ ]]` test, asks in `manual`, and says earlier messages may be summarized. These bullets replace one that repeated the caution section. - **`plan` denials:** a call `plan` denies now returns ``The <tool> call was denied by `plan` mode, which allows only reads. Do not retry it. Finish investigating with `read`, `glob`, and `grep`, then present your plan.`` Denials by a rule or by the user keep their wording. This settles the third criterion of #727. - **Project config error:** the error for a project file that sets a user-only key now lists `[tui]` among what a project file may set, since `PROJECT_TABLES` has always allowed it and the old text told a user that a valid `tui.theme` key was refused too. - **Shell:** the environment section reads `Shell: bash, which runs each bash tool call` and lists the login shell on its own line, and the `bash` description says each call starts a new `bash -c` in the session's working directory, reads no stdin, and has `EDITOR`, `VISUAL`, and `GIT_EDITOR` set to `true`. - **Tool descriptions:** `read` gives its row format, `edit` says to copy `old_string` from after the tab that follows the line number while keeping the line's indentation, `grep` names the Rust `regex` dialect without lookaround or backreferences, says each line is matched on its own, and names the files a directory search skips, and `glob` names the same filters and its newest-first order. The `read` schema's default limit now comes from `DEFAULT_LINE_LIMIT`. - **Duplicates:** brevity was stated three times and is now stated once. The two speculative-scope bullets and the two compatibility-shim bullets are each merged into one with their qualifiers kept. The issue-link bullet asks for full URLs, since the TUI draws `owner/repo#123` as plain text and terminals detect only URLs. - **Design page:** [System Prompt](docs/design/prompt.md) records the request layout, the sections, the environment, the user context, the tool descriptions, and the decisions below, and takes over the context-refresh description from the persistence page, which links it. Design decisions, each recorded with its reason in the new page: - Claude Code's section order and wording stay wherever `ox` behaves the same, because Claude models are tuned against that prompt, and every sentence was checked against what `ox` does. This PR rewrites every sentence `ox` contradicts and merges rules the copied prompt stated twice. - The permission modes and the chain rule are described in the cached static prefix, since they are the same in every session. What to do after a `plan` denial goes in that denial's result, where it is the latest instruction the model reads and costs nothing on other requests. A static `plan` sentence would have contradicted the old denial tail at the moment it mattered. Telling the model which mode is active belongs in the user context and needs the engine's mode-adoption rework first, so it stays in #727. - The login shell line stays even when `$SHELL` is unset, where it reads `unknown`. Omitting it would need either a sentinel check or a new optional field in the recorded environment, which changes the session format for no gain to the model. - Tool descriptions carry only facts that would cost a failed call and that no result reports. The `read` binary refusal, the `read` page size, the `glob` result cap, and the `grep` size skip stay out, because each result already reports them and every request would otherwise pay for the sentence. Line-by-line `grep` matching stays in, because a multi-line pattern returns `No matches found`, which reads as absence. PR #729 rewrites the persistence page's Prompt Context section and still carries the context-refresh bullet this PR moves into the design page, so whichever lands second drops it. ## Test plan - [x] `cargo fmt --check`, `cargo build`, `cargo clippy --all-targets`, `cargo clippy`, `cargo doc --no-deps`, `cargo llvm-cov`, `pnpm format`, `pnpm lint`, and `pnpm spellcheck` pass, and all 94 added Rust lines are covered according to the local lcov report. - [x] Tests pin the new rules in the introduction, the System section, and Tone and style, the `bash` and `grep` description facts, and the full `plan` denial text in a `gate` test beside the deny-rule test, while the engine turn test and the `ox` CLI test check only that `plan` mode denied the call. - [x] `OX_LIVE=1 cargo live` against the Anthropic API over OAuth: 5 passed, covering streamed text, the tool round trip with a prompt cache read, `--continue`, auto-compaction, and thinking replay. - [x] The same suite through a third-party relay gateway that fingerprints the client request: 5 passed. - [x] The same suite through a corporate Anthropic-compatible gateway with custom headers and an extra CA: 5 passed. The suite's own leak check found no credential in any run's output or scratch files. - [x] The relative links and anchors in the edited design pages resolve.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Sessions lived in one JSON lines file per session, which the loader replayed and repaired on every resume, and two
oxprocesses on one session interleaved their entries in the same file. Sessions now live in one SQLite database,$XDG_DATA_HOME/ox/sessions.db, and JSON lines remain only as the interchange form thatox exportwrites andox -r <file>imports. This is PR 4 of the session storage redesign, following #714 and #719.synchronous = NORMALwithcheckpoint_fullfsync = ON, a 5 s busy timeout, foreign keys, andSTRICTtables.NORMALsurvives a process crash, and power loss may roll back the last commits but leaves the file intact as long as each checkpoint reaches the disk in order, which macOS guarantees only underF_FULLFSYNC. The schema has three tables:sessions, with the head pointer and metadata;messages, immutable rows keyed by(session_id, id)whose composite foreign key makes "parents first, one session" a database invariant; andusage, one row per billed request.PRAGMA user_versionversions the schema, and a per-sessionformatcolumn versions message content, so listings hide a session a newer build wrote. Each process opens the store once and hands it to the picker,ox --list, andox export. Switching a fresh file to WAL upgrades a read lock to a write lock, which SQLite fails at once without calling the busy handler, soopenholds an exclusive lock onlocks/sessions.db.lockwhile it sets the file up. A store already at this revision opens without taking the write lock. A file whose header or schema SQLite cannot read fails with the recovery steps in order: quit everyox, runsqlite3 .recoverwhile the WAL still sits beside the database, then move the database aside with its-waland-shmfiles. The path in the steps is quoted.BEGIN IMMEDIATEtransaction on a blocking task. A fresh session gets its row with its first message. A failed commit rolls back and stops persistence for the rest of the process's session, with no retry, and later batches fail withsession persistence stopped after an earlier write failed. Each ack carries aWriteReport { failure, fork }, which reports a failure once per session, except to archive, which reports every failure.forked_from, the title, and the manual flag copied, copies the base chain since the last compaction with its message IDs unchanged, and writes the batch there. Usage stays in the source. The handle's live session ID and artifact directory follow the fork, so the next request'sx-claude-code-session-idand the next tool call use it. The engine emitsEvent::SessionForked, which the TUI notes in chat while moving its status bar to the fork, the stdio drivers print to stderr, and the headless result reports assession_id. Listings label a fork(fork of {id8}).locks/{id}.lock, and delete takes a non-blocking exclusive lock, refusing a session another process has open.FileLockgainssharedandtry_exclusive.title_manualflag.--listand picker message column shows0for a session without messages, the delete modal always shows the project, and truncation shortens the title before a fork label.ox export <id-prefix>writes the session record, then every message in commit order, then every usage record.ox -r <file>validates the session ID, theforked_fromsource ID, and the format on line 1 and parent order, names the failing line, and lands by which messages each side holds: it fast-forwards when the local head is among the exported messages, keeps the local copy when that holds the exported head, extends an existing fork that relates the same way, and otherwise creates a fork. Membership holds across compaction and rewind, where an ancestry walk stops at the compaction root. A session the import creates is filed under the importing host's project and working directory. An import that moves the head of a session another process has open makes that process fork at its next write.sessions/tree, which the guide tells users they can delete.scripts/check-leaks.shsearches asqlite3 .dumpof the store, since a byte scan of the database can miss a value split across pages, and the dev shell addssqlite3. The live harness reads sessions throughox export..sqland.jsonl), the testing conventions, and the design docs that referenced session files are updated.Measurements
libsqlite3-sysbuild on an M-series MacBook: dev 8.4 s with 241 MB peak RSS, release 25.6 s with 511 MB peak RSS.aarch64-apple-darwin: 13,547,952 bytes on main, 15,491,280 bytes on this branch, +1,943,328 bytes (+14.3%), with the JSONL code removed.Design notes
find_headreturnsOption<Option<Uuid>>(a missing session differs from one whose branch is empty) and carries#[expect(clippy::option_option)], andSessionStatecarries#[expect(clippy::struct_excessive_bools)]for its independent lifecycle flags.disk full, which exercise the real rollback path./resumepicker's page worker has no cancel flag, since each page is one query, and a stale view's page is discarded when it arrives.session::handlesession_format, next to the resume tests they share fixtures with.persist_noclobber. tempfile publishes with a no-replace rename and falls back to a hard link only onENOSYSorEINVAL, so on macOS exFAT, where the rename returnsENOTSUP(fix(tool): create files on volumes without no-replace renames, such as exFAT #730), the first run would fail. The liveness locks already need file locks inlocks/, so the setup lock adds no filesystem requirement, and its name holds a dot, which no session ID can, so it cannot collide with a liveness lock.Test plan
store::schemaandstore::open_in: two first runs racing throughSessionStore::opencreate one schema, a set-up store opens while another connection holds a write, the first-run race repeated over 100 fresh directories (it fails within the first few races when the setup lock is released beforeschema::open), a store a newer build migrated opens untouched, per-connection pragmas includingcheckpoint_fullfsync, a damaged file's error naming the recovery steps, a table of SQLite codes that onlyNOTADBandCORRUPTcount as damage, and on Unixsessions.db,-wal, and-shmare0600store::load,store::listing,store::export: chain and state reads, the first-prompt title latch table, usage across compactions, newer-format refusal, keyset pages without gaps, scope and archive filters, prefix lookups, an import table over new, behind, empty local branch, ahead, diverged, compacted on either side, and rewound exports, one fork extended across repeated diverged imports, a second fork for an export no existing fork relates to, imported sessions filed under this project, line-named import errors including aforked_fromthat is no session ID, and an import forking an open handlesession::statelazy_fork: the six-scenario table from the design, the copied chain since the last compaction with IDs, title, and manual flag kept, usage left in the source, both locks, a fork from an empty branch, and a stale finish leaving the source's snapshots alonesession::actor: a failed commit surfaces once except to archive, the fork rides on the first head-moving ack, and commands queued behind the first commit in ordersession::handlesession_format: snapshots of the SQL dump and the export of a session holding every row kind, an import of that export reproducing the same rows, and a resume of the dump this build writesSessionForkedonce, and writes later records to the fork, whose ID both of that turn's requests and its tool call carry. A second test moves the head from a second handle during a tool call, so the round's commit forks mid-turn: the forked round's request carries the source ID, while the next round in the same turn, or the auto-compaction summary and the rounds after it, carry the fork's ID, and the next tool call sees the fork's ID and artifact directorysession_id, andcrates/ox/tests/cli.rsrunningox exportinto a file, thenox -r <file>headless in a fresh data dir, plus an archived import unarchiving with a note and a non-export file failing by nameOX_LIVE=1 cargo live): 5 passed, including--resumeand auto-compaction read back throughox exportcargo mutantsoversession::storebefore the review fixes (145 mutants): 73 caught, 27 timed out, 40 unviable, and 5 missed. New tests now fail on thenow_millisand forkcreated_atmutants, and the lock-fileNotFoundcheck moved into anignore_missinghelper with its own test. The timeouts are engineruntests whosenext_matchingwaits for an event a broken store never sends, so they hang until the timeout instead of failingcargo fmt --check,cargo build,cargo clippy --all-targets,cargo clippy, andcargo doc --no-deps: passcargo llvm-cov: 3453 tests pass with 99.19% line coveragecargo deny check: pass, with no new duplicate cratespnpm format,pnpm lint, andpnpm spellcheck: passUncovered changed lines are
?propagation of SQLite and I/O errors,unreachable!arms, the fixture loop that has no fixtures untilv0.1.0, the TUI startup wiring, and the migration's revision recheck underBEGIN IMMEDIATE, which finds the schema already created only when a writer outside the setup lock, such as another SQLite client, set it up first. The TUI fork notice and picker were checked through snapshots, not in a live terminal.