Skip to content

refactor(client): take the session ID per request - #719

Merged
hakula139 merged 2 commits into
mainfrom
refactor/client-session-id-per-request
Oct 28, 2026
Merged

hakula139 merged 2 commits into
mainfrom
refactor/client-session-id-per-request

Conversation

@hakula139

@hakula139 hakula139 commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Summary

The Anthropic client kept its own copy of the live session ID for the x-claude-code-session-id header and metadata.user_id. Engine::new passed it in, and adopt_session copied the handle's ID back after /clear and /resume, so every place that changes the live session also had to resync the client or send later requests under the old ID. Tool dispatch kept a second copy of the ID and the artifact directory for each turn. The coming SQLite store forks a session lazily mid-turn, which would add more places to keep in sync. Each request and each tool call now reads the session from the live handle, so the handle is the only owner of the live ID, and requests carry the same header and metadata as before.

  • Client: Wire::stream_message, Wire::stream_one_shot, and Client::complete take the session ID as their first argument, and RequestSpec carries it into the body's metadata.user_id and the request's x-claude-code-session-id header. Client drops its session_id field, set_session_id, and the constructor's session_id parameter, along with the UUID fallback no caller used.
  • Side queries: complete's model, prompt, and output settings move into a SideQuery struct, since the extra argument would have put the method over Clippy's too_many_arguments limit.
  • Callers: turns pass the live transcript's session ID, title generation passes the ID of the session it titles, and request_summary takes the parent LiveTranscript, so a compaction summary and its overflow retries read the session ID, prompt, and messages from the conversation they fork. adopt_session no longer touches the client.
  • Tool dispatch: DispatchContext holds a clone of the live session handle in place of a copied ID and artifact directory, and each tool call reads both from it when it starts, so OX_SESSION_ID and spill files follow the handle.
  • Docs: docs/design/resume.md describes how the resumed session's ID reaches the next request and tool call, in place of the removed rebind.

This is PR 3 of the session storage redesign, following #714, and it touches only the client, engine request, and dispatch paths.

Test plan

  • New engine::sessions tests clear_sends_later_requests_as_the_new_session and resume_sends_later_requests_as_the_resumed_session: a turn before and a turn after the switch send x-claude-code-session-id with the old ID and then the new one, as the mock server records them
  • New engine test submit_prompt::runs_every_round_and_turn_in_the_live_session: a tool records the session ID and artifact directory of each call across two tool rounds, then after /clear a third call, and sees the live handle's values each time. A handle's ID cannot change mid-turn until the lazy fork lands, so this covers rounds and turns but not a mid-turn switch
  • client::anthropic stream_message::attributes_the_request_to_the_caller_session checks the header and metadata.user_id for the ID the caller passed, and completion complete::sends_the_caller_session_id_header checks the header for side queries
  • client wire::stream_one_shot::defaults_to_the_same_request_through_stream_message checks that the default stream_one_shot forwards the session ID, messages, system prompt, user context, and tools unchanged
  • request_summary::request_forks_the_conversation_prefix checks that the summary sends the parent's session header and metadata, and retries_an_overflow_without_the_oldest_rounds_or_thinking checks the header on the stream_one_shot retry
  • The title generator's spawn success test matches the title request on the titled session's header, and session::state fresh::names_the_session_with_a_uuid_v4 pins the fresh ID's UUID version, which mirrors Claude Code
  • cargo fmt --check, cargo build, cargo clippy --all-targets, cargo clippy, and cargo doc --no-deps pass
  • cargo llvm-cov: 3545 tests pass with 99.16% line coverage
  • pnpm format, pnpm lint, and pnpm spellcheck pass
  • Live tests not run. The header and metadata now come from the caller's handle, but their wire format is unchanged

@hakula139 hakula139 added refactor Behavior-preserving restructuring area: client Touches the model API client, authentication, or request wire area: session Touches session storage, listing, or resume area: engine Touches the engine, its protocol, or the drivers that run it labels Oct 28, 2026
@hakula139 hakula139 self-assigned this Oct 28, 2026
@codecov

codecov Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@hakula139
hakula139 force-pushed the refactor/client-session-id-per-request branch from 89ab899 to 74c57ff Compare October 28, 2026 07:39
The client kept its own copy of the live session ID, set at construction
and resynced by `adopt_session` after `/clear` and `/resume`. A later
lazy fork would need a third sync point, and a missed one sends requests
under a stale ID.

`Wire::stream_message`, `stream_one_shot`, and `Client::complete` now take
the session ID from their caller, which reads it from the session handle.
Turns and compaction pass the live transcript's handle, and title
generation passes the handle of the session it titles. The client loses
its `session_id` field, `set_session_id`, and the constructor parameter.
`request_summary` takes the parent `LiveTranscript`, so the summary
shares the conversation's session ID, prompt, and messages from one
source, and `complete`'s request settings move into `SideQuery` to stay
under Clippy's argument limit.
The dispatch context copied the session ID and artifact directory once
per turn, so tools kept their own copy beside the handle. It now holds
a handle clone, and each call reads both values from it when it starts.

Also covers the default `Wire::stream_one_shot` forwarding, splits the
clear and resume request tests, narrows `SESSION_ID`, and pins that a
fresh session's ID is a UUID v4.
@hakula139
hakula139 force-pushed the refactor/client-session-id-per-request branch from 74c57ff to d0531b3 Compare October 28, 2026 08:08
@hakula139
hakula139 merged commit 3479f2d into main Oct 28, 2026
9 checks passed
@hakula139
hakula139 deleted the refactor/client-session-id-per-request branch October 28, 2026 08:19
@hakula139 hakula139 mentioned this pull request Oct 28, 2026
13 tasks done
hakula139 added a commit that referenced this pull request Oct 28, 2026
## Summary

Sessions lived in one JSON lines file per session, which the loader
replayed and repaired on every resume, and two `ox` processes 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 that `ox export` writes and `ox -r
<file>` imports. This is PR 4 of the session storage redesign, following
#714 and #719.

- **Store:** rusqlite with bundled SQLite, so every platform gets the
fix for the WAL-reset corruption bug that concurrent writers in separate
processes can hit
([3.51.3](https://www.sqlite.org/releaselog/3_51_3.html)). WAL mode,
`synchronous = NORMAL` with `checkpoint_fullfsync = ON`, a 5 s busy
timeout, foreign keys, and `STRICT` tables. `NORMAL` survives 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 under `F_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; and `usage`, one row
per billed request. `PRAGMA user_version` versions the schema, and a
per-session `format` column 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`, and `ox 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, so `open` holds an exclusive lock on
`locks/sessions.db.lock` while 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 every `ox`, run `sqlite3 .recover` while the WAL still sits beside
the database, then move the database aside with its `-wal` and `-shm`
files. The path in the steps is quoted.
- **Writes:** the actor commits each batch in one `BEGIN IMMEDIATE`
transaction 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
with `session persistence stopped after an earlier write failed`. Each
ack carries a `WriteReport { failure, fork }`, which reports a failure
once per session, except to archive, which reports every failure.
- **Lazy fork:** a commit that moves the head compares the stored head
with the one this process last committed or loaded. A different head
means another process wrote since, so the commit inserts a fork with
`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's
`x-claude-code-session-id` and the next tool call use it. The engine
emits `Event::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 as `session_id`. Listings label a fork `(fork of
{id8})`.
- **Liveness locks:** an open session holds a shared lock on
`locks/{id}.lock`, and delete takes a non-blocking exclusive lock,
refusing a session another process has open. `FileLock` gains `shared`
and `try_exclusive`.
- **Resume:** the loader walks the chain from the head with a recursive
CTE to the nearest root, the session start or the last compaction, so
compaction, rewind, and refused-turn rollback are head moves with no
loader rules. The first-prompt title latch derives from the chain and a
stored `title_manual` flag.
- **Listing:** keyset-paged queries ordered by last activity, so the
picker's pages never overlap. Prefix lookups use the primary key and
match nothing for a GLOB metacharacter. The `--list` and picker message
column shows `0` for a session without messages, the delete modal always
shows the project, and truncation shortens the title before a fork
label.
- **Export and import:** `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, the `forked_from` source 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.
- **Removed:** the JSONL entry types, chain builder, and path layout,
with their prerelease shims. The store starts empty and does not read
the old `sessions/` tree, which the guide tells users they can delete.
- **Tooling:** `scripts/check-leaks.sh` searches a `sqlite3 .dump` of
the store, since a byte scan of the database can miss a value split
across pages, and the dev shell adds `sqlite3`. The live harness reads
sessions through `ox export`.
- **Docs:** the persistence design is rewritten, and the sessions and
headless guides, README, SECURITY, RELEASING (the stability surface and
the two release fixtures, `.sql` and `.jsonl`), the testing conventions,
and the design docs that referenced session files are updated.

### Measurements

- `libsqlite3-sys` build on an M-series MacBook: dev 8.4 s with 241 MB
peak RSS, release 25.6 s with 511 MB peak RSS.
- Release binary on `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_head` returns `Option<Option<Uuid>>` (a missing session differs
from one whose branch is empty) and carries
`#[expect(clippy::option_option)]`, and `SessionState` carries
`#[expect(clippy::struct_excessive_bools)]` for its independent
lifecycle flags.
- Fault injection uses triggers that raise `disk full`, which exercise
the real rollback path.
- The `/resume` picker's page worker has no cancel flag, since each page
is one query, and a stale view's page is discarded when it arrives.
- The session-format snapshot and round-trip tests live in
`session::handle` `session_format`, next to the resume tests they share
fixtures with.
- First-run setup serializes on a lock file instead of building the
store in a temp file and publishing it with `persist_noclobber`.
tempfile publishes with a no-replace rename and falls back to a hard
link only on `ENOSYS` or `EINVAL`, so on macOS exFAT, where the rename
returns `ENOTSUP` (#730), the first run would fail. The liveness locks
already need file locks in `locks/`, 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

- [x] `store::schema` and `store::open_in`: two first runs racing
through `SessionStore::open` create 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 before `schema::open`), a store a newer build
migrated opens untouched, per-connection pragmas including
`checkpoint_fullfsync`, a damaged file's error naming the recovery
steps, a table of SQLite codes that only `NOTADB` and `CORRUPT` count as
damage, and on Unix `sessions.db`, `-wal`, and `-shm` are `0600`
- [x] `store::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 a `forked_from` that is no
session ID, and an import forking an open handle
- [x] `session::state` `lazy_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 alone
- [x] `session::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 order
- [x] `session::handle` `session_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 writes
- [x] Engine: two engines on one store, where another engine's prompt
makes the stale one fork when it records its next prompt, emits
`SessionForked` once, 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 directory
- [x] Frontends: the TUI fork notice snapshot with the status bar's new
ID, the picker's fork label, the stdio fork notice ordering, the
headless result's `session_id`, and `crates/ox/tests/cli.rs` running `ox
export` into a file, then `ox -r <file>` headless in a fresh data dir,
plus an archived import unarchiving with a note and a non-export file
failing by name
- [x] Live tests through an Anthropic-compatible gateway (`OX_LIVE=1
cargo live`): 5 passed, including `--resume` and auto-compaction read
back through `ox export`
- [x] `cargo mutants` over `session::store` before the review fixes (145
mutants): 73 caught, 27 timed out, 40 unviable, and 5 missed. New tests
now fail on the `now_millis` and fork `created_at` mutants, and the
lock-file `NotFound` check moved into an `ignore_missing` helper with
its own test. The timeouts are engine `run` tests whose `next_matching`
waits for an event a broken store never sends, so they hang until the
timeout instead of failing
- [x] `cargo fmt --check`, `cargo build`, `cargo clippy --all-targets`,
`cargo clippy`, and `cargo doc --no-deps`: pass
- [x] `cargo llvm-cov`: 3453 tests pass with 99.19% line coverage
- [x] `cargo deny check`: pass, with no new duplicate crates
- [x] `pnpm format`, `pnpm lint`, and `pnpm spellcheck`: pass

Uncovered changed lines are `?` propagation of SQLite and I/O errors,
`unreachable!` arms, the fixture loop that has no fixtures until
`v0.1.0`, the TUI startup wiring, and the migration's revision recheck
under `BEGIN 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: client Touches the model API client, authentication, or request wire area: engine Touches the engine, its protocol, or the drivers that run it area: session Touches session storage, listing, or resume refactor Behavior-preserving restructuring

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant