From c20fd889871c8edd3db333331a0dc7fb6532a51e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 13:58:09 -0600 Subject: [PATCH 01/20] server: --cache-ram is the ONE host budget of the prompt cache and every slot's checkpoints (CONTINUUM-ENGINE 4.7.6 step 1) The M5, 2026-11-16 19:53Z: the engine (up 2h58m, 4 residents, --cache-ram 9494, --ctx-checkpoints 32, --parallel 5) held 16.1 GB SWAPPED (vmmap: resident 33.2G, swapped 16.1G; system swap 15.0 of 15.4 GB) and decode ran at a median 1.3 tok/s over its last 80 acts (par ~56): two holders sized apart, nothing bounding their sum (the log: 89-103 MiB checkpoints, stores full; cache entries up to 2.35 GB, 224 cache evictions in 3h). - --cache-ram N (MiB, > 0) bounds the prompt cache AND every slot's checkpoints together. - Checkpoints are charged first (they serve the minds in the slots): a checkpoint is quoted before it is copied (llama_state_seq_get_size_ext, target + draft parts), and the slot holding the most checkpoint bytes gives up its least valuable one (checkpoint_to_evict keeps her head) until it fits; one larger than the whole budget is not made. - The prompt cache holds the rest: its limit is the budget less the checkpoint bytes, applied after every checkpoint and before every cache save (the cache then evicts down to it). - -1 (no limit) and 0 (disabled) behave as before. Step 1 of 4.7.6: the accounting bound, no new flag (the core's existing --cache-ram figure is the grant until the one-pool ABI replaces both sizers with Codex's core change). The arena (4.7.6 revision) follows. Receipt (qwen35-0.8b, M5, --cache-ram 150 --ctx-checkpoints 32 --parallel 4, 4 slots x 3 rounds of growing prompts): "host budget (prompt cache + checkpoints, all slots): 150 MiB"; 8 budget evictions of 19.3 MiB checkpoints; 0 warnings. The real-persona read is the M5 deploy. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context.cpp | 86 +++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 15831cececbc..8df6835705f7 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1567,6 +1567,14 @@ struct server_context_impl { SRV_TRC("%s", "use `--cache-ram 0` to disable the prompt cache\n"); prompt_cache = std::make_unique(params_base.cache_ram_mib, n_ctx); + // Continuum fork (CONTINUUM-ENGINE 4.7.6, step 1): --cache-ram is the ONE host budget of the prompt + // cache AND every slot's checkpoints. They were sized apart and nothing held their sum: on the M5 + // (2026-11-16) a 9.5 GB cache plus up to 32 x ~100 MB checkpoints x 5 slots swapped 16 GB out of the + // engine and decode fell to 1.3 tok/s (par ~56). + if (params_base.cache_ram_mib > 0) { + host_budget = 1024ull * 1024ull * (size_t) params_base.cache_ram_mib; + SRV_INF("host budget (prompt cache + checkpoints, all slots): %d MiB\n", params_base.cache_ram_mib); + } } else { SRV_TRC("%s", "prompt cache is disabled - use `--cache-ram N` to enable it\n"); } @@ -1861,6 +1869,7 @@ struct server_context_impl { const int64_t t_start = ggml_time_us(); + fit_prompt_cache_to_budget(); // its share of the one host budget, before it takes a new entry ret->prompt_save(*prompt_cache); const auto task_lora = task.params.lora.empty() ? params_base.lora_adapters @@ -2601,6 +2610,68 @@ struct server_context_impl { } } + // ---- the one host budget (CONTINUUM-ENGINE 4.7.6, step 1) ------------------------------------------ + // 0: no budget (--cache-ram -1 or 0). Checkpoints are charged first (they serve the minds in the slots); + // the prompt cache holds what is left and evicts down to it. + size_t host_budget = 0; + + size_t checkpoint_bytes() const { + size_t b = 0; + for (const auto & s : slots) { + for (const auto & c : s.prompt.checkpoints) { + b += c.size(); + } + } + return b; + } + + // The prompt cache's share: the budget less every checkpoint (1 byte, not 0, when none is left: the + // cache reads 0 as "no limit"). + void fit_prompt_cache_to_budget() { + if (!prompt_cache || host_budget == 0) { + return; + } + const size_t ck = checkpoint_bytes(); + prompt_cache->limit_size = host_budget > ck ? host_budget - ck : 1; + prompt_cache->update(); + } + + // Room for a checkpoint of `bytes` under the budget: the slot holding the most checkpoint bytes gives up its + // least valuable one (checkpoint_to_evict keeps her head while anything else is left), until it fits. False: + // it cannot fit even with every checkpoint gone (larger than the budget); the caller makes none. + bool make_room_for_checkpoint(size_t bytes) { + if (host_budget == 0) { + return true; + } + if (bytes > host_budget) { + return false; + } + size_t held = checkpoint_bytes(); + while (held + bytes > host_budget) { + server_slot * from = nullptr; + size_t most = 0; + for (auto & s : slots) { + size_t b = 0; + for (const auto & c : s.prompt.checkpoints) { + b += c.size(); + } + if (b > most) { + most = b; + from = &s; + } + } + if (from == nullptr) { + return false; + } + auto victim = checkpoint_to_evict(from->prompt.checkpoints, from->prompt.view_end); + SLT_WRN(*from, "host budget: erasing a checkpoint (n_tokens = %" PRId64 ", %.3f MiB) for a new one of %.3f MiB\n", + victim->n_tokens, (float) victim->size() / 1024 / 1024, (float) bytes / 1024 / 1024); + held -= victim->size(); + from->prompt.checkpoints.erase(victim); + } + return true; + } + // n_tokens_cur: the number of tokens added to the batch for the current slot void create_checkpoint(server_slot & slot, const int64_t n_tokens_cur, llama_pos pos_min, llama_pos pos_max) { const int id_task = slot.task->id; @@ -2633,6 +2704,19 @@ struct server_context_impl { slot.prompt.checkpoints.erase(victim); } + // under the one host budget: quote the copy before making it (its peak), and make room first + { + size_t quote = llama_state_seq_get_size_ext(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + if (ctx_dft && ctx_dft_seq_rm_type != COMMON_CONTEXT_SEQ_RM_TYPE_PART) { + quote += llama_state_seq_get_size_ext(ctx_dft, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + } + if (!make_room_for_checkpoint(quote)) { + SLT_WRN(slot, "host budget: a checkpoint of %.3f MiB is larger than the whole budget; none is made\n", + (float) quote / 1024 / 1024); + return; + } + } + // the copy is made aside and kept only once complete common_prompt_checkpoint cur; @@ -2660,6 +2744,8 @@ struct server_context_impl { it.n_tokens, (float) it.size() / 1024 / 1024); }); + fit_prompt_cache_to_budget(); // the cache yields what the checkpoints now hold + SLT_TRC(slot, "created context checkpoint %d of %d (pos_min = %d, pos_max = %d, n_tokens = %" PRId64 ", size = %.3f MiB)\n", (int) slot.prompt.checkpoints.size(), params_base.n_ctx_checkpoints, kept.pos_min, From 79a63b3106cfa26c94dac507c62c338c099750af Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 14:21:50 -0600 Subject: [PATCH 02/20] server: a mind switch is a sequence move, in milliseconds, through the pool and flash; never a serialization, a drop or a truncation (Joel: "almost zero cost to context switch") The M5, 2026-11-16: a mind leaving a lane was serialized into the size-capped prompt cache (up to 2.35 GB per switch, 224 evictions in 3h) and DROPPED when it did not fit (10 "exceeds cache size limit, skipping", 8.7 GB); the arriving mind resumed from an older checkpoint and re-prefilled (one switch: 102k tokens discarded, 59k redone). Every mind the request names ("page": the core's PageKey::Mind, 128 bits, parsed once at the JSON edge) has one home: a lane (decoding); PARKED, a sequence of the unified KV pool (seq_cp + seq_rm: attention cells re-tagged, the recurrent state moved by id, target and draft); or FLASH (her sequence copied out of the pool, a memcpy inside unified memory, her cells freed at once, the file written by the page-IO worker off the decode thread). - A named request on a lane holding another mind parks her (or, the pool out of parked ids, sends the coldest parked mind to flash first, or her straight from the lane) and moves the arriving mind in from where she is: parked (a move) or flash (her file mapped and inserted; the pool full, the coldest parked mind goes down first, then the insert is tried again; she is never dropped: on failure her file and record stay). - The decode's "no free space in the KV cache" sends the coldest parked mind to flash (was: purge an idle slot, i.e. truncate a mind); an idle lane's named mind goes to flash whole, never purged. - Content no named mind owns (a core page restore, scratch) is adopted by the arriving mind, never cleared: the prompt's prefix match keeps what is hers. Erase and page restore reset the lane's mind. - --minds N (the core's resident count): the context's sequence capacity is lanes + N; the parked ids are what the context reports (llama_n_seq_max), never assumed; output rows cover every sequence. --minds needs --kv-unified and --slot-save-path (typed refusal to start otherwise). - The prompt cache is off the switch path for named requests. Receipts (qwen35-0.8b hybrid, M5, --parallel 2 --kv-unified --minds 3, three minds of ~3.3k tokens rotating through one lane, 3 rounds): - pool holds all three (-c 16384): switch out 0.16-0.20 ms, in (parked) 0.16-0.18 ms; every return cache_n 3300 of 3304 (4 tokens prefilled). - pool holds two (-c 8192): coldest to flash 58.1 MiB copied out in 1.7-2.9 ms; back from flash inserted in 5.9-8.0 ms; whole switch 6.7-8.8 ms; every return cache_n 3300 of 3304; nothing purged, nothing lost. Next: prefetch the next mind from flash into a free parked sequence while others decode (the core names who is next), so her switch is the 0.2 ms move. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- common/arg.cpp | 11 ++ common/common.cpp | 3 +- common/common.h | 1 + common/speculative.cpp | 2 +- tools/server/CMakeLists.txt | 3 + tools/server/server-context-minds.inc | 266 ++++++++++++++++++++++++++ tools/server/server-context-page.inc | 1 + tools/server/server-context.cpp | 47 ++++- tools/server/server-mapped-file.cpp | 80 ++++++++ tools/server/server-mapped-file.h | 28 +++ tools/server/server-mind.h | 50 +++++ tools/server/server-task.h | 3 + 12 files changed, 492 insertions(+), 3 deletions(-) create mode 100644 tools/server/server-context-minds.inc create mode 100644 tools/server/server-mapped-file.cpp create mode 100644 tools/server/server-mapped-file.h create mode 100644 tools/server/server-mind.h diff --git a/common/arg.cpp b/common/arg.cpp index 4353464d2847..95cfa4bfaf06 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -2544,6 +2544,17 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.n_parallel = value; } ).set_env("LLAMA_ARG_N_PARALLEL").set_examples({LLAMA_EXAMPLE_SERVER})); + add_opt(common_arg( + {"--minds"}, "N", + "continuum: minds the engine keeps resident beside its lanes, each as its own parked sequence of the unified " + "KV pool (a mind switch is a sequence move, never a serialization); the core's resident count, 0 = off", + [](common_params & params, int value) { + if (value < 0) { + throw std::invalid_argument("error: --minds must be >= 0\n"); + } + params.n_minds = value; + } + ).set_env("LLAMA_ARG_MINDS").set_examples({LLAMA_EXAMPLE_SERVER})); } else { add_opt(common_arg( {"-np", "--parallel"}, "N", diff --git a/common/common.cpp b/common/common.cpp index 09fe1b77e3d7..eccd8f0506b8 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1726,7 +1726,8 @@ struct llama_context_params common_context_params_to_llama(const common_params & auto cparams = llama_context_default_params(); cparams.n_ctx = params.n_ctx; - cparams.n_seq_max = params.n_parallel; + // continuum: every resident mind keeps its own sequence (lanes + parked minds) in the unified pool + cparams.n_seq_max = params.n_parallel + std::max(0, params.n_minds); cparams.n_rs_seq = params.speculative.need_n_rs_seq(); cparams.n_outputs_max = std::max(params.n_outputs_max, 0); cparams.n_outputs_max_per_seq = std::max(params.n_outputs_max_per_seq, 0); diff --git a/common/common.h b/common/common.h index f57bafb83295..8a3ffd768e18 100644 --- a/common/common.h +++ b/common/common.h @@ -446,6 +446,7 @@ struct common_params { int32_t n_keep = 0; // number of tokens to keep from initial prompt int32_t n_chunks = -1; // max number of chunks to process (-1 = unlimited) int32_t n_parallel = 1; // number of parallel sequences to decode + int32_t n_minds = 0; // continuum: minds kept resident beside the lanes (parked sequences); the core's count int32_t n_sequences = 1; // number of sequences to decode int32_t n_outputs_max = 0; // max outputs in a batch (0 = n_batch) int32_t n_outputs_max_per_seq = 1; // max outputs per sequence diff --git a/common/speculative.cpp b/common/speculative.cpp index 4b67bbb88599..5de770c9c3a5 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -2343,7 +2343,7 @@ common_params common_base_params_to_speculative(const common_params & params) { result.cache_type_k = params_spec.cache_type_k; result.cache_type_v = params_spec.cache_type_v; - result.n_outputs_max = params.n_parallel; + result.n_outputs_max = params.n_parallel + std::max(0, params.n_minds); // one row per sequence, parked minds included result.n_outputs_max_per_seq = 1; // dflash/dspark decode the whole noise block in a single pass and sample every block position on the backend diff --git a/tools/server/CMakeLists.txt b/tools/server/CMakeLists.txt index 67fb03964d7c..3a409e4f09f9 100644 --- a/tools/server/CMakeLists.txt +++ b/tools/server/CMakeLists.txt @@ -14,6 +14,9 @@ add_library(${TARGET} STATIC server-common.cpp server-common.h server-context.cpp + server-mapped-file.cpp + server-mapped-file.h + server-mind.h server-train.cpp server-context.h server-stream.cpp diff --git a/tools/server/server-context-minds.inc b/tools/server/server-context-minds.inc new file mode 100644 index 000000000000..6fa6792b70c9 --- /dev/null +++ b/tools/server/server-context-minds.inc @@ -0,0 +1,266 @@ +// Methods of server_context_impl: resident minds and the switch between them (server-mind.h). +// +// Every mind the core names has exactly one home: +// lane her sequence is a slot's (she decodes); +// parked her sequence is one of the pool's parked ids (unified memory: on an M5 the same physical memory the +// GPU reads; nothing copied, her attention cells re-tagged and her recurrent state moved by id); +// flash her sequence was copied out of the pool (a memcpy inside unified memory), its cells freed at once, +// and the bytes written to her page file by the page-IO worker, off the decode thread. +// A switch moves her between homes; it never serializes her into a cache, never drops her, never truncates her. +// The pool runs out of CELLS, not of minds: when a decode finds no room, the coldest parked mind goes to flash +// (was: the idle slot's mind was purged). A mind on flash comes back by mapping her file and inserting it. + + struct resident_mind { + mind_page page; + server_prompt prompt; // her tokens, checkpoints and view end (host bookkeeping) + std::vector lora; + uint64_t last_use = 0; + int32_t seq = -1; // parked: the pool sequence id; flash: -1 + std::string file; // flash: her page file + bool writing = false; // flash: the page-IO worker has not landed it yet + std::shared_ptr> written; // 0 pending, 1 landed, -1 failed + }; + + std::vector park_free; // free parked sequence ids (sized once at load) + std::vector minds; // parked and flashed minds (reserved once at load) + uint64_t mind_clock = 0; + + // At load: the parked ids are what the context reports beyond the lanes (llama_n_seq_max), never assumed. + bool minds_init() { + const int32_t n_seq = (int32_t) llama_n_seq_max(ctx_tgt); + const int32_t n_lane = params_base.n_parallel; + if (params_base.n_minds <= 0) { + return true; + } + if (!params_base.kv_unified) { + SRV_ERR("%s", "--minds needs --kv-unified: a parked mind shares the pool's cells by sequence id\n"); + return false; + } + if (params_base.slot_save_path.empty()) { + SRV_ERR("%s", "--minds needs --slot-save-path: a mind the pool cannot hold goes to flash, never dropped\n"); + return false; + } + for (int32_t s = n_seq - 1; s >= n_lane; --s) { + park_free.push_back(s); + } + minds.reserve((size_t) params_base.n_minds * 2); + SRV_INF("resident minds: %d lanes, %zu parked sequence ids (context reports %d), flash at %s\n", + n_lane, park_free.size(), n_seq, params_base.slot_save_path.c_str()); + return true; + } + + bool minds_on() const { return !park_free.empty() || !minds.empty(); } + + resident_mind * find_mind(mind_page page) { + for (auto & m : minds) { + if (m.page == page) { + return &m; + } + } + return nullptr; + } + + void seq_move(llama_seq_id from, llama_seq_id to) { + llama_memory_seq_rm(llama_get_memory(ctx_tgt), to, -1, -1); + llama_memory_seq_cp(llama_get_memory(ctx_tgt), from, to, -1, -1); + llama_memory_seq_rm(llama_get_memory(ctx_tgt), from, -1, -1); + if (ctx_dft) { + llama_memory_seq_rm(llama_get_memory(ctx_dft), to, -1, -1); + llama_memory_seq_cp(llama_get_memory(ctx_dft), from, to, -1, -1); + llama_memory_seq_rm(llama_get_memory(ctx_dft), from, -1, -1); + } + } + + std::string mind_file(mind_page page) const { + char name[64]; + std::snprintf(name, sizeof(name), "mind-%016llx%016llx.bin", (unsigned long long) page.hi, (unsigned long long) page.lo); + return params_base.slot_save_path + name; + } + + // The coldest parked mind leaves the pool for flash. False: nothing is parked. + bool flash_coldest() { + resident_mind * cold = nullptr; + for (auto & m : minds) { + if (m.seq >= 0 && (cold == nullptr || m.last_use < cold->last_use)) { + cold = &m; + } + } + if (cold == nullptr) { + return false; + } + const llama_seq_id seq = cold->seq; + if (!flash_out(*cold, seq)) { + return false; + } + park_free.push_back(seq); + return true; + } + + // Mind `m`'s state in sequence `seq` leaves the pool for flash: copied out (unified memory, a memcpy), the + // sequence's cells freed now, the bytes written by the page-IO worker off the decode thread. + bool flash_out(resident_mind & m, llama_seq_id seq) { + resident_mind * cold = &m; + const int64_t t0 = ggml_time_us(); + auto bytes = std::make_shared>(); + const size_t n_tgt = llama_state_seq_get_size_ext(ctx_tgt, seq, LLAMA_STATE_SEQ_FLAGS_NONE); + const size_t n_dft = ctx_dft ? llama_state_seq_get_size_ext(ctx_dft, seq, LLAMA_STATE_SEQ_FLAGS_NONE) : 0; + bytes->resize(2 * sizeof(uint64_t) + n_tgt + n_dft); + uint8_t * w = bytes->data(); + const uint64_t h[2] = { n_tgt, n_dft }; + std::memcpy(w, h, sizeof(h)); + w += sizeof(h); + if (llama_state_seq_get_data_ext(ctx_tgt, w, n_tgt, seq, LLAMA_STATE_SEQ_FLAGS_NONE) != n_tgt || + (ctx_dft && llama_state_seq_get_data_ext(ctx_dft, w + n_tgt, n_dft, seq, LLAMA_STATE_SEQ_FLAGS_NONE) != n_dft)) { + SRV_ERR("mind %016llx: her state could not be copied out of the pool; she stays where she is\n", (unsigned long long) cold->page.hi); + return false; + } + const int64_t t_copy = ggml_time_us() - t0; + llama_memory_seq_rm(llama_get_memory(ctx_tgt), seq, -1, -1); + if (ctx_dft) { + llama_memory_seq_rm(llama_get_memory(ctx_dft), seq, -1, -1); + } + cold->seq = -1; + cold->file = mind_file(cold->page); + cold->writing = true; + cold->written = std::make_shared>(0); + const std::string path = cold->file; + auto done = cold->written; + page_io->submit(path, [path, bytes, done] { + FILE * f = std::fopen(path.c_str(), "wb"); + bool ok = f != nullptr && std::fwrite(bytes->data(), 1, bytes->size(), f) == bytes->size(); + ok = (f != nullptr && std::fclose(f) == 0) && ok; + done->store(ok ? 1 : -1, std::memory_order_release); + }); + SRV_INF("mind %016llx%016llx to flash: %.1f MiB copied out of the pool in %.2f ms, cells freed; written off the decode thread\n", + (unsigned long long) cold->page.hi, (unsigned long long) cold->page.lo, + bytes->size() / (1024.0 * 1024.0), t_copy / 1000.0); + return true; + } + + // Her flash page back into `seq`: the file is mapped and inserted directly (no read into a buffer first). + // A write still in flight is waited for here (it is her own bytes; the page-IO worker is landing them). + bool flash_insert(resident_mind & m, llama_seq_id seq) { + if (m.writing) { + while (m.written->load(std::memory_order_acquire) == 0) { + std::this_thread::yield(); + } + m.writing = false; + if (m.written->load() < 0) { + SRV_ERR("mind %016llx: her flash page failed to write; she starts cold\n", (unsigned long long) m.page.hi); + return false; + } + } + const int64_t t0 = ggml_time_us(); + server_mapped_file map(m.file); + if (!map.ok() || map.size() < 2 * sizeof(uint64_t)) { + return false; + } + uint64_t h[2]; + std::memcpy(h, map.data(), sizeof(h)); + if (map.size() != 2 * sizeof(uint64_t) + h[0] + h[1]) { + return false; + } + const uint8_t * r = map.data() + sizeof(h); + // her cells come from the pool: when it is full, the coldest parked mind goes down to flash first, and the + // insert is tried again (a level above makes room for the level below, never a drop) + bool ok = false; + while (true) { + llama_memory_seq_rm(llama_get_memory(ctx_tgt), seq, -1, -1); + ok = llama_state_seq_set_data_ext(ctx_tgt, r, h[0], seq, LLAMA_STATE_SEQ_FLAGS_NONE) == h[0]; + if (ok || !flash_coldest()) { + break; + } + } + while (ok && ctx_dft && h[1] > 0) { + llama_memory_seq_rm(llama_get_memory(ctx_dft), seq, -1, -1); + ok = llama_state_seq_set_data_ext(ctx_dft, r + h[0], h[1], seq, LLAMA_STATE_SEQ_FLAGS_NONE) == h[1]; + if (ok || !flash_coldest()) { + break; + } + } + if (!ok) { + llama_memory_seq_rm(llama_get_memory(ctx_tgt), seq, -1, -1); + if (ctx_dft) { + llama_memory_seq_rm(llama_get_memory(ctx_dft), seq, -1, -1); + } + SRV_WRN("mind %016llx%016llx: the pool cannot hold her even with every other mind on flash; she stays on flash\n", + (unsigned long long) m.page.hi, (unsigned long long) m.page.lo); + return false; // her file and record are kept: she is still on flash, never lost + } + SRV_INF("mind %016llx%016llx from flash: %.1f MiB inserted in %.2f ms\n", (unsigned long long) m.page.hi, + (unsigned long long) m.page.lo, map.size() / (1024.0 * 1024.0), (ggml_time_us() - t0) / 1000.0); + std::error_code ec; + std::filesystem::remove(m.file, ec); + m.file.clear(); + return ok; + } + + // `slot` serves `page` next. The mind it holds (if any) is parked; hers comes back from where she is. + void mind_switch(server_slot & slot, mind_page page) { + if (slot.page == page) { + return; + } + const int64_t t0 = ggml_time_us(); + // the lane's mind leaves, whole + if (slot.page.valid() && slot.prompt.n_tokens() > 0) { + resident_mind m; + m.page = slot.page; + m.lora = slot.lora; + m.last_use = ++mind_clock; + if (park_free.empty()) { + flash_coldest(); // the pool's coldest parked mind makes room, if one is parked + } + if (!park_free.empty()) { + m.seq = park_free.back(); + park_free.pop_back(); + seq_move(slot.id, m.seq); + } else if (!flash_out(m, slot.id)) { + SLT_ERR(slot, "%s", "the leaving mind could be neither parked nor copied out; she is kept on this lane\n"); + return; // her state is intact on the lane; the arriving request waits for another lane + } + m.prompt = std::move(slot.prompt); + slot.prompt.clear(); + minds.push_back(std::move(m)); + } else if (!slot.page.valid()) { + // content no named mind owns (a core page restore, or scratch): adopted, never cleared; the prompt's + // prefix match keeps what is hers and re-prefills only what diverges + } + const int64_t t_out = ggml_time_us() - t0; + // hers comes in from where she is + const char * from = "new"; + for (size_t i = 0; i < minds.size(); ++i) { + if (minds[i].page != page) { + continue; + } + resident_mind & m = minds[i]; + bool ok; + if (m.seq >= 0) { + seq_move(m.seq, slot.id); + park_free.push_back(m.seq); + from = "parked"; + ok = true; + } else { + from = "flash"; + ok = flash_insert(m, slot.id); + } + if (!ok) { + // she stays where she is (on flash, record and file intact); the lane starts this request empty + slot.prompt_clear(); + from = "flash, pool full"; + break; + } + slot.prompt = std::move(m.prompt); + slot.lora = std::move(m.lora); + // the record may move under flash_coldest() above: find her again by page before erasing + for (size_t j = 0; j < minds.size(); ++j) { + if (minds[j].page == page) { + minds.erase(minds.begin() + (long) j); + break; + } + } + break; + } + slot.page = page; + SLT_INF(slot, "mind switch: out %.3f ms, in (%s) %.3f ms, she holds %d tokens\n", t_out / 1000.0, from, + (ggml_time_us() - t0 - t_out) / 1000.0, slot.prompt.n_tokens()); + } diff --git a/tools/server/server-context-page.inc b/tools/server/server-context-page.inc index 85de81265f67..5672a599217d 100644 --- a/tools/server/server-context-page.inc +++ b/tools/server/server-context-page.inc @@ -681,6 +681,7 @@ return; } std::vector().swap(job.body); + slot->page = mind_page{}; // a core page restore: the arriving request's mind adopts it (server-context-minds.inc) // The draft's KV comes back with the page (#79) when it covers exactly these tokens; otherwise the // draft sequence is cleared, never left holding another occupant's KV at these positions: it then diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 15831cececbc..524f29bbebdb 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -2,6 +2,9 @@ #include "server-context.h" #include "server-checkpoint-policy.h" #include "server-view-end.h" +#include "server-mapped-file.h" +#include +#include #include "../../src/llama-ext.h" #include "server-train.h" #include "server-adapter-file.h" @@ -319,6 +322,9 @@ struct server_slot { server_prompt prompt; + // Continuum fork: the mind whose sequence this lane holds (server-context-minds.inc); invalid: anonymous + mind_page page; + bool prompt_save(server_prompt_cache & prompt_cache) const { if (prompt.tokens.size() == 0) { return false; @@ -1244,7 +1250,9 @@ struct server_context_impl { params_base = params; const auto output_limits = server_output_limits(params_base); - params_base.n_outputs_max = output_limits.total; + // the context reserves at least one output row per sequence: parked minds are sequences (they produce no + // outputs, but the reserve counts them) + params_base.n_outputs_max = std::max(output_limits.total, params_base.n_parallel + std::max(0, params_base.n_minds)); params_base.n_outputs_max_per_seq = output_limits.per_seq; const bool has_mmproj = !params.mmproj.path.empty(); @@ -1463,6 +1471,9 @@ struct server_context_impl { if (!page_io) { page_io = std::make_unique((size_t) params_base.n_parallel); } + if (!minds_init()) { + return false; + } // try speculative decoding if (ctx_tgt_seq_rm_type != COMMON_CONTEXT_SEQ_RM_TYPE_NO) { @@ -1850,6 +1861,15 @@ struct server_context_impl { } } + // a named mind switches by sequence moves (server-context-minds.inc), never through the prompt cache + if (ret && minds_on() && task.params.page.valid()) { + mind_switch(*ret, task.params.page); + if (ret->page != task.params.page) { + return nullptr; // the lane's mind could not leave intact: this request waits for a lane + } + update_cache = false; + } + if (ret) { update_cache = update_cache && prompt_cache; @@ -1890,6 +1910,28 @@ struct server_context_impl { return res; } + // resident minds: the pool's coldest parked mind goes to flash, whole; an idle lane's mind is never purged + if (minds_on()) { + if (flash_coldest()) { + return true; + } + for (auto & slot : slots) { + if (!slot.is_processing() && slot.page.valid() && slot.prompt.n_tokens() > 0) { + resident_mind m; + m.page = slot.page; + m.lora = slot.lora; + m.last_use = ++mind_clock; + if (flash_out(m, slot.id)) { + m.prompt = std::move(slot.prompt); + slot.prompt.clear(); + slot.page = mind_page{}; + minds.push_back(std::move(m)); + return true; + } + } + } + } + for (auto & slot : slots) { if (slot.is_processing()) { continue; @@ -2309,6 +2351,7 @@ struct server_context_impl { #include "server-context-learn.inc" #include "server-context-learn-checkpoint.inc" #include "server-context-page.inc" +#include "server-context-minds.inc" void send_final_response(server_slot & slot) { if (slot.task->params.learn_only) { @@ -2902,6 +2945,7 @@ struct server_context_impl { const size_t n_erased = slot->prompt.tokens.size(); slot->prompt_clear(); + slot->page = mind_page{}; // erased: no mind's sequence is here now page_slot_reassigned(*slot); // a restore buffered for this slot is dropped, never applied over it auto res = std::make_unique(); @@ -4993,6 +5037,7 @@ std::unique_ptr server_routes::handle_completions_impl( } task.id_slot = json_value(data, "id_slot", -1); + task.params.page = mind_page_parse(json_value(data, "page", std::string())); // text only at this edge sse_ping_interval = task.params.sse_ping_interval; // OAI-compat diff --git a/tools/server/server-mapped-file.cpp b/tools/server/server-mapped-file.cpp new file mode 100644 index 000000000000..19ca94eaca4e --- /dev/null +++ b/tools/server/server-mapped-file.cpp @@ -0,0 +1,80 @@ +#include "server-mapped-file.h" + +#if defined(_WIN32) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +server_mapped_file::server_mapped_file(const std::string & path) { + HANDLE f = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr); + if (f == INVALID_HANDLE_VALUE) { + return; + } + LARGE_INTEGER sz; + if (!GetFileSizeEx(f, &sz) || sz.QuadPart == 0) { + CloseHandle(f); + return; + } + HANDLE m = CreateFileMappingA(f, nullptr, PAGE_READONLY, 0, 0, nullptr); + if (m == nullptr) { + CloseHandle(f); + return; + } + void * p = MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0); + if (p == nullptr) { + CloseHandle(m); + CloseHandle(f); + return; + } + data_ = static_cast(p); + size_ = (size_t) sz.QuadPart; + file_ = (intptr_t) f; + map_ = (intptr_t) m; +} + +server_mapped_file::~server_mapped_file() { + if (data_ != nullptr) { + UnmapViewOfFile(data_); + CloseHandle((HANDLE) map_); + CloseHandle((HANDLE) file_); + } +} + +#else +#include +#include +#include +#include + +server_mapped_file::server_mapped_file(const std::string & path) { + const int fd = ::open(path.c_str(), O_RDONLY); + if (fd < 0) { + return; + } + struct stat st; + if (::fstat(fd, &st) != 0 || st.st_size <= 0) { + ::close(fd); + return; + } + void * p = ::mmap(nullptr, (size_t) st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + if (p == MAP_FAILED) { + ::close(fd); + return; + } + ::madvise(p, (size_t) st.st_size, MADV_SEQUENTIAL | MADV_WILLNEED); + data_ = static_cast(p); + size_ = (size_t) st.st_size; + file_ = fd; +} + +server_mapped_file::~server_mapped_file() { + if (data_ != nullptr) { + ::munmap(const_cast(data_), size_); + ::close((int) file_); + } +} +#endif diff --git a/tools/server/server-mapped-file.h b/tools/server/server-mapped-file.h new file mode 100644 index 000000000000..44f721662f13 --- /dev/null +++ b/tools/server/server-mapped-file.h @@ -0,0 +1,28 @@ +#pragma once + +// Continuum fork: a file mapped read-only, so its bytes are inserted straight into a sequence (flash -> unified +// memory at the drive's speed, no read into a buffer first). The OS calls live in server-mapped-file.cpp. + +#include +#include +#include + +class server_mapped_file { +public: + explicit server_mapped_file(const std::string & path); + ~server_mapped_file(); + server_mapped_file(const server_mapped_file &) = delete; + server_mapped_file & operator=(const server_mapped_file &) = delete; + + bool ok() const { return data_ != nullptr; } + const uint8_t * data() const { return data_; } + size_t size() const { return size_; } + +private: + const uint8_t * data_ = nullptr; + size_t size_ = 0; + intptr_t file_ = -1; // a POSIX descriptor or a Windows file HANDLE +#if defined(_WIN32) + intptr_t map_ = -1; // the mapping HANDLE (Windows maps through a second handle) +#endif +}; diff --git a/tools/server/server-mind.h b/tools/server/server-mind.h new file mode 100644 index 000000000000..a4b6b6666d91 --- /dev/null +++ b/tools/server/server-mind.h @@ -0,0 +1,50 @@ +#pragma once + +// Continuum fork: a MIND, named by the request (the core's PageKey::Mind, a 128-bit id), never guessed from her +// tokens. Text exists only at the JSON edge: a request's "page" is parsed here once, into two integers. +// +// Switching minds costs almost nothing (Joel, 2026-11-16: "This is the entire difference between a multi mind +// system and a POS"): a mind leaving a lane is PARKED as a sequence of the unified KV pool (seq_cp + seq_rm: +// attention cells re-tagged, the recurrent state moved by id, nothing serialized), and a mind arriving is moved +// back the same way, continuing at her own end. server-context.cpp holds the parked table (sized once at load +// from the context's sequence capacity) and performs the moves. + +#include +#include + +struct mind_page { + uint64_t hi = 0, lo = 0; + bool valid() const { return hi != 0 || lo != 0; } + bool operator==(const mind_page & o) const { return hi == o.hi && lo == o.lo; } + bool operator!=(const mind_page & o) const { return !(*this == o); } +}; + +// "page": 32 hexadecimal digits, dashes allowed (a UUID). Anything else is no page (the request is anonymous). +inline mind_page mind_page_parse(const std::string & s) { + mind_page p; + int n = 0; + for (char c : s) { + if (c == '-') { + continue; + } + int v; + if (c >= '0' && c <= '9') { + v = c - '0'; + } else if (c >= 'a' && c <= 'f') { + v = c - 'a' + 10; + } else if (c >= 'A' && c <= 'F') { + v = c - 'A' + 10; + } else { + return mind_page{}; + } + if (n < 16) { + p.hi = (p.hi << 4) | (uint64_t) v; + } else if (n < 32) { + p.lo = (p.lo << 4) | (uint64_t) v; + } else { + return mind_page{}; + } + ++n; + } + return n == 32 ? p : mind_page{}; +} diff --git a/tools/server/server-task.h b/tools/server/server-task.h index c757135afcc0..75e88ee1a7f8 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -1,5 +1,6 @@ #pragma once +#include "server-mind.h" #include "common.h" #include "llama.h" @@ -174,6 +175,8 @@ struct task_params { // append-only part of the prompt the caller's next request sends again unchanged. The prompt // is checkpointed exactly there and a saved page keeps that checkpoint. -1 = not given. int32_t view_end_pos = -1; + // Continuum fork: the mind this request is (the core's PageKey::Mind; server-mind.h). Invalid: anonymous. + mind_page page; // Embeddings int32_t embd_normalize = 2; // (-1=none, 0=max absolute int16, 1=taxicab, 2=Euclidean/L2, >2=p-norm) From a8388c4aa52ba78f991a9aa7b792ec77e89b664e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 14:24:53 -0600 Subject: [PATCH 03/20] server: prefetch the next mind from flash into the pool while others decode (POST /minds/prefetch), so her switch is the 0.16 ms move Like a streaming engine loading what the camera needs next: the core names who is next; the engine inserts her flash page into a free parked sequence now (the coldest parked mind going down to flash to make room), between the current mind's decode steps. When her request arrives, the switch is a sequence move. POST /minds/prefetch {"page": ""} -> {success, message: lane | parked | new | flash, no parked id free | flash, pool full (ms)}; a task on the engine thread (SERVER_TASK_TYPE_MIND_PREFETCH), the only owner of the KV. Receipt (qwen35-0.8b hybrid, M5, --parallel 2 --kv-unified --minds 3 -c 8192: the pool holds two of three ~3.3k-token minds; each request's next mind prefetched 150 ms into its decode): prefetch 6.9-10.1 ms each (flash insert 6.1-8.6 ms, the coldest out in 1.8-2.9 ms), all landing during the previous mind's decode; every switch out 0.166-0.177 ms, in (parked) 0.155-0.163 ms; every return cache_n 3300 of 3304, she holds 3327 tokens. Without prefetch the same rotation switched in 6.7-8.8 ms (from flash at the switch). 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context-minds.inc | 35 +++++++++++++++++++++++ tools/server/server-context.cpp | 40 +++++++++++++++++++++++++++ tools/server/server-context.h | 2 ++ tools/server/server-task.h | 1 + tools/server/server.cpp | 2 ++ 5 files changed, 80 insertions(+) diff --git a/tools/server/server-context-minds.inc b/tools/server/server-context-minds.inc index 6fa6792b70c9..46405fe765a8 100644 --- a/tools/server/server-context-minds.inc +++ b/tools/server/server-context-minds.inc @@ -195,6 +195,41 @@ return ok; } + // Ahead of her turn (the core names who is next): a mind on flash is inserted into a free parked sequence + // now, while the others decode, so her switch is the sequence move. Returns where she is afterwards. + const char * mind_prefetch(mind_page page) { + for (const auto & s : slots) { + if (s.page == page) { + return "lane"; + } + } + resident_mind * m = find_mind(page); + if (m == nullptr) { + return "new"; + } + if (m->seq >= 0) { + m->last_use = ++mind_clock; // she is next: the last to be sent down + return "parked"; + } + if (park_free.empty()) { + flash_coldest(); + } + if (park_free.empty()) { + return "flash, no parked id free"; + } + const llama_seq_id seq = park_free.back(); + park_free.pop_back(); + // flash_coldest() may run inside the insert and move records: hold her by page, not by pointer + if (!flash_insert(*find_mind(page), seq)) { + park_free.push_back(seq); + return "flash, pool full"; + } + resident_mind * back = find_mind(page); + back->seq = seq; + back->last_use = ++mind_clock; + return "parked"; + } + // `slot` serves `page` next. The mind it holds (if any) is parked; hers comes back from where she is. void mind_switch(server_slot & slot, mind_page page) { if (slot.page == page) { diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 524f29bbebdb..2313a416a0fc 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -2926,6 +2926,16 @@ struct server_context_impl { { page_io_done(std::move(task)); } break; + case SERVER_TASK_TYPE_MIND_PREFETCH: + { + const int64_t t0 = ggml_time_us(); + const char * where = minds_on() ? mind_prefetch(task.params.page) : "minds off"; + auto res = std::make_unique(); + res->id = task.id; + res->success = std::strcmp(where, "lane") == 0 || std::strcmp(where, "parked") == 0; + res->message = std::string(where) + " (" + std::to_string((ggml_time_us() - t0) / 1000.0) + " ms)"; + queue_results.send(std::move(res)); + } break; case SERVER_TASK_TYPE_SLOT_ERASE: { const int id_slot = task.slot_action.id_slot; @@ -6504,6 +6514,7 @@ void server_routes::init_routes() { res->ok(page_io_snapshot()); return res; }; + this->post_minds_prefetch = [this](const server_http_req & req) { return handle_minds_prefetch(req); }; this->post_learn_grants = [grant_route](const server_http_req & req) { return grant_route(req, "register"); }; this->revoke_learn_grant = [grant_route](const server_http_req & req) { return grant_route(req, "revoke"); }; @@ -6858,6 +6869,35 @@ std::unique_ptr server_routes::handle_slots_restore(const return res; } +// Continuum fork: POST /minds/prefetch {"page": ""}: her state comes from flash into a parked sequence now, +// ahead of her turn (server-context-minds.inc). The reply names where she is. +std::unique_ptr server_routes::handle_minds_prefetch(const server_http_req & req) { + auto res = create_response(); + auto & rd = res->rd; + const json body = req.body.empty() ? json::object() : json::parse(req.body); + { + server_task task(SERVER_TASK_TYPE_MIND_PREFETCH); + task.id = rd.get_new_id(); + task.params.page = mind_page_parse(json_value(body, "page", std::string())); + if (!task.params.page.valid()) { + res->error(format_error_response("page must name a mind (32 hexadecimal digits, a UUID)", ERROR_TYPE_INVALID_REQUEST)); + return res; + } + rd.post_task(std::move(task)); + } + auto result = rd.next(req.should_stop); + if (!result) { + GGML_ASSERT(req.should_stop()); + return res; + } + if (result->is_error()) { + res->error(result->to_json()); + return res; + } + res->ok(result->to_json()); + return res; +} + std::unique_ptr server_routes::handle_slots_erase(const server_http_req & req, int id_slot) { auto res = create_response(); auto & rd = res->rd; diff --git a/tools/server/server-context.h b/tools/server/server-context.h index 78d544aba9e1..0fabe3b530a6 100644 --- a/tools/server/server-context.h +++ b/tools/server/server-context.h @@ -180,6 +180,7 @@ struct server_routes { server_http_context::handler_t get_learn_events; server_http_context::handler_t post_prompt_cache_limit; server_http_context::handler_t get_page_io, post_page_io_budget; // the KV page IO budget (server-page-io.h) + server_http_context::handler_t post_minds_prefetch; // the next mind, from flash into the pool (server-context-minds.inc) server_http_context::handler_t get_train; server_http_context::handler_t post_train; server_http_context::handler_t post_train_cancel; @@ -200,6 +201,7 @@ struct server_routes { std::unique_ptr handle_slots_save(const server_http_req & req, int id_slot, bool size_only); std::unique_ptr handle_slots_restore(const server_http_req & req, int id_slot); std::unique_ptr handle_slots_erase(const server_http_req &, int id_slot); + std::unique_ptr handle_minds_prefetch(const server_http_req &); std::unique_ptr handle_embeddings_impl(const server_http_req & req, task_response_type res_type); std::unique_ptr handle_count_tokens(const llama_vocab * vocab, mtmd_context * mctx, const server_http_req & req, task_response_type res_type); diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 75e88ee1a7f8..47b165e47774 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -60,6 +60,7 @@ enum server_task_type { SERVER_TASK_TYPE_SLOT_SAVE, SERVER_TASK_TYPE_SLOT_RESTORE, SERVER_TASK_TYPE_SLOT_ERASE, + SERVER_TASK_TYPE_MIND_PREFETCH, // Continuum fork: the next mind, from flash into a parked sequence, ahead of her turn SERVER_TASK_TYPE_SLOT_PAGE_IO_DONE, // Continuum fork: a save's or restore's file IO finished on its worker SERVER_TASK_TYPE_SET_LORA, SERVER_TASK_TYPE_LOAD_LORA, diff --git a/tools/server/server.cpp b/tools/server/server.cpp index 7724d41bfa04..9fd8bcf50f5f 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -230,6 +230,7 @@ int llama_server(common_params & params, int argc, char ** argv) { routes.post_prompt_cache_limit = models_routes->proxy_post; routes.get_page_io = models_routes->proxy_get; routes.post_page_io_budget = models_routes->proxy_post; + routes.post_minds_prefetch = models_routes->proxy_post; routes.post_learn_residency = models_routes->proxy_post; routes.release_learn_residency = models_routes->proxy_post; routes.revoke_learn_residency = models_routes->proxy_post; @@ -303,6 +304,7 @@ int llama_server(common_params & params, int argc, char ** argv) { ctx_http.post("/prompt-cache/limit", ex_wrapper(routes.post_prompt_cache_limit)); ctx_http.get ("/page-io", ex_wrapper(routes.get_page_io)); ctx_http.post("/page-io/budget", ex_wrapper(routes.post_page_io_budget)); + ctx_http.post("/minds/prefetch", ex_wrapper(routes.post_minds_prefetch)); ctx_http.post("/learn/grants/revoke", ex_wrapper(routes.revoke_learn_grant)); ctx_http.get ("/train", ex_wrapper(routes.get_train)); ctx_http.post("/train", ex_wrapper(routes.post_train)); From 22ba0d9cab6e1019dd59968a035116e90656046d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 14:30:03 -0600 Subject: [PATCH 04/20] minds: her bytes stay in RAM until her file has landed; insert never waits on the disk; a failed write keeps her in RAM (Codex's review of #139) - flash_out: the record holds her bytes (ram) beside the page-IO worker's write; the worker never owns the last copy. minds_reap (each loop, never waiting) releases the RAM copy once the file landed; a failed write keeps it (she lives in RAM) without retrying every step against a failing disk: her next trip out of a lane writes again. - flash_insert: from RAM while the write is in flight or failed (no spin on the engine thread), else her file mapped; the file is removed on the page-IO worker, ordered after its own write. Receipts (qwen35-0.8b hybrid, M5, --parallel 2 --kv-unified --minds 3 -c 8192, three ~3.3k-token minds x 3 rounds): normal: back from flash 5.0-7.5 ms, every return cache_n 3300/3304. Pages dir read-only (every write fails): every return still cache_n 3300 (back from RAM 3.7-5.6 ms), 7 failed-write lines (one per write, no storm), nothing lost. 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context-minds.inc | 91 ++++++++++++++++++--------- tools/server/server-context.cpp | 3 + 2 files changed, 66 insertions(+), 28 deletions(-) diff --git a/tools/server/server-context-minds.inc b/tools/server/server-context-minds.inc index 46405fe765a8..1927f467fcf7 100644 --- a/tools/server/server-context-minds.inc +++ b/tools/server/server-context-minds.inc @@ -17,7 +17,9 @@ uint64_t last_use = 0; int32_t seq = -1; // parked: the pool sequence id; flash: -1 std::string file; // flash: her page file - bool writing = false; // flash: the page-IO worker has not landed it yet + // her bytes in RAM, held by this record (never by the worker alone) until her file has landed: while the + // write is in flight, or after it failed, she lives here and is inserted from here, never lost + std::shared_ptr> ram; std::shared_ptr> written; // 0 pending, 1 landed, -1 failed }; @@ -121,46 +123,77 @@ } cold->seq = -1; cold->file = mind_file(cold->page); - cold->writing = true; + cold->ram = bytes; // the record holds her bytes until her file has landed cold->written = std::make_shared>(0); - const std::string path = cold->file; - auto done = cold->written; + flash_write(*cold); + SRV_INF("mind %016llx%016llx out of the pool: %.1f MiB copied out in %.2f ms, cells freed; held in RAM until written\n", + (unsigned long long) cold->page.hi, (unsigned long long) cold->page.lo, + bytes->size() / (1024.0 * 1024.0), t_copy / 1000.0); + return true; + } + + // Her bytes to her file on the page-IO worker; the worker shares them, the record keeps them. + void flash_write(resident_mind & m) { + const std::string path = m.file; + auto bytes = m.ram; + auto done = m.written; + done->store(0, std::memory_order_release); page_io->submit(path, [path, bytes, done] { FILE * f = std::fopen(path.c_str(), "wb"); bool ok = f != nullptr && std::fwrite(bytes->data(), 1, bytes->size(), f) == bytes->size(); ok = (f != nullptr && std::fclose(f) == 0) && ok; done->store(ok ? 1 : -1, std::memory_order_release); }); - SRV_INF("mind %016llx%016llx to flash: %.1f MiB copied out of the pool in %.2f ms, cells freed; written off the decode thread\n", - (unsigned long long) cold->page.hi, (unsigned long long) cold->page.lo, - bytes->size() / (1024.0 * 1024.0), t_copy / 1000.0); - return true; } - // Her flash page back into `seq`: the file is mapped and inserted directly (no read into a buffer first). - // A write still in flight is waited for here (it is her own bytes; the page-IO worker is landing them). - bool flash_insert(resident_mind & m, llama_seq_id seq) { - if (m.writing) { - while (m.written->load(std::memory_order_acquire) == 0) { - std::this_thread::yield(); + // Between steps: a landed file releases her RAM copy; a failed write keeps it (she lives in RAM) and is + // written again. Never waits. + void minds_reap() { + for (auto & m : minds) { + if (!m.ram || !m.written) { + continue; } - m.writing = false; - if (m.written->load() < 0) { - SRV_ERR("mind %016llx: her flash page failed to write; she starts cold\n", (unsigned long long) m.page.hi); - return false; + const int st = m.written->load(std::memory_order_acquire); + if (st == 1) { + m.ram.reset(); + } else if (st == -1) { + // she lives in RAM (never lost); the write is not retried every step against a failing disk: her + // next trip out of a lane writes her again + SRV_WRN("mind %016llx%016llx: her flash write failed; she stays in RAM\n", + (unsigned long long) m.page.hi, (unsigned long long) m.page.lo); + m.written.reset(); } } + } + + // Her bytes back into `seq`, from where they are: RAM while her write is in flight or failed (never a wait on + // the disk), else her file mapped and inserted directly (no read into a buffer first). + bool flash_insert(resident_mind & m, llama_seq_id seq) { const int64_t t0 = ggml_time_us(); - server_mapped_file map(m.file); - if (!map.ok() || map.size() < 2 * sizeof(uint64_t)) { + std::unique_ptr map; + auto ram = m.ram; // held for the insert even if the write lands meanwhile + const uint8_t * base = nullptr; + size_t size = 0; + if (ram) { + base = ram->data(); + size = ram->size(); + } else { + map = std::make_unique(m.file); + if (!map->ok()) { + return false; + } + base = map->data(); + size = map->size(); + } + if (size < 2 * sizeof(uint64_t)) { return false; } uint64_t h[2]; - std::memcpy(h, map.data(), sizeof(h)); - if (map.size() != 2 * sizeof(uint64_t) + h[0] + h[1]) { + std::memcpy(h, base, sizeof(h)); + if (size != 2 * sizeof(uint64_t) + h[0] + h[1]) { return false; } - const uint8_t * r = map.data() + sizeof(h); + const uint8_t * r = base + sizeof(h); // her cells come from the pool: when it is full, the coldest parked mind goes down to flash first, and the // insert is tried again (a level above makes room for the level below, never a drop) bool ok = false; @@ -187,12 +220,14 @@ (unsigned long long) m.page.hi, (unsigned long long) m.page.lo); return false; // her file and record are kept: she is still on flash, never lost } - SRV_INF("mind %016llx%016llx from flash: %.1f MiB inserted in %.2f ms\n", (unsigned long long) m.page.hi, - (unsigned long long) m.page.lo, map.size() / (1024.0 * 1024.0), (ggml_time_us() - t0) / 1000.0); - std::error_code ec; - std::filesystem::remove(m.file, ec); + SRV_INF("mind %016llx%016llx back from %s: %.1f MiB inserted in %.2f ms\n", (unsigned long long) m.page.hi, + (unsigned long long) m.page.lo, ram ? "RAM" : "flash", size / (1024.0 * 1024.0), (ggml_time_us() - t0) / 1000.0); + // her file is removed on the page-IO worker, ordered after its own write (it may still be landing) + const std::string path = m.file; + page_io->submit(path, [path] { std::error_code ec; std::filesystem::remove(path, ec); }); m.file.clear(); - return ok; + m.ram.reset(); + return true; } // Ahead of her turn (the core names who is next): a mind on flash is inserted into a free parked sequence diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 2313a416a0fc..022ec5bbefe4 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -3319,6 +3319,9 @@ struct server_context_impl { #endif void update_slots() { + if (minds_on()) { + minds_reap(); // a landed flash write frees her RAM copy; a failed one is written again + } const bool learning_at_start = bool(learning); publish_busy_slots(); struct publish_on_exit { server_context_impl * s; ~publish_on_exit() { s->publish_busy_slots(); } } publish_guard{this}; From 5111d28d978dc0115457f47e1c02d4cb882a3f15 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 14:32:17 -0600 Subject: [PATCH 05/20] minds: every named reply carries the switch receipt (page, where she came from, switch ms, generation), so the core deletes its own page moves only on the engine's word (Codex on #139) timings.mind = {page, from: lane | parked | flash | ram | new | adopted | flash_pool_full, switch_ms, generation}; typed in the slot's stats (enum mind_from, the page as two integers), text only at the JSON edge. Her generation advances each time her state moves (out of a lane, back into one), carried with her record. Receipt (qwen35-0.8b, M5, three minds through a two-mind pool): turn 1 {from new, generation 1}; turn 2 {from flash, switch 5.7-7.8 ms, generation 3, cache_n 3300}. 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-common.cpp | 12 ++++++++++++ tools/server/server-common.h | 10 ++++++++++ tools/server/server-context-minds.inc | 28 ++++++++++++++++++++++----- tools/server/server-context.cpp | 4 +++- 4 files changed, 48 insertions(+), 6 deletions(-) diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index eadc271dc706..69795c0427d4 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -84,6 +84,18 @@ json server_slot_stats::to_json() const { base["draft_n_accepted"] = n_draft_accepted; } + if (mind_hi != 0 || mind_lo != 0) { + static const char * names[] = { "none", "lane", "parked", "flash", "ram", "new", "adopted", "flash_pool_full" }; + char page[33]; + std::snprintf(page, sizeof(page), "%016llx%016llx", (unsigned long long) mind_hi, (unsigned long long) mind_lo); + base["mind"] = { + {"page", page}, + {"from", names[(size_t) mind_came_from]}, + {"switch_ms", mind_switch_us / 1000.0}, + {"generation", mind_generation}, + }; + } + return base; } diff --git a/tools/server/server-common.h b/tools/server/server-common.h index 24bbb7a0bd57..20385cdca65f 100644 --- a/tools/server/server-common.h +++ b/tools/server/server-common.h @@ -362,7 +362,17 @@ json format_response_rerank( // // shared between server_slot and server_task_result_* +// Continuum fork: where the mind a request named came from when she took the lane (server-context-minds.inc) +enum class mind_from : uint8_t { none, lane, parked, flash, ram, fresh, adopted, flash_pool_full }; + struct server_slot_stats { + // the switch receipt (a request that named its mind): her page, where her state came from, how long the + // switch took and her state's generation (it advances each time her state moves) + uint64_t mind_hi = 0, mind_lo = 0; + mind_from mind_came_from = mind_from::none; + int64_t mind_switch_us = 0; + uint64_t mind_generation = 0; + uint64_t n_prompt_cached = 0; uint64_t n_prompt_processed = 0; uint64_t n_gen = 0; diff --git a/tools/server/server-context-minds.inc b/tools/server/server-context-minds.inc index 1927f467fcf7..e75d3bb6c749 100644 --- a/tools/server/server-context-minds.inc +++ b/tools/server/server-context-minds.inc @@ -15,6 +15,7 @@ server_prompt prompt; // her tokens, checkpoints and view end (host bookkeeping) std::vector lora; uint64_t last_use = 0; + uint64_t generation = 0; // advances each time her state moves int32_t seq = -1; // parked: the pool sequence id; flash: -1 std::string file; // flash: her page file // her bytes in RAM, held by this record (never by the worker alone) until her file has landed: while the @@ -267,16 +268,22 @@ // `slot` serves `page` next. The mind it holds (if any) is parked; hers comes back from where she is. void mind_switch(server_slot & slot, mind_page page) { + slot.stats.mind_hi = page.hi; + slot.stats.mind_lo = page.lo; if (slot.page == page) { + slot.stats.mind_came_from = mind_from::lane; + slot.stats.mind_switch_us = 0; + slot.stats.mind_generation = slot.page_generation; return; } const int64_t t0 = ggml_time_us(); // the lane's mind leaves, whole if (slot.page.valid() && slot.prompt.n_tokens() > 0) { resident_mind m; - m.page = slot.page; - m.lora = slot.lora; - m.last_use = ++mind_clock; + m.page = slot.page; + m.lora = slot.lora; + m.last_use = ++mind_clock; + m.generation = slot.page_generation + 1; if (park_free.empty()) { flash_coldest(); // the pool's coldest parked mind makes room, if one is parked } @@ -298,6 +305,8 @@ const int64_t t_out = ggml_time_us() - t0; // hers comes in from where she is const char * from = "new"; + mind_from kind = slot.page.valid() || slot.prompt.n_tokens() == 0 ? mind_from::fresh : mind_from::adopted; + uint64_t generation = 1; for (size_t i = 0; i < minds.size(); ++i) { if (minds[i].page != page) { continue; @@ -308,15 +317,20 @@ seq_move(m.seq, slot.id); park_free.push_back(m.seq); from = "parked"; + kind = mind_from::parked; ok = true; } else { - from = "flash"; + const bool in_ram = (bool) m.ram; + from = in_ram ? "RAM" : "flash"; + kind = in_ram ? mind_from::ram : mind_from::flash; ok = flash_insert(m, slot.id); } + generation = m.generation + 1; if (!ok) { // she stays where she is (on flash, record and file intact); the lane starts this request empty slot.prompt_clear(); from = "flash, pool full"; + kind = mind_from::flash_pool_full; break; } slot.prompt = std::move(m.prompt); @@ -330,7 +344,11 @@ } break; } - slot.page = page; + slot.page = page; + slot.page_generation = generation; + slot.stats.mind_came_from = kind; + slot.stats.mind_switch_us = ggml_time_us() - t0; + slot.stats.mind_generation = generation; SLT_INF(slot, "mind switch: out %.3f ms, in (%s) %.3f ms, she holds %d tokens\n", t_out / 1000.0, from, (ggml_time_us() - t0 - t_out) / 1000.0, slot.prompt.n_tokens()); } diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 022ec5bbefe4..693f493d110a 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -324,6 +324,7 @@ struct server_slot { // Continuum fork: the mind whose sequence this lane holds (server-context-minds.inc); invalid: anonymous mind_page page; + uint64_t page_generation = 0; // her state's generation on this lane bool prompt_save(server_prompt_cache & prompt_cache) const { if (prompt.tokens.size() == 0) { @@ -1920,7 +1921,8 @@ struct server_context_impl { resident_mind m; m.page = slot.page; m.lora = slot.lora; - m.last_use = ++mind_clock; + m.last_use = ++mind_clock; + m.generation = slot.page_generation + 1; if (flash_out(m, slot.id)) { m.prompt = std::move(slot.prompt); slot.prompt.clear(); From 53457dfbbfa3b69e6be24ee309a89b2b0f2b04ce Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 14:40:11 -0600 Subject: [PATCH 06/20] server: learn a past turn on a side sequence (her own sequence never cut, reloaded or re-served); a failed switch defers the request, never runs cold The M5, 2026-11-16: 26 of 30 page restores put the same mind back into the same slot ~16 s after it was saved out, around a learning step: /learn ran ON her sequence and cut it back to the learned turn (keep_first(n0)), or served the past example on her slot first (cutting her newer context to the example's prompt), so the core saved and restored her around every learning step. - POST /learn {"side_sequence": true, messages...}: never served on her slot. From the longest prefix her slot shares with the served prompt, back to the latest checkpoint at or before it: her cells [0, from) re-tagged onto a free side sequence (a parked id; nothing copied), that checkpoint's recurrent state loaded there, the served prompt's own tokens [from, n0) decoded on it, then llama_opt_learn on the side sequence (its restore one token). The side sequence is removed after. Typed refusals: no side sequence free (launch with --minds), no checkpoint at or before the shared prefix; never a fallback onto her slot. - learn_pin on a completion pins the checkpoint at its prompt's end - 1; checkpoint_to_evict and erase_superseded_checkpoints skip pinned ones; a side learn releases it. - mind_switch returns false when the leaving mind cannot leave intact or the arriving mind cannot be inserted; the request then waits for a lane (Codex on #139: never a cold run beside a stored version of her). Receipt (qwen35-0.8b hybrid, M5, --parallel 2 --kv-unified --minds 2 --train-dir): she is served a turn (537-token prompt, learn_pin), acts again (564 tokens; the template renders that turn's generation suffix differently in history, so her slot differs from the served prompt at token 535), then the past turn is learned side_sequence: success, 9 labels from position 536, loss 5.70, 531.7 ms; her next act reuses 563 of 564 tokens (nothing cut, re-served or paged). Before this commit the same learn was refused ("no longer holds this turn's prompt"). 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- common/common.h | 4 ++ tools/server/server-checkpoint-policy.h | 9 ++- tools/server/server-context-learn.inc | 90 ++++++++++++++++++++++--- tools/server/server-context-minds.inc | 18 +++-- tools/server/server-context.cpp | 35 ++++++++-- tools/server/server-task.h | 6 ++ 6 files changed, 140 insertions(+), 22 deletions(-) diff --git a/common/common.h b/common/common.h index 8a3ffd768e18..074a6b33422d 100644 --- a/common/common.h +++ b/common/common.h @@ -1156,6 +1156,10 @@ enum ggml_opt_optimizer_type common_opt_get_optimizer(const char *); struct common_prompt_checkpoint { int64_t n_tokens; + // continuum: held for a turn the core will learn (its served prompt's end, n_prefix - 1): never evicted or + // superseded until that turn is learned on a side sequence or abandoned + bool pinned = false; + // (optional) id of the task that created the checkpoint int id_task = -1; diff --git a/tools/server/server-checkpoint-policy.h b/tools/server/server-checkpoint-policy.h index df2337bd9514..ff9e417f05a2 100644 --- a/tools/server/server-checkpoint-policy.h +++ b/tools/server/server-checkpoint-policy.h @@ -27,12 +27,19 @@ inline bool checkpoint_at_user_start(bool view_spans, bool store_empty, int64_t // The checkpoint to erase to make room for one more. With view spans (view_end >= 0) her head (the // oldest) is her restore point when her next prompt diverges before her view end, so the oldest AFTER // it goes first; the head goes only when it is all there is. Without view spans, the oldest goes. +// A checkpoint pinned for learning is never the victim; end() when every candidate is pinned. template typename List::iterator checkpoint_to_evict(List & checkpoints, int32_t view_end) { auto victim = checkpoints.begin(); if (view_end >= 0 && checkpoints.size() >= 2) { ++victim; } + while (victim != checkpoints.end() && victim->pinned) { + ++victim; + } + if (victim == checkpoints.end() && !checkpoints.empty() && !checkpoints.front().pinned) { + return checkpoints.begin(); // only her head is left unpinned + } return victim; } @@ -48,7 +55,7 @@ size_t erase_superseded_checkpoints(List & checkpoints, const Checkpoint & kept, const auto * head = &checkpoints.front(); size_t erased = 0; for (auto it = checkpoints.begin(); it != checkpoints.end();) { - if (&*it != head && it->id_task != id_task) { + if (&*it != head && it->id_task != id_task && !it->pinned) { on_erase(*it); it = checkpoints.erase(it); ++erased; diff --git a/tools/server/server-context-learn.inc b/tools/server/server-context-learn.inc index b39a0789c92d..516a6b6992ca 100644 --- a/tools/server/server-context-learn.inc +++ b/tools/server/server-context-learn.inc @@ -392,7 +392,7 @@ } // the served prompt, when the request carries it: her slot must still hold exactly it (a // slot that has served other turns since, or compacted, would teach the wrong context) - if (!L.prompt.empty()) { + if (!L.prompt.empty() && !L.side) { // a side sequence builds the served prompt itself (below) int32_t i = 0; while (i < L.n_prefix && slot.prompt.tokens[i] == L.prompt[i]) { ++i; @@ -405,7 +405,32 @@ // the recurrent part cannot be cut back: her state one token before the prompt's end const common_prompt_checkpoint * cp = nullptr; const bool needs_cp = ctx_tgt_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_FULL || ctx_tgt_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_RS; - if (needs_cp) { + // a side sequence: from the longest prefix her slot shares with the served prompt, back to the latest + // checkpoint at or before it; the served prompt's own tokens from there to n0 are decoded on the side + int32_t side_from = n0; + if (L.side) { + if (L.prompt.size() < (size_t) L.n_prefix) { + return refused("a side-sequence learn needs the served prompt's tokens (messages)"); + } + int32_t lcp = 0; + while (lcp < n0 && lcp < (int32_t) slot.prompt.n_tokens() && slot.prompt.tokens[lcp] == L.prompt[lcp]) { + ++lcp; + } + side_from = needs_cp ? -1 : lcp; + if (needs_cp) { + for (const auto & c : slot.prompt.checkpoints) { + if (c.n_tokens <= lcp && (cp == nullptr || c.n_tokens > cp->n_tokens)) { + cp = &c; + } + } + if (cp == nullptr) { + return refused("slot " + std::to_string(slot.id) + " has no checkpoint at or before the " + std::to_string(lcp) + + " tokens it shares with this turn's prompt: no side sequence can be built"); + } + side_from = (int32_t) cp->n_tokens; + } + } + if (needs_cp && !L.side) { for (const auto & c : slot.prompt.checkpoints) { if (c.n_tokens == n0) { cp = &c; @@ -416,9 +441,13 @@ + std::to_string(n0) + "): the lane learns only with --train-dir, which keeps one"); } } + // a side sequence: her own sequence is never touched (refused, typed, before anything is changed) + if (L.side && park_free.empty()) { + return refused("no side sequence is free to learn on (launch with --minds; every parked id holds a mind)"); + } // the tokens from the last prompt token on, each labelled with the next std::vector toks; - toks.push_back(slot.prompt.tokens[n0]); + toks.push_back(L.side ? L.prompt[n0] : slot.prompt.tokens[n0]); // the served prompt's last token toks.insert(toks.end(), L.reply.begin(), L.reply.end()); std::vector labels(toks.size(), -1); for (size_t i = 0; i + 1 < toks.size(); ++i) { @@ -438,18 +467,50 @@ settle_learning_residency(L.lora_id); return refused("adapter " + std::to_string(L.lora_id) + " cannot be trained: " + llama_opt_failure(ctx_tgt)); } - // drop what follows n0 (attention) and put her recurrent state back at n0 - if (cp != nullptr) { - cp->load_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); - } const auto & served_tokens = slot.prompt.tokens.get_tokens(); ggml_opt_result_t result = ggml_opt_result_init(); - const bool begun = llama_opt_learn_begin(ctx_tgt, slot.id, n0, toks.data(), labels.data(), (int32_t) toks.size(), - served_tokens.data() + n0, (int32_t) served_tokens.size() - n0, result); + llama_seq_id learn_seq = slot.id; + int32_t n_restore = (int32_t) served_tokens.size() - n0; + if (L.side) { + // her shared prefix [0, side_from) re-tagged onto a side sequence (attention cells, nothing copied), + // the checkpoint's recurrent state loaded there, then the served prompt's own tokens [side_from, n0) + // decoded on it; the learn's own restore re-decodes one token there. Her sequence is never touched. + learn_seq = park_free.back(); + park_free.pop_back(); + llama_memory_seq_rm(llama_get_memory(ctx_tgt), learn_seq, -1, -1); + llama_memory_seq_cp(llama_get_memory(ctx_tgt), slot.id, learn_seq, 0, side_from); + if (cp != nullptr) { + cp->load_tgt(ctx_tgt, learn_seq, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + } + if (side_from < n0) { + llama_batch b = llama_batch_init(n0 - side_from, 0, 1); + for (int32_t i = side_from; i < n0; ++i) { + common_batch_add(b, L.prompt[i], i, { learn_seq }, false); + } + const int rc = llama_decode(ctx_tgt, b); + llama_batch_free(b); + if (rc != 0) { + llama_memory_seq_rm(llama_get_memory(ctx_tgt), learn_seq, -1, -1); + park_free.push_back(learn_seq); + common_set_adapter_lora(ctx_tgt, slot.lora); + settle_learning_residency(L.lora_id); + return refused("the served prompt's last " + std::to_string(n0 - side_from) + + " tokens could not be decoded on the side sequence"); + } + } + n_restore = 1; + } else if (cp != nullptr) { + // drop what follows n0 (attention) and put her recurrent state back at n0 + cp->load_tgt(ctx_tgt, learn_seq, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + } + const llama_token * restore = L.side ? L.prompt.data() + n0 : served_tokens.data() + n0; + const bool begun = llama_opt_learn_begin(ctx_tgt, learn_seq, n0, toks.data(), labels.data(), (int32_t) toks.size(), + restore, n_restore, result); common_set_adapter_lora(ctx_tgt, slot.lora); learning = std::make_unique(&slot, cp, std::move(set), result, toks[0], L.n_prefix, (int32_t) toks.size() - 1, loras[L.lora_id].ptr, t0); learning->began = begun; + learning->side = L.side ? learn_seq : -1; learning->grant = L.grant; learning->lora_id = L.lora_id; if (!begun) { @@ -556,7 +617,16 @@ // The native owner restored the exact served tail once (not the supplied correction). // Target KV, token metadata and the untouched draft therefore still name the same tail. // If begin refused after loading the recurrent prefix, retain only that proven prefix. - if (!pending.began || !ok) { + if (pending.side >= 0) { + // learned on a side sequence: it goes, her own sequence was never touched; the pin is released + llama_memory_seq_rm(llama_get_memory(ctx_tgt), pending.side, -1, -1); + park_free.push_back(pending.side); + for (auto & c : slot.prompt.checkpoints) { + if (c.n_tokens == n0) { + c.pinned = false; + } + } + } else if (!pending.began || !ok) { llama_memory_seq_rm(llama_get_memory(ctx_tgt), slot.id, n0, -1); if (cp) { cp->load_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); } if (ctx_dft) { diff --git a/tools/server/server-context-minds.inc b/tools/server/server-context-minds.inc index e75d3bb6c749..9b1b7b4b201b 100644 --- a/tools/server/server-context-minds.inc +++ b/tools/server/server-context-minds.inc @@ -267,14 +267,16 @@ } // `slot` serves `page` next. The mind it holds (if any) is parked; hers comes back from where she is. - void mind_switch(server_slot & slot, mind_page page) { + // false: the switch could not complete (the leaving mind could not leave intact, or the arriving mind's state + // could not be inserted): the request waits for a lane, never runs cold beside a stored version of her. + bool mind_switch(server_slot & slot, mind_page page) { slot.stats.mind_hi = page.hi; slot.stats.mind_lo = page.lo; if (slot.page == page) { slot.stats.mind_came_from = mind_from::lane; slot.stats.mind_switch_us = 0; slot.stats.mind_generation = slot.page_generation; - return; + return true; } const int64_t t0 = ggml_time_us(); // the lane's mind leaves, whole @@ -293,7 +295,7 @@ seq_move(slot.id, m.seq); } else if (!flash_out(m, slot.id)) { SLT_ERR(slot, "%s", "the leaving mind could be neither parked nor copied out; she is kept on this lane\n"); - return; // her state is intact on the lane; the arriving request waits for another lane + return false; // her state is intact on the lane; the arriving request waits for another lane } m.prompt = std::move(slot.prompt); slot.prompt.clear(); @@ -327,11 +329,12 @@ } generation = m.generation + 1; if (!ok) { - // she stays where she is (on flash, record and file intact); the lane starts this request empty + // she stays where she is (record and bytes intact: one version of her); the request waits for + // cells, never runs cold beside her stored state slot.prompt_clear(); - from = "flash, pool full"; - kind = mind_from::flash_pool_full; - break; + slot.page = mind_page{}; + SLT_WRN(slot, "%s", "the arriving mind could not be inserted (the pool is full even with every other mind out); her request waits\n"); + return false; } slot.prompt = std::move(m.prompt); slot.lora = std::move(m.lora); @@ -351,4 +354,5 @@ slot.stats.mind_generation = generation; SLT_INF(slot, "mind switch: out %.3f ms, in (%s) %.3f ms, she holds %d tokens\n", t_out / 1000.0, from, (ggml_time_us() - t0 - t_out) / 1000.0, slot.prompt.n_tokens()); + return true; } diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 693f493d110a..528ca12401dc 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1065,6 +1065,7 @@ struct server_context_impl { bool began = false; std::string grant; int32_t lora_id = -1; + llama_seq_id side = -1; // learning on a side sequence: her own sequence is never touched std::string refusal = "none"; bool drained = false; uint64_t restoration_reservation = 0; @@ -1864,9 +1865,8 @@ struct server_context_impl { // a named mind switches by sequence moves (server-context-minds.inc), never through the prompt cache if (ret && minds_on() && task.params.page.valid()) { - mind_switch(*ret, task.params.page); - if (ret->page != task.params.page) { - return nullptr; // the lane's mind could not leave intact: this request waits for a lane + if (!mind_switch(*ret, task.params.page)) { + return nullptr; // the switch could not complete intact: this request waits (never runs cold) } update_cache = false; } @@ -2671,6 +2671,9 @@ struct server_context_impl { // make room for the new checkpoint, if needed: her head stays while there is anything else // to evict (server-checkpoint-policy.h) auto victim = checkpoint_to_evict(slot.prompt.checkpoints, slot.prompt.view_end); + if (victim == slot.prompt.checkpoints.end()) { + break; // every checkpoint is pinned for learning: the store holds one more until they are learned + } SLT_WRN(slot, "erasing old context checkpoint (pos_min = %d, pos_max = %d, n_tokens = %" PRId64 ", size = %.3f MiB)\n", victim->pos_min, victim->pos_max, victim->n_tokens, (float) victim->size() / 1024 / 1024); @@ -2693,7 +2696,10 @@ struct server_context_impl { return; } - const auto & kept = slot.prompt.checkpoints.emplace_back(std::move(cur)); + auto & kept = slot.prompt.checkpoints.emplace_back(std::move(cur)); + if (slot.task->params.learn_pin && kept.n_tokens == (int64_t) slot.task->n_tokens() - 1) { + kept.pinned = true; // the core will learn this turn: kept until learned or abandoned + } // Continuum fork (CONTINUUM-ENGINE 4.7.3, placed checkpoints): her new view-end checkpoint // supersedes every checkpoint an earlier act left on this prefix except her head's (the oldest, @@ -5053,6 +5059,7 @@ std::unique_ptr server_routes::handle_completions_impl( task.id_slot = json_value(data, "id_slot", -1); task.params.page = mind_page_parse(json_value(data, "page", std::string())); // text only at this edge + task.params.learn_pin = json_value(data, "learn_pin", false); sse_ping_interval = task.params.sse_ping_interval; // OAI-compat @@ -6543,6 +6550,7 @@ void server_routes::init_routes() { task.learn.n_prefix = json_value(body, "n_prefix", 0); task.learn.lora_id = json_value(body, "lora_id", -1); task.learn.lr = json_value(body, "lr", 1e-4f); + task.learn.side = json_value(body, "side_sequence", false); if (body.contains("messages")) { try { const auto example = render_learn_example(body); @@ -6573,6 +6581,25 @@ void server_routes::init_routes() { if (result) { res->ok(result->to_json()); } return res; } + // A side-sequence learn never serves the example on her slot (that would cut her context back to the + // example's prompt): her slot must already hold the prompt as a prefix of what she has now, and the + // learn runs on a side sequence (server-context-learn.inc), refused typed otherwise + if (task.learn.side) { + auto & rd = res->rd; + task.id = rd.get_new_id(); + rd.post_task(std::move(task)); + auto result = rd.next(req.should_stop); + if (!result) { + GGML_ASSERT(req.should_stop()); + return res; + } + if (result->is_error()) { + res->error(result->to_json()); + return res; + } + res->ok(result->to_json()); + return res; + } // A past example (S4 (f); fork #89): her slot may no longer hold this prompt. Serve it // first through the ordinary completion path (prompt cache, checkpoints, the slot's // own admission and the grant), one token, and learn as it finishes: when the slot diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 47b165e47774..02a20a283b55 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -102,6 +102,10 @@ struct learn_request { std::vector prompt; // the served prompt, when known: her slot must hold exactly it int32_t lora_id = -1; // the trainable adapter (the shadow), loaded dormant float lr = 1e-4f; + // continuum: learn on a side sequence (her prefix re-tagged, the pinned checkpoint's recurrent state loaded): + // her own sequence is never cut, reloaded or truncated; refused, typed, when no side sequence or no pinned + // checkpoint at n_prefix - 1 exists (never a fallback to her slot) + bool side = false; }; struct learn_outcome { @@ -178,6 +182,8 @@ struct task_params { int32_t view_end_pos = -1; // Continuum fork: the mind this request is (the core's PageKey::Mind; server-mind.h). Invalid: anonymous. mind_page page; + // Continuum fork: the core will learn this turn later: pin the checkpoint at its prompt's end - 1 + bool learn_pin = false; // Embeddings int32_t embd_normalize = 2; // (-1=none, 0=max absolute int16, 1=taxicab, 2=Euclidean/L2, >2=p-norm) From ad10873adbd22f64a1cf7c5b726877437bfc8503 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 14:47:07 -0600 Subject: [PATCH 07/20] server: /props.context_geometry.resident_minds {enabled, lanes, parked_ids}: the core reads before dispatch that the engine owns mind switches (Codex on #139: a completion receipt cannot authorize skipping the save that precedes the same request) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 528ca12401dc..d178e8a60835 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4939,6 +4939,13 @@ server_context_meta server_context::get_meta() const { { "allocated_tokens", llama_n_ctx(impl->ctx_tgt) }, { "max_tokens_per_sequence", impl->n_ctx_slot }, { "sequence_capacity", llama_n_seq_max(impl->ctx_tgt) }, + // the engine owns mind switches (server-context-minds.inc): a request naming its "page" is switched by + // sequence moves; the core reads this BEFORE dispatch to skip its own page save/restore (Codex on #139) + { "resident_minds", json { + { "enabled", impl->minds_on() }, + { "lanes", impl->params_base.n_parallel }, + { "parked_ids", (int64_t) impl->park_free.size() }, + } }, }, }; } From f78f45f172642d9d4991e41c546c8a955a3986f5 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 14:48:19 -0600 Subject: [PATCH 08/20] learn: the side replay decodes in n_batch chunks; its failure frees the optimizer result; the pin is released only when the learn committed; the reply says learned_on and live_sequence_preserved, typed (Codex's review of #139) Receipt (qwen35-0.8b, M5, -b 256 -ub 256): past turn learned side_sequence, 9 labels, 407.8 ms, learned_on=side_sequence, live_sequence_preserved=true; her next act cache_n 563 of 564. 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context-learn.inc | 41 ++++++++++++++++----------- tools/server/server-task.cpp | 2 ++ tools/server/server-task.h | 3 ++ 3 files changed, 30 insertions(+), 16 deletions(-) diff --git a/tools/server/server-context-learn.inc b/tools/server/server-context-learn.inc index 516a6b6992ca..3c3550ad720a 100644 --- a/tools/server/server-context-learn.inc +++ b/tools/server/server-context-learn.inc @@ -482,21 +482,26 @@ if (cp != nullptr) { cp->load_tgt(ctx_tgt, learn_seq, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); } - if (side_from < n0) { - llama_batch b = llama_batch_init(n0 - side_from, 0, 1); - for (int32_t i = side_from; i < n0; ++i) { + // the served prompt's own tokens [side_from, n0), decoded in batches the context accepts + const int32_t chunk = (int32_t) llama_n_batch(ctx_tgt); + int rc = 0; + for (int32_t at = side_from; at < n0 && rc == 0; at += chunk) { + const int32_t n = std::min(chunk, n0 - at); + llama_batch b = llama_batch_init(n, 0, 1); + for (int32_t i = at; i < at + n; ++i) { common_batch_add(b, L.prompt[i], i, { learn_seq }, false); } - const int rc = llama_decode(ctx_tgt, b); + rc = llama_decode(ctx_tgt, b); llama_batch_free(b); - if (rc != 0) { - llama_memory_seq_rm(llama_get_memory(ctx_tgt), learn_seq, -1, -1); - park_free.push_back(learn_seq); - common_set_adapter_lora(ctx_tgt, slot.lora); - settle_learning_residency(L.lora_id); - return refused("the served prompt's last " + std::to_string(n0 - side_from) - + " tokens could not be decoded on the side sequence"); - } + } + if (rc != 0) { + llama_memory_seq_rm(llama_get_memory(ctx_tgt), learn_seq, -1, -1); + park_free.push_back(learn_seq); + ggml_opt_result_free(result); + common_set_adapter_lora(ctx_tgt, slot.lora); + settle_learning_residency(L.lora_id); + return refused("the served prompt's last " + std::to_string(n0 - side_from) + + " tokens could not be decoded on the side sequence"); } n_restore = 1; } else if (cp != nullptr) { @@ -618,12 +623,15 @@ // Target KV, token metadata and the untouched draft therefore still name the same tail. // If begin refused after loading the recurrent prefix, retain only that proven prefix. if (pending.side >= 0) { - // learned on a side sequence: it goes, her own sequence was never touched; the pin is released + // learned on a side sequence: it goes, her own sequence was never touched. The pin is released only + // when the learn committed; an abandoned or failed one keeps it, so a retry still finds it. llama_memory_seq_rm(llama_get_memory(ctx_tgt), pending.side, -1, -1); park_free.push_back(pending.side); - for (auto & c : slot.prompt.checkpoints) { - if (c.n_tokens == n0) { - c.pinned = false; + if (pending.began && ok && !pending.drained) { + for (auto & c : slot.prompt.checkpoints) { + if (c.pinned && c.n_tokens == n0) { + c.pinned = false; + } } } } else if (!pending.began || !ok) { @@ -637,6 +645,7 @@ slot.prompt.checkpoints.remove_if([&](const common_prompt_checkpoint & c) { return c.n_tokens > n0; }); } learn_outcome out; + out.learned_on = pending.side >= 0 ? learn_outcome::learned_on_kind::side_sequence : learn_outcome::learned_on_kind::slot; out.ok = ok && !pending.drained; out.refusal = pending.refusal; out.deferred = pending.drained; diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index e502d728cda1..8a3de7a52680 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1740,6 +1740,8 @@ json learn_outcome::to_json() const { if (!ok) { res["failure"] = failure; } + res["learned_on"] = learned_on == learned_on_kind::side_sequence ? "side_sequence" : "slot"; + res["live_sequence_preserved"] = learned_on == learned_on_kind::side_sequence; return res; } diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 02a20a283b55..258fef9bc79f 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -113,6 +113,9 @@ struct learn_outcome { bool effects_uncertain = false; std::string refusal = "none"; bool ok = false; + // continuum: where it learned, typed. side_sequence: her live sequence was never touched (preserved whatever + // the outcome); slot: on her own sequence (cut back to the learned turn's prefix) + enum class learned_on_kind : uint8_t { slot, side_sequence } learned_on = learned_on_kind::slot; bool deferred = false; int64_t retry_after_ms = 0; std::string failure; From e3795f9a0ef410ac4a0b20ff7d2d21af0c1832a6 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 14:49:57 -0600 Subject: [PATCH 09/20] minds: a flashed mind's checkpoints go down with her (written into her bytes, released from RAM) and come back with her; her prompt moves into her record before she leaves, back onto her lane if she cannot The record kept every checkpoint of a flashed mind in host RAM (~100 MB each on a 35B hybrid), so going to flash did not free what she held. Her bytes are now [target state][draft state][checkpoints: count, then per checkpoint its positions, pin and three blobs], validated on the way back (sizes checked before any copy). Receipt (qwen35-0.8b hybrid, M5, three minds through a two-mind pool, 3 rounds): her flash bytes 96.6 MiB (58.1 state + 2 checkpoints of 19.3 MiB), copied out in 2.4 ms, inserted back in 7.8-8.1 ms; whole switch 9.0-11.1 ms (from flash or RAM); every return cache_n 3300; she comes back holding her 2 checkpoints (2788 and 3300 tokens). 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context-minds.inc | 68 ++++++++++++++++++++++++--- tools/server/server-context.cpp | 5 +- 2 files changed, 64 insertions(+), 9 deletions(-) diff --git a/tools/server/server-context-minds.inc b/tools/server/server-context-minds.inc index 9b1b7b4b201b..7049a890d540 100644 --- a/tools/server/server-context-minds.inc +++ b/tools/server/server-context-minds.inc @@ -24,6 +24,47 @@ std::shared_ptr> written; // 0 pending, 1 landed, -1 failed }; + // her checkpoints as bytes beside her state: count, then per checkpoint its position fields, three sizes and + // the three blobs (target, draft, speculative state) + static constexpr size_t ckpt_header_bytes = sizeof(int64_t) + 3 * sizeof(int32_t) + 1 + 3 * sizeof(uint64_t); + + static void ckpt_write(const std::list & cks, uint8_t * w) { + auto put = [&](const void * p, size_t n) { std::memcpy(w, p, n); w += n; }; + const uint64_t count = cks.size(); + put(&count, sizeof(count)); + for (const auto & c : cks) { + const int32_t id = c.id_task, mn = c.pos_min, mx = c.pos_max; + const uint8_t pin = c.pinned ? 1 : 0; + const uint64_t a = c.data_tgt.size(), b = c.data_dft.size(), d = c.data_spec.size(); + put(&c.n_tokens, sizeof(c.n_tokens)); put(&id, 4); put(&mn, 4); put(&mx, 4); put(&pin, 1); + put(&a, 8); put(&b, 8); put(&d, 8); + put(c.data_tgt.data(), a); put(c.data_dft.data(), b); put(c.data_spec.data(), d); + } + } + + static bool ckpt_read(const uint8_t * r, uint64_t n, std::list & out) { + const uint8_t * end = r + n; + auto get = [&](void * p, size_t k) { if ((size_t) (end - r) < k) { return false; } std::memcpy(p, r, k); r += k; return true; }; + uint64_t count = 0; + if (!get(&count, sizeof(count))) { + return false; + } + for (uint64_t i = 0; i < count; ++i) { + common_prompt_checkpoint c; + int32_t id, mn, mx; uint8_t pin; uint64_t a, b, d; + if (!get(&c.n_tokens, sizeof(c.n_tokens)) || !get(&id, 4) || !get(&mn, 4) || !get(&mx, 4) || !get(&pin, 1) || + !get(&a, 8) || !get(&b, 8) || !get(&d, 8) || (uint64_t) (end - r) < a + b + d) { + return false; + } + c.id_task = id; c.pos_min = mn; c.pos_max = mx; c.pinned = pin != 0; + c.data_tgt.assign(r, r + a); r += a; + c.data_dft.assign(r, r + b); r += b; + c.data_spec.assign(r, r + d); r += d; + out.push_back(std::move(c)); + } + return r == end; + } + std::vector park_free; // free parked sequence ids (sized once at load) std::vector minds; // parked and flashed minds (reserved once at load) uint64_t mind_clock = 0; @@ -107,17 +148,24 @@ auto bytes = std::make_shared>(); const size_t n_tgt = llama_state_seq_get_size_ext(ctx_tgt, seq, LLAMA_STATE_SEQ_FLAGS_NONE); const size_t n_dft = ctx_dft ? llama_state_seq_get_size_ext(ctx_dft, seq, LLAMA_STATE_SEQ_FLAGS_NONE) : 0; - bytes->resize(2 * sizeof(uint64_t) + n_tgt + n_dft); + // her checkpoints go down with her (they are host bytes too: ~100 MB each on a 35B hybrid) + size_t n_ck = sizeof(uint64_t); + for (const auto & c : cold->prompt.checkpoints) { + n_ck += ckpt_header_bytes + c.data_tgt.size() + c.data_dft.size() + c.data_spec.size(); + } + bytes->resize(3 * sizeof(uint64_t) + n_tgt + n_dft + n_ck); uint8_t * w = bytes->data(); - const uint64_t h[2] = { n_tgt, n_dft }; + const uint64_t h[3] = { n_tgt, n_dft, n_ck }; std::memcpy(w, h, sizeof(h)); w += sizeof(h); + ckpt_write(cold->prompt.checkpoints, w + n_tgt + n_dft); if (llama_state_seq_get_data_ext(ctx_tgt, w, n_tgt, seq, LLAMA_STATE_SEQ_FLAGS_NONE) != n_tgt || (ctx_dft && llama_state_seq_get_data_ext(ctx_dft, w + n_tgt, n_dft, seq, LLAMA_STATE_SEQ_FLAGS_NONE) != n_dft)) { SRV_ERR("mind %016llx: her state could not be copied out of the pool; she stays where she is\n", (unsigned long long) cold->page.hi); return false; } const int64_t t_copy = ggml_time_us() - t0; + std::list().swap(cold->prompt.checkpoints); // their bytes are in hers now llama_memory_seq_rm(llama_get_memory(ctx_tgt), seq, -1, -1); if (ctx_dft) { llama_memory_seq_rm(llama_get_memory(ctx_dft), seq, -1, -1); @@ -186,15 +234,19 @@ base = map->data(); size = map->size(); } - if (size < 2 * sizeof(uint64_t)) { + if (size < 3 * sizeof(uint64_t)) { return false; } - uint64_t h[2]; + uint64_t h[3]; std::memcpy(h, base, sizeof(h)); - if (size != 2 * sizeof(uint64_t) + h[0] + h[1]) { + if (size != 3 * sizeof(uint64_t) + h[0] + h[1] + h[2]) { return false; } const uint8_t * r = base + sizeof(h); + std::list checkpoints; + if (!ckpt_read(r + h[0] + h[1], h[2], checkpoints)) { + return false; + } // her cells come from the pool: when it is full, the coldest parked mind goes down to flash first, and the // insert is tried again (a level above makes room for the level below, never a drop) bool ok = false; @@ -223,6 +275,7 @@ } SRV_INF("mind %016llx%016llx back from %s: %.1f MiB inserted in %.2f ms\n", (unsigned long long) m.page.hi, (unsigned long long) m.page.lo, ram ? "RAM" : "flash", size / (1024.0 * 1024.0), (ggml_time_us() - t0) / 1000.0); + m.prompt.checkpoints = std::move(checkpoints); // her file is removed on the page-IO worker, ordered after its own write (it may still be landing) const std::string path = m.file; page_io->submit(path, [path] { std::error_code ec; std::filesystem::remove(path, ec); }); @@ -289,16 +342,17 @@ if (park_free.empty()) { flash_coldest(); // the pool's coldest parked mind makes room, if one is parked } + m.prompt = std::move(slot.prompt); + slot.prompt.clear(); if (!park_free.empty()) { m.seq = park_free.back(); park_free.pop_back(); seq_move(slot.id, m.seq); } else if (!flash_out(m, slot.id)) { + slot.prompt = std::move(m.prompt); // she stays whole on her lane SLT_ERR(slot, "%s", "the leaving mind could be neither parked nor copied out; she is kept on this lane\n"); return false; // her state is intact on the lane; the arriving request waits for another lane } - m.prompt = std::move(slot.prompt); - slot.prompt.clear(); minds.push_back(std::move(m)); } else if (!slot.page.valid()) { // content no named mind owns (a core page restore, or scratch): adopted, never cleared; the prompt's diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index d178e8a60835..8a76e69c0335 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1923,13 +1923,14 @@ struct server_context_impl { m.lora = slot.lora; m.last_use = ++mind_clock; m.generation = slot.page_generation + 1; + m.prompt = std::move(slot.prompt); + slot.prompt.clear(); if (flash_out(m, slot.id)) { - m.prompt = std::move(slot.prompt); - slot.prompt.clear(); slot.page = mind_page{}; minds.push_back(std::move(m)); return true; } + slot.prompt = std::move(m.prompt); // she stays whole on her lane } } } From 0793fa609dca9090e53957d932186329c73ff882 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 14:51:30 -0600 Subject: [PATCH 10/20] minds + one host budget (#138 merged in): parked minds' checkpoints and flashed minds' RAM copies count against --cache-ram; to make room, the coldest parked mind goes down to flash first (her checkpoints with her), before any lane gives one up The make-room decision counts only what stays resident (a RAM copy is freed within ms of its write landing), so sending one mind down is seen to free her checkpoints and the loop stops there. Receipt (qwen35-0.8b hybrid, M5, --cache-ram 60 with three ~38 MiB-of-checkpoints minds through a two-mind pool, 3 rounds): 7 minds sent to flash under the budget before 4 lane-checkpoint evictions; 3 of 6 returns re-prefilled (cache_n 0) because the lane's checkpoint at their resume point was among those evicted: the budget's trade-off at an intentionally tight grant (unbounded, every return was cache_n 3300). Choosing which checkpoint goes by value per byte (keep the one her next resume needs) is 4.7.6's pool policy, next. 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context.cpp | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 0dfcd35cee25..1a058a8df274 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -2661,13 +2661,25 @@ struct server_context_impl { // the prompt cache holds what is left and evicts down to it. size_t host_budget = 0; - size_t checkpoint_bytes() const { + // every host byte the engine holds beside the prompt cache: the lanes' checkpoints, the parked minds' + // checkpoints, and a flashed mind's RAM copy until her file has landed (server-context-minds.inc) + // `in_flight`: also a flashed mind's RAM copy (freed within ms of its write landing). The make-room decision + // counts only what stays resident, so sending one mind down is seen to free her checkpoints. + size_t checkpoint_bytes(bool in_flight = true) const { size_t b = 0; for (const auto & s : slots) { for (const auto & c : s.prompt.checkpoints) { b += c.size(); } } + for (const auto & m : minds) { + for (const auto & c : m.prompt.checkpoints) { + b += c.size(); + } + if (in_flight && m.ram) { + b += m.ram->size(); + } + } return b; } @@ -2692,6 +2704,9 @@ struct server_context_impl { if (bytes > host_budget) { return false; } + // the coldest parked mind goes down to flash first (her checkpoints with her): the minds acting keep theirs + while (checkpoint_bytes(false) + bytes > host_budget && minds_on() && flash_coldest()) { + } size_t held = checkpoint_bytes(); while (held + bytes > host_budget) { server_slot * from = nullptr; From 1cd4db0d946d896109bce71e738782eb55d25e58 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 14:55:18 -0600 Subject: [PATCH 11/20] one host budget: making room counts only what stays resident, and her newest checkpoint (her resume point) goes last The lane-eviction loop counted minds' RAM copies already on their way to flash (96.6 + 58.1 MiB against a 60 MiB grant): it looked unsatisfiable, stripped the lane's checkpoints and refused the new one ('larger than the whole budget'), so that mind went to flash with none and came back cold. Now both make-room loops count resident bytes; a lane gives up its oldest unpinned checkpoint, never her newest while anything else is left; the refusal says what it means. Receipt (qwen35-0.8b hybrid, M5, --cache-ram 60, three minds with ~38 MiB of checkpoints each through a two-mind pool, 3 rounds): every return cache_n 3300 (was 3 of 6 cold); 8 minds to flash with their checkpoints; 0 lane-checkpoint evictions; 0 refusals. 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context.cpp | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 1a058a8df274..b6729eb68f5e 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -2707,7 +2707,7 @@ struct server_context_impl { // the coldest parked mind goes down to flash first (her checkpoints with her): the minds acting keep theirs while (checkpoint_bytes(false) + bytes > host_budget && minds_on() && flash_coldest()) { } - size_t held = checkpoint_bytes(); + size_t held = checkpoint_bytes(false); // what stays resident: copies on their way to flash are leaving while (held + bytes > host_budget) { server_slot * from = nullptr; size_t most = 0; @@ -2724,7 +2724,28 @@ struct server_context_impl { if (from == nullptr) { return false; } - auto victim = checkpoint_to_evict(from->prompt.checkpoints, from->prompt.view_end); + // her newest checkpoint is where her next act resumes (her context only appends): it goes last. + // Otherwise the store's own order (her head kept while anything else is left), never a pinned one. + auto & cks = from->prompt.checkpoints; + auto newest = cks.end(); + for (auto it = cks.begin(); it != cks.end(); ++it) { + if (newest == cks.end() || it->n_tokens > newest->n_tokens) { + newest = it; + } + } + auto victim = cks.end(); + for (auto it = cks.begin(); it != cks.end(); ++it) { + if (it != newest && !it->pinned) { + victim = it; + break; + } + } + if (victim == cks.end() && newest != cks.end() && !newest->pinned) { + victim = newest; // all that is left + } + if (victim == cks.end()) { + return false; // every checkpoint left is pinned for learning + } SLT_WRN(*from, "host budget: erasing a checkpoint (n_tokens = %" PRId64 ", %.3f MiB) for a new one of %.3f MiB\n", victim->n_tokens, (float) victim->size() / 1024 / 1024, (float) bytes / 1024 / 1024); held -= victim->size(); @@ -2775,8 +2796,8 @@ struct server_context_impl { quote += llama_state_seq_get_size_ext(ctx_dft, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); } if (!make_room_for_checkpoint(quote)) { - SLT_WRN(slot, "host budget: a checkpoint of %.3f MiB is larger than the whole budget; none is made\n", - (float) quote / 1024 / 1024); + SLT_WRN(slot, "host budget: a checkpoint of %.3f MiB does not fit beside what stays resident (budget %.3f MiB); none is made\n", + (float) quote / 1024 / 1024, (float) host_budget / 1024 / 1024); return; } } From 793bd184868cde970d7c06d2b93d5ba53245b40a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 15:00:45 -0600 Subject: [PATCH 12/20] minds: /minds/prefetch refuses, typed, a stream meant for another engine process (engine_pid; Codex on #6087: a stream must never land on a replacement engine) Receipt (qwen35-0.8b, M5): engine_pid = this process -> answered ('new'); engine_pid = 1 -> 400 'engine_pid names another engine process'. The OS call lives beside the file mapping (server-mapped-file.cpp). 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context.cpp | 5 +++++ tools/server/server-mapped-file.cpp | 4 ++++ tools/server/server-mapped-file.h | 3 +++ 3 files changed, 12 insertions(+) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index b6729eb68f5e..d43b57f550c0 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -7041,6 +7041,11 @@ std::unique_ptr server_routes::handle_minds_prefetch(const server_task task(SERVER_TASK_TYPE_MIND_PREFETCH); task.id = rd.get_new_id(); task.params.page = mind_page_parse(json_value(body, "page", std::string())); + // a stream meant for another process of this engine (a replacement after a restart) is refused, typed + if (body.contains("engine_pid") && json_value(body, "engine_pid", (int64_t) -1) != (int64_t) server_process_pid()) { + res->error(format_error_response("engine_pid names another engine process: this prefetch was for a replaced engine", ERROR_TYPE_INVALID_REQUEST)); + return res; + } if (!task.params.page.valid()) { res->error(format_error_response("page must name a mind (32 hexadecimal digits, a UUID)", ERROR_TYPE_INVALID_REQUEST)); return res; diff --git a/tools/server/server-mapped-file.cpp b/tools/server/server-mapped-file.cpp index 19ca94eaca4e..1dd42ed65924 100644 --- a/tools/server/server-mapped-file.cpp +++ b/tools/server/server-mapped-file.cpp @@ -9,6 +9,8 @@ #endif #include +int64_t server_process_pid() { return (int64_t) GetCurrentProcessId(); } + server_mapped_file::server_mapped_file(const std::string & path) { HANDLE f = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr); if (f == INVALID_HANDLE_VALUE) { @@ -50,6 +52,8 @@ server_mapped_file::~server_mapped_file() { #include #include +int64_t server_process_pid() { return (int64_t) ::getpid(); } + server_mapped_file::server_mapped_file(const std::string & path) { const int fd = ::open(path.c_str(), O_RDONLY); if (fd < 0) { diff --git a/tools/server/server-mapped-file.h b/tools/server/server-mapped-file.h index 44f721662f13..72a490362ca2 100644 --- a/tools/server/server-mapped-file.h +++ b/tools/server/server-mapped-file.h @@ -7,6 +7,9 @@ #include #include +// This engine process's id (the core binds a mind prefetch to it). OS call in server-mapped-file.cpp. +int64_t server_process_pid(); + class server_mapped_file { public: explicit server_mapped_file(const std::string & path); From 8a53bd561a3de5c7d2d7e3a1a370845d8525282a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 15:12:26 -0600 Subject: [PATCH 13/20] minds: the engine issues its own incarnation token (resident_minds.incarnation on /props); /minds/prefetch refuses any other, typed (Codex: a pid is reused, never an identity) Drawn once per process from std::random_device; the core reads it with the pool and sends it back. Replaces the pid check and its OS call. Receipt (qwen35-0.8b, M5): the /props token -> answered ('new'); 5 -> 400 'incarnation names another engine'; absent -> 400. 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context.cpp | 7 ++++--- tools/server/server-mapped-file.cpp | 4 ---- tools/server/server-mapped-file.h | 3 --- tools/server/server-mind.h | 13 +++++++++++++ 4 files changed, 17 insertions(+), 10 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index d43b57f550c0..a7b7150c87aa 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -5068,6 +5068,7 @@ server_context_meta server_context::get_meta() const { { "enabled", impl->minds_on() }, { "lanes", impl->params_base.n_parallel }, { "parked_ids", (int64_t) impl->park_free.size() }, + { "incarnation", mind_incarnation() }, } }, }, }; @@ -7041,9 +7042,9 @@ std::unique_ptr server_routes::handle_minds_prefetch(const server_task task(SERVER_TASK_TYPE_MIND_PREFETCH); task.id = rd.get_new_id(); task.params.page = mind_page_parse(json_value(body, "page", std::string())); - // a stream meant for another process of this engine (a replacement after a restart) is refused, typed - if (body.contains("engine_pid") && json_value(body, "engine_pid", (int64_t) -1) != (int64_t) server_process_pid()) { - res->error(format_error_response("engine_pid names another engine process: this prefetch was for a replaced engine", ERROR_TYPE_INVALID_REQUEST)); + // a stream meant for another incarnation of this engine (a replacement after a restart) is refused, typed + if (json_value(body, "incarnation", (uint64_t) 0) != mind_incarnation()) { + res->error(format_error_response("incarnation names another engine: this prefetch was for a replaced engine", ERROR_TYPE_INVALID_REQUEST)); return res; } if (!task.params.page.valid()) { diff --git a/tools/server/server-mapped-file.cpp b/tools/server/server-mapped-file.cpp index 1dd42ed65924..19ca94eaca4e 100644 --- a/tools/server/server-mapped-file.cpp +++ b/tools/server/server-mapped-file.cpp @@ -9,8 +9,6 @@ #endif #include -int64_t server_process_pid() { return (int64_t) GetCurrentProcessId(); } - server_mapped_file::server_mapped_file(const std::string & path) { HANDLE f = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr); if (f == INVALID_HANDLE_VALUE) { @@ -52,8 +50,6 @@ server_mapped_file::~server_mapped_file() { #include #include -int64_t server_process_pid() { return (int64_t) ::getpid(); } - server_mapped_file::server_mapped_file(const std::string & path) { const int fd = ::open(path.c_str(), O_RDONLY); if (fd < 0) { diff --git a/tools/server/server-mapped-file.h b/tools/server/server-mapped-file.h index 72a490362ca2..44f721662f13 100644 --- a/tools/server/server-mapped-file.h +++ b/tools/server/server-mapped-file.h @@ -7,9 +7,6 @@ #include #include -// This engine process's id (the core binds a mind prefetch to it). OS call in server-mapped-file.cpp. -int64_t server_process_pid(); - class server_mapped_file { public: explicit server_mapped_file(const std::string & path); diff --git a/tools/server/server-mind.h b/tools/server/server-mind.h index a4b6b6666d91..337471b4af12 100644 --- a/tools/server/server-mind.h +++ b/tools/server/server-mind.h @@ -10,8 +10,21 @@ // from the context's sequence capacity) and performs the moves. #include +#include #include +// This engine incarnation's token, drawn once per process and reported on /props (resident_minds.incarnation). +// The core sends it back with a prefetch, so a stream meant for a replaced engine is refused: issued by the engine +// itself, never inferred from an OS pid (which the OS reuses). +inline uint64_t mind_incarnation() { + static const uint64_t token = [] { + std::random_device rd; + const uint64_t t = ((uint64_t) rd() << 32) ^ (uint64_t) rd(); + return t != 0 ? t : 1; + }(); + return token; +} + struct mind_page { uint64_t hi = 0, lo = 0; bool valid() const { return hi != 0 || lo != 0; } From e8ee0b2f4865ba35e748bed30c99d4ab773c3c61 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 15:19:41 -0600 Subject: [PATCH 14/20] minds + learn: every reply value a frozen typed enum (Codex: callers must never guess a default) - /minds/prefetch answers {mind, elapsed_ms}; mind is one of lane | parked | unknown | deferred_no_parked_id | deferred_pool_full | minds_off (mind_place). Was a success bool and free text; the handler also asserted the wrong result type (copied from slot erase). - learn_outcome: learned_on is none | slot | side_sequence (none = no learning ran); live_sequence_preserved is its own field, stated by the path that ran (true for every refusal before custody and every side learn, false only when the slot path cut her sequence), never inferred from success. - Every learn refusal sets the typed refusal (failure is detail only): busy, unsupported, no_adapter, prefix_mismatch, no_messages, no_checkpoint, no_side_sequence, residency, replay_failed, optimizer_failed, plus the ledger's names and residency_revoked / effects_uncertain. Before, a refused side learn reported refusal 'none'. Receipt (qwen35-0.8b, M5): never served -> unknown; on the lane -> lane; after another mind took the lane -> parked (0.001-0.002 ms each). 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context-learn.inc | 33 ++++++++++++++++----------- tools/server/server-context-minds.inc | 14 ++++++------ tools/server/server-context.cpp | 11 ++++----- tools/server/server-mind.h | 11 +++++++++ tools/server/server-task.cpp | 5 ++-- tools/server/server-task.h | 19 ++++++++++++--- 6 files changed, 62 insertions(+), 31 deletions(-) diff --git a/tools/server/server-context-learn.inc b/tools/server/server-context-learn.inc index 3c3550ad720a..6bec9f23675a 100644 --- a/tools/server/server-context-learn.inc +++ b/tools/server/server-context-learn.inc @@ -308,6 +308,7 @@ if (learning) { learn_outcome out; out.deferred = true; + out.refusal = "busy"; out.failure = "the lane optimizer is restoring an admitted reply; retain this experience for retry"; return out; } @@ -370,8 +371,10 @@ } learn_outcome learn_on_slot_admitted(server_slot & slot, const learn_request & L, int64_t t0) { - auto refused = [&](const std::string & why) { + // `kind` is the typed refusal a caller matches (frozen: see learn_outcome::refusal); `why` is detail only + auto refused = [&](const char * kind, const std::string & why) { learn_outcome out; + out.refusal = kind; out.failure = why; SRV_WRN("learn refused: %s\n", why.c_str()); return out; @@ -379,15 +382,15 @@ // the same refusal /train gives: repacked CPU weights fail the backward (x86) or crash // the copy to Metal (an M5 at -ngl 0), card 5b497852 if (const std::string why = train_repack_refusal(model_tgt, params_base); !why.empty()) { - return refused(why); + return refused("unsupported", why); } auto & loras = params_base.lora_adapters; if (L.lora_id < 0 || (size_t) L.lora_id >= loras.size() || loras[L.lora_id].ptr == nullptr) { - return refused("no loaded adapter " + std::to_string(L.lora_id) + " to train (POST /lora-adapters/load it first)"); + return refused("no_adapter", "no loaded adapter " + std::to_string(L.lora_id) + " to train (POST /lora-adapters/load it first)"); } const int32_t n0 = L.n_prefix - 1; // the last prompt token is re-decoded with the reply's first token as its label if (n0 < 0 || L.n_prefix > slot.prompt.n_tokens() || L.reply.empty()) { - return refused("slot " + std::to_string(slot.id) + " holds " + std::to_string(slot.prompt.n_tokens()) + return refused("prefix_mismatch", "slot " + std::to_string(slot.id) + " holds " + std::to_string(slot.prompt.n_tokens()) + " prompt tokens; the served prefix is " + std::to_string(L.n_prefix) + " and the reply must not be empty"); } // the served prompt, when the request carries it: her slot must still hold exactly it (a @@ -398,7 +401,7 @@ ++i; } if (i < L.n_prefix) { - return refused("slot " + std::to_string(slot.id) + " no longer holds this turn's prompt (it differs at token " + return refused("prefix_mismatch", "slot " + std::to_string(slot.id) + " no longer holds this turn's prompt (it differs at token " + std::to_string(i) + " of " + std::to_string(L.n_prefix) + "): serve the prompt again, then learn"); } } @@ -410,7 +413,7 @@ int32_t side_from = n0; if (L.side) { if (L.prompt.size() < (size_t) L.n_prefix) { - return refused("a side-sequence learn needs the served prompt's tokens (messages)"); + return refused("no_messages", "a side-sequence learn needs the served prompt's tokens (messages)"); } int32_t lcp = 0; while (lcp < n0 && lcp < (int32_t) slot.prompt.n_tokens() && slot.prompt.tokens[lcp] == L.prompt[lcp]) { @@ -424,7 +427,7 @@ } } if (cp == nullptr) { - return refused("slot " + std::to_string(slot.id) + " has no checkpoint at or before the " + std::to_string(lcp) + return refused("no_checkpoint", "slot " + std::to_string(slot.id) + " has no checkpoint at or before the " + std::to_string(lcp) + " tokens it shares with this turn's prompt: no side sequence can be built"); } side_from = (int32_t) cp->n_tokens; @@ -437,13 +440,13 @@ } } if (cp == nullptr) { - return refused("slot " + std::to_string(slot.id) + " has no checkpoint one token before its prompt's end (" + return refused("no_checkpoint", "slot " + std::to_string(slot.id) + " has no checkpoint one token before its prompt's end (" + std::to_string(n0) + "): the lane learns only with --train-dir, which keeps one"); } } // a side sequence: her own sequence is never touched (refused, typed, before anything is changed) if (L.side && park_free.empty()) { - return refused("no side sequence is free to learn on (launch with --minds; every parked id holds a mind)"); + return refused("no_side_sequence", "no side sequence is free to learn on (launch with --minds; every parked id holds a mind)"); } // the tokens from the last prompt token on, each labelled with the next std::vector toks; @@ -453,7 +456,7 @@ for (size_t i = 0; i + 1 < toks.size(); ++i) { labels[i] = toks[i + 1]; } - if (const auto why = admit_learning_residency(L); !why.empty()) { return refused(why); } + if (const auto why = admit_learning_residency(L); !why.empty()) { return refused("residency", why); } // her stable set plus the shadow: the shadow applies to labelled rows only std::vector set = slot.lora.empty() ? construct_lora_list({}) : slot.lora; if ((size_t) L.lora_id >= set.size()) { @@ -465,7 +468,7 @@ if (!select_learning_shadow(L.lora_id)) { common_set_adapter_lora(ctx_tgt, slot.lora); settle_learning_residency(L.lora_id); - return refused("adapter " + std::to_string(L.lora_id) + " cannot be trained: " + llama_opt_failure(ctx_tgt)); + return refused("unsupported", "adapter " + std::to_string(L.lora_id) + " cannot be trained: " + llama_opt_failure(ctx_tgt)); } const auto & served_tokens = slot.prompt.tokens.get_tokens(); ggml_opt_result_t result = ggml_opt_result_init(); @@ -500,7 +503,7 @@ ggml_opt_result_free(result); common_set_adapter_lora(ctx_tgt, slot.lora); settle_learning_residency(L.lora_id); - return refused("the served prompt's last " + std::to_string(n0 - side_from) + return refused("replay_failed", "the served prompt's last " + std::to_string(n0 - side_from) + " tokens could not be decoded on the side sequence"); } n_restore = 1; @@ -604,7 +607,10 @@ } if (status != LLAMA_OPT_LEARN_MORE) { pending.finished = status == LLAMA_OPT_LEARN_DONE; - if (status != LLAMA_OPT_LEARN_DONE) { pending.failure = llama_opt_failure(ctx_tgt); } + if (status != LLAMA_OPT_LEARN_DONE) { + pending.refusal = "optimizer_failed"; + pending.failure = llama_opt_failure(ctx_tgt); + } } // Even the final chunk yields before the last prompt token is restored below. return; @@ -646,6 +652,7 @@ } learn_outcome out; out.learned_on = pending.side >= 0 ? learn_outcome::learned_on_kind::side_sequence : learn_outcome::learned_on_kind::slot; + out.live_sequence_preserved = pending.side >= 0; // the slot path cut her sequence back to the learned prefix out.ok = ok && !pending.drained; out.refusal = pending.refusal; out.deferred = pending.drained; diff --git a/tools/server/server-context-minds.inc b/tools/server/server-context-minds.inc index 7049a890d540..7eb64c5211b5 100644 --- a/tools/server/server-context-minds.inc +++ b/tools/server/server-context-minds.inc @@ -286,37 +286,37 @@ // Ahead of her turn (the core names who is next): a mind on flash is inserted into a free parked sequence // now, while the others decode, so her switch is the sequence move. Returns where she is afterwards. - const char * mind_prefetch(mind_page page) { + mind_place mind_prefetch(mind_page page) { for (const auto & s : slots) { if (s.page == page) { - return "lane"; + return mind_place::lane; } } resident_mind * m = find_mind(page); if (m == nullptr) { - return "new"; + return mind_place::unknown; } if (m->seq >= 0) { m->last_use = ++mind_clock; // she is next: the last to be sent down - return "parked"; + return mind_place::parked; } if (park_free.empty()) { flash_coldest(); } if (park_free.empty()) { - return "flash, no parked id free"; + return mind_place::deferred_no_parked_id; } const llama_seq_id seq = park_free.back(); park_free.pop_back(); // flash_coldest() may run inside the insert and move records: hold her by page, not by pointer if (!flash_insert(*find_mind(page), seq)) { park_free.push_back(seq); - return "flash, pool full"; + return mind_place::deferred_pool_full; } resident_mind * back = find_mind(page); back->seq = seq; back->last_use = ++mind_clock; - return "parked"; + return mind_place::parked; } // `slot` serves `page` next. The mind it holds (if any) is parked; hers comes back from where she is. diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index a7b7150c87aa..8d10aef238ba 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -3060,11 +3060,10 @@ struct server_context_impl { case SERVER_TASK_TYPE_MIND_PREFETCH: { const int64_t t0 = ggml_time_us(); - const char * where = minds_on() ? mind_prefetch(task.params.page) : "minds off"; - auto res = std::make_unique(); - res->id = task.id; - res->success = std::strcmp(where, "lane") == 0 || std::strcmp(where, "parked") == 0; - res->message = std::string(where) + " (" + std::to_string((ggml_time_us() - t0) / 1000.0) + " ms)"; + auto res = std::make_unique(); + res->id = task.id; + res->place = minds_on() ? mind_prefetch(task.params.page) : mind_place::minds_off; + res->elapsed_ms = (ggml_time_us() - t0) / 1000.0; queue_results.send(std::move(res)); } break; case SERVER_TASK_TYPE_SLOT_ERASE: @@ -7092,7 +7091,7 @@ std::unique_ptr server_routes::handle_slots_erase(const se return res; } - GGML_ASSERT(dynamic_cast(result.get()) != nullptr); + GGML_ASSERT(dynamic_cast(result.get()) != nullptr); res->ok(result->to_json()); return res; } diff --git a/tools/server/server-mind.h b/tools/server/server-mind.h index 337471b4af12..21e73a87d531 100644 --- a/tools/server/server-mind.h +++ b/tools/server/server-mind.h @@ -32,6 +32,17 @@ struct mind_page { bool operator!=(const mind_page & o) const { return !(*this == o); } }; +// Where a prefetch left her (POST /minds/prefetch's "mind"; frozen spellings in mind_place_name). lane / parked: she +// is in the pool and her switch is a sequence move. unknown: the engine has never served her (her first turn builds +// her). deferred_no_parked_id / deferred_pool_full: she stays on flash and her turn switches through it. +// minds_off: the engine was launched without --minds. +enum class mind_place : uint8_t { lane, parked, unknown, deferred_no_parked_id, deferred_pool_full, minds_off }; + +inline const char * mind_place_name(mind_place p) { + static const char * names[] = { "lane", "parked", "unknown", "deferred_no_parked_id", "deferred_pool_full", "minds_off" }; + return names[(size_t) p]; +} + // "page": 32 hexadecimal digits, dashes allowed (a UUID). Anything else is no page (the request is anonymous). inline mind_page mind_page_parse(const std::string & s) { mind_page p; diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index 8a3de7a52680..673bcf778824 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1740,8 +1740,9 @@ json learn_outcome::to_json() const { if (!ok) { res["failure"] = failure; } - res["learned_on"] = learned_on == learned_on_kind::side_sequence ? "side_sequence" : "slot"; - res["live_sequence_preserved"] = learned_on == learned_on_kind::side_sequence; + static const char * learned_on_names[] = { "none", "slot", "side_sequence" }; + res["learned_on"] = learned_on_names[(size_t) learned_on]; + res["live_sequence_preserved"] = live_sequence_preserved; return res; } diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 258fef9bc79f..716423d9d3ac 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -113,9 +113,12 @@ struct learn_outcome { bool effects_uncertain = false; std::string refusal = "none"; bool ok = false; - // continuum: where it learned, typed. side_sequence: her live sequence was never touched (preserved whatever - // the outcome); slot: on her own sequence (cut back to the learned turn's prefix) - enum class learned_on_kind : uint8_t { slot, side_sequence } learned_on = learned_on_kind::slot; + // continuum: where it learned, typed. none: no learning ran (a refusal or deferral before custody); + // side_sequence: on a side sequence; slot: on her own sequence (cut back to the learned turn's prefix). + enum class learned_on_kind : uint8_t { none, slot, side_sequence } learned_on = learned_on_kind::none; + // whether her live sequence is exactly as it was: stated by the path that ran, never inferred from success + // (true for every refusal before custody and every side-sequence learn; false only when the slot path cut it) + bool live_sequence_preserved = true; bool deferred = false; int64_t retry_after_ms = 0; std::string failure; @@ -720,6 +723,16 @@ struct server_task_result_control : server_task_result { } }; +// continuum: POST /minds/prefetch's reply, typed (`mind`: a mind_place_name spelling) +struct server_task_result_mind_prefetch : server_task_result { + mind_place place = mind_place::minds_off; + double elapsed_ms = 0.0; + + virtual json to_json() override { + return json { { "mind", mind_place_name(place) }, { "elapsed_ms", elapsed_ms } }; + } +}; + struct server_task_result_apply_lora : server_task_result { virtual json to_json() override; }; From 5b5e22a4e6fe838d9a43bd705491ea38bdcaa850 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 15:30:23 -0600 Subject: [PATCH 15/20] minds: POST /learn/release frees an abandoned turn's learn pin, wherever she is (Codex: a bool pin with no release keeps a checkpoint forever) The turn receipt reports timings.mind.pinned_at (the pinned checkpoint's position); the core sends {page, pinned_at, incarnation} back to release it. On a lane or parked: unpinned now. On flash: recorded on her record and applied when her checkpoints come back. The checkpoint stays as an ordinary one the budget may evict. Typed reply {release: released | released_on_flash | not_pinned | unknown_mind}; a replaced engine refuses (400). Receipt (qwen35-0.8b, M5, learning lane --train-dir, ~3.3k-token turns): pinned_at 3300; lane release -> released; again -> not_pinned; unknown page -> unknown_mind; a pinned mind moved off her lane (parked) -> released; wrong incarnation -> 400. Not exercised: the released_on_flash path. 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-common.cpp | 3 ++ tools/server/server-common.h | 1 + tools/server/server-context-minds.inc | 35 +++++++++++++++++++++ tools/server/server-context.cpp | 45 ++++++++++++++++++++++++++- tools/server/server-context.h | 2 ++ tools/server/server-mind.h | 11 +++++++ tools/server/server-task.h | 13 +++++++- tools/server/server.cpp | 2 ++ 8 files changed, 110 insertions(+), 2 deletions(-) diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index 69795c0427d4..30a5889cb078 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -94,6 +94,9 @@ json server_slot_stats::to_json() const { {"switch_ms", mind_switch_us / 1000.0}, {"generation", mind_generation}, }; + if (mind_pinned_at >= 0) { + base["mind"]["pinned_at"] = mind_pinned_at; + } } return base; diff --git a/tools/server/server-common.h b/tools/server/server-common.h index 20385cdca65f..9db5ba54a608 100644 --- a/tools/server/server-common.h +++ b/tools/server/server-common.h @@ -372,6 +372,7 @@ struct server_slot_stats { mind_from mind_came_from = mind_from::none; int64_t mind_switch_us = 0; uint64_t mind_generation = 0; + int64_t mind_pinned_at = -1; // learn_pin: the pinned checkpoint's position (the token /learn/release takes) uint64_t n_prompt_cached = 0; uint64_t n_prompt_processed = 0; diff --git a/tools/server/server-context-minds.inc b/tools/server/server-context-minds.inc index 7eb64c5211b5..85af53f89cdc 100644 --- a/tools/server/server-context-minds.inc +++ b/tools/server/server-context-minds.inc @@ -22,8 +22,39 @@ // write is in flight, or after it failed, she lives here and is inserted from here, never lost std::shared_ptr> ram; std::shared_ptr> written; // 0 pending, 1 landed, -1 failed + std::vector released; // pins released while she was on flash (positions) }; + // unpin her checkpoint at `at` in `cks`; true when one was pinned there + static bool unpin_at(std::list & cks, int64_t at) { + for (auto & c : cks) { + if (c.pinned && c.n_tokens == at) { + c.pinned = false; + return true; + } + } + return false; + } + + // An abandoned turn's learn pin, released wherever she is: on a lane, parked, or on flash (applied when her + // checkpoints come back). The checkpoint stays as an ordinary one: the budget may now evict it. + pin_release learn_release(mind_page page, int64_t at) { + for (auto & s : slots) { + if (s.page == page) { + return unpin_at(s.prompt.checkpoints, at) ? pin_release::released : pin_release::not_pinned; + } + } + resident_mind * m = find_mind(page); + if (m == nullptr) { + return pin_release::unknown_mind; + } + if (!m->file.empty() || m->ram) { + m->released.push_back(at); // her checkpoints are in her flash bytes + return pin_release::released_on_flash; + } + return unpin_at(m->prompt.checkpoints, at) ? pin_release::released : pin_release::not_pinned; + } + // her checkpoints as bytes beside her state: count, then per checkpoint its position fields, three sizes and // the three blobs (target, draft, speculative state) static constexpr size_t ckpt_header_bytes = sizeof(int64_t) + 3 * sizeof(int32_t) + 1 + 3 * sizeof(uint64_t); @@ -276,6 +307,10 @@ SRV_INF("mind %016llx%016llx back from %s: %.1f MiB inserted in %.2f ms\n", (unsigned long long) m.page.hi, (unsigned long long) m.page.lo, ram ? "RAM" : "flash", size / (1024.0 * 1024.0), (ggml_time_us() - t0) / 1000.0); m.prompt.checkpoints = std::move(checkpoints); + for (const int64_t at : m.released) { + unpin_at(m.prompt.checkpoints, at); // released while she was on flash + } + m.released.clear(); // her file is removed on the page-IO worker, ordered after its own write (it may still be landing) const std::string path = m.file; page_io->submit(path, [path] { std::error_code ec; std::filesystem::remove(path, ec); }); diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 8d10aef238ba..cc6ae8766c3d 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -2819,7 +2819,8 @@ struct server_context_impl { auto & kept = slot.prompt.checkpoints.emplace_back(std::move(cur)); if (slot.task->params.learn_pin && kept.n_tokens == (int64_t) slot.task->n_tokens() - 1) { - kept.pinned = true; // the core will learn this turn: kept until learned or abandoned + kept.pinned = true; // the core will learn this turn: kept until learned or released (/learn/release) + slot.stats.mind_pinned_at = kept.n_tokens; } // Continuum fork (CONTINUUM-ENGINE 4.7.3, placed checkpoints): her new view-end checkpoint @@ -3057,6 +3058,13 @@ struct server_context_impl { { page_io_done(std::move(task)); } break; + case SERVER_TASK_TYPE_LEARN_RELEASE: + { + auto res = std::make_unique(); + res->id = task.id; + res->outcome = learn_release(task.params.page, task.params.learn_release_at); + queue_results.send(std::move(res)); + } break; case SERVER_TASK_TYPE_MIND_PREFETCH: { const int64_t t0 = ggml_time_us(); @@ -6657,6 +6665,7 @@ void server_routes::init_routes() { return res; }; this->post_minds_prefetch = [this](const server_http_req & req) { return handle_minds_prefetch(req); }; + this->post_learn_release = [this](const server_http_req & req) { return handle_learn_release(req); }; this->post_learn_grants = [grant_route](const server_http_req & req) { return grant_route(req, "register"); }; this->revoke_learn_grant = [grant_route](const server_http_req & req) { return grant_route(req, "revoke"); }; @@ -7033,6 +7042,40 @@ std::unique_ptr server_routes::handle_slots_restore(const // Continuum fork: POST /minds/prefetch {"page": ""}: her state comes from flash into a parked sequence now, // ahead of her turn (server-context-minds.inc). The reply names where she is. +// an abandoned turn's learn pin, released (the core sends the turn receipt's mind.page and mind.pinned_at) +std::unique_ptr server_routes::handle_learn_release(const server_http_req & req) { + auto res = create_response(); + auto & rd = res->rd; + const json body = req.body.empty() ? json::object() : json::parse(req.body); + { + server_task task(SERVER_TASK_TYPE_LEARN_RELEASE); + task.id = rd.get_new_id(); + task.params.page = mind_page_parse(json_value(body, "page", std::string())); + task.params.learn_release_at = json_value(body, "pinned_at", (int64_t) -1); + if (json_value(body, "incarnation", (uint64_t) 0) != mind_incarnation()) { + res->error(format_error_response("incarnation names another engine: this release was for a replaced engine", ERROR_TYPE_INVALID_REQUEST)); + return res; + } + if (!task.params.page.valid() || task.params.learn_release_at < 0) { + res->error(format_error_response("page must name a mind and pinned_at the receipt's position", ERROR_TYPE_INVALID_REQUEST)); + return res; + } + rd.post_task(std::move(task)); + } + auto result = rd.next(req.should_stop); + if (!result) { + GGML_ASSERT(req.should_stop()); + return res; + } + if (result->is_error()) { + res->error(result->to_json()); + return res; + } + GGML_ASSERT(dynamic_cast(result.get()) != nullptr); + res->ok(result->to_json()); + return res; +} + std::unique_ptr server_routes::handle_minds_prefetch(const server_http_req & req) { auto res = create_response(); auto & rd = res->rd; diff --git a/tools/server/server-context.h b/tools/server/server-context.h index 0fabe3b530a6..c2dee6cd8edf 100644 --- a/tools/server/server-context.h +++ b/tools/server/server-context.h @@ -180,6 +180,7 @@ struct server_routes { server_http_context::handler_t get_learn_events; server_http_context::handler_t post_prompt_cache_limit; server_http_context::handler_t get_page_io, post_page_io_budget; // the KV page IO budget (server-page-io.h) + server_http_context::handler_t post_learn_release; // an abandoned turn's learn pin, released server_http_context::handler_t post_minds_prefetch; // the next mind, from flash into the pool (server-context-minds.inc) server_http_context::handler_t get_train; server_http_context::handler_t post_train; @@ -202,6 +203,7 @@ struct server_routes { std::unique_ptr handle_slots_restore(const server_http_req & req, int id_slot); std::unique_ptr handle_slots_erase(const server_http_req &, int id_slot); std::unique_ptr handle_minds_prefetch(const server_http_req &); + std::unique_ptr handle_learn_release(const server_http_req &); std::unique_ptr handle_embeddings_impl(const server_http_req & req, task_response_type res_type); std::unique_ptr handle_count_tokens(const llama_vocab * vocab, mtmd_context * mctx, const server_http_req & req, task_response_type res_type); diff --git a/tools/server/server-mind.h b/tools/server/server-mind.h index 21e73a87d531..3b986c2a2050 100644 --- a/tools/server/server-mind.h +++ b/tools/server/server-mind.h @@ -43,6 +43,17 @@ inline const char * mind_place_name(mind_place p) { return names[(size_t) p]; } +// What POST /learn/release did with a learn pin (frozen spellings): released: the checkpoint is unpinned now; +// released_on_flash: she is on flash, and it is unpinned when her checkpoints come back; not_pinned: no pinned +// checkpoint of hers is at that position (already learned, released, or never pinned); unknown_mind: the engine +// holds no mind by that page. +enum class pin_release : uint8_t { released, released_on_flash, not_pinned, unknown_mind }; + +inline const char * pin_release_name(pin_release r) { + static const char * names[] = { "released", "released_on_flash", "not_pinned", "unknown_mind" }; + return names[(size_t) r]; +} + // "page": 32 hexadecimal digits, dashes allowed (a UUID). Anything else is no page (the request is anonymous). inline mind_page mind_page_parse(const std::string & s) { mind_page p; diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 716423d9d3ac..066b1b229312 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -60,7 +60,8 @@ enum server_task_type { SERVER_TASK_TYPE_SLOT_SAVE, SERVER_TASK_TYPE_SLOT_RESTORE, SERVER_TASK_TYPE_SLOT_ERASE, - SERVER_TASK_TYPE_MIND_PREFETCH, // Continuum fork: the next mind, from flash into a parked sequence, ahead of her turn + SERVER_TASK_TYPE_MIND_PREFETCH, + SERVER_TASK_TYPE_LEARN_RELEASE, // Continuum fork: an abandoned turn's learn pin, released (server-context-minds.inc) // Continuum fork: the next mind, from flash into a parked sequence, ahead of her turn SERVER_TASK_TYPE_SLOT_PAGE_IO_DONE, // Continuum fork: a save's or restore's file IO finished on its worker SERVER_TASK_TYPE_SET_LORA, SERVER_TASK_TYPE_LOAD_LORA, @@ -190,6 +191,7 @@ struct task_params { mind_page page; // Continuum fork: the core will learn this turn later: pin the checkpoint at its prompt's end - 1 bool learn_pin = false; + int64_t learn_release_at = -1; // /learn/release: the pinned checkpoint's position (the turn receipt's mind.pinned_at) // Embeddings int32_t embd_normalize = 2; // (-1=none, 0=max absolute int16, 1=taxicab, 2=Euclidean/L2, >2=p-norm) @@ -723,6 +725,15 @@ struct server_task_result_control : server_task_result { } }; +// continuum: POST /learn/release's reply, typed (`release`: a pin_release_name spelling) +struct server_task_result_learn_release : server_task_result { + pin_release outcome = pin_release::unknown_mind; + + virtual json to_json() override { + return json { { "release", pin_release_name(outcome) } }; + } +}; + // continuum: POST /minds/prefetch's reply, typed (`mind`: a mind_place_name spelling) struct server_task_result_mind_prefetch : server_task_result { mind_place place = mind_place::minds_off; diff --git a/tools/server/server.cpp b/tools/server/server.cpp index 9fd8bcf50f5f..bfabf52427b2 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -231,6 +231,7 @@ int llama_server(common_params & params, int argc, char ** argv) { routes.get_page_io = models_routes->proxy_get; routes.post_page_io_budget = models_routes->proxy_post; routes.post_minds_prefetch = models_routes->proxy_post; + routes.post_learn_release = models_routes->proxy_post; routes.post_learn_residency = models_routes->proxy_post; routes.release_learn_residency = models_routes->proxy_post; routes.revoke_learn_residency = models_routes->proxy_post; @@ -305,6 +306,7 @@ int llama_server(common_params & params, int argc, char ** argv) { ctx_http.get ("/page-io", ex_wrapper(routes.get_page_io)); ctx_http.post("/page-io/budget", ex_wrapper(routes.post_page_io_budget)); ctx_http.post("/minds/prefetch", ex_wrapper(routes.post_minds_prefetch)); + ctx_http.post("/learn/release", ex_wrapper(routes.post_learn_release)); ctx_http.post("/learn/grants/revoke", ex_wrapper(routes.revoke_learn_grant)); ctx_http.get ("/train", ex_wrapper(routes.get_train)); ctx_http.post("/train", ex_wrapper(routes.post_train)); From 97019d6c765e343b771a016f5a1fb90e4ce12c8d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 15:39:51 -0600 Subject: [PATCH 16/20] minds: a learn pin is a unique id, never a position (Codex: two turns of the same length shared pinned_at, so a late release could free the newer turn's pin) common_prompt_checkpoint.pin: the id (per engine process; 0 = not pinned) replaces the bool, through eviction, the policy, the side learn's commit, the flash bytes (8 bytes) and the pending releases of a flashed mind. Receipt: timings.mind.pin (+ pinned_at, information only). POST /learn/release takes {page, pin, incarnation}. Also fixed: the close-checkpoint eviction in create_checkpoint erased pinned checkpoints, so a pin never survived her next turn. Receipt (qwen35-0.8b, M5, --train-dir, ~3.3k-token append-only turns; three minds through a two-lane pool): parked, no release while away -> after her return: released (pin survived); on flash (--cache-ram 60, 2 flashes), no release while away -> returns from flash with cache_n 3300 -> released; released while on flash -> released_on_flash -> returns whole -> not_pinned (applied on read-back); two pinned turns at the same position -> pins 1 and 2; releasing 1 -> released, 2 still pinned -> released. 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- common/common.h | 2 +- tools/server/server-checkpoint-policy.h | 6 ++--- tools/server/server-common.cpp | 3 ++- tools/server/server-common.h | 3 ++- tools/server/server-context-learn.inc | 4 +-- tools/server/server-context-minds.inc | 35 +++++++++++++------------ tools/server/server-context.cpp | 20 +++++++------- tools/server/server-mind.h | 7 ++--- tools/server/server-task.h | 2 +- 9 files changed, 44 insertions(+), 38 deletions(-) diff --git a/common/common.h b/common/common.h index 074a6b33422d..495ab6d1a4e7 100644 --- a/common/common.h +++ b/common/common.h @@ -1158,7 +1158,7 @@ struct common_prompt_checkpoint { // continuum: held for a turn the core will learn (its served prompt's end, n_prefix - 1): never evicted or // superseded until that turn is learned on a side sequence or abandoned - bool pinned = false; + uint64_t pin = 0; // continuum: the learn pin holding it (unique per engine process; 0: not pinned) // (optional) id of the task that created the checkpoint int id_task = -1; diff --git a/tools/server/server-checkpoint-policy.h b/tools/server/server-checkpoint-policy.h index ff9e417f05a2..6b5ccaeec3b7 100644 --- a/tools/server/server-checkpoint-policy.h +++ b/tools/server/server-checkpoint-policy.h @@ -34,10 +34,10 @@ typename List::iterator checkpoint_to_evict(List & checkpoints, int32_t view_end if (view_end >= 0 && checkpoints.size() >= 2) { ++victim; } - while (victim != checkpoints.end() && victim->pinned) { + while (victim != checkpoints.end() && victim->pin != 0) { ++victim; } - if (victim == checkpoints.end() && !checkpoints.empty() && !checkpoints.front().pinned) { + if (victim == checkpoints.end() && !checkpoints.empty() && checkpoints.front().pin == 0) { return checkpoints.begin(); // only her head is left unpinned } return victim; @@ -55,7 +55,7 @@ size_t erase_superseded_checkpoints(List & checkpoints, const Checkpoint & kept, const auto * head = &checkpoints.front(); size_t erased = 0; for (auto it = checkpoints.begin(); it != checkpoints.end();) { - if (&*it != head && it->id_task != id_task && !it->pinned) { + if (&*it != head && it->id_task != id_task && it->pin == 0) { on_erase(*it); it = checkpoints.erase(it); ++erased; diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index 30a5889cb078..5c1cd50d1e51 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -94,7 +94,8 @@ json server_slot_stats::to_json() const { {"switch_ms", mind_switch_us / 1000.0}, {"generation", mind_generation}, }; - if (mind_pinned_at >= 0) { + if (mind_pin != 0) { + base["mind"]["pin"] = mind_pin; base["mind"]["pinned_at"] = mind_pinned_at; } } diff --git a/tools/server/server-common.h b/tools/server/server-common.h index 9db5ba54a608..6ea33aa2441c 100644 --- a/tools/server/server-common.h +++ b/tools/server/server-common.h @@ -372,7 +372,8 @@ struct server_slot_stats { mind_from mind_came_from = mind_from::none; int64_t mind_switch_us = 0; uint64_t mind_generation = 0; - int64_t mind_pinned_at = -1; // learn_pin: the pinned checkpoint's position (the token /learn/release takes) + uint64_t mind_pin = 0; // learn_pin: the pin's id (what /learn/release takes; unique per engine process) + int64_t mind_pinned_at = -1; // learn_pin: the pinned checkpoint's position (information only) uint64_t n_prompt_cached = 0; uint64_t n_prompt_processed = 0; diff --git a/tools/server/server-context-learn.inc b/tools/server/server-context-learn.inc index 6bec9f23675a..bb92ec76bd9e 100644 --- a/tools/server/server-context-learn.inc +++ b/tools/server/server-context-learn.inc @@ -635,8 +635,8 @@ park_free.push_back(pending.side); if (pending.began && ok && !pending.drained) { for (auto & c : slot.prompt.checkpoints) { - if (c.pinned && c.n_tokens == n0) { - c.pinned = false; + if (c.pin != 0 && c.n_tokens == n0) { + c.pin = 0; } } } diff --git a/tools/server/server-context-minds.inc b/tools/server/server-context-minds.inc index 85af53f89cdc..cdb907a8aeb4 100644 --- a/tools/server/server-context-minds.inc +++ b/tools/server/server-context-minds.inc @@ -22,14 +22,14 @@ // write is in flight, or after it failed, she lives here and is inserted from here, never lost std::shared_ptr> ram; std::shared_ptr> written; // 0 pending, 1 landed, -1 failed - std::vector released; // pins released while she was on flash (positions) + std::vector released; // pins released while she was on flash }; - // unpin her checkpoint at `at` in `cks`; true when one was pinned there - static bool unpin_at(std::list & cks, int64_t at) { + // release learn pin `pin` in `cks`; true when a checkpoint held it + static bool unpin(std::list & cks, uint64_t pin) { for (auto & c : cks) { - if (c.pinned && c.n_tokens == at) { - c.pinned = false; + if (c.pin == pin) { + c.pin = 0; return true; } } @@ -38,10 +38,10 @@ // An abandoned turn's learn pin, released wherever she is: on a lane, parked, or on flash (applied when her // checkpoints come back). The checkpoint stays as an ordinary one: the budget may now evict it. - pin_release learn_release(mind_page page, int64_t at) { + pin_release learn_release(mind_page page, uint64_t pin) { for (auto & s : slots) { if (s.page == page) { - return unpin_at(s.prompt.checkpoints, at) ? pin_release::released : pin_release::not_pinned; + return unpin(s.prompt.checkpoints, pin) ? pin_release::released : pin_release::not_pinned; } } resident_mind * m = find_mind(page); @@ -49,15 +49,15 @@ return pin_release::unknown_mind; } if (!m->file.empty() || m->ram) { - m->released.push_back(at); // her checkpoints are in her flash bytes + m->released.push_back(pin); // her checkpoints are in her flash bytes return pin_release::released_on_flash; } - return unpin_at(m->prompt.checkpoints, at) ? pin_release::released : pin_release::not_pinned; + return unpin(m->prompt.checkpoints, pin) ? pin_release::released : pin_release::not_pinned; } // her checkpoints as bytes beside her state: count, then per checkpoint its position fields, three sizes and // the three blobs (target, draft, speculative state) - static constexpr size_t ckpt_header_bytes = sizeof(int64_t) + 3 * sizeof(int32_t) + 1 + 3 * sizeof(uint64_t); + static constexpr size_t ckpt_header_bytes = sizeof(int64_t) + 3 * sizeof(int32_t) + 4 * sizeof(uint64_t); static void ckpt_write(const std::list & cks, uint8_t * w) { auto put = [&](const void * p, size_t n) { std::memcpy(w, p, n); w += n; }; @@ -65,9 +65,9 @@ put(&count, sizeof(count)); for (const auto & c : cks) { const int32_t id = c.id_task, mn = c.pos_min, mx = c.pos_max; - const uint8_t pin = c.pinned ? 1 : 0; + const uint64_t pin = c.pin; const uint64_t a = c.data_tgt.size(), b = c.data_dft.size(), d = c.data_spec.size(); - put(&c.n_tokens, sizeof(c.n_tokens)); put(&id, 4); put(&mn, 4); put(&mx, 4); put(&pin, 1); + put(&c.n_tokens, sizeof(c.n_tokens)); put(&id, 4); put(&mn, 4); put(&mx, 4); put(&pin, 8); put(&a, 8); put(&b, 8); put(&d, 8); put(c.data_tgt.data(), a); put(c.data_dft.data(), b); put(c.data_spec.data(), d); } @@ -82,12 +82,12 @@ } for (uint64_t i = 0; i < count; ++i) { common_prompt_checkpoint c; - int32_t id, mn, mx; uint8_t pin; uint64_t a, b, d; - if (!get(&c.n_tokens, sizeof(c.n_tokens)) || !get(&id, 4) || !get(&mn, 4) || !get(&mx, 4) || !get(&pin, 1) || + int32_t id, mn, mx; uint64_t pin, a, b, d; + if (!get(&c.n_tokens, sizeof(c.n_tokens)) || !get(&id, 4) || !get(&mn, 4) || !get(&mx, 4) || !get(&pin, 8) || !get(&a, 8) || !get(&b, 8) || !get(&d, 8) || (uint64_t) (end - r) < a + b + d) { return false; } - c.id_task = id; c.pos_min = mn; c.pos_max = mx; c.pinned = pin != 0; + c.id_task = id; c.pos_min = mn; c.pos_max = mx; c.pin = pin; c.data_tgt.assign(r, r + a); r += a; c.data_dft.assign(r, r + b); r += b; c.data_spec.assign(r, r + d); r += d; @@ -99,6 +99,7 @@ std::vector park_free; // free parked sequence ids (sized once at load) std::vector minds; // parked and flashed minds (reserved once at load) uint64_t mind_clock = 0; + uint64_t learn_pin_clock = 0; // learn pins issued by this process (a pin's id; 0 is none) // At load: the parked ids are what the context reports beyond the lanes (llama_n_seq_max), never assumed. bool minds_init() { @@ -307,8 +308,8 @@ SRV_INF("mind %016llx%016llx back from %s: %.1f MiB inserted in %.2f ms\n", (unsigned long long) m.page.hi, (unsigned long long) m.page.lo, ram ? "RAM" : "flash", size / (1024.0 * 1024.0), (ggml_time_us() - t0) / 1000.0); m.prompt.checkpoints = std::move(checkpoints); - for (const int64_t at : m.released) { - unpin_at(m.prompt.checkpoints, at); // released while she was on flash + for (const uint64_t pin : m.released) { + unpin(m.prompt.checkpoints, pin); // released while she was on flash } m.released.clear(); // her file is removed on the page-IO worker, ordered after its own write (it may still be landing) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index cc6ae8766c3d..cab517bfe9b7 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -2735,12 +2735,12 @@ struct server_context_impl { } auto victim = cks.end(); for (auto it = cks.begin(); it != cks.end(); ++it) { - if (it != newest && !it->pinned) { + if (it != newest && it->pin == 0) { victim = it; break; } } - if (victim == cks.end() && newest != cks.end() && !newest->pinned) { + if (victim == cks.end() && newest != cks.end() && newest->pin == 0) { victim = newest; // all that is left } if (victim == cks.end()) { @@ -2763,7 +2763,8 @@ struct server_context_impl { const int64_t step = checkpoint_step(slot); int64_t last = -1; for (auto it = slot.prompt.checkpoints.begin(); it != slot.prompt.checkpoints.end(); ) { - if (it->id_task != id_task && last >= 0 && it->n_tokens <= last + step) { + // a checkpoint pinned for learning stays until learned or released, however close (/learn/release) + if (it->id_task != id_task && it->pin == 0 && last >= 0 && it->n_tokens <= last + step) { SLT_TRC(slot, "erasing context checkpoint too close to an earlier one (pos_min = %d, pos_max = %d, n_tokens = %" PRId64 ", size = %.3f MiB)\n", it->pos_min, it->pos_max, it->n_tokens, (float) it->size() / 1024 / 1024); @@ -2819,7 +2820,8 @@ struct server_context_impl { auto & kept = slot.prompt.checkpoints.emplace_back(std::move(cur)); if (slot.task->params.learn_pin && kept.n_tokens == (int64_t) slot.task->n_tokens() - 1) { - kept.pinned = true; // the core will learn this turn: kept until learned or released (/learn/release) + kept.pin = ++learn_pin_clock; // the core will learn this turn: kept until learned or released (/learn/release) + slot.stats.mind_pin = kept.pin; slot.stats.mind_pinned_at = kept.n_tokens; } @@ -3062,7 +3064,7 @@ struct server_context_impl { { auto res = std::make_unique(); res->id = task.id; - res->outcome = learn_release(task.params.page, task.params.learn_release_at); + res->outcome = learn_release(task.params.page, task.params.learn_release_pin); queue_results.send(std::move(res)); } break; case SERVER_TASK_TYPE_MIND_PREFETCH: @@ -7042,7 +7044,7 @@ std::unique_ptr server_routes::handle_slots_restore(const // Continuum fork: POST /minds/prefetch {"page": ""}: her state comes from flash into a parked sequence now, // ahead of her turn (server-context-minds.inc). The reply names where she is. -// an abandoned turn's learn pin, released (the core sends the turn receipt's mind.page and mind.pinned_at) +// an abandoned turn's learn pin, released (the core sends the turn receipt's mind.page and mind.pin) std::unique_ptr server_routes::handle_learn_release(const server_http_req & req) { auto res = create_response(); auto & rd = res->rd; @@ -7051,13 +7053,13 @@ std::unique_ptr server_routes::handle_learn_release(const server_task task(SERVER_TASK_TYPE_LEARN_RELEASE); task.id = rd.get_new_id(); task.params.page = mind_page_parse(json_value(body, "page", std::string())); - task.params.learn_release_at = json_value(body, "pinned_at", (int64_t) -1); + task.params.learn_release_pin = json_value(body, "pin", (uint64_t) 0); if (json_value(body, "incarnation", (uint64_t) 0) != mind_incarnation()) { res->error(format_error_response("incarnation names another engine: this release was for a replaced engine", ERROR_TYPE_INVALID_REQUEST)); return res; } - if (!task.params.page.valid() || task.params.learn_release_at < 0) { - res->error(format_error_response("page must name a mind and pinned_at the receipt's position", ERROR_TYPE_INVALID_REQUEST)); + if (!task.params.page.valid() || task.params.learn_release_pin == 0) { + res->error(format_error_response("page must name a mind and pin the turn receipt's mind.pin", ERROR_TYPE_INVALID_REQUEST)); return res; } rd.post_task(std::move(task)); diff --git a/tools/server/server-mind.h b/tools/server/server-mind.h index 3b986c2a2050..c6570edfe12d 100644 --- a/tools/server/server-mind.h +++ b/tools/server/server-mind.h @@ -44,9 +44,10 @@ inline const char * mind_place_name(mind_place p) { } // What POST /learn/release did with a learn pin (frozen spellings): released: the checkpoint is unpinned now; -// released_on_flash: she is on flash, and it is unpinned when her checkpoints come back; not_pinned: no pinned -// checkpoint of hers is at that position (already learned, released, or never pinned); unknown_mind: the engine -// holds no mind by that page. +// released_on_flash: she is on flash, and it is unpinned when her checkpoints come back; not_pinned: no checkpoint +// of hers holds that pin (already learned, released, or invalidated by a prompt that diverged before it); +// unknown_mind: the engine holds no mind by that page. A pin is its id (mind.pin on the turn receipt), never a +// position: two turns of the same length never share one. enum class pin_release : uint8_t { released, released_on_flash, not_pinned, unknown_mind }; inline const char * pin_release_name(pin_release r) { diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 066b1b229312..e7ae1eeff1f6 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -191,7 +191,7 @@ struct task_params { mind_page page; // Continuum fork: the core will learn this turn later: pin the checkpoint at its prompt's end - 1 bool learn_pin = false; - int64_t learn_release_at = -1; // /learn/release: the pinned checkpoint's position (the turn receipt's mind.pinned_at) + uint64_t learn_release_pin = 0; // /learn/release: the pin to release (the turn receipt's mind.pin) // Embeddings int32_t embd_normalize = 2; // (-1=none, 0=max absolute int16, 1=taxicab, 2=Euclidean/L2, >2=p-norm) From 6f6221a24aafe3e31dd07bbcd5e5cae94876ab8c Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 18:32:05 -0600 Subject: [PATCH 17/20] minds: slot erase asserts its own result again (my e8ee0b2f4 put the prefetch result type on the ERASE handler: every /slots/:id?action=erase aborted the server, caught by Windows CI test_slot_erase); the prefetch handler gets the assertion it never had My e8ee0b2f4 message also claimed the prefetch handler 'asserted the wrong result type (copied from slot erase)': wrong. It had no assertion; my edit replaced the next function's. Retracted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index cab517bfe9b7..29537a88f4cf 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -7106,6 +7106,7 @@ std::unique_ptr server_routes::handle_minds_prefetch(const res->error(result->to_json()); return res; } + GGML_ASSERT(dynamic_cast(result.get()) != nullptr); res->ok(result->to_json()); return res; } @@ -7136,7 +7137,7 @@ std::unique_ptr server_routes::handle_slots_erase(const se return res; } - GGML_ASSERT(dynamic_cast(result.get()) != nullptr); + GGML_ASSERT(dynamic_cast(result.get()) != nullptr); res->ok(result->to_json()); return res; } From 0df8dc443f60bdbeba8fb1a93e4182e2dea8f77f Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 18:43:22 -0600 Subject: [PATCH 18/20] checkpoint policy test: its ckpt carries the learn pin the policy reads (Ubuntu CI: 'struct ckpt has no member named pin'), plus the case it guards: a pinned checkpoint is never the victim and an all-pinned store yields end() Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/test-server-checkpoint-policy.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/tests/test-server-checkpoint-policy.cpp b/tests/test-server-checkpoint-policy.cpp index 5943b236654a..73d230d41002 100644 --- a/tests/test-server-checkpoint-policy.cpp +++ b/tests/test-server-checkpoint-policy.cpp @@ -22,6 +22,7 @@ struct ckpt { int64_t n_tokens; int id_task; int serial; // identity: a checkpoint is the same one only if its serial matches + uint64_t pin = 0; // nonzero: held for learning (common.h server_prompt_checkpoint::pin) }; using store = std::list; @@ -51,6 +52,23 @@ static void head_survives_a_full_store_across_many_acts() { } } +// regression for the pin added on #139: a checkpoint pinned for learning is never the victim, and a store whose +// every candidate is pinned yields end() so the caller defers instead of erasing a learner's checkpoint +static void a_pinned_checkpoint_is_never_evicted() { + store s; + for (int i = 0; i < 4; ++i) { + s.push_back({ 9655 + i * 1000, i, i }); + } + s.front().pin = 0; + std::next(s.begin(), 1)->pin = 7; + auto victim = checkpoint_to_evict(s, /*view_end=*/100000); + require(victim != s.end() && victim->pin == 0, "the victim is unpinned"); + for (auto & c : s) { + c.pin = 1 + (uint64_t) c.serial; + } + require(checkpoint_to_evict(s, 100000) == s.end(), "all pinned: no victim"); +} + static void the_pre_fix_rule_loses_the_head() { const size_t capacity = 4; store s; @@ -142,6 +160,7 @@ static void a_cold_prompt_with_view_spans_makes_her_head() { int main() { a_cold_prompt_with_view_spans_makes_her_head(); + a_pinned_checkpoint_is_never_evicted(); head_survives_a_full_store_across_many_acts(); the_pre_fix_rule_loses_the_head(); capacity_one_keeps_only_what_fits(); From 7643fb9369c6cd6f89ce53e551eb393c28ddae69 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 20:58:48 -0600 Subject: [PATCH 19/20] minds: /props reports the parked CAPACITY (fixed) and the free count apart; a mind is never purged when no legal move exists (Codex's two blockers on the exact pair 0df8dc443/d5c4e5dca) 1. parked_ids was park_free.size(), the current free count: the first mind that parked changed it, and the core's next discovery of the same engine failed with MindsMismatch. It is now the fixed capacity (sequences beyond the lanes while minds are on), and parked_free is the free count. The core decodes the new field as unknown (ignored). 2. try_clear_idle_slots: when neither the coldest parked mind nor an idle lane's mind could go to flash, the code restored her prompt and FELL THROUGH to the legacy purge, which cleared her. With minds on, a slot holding a mind is skipped by that loop (no legal move -> false); an anonymous slot's cached prompt may still be cleared. tests/unit/test_minds.py (the first server test of resident minds; harness gains n_minds/--minds): the capacity holds across park and unpark while the free count moves; a returning mind comes back from 'parked' with her prompt from cache. Not run here: it runs in this window's build or CI. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context.cpp | 13 +++++- tools/server/tests/unit/test_minds.py | 65 +++++++++++++++++++++++++++ tools/server/tests/utils.py | 3 ++ 3 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 tools/server/tests/unit/test_minds.py diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 29537a88f4cf..c8c57580a280 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1948,6 +1948,12 @@ struct server_context_impl { if (slot.is_processing()) { continue; } + // a mind is never purged: when neither a parked mind nor an idle lane's mind could go to flash above, + // there is no legal move for her and this returns false (Codex on #139); an anonymous slot's cached + // prompt (no mind) may still be cleared + if (minds_on() && slot.page.valid()) { + continue; + } if (slot.prompt.n_tokens() > 0) { SRV_WRN("purging slot %d with %zu tokens\n", slot.id, slot.prompt.tokens.size()); @@ -5076,7 +5082,12 @@ server_context_meta server_context::get_meta() const { { "resident_minds", json { { "enabled", impl->minds_on() }, { "lanes", impl->params_base.n_parallel }, - { "parked_ids", (int64_t) impl->park_free.size() }, + // fixed capacity (the context's sequences beyond the lanes, while minds are on): the core compares it + // across discoveries, so it must not move when a mind parks (Codex on #139/#6087); the free count is + // its own field + { "parked_ids", (int64_t) (impl->params_base.n_minds > 0 + ? llama_n_seq_max(impl->ctx_tgt) - impl->params_base.n_parallel : 0) }, + { "parked_free", (int64_t) impl->park_free.size() }, { "incarnation", mind_incarnation() }, } }, }, diff --git a/tools/server/tests/unit/test_minds.py b/tools/server/tests/unit/test_minds.py new file mode 100644 index 000000000000..c06ab1ecfe07 --- /dev/null +++ b/tools/server/tests/unit/test_minds.py @@ -0,0 +1,65 @@ +import tempfile +import pytest +from utils import * + +# Resident minds (the fast single lane): one decode lane serves several minds, each parked in the pool by sequence +# id while another decodes, and switched back without re-prefill. These run a real tiny model. + +server: ServerProcess + +PROMPT = "Once upon a time in a land far away, there lived a brave knight who traveled across mountains and rivers. " * 3 +MIND_A = "0" * 31 + "a" +MIND_B = "0" * 31 + "b" + + +@pytest.fixture(autouse=True) +def create_server(): + global server + server = ServerPreset.tinyllama2() + server.n_slots = 1 # one decode lane + server.kv_unified = True # parked minds share the pool's cells by sequence id + server.n_minds = 2 + server.n_ctx = 2048 + server.slot_save_path = tempfile.mkdtemp() + "/" + + +def complete(page: str): + res = server.make_request("POST", "/completion", data={ + "prompt": PROMPT, "n_predict": 4, "temperature": 0.0, "cache_prompt": True, "page": page, + }) + assert res.status_code == 200, res.body + return res.body + + +def resident_minds(): + res = server.make_request("GET", "/props") + assert res.status_code == 200 + return res.body["context_geometry"]["resident_minds"] + + +# what this catches: /props reported the parked ids as the CURRENT free count, so the first mind that parked +# changed the descriptor and the core's next discovery of the same engine failed (MindsMismatch). The capacity +# must hold across park and unpark; the free count is its own field. +def test_the_parked_capacity_holds_across_park_and_unpark(): + server.start() + complete(MIND_A) + before = resident_minds() + assert before["enabled"] is True and before["parked_ids"] > 0 + complete(MIND_B) # A leaves the one lane for a parked sequence + parked = resident_minds() + assert parked["parked_ids"] == before["parked_ids"] + assert parked["parked_free"] == before["parked_free"] - 1 + complete(MIND_A) # A back onto the lane, B parked + after = resident_minds() + assert after["parked_ids"] == before["parked_ids"] + + +# what this catches: a switch that re-prefills. A mind returning from her parked sequence is inserted whole: the +# receipt says parked and her prompt is served from cache. +def test_a_returning_mind_comes_back_from_her_parked_sequence_without_prefill(): + server.start() + complete(MIND_A) + complete(MIND_B) + back = complete(MIND_A) + assert back["timings"]["mind"]["from"] == "parked", back["timings"] + assert back["timings"]["cache_n"] > 0, back["timings"] diff --git a/tools/server/tests/utils.py b/tools/server/tests/utils.py index cb66d76874f4..b5722e14a3db 100644 --- a/tools/server/tests/utils.py +++ b/tools/server/tests/utils.py @@ -75,6 +75,7 @@ class ServerProcess: n_predict: int | None = None n_prompts: int | None = 0 slot_save_path: str | None = None + n_minds: int | None = None id_slot: int | None = None cache_prompt: bool | None = None n_slots: int | None = None @@ -225,6 +226,8 @@ def start(self, timeout_seconds: int = DEFAULT_HTTP_TIMEOUT) -> None: server_args.extend(["-fa", self.fa]) if self.n_predict: server_args.extend(["--n-predict", self.n_predict]) + if self.n_minds: + server_args.extend(["--minds", self.n_minds]) if self.slot_save_path: server_args.extend(["--slot-save-path", self.slot_save_path]) if self.n_ga: From 945a742c3bc5b3e94845356b828e22422a53b52b Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 20:59:55 -0600 Subject: [PATCH 20/20] minds: page and checkpoint lengths are checked part by part, never as an overflowing sum; a failed flash write's RAM copy counts against the host budget; a flash-out copy is admitted before it is allocated (Codex's remaining P1s on #139) 3. budget: checkpoint_bytes counted a mind's RAM copy only as in-flight, so one whose flash write FAILED (she lives in RAM for good) was outside the budget; it now counts as resident. flash_out allocated her full copy without admission; it now checks host_budget for what the copy adds (her state + header; her checkpoints are already counted) and, over budget, refuses: she stays where she is. 4. lengths: flash_insert accepted size == 24 + h0 + h1 + h2 and ckpt_read (end - r) < a + b + d; a corrupt or crafted length could wrap the u64 sum into a 'fitting' total and index far out of bounds. lengths_fit() checks each part against what is left; the exact total is compared only after that. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context-minds.inc | 26 ++++++++++++++++++++++++-- tools/server/server-context.cpp | 5 ++++- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/tools/server/server-context-minds.inc b/tools/server/server-context-minds.inc index cdb907a8aeb4..925687c0aab2 100644 --- a/tools/server/server-context-minds.inc +++ b/tools/server/server-context-minds.inc @@ -73,6 +73,18 @@ } } + // whether lengths `lens`, taken in order, fit within `room` bytes: each is checked against what is left, so no + // sum is formed and a corrupt or crafted length cannot wrap past 2^64 into a "fitting" total (Codex on #139) + static bool lengths_fit(uint64_t room, std::initializer_list lens) { + for (const uint64_t n : lens) { + if (n > room) { + return false; + } + room -= n; + } + return true; + } + static bool ckpt_read(const uint8_t * r, uint64_t n, std::list & out) { const uint8_t * end = r + n; auto get = [&](void * p, size_t k) { if ((size_t) (end - r) < k) { return false; } std::memcpy(p, r, k); r += k; return true; }; @@ -84,7 +96,7 @@ common_prompt_checkpoint c; int32_t id, mn, mx; uint64_t pin, a, b, d; if (!get(&c.n_tokens, sizeof(c.n_tokens)) || !get(&id, 4) || !get(&mn, 4) || !get(&mx, 4) || !get(&pin, 8) || - !get(&a, 8) || !get(&b, 8) || !get(&d, 8) || (uint64_t) (end - r) < a + b + d) { + !get(&a, 8) || !get(&b, 8) || !get(&d, 8) || !lengths_fit((uint64_t) (end - r), { a, b, d })) { return false; } c.id_task = id; c.pos_min = mn; c.pos_max = mx; c.pin = pin; @@ -185,6 +197,14 @@ for (const auto & c : cold->prompt.checkpoints) { n_ck += ckpt_header_bytes + c.data_tgt.size() + c.data_dft.size() + c.data_spec.size(); } + // admitted before it is allocated: her checkpoints are host bytes already counted, so what this copy adds is + // her state and the header; over the host budget she is not copied out and stays where she is (Codex on #139) + const size_t adds = 3 * sizeof(uint64_t) + n_tgt + n_dft; + if (host_budget > 0 && checkpoint_bytes(true) + adds > host_budget) { + SRV_WRN("mind %016llx: copying her out would exceed the host budget (%zu + %zu > %zu); she stays where she is\n", + (unsigned long long) cold->page.hi, checkpoint_bytes(true), adds, host_budget); + return false; + } bytes->resize(3 * sizeof(uint64_t) + n_tgt + n_dft + n_ck); uint8_t * w = bytes->data(); const uint64_t h[3] = { n_tgt, n_dft, n_ck }; @@ -271,7 +291,9 @@ } uint64_t h[3]; std::memcpy(h, base, sizeof(h)); - if (size != 3 * sizeof(uint64_t) + h[0] + h[1] + h[2]) { + // exact: the three parts fill the rest of her bytes, checked part by part (no overflowing sum) + const uint64_t body = size - 3 * sizeof(uint64_t); + if (!lengths_fit(body, { h[0], h[1], h[2] }) || h[0] + h[1] + h[2] != body) { return false; } const uint8_t * r = base + sizeof(h); diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index c8c57580a280..570c047a5465 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -2682,7 +2682,10 @@ struct server_context_impl { for (const auto & c : m.prompt.checkpoints) { b += c.size(); } - if (in_flight && m.ram) { + // a RAM copy whose flash write FAILED is where she lives now (minds_reap dropped `written`): resident, + // counted always; one whose write is still in flight is transient, counted with `in_flight` (Codex on #139) + const bool failed_write = m.ram && !m.written; + if (m.ram && (in_flight || failed_write)) { b += m.ram->size(); } }