Skip to content

kv: persona KV moves raw between a stream and host memory, bound to any stream (4.14 prototype) - #147

Merged
joelteply merged 30 commits into
codex/s4-per-mind-integrationfrom
fable/kv-stream-blocks
Nov 18, 2026
Merged

joelteply merged 30 commits into
codex/s4-per-mind-integrationfrom
fable/kv-stream-blocks

Conversation

@joelteply

Copy link
Copy Markdown

Prototype for CONTINUUM-ENGINE 4.14 (continuum ggml-org#6092), isolated; no serving change.

  • stream_save / stream_load: her used rows per layer copied raw (K, V); her llama_kv_cells swapped out/in. No cell walk, serialization or recompute.
  • stream_bind: her own sequence id mapped to a physical stream (seq_to_stream stays a permutation); cells never retagged.
  • Graph reuse compares each sequence's physical stream (llama_memory_i::seq_stream, forwarded by iswa/hybrid wrappers): K/V views are built at the stream.
  • Contract: the completion fence (llama_synchronize) before a raw copy.

Measured (M5 Metal, stories15M, 715840b)

test-kv-stream-blocks: next-token logits byte-identical (max|diff| 0) after stream 0 -> host -> stream 1 + bind; mirror direction; with/without the destination used first; first and second token after the move. Without the fence: max|diff| 18.15, top token changed (the save read the cache before the decode's writes landed).

Not yet

Recurrent rows (hybrid 35B), draft-context streams, sampler custody, owner handle instead of swap, per-layer fences, copy time vs bandwidth at real lengths, 4/8/16 scaling.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

…, her metadata by swap, her sequence bound to any stream (CONTINUUM-ENGINE 4.14 prototype)

stream_save/stream_load copy her used rows per layer raw (K, V) and swap her llama_kv_cells
out/in (no cell walk, no serialization, no recompute); stream_bind maps her own sequence id to a
physical stream (seq_to_stream stays a permutation; her cells are never retagged). Graph reuse
now compares each sequence's physical stream (llama_memory_i::seq_stream), since K/V views are
built at the stream, not the sequence id. The raw copies require the completion fence
(llama_synchronize) first: a decode returns before its KV writes land.

test-kv-stream-blocks (Metal, M5): next-token logits byte-identical (max|diff| 0) after moving
her stream 0 -> host -> stream 1 with her sequence bound there; mirror direction; with and
without the destination used first; first and second token after the move. Without the fence
the move read zeros (max|diff| 18.15, top token changed).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…recurrent rows), byte-identical (CONTINUUM-ENGINE 4.14)

llama_memory_recurrent::seq_save/seq_load copy her row in every snapshot group (live + n_rs_seq
rollback groups) raw and carry her cell record (pos, rs_idx); a load takes any free cell and
sets her tail there (her sequence id is kept; nothing recomputed). llama_memory_hybrid::
persona_save/persona_load compose it with the attention stream move and bind.

test-persona-blocks (Metal, M5, tiny random qwen35moe from test-llama-archs -s 42): her first
and second token after the move byte-identical (max|diff| 0). Not exercised here: rollback groups
(n_rs_seq = 0 without an MTP draft).

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

Copy link
Copy Markdown
Author

1770577: the persona's WHOLE hybrid state moves raw. test-persona-blocks on a tiny random qwen35moe (the M5's arch; test-llama-archs -a qwen35moe -s 42 -o): first and second token after moving her attention stream + recurrent rows out and back into stream 1 bound to her id are byte-identical (max|diff| 0). Rollback snapshot groups are copied but not exercised (n_rs_seq = 0 without MTP).

@joelteply

Copy link
Copy Markdown
Author

Review of exact 715840b. Useful isolated attention-cache prototype, not accepted for integration or as no-walk switching yet.

  1. stream_save still walks all KV cells. out.cells.resize(cells.size()) calls reset; the equal-size branch calls out.cells.reset() directly. llama_kv_cells::reset loops every cell, then clears used and every seq_pos map. Thus repeated switching still scales with kv_size even with only 40 used rows. Replace this with prepared empty ownership/handle exchange under the allocation owner, with no reset/reconstruction on save. Per-layer sizing/allocation and stream_bind's map scan also remain prototype work, not prebuilt descriptors/constant binding.

  2. test-kv-stream-blocks only asserts moved_exact for the main move. report() returns void: X1, mirror X3, first/second-token X4, same-stream control and rows_equal can all fail while the test exits successfully. Make each claimed variant assert byte equality. Keep diagnostic reporting, but attach a failing assertion to each case. Confirm CI actually runs the model-labelled test, not only builds it. The reported M5 logs may show success, but current regression protection does not prove every advertised variant.

  3. stream_load validates row count and cell capacity but not k/v outer counts, per-layer byte lengths, type/shape/model identity or metadata extent consistency. With a public mutable blocks value, mismatched blocks can index outside in.k/in.v or write an incompatible amount into tensors. Validate the complete typed layout before the first tensor write (or constrain construction through the exact allocation owner); refusal must leave both source and destination unchanged. Add malformed/truncated/wrong-layout rejection cases.

  4. The fence is currently a caller comment and test helper. Keep this explicitly prototype-only until the existing completion owner makes the dependency part of the transfer operation. A whole-context synchronize proves ordering but not asynchronous overlap/per-consumer scheduling. Also add a two-live-persona case: stream_bind permutes another sequence's mapping without moving its data; require/document legal empty/displaced ownership states and prove the other persona remains resumable.

No serving change requested. Recurrent/draft/sampler support and real-size timing remain separate outstanding gates; do not expand the correctness claim from stories15M/40 rows to the hybrid resident model.

@joelteply

Copy link
Copy Markdown
Author

Follow-up on new head 1770577: the attention reset walk and print-only assertions remain. The hybrid addition introduces a further custody blocker: persona_save/load compose mutating attention and recurrent operations using &&. For example, attention save removes the resident metadata before recurrent save can return shared_cell; attention load and bind commit before recurrent load can return no_free_cell/seq_holds_state. A false result therefore leaves the persona split across host/device owners. Reserve and validate both halves before mutation, and retain an explicit completion/transaction state for any partial device submission. Fault replay must prove both halves remain resumable after each refusal. Recurrent seq_load also scans every cell for a free destination: destination allocation belongs before the move, not inside resume. Its r/s vectors and group byte lengths need prevalidation just like KV.

…l), fenced by the context (Codex's #147 review)

- llama_memory_i gains persona_prepare / persona_check_save / persona_check_load (const: every
  condition decided, destination reserved) and persona_commit_save / persona_commit_load (raw copies
  and record writes only). KV cache, recurrent memory and hybrid implement it; the hybrid checks both
  halves before either commits, so a refusal never splits a persona.
- llama_context::persona_save / persona_load are the one entry point and take the completion fence
  (synchronize) themselves.
- No cell walk on a move: her blocks hold an empty, stream-sized cells object prepared once
  (persona_prepare); a save checks it in O(1) (used set, has_shift flag) and refuses
  cells_not_prepared, never resets.
- Loads validate layer counts and every per-layer byte length (KV rows; recurrent rows x groups)
  before the first write: layout_mismatch.
- Recurrent destination: reserved in check_load by a search over the memory's cells (one per sequence
  slot: bounded by the slot count, not context length).
- One typed outcome, llama_persona_move, in llama-persona-blocks.h.
- test-persona-blocks replaces test-kv-stream-blocks; every variant is asserted.

Measured (Metal, M5): test-persona-blocks passes on stories15M (ctest) and on a tiny random qwen35moe
(test-llama-archs -s 42): move to another stream, mirror, same-stream round trip, and two live
personas exchanging streams each byte-identical on two tokens; refusals (unprepared save, load over
an occupied stream, layout mismatch) typed and leave every persona unchanged.

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

Copy link
Copy Markdown
Author

a1c5c8e addresses the 715840b and 1770577 reviews:

  • Walk on save: removed. Her blocks hold an empty, stream-sized llama_kv_cells prepared once (persona_prepare); save checks it in O(1) (used set, has_shift) and refuses cells_not_prepared; no reset.
  • Split persona (P1): one two-phase interface on llama_memory_i: const persona_check_save/load decide every condition and reserve the destination; persona_commit_* only copy and write records (cannot fail). Hybrid checks both halves before either commits.
  • Validation: layer counts and every per-layer byte length (KV rows; recurrent rows x groups) checked before the first write: layout_mismatch.
  • Fence: enforced, not commented: llama_context::persona_save/load are the one entry and synchronize first.
  • Recurrent destination: reserved in check_load; the search is over the memory's cells (one per sequence slot), bounded by slot count, not context. Not an allocator yet; stated as such.
  • Asserts: every variant asserted; test-persona-blocks replaces test-kv-stream-blocks.
  • Two live personas: exchange streams; map stays a permutation; each continues byte-identical.

Measured (Metal, M5, a1c5c8e)

stories15M (ctest) and tiny random qwen35moe (test-llama-archs -s 42): move, mirror, same-stream round trip, two-persona exchange each byte-identical on two tokens; refusals (unprepared save, load over an occupied stream, layout mismatch) typed and leave every persona unchanged. Not an overlap proof (fence is a full synchronize); rollback groups not exercised (no MTP in the tiny model).

@joelteply

Copy link
Copy Markdown
Author

Rereview exact a1c5c8e: the prior full KV reset walk is removed from save, assertions and length checks improved, and the context entry point fences. Those are real corrections. Two remaining correctness blockers:

  1. Commit is still fallible after half the persona moved. persona_prepare sizes only outer vectors. KV/recurrent persona_commit_save resize inner vectors; hybrid commits KV (including swapping metadata out) before recurrent allocations. A recurrent bad_alloc leaves KV parked and recurrent live. persona_commit_load likewise commits KV before recurrent cell.seq_id.insert(seq_id), which allocates a set node. Reserve all byte buffers and metadata nodes before either half mutates, or retain a recoverable transaction state that restores custody after any failed operation. A void return does not establish infallibility. Replay allocation failure at the recurrent phase and prove the persona remains whole/resumable.

  2. The mutable blocks carry no verified persona/layout identity. KV check_load does not ensure its preserved sequence bits belong to the requested seq_id, and recurrent rs_idx is copied without checking it against n_rs_seq. Saving seq0 and loading as seq1 can pass sizes while attention metadata retains seq0 and recurrent gets seq1. Reject wrong-persona input without retagging. Add immutable owner/layout/generation identity and validate rollback index bounds before any write; lengths alone cannot distinguish equal-sized incompatible layouts. Exercise wrong sequence id and out-of-range rollback index with unchanged source/destination on refusal.

The remaining per-layer sizing/validation and recurrent free-cell scan still mean this is not the final prepared-descriptor/owner-handle switching implementation. No merge/deployment approval; the flash-native layout is a separate owned design slice.

…her identity; measured on the 35B (Codex's a1c5c8e review)

- Check phases reserve every byte the commit copies (KV rows at her used length; recurrent rows x
  groups) and her recurrent cell's sequence-set node (a C++17 node handle), so a commit only copies,
  swaps and inserts a reserved node: nothing allocates after either half changes.
- Her blocks carry her sequence and a layout fingerprint per memory (layers, stream size, row types
  and widths, snapshot groups). A load refuses wrong_persona (her metadata is tagged with her
  sequence; never retagged), layout_mismatch, and invalid_rollback (rs_idx > n_rs_seq), before any
  write.
- Measure mode (-n N): recompute (prefill) vs her native state saved and loaded; the in-place
  reference comes from a second clean run (recurrent state cannot be rolled back).

## Measured (M5, Metal, this tree; serving down 04:02-04:05Z)
Qwen3.6-35B-A3B Q4_K_M, KV q4_0, flash attention, ub 2048; her next 2 tokens byte-identical after
the move in every run:
- 4096 tokens: state 89.5 MB; recompute 4350.6 ms; save 5.26 ms; load 1.40 ms (63.9 GB/s); 3108x
- 16384 tokens: state 160.2 MB; recompute 20419.4 ms; save 9.88 ms; load 2.64 ms (60.8 GB/s); 7746x
- 32768 tokens: state 254.6 MB; recompute 50833.8 ms; save 14.09 ms; load 4.09 ms (62.3 GB/s); 12429x
test-persona-blocks passes on stories15M (ctest) and tiny random qwen35moe, incl. wrong_persona and
invalid_rollback refusals that write neither half.

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

Copy link
Copy Markdown
Author

8c186c8 answers the a1c5c8e review and adds the first real-model receipts.

Review fixes: check phases reserve every byte the commit copies and the recurrent cell's set node (node handle), so a commit only copies/swaps/inserts a reserved node (no allocation after either half changes). Blocks carry her sequence + a per-memory layout fingerprint; a load refuses wrong_persona, layout_mismatch, invalid_rollback (rs_idx > n_rs_seq) before any write; both tested, writing neither half. Not tested: injected allocation faults (the commit has no allocating call; stated, not fault-injected).

Measured (M5 Metal, 8c186c8 tree, serving down 04:02-04:05Z)

Qwen3.6-35B-A3B Q4_K_M, KV q4_0, FA on, ub 2048; next 2 tokens byte-identical after every move:

her tokens state recompute (prefill) save load
4096 89.5 MB 4350.6 ms 5.26 ms 1.40 ms (63.9 GB/s)
16384 160.2 MB 20419.4 ms 9.88 ms 2.64 ms (60.8 GB/s)
32768 254.6 MB 50833.8 ms 14.09 ms 4.09 ms (62.3 GB/s)

Load is 3108x / 7746x / 12429x faster than recomputing her. Fence is a full synchronize (not an overlap proof); no MTP draft in these runs.

…group proofs (Codex's 8c186c8 review)

- persona_layout() returns an id computed once at construction (KV cache, recurrent memory): the
  allocation layout is immutable, so no per-check rehash of every layer.
- test-persona-blocks:
  - allocation faults: both commits run with every allocation in the process failing (global
    operator new armed) and complete; a reserve phase failing on allocation leaves her in the
    memory and continuing byte-identical.
  - rollback groups (--test-rs-seq N: serving's draft-mtp configuration, n_rs_seq = N): her state
    moved while a rollback is pending (two drafted tokens, one taken back) continues exactly.

## Measured (M5 Metal, this tree, serving down 04:09:12-04:09:19Z)
test-persona-blocks passes on stories15M (ctest), tiny random qwen35moe, and tiny qwen35moe with
--test-rs-seq 4 (n_rs_seq=4, her rs_idx=1 carried; continuation max|diff| 0). Test binary sha256
939384c5cab7fd124852454f25e872b449fe1df69a6cdc4c9cb00b70b258040b.
Not yet: model/genome owner identity in her blocks (needed before any persistent-tier reuse).

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

Copy link
Copy Markdown
Author

70ab7f7 answers the 8c186c8 review.

  • Layout id once: computed at construction (KV cache, recurrent), returned by persona_layout(); no per-check rehash.
  • Fault injection: test overrides global operator new; both commits run with every allocation failing and complete; a reserve phase failing on allocation leaves her in the memory and continuing byte-identical.
  • Rollback groups: --test-rs-seq 4 (serving's draft-mtp config, n_rs_seq=4): moved with a rollback pending (rs_idx=1 carried), continuation max|diff| 0.
  • Owner identity: not yet; blocks carry seq + layout only. Model/genome generation identity is required before any persistent-tier reuse (next slice, with the native flash layout).

Evidence for the 35B receipts (8c186c8 tree)

  • raw log: /private/tmp/claude-501/-Users-joel-Development-continuum/eeaaf632-3524-4ecb-bb1a-3ca88a22f414/scratchpad/measure-window.log (window 04:02:14-04:05:03Z)
  • model: Qwen3.6-35B-A3B-Q4_K_M.gguf, 20419565568 bytes, sha256 671e47e0ec53c665d048b98c3ecbfd5236b5ca9c3e02ed19fc8f81f7b85140c7
  • flags: -n N -c 2*(N+512) -ngl 999 -ctk q4_0 -ctv q4_0 -fa on -b 2048 -ub 2048
  • that run's test binary was rebuilt since (not retained); today's binary sha256 939384c5...040b (70ab7f7 tree)
  • timer boundaries: prefill = all prompt batches + synchronize. save = llama_context::persona_save whole: synchronize + check (incl. reserving her byte buffers; first save allocates them) + commit (device->host copies). load = persona_load whole: synchronize + check (incl. node-handle allocation) + commit (host->device copies, swap, bind). So 4.09 ms is the full fenced load call, not an overlapped switch; no MTP draft, no flash.

joelteply and others added 5 commits November 16, 2026 22:20
…angling-reference on a range-for over {make_pair(...)})

Same copies, no temporary pairs. Verified on Metal, M5 (serving down 04:19:15-04:20:23Z):
test-persona-blocks passes on stories15M (ctest), tiny qwen35moe, and tiny qwen35moe --test-rs-seq 4
(pending rollback carried, continuation byte-identical).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…ed builds do not export llama_context internals); CI runs it on the generated hybrid and with rollback groups

Windows CI (lld-link: undefined llama_context::persona_* / llama_persona_move_name) linked the test
against a llama.dll that exports only LLAMA_API. It now builds in the existing
'NOT WIN32 OR NOT BUILD_SHARED_LIBS' block, beside test-llama-archs, and CI runs it three ways:
- test-persona-blocks: stories15M (download fixture)
- test-persona-blocks-hybrid: generated qwen35moe (generate-models fixture)
- test-persona-blocks-rollback: generated qwen35moe --test-rs-seq 4

Checked by configure + ctest -N (tests #40, #41, #66 registered); no build beside serving.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…th it (Windows CI: the allocation-free commit allocated)

windows/x64-cpu-static aborted (0xc0000409) in test-persona-blocks' allocation-fault variant: the
commit allocated. std::swap of llama_kv_cells moves through a temporary, and MSVC's std::set/std::map
move constructors allocate a sentinel node (libc++ does not, so macOS passed). llama_kv_cells::swap
exchanges each member with its own container swap (no allocation on any standard library); the KV
cache's persona commits use it.

Not run locally: serving-down windows on the M5 are on hold (shutdown custody); CI (Windows static,
Ubuntu, macOS) is the verification for this commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…ata has no node containers

CONTINUUM-ENGINE 4.14, the flash tier (direction agreed by Codex for an isolated prototype, not layout sign-off):
llama_kv_cells derived `used` (std::set) and `seq_pos` (std::map per sequence) from its cells. A flash generation
cannot hold node containers, and rebuilding them on load is the recomputation the design forbids. Now:
- llama_kv_used: a bitmap over the cell rows with its count and extrema (bounded by the stream size, never a
  position); insert/erase O(1), an extremum leaving scans forward/back to the next occupied cell.
- llama_kv_seq_pos: each sequence's positions sorted with their counts, its own array (a change to one sequence
  never moves another's). Exact on its O(1) paths (append at her newest position, rollback/removal of it); any other
  change (removal inside the range, a shift, a division that merges positions) marks it stale, and the next query
  recomputes it once from the cells (scan, sort, merge of equal positions), never cell by cell (a front discard
  cell by cell would be quadratic in a flat array).
- swap stays allocation-free (vector swaps).

test-kv-cell-index: 8 seeds x 20000 random cache operations (appends with repeats, shared sequences, removals,
seq_rm/seq_keep, shifts below zero, divisions that merge) against a reference with the replaced std::set/std::map,
compared after every step; `--cost` times the same append/discard/shift workload on both at 4k/32k/100k cells.

Not yet: the flash generation itself (typed header, owner identity, checksums, one fenced generation with recurrent,
draft, sampler and genome), and the cost receipts (need a serving-down window on the M5 to build).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…ry query after it recompute nothing

Codex's review of 2d54d48: a recomputation caused by a genuine change (a division that merges positions, a shift,
an inner removal) is new work, but it is never deferred across a freeze. persona_check_save (the fallible reserve
phase, where allocation may fail and leave her whole) now calls llama_kv_cells::settle_all, so her blocks leave a
stream with every index valid and the commit, the bind and any later query perform no scan and no sort. A failed
settle leaves the index stale (its flag is cleared last), never half-written.

test-kv-cell-index: freeze_then_bind divides positions so they merge and removes one inside the range, settles as
the save does, binds her object into a fresh stream by swap, and checks the bound object answers every query as the
node-container reference does with zero recomputations (settles() counts them). The --cost read already charges
the deferred recomputation: its extrema are read after each phase.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply and others added 6 commits November 17, 2026 09:28
…cells, with allocation counts

Codex's review of 347a13a: the timing reference kept each cell's sequences in a std::set, while the previous
llama_kv_cells used bitset membership, so the old side was charged allocations it never made. The oracle stays as
the equivalence check; the cost read now runs the same workload on kv-cells-previous.h (the class at accc9e3,
verbatim but for its name) and on the native one, and counts this binary's allocations during each.

Measured on the M5 (clang++ -O2 -Wall -Wextra -Werror, nice 19, three runs, ~16:35Z): n=4096 previous ~1.00 ms /
10240 allocations vs native ~0.54 ms / 37; n=32768 ~8.8 ms / 81920 vs ~4.2 ms / 46; n=100000 ~28.1 ms / 250000 vs
~12.85 ms / 52. The 4k slowdown reported earlier was an artifact of the simplified baseline (it skipped the previous
class's per-cell work across every sequence), not of the native indices.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…ations in a separate pass of the same workload

Codex's review of 8fe7f7d: the counter's atomic add per allocation charged the side that allocates more. M5, -O2,
nice 19, three runs ~16:41Z, timing with counting off: n=4096 previous 0.93-0.96 ms vs native 0.52-0.53; n=32768
8.47-8.64 vs 4.15-4.17; n=100000 26.8-27.8 vs 12.7-12.9. Allocations (separate pass): 10240/81920/250000 vs 37/46/52.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
… what it changed as it returns

llama-server answers /slots and /metrics on its worker thread while a decode runs (yield_to_queue), and /slots
reads kv_pos_min/kv_pos_max. The lazy index recomputed a stale sequence inside that const query, so a query
wrote the index the decode thread was changing. Now:

- the owner settles: llama_kv_cache's cell-changing operations (seq_rm, seq_cp, seq_keep, seq_add, seq_div,
  prepare, apply_ubatch, state_read) settle every stale index as they return, on their own thread; a bitset of
  stale sequences means settling visits only those;
- a query is pure: a stale index (a missed settle) is answered exactly from the cells without writing it, and
  counted (stale_queries, an atomic: the only thing a query writes), so a miss is loud in tests, never wrong;
- persona_check_save no longer settles (it is const, and every change was settled by its operation).

test-kv-cell-index: every random operation is followed by the cache's settle, after which no query is answered
from the cells; queries_never_write checks a stale query is exact, counted, and leaves the index stale.
Cost unchanged (M5, --cost): 4k 0.91 -> 0.53 ms, 32k 8.5 -> 4.2 ms, 100k 27.0 -> 13.0 ms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…ic late-arrival capacity test

/slots and /cells read the cache (kv_pos_min/kv_pos_max, llama_memory_cell_usage; this fork's additions, #92) and
SLOT_GET is answered on the queue's worker while a decode changes the cache (yield_to_queue). Now the main thread
reads them: yield_decoding reads every slot's positions and the cell usage, then yields; the yield's mutex orders
that read before the worker's, and the worker answers from what was read, never the cache. On the main thread
(not yielding) SLOT_GET reads first. All four decode/draft yields go through yield_decoding.

test_completion_unified_late_arrival_overflows: the capacity contract behind test_completion_unified's all-pass case,
made deterministic. The 40-token request is sent only after /slots shows the three 90-token requests 40+ tokens in;
12 + 4g + 3d cells exceed 256 before it can finish, so it and the batch fail with "Context size has been exceeded"
on any machine. Both Windows failures on #147 had the fourth request posted 15 and 25 ms late (d = 41, 255 cells).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply and others added 4 commits November 17, 2026 13:48
…atus

The persona move (CONTINUUM-ENGINE 4.14: raw block copies plus a swap of her cell records, two-phase, typed
refusals) was internal to llama_context, so the server could not switch personas with it and still serialized
through llama_state_seq. llama_persona is now an opaque handle to her host blocks, prepared once for the
context's memory; llama_persona_save moves a sequence out (her stream left empty) and llama_persona_load binds
her back, as the sequence she was saved from, into an empty stream. Status codes are the existing
llama_persona_move values, named by llama_persona_status_name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…ppended by one validated transaction (prototype, CONTINUUM-ENGINE 4.14)

Her token ids live in one reserved array owned with her blocks. A request appends only its
new ids: the header names persona, epoch, expected frontier and the request's 128-bit
identity; the owner validates all of it, then writes the delta into reserved capacity
(never an allocation or a copy of what she holds). The same request again returns its
receipt; the same identity with another delta is refused; past capacity is refused for
the owner to grow. Her generated tokens join the same tail as she samples them.

test-persona-tokens: three acts with generated reasoning (history == served + generated +
new), replay/changed, stale/foreign/moved/empty, no_room; measured on the M5 at -O2 with
the writes read back: a 2,048-token append onto a 100k-token history, 756-846 ns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…, not only the last request

Codex's review of 0f1acdb: a last-request receipt let a delayed retry of A after B read as
'moved', and an empty retry at the same frontier be accepted twice. Each append now carries
her request sequence (1, 2, 3 per persona and epoch); every committed append keeps its receipt
at index seq - 1. A retry of any committed sequence returns its original receipt and writes
nothing; the same sequence with another identity or delta is 'changed'; a later sequence first
is 'out_of_order'. Raw contract explicit: a null delta only with length 0 (an empty append
commits its sequence); capacity checked without overflow (SIZE_MAX is no_room).
test-persona-tokens adds delayed, duplicate, empty and reordered retries; -Wall -Wextra clean;
the M5 at -O2 with writes read back: 644-795 ns per 2,048-token append onto 100k.

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

Codex on d853768: the receipt push_back could allocate on the hot path after the delta was
written. Receipts are now a fixed array reserved at construction beside her tokens; both
reservations are checked before any write, and either running out is no_room (an empty
append consumes a receipt). Test: receipt exhaustion leaves her tokens, frontier and commits
unchanged, and a committed sequence still replays. M5 -O2, reads back: 395-608 ns per
2,048-token append onto 100k (1,773 ns once, first touch of the reserved pages).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…seam to reserve, append and read it

llama_persona now owns her llama_persona_tokens, so a save or load of her blocks carries her
token history by reference, never a copy. C API: llama_persona_reserve_tokens (her admitted
owner reserves tokens and receipts once), llama_persona_append (fixed-width header + ids read
in place, returns the receipt), llama_persona_token_ids, llama_persona_append_status_name.
The internal request struct is llama_persona_append_request (the C function owns the name).
Syntax-checked llama-context.cpp; test-persona-tokens ok.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply and others added 2 commits November 18, 2026 00:16
…econd reserve and an allocation failure are statuses

Codex on #147 at e046: persona/generation ownership. llama_persona_reserve_tokens replaced an
existing history (dropping it) and could throw bad_alloc across the C boundary; her blocks carried
sequence and layout but no owner, so blocks saved under one epoch could load under another.

- reserve_tokens: already_reserved when her history exists (it would be dropped); out_of_memory
  on allocation failure, nothing changed. Both are llama_persona_move statuses.
- save / load before a reserve: no_owner.
- A completed save stamps her blocks with her owner (persona + epoch of her token history); a load
  of blocks stamped by another persona or epoch of her returns wrong_owner before any write.
- llama_persona_owner reads the stamp (the flash tier writes it into its header next slice).

test-persona-blocks, public seam only: no_owner before a reserve, already_reserved on a second
reserve, the save stamped with exactly the reserved owner, and her next tokens byte-identical after
an owned move into the other stream. wrong_owner is reachable only once blocks outlive their
persona object (the flash tier); its check is in place and its fixture comes with that slice.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
… not stated (Codex on #147 at f3eb)

Every allocation in the test binary is counted. At a real-size history (100k tokens, 2k deltas),
after the one reserve: an accepted append, eight more, a refusal for no room, a wrong epoch, a stale
frontier and a replay together allocate nothing (g_allocations unchanged). Her capacity and
receipts are fixed at reserve; the hot path only writes.

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

Copy link
Copy Markdown
Author

Answers the two open items at e046/f3eb (head 6078f43):

  • Persona/generation ownership (b004e38): llama_persona_reserve_tokens refuses a second reserve (already_reserved, it would drop her history) and returns out_of_memory instead of throwing across the C boundary. Save/load before a reserve return no_owner. A completed save stamps her blocks with her owner (persona + epoch of her token history); a load of blocks stamped by another persona or epoch returns wrong_owner before any write. llama_persona_owner reads the stamp for the flash tier's header. Tested through the public seam in test-persona-blocks. wrong_owner is only reachable once blocks outlive their persona object (flash); its check is in place and its fixture comes with that slice.
  • Fixed capacity ($S): test-persona-tokens counts every allocation in the binary. At a 100k-token history, 13 appends, refusals (no room, wrong epoch, stale frontier) and a replay allocate nothing.

Built and run by this PR's CI; no build on the serving M5.

joelteply and others added 7 commits November 18, 2026 00:17
…ooses; the caller never numbers streams

The persona engine must not number streams (Joel: nothing is sized or numbered by the caller), but
llama_persona_load took a stream index and the public API had no way to ask which was empty.

- llama_memory_i::persona_empty_stream: the memory that owns the streams answers (KV cache: the first
  stream with no used cells, bounded by its stream count, no cell walk; hybrid: its attention cache;
  -1 when none is empty or the cache is unified).
- llama_context::persona_bind and the C seam's llama_persona_bind: place her there, or
  no_empty_stream with nothing changed; otherwise exactly load's owner and layout checks
  (persona_owner_check is shared by load and bind).

test-persona-blocks (public seam): the owned move binds into a stream the memory chose and her next
tokens are byte-identical; with both streams occupied a bind returns no_empty_stream and both
residents continue untouched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…rows it ahead of need

Joel: nothing sized at creation, it's dynamic. llama_persona_reserve_tokens took a fixed capacity
(n_tokens, n_receipts) and the tokens class held that size for life.

- llama_persona_tokens(persona, epoch) starts empty; grow(more_tokens, more_receipts) adds room
  keeping everything she holds (nothrow; false on allocation failure, unchanged).
- C seam: llama_persona_reserve_tokens(persona, id, epoch) names only her owner;
  llama_persona_grow_tokens(persona, more_tokens, more_receipts) is called by her owner between acts
  (no_owner before a reserve, out_of_memory on failure). An append on the hot path still only
  writes: it returns no_room when her owner did not grow her in time.
- Tests: every history starts unsized and is grown; a new case shows an append refused for room,
  her owner grows her, the same request lands with her history kept and her earlier commit
  replayable; the zero-allocation measurement now follows growth ahead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…rows and shrinks with her

Joel: "we don't reserve, we literally do the opposite: we grow and shrink, we switch contexts."

- llama_persona_init(ctx, persona_id, epoch) makes her owned from the start; reserve_tokens is gone,
  with the no_owner and already_reserved statuses and their checks (unreachable now).
- llama_persona_grow_tokens adds room ahead of need; llama_persona_shrink_tokens gives back the room she
  does not hold as she cools, dropping nothing. Both between acts, never inside one.
- Header and class docs say grown, not reserved.

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

Codex on #147: the native llama_context::persona_load/persona_bind took bare blocks, so a native caller could
bind another persona's state. Every move now names who it is for (llama_persona_identity): the native save
stamps the owner, the native load and bind refuse blocks stamped by anyone else before anything is written.
The public seam passes her token history's identity and no longer carries its own copy of the check.

- test-persona-blocks: native calls carry each persona's identity; a's blocks under b's identity are
  refused (wrong_owner) on the native path.
- test-persona-tokens: the expected history is built with push_back per token; GCC 14 (Ubuntu arm64)
  -Werror=stringop-overflow refused the 6-token range insert (Codex traced CI on 57812cd).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…ls are relabeled, never refused

Two execution streams must serve any number of minds: the active one decodes in one while the next binds
into the other, so a mind saved from sequence 0 has to come back as sequence 1. The bind refused that
(wrong_persona, "never retagged").

- llama_kv_cells::seq_rename relabels every cell of one sequence as another, with its position index (a
  stream holds one persona, so nothing merges); the KV load calls it after taking her cells.
- The recurrent load already builds her cell's sequence node as the bound sequence; its refusal goes too.
- test-persona-blocks: saved as sequence 0, she binds as sequence 1, answers to 1 only, and continues
  byte-identically.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
@joelteply
joelteply marked this pull request as ready for review November 18, 2026 12:48
@joelteply
joelteply merged commit 42a8db6 into codex/s4-per-mind-integration Nov 18, 2026
13 of 16 checks passed
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