Skip to content

perf(agent): cache a run's folded snapshot beside its journal - #1486

Merged
huichen merged 5 commits into
mainfrom
pr/huichen
Nov 3, 2026
Merged

huichen merged 5 commits into
mainfrom
pr/huichen

Conversation

@huichen

@huichen huichen commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

A reconnecting client used to re-fold a run's whole journal to be shown where the run stands. This keeps the fold in a versioned row beside the raw journal, so the answer is one row instead of a fold, while the journal itself stays reclaimable — a cached projection must never stop an operator from compacting a journal.

Commits

  • perf(agent): keep a run's folded snapshot beside its journal
  • test(agent): record the unreproduced journal-compaction flake and where to look
  • fix(agent): drop the redundant Ok and ? around the run-epoch read
  • test(agent): assert the reopen layout the startup really guarantees

Verification

Run on a worktree at edefe5ac2 with the pinned toolchain (rust-toolchain.toml: rustc 1.99.1, not the Homebrew 1.96.0 that shadows it) and ulimit -n 8192:

  • cargo fmt --all -- --check — clean
  • cargo clippy -p future-agent --all-targets -- -D warnings — clean
  • cargo test -p future-agent --lib — 2962 passed / 0 failed / 5 ignored (207.8s)
  • make check-docs — 394 docs OK, 0 pairs pending, provider matrix 13 rows

The reopen-layout assertion was falsified in both directions before it was kept: injecting PRAGMA incremental_vacuum into the open path turns the page_count assertion red, and injecting a freelist-claiming startup step turns the freelist assertion red.

Notes

  • agent/src/session/database/schema.sql gains run_snapshot_cache (CREATE TABLE IF NOT EXISTS), keyed by session, run and epoch and stamped with SNAPSHOT_CACHE_VERSION: any mismatch is a cache miss that falls back to folding the journal, never a stale projection.
  • opening_bloated_incremental_database_does_not_rewrite_it changed shape. Startup already writes even when nothing needs migrating: it re-creates the derived views so a code change to them takes effect, and each DROP VIEW IF EXISTS / CREATE VIEW pair re-inserts that view's sqlite_schema row, which can fragment the schema btree by one leaf and allocate it from the freelist. Whether that leaf is needed is decided by the total schema size, and the new table is what pushed it over the boundary — so the old exact freelist equality was describing the schema's size, not the startup's behaviour. The case now asserts page_count exactly, at most one pushed page (REOPEN_SCHEMA_PAGES), and that a second reopen lands exactly where the first left off (a page per start would be unbounded growth). The reasoning and the measured numbers are in the constant's doc comment.
  • docs/.../streaming-sync-snapshot-optimization*.md (English and zh-CN) record the design for the snapshot cache.

Opening a conversation whose run has a long journal folds the whole run to
answer the first replay page: 4.1 s for 136k events, every time, because the
fold was never kept. The reclaim path can write one (run_snapshots), but that row
means 'this run is compacted' — read_compaction_source short-circuits on it and
the operator's reclaim would then skip a journal it should retire. So the cache
lives in its own table, run_snapshot_cache, keyed (session_id,run_id) and
versioned by (SNAPSHOT_CACHE_VERSION, epoch):

  - a different version (fold algorithm changed) is a miss;
  - a different epoch (the run restarted or forked) is a miss;
  - an unreadable or invalid row is a miss, never an error.

The write is 3.5 ms for the 1.82 MB row and runs on spawn_blocking after the
reply is built, so the first open still pays its fold and the next one does not:
4094.7 ms cold, then 206-217 ms on the same run and home (debug build).

Measured on an isolated home holding the four sampled sessions (997k events).
…re to look

One run reported 29 passed / 1 failed without the failing test's name being
captured; 30 runs since (20 parallel, 10 with --test-threads=1) are green, so the
row records the observation and the three timing-dependent tests to read first
instead of claiming a cause. Notes why the snapshot cache is not a suspect: its
only off-thread write is broadcaster::replay::run_snapshot, which this suite
never calls.
`SqliteStore::run_epoch` wrapped `self.db.read(..)` in `Ok(..?)`, which clippy
rejects (`-D warnings`) as an enclosing `Ok` and `?` that are unneeded: `read`
already returns `Result<T>`. Return the call directly, as `cached_run_snapshot`
does one method below.
`opening_bloated_incremental_database_does_not_rewrite_it` compared the
freelist of a reopened bloated database with exact equality, and the branch
that added `run_snapshot_cache` broke it: 20499 free pages after the reopen
against 20500 before, with `page_count` unchanged at 20642.

The page is not a rewrite. A startup writes even with nothing to migrate:
`initialize_schema` re-creates the derived views, and each `DROP VIEW IF
EXISTS` + `CREATE VIEW` re-inserts that view's `sqlite_schema` row where the
cell fits instead of into the hole it just left. The btree therefore comes out
fragmented — 12 pages as the file is created, 13 after the first reopen — and
that extra leaf is taken from the freelist (`dbstat` names it: page 20483 joins
`sqlite_schema`). Whether it still fits is decided by the schema's total size,
which is why one more table tipped it: with `run_snapshot_cache` removed from
`schema.sql`, the same reopen leaves the freelist exactly as it found it.
So the equality was pinning the schema's size, not the behaviour the test is
named for.

What the test protects is that opening does not rewrite the file, and that is
still asserted exactly: `page_count` must not move (a `VACUUM` or an
auto-vacuum pass collapses it to the ~116 schema pages and empties the
freelist), the freelist may only move by the one schema leaf the bootstrap
needs, and a second open must land on exactly the layout the first one left —
a page per start would be unbounded growth. Falsified both ways: injecting
`PRAGMA incremental_vacuum` into the open path fails the `page_count`
assertion, and a startup that claims 10 MB of the freelist fails this one
(20500 before, 17935 after), while today's code passes.
@huichen
huichen enabled auto-merge (squash) November 3, 2026 16:43
@huichen
huichen merged commit 0bfa70f into main Nov 3, 2026
47 of 50 checks passed
@huichen
huichen deleted the pr/huichen branch November 3, 2026 17:38
huichen added a commit that referenced this pull request Nov 13, 2026
`run_epoch` asked only `run_events`, but a converted conversation keeps its
journal in the canonical stream tables and writes no `run_events` row at all.
It therefore answered `None` for every run created since the conversion, and
`uncaptured_run_snapshot` — whose cache block is gated on `if let Some(epoch)`
— never consulted the fold cache added in #1486. Every open of a run no longer
in the agent's memory paid the whole fold again: the cost that cache was
measured to remove (4.1 s -> 0.2 s on a 136k-event run).

The epoch now comes from whichever store holds the run: the canonical stream
tables first (newest epoch; a retired stream is not a source), then the legacy
table, which is the shape `run_replay_watermark` already used for the same
question. The cache identity is unchanged — version, epoch and the stored
fold's own validation still decide a hit, so a restart or fork that bumps the
epoch is still a miss.

Test: a canonical run reports its epoch and hits its cached fold, and a newer
epoch on the same run invalidates it. Falsified against the previous
`run_epoch`, which returned `None` on the same fixture.
huichen added a commit that referenced this pull request Nov 13, 2026
…anonical run fold cache (#1602)

* fix(desktop): the files panel's button no longer lands on a right-docked terminal

Reported on the docked-right screenshot: the collapsed files panel's button (top
right of the conversation) was drawn over the terminal's own header, next to its
close control.

That button — and the panel's drawer — are absolutely positioned, and their
containing block was the shell root, i.e. the window. That was the same thing as
"the conversation's right edge" only while nothing else sat to the right of the
content column.

The right-docked terminal is now a sibling of that column instead of a child of
it, and the column itself is `relative`. The two affordances therefore resolve
against the column (conversation + files panel) and stop at the terminal's left
edge; the drawer stops there too, so it no longer covers the terminal either.

Measured at 1440×900: the column is 1020..1440 and the button 972..1004, so it
sits inside the conversation as intended (it used to be at ~1232..1264, on the
terminal's header). The `terminal-right` scenario now asserts that gap, so a
return of the overlap fails the capture instead of needing a pair of eyes.

* fix(agent): keep the fold cache reachable for canonical runs

`run_epoch` asked only `run_events`, but a converted conversation keeps its
journal in the canonical stream tables and writes no `run_events` row at all.
It therefore answered `None` for every run created since the conversion, and
`uncaptured_run_snapshot` — whose cache block is gated on `if let Some(epoch)`
— never consulted the fold cache added in #1486. Every open of a run no longer
in the agent's memory paid the whole fold again: the cost that cache was
measured to remove (4.1 s -> 0.2 s on a 136k-event run).

The epoch now comes from whichever store holds the run: the canonical stream
tables first (newest epoch; a retired stream is not a source), then the legacy
table, which is the shape `run_replay_watermark` already used for the same
question. The cache identity is unchanged — version, epoch and the stored
fold's own validation still decide a hit, so a restart or fork that bumps the
epoch is still a miss.

Test: a canonical run reports its epoch and hits its cached fold, and a newer
epoch on the same run invalidates it. Falsified against the previous
`run_epoch`, which returned `None` on the same fixture.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant