Skip to content

server: a KV page's file IO runs on a worker; the task loop only copies the state in or out - #118

Merged
joelteply merged 5 commits into
codex/s4-per-mind-integrationfrom
fx-async-paging-fork
Nov 14, 2026
Merged

joelteply merged 5 commits into
codex/s4-per-mind-integrationfrom
fx-async-paging-fork

Conversation

@joelteply

@joelteply joelteply commented Nov 14, 2026 •

Copy link
Copy Markdown

Serves path step 1 "Fast" and continuum order-of-work line 3b (one live engine, its minds' memory moved by us). A page switch no longer stalls the other minds' decode, and switches issued together overlap: the render thread never blocks on IO, as in texture streaming.

Problem (measured)

Every page save and restore ran as one task on the single task loop, disk IO included (server-queue.cpp process_new_tasks; save at server-context.cpp ~2809/2960, restore ~2996/3076 on cd2e16d). While one ran, no slot decoded, and switches waited for each other. Receipt: the M5 on 2026-11-14 at 00:18:13Z. The core issued two restores together, and Benchy's waited 1,024 ms, which is exactly Aris's 1,012 ms in the engine.

Change

  • Library (llama.h): llama_state_seq_file_body_size / llama_state_seq_get_file_body / llama_state_seq_set_file_body. A seq state file's body (what llama_state_seq_save_file writes after its tokens) is copied out of or into host memory, so the file IO can run off the context's thread. The framing is unchanged, so pages written before this change still restore.
  • Server: the loop copies the state, tokens and sidecars into the switch. That copy is bounded and proportional to the bytes, with each buffer sized once. The files are written or read on server_page_io_pool (server-page-io.h). The pool has one worker per slot, and switches on one file run one at a time, in order, so a restore never reads a file a save is still writing. Completion is a SERVER_TASK_TYPE_SLOT_PAGE_IO_DONE task posted back to the loop, and only that task touches the slot. Nothing polls and no timer decides.
  • Restore: the read starts at once, even while its slot finishes another turn, so it overlaps that turn's decode. It applies when the slot is free: the completion defers on is_processing() and is bound to its slot through pop_deferred_task(id_slot). The adapter identity and the tokens are checked before the KV is touched. A restore whose slot was given another task or erased while it read is refused: 400 invalid_request_error, with "refusal": "slot_reassigned". The occupant is kept, not overwritten. This uses server_slot::n_occupancy, which counts task launches and erases.
  • Receipts: the /slots save/restore contract is unchanged. timings adds copy_ms (the loop's share) and io_ms (the worker's), and save_ms/restore_ms is their sum, which is the engine's work without any wait for the slot.
  • The save/restore arms move out of server-context.cpp into server-context-page.inc, which takes 322 lines out of server-context.cpp. The sidecar formats are byte-identical.

Predicted by the simulator (continuum dyno 11b, core/continuum-engine/src/capacity/dyno/restart/stall.rs)

The inputs are the restart day's receipts: save at 603,433 B/ms, restore at 1,464,377 B/ms, and pages at 32,273 B/token. The host copy rate is 40,558,095 B/ms, a memcpy measured on the M5 at 2026-11-14T07:24:45Z. This PR's copy_ms receipt replaces it after deploy.

Scenario On the loop (now) Streamed (this PR)
Four residents' saves at once: decode stall on every other slot 13,547 ms 204 ms
Four saves at once: last receipt 13,547 ms 5,021 ms
Aris and Benchy restores together: Benchy's receipt 1,917 ms 1,026 ms
Those two restores: decode stall on other slots 1,917 ms 70 ms

Assumption, not measured: each switch's disk IO runs at its measured single-stream rate while others run. The per-stream rate (0.6 to 1.5 GB/s) is well under the M5 SSD's, but the aggregate is unmeasured, and io_ms on the live node settles it.

Memory: one budget (review fix, 4731f0b). Each switch's host bytes are admitted against one budget before anything is allocated. The bytes counted are the page body plus its sidecars, up to about 1.6 GB a switch on the live M5. A switch that does not fit waits in order and is admitted by the release that makes room. The core sets the budget at runtime from its live host room (POST /page-io/budget, GET /page-io). Until then the budget is 0, meaning one switch at a time. A restore buffered for a slot that is given another task or erased returns its bytes at once. Receipts report page_io {io_bytes, io_bytes_in_flight, io_budget_bytes} and timings.admit_ms.

Tests

  • tests/test-server-page-io.cpp is model-free and runs in the server workflow beside test-server-prefill. It covers four cases. First, saves of different files overlap: peak concurrency equals N, and every save's interval contains the instant all N were in flight. That proves it by event order rather than by comparing durations: wall < sum flaked on a Windows runner. Second, one file has one switch in flight at a time, in submit order, and another file is not held behind it. Third, the loop keeps decoding while a save is held, and the completion arrives as an event. Fourth, the page framing round trips, and a wrong version, a cancel, or a token count past EOF is refused. It also checks that shutdown runs every submitted switch.
  • test_slot_save.py has two gated tests (LLAMA_SERVER_TEST_PAGE_IO_GATE, a FIFO the test holds; opening its write end returns once the IO waits, and no test sleeps). In the first, slot 1 decodes a whole completion while slot 0's save is held in its write; the save then answers, and save_ms == copy_ms + io_ms. In the second, a restore whose slot was given another task while it read is refused with refusal == "slot_reassigned", and the occupant keeps its cache (prompt_n == 1).
  • The existing slot tests still pass unchanged: the deferred restore stays bound to its slot, live save, progress phases, and the legacy token list.

Measured after deploy (open)

On the M5, under the core's inference.kv_page.action probe: copy_ms / io_ms per switch, other slots' decode during a stop checkpoint, and the restore pair's wait. Owner: Fable. Due on the first deploy after the continuum pin bump.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

…es the state in or out

Every page save and restore ran, disk IO included, as one task on the single task loop
(server-queue.cpp process_new_tasks), so a switch stalled decode for every other slot and
switches issued together waited for each other (the M5 2026-11-14 00:18:13Z: Benchy's
restore waited 1,024 ms behind Aris's 1,012 ms).

Now the loop copies the sequence's state out (llama_state_seq_get_file_body, new) or in
(llama_state_seq_set_file_body, new), bounded and proportional to its bytes; the page's
files are written or read on a worker pool (server-page-io.h, a worker per slot, one
switch per file at a time, in order), and the IO's completion is a task posted back to
the loop (SERVER_TASK_TYPE_SLOT_PAGE_IO_DONE), which alone touches the slot. A restore
reads at once, even while its slot finishes another turn, and applies when the slot is
free; one whose slot was given another task or erased while it read is refused, typed
("refusal": "slot_reassigned"), and the occupant is kept.

The HTTP contract and the page files are unchanged (the library's own framing: pages
written before restore). The receipts add timings.copy_ms (the loop's share) and
timings.io_ms (the worker's); save_ms/restore_ms are their sum.

The save/restore arms move out of server-context.cpp into server-context-page.inc
(-322 lines there).

Tests: test-server-page-io (model-free: different files overlap, one file serialized in
order, decode continues while a save is held, page framing round trip and defects,
shutdown runs every switch) in the server workflow; test_slot_save.py gains two gated
tests (LLAMA_SERVER_TEST_PAGE_IO_GATE, a FIFO the test holds; no sleeps): a slot decodes
a whole completion while another's save is held in its write, and a restore whose slot
was given another task meanwhile is refused typed with the occupant's cache kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply and others added 2 commits November 14, 2026 01:47
…ng durations

Windows runners failed wall < sum on microsecond jobs (thread start-up counted in the wall).
Every save's interval now must contain the instant all four were in flight.

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

Copy link
Copy Markdown
Author

Review from Fable at head 4cd5e5d. I read the new llama.h/llama-context API, server-context-page.inc and the io pool.

The design is right. state_seq_{get,set}_file_body copies a sequence through host memory with the context synchronized, file IO moves to a worker, a restore's read overlaps the slot's current decode, the completion is applied on the loop when the slot frees, and it arrives as an event. This removes the cost the M5 measures today: in inference.kv_page.action, a 12:44Z restore spent wait_ms 8,720 of 9,882 ms queued behind decode batches.

Blocking: in-flight page bytes are unbounded against host memory. The pool runs a worker per slot (~L949/L1419), and each job holds its full body plus ckpt_sidecar/lora_sidecar in RAM. A restore reads at once and keeps its buffer until the slot frees, which can be a whole turn. Live M5 sizes from ~/.continuum/cache/kv-pages: page bodies are 0.24–0.58 GB and .ckpt sidecars 0.34–1.04 GB, so one switch is up to ~1.6 GB, and five concurrent switches several GB. On the M5 at 11:33Z the host had 0.1 GB free (engine 37 GB wired). Without a bound this turns a queue wait into swap and compression stalls for every mind.

Fix: the bytes held by in-flight page jobs are admitted against one budget before the job allocates. Don't use a hand-set constant. Either expose the projected job bytes (you already compute projected_bytes) on the request/receipt so the core admits it against its live host room (ggml-org#6011, one memory budget), or have the server take a byte budget the core sets at runtime and defer a job that doesn't fit until a running one frees its buffer (event, not poll). A deferred restore still beats today's queue: its read starts as soon as bytes free up.

Non-blocking:

  • A restore buffered for a slot that then gets a different page (the mind left) should drop its buffer at once. Please confirm cancellation frees it, and add that case to test-server-page-io.cpp.
  • Report io_bytes_in_flight in the page receipt, so the core's probe can show it.

… a restore whose slot is reassigned returns its bytes at once

Review (Fable on #118): every slot's page job held its body and sidecars in host memory with no
bound (live M5 pages up to ~1.6 GB a switch; 0.1 GB free at 11:33Z), and a restore held its buffer
until its slot freed.

- server_page_admission (server-page-io.h): a switch is admitted against ONE byte budget before it
  allocates; one that does not fit waits in order and the release that makes room admits it in that
  release (an event, never a poll). A switch larger than the whole budget runs alone, never starves.
  The core sets the budget at runtime from its live host room (POST /page-io/budget, GET /page-io);
  unset it is 0: one switch at a time, still off the task loop. No hand-set number.
- A save is sized (body, tokens, sidecars) before its copy and parks unrun when it does not fit; a
  restore is sized from its files on disk before its read. A save returns its bytes when its write
  ends, a restore when it is applied.
- A slot given another task or erased drops every restore buffered for it: its bytes return at once,
  a read in flight stops at its next part, and a read already done is freed and answered
  slot_reassigned then, never held behind the slot's new turn.
- Receipts: page_io {io_bytes, io_bytes_in_flight, io_budget_bytes} and timings.admit_ms.
- Shutdown drains the pool, then closes the budget, so no waiter posts into a queue being torn down.

Tests: test-server-page-io adds the budget (unset serializes; fits run together; FIFO; one release
admits all that now fit; oversize runs alone; raising admits; resize) and a dropped restore returning
its bytes once and at once. test_slot_save: the reassigned restore's bytes are 0 in flight while its
read is still held; a save's receipt reports its bytes; a second save waits for the first's release;
the slot-binding test runs with room for both pages.

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

Copy link
Copy Markdown
Author

Fixed at 4731f0b.

Blocking: one budget for in-flight page bytes.

  • server_page_admission (server-page-io.h) admits each switch's bytes before anything is allocated.
    • A save is sized before its copy: body from llama_state_seq_file_body_size, plus tokens, plus the .ckpt/.lora sidecars counted by the same writers.
    • A restore is sized from its three files on disk before its read.
  • A switch that does not fit parks unrun and waits in FIFO order. The release that makes room admits it inside that release's own call, as an event, never a poll. A switch larger than the whole budget runs alone once nothing else is in flight, so it never starves.
  • The budget is the core's. POST /page-io/budget {"budget_bytes": N} sets it, and GET /page-io reports {budget_bytes, in_flight_bytes, waiting}. Both are answered off the task loop. Raising the budget admits waiters at once.
  • Release points.
    • A save returns its bytes when its write ends, before its receipt.
    • A restore returns its bytes when it is applied, because its state then belongs to the slot.
    • A refusal or failure returns them through the reservation's destructor, exactly once.

Non-blocking items: both done.

  • Restore dropped when its slot is reassigned. A slot given another task (launch_slot_with_task) or erased runs page_slot_reassigned, which drops every restore buffered for that slot.
    • Its bytes return to the budget immediately.
    • A read still in flight stops at its next 1/64 part and frees its own buffers.
    • A read already done is freed on the loop and answered slot_reassigned right then, so it is never held behind the slot's new turn.
    • Tests: a_dropped_restore_returns_its_bytes_at_once in test-server-page-io.cpp covers the mechanism. In the real server, the reassigned-restore pytest now asserts in_flight_bytes == 0 while that restore's read is still held at the gate.
  • Receipt. It now carries page_io: {io_bytes, io_bytes_in_flight, io_budget_bytes} and timings.admit_ms.

Also changed.

  • At shutdown the pool is drained first, then the budget is closed, so a waiter never posts into a queue that is being torn down.
  • test_deferred_restore_is_bound_to_its_slot now sets a budget of twice its page's bytes on disk. That test is about slot binding, and with a budget of 0 the long slot's buffered restore would hold the pipe.

@joelteply
joelteply merged commit 20b108f into codex/s4-per-mind-integration Nov 14, 2026
14 of 16 checks passed
joelteply added a commit that referenced this pull request Nov 16, 2026
…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 added a commit that referenced this pull request Nov 16, 2026
…he live reconfigure (S2)

Conflicts resolved:
- server-test-faults.h: both hooks kept (this line's step_delay_ms, #118's page_io_gate); any() and the
  startup log name both.
- server-context.cpp: slots are created by bind_slots() (a reconfigure re-binds them), so the integration's
  inline slot setup goes; its page-io pool is created beside bind_slots; the trace/debug/test-fault reads
  stay where this line moved them (load()). SLOT_SAVE takes #118's page_save / page_restore /
  page_io_done (off the task loop); those resolve slots through get_slot_by_id, which this line made
  exact (a parked id is never another mind's slot).

Receipt (qwen35-0.8b, M5, 2026-11-16, this merge): 0 build warnings; 20 live reconfigures cycling
(16384,4) (4096,1) (12288,3) (8192,2) for (n_ctx, n_seq): a temperature-0 reply identical before and
after, the weights loaded once (one load in the log), RSS 1,098 MB before and 1,167 MB after (+69 MB;
not claimed flat).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Nov 16, 2026
…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 added a commit that referenced this pull request Nov 16, 2026
…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
joelteply added a commit that referenced this pull request Nov 16, 2026
…it (#79 on the shipping line, through #118's pipeline) (#130)

* server: a page carries the draft's KV once; checkpoints stop copying it (#79 on the shipping line, through #118's page pipeline)

A draft whose memory rolls back by trimming (plain attention KV: the MTP head) has nothing a checkpoint must
hold; on restore slot.mem.seq_rm trims its live KV to the checkpoint (common_memory holds both contexts).
Copying it made it 79% of every checkpoint (#79's M5 receipt: 246 MB at 118k tokens), up to
n_ctx_checkpoints copies per slot in host RAM. Now:
- create_checkpoint skips the draft's state when ctx_dft_seq_rm_type is PART;
- a saved page carries the draft KV once, the `.dft` sidecar, riding #118's pipeline: copied on the loop
  into the job (counted in the size quote and in the page IO admission), written on the pool to .partial
  and renamed over (never torn; a stale .dft is removed when a page has none);
- the header binds it to exactly the page's tokens (count + FNV-1a hash) and names the state's size; the
  pool reads it only when the file is exactly a header plus that state (never allocated from a claim);
  the loop applies it only when it covers exactly the restored tokens, else clears the draft sequence
  (never another occupant's KV at these positions): the draft then starts cold and the target still
  verifies every token.

Receipts (qwen35-0.8b, --spec-type draft-mtp, M5, 2026-11-16): generate, save the page, erase the slot,
restore it, continue at temperature 0: with the .dft sidecar the draft accepted 47 of 47; with it deleted
before the restore, 43 of 59 (cold); the continuation text identical both ways. The same save on the
shipping line without this change: .ckpt 43.9 MiB vs 38.5 MiB here with the draft carried once (3.3 MiB
.dft) at ~1.7k tokens; the saving is ~2 KiB per token per checkpoint, so it grows with her context. 0 warnings.

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

* server: the draft sidecar is bound to its page's computation and can never outlive an interrupted save (Codex's review of #130)

- .dft v2 names an FNV-1a hash of the save's own .lora sidecar bytes (adapters + file revisions) beside the
  token hash; the restore applies the draft only when tokens AND computation match, else it drafts cold.
- page_write removes the old .dft before publishing the page, and writes the new one last (temp + rename):
  an interruption anywhere leaves no draft or this save's, never an earlier save's of the same tokens.

Receipt (qwen35-0.8b, draft-mtp, M5): clean save/erase/restore matched (no cold draft); the same .dft with its
computation hash changed was refused ("no draft sidecar matching this page ... the draft starts cold");
a re-save rewrote it and the next restore matched again. 0 warnings.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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