Skip to content

Pack small session bodies into one file per session - #2245

Draft
fazxes wants to merge 4 commits into
mainfrom
fazxes/session-blob-pack
Draft

fazxes wants to merge 4 commits into
mainfrom
fazxes/session-blob-pack

Conversation

@fazxes

@fazxes fazxes commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

A session that holds many small bodies, such as tool results, command outputs, and compaction records, used to write one blob file per body. A long session could hold tens of thousands of files, and each body cost two syncs. Small bodies now go into one pack file per session, blobs.pack. The pack is appended with one sync per batch.

Larger bodies, and bodies that a tool or the model opens by path, stay blob files. The decision is recorded as D102 in tests/tla/session_manager/system-design.md, which amends D44 and D48.

Why

On a synthetic session that matches a long real one (36,000 small bodies and 6,194 bodies of 18 KiB), the pack writes faster, reads at least as fast, and uses less disk:

Blob files Pack
Write, total 13.1 s 4.7 s
Open plus all 36,000 small reads 936 ms and 1,001 ms 873 ms and 800 ms
Files on disk 42,194 6,194 blob files plus one pack
Disk use (du) 273.7 MB 168.4 MB (124.7 MB of blobs, 43.7 MB of pack)

Two runs per variant. The pack's open cost is its index build, 69 to 84 ms for 36,000 records, paid once per session on the first lock-free read. The index is estimated at about 3 MB for that many records; it was not measured.

Copying a 160 MB pack for a fork took 94 to 109 ms in the sandbox with a warm cache.

Safety rules

  • One sync per batch. A pack record is appended now. The pack is synced before any log line that names one of its records, so a durable line never names a body that a crash can lose.
  • Names come from structure. The log check reads each line's parsed blobs list through the log's chunked reader. Free text, such as a 64-character hex string in a prompt, is never a name.
  • Torn tails are cut. On a writable open, the walk stops at the first record it cannot read whole: a bad header, a length past EOF, a zeroed tail, or a last record whose CRC fails.
  • Named records are never cut. At that stop the log decides. If a durable line names a body that the good prefix lacks, and that body is not a blob file, the open is refused read-only and nothing is cut. The refusal is reported as pack_refused, with the record's offset. A cut is reported as pack_cut, with the bytes cut.
  • A damaged body in the middle is reported, not cut. A body whose CRC fails, with a sane header, is reported by verify. Later bodies still read.
  • Stale caches cannot report false damage. A lock-free reader keeps one index per session. A miss on a cached index rebuilds it at most once per pack length, then reports.
  • Forks copy the pack. A fork copies the pack with a byte copy, never a hard link, so an append on either side never reaches the other. A fork's search checks every reference through one index, so the pack is walked once per search.

Builds without packs

The wasm core (fx-core.wasm) builds the session manager without the pack. One switch decides it: pack.enabled, set from the session_packs build option, which build.zig sets to false for wasm targets. In a build without packs, a small body is a blob file, and no code reads or writes a pack.

The reason is that the wasm core has no session folder. Its ACP server does not open the native session store on wasm (src/acp/server.zig, the store is opened only when !host_target.is_wasm), and its sessions go through the JS host's store (js_host_session_store). Its WASI shim has no preopened folder (sdk/wasm-runtime.js: fd_prestat_get returns 8, and path_open and fd_pread are unavailable). So the pack is unreachable there at runtime.

The compile check confirms the compiler drops the pack's code. A temporary @compileError at the file-storage entry points (openRoot, createFile, openFile) fails the wasm build, which shows that the storage code is in the wasm graph. The same probe at the pack's entry points (walk, readBody, appendRecord, copyInto) does not fail, which shows that the pack code is not. Both edits were reverted.

Measured with zig build fx-core-wasm -Dwasm-surface=core -Doptimize=ReleaseSmall, then node sdk/scripts/optimize-wasm.mjs:

Build Raw Optimized
origin/main 2,888,459 2,461,219
This branch, with the switch 2,889,851 2,462,463
Budget (sdk/tests/package-size-budgets.json) 2,465,000

The optimized file is 1,244 bytes above origin/main and 2,537 bytes under the budget. The budget is not raised in this change.

A test, a non-pack build writes files: a small body is a blob file, and no pack is made, runs in its own test binary built with the switch off. The test-session-manager step runs that binary. In the packed build, the test skips.

Older-reader behavior

Once a session has a pack, every line it writes is at format version 2, snapshots included. A reader built before this change stops at the first version 2 line and opens the session read-only. It never rewrites the session.

New session folders that hold a pack also write version 2: forks, recover forks, child copies, and resumed sessions. A fork or copy's first line is version 2, and from the first line that names a packed body on, every line is version 2. History copied from the source before its pack keeps the version it was written at. The tests are a fork of a pack session writes version 2 on every later line, snapshots included, a recover fork of a pack session writes version 2 on every later line, a child copy of a pack child writes version 2 on every later line, and a resumed session whose folder holds a pack writes version 2 on every later line.

Checked by hand against origin/main built from git archive. The session was written by this branch's build, with one packed tool result, 18 lines of which 9 are version 2. The main build resumed it with ask --json --auto --resume <id>:

  • exit code 1, "error":"UnsupportedSessionFormat";
  • the log stayed at 5,135 bytes before and after, so it appended nothing.

The unit test an older reader stops at the first line naming a packed body, and leaves the session unwritten covers the same rule.

Refusals and where the cause shows

A named damaged record refuses a writable resume. The user sees the existing protocol code InvalidSessionFormat, and the cause is not in the error text.

  • Diagnostic. The session manager reports the refusal as pack_refused, with the record's byte offset. The adapter forwards it to the debug trace as event=sessions_v2_diagnostic kind=pack_refused session=<id> offset=<n> in the session scope. The trace is written only when debug tracing is on, so a user does not see it by default.
  • Next step. The text fx session recover <id> is not printed anywhere yet. It is the step this message should name.
  • Follow-up. A clearer message, which names the cause and the next step in the error itself, needs a new public error code. A new code is a control under the fx CLI shape rules, so it needs the maintainer's approval and is not in this change.

Tests

  • Store, unit tests (session.zig, pack.zig): packed and file bodies at the 4 KiB boundary; read-back by name; the version 2 rule for every line after the first pack, snapshots included; the crash before a line; a torn tail, cut and reported; an unnamed damaged last record, cut; a named damaged last record, read-only and reported; a body flip in the middle, later bodies still read and nothing cut; a header flip in the middle, read-only; a fork copy, with an append on either side never reaching the other; a fork search that walks the pack once; a hex string in a line's text is not a name; a rebuild on a strict miss, at most once per pack length; a non-pack build writes files.
  • Fuzz target: session_pack_records, with three saved inputs.
  • Adapter: tool results and command outputs are packed. A small body has no blob file, and a damaged pack byte is counted by verify. A tool result over 4 KiB stays a blob file.
  • Command replays: a replay is written as a blob file, not a packed record, because its reader opens it by path. The testing store keeps small bodies in memory only, so a test that opens a packed body by path fails. The replay unit test failed before the fix and passes after it.
  • E2E (sessions.test.ts): a tool result is packed, and a restarted fx reads it back. A short command output is paged by the model after a restart. This is a plain restart check: the shell's capture spools, so it does not reach the inline path, and the unit test above is the guard for that rule. A half-written record is cut on resume, and the packed body still reads. A moved side folder keeps its copy as a blob file, and the moved map is packed. A reader process runs fx session while a writer is held in a turn.
  • E2E (file-tool-paths.test.ts): a corrupted stored tool image degrades to an explicit notice on resume. The damage is in the image's packed record, with a later packed result after it, so the record is mid-pack and the session stays writable.
  • E2E (compaction-policy, gateway-stream-lifecycle): the compaction helper reads a record from its file or from the pack.
  • Fuzzing in CI: the target's tests live in pack.zig, which the session-manager test root now imports. See the next section for the failure this fixed.

Fuzzing

The fuzz target session_pack_records never ran in CI. Its tests lived in pack.zig, which the session-manager test root did not import, so the fuzz build found no test and failed with build-error. api.zig now imports pack.zig in its test block. The target builds, runs its replay, and the nightly driver passes locally (python3 -m scripts.fuzz_nightly run --target session_pack_records --budget-seconds 30: build ok, round 1 ok). The driver's unit tests pass: python3 -m unittest scripts.tests.test_fuzz_nightly, 21 tests, OK.

Thread Sanitizer

zig build test-session-manager -Dsanitize-thread=true, with TSAN_OPTIONS=halt_on_error=0:abort_on_error=0, run in the sandbox. Two test binaries are linked with ThreadSanitizer, and the run reports zero WARNING: ThreadSanitizer lines. The run's summary is the same as the normal run: 320 of 334 pass, and the same eight baseline failures. That run was before the wasm switch.

Model

tests/tla/session_store/SmallBlobs.tla models the pack's ordering and crash rules. design-pack.cfg checks the design: no line names an unsynced record (Dangling is never violated). mutant-early-ref.cfg plants a line that names a record before its sync, and the check requires that Dangling is violated. check.sh runs both, and the README has its row.

The model does not cover forks, the index, the damage rules, or the wasm switch. The unit tests cover those.

Checks run

On the branch after the wasm switch:

  • zig build test-session-manager --summary all: 329 pass, 8 skip, 8 fail. The eight failures are the baseline (api D29, D39 and D49; storage read-only; in both build modes). The skips include the pack-only test in the packed binaries.
  • sessions.test.ts, file-tool-paths.test.ts and compaction-policy.test.ts: 157 pass, 32 skip (tmux), 0 fail.
  • zig build fuzz -Dfuzz-target=session_pack_records: exit 0.
  • zig fmt --check src/ build.zig: exit 0. scripts/check-public-surface.sh: exit 0.
  • fx-core.wasm optimized: 2,462,463 bytes, under the 2,465,000 budget.

The full zig build test last ran before the wasm switch: 12,888 pass, 33 skip, and the eight baseline failures in both build modes. It was not rerun after the switch. The SDK package-size test (sdk/tests/test-package-size.mjs) was not run: it reads a packed libfx tarball with a native addon for every platform, which this sandbox cannot build. Its wasm figure is the one measured above, from the same optimize step.

Known limits

  • No collector. This change never removes a pack record, so a pack grows with its session. Removing records belongs to a later change, such as prune.
  • Forks copy, they do not link. A 160 MB pack costs about 0.1 s to copy and 160 MB of disk. clonefile is a follow-up.
  • Name check is conservative. The log check treats a blobs entry as a name. A damaged record that a line names refuses a writable open; it never loses data.
  • An unnamed damaged last record is cut. No durable line names it, so nothing a line needs is lost.
  • Moved side files from disk stay blob files. The move copies them from disk, so no pack copy exists yet. Moved bodies held in memory, and their map, are packed.
  • The refusal error is a generic code. A named damaged record refuses a writable resume with InvalidSessionFormat. The cause shows only in the debug-trace diagnostic, and the recovery step is not printed. A clearer message needs a new public error code, which is a follow-up with the maintainer.
  • Concurrency tests use a held turn. The two-process E2E holds a turn at the gateway. It does not kill a process in the middle of an append. The crash-in-flight case is covered by a unit test.
  • New writes only. Existing sessions keep their blob files; nothing repacks them.
  • Shared model folder. Add fx session prune to shrink old session logs #2230 also adds tests/tla/session_store/. Whichever of the two merges second lists both models in one check.sh and one README row.

Docs

No fx.sh page describes the session folder layout or blob files, so the manual needs no change.

A session wrote one blob file per tool result, command output, and
compaction record, so a long session held tens of thousands of small files,
and each body cost two syncs. A body of at most 4 KiB that fx reads back
through the session now goes into `blobs.pack`, one append-only file per
session, synced once per batch before any line that names it. Larger
bodies, and bodies a tool or the model opens by path, stay blob files.

A line that names a packed body is written at format version 2, so an
older fx opens such a session read-only. A writable open cuts only a torn
tail that no durable line names; damage in the middle leaves the pack as it
is and is reported. Forks copy the pack. D102 records the rules and amends
D44 and D48, and `tests/tla/session_store/SmallBlobs.tla` checks that no
line names an unsynced record.
@fazxes fazxes added the type: feature Adds a new user-facing capability label Nov 23, 2026
Once a session has a pack, every line it writes is format version 2,
snapshots included, so an older fx that checks only the newest lines opens
the session read-only and appends nothing.

A writable open cuts a damaged pack tail only when no durable line names a
body there, and it takes names only from the lines' parsed blob lists, read
in chunks, so a 64-character hex string in a prompt no longer blocks a
resume. The cut and a refusal are reported as diagnostics.

Forks check every reference against one pack index instead of walking the
pack per reference. Command replays stay blob files, since their readers
open them by path, and the testing store keeps small bodies out of the
path API so that rule is tested. pack.zig's own tests and fuzz target now
compile. The wasm core, which has no session folder, builds without packs.
A fork, a recover fork, and a child copy now decide from the source folder that the session has a pack before they write their first line, and a resume decides it from its own folder. So every line those sessions write is version 2, and an older fx opens them read-only.
The two subagent commit-failure tests broke the blobs folder to fail the child's commit. Small results now go to the session's pack, so the commit succeeded and the fault never fired. Each fault now also blocks the pack's creation, and the child's earlier output is over the pack limit, so the failing commit is the first packed write.
@fazxes fazxes closed this Nov 24, 2026
@fazxes fazxes reopened this Nov 24, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: feature Adds a new user-facing capability

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant