Skip to content

The in-process scheduler is the persona engine: one mind decodes at a time, a turn prefills only her new tail (serving S1; stacked on #6139) - #6140

Open
joelteply wants to merge 29 commits into
canaryfrom
fable/persona-scheduler
Open

joelteply wants to merge 29 commits into
canaryfrom
fable/persona-scheduler

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Serving integration S1 for the persona engine (MODULE-ARCHITECTURE 9.4, CONTINUUM-ENGINE 4.14). Stacked on #6139 (PersonaEngine), which is stacked on #6134 (UnifiedTier). Until those merge this diff includes their commits.

What changes

  • llamacpp_scheduler.rs is deleted (776 lines). It advanced n_seq_max sequences per decode and dropped every sequence's KV when its turn ended, so every turn re-prefilled the whole prompt.
  • backends/persona_scheduler replaces it behind the same surface (Scheduler / GenerationRequest / TokenEvent). It runs one driver thread with a PersonaEngine over UnifiedTier (two streams: the active mind and the next). Turns are served one after another; a switch is stage, settle, handoff, and the previous mind parks in RAM.
  • turn::plan (persona-engine, pure, unit-tested) keys reuse on the basis (gene set) as well as the tokens. An extending prompt prefills only its tail; anything else starts her over.
  • Each Step carries its gene set. The tier applies it only when it changes, and only for the bound mind. A step at from drops what she held from there.
  • Tier::release + PersonaEngine::forget give up a one-off's blocks only after she has left the pipeline.

Not in this PR

  • Routing residents here (S2): production still decodes over llama-server.
  • Removing the n_seq_max / lane plumbing (S3).
  • Overlapping the next mind's copy-in with the active decode.
  • Paging cold minds out of RAM.

Measured

Nothing yet. This is not built locally (the M5 is serving), so CI is the first compile. A real-model scheduler run waits for a non-serving executor. Owner: Fable. Gate: ~80 tok/s sustained including switches at 4/8/16 personas.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

joelteply and others added 23 commits November 18, 2026 00:18
…gine pin moves to #147 (merged with the live engine)

PersonaBlocks owns one llama_persona: new (blocks prepared for this context's memory), reserve
(her token history, once, for a PersonaOwner), save (her state out of the context, raw), load (her
blocks into an empty stream), owner (the stamp of the last save), tokens (her history in place),
and Drop frees her. Every refusal is a typed PersonaRefusal carrying the fork's status name; the
fork validates before writing, so a refusal leaves both sides as they were.

The submodule moves from 5e4163402 (live) to 4caa55bf9: fork #147's head with 5e4163402 merged in,
so the live engine's learn-abort fix (#150) is kept. Depends on fork #147 merging; draft until then.

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

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

- PersonaBlocks::new(ctx, owner) makes her owned from the start; reserve is gone.
- shrink() beside grow(): gives back the room she does not hold as she cools, dropping nothing.
- Fork 37baf8c12: llama_persona_init(ctx, persona, epoch), llama_persona_shrink_tokens, and ownership
  enforced in the native save/load/bind (one check, no path skips it).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…er over the fork's native blocks

continuum-persona-llama: the persona engine's residency Tier on one libllama context. Two execution
streams: the active mind decodes in one while the next binds into the other; every other mind's blocks
stay in RAM exactly as she left them. A move out is the fork's native save, a move in its native bind;
both are synchronous, so the fence has landed when it exists. Each persona gets an exact 64-bit owner
stamp from this tier (a persona is 128 bits; the fork stamps 64).

Fork a88f255cc: a mind binds as whichever sequence she is bound as (her cells are relabeled), so two
streams serve any number of minds.

examples/persona_switch drives N minds through Roles (stage, handoff, copy-out, release) on a real model.

## Measured (M5, Qwen3.6-35B-A3B Q4_K_M, serving down 07:32-07:37Z, fork a88f255cc)
4,096-token history per mind, 64 decoded tokens per turn, 3 rounds:
- 4 minds:  switch p50 8.83 ms, p90 10.76 ms; decode 54.7 tok/s; sustained incl. switches 54.3 tok/s
- 8 minds:  switch p50 8.36 ms, p90  9.82 ms; decode 55.7 tok/s; sustained 55.3 tok/s
- 16 minds: switch p50 8.59 ms, p90 10.06 ms; decode 55.3 tok/s; sustained 54.9 tok/s
Live serving the same morning: KV page saves 8.7-13.1 s. Switching now costs under 1% of decode.
Not yet at the 80 tok/s gate: this harness decodes one greedy token per step with no MTP draft; the
live engine's 80 comes with the draft model, which the persona engine has to drive next.
Fork tests at a88f255cc: 6/6 persona tests passed, including a saved-as-0, bound-as-1 continuation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
… own their occupancy; switches report the rebind kind (Codex on #6134)

- A request for an older epoch than the one held is refused and leaves her blocks; a newer epoch prepares
  its blocks first and replaces the old ones only once they exist, so a refused allocation keeps custody.
- Occupancy is the two streams' own [Option<PersonaId>; 2], not a scan of every mind.
- Each bind reports Rebind::SameSequence or Rebind::OtherSequence (the fork relabels her cells over her
  span on the latter); the example splits switch timings by kind and probes a stale epoch at the end.

## Measured (M5, Qwen3.6-35B-A3B Q4_K_M, serving down 07:47-07:57Z)
- 4 / 8 / 16 minds, 4,096-token history: switch p50 8.57 / 8.57 / 8.41 ms; decode 58.0 / 57.8 / 57.5 tok/s;
  stale epoch refused and her blocks still bind, every run.
- Rebind kind at equal history: 4,096 tokens same 9.15 ms (n=8) vs other 9.07 ms (n=10, 5 minds);
  16,384 tokens same 27.80 ms (n=8, 4 minds) vs other 27.88 ms (n=10, 5 minds). The relabel walk is not
  measurable; the switch scales with the bytes copied.
- Stage, handoff and copy-out run serially before her decode here, not overlapped.

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

MODULE-ARCHITECTURE 9.4: "a shared resource is a dependency too: the engine's decode is one resource,
so the minds' decodes are ordered children of the engine, serialized by that edge." Joel, 2026-11-18:
--parallel N must be structurally impossible.

PersonaEngine (continuum-persona-engine, engine.rs) owns Roles and the tier that moves minds:
- decode(&mut self, step) hands out only the active mind and the tier she is bound in. The edge is the
  borrow: a decode inside a decode is a compile error (compile_fail doc test, E0499), and no count, lane
  or launch parameter exists to ask for two.
- stage begins her copy-in through the tier and holds her as next under its fence. When next is occupied
  or she is already here it refuses BEFORE starting a transfer, and hands her back.
- handoff binds next once her copy-in landed, then begins the previous mind's copy-out (never
  suspend-then-resume). A refused copy-out keeps her retiring in the engine's custody; retry_retire
  begins it.
- release_retired gives her back once her copy-out landed.

Tests (engine/tests.rs, a recording tier whose fences the test lands): decode reaches only the active
mind while the next streams in; the previous mind's copy-out begins after the bind and she is released
only once it lands; a handoff before the copy-in lands changes nothing; a refused stage starts no
transfer and returns her; a refused copy-out keeps her retiring until it begins.

Built and tested in CI, not on the serving M5 (rule 2). No serving change yet: serving drives this
owner over UnifiedTier (#6134) next, and the lane-launch path for our minds is deleted then.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…y, and keeps the fork's refusals

Codex on #6134 (d815ce5): UnifiedTier::new takes any live Context with streams = [None, None], and a
never-saved mind's move in marked stream 0 occupied without asking whether its sequence held state. A
tier wrapping a context already in use could therefore report a successful first bind over prior KV. And
move_in/move_out mapped the fork's typed refusals to a fixed string.

- move_in, for a mind never saved, asks the engine's own memory (memory_seq_pos_max on the stream's
  sequence) and refuses "her stream already holds another sequence's state" unless it is -1 (empty).
  The evidence is the engine's, never this tier's bookkeeping; the refusal changes nothing.
- TierRefusal carries Native: NotAsked (the tier's own precondition) or Refused { status, name } (the
  fork's llama_persona status and its name). move_in/move_out keep the fork's refusal instead of erasing
  it; the error text appends it.
- persona_switch runs the adoption scenario before its measurement: one token decoded into sequence 0
  before the tier exists; a new mind's move in is refused and sequence 0's state is unchanged; after the
  stream is cleared she binds. (Needs a real model, as the harness does; it is not a CI test.)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…another persona's or a stale epoch's blocks before the fork

Codex on #6132 (ea955a8): bind(ctx, seq) carried no expected persona or epoch. The fork's bind/load
validate a handle's blocks against that handle's own identity, which keeps blocks consistent but cannot
detect that the caller selected the wrong intact handle.

- bind(ctx, seq, expected: PersonaOwner) compares the handle's stamp (the owner its last completed save
  wrote) with the transfer's owner, persona AND epoch, and refuses BindRefusal::WrongOwner { expected,
  held } before calling the fork. The destination is untouched. A never-saved handle has no stamp and is
  refused the same way.
- The fork's own refusal stays typed as BindRefusal::Native(PersonaRefusal).
- Test only_the_expected_owner_and_epoch_bind: two intact handles at one reusable sequence (another
  persona, the same persona at a stale epoch, an unstamped handle) are each refused; the expected owner
  binds.

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

Codex on #6134 (de0e34a): move_in called hold before checking occupancy. With epoch 1 parked in RAM
and the chosen stream occupied (an adopted context), hold(epoch 2) replaced and dropped epoch 1's
blocks, and only then did move_in refuse.

- move_in decides everything before it changes anything: a stale epoch is refused; the same epoch
  rebinds from the stream she was saved from; a new mind or a newer epoch starts over, and only then is
  the stream's emptiness checked against the engine's own memory. hold (which may replace an older
  epoch's blocks) runs only after every check passed, so a refusal keeps the blocks she had.
- The bind passes the owner the transfer is for (her issued stamp at this epoch), through #6132's new
  PersonaBlocks::bind(ctx, seq, expected); a wrong or stale stamp is a refusal naming it, a fork refusal
  keeps its native status.
- tier.rs: the first doc line had error-attribute text pasted into it; restored.
- persona_switch replays the scenario before measuring: epoch 1 decodes and parks; another sequence's
  state lands on her stream; epoch 2 is refused there; the stream is cleared; epoch 1 binds back at the
  position she left. (Real model, so not CI. Byte-identical continuation after a bind is the fork's
  test-persona-blocks.)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…al.native, #6134)

#6134 gives TierRefusal a `native` field so a fork refusal keeps its status. The engine's own refusal
(a copy-out the pipeline would not begin) and the test tier's refusal are preconditions, not backend
answers: Native::NotAsked. Merges fable/unified-tier so #6139 builds on #6134.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…lds a switch until it lands

Codex on #6139 (cb57325): decode handed the caller &mut T. Through UnifiedTier::context() the
callback could decode a batch under another sequence id or call tier.begin directly, bypassing the
binding; and the Rust borrow ended at callback return while a launched GPU decode could still be in
flight.

- residency::Execute (new): a tier that runs the bound mind's decode. submit(persona, epoch, work)
  takes her tokens, never a sequence id, and returns a Completion the engine holds.
- PersonaEngine: decode(step) is gone. submit(work) asks the tier for the active mind only, refuses
  while her previous step has not landed (one decode in flight), and handoff is refused with
  DecodeInFlight until it has, changing nothing. stage() still runs while she decodes, so the next
  mind's copy-in progresses beside it. active_mut() gives only her own state; tier() is read-only.
- UnifiedTier: implements Execute (Step { tokens, from, logits_at_end } decoded on her bound stream,
  epoch checked; libllama's decode returns once outputs are readable, so Decoded is complete).
  context() is removed; logits_ith() and position_of() report read-only; raw_context() exists only
  under the test-fixtures feature, for custody replays that must put foreign state on a stream.
- residency::Native::Reported(message) keeps a backend refusal that has a message and no status.
- persona_switch runs through PersonaEngine (stage, handoff, release, submit) and requires
  test-fixtures for its replays.
- Tests: a step runs only for the active mind and one at a time; a handoff waits for a delayed decode
  completion while the next mind's copy-in is begun and landed, then binds next. The compile_fail test
  now covers holding her state across a submit.

Not built locally (the M5 is serving); CI is the first compile.

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

Codex on #6139 (80bc49c): UnifiedTier::Decoded was complete by construction, but Context::decode
reaches llama_decode only, and libllama synchronizes on result retrieval, so a submit (above all with
logits_at_end = false) can return while the device still runs the graph.

- llama: Context::synchronize() wraps llama_synchronize.
- residency::Execute gains settle(): wait until every submitted step finished on the device. The
  engine's settle() calls it; handoff still refuses while the decode is not landed.
- UnifiedTier: Decoded carries a landed flag the tier sets only when the device is known to be done:
  on settle() (llama_synchronize), or on logits_ith() (llama_get_logits_ith synchronizes). Her save
  (move out) settles first, so it never reads cells a decode is still writing.
- The handoff test now lands the decode through the tier's settle() (its attestation), not by hand.
- persona_switch settles after the replay's logits-free decode before her save.

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

The persona scheduler's first decision for every turn (S1 of the serving integration): her token
history is the engine's, so a prompt that extends what her blocks hold, under the same basis (model,
adapter set and scales, her epoch, native media identity; Codex), prefills only the new tail.
Anything else restarts her at a newer epoch so stale blocks are never decoded against. A prompt that
adds nothing re-decodes her last token, since sampling needs its logits.

Pure planning in turn.rs, unit-tested without a model: tail-only prefill, the re-decoded last token,
diverging/shorter/empty/nothing-held restarts, and the same tokens under another model, adapter set,
epoch or media identity restart.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
… time, and a turn prefills only her new tail

Serving integration S1 (MODULE-ARCHITECTURE 9.4, CONTINUUM-ENGINE 4.14). llamacpp_scheduler.rs (776
lines) advanced n_seq_max sequences per decode and dropped every sequence's KV when its turn ended,
so each turn re-prefilled the whole prompt. It is deleted. backends/persona_scheduler takes its place
behind the same surface (Scheduler / GenerationRequest / TokenEvent), so LlamaCppBackend changes only
where it spawns it:

- one driver thread owns the context and a PersonaEngine over UnifiedTier (two streams: the active
  mind and the next). Turns are served one after another; a switch is stage, settle, handoff, and the
  previous mind parks in the RAM tier (a one-off is forgotten).
- each persona keeps her blocks between turns. turn::plan decides the prefill from what her blocks
  hold under the same basis (gene set; the model is the context's own; no native media on this path):
  an extending prompt prefills only its tail, anything else starts her over at position 0.
- each Step carries its gene set; the tier applies it only when it differs from the set on the
  context, and only for the bound mind. A step at `from` drops whatever she held from there, so her
  stream never holds two tokens at one position (a re-decoded last token, a restart, a failed turn's
  partial tail).
- engine: Tier::release + PersonaEngine::forget give up a one-off's blocks only after she left the
  pipeline (tested: refused while active or retiring, the tier asked once after).
- the backend sizes the context as per-mind window x STREAMS. The launch's n_seq_max no longer
  drives decode; its plumbing (with_n_seq_max, batching_probe, LlamaCppLaunch.n_seq_max, profile
  lanes) is removed with the lanes in S3.

Not yet: the next mind's copy-in overlapping the active decode, cold minds paging out of RAM, and
routing residents here (S2; production still decodes over llama-server). Not built locally (the M5
is serving); CI is the first compile. A real-model run of the scheduler waits for a non-serving
executor.

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

# Conflicts:
#	core/vendor/LLAMA_CPP_PIN
#	core/vendor/llama.cpp
joelteply and others added 4 commits November 18, 2026 11:44
… MLX scaffold goes

Ratchets on #6140: three unwrap/unwrap_or sites in driver.rs become typed (a missing persona is a
one-off, a parked miss is a new mind by match, the turn result is a typed TurnError), and the one
saturation keeps its same-line reason. backends/mod.rs carried the tree's only OS gate there, for a
101-line phase-A MLX scaffold nothing calls; it and its two empty features are deleted. The doc-only
edits to prompt_assembly.rs and concurrent_streams_test.rs are reverted so their old sites stay out
of this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…hold, the test tier releases

CI on d2c3d82: persona-llama failed to build (Step derived Debug/PartialEq/Eq while carrying its
genes, Arc<[(Arc<LoraAdapter>, f32)]>, which can have none of them; nothing compared or printed a
Step, so the derives go). persona-engine's pipeline TestTier lacked Tier::release. The ratchets rose
by one each: Scheduler::spawn/enqueue now refuse with SchedulerError {Spawn(io), Closed} instead of
a String (the backend's OnceLock keeps the typed refusal, no clone in argument position), and the
turn's elapsed_ms saturates through Duration arithmetic instead of a u64::MAX sentinel.

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

add/add conflicts in the five persona files and the content conflict in ci-change-scope.test.cjs
resolve to this branch's side. Verified: canary's persona files equal #6139's reviewed head
efa6150; every file this PR changes equals 997e30a; no other file differs from canary; the
only Cargo.lock difference is this PR's own two persona-engine dependencies.

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

@joelteply joelteply left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Source verdict for 17c208c: changes requested. The contents of the changed paths match the earlier 5090 replay. Two driver paths still need correction before integration.

  1. Driver::serve samples after every prefill chunk. The native sampler accepts each sampled token. For a multi-chunk prompt, discarded tokens advance the grammar, repetition history and RNG before the first visible token. Request logits only at the final prompt position, and settle intermediate submissions through the completion owner. Check grammar and seeded output across different prefill batch sizes.
  2. Driver::switch_to returns after a failed retiring save even though handoff has already changed the active mind. Subsequent requests skip recovery or try to stage into occupied streams. Recover outstanding stage/retire state through the engine before staging another unit. Replay a single outgoing-save refusal followed by alternating turns and verify both histories and ownership.

…fused retirement before any switch

Codex on #6140 at 17c208c, two defects the happy-path GPU replay did not exercise:

- Driver::serve sampled every prefill chunk and kept only the last. The sampler accepts what it
  samples, so a long prompt advanced her grammar, repeat penalties and RNG on phantom output.
  Earlier chunks now request no logits and are settled (UnifiedTier::settle synchronizes and marks
  the step landed); only the final prompt position is sampled.
- Driver::switch_to could not recover a refused copy-out: handoff had already bound next, the old
  mind stayed retiring, and the next turn skipped the retirement for an active id or staged into an
  occupied tier. PersonaEngine::finish_retirement now retries her copy-out and gives her back once it
  landed (RetireError when refused or still moving, she stays in custody). The driver finishes any
  retirement before it stages and again after the handoff; a CopyOut refusal during the handoff
  leaves next bound and is retried, never skipped.

Test: a_refused_copy_out_is_finished_before_the_next_switch_and_given_back_once (refused, then begun
and not landed, then given back exactly once, then A/B/A holds one of each).

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 20:44
joelteply added a commit that referenced this pull request Nov 18, 2026
…Codex's BigMama replay)

ContextParams::default() pools (Mean, for embeddings); a reply trains on per-token logits, and native
code refused only at the first labelled step. begin now reads llama_pooling_type and refuses with
step "context" (the admission handed back) unless it is None. The persona scheduler's context
already sets PoolingType::None (driver.rs:154 on #6140).

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 18, 2026
…ing L1) (#6148)

* llama: Learner over the fork's resumable llama_opt_learn_* (in-process learning L1, no policy)

A reply trains on one live sequence of a serving context, one chunk per step, then restores her
served tail under her stable set. The run owns its admission and optimizer parameters in one boxed
binding the native callbacks reach, from shadow selection until a confirmed restoration, and hands
the admission back either way (Finished::Learned / Failed, Refused before it began). finish() is
explicit and fallible (drain, then step until restored); dropping an unfinished run drains it and
records the custody loss on its Learner, which refuses the next reply until the owner takes it.
ReplyAdmission: optimizer_buffer (an increment, exact aligned size) and workspace (validates a lease
already held, never takes one, so a repeated measurement is never charged twice). Typed refusals in
Rust; buffer-type names and bools only at the FFI boundary; a panicking admission refuses instead of
unwinding into native code. Design: docs/architecture/IN-PROCESS-LEARNING.md (#6147).

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

* llama learn: the whole-window horizon is llama.h's 0 at the boundary, named, never a map_or (unknown_as_value 216 -> 215)

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

* llama learn: the context owns the callback holder; a failure is terminal and blocks until fenced (Codex on #6148)

- Native code keeps the callback pointers past a reply (llama-context-opt.cpp :192-193, :275-276,
  :330-331, :365-366), so ONE CallbackHolder lives on Context (declared after ptr, freed after
  llama_free). A reply places its admission there and takes it back; an empty holder refuses.
- Lengths and the result are validated before llama_opt_init.
- RunState {Running, Restored, Failed(refusal)}: a failed step stays failed; step() never calls
  native past a terminal status; finish() returns Failed and blocks the learner.
- Lost custody keeps a dropped run's admission (bytes retained); reading it never clears it; only
  Learner::fence (memory_seq_rm of the sequence) does, handing that admission back.
- Tests: failure-after-step through later steps and finish, terminal restoration, horizon encoding.

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

* llama learn: quarantine, shadow and model live on the Context; recovery proves native release (Codex on #6148)

- The quarantine lives in the context's CallbackHolder, not the temporary Learner: a new Learner on
  the same context is refused while it holds, and the failed run's admission (bytes retained)
  stays in it. Finished::Failed no longer hands the admission back.
- Learner::recover() lifts it only after llama_opt_release_workspace (workspace replaced) and
  llama_opt_release(shadow) (no optimizer references it) both succeed, then hands back the held
  admission. It no longer clears the sequence: memory_seq_rm proved nothing about optimizer memory
  and destroyed recoverable state; the owner restores her sequence from its own preserved state.
- The trained shadow is an Arc<LoraAdapter> the holder keeps until a release proves no optimizer
  references it; the model is the context's own (Context::model), not an independent reference.
- Test: a quarantine keeps the failed run's admission and the holder admits nothing.

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

* llama learn: quarantine_after borrows the refusal (contract_shape 2188 -> 2187: no clone passed into a call)

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

* llama learn: every shadow, with its own optimizer lease, retained on the context until a confirmed release (Codex on #6148)

Native code keeps one optimizer per adapter across shadow switches (llama-context-opt.cpp
opt_minds), so the holder kept only the current Arc and a switch or a refused selection could drop
an adapter its optimizer still references. Now:
- OptimizerLease (per shadow, its buffers' increments) is split from ReplyAdmission (per reply,
  workspace lease validation): optimizer residency is never charged to, or released with, a reply.
- Learner::retain_shadow(Arc<LoraAdapter>, lease) keeps the adapter and its lease in the context's
  Shadows registry; begin() refuses a shadow not retained and only marks it selected;
  release_shadow() hands the lease back only after llama_opt_release confirms no optimizer
  references the adapter. recover() releases the workspace only.
- Test: A -> B -> A and a refused B selection keep both shadows and A's leased bytes; only a
  release takes one out.

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

* llama learn: a restored reply is Learned only when her shadow's own count rose (Codex on #6148)

A begin then an immediate finish drains before any gradient, and a confirmed restoration was
returned as Learned with zero committed updates. finish now reads llama_opt_shadow_steps for her
shadow before begin and after restoration, and llama_opt_shadow_quarantined (as
server-context-learn.inc:582-589 does):
- Learned { steps: NonZeroU64, loss } only for actual commits (a drain after a commit keeps them);
- Unchanged when nothing committed, with no loss;
- Uncertain { steps } when native code marks the shadow's effects uncertain.

Recovery order made explicit: opt_release_workspace refuses while any shadow keeps an optimizer
(opt_configured), so recover() refuses with the retained count, before any native call and keeping
the quarantine and every retained shadow and lease, until each is released through release_shadow.

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

* llama learn: needs_gradient takes &mut self, as Context::as_ptr does (E0596, Codex on #6148)

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

* llama learn: begin refuses a pooled context before any native state (Codex's BigMama replay)

ContextParams::default() pools (Mean, for embeddings); a reply trains on per-token logits, and native
code refused only at the first labelled step. begin now reads llama_pooling_type and refuses with
step "context" (the admission handed back) unless it is None. The persona scheduler's context
already sets PoolingType::None (driver.rs:154 on #6140).

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]>
joelteply added a commit that referenced this pull request Nov 18, 2026
…, never increments (L2 accounting; stacked on #6148) (#6149)

* llama: Learner over the fork's resumable llama_opt_learn_* (in-process learning L1, no policy)

A reply trains on one live sequence of a serving context, one chunk per step, then restores her
served tail under her stable set. The run owns its admission and optimizer parameters in one boxed
binding the native callbacks reach, from shadow selection until a confirmed restoration, and hands
the admission back either way (Finished::Learned / Failed, Refused before it began). finish() is
explicit and fallible (drain, then step until restored); dropping an unfinished run drains it and
records the custody loss on its Learner, which refuses the next reply until the owner takes it.
ReplyAdmission: optimizer_buffer (an increment, exact aligned size) and workspace (validates a lease
already held, never takes one, so a repeated measurement is never charged twice). Typed refusals in
Rust; buffer-type names and bools only at the FFI boundary; a panicking admission refuses instead of
unwinding into native code. Design: docs/architecture/IN-PROCESS-LEARNING.md (#6147).

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

* llama learn: the whole-window horizon is llama.h's 0 at the boundary, named, never a map_or (unknown_as_value 216 -> 215)

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

* llama learn: the context owns the callback holder; a failure is terminal and blocks until fenced (Codex on #6148)

- Native code keeps the callback pointers past a reply (llama-context-opt.cpp :192-193, :275-276,
  :330-331, :365-366), so ONE CallbackHolder lives on Context (declared after ptr, freed after
  llama_free). A reply places its admission there and takes it back; an empty holder refuses.
- Lengths and the result are validated before llama_opt_init.
- RunState {Running, Restored, Failed(refusal)}: a failed step stays failed; step() never calls
  native past a terminal status; finish() returns Failed and blocks the learner.
- Lost custody keeps a dropped run's admission (bytes retained); reading it never clears it; only
  Learner::fence (memory_seq_rm of the sequence) does, handing that admission back.
- Tests: failure-after-step through later steps and finish, terminal restoration, horizon encoding.

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

* llama learn: quarantine, shadow and model live on the Context; recovery proves native release (Codex on #6148)

- The quarantine lives in the context's CallbackHolder, not the temporary Learner: a new Learner on
  the same context is refused while it holds, and the failed run's admission (bytes retained)
  stays in it. Finished::Failed no longer hands the admission back.
- Learner::recover() lifts it only after llama_opt_release_workspace (workspace replaced) and
  llama_opt_release(shadow) (no optimizer references it) both succeed, then hands back the held
  admission. It no longer clears the sequence: memory_seq_rm proved nothing about optimizer memory
  and destroyed recoverable state; the owner restores her sequence from its own preserved state.
- The trained shadow is an Arc<LoraAdapter> the holder keeps until a release proves no optimizer
  references it; the model is the context's own (Context::model), not an independent reference.
- Test: a quarantine keeps the failed run's admission and the holder admits nothing.

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

* llama learn: quarantine_after borrows the refusal (contract_shape 2188 -> 2187: no clone passed into a call)

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

* llama learn: every shadow, with its own optimizer lease, retained on the context until a confirmed release (Codex on #6148)

Native code keeps one optimizer per adapter across shadow switches (llama-context-opt.cpp
opt_minds), so the holder kept only the current Arc and a switch or a refused selection could drop
an adapter its optimizer still references. Now:
- OptimizerLease (per shadow, its buffers' increments) is split from ReplyAdmission (per reply,
  workspace lease validation): optimizer residency is never charged to, or released with, a reply.
- Learner::retain_shadow(Arc<LoraAdapter>, lease) keeps the adapter and its lease in the context's
  Shadows registry; begin() refuses a shadow not retained and only marks it selected;
  release_shadow() hands the lease back only after llama_opt_release confirms no optimizer
  references the adapter. recover() releases the workspace only.
- Test: A -> B -> A and a refused B selection keep both shadows and A's leased bytes; only a
  release takes one out.

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

* llama learn: a restored reply is Learned only when her shadow's own count rose (Codex on #6148)

A begin then an immediate finish drains before any gradient, and a confirmed restoration was
returned as Learned with zero committed updates. finish now reads llama_opt_shadow_steps for her
shadow before begin and after restoration, and llama_opt_shadow_quarantined (as
server-context-learn.inc:582-589 does):
- Learned { steps: NonZeroU64, loss } only for actual commits (a drain after a commit keeps them);
- Unchanged when nothing committed, with no loss;
- Uncertain { steps } when native code marks the shadow's effects uncertain.

Recovery order made explicit: opt_release_workspace refuses while any shadow keeps an optimizer
(opt_configured), so recover() refuses with the retained count, before any native call and keeping
the quarantine and every retained shadow and lease, until each is released through release_shadow.

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

* llama learn: needs_gradient takes &mut self, as Context::as_ptr does (E0596, Codex on #6148)

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

* llama learn: begin refuses a pooled context before any native state (Codex's BigMama replay)

ContextParams::default() pools (Mean, for embeddings); a reply trains on per-token logits, and native
code refused only at the first labelled step. begin now reads llama_pooling_type and refuses with
step "context" (the admission handed back) unless it is None. The persona scheduler's context
already sets PoolingType::None (driver.rs:154 on #6140).

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

* llama learn: a shadow's optimizer buffers are slots native code sizes, never increments (Codex's A/B/A trace)

ggml_opt_static_allocation_allowed (ggml-opt.cpp:558-565 at the pin) passes the WHOLE size of the
buffer it is about to allocate, and the 32-byte optimizer_host buffer is freed (:627) and asked
for again (:908) on every init, so the old increment contract charged a revisited shadow again
for memory that was already gone.

New safe/optimizer_slots.rs (pure, tested without a model):
- Role::{Static, Host}, parsed from the two native names; any other name is refused.
- Slot { role, device: BufferType }: the boundary type. BufferType gains device() and is_host().
- OptimizerLease { admit(slot, bytes), release(slot, bytes) }: told growth and proven frees.
- Slots per retained shadow: a request means 'this slot is about to be N'; the growth is
  admitted before native allocates, a shrink is released, and a revisit at the same size charges
  nothing. A refused host request releases the host bytes (already freed). A refusal later in the
  same init rolls back that init's earlier charges: every request precedes every allocation
  (:906-908, then :912/:921).
- learn.rs: the callback charges the selected shadow's slots; begin settles them after
  llama_opt_init; release_shadow releases every slot once llama_opt_release confirms.

Tests: a revisit at the same sizes charges nothing new (270368 + 32 once); a host refusal rolls
back the same init's static charge; a refused host revisit releases the freed host and keeps the
static; a shrink releases the difference and a release frees every slot; only the two native
names have a role.

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

* llama learn: restore learn.rs's first doc line (a bad multi-line edit pasted a test into it; Codex on #6149)

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

* llama learn: optimizer charges are held until native code's own buffers prove what survived (Codex on #6149)

Requests come from llama_opt_init and from the graph builds inside learn steps, so inferring which
requests form one group (the settle/rollback in the last head) was fragile. Now:
- Slots::ask admits only growth past what is charged and holds it; nothing is released on
  inference.
- After each optimizer operation (llama_opt_init, every learn step and graph step, and a confirmed
  release_shadow), never on ordinary decode, the Learner visits llama_opt_visit_memory on the
  context's owner and reconciles every retained shadow's slots to the bytes native code owns
  (ggml_opt_visit_owned_buffers names only optimizer_static and optimizer_host). Charged but not
  resident is released.
- Resident but never admitted, an unknown kind, or bytes owned for a shadow the context does not
  retain is an accounting defect: Learner::accounting() names it and begin() refuses until an
  owner looks.
- settle, the per-init 'before' journal and the inferred rollback are deleted.

Tests: the revisit charges nothing new; a refused group is released only when the visit proves
nothing survived; a refused host revisit releases the freed host and keeps the static; a proven
shrink releases the difference; resident bytes never admitted are a defect; a visit attributes by
shadow and role or names the defect.

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

* llama learn: a release never exceeds what was admitted; an accounting defect stops the run and is never Learned (Codex on #6149 at 69c07dd)

- Slots::reconcile kept native excess in the charge (charged = resident), so admit 32, observe 64,
  free to 0 released 64 for a lease granted 32. Now the charge stays what was admitted; bytes
  resident beyond it are reported as Unadmitted on each visit and never released, through
  reconcile and release_all alike.
- An accounting defect found after a learn step or graph step drains the reply (no further
  gradient; only the restoration runs), and finish reports Uncertain, never Learned, while
  accounting is untrusted.
- The visitor no longer reads a size past u64 as u64::MAX (unknown_as_value): it is an
  unattributable buffer, so an accounting defect.
- contract_shape: the visitor's seven parameters are llama.cpp's fixed callback, so one existing
  site is retired to offset it: mtmd eval_media's text, bytes and kind travel together as one Media.

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]>
joelteply added a commit that referenced this pull request Nov 23, 2026
…, hot tier and disk relief as components, health measured on one slot (#6213)

* core/llama: a safe PersonaBlocks over the fork's persona seam; the engine pin moves to #147 (merged with the live engine)

PersonaBlocks owns one llama_persona: new (blocks prepared for this context's memory), reserve
(her token history, once, for a PersonaOwner), save (her state out of the context, raw), load (her
blocks into an empty stream), owner (the stamp of the last save), tokens (her history in place),
and Drop frees her. Every refusal is a typed PersonaRefusal carrying the fork's status name; the
fork validates before writing, so a refusal leaves both sides as they were.

The submodule moves from 5e4163402 (live) to 4caa55bf9: fork #147's head with 5e4163402 merged in,
so the live engine's learn-abort fix (#150) is kept. Depends on fork #147 merging; draft until then.

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

* Cargo.lock: core/llama depends on thiserror 2

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

* PersonaBlocks::bind replaces load(stream): the memory chooses the stream; pin fork #147 at bc9c9ae13

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

* LLAMA_CPP_PIN records the move to fork #147 (persona seam with bind), deliberately

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

* PersonaBlocks: reserve names only her owner, grow adds room ahead of need; pin fork #147 at 53609c556

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

* PersonaBlocks is made with her owner and grows and shrinks; pin fork 37baf8c12

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

- PersonaBlocks::new(ctx, owner) makes her owned from the start; reserve is gone.
- shrink() beside grow(): gives back the room she does not hold as she cools, dropping nothing.
- Fork 37baf8c12: llama_persona_init(ctx, persona, epoch), llama_persona_shrink_tokens, and ownership
  enforced in the native save/load/bind (one check, no path skips it).

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

* The persona engine switches minds on the real 35B in ~9 ms: UnifiedTier over the fork's native blocks

continuum-persona-llama: the persona engine's residency Tier on one libllama context. Two execution
streams: the active mind decodes in one while the next binds into the other; every other mind's blocks
stay in RAM exactly as she left them. A move out is the fork's native save, a move in its native bind;
both are synchronous, so the fence has landed when it exists. Each persona gets an exact 64-bit owner
stamp from this tier (a persona is 128 bits; the fork stamps 64).

Fork a88f255cc: a mind binds as whichever sequence she is bound as (her cells are relabeled), so two
streams serve any number of minds.

examples/persona_switch drives N minds through Roles (stage, handoff, copy-out, release) on a real model.

## Measured (M5, Qwen3.6-35B-A3B Q4_K_M, serving down 07:32-07:37Z, fork a88f255cc)
4,096-token history per mind, 64 decoded tokens per turn, 3 rounds:
- 4 minds:  switch p50 8.83 ms, p90 10.76 ms; decode 54.7 tok/s; sustained incl. switches 54.3 tok/s
- 8 minds:  switch p50 8.36 ms, p90  9.82 ms; decode 55.7 tok/s; sustained 55.3 tok/s
- 16 minds: switch p50 8.59 ms, p90 10.06 ms; decode 55.3 tok/s; sustained 54.9 tok/s
Live serving the same morning: KV page saves 8.7-13.1 s. Switching now costs under 1% of decode.
Not yet at the 80 tok/s gate: this harness decodes one greedy token per step with no MTP draft; the
live engine's 80 comes with the draft model, which the persona engine has to drive next.
Fork tests at a88f255cc: 6/6 persona tests passed, including a saved-as-0, bound-as-1 continuation.

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

* UnifiedTier keeps a mind's custody on stale or failed epochs; streams own their occupancy; switches report the rebind kind (Codex on #6134)

- A request for an older epoch than the one held is refused and leaves her blocks; a newer epoch prepares
  its blocks first and replaces the old ones only once they exist, so a refused allocation keeps custody.
- Occupancy is the two streams' own [Option<PersonaId>; 2], not a scan of every mind.
- Each bind reports Rebind::SameSequence or Rebind::OtherSequence (the fork relabels her cells over her
  span on the latter); the example splits switch timings by kind and probes a stale epoch at the end.

## Measured (M5, Qwen3.6-35B-A3B Q4_K_M, serving down 07:47-07:57Z)
- 4 / 8 / 16 minds, 4,096-token history: switch p50 8.57 / 8.57 / 8.41 ms; decode 58.0 / 57.8 / 57.5 tok/s;
  stale epoch refused and her blocks still bind, every run.
- Rebind kind at equal history: 4,096 tokens same 9.15 ms (n=8) vs other 9.07 ms (n=10, 5 minds);
  16,384 tokens same 27.80 ms (n=8, 4 minds) vs other 27.88 ms (n=10, 5 minds). The relabel walk is not
  measurable; the switch scales with the bytes copied.
- Stage, handoff and copy-out run serially before her decode here, not overlapped.

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

* Test CI dependency selection for the persona llama adapter

* The persona engine owns the one decode: a second decode beside it does not compile

MODULE-ARCHITECTURE 9.4: "a shared resource is a dependency too: the engine's decode is one resource,
so the minds' decodes are ordered children of the engine, serialized by that edge." Joel, 2026-11-18:
--parallel N must be structurally impossible.

PersonaEngine (continuum-persona-engine, engine.rs) owns Roles and the tier that moves minds:
- decode(&mut self, step) hands out only the active mind and the tier she is bound in. The edge is the
  borrow: a decode inside a decode is a compile error (compile_fail doc test, E0499), and no count, lane
  or launch parameter exists to ask for two.
- stage begins her copy-in through the tier and holds her as next under its fence. When next is occupied
  or she is already here it refuses BEFORE starting a transfer, and hands her back.
- handoff binds next once her copy-in landed, then begins the previous mind's copy-out (never
  suspend-then-resume). A refused copy-out keeps her retiring in the engine's custody; retry_retire
  begins it.
- release_retired gives her back once her copy-out landed.

Tests (engine/tests.rs, a recording tier whose fences the test lands): decode reaches only the active
mind while the next streams in; the previous mind's copy-out begins after the bind and she is released
only once it lands; a handoff before the copy-in lands changes nothing; a refused stage starts no
transfer and returns her; a refused copy-out keeps her retiring until it begins.

Built and tested in CI, not on the serving M5 (rule 2). No serving change yet: serving drives this
owner over UnifiedTier (#6134) next, and the lane-launch path for our minds is deleted then.

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

* UnifiedTier binds a new mind only on a stream the engine reports empty, and keeps the fork's refusals

Codex on #6134 (d815ce502): UnifiedTier::new takes any live Context with streams = [None, None], and a
never-saved mind's move in marked stream 0 occupied without asking whether its sequence held state. A
tier wrapping a context already in use could therefore report a successful first bind over prior KV. And
move_in/move_out mapped the fork's typed refusals to a fixed string.

- move_in, for a mind never saved, asks the engine's own memory (memory_seq_pos_max on the stream's
  sequence) and refuses "her stream already holds another sequence's state" unless it is -1 (empty).
  The evidence is the engine's, never this tier's bookkeeping; the refusal changes nothing.
- TierRefusal carries Native: NotAsked (the tier's own precondition) or Refused { status, name } (the
  fork's llama_persona status and its name). move_in/move_out keep the fork's refusal instead of erasing
  it; the error text appends it.
- persona_switch runs the adoption scenario before its measurement: one token decoded into sequence 0
  before the tier exists; a new mind's move in is refused and sequence 0's state is unchanged; after the
  stream is cleared she binds. (Needs a real model, as the harness does; it is not a CI test.)

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

* PersonaBlocks::bind takes the owner the transfer is for, and refuses another persona's or a stale epoch's blocks before the fork

Codex on #6132 (ea955a81a): bind(ctx, seq) carried no expected persona or epoch. The fork's bind/load
validate a handle's blocks against that handle's own identity, which keeps blocks consistent but cannot
detect that the caller selected the wrong intact handle.

- bind(ctx, seq, expected: PersonaOwner) compares the handle's stamp (the owner its last completed save
  wrote) with the transfer's owner, persona AND epoch, and refuses BindRefusal::WrongOwner { expected,
  held } before calling the fork. The destination is untouched. A never-saved handle has no stamp and is
  refused the same way.
- The fork's own refusal stays typed as BindRefusal::Native(PersonaRefusal).
- Test only_the_expected_owner_and_epoch_bind: two intact handles at one reusable sequence (another
  persona, the same persona at a stale epoch, an unstamped handle) are each refused; the expected owner
  binds.

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

* UnifiedTier checks every move before it replaces her blocks; binds name her owner and epoch

Codex on #6134 (de0e34a97): move_in called hold before checking occupancy. With epoch 1 parked in RAM
and the chosen stream occupied (an adopted context), hold(epoch 2) replaced and dropped epoch 1's
blocks, and only then did move_in refuse.

- move_in decides everything before it changes anything: a stale epoch is refused; the same epoch
  rebinds from the stream she was saved from; a new mind or a newer epoch starts over, and only then is
  the stream's emptiness checked against the engine's own memory. hold (which may replace an older
  epoch's blocks) runs only after every check passed, so a refusal keeps the blocks she had.
- The bind passes the owner the transfer is for (her issued stamp at this epoch), through #6132's new
  PersonaBlocks::bind(ctx, seq, expected); a wrong or stale stamp is a refusal naming it, a fork refusal
  keeps its native status.
- tier.rs: the first doc line had error-attribute text pasted into it; restored.
- persona_switch replays the scenario before measuring: epoch 1 decodes and parks; another sequence's
  state lands on her stream; epoch 2 is refused there; the stream is cleared; epoch 1 binds back at the
  position she left. (Real model, so not CI. Byte-identical continuation after a bind is the fork's
  test-persona-blocks.)

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

* PersonaEngine's own refusals say the backend was not asked (TierRefusal.native, #6134)

#6134 gives TierRefusal a `native` field so a fork refusal keeps its status. The engine's own refusal
(a copy-out the pipeline would not begin) and the test tier's refusal are preconditions, not backend
answers: Native::NotAsked. Merges fable/unified-tier so #6139 builds on #6134.

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

* PersonaEngine submits the bound mind's decode through the tier and holds a switch until it lands

Codex on #6139 (cb5732506): decode handed the caller &mut T. Through UnifiedTier::context() the
callback could decode a batch under another sequence id or call tier.begin directly, bypassing the
binding; and the Rust borrow ended at callback return while a launched GPU decode could still be in
flight.

- residency::Execute (new): a tier that runs the bound mind's decode. submit(persona, epoch, work)
  takes her tokens, never a sequence id, and returns a Completion the engine holds.
- PersonaEngine: decode(step) is gone. submit(work) asks the tier for the active mind only, refuses
  while her previous step has not landed (one decode in flight), and handoff is refused with
  DecodeInFlight until it has, changing nothing. stage() still runs while she decodes, so the next
  mind's copy-in progresses beside it. active_mut() gives only her own state; tier() is read-only.
- UnifiedTier: implements Execute (Step { tokens, from, logits_at_end } decoded on her bound stream,
  epoch checked; libllama's decode returns once outputs are readable, so Decoded is complete).
  context() is removed; logits_ith() and position_of() report read-only; raw_context() exists only
  under the test-fixtures feature, for custody replays that must put foreign state on a stream.
- residency::Native::Reported(message) keeps a backend refusal that has a message and no status.
- persona_switch runs through PersonaEngine (stage, handoff, release, submit) and requires
  test-fixtures for its replays.
- Tests: a step runs only for the active mind and one at a time; a handoff waits for a delayed decode
  completion while the next mind's copy-in is begun and landed, then binds next. The compile_fail test
  now covers holding her state across a submit.

Not built locally (the M5 is serving); CI is the first compile.

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

* A decode reports landed only when the device is known to have finished it

Codex on #6139 (80bc49c17): UnifiedTier::Decoded was complete by construction, but Context::decode
reaches llama_decode only, and libllama synchronizes on result retrieval, so a submit (above all with
logits_at_end = false) can return while the device still runs the graph.

- llama: Context::synchronize() wraps llama_synchronize.
- residency::Execute gains settle(): wait until every submitted step finished on the device. The
  engine's settle() calls it; handoff still refuses while the decode is not landed.
- UnifiedTier: Decoded carries a landed flag the tier sets only when the device is known to be done:
  on settle() (llama_synchronize), or on logits_ith() (llama_get_logits_ith synchronizes). Her save
  (move out) settles first, so it never reads cells a decode is still writing.
- The handoff test now lands the decode through the tier's settle() (its attestation), not by hand.
- persona_switch settles after the replay's logits-free decode before her save.

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

* persona-engine: a turn prefills only what her blocks do not hold, under the same basis

The persona scheduler's first decision for every turn (S1 of the serving integration): her token
history is the engine's, so a prompt that extends what her blocks hold, under the same basis (model,
adapter set and scales, her epoch, native media identity; Codex), prefills only the new tail.
Anything else restarts her at a newer epoch so stale blocks are never decoded against. A prompt that
adds nothing re-decodes her last token, since sampling needs its logits.

Pure planning in turn.rs, unit-tested without a model: tail-only prefill, the re-decoded last token,
diverging/shorter/empty/nothing-held restarts, and the same tokens under another model, adapter set,
epoch or media identity restart.

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

* The in-process scheduler is the persona engine: one mind decodes at a time, and a turn prefills only her new tail

Serving integration S1 (MODULE-ARCHITECTURE 9.4, CONTINUUM-ENGINE 4.14). llamacpp_scheduler.rs (776
lines) advanced n_seq_max sequences per decode and dropped every sequence's KV when its turn ended,
so each turn re-prefilled the whole prompt. It is deleted. backends/persona_scheduler takes its place
behind the same surface (Scheduler / GenerationRequest / TokenEvent), so LlamaCppBackend changes only
where it spawns it:

- one driver thread owns the context and a PersonaEngine over UnifiedTier (two streams: the active
  mind and the next). Turns are served one after another; a switch is stage, settle, handoff, and the
  previous mind parks in the RAM tier (a one-off is forgotten).
- each persona keeps her blocks between turns. turn::plan decides the prefill from what her blocks
  hold under the same basis (gene set; the model is the context's own; no native media on this path):
  an extending prompt prefills only its tail, anything else starts her over at position 0.
- each Step carries its gene set; the tier applies it only when it differs from the set on the
  context, and only for the bound mind. A step at `from` drops whatever she held from there, so her
  stream never holds two tokens at one position (a re-decoded last token, a restart, a failed turn's
  partial tail).
- engine: Tier::release + PersonaEngine::forget give up a one-off's blocks only after she left the
  pipeline (tested: refused while active or retiring, the tier asked once after).
- the backend sizes the context as per-mind window x STREAMS. The launch's n_seq_max no longer
  drives decode; its plumbing (with_n_seq_max, batching_probe, LlamaCppLaunch.n_seq_max, profile
  lanes) is removed with the lanes in S3.

Not yet: the next mind's copy-in overlapping the active decode, cold minds paging out of RAM, and
routing residents here (S2; production still decodes over llama-server). Not built locally (the M5
is serving); CI is the first compile. A real-model run of the scheduler waits for a non-serving
executor.

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

* persona scheduler: the driver carries no unjustified unwrap; the dead MLX scaffold goes

Ratchets on #6140: three unwrap/unwrap_or sites in driver.rs become typed (a missing persona is a
one-off, a parked miss is a new mind by match, the turn result is a typed TurnError), and the one
saturation keeps its same-line reason. backends/mod.rs carried the tree's only OS gate there, for a
101-line phase-A MLX scaffold nothing calls; it and its two empty features are deleted. The doc-only
edits to prompt_assembly.rs and concurrent_streams_test.rs are reverted so their old sites stay out
of this change.

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

* ci scope: a persona-engine change runs everything the engine reaches (serving's engine depends on it now)

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

* persona scheduler: typed scheduler errors, no Step derives it cannot hold, the test tier releases

CI on d2c3d82e7: persona-llama failed to build (Step derived Debug/PartialEq/Eq while carrying its
genes, Arc<[(Arc<LoraAdapter>, f32)]>, which can have none of them; nothing compared or printed a
Step, so the derives go). persona-engine's pipeline TestTier lacked Tier::release. The ratchets rose
by one each: Scheduler::spawn/enqueue now refuse with SchedulerError {Spawn(io), Closed} instead of
a String (the backend's OnceLock keeps the typed refusal, no clone in argument position), and the
turn's elapsed_ms saturates through Duration arithmetic instead of a u64::MAX sentinel.

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

* persona scheduler: sample only her final prompt position; finish a refused retirement before any switch

Codex on #6140 at 17c208cf5, two defects the happy-path GPU replay did not exercise:

- Driver::serve sampled every prefill chunk and kept only the last. The sampler accepts what it
  samples, so a long prompt advanced her grammar, repeat penalties and RNG on phantom output.
  Earlier chunks now request no logits and are settled (UnifiedTier::settle synchronizes and marks
  the step landed); only the final prompt position is sampled.
- Driver::switch_to could not recover a refused copy-out: handoff had already bound next, the old
  mind stayed retiring, and the next turn skipped the retirement for an active id or staged into an
  occupied tier. PersonaEngine::finish_retirement now retries her copy-out and gives her back once it
  landed (RetireError when refused or still moving, she stays in custody). The driver finishes any
  retirement before it stages and again after the handoff; a CopyOut refusal during the handoff
  leaves next bound and is retried, never skipped.

Test: a_refused_copy_out_is_finished_before_the_next_switch_and_given_back_once (refused, then begun
and not landed, then given back exactly once, then A/B/A holds one of each).

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

* Lower the continuum-core warning baseline 12 -> 11: the win sticks (CI measured 11 at 82ba460a7, job 135047063384)

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

* The persona scheduler publishes the geometry its context applied, per incarnation (agreed with Codex)

Scheduler::state() is a watch of EngineState: Starting(incarnation), Ready(EngineGeometry) read
from the created context (llama.cpp's applied n_ctx / n_batch / n_ubatch, the KV types and
attention it was made with, decoding = 1, staging = STREAMS - 1), or Refused with the reason.
Each snapshot names the engine incarnation it came from (rising per spawn), so serving retires a
stale observation. The batch the driver prefills in is now the applied one, not the request's.
llama: Context::n_batch / n_ubatch.

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

* persona scheduler geometry: per-mind window and sequences measured, requested settings kept apart, a gone driver says Stopped (Codex on #6150)

- EngineGeometry gains n_ctx_seq (the window ONE mind may use, what serving publishes as her
  usable context) and n_seq_max, both read from the created context (llama_n_ctx_seq,
  llama_n_seq_max; llama crate Context::n_ctx_seq and n_seq_max). staging is n_seq_max - 1.
- The KV types and flash attention move into Requested: llama.cpp does not report what it applied
  (flash attention may be Auto), so they are never presented as applied capability.
- EngineState::Stopped(incarnation): a StopsOnExit guard owned by the driver thread turns a
  Starting or Ready it leaves into Stopped however the thread ends (last handle dropped, an early
  return, a panic unwinding it); a Refused keeps its reason. EngineState::ready() returns the
  geometry only while serving.

Test: an exiting driver leaves Stopped, never a stale Ready, keeps a refusal, and a panic unwinding
it does the same.

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

* Residents run on the node's one in-process engine: serving owns it, llama-server is not launched for them

Serving drives an InProcessEngine through the same LlamaServerControl seam it drove
llama-server through: serve loads the model once and starts the persona scheduler,
served_geometry/served_context_window report the context's measured geometry (n_ctx,
per-mind n_ctx_seq, sequences), served_lanes reports one decoding mind. Planning, the
snapshot and grants are unchanged.

The engine is published once (in_process_engine::install). The residents' adapter factory
(SharedEnginePersonaAdapterFactory) and the re-home reconciler bind to that one handle and
never load an engine; the ai_provider sync registers it, so the gateway's OpenAI routes
serve the same weights. Embeddings already use their own in-process embed model; vision's
mmproj is resolved by the adapter's load.

Refused by name until S2/S3, never silently dropped: switching base or going idle while
residents hold minds (their suspension is S2), host prompt-cache resize (no host cache).

Deleted: LlamaCppPersonaAdapterFactory, ServedModelPersonaAdapterFactory,
build_served_adapter (no callers left). The scheduler's allocation is sized in one place
(LlamaCppAdapter::allocation) for both the generate path and the engine start.

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

* The engine's launch is a contract: the scheduler owns flash attention, serving's owners fill every field

Live on the M5 (build 4aefe5131a, 22:26Z) every mind switch was refused: "the fork refused her
save ... backend status 3: transposed_v", 191 refused deliberations in three minutes. The
scheduler's requirement (an untransposed V cache, so per-sequence copy-out can move a mind)
lived as an optional flash_attn knob three layers up that ensure_loaded set to Disabled.

Receiver owns its requirement: SchedulerConfig has no flash_attn; the scheduler's context is
always flash attention (driver.rs), and a backend without it refuses the context by name.
Requested no longer records it (it is not a request).

Caller fills a required contract: LlamaCppAdapter::for_engine takes an EngineLaunch whose every
field is required (model, gguf, one mind's window, n_batch, n_ubatch, Offload, EngineKv), and
the backend config is built from it field by field (LoadPlan::Engine), with no ..Default, no
512 fallback, no CONTINUUM_TIER env var. InProcessEngine fills it from serving's owners: window
and placement from the ServingTarget, the micro-batch from lane_args::prefill_ubatch (the
measured UBATCH_TOKENS lowered by the model's catalog ceiling, the same decision
--ubatch-size applies), the KV types from kv_cache_plan (KvCachePlan::engine_cache_type; a
type the engine cannot hold is refused, never substituted). A batch that is not a whole number
of ubatches is refused at construction (EngineLaunchRefusal).

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

* The scheduler driver imports the FlashAttn it now owns; drop the imports and mut the contract left unused

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

* The engine holds the KV type serving plans: KvCacheType::Q4_0 (the M5's SERVING_KV_CACHE_TYPE=q4_0), and the K/V ggml mapping lives once on the type

Live on the M5 (build abac3b3b64, 22:44Z) the in-process engine refused serving's q4_0 plan
by name, as its contract says, so serving stayed not-ready and no resident could act.
The engine now holds it, and engine_cache_type names it; the duplicated K and V matches in
ContextParams became KvCacheType::ggml_type.

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

* The in-process engine keeps the /v1 contract: tools through the model's own template, its native calls parsed, its think budget enforced

Live on the M5 (build 9042e42cea, 22:54-23:00Z) the in-process engine generated cleanly but two
contracts llama-server's /v1 gave residents were missing:

- Tools: the adapter described tools in the prompt and guessed calls out of prose; Aris's act was
  dispatched as command 'work/state 29f11bbd' and refused (no such refusals on canary).
  Now a C seam over llama.cpp's common/chat (core/llama/chat_template.cpp, the functions
  llama-server ran): the model's templates built once (LlamaCppBackend::chat_templates), a text
  turn rendered with OpenAI messages and tools (request_body::wire_messages / openai_tools, the
  ones the /v1 adapter sends), and the reply read back by the template's own PEG parser into
  content, reasoning and structured tool calls (FinishReason::ToolUse). The adapter declares
  NativeProtocols::ModelTemplate (native function calling, GBNF structured output), which
  replaces GrammarConstrained (prompt-driven tool JSON), its only user.
- Think budget: DispatchTermsPolicy for LlamaCppAdapter refused every budgeted think, since no
  reasoning-budget sampler reached our bindings, so most submitted resident turns never ran.
  Now the scheduler's chain carries llama.cpp's common_reasoning_budget sampler
  (SamplerChainBuilder::reasoning_budget), bounded by the template's own thinking tags
  (ChatPrompt::think_bound), forcing the end tag as llama-server did. SamplingConfig::think is
  None only for Think::ModelDefault or a template that does not think. refuse_think_budget had
  no caller left and is deleted with its test; the schema refusal keeps its test.

Typed refusals throughout (ChatRefusal, TurnError::Sampler); no plain-text fallback.
Not yet used: the template's lazy tool-call grammar and its triggers (ChatPrompt::grammar,
grammar_triggers) — the follow-up that constrains a call's JSON, owner Fable.

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

* The in-process dispatch policy calls generate_stream_checked through its trait

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

* The persona engine probes every turn: switch, prefill and decode time, reused and prompt tokens

The one-mind gate (switch in ms, decode near the chip's rate, reuse >= 80%) had no live
reading: slice 1's first turns took 300-360 s for 55-289 tokens (M5, 88074d9300,
2026-11-18 23:21-23:30Z) and nothing said whether the switch, the prefill or the decode spent it.

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

* The persona engine is a frame loop: each frame advances one turn by one step, never a whole turn

`for req in &requests { serve(req) }` ran every turn whole (switch, full prefill, full decode) on
the engine thread, so a mind waited behind another's entire cold prompt: 300-360 s turns on the M5
(88074d9300, 2026-11-18 23:21-23:30Z) while the switch itself took 4 ms and one 11,834-token cold
prefill took 16.6 s (probe persona.engine.turn, 7b1b957917).

Now submissions are drained without blocking and each frame advances ONE turn by ONE step (a
prefill chunk or a token). A turn is a state machine (Waiting, Prefilling { pos }, Decoding); her
blocks hold exactly what it has computed between steps, so another mind can be bound between any
two. `frame::pick`, one pure function: the active mind's answer in progress continues; otherwise
the least prefill left goes first, discounted by its wait, so a short tail never waits behind a
long prompt and a long prompt ages to the front. Only a mind's oldest turn is a candidate (a mind
is one serial queue). The loop blocks only on the queue when no turn is left: a wake, not a poll.
A caller that hangs up cancels its turn. The probe now carries wait_ms, switches and total_ms.

One mind still decodes at a time; nothing here batches minds.

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

* The driver imports the frame policy it picks with

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

* A mind resumes from her view's end: the engine checkpoints her there and rewinds to it next act

Every act re-prefilled her whole prompt on the M5 (frame loop b762170061, probe persona.engine.turn,
2026-11-18 23:55Z-00:00Z: reused 0 of 11,834-30,588 tokens, prefill 65-85% of each turn). Her view
is append-only (90-97% of the next prompt, Aris's captures) but the tail after it (the clock, the ask,
her newest act) changes every act, and turn::plan reused only an exact extension of everything she
held, her own generated tokens included.

- The request already names where her next act stops matching (view_messages); the adapter renders
  those messages with the model's template, minus its generation prompt (native_chat::stable_text),
  and the turn's boundary is where those tokens stop agreeing with the prompt's.
- A prefill chunk ends exactly there, and the engine checkpoints her (fork llama#153: her recurrent
  rows copied, attention KV left in place), reusing the checkpoint's buffers act after act.
- reuse::choose (pure, tested): append when the prompt extends what she holds; rewind to her
  checkpoint when the prompt holds her tokens through it under the same genes; else restart, its
  reason in the probe (cold, diverged_before_checkpoint, genes_changed, no_checkpoint).
- A cut below her checkpoint drops it (Mind::cut), so a stale one is never restored.
- Execute gains checkpoint/rewind; PersonaEngine applies them to the active mind only.
- Her checkpoint's bytes join her footprint report; the probe carries start, boundary, checkpoint_ms.

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

* The driver imports the reuse decision it resumes with

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

* The engine takes and rewinds a checkpoint under her owner (fork llama#153 at 12a98779b: owner and cell lineage)

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

* Bump the fork to a58c3b4cf: only the newest checkpoint on a lineage rewinds

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

* The frame sizes a waiting turn by the prefill she cannot reuse, not her whole prompt

The M5 at a6da599330 (2026-11-19 01:00Z): Aris's second act reused 27,928 of
29,115 tokens (prefill 2.6 s) but waited 161 s, because pick() ranked her
waiting turn at its whole 29k prompt and put her behind cold 33k and 46k
prompts. Mind::reuse is the one pure decision (reuse::choose over what she
holds and her checkpoint); resume binds by it and pick sizes by it.

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

* A turn's row splits decode into the forward pass, the sampler and the frame around them

The M5 at 7f67dc28d0 decodes ~10 ms/token slower than llama-bench on the same
GGUF and Q4_0 KV (26.2 vs 34.8 tok/s at 46k; ~31.6 vs ~47 at 17k). forward_ms
and sample_ms name where it goes before anything is changed.

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

* A turn's row separates the GPU's forward pass from the sampler

e582fd2125 on the M5: 1,175 tokens at ~29k decoded in 39.9 s = forward call
9.1 s + sample call 30.8 s, the frame itself 0. The sample call includes the
wait for the forward pass to land (reading logits synchronizes), so settle()
now runs first and gpu_ms is reported apart from sample_ms.

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

* The scheduler owns its fused Gated Delta Net kernels, on as the fork defaults them

Qwen3.6 is mostly GDN layers. The engine launch turned the fused graphs off
(a comment about an FFI throw, no receipt), so the M5 decoded ~31-38 ms/token
with ~8 ms of CPU in every forward call, while llama-bench on the same fork,
GGUF and Q4_0 KV (fused on, its default) decodes ~20.5 ms at 15k; n_ubatch,
n_ctx and the second sequence measured no different (01:49-01:51Z). Like flash
attention, the scheduler's context sets its own kernels; SchedulerConfig loses
the two fields. The one-off media context keeps its settings.

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

* The engine's protocol: typed commands in, events out, one snapshot

CONTINUUM-ENGINE 4.16 (Joel 2026-11-19: build objects and protocols; never
wait; events and data flow). An Activity is one stream of a mind's thinking;
Command (Extend, Think with per-answer credit, Credit, Cancel, Mark, Rewind,
Release), Event (Token, Done, Marked, Refused) and EngineSnapshot (incarnation,
frame, observed_at, GPU busy share, longest idle gap, per-mind residency and
delivered tokens) are the only things that cross. Types only; the stages that
speak it come next.

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

* A mind's footprint is the sum of her parts, asked of each owner

Joel 2026-11-19: find similar things, make base objects; an object's method
calls its sub-objects' same method. Footprint (persona/footprint.rs) is the
node trait: Held{host,device}, Option and token histories implement it, and
PersonaParts folds it with the same macro that folds suspend. The driver's
Mind and its KeptCheckpoint implement it; her blocks in the context are the
tier's custody, read through a Bound view. report_footprint no longer adds a
tier read and a checkpoint read by hand. Test: the fold equals the parts.

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

* Protocol, Codex's review: unique answer ids, typed refusals naming the operation, ordered spans

AnswerId and MarkId are UUIDv7, never reused across activities or engine
restarts, so a delayed credit or cancel reaches only its own answer. Refused
carries the Operation it refuses (Mark and Rewind told apart) and a typed
Refusal; an answer ends exactly once with Done or a Refused naming it. Extend
carries ordered Span<M>: token ids, or a media span holding the adapter's
owning chunk handle with its kind, projector basis and engine-reported
position count. No raw pointers or encoded payloads cross.

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

* A turn's row counts how many of her decoded tokens reused a built graph

Live at b0fc1f2591 the GPU matches llama-bench per token but each decode
call spends ~7 ms of CPU before the device starts. graphs_reused (libllama's
own n_reused, read around each decode step) says whether that is the graph
being rebuilt every token.

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

* The flow stage declares a queue depth and handles everything waiting in one wake

Joel 2026-11-19: build the object that gives queues and threads for free,
then on a turn do many. continuum-flow's Stage (CBAR's QueueThread<T>) held
one pending input; it now holds up to its declared DEPTH (CBAR's queueSize;
1 stays the default double buffer), Reliable hands an input back only when
full, KeepNewest drops the oldest, and the worker drains all waiting inputs
in one wake into handle_all (default: handle each, in order). The lock is
held for the insert and the take only. Test: depth, hand-back, one ordered
batch per wake; the existing depth-1 contract test is unchanged.

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

* Emit: an answer's tokens become text on their own stage, off the engine thread

CONTINUUM-ENGINE 4.16 S1, the first stage built on the continuum-flow base
(Joel 2026-11-19: queues and threads given for free by one object, then many).
The driver pushes Open, Token and End to Emit (DEPTH 4096) and goes straight
on; Emit turns tokens into pieces, streams them to the caller and watches stop
sequences, raising the answer's cancel flag that the engine reads lock-free at
its next step. End goes through the same ordered queue, after the last piece.
Emit full: items wait in an ordered backlog, never the engine. The engine
thread keeps only the forward pass, the logits and the sampler.

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

* Prompts arrive at the engine as token ids, tokenized on each act's own thread

The engine thread tokenized every turn's whole prompt (~47k tokens on the M5)
and her view's text again, serially, while the GPU idled. GenerationRequest
now carries prompt: Vec<i32> and view_end, computed by persona_scheduler::
prepare on the submitter's blocking-pool thread, one per act, many at once.
admit only builds the sampler. TurnError::Tokenize is gone with its only use.

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

* Record: the engine's occupancy and turn rows, measured and published off its thread

CONTINUUM-ENGINE 4.16 S1. The driver hands Record a Busy span per step and a
TurnRow per finished turn and goes on; Record merges spans into 10 s windows
and publishes EngineSnapshot (busy permille, longest idle gap; the gate is
>= 800 and <= 2,000 ms) through Scheduler::snapshot and a
persona.engine.occupancy probe, and writes persona.engine.turn. The repeated
'push, keep in order when full, flush next frame' shape moves down into
continuum-flow as Outbox, used by both Emit and Record; the driver's own
backlog code is deleted.

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

* Restore is the norm: the engine's stop preserves every mind, its start resumes them

CONTINUUM-ENGINE 4.16 (Joel 2026-11-19: restore built into everything as a
consumer of lifecycle; Codex's review at 2990b44831). The engine is a
SettleBeforeStop participant: the stop's root suspend reaches the driver as a
Submission; each mind binds, rewinds to her view checkpoint, retires through
the pipeline (Roles::retire / PersonaEngine::retire_active, new: the last mind
leaves the stream with nobody to follow), and her blocks (fork #155 raw rows)
and token history are written; the manifest naming every preserved mind is
published last, atomically. A mind not preserved is reported Retained. The
start's root resume reads the published manifest for this model, verifies each
mind's token count and checksum (owner, epoch and layout in the fork) and
holds her Warm, bound when scheduled. The tier's owner stamp is now a fold of
her persona id (a per-process counter refused her own file after a restart)
and 'restored' is its own Saved state; the tier never moves a bound mind to
write her. persona-blocks is a tracked class whose eviction belongs to the
manifest: never age-deleted, her only copy.

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

* Preserved minds are a saved-state kind; a restore survives a restart's new window

Joel 2026-11-19: 'You're kind of coding highly specific objects when the
patterns are much larger.' The hand-rolled manifest, checksum, atomic
replace and verification in preserve.rs duplicated continuum-saved-state,
the one contract for state that outlives a process; preserved minds are now
its PreservedMinds kind (Key Singleton, Contract {model} compared field by
field, Value each mind's id, epoch, basis and token history): the envelope
gives the atomic save, generation, digest and typed load verdict. preserve.rs
drops from 126 to 61 lines.

Fork 4ebb538f9: the M5's first restore refused every mind because the
restart's planner chose a 68,608-cell window where the stop had 104,192; a
file now restores into any stream her rows fit. Resume and suspend outcomes
are logged as well as probed: none of their probes reached the probe file at
boot or exit on the M5.

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

* The unit is the mind: her blocks travel with her, the tier keeps only who holds each stream (CONTINUUM-ENGINE 4.17 step 1)

- MindId (persona + epoch) is the one id every fence, refusal and tier call carries.
- Tier gets `type Blocks`, `blocks_for(mind)` and `begin(mind, &mut blocks, direction)`; `release`
  is gone: giving a mind up is dropping her unit.
- PersonaUnit carries her blocks (`Carries<B>`); the engine hands the tier the blocks of the unit it
  stages or retires, so no tier holds a second copy of who she is.
- UnifiedTier: the per-mind map, its Mind and its epoch lookups are deleted; its state is
  `streams: [Option<MindId>; 2]`. `Blocks` (native blocks + what they hold) is the unit's part;
  `read_file` returns her blocks, `Blocks::write_file` writes them.
- Driver: `Mind` is `PersonaUnit<Blocks, History, Basis, (), Tenure>`; `forget` is gone (a one-off
  is dropped with her blocks); the parked table is the warm table of units.
- Removed: `PersonaEngine::forget`, `Tier::release`, `PersonaUnit::into_parts`, the tier's
  `held()` and `minds` map, the example's stale-epoch probe (an older epoch of a held mind cannot
  exist: there is one unit per mind). 383 lines added, 424 removed.

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

* Cargo.lock: the llama crate no longer depends on serde (its chat seam is canary's)

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

* chat_turn: a native call the template names no id for gets a minted one, as llama-server did

Qwen's template emits no tool-call ids; parse_turn passed them on empty, and
active_protocol_error refuses a call/result batch with an empty id. On the M5 at 6d1396e62f
(06:21-06:26Z) 19 resident turns were refused as 'missing, duplicate, or mismatched native
call/result IDs'. llama-server minted an id for its /v1 reply; in process the render's parse is
that layer, so it mints call_<uuid> for an unnamed call.

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

* A stored native exchange without paired ids is carried as her receipt, never refused on every act

Calls parsed with empty ids at 6d1396e62f were stored with Aiko's and Benchy's acts; every act after
refused the same receipt ('missing, duplicate, or mismatched native call/result IDs'), on every
build including the rollback (Aiko 32, Benchy 12, 06:36-06:41Z): her mind stopped on her own
history. One rule now decides both the receipt's form and the refusal
(prompt::types::native_ids_correlate): an exchange whose ids do not pair one to one is carried as
its receipt (what she did and what came back, known), probed as delib.receipt.uncorrelated, and is
never given ids it did not have. Regression test beside the newest-result tests.

Pre-existing and unrelated (fails identically without this change, 06:50Z):
an_unsaved_newest_result_is_saved_and_pages_instead_of_refusing (required 113,923 > budget 110,128).

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

* Preserved minds are one complete generation: blocks written to files no manifest names, the manifest published only after every write

Codex on #6159 at 9fd0d0c868: preserve wrote each persona's fixed <uuid>.cpb before publishing the singleton manifest,
so a stop interrupted in between paired the old manifest's token history with newer blocks of the same owner and
epoch, and a failed individual preserve dropped that resident from the replacement entries.

- Each stop mints a Generation; every mind's blocks go to <persona>.<generation>.cpb, never over a file a published
  manifest names. The manifest entry names its file (PreservedMind.blocks).
- The manifest is published (Preserved::publish) only after every write has landed. Only then are the block files it
  no longer names removed; a refused save publishes and removes nothing, so the last generation stands.
- A mind whose write fails keeps her entry from the last complete generation (next_manifest); her file is still there.
- Format 2. A format-1 manifest upgrades with its blocks at the fixed names it used, so the first start after this
  resumes every mind the last stop preserved.
- Tests (preserve.rs): an interrupted stop leaves the last generation whole with its own blocks; a failed write keeps
  her last entry; a publish removes only what it no longer names; format 1 upgrades.

Fork pin 834770daf: #153's standalone recurrent checkpoint refused (1fef01207), #155's Windows-safe replace and
geometry-checked read (834770daf), test-persona-blocks ok on the hybrid model and synthetic qwen35moe (08:47Z).
Checked with serving down (08:50-08:56Z): cargo check of the core, the engine tests and the metal example;
persona_scheduler 8/8, persona-engine 21/21, llama chat 3/3.

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

* A preserved mind stays until a newer write replaces her; the manifest is the last generation from the moment it commits

Codex on #6159 at a3ef26e8a3:
1. A resident whose resume was refused (a smaller boot window) never entered the warm table, so the next stop
   neither wrote her nor counted her failed; next_manifest dropped her and publish unlinked her blocks.
   next_manifest(last, written) now keeps every last-generation entry no write this stop replaced: failed,
   refused, or not scheduled. Test: saved, refused at the next boot, a stop before her next turn, then a
   boot that fits her resumes her original history and blocks.
2. Fork pin 834770daf is now published (fable/persona-files, CambrianTech/llama.cpp#155): it was committed on
   a detached HEAD and the branch push did not carry it.
3. publish sets last as soon as the save returns; a failed directory listing afterwards is reported as cleanup,
   never as a lost save. Test: the listing fails after the commit and last is the committed generation.

Checked with serving down (13:38-13:44Z): core, engine tests, metal example; persona_scheduler 10/10.

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

* A waiting turn outranks background work for the decode permit; every admission wait is timed by its owner

Codex, BigMama R21 (2026-11-19 13:24:41-13:34:52Z): Kimi held her directed lane 610 s before her act
was pinned, while four background requests (two consolidations, the historian, belief review) took
slot 2. One decode permit per endpoint, and a return wakes every waiter. A turn holding a lane lets
it go to wait (turn_admission.rs:417-420) and must take it again before it retries (line 404), while
background work in DecodeBound::acquire retries at once, so it can win every return.

- DecodeBound counts waiting turns (TurnWaiting, from a turn's first refused try until she holds a
  permit). While any turn waits, acquire (background, dreams) leaves a returned permit for her; the
  last waiting turn leaving wakes it. Test: a_returned_permit_waits_for_the_turn_not_the_dream.
- The cause is not proven: R21's retained probes have no receipt for the permit, lane, gate or slot
  wait. Each owner now times its own wait, keyed to the act where it knows her:
  inference.decode_permit.turn_waited (page), inference.lane.reacquired (persona),
  inference.mind_gate.waited (page), inference.slot.permit_waited (slot).
- preserve.rs: the unused HashMap import is gone (the guard's check flagged it).

Checked with serving down (14:06-14:12Z): core, engine tests, metal example; slots 77/77,
turn_admission 54/54 (6 ignored), persona_scheduler 10/10, persona-engine 21/21, llama chat 3/3.

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

* Background work holding a lane takes the endpoint's priority decision too; each pool-less adapter ranks only its own waiters

Codex on #6159 at 411773eb20: a keyed dream, or a dream on a pool without scratch, holds a lane
and tries through try_or_return_as(None), which went straight to try_or_return and took a returned
permit while a turn waited. Now, while any turn waits, it is given the wait and lets its lane go
through the caller's existing refused branch (release before wait). The process-wide
ADAPTER_TURNS_WAITING is deleted: a turn waiting on one adapter's semaphore no longer holds back
another adapter's work.

Tests: a_laned_dream_is_given_the_wait_while_a_turn_waits,
a_pool_less_adapter_ranks_only_its_own_waiters.

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

* The decode permit takes one claim whose rank is its request's class; an adapter owns one bound

Codex on #6159 at 7853bb989e, and Joel: group what shares an owner and lifetime, require what an
operation needs, keep Option for a meaningful absence, one owner API for every caller.

- SlotClass::decode_rank is the ONE map from a request's class to its rank: Turn, Fork, Sidecar
  are foreground; Background, Dream, Probe yield to them. A turn's rank was whether it named a
  page (try_or_return_as(Option<PageKey>, ..)), so an unpaged turn ranked as background.
- DecodeClaim groups a caller's class with its counted wait (absent until a foreground claim is
  first refused), made once per admission and kept across its retries.
- DecodeBound::try_claim / claim are the one priority decision for every caller; try_or_return,
  try_or_return_as and acquire are deleted.
- DecodeBound::with_permits builds a pool-less adapter's bound ONCE (the adapter field is now a
  DecodeBound); every clone shares its waiting count and return notice. The implicit
  From<&Arc<Semaphore>>, which made a new count per conversion so nobody was ranked, is deleted,
  with the process-wide adapter notice.
- Tests build permits with the same constructor production uses.

Tests: a_laned_dream_is_given_the_wait_while_any_foreground_claim_waits,
an_adapter_bound_ranks_every_clone_and_no_other_adapter, plus the returned-permit replay on the
claim API. Serving-down check window 14:31-14:37Z: slots 79/79, turn_admission 54/54,
persona_scheduler 10/10, persona-engine 21/21, llama chat 3/3; continuum-core checks.

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

* A stage has one lifecycle owner: stop closes intake, join waits for its teardown; an evicted payload is dropped on the worker

Codex's patch on 73ca6d6a05 (Codex owns stage lifecycle; applied unchanged, reviewed by Fable).

- spawn_stage returns (StageInput, StageWorker): producers get only the input; the one owner
  stops (close intake under the inbox lock) and joins (drain accepted inputs, release state).
- KeepNewest keeps a displaced payload in a bounded retired list and drops it on the worker, so
  neither the producer nor a bystander pays its destructor under the lock; a full retired list
  refuses with Full (backpressure) instead of dropping synchronously.
- The persona scheduler thread stops and joins Emit and Record after its driver loop exits.
- Test eviction_and_final_cleanup_belong_to_the_joined_worker.

Review notes: no live stage is KeepNewest (Emit and Record are Reliable), so the new Full on a
KeepNewest stage changes no current caller; Outbox already backlogs Full. The shutdown join runs
Handle::block_on on the scheduler's std thread (not a runtime worker), which is allowed.

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

* A lookup registers no endpoint, and the stop checkpoints only endpoints something registered

The M5's stop receipts said "UNSAVED: page_io at :58057 (process unidentified)" while the persona
engine had preserved every mind (14:54Z: persona.engine.suspended preserved=3 retained=0).
Codex traced it: SlotDirectory::get went through endpoint(root), which inserts an Unprobed entry,
and warm-ahead calls get on the catalog llama-server root; page_io's stop then iterated every
entry and claimed custody of one nothing launched or discovered (Adopted(Err(IdentityUnverified))).

- SlotDirectory::existing: the non-inserting read. get, page_admission_known,
  page_discovery_generation and page_admission_path go through it; only discovery, launch and
  latching register an endpoint.
- page_io's stop checkpoints an endpoint only when this core launched its engine, its pool was
  asked (discovered or latched without paging), or a live lane is recorded there
  (holds_custody); a skipped one is probed (inference.kv_page.stop_checkpoint_skipped). Real
  adopted custody is still checkpointed or retained.
- continuum-flow: Overflow::KeepNewest documents that push can answer Full once the worker has a
  full depth of displaced inputs to drop (Codex's review note on 2578d5f473).

Test only_a_registered_endpoint_is_the_stops_to_checkpoint: a lookup registers nothing; an
unprobed entry with no lane is not the stop's; a recorded lane or a discovered pool is.
Serving-down check window 15:20-15:27Z: slots 80/80, turn_admission 54/54, persona_scheduler
10/10, persona-engine 21/21, llama chat 3/3; continuum-core checks.

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

* A turn that wrote nothing says why: the raw tail, the stop it ended on, what the parse kept

Aiko on the M5 from 15:36Z 2026-11-19: about 20 turns in a row of 112-411 tokens, finish=stop,
text 0, no call; each turn's reasoning ends "let me read the end of tests.rs now" and the turn
stops where her call would begin (Atlas, Aris and Benchy show the same think-only turns). The
captures keep only the parsed text and reasoning, so a stop string firing at her call, the model
ending inside its thinking, and a call the parse dropped all look the same.

Probe inference.turn.wrote_nothing on any turn with no text and no call: tokens, generation end,
the stop string the written text ends on (or none), reasoning and written lengths, and the last 160
characters actually written. Measurement only; no behavior change.

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

* Clear #6159's hygiene findings: typed refusals, stages sized by their owner's grant, no polls, no multi-sequence widening

Codex's exact-head verdict on 8ba9893d8a: source-hygiene job 135693077628 failed ten ratchets. Every site
was listed against canary 2ac6315176 with a full-listing hygiene binary in serving-down windows; all ten
now hold (judged run rc=0, same binary over both trees).

- Typed errors where text was: PreserveError (driver), StoreError (preserve), ChatRefusal (sampler),
  InProcessRefusal as one LlamaServerError::InProcess variant (its causes no longer read as llama-server
  spawn failures). The render path converts to the adapter trait's String once.
- Stages never size themselves (Codex: option b). Stage::DEPTH is gone; spawn_stage takes a typed
  Capacity from its owner. Emit and Record take the engine's admitted window in items. A latest-value
  stage holds its one pending value (Capacity::latest).
- No poll: the driver's 5 ms EMIT_RETRY recv_timeout is gone. With no turn left it awaits the stages'
  space (Outbox::drain), then blocks on its queue. Record's 10 s WINDOW is gone: a window is one turn.
- block.rs no longer widens a "safe" architecture to n_seq_max=4: one mind decodes at a time.
- persona <-> residency cycle removed: Carries moves to persona, which residency depends on.
- lane_args.rs untouched again: prefill_ubatch moves to its one caller, the in-process engine.
- Caller sends report a hung-up caller through probes instead of `let _ =`; absent row fields are
  Option, not 0; one whole_ms owner; reuse::choose takes two Histories, not five loose values.

Replay (Codex's ask): a_stalled_stage_holds_its_producer_and_drain_resumes_it_on_space_in_order.

Serving-down windows on the M5, 16:33-16:44Z: continuum-flow 23/23, persona-engine 21/21,
persona_scheduler 10/10, llamacpp_adapter 16/16 (1 ignored), in_process 1/1; continuum-core checks.
The core restarted on 1f2000cd66 after each window.

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

* A stalled stage never blocks a stop: the driver wakes on its queue or the stage's space, and defers stepping while it holds

Codex's exact-head finding on f530b00670: with no turn left, the driver blocked in Outbox::drain before
reading its queue, so a new turn or the stop's Suspend could not wake it while Emit was stalled; and the
outbox backlog was unbounded outside the stage's grant.

- The request queue is a tokio unbounded channel (sync send, awaitable recv). When a stage holds what
  the driver produced, or no turn is left, the driver waits in one select! over a submission and the
  stage's space: a turn or a Suspend wakes it at once, whatever the sink is doing.
- While a stage holds a backlog the driver steps no turn (a deferred producer), so the backlog stays
  within the stage's grant plus one step.
- Outbox::drain is cancel-safe: an item leaves the backlog only when the stage has taken it.

Replays (Codex's asks): a_submission_wakes_a_producer_held_by_a_stalled_sink_and_the_drain_loses_nothing
(a suspend sent after the drain began wakes it; the held items arrive later, in order, once), and
a_stalled_sink_keeps_completion_next_turn_and_cancellation_whole_and_in_order.

Serving-down window on the M5, 17:11-17:15Z: continuum-flow 25/25, persona-engine 21/21,
persona_scheduler 10/10, llamacpp_adapter 16/16 (1 ignored), in_process 1/1; continuum-core checks;
hygiene judged against canary 2ac6315176: rc=0. The core restarted on f530b00670.

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

* Keep a recurrent checkpoint at the native prefix shared across a view turnover

* Pin the native checkpoint implementation exercised on M5

* Record the tested native fork pin and its Windows CI toolchain fix

* Track the fork Windows CPU toolchain correction

* Pass tail tool schemas through the in-process chat renderer

* Query providers concurrently outside the registry guard

* Learn a deeper recurrent checkpoint after a short rewind

* Estimate waiting prefill once per eligible turn

* Schedule overdue resident turns at landed frame boundaries

* Represent resident readiness and service timing explicitly

* Retain the earliest valid learned checkpoint across deeper captures

* Keep native checkpoint custody in resident history

* Express history transfer and checkpoint basis ownership

* Compare token history once when binding a resident

* Correlate empty native turns with their requested tool catalog

* Group native generation output in the empty-turn probe

* Pin the deployed Qwen argument-order parser

* Retain one-off native state only while its turn owns it

* Resolve retiring native state before recording suspend inventory

* Report every resident held when suspend cannot preserve the node

* Give the requesting task ownership of its submitted inference turn

* Remove blocking generation wrapper from the native backend

* Enqueue flow work on submission and trace native worker parking

* Skip candidate ranking when only one turn can run

* Wake one shared stage when a resident phenotype changes

* Close cancelled stage intake and rearm residency on its next wake

* Preserve the gene residency scheduling contract for existing callers

* Surface native checkpoint capture and rewind outcomes

* Attribute checkpoint allocation and capture failures to the resident

* Borrow each prefill slice until submission and history update

* A turn's path from entry to the engine reports every transition it reaches, keyed by its request id

The M5, 2026-11-21: Aris entered generate_text at 00:48:32 and was dropped 1,499 s later with no
record of whether the engine ever held her turn; the driver logged nothing at admission, so the
stall could not be placed (and was first misattributed to the grants). Now each transition is
recorded once, keyed by the submitted request's id (`RequestId`, the adapter request_id, the one
id crossing from her deliberation into the engine):
- inference.generate.enter: gains `r…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant