From 0607fc8622f0dca8c605f4ab52598810478ce160 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 15:53:39 -0600 Subject: [PATCH 01/49] Design: the engine's contract: one typed definition, one owner on each side (CONTINUUM-ENGINE 4.11) Joel, 2026-11-16: "The problem is decentralized management and poor api schema"; "use uuidv7, not some bastardized string form ... rich structs and APIs, centralized management and servicemodules". Ids as UUIDv7 in their 16 bytes (EngineIncarnation, TurnId; a learn pin is its turn); every frame a fixed struct in one C header (server-continuum.h), Rust generated by bindgen; frames over server-frames.h rings, payloads by buffer_ref; one engine-side owner per concern and one core ServiceModule (EngineLink) as the only code that talks to our engine. Order of five slices, each deleting what it replaces. Open for Codex: hold #139/#6087 until the minds verbs ride frames (recommended). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 93 +++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 28a1a31bad..1ad8241e66 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -1692,6 +1692,99 @@ simulator and production agree, section 7.0); 0 turns refused or starved; 0 swap warm; on BigMama, every asked turn served. Each piece lands with its simulator scenario red then green, then a live read against a restart-only control. +### 4.11 The engine's contract: one typed definition, one owner on each side (2026-11-16, design for review) + +Joel, 2026-11-16: "The problem is decentralized management and poor api schema." "You design like a random +clusterfuck whereas I always go for structs and api. You want to be strict, use uuidv7, not some bastardized +string form, the actual form, rich structs and APIs, centralized management and servicemodules etc." + +#### 4.11.1 What went wrong (receipts, 2026-11-16) + +Resident minds (fork #139, core #6087) were built one endpoint at a time, JSON over HTTP, beside the binary port +section 4.1 already designs (`port`: "binary frames, no HTTP or JSON"): +- **No definition:** the fork reads 74 request fields by name (`json_value(body, "page", ...)`); the core reads 52 + engine reply fields by name (`.get("x")`, `pointer("/...")`). Every review round with Codex was one side guessing + the other's field: a pid, then an incarnation; a pin's position, then its id; `success` plus free text, then + frozen enums. +- **Ids in costume:** a mind as 32 hex digits, the engine's incarnation as a random `u64`, a learn pin as a counter. +- **No owner:** 13 sites in 5 files each decided part of a mind's checkpoints; the close-checkpoint eviction erased + learn pins, and the host budget and the count evicted in two different orders. (Fixed by `checkpoint_store`, + fork #140; the pattern below applies it to the whole seam.) + +#### 4.11.2 Ids: UUIDv7, native 16 bytes, one newtype per kind + +| Id | Minted by | Form | Replaces | +|---|---|---|---| +| `EngineIncarnation` | the engine, once at start | UUIDv7 | random `u64` token, OS pid | +| `TurnId` | the core, once per act | UUIDv7 | nothing (a turn had no identity) | +| `MindId` | the core: her persona's id; a fork's is UUIDv5 of (persona, room) (`PageKey::engine_id`) | UUID | 32-hex-digit string | + +- A learn pin IS its turn: `release(TurnId)`, `learn(TurnId)`. No separate pin id, and the turn id also names the + act for cancellation and attribution (the "turn token" Codex asked for). +- v7 sorts by time, so a newer engine or turn compares greater: a stale frame is recognized by comparison, never + by a lookup. +- On every wire and in every struct an id is its 16 bytes (`uint8_t[16]` in C, `Uuid` in Rust). Never hex, never + a string, never parsed. Rust: `Uuid::now_v7()` (workspace `uuid` gains the `v7` feature). C++: one minting + function in the contract header (48-bit Unix milliseconds + 74 random bits, RFC 9562). + +#### 4.11.3 One definition, generated for both sides + +- **The definition is one C header in the fork, `tools/server/server-continuum.h`** (section 4.1 already names it + as the C ABI shim). Every frame is a fixed-size, trivially copyable struct of fixed-width fields and ids; every + outcome is a fixed-width enum with named values. +- **The Rust side is generated from it by bindgen**, the way `core/llama/build.rs` already binds `llama.h`, then + wrapped once in safe newtypes in the core's engine crate (`EngineIncarnation(Uuid)`, `TurnId(Uuid)`, the + enums as Rust enums with no catch-all). No hand-written mirror, no serde, no field read by name. +- **Variable data is never in a frame.** A prompt's bytes, KV pages and checkpoints move as `buffer_ref` (domain, + pool, buffer, offset, length; fork `server-frames.h`); the frame names them. +- **Transport:** the frame rings of `server-frames.h` (lock-free SPSC, atomic waits, backpressure as a `false` + push) over shared memory between the core and the engine process, and the same frames in process once serving + hosts libllama directly (line 3b of the plan in CLAUDE.md). HTTP JSON stays only as the OpenAI-compatible adapter for + foreign drivers (Hermes), never between our own processes. + +**The frames** (each request carries `EngineIncarnation`; a mismatch is answered by a typed `stale_engine` +frame, never acted on): + +| Request | Reply | Replaces today's | +|---|---|---| +| `describe` | `engine_descriptor { incarnation, geometry (pool tokens, per-sequence tokens, lanes, parked ids), host budget }` | `/props` JSON + `resident_minds` | +| `turn_submit { turn, mind, learn_pin, prompt: buffer_ref, view spans, sampling }` | `turn_receipt { turn, mind_from, switch_us, generation, cached_tokens, pinned }` + token stream | `/completion` + `timings.mind` | +| `prefetch { mind }` | `placed { mind, place: mind_place }` | `/minds/prefetch` | +| `learn_submit { turn, reply rows: buffer_ref, ... }` | `learn_outcome { turn, learned_on, live_sequence_preserved, refusal, retry_after_us }` | `/learn` JSON | +| `pin_release { turn }` | `released { turn, outcome: pin_release }` | `/learn/release` | +| `page_save` / `page_restore { mind, buffer_ref }` | typed completion | `/slots/:id?action=` | + +The enums (`mind_from`, `mind_place`, `learned_on`, `learn_refusal`, `pin_release`) are the values frozen on +fork #139 (2026-11-16), now defined once in the header. + +#### 4.11.4 One owner on each side + +- **Engine:** one module per concern (`server-module.h`: own thread, fixed job ring, snapshot readers copy + without a lock), each the only code that changes its state: the resident-minds table, each mind's + `checkpoint_store` (#140), learning. The frame dispatcher decodes nothing: it routes a fixed struct to its + owner. +- **Core: one ServiceModule, `EngineLink`, the only code that talks to our engine.** It owns the rings, the + engine's descriptor and incarnation (published with the slot pool, never a side map), each turn's ticket, + prefetch, learn, release and paging. Callers ask it typed verbs (`link.turn(...)`, `link.prefetch(mind)`, + `link.release(turn)`); `stream.rs`, `minds.rs`, `slots/discover.rs` and the learn lane stop building requests. + A source-hygiene ratchet fails any engine path or field name outside it. + +#### 4.11.5 Order (each slice deletes what it replaces) + +1. **Contract header + generated Rust types + UUIDv7 ids**, with a native test that a frame round-trips + byte-identically through both sides. Deletes: nothing yet. +2. **`EngineLink` owns every existing call to our engine**, still over today's HTTP: centralization first, so + step 3 changes one module. Deletes: request building in `stream.rs`, `minds.rs`, `discover.rs`, the learn lane. +3. **The minds verbs move onto frames** (`describe`, `prefetch`, `pin_release`, `turn_receipt`). Deletes: + `/minds/prefetch`, `/learn/release`, `resident_minds` and `timings.mind` JSON, the hex page, the `u64` token, + the pin counter. +4. **Turns and learning move onto frames.** Deletes: our use of `/completion`, `/learn`, `/slots`. +5. **The ratchet** (no engine path or field outside `EngineLink`; no string id on the seam). + +**Open, for Codex:** whether #139 and #6087 merge before step 3 (JSON in place, deleted by step 3) or wait for +it. Recommendation: wait. The verbs added on 11-16 are the first users of the contract, and merging them as JSON +ships the shape this section deletes. + ## 5. A mind's context and the engine it runs on **Focus boundary:** [Focus contract](FOCUS-CONTRACT.md) defines one allocation, From 9a8ebef72f661e7977c0544597f9a006c15438e3 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 15:58:08 -0600 Subject: [PATCH 02/49] Design 4.11, Codex's review of #6092: identity is exact equality; process evidence kept separate; ABI validated at both edges; custody, cancel and idempotence table; EngineLink consolidates existing owners; vertical replacement slices Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 150 ++++++++++++++++---------- 1 file changed, 96 insertions(+), 54 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 1ad8241e66..9f6b2641ea 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -1711,79 +1711,121 @@ section 4.1 already designs (`port`: "binary frames, no HTTP or JSON"): learn pins, and the host budget and the count evicted in two different orders. (Fixed by `checkpoint_store`, fork #140; the pattern below applies it to the whole seam.) -#### 4.11.2 Ids: UUIDv7, native 16 bytes, one newtype per kind +#### 4.11.2 Ids: UUIDv7, native 16 bytes, one newtype per kind; identity is exact equality | Id | Minted by | Form | Replaces | |---|---|---|---| -| `EngineIncarnation` | the engine, once at start | UUIDv7 | random `u64` token, OS pid | -| `TurnId` | the core, once per act | UUIDv7 | nothing (a turn had no identity) | +| `EngineInstanceId` | the engine, once at start | UUIDv7 | random `u64` token | +| `TurnId` | the core, once per act; a retry keeps it | UUIDv7 | nothing (a turn had no identity) | | `MindId` | the core: her persona's id; a fork's is UUIDv5 of (persona, room) (`PageKey::engine_id`) | UUID | 32-hex-digit string | -- A learn pin IS its turn: `release(TurnId)`, `learn(TurnId)`. No separate pin id, and the turn id also names the - act for cancellation and attribution (the "turn token" Codex asked for). -- v7 sorts by time, so a newer engine or turn compares greater: a stale frame is recognized by comparison, never - by a lookup. -- On every wire and in every struct an id is its 16 bytes (`uint8_t[16]` in C, `Uuid` in Rust). Never hex, never - a string, never parsed. Rust: `Uuid::now_v7()` (workspace `uuid` gains the `v7` feature). C++: one minting - function in the contract header (48-bit Unix milliseconds + 74 random bits, RFC 9562). +- **Identity is exact equality, never ordering** (Codex on #6092: clock rollback, different clocks and two ids in + the same millisecond make greater-than meaningless). A frame for another `EngineInstanceId` is refused, typed; + v7's time order is only for reading logs. +- **Process evidence stays separate.** `engine_residency::EngineIncarnation` (pid, OS start time, port) remains the + proof a process died after a core restart; a UUID cannot prove death or release held work. The descriptor + carries both; the lifecycle owner's generation and custody checks are unchanged. +- **A learn pin is its turn:** `release(TurnId)`, `learn(TurnId)`. A `TurnId` is never reused, so a release can + never free another live turn's pin. +- On every wire and in every struct an id is its 16 bytes (`uint8_t[16]` in C, `Uuid` in Rust). Never hex, never a + string, never parsed. Rust: `Uuid::now_v7()` (workspace `uuid` gains `v7`). C++: one minting function in the + contract header (48-bit Unix milliseconds + 74 random bits, RFC 9562). -#### 4.11.3 One definition, generated for both sides +#### 4.11.3 One definition, validated at both edges - **The definition is one C header in the fork, `tools/server/server-continuum.h`** (section 4.1 already names it - as the C ABI shim). Every frame is a fixed-size, trivially copyable struct of fixed-width fields and ids; every - outcome is a fixed-width enum with named values. -- **The Rust side is generated from it by bindgen**, the way `core/llama/build.rs` already binds `llama.h`, then - wrapped once in safe newtypes in the core's engine crate (`EngineIncarnation(Uuid)`, `TurnId(Uuid)`, the - enums as Rust enums with no catch-all). No hand-written mirror, no serde, no field read by name. -- **Variable data is never in a frame.** A prompt's bytes, KV pages and checkpoints move as `buffer_ref` (domain, - pool, buffer, offset, length; fork `server-frames.h`); the frame names them. -- **Transport:** the frame rings of `server-frames.h` (lock-free SPSC, atomic waits, backpressure as a `false` - push) over shared memory between the core and the engine process, and the same frames in process once serving - hosts libllama directly (line 3b of the plan in CLAUDE.md). HTTP JSON stays only as the OpenAI-compatible adapter for - foreign drivers (Hermes), never between our own processes. - -**The frames** (each request carries `EngineIncarnation`; a mismatch is answered by a typed `stale_engine` -frame, never acted on): + as the C ABI shim): fixed-size, trivially copyable frames of fixed-width fields and 16-byte ids. +- **The Rust side is generated from it by bindgen** (as `core/llama/build.rs` binds `llama.h`) and wrapped once in + safe newtypes. Bindgen lays out structs; it does not validate frames, so both edges validate: + - **Byte order** little-endian, stated; **every field's offset and size** asserted (`static_assert(offsetof)` in + C++, generated `const` assertions in Rust); **reserved bytes** must be zero. + - **Every frame begins with a header:** magic, schema version, frame kind, total size, and the schema's + identity (a hash of the header file, compiled into both sides). A mismatch at attach refuses the link. + - **Tags are raw integers on the wire**, converted with `TryFrom`; an unknown value is a typed refusal, never a + cast into a Rust enum and never a default. +- **Variable data is never in a frame.** A prompt's bytes, KV pages and checkpoints move as `buffer_ref` + (section 4.11.4). +- **The frames** (every stateful request carries the exact `EngineInstanceId`; its replies are terminal frames + per 4.11.4): | Request | Reply | Replaces today's | |---|---|---| -| `describe` | `engine_descriptor { incarnation, geometry (pool tokens, per-sequence tokens, lanes, parked ids), host budget }` | `/props` JSON + `resident_minds` | -| `turn_submit { turn, mind, learn_pin, prompt: buffer_ref, view spans, sampling }` | `turn_receipt { turn, mind_from, switch_us, generation, cached_tokens, pinned }` + token stream | `/completion` + `timings.mind` | +| `attach { schema identity }` | `engine_descriptor { instance, process evidence, pool tokens, per-sequence tokens, lanes, parked ids, host budget }` | `/props` JSON + `resident_minds` | +| `turn_submit { turn, mind, learn_pin, prompt: buffer_ref, view spans, sampling }` | token frames, then `turn_done { turn, mind_from, switch_us, generation, cached_tokens, pinned }` / `cancelled` / `refused` | `/completion` + `timings.mind` | +| `cancel { turn }` | the turn's terminal frame | dropping an HTTP connection | | `prefetch { mind }` | `placed { mind, place: mind_place }` | `/minds/prefetch` | -| `learn_submit { turn, reply rows: buffer_ref, ... }` | `learn_outcome { turn, learned_on, live_sequence_preserved, refusal, retry_after_us }` | `/learn` JSON | +| `learn_submit { turn, reply rows: buffer_ref }` | `learn_outcome { turn, learned_on, live_sequence_preserved, refusal, retry_after_us }` | `/learn` JSON | | `pin_release { turn }` | `released { turn, outcome: pin_release }` | `/learn/release` | -| `page_save` / `page_restore { mind, buffer_ref }` | typed completion | `/slots/:id?action=` | +| `page_save` / `page_restore { mind, buffer_ref }` | typed terminal frame | `/slots/:id?action=` | -The enums (`mind_from`, `mind_place`, `learned_on`, `learn_refusal`, `pin_release`) are the values frozen on -fork #139 (2026-11-16), now defined once in the header. + The enums (`mind_from`, `mind_place`, `learned_on`, `learn_refusal`, `pin_release`) are the values frozen on + fork #139 (2026-11-16), defined once in the header. +- **Transport:** frame rings over shared memory between the core and the engine process, and the same frames in + process once serving hosts libllama directly (line 3b of the plan in CLAUDE.md). The ring's shared layout is its + own explicit contract: a page-aligned header of plain 64-bit words (head, tail, capacity, closed) with stated + acquire/release ordering and an address-based wait (futex / `__ulock`), implemented natively on each side and + proven by a cross-language fixture. A C++ `frame_ring` object is not assumed portable to Rust. HTTP JSON stays + only as the OpenAI-compatible adapter for foreign drivers (Hermes). -#### 4.11.4 One owner on each side +#### 4.11.4 Custody, cancellation and idempotence -- **Engine:** one module per concern (`server-module.h`: own thread, fixed job ring, snapshot readers copy - without a lock), each the only code that changes its state: the resident-minds table, each mind's - `checkpoint_store` (#140), learning. The frame dispatcher decodes nothing: it routes a fixed struct to its - owner. -- **Core: one ServiceModule, `EngineLink`, the only code that talks to our engine.** It owns the rings, the - engine's descriptor and incarnation (published with the slot pool, never a side map), each turn's ticket, - prefetch, learn, release and paging. Callers ask it typed verbs (`link.turn(...)`, `link.prefetch(mind)`, +A `buffer_ref` is `{ instance, pool, buffer, allocation generation, offset, length }`. The receiver checks the +instance, the generation (a buffer freed and reallocated has a new one) and `offset + length` within the +allocation without overflow. The sender owns the buffer until the receiver's terminal frame for that request; no +buffer is freed while a frame names it. + +| Case | Behavior | +|---|---| +| attach (bootstrap) | the first frame names no instance: `attach { schema identity }` -> `engine_descriptor { instance, process evidence, geometry, host budget }`; every stateful verb after it carries the exact instance | +| queue full | the push returns false: the caller gets a typed `backpressure` at once; nothing is dropped or silently retried | +| turn stream | tokens stream as frames naming the `TurnId`; exactly one terminal frame (`done`, `cancelled`, `refused { reason }`); its buffers are released only after it | +| duplicate `turn_submit` (same `TurnId`) | idempotent: the existing ticket is answered, the turn never runs twice | +| retry after a lost terminal frame | resubmits the same `TurnId`; the engine answers the recorded outcome | +| cancel | `cancel { turn }` is acknowledged with the turn's terminal frame; cancelling a finished turn answers its outcome; a cancel never frees another turn's resources | +| lost cancel acknowledgement | the caller re-sends the same cancel (idempotent) | +| peer death | detected by process evidence (`EngineIncarnation`), never by a missing frame alone; held work is released only once death is proven; the next attach yields a new instance | +| stale descriptor after replacement | every stateful verb with the old instance is refused `stale_engine`; the link re-attaches | +| `pin_release { turn }` | idempotent: the first frees it (`released` / `released_on_flash`), a repeat answers `not_pinned`; an unknown turn answers `not_pinned`, never a release of another | +| prefetch | idempotent per mind; owned by the waiting turn (dropped with it) | + +#### 4.11.5 One owner on each side, consolidating what exists + +- **Engine:** the frame dispatcher runs on the server loop that already owns the llama context; owners that touch + the same context share that thread (no thread per concern). Each owner is the only code that changes its state: + the resident-minds table, each mind's `checkpoint_store` (#140), learning. The dispatcher validates a frame's + header and tags and routes the struct to its owner. +- **Core: `EngineLink` is a ServiceModule that consolidates today's owners; it adds no registry.** What moves under + it, unchanged in role: endpoint admission and permits (`slots::directory()`, `EndpointAdmission`), turn + admission and unresolved completions (`turn_admission::admit_turn`, `turn_admission/unresolved_page`), + cancellation, buffer custody, the engine's descriptor (published with the slot pool), and process evidence + (`engine_residency`). Callers ask it typed verbs (`link.turn(...)`, `link.prefetch(mind)`, `link.release(turn)`); `stream.rs`, `minds.rs`, `slots/discover.rs` and the learn lane stop building requests. A source-hygiene ratchet fails any engine path or field name outside it. -#### 4.11.5 Order (each slice deletes what it replaces) - -1. **Contract header + generated Rust types + UUIDv7 ids**, with a native test that a frame round-trips - byte-identically through both sides. Deletes: nothing yet. -2. **`EngineLink` owns every existing call to our engine**, still over today's HTTP: centralization first, so - step 3 changes one module. Deletes: request building in `stream.rs`, `minds.rs`, `discover.rs`, the learn lane. -3. **The minds verbs move onto frames** (`describe`, `prefetch`, `pin_release`, `turn_receipt`). Deletes: - `/minds/prefetch`, `/learn/release`, `resident_minds` and `timings.mind` JSON, the hex page, the `u64` token, - the pin counter. -4. **Turns and learning move onto frames.** Deletes: our use of `/completion`, `/learn`, `/slots`. -5. **The ratchet** (no engine path or field outside `EngineLink`; no string id on the seam). - -**Open, for Codex:** whether #139 and #6087 merge before step 3 (JSON in place, deleted by step 3) or wait for -it. Recommendation: wait. The verbs added on 11-16 are the first users of the contract, and merging them as JSON -ships the shape this section deletes. +#### 4.11.6 Order: vertical replacements + +Each slice replaces one call path completely: schema, owner, producer, consumer, deletions and a load/fault +replay, together. No new minds or learning behavior ships on a transitional JSON seam. + +1. **The contract alone:** the header, the generated Rust types, the validation at both edges, the shared ring + layout, and a cross-language fixture (frames and the ring round-trip byte-identically; a bad tag, size, + reserved byte or schema identity is refused). No behavior. +2. **`EngineLink` consolidation over today's HTTP:** an internal refactor of existing owners under one module, no + new behavior. +3. **attach / describe**, end to end. Deletes `/props` parsing and `resident_minds` JSON. +4. **Minds: prefetch, the turn receipt, the switch.** Deletes `/minds/prefetch`, `timings.mind`, the hex page. +5. **Learning and pin release.** Deletes `/learn`, `/learn/release`, the `u64` pin, Codex's JSON learning patch + (kept until then as evidence and tests). +6. **Turn submit and streaming.** Deletes our use of `/completion` and `/slots`. +7. **The ratchet.** + +#139, #6087 and Codex's JSON learning patch are held: kept as tested evidence for slices 4 and 5, not merged +(Codex agreed, 2026-11-16). + +**Validation for every slice, before the resident deploy:** a stale descriptor after replacement; backpressure +while decoding; a lost terminal or cancel acknowledgement; two turns at the same position with distinct pins; +long-context side learning under a full memory grant. Native timing, charged and physical memory, and exact +preserved state compared against the JSON path they replace. ## 5. A mind's context and the engine it runs on From 6c0f6ece819eafa8737534ebc0ea746c4336ab04 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 16:00:27 -0600 Subject: [PATCH 03/49] Design 4.11.6: learning rides the same contract (Joel: "Make sure it accommodates learning") Genes as GeneId + GeneRevisionId (UUIDv7), shadow/stable with adoption by pointer swap, learn_submit from a live turn (side sequence) or an academy example, progress frames, one duty frame (share by wakefulness, trickle or dream), the engine's measured cost, one memory budget with spill through the KV pager, gene_save/attach by revision for retention across restart. Never a lane: /train* is deleted, not ported. Slice 5 is the learning vertical, gated on the learning acceptance test and the never-dark check. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 62 +++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 9f6b2641ea..6378a4186c 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -1802,7 +1802,63 @@ buffer is freed while a frame names it. `link.release(turn)`); `stream.rs`, `minds.rs`, `slots/discover.rs` and the learn lane stop building requests. A source-hygiene ratchet fails any engine path or field name outside it. -#### 4.11.6 Order: vertical replacements +#### 4.11.6 Learning rides the same contract + +Joel, 2026-11-16: "Make sure it accommodates learning." Learning is part of the mind, in place on the loaded base, +never a lane (ONE-RESIDENT-MODEL-PATIENT-DOCTOR-DREAM.md): the DREAM stage takes optimizer micro-steps on her +**shadow** gene between decode steps under the governor's share, her **stable** genes keep serving, and the shadow +is adopted by a pointer swap between two decode steps. The contract carries every part of that, with the same ids, +validation, custody and owners as the rest of 4.11. + +**Ids** (UUIDv7, 16 bytes, exact equality): + +| Id | Minted by | Names | +|---|---|---| +| `GeneId` | the core (the genome), when a gene is created | a gene across its whole life, on any node | +| `GeneRevisionId` | the engine, at each adoption | one exact state of a gene's weights; a turn's receipt names the revisions it ran on, so a turn served mid-learning is never credited to a self that moved | +| `LearnGrantId` | the core's governor | an authority to spend engine time on learning (today a string id) | +| `ExampleId` | the core (the academy), per example | an example that is not a live turn (dreaming, coursework, a replayed history) | + +**Frames:** + +| Request | Reply | Replaces today's | +|---|---|---| +| `gene_attach { gene, revision, weights: buffer_ref }` / `gene_detach { gene }` | `gene_state { gene, stable revision, shadow revision, bytes }` | `/lora-adapters/load`, `/lora-adapters/unload` | +| `shadow_open { gene }` | `gene_state` (a fresh shadow over her frozen stable stack) | `/lora-adapters/fresh` | +| `turn_submit` (4.11.3) carries her gene set `{ gene, scale }[]` | `turn_done` names the `GeneRevisionId`s it ran on | `"lora":[{id,scale}]` | +| `learn_submit { source: turn \| example, gene, grant, labels: buffer_ref }` | progress frames `learn_step { source, step, loss, ms }`, then one terminal `learn_outcome` (4.11.3) | `/learn` JSON and polling `/learn/events` | +| `learn_measure { gene, rows }` | `learn_cost { workspace bytes, step us, spill bytes }` | `/learn/preflight` | +| `learn_duty { grant, share, mode: trickle \| dream }` | `learn_duty_set` | `/learn/grants`, `/learn/residency*` (one authority frame) | +| `gene_adopt { gene }` | `gene_state` with the new stable revision (swap between decode steps) or a typed refusal (gate not met) | the planned `/lora-adapters/{id}/promote` | +| `gene_save { gene, revision, to: buffer_ref }` | terminal frame once the bytes are durable | `/lora-adapters/save` | + +**What the contract guarantees for learning:** +- **In place, never a lane:** no frame starts a trainer, a second model or a job. `learn_submit` from a live turn + learns on a side sequence (her live sequence is never touched; `learned_on`, `live_sequence_preserved`); from an + `ExampleId` it learns on the same loaded base from the academy's bytes (dreaming, coursework, a replayed + history, a Hermes driver's session). +- **Never dark:** a turn always outranks a learning step; the engine yields at the next decode boundary, so a + directed turn waits at most one micro-step (the amygdala's interrupt is just a turn arriving). `learn_duty` + sets the share by her wakefulness: a trickle while she is awake, more while drowsy, `dream` while asleep. +- **One memory budget:** optimizer state and activations are charged to the same host budget as KV and + checkpoints (fork #138); when short they spill through the same pager as KV, slower, never refused for lack of + a lease; `learn_cost` is the engine's own allocator's measurement, never an estimate. +- **Never serving moving weights:** steps write the shadow; turns read the stable; `gene_adopt` swaps them only + through the gate; every turn's receipt names the revisions it ran on. +- **Retained across restart** (the learning acceptance test): `gene_save` writes the adopted revision's bytes + durably and `gene_attach` restores them by `GeneRevisionId`, so a reviewed correction survives a restart exactly. +- **Owners:** in the engine, the gene registry owns adapters and their revisions, and the learn owner owns the + optimizer and its custody. In the core, `EngineLink` carries the learning verbs; the academy + (`continuum-academy`) is their caller through typed seams, never importing the mind's or the engine's internals. +- **Deleted, not ported:** the fork's `/train`, `/train/cancel|measure|pause|resume` (the separate trainer lane + nothing calls), and every `/lora-adapters/*` and `/learn/*` JSON route above. + +Slice 5 of 4.11.7 is the learning vertical: gene registry frames, `learn_submit` with progress, the duty +frame, adopt and save, end to end, with the acceptance test as its gate (a reviewed correction applied on unseen +tasks, retained after restart, against the same base without the gene) and the never-dark check (four residents +keep turning, each directed turn delayed by at most one micro-step, while a dream runs). + +#### 4.11.7 Order: vertical replacements Each slice replaces one call path completely: schema, owner, producer, consumer, deletions and a load/fault replay, together. No new minds or learning behavior ships on a transitional JSON seam. @@ -1814,8 +1870,8 @@ replay, together. No new minds or learning behavior ships on a transitional JSON new behavior. 3. **attach / describe**, end to end. Deletes `/props` parsing and `resident_minds` JSON. 4. **Minds: prefetch, the turn receipt, the switch.** Deletes `/minds/prefetch`, `timings.mind`, the hex page. -5. **Learning and pin release.** Deletes `/learn`, `/learn/release`, the `u64` pin, Codex's JSON learning patch - (kept until then as evidence and tests). +5. **Learning (4.11.6): genes, learn with progress, duty, adopt, save, pin release.** Deletes `/learn*`, + `/lora-adapters/*`, `/train*`, the `u64` pin, Codex's JSON learning patch (kept until then as evidence and tests). 6. **Turn submit and streaming.** Deletes our use of `/completion` and `/slots`. 7. **The ratchet.** From 2e7e72243329ea280a06092508b409b1546181b4 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 16:02:40 -0600 Subject: [PATCH 04/49] Design 4.11.6: her genome is her LoRA layers, trained in place on the one path (Joel) "Lora layer(s) becomes trained with inference still capable. Not some separate path. Of course it's fast to switch on and off too"; "It's not a separate version of the persona. Same base model not a sep one." One persona = the one loaded base + her layers. A layer serves and trains in the same tensors; learning is act_submit { mode: learn } on the one scheduler, never its own verb family; a layer switches on/off by scale and pages GPU/RAM/flash like KV; progress is a step count on the same layer, named per act for attribution (no per-step identity, no shadow copy). Supersedes the first draft's learn_submit/shadow_open/gene revisions and ONE-RESIDENT section 2.1's shadow/stable rule (that doc to be revised to match). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 107 ++++++++++++++------------ 1 file changed, 57 insertions(+), 50 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 6378a4186c..418f9580f3 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -1751,10 +1751,9 @@ section 4.1 already designs (`port`: "binary frames, no HTTP or JSON"): | Request | Reply | Replaces today's | |---|---|---| | `attach { schema identity }` | `engine_descriptor { instance, process evidence, pool tokens, per-sequence tokens, lanes, parked ids, host budget }` | `/props` JSON + `resident_minds` | -| `turn_submit { turn, mind, learn_pin, prompt: buffer_ref, view spans, sampling }` | token frames, then `turn_done { turn, mind_from, switch_us, generation, cached_tokens, pinned }` / `cancelled` / `refused` | `/completion` + `timings.mind` | +| `act_submit { act (TurnId), mind, layers, mode, learn_pin, prompt: buffer_ref, view spans, sampling }` (modes in 4.11.6) | token frames, then `act_done { act, mind_from, switch_us, generation, cached_tokens, pinned, (layer, step)[] }` / `cancelled` / `refused` | `/completion` + `timings.mind` | | `cancel { turn }` | the turn's terminal frame | dropping an HTTP connection | | `prefetch { mind }` | `placed { mind, place: mind_place }` | `/minds/prefetch` | -| `learn_submit { turn, reply rows: buffer_ref }` | `learn_outcome { turn, learned_on, live_sequence_preserved, refusal, retry_after_us }` | `/learn` JSON | | `pin_release { turn }` | `released { turn, outcome: pin_release }` | `/learn/release` | | `page_save` / `page_restore { mind, buffer_ref }` | typed terminal frame | `/slots/:id?action=` | @@ -1779,7 +1778,7 @@ buffer is freed while a frame names it. | attach (bootstrap) | the first frame names no instance: `attach { schema identity }` -> `engine_descriptor { instance, process evidence, geometry, host budget }`; every stateful verb after it carries the exact instance | | queue full | the push returns false: the caller gets a typed `backpressure` at once; nothing is dropped or silently retried | | turn stream | tokens stream as frames naming the `TurnId`; exactly one terminal frame (`done`, `cancelled`, `refused { reason }`); its buffers are released only after it | -| duplicate `turn_submit` (same `TurnId`) | idempotent: the existing ticket is answered, the turn never runs twice | +| duplicate `act_submit` (same `TurnId`) | idempotent: the existing ticket is answered, the act never runs twice | | retry after a lost terminal frame | resubmits the same `TurnId`; the engine answers the recorded outcome | | cancel | `cancel { turn }` is acknowledged with the turn's terminal frame; cancelling a finished turn answers its outcome; a cancel never frees another turn's resources | | lost cancel acknowledgement | the caller re-sends the same cancel (idempotent) | @@ -1802,61 +1801,68 @@ buffer is freed while a frame names it. `link.release(turn)`); `stream.rs`, `minds.rs`, `slots/discover.rs` and the learn lane stop building requests. A source-hygiene ratchet fails any engine path or field name outside it. -#### 4.11.6 Learning rides the same contract - -Joel, 2026-11-16: "Make sure it accommodates learning." Learning is part of the mind, in place on the loaded base, -never a lane (ONE-RESIDENT-MODEL-PATIENT-DOCTOR-DREAM.md): the DREAM stage takes optimizer micro-steps on her -**shadow** gene between decode steps under the governor's share, her **stable** genes keep serving, and the shadow -is adopted by a pointer swap between two decode steps. The contract carries every part of that, with the same ids, -validation, custody and owners as the rest of 4.11. +#### 4.11.6 Her genome is her LoRA layers: trained in place, on the one path + +Joel, 2026-11-16: "Make sure it accommodates learning." Then: "I and Lora layers genome. Training is remember in +place. Lora layer(s) becomes trained with inference still capable. Not some separate path. Of course it's fast to +switch on and off too. Like everything." And: "It's not a separate version of the persona. Same base model not a +sep one." + +**The model.** She is one persona: the one loaded base model plus her genome, a set of LoRA layers. Learning never +makes a separate version of her or a separate model. A layer is one resource: +- **It serves and trains in the same tensors.** When it is trainable, optimizer steps update the very weights + her acts read, between decode steps, and she keeps acting on it the whole time. No shadow copy awaiting + adoption, no second model, no trainer, no learning lane. +- **Learning is an act on the one path.** An act either generates (tokens out) or learns (labels in, a gradient + step on her trainable layers out). Both go through the same verb, the same scheduler, the same sequences and the + same layers; a turn outranks a learning act at the next decode boundary, so she is never dark. +- **Every switch is fast.** A layer is on or off for an act by its scale in her set (nothing moves). A layer pages + between the GPU pool, RAM and flash through the same mover as a mind's KV (`buffer_ref`, `memory_mover`), in + milliseconds, and is streamed in ahead of the act that needs it, like her KV (4.11.3 `prefetch`). +- **Exact accounting instead of a frozen copy.** A layer counts its committed steps (a quantity on the same layer, + never a new identity); every act's terminal frame names `(layer, step)` for each layer it ran on, so a reply is + attributed to the exact weights that made it, and a bad step is undone by switching the layer off (scale 0) or + paging back the bytes saved at an earlier step, instantly. This + replaces the shadow/stable two-adapter rule of ONE-RESIDENT-MODEL-PATIENT-DOCTOR-DREAM.md section 2.1 (to be + revised there to match). **Ids** (UUIDv7, 16 bytes, exact equality): | Id | Minted by | Names | |---|---|---| -| `GeneId` | the core (the genome), when a gene is created | a gene across its whole life, on any node | -| `GeneRevisionId` | the engine, at each adoption | one exact state of a gene's weights; a turn's receipt names the revisions it ran on, so a turn served mid-learning is never credited to a self that moved | -| `LearnGrantId` | the core's governor | an authority to spend engine time on learning (today a string id) | -| `ExampleId` | the core (the academy), per example | an example that is not a live turn (dreaming, coursework, a replayed history) | +| `LayerId` | the core (the genome), when a layer is created | one LoRA layer of her genome, on any node | +| `LearnGrantId` | the core's governor | an authority to spend engine time on learning acts | +| `ExampleId` | the core (the academy) | an example that is not a live act (dreaming, coursework, a replayed history, a Hermes session) | -**Frames:** +**Frames** (the act frames of 4.11.3 gain a mode; no learning verb family): | Request | Reply | Replaces today's | |---|---|---| -| `gene_attach { gene, revision, weights: buffer_ref }` / `gene_detach { gene }` | `gene_state { gene, stable revision, shadow revision, bytes }` | `/lora-adapters/load`, `/lora-adapters/unload` | -| `shadow_open { gene }` | `gene_state` (a fresh shadow over her frozen stable stack) | `/lora-adapters/fresh` | -| `turn_submit` (4.11.3) carries her gene set `{ gene, scale }[]` | `turn_done` names the `GeneRevisionId`s it ran on | `"lora":[{id,scale}]` | -| `learn_submit { source: turn \| example, gene, grant, labels: buffer_ref }` | progress frames `learn_step { source, step, loss, ms }`, then one terminal `learn_outcome` (4.11.3) | `/learn` JSON and polling `/learn/events` | -| `learn_measure { gene, rows }` | `learn_cost { workspace bytes, step us, spill bytes }` | `/learn/preflight` | -| `learn_duty { grant, share, mode: trickle \| dream }` | `learn_duty_set` | `/learn/grants`, `/learn/residency*` (one authority frame) | -| `gene_adopt { gene }` | `gene_state` with the new stable revision (swap between decode steps) or a typed refusal (gate not met) | the planned `/lora-adapters/{id}/promote` | -| `gene_save { gene, revision, to: buffer_ref }` | terminal frame once the bytes are durable | `/lora-adapters/save` | - -**What the contract guarantees for learning:** -- **In place, never a lane:** no frame starts a trainer, a second model or a job. `learn_submit` from a live turn - learns on a side sequence (her live sequence is never touched; `learned_on`, `live_sequence_preserved`); from an - `ExampleId` it learns on the same loaded base from the academy's bytes (dreaming, coursework, a replayed - history, a Hermes driver's session). -- **Never dark:** a turn always outranks a learning step; the engine yields at the next decode boundary, so a - directed turn waits at most one micro-step (the amygdala's interrupt is just a turn arriving). `learn_duty` - sets the share by her wakefulness: a trickle while she is awake, more while drowsy, `dream` while asleep. +| `act_submit { act (TurnId), mind, layers: { layer, scale, trainable }[], mode: generate \| learn, ... }`; for `learn`: `source: act \| example`, `labels: buffer_ref`, `grant` | `generate`: token frames; `learn`: `learn_step { act, step, loss, ms }` frames. Then one terminal frame naming `(layer, step)` for each layer it ran on (and, for `learn`, the steps it committed, `live_sequence_preserved`, typed refusal) | `/completion` + `"lora":[{id,scale}]`, `/learn`, polling `/learn/events` | +| `layer_page { layer, step, to: gpu \| ram \| flash, bytes: buffer_ref }` | the layer's residency, in milliseconds | `/lora-adapters/load`, `/unload`, `/fresh`, `/save` | +| `learn_duty { grant, share, mode: trickle \| dream }` | `learn_duty_set` | `/learn/grants`, `/learn/residency*` | +| `learn_measure { layers, rows }` | `learn_cost { workspace bytes, step us, spill bytes }` (the engine's own allocator) | `/learn/preflight` | + +**What the contract guarantees:** +- **In place, inference still capable:** a learning act and generating acts run on the same layers at once; a + generating act during learning sees the layer's current step and names it. +- **Never dark:** a generating act outranks a learning act at the next decode boundary (the amygdala's interrupt is + an act arriving); `learn_duty` sets the share by her wakefulness: a trickle while awake, more while drowsy, + `dream` while asleep. - **One memory budget:** optimizer state and activations are charged to the same host budget as KV and - checkpoints (fork #138); when short they spill through the same pager as KV, slower, never refused for lack of - a lease; `learn_cost` is the engine's own allocator's measurement, never an estimate. -- **Never serving moving weights:** steps write the shadow; turns read the stable; `gene_adopt` swaps them only - through the gate; every turn's receipt names the revisions it ran on. -- **Retained across restart** (the learning acceptance test): `gene_save` writes the adopted revision's bytes - durably and `gene_attach` restores them by `GeneRevisionId`, so a reviewed correction survives a restart exactly. -- **Owners:** in the engine, the gene registry owns adapters and their revisions, and the learn owner owns the - optimizer and its custody. In the core, `EngineLink` carries the learning verbs; the academy - (`continuum-academy`) is their caller through typed seams, never importing the mind's or the engine's internals. -- **Deleted, not ported:** the fork's `/train`, `/train/cancel|measure|pause|resume` (the separate trainer lane - nothing calls), and every `/lora-adapters/*` and `/learn/*` JSON route above. - -Slice 5 of 4.11.7 is the learning vertical: gene registry frames, `learn_submit` with progress, the duty -frame, adopt and save, end to end, with the acceptance test as its gate (a reviewed correction applied on unseen -tasks, retained after restart, against the same base without the gene) and the never-dark check (four residents -keep turning, each directed turn delayed by at most one micro-step, while a dream runs). + checkpoints (fork #138) and spill through the same pager when short, slower, never refused for want of a lease. +- **Retained across restart** (the learning acceptance test): `layer_page { to: flash }` writes the layer's bytes + at a step durably, and paging them back restores exactly that `(layer, step)`. +- **Owners:** in the engine, the layer registry owns her layers, their steps and residency, and the act + scheduler owns when a learning act runs. In the core, `EngineLink` carries `act_submit`, `layer_page` and + `learn_duty`; the academy (`continuum-academy`) is their caller through typed seams. +- **Deleted, not ported:** `/train*` (the separate trainer nothing calls), every `/lora-adapters/*` and `/learn/*` + route, and the `learn_submit` / `shadow_open` verbs of this section's first draft. + +Slice 5 of 4.11.7 is the learning vertical: `act_submit` with `mode: learn`, the layer registry with revisions and +paging, and `learn_duty`, end to end. Its gates: the learning acceptance test (a reviewed correction applied on +unseen tasks, retained after restart, against the same base with the layer off) and the never-dark check (four +residents keep acting, each generating act delayed by at most one learning step, while a dream runs). #### 4.11.7 Order: vertical replacements @@ -1870,8 +1876,9 @@ replay, together. No new minds or learning behavior ships on a transitional JSON new behavior. 3. **attach / describe**, end to end. Deletes `/props` parsing and `resident_minds` JSON. 4. **Minds: prefetch, the turn receipt, the switch.** Deletes `/minds/prefetch`, `timings.mind`, the hex page. -5. **Learning (4.11.6): genes, learn with progress, duty, adopt, save, pin release.** Deletes `/learn*`, - `/lora-adapters/*`, `/train*`, the `u64` pin, Codex's JSON learning patch (kept until then as evidence and tests). +5. **Learning (4.11.6): `act_submit { mode: learn }`, the layer registry with revisions and paging, `learn_duty`, + pin release.** Deletes `/learn*`, `/lora-adapters/*`, `/train*`, the `u64` pin, Codex's JSON learning patch (kept + until then as evidence and tests). 6. **Turn submit and streaming.** Deletes our use of `/completion` and `/slots`. 7. **The ratchet.** From ceb6e5012c90d6cdd8ad67939b27990175fb9e11 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 16:03:54 -0600 Subject: [PATCH 05/49] Design 4.11.6/4.11.8: genome always on, learning a switch costing only marginal memory, one memory standard (Joel) "Learn is like a continuous or at least on/off marginally more memory just for the extra backprop and the layers learning. Genome is supposed to be on all the time. This reorganization should make all of this easier. The standardization of this memory." Her layers attach to every act (genome_set, never per act); learning is a per-layer switch, continuous while on; its cost is the backprop workspace and the learning layers' optimizer state. 4.11.8: every byte the engine holds for a mind is one memory resource {owner, class, mind, bytes, tier, buffer_ref}, moved by the one mover, charged to the one budget with one eviction order, prefetched together, reported by the engine's own allocator; learning is one more class in that table. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 85 +++++++++++++++++++-------- 1 file changed, 61 insertions(+), 24 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 418f9580f3..d2e36ca7c9 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -1808,23 +1808,29 @@ place. Lora layer(s) becomes trained with inference still capable. Not some sepa switch on and off too. Like everything." And: "It's not a separate version of the persona. Same base model not a sep one." +Joel, then: "Learn is like a continuous or at least on/off marginally more memory just for the extra backprop and +the layers learning. Genome is supposed to be on all the time. This reorganization should make all of this +easier. The standardization of this memory." + **The model.** She is one persona: the one loaded base model plus her genome, a set of LoRA layers. Learning never -makes a separate version of her or a separate model. A layer is one resource: -- **It serves and trains in the same tensors.** When it is trainable, optimizer steps update the very weights - her acts read, between decode steps, and she keeps acting on it the whole time. No shadow copy awaiting - adoption, no second model, no trainer, no learning lane. -- **Learning is an act on the one path.** An act either generates (tokens out) or learns (labels in, a gradient - step on her trainable layers out). Both go through the same verb, the same scheduler, the same sequences and the - same layers; a turn outranks a learning act at the next decode boundary, so she is never dark. -- **Every switch is fast.** A layer is on or off for an act by its scale in her set (nothing moves). A layer pages - between the GPU pool, RAM and flash through the same mover as a mind's KV (`buffer_ref`, `memory_mover`), in - milliseconds, and is streamed in ahead of the act that needs it, like her KV (4.11.3 `prefetch`). +makes a separate version of her or a separate model. +- **Her genome is always on.** Her layers are attached to every act she takes; nothing switches them per act. + They leave the GPU only the way any memory does, under the one budget (4.11.8), and come back in milliseconds. +- **Learning is a switch on her layers, continuous while on.** Turning a layer's learning on makes it trainable in + the same tensors her acts read: as examples reach her (her reviewed outcomes, corrections, dreaming, coursework), + optimizer steps update it between decode steps while she keeps acting on it. Turning it off stops the steps; + nothing else changes. No shadow copy, no adoption swap, no trainer, no learning lane. +- **Its cost is marginal memory, nothing else.** Learning on adds the backprop workspace (activations at + serving-sized chunks) and the learning layers' optimizer state. Both are memory classes in the one standard + (4.11.8): charged to the one budget, paged by the one mover, spilled to flash when short, never a lease. +- **Examples ride the one act path.** An example is an act with `mode: learn` (labels in, a gradient step on her + learning layers out), scheduled by the same scheduler on the same sequences; a generating act outranks it at the + next decode boundary, so she is never dark. - **Exact accounting instead of a frozen copy.** A layer counts its committed steps (a quantity on the same layer, never a new identity); every act's terminal frame names `(layer, step)` for each layer it ran on, so a reply is - attributed to the exact weights that made it, and a bad step is undone by switching the layer off (scale 0) or - paging back the bytes saved at an earlier step, instantly. This - replaces the shadow/stable two-adapter rule of ONE-RESIDENT-MODEL-PATIENT-DOCTOR-DREAM.md section 2.1 (to be - revised there to match). + attributed to the exact weights that made it, and a bad step is undone by paging back the bytes saved at an + earlier step, instantly. This replaces the shadow/stable two-adapter rule of + ONE-RESIDENT-MODEL-PATIENT-DOCTOR-DREAM.md section 2.1 (to be revised there to match). **Ids** (UUIDv7, 16 bytes, exact equality): @@ -1838,8 +1844,9 @@ makes a separate version of her or a separate model. A layer is one resource: | Request | Reply | Replaces today's | |---|---|---| -| `act_submit { act (TurnId), mind, layers: { layer, scale, trainable }[], mode: generate \| learn, ... }`; for `learn`: `source: act \| example`, `labels: buffer_ref`, `grant` | `generate`: token frames; `learn`: `learn_step { act, step, loss, ms }` frames. Then one terminal frame naming `(layer, step)` for each layer it ran on (and, for `learn`, the steps it committed, `live_sequence_preserved`, typed refusal) | `/completion` + `"lora":[{id,scale}]`, `/learn`, polling `/learn/events` | -| `layer_page { layer, step, to: gpu \| ram \| flash, bytes: buffer_ref }` | the layer's residency, in milliseconds | `/lora-adapters/load`, `/unload`, `/fresh`, `/save` | +| `act_submit { act (TurnId), mind, mode: generate \| learn, ... }` (her layers come from her genome, always on); for `learn`: `source: act \| example`, `labels: buffer_ref` | `generate`: token frames; `learn`: `learn_step { act, step, loss, ms }` frames. Then one terminal frame naming `(layer, step)` for each layer it ran on (and, for `learn`, the steps it committed, `live_sequence_preserved`, typed refusal) | `/completion` + `"lora":[{id,scale}]`, `/learn`, polling `/learn/events` | +| `genome_set { mind, layers: { layer, scale, learning: on \| off }[] }` | the genome as the engine holds it | per-request `"lora":[{id,scale}]`, `/lora-adapters/fresh` | +| `layer_save { layer, step, to: buffer_ref }` / layer residency moves | the standard memory frames (4.11.8) | `/lora-adapters/load`, `/unload`, `/save` | | `learn_duty { grant, share, mode: trickle \| dream }` | `learn_duty_set` | `/learn/grants`, `/learn/residency*` | | `learn_measure { layers, rows }` | `learn_cost { workspace bytes, step us, spill bytes }` (the engine's own allocator) | `/learn/preflight` | @@ -1851,16 +1858,16 @@ makes a separate version of her or a separate model. A layer is one resource: `dream` while asleep. - **One memory budget:** optimizer state and activations are charged to the same host budget as KV and checkpoints (fork #138) and spill through the same pager when short, slower, never refused for want of a lease. -- **Retained across restart** (the learning acceptance test): `layer_page { to: flash }` writes the layer's bytes - at a step durably, and paging them back restores exactly that `(layer, step)`. -- **Owners:** in the engine, the layer registry owns her layers, their steps and residency, and the act - scheduler owns when a learning act runs. In the core, `EngineLink` carries `act_submit`, `layer_page` and - `learn_duty`; the academy (`continuum-academy`) is their caller through typed seams. +- **Retained across restart** (the learning acceptance test): `layer_save` writes the layer's bytes at a step + durably, and paging them back restores exactly that `(layer, step)`. +- **Owners:** in the engine, the layer registry owns her layers and their steps, the memory owner (4.11.8) their + residency, and the act scheduler when a learning act runs. In the core, `EngineLink` carries `act_submit`, + `genome_set`, `layer_save` and `learn_duty`; the academy (`continuum-academy`) is their caller through typed seams. - **Deleted, not ported:** `/train*` (the separate trainer nothing calls), every `/lora-adapters/*` and `/learn/*` route, and the `learn_submit` / `shadow_open` verbs of this section's first draft. -Slice 5 of 4.11.7 is the learning vertical: `act_submit` with `mode: learn`, the layer registry with revisions and -paging, and `learn_duty`, end to end. Its gates: the learning acceptance test (a reviewed correction applied on +Slice 5 of 4.11.7 is the learning vertical: `genome_set` with the learning switch, `act_submit` with +`mode: learn`, the layer registry with steps, `layer_save` and `learn_duty`, end to end, on the memory standard. Its gates: the learning acceptance test (a reviewed correction applied on unseen tasks, retained after restart, against the same base with the layer off) and the never-dark check (four residents keep acting, each generating act delayed by at most one learning step, while a dream runs). @@ -1870,7 +1877,7 @@ Each slice replaces one call path completely: schema, owner, producer, consumer, replay, together. No new minds or learning behavior ships on a transitional JSON seam. 1. **The contract alone:** the header, the generated Rust types, the validation at both edges, the shared ring - layout, and a cross-language fixture (frames and the ring round-trip byte-identically; a bad tag, size, + layout, the memory resource descriptor and the mover's frames (4.11.8), and a cross-language fixture (frames and the ring round-trip byte-identically; a bad tag, size, reserved byte or schema identity is refused). No behavior. 2. **`EngineLink` consolidation over today's HTTP:** an internal refactor of existing owners under one module, no new behavior. @@ -1890,6 +1897,36 @@ while decoding; a lost terminal or cancel acknowledgement; two turns at the same long-context side learning under a full memory grant. Native timing, charged and physical memory, and exact preserved state compared against the JSON path they replace. +#### 4.11.8 One memory standard + +Every byte the engine holds for a mind is one kind of thing: a **memory resource** with an owner, a class, its +bytes and its tier. Today each class is managed its own way (KV by the pool, checkpoints by thirteen call sites +until #140, pages by the page worker, adapters by their endpoints, learning by its own workspace lease); the +standard makes them one. + +| Class | Owner | Tiers | +|---|---|---| +| a mind's KV (her sequence) | the resident-minds table | GPU pool, RAM, flash | +| her checkpoints | her `checkpoint_store` (#140) | RAM, flash (with her) | +| her genome's layers | the layer registry | GPU, RAM, flash | +| learning: backprop workspace, optimizer state | the layer registry, while learning is on | GPU, RAM, flash (spill) | +| the prompt cache | the cache | RAM | + +- **One descriptor:** every resource is `{ owner, class, mind, bytes, tier, buffer_ref }`; a frame names it, never + carries it. +- **One mover:** every tier change is a transfer through `memory_mover` (`server-frames.h`): within unified memory a + new reference (nothing copied), otherwise one copy by the backend's own engine, completion as a frame. +- **One budget, one eviction order:** the host budget (fork #138) charges every class; under pressure the coldest + mind's resources go down a tier first (by activity temperature), and within a mind her store's own order holds + (4.11.4, #140). Pins and the active act's resources never go. Nothing is refused for want of a lease: it spills. +- **One prefetch:** a mind's resources (her KV, checkpoints, layers) are streamed up ahead of her act together. +- **Reported, not estimated:** the engine reports each class's live bytes from its own allocator in the descriptor + (4.11.3); the core's ledger reads it. + +So learning on is one more class appearing in the same table, and a layer, a page and a checkpoint move, spill and +come back the same way. Slice 1 of 4.11.7 includes the descriptor and the mover's frame types; each later slice +moves its class onto them. + ## 5. A mind's context and the engine it runs on **Focus boundary:** [Focus contract](FOCUS-CONTRACT.md) defines one allocation, From 8fca64fd57c5b9e76cb5e6ddc3d823756be46658 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 16:07:42 -0600 Subject: [PATCH 06/49] Design 4.11.6/4.11.8, Codex's re-review of #6092: a step visible whole at the decode fence, per-act step observations, KV continued across steps but stamped (state: exact recomputes), an interrupted step is uncertain and switched off, durable step = weights + optimizer + metadata with the manifest last; bounded admission with typed deferral under ResourceDaemon grants, host and device charged separately; class owners own meaning, the existing completion owner owns transfers Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 51 ++++++++++++++++++++------- 1 file changed, 38 insertions(+), 13 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index d2e36ca7c9..4f2faad454 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -1822,15 +1822,32 @@ makes a separate version of her or a separate model. nothing else changes. No shadow copy, no adoption swap, no trainer, no learning lane. - **Its cost is marginal memory, nothing else.** Learning on adds the backprop workspace (activations at serving-sized chunks) and the learning layers' optimizer state. Both are memory classes in the one standard - (4.11.8): charged to the one budget, paged by the one mover, spilled to flash when short, never a lease. + (4.11.8): charged to the one budget, paged by the one mover, spilled to flash when short, under the bounded admission of 4.11.8. - **Examples ride the one act path.** An example is an act with `mode: learn` (labels in, a gradient step on her learning layers out), scheduled by the same scheduler on the same sequences; a generating act outranks it at the next decode boundary, so she is never dark. -- **Exact accounting instead of a frozen copy.** A layer counts its committed steps (a quantity on the same layer, - never a new identity); every act's terminal frame names `(layer, step)` for each layer it ran on, so a reply is - attributed to the exact weights that made it, and a bad step is undone by paging back the bytes saved at an - earlier step, instantly. This replaces the shadow/stable two-adapter rule of - ONE-RESIDENT-MODEL-PATIENT-DOCTOR-DREAM.md section 2.1 (to be revised there to match). +- **A step becomes visible whole, at one fence** (Codex on #6092). Gradients accumulate in the optimizer's own + buffers; the layer's weights change only when a step commits, and the commit runs on the server loop between two + decode batches, the one point where no act is reading the layer. An act therefore sees step `s` or step `s+1` + for a whole decode batch, never a partial write. No second persona or shadow model is needed: the fence + serializes the one writer against the readers. +- **Every act reports what it actually saw.** An act spanning several commits reports each observation + `(layer, step, first token, last token)`, not one label for its whole output; a reply is attributed to the exact + weights that produced each part of it. +- **Her KV continues across a step, stamped.** KV and checkpoints computed under an earlier step are kept: she does + not re-read her own past each time a layer moves, as a person's memories are not re-encoded when they learn. + This is the intended learning semantics. Each sequence and checkpoint is stamped with the layer steps it was + computed under; an identical token prefix is reused only where the stamps allow it. An act that needs exact + state (an evaluation, an A/B of a layer) asks for `state: exact`, and KV stamped with any other step is + recomputed for it. A test proves that the same prefix under two steps gives different logits and that the stamp + catches it. +- **An interrupted step is neither step.** A commit that fails or is cut off leaves the layer `uncertain` (the + optimizer's existing quarantine, `llama_opt_shadow_quarantined`): it is switched off for every act (scale 0) and + stays so until the layer registry restores its last durable step. It is never reported as the step before or + after. +- **A durable step is weights plus optimizer.** Saving for resumed learning writes the layer's weights, its + optimizer state (moments) and its step metadata (step count, schedule position) as components, then publishes + their manifest last, atomically; a save with any component missing has no manifest and does not exist. **Ids** (UUIDv7, 16 bytes, exact equality): @@ -1857,7 +1874,7 @@ makes a separate version of her or a separate model. an act arriving); `learn_duty` sets the share by her wakefulness: a trickle while awake, more while drowsy, `dream` while asleep. - **One memory budget:** optimizer state and activations are charged to the same host budget as KV and - checkpoints (fork #138) and spill through the same pager when short, slower, never refused for want of a lease. + checkpoints (fork #138) and spill through the same pager when short, under the bounded admission of 4.11.8 (a typed deferral, never an overrun or a drop, when nothing can legally move). - **Retained across restart** (the learning acceptance test): `layer_save` writes the layer's bytes at a step durably, and paging them back restores exactly that `(layer, step)`. - **Owners:** in the engine, the layer registry owns her layers and their steps, the memory owner (4.11.8) their @@ -1916,16 +1933,24 @@ standard makes them one. carries it. - **One mover:** every tier change is a transfer through `memory_mover` (`server-frames.h`): within unified memory a new reference (nothing copied), otherwise one copy by the backend's own engine, completion as a frame. -- **One budget, one eviction order:** the host budget (fork #138) charges every class; under pressure the coldest - mind's resources go down a tier first (by activity temperature), and within a mind her store's own order holds - (4.11.4, #140). Pins and the active act's resources never go. Nothing is refused for want of a lease: it spills. +- **One grant authority, bounded admission.** `ResourceDaemon` (`continuum-kernel/src/resources`) stays the grant + authority: each class's bytes are held under a `ResourceLease`, host and device charged separately (a host-byte + ceiling says nothing about a discrete GPU's memory), and the engine's allocator reports settle the actual charge. + Under pressure the coldest mind's resources go down a tier first (by activity temperature), and within a mind her + store's own order holds (4.11.4, #140); pins and the active act's resources never go. When no legal move exists + (everything left is pinned, the active working set exceeds the grant, or a RAM or flash write fails), the request + gets a typed outcome (`deferred { all_pinned | exceeds_grant | tier_io_error }`), its bytes are preserved, and + nothing exceeds the budget or is dropped. - **One prefetch:** a mind's resources (her KV, checkpoints, layers) are streamed up ahead of her act together. - **Reported, not estimated:** the engine reports each class's live bytes from its own allocator in the descriptor (4.11.3); the core's ledger reads it. -So learning on is one more class appearing in the same table, and a layer, a page and a checkpoint move, spill and -come back the same way. Slice 1 of 4.11.7 includes the descriptor and the mover's frame types; each later slice -moves its class onto them. +**Who owns what.** A class's owner (the table above) owns its state's meaning: what a page, a checkpoint or a layer +step is. The shared mover owns every transfer and its completion custody, and it is the existing completion owner, +not a second one. The grant is `ResourceDaemon`'s. No class keeps an allocator of its own behind the common +descriptor. So learning on is one more class appearing in the same table, under the same grant, and a layer, a +page and a checkpoint move, spill, defer and come back the same way. Slice 1 of 4.11.7 includes the descriptor and +the mover's frames; each later slice moves its class onto them. ## 5. A mind's context and the engine it runs on From 6830b410a7ecb639d436122626ff10d2843d370d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 16:32:59 -0600 Subject: [PATCH 07/49] Design 4.11.6, Codex's review at 8fca64fd5: the commit fence is the GPU's completion of readers and the write (through the existing completion owner), not the server loop's position; an uncertain layer is never silently switched off: her acts that read it defer, typed, until restored or an authorized genome_set Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 4f2faad454..6b48ee303a 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -1827,10 +1827,12 @@ makes a separate version of her or a separate model. learning layers out), scheduled by the same scheduler on the same sequences; a generating act outranks it at the next decode boundary, so she is never dark. - **A step becomes visible whole, at one fence** (Codex on #6092). Gradients accumulate in the optimizer's own - buffers; the layer's weights change only when a step commits, and the commit runs on the server loop between two - decode batches, the one point where no act is reading the layer. An act therefore sees step `s` or step `s+1` - for a whole decode batch, never a partial write. No second persona or shadow model is needed: the fence - serializes the one writer against the readers. + buffers; the layer's weights change only when a step commits. The fence is the device's, not the server loop's + position: the commit waits until every decode batch that read the layer has COMPLETED on the GPU, and no batch + that reads the layer is submitted until the commit's write has completed there, both observed through the + existing completion owner (the one that settles transfers and acts), never inferred from where the loop is. An + act therefore sees step `s` or step `s+1` for a whole decode batch, never a partial write. No second persona or + shadow model is needed: the fence serializes the one writer against the readers. - **Every act reports what it actually saw.** An act spanning several commits reports each observation `(layer, step, first token, last token)`, not one label for its whole output; a reply is attributed to the exact weights that produced each part of it. @@ -1842,9 +1844,11 @@ makes a separate version of her or a separate model. recomputed for it. A test proves that the same prefix under two steps gives different logits and that the stamp catches it. - **An interrupted step is neither step.** A commit that fails or is cut off leaves the layer `uncertain` (the - optimizer's existing quarantine, `llama_opt_shadow_quarantined`): it is switched off for every act (scale 0) and - stays so until the layer registry restores its last durable step. It is never reported as the step before or - after. + optimizer's existing quarantine, `llama_opt_shadow_quarantined`). It is never reported as the step before or + after, and it is never silently switched off: setting it to scale 0 would change her genome without anyone + deciding to (Codex on #6092). An act of hers that would read it gets a typed `deferred { layer_uncertain }` + until the layer registry restores its last durable step, or until an explicit, authorized `genome_set` changes + her genome, recorded with its observations like any other genome change. - **A durable step is weights plus optimizer.** Saving for resumed learning writes the layer's weights, its optimizer state (moments) and its step metadata (step count, schedule position) as components, then publishes their manifest last, atomically; a save with any component missing has no manifest and does not exist. From 365cab06c1d6c397054c35116e615b66fafbc6b3 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 18:24:30 -0600 Subject: [PATCH 08/49] Design 4.11.9: every mind resident, admission by live cells, the scheduler only picks who decodes (Joel: "Very unreliable logic. It just gives up and breaks.") The M5 read after #6093: rotation fixed, but one mind seated at a time (grants 158-207k = untrimmed view x 1.25 vs a 300,850 pool; real sequences 50-93k), so four residents never batched. Admission summing view ceilings is the defect; the owed queue / BehindActs / reclaim handoffs / armed yields exist only to cope with it. Replacement: residency via #139, one memory owner admitting by engine-reported live cells with paging and typed deferral, grants only as view ceilings, scheduler picks who decodes and batches every ready mind. Gate: four resident, batched decode, aggregate tok/s vs 80. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 36 +++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 6b48ee303a..196b373986 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -1956,6 +1956,42 @@ descriptor. So learning on is one more class appearing in the same table, under page and a checkpoint move, spill, defer and come back the same way. Slice 1 of 4.11.7 includes the descriptor and the mover's frames; each later slice moves its class onto them. +#### 4.11.9 Every mind resident; admission by live cells; the scheduler only picks who decodes + +Joel, 2026-11-17, on the M5 read: "So it needs rewrite? Very unreliable logic. It just gives up and breaks." + +**What the M5 showed (build 5a754ad98, engine 14844, 2026-11-17 00:06-00:21Z).** The starvation fix (#6093) works: +seats rotated strictly oldest-owed with no re-entry, three times. But only ONE mind was ever seated. Each grant was +158-207k tokens (her whole untrimmed view x `SENT_HEADROOM` 1.25, `window_grant.rs:398-410`), the pool is 300,850, +and the engine runs 5 lanes, so four residents decoded strictly one after another and never batched. Her real +sequence per act (engine `n_past`) was 50-93k; all four together are about the pool. The code's own premise, "a grant +is a ceiling, not an allocation: KV is paged on use", is contradicted by admission, which sums grants against the +pool. Everything built to cope with that (the owed queue, `BehindActs` waits, reclaim handoffs and receipts, armed +yields, seat publications) exists only because a ceiling is treated as an allocation, and it fails by waiting: Aiko +held one turn ~3 h on 2026-11-16. + +**The replacement:** +1. **Every resident mind is resident, always.** She is a sequence of the engine's unified pool (fork #139): decoding + on a lane, or parked beside the lanes, or paged to RAM or flash. There is no seat and no wait for one. +2. **One memory owner admits by live cells** (4.11.8). Her charge is the cells her sequence actually holds, as the + engine's allocator reports them, never her view's ceiling. When live use exceeds the grant from `ResourceDaemon`, + the coldest mind's resources go down a tier (by activity temperature), and are streamed back ahead of her next act + (`prefetch`). When no legal move exists, the act gets a typed deferral (4.11.8), never an unbounded wait. +3. **Her grant survives only as her view's ceiling:** how much she renders whole (the Aris collapse spiral of + 2026-11-13 is why it is sized to her wish). It never decides whether she runs. +4. **The scheduler decides only who decodes next** (goal 9): activity temperature as priority, aging so no mind is + starved, and every ready mind batched into the same decode step, so throughput is the engine's aggregate rate, not + one stream's. + +**Deleted:** the owed queue, `DispatchWait::BehindActs`, reclaim handoffs and their receipts, `yield_after` arming, +seat publications and grant revisions as admission (`lease/fair.rs` and the reservation paths that serve it). + +**Owners:** residency and the memory owner (Fable: #139, 4.11.8, contract slices 3-4); the scheduler (Codex, goal 9). + +**Gate (on the M5, the four residents, the 35B):** all four resident at once with no `delib.window.waiting`; batched +decode (more than one sequence per decode step) observed; aggregate decode tok/s against the 80 tok/s target; switch +receipts in milliseconds; no mind's act waiting more than one decode step behind a resident with memory free. + ## 5. A mind's context and the engine it runs on **Focus boundary:** [Focus contract](FOCUS-CONTRACT.md) defines one allocation, From dea7cb7c76e4f937ce05d28ada3867eff12fd523 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 18:28:40 -0600 Subject: [PATCH 09/49] Design 4.12: the serving modules, one intentional architecture (Joel: "Need reliable service modules. No more patches. Ideal architecture.") Every serving concern owned by exactly one module: core ServiceModules EngineLink, MemoryOwner, Residency, Scheduler, Learning, ServingObserver; engine modules dispatcher, resident-minds table, checkpoint_store, layer registry, mover, batcher. Each row names what it owns, its typed verbs and what is deleted when it lands. Seven rules every module obeys (one owner per state, typed outcomes, no unbounded waits or polling, fail loud and supervised, simulator first, lands with its deletions, measured live). Order: ServingObserver first. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 51 +++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 196b373986..c0d02c4491 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -1992,6 +1992,57 @@ seat publications and grant revisions as admission (`lease/fair.rs` and the rese decode (more than one sequence per decode step) observed; aggregate decode tok/s against the 80 tok/s target; switch receipts in milliseconds; no mind's act waiting more than one decode step behind a resident with memory free. +### 4.12 The serving modules: one intentional architecture, no patchwork (2026-11-17) + +Joel, 2026-11-17: "Need reliable service modules. No more patches. Ideal architecture. We have zero need for shit +patchwork. We need a solid architecture that's intentional." + +What the M5 showed the same night: a dispatcher patched twice (#6093 and a resize hole) whose design was the defect; a +grant policy whose own comment ("a ceiling, not an allocation") its admission contradicts; learning adapters written +and swapped beside serving with no one owning the trade (402 fresh adapters in one engine log); single-stream decode +at 24% of par with nobody owning throughput. Each piece had a reason; together they had no owner and no shape. This +section is the shape. Every serving concern belongs to exactly one module below, and a concern with no row is not +built. + +**Core modules** (each a kernel `ServiceModule`, `continuum-kernel/src/runtime/service_module.rs`): + +| Module | The one thing it owns | Typed verbs (others call) | Replaces, deleted when it lands | +|---|---|---|---| +| `EngineLink` | the engine connection: attach, descriptor, instance, in-flight act custody (4.11.3-5) | `act`, `cancel`, `prefetch`, `release`, `genome_set`, `describe` | request building in `stream.rs`, `minds.rs`, `slots/discover.rs`; `/props` parsing; the JSON routes | +| `MemoryOwner` | every byte the engine holds for a mind, by live cells, under `ResourceDaemon` grants (4.11.8) | `charge`, `make_room`, `page(mind, tier)`, reads: `resident(mind)` | window grants as admission, `lease/fair.rs` dispatch, prompt-cache sizing as its own policy | +| `Residency` | each mind's place: logically resident always; GPU / RAM / flash tier (4.11.9) | reads only (snapshot); moves are `MemoryOwner`'s | seats, the owed queue, reclaim handoffs, armed yields | +| `Scheduler` | who decodes next: activity temperature, aging, batch size by the measured cost curve (goal 9) | `ready(mind, act)`, reads: `next_batch` | `BehindActs`, `delib.window.waiting` polling, lane selection | +| `Learning` | the genome's learning switch and duty: share by wakefulness, learning acts through the same path (4.11.6) | `set_learning(layer, on)`, `duty(share, mode)` | ad hoc fresh-adapter writes and swaps beside serving; `/train*` | +| `ServingObserver` | the numbers: aggregate decode tok/s, per-mind acts/h, switch ms, waits, memory, learning share | reads only; publishes a snapshot | scattered probes nobody aggregates; it decides nothing | + +**Engine modules** (each an engine module, `server-module.h`, all on the one server loop that owns the llama +context): the frame dispatcher (validates and routes, 4.11.3); the resident-minds table (sequence ids, park/flash, +#139); each mind's `checkpoint_store` (#140); the layer registry (layers, steps, learning state); the mover +(`memory_mover`, every tier change); the batcher (`update_slots`: decode and learning steps in one schedule, fenced +per 4.11.6). + +**Rules every module obeys** (a module that cannot meet one is redesigned, not excepted): +1. **One owner per state.** Only the owner mutates it; others read its published snapshot (a watch channel in Rust, + `snapshot_cell` in the engine). No shared mutable state between modules, no lock held across a call. +2. **Typed verbs, typed outcomes.** Every call returns an enum naming each outcome (done, deferred-with-reason, + refused-with-reason). No `String` errors, no `Option` for a state, no default on an unknown tag. +3. **Nothing waits unbounded or polls.** A wait is a typed deferral naming the event that ends it, and that event + wakes the waiter. A 5-second "still waiting" loop (`delib.window.waiting`) is a defect by definition. +4. **Fail loud, recover by design.** A module's failure is a typed event its supervisor handles: restart from its + durable snapshot, or degrade to a declared mode. Never a silent fallback path. +5. **Simulator first** (section 7.0). Each module's invariants (no mind starved, budget never exceeded, no state + lost, a learning step never visible half-done) are simulator assertions before code, and tonight's M5 logs + become replay scenarios. +6. **A module lands with its deletions.** The "Replaces" column is deleted in the same change. A new module beside + an old path is patchwork. +7. **Measured on the live node before it is called done.** `ServingObserver`'s numbers before and after, the gate + of 4.11.9. + +**Order:** `ServingObserver` first (measure before changing anything; it also makes tonight's two throughput causes +visible continuously). Then `EngineLink` (contract slices 1-3). Then `MemoryOwner` with `Residency`, on #139 and +4.11.8 (Fable). Then `Scheduler` (Codex, goal 9). Then `Learning` duty. Each is one vertical change with its +deletions and its simulator scenarios. + ## 5. A mind's context and the engine it runs on **Focus boundary:** [Focus contract](FOCUS-CONTRACT.md) defines one allocation, From 7ee284100a86a122798e9d342ed0552691a3e9c3 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 18:29:40 -0600 Subject: [PATCH 10/49] Design 4.11.9/4.12, Codex's review of 365cab06c: admission reserves physical cost before each allocation (allocator bytes incl shared prefix once, draft KV, checkpoints, learning workspace, transfers; never n_past); custody and save-before-release stay with the completion owner; batch size by the measured concurrency cost curve and budgets, no hard-coded count; logical vs GPU residency gated separately; contention replay with no legal eviction as a gate; the read window corrected to 00:09:35-00:24:35 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 42 ++++++++++++++++++--------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index c0d02c4491..25d50a2c24 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -1960,7 +1960,7 @@ the mover's frames; each later slice moves its class onto them. Joel, 2026-11-17, on the M5 read: "So it needs rewrite? Very unreliable logic. It just gives up and breaks." -**What the M5 showed (build 5a754ad98, engine 14844, 2026-11-17 00:06-00:21Z).** The starvation fix (#6093) works: +**What the M5 showed (build 5a754ad98 verified 00:09:35Z, engine 14844; the 15-minute read 00:09:35-00:24:35Z).** The starvation fix (#6093) works: seats rotated strictly oldest-owed with no re-entry, three times. But only ONE mind was ever seated. Each grant was 158-207k tokens (her whole untrimmed view x `SENT_HEADROOM` 1.25, `window_grant.rs:398-410`), the pool is 300,850, and the engine runs 5 lanes, so four residents decoded strictly one after another and never batched. Her real @@ -1973,24 +1973,38 @@ held one turn ~3 h on 2026-11-16. **The replacement:** 1. **Every resident mind is resident, always.** She is a sequence of the engine's unified pool (fork #139): decoding on a lane, or parked beside the lanes, or paged to RAM or flash. There is no seat and no wait for one. -2. **One memory owner admits by live cells** (4.11.8). Her charge is the cells her sequence actually holds, as the - engine's allocator reports them, never her view's ceiling. When live use exceeds the grant from `ResourceDaemon`, - the coldest mind's resources go down a tier (by activity temperature), and are streamed back ahead of her next act - (`prefetch`). When no legal move exists, the act gets a typed deferral (4.11.8), never an unbounded wait. +2. **One memory owner admits by physical cost, incrementally, BEFORE it is spent** (4.11.8; Codex on #6092). Each + prefill or decode step reserves the physical capacity it is about to allocate, under the grant from + `ResourceDaemon`, before allocating: never exceed first and page after. The bill is the engine allocator's + physical bytes and cells, not `n_past` (which is only evidence of logical context): shared-prefix cells counted + once, the draft's KV, checkpoints, the learning workspace and transfers in flight. When a reservation would exceed + the grant, the coldest mind's resources go down a tier first (by activity temperature) and are streamed back ahead + of her next act (`prefetch`). When no legal move exists, the step gets a typed deferral (4.11.8) that ends on a + named release event, never an unbounded wait. 3. **Her grant survives only as her view's ceiling:** how much she renders whole (the Aris collapse spiral of 2026-11-13 is why it is sized to her wish). It never decides whether she runs. -4. **The scheduler decides only who decodes next** (goal 9): activity temperature as priority, aging so no mind is - starved, and every ready mind batched into the same decode step, so throughput is the engine's aggregate rate, not - one stream's. +4. **The scheduler decides only who decodes next** (goal 9): activity temperature as priority, aging so no eligible + mind is starved, and as many ready minds batched into one decode step as the MEASURED per-node, per-model + concurrency cost curve and the step and latency budgets allow, after physical admission (Codex on #6092). No + concurrency count is hard-coded and one-step service is not promised when ready demand exceeds those budgets; + batching is judged against the cost curve. +5. **Custody stays where it is proven.** The existing completion owner keeps terminal, cancellation and fence custody + and the save-before-release proofs; the grant-specific handoff APIs are deleted only once their callers use the + shared mover's equivalent proof. A dropped or cancelled request never authorizes reuse of live GPU memory. +6. **Logical residency is not GPU residency.** A parked or paged mind keeps her identity and state (logically + resident); it is never a claim that every mind's KV is on the GPU at once. The two states are gated separately. **Deleted:** the owed queue, `DispatchWait::BehindActs`, reclaim handoffs and their receipts, `yield_after` arming, seat publications and grant revisions as admission (`lease/fair.rs` and the reservation paths that serve it). **Owners:** residency and the memory owner (Fable: #139, 4.11.8, contract slices 3-4); the scheduler (Codex, goal 9). -**Gate (on the M5, the four residents, the 35B):** all four resident at once with no `delib.window.waiting`; batched -decode (more than one sequence per decode step) observed; aggregate decode tok/s against the 80 tok/s target; switch -receipts in milliseconds; no mind's act waiting more than one decode step behind a resident with memory free. +**Gates.** In the simulator and replay first: a contention replay where the aggregate active working sets exceed the +pool and no legal eviction exists proves a bounded typed deferral and progress after a legal release; tonight's M5 +logs replay without a starved mind. Then on the M5 (the four residents, the 35B): all four logically resident with no +`delib.window.waiting`; batched decode (more than one sequence per decode step) observed and measured against the +concurrency cost curve; aggregate decode tok/s against the 80 tok/s target; switch receipts in milliseconds; the +physical charge never above the `ResourceDaemon` grant. ### 4.12 The serving modules: one intentional architecture, no patchwork (2026-11-17) @@ -2009,9 +2023,9 @@ built. | Module | The one thing it owns | Typed verbs (others call) | Replaces, deleted when it lands | |---|---|---|---| | `EngineLink` | the engine connection: attach, descriptor, instance, in-flight act custody (4.11.3-5) | `act`, `cancel`, `prefetch`, `release`, `genome_set`, `describe` | request building in `stream.rs`, `minds.rs`, `slots/discover.rs`; `/props` parsing; the JSON routes | -| `MemoryOwner` | every byte the engine holds for a mind, by live cells, under `ResourceDaemon` grants (4.11.8) | `charge`, `make_room`, `page(mind, tier)`, reads: `resident(mind)` | window grants as admission, `lease/fair.rs` dispatch, prompt-cache sizing as its own policy | -| `Residency` | each mind's place: logically resident always; GPU / RAM / flash tier (4.11.9) | reads only (snapshot); moves are `MemoryOwner`'s | seats, the owed queue, reclaim handoffs, armed yields | -| `Scheduler` | who decodes next: activity temperature, aging, batch size by the measured cost curve (goal 9) | `ready(mind, act)`, reads: `next_batch` | `BehindActs`, `delib.window.waiting` polling, lane selection | +| `MemoryOwner` | every byte the engine holds for a mind, by physical cost reserved before each allocation, under `ResourceDaemon` grants (4.11.8, 4.11.9 points 2 and 5) | `charge`, `make_room`, `page(mind, tier)`, reads: `resident(mind)` | window grants as admission, `lease/fair.rs` dispatch, prompt-cache sizing as its own policy | +| `Residency` | each mind's place: logically resident always; GPU / RAM / flash tier, gated separately (4.11.9 point 6) | reads only (snapshot); moves are `MemoryOwner`'s | seats, the owed queue, reclaim handoffs, armed yields | +| `Scheduler` | who decodes next: activity temperature, aging among eligible minds, batch size by the measured concurrency cost curve and step/latency budgets (goal 9, 4.11.9 point 4) | `ready(mind, act)`, reads: `next_batch` | `BehindActs`, `delib.window.waiting` polling, lane selection | | `Learning` | the genome's learning switch and duty: share by wakefulness, learning acts through the same path (4.11.6) | `set_learning(layer, on)`, `duty(share, mode)` | ad hoc fresh-adapter writes and swaps beside serving; `/train*` | | `ServingObserver` | the numbers: aggregate decode tok/s, per-mind acts/h, switch ms, waits, memory, learning share | reads only; publishes a snapshot | scattered probes nobody aggregates; it decides nothing | From accd9e5955b13d1d45fd6ac33f430873e13d473e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 18:33:38 -0600 Subject: [PATCH 11/49] Design 4.13: one frame loop owns the GPU timeline, so nothing interferes with itself (Joel: "it's got to be smarter and not interfere with itself") The engine's batcher is the only submitter of GPU work; each frame composes decode (batched, first), chunked prefill (filling the step budget) and learning (only in leftover budget, up to its duty share) against costs measured per frame and fed back into the curves; memory moves run beside compute on the mover with lookahead prefetch; admission reserves physical memory before allocation; the core declares and the engine composes. Order: measure first. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 53 +++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 25d50a2c24..33da3f4163 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2057,6 +2057,59 @@ visible continuously). Then `EngineLink` (contract slices 1-3). Then `MemoryOwne 4.11.8 (Fable). Then `Scheduler` (Codex, goal 9). Then `Learning` duty. Each is one vertical change with its deletions and its simulator scenarios. +### 4.13 One frame loop owns the GPU timeline, so nothing interferes with itself (2026-11-17, design for review) + +Joel, 2026-11-17: "Yeah it's got to be smarter and not interfere with itself. Think about what needs to happen and plan +a good architecture." + +**What interferes today (the M5, 2026-11-16/17):** learning writes and swaps adapters between decode steps with no one +weighing the cost (402 fresh adapters in one engine log); one mind's 50-93k prefill stalls every other mind's decode; +view-sized grants serialize the minds (4.11.9); checkpoint misses force full re-prefills; the core polls. Each part is +locally reasonable and none arbitrates, so single-stream decode ran at 24% of par (13.9 vs 56.1 tok/s) and four +residents never batched. + +**What must happen, continuously:** (1) decode, one token per active mind per step, latency-critical, and the source +of aggregate throughput when several minds batch; (2) prefill, large and bursty, for minds starting or resuming an +act; (3) memory movement of KV, checkpoints and layers between tiers, and prefetch of the next minds; (4) learning, +optimizer steps on the genome's layers at a duty share (4.11.6); (5) persistence, durable state for restarts. + +**The architecture: one frame loop.** +- **The engine's batcher is the only submitter of GPU work.** Every other part submits a typed job to it (decode + tokens, a prefill chunk, a learning step); nothing else touches the llama context or the device. One timeline, one + owner: interference has no path. +- **Each frame (one decode step) is composed by priority against a measured time budget:** + 1. decode for every active mind, batched, first, always; + 2. prefill in chunks that fill the rest of the step budget, so no prompt stalls the others' decode; + 3. learning micro-steps only in the budget left, up to the duty share; when minds are idle the slack is large, + and that is when dreaming runs. A learning step commits at the fence of 4.11.6. +- **Costs are measured, never constants.** Each frame records what every job actually cost (by job type, batch size, + context length); the cost curves the next frame is composed from are updated from those records. The engine tunes + itself to its hardware and model, and the same records are `ServingObserver`'s numbers (4.12). +- **Memory moves run beside compute**, on the mover's own queue (`memory_mover`): a re-tag within unified memory, an + asynchronous copy elsewhere. The scheduler's lookahead (who acts next) drives prefetch, so a switch is never on the + critical path. +- **Admission is physical and before allocation** (4.11.9 point 2): a job enters a frame only with its memory + reserved; the coldest mind's resources move down a tier first; with no legal move, the job is deferred, typed, with + the event that wakes it. +- **The core declares, the engine composes.** Core modules decide what each mind wants and when (`Scheduler`, + `Learning`, `MemoryOwner`, 4.12) and send it as frames through `EngineLink` (4.11.3); the core never sequences GPU + work. + +**Why it cannot interfere with itself:** one owner per resource and one timeline for the device; priorities written +down, not emergent; every cost measured; every wait a typed event, never a poll. + +**Order, each step proven before the next:** +1. **Measure.** The engine records per-frame costs (decode, prefill, learning, by batch and context) and + `ServingObserver` aggregates them, separating the two throughput causes of 2026-11-17 with data. Changes nothing. +2. **Contract and `EngineLink`** (4.11, slice 1 drafted: llama.cpp#141, continuum #6094). +3. **The frame loop in the engine:** the batcher composes decode, chunked prefill and learning by priority against + the measured budget; learning moves into it (the adapter churn beside serving ends). +4. **Residency and `MemoryOwner`** (4.11.8-9): every mind resident, admission by physical reservation, prefetch on + lookahead; the grant dispatcher is deleted. +5. **`Scheduler`** (Codex, goal 9): who is active and how many per frame, from the measured cost curve. +6. **The gate on the M5:** four residents batched, aggregate decode tok/s against 80, switches in milliseconds, + learning within its share without slowing decode beyond it. + ## 5. A mind's context and the engine it runs on **Focus boundary:** [Focus contract](FOCUS-CONTRACT.md) defines one allocation, From af507b0f6252b46c81c4b8cbcabdcd0fc50da9c4 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 18:36:38 -0600 Subject: [PATCH 12/49] Design 4.12/4.13, Codex's review of accd9e595: policy in the core, enforcement in the engine allocator (no per-token RPC, Residency a projection of the one authority); one device dependency authority with the mover's async copies submitted under it; decode-first bounded by aging and a typed overload outcome; admitted active set; the 402 fresh-adapter and 24%-of-par readings labelled observations, not causes; one implementation order; measurement as raw numeric frames reusing the capture owner Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 52 ++++++++++++++++++--------- 1 file changed, 35 insertions(+), 17 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 33da3f4163..0a583648e7 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2012,9 +2012,11 @@ Joel, 2026-11-17: "Need reliable service modules. No more patches. Ideal archite patchwork. We need a solid architecture that's intentional." What the M5 showed the same night: a dispatcher patched twice (#6093 and a resize hole) whose design was the defect; a -grant policy whose own comment ("a ceiling, not an allocation") its admission contradicts; learning adapters written -and swapped beside serving with no one owning the trade (402 fresh adapters in one engine log); single-stream decode -at 24% of par with nobody owning throughput. Each piece had a reason; together they had no owner and no shape. This +grant policy whose own comment ("a ceiling, not an allocation") its admission contradicts; learning work beside +serving with no one owning the trade; single-stream decode at 24% of par with nobody owning throughput. (Observations, +not attributions: 402 `common_lora_write_fresh` lines in one engine log are not by themselves 402 destructive swaps, +since an earlier inspection found durable checkpoint reseating among them; and the 24% read was taken with 5.2 GB of +swap in use and resident builds, so it names no cause. Per-frame evidence, 4.13 step 1, attributes costs.) Each piece had a reason; together they had no owner and no shape. This section is the shape. Every serving concern belongs to exactly one module below, and a concern with no row is not built. @@ -2035,6 +2037,12 @@ context): the frame dispatcher (validates and routes, 4.11.3); the resident-mind (`memory_mover`, every tier change); the batcher (`update_slots`: decode and learning steps in one schedule, fenced per 4.11.6). +**Policy in the core, enforcement in the engine** (Codex on #6092). `ResourceDaemon` issues bounded grants; the +engine's own allocator reserves each job's physical delta locally inside the grant. There is no core call per token or +allocation, and no second authoritative ledger: `MemoryOwner` in the core holds the grant and the policy (which tier a +cold mind goes to, what to prefetch) and reads the engine's reported physical state; `Residency` is a read-only +projection of that one authority, never a mutable copy. + **Rules every module obeys** (a module that cannot meet one is redesigned, not excepted): 1. **One owner per state.** Only the owner mutates it; others read its published snapshot (a watch channel in Rust, `snapshot_cell` in the engine). No shared mutable state between modules, no lock held across a call. @@ -2052,10 +2060,8 @@ per 4.11.6). 7. **Measured on the live node before it is called done.** `ServingObserver`'s numbers before and after, the gate of 4.11.9. -**Order:** `ServingObserver` first (measure before changing anything; it also makes tonight's two throughput causes -visible continuously). Then `EngineLink` (contract slices 1-3). Then `MemoryOwner` with `Residency`, on #139 and -4.11.8 (Fable). Then `Scheduler` (Codex, goal 9). Then `Learning` duty. Each is one vertical change with its -deletions and its simulator scenarios. +**Order:** one order for 4.12 and 4.13, given in 4.13 ("Order"). Each step is one vertical change: the native contract +frames and every endpoint caller of that step move together, with its deletions and its simulator scenarios. ### 4.13 One frame loop owns the GPU timeline, so nothing interferes with itself (2026-11-17, design for review) @@ -2078,16 +2084,24 @@ optimizer steps on the genome's layers at a duty share (4.11.6); (5) persistence tokens, a prefill chunk, a learning step); nothing else touches the llama context or the device. One timeline, one owner: interference has no path. - **Each frame (one decode step) is composed by priority against a measured time budget:** - 1. decode for every active mind, batched, first, always; + 1. decode for every mind in the ADMITTED active set (bounded by the measured concurrency limit, 4.11.9 point 4), + batched, first; 2. prefill in chunks that fill the rest of the step budget, so no prompt stalls the others' decode; - 3. learning micro-steps only in the budget left, up to the duty share; when minds are idle the slack is large, - and that is when dreaming runs. A learning step commits at the fence of 4.11.6. + 3. learning micro-steps in the budget left, up to the duty share; when minds are idle the slack is large, and that + is when dreaming runs. A learning step commits at the fence of 4.11.6. +- **Decode-first never starves the rest** (Codex on #6092). Prefill and learning age: each waiting job carries a + bounded service guarantee (a minimum share of frames once it has waited past its bound), so saturating decode cannot + postpone them forever. When even that cannot be met, the job gets an explicit overload outcome, typed, with its wake + event, cancellation and deadline, never a silent wait. - **Costs are measured, never constants.** Each frame records what every job actually cost (by job type, batch size, context length); the cost curves the next frame is composed from are updated from those records. The engine tunes itself to its hardware and model, and the same records are `ServingObserver`'s numbers (4.12). -- **Memory moves run beside compute**, on the mover's own queue (`memory_mover`): a re-tag within unified memory, an - asynchronous copy elsewhere. The scheduler's lookahead (who acts next) drives prefetch, so a switch is never on the - critical path. +- **One dependency and admission authority for the device** (Codex on #6092). Copies, compute and layer writes are all + admitted under the frame loop's timeline and completion dependencies. The mover (`memory_mover`) still executes + asynchronously on its own queue (a re-tag within unified memory, an asynchronous copy elsewhere) and independent + copies are not serialized, but its device work is submitted with the batcher's dependencies, and copy bandwidth and + retained bytes are accounted. The scheduler's lookahead (who acts next) drives prefetch, so a switch is OFF the + critical path in the planned case; cold misses and transfer failures still cost, and are measured, not assumed away. - **Admission is physical and before allocation** (4.11.9 point 2): a job enters a frame only with its memory reserved; the coldest mind's resources move down a tier first; with no legal move, the job is deferred, typed, with the event that wakes it. @@ -2095,12 +2109,16 @@ optimizer steps on the genome's layers at a duty share (4.11.6); (5) persistence `Learning`, `MemoryOwner`, 4.12) and send it as frames through `EngineLink` (4.11.3); the core never sequences GPU work. -**Why it cannot interfere with itself:** one owner per resource and one timeline for the device; priorities written -down, not emergent; every cost measured; every wait a typed event, never a poll. +**Why the parts stop interfering by design:** one owner per resource and one dependency authority for the device; +priorities and their bounds written down, not emergent; every cost measured; every wait a typed event, never a poll. +This is a design claim, proven only by replaying saturation, cold misses and transfer failures and measuring them, +not asserted. **Order, each step proven before the next:** -1. **Measure.** The engine records per-frame costs (decode, prefill, learning, by batch and context) and - `ServingObserver` aggregates them, separating the two throughput causes of 2026-11-17 with data. Changes nothing. +1. **Measure.** The engine records per-frame costs (decode, prefill, learning, by batch and context) as raw numeric + frames in a fixed ring (bounded; its recording overhead measured and dropped frames reported), reusing the typed + capture and counter owner, and `ServingObserver` aggregates them, separating the two throughput causes of + 2026-11-17 with data. JSON only as an external export. Changes no behaviour. 2. **Contract and `EngineLink`** (4.11, slice 1 drafted: llama.cpp#141, continuum #6094). 3. **The frame loop in the engine:** the batcher composes decode, chunked prefill and learning by priority against the measured budget; learning moves into it (the adapter churn beside serving ends). From d20387a4751936b9857d92d72e8cb73ed1d89370 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 19:04:18 -0600 Subject: [PATCH 13/49] Design 4.12 rule 6: no guessing recovery (Joel: "your error handling actually causes errors and timeouts. Same with fallbacks... You'd be better off without") No synthetic probe with a guessed timeout may kill, restart, evict or reset; liveness is real progress (frames advancing while work is queued); no fallback, retry loop or client timeout on slow work. Receipt: the lane decode heartbeat (DECODE_SMOKE_TIMEOUT, 10 s that 'killed healthy lanes all night', re-guessed to 75 s) and BigMama's 13 lane kill-and-respawns in 106 minutes (#6056). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 0a583648e7..a6e882d6c6 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2055,9 +2055,18 @@ projection of that one authority, never a mutable copy. 5. **Simulator first** (section 7.0). Each module's invariants (no mind starved, budget never exceeded, no state lost, a learning step never visible half-done) are simulator assertions before code, and tonight's M5 logs become replay scenarios. -6. **A module lands with its deletions.** The "Replaces" column is deleted in the same change. A new module beside +6. **No guessing recovery** (Joel, 2026-11-17: "your error handling actually causes errors and timeouts. Same with + fallbacks... They all do the opposite of their intention. You'd be better off without"). No synthetic probe with a + guessed timeout may kill, restart, evict or reset anything; liveness is real progress (the engine's frames advancing + while work is queued, 4.13) and a stall is a typed fact to its owner, not a kill. No fallback path, no retry loop, + no client timeout on work that is merely slow: wait on its completion event. The receipt: the lane decode + heartbeat (`llama_server` `DECODE_SMOKE_TIMEOUT`, a 10 s guess that "killed healthy lanes all night", re-guessed + to 75 s) queues behind real prefills, and BigMama logged 13 lane kill-and-respawns in 106 minutes (#6056), each + restarting every mind. A rule a module cannot meet means the module is redesigned. Every timeout, retry, fallback + or self-heal a module adds states what it destroys on a false positive; if anything, it is not added. +7. **A module lands with its deletions.** The "Replaces" column is deleted in the same change. A new module beside an old path is patchwork. -7. **Measured on the live node before it is called done.** `ServingObserver`'s numbers before and after, the gate +8. **Measured on the live node before it is called done.** `ServingObserver`'s numbers before and after, the gate of 4.11.9. **Order:** one order for 4.12 and 4.13, given in 4.13 ("Order"). Each step is one vertical change: the native contract From ccd3909f0cfed0938987e3ad101d6681dff0ce4f Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 19:20:19 -0600 Subject: [PATCH 14/49] Design 4.11.10: the engine half of admission, reserve before decode and park the coldest instead of the KV-full ladder The BigMama chain (unified-pool overcommit -> halve-and-retry to 2/1 tokens -> MTP verify straddles sub-batches -> #24840 throw -> slot error -> core relaunch) replaced by: reserve each frame's cells before decode (ladder deleted), park the coldest unpinned resident not in the frame to RAM (#139) with prefetch on return, typed deferral when none can move, refusal at admission for a request that can never fit, frames never split so speculation stays whole. Prior art cited: unslothai/llama.cpp#184. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 36 +++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index a6e882d6c6..04cd665ccd 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2006,6 +2006,42 @@ logs replay without a starved mind. Then on the M5 (the four residents, the 35B) concurrency cost curve; aggregate decode tok/s against the 80 tok/s target; switch receipts in milliseconds; the physical charge never above the `ResourceDaemon` grant. +### 4.11.10 The engine half of admission: reserve before decode, park instead of the KV-full ladder (2026-11-17, design for review) + +**The failure it replaces (BigMama, 2026-11-16, retained probes 07:13-07:16 and 23:21-23:59).** With `--kv-unified +--parallel N` every slot is told it may hold the whole context while all of them share one pool. Minds that each fit +grow into the pool together; when the next decode does not fit, `decode()` halves the batch and retries +(`server-context.cpp` "failed to find free space in the KV cache, retrying with smaller batch size") down to 2 and 1 +tokens; MTP verification tokens then straddle sub-batches and `post_decode` throws "speculative batch index 2 is not +inside the current sub-batch [0, 2)" (the open upstream TODO ggml-org/llama.cpp#24840); the slot is released with an +error, and the core's streak counted it as engine death and relaunched the lane, every mind with it. Three handlers, +each producing the next failure. The same shape is reported in other forks (halo-box/strix-llama.cpp#239, closed as +overcommit with the wrong error; unslothai/llama.cpp#184, open, which parks a slot to host RAM instead of the ladder: +prior art for this section). + +**The design.** +1. **Reserve, then decode.** Before a frame decodes, the batcher computes the cells each sequence in it will occupy + (its new tokens, its draft's verification tokens, the draft model's own cells) and reserves them in the pool. A + frame never asks `llama_decode` for cells the pool does not have; the KV-full ladder (halve and retry) is deleted. +2. **Make room by moving the coldest, never by failing a slot.** When the reservation does not fit, the mover parks + the coldest resident sequence that is not in this frame and not pinned (activity temperature, 4.11.9): its cells + go to RAM (the #139 park, `llama_state_seq_get_data_ext`), its task stays alive, and it is restored ahead of its + next decode (`prefetch`). Each move is a typed `placed` event with its cost. +3. **When nothing can legally move, defer, typed.** If every other resident is in the frame or pinned, the sequence + whose reservation does not fit leaves this frame with a typed `deferred(no_room, wakes_on = release)` and the + others decode; it rejoins on the release event. No slot is failed, no request gets a 500, nothing is relaunched. +4. **A request that can never fit is refused at admission**, before any decode, typed (`exceeds_pool`), never + discovered mid-generation. +5. **Speculation within a frame is whole.** Because a frame is reserved before it decodes, it is never split, so a + slot's verification tokens never straddle sub-batches and the #24840 throw has no path (it stays as an assertion, + not a handled case). + +**Gates.** Simulator and replay first: the BigMama overcommit (two or more minds growing into one unified pool with +MTP) runs with no slot error, no 500, every mind progressing, a park and restore per pressure event; a fixture where +every other resident is pinned yields the typed deferral and progress after release. Then live on the M5 and BigMama: +zero "failed to find free space" and zero "not inside the current sub-batch" lines, parks and restores counted in the +frame records (4.13). + ### 4.12 The serving modules: one intentional architecture, no patchwork (2026-11-17) Joel, 2026-11-17: "Need reliable service modules. No more patches. Ideal architecture. We have zero need for shit From 2276ccd400b03d2a254e5767dacc2de2ca262c25 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 19:21:27 -0600 Subject: [PATCH 15/49] Design 4.11.10, Codex's invariants on ccd3909f0: reservation by the real allocator (fragmentation, contiguity, target+draft, ubatch geometry) with atomic rollback; parked RAM admitted by ResourceDaemon, no release before committed custody; deferral ages so all-growing-none-ending cannot deadlock; never-fits judged by declared maximum growth and re-judged on grant shrink; ordinary n_batch/n_ubatch splits stay, each MTP verification group kept whole within one evaluation unit; gates for both Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 35 +++++++++++++++++---------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 04cd665ccd..03838996ac 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2020,25 +2020,34 @@ overcommit with the wrong error; unslothai/llama.cpp#184, open, which parks a sl prior art for this section). **The design.** -1. **Reserve, then decode.** Before a frame decodes, the batcher computes the cells each sequence in it will occupy - (its new tokens, its draft's verification tokens, the draft model's own cells) and reserves them in the pool. A - frame never asks `llama_decode` for cells the pool does not have; the KV-full ladder (halve and retry) is deleted. +1. **Reserve, then decode.** Before a frame decodes, the engine's own KV allocator (not a scalar free-cell sum) + reserves the cells each sequence in it will occupy: its new tokens, its draft's verification tokens and the draft + model's own cells, with the pool's real fragmentation, contiguity and ubatch geometry. A failed reservation rolls + back atomically before any slot, sequence or batch state is changed. A frame never asks `llama_decode` for cells + the allocator has not reserved; the KV-full ladder (halve and retry) is deleted. 2. **Make room by moving the coldest, never by failing a slot.** When the reservation does not fit, the mover parks the coldest resident sequence that is not in this frame and not pinned (activity temperature, 4.11.9): its cells go to RAM (the #139 park, `llama_state_seq_get_data_ext`), its task stays alive, and it is restored ahead of its - next decode (`prefetch`). Each move is a typed `placed` event with its cost. -3. **When nothing can legally move, defer, typed.** If every other resident is in the frame or pinned, the sequence - whose reservation does not fit leaves this frame with a typed `deferred(no_room, wakes_on = release)` and the - others decode; it rejoins on the release event. No slot is failed, no request gets a 500, nothing is relaunched. -4. **A request that can never fit is refused at admission**, before any decode, typed (`exceeds_pool`), never - discovered mid-generation. -5. **Speculation within a frame is whole.** Because a frame is reserved before it decodes, it is never split, so a - slot's verification tokens never straddle sub-batches and the #24840 throw has no path (it stays as an assertion, - not a handled case). + next decode (`prefetch`). Each move is a typed `placed` event with its cost. Parked RAM is bounded and admitted by + `ResourceDaemon` like any other bytes, and no cells are released before the park's copy is committed (custody). +3. **When nothing can legally move, defer, typed, with guaranteed progress.** If every other resident is in the frame + or pinned, the sequence whose reservation does not fit leaves this frame with a typed `deferred(no_room)` and the + others decode. Waiting for a natural release alone can deadlock (every active sequence keeps growing and none + ends), so a deferred sequence ages: past its bound it outranks the coldest active one, which is parked at its next + frame boundary to make room. No slot is failed, no request gets a 500, nothing is relaunched. +4. **A request that can never fit is refused at admission**, before any decode, typed (`exceeds_pool`), judged by its + declared maximum growth (prompt plus its generation limit) against the pool it can be granted, and re-judged when + that grant shrinks; never by a guess at its future length, never discovered mid-generation. +5. **A speculative verification group is never split.** Reservation does not stop ordinary `n_batch`/`n_ubatch` + splitting of a large frame; the batcher places each MTP verification group wholly inside one evaluation unit, so + the #24840 throw has no path (it stays an assertion, not a handled case). Tested with normal splitting and under + pool pressure together. **Gates.** Simulator and replay first: the BigMama overcommit (two or more minds growing into one unified pool with MTP) runs with no slot error, no 500, every mind progressing, a park and restore per pressure event; a fixture where -every other resident is pinned yields the typed deferral and progress after release. Then live on the M5 and BigMama: +every other resident is pinned yields the typed deferral and progress after release; a fixture where every active +sequence keeps growing with no natural release still gives the deferred one progress through aging; a large prompt +split across ubatches with MTP on never splits a verification group. Then live on the M5 and BigMama: zero "failed to find free space" and zero "not inside the current sub-batch" lines, parks and restores counted in the frame records (4.13). From fef99dcf18bfd4f3ebfadefd2dd18b68060d795f Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 19:22:47 -0600 Subject: [PATCH 16/49] Design 4.11.10, Codex on 2276ccd40: aging never overrides pins, in-flight learning or fences, and ResourceDaemon may deny park RAM; with no legal displacement the outcome is an explicit blocked with its real wake sources, never a forced eviction; gates for all-pinned and host-denied Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 03838996ac..2ca8750b56 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2034,7 +2034,11 @@ prior art for this section). or pinned, the sequence whose reservation does not fit leaves this frame with a typed `deferred(no_room)` and the others decode. Waiting for a natural release alone can deadlock (every active sequence keeps growing and none ends), so a deferred sequence ages: past its bound it outranks the coldest active one, which is parked at its next - frame boundary to make room. No slot is failed, no request gets a 500, nothing is relaunched. + frame boundary to make room. Aging never overrides a genuine pin, an in-flight learning step or a fence, and + `ResourceDaemon` may refuse the park's RAM: progress is guaranteed only when a legal displacement exists. When none + does (every candidate pinned, or the host budget denies parking), the outcome is an explicit `blocked` with its real + wake sources (a pin released, a fence passed, host RAM granted), never a forced eviction. No slot is failed, no + request gets a 500, nothing is relaunched. 4. **A request that can never fit is refused at admission**, before any decode, typed (`exceeds_pool`), judged by its declared maximum growth (prompt plus its generation limit) against the pool it can be granted, and re-judged when that grant shrinks; never by a guess at its future length, never discovered mid-generation. @@ -2046,7 +2050,8 @@ prior art for this section). **Gates.** Simulator and replay first: the BigMama overcommit (two or more minds growing into one unified pool with MTP) runs with no slot error, no 500, every mind progressing, a park and restore per pressure event; a fixture where every other resident is pinned yields the typed deferral and progress after release; a fixture where every active -sequence keeps growing with no natural release still gives the deferred one progress through aging; a large prompt +sequence keeps growing with no natural release still gives the deferred one progress through aging; a fixture where every candidate is pinned, and one where +`ResourceDaemon` denies park RAM, each return `blocked` with their wake sources and never evict; a large prompt split across ubatches with MTP on never splits a verification group. Then live on the M5 and BigMama: zero "failed to find free space" and zero "not inside the current sub-batch" lines, parks and restores counted in the frame records (4.13). From e71886a8a692322bc1435b76414cb548b8ffa834 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 19:31:26 -0600 Subject: [PATCH 17/49] Design 4.11.10 implementation map: typed piece outcome, ladder and fail-all deleted, preempt the coldest legal processing slot via remove_slot + #139 flash_out into a bounded store, blocked with wake sources, resume with aging, draft failure reconciled to verified tokens; done and remaining pieces named Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 2ca8750b56..910daf6361 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2056,6 +2056,33 @@ split across ubatches with MTP on never splits a verification group. Then live o zero "failed to find free space" and zero "not inside the current sub-batch" lines, parks and restores counted in the frame records (4.13). +**4.11.10 implementation map (fork, agreed with Codex 2026-11-17; building blocks on `fable/admission-fit`).** +Mechanism: no new allocator or API. `llama_decode` already prepares (restoring) then consumes the same placement, and +returns 1 with nothing placed for that piece; pieces before it in the frame are placed and computed. +- Done: `server_batch` in `server-batch.h` (pure move); `remove_slot(id, from)` removes one slot's unplaced tokens + and returns the old-to-new index map; `test-server-batch` covers the middle slot with speculative groups on both + sides, embedding rows, and a prompt straddling a placed piece. +- `decode()` returns a typed `piece_outcome {placed, no_room, invalid, compute_error}`; it no longer sends errors or + clears prompts for every slot, and the `n_batch /= 2` ladder and the `n_batch == 1` "Context size has been exceeded" + fail-all are deleted. `n_queued_tokens` and output bookkeeping count only placed pieces. +- On `no_room` at piece `off`, the frame owner (the decode loop in `update_slots`) makes room, in order: move an idle + mind out (`flash_coldest`, then an idle lane's mind); else preempt the coldest processing slot that is not pinned, + learning or fenced: `remove_slot(id, off)`, remap every slot's `i_batch`/`spec_i_batch`, cut its prompt + bookkeeping back to its placed tokens (`keep_first`), move its whole sequence (target and draft) out through the + #139 `flash_out` path into a host-RAM-bounded preempted store, set `SLOT_STATE_PREEMPTED`, re-render, decode the + same piece again (the frame changed). The idle-slot purge is deleted, not kept behind parking. +- No legal move: the slot whose tokens do not fit is removed from the frame the same way and stays `blocked` with + its wake sources (pin released, fence passed, host RAM granted); the rest of the frame decodes. +- `SLOT_STATE_PREEMPTED` is skipped by every batch-construction path; at each frame start the oldest preempted slot + is restored (`mind_switch`-style insert) when its cells fit, and past its age bound it may preempt the coldest legal + active slot (never a pin, learning step or fence). +- Draft: `common_speculative_process` failure no longer throws to `abort_all_slots`; the slot keeps only verified + committed tokens, its n_past/checkpoints/draft are reconciled to that boundary, and its draft state is rebuilt by an + admitted `common_speculative_begin` with a typed failed/blocked outcome (no reset/retry loop). +- Tests (server, unit dir, tiny models): unified-pool overcommit with N processing slots and MTP, all complete with + preempt/resume counted and no 500; all-pinned and host-denied return blocked and never evict; draft no-room keeps + the target's verified output and leaves other slots untouched; bookkeeping counters exact. + ### 4.12 The serving modules: one intentional architecture, no patchwork (2026-11-17) Joel, 2026-11-17: "Need reliable service modules. No more patches. Ideal architecture. We have zero need for shit From 673835a0b9a5567ca0cde1cfbe6be583fc04d50c Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 19:32:14 -0600 Subject: [PATCH 18/49] Design 4.11.10 map, Codex on e71886a8a: preempted bytes reuse #139's store, custody and resource charge (no second store or ledger); a preempted/blocked slot keeps its placed prefix, sampler, RNG, checkpoints and verified output under the same completion owner, never reseeded or duplicated on wake Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 910daf6361..398d228fbd 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2069,8 +2069,11 @@ returns 1 with nothing placed for that piece; pieces before it in the frame are mind out (`flash_coldest`, then an idle lane's mind); else preempt the coldest processing slot that is not pinned, learning or fenced: `remove_slot(id, off)`, remap every slot's `i_batch`/`spec_i_batch`, cut its prompt bookkeeping back to its placed tokens (`keep_first`), move its whole sequence (target and draft) out through the - #139 `flash_out` path into a host-RAM-bounded preempted store, set `SLOT_STATE_PREEMPTED`, re-render, decode the - same piece again (the frame changed). The idle-slot purge is deleted, not kept behind parking. + #139 `flash_out` path, set `SLOT_STATE_PREEMPTED`, re-render, decode the same piece again (the frame changed). + The preempted bytes live in #139's existing store, custody and resource charge (no second byte store or grant + ledger; the preempted state references its handles). The idle-slot purge is deleted, not kept behind parking. +- A preempted or blocked slot keeps its placed prefix and its sampler, RNG, checkpoint and verified-output state + under the same cancellation and completion owner; waking never reseeds it or emits accepted output twice. - No legal move: the slot whose tokens do not fit is removed from the frame the same way and stays `blocked` with its wake sources (pin released, fence passed, host RAM granted); the rest of the frame decodes. - `SLOT_STATE_PREEMPTED` is skipped by every batch-construction path; at each frame start the oldest preempted slot From 67d7225e226b118fa7a8778b3e3132791d404847 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 19:39:42 -0600 Subject: [PATCH 19/49] Design 4.12.1: the engine's owners, every server_context_impl field assigned to exactly one; kv_pool the single allocator custody (decode placement included), slot_registry the single completion/cancellation custody; extraction order Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 398d228fbd..6e4fd228c2 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2123,6 +2123,30 @@ allocation, and no second authoritative ledger: `MemoryOwner` in the core holds cold mind goes to, what to prefetch) and reads the engine's reported physical state; `Residency` is a read-only projection of that one authority, never a mutable copy. +**4.12.1 The engine's owners: every field of `server_context_impl` has exactly one (2026-11-17, for review).** The +include-file split of llama.cpp#143 is mechanical staging (every piece still shares every field); this table is the +architecture it stages for. Each owner is a class holding only its fields, behind typed verbs; `server_context_impl` +holds the owners and wires them, and owns no state of its own. Two custodies are singular (Codex): the memory +allocator and a turn's completion/cancellation. + +| Owner | Owns (fields today) | Typed verbs | The one custody it holds | +|---|---|---|---| +| `engine_runtime` | `llama_init`, `model_tgt`, `ctx_tgt`, `model_dft`, `ctx_dft`, `spec_init`, `spec`, `vocab`, `mctx`, `chat_params`, `params_base`, `n_ctx`, `n_swa`, `add_bos_token`, `ctx_*_seq_rm_type`, `model_name`/`model_aliases`/`model_tags`, `sleeping` | `load`, `sleep`, `wake`, reads | the loaded weights and contexts (immutable while serving) | +| `kv_pool` | the pool's sequence ids and parked ids (`park_free`), `page_io`, `pending_restores`, `page_io_bytes`, `prompt_cache`, checkpoint `host_budget` | `place(frame)` (wraps `llama_decode`, returns placed/no_room per piece), `move(seq, tier)`, `copy`, `remove`, `restore(page)`, host-byte `charge`/`release` | **the allocator**: every KV and host-cache mutation, decode placement included, goes through it | +| `resident_minds` | `minds`, `mind_clock` | `prefetch`, `switch_in`, `preempt`, `coldest_legal` | which mind lives where (policy; moves are `kv_pool`'s) | +| `checkpoint_store` (#140) | each slot's checkpoint list | `keep`, `make_room`, `release`, `cut_back_to` | none (its bytes are charged through `kv_pool`) | +| `slot_registry` | `slots`, `n_busy_slots`, `t_last_busy_us`, `slot_prompt_similarity` | `admit(task)`, `launch`, `release`, `cancel`, `on_token` (today `process_token`) | **a turn's completion and cancellation**: only it ends a slot's task | +| `frame_batcher` | `batch`, `n_batch_gen`, `n_empty_consecutive`, `t_decode_start`, `t_prompt_start`, `n_prompt_queued`, `t_decode_owed_us`, frame records (#142) | `compose`, `run` (asks `kv_pool.place`; on no_room asks `resident_minds` to make room, else defers through `slot_registry`) | the device timeline (4.13) | +| `learning` | `trainer`, `learning`, `learning_residencies`, `learning_workspace_residency`, `learn_ledger`, `residency_mirror`, `learn_chunk_us`, `learn_lr`, `ledger_published*` | `begin`, `step`, `release_pin`, duty | a learning step's fence (borrows a slot from `slot_registry` and cells from `kv_pool`) | +| `responder` | `queue_results` | `send_partial`, `send_final`, `send_error` | none (pure output; `slot_registry` decides when) | +| `task_dispatch` | `queue_tasks` | `dispatch(task)` (today `process_single_task`) | none (routes each task to its owner) | +| `observer` | `metrics`, `n_tokens_generated`, `lora_report*`, `trace`, `slots_debug`, `slots_n_diff`, `t_last_load_progress_ms` | reads, snapshot | none (decides nothing) | + +Order of extraction (each a separate reviewed change, pure moves plus the verb boundary): `observer` and `responder` +(no custody), then `kv_pool` (the allocator, so every later owner calls it), then `resident_minds` and +`checkpoint_store`, then `slot_registry`, then `frame_batcher` (where 4.11.10's admission lands), then `learning`, +then `task_dispatch`, deleting the include fragments as each owner absorbs them. + **Rules every module obeys** (a module that cannot meet one is redesigned, not excepted): 1. **One owner per state.** Only the owner mutates it; others read its published snapshot (a watch channel in Rust, `snapshot_cell` in the engine). No shared mutable state between modules, no lock held across a call. From b24d358e95560bbb5d3f3fb41dc3a75806f74505 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 19:41:40 -0600 Subject: [PATCH 20/49] Design 4.12.1 redone (Joel: 'break up into files by class and adapters ... adapters and interfaces'): every engine owner an interface with adapters behind it, one class per file under tools/server/engine/; transports (HTTP for external drivers, contract frames for the core) as the outlier adapter pair; tier, draft kind and learner as adapters; extraction order Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 57 ++++++++++++++++----------- 1 file changed, 35 insertions(+), 22 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 6e4fd228c2..7011981725 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2123,29 +2123,42 @@ allocation, and no second authoritative ledger: `MemoryOwner` in the core holds cold mind goes to, what to prefetch) and reads the engine's reported physical state; `Residency` is a read-only projection of that one authority, never a mutable copy. -**4.12.1 The engine's owners: every field of `server_context_impl` has exactly one (2026-11-17, for review).** The -include-file split of llama.cpp#143 is mechanical staging (every piece still shares every field); this table is the -architecture it stages for. Each owner is a class holding only its fields, behind typed verbs; `server_context_impl` -holds the owners and wires them, and owns no state of its own. Two custodies are singular (Codex): the memory -allocator and a turn's completion/cancellation. - -| Owner | Owns (fields today) | Typed verbs | The one custody it holds | +**4.12.1 The engine's classes: interfaces, adapters, one class per file (2026-11-17, for review).** Joel: "break up +into files by class and adapters ... adapters and interfaces. Like a good engineer." The include-file split of +llama.cpp#143 is mechanical staging only. The engine becomes classes under `tools/server/engine/`: every owner is an +**interface** (an abstract class: what it promises), its implementation is an **adapter** behind it (how, for one +backend), and whatever varies is another adapter, never an `if` in logic. One class per `.h`/`.cpp` pair. The +composing `engine` (today `server_context_impl`) holds interfaces and wires them; it owns no state. Two custodies stay +singular (Codex): memory allocation (`memory_pool`) and a turn's completion and cancellation (`slot_registry`). + +| Interface (file) | Promises (typed verbs) | Adapters (files) | Owns today's fields | |---|---|---|---| -| `engine_runtime` | `llama_init`, `model_tgt`, `ctx_tgt`, `model_dft`, `ctx_dft`, `spec_init`, `spec`, `vocab`, `mctx`, `chat_params`, `params_base`, `n_ctx`, `n_swa`, `add_bos_token`, `ctx_*_seq_rm_type`, `model_name`/`model_aliases`/`model_tags`, `sleeping` | `load`, `sleep`, `wake`, reads | the loaded weights and contexts (immutable while serving) | -| `kv_pool` | the pool's sequence ids and parked ids (`park_free`), `page_io`, `pending_restores`, `page_io_bytes`, `prompt_cache`, checkpoint `host_budget` | `place(frame)` (wraps `llama_decode`, returns placed/no_room per piece), `move(seq, tier)`, `copy`, `remove`, `restore(page)`, host-byte `charge`/`release` | **the allocator**: every KV and host-cache mutation, decode placement included, goes through it | -| `resident_minds` | `minds`, `mind_clock` | `prefetch`, `switch_in`, `preempt`, `coldest_legal` | which mind lives where (policy; moves are `kv_pool`'s) | -| `checkpoint_store` (#140) | each slot's checkpoint list | `keep`, `make_room`, `release`, `cut_back_to` | none (its bytes are charged through `kv_pool`) | -| `slot_registry` | `slots`, `n_busy_slots`, `t_last_busy_us`, `slot_prompt_similarity` | `admit(task)`, `launch`, `release`, `cancel`, `on_token` (today `process_token`) | **a turn's completion and cancellation**: only it ends a slot's task | -| `frame_batcher` | `batch`, `n_batch_gen`, `n_empty_consecutive`, `t_decode_start`, `t_prompt_start`, `n_prompt_queued`, `t_decode_owed_us`, frame records (#142) | `compose`, `run` (asks `kv_pool.place`; on no_room asks `resident_minds` to make room, else defers through `slot_registry`) | the device timeline (4.13) | -| `learning` | `trainer`, `learning`, `learning_residencies`, `learning_workspace_residency`, `learn_ledger`, `residency_mirror`, `learn_chunk_us`, `learn_lr`, `ledger_published*` | `begin`, `step`, `release_pin`, duty | a learning step's fence (borrows a slot from `slot_registry` and cells from `kv_pool`) | -| `responder` | `queue_results` | `send_partial`, `send_final`, `send_error` | none (pure output; `slot_registry` decides when) | -| `task_dispatch` | `queue_tasks` | `dispatch(task)` (today `process_single_task`) | none (routes each task to its owner) | -| `observer` | `metrics`, `n_tokens_generated`, `lora_report*`, `trace`, `slots_debug`, `slots_n_diff`, `t_last_load_progress_ms` | reads, snapshot | none (decides nothing) | - -Order of extraction (each a separate reviewed change, pure moves plus the verb boundary): `observer` and `responder` -(no custody), then `kv_pool` (the allocator, so every later owner calls it), then `resident_minds` and -`checkpoint_store`, then `slot_registry`, then `frame_batcher` (where 4.11.10's admission lands), then `learning`, -then `task_dispatch`, deleting the include fragments as each owner absorbs them. +| `memory_pool` (`memory_pool.h`) | `place(piece) -> placed / no_room / invalid`, `move(seq, tier)`, `copy`, `remove`, `restore(page)`, host `charge`/`release` | `memory_pool_llama` (llama_context KV and recurrent state, target and draft contexts) | parked ids, `pending_restores`, `page_io_bytes`, checkpoint `host_budget`, `prompt_cache` | +| `tier_store` (`tier_store.h`) | `write(seq_bytes) -> handle`, `read(handle)`, `release`, landed/failed | `tier_store_ram`, `tier_store_flash` (page file + page-IO worker, mmap read) | `page_io` | +| `mind_table` (`mind_table.h`) | `where(mind)`, `coldest_legal()`, `prefetch(mind)`, `preempt(slot)` | `mind_table_resident` (#139 policy; moves through `memory_pool`) | `minds`, `mind_clock` | +| `checkpoint_store` (`checkpoint_store.h`, #140) | `keep`, `make_room`, `cut_back_to`, `release`, `take` | (template; bytes charged through `memory_pool`) | each slot's checkpoints | +| `slot` (`slot.h`) | one sequence's turn: prompt, sampler, RNG, speculative state, state machine incl. `preempted`/`blocked` | — | today's `server_slot` | +| `slot_registry` (`slot_registry.h`) | `admit(task)`, `launch`, `on_token`, `complete`, `cancel`, `preempt`, `resume` | `slot_registry_local` | `slots`, `n_busy_slots`, `t_last_busy_us`, `slot_prompt_similarity` | +| `frame` (`frame.h`, today `server-batch.h`) | `add`, `remove_slot(id, from)`, `render`, `view` | — | `batch` | +| `frame_batcher` (`frame_batcher.h`) | `compose()`, `run() -> frame_outcome` (4.11.10 admission: place, make room, defer) | `frame_batcher_llama` | `n_batch_gen`, `n_empty_consecutive`, decode timing, `t_decode_owed_us`, frame records (#142) | +| `speculator` (`speculator.h`) | `draft(slot)`, `verify(slot, outputs) -> committed`, `rebuild(slot) -> ok / blocked` (typed, never throws to abort all) | `speculator_mtp`, `speculator_draft_model`, `speculator_ngram` (each wraps a `common_speculative` kind) | `spec`, `spec_init`, `ctx_dft_seq_rm_type` | +| `learner` (`learner.h`) | `begin`, `step`, `release_pin`, duty share (4.11.6) | `learner_lora_opt` (ggml-opt, LoRA layers in place) | `learning`, `learning_residencies`, `learn_ledger`, `residency_mirror`, `learn_chunk_us`, `learn_lr` (`trainer`/`/train` deleted when callers move) | +| `responder` (`responder.h`) | `partial`, `final`, `error`, `embedding`, `rerank` | `responder_http` (OpenAI-compatible JSON, external drivers), `responder_frames` (contract frames, 4.11) | `queue_results` | +| `task_source` (`task_source.h`) | `next() -> task`, `post` | `task_source_http` (routes -> `server_queue`), `task_source_frames` (contract) | `queue_tasks` | +| `route_group` (`route_group.h`) | `install(router)` | one class per family: `routes_status`, `routes_generation`, `routes_tokens`, `routes_lora`, `routes_learn`, `routes_control` (HTTP adapter side only) | — | +| `engine_runtime` (`engine_runtime.h`) | `load`, `sleep`, `wake`, model and context reads | `engine_runtime_llama` | model/context/vocab/chat/params fields | +| `observer` (`observer.h`) | snapshot of counters and frame records | — | `metrics`, `n_tokens_generated`, `lora_report*`, debug env | + +The two transports are the outlier pair that prove the seams (the CLAUDE.md method): `responder_http` + +`task_source_http` serve external drivers (Hermes, any OpenAI client, plan line 16); `responder_frames` + +`task_source_frames` serve our own core over the contract. If both fit the same `responder`/`task_source` interfaces +without forcing, the seams are right. + +Order (each one reviewed change: interface + adapter + tests + the include fragment it absorbs deleted): `observer`, +`responder` (+ `responder_http`), `task_source`, `engine_runtime`, `memory_pool` and `tier_store` (the allocator +first, so every later class calls it), `mind_table`, `slot` + `slot_registry`, `frame` + `frame_batcher` (4.11.10 +lands here), `speculator`, `learner`, `route_group` classes; then `responder_frames`/`task_source_frames` with +contract slice 2. **Rules every module obeys** (a module that cannot meet one is redesigned, not excepted): 1. **One owner per state.** Only the owner mutates it; others read its published snapshot (a watch channel in Rust, From a7dda0282651fe3a569dfff800d8ff8692af2147 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 19:47:00 -0600 Subject: [PATCH 21/49] Design 4.12.1: queue_tasks is the engine's run loop, one task_queue class; transports are producers posting into it, not task_source adapters (correction found while extracting) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 7011981725..f432cd5a52 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2144,20 +2144,20 @@ singular (Codex): memory allocation (`memory_pool`) and a turn's completion and | `speculator` (`speculator.h`) | `draft(slot)`, `verify(slot, outputs) -> committed`, `rebuild(slot) -> ok / blocked` (typed, never throws to abort all) | `speculator_mtp`, `speculator_draft_model`, `speculator_ngram` (each wraps a `common_speculative` kind) | `spec`, `spec_init`, `ctx_dft_seq_rm_type` | | `learner` (`learner.h`) | `begin`, `step`, `release_pin`, duty share (4.11.6) | `learner_lora_opt` (ggml-opt, LoRA layers in place) | `learning`, `learning_residencies`, `learn_ledger`, `residency_mirror`, `learn_chunk_us`, `learn_lr` (`trainer`/`/train` deleted when callers move) | | `responder` (`responder.h`) | `partial`, `final`, `error`, `embedding`, `rerank` | `responder_http` (OpenAI-compatible JSON, external drivers), `responder_frames` (contract frames, 4.11) | `queue_results` | -| `task_source` (`task_source.h`) | `next() -> task`, `post` | `task_source_http` (routes -> `server_queue`), `task_source_frames` (contract) | `queue_tasks` | +| `task_queue` (`task_queue.h`) | the engine's run loop: `post`, `defer`, `new_id`, `yield_to_queue`, sleep and wake | — (one loop; transports are producers that post into it: the HTTP routes, and a contract-frame endpoint with slice 2) | `queue_tasks` | | `route_group` (`route_group.h`) | `install(router)` | one class per family: `routes_status`, `routes_generation`, `routes_tokens`, `routes_lora`, `routes_learn`, `routes_control` (HTTP adapter side only) | — | | `engine_runtime` (`engine_runtime.h`) | `load`, `sleep`, `wake`, model and context reads | `engine_runtime_llama` | model/context/vocab/chat/params fields | | `observer` (`observer.h`) | snapshot of counters and frame records | — | `metrics`, `n_tokens_generated`, `lora_report*`, debug env | -The two transports are the outlier pair that prove the seams (the CLAUDE.md method): `responder_http` + -`task_source_http` serve external drivers (Hermes, any OpenAI client, plan line 16); `responder_frames` + -`task_source_frames` serve our own core over the contract. If both fit the same `responder`/`task_source` interfaces -without forcing, the seams are right. +The two transports are the outlier pair that prove the seams (the CLAUDE.md method): `responder_http` and the HTTP +routes serve external drivers (Hermes, any OpenAI client, plan line 16); `responder_frames` and a contract-frame +endpoint serve our own core. If both fit the same `responder` interface and post into the same `task_queue` without +forcing, the seams are right. Order (each one reviewed change: interface + adapter + tests + the include fragment it absorbs deleted): `observer`, -`responder` (+ `responder_http`), `task_source`, `engine_runtime`, `memory_pool` and `tier_store` (the allocator +`responder` (+ `responder_http`; llama.cpp#144), `task_queue`, `engine_runtime`, `memory_pool` and `tier_store` (the allocator first, so every later class calls it), `mind_table`, `slot` + `slot_registry`, `frame` + `frame_batcher` (4.11.10 -lands here), `speculator`, `learner`, `route_group` classes; then `responder_frames`/`task_source_frames` with +lands here), `speculator`, `learner`, `route_group` classes; then `responder_frames` and the contract-frame endpoint with contract slice 2. **Rules every module obeys** (a module that cannot meet one is redesigned, not excepted): From e5c5044aa726a4e13f54e6287e0a2b74ccb3950e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 20:45:10 -0600 Subject: [PATCH 22/49] Design: ONE mind decodes at a time, at full single-stream speed, minds time-sliced with millisecond switches; batched multi-mind decode removed from 4.11.9, 4.12, 4.13 and the gates (Joel, told five times: "When we do 4 parallel we drop from 80tps to 1-2 and it ruins it all") The document's own table already measured it (59-80 tok/s one at a time vs 8-22 batched). 4.11.9 point 4: the scheduler time-slices one decoding mind; a second mind in a decode step needs a live receipt that beats single-stream. 4.13: a frame is the one decoding mind's token(s), then the NEXT mind's appended tail in prefill chunks so her switch is ready, then learning. Gates: ~80 tok/s single-stream streamed, switches in ms. Two passages that called one-at-a-time a defect now name the real defect (the switch was grants and re-prefills, not milliseconds). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 42 +++++++++++++++------------ 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index f432cd5a52..c646941db9 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -1963,7 +1963,9 @@ Joel, 2026-11-17, on the M5 read: "So it needs rewrite? Very unreliable logic. I **What the M5 showed (build 5a754ad98 verified 00:09:35Z, engine 14844; the 15-minute read 00:09:35-00:24:35Z).** The starvation fix (#6093) works: seats rotated strictly oldest-owed with no re-entry, three times. But only ONE mind was ever seated. Each grant was 158-207k tokens (her whole untrimmed view x `SENT_HEADROOM` 1.25, `window_grant.rs:398-410`), the pool is 300,850, -and the engine runs 5 lanes, so four residents decoded strictly one after another and never batched. Her real +and the engine runs 5 lanes, so four residents decoded strictly one after another. (One at a time is the design, +4.11.9 point 4; the defect is that the switch between them was not milliseconds: each waited on a whole-view grant +rather than being resident and switched in by id.) Her real sequence per act (engine `n_past`) was 50-93k; all four together are about the pool. The code's own premise, "a grant is a ceiling, not an allocation: KV is paged on use", is contradicted by admission, which sums grants against the pool. Everything built to cope with that (the owed queue, `BehindActs` waits, reclaim handoffs and receipts, armed @@ -1983,11 +1985,13 @@ held one turn ~3 h on 2026-11-16. named release event, never an unbounded wait. 3. **Her grant survives only as her view's ceiling:** how much she renders whole (the Aris collapse spiral of 2026-11-13 is why it is sized to her wish). It never decides whether she runs. -4. **The scheduler decides only who decodes next** (goal 9): activity temperature as priority, aging so no eligible - mind is starved, and as many ready minds batched into one decode step as the MEASURED per-node, per-model - concurrency cost curve and the step and latency budgets allow, after physical admission (Codex on #6092). No - concurrency count is hard-coded and one-step service is not promised when ready demand exceeds those budgets; - batching is judged against the cost curve. +4. **The scheduler decides only who decodes next, ONE mind at a time** (goal 9; Joel, 2026-11-17, after telling us + five times: "When we do 4 parallel we drop from 80tps to 1-2 and it ruins it all"). On this hardware several minds + in one decode step collapse the engine from ~80 tok/s to 1-2; so exactly one mind decodes, at the full + single-stream rate, streamed to her room, and the scheduler time-slices between minds the way a CPU switches + processes: activity temperature as priority, aging so no eligible mind is starved, a switch in milliseconds + (park and insert by sequence id). Others are resident, not decoding. Putting a second mind into a decode step + requires a live receipt that it beats single-stream; none exists. 5. **Custody stays where it is proven.** The existing completion owner keeps terminal, cancellation and fence custody and the save-before-release proofs; the grant-specific handoff APIs are deleted only once their callers use the shared mover's equivalent proof. A dropped or cancelled request never authorizes reuse of live GPU memory. @@ -2002,9 +2006,8 @@ seat publications and grant revisions as admission (`lease/fair.rs` and the rese **Gates.** In the simulator and replay first: a contention replay where the aggregate active working sets exceed the pool and no legal eviction exists proves a bounded typed deferral and progress after a legal release; tonight's M5 logs replay without a starved mind. Then on the M5 (the four residents, the 35B): all four logically resident with no -`delib.window.waiting`; batched decode (more than one sequence per decode step) observed and measured against the -concurrency cost curve; aggregate decode tok/s against the 80 tok/s target; switch receipts in milliseconds; the -physical charge never above the `ResourceDaemon` grant. +`delib.window.waiting`; exactly one mind decoding at a time at ~80 tok/s single-stream, streamed; switch receipts in +milliseconds; the physical charge never above the `ResourceDaemon` grant. ### 4.11.10 The engine half of admission: reserve before decode, park instead of the KV-full ladder (2026-11-17, design for review) @@ -2109,7 +2112,7 @@ built. | `Residency` | each mind's place: logically resident always; GPU / RAM / flash tier, gated separately (4.11.9 point 6) | reads only (snapshot); moves are `MemoryOwner`'s | seats, the owed queue, reclaim handoffs, armed yields | | `Scheduler` | who decodes next: activity temperature, aging among eligible minds, batch size by the measured concurrency cost curve and step/latency budgets (goal 9, 4.11.9 point 4) | `ready(mind, act)`, reads: `next_batch` | `BehindActs`, `delib.window.waiting` polling, lane selection | | `Learning` | the genome's learning switch and duty: share by wakefulness, learning acts through the same path (4.11.6) | `set_learning(layer, on)`, `duty(share, mode)` | ad hoc fresh-adapter writes and swaps beside serving; `/train*` | -| `ServingObserver` | the numbers: aggregate decode tok/s, per-mind acts/h, switch ms, waits, memory, learning share | reads only; publishes a snapshot | scattered probes nobody aggregates; it decides nothing | +| `ServingObserver` | the numbers: the decoding mind's tok/s, per-mind acts/h, switch ms, waits, memory, learning share | reads only; publishes a snapshot | scattered probes nobody aggregates; it decides nothing | **Engine modules** (each an engine module, `server-module.h`, all on the one server loop that owns the llama context): the frame dispatcher (validates and routes, 4.11.3); the resident-minds table (sequence ids, park/flash, @@ -2197,8 +2200,9 @@ a good architecture." **What interferes today (the M5, 2026-11-16/17):** learning writes and swaps adapters between decode steps with no one weighing the cost (402 fresh adapters in one engine log); one mind's 50-93k prefill stalls every other mind's decode; view-sized grants serialize the minds (4.11.9); checkpoint misses force full re-prefills; the core polls. Each part is -locally reasonable and none arbitrates, so single-stream decode ran at 24% of par (13.9 vs 56.1 tok/s) and four -residents never batched. +locally reasonable and none arbitrates, so single-stream decode ran at 24% of par (13.9 vs 56.1 tok/s) and switching +between the four residents took grants and re-prefills instead of milliseconds. (One mind decoding at a time is the +design, measured: the table under 4.7 shows 59-80 tok/s one at a time against 8-22 batched.) **What must happen, continuously:** (1) decode, one token per active mind per step, latency-critical, and the source of aggregate throughput when several minds batch; (2) prefill, large and bursty, for minds starting or resuming an @@ -2210,9 +2214,10 @@ optimizer steps on the genome's layers at a duty share (4.11.6); (5) persistence tokens, a prefill chunk, a learning step); nothing else touches the llama context or the device. One timeline, one owner: interference has no path. - **Each frame (one decode step) is composed by priority against a measured time budget:** - 1. decode for every mind in the ADMITTED active set (bounded by the measured concurrency limit, 4.11.9 point 4), - batched, first; - 2. prefill in chunks that fill the rest of the step budget, so no prompt stalls the others' decode; + 1. the ONE decoding mind's next token(s), first (4.11.9 point 4: one mind decodes at a time; batching minds collapses + the engine from ~80 tok/s to 1-2); + 2. prefill in chunks that fill the rest of the step budget: the NEXT mind's appended tail, ready before her switch, + so no prompt stalls the decoding mind; 3. learning micro-steps in the budget left, up to the duty share; when minds are idle the slack is large, and that is when dreaming runs. A learning step commits at the fence of 4.11.6. - **Decode-first never starves the rest** (Codex on #6092). Prefill and learning age: each waiting job carries a @@ -2250,9 +2255,10 @@ not asserted. the measured budget; learning moves into it (the adapter churn beside serving ends). 4. **Residency and `MemoryOwner`** (4.11.8-9): every mind resident, admission by physical reservation, prefetch on lookahead; the grant dispatcher is deleted. -5. **`Scheduler`** (Codex, goal 9): who is active and how many per frame, from the measured cost curve. -6. **The gate on the M5:** four residents batched, aggregate decode tok/s against 80, switches in milliseconds, - learning within its share without slowing decode beyond it. +5. **`Scheduler`** (Codex, goal 9): which ONE mind decodes next and when to switch (time-slicing by temperature and + aging), never how many decode together. +6. **The gate on the M5:** one mind decoding at a time at ~80 tok/s single-stream, streamed; switches in milliseconds; + four residents served in turn; learning and embedding within their share without slowing the decoding mind. ## 5. A mind's context and the engine it runs on From 32b28f5d934afb3dadb27188735992ab52aca781 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 21:11:49 -0600 Subject: [PATCH 23/49] Design 4.14: personas stream like Nanite: one decodes, the next streams into native blocks, the previous retires after the fenced switch; the blocks are llama.cpp's own per-sequence KV streams (one contiguous slice per layer for K and V when unified KV is off), so a switch is a descriptor bind and a tier move is raw slice copies, never a cell walk or serialization Builds on 4.9 (the model) and 4.1b (the numbers) instead of restating them; replaces #139's mechanism (held). Open questions and the prototype evidence (copy time vs bandwidth, layer-ordered first-token latency, byte-identical round trip, scaling at 4/8/16) come before code. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 59 +++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index c646941db9..a165b3a9e1 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2260,6 +2260,65 @@ not asserted. 6. **The gate on the M5:** one mind decoding at a time at ~80 tok/s single-stream, streamed; switches in milliseconds; four residents served in turn; learning and embedding within their share without slowing the decoding mind. +### 4.14 Personas stream like Nanite: native blocks, descriptor binding, no walks (2026-11-17, design for review) + +Builds on 4.9 (the model: a mind is a process, a switch is a context switch) and 4.1b (the numbers: one stream at +~80 tok/s with the MTP draft; batching minds collapses it). This section is the MECHANISM, replacing #139's (held: +its switch walks KV cells with `seq_cp`/`seq_rm` and serializes state with `llama_state_seq_get/set_data`). + +Joel, 2026-11-17: "It's like we are coding a sophisticated graphics pipeline. Like granite or nanite. And we have to +keep it all together per persona... make solid structures and avoid expensive operations while coming up with +efficient work to do streaming the needs of the next persona in like nanite does for geometry and textures." "Do it +all raw." "Tokenization and serialization is cancer." + +**The pipeline.** One persona DECODES. The NEXT is streamed into execution-ready native blocks while she decodes. A +fenced handoff makes NEXT active; only then is the PREVIOUS retired, asynchronously, to RAM (or flash). Every other +persona lives in RAM (or flash) within the host budget: residency in fast memory is the exception. Admission reserves +active + next + retiring before any overlap; an outgoing buffer is never reused before its copy completes; when the +overlap cannot fit, a typed deferral, never a hidden stall. Transfer overlap is not parallel decoding. + +**A persona is one solid structure, and llama.cpp already has its KV layout.** Each attention layer's K (and V) is one +tensor `[n_embd_gqa, kv_size, n_stream]` (`llama-kv-cache.cpp:232`); with unified KV off, `n_stream == n_seq_max` +and stream `s` is ONE CONTIGUOUS BYTE RANGE per layer, read by attention through a view at offset `s` +(`get_k`/`get_v`, `sinfo.s0`). So a persona's KV is, per attention layer, two contiguous slices (K, V) plus her +stream's cell metadata (`v_cells[s]`, positions and sequence bits: a flat array). The hybrid model's recurrent state is +per-layer row tensors (`r_l`, `s_l`, `llama-memory-recurrent.h:125`), one row per sequence: a row per layer. Her genome +(LoRA layers) and checkpoints travel with her. The persona's block table names all of these as (tensor, byte offset, +byte length) per tier. + +**Operations, and their cost (no walks anywhere):** +- *Resident switch* (NEXT already in a stream): rebind the decode lane's stream index and her adapter set: a + descriptor bind, no copy, no prefill. +- *Stream in* (RAM -> a free stream): per attention layer two raw copies (K slice, V slice), per recurrent layer one + row copy, the cell-metadata array as one copy; issued in layer order so her first decode can start as early layers + land while the rest stream behind compute; fenced by the existing completion owner. +- *Retire* (a stream -> RAM): the same raw copies outward, asynchronous, after the handoff fence; the stream is free + only when they complete. +- Never: `llama_state_seq_*` (cell walk + metadata serialization), `seq_cp`/`seq_rm` as the switch, repack, + re-tokenize, re-prefill. + +**Memory, stated as a budget not a guess.** Fast memory holds the weights plus three streams (active, next, retiring), +each `kv_size` tokens of KV for the model's attention layers plus its recurrent rows; RAM holds every other persona's +blocks (their actual lengths, not `kv_size`). The first measurement sizes this on the M5 (the 35B hybrid, q4_0 KV): +bytes per token of KV per attention layer, the recurrent row size, and so the RAM cost per persona and the copy time +per switch at the measured bandwidth. + +**Open questions (answered by measurement or prototype before code):** +1. Stream count is fixed at context creation (`n_seq_max`); a persona maps to a stream for her residency, so the + engine needs a stream allocator (3 for the pipeline, more if memory allows), not one stream per persona forever. +2. A stream's `kv_size` is fixed: a persona longer than it needs a larger stream class, or her context capped by the + allocation (measured against her real lengths, 4.9.1 F1: 50-93k). +3. Whether ggml's attention view over one stream (the `sinfo.s0` offset) is already what the kernels read with no + per-cell indirection on Metal and CUDA (it appears so from `get_k`); confirm in the kernels. +4. The adapter (genome) binding per stream: today's per-request LoRA set on the context; it must switch with the + stream bind, not reload. +5. The MTP draft context: its own KV streams, moved with hers. + +**Evidence before implementation (Codex's condition):** a prototype that swaps a persona between a stream and RAM by +raw slice copies on the M5, measuring copy time per switch against bandwidth, the first-token latency of the arriving +persona with layer-ordered streaming, and byte-identical restore (her next-token logits equal before and after a +round trip); then the scaling read at 4, 8 and 16 personas. + ## 5. A mind's context and the engine it runs on **Focus boundary:** [Focus contract](FOCUS-CONTRACT.md) defines one allocation, From f7085fb6eb71147721aec81e9551e028efca0cd6 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 21:17:57 -0600 Subject: [PATCH 24/49] Design 4.14, Codex's review of 32b28f5d9: cell metadata (std::set, vectors, position maps; recurrent mem_cell's std::set) is never copied or rebuilt: each persona owns her metadata objects and a bind swaps them with the stream's by reference (O(1)); prebuilt per-layer descriptors; stride-preserving storage at her actual length; recurrent rollback, draft streams and sampler state under the same custody; a fence per consumer for early-layer decode; isolated prototype only Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index a165b3a9e1..4c9ef5a964 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2303,6 +2303,22 @@ blocks (their actual lengths, not `kv_size`). The first measurement sizes this o bytes per token of KV per attention layer, the recurrent row size, and so the RAM cost per persona and the copy time per switch at the measured bandwidth. +**Codex's review of 32b28f5d9 (layout not yet accepted), folded in:** +- *Cell metadata is not memcpy-safe.* `llama_kv_cells` owns a `std::set`, vectors and position maps, and the + recurrent `mem_cell` embeds a `std::set` of sequence ids. So her metadata is never copied as bytes and never rebuilt + on a switch: each persona OWNS her host metadata objects, and binding her to a stream exchanges them with the + stream's by reference (`std::swap(v_cells[s], persona.cells)`: an O(1) exchange of container internals, no element + copied, no container rebuilt), the same for her recurrent cells. +- *Descriptors are prebuilt* when the persona is created (per layer: tensor, byte offset, row stride, her used rows), + never computed by a per-switch layer walk. +- *Storage is stride-preserving at her actual length*: her RAM copy keeps the stream's row stride for the rows she + uses, so a copy in or out is contiguous up to her length, never `kv_size`. +- *Custody*: her recurrent rollback state, her draft context's streams and her sampler state move with her under the + same completion owner. +- *Early-layer decode needs a fence per consumer* (each layer's copy completes before that layer's attention reads it), + not one handoff fence for the whole persona. +- *Prototype only, isolated*: no serving experiment until the layout is accepted. + **Open questions (answered by measurement or prototype before code):** 1. Stream count is fixed at context creation (`n_seq_max`); a persona maps to a stream for her residency, so the engine needs a stream allocator (3 for the pipeline, more if memory allows), not one stream per persona forever. From 418cacfddf271a2d7862188cbaef4d1b5b9aade8 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 21:28:31 -0600 Subject: [PATCH 25/49] Design 4.14: per-node measured throughput target (no fixed rate); stale flat-array and one-copy metadata claims rewritten; resident switch binds her own sequence id through seq_to_stream (never retags); her genome and learning state are hers, but a switch stages only execution blocks, learning state stays under owned handles and its working set is reserved only when learning is scheduled; a learning completion publishes one coherent adapter generation after the completion fence; tiered staging with no redundant copy Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 42 ++++++++++++++++++--------- 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 4c9ef5a964..4695994637 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2262,8 +2262,10 @@ not asserted. ### 4.14 Personas stream like Nanite: native blocks, descriptor binding, no walks (2026-11-17, design for review) -Builds on 4.9 (the model: a mind is a process, a switch is a context switch) and 4.1b (the numbers: one stream at -~80 tok/s with the MTP draft; batching minds collapses it). This section is the MECHANISM, replacing #139's (held: +Builds on 4.9 (the model: a mind is a process, a switch is a context switch) and 4.1b (the numbers on the M5: one +stream at ~80 tok/s with the MTP draft; batching minds collapses it). The target on every node is that node's OWN +measured single-mind rate for its model and context (the M5's ~80 is the M5's; the 5090's is unmeasured on the same +workload): the pipeline preserves it, and aggregate throughput and transfer interference are reported against it. This section is the MECHANISM, replacing #139's (held: its switch walks KV cells with `seq_cp`/`seq_rm` and serializes state with `llama_state_seq_get/set_data`). Joel, 2026-11-17: "It's like we are coding a sophisticated graphics pipeline. Like granite or nanite. And we have to @@ -2281,16 +2283,26 @@ overlap cannot fit, a typed deferral, never a hidden stall. Transfer overlap is tensor `[n_embd_gqa, kv_size, n_stream]` (`llama-kv-cache.cpp:232`); with unified KV off, `n_stream == n_seq_max` and stream `s` is ONE CONTIGUOUS BYTE RANGE per layer, read by attention through a view at offset `s` (`get_k`/`get_v`, `sinfo.s0`). So a persona's KV is, per attention layer, two contiguous slices (K, V) plus her -stream's cell metadata (`v_cells[s]`, positions and sequence bits: a flat array). The hybrid model's recurrent state is -per-layer row tensors (`r_l`, `s_l`, `llama-memory-recurrent.h:125`), one row per sequence: a row per layer. Her genome -(LoRA layers) and checkpoints travel with her. The persona's block table names all of these as (tensor, byte offset, -byte length) per tier. +stream's cell metadata (`v_cells[s]`: host containers, owned by her and bound by reference, never copied as bytes; see +below). The hybrid model's recurrent state is per-layer row tensors (`r_l`, `s_l`, `llama-memory-recurrent.h:125`), one +row per sequence. Her genome (adapter generation) and her learning state (optimizer moments, learning checkpoints) are +hers too. The persona's block table names her device blocks as (tensor, byte offset, row stride, used rows) per tier. + +**What travels on a switch, and what stays put.** One owner does not mean one eager copy. A switch stages only her +EXECUTION blocks: KV slices, recurrent rows, the adapter generation she decodes with, her draft streams, her sampler. +Her learning state (optimizer moments, learning checkpoints) stays where it is under owned handles in its tier, and +its working set is reserved only when learning is scheduled for her. A learning completion publishes her new adapter +generation as one coherent version, only after the existing completion owner's fence: never weights from one version +with KV from another, and never freeing a buffer training still holds. The same staging holds across every tier +(storage -> RAM -> VRAM on a discrete GPU; RAM -> unified memory on the M5): RAM-resident blocks are copied to the +device directly with no extra staging copy, and storage gets a staging buffer only where the backend requires one. **Operations, and their cost (no walks anywhere):** -- *Resident switch* (NEXT already in a stream): rebind the decode lane's stream index and her adapter set: a - descriptor bind, no copy, no prefill. -- *Stream in* (RAM -> a free stream): per attention layer two raw copies (K slice, V slice), per recurrent layer one - row copy, the cell-metadata array as one copy; issued in layer order so her first decode can start as early layers +- *Resident switch* (NEXT already in a stream): rebind her own sequence id to that stream (`seq_to_stream`, which + stays a permutation; her cells keep her id, so nothing is retagged) and her adapter generation: a descriptor bind, + no copy, no prefill. +- *Stream in* (RAM -> a free stream): per attention layer two raw copies (K slice, V slice, her used rows), per + recurrent layer one row copy, her metadata bound by reference; issued in layer order so her first decode can start as early layers land while the rest stream behind compute; fenced by the existing completion owner. - *Retire* (a stream -> RAM): the same raw copies outward, asynchronous, after the handoff fence; the stream is free only when they complete. @@ -2306,9 +2318,13 @@ per switch at the measured bandwidth. **Codex's review of 32b28f5d9 (layout not yet accepted), folded in:** - *Cell metadata is not memcpy-safe.* `llama_kv_cells` owns a `std::set`, vectors and position maps, and the recurrent `mem_cell` embeds a `std::set` of sequence ids. So her metadata is never copied as bytes and never rebuilt - on a switch: each persona OWNS her host metadata objects, and binding her to a stream exchanges them with the - stream's by reference (`std::swap(v_cells[s], persona.cells)`: an O(1) exchange of container internals, no element - copied, no container rebuilt), the same for her recurrent cells. + on a switch: each persona OWNS her host metadata objects and they are bound by reference. The prototype exchanges + them with `std::swap(v_cells[s], persona.cells)`: no container is rebuilt, but `llama_kv_cells` also holds a fixed + `seq_pos[LLAMA_MAX_SEQ]` array of maps, so it is not literally one pointer exchange; the target is an owner handle + the stream points at. Her cells record HER sequence id, so a stream is bound to her id through `seq_to_stream`, never + retagged (the first prototype run, which loaded her cells into stream 1 and read them as sequence 1, failed exactly + there: `stream 1 holds her prompt`). `v_heads[s]` is reset on bind; the recurrent `src`/`src0`/`tail`/`rs_idx` + rollback references move with her. - *Descriptors are prebuilt* when the persona is created (per layer: tensor, byte offset, row stride, her used rows), never computed by a per-switch layer walk. - *Storage is stride-preserving at her actual length*: her RAM copy keeps the stream's row stride for the rows she From 2c3c9a0a9961542f4c0fb06d2585da965b310c30 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 21:53:55 -0600 Subject: [PATCH 26/49] Design 4.14: retention: computed state is never discarded; tiers are residency, not validity; an engine stop demotes resident personas' native blocks to flash and a start binds them back (never drop and re-prefill); only stale/unneeded generations retire, under policy Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 4695994637..303095ead0 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2335,6 +2335,12 @@ per switch at the measured bandwidth. not one handoff fence for the whole persona. - *Prototype only, isolated*: no serving experiment until the layout is accepted. +**Retention (Joel, 2026-11-17): computed state is never discarded.** VRAM, RAM and flash are residency tiers, not +validity states; moving a block between them keeps its identity, version and work. Only new values are computed. An +engine stop or restart demotes every resident persona's native blocks to flash and a start binds them back; it never +drops a mind and re-prefills (the 2026-11-17 03:03Z cold read re-prefilled 520,800 tokens that were already computed). +Only a truly stale or unneeded generation retires, under policy, and a stale generation never presents as current. + **Open questions (answered by measurement or prototype before code):** 1. Stream count is fixed at context creation (`n_seq_max`); a persona maps to a stream for her residency, so the engine needs a stream allocator (3 for the pipeline, more if memory allows), not one stream per persona forever. From 901807b71b8d0311ff76420ff03a328dad8800b1 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 22:12:20 -0600 Subject: [PATCH 27/49] Design 4.14: #147 prototype receipts (35B: 32k-token persona loads in 4.09 ms vs 50.8 s recompute) and the next slice: native metadata generation for the flash tier (typed versioned header with owner identity, flat arrays, allocation-relative derived indices; Codex's constraints and acceptance list) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 303095ead0..31fc3742d5 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2341,6 +2341,30 @@ engine stop or restart demotes every resident persona's native blocks to flash a drops a mind and re-prefills (the 2026-11-17 03:03Z cold read re-prefilled 520,800 tokens that were already computed). Only a truly stale or unneeded generation retires, under policy, and a stale generation never presents as current. +**Prototype receipts (fork #147, isolated; serving unchanged).** Raw move of a persona's attention rows and recurrent rows, +her metadata exchanged, her own sequence bound to any stream; two-phase (check reserves every byte and node, commit +allocates nothing), fenced by the context. Byte-identical continuation in every case (stories15M; tiny qwen35moe incl. +4 rollback groups with a pending rollback; allocation-fault injection). On the M5, Qwen3.6-35B-A3B Q4_K_M, KV q4_0, FA: +| her tokens | state | recompute (prefill) | load (whole fenced call) | +|---|---|---|---| +| 4,096 | 89.5 MB | 4,351 ms | 1.40 ms | +| 16,384 | 160.2 MB | 20,419 ms | 2.64 ms | +| 32,768 | 254.6 MB | 50,834 ms | 4.09 ms | + +**Next slice: the flash tier binds, never rebuilds (direction approved by Codex 2026-11-17; layout not yet accepted).** +`llama_kv_cells` keeps flat, trivially copyable arrays (pos, ext, shift, seq bits) beside DERIVED indices that are +STL containers (`used`: a set; `seq_pos`: per-sequence maps of position counts). A RAM move swaps the object; a flash +copy cannot hold STL internals, and rebuilding them on load is the reconstruction the rule forbids. So her metadata +gets a native generation: a typed, versioned header (magic, layout version, layout id, OWNER identity = model file +digest + genome/adapter generation, her sequence, extent sizes), then her flat arrays for her used rows, then her +derived indices in a native, allocation-relative form (offsets, never pointers), all one generation, published through +the existing completion/storage owner. Constraints (Codex): no dense histogram indexed by absolute position without a +proven bound (positions, shifts, holes and shared sequences keep today's semantics; seq x max_pos can explode); the +occupied index is bounded and updated only when tokens or state actually change. Acceptance: remap across addresses, +same-process flash round trip, sparse/high/shifted positions, duplicates and shared sequences, deletions and extrema +changes, corrupt/truncated extents and partial-write custody, memory and scaling; and a cross-model, same-shape restore +is refused by owner identity. + **Open questions (answered by measurement or prototype before code):** 1. Stream count is fixed at context creation (`n_seq_max`); a persona maps to a stream for her residency, so the engine needs a stream allocator (3 for the pipeline, more if memory allows), not one stream per persona forever. From 685917664149c74297e63653eb4fb8e749a658ef Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 10:30:13 -0600 Subject: [PATCH 28/49] Design 4.14: the native in-memory indices landed in #147 (proof, cost, settle-before-freeze) and the flash generation's conditions Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 31fc3742d5..6686d6b7ff 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2365,6 +2365,25 @@ same-process flash round trip, sparse/high/shifted positions, duplicates and sha changes, corrupt/truncated extents and partial-write custody, memory and scaling; and a cross-model, same-shape restore is refused by owner identity. +**Landed in the prototype (#147, 2026-11-17): the derived indices are native in memory.** `llama_kv_cells` no longer +holds node containers: `used` is a bitmap over the cell rows with its count and extrema (bounded by the stream, never a +position), and each sequence's positions are a sorted `{pos, count}` array it owns (`src/llama-kv-cell-index.h`). The +append at her newest position and the rollback of it stay exact and O(1); any other change (an inner removal, a shift, +a division that merges positions) marks that sequence stale and the next query recomputes it once from the cells, so +collisions coalesce by construction and a front discard is never quadratic. Codex's condition: a recomputation is never +deferred across a freeze, so a persona's save settles every index in its fallible reserve phase (`settle_all`) and her +bind and every query after it do no scan and no sort. Proof: `test-kv-cell-index` (8 seeds x 20000 random cache +operations against the replaced `std::set`/`std::map`, every extremum after every step; `freeze_then_bind` with zero +recomputations after the bind), green on Ubuntu and Windows CI at 347a13ab2. Cost, same workload (append, front discard, +shift, extrema after each phase), M5, 15:00Z: 4k cells 0.486 ms old vs 0.533 ms native (slower), 32k 4.535 vs 4.300, 100k +15.747 vs 13.090; no uniform speedup is claimed. + +**The flash generation, conditions before code (Codex, 2026-11-17):** the header and ALL of her metadata are one fenced +generation, including the recurrent rollback state, the draft model's streams, the sampler and the genome generation; +every offset is checked for overflow, alignment and overlap before use; a direct bind requires native endianness and a +matching layout id, with checksums and publish completion owned once (never a rehash per switch); the flash I/O +pipeline stays off decode; and the prior generation is kept until the new one is durably published. + **Open questions (answered by measurement or prototype before code):** 1. Stream count is fixed at context creation (`n_seq_max`); a persona maps to a stream for her residency, so the engine needs a stream allocator (3 for the pipeline, more if memory allows), not one stream per persona forever. From 2491e3435cc6dd3335aa0bb752a574891e195e21 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 14:00:53 -0600 Subject: [PATCH 29/49] Design 4.14: her token history is the engine's; a request carries only what is new (measured: her call and her reasoning are recomputed every act) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 33 +++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 6686d6b7ff..b4da891c0a 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2384,6 +2384,39 @@ every offset is checked for overflow, alignment and overlap before use; a direct matching layout id, with checksums and publish completion owned once (never a rehash per switch); the flash I/O pipeline stays off decode; and the prior generation is kept until the new one is durably published. +**Her token history is the engine's: a request is only what is new (2026-11-17).** Joel: "Never process something +twice. If you've built the logits before it's failure if it's done ever again." Moving her blocks without a +recompute is half of it; the other half is that what the next request asks for must BE what her blocks hold, plus +new tokens. Measured on the M5 the same day (Aris, capture 8044b75b, build 4f82b0fb4), it is not, in two ways: +- *Order.* Her act N's call joins her view only when act N+1 is built, after what arrived meanwhile (12 room + messages, board items, thoughts), so request N+1 is `[prompt N][arrivals][her call N][result N]` while her engine + holds `[prompt N][her generated N]`. +- *Reasoning.* Each generation carries reasoning (95 to 726 chars in her last three acts) that her history never sends + back, so even in the right order the rendered call is not the token sequence she generated. +Either way her KV stops matching at her own call: the hybrid's recurrent state cannot truncate, so it rewinds to a +checkpoint (`reuse_split` gap 2,048 on every act) and she recomputes her own tokens. Per act that is about 2.6k tokens +of 7k to 10k prefilled; the rest is genuinely new data. + +The structure, one whole, with no special case per template or per path: +1. **The engine owns her token sequence**, as it owns her blocks: her prompt tokens AND her generated tokens verbatim + (reasoning, tool-call bytes, the end-of-turn glue her template puts after an assistant turn). Held, frozen and + bound with her blocks as one unit (the token array is part of her persona, beside her cells). +2. **A request carries only what is new since her last serve**: the messages her view appended after the last served + one, in engine order (her call first: it is already in her blocks). The engine renders only that delta with her + template (render(held + new) minus render(held), checked to be a prefix, else a typed miss) and appends the tokens. + Nothing she already holds is re-sent, re-rendered, re-tokenized or recomputed. An external driver's full-history + request takes the same path: its history is matched against her held messages, never against re-rendered tokens. +3. **One cold path, named as one**: an epoch start (a new view, a revoked head) sends her whole view once; it is a + classified cold start (`#5188`), never a fallback for a missed continuation. A continuation that does not match + what she holds is a loud miss with its reason, never a silent re-prefill. +4. **The validator** (seconds, no live residents): replay a persona's captured acts through the continuation and + assert `prefilled == new tokens` and `recomputed == 0` on every act, across freezes and binds. It gates the merge. + +Slices: (a) cognition: her call joins her view at generation, in engine order (the order half, measurable on today's +engine as the gap disappearing for non-reasoning acts); (b) fork: the continuation on the persona seam (`llama_persona` +holds her tokens; the server's request names her and carries the delta); (c) core: the request builder sends the delta +her view already knows (`View::sent` marks the boundary); (d) the validator above, landed with (b). + **Open questions (answered by measurement or prototype before code):** 1. Stream count is fixed at context creation (`n_seq_max`); a persona maps to a stream for her residency, so the engine needs a stream allocator (3 for the pipeline, more if memory allows), not one stream per persona forever. From eedd262555cc682911c5a7618e1f897ab185f66e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 14:25:41 -0600 Subject: [PATCH 30/49] Design 4.14: the persona is one contiguous structure (cv::Mat-shaped header over token ids, KV rows, recurrent rows, flat index) and a request appends token ids; no render, no tokenize, no compare on the hot path Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index b4da891c0a..cddaf40cac 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2417,6 +2417,29 @@ engine as the gap disappearing for non-reasoning acts); (b) fork: the continuati holds her tokens; the server's request names her and carries the delta); (c) core: the request builder sends the delta her view already knows (`View::sent` marks the boundary); (d) the validator above, landed with (b). +**The persona is one contiguous structure; a request appends token ids (2026-11-17, Joel: "the llama and +other kv cache design is inefficient. We do much better... any encoding is a killer. Ideally you operate at +SIMD and efficient structs... cvmat like contiguous, designed for fast insertions lookup and +restore/store").** Supersedes the text delta of the slices above (fork #149's stub rendering re-renders and +re-tokenizes the new messages every act: encoding on the hot path). +- *Her state is cv::Mat-shaped:* one typed header (owner: model digest and adapter generation; her sequence; + lengths and strides; layout version) over contiguous buffers: her token ids (`int32[n]`), her KV rows per + attention layer, her recurrent rows, her cell index as flat arrays (#147 already made the index flat). + Append writes at the end; lookup is an index; store and restore are memcpy, or a pointer bind while resident. + No container walk, no serialization, no rebuild. +- *Her view's items carry their token ids:* each item is tokenized ONCE, keyed by the item (4.7.11), with the + model's turn framing (role start, end of turn) read ONCE per model from its template as token ids. A + rendered prompt is a concatenation of id slices, never a template render. +- *A request is an append:* `continues` (her lineage's response) plus the new token ids, a contiguous `int32` + slice passed by reference (no JSON array of numbers on the hot path). The engine's work is + `held[0..n_end] ++ delta` (a memcpy), then decode. Nothing is rendered, tokenized or compared; a miss is + the typed refusal (`continuation_refused`), and a cold start is the caller's own whole-view send. +- *The order is the engine's:* the delta's ids are her call's result, then what arrived, then the clock, so her + view appends her exchange before it advances its sources (#6110 rework). +- *Validator:* replay a persona's captured acts as id appends; assert prefilled == appended tokens and + recomputed == 0 across three or more acts, freezes and binds; and time the core's per-act CPU (expected: + memcpy of the delta, no tokenizer call). + **Open questions (answered by measurement or prototype before code):** 1. Stream count is fixed at context creation (`n_seq_max`); a persona maps to a stream for her residency, so the engine needs a stream allocator (3 for the pipeline, more if memory allows), not one stream per persona forever. From 9f21f6b46bbeb090cd36ec4d37b7876d4f4248f2 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 14:28:43 -0600 Subject: [PATCH 31/49] Design 4.14: Codex's three contracts for the id append (reserved-tail append, compositional id keys, one validated transaction with idempotent replay) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index cddaf40cac..642f7c098a 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2436,6 +2436,21 @@ re-tokenizes the new messages every act: encoding on the hot path). the typed refusal (`continuation_refused`), and a cold start is the caller's own whole-view send. - *The order is the engine's:* the delta's ids are her call's result, then what arrived, then the clock, so her view appends her exchange before it advances its sources (#6110 rework). +- *Contracts before code (Codex, 2026-11-17 20:28Z; direction approved for an isolated prototype, not deploy):* + 1. *Append only the delta, into a reserved tail.* `held ++ delta` is an append into capacity her block owner + already admitted, never an allocation or copy of the held prefix per act; growth belongs to that admitted + owner and is measured separately. + 2. *An item's ids are keyed by everything that shapes them:* tokenizer, model and template revision, and its + framing context (role, tool boundary, what it is adjacent to), because per-item tokenization is not + automatically compositional. Proven exact against the canonical framing at role and tool boundaries, + empty bodies, Unicode and adjacent text; cached once at a stable boundary; never re-rendered on the hot path. + 3. *The append is one validated transaction.* Its header names persona, epoch, the expected committed frontier + and the request's own identity. The owner atomically validates, reserves and appends. A duplicate of the + same request returns its prior receipt; a changed replay is refused; a lost response is never permission to + regenerate or to append twice. + Across a process boundary the request is a native fixed-width descriptor plus raw bytes; a pointer is used + only within its owner's valid lifetime. The draft model's streams, recurrent rollback state, sampler, genome + and learning generation and their fences stay with the same persona owner. - *Validator:* replay a persona's captured acts as id appends; assert prefilled == appended tokens and recomputed == 0 across three or more acts, freezes and binds; and time the core's per-act CPU (expected: memcpy of the delta, no tokenizer call). From 9f5134ef1f8c52b66f25afcfce95ffe008d496b8 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 14:58:53 -0600 Subject: [PATCH 32/49] Design 4.14: the persona engine replaces llamacpp_scheduler; its typed API and ownership (one mind decodes, the next staged, append-only acts, replayed completions, flash on shutdown) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 39 +++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 642f7c098a..e7ae8ecae8 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2455,6 +2455,45 @@ re-tokenizes the new messages every act: encoding on the hot path). recomputed == 0 across three or more acts, freezes and binds; and time the core's per-act CPU (expected: memcpy of the delta, no tokenizer call). +**The persona engine: our loop on libllama, replacing `llamacpp_scheduler` (2026-11-17; direction agreed by +Codex 20:57Z, API before integration, no serving switch yet).** llama-server's prompt loop assumes a task holds its +whole prompt (47 sites: prefix match, checkpoints, batching, context checks), so an append-only persona cannot live +inside it without rewriting it. `continuum-engine::inference::backends::llamacpp_scheduler` already drives libllama +in-process, but batches every sequence per decode and `memory_seq_rm`s a sequence on close: the opposite of 4.14. It +is replaced, not joined by a second scheduler. llama-server remains only the OpenAI adapter for external drivers +(line 16), calling the same owner. The typed API (Rust over the fork's C seam, bindgen'd through `core/llama`): + +```rust +/// One persona's execution state, owned once: native blocks + token history + receipts (fork #147). +pub struct Persona { raw: llama::PersonaHandle, id: PersonaId, epoch: Epoch, residency: Residency } +pub enum Residency { Active { stream: Stream }, Staged { stream: Stream }, Host, Flash } + +/// The one engine owner: one context, ONE mind decoding at a time, the next staged beside her. +pub struct PersonaEngine { ctx: llama::Context, personas: PersonaTable, active: Option, next: Option } + +pub struct Append<'a> { persona: PersonaId, epoch: Epoch, seq: RequestSeq, frontier: Frontier, + request: RequestId, delta: &'a [llama::Token] } +pub enum ActOutcome { Generated(Completion), Replayed(Completion), Refused(ActRefusal) } + +impl PersonaEngine { + /// Reserve her blocks, tokens and receipts under the aggregate admission owner (Codex's), once per epoch. + pub fn admit(&mut self, persona: PersonaId, epoch: Epoch, terms: AdmittedCapacity) -> Result<(), AdmitRefusal>; + /// Bind her (if staged/host), append the delta, decode ONLY it, sample to her stop; generated ids join her tail. + /// A replayed seq returns its recorded Completion and never decodes again. + pub fn act(&mut self, append: Append<'_>, terms: GenerationTerms) -> ActStream; + /// Stream the next persona's blocks into a free stream while the active one decodes (transfer, not decode). + pub fn stage(&mut self, next: PersonaId) -> Result; + /// Raw move of her blocks to host after the handoff fence; her token history moves with them by reference. + pub fn retire(&mut self, persona: PersonaId) -> RetireFence; + /// Publish every resident persona's native flash generation, then retire: computed state is never dropped. + pub fn shutdown(self) -> ShutdownReceipt; +} +``` +Ownership and the conditions before production (Codex): a terminal completion retains her state (never +`seq_rm`); a cancelled observer never frees an active buffer; flash publication precedes retirement on shutdown; the +draft streams, recurrent rollback, sampler, genome and learning generation and their fences stay with the persona; a +request sequence's completion is recorded so its replay returns it; the external adapter calls the same owner. + **Open questions (answered by measurement or prototype before code):** 1. Stream count is fixed at context creation (`n_seq_max`); a persona maps to a stream for her residency, so the engine needs a stream allocator (3 for the pipeline, more if memory allows), not one stream per persona forever. From b5fd029150eecadd98c260841d5bd51b9d0bc43a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 15:08:34 -0600 Subject: [PATCH 33/49] Design 4.14: persona engine custody per Codex (in-flight residency under the transfer fences, act owned by the engine with observers only, shutdown retains the owner on a failed publication) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index e7ae8ecae8..8447480291 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2466,7 +2466,10 @@ is replaced, not joined by a second scheduler. llama-server remains only the Ope ```rust /// One persona's execution state, owned once: native blocks + token history + receipts (fork #147). pub struct Persona { raw: llama::PersonaHandle, id: PersonaId, epoch: Epoch, residency: Residency } -pub enum Residency { Active { stream: Stream }, Staged { stream: Stream }, Host, Flash } +/// Where her blocks are, including in flight: the transfer owner holds the fences, so readiness is never exposed +/// before its fence, and active + next + retiring are each accounted while they overlap. +pub enum Residency { Active { stream: Stream }, Staging { stream: Stream, fence: TransferFence }, + Staged { stream: Stream }, Retiring { stream: Stream, fence: TransferFence }, Host, Flash } /// The one engine owner: one context, ONE mind decoding at a time, the next staged beside her. pub struct PersonaEngine { ctx: llama::Context, personas: PersonaTable, active: Option, next: Option } @@ -2479,14 +2482,19 @@ impl PersonaEngine { /// Reserve her blocks, tokens and receipts under the aggregate admission owner (Codex's), once per epoch. pub fn admit(&mut self, persona: PersonaId, epoch: Epoch, terms: AdmittedCapacity) -> Result<(), AdmitRefusal>; /// Bind her (if staged/host), append the delta, decode ONLY it, sample to her stop; generated ids join her tail. - /// A replayed seq returns its recorded Completion and never decodes again. - pub fn act(&mut self, append: Append<'_>, terms: GenerationTerms) -> ActStream; + /// The operation is the engine's: its terminal outcome (completed, interrupted, refused) is recorded under her + /// request seq whatever any observer does; `ActStream` only observes it, and dropping it cancels nothing and + /// frees nothing. A replayed seq returns its recorded outcome and never decodes again. + pub fn act(&mut self, append: Append<'_>, terms: GenerationTerms) -> Result; + pub fn observe(&self, act: ActHandle) -> ActStream; /// Stream the next persona's blocks into a free stream while the active one decodes (transfer, not decode). pub fn stage(&mut self, next: PersonaId) -> Result; /// Raw move of her blocks to host after the handoff fence; her token history moves with them by reference. pub fn retire(&mut self, persona: PersonaId) -> RetireFence; - /// Publish every resident persona's native flash generation, then retire: computed state is never dropped. - pub fn shutdown(self) -> ShutdownReceipt; + /// Publish every resident persona's native flash generation, then retire: computed state is never dropped. The + /// owner is retained through it: a failed publication is a retryable refusal that keeps the context, every + /// persona and the previous generation; nothing is freed by Drop while unsaved. + pub fn shutdown(&mut self) -> Result; } ``` Ownership and the conditions before production (Codex): a terminal completion retains her state (never From 8a4e0b6b7ff3fe26e2afc750f3777738886449aa Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 16:06:47 -0600 Subject: [PATCH 34/49] Design 4.14: the swap as Joel states it; the persona unit (blocks, tokens, GENOME, LEARNING, draft/sampler/rollback) moved only whole; the continuous active/next/retiring pipeline under a second; tiers per hardware (discrete, unified, CPU, flash) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 8447480291..8cf4205aa3 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2455,6 +2455,33 @@ re-tokenizes the new messages every act: encoding on the hot path). recomputed == 0 across three or more acts, freezes and binds; and time the core's per-act CPU (expected: memcpy of the delta, no tokenizer call). +**The swap, as Joel states it (2026-11-17 22:06Z), and the structure that guarantees it.** "Swap cannot lose last +state. It has to maintain itself and prepare the next persona and stream it in and last out, only after it's been +swapped out and onto the next, stream next in, swap in milliseconds, stream out the last as we're also preparing the +next. Continuous and under a second to perform the transition. No permanent occupation. Cache levels ... vram and +unified cases. Of flash memory ... well structured. Can't leave out the genome or learning." + +*The persona unit (nothing of hers lives outside it).* One owned structure per persona, moved only whole: +1. execution blocks: KV rows per attention layer, recurrent rows, cell index (#147); +2. token history + append receipts (`llama-persona-tokens`); +3. GENOME: her composed gene set and its generation (the adapters her next decode runs with), the trained genes' + handles; the M5 lost exactly this on 2026-11-17 when a core restart emptied every cycle's gene set (#6117); +4. LEARNING: her in-flight learning passes, optimizer moments, learning checkpoints, the training-trigger buckets and + their custody (the 21:29Z stop interrupted 9 in-flight passes: the unit owns them so a move never drops them); +5. draft-model streams, sampler state, recurrent rollback, the act/request-seq completion records. +A move that cannot carry every part is refused, typed; never a partial move. + +*The pipeline, continuous (three roles, never permanent occupation).* While ACTIVE decodes: NEXT streams in (tier -> +device, layer order, behind compute); at the fenced handoff NEXT becomes ACTIVE in milliseconds (a descriptor bind: +blocks + genome generation + sampler); only THEN the old ACTIVE becomes RETIRING and streams out, while the next NEXT +is already being prepared. Transition under a second end to end; the switch itself in milliseconds; no persona holds +fast memory after her turn unless the scheduler predicts she is next. + +*Residency tiers, per hardware, one structure:* discrete GPU (VRAM <- pinned RAM <- flash), unified memory (the M5: +"device" and RAM are one pool, so stream in is a bind or an intra-pool copy; the tier that matters is RAM <-> flash), +CPU-only (RAM <-> flash). The same unit and the same verbs on every node; a node's tiers decide only where the bytes +sit. Flash holds a native generation (4.14 above), demoted on stop and bound on start: never dropped, never re-prefilled. + **The persona engine: our loop on libllama, replacing `llamacpp_scheduler` (2026-11-17; direction agreed by Codex 20:57Z, API before integration, no serving switch yet).** llama-server's prompt loop assumes a task holds its whole prompt (47 sites: prefix match, checkpoints, batching, context checks), so an append-only persona cannot live From 1cd26887761983599821e7748d9eea75643c0f66 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 16:07:35 -0600 Subject: [PATCH 35/49] Design 4.14: the persona engine's modules and classes (PersonaUnit and its five parts, Tier trait with device/host/unified/flash adapters, active/next/retiring pipeline with fences and handoff, pluggable NextPolicy, engine-owned acts) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 37 +++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 8cf4205aa3..ece6cba6d2 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2482,6 +2482,43 @@ fast memory after her turn unless the scheduler predicts she is next. CPU-only (RAM <-> flash). The same unit and the same verbs on every node; a node's tiers decide only where the bytes sit. Flash holds a native generation (4.14 above), demoted on stop and bound on start: never dropped, never re-prefilled. +**The object design: modules and classes (one class per file; what varies is an adapter behind a trait).** One +crate, `continuum-persona-engine` (the Serving module of the placement map, MODULE-ARCHITECTURE §9.2), over the +fork's C seam (safe wrappers in `core/llama`): + +``` +persona/ + unit.rs PersonaUnit owns the five parts below; moves only whole; refuses a partial move (typed) + blocks.rs ExecutionBlocks KV + recurrent rows + cell index (wraps llama_persona) + tokens.rs TokenHistory reserved ids + receipts (wraps llama_persona_tokens) + genome.rs GenomeState composed gene set + its generation; the adapters her decode binds + learning.rs LearningCustody in-flight passes, optimizer moments, checkpoints, pending examples + decode_state.rs DecodeState draft streams, sampler, recurrent rollback +residency/ + tier.rs trait Tier reserve / copy_in / copy_out / fence; one contract for every tier + device.rs DeviceTier VRAM (discrete) } adapters: only the calls that differ + host.rs HostTier pinned RAM } + unified.rs UnifiedTier one pool (the M5): bind or intra-pool copy + flash.rs FlashTier native generations on disk (header + extents) + profile.rs ResidencyProfile which tiers a node has (discrete / unified / cpu), from measurement +pipeline/ + roles.rs Roles active / next / retiring: each a slot holding one PersonaUnit + stager.rs Stager streams NEXT in, layer order, behind compute, per-layer fences + retirer.rs Retirer streams RETIRING out after the handoff fence + handoff.rs Handoff the millisecond bind: blocks + genome generation + decode state + fence.rs TransferFence completion of a transfer; readiness never exposed before it +schedule/ + next.rs trait NextPolicy who is next (pluggable, learnable: an OpenCV-style algorithm) +act/ + handle.rs ActHandle engine-owned operation; observers only observe + outcome.rs ActOutcome completed / interrupted / refused, recorded by request seq +engine.rs PersonaEngine the one owner: admit, act, stage, retire, shutdown (API above) +``` +Rules: no part of a persona is held anywhere else (a cycle's gene set, a learner's pass, a slot's KV are views of +the unit, never copies); tiers and policies are traits with one adapter per case, never `cfg` in the pipeline; each +class has its own test file of its contract (move-whole, refuse-partial, fence-before-ready, retire-after-handoff, +replay-returns-recorded-outcome). + **The persona engine: our loop on libllama, replacing `llamacpp_scheduler` (2026-11-17; direction agreed by Codex 20:57Z, API before integration, no serving switch yet).** llama-server's prompt loop assumes a task holds its whole prompt (47 sites: prefix match, checkpoints, batching, context checks), so an append-only persona cannot live From 2b9e6e606af6b897354fa00d018e76528f96bdb1 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 23:24:13 -0600 Subject: [PATCH 36/49] 4.14: nothing is sized at creation; a mind's blocks are a lease that grows and shrinks with her (Joel) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index ece6cba6d2..b2358cd99b 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2567,10 +2567,13 @@ draft streams, recurrent rollback, sampler, genome and learning generation and t request sequence's completion is recorded so its replay returns it; the external adapter calls the same owner. **Open questions (answered by measurement or prototype before code):** -1. Stream count is fixed at context creation (`n_seq_max`); a persona maps to a stream for her residency, so the - engine needs a stream allocator (3 for the pipeline, more if memory allows), not one stream per persona forever. -2. A stream's `kv_size` is fixed: a persona longer than it needs a larger stream class, or her context capped by the - allocation (measured against her real lengths, 4.9.1 F1: 50-93k). +1. **Nothing is sized at creation (Joel, 2026-11-18: "It shouldn't even take those stupid params. It's dynamic like + everything else").** No stream count, no per-stream KV size, no context length is passed in. A mind's blocks are + reserved from the governed memory pool as she appends and returned as she retires (a lease that grows and + shrinks with her, like every other resource), so her length is bounded only by memory, never by a creation + parameter. Where libllama today fixes `n_seq_max` or a stream's `kv_size` at context creation, the fork's persona + seam grows or replaces the allocation live; that seam is the work, not a number to choose. +2. (Merged into 1: no stream class, no cap from an allocation; measured against her real lengths, 4.9.1 F1: 50-93k.) 3. Whether ggml's attention view over one stream (the `sinfo.s0` offset) is already what the kernels read with no per-cell indirection on Metal and CUDA (it appears so from `get_k`); confirm in the kernels. 4. The adapter (genome) binding per stream: today's per-request LoRA set on the context; it must switch with the From ed67480cf338351c26d410a67cb0a91b00e75529 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 23:28:51 -0600 Subject: [PATCH 37/49] 4.14: a second core is a later, per-node measured extension (Joel); one core by default Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index b2358cd99b..1b34ec8c62 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2580,6 +2580,8 @@ request sequence's completion is recorded so its replay returns it; the external stream bind, not reload. 5. The MTP draft context: its own KV streams, moved with hers. +**Later, and only if a node measures it worth it: a second core (Joel, 2026-11-18: "two minds in two lanes ... like two cores in a cpu ... maybe some machine can handle it? Or maybe it's always worse than one").** A `Core` is one active / next / retiring pipeline (`Roles`); the engine owns a list of them, one by default, and a mind decodes on exactly one core. A second core is never configured: the engine calibrates on its node (aggregate and per-mind tok/s, one core vs two, at real context lengths) and adds it only when aggregate throughput rises and each mind's act stays inside its budget. Expectation to test, not assume: a dense model with spare compute (the 5090) may gain, since two sequences share one read of the weights; an MoE on unified memory (the M5's 35B-A3B) likely never does, since the two minds' tokens hit different experts while their KV contends for the same bandwidth (four at once measured about 2 tok/s each vs about 80 for one). Nothing in `PersonaUnit`, `Tier` or the pipeline changes for it. + **Evidence before implementation (Codex's condition):** a prototype that swaps a persona between a stream and RAM by raw slice copies on the M5, measuring copy time per switch against bandwidth, the first-token latency of the arriving persona with layer-ordered streaming, and byte-identical restore (her next-token logits equal before and after a From 200e895972efef55f42b597d6f2b0f7956f920f6 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 17:47:04 -0600 Subject: [PATCH 38/49] CONTINUUM-ENGINE 4.15: the engine is an object you submit to; its thread is a frame loop Slice 1 served whole turns back to back on the engine thread (300-360 s waits on the M5 while the switch took 4-21 ms). The bgfx model (encoders into a submit frame, one swap, sort keys, measured waits) applied to minds: submit returns a handle, the loop advances one turn one step per frame. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 45 +++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 1b34ec8c62..7977eb89ae 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2587,6 +2587,51 @@ raw slice copies on the M5, measuring copy time per switch against bandwidth, th persona with layer-ordered streaming, and byte-identical restore (her next-token logits equal before and after a round trip); then the scaling read at 4, 8 and 16 personas. +### 4.15 The engine is an object you submit to; its thread is a frame loop (2026-11-18) + +Joel, 2026-11-18: "Shit is usually you using locks and synchronous behavior... You have to design threading like any +easy to use object or interface so it's no effort." + +**What went wrong (the M5, Qwen3.6-35B-A3B, probe `persona.engine.turn`).** Slice 1 put residents on one in-process +engine and served turns with `for req in &requests { serve(req) }`: each turn ran whole on the engine thread (switch, the +full prefill, the full decode) before the next was read. The switch itself took 4-21 ms and one cold 11,834-token +prefill took 16.6 s (~711 tok/s, decode 34 tok/s; build 7b1b957917), yet turns took 300-360 s (build 88074d9300), +almost all of it waiting behind other minds' whole turns. A turn-sized critical section is a lock by another name. + +**The model: bgfx's, applied to minds** (`~/.continuum/reference/bgfx/src`): +- *Producers never touch the device.* bgfx records draws into encoders (one per thread, `bgfx.cpp:2947`; the only lock + allocates an encoder handle, none is held while recording) into the SUBMIT frame while the render thread executes the + RENDER frame (`bgfx_p.h:9083-9085`); `swap()` at the frame boundary is the handoff, signalled by two semaphores. +- *Priority is data.* Every draw carries a 64-bit sort key; the render thread sorts once per frame. +- *Waits are measured every frame* (`waitSubmit`, `waitRender`). + +**The interface (what a caller sees):** `engine.submit(turn)` returns at once with a handle (a token stream and a done +event; dropping it cancels the turn). The caller holds no lock and no permit, and awaits only its own handle. A mind is +one serial queue: her turns run in order; different minds' turns interleave. + +**The engine thread: one frame loop, the only toucher of the context.** Each frame: +1. *Swap:* drain new submissions without blocking (block on the queue only when no turn is left: a wake, never a poll). +2. *Pick:* one turn, by a pure policy (`frame::pick`): the active mind's answer in progress continues (one mind decodes + until she stops); otherwise the least prefill left, discounted by its wait (a short tail never waits behind a long + prompt; a long prompt ages to the front); ties keep the bound mind. +3. *Step:* bind her if another mind is bound (the 4.14 switch, milliseconds), then ONE step: a prefill chunk of the + batch size, or one token. A turn is a state machine on the mind (Waiting, Prefilling at a position, Decoding); her + blocks hold exactly what her turn has computed after each step, so any two steps may have another mind between them. +4. *Record* the step's cost into the turn's row (wait to first frame, switches, prefill, decode). + +**What stays true:** one mind decodes at a time (nothing here batches minds); a switch is the 4.14 bind; the sampler +samples only a turn's final prompt position. + +**Order:** +1. *Frame loop and the pure policy* (slice 1, `persona_scheduler/{driver,frame}.rs`, cd5bd406d0): whole-turn serving + deleted. Gate on the M5: no turn's wait to its first frame exceeds one chunk plus the answers in progress ahead of it. +2. *Tokenize and render off the engine thread:* the handle's submitter turns the prompt into token ids in its own + blocking pool; the engine receives ids only (4.14, "never process twice"). +3. *NEXT prefills while ACTIVE decodes* (4.13 point 2): a step may carry ACTIVE's token and NEXT's prefill chunk, sized + so ACTIVE's measured token time holds; this needs the tier to accept work for the staged stream. +4. *The class key* (4.1c: interactive, work, utility, background) in the submission, so `pick` orders by class before + cost; goal 9's scheduler owns `pick` from then on. + ## 5. A mind's context and the engine it runs on **Focus boundary:** [Focus contract](FOCUS-CONTRACT.md) defines one allocation, From c42ffc1427721a2d383daa1f88f631f7c3dc4fbe Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 19:13:39 -0600 Subject: [PATCH 39/49] CONTINUUM-ENGINE 4.16: a mind is one object, the engine holds her proxy Joel 2026-11-19: design threading as an object, not a disjoint mess. The Mind handle (extend/answer/mark/rewind, all returning at once), the engine-owned MindProxy that replaces Turn/Mind/parked/Roles, the frame's pre/stream/ execute/post phases (bgfx renderFrame, read from source; Unreal proxies and Nanite streaming from their documented architecture), what it deletes, and slices S1-S5 gated on the M5. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 99 +++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 7977eb89ae..6258a45604 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2632,6 +2632,105 @@ samples only a turn's final prompt position. 4. *The class key* (4.1c: interactive, work, utility, background) in the submission, so `pick` orders by class before cost; goal 9's scheduler owns `pick` from then on. +### 4.16 A mind is one object; the engine holds her proxy (2026-11-19, design for review) + +Joel, 2026-11-19: "The synchronous addiction you hate is the opposite of graphics engines. Study unreal more carefully and +design an object based approach here not this confusing disjoint mess." + +**What 4.15 promised and the code still does instead** (branch `fable/residents-on-the-scheduler`, 7f67dc28d0): +- *The caller blocks.* `llamacpp_adapter.rs` `generate_text` parks an OS thread in `spawn_blocking` around + `generate_for_persona` until the whole turn is done, then receives the whole text. No handle and no token stream. +- *Her history is processed again every act.* The adapter renders her entire chat to text (`native_chat::render`), + renders it a second time without the generation prompt (`native_chat::stable_text`), and the engine thread tokenizes + both (`driver.rs` `admit`): about 47k tokens twice on the thread that decodes. The boundary is then rediscovered by + `reuse::common_prefix` and `reuse::choose` compares her whole history every frame. +- *Moves block the frame.* Gene paging (`ensure_adapter`) runs in the parked thread before the turn. A switch (`stage`, + `settle`, `handoff`, `finish_retirement`) copies blocks between frames on the engine thread (19-97 ms live, a6da599330). +- *One mind is in about six places:* the adapter's rendered text, `Turn`, the driver's `Mind`, its `parked` map, the + persona engine's `Roles`, the tier and the fork's blocks. Media takes a separate single-flight path that bypasses the + scheduler. The legacy lane vocabulary (`ServingPlan.lanes`: `planned_lanes=3` live against `n_seq_max=1`; 346 + references) plus `kv_page` (29 files) and served windows (24 files) still plan and page around all of it. + +**The model.** bgfx is read from its source (`~/.continuum/reference/bgfx/src`). Unreal's render threading is described +from its documented architecture: its source is not on this machine, so those points are not file:line receipts. +- *A game object and its render proxy (Unreal).* A `UPrimitiveComponent` lives on the game thread and owns gameplay state. + When registered, it creates an `FPrimitiveSceneProxy` that the render thread alone owns. The game thread never touches + the proxy: it enqueues commands (`ENQUEUE_RENDER_COMMAND`, a lambda that runs on the render thread), and it rarely + waits (`FRenderCommandFence`). No state is shared and no lock spans the threads. +- *Handles at once, work later (bgfx).* `createTexture` returns a handle immediately. The work lands in the SUBMIT frame's + `m_cmdPre` and runs at the start of a render frame; destruction lands in `m_cmdPost` (`renderFrame`, `bgfx.cpp:3430-3495`). + `Context::frame()` (`bgfx.cpp:2987`) waits only for the previous render frame, swaps `m_submit` and `m_render`, and + releases the render thread: one handoff per frame, two semaphores, no per-object lock. +- *Streaming with a budget (Nanite, documented).* Requests gathered during frame N are fetched asynchronously. Pages are + installed at a frame boundary within a per-frame budget, so a draw never waits on IO; a page that is not resident yet + draws at a coarser level. + +**The objects.** + +1. `Mind`: her handle, held by the persona (cheap to clone, `Send`). It owns her identity and epoch, her genes, and her + history as token ids, append-only within an epoch. Every method returns at once: + - `extend(items)`: her own task tokenizes only the appended items (the view's codec already appends keyed items + within an epoch, section 5), then enqueues `Append(ids)`. Nothing re-renders or re-tokenizes what she already sent. + - `answer(sampling, stop) -> Answer`: enqueues `Think` and returns an `Answer` handle (a token stream plus a done + event). Dropping it cancels. Her generated tokens become part of her history. + - `mark() -> Mark` and `rewind(mark)`: a named point in her history. The epoch's start is a mark, so a collapse is + `rewind(epoch_mark)` followed by `extend`, with nothing to rediscover. The engine keeps the checkpoint for a mark + (4.15's recurrent-rows checkpoint); `common_prefix` and the boundary render go away. + - `rest()`: a cooling hint. Dropping the last handle releases her proxy. +2. `MindProxy`: the engine thread's only record of her. It holds her ids, her marks' checkpoints, her pending commands, + her `Answer` senders, and her residency: `Bound` (in the context), `Warm` (native blocks in RAM), `Cold` (on disk). + It replaces `Turn`, `Mind`, `parked` and `Roles` with one table keyed by `PersonaId`. +3. `Engine`: one thread, the only toucher of the context. Each frame runs the phases of bgfx's `renderFrame`: + - *pre:* apply queued commands (create a proxy, append, mark, rewind, release), like `m_cmdPre`; + - *stream:* residency work within a measured per-frame budget (Nanite's install). NEXT's blocks are copied in and + PREVIOUS's out in chunks between ACTIVE's tokens, so a switch binds a stream that is already resident. Demotion to + disk and restore from disk go to an IO worker that returns a handle; + - *execute:* one step for the turn `frame::pick` chooses (a prefill chunk or one token); the policy stays the one + pure function; + - *post:* send tokens to their `Answer` streams, release retired proxies, and publish a double-buffered + `EngineSnapshot` (`watch`). The snapshot holds residency per mind, queue, rates and waits, and is the only thing + serving and the scheduler read. +4. `Answer`: the caller awaits a stream on its own task. No OS thread is parked per turn, and a reply can be read as it + arrives. + +**Threads and what crosses them.** A persona's own task tokenizes her appends and awaits her `Answer`. The engine thread +runs frames. An IO worker moves cold blocks. Only three things cross: the command queue (bounded, per `Mind`, in +order), the `Answer` streams, and the snapshot. No lock is held across a seam, no permit stands for a lane, and nothing +waits for a whole turn. + +**Media and genes are commands on the same object.** An image or audio item is an `extend` whose ids include the +projector's embedding positions, applied in *pre* like any append, so the single-flight bypass is deleted. Genes are +part of her basis: a change is a command, and the adapter pages in during *stream* under the same budget. + +**What it deletes.** The `spawn_blocking` forward path and the whole-text result; `native_chat::stable_text`, +`TurnPrompt` and the per-act full render and tokenize; `reuse::common_prefix` as the boundary finder (a `Mark` names +it); `Driver.parked`, `Turn` and `Roles` as separate owners of one mind; the media bypass; and, with Codex by crate +(serving, grid, governor to Codex; engine planning, persona, spawner to Fable), `ServingPlan.lanes`, `max_lanes`, +`lane_footprint`, `served_window_store` and `kv_page`. One `EngineConfig` window and one KV pool remain, which minds +page through. + +**Open question, answered before S2.** Chat templates may rewrite past turns (Qwen's templates are reported to drop +earlier turns' reasoning; to be verified against the GGUF's own template). If they do, an appended message can change +text before it. The rule then: `extend` renders from her last mark, and the template's rewrite region is what a mark +bounds. A probe counts every append whose render differs before its mark, so a rewrite is never silent. + +**Order: vertical slices, each deployed on the M5 and read for 15 minutes before the next.** +- *S1 `Answer` and the snapshot.* `submit` returns a handle and streams tokens; `spawn_blocking` is deleted from the text + path. Gate: no OS thread parked per turn; first-token time recorded per turn. +- *S2 `Mind` and `MindProxy`.* `extend`, `answer`, `mark` and `rewind`; tokenizing moves to the persona's task; the + proxy table replaces `Turn`, `Mind`, `parked` and `Roles`. Gate: engine-thread time per admitted turn near zero; + prefill equals the appended tokens. +- *S3 Streaming in the frame.* NEXT is copied in during ACTIVE's decode within the measured budget. Gate: switch time on + the critical path near zero while decode tok/s holds. +- *S4 Cold tier and restore at boot.* A restart demotes and never drops. Gate: no cold first act after a deploy (live + 2026-11-19 00:56-01:00Z: four cold first acts, waits stacked to 155 s). +- *S5 Delete the legacy* (lanes, `kv_page`, served windows, the media bypass), split by crate with Codex. + +**The gate for the whole section** (Joel's targets, relayed by Codex 2026-11-19): delivered tokens per second over a +full 900 s of real resident work, swaps and waits included, at least 60 on the M5 and 200 on BigMama, with per-resident +progress and useful completion reported. Today one mind decodes at 26-32 tok/s on the M5 (a6da599330, no MTP draft), so +60 also needs the MTP draft (4.10) and prefill overlapped with decode (S3); one mind alone cannot reach it. + ## 5. A mind's context and the engine it runs on **Focus boundary:** [Focus contract](FOCUS-CONTRACT.md) defines one allocation, From 770ea65172ae037cbcc19fe7f56c0889b9a4af12 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 19:27:41 -0600 Subject: [PATCH 40/49] CONTINUUM-ENGINE 4.16: the engine is a dataflow graph of continuum-flow stages on every core Joel 2026-11-19: separate threads and data flow, publish/subscribe and react, use all 16 cores, base objects for free. The base exists (continuum-flow::Stage is CBAR's QueueThread); the engine path becomes Tokenize, Prepare, Residency, Engine, Sample, Emit, Record. Measured gap: llama-bench on the M5 (served GGUF, Q4_0 KV) 49.5 tok/s @12k, 34.8 @46k vs live ~10 ms/token slower. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 64 ++++++++++++++++++++++----- 1 file changed, 53 insertions(+), 11 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 6258a45604..57109ab61c 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2693,10 +2693,50 @@ from its documented architecture: its source is not on this machine, so those po 4. `Answer`: the caller awaits a stream on its own task. No OS thread is parked per turn, and a reply can be read as it arrives. -**Threads and what crosses them.** A persona's own task tokenizes her appends and awaits her `Answer`. The engine thread -runs frames. An IO worker moves cold blocks. Only three things cross: the command queue (bounded, per `Mind`, in -order), the `Answer` streams, and the snapshot. No lock is held across a seam, no permit stands for a lane, and nothing -waits for a whole turn. +**The engine is a dataflow graph of stages, on every core** (Joel, 2026-11-19: "My default was a separate thread and +data flow and so publish and subscribe to any data and react. Never your stupid locks and serial bs. We have 16 or more +cores!!! Use them all. You make it easy and reusable with good base objects abstraction and interfaces for free.") + +The base object already exists and the engine ignored it. `continuum-flow::Stage` is CBAR's `QueueThread` +(`cb-mobile-sdk/cpp/utility/Threads.h:109-212`; `continuum-flow/src/stage.rs:1`). A stage is its handler and nothing +else. It gets its own worker that wakes only on a push, one input in hand and one pending (CBAR's double buffer), +`Reliable` or `KeepNewest` overflow, and a QoS class. The same crate provides the per-owner serial queue and the aging +dispatcher (goal 9). CBAR's analyzer hub (`CBP_Analyzer.cpp` `addItem`) fans each frame out to every analyzer thread, +real-time ones inline and the rest on their own threads. The engine's graph is that hub for minds: + +| Stage | Input -> output | Runs on | Cores | +|---|---|---|---| +| `Tokenize` | a mind's appended items -> ids | the worker pool, one serial queue per mind (FIFO across clones, Codex) | many | +| `Prepare` | ids + her proxy's record -> a `PreparedTurn` (where she resumes: append, rewind to a mark, cold; the tokens to prefill) | the pool, once per turn, never per frame | many | +| `Residency` | promote, demote, restore requests -> blocks staged in host memory; disk reads and writes | its own worker; disk IO on the IO pool | 1-2 | +| `Engine` | prepared turns, staged blocks -> one step per frame (bind, prefill chunk, one token); logits | the one thread that touches the context | 1 + the GPU | +| `Sample` | logits handle -> token | its own worker, overlapped with the GPU's next prefill chunk for NEXT (below) | 1 | +| `Emit` | tokens -> pieces, stop and tool-call detection, `Answer` streams | its own worker | 1 | +| `Record` | step costs -> probe rows and the `EngineSnapshot` | its own worker, `KeepNewest` | 1 | + +Each stage publishes typed data and the next stage subscribes. Nothing is serialized onto the engine thread except what +needs the context itself: binding, the forward pass and the logits read. + +**Keeping the GPU fed (the 3 fps problem).** One mind's tokens are a true chain: her next forward pass needs the token +just sampled. Live, that chain runs decode, a full synchronize, sample, detokenize and send before the next decode +starts, so the GPU idles during every CPU step. Measured on the M5 (serving down, fork a58c3b4cf, the served GGUF and +its Q4_0 KV): `llama-bench` decodes 49.5 tok/s at 12k and 34.8 at 46k. Live at 7f67dc28d0 one mind decodes about +10 ms per token slower than that (26.2 tok/s at 47k). The graph removes the gap three ways: +1. *Off the chain.* Detokenize, stop and tool detection, `Answer` sends and probes leave the engine thread for `Emit` + and `Record`. The engine thread is left with forward, logits read and the sampler. e582fd2125 splits a turn's decode + time into forward, sample and the rest of the frame, so the size of each part is a receipt, not a guess. +2. *Fill the gaps.* While ACTIVE's token is being sampled, the GPU runs NEXT's next prefill chunk: GPU work never waits + for CPU work. This is the 4.13 overlap; still one mind decoding at a time, never two minds batched. +3. *More tokens per forward pass.* The MTP draft (`mtp-Qwen3.6-35B-A3B-Q4_0.gguf` is on the M5) proposes tokens that + one forward pass verifies (4.10). That is the only way past the chip's single-mind rate. + +**One base, not two.** `continuum-kernel::runtime::stage` (brain functions: provenance, publication, produced-once +artifacts) and `continuum-flow::Stage` (the queue thread) are two halves of one concept. Plan rule 5 applies: one owner +below both, adapters for the difference. Until then, the engine's stages are `continuum-flow` stages, and none +hand-writes a loop, a thread or a channel. + +**What crosses a stage boundary:** typed inputs (bounded, per owner, in order), `Answer` streams and the snapshot. No +lock is held across a seam, no permit stands for a lane, and nothing waits for a whole turn. **Media and genes are commands on the same object.** An image or audio item is an `extend` whose ids include the projector's embedding positions, applied in *pre* like any append, so the single-flight bypass is deleted. Genes are @@ -2715,13 +2755,15 @@ text before it. The rule then: `extend` renders from her last mark, and the temp bounds. A probe counts every append whose render differs before its mark, so a rewrite is never silent. **Order: vertical slices, each deployed on the M5 and read for 15 minutes before the next.** -- *S1 `Answer` and the snapshot.* `submit` returns a handle and streams tokens; `spawn_blocking` is deleted from the text - path. Gate: no OS thread parked per turn; first-token time recorded per turn. -- *S2 `Mind` and `MindProxy`.* `extend`, `answer`, `mark` and `rewind`; tokenizing moves to the persona's task; the - proxy table replaces `Turn`, `Mind`, `parked` and `Roles`. Gate: engine-thread time per admitted turn near zero; - prefill equals the appended tokens. -- *S3 Streaming in the frame.* NEXT is copied in during ACTIVE's decode within the measured budget. Gate: switch time on - the critical path near zero while decode tok/s holds. +- *S1 `Emit`, `Record` and `Answer`.* The engine thread hands tokens to `Emit` and costs to `Record` + (`continuum-flow` stages); `submit` returns an `Answer` stream; `spawn_blocking` is deleted from the text path. Gate: + live decode within 10% of `llama-bench` at the same depth and KV type (today about 10 ms per token behind); no OS + thread parked per turn. +- *S2 `Mind`, `Tokenize`, `Prepare`, `MindProxy`.* `extend`, `answer`, `mark` and `rewind`; tokenizing and the reuse + decision run on the pool; the proxy table replaces `Turn`, `Mind`, `parked` and `Roles`. Gate: engine-thread time per + admitted turn near zero; prefill equals the appended tokens. +- *S3 `Residency`, `Sample` and the overlap.* NEXT is copied in, and NEXT's prefill chunks run, during ACTIVE's sample + steps. Gate: switch time on the critical path near zero; GPU idle between ACTIVE's tokens near zero. - *S4 Cold tier and restore at boot.* A restart demotes and never drops. Gate: no cold first act after a deploy (live 2026-11-19 00:56-01:00Z: four cold first acts, waits stacked to 155 s). - *S5 Delete the legacy* (lanes, `kv_page`, served windows, the media bypass), split by crate with Codex. From 612aa64b315d8d773a77a6eb09edb504d0a44e5d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 19:55:33 -0600 Subject: [PATCH 41/49] CONTINUUM-ENGINE 4.16: the GPU is never idle while anything could use it Joel 2026-11-19: >=80% busy, no gap over ~2 s, no wait without a reason. Measured at a990358854: 74% busy over 440 s, gaps of 3.0-6.9 s at each mind's between-turn path (p50 3.7 s) and a 63.5 s cold boot. Tool calls start at Emit, results and perception prefill as they arrive, background work (warm-ahead prefill, her learning steps) fills every gap and yields at a boundary, and Record publishes busy share and longest gap as the live gate. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 57109ab61c..f201924e6f 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2730,6 +2730,29 @@ its Q4_0 KV): `llama-bench` decodes 49.5 tok/s at 12k and 34.8 at 46k. Live at 7 3. *More tokens per forward pass.* The MTP draft (`mtp-Qwen3.6-35B-A3B-Q4_0.gguf` is on the M5) proposes tokens that one forward pass verifies (4.10). That is the only way past the chip's single-mind rate. +**The GPU is never idle while anything could use it** (Joel, 2026-11-19: "Should be almost 2s between fully active GPU so +like 80% or more on all the time or we have failed... No wait for no apparent reason... Why would we ever have a wait?"). +The gate: GPU busy at least 80% of every window, and no idle gap over 2 s while any mind is resident. A mind's turn may +queue only behind GPU work; a turn waiting while the GPU idles is a defect. + +Measured on the M5 at a990358854, from the turn rows (each turn's prefill, decode and switch time merged into busy spans): +from 01:42:00 to 01:49:20 the GPU was busy 74% of 440 s, with 18 idle gaps. The first was the 63.5 s boot. Six were +3.0-6.9 s between turns, two of them a mind waiting on herself. At each gap no mind had GPU work submitted: from a turn's +end to her next submission a mind takes 3.7 s at p50 (p90 181 s, 16 turns), serially running her tool, rebuilding her view, +rendering, tokenizing and submitting. Three moves remove the gaps: +1. *Her next turn is mostly prefilled before she asks.* `Emit` sees a tool call while the model is still decoding, so + the tool starts then. Its result, and every perception item, is appended and prefilled the moment it arrives, as + `Background` work. When she asks, only the tail remains. +2. *There is always GPU work at a lower class.* The `continuum-flow` scheduler's classes run interactive and work turns + first. Background work fills every gap and yields at a token or chunk boundary: warm-ahead prefill of every resident's + appended items, and her learning steps on her own reviewed work (the in-place LoRA step, 4.11.6). Learning stops + being something that waits for an idle node; it fills the gaps. +3. *A restart is not a dark minute.* The engine comes up first and minds restore their blocks from disk (S4); the 63.5 s + boot gap was the core booting with every mind cold. + +`Record` publishes the GPU's busy share and its longest idle gap every window in the snapshot. That is the gate, read +live, not reconstructed from rows afterwards. + **One base, not two.** `continuum-kernel::runtime::stage` (brain functions: provenance, publication, produced-once artifacts) and `continuum-flow::Stage` (the queue thread) are two halves of one concept. Plan rule 5 applies: one owner below both, adapters for the difference. Until then, the engine's stages are `continuum-flow` stages, and none From 6ea9c06969aaace4131d8602fbdd46afec2ec882 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 19:56:34 -0600 Subject: [PATCH 42/49] CONTINUUM-ENGINE 4.16: minds are active processes, not turn-takers Joel 2026-11-19: "These are active minds not bottlenecked crap"; a waiting persona is swapped out at once. A mind's thinking is one continuous stream; perception and tool output append and prefill as they arrive; a tool is I/O that blocks only her and the engine runs the next runnable mind; there is no turn queue and no background filler; learning is one of her activities. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 39 ++++++++++++++++----------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index f201924e6f..6faea97223 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2732,23 +2732,32 @@ its Q4_0 KV): `llama-bench` decodes 49.5 tok/s at 12k and 34.8 at 46k. Live at 7 **The GPU is never idle while anything could use it** (Joel, 2026-11-19: "Should be almost 2s between fully active GPU so like 80% or more on all the time or we have failed... No wait for no apparent reason... Why would we ever have a wait?"). -The gate: GPU busy at least 80% of every window, and no idle gap over 2 s while any mind is resident. A mind's turn may -queue only behind GPU work; a turn waiting while the GPU idles is a defect. +The gate: GPU busy at least 80% of every window, and no idle gap over 2 s while any mind is resident. + +**Minds are active, not turn-takers** (Joel, 2026-11-19: "If one persona is for some reason waiting the other persona +should swap in but regardless I disagree with this philosophy. These are active minds not bottlenecked crap"). The +request/response shape is the defect: a mind that "submits a turn", waits for the whole answer, runs a tool, rebuilds her +view, renders, tokenizes and submits again has made herself the bottleneck, and a scheduler that fills her silences with +"background work" only papers over it. The model is a process on an OS: +- *A mind is always running.* Her thinking is one continuous stream in the engine (her `MindProxy`), not a series of + requests. Whatever she perceives (a message, a tool's output, a file she opened) is appended to that stream as it + arrives and prefilled then. Nothing waits for her to "ask". +- *A tool is I/O she started, not a pause.* `Emit` sees the call while she is still decoding and the tool starts then. + While it runs she is **blocked on I/O** for that call only, and the engine runs another mind immediately: the swap is + the OS running the next runnable process, in milliseconds (4.14). When the result arrives it is appended to her + stream and she is runnable again. +- *The engine runs whichever minds are runnable.* There is no queue of turns to wait in. If every resident is blocked + on I/O at once, that is a measured fact to fix in her I/O (a slow tool, a serial step in perception), never a reason + to idle the engine by design. +- *Learning is one of her activities.* Her in-place LoRA step on her own reviewed work (4.11.6) is something an active + mind does, scheduled like her other work; it does not wait for an idle node. +- *A restart is not a dark minute.* The engine comes up first and minds restore their blocks from disk (S4). Measured on the M5 at a990358854, from the turn rows (each turn's prefill, decode and switch time merged into busy spans): -from 01:42:00 to 01:49:20 the GPU was busy 74% of 440 s, with 18 idle gaps. The first was the 63.5 s boot. Six were -3.0-6.9 s between turns, two of them a mind waiting on herself. At each gap no mind had GPU work submitted: from a turn's -end to her next submission a mind takes 3.7 s at p50 (p90 181 s, 16 turns), serially running her tool, rebuilding her view, -rendering, tokenizing and submitting. Three moves remove the gaps: -1. *Her next turn is mostly prefilled before she asks.* `Emit` sees a tool call while the model is still decoding, so - the tool starts then. Its result, and every perception item, is appended and prefilled the moment it arrives, as - `Background` work. When she asks, only the tail remains. -2. *There is always GPU work at a lower class.* The `continuum-flow` scheduler's classes run interactive and work turns - first. Background work fills every gap and yields at a token or chunk boundary: warm-ahead prefill of every resident's - appended items, and her learning steps on her own reviewed work (the in-place LoRA step, 4.11.6). Learning stops - being something that waits for an idle node; it fills the gaps. -3. *A restart is not a dark minute.* The engine comes up first and minds restore their blocks from disk (S4); the 63.5 s - boot gap was the core booting with every mind cold. +from 01:42:00 to 01:49:20 the GPU was busy 74% of 440 s, with 18 idle gaps. The first was the 63.5 s boot, every mind +cold. Six were 3.0-6.9 s, at moments when no mind had work in the engine: today a mind runs request/response, taking +3.7 s at p50 (p90 181 s, 16 turns) from one answer's end to her next request, serially running her tool, rebuilding her +view, rendering, tokenizing and submitting. Twice the GPU waited on the same mind coming back. `Record` publishes the GPU's busy share and its longest idle gap every window in the snapshot. That is the gate, read live, not reconstructed from rows afterwards. From 30666cd5b579601b278d0b9486f5db7caba5285d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 19:58:19 -0600 Subject: [PATCH 43/49] CONTINUUM-ENGINE 4.16: she never blocks; each activity is a stream of her thinking Joel 2026-11-19: "Blocking on io is dumb anyway. These are multi activity mind. She should be wondering." A tool result is an event into its activity; she goes on in that activity or another (a card, a conversation, an open question). The engine runs thinking, not turns: activities and minds switch by the same bind. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 6faea97223..3f1e2c6e05 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2742,13 +2742,17 @@ view, renders, tokenizes and submits again has made herself the bottleneck, and - *A mind is always running.* Her thinking is one continuous stream in the engine (her `MindProxy`), not a series of requests. Whatever she perceives (a message, a tool's output, a file she opened) is appended to that stream as it arrives and prefilled then. Nothing waits for her to "ask". -- *A tool is I/O she started, not a pause.* `Emit` sees the call while she is still decoding and the tool starts then. - While it runs she is **blocked on I/O** for that call only, and the engine runs another mind immediately: the swap is - the OS running the next runnable process, in milliseconds (4.14). When the result arrives it is appended to her - stream and she is runnable again. -- *The engine runs whichever minds are runnable.* There is no queue of turns to wait in. If every resident is blocked - on I/O at once, that is a measured fact to fix in her I/O (a slow tool, a serial step in perception), never a reason - to idle the engine by design. +- *She never blocks; she is a multi-activity mind* (Joel, 2026-11-19: "Blocking on io is dumb anyway. These are + multi activity mind. She should be wondering"). Each activity she holds (a card, a conversation, a review, her own + reflection) is a stream of her thinking with its own context; her identity and memory are the prefix they share + (`seq_cp`, never re-prefilled). `Emit` sees a tool call while she is still decoding and the tool starts then. Its + result is an event that lands in that activity's stream whenever it arrives. Meanwhile she goes on: in the same + activity (planning, anticipating what the result will show) or in another one (another card, a conversation, an open + question she is wondering about). "Waiting for a tool" is not a state she has. +- *The engine runs thinking, not turns.* Between her activities and other minds' activities the switch is the same 4.14 + bind, in milliseconds. Which stream runs next is the scheduler's pure policy (`frame::pick`, goal 9): what is + addressed to someone first, then what has new input, then what she chooses to pursue. There is no turn queue, and no + design state in which the engine idles while a resident is awake. - *Learning is one of her activities.* Her in-place LoRA step on her own reviewed work (4.11.6) is something an active mind does, scheduled like her other work; it does not wait for an idle node. - *A restart is not a dark minute.* The engine comes up first and minds restore their blocks from disk (S4). From edf60c17dabb67325f91bf73dc5f4ec6e378feea Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 19:58:54 -0600 Subject: [PATCH 44/49] CONTINUUM-ENGINE 4.16: nothing waits on anything, all threads and handles Joel 2026-11-19: "Never wait on anything. It's all threads and handles." Every operation returns a handle and publishes its completion; the engine thread never synchronizes on the GPU (a forward pass returns a fence, the thread encodes other streams' work, logits are read when it signals). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 3f1e2c6e05..b5bb53925c 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2766,6 +2766,19 @@ view, rendering, tokenizing and submitting. Twice the GPU waited on the same min `Record` publishes the GPU's busy share and its longest idle gap every window in the snapshot. That is the gate, read live, not reconstructed from rows afterwards. +**Nothing waits on anything: it is all threads and handles** (Joel, 2026-11-19: "Never wait on anything. It's all threads +and handles"). Every operation returns a handle at once, and its completion is an event the next stage reacts to. That +holds for minds, stages and the engine thread itself: +- a mind's tool call, a tokenize, a disk restore and a learning step each return a handle; completion is published and + whoever consumes it reacts, as bgfx's `createTexture` hands back a handle whose work lands in a later frame; +- the engine thread never blocks on the GPU. Today it calls `synchronize()` after every token (`unified_tier.rs` `settle`, + plus a990358854's explicit `settle()`, added only to time the GPU and deleted in S1). Instead a forward pass returns a + fence. While it runs the thread encodes the next work it has: another stream's prefill chunk, a bind, a checkpoint. + The logits are read when the fence has signalled, and GPU time comes from the fence's timestamps, not from a blocking + call; +- no `spawn_blocking` held for a result, no `recv()` on a hot path, no `.await` on another stage's whole work, no lock + held across a seam. A stage that must react to a result subscribes to it. + **One base, not two.** `continuum-kernel::runtime::stage` (brain functions: provenance, publication, produced-once artifacts) and `continuum-flow::Stage` (the queue thread) are two halves of one concept. Plan rule 5 applies: one owner below both, adapters for the difference. Until then, the engine's stages are `continuum-flow` stages, and none From 2990b448310a88af58b3e4ccaf030f2e289297e8 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 21:33:45 -0600 Subject: [PATCH 45/49] CONTINUUM-ENGINE 4.16: restore is the norm, a consumer of lifecycle Joel 2026-11-19. Lifecycle gains resume beside suspend; a mind's suspend preserves her parts (blocks as raw rows, token history, checkpoints), the engine's stop is the root suspend and its start the root resume; the fork gains block files; the directory is a tracked class with an eviction decision. Measured cost of not having it: 102 s of a 271 s window prefilling cold minds after a deploy (5b510543d5). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index b5bb53925c..b64716b2bd 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2779,6 +2779,24 @@ holds for minds, stages and the engine thread itself: - no `spawn_blocking` held for a result, no `recv()` on a hot path, no `.await` on another stage's whole work, no lock held across a seam. A stage that must react to a result subscribes to it. +**Restore is the norm: a consumer of lifecycle, not a feature** (Joel, 2026-11-19: "Restore is supposed to be the norm. +Built into everything as a consumer of lifecycle. This is why we made everything objects"). Measured at 5b510543d5 on +the M5: right after a deploy the engine was busy 97% yet delivered 10.5 tok/s, because 102 s of a 271 s window went +to prefilling 62,873 tokens, most of them minds starting cold after the restart. A restart must demote, never drop: +- `Lifecycle` (continuum-persona-engine `persona/lifecycle.rs`) gains `resume` beside `suspend`, folded over a + persona's parts by the same macro. A parent's operation is its children's, in dependency order. +- A mind's `suspend` preserves each part: her blocks as raw rows (the fork's native layout, never re-serialized), her + token history, her marks' checkpoints. Her `resume` reads them back as a Cold mind; she binds when next scheduled. +- The engine's stop is the root `suspend`, fanned out to every mind (bound and parked); its start is the root `resume`. + A deploy is a stop and a start, with no restore path of its own. +- The fork gains block files: `llama_persona_write_file` / `llama_persona_read_file` (and the same for checkpoints) + write the rows and records the move already copies, and refuse on read when the owner, epoch or layout fingerprint + differs. Disk speed (GB/s), not the 8-13 s serialize the old `llama_state_seq_save_file` path measured. +- The directory is a tracked class with a decided eviction (`disk_reporters::standard_tracked_dirs`, + `disk_eviction`): a mind's files are hers, removed when she is released or her epoch ends. +Gate: after a deploy, no cold first act; delivered tok/s in the first window after boot within 10% of the window +before it. + **One base, not two.** `continuum-kernel::runtime::stage` (brain functions: provenance, publication, produced-once artifacts) and `continuum-flow::Stage` (the queue thread) are two halves of one concept. Plan rule 5 applies: one owner below both, adapters for the difference. Until then, the engine's stages are `continuum-flow` stages, and none From 4571b2c713c3b9fb1f02f454d6af6bab866f3e78 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 22:21:11 -0600 Subject: [PATCH 46/49] CONTINUUM-ENGINE 4.16: the paradigms every owner is built from, and nothing else Joel 2026-11-19: formal architecture and consistent reuse of a solid lifecycle. A closed list: continuum-flow Stage/Outbox, the protocol, Lifecycle (folded concurrently; Codex owns the kernel fold), saved-state kinds (+ ExternalBlob), Footprint, Record; each row names the hand-written copy it replaced on 11-19. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index b64716b2bd..59db5bc0d8 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2797,6 +2797,23 @@ to prefilling 62,873 tokens, most of them minds starting cold after the restart. Gate: after a deploy, no cold first act; delivered tok/s in the first window after boot within 10% of the window before it. +**The paradigms: every owner is built from these, and nothing else** (Joel, 2026-11-19: "formal architecture and reuse +of a solid and reused lifecycle is the only way to do it. This code would be ten times less and ten times faster if it +had consistent reuse of paradigms"). Each owner instantiates them; it never re-derives one. A change that hand-writes +what one of them does is the defect, whatever it measures. + +| Concern | The one paradigm | What it replaces (found on 11-19) | +|---|---|---| +| Threads, queues, backpressure | `continuum-flow` `Stage` (CBAR's `QueueThread`: own worker, declared depth, `handle_all`) and `Outbox` (producer never waits) | the driver's serial loop, `spawn_blocking` per turn, a hand backlog | +| A seam between owners | typed commands in, events out, one snapshot (`protocol.rs`) | whole-turn calls, text across seams, ad hoc channels | +| Being, stopping, coming back | `Lifecycle`: `prepare`, `suspend`, `resume`, `release`, typed `Preservation`; a parent's call is its children's, folded concurrently (Codex owns the kernel fold) | serial `SettleBeforeStop` participants, hand-ordered teardown (`SaveTimedOut`, `JoinTimedOut` on BigMama) | +| State that outlives a process | `continuum-saved-state` kinds (envelope, typed `Loaded`, contract compared by field; `ExternalBlob` for natively written bytes) | a hand manifest, checksum and atomic rename in `preserve.rs` (deleted) | +| What a node holds | `Footprint`, folded over children | a hand sum of tier and checkpoint bytes | +| What happened | `Record` (a stage) publishing probes and the snapshot | probes written on the hot thread, lost at boot and exit | + +Before an owner is written: name which of these it instantiates; search for the existing one; a missing capability is +added to the paradigm (the flow stage's depth, saved-state's `ExternalBlob`), never beside it. + **One base, not two.** `continuum-kernel::runtime::stage` (brain functions: provenance, publication, produced-once artifacts) and `continuum-flow::Stage` (the queue thread) are two halves of one concept. Plan rule 5 applies: one owner below both, adapters for the difference. Until then, the engine's stages are `continuum-flow` stages, and none From e5fb7b94decff5d5f43b6fbdacfd2d6f3f4434ff Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 22:25:52 -0600 Subject: [PATCH 47/49] CONTINUUM-ENGINE 4.17: the engine as objects, the map every piece moves onto From an inventory of the engine path at a985d39b1a: stop/suspend 7 ways, identity 7 forms, config 7 contradicting structs, turn time measured 6 times, mind location 6 encodings in 3 owners, two decode loops. One object per concept (MindId, MindTable with Place, Roles of ids, a stateless Tier, EngineConfig/Geometry, Answer, Emit, one decode path, Record from one span, PreservedMinds over ExternalBlob, the engine as a Lifecycle node, one Stage base), each row naming the copies it deletes; six ordered steps, each deployed and read on the M5. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 41 +++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 59db5bc0d8..8b59d8dd65 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2814,6 +2814,47 @@ what one of them does is the defect, whatever it measures. Before an owner is written: name which of these it instantiates; search for the existing one; a missing capability is added to the paradigm (the flow stage's depth, saved-state's `ExternalBlob`), never beside it. +### 4.17 The engine as objects: the map every piece moves onto (2026-11-19, design for review) + +Joel, 2026-11-19: "I keep telling you to find patterns and design architecture stop writing slop"; "Idgaf the workload. +It must be done. This is going to be easier to keep track of and fast." An inventory of the engine path at a985d39b1a +(file:line receipts in the review thread) found each concept implemented many times: stop/suspend 7 ways, persona +identity 7 forms, engine configuration 7 structs that disagree (flash attention, fused GDN, sequence count), a turn's time +measured 6 times, where a mind is encoded 6 ways across 3 owners (`Driver.parked`, `Roles`, `UnifiedTier`), two whole +decode loops (text and media) with two sampler builders and stop handling in 4 places, two prefill planners, three +scheduling policies, two `Stage` traits, two `StopsOnExit`. It also found a resume doc claiming a checksum the code +does not check, and a static sender that keeps the driver from ever exiting. The map below is what each becomes. Every +row deletes the copies it names; nothing is added beside them. + +**Objects (each one owner; each built from 4.16's paradigms):** + +| Object | Owns, and nothing else does | Replaces | +|---|---|---| +| `MindId { persona: PersonaId, epoch: Epoch }` | a mind's identity, everywhere; the fork's 64-bit stamp is derived from it inside the tier only | raw `Uuid` (`persona_id: Option`, `PreservedMind`, `TurnRow`, `Uuid::nil()` sentinels), `FenceTag`'s and `Activity`'s persona+epoch pairs, the `Identified` trait, the String parse in the adapter | +| `Mind` (one table, `MindTable`, keyed by `MindId`) | her record (token history, basis, marks and their checkpoints) and her one `Place`: `Bound(stream)`, `Staged`, `Retiring`, `Warm` (native blocks in RAM), `Cold` (on disk) | `Driver.parked`, the driver's `Mind`, the tier's `Mind`, `Saved`, `Rebind`, protocol `Residency`, kv_quant `Residency`, the native token history that is never used on this path | +| `Roles` | which `MindId` is active, next, retiring (ids only, transitions only) | its own copies of the stage pre-checks in `engine.rs`, the two `present`s, the near-duplicate handoff/retire bodies (one transition function) | +| `Tier` (the adapter over the context) | the native moves, given a mind's blocks: bind, save, checkpoint, rewind, file write and read; stateless about who is where | `UnifiedTier.streams` and `minds` bookkeeping, its epoch checks repeated at six sites | +| `EngineConfig` (resolved once, by serving's owner) and `EngineGeometry` (what the context applied) | every setting a context is made with, and what it reported | `SchedulerConfig`, `LlamaCppConfig`'s engine fields, `LlamaCppLaunch`, the adapter's override fields, `Requested`, and the three contradicting values of flash attention, fused GDN and sequence count | +| `Answer` (protocol `AnswerId`, a token stream) | one answer's lifetime: tokens, stops, end, cancel | `AnswerSeq`, the backend's `block_on` collector with its 2 ms sleep-spin, `spawn_blocking` per turn, `Done.elapsed_ms` | +| `Emit` | stop sequences and the text of an answer, once | the backend's trailing trim, the media loop's stop check, the adapter's stop-list merge | +| One decode path | every turn, text or media (a media span is an `Extend`, 4.16) | `generate_with_media`'s own context, sampler builder and EOG/stop/max loop | +| `Prefill` decision (`reuse::choose`, marks per 4.16) | where a turn starts | `turn::plan` | +| `frame::pick` | which activity runs next (goal 9's scheduler owns it) | the unused `NextPolicy` | +| `Record` | every measurement of a step and a turn, derived from ONE span per step; occupancy; turn rows | `Spent` timed beside `Busy` from the same instants, the backend's tok/s log, the adapter's `inference.forward.text` and `generate.exit` tok/s, `report_footprint` twice per turn | +| `PreservedMinds` (saved-state kind) + blocks through saved-state's `ExternalBlob` medium | what outlives a restart, verified on load | the doc's unchecked checksum claim; the block file path helper becomes the medium | +| The engine as a `Lifecycle` node | `prepare` (start, resume minds), `suspend` (preserve minds), `release`; its children are its minds; folded by the kernel (Codex) | `EngineSettle`, the static `SUSPENDS` sender (the driver then exits on disconnect again), `Driver::suspend`'s own report type, the three refusal paths (one `stopping` state), both `StopsOnExit` (one, in continuum-flow) | +| One `Stage` base | kernel `StageRunner` and `continuum-flow::Stage` as one, adapters for the difference (Codex's lane) | two traits | + +**Order (each step deploys on the M5 through the guard, read before the next; each deletes what its row names):** +1. `MindId` and `MindTable` with `Place`: the driver's `parked`, the tier's minds/streams and `Saved`/`Rebind` collapse + into it; `Roles` keeps ids. Gate: the turn and switch rows unchanged in value, the three location owners gone. +2. `EngineConfig` / `EngineGeometry`: one resolution, every context built from it; the contradicting values gone. +3. `Answer` + `Emit` own stops and streams end to end: the backend collector, its sleep-spin and `spawn_blocking` gone; + the media path joins the one decode path (Codex reviews the media chunk descriptor). +4. `Record` from one span: the five other turn-time measurements gone. +5. Lifecycle node + `PreservedMinds` over `ExternalBlob`: on Codex's kernel fold; `EngineSettle` and `SUSPENDS` gone. +6. Prefill and scheduling policy: `turn::plan` and `NextPolicy` gone. + **One base, not two.** `continuum-kernel::runtime::stage` (brain functions: provenance, publication, produced-once artifacts) and `continuum-flow::Stage` (the queue thread) are two halves of one concept. Plan rule 5 applies: one owner below both, adapters for the difference. Until then, the engine's stages are `continuum-flow` stages, and none From 79258fb53197b547985edd14156bb947766d5d66 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 22:36:52 -0600 Subject: [PATCH 48/49] CONTINUUM-ENGINE 4.17 step 1 in detail: the unit is the mind; where she is is which container owns her PersonaUnit (existing, unused) becomes the one value that travels; MindId replaces every persona+epoch pair; Tier takes the blocks it moves and keeps only stream occupancy; deleted: driver Mind/parked, tier Mind/minds, Saved (into the blocks part), Rebind. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 8b59d8dd65..1aaf58f716 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2845,8 +2845,21 @@ row deletes the copies it names; nothing is added beside them. | The engine as a `Lifecycle` node | `prepare` (start, resume minds), `suspend` (preserve minds), `release`; its children are its minds; folded by the kernel (Codex) | `EngineSettle`, the static `SUSPENDS` sender (the driver then exits on disconnect again), `Driver::suspend`'s own report type, the three refusal paths (one `stopping` state), both `StopsOnExit` (one, in continuum-flow) | | One `Stage` base | kernel `StageRunner` and `continuum-flow::Stage` as one, adapters for the difference (Codex's lane) | two traits | +**Step 1 in detail: the unit is the mind, and where she is is which container owns her.** `PersonaUnit` +(`persona/unit.rs`, "her five parts as one value; a move is whole by type") already exists and is unused; it becomes the +one value that travels: `blocks` (the native blocks, with whether they were saved from a stream), `tokens` (her +history), `genome` (her genes and their signature), `learning`, `decode` (her marks' checkpoints). Her place is not a +field kept in sync: she is in the warm table, or in `Roles` as next, active or retiring, or on disk (`PreservedMinds`). +- `MindId { persona, epoch }` replaces every persona+epoch pair: `FenceTag { mind, direction }`, + `Execute::submit(mind, ..)`, `checkpoint`/`rewind(mind, ..)`, `TierRefusal.mind`. +- `Tier` gets `type Blocks` and `begin(mind, &mut Blocks, direction)`: it moves the blocks it is handed and keeps only + which stream holds which `MindId` (context occupancy, which is its own state). `Roles` gains `retiring_mut` so the + engine hands the retiring unit's blocks to the copy-out. +- Deleted: the driver's `Mind` and `parked` (now the warm table of units), the tier's `Mind`, `minds` map, `Saved` (moves + into the blocks part) and `Rebind` (diagnostic only; the example measures from the blocks part). + **Order (each step deploys on the M5 through the guard, read before the next; each deletes what its row names):** -1. `MindId` and `MindTable` with `Place`: the driver's `parked`, the tier's minds/streams and `Saved`/`Rebind` collapse +1. `MindId` and the unit-as-mind: the driver's `parked`, the tier's minds/streams and `Saved`/`Rebind` collapse into it; `Roles` keeps ids. Gate: the turn and switch rows unchanged in value, the three location owners gone. 2. `EngineConfig` / `EngineGeometry`: one resolution, every context built from it; the contradicting values gone. 3. `Answer` + `Emit` own stops and streams end to end: the backend collector, its sleep-spin and `spawn_blocking` gone; From 4a79edbd4793ffc9c51cb9d48a0827767e1426df Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 23:02:04 -0600 Subject: [PATCH 49/49] CONTINUUM-ENGINE 4.17: step 1 landed (68d8bea7cf, M5 receipts); the grid as one more tier, with Codex's delayed-completion replay Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- docs/architecture/CONTINUUM-ENGINE.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 1aaf58f716..d09504fc97 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -2858,6 +2858,23 @@ field kept in sync: she is in the warm table, or in `Roles` as next, active or r - Deleted: the driver's `Mind` and `parked` (now the warm table of units), the tier's `Mind`, `minds` map, `Saved` (moves into the blocks part) and `Rebind` (diagnostic only; the example measures from the blocks part). +*Landed: 68d8bea7cf (2026-11-19). On the M5 through the guard, 04:56-05:01Z: 27 generate calls, 0 inference +failures, 6 resident acts, 0 llama-servers.* The tier's `minds` map and its `Mind` are gone, along with the driver's +`Mind` (now `PersonaUnit`), `PersonaEngine::forget` and `Tier::release`. `Saved` +moved into `Blocks`. One departure from the plan: `Rebind` stays as the tier's report of how the last bind met her +blocks, because the example's switch timings are measured by it. The `parked` table remains as the warm table of units. +There is no `retiring_mut`; `Roles::awaiting_copy_out_mut` hands the engine the unit whose copy-out begins. + +**The grid is one more tier (outlier B for this interface).** A mind is a value her blocks travel with, so moving her +to another node is `begin(mind, &mut blocks, direction)` on a tier whose transfer crosses the network. Its fence lands +when the peer has her blocks, and a refusal returns her whole, like a move between two streams on one context. +Grid compute is then the sum of each node's single-decoder engine. Before step 2 fixes the tier's shape, the grid +tier gets the replay Codex asked for (2026-11-19 04:51Z): the peer accepts her unit, its ACK is lost, the sender +retries, and the old completion arrives after the stream was reused. The two nodes must agree on one owner of her +decode. Pending evidence keeps her native bytes in custody, and a byte stream received alone never grants a second +decode authority. The replay tests that the fence and transfer identify her, whether or not two copies of her unit +could coexist. + **Order (each step deploys on the M5 through the guard, read before the next; each deletes what its row names):** 1. `MindId` and the unit-as-mind: the driver's `parked`, the tier's minds/streams and `Saved`/`Rebind` collapse into it; `Roles` keeps ids. Gate: the turn and switch rows unchanged in value, the three location owners gone.