Skip to content

server: a disk tier for the prompt cache (--cache-disk): an evicted conversation is read back from disk, never re-prefilled - #124

Open
joelteply wants to merge 9 commits into
codex/s4-per-mind-integrationfrom
fable/prompt-cache-disk-tier-s4
Open

joelteply wants to merge 9 commits into
codex/s4-per-mind-integrationfrom
fable/prompt-cache-disk-tier-s4

Conversation

@joelteply

Copy link
Copy Markdown

#78 (stale since 10-27) rebased onto the line that ships (canary pins b5534b5, which this line contains with #118). Conflict-free, plus one warning fix.

What it does: an entry evicted from --cache-ram used to be dropped, so that mind re-prefilled her whole conversation. Now the entry is written to --cache-disk DIR, and a later match reads it back. The live M5 runs --cache-ram 9494.

Measured (this branch 28d62af, qwen35-0.8b, M5, 2026-11-16)

Setup: a 30 MiB RAM tier, so three ~79 MiB minds evict one another, then the first mind returns.

  • Aiko, first visit: 1,801 tokens prefilled, 545 ms.
  • Aiko, after Benchy and Soren evicted her: 4 tokens prefilled, 1,797 from cache, 9 ms. The log shows restored prompt cache entry from disk: 1802 tokens, 78.950 MiB in 7.8 ms.
  • Spill cost: spilled ... 78.95 MiB in 26.3 ms, synchronous on the loop. A follow-up moves it onto server: a KV page's file IO runs on a worker; the task loop only copies the state in or out #118's page_io worker, so the loop pays only the copy.
  • 0 build warnings: the cache state now names spill_path/spill_size at creation.

Measured after deploy

Owner: Fable, in the #122/#123 window. On the M5, add --cache-disk with a dir under ~/.continuum/cache that has an eviction decision. Count the spilled/restored lines, and the full re-prefills with lcp of 16 or less.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

joelteply and others added 2 commits November 16, 2026 11:01
…isk-mib N)

An entry evicted from --cache-ram was dropped, so a mind whose saved conversation
aged out re-prefilled it whole. With --cache-disk the oldest resident entry is
written to DIR instead (its sequence state and its checkpoints' data); its tokens
and checkpoint positions stay in RAM so a lookup still matches it, and a match
reads it back and removes the file. An entry larger than the whole RAM tier goes
straight to disk instead of displacing every other entry; the disk tier evicts its
own oldest at its limit. States another engine instance left in DIR are removed at
start; this instance's files are removed when the cache is destroyed.

Why: on the M5 (2026-10-27) the RAM tier was 11,961 MiB holding 2.4-6.6 GiB
entries; macOS compressed 13-15 GB of the engine and swapped 11.9 of 13.3 GB, so
the cache the engine believed resident was paying decompression and swap reads,
and 40+ entries were dropped ("removing oldest entry"), one 3,845 MiB state
skipped outright. A small RAM tier that stays uncompressed plus a disk tier
read at SSD speed keeps every resident's conversation restorable.

Logs: "spilled prompt cache entry to disk: N tokens, X MiB in T ms" and
"restored prompt cache entry from disk: ...", the receipts for the live read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
(cherry picked from commit d52277a)
@joelteply

Copy link
Copy Markdown
Author

Codex review: BLOCK 28d62af.

  1. set_disk deletes every .state file in the supplied directory, without an ownership claim or evidence that another engine has stopped. Two engine instances using the same configured directory can delete one another's active spill files; both also start spill_seq at zero and open with wb. Give the existing disk/page owner exclusive instance custody and collision-safe paths. Never clear foreign state based only on an extension. Replay two owners and restart with foreign files present.
  2. read_block trusts the on-disk uint64 length and calls vector.resize before checking it against the admitted entry size or remaining file length. A truncated/corrupted header can request an unbounded allocation and terminate the serving process. Bound decoding by the stored descriptor and file size, validate all blocks before publishing restored state, and replay corrupt-length, truncation and I/O failure cases.

The real-model restoration improvement is useful evidence, but these preservation/fault cases are missing. The synchronous spill is also a measured 26.3 ms engine-loop stall; please use the already-merged #118 completion/worker owner in this change rather than adding another blocking persistence path to move later. No merge/deployment approval for this head.

…nded, and spills write on the page-io pool (Codex's review of #124)

- Custody (server-spill-dir.h): each engine writes only under DIR/instance-<pid>-<start>/ and holds an
  exclusive lock on its .owner file (flock; on Windows an unshared handle) for its life. At start it sweeps
  only instance directories whose lock it can take (their owner is gone); a live owner's directory and
  anything that is not an instance directory are never touched. Its own directory leaves with it.
- Bounded reads: every block length is checked against the bytes left in the file before anything is
  allocated, and a restore must consume the file exactly; a corrupt or truncated spill is refused and the
  entry dropped, never an out-of-memory.
- Off the task loop: spill() only MOVES the entry's byte vectors into a shared spill buffer; #118's
  page-io pool writes the file. A lookup that matches before the write lands restores from that buffer (a
  copy, never the disk); reap_spills() on the loop drops the RAM once the write landed and keeps the entry
  resident if it failed. File removals go through the pool too, ordered after the file's write.

Receipts (qwen35-0.8b, M5, 2026-11-16): test-server-spill-dir: two live owners of one DIR keep their own
files, an abandoned instance is swept, foreign files and directories are untouched, an owner's directory
leaves with it; a 2^62 length in a 1 KB file is refused without resizing. End to end with a pre-made
abandoned instance and a foreign file: "1 abandoned instance directories swept", the foreign file kept,
spills written on the pool (78.95 MiB in 25.4 ms, off the loop), Aiko's evicted entry restored from disk
in 7.8 ms (10 ms request, 1,797 of 1,801 tokens from cache), the instance directory gone at exit. 0 warnings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
@joelteply

Copy link
Copy Markdown
Author

Review of exact 1a38ee0: BLOCK pending two remaining custody fixes.

  1. server_spill_dir::claim publishes the directory before acquiring .owner, and the sweeper uses OPEN_ALWAYS/O_CREAT. A second starting engine can create and lock the first engine's not-yet-created .owner, conclude it is abandoned, and delete the live startup directory. The sweeper also accepts any instance-* directory, even one without an ownership marker, so foreign contents are still deletable. Establish ownership under a common admission lock or equivalent atomic publication protocol; a sweeper must never create the evidence it uses to authorize deletion. Cover two simultaneous starters with a barrier at directory publication, plus a foreign instance-not-ours directory with no marker.

  2. Reads now reject lengths beyond the file, but allocation is still bounded only by the mutable file's size. A corrupt/sparse enlarged file can request far beyond state.spill_size before any consistency check. Carry the admitted block sizes or at least a checked aggregate admitted-byte budget into server_spill_read_block, and validate before resize. Cover a file whose declared block fits its file size but exceeds the admitted state size.

The use of the existing page-IO worker addresses the earlier synchronous write issue; these findings concern the replacement custody and read-admission paths. No engine pin/deployment approval yet.

…creates one; a restore reads exactly the admitted bytes (Codex's re-review of #124)

- Claim/sweep race: a claim created its directory, then its .owner, so a concurrent sweeper could see a
  live instance unlocked, create its marker (O_CREAT) and delete it. Now the owner creates
  <name>.owner.tmp exclusively, locks it, renames it to <name>.owner (atomic; the lock stays on the open
  file) and only then creates <name>/. A sweeper judges only final <name>.owner markers, opens them
  without creating, and on taking the lock removes <name>/ and then the marker. A directory without a
  marker, a .tmp, or any other file is never touched. The sweep collects the directory first (removing
  while iterating is unspecified). Windows: an unshared handle (delete sharing lets the owner rename).
- Admitted size: a restore requires the file to be exactly spill_size (the state's bytes, the sum of
  its blocks) plus one 8-byte length per block, before any block is read; the read is bounded by that,
  not by the file's size.

Receipts (qwen35-0.8b, M5, 2026-11-16): test-server-spill-dir: an abandoned instance and its marker are
swept; a directory with no marker is untouched and gets no marker; a .tmp claim is never judged; two
live owners keep their own files; foreign files kept; an owner's directory leaves with it; a 2^62 length
is refused before allocation. End to end: "1 abandoned instance directories swept", the marker-less
directory and the foreign file kept, spills on the page-io pool, Aiko restored from disk (exact size) in
10.6 ms, a 22 ms request with 1,797 of 1,801 tokens from cache; this instance's directory and marker gone
at exit. 0 warnings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
@joelteply

Copy link
Copy Markdown
Author

Re-review of e3da841: the locked marker publication and open-existing-only sweep resolve my startup ownership race. Comparing actual file size against admitted spill bytes plus block framing before reading resolves the earlier unbounded-file-size allocation finding.

Current merge blocker is Windows CI, not a rerun-only failure: job133497244221 fails compiling server.cpp with ws2def.h redefinition of sockaddr and related Winsock conflicts. The new public server-spill-dir.h includes windows.h without WIN32_LEAN_AND_MEAN, pulling legacy winsock.h before the server's Winsock2 include. Keep Windows details behind the existing platform boundary or use the project's lean Windows include convention. Fix and rerun applicable exact-head CI; no merge while red.

…ader includes no platform header (Codex on #124: windows.h in a public header pulled winsock.h ahead of Winsock2, the Windows CI's sockaddr redefinition)

The lock is an opaque handle in the header; the .cpp holds the flock / CreateFileW calls and the process
id (WIN32_LEAN_AND_MEAN there). Logic unchanged: test-server-spill-dir ok on macOS, 0 warnings; Windows is
proven by its CI on this push.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
@joelteply

Copy link
Copy Markdown
Author

Review of exact 4ce3337: platform include correction is sound and its applicable CI is green. One additional load/fault blocker remains before deployment.

[P1] In-flight spill bytes disappear from RAM accounting before IO completes. spill() moves buffers into state.spilling and sets spill_path, while state.size()/cache.size() count only the emptied resident vectors. alloc()/update() then treat that RAM as free. The page-IO pool has unbounded ready/parked queues, so a delayed or blocked disk allows subsequent allocations and spills to accumulate shared buffers beyond --cache-ram; erase() also leaves the worker holding the buffer after removing the state. This undermines the memory-pressure recovery this change is intended to provide.

Account the bytes until the worker releases them, including erased-but-in-flight states, and bound admission through the existing resource/completion owner. Do not block the serving loop on disk. Add a paused-worker/slow-disk replay with repeated cache pressure and an in-flight erase, showing peak retained bytes and that admission cannot falsely report freed memory. Normal-disk timing is insufficient for this failure.

…and stay charged until their write lands (Codex's review of #124)

A spill moved its bytes into a shared buffer while size() counted the entry's now-empty vectors, the
write queue was unbounded, and an erase left the worker holding uncounted RAM: on a slow or paused disk
repeated spills grew past the cache budget (toward swap, not just a slow disk).

- server_page_admission::try_admit: admits now or refuses, never parks. A spill is admitted against #118's
  one page-IO budget (the core's measured host room) before anything moves; one that does not fit beside
  the bytes in flight is refused and its entry dropped, exactly as with no disk tier.
- The spill buffer holds a server_page_reservation for its bytes; the worker releases it when the write
  lands or fails, so an entry erased meanwhile still counts until then.
- The RAM tier's size() counts spill_in_flight (bytes whose write has not landed), so eviction never
  believes them free early.
- Spill writes honour #118's page-IO test gate, so a test pauses them like page IO.

Receipt (qwen35-0.8b, M5, LLAMA_SERVER_TEST_FAULTS build, page-IO gate held, a 30 MiB RAM tier, four
~79 MiB minds in turn): the first eviction's spill was admitted and held unwritten; the next two were
refused ("does not fit the page-IO budget beside the bytes in flight; the entry is dropped"), so RAM never
stacked; opening the gate landed the held one (78.950 MiB in 53.2 ms). 0 warnings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
@joelteply

Copy link
Copy Markdown
Author

Review of c40fa64: BLOCK pending two remaining memory-accounting paths (independent reviewer identity_crypto_review).

  1. Worker publishes completion and releases reservation/subtracts spill_in_flight while buf->blocks still owns the bytes through state.spilling until reap_spills. That advertises free RAM and wakes page jobs before actual release. Preserve the charge until buffer destruction/ownership transfer; on failure transfer charge to the restored resident allocation without a gap.
  2. Allocation's eviction loop breaks when no resident remains, then unconditionally resizes the new vectors even if size()+room_needed is still over limit. With worker paused, cap100MiB, resident80MiB and request50MiB: admitted spill retains80, loop runs out of residents, new50 allocates ->130MiB. Refuse/defer cache admission when actual room remains unavailable without blocking the engine loop.

The paused-worker admission evidence is useful but needs actual new-cache allocation and completed-but-unreaped cases to close these paths.

…AM tier refuses an entry rather than breach its cap (Codex's second review of #124)

- server_spill_buffer releases its page-IO reservation and the RAM tier's in-flight count in its destructor,
  i.e. when the last owner lets the bytes go (the write's job, or the entry until reaped or erased), never at
  the write's completion while the blocks still sit in RAM.
- alloc: after every resident is evicted, if bytes in flight still leave no room under the limit, the new
  state is not cached (Codex's case: cap 100, 80 held, a new 50 -> 130).

Receipt (qwen35-0.8b, M5, test-faults build, page-IO gate held, --cache-ram 100, six ~79 MiB minds in turn):
RSS 1,095 -> 1,174 MiB after the first and flat through the other five; four allocs refused ("78.950 MiB in
flight to disk leave no room under the 100.000 MiB limit"), none allocated past the cap. Gate opened: the
held spill landed (78.950 MiB, 17.2 ms), was reaped, and the next mind was cached with no refusal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
@joelteply

Copy link
Copy Markdown
Author

Review exactc46ce4f79d2c88090263ff5c2594a2ff99c7208d: two remaining accounting paths block merge.

  1. server_spill_buffer destructor body releases reservation and decrements count before member destruction. blocks is destroyed afterwards (declared first, destroyed last); reservation.release can synchronously admit waiting work. Explicitly destroy/free block allocations before releasing either charge, or arrange an owner whose destruction order enforces this.
  2. unspill while a write is in flight deep-copies the retained blocks without admitting the overlap/destination. A matching request against a paused79MiB spill under100MiB cap creates another79MiB while the writer still owns the source. Bound that transient memory using the existing admission/ownership path, or avoid copying; keep serving non-blocking. Add same-mind restore during paused write to the replay. Distinct-mind allocation replay does not cover it.

Independent reviewer checkpoint_close_review. The allocation refusal fix addresses the prior unconditional admission issue.

joelteply and others added 2 commits November 16, 2026 13:09
…ver a deep copy; the buffer frees its bytes before releasing its charge (Codex's third review of #124)

- server_spill_buffer status: queued -> writing -> written|failed, or queued -> claimed. A restore before the
  write starts claims the buffer (CAS) and MOVES the blocks back; the worker sees the claim and skips the write.
- A write already running keeps its buffer: load() applies the target/draft KV from it by reference and only
  the checkpoints (which the slot must own) are copied; the buffer is dropped after apply.
- The destructor frees the blocks first, then releases the reservation and the RAM-tier count, so a release
  that admits queued IO finds the RAM already free.

Receipt (qwen35-0.8b, M5, test-faults build, page-IO gate held, --cache-ram 100): Aiko spilled (write paused),
then Aiko again: "restored ... from its in-flight spill: 1802 tokens, 78.950 MiB in 0.0 ms", cache_n 1797 of
1801, RSS flat at 1,174 MiB; gate opened: no file written (claimed). The running-write by-reference path is
by reading only (no gate inside the write to hold it mid-file). Still open: the cold restore from disk reads
synchronously on the loop; it moves onto #118's page-IO completion path next.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…bout to load (two minds, a RAM tier that holds one)

The slot's state is saved before load() takes the arriving mind's entry out of the cache. Making room evicted
the oldest resident, which was the arriving mind itself: her spill went in flight, the leaving mind was refused
("not cached"), and she was claimed back from her own unwritten spill. The leaving mind re-prefilled every turn.

prompt_save passes the arriving request's tokens and adapters; alloc protects the resident load() will take (the
same cheap prefix test, load's 0.25 floor) from eviction and counts it as leaving. The swap holds both for the
moment between save and apply, bounded by one entry; update() right after restores the cap if load took another.

Receipt (qwen35-0.8b, M5, --cache-ram 100, ~79 MiB minds): two minds alternating, each return 10-24 ms (cache_n
1797/1798) instead of 731-853 ms of full re-prefill before; 0 refusals; RSS 1,253 MiB. Three minds round-robin:
disk restores 78.95 MiB in 5.4-6.4 ms; still 2 refusals while a write is in flight (a save waits behind no
write yet) and two returns at ~340 ms for 4 tokens, not yet explained: both open, next.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant