From bbef4db58d58ff380ca85415be432c7560c0a122 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 27 Oct 2026 07:19:44 -0500 Subject: [PATCH 1/9] server: a disk tier for the prompt cache (--cache-disk DIR, --cache-disk-mib N) An entry evicted from --cache-ram was dropped, so a mind whose saved conversation aged out re-prefilled it whole. With --cache-disk the oldest resident entry is written to DIR instead (its sequence state and its checkpoints' data); its tokens and checkpoint positions stay in RAM so a lookup still matches it, and a match reads it back and removes the file. An entry larger than the whole RAM tier goes straight to disk instead of displacing every other entry; the disk tier evicts its own oldest at its limit. States another engine instance left in DIR are removed at start; this instance's files are removed when the cache is destroyed. Why: on the M5 (2026-10-27) the RAM tier was 11,961 MiB holding 2.4-6.6 GiB entries; macOS compressed 13-15 GB of the engine and swapped 11.9 of 13.3 GB, so the cache the engine believed resident was paying decompression and swap reads, and 40+ entries were dropped ("removing oldest entry"), one 3,845 MiB state skipped outright. A small RAM tier that stays uncompressed plus a disk tier read at SSD speed keeps every resident's conversation restorable. Logs: "spilled prompt cache entry to disk: N tokens, X MiB in T ms" and "restored prompt cache entry from disk: ...", the receipts for the live read. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo (cherry picked from commit d52277a6b6adece3545cf6141ac744925330f412) --- common/arg.cpp | 15 +++ common/common.h | 2 + tools/server/server-context.cpp | 4 + tools/server/server-task.cpp | 231 ++++++++++++++++++++++++++++---- tools/server/server-task.h | 42 ++++++ 5 files changed, 266 insertions(+), 28 deletions(-) diff --git a/common/arg.cpp b/common/arg.cpp index 4353464d2847..56b19576fe07 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -1714,6 +1714,21 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.cache_ram_mib = value; } ).set_env("LLAMA_ARG_CACHE_RAM").set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI})); + add_opt(common_arg( + {"--cache-disk"}, "DIR", + "a disk tier for the prompt cache: an entry evicted from --cache-ram is written here instead of dropped, " + "and read back when a prompt matches it (default: none)", + [](common_params & params, const std::string & value) { + params.cache_disk_dir = value; + } + ).set_env("LLAMA_ARG_CACHE_DISK").set_examples({LLAMA_EXAMPLE_SERVER})); + add_opt(common_arg( + {"--cache-disk-mib"}, "N", + string_format("the prompt cache disk tier's size limit in MiB (default: %d, 0 - no limit)", params.cache_disk_mib), + [](common_params & params, int value) { + params.cache_disk_mib = value; + } + ).set_env("LLAMA_ARG_CACHE_DISK_MIB").set_examples({LLAMA_EXAMPLE_SERVER})); add_opt(common_arg( {"-kvu", "--kv-unified"}, {"-no-kvu", "--no-kv-unified"}, diff --git a/common/common.h b/common/common.h index f57bafb83295..9ef7d388efce 100644 --- a/common/common.h +++ b/common/common.h @@ -625,6 +625,8 @@ struct common_params { int32_t n_ctx_checkpoints = 32; // max number of context checkpoints per slot int32_t checkpoint_min_step = 8192; // minimum spacing between context checkpoints int32_t cache_ram_mib = 8192; // -1 = no limit, 0 - disable, 1 = 1 MiB, etc. + std::string cache_disk_dir; // the prompt cache's disk tier, empty = none + int32_t cache_disk_mib = 0; // the disk tier's size limit in MiB, 0 = no limit std::string hostname = "127.0.0.1"; std::string public_path = ""; // NOLINT diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index ba7b2093053a..90a2c411abca 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1553,6 +1553,10 @@ 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); + if (!params_base.cache_disk_dir.empty() && !prompt_cache->set_disk(params_base.cache_disk_dir, params_base.cache_disk_mib)) { + SRV_ERR("%s", "the prompt cache disk tier could not be set up, refusing to start without it\n"); + return false; + } } else { SRV_TRC("%s", "prompt cache is disabled - use `--cache-ram N` to enable it\n"); } diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index e502d728cda1..ba9836669df2 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -10,6 +10,11 @@ #include "speculative.h" #include "server-common.h" +#include +#include +#include +#include + #include // @@ -1756,16 +1761,188 @@ size_t server_prompt_cache::size() const { return res; } +size_t server_prompt_cache::disk_size() const { + size_t res = 0; + + for (const auto & state : states) { + res += state.spill_size; + } + + return res; +} + size_t server_prompt_cache::n_tokens() const { size_t res = 0; for (const auto & state : states) { - res += state.prompt.n_tokens(); + if (!state.spilled()) { + res += state.prompt.n_tokens(); + } } return res; } +server_prompt_cache::~server_prompt_cache() { + for (const auto & state : states) { + if (state.spilled()) { + std::error_code ec; + std::filesystem::remove(state.spill_path, ec); + } + } +} + +bool server_prompt_cache::set_disk(const std::string & dir, int32_t limit_mib) { + std::error_code ec; + std::filesystem::create_directories(dir, ec); + if (ec) { + SRV_ERR("prompt cache disk tier: cannot create %s: %s\n", dir.c_str(), ec.message().c_str()); + return false; + } + // a state written by another engine instance is not this one's: its slot ids, adapters and + // tokens were never recorded here, so it could never be matched, only leak + for (const auto & entry : std::filesystem::directory_iterator(dir, ec)) { + if (entry.path().extension() == ".state") { + std::filesystem::remove(entry.path(), ec); + } + } + disk_dir = dir; + disk_limit = 1024ull*1024ull*(limit_mib < 0 ? 0 : limit_mib); + SRV_INF("prompt cache disk tier: %s, size limit: %d MiB\n", dir.c_str(), limit_mib); + return true; +} + +static bool write_block(FILE * f, const std::vector & data) { + const uint64_t n = data.size(); + return fwrite(&n, sizeof(n), 1, f) == 1 && (n == 0 || fwrite(data.data(), 1, n, f) == n); +} + +static bool read_block(FILE * f, std::vector & data) { + uint64_t n = 0; + if (fread(&n, sizeof(n), 1, f) != 1) { + return false; + } + data.resize(n); + return n == 0 || fread(data.data(), 1, n, f) == n; +} + +bool server_prompt_cache::spill(server_prompt_cache_state & state) { + if (disk_dir.empty() || state.spilled()) { + return false; + } + const size_t bytes = state.size(); + if (disk_limit > 0 && bytes > disk_limit) { + return false; + } + while (disk_limit > 0 && disk_size() + bytes > disk_limit) { + auto oldest = std::find_if(states.begin(), states.end(), [](const server_prompt_cache_state & s) { return s.spilled(); }); + if (oldest == states.end()) { + break; + } + SRV_WRN(" - disk tier full, removing oldest spilled entry (size = %.3f MiB)\n", oldest->spill_size / (1024.0 * 1024.0)); + erase(oldest); + } + + const auto t0 = std::chrono::steady_clock::now(); + const std::string path = disk_dir + "/" + std::to_string(spill_seq++) + ".state"; + FILE * f = fopen(path.c_str(), "wb"); + if (f == nullptr) { + SRV_ERR("prompt cache disk tier: cannot open %s\n", path.c_str()); + return false; + } + bool ok = write_block(f, state.data.main) && write_block(f, state.data.drft); + for (const auto & ckpt : state.prompt.checkpoints) { + ok = ok && write_block(f, ckpt.data_tgt) && write_block(f, ckpt.data_dft) && write_block(f, ckpt.data_spec); + } + ok = (fclose(f) == 0) && ok; + if (!ok) { + SRV_ERR("prompt cache disk tier: failed writing %s\n", path.c_str()); + std::error_code ec; + std::filesystem::remove(path, ec); + return false; + } + + state.data.main.clear(); + state.data.main.shrink_to_fit(); + state.data.drft.clear(); + state.data.drft.shrink_to_fit(); + for (auto & ckpt : state.prompt.checkpoints) { + ckpt.data_tgt.clear(); + ckpt.data_tgt.shrink_to_fit(); + ckpt.data_dft.clear(); + ckpt.data_dft.shrink_to_fit(); + ckpt.data_spec.clear(); + ckpt.data_spec.shrink_to_fit(); + } + state.spill_path = path; + state.spill_size = bytes; + + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + SRV_INF(" - spilled prompt cache entry to disk: %d tokens, %.3f MiB in %.1f ms\n", + state.prompt.n_tokens(), bytes / (1024.0 * 1024.0), ms); + return true; +} + +bool server_prompt_cache::unspill(server_prompt_cache_state & state) { + if (!state.spilled()) { + return true; + } + const auto t0 = std::chrono::steady_clock::now(); + FILE * f = fopen(state.spill_path.c_str(), "rb"); + if (f == nullptr) { + SRV_ERR("prompt cache disk tier: cannot open %s\n", state.spill_path.c_str()); + return false; + } + bool ok = read_block(f, state.data.main) && read_block(f, state.data.drft); + for (auto & ckpt : state.prompt.checkpoints) { + ok = ok && read_block(f, ckpt.data_tgt) && read_block(f, ckpt.data_dft) && read_block(f, ckpt.data_spec); + } + fclose(f); + if (!ok) { + SRV_ERR("prompt cache disk tier: failed reading %s\n", state.spill_path.c_str()); + return false; + } + std::error_code ec; + std::filesystem::remove(state.spill_path, ec); + const size_t bytes = state.spill_size; + state.spill_path.clear(); + state.spill_size = 0; + + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + SRV_INF(" - restored prompt cache entry from disk: %d tokens, %.3f MiB in %.1f ms\n", + state.prompt.n_tokens(), bytes / (1024.0 * 1024.0), ms); + return true; +} + +std::list::iterator server_prompt_cache::erase(std::list::iterator it) { + if (it->spilled()) { + std::error_code ec; + std::filesystem::remove(it->spill_path, ec); + } + return states.erase(it); +} + +bool server_prompt_cache::evict_oldest_resident() { + // a state larger than the whole RAM tier leaves first: it cannot stay, so evicting older + // states for it would only push them to disk as well + auto oldest = std::find_if(states.begin(), states.end(), [this](const server_prompt_cache_state & s) { + return !s.spilled() && limit_size > 0 && s.size() > limit_size; + }); + if (oldest == states.end()) { + oldest = std::find_if(states.begin(), states.end(), [](const server_prompt_cache_state & s) { return !s.spilled(); }); + } + if (oldest == states.end()) { + return false; + } + if (spill(*oldest)) { + return true; + } + SRV_WRN(" - making room for prompt cache entry, removing oldest entry (size = %.3f MiB)\n", + oldest->size() / (1024.0 * 1024.0)); + erase(oldest); + return true; +} + server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & prompt, const lora_active_set & lora, size_t state_size_tgt, size_t state_size_dft) { // first check if the current state is contained fully in the cache for (auto it = states.begin(); it != states.end(); ++it) { @@ -1788,8 +1965,10 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro const size_t state_size_new = state_size_tgt + state_size_dft + checkpoints_size; - // skip over-limit entries to avoid disturbing the cache - if (limit_size > 0 && state_size_new > limit_size) { + // skip over-limit entries to avoid disturbing the cache; with a disk tier that can hold it, + // the entry is taken and `update` spills it once the caller has filled it + const bool disk_holds = !disk_dir.empty() && (disk_limit == 0 || state_size_new <= disk_limit); + if (limit_size > 0 && state_size_new > limit_size && !disk_holds) { SRV_WRN(" - prompt state size %.3f MiB exceeds cache size limit %.3f MiB, skipping\n", state_size_new / (1024.0 * 1024.0), limit_size / (1024.0 * 1024.0)); return nullptr; @@ -1802,19 +1981,17 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro if (it->lora == lora && len == (int) it->prompt.tokens.size()) { SRV_TRC(" - removing obsolete cached prompt with length %d\n", len); - it = states.erase(it); + it = erase(it); } else { ++it; } } if (limit_size > 0) { - // make room before allocating the new vectors to avoid breaching the limit - while (!states.empty() && size() + state_size_new > limit_size) { - SRV_WRN(" - making room for prompt cache entry, removing oldest entry (size = %.3f MiB)\n", - states.front().size() / (1024.0 * 1024.0)); - - states.pop_front(); + // make room before allocating the new vectors to avoid breaching the limit; an entry + // larger than the whole RAM tier goes to disk itself in `update`, displacing nothing + const size_t room_needed = state_size_new > limit_size ? 0 : state_size_new; + while (size() + room_needed > limit_size && evict_oldest_resident()) { } } @@ -1853,14 +2030,13 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro } void server_prompt_cache::evict_lora(const llama_adapter_lora * adapter) { - states.remove_if([adapter](const server_prompt_cache_state & state) { - for (const auto & [ptr, scale] : state.lora) { - if (ptr == adapter) { - return true; - } + for (auto it = states.begin(); it != states.end();) { + bool uses = false; + for (const auto & [ptr, scale] : it->lora) { + uses = uses || ptr == adapter; } - return false; - }); + it = uses ? erase(it) : std::next(it); + } } bool server_prompt_cache::load(server_prompt & prompt, const lora_active_set & lora, const server_tokens & tokens_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot) { @@ -1901,6 +2077,11 @@ bool server_prompt_cache::load(server_prompt & prompt, const lora_active_set & l if (it_best != states.end()) { SRV_TRC(" - found better prompt with f_keep = %.3f, f_sim = %.3f\n", f_keep_best, f_sim_best); + if (!unspill(*it_best)) { + erase(it_best); + return false; + } + { auto & data = it_best->data.main; @@ -1945,10 +2126,7 @@ bool server_prompt_cache::load(server_prompt & prompt, const lora_active_set & l void server_prompt_cache::update() { if (limit_size > 0) { - while (!states.empty() && size() > limit_size) { - SRV_WRN(" - cache size limit reached, removing oldest entry (size = %.3f MiB)\n", states.front().size() / (1024.0 * 1024.0)); - - states.pop_front(); + while (size() > limit_size && evict_oldest_resident()) { } } @@ -1959,16 +2137,13 @@ void server_prompt_cache::update() { const size_t limit_tokens_cur = limit_size > 0 ? std::max(limit_tokens, limit_size/size_per_token) : limit_tokens; if (limit_tokens > 0) { - while (!states.empty() && n_tokens() > limit_tokens_cur) { - SRV_WRN(" - cache token limit (%zu, est: %zu) reached, removing oldest entry (size = %.3f MiB)\n", - limit_tokens, limit_tokens_cur, states.front().size() / (1024.0 * 1024.0)); - - states.pop_front(); + while (n_tokens() > limit_tokens_cur && evict_oldest_resident()) { } } - SRV_TRC(" - cache state: %zu prompts, %.3f MiB (limits: %.3f MiB, %zu tokens, %zu est)\n", - states.size(), size() / (1024.0 * 1024.0), limit_size / (1024.0 * 1024.0), limit_tokens, limit_tokens_cur); + SRV_TRC(" - cache state: %zu prompts, %.3f MiB in RAM, %.3f MiB on disk (limits: %.3f MiB, %.3f MiB on disk, %zu tokens, %zu est)\n", + states.size(), size() / (1024.0 * 1024.0), disk_size() / (1024.0 * 1024.0), limit_size / (1024.0 * 1024.0), + disk_limit / (1024.0 * 1024.0), limit_tokens, limit_tokens_cur); for (const auto & state : states) { SRV_TRC(" - prompt %p: %7d tokens, checkpoints: %2zu, %9.3f MiB\n", diff --git a/tools/server/server-task.h b/tools/server/server-task.h index c757135afcc0..e56e9141ca63 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -780,6 +780,17 @@ struct server_prompt_cache_state { // the adapters the state was computed under; restored only into the same set lora_active_set lora; + // set while the state's bytes (its sequence state and its checkpoints' data) live in this + // file instead of RAM; its tokens and checkpoint positions stay in RAM, so a lookup still + // matches it without touching the disk + std::string spill_path; + size_t spill_size = 0; + + bool spilled() const { + return !spill_path.empty(); + } + + // bytes held in RAM: a spilled state holds none size_t size() const { size_t res = data.size(); @@ -805,10 +816,41 @@ struct server_prompt_cache { // in tokens, 0 = no limit size_t limit_tokens = 0; + // the disk tier: when set, a state evicted from RAM is written here instead of dropped, and + // a lookup that matches it reads it back; empty = no disk tier + std::string disk_dir; + + // in bytes, 0 = no limit + size_t disk_limit = 0; + + uint64_t spill_seq = 0; + + ~server_prompt_cache(); + + // enable the disk tier in `dir` (created, and emptied of states a previous engine left) + bool set_disk(const std::string & dir, int32_t limit_mib); + + // bytes held in RAM, by resident states only size_t size() const; + // bytes held on disk, by spilled states + size_t disk_size() const; + + // tokens of the resident states (the RAM tier's token limit) size_t n_tokens() const; + // move the state's bytes to a file; false leaves it resident + bool spill(server_prompt_cache_state & state); + + // read a spilled state's bytes back into RAM and remove its file + bool unspill(server_prompt_cache_state & state); + + // remove a state, and its file if it has one + std::list::iterator erase(std::list::iterator it); + + // make room in RAM: the oldest resident state goes to disk, or is dropped without a disk tier + bool evict_oldest_resident(); + server_prompt_cache_state * alloc(const server_prompt & prompt, const lora_active_set & lora, size_t state_size_main, size_t state_size_drft); bool load(server_prompt & prompt, const lora_active_set & lora, const server_tokens & tokens_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot); From 28d62afd31bd56bad03cf2583fc79fc4aa0ab2c7 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 11:02:17 -0600 Subject: [PATCH 2/9] server: the cache state names its spill fields at creation (0 warnings: -Wmissing-field-initializers) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-task.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index ba9836669df2..6c2d6be3973a 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -2024,6 +2024,8 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro /*.drft =*/ std::move(state_data_dft), }, /*.lora =*/ lora, + /*.spill_path =*/ {}, // resident in RAM until the disk tier spills it + /*.spill_size =*/ 0, }); return &states.back(); From 1a38ee0efb1723fe3de9689941453e3358a0ff0b Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 11:30:17 -0600 Subject: [PATCH 3/9] server: the disk tier owns only its instance directory, reads are bounded, and spills write on the page-io pool (Codex's review of #124) - Custody (server-spill-dir.h): each engine writes only under DIR/instance--/ and holds an exclusive lock on its .owner file (flock; on Windows an unshared handle) for its life. At start it sweeps only instance directories whose lock it can take (their owner is gone); a live owner's directory and anything that is not an instance directory are never touched. Its own directory leaves with it. - Bounded reads: every block length is checked against the bytes left in the file before anything is allocated, and a restore must consume the file exactly; a corrupt or truncated spill is refused and the entry dropped, never an out-of-memory. - Off the task loop: spill() only MOVES the entry's byte vectors into a shared spill buffer; #118's page-io pool writes the file. A lookup that matches before the write lands restores from that buffer (a copy, never the disk); reap_spills() on the loop drops the RAM once the write landed and keeps the entry resident if it failed. File removals go through the pool too, ordered after the file's write. Receipts (qwen35-0.8b, M5, 2026-11-16): test-server-spill-dir: two live owners of one DIR keep their own files, an abandoned instance is swept, foreign files and directories are untouched, an owner's directory leaves with it; a 2^62 length in a 1 KB file is refused without resizing. End to end with a pre-made abandoned instance and a foreign file: "1 abandoned instance directories swept", the foreign file kept, spills written on the pool (78.95 MiB in 25.4 ms, off the loop), Aiko's evicted entry restored from disk in 7.8 ms (10 ms request, 1,797 of 1,801 tokens from cache), the instance directory gone at exit. 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/CMakeLists.txt | 6 ++ tests/test-server-spill-dir.cpp | 75 +++++++++++++ tools/server/server-context.cpp | 2 +- tools/server/server-spill-dir.h | 163 ++++++++++++++++++++++++++++ tools/server/server-task.cpp | 182 +++++++++++++++++++------------- tools/server/server-task.h | 28 ++++- 6 files changed, 381 insertions(+), 75 deletions(-) create mode 100644 tests/test-server-spill-dir.cpp create mode 100644 tools/server/server-spill-dir.h diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 4e1fd12b03dc..67cb4b102bdc 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,6 +1,12 @@ llama_add_compile_flags() # Model-free scheduling validator: compile the same traversal used by server-context. +# Model-free: the disk tier's instance custody and bounded reads (llama.cpp#124). +add_executable(test-server-spill-dir test-server-spill-dir.cpp) +target_compile_features(test-server-spill-dir PRIVATE cxx_std_17) +add_test(NAME test-server-spill-dir COMMAND test-server-spill-dir) +set_tests_properties(test-server-spill-dir PROPERTIES LABELS "main") + add_executable(test-server-prefill test-server-prefill.cpp) target_compile_features(test-server-prefill PRIVATE cxx_std_17) add_test(NAME test-server-prefill COMMAND test-server-prefill) diff --git a/tests/test-server-spill-dir.cpp b/tests/test-server-spill-dir.cpp new file mode 100644 index 000000000000..cb9dd8ecabf8 --- /dev/null +++ b/tests/test-server-spill-dir.cpp @@ -0,0 +1,75 @@ +// what this catches: the prompt cache's disk tier deleting another engine's files (Codex's review of +// llama.cpp#124: two owners of one --cache-disk DIR deleted each other's spills), sweeping a live owner's +// directory, touching files that are not instance directories, and sizing a read from a corrupt file's own +// length claim (an out-of-memory). Model-free. +#include "../tools/server/server-spill-dir.h" + +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +static void require(bool condition, const char * message) { + if (!condition) { + std::cerr << "FAILED: " << message << '\n'; + std::exit(1); + } +} + +static void two_owners_never_touch_each_other() { + const fs::path base = fs::temp_directory_path() / ("spill-dir-test-" + std::to_string(std::rand())); + fs::remove_all(base); + fs::create_directories(base); + { std::ofstream(base / "foreign.state") << "not ours"; } // a file in DIR that is no instance's + fs::create_directories(base / "notes"); // a directory that is no instance's + // an abandoned instance: its .owner exists but nobody holds the lock + fs::create_directories(base / "instance-1-1"); + { std::ofstream(base / "instance-1-1" / ".owner") << ""; } + { std::ofstream(base / "instance-1-1" / "0.state") << "stale"; } + + std::error_code ec; + auto a = std::make_unique(); + require(a->claim(base, ec) == 1 && a->ok(), "the first owner claims its directory and sweeps the abandoned one"); + { std::ofstream(a->path() / "0.state") << "a's spill"; } + server_spill_dir b; + require(b.claim(base, ec) == 0 && b.ok(), "a second live owner sweeps nothing"); + require(a->path() != b.path(), "each owner has its own directory"); + require(fs::exists(a->path() / "0.state"), "the second owner never deletes the first owner's spill"); + require(fs::exists(base / "foreign.state") && fs::exists(base / "notes"), "nothing that is not an instance directory is touched"); + require(!fs::exists(base / "instance-1-1"), "an abandoned instance directory is swept"); + const fs::path a_dir = a->path(); + a.reset(); + require(!fs::exists(a_dir), "an owner's directory leaves with it"); + require(b.ok() && fs::exists(b.path()), "and the other owner's stays"); + fs::remove_all(base); +} + +static void a_corrupt_length_is_refused_before_allocation() { + const fs::path p = fs::temp_directory_path() / ("spill-block-" + std::to_string(std::rand())); + { + FILE * f = std::fopen(p.string().c_str(), "wb"); + require(server_spill_write_block(f, std::vector(1000, 7)), "write a block"); + const uint64_t lie = 1ull << 62; // a corrupt length: far beyond the file + std::fwrite(&lie, sizeof(lie), 1, f); + std::fclose(f); + } + FILE * f = std::fopen(p.string().c_str(), "rb"); + uint64_t remaining = fs::file_size(p); + std::vector block; + require(server_spill_read_block(f, block, remaining) && block.size() == 1000 && block[999] == 7, "a sound block reads back"); + require(!server_spill_read_block(f, block, remaining), "a length beyond the file is refused"); + require(block.size() == 1000, "and nothing was resized from its claim"); + std::fclose(f); + fs::remove(p); +} + +int main() { + two_owners_never_touch_each_other(); + a_corrupt_length_is_refused_before_allocation(); + std::cout << "test-server-spill-dir: ok\n"; + return 0; +} diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 90a2c411abca..85b75ae6a7fa 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1553,7 +1553,7 @@ 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); - if (!params_base.cache_disk_dir.empty() && !prompt_cache->set_disk(params_base.cache_disk_dir, params_base.cache_disk_mib)) { + if (!params_base.cache_disk_dir.empty() && !prompt_cache->set_disk(params_base.cache_disk_dir, params_base.cache_disk_mib, page_io.get())) { SRV_ERR("%s", "the prompt cache disk tier could not be set up, refusing to start without it\n"); return false; } diff --git a/tools/server/server-spill-dir.h b/tools/server/server-spill-dir.h new file mode 100644 index 000000000000..87eacab6d301 --- /dev/null +++ b/tools/server/server-spill-dir.h @@ -0,0 +1,163 @@ +#pragma once + +// Continuum fork: the prompt cache's disk tier keeps its files in a directory this engine instance owns +// (Codex's review of llama.cpp#124: two engines sharing one --cache-disk DIR deleted each other's files). +// +// - Each instance writes only under DIR/instance--/, and holds an exclusive lock on its +// `.owner` file there for as long as it lives (the OS releases it if the process dies). +// - At start, an instance removes only instance directories whose `.owner` lock it can take: their owner +// is gone. A live owner's directory, and anything else in DIR, is never touched. +// - Spill files hold length-prefixed blocks; a read checks every length against the bytes left in the +// file BEFORE allocating, so a corrupt or truncated file is refused, never an out-of-memory. +// +// The OS lock is the only platform-specific part (server_owner_lock below). + +#include +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#include +#include +#endif + +// An exclusive, non-blocking lock on one file, released when this object or its process ends. +class server_owner_lock { +public: + server_owner_lock() = default; + server_owner_lock(const server_owner_lock &) = delete; + server_owner_lock & operator=(const server_owner_lock &) = delete; + ~server_owner_lock() { release(); } + + // true when this process now holds the lock on `path` (created if absent) + bool try_take(const std::filesystem::path & path) { + release(); +#if defined(_WIN32) + // no sharing: a second open of a file another process holds open fails + handle = CreateFileW(path.wstring().c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + return handle != INVALID_HANDLE_VALUE; +#else + fd = ::open(path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600); + if (fd < 0) { + return false; + } + if (::flock(fd, LOCK_EX | LOCK_NB) != 0) { + ::close(fd); + fd = -1; + return false; + } + return true; +#endif + } + + void release() { +#if defined(_WIN32) + if (handle != INVALID_HANDLE_VALUE) { + CloseHandle(handle); + handle = INVALID_HANDLE_VALUE; + } +#else + if (fd >= 0) { + ::close(fd); // closing releases the flock + fd = -1; + } +#endif + } + +private: +#if defined(_WIN32) + HANDLE handle = INVALID_HANDLE_VALUE; +#else + int fd = -1; +#endif +}; + +class server_spill_dir { +public: + // Claims an instance directory under `base` and sweeps instance directories whose owner is gone. + // Returns the number swept; `ok()` says whether this instance holds its directory. + size_t claim(const std::filesystem::path & base, std::error_code & ec) { + std::filesystem::create_directories(base, ec); + if (ec) { + return 0; + } + const auto ns = std::chrono::steady_clock::now().time_since_epoch().count(); +#if defined(_WIN32) + const unsigned long pid = GetCurrentProcessId(); +#else + const long pid = (long) ::getpid(); +#endif + dir = base / ("instance-" + std::to_string(pid) + "-" + std::to_string(ns)); + std::filesystem::create_directories(dir, ec); + if (ec || !owner.try_take(dir / ".owner")) { + dir.clear(); + return 0; + } + size_t swept = 0; + for (const auto & entry : std::filesystem::directory_iterator(base, ec)) { + const auto name = entry.path().filename().string(); + if (!entry.is_directory() || name.rfind("instance-", 0) != 0 || entry.path() == dir) { + continue; // anything that is not an instance directory is never ours to touch + } + server_owner_lock probe; + if (!probe.try_take(entry.path() / ".owner")) { + continue; // a live owner holds it + } + probe.release(); + std::error_code rm; + std::filesystem::remove_all(entry.path(), rm); + swept += rm ? 0 : 1; + } + return swept; + } + + bool ok() const { return !dir.empty(); } + const std::filesystem::path & path() const { return dir; } + + ~server_spill_dir() { + if (ok()) { + owner.release(); + std::error_code ec; + std::filesystem::remove_all(dir, ec); // this instance's files leave with it + } + } + +private: + std::filesystem::path dir; + server_owner_lock owner; +}; + +// Length-prefixed blocks. `remaining` is the bytes left in the file; a length beyond it is refused +// before anything is allocated. +inline bool server_spill_write_block(FILE * f, const std::vector & data) { + const uint64_t n = data.size(); + return fwrite(&n, sizeof(n), 1, f) == 1 && (n == 0 || fwrite(data.data(), 1, n, f) == n); +} + +inline bool server_spill_read_block(FILE * f, std::vector & data, uint64_t & remaining) { + uint64_t n = 0; + if (remaining < sizeof(n) || fread(&n, sizeof(n), 1, f) != 1) { + return false; + } + remaining -= sizeof(n); + if (n > remaining) { + return false; // a corrupt or truncated file: refused, never sized from its own claim + } + data.resize(n); + if (n != 0 && fread(data.data(), 1, n, f) != n) { + return false; + } + remaining -= n; + return true; +} diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index 6c2d6be3973a..0c6f82396009 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1783,49 +1783,24 @@ size_t server_prompt_cache::n_tokens() const { return res; } -server_prompt_cache::~server_prompt_cache() { - for (const auto & state : states) { - if (state.spilled()) { - std::error_code ec; - std::filesystem::remove(state.spill_path, ec); - } - } -} +server_prompt_cache::~server_prompt_cache() = default; // spill_dir removes this instance's directory -bool server_prompt_cache::set_disk(const std::string & dir, int32_t limit_mib) { +bool server_prompt_cache::set_disk(const std::string & dir, int32_t limit_mib, server_page_io_pool * pool) { std::error_code ec; - std::filesystem::create_directories(dir, ec); - if (ec) { - SRV_ERR("prompt cache disk tier: cannot create %s: %s\n", dir.c_str(), ec.message().c_str()); + const size_t swept = spill_dir.claim(dir, ec); + if (!spill_dir.ok() || pool == nullptr) { + SRV_ERR("prompt cache disk tier: cannot claim an instance directory under %s: %s\n", dir.c_str(), + ec ? ec.message().c_str() : (pool ? "its owner lock is held" : "no page-io pool")); return false; } - // a state written by another engine instance is not this one's: its slot ids, adapters and - // tokens were never recorded here, so it could never be matched, only leak - for (const auto & entry : std::filesystem::directory_iterator(dir, ec)) { - if (entry.path().extension() == ".state") { - std::filesystem::remove(entry.path(), ec); - } - } - disk_dir = dir; + disk_dir = spill_dir.path().string(); + io = pool; disk_limit = 1024ull*1024ull*(limit_mib < 0 ? 0 : limit_mib); - SRV_INF("prompt cache disk tier: %s, size limit: %d MiB\n", dir.c_str(), limit_mib); + SRV_INF("prompt cache disk tier: %s, size limit: %d MiB (%zu abandoned instance directories swept)\n", + disk_dir.c_str(), limit_mib, swept); return true; } -static bool write_block(FILE * f, const std::vector & data) { - const uint64_t n = data.size(); - return fwrite(&n, sizeof(n), 1, f) == 1 && (n == 0 || fwrite(data.data(), 1, n, f) == n); -} - -static bool read_block(FILE * f, std::vector & data) { - uint64_t n = 0; - if (fread(&n, sizeof(n), 1, f) != 1) { - return false; - } - data.resize(n); - return n == 0 || fread(data.data(), 1, n, f) == n; -} - bool server_prompt_cache::spill(server_prompt_cache_state & state) { if (disk_dir.empty() || state.spilled()) { return false; @@ -1843,63 +1818,121 @@ bool server_prompt_cache::spill(server_prompt_cache_state & state) { erase(oldest); } - const auto t0 = std::chrono::steady_clock::now(); + // the task loop only MOVES the bytes into the spill buffer; the file is written on the page-io pool const std::string path = disk_dir + "/" + std::to_string(spill_seq++) + ".state"; - FILE * f = fopen(path.c_str(), "wb"); - if (f == nullptr) { - SRV_ERR("prompt cache disk tier: cannot open %s\n", path.c_str()); - return false; - } - bool ok = write_block(f, state.data.main) && write_block(f, state.data.drft); - for (const auto & ckpt : state.prompt.checkpoints) { - ok = ok && write_block(f, ckpt.data_tgt) && write_block(f, ckpt.data_dft) && write_block(f, ckpt.data_spec); - } - ok = (fclose(f) == 0) && ok; - if (!ok) { - SRV_ERR("prompt cache disk tier: failed writing %s\n", path.c_str()); - std::error_code ec; - std::filesystem::remove(path, ec); - return false; + auto buf = std::make_shared(); + buf->blocks.reserve(2 + 3 * state.prompt.checkpoints.size()); + buf->blocks.push_back(std::move(state.data.main)); + buf->blocks.push_back(std::move(state.data.drft)); + for (auto & ckpt : state.prompt.checkpoints) { + buf->blocks.push_back(std::move(ckpt.data_tgt)); + buf->blocks.push_back(std::move(ckpt.data_dft)); + buf->blocks.push_back(std::move(ckpt.data_spec)); } - - state.data.main.clear(); - state.data.main.shrink_to_fit(); - state.data.drft.clear(); - state.data.drft.shrink_to_fit(); + state.data.main = {}; + state.data.drft = {}; for (auto & ckpt : state.prompt.checkpoints) { - ckpt.data_tgt.clear(); - ckpt.data_tgt.shrink_to_fit(); - ckpt.data_dft.clear(); - ckpt.data_dft.shrink_to_fit(); - ckpt.data_spec.clear(); - ckpt.data_spec.shrink_to_fit(); + ckpt.data_tgt = {}; + ckpt.data_dft = {}; + ckpt.data_spec = {}; } state.spill_path = path; state.spill_size = bytes; - - const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - SRV_INF(" - spilled prompt cache entry to disk: %d tokens, %.3f MiB in %.1f ms\n", - state.prompt.n_tokens(), bytes / (1024.0 * 1024.0), ms); + state.spilling = buf; + + const int n_tokens = state.prompt.n_tokens(); + io->submit(path, [buf, path, bytes, n_tokens] { + const auto t0 = std::chrono::steady_clock::now(); + FILE * f = fopen(path.c_str(), "wb"); + bool ok = f != nullptr; + for (const auto & block : buf->blocks) { + ok = ok && server_spill_write_block(f, block); + } + ok = (f == nullptr || fclose(f) == 0) && ok; + if (!ok) { + std::error_code ec; + std::filesystem::remove(path, ec); + SRV_ERR("prompt cache disk tier: failed writing %s; the entry stays in RAM\n", path.c_str()); + } else { + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + SRV_INF(" - spilled prompt cache entry to disk: %d tokens, %.3f MiB in %.1f ms (page-io pool)\n", + n_tokens, bytes / (1024.0 * 1024.0), ms); + } + buf->status.store(ok ? 1 : -1, std::memory_order_release); + }); return true; } +void server_prompt_cache::reap_spills() { + for (auto & state : states) { + if (!state.spilling) { + continue; + } + const int status = state.spilling->status.load(std::memory_order_acquire); + if (status == 1) { + state.spilling.reset(); // written: the RAM copy goes + } else if (status == -1) { + // the write failed: the bytes come back and the entry stays resident + auto & blocks = state.spilling->blocks; + size_t b = 0; + state.data.main = std::move(blocks[b++]); + state.data.drft = std::move(blocks[b++]); + for (auto & ckpt : state.prompt.checkpoints) { + ckpt.data_tgt = std::move(blocks[b++]); + ckpt.data_dft = std::move(blocks[b++]); + ckpt.data_spec = std::move(blocks[b++]); + } + state.spilling.reset(); + state.spill_path.clear(); + state.spill_size = 0; + } + } +} + bool server_prompt_cache::unspill(server_prompt_cache_state & state) { if (!state.spilled()) { return true; } const auto t0 = std::chrono::steady_clock::now(); + if (state.spilling) { + // its bytes are still in RAM (the write is running, landed unreaped, or failed): copy them back + // from the buffer the write reads, never the disk + const auto & blocks = state.spilling->blocks; + size_t b = 0; + state.data.main = blocks[b++]; + state.data.drft = blocks[b++]; + for (auto & ckpt : state.prompt.checkpoints) { + ckpt.data_tgt = blocks[b++]; + ckpt.data_dft = blocks[b++]; + ckpt.data_spec = blocks[b++]; + } + state.spilling.reset(); + // the file is removed after its write, in order, on the pool + const std::string path = state.spill_path; + io->submit(path, [path] { std::error_code rm; std::filesystem::remove(path, rm); }); + const size_t bytes = state.spill_size; + state.spill_path.clear(); + state.spill_size = 0; + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + SRV_INF(" - restored prompt cache entry from its in-flight spill: %d tokens, %.3f MiB in %.1f ms\n", + state.prompt.n_tokens(), bytes / (1024.0 * 1024.0), ms); + return true; + } FILE * f = fopen(state.spill_path.c_str(), "rb"); if (f == nullptr) { SRV_ERR("prompt cache disk tier: cannot open %s\n", state.spill_path.c_str()); return false; } - bool ok = read_block(f, state.data.main) && read_block(f, state.data.drft); + std::error_code size_ec; + uint64_t remaining = std::filesystem::file_size(state.spill_path, size_ec); + bool ok = !size_ec && server_spill_read_block(f, state.data.main, remaining) && server_spill_read_block(f, state.data.drft, remaining); for (auto & ckpt : state.prompt.checkpoints) { - ok = ok && read_block(f, ckpt.data_tgt) && read_block(f, ckpt.data_dft) && read_block(f, ckpt.data_spec); + ok = ok && server_spill_read_block(f, ckpt.data_tgt, remaining) && server_spill_read_block(f, ckpt.data_dft, remaining) && + server_spill_read_block(f, ckpt.data_spec, remaining); } fclose(f); - if (!ok) { - SRV_ERR("prompt cache disk tier: failed reading %s\n", state.spill_path.c_str()); + if (!ok || remaining != 0) { + SRV_ERR("prompt cache disk tier: %s is corrupt or truncated; the entry is dropped\n", state.spill_path.c_str()); return false; } std::error_code ec; @@ -1916,8 +1949,9 @@ bool server_prompt_cache::unspill(server_prompt_cache_state & state) { std::list::iterator server_prompt_cache::erase(std::list::iterator it) { if (it->spilled()) { - std::error_code ec; - std::filesystem::remove(it->spill_path, ec); + // ordered after any write of the same file on the pool, so a writer never recreates it + const std::string path = it->spill_path; + io->submit(path, [path] { std::error_code rm; std::filesystem::remove(path, rm); }); } return states.erase(it); } @@ -1944,6 +1978,7 @@ bool server_prompt_cache::evict_oldest_resident() { } server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & prompt, const lora_active_set & lora, size_t state_size_tgt, size_t state_size_dft) { + reap_spills(); // first check if the current state is contained fully in the cache for (auto it = states.begin(); it != states.end(); ++it) { if (it->lora != lora) { @@ -2026,6 +2061,7 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro /*.lora =*/ lora, /*.spill_path =*/ {}, // resident in RAM until the disk tier spills it /*.spill_size =*/ 0, + /*.spilling =*/ nullptr, }); return &states.back(); @@ -2042,6 +2078,7 @@ void server_prompt_cache::evict_lora(const llama_adapter_lora * adapter) { } bool server_prompt_cache::load(server_prompt & prompt, const lora_active_set & lora, const server_tokens & tokens_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot) { + reap_spills(); const int lcp_best = prompt.tokens.get_common_prefix(tokens_new); float f_keep_best = prompt.tokens.size() > 0 ? float(lcp_best) / prompt.tokens.size() : -1.0f; // empty slot: any cache entry wins @@ -2127,6 +2164,7 @@ bool server_prompt_cache::load(server_prompt & prompt, const lora_active_set & l } void server_prompt_cache::update() { + reap_spills(); if (limit_size > 0) { while (size() > limit_size && evict_oldest_resident()) { } diff --git a/tools/server/server-task.h b/tools/server/server-task.h index e56e9141ca63..a5d86bf23e29 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -9,9 +9,12 @@ #include #include #include +#include // TODO: prevent including the whole server-common.h as we only use server_tokens #include "server-common.h" +#include "server-page-io.h" +#include "server-spill-dir.h" struct server_page_job; // server-page-job.h: one page switch between the task loop and its file IO @@ -773,6 +776,13 @@ struct server_prompt_data { } }; +// A spill in flight: the state's bytes in file order (sequence state main, draft; then each checkpoint's +// target, draft, speculative). `status`: 0 writing, 1 written, -1 failed. +struct server_spill_buffer { + std::vector> blocks; + std::atomic status{0}; +}; + struct server_prompt_cache_state { server_prompt prompt; server_prompt_data data; @@ -786,6 +796,10 @@ struct server_prompt_cache_state { std::string spill_path; size_t spill_size = 0; + // while its file is being written on the page-io pool: the bytes, moved out of this state (never + // copied), read by the write and by a lookup that matches before the write lands + std::shared_ptr spilling; + bool spilled() const { return !spill_path.empty(); } @@ -825,10 +839,20 @@ struct server_prompt_cache { uint64_t spill_seq = 0; + // this instance's directory under the configured one (server-spill-dir.h: another engine's files are + // never touched), and the pool its files are written on (the task loop only moves the bytes) + server_spill_dir spill_dir; + server_page_io_pool * io = nullptr; + ~server_prompt_cache(); - // enable the disk tier in `dir` (created, and emptied of states a previous engine left) - bool set_disk(const std::string & dir, int32_t limit_mib); + // enable the disk tier under `dir` (this instance's own directory; instance directories whose owner + // is gone are swept), writing on `pool` + bool set_disk(const std::string & dir, int32_t limit_mib, server_page_io_pool * pool); + + // on the task loop: drop the bytes of spills whose write landed, and keep resident the ones whose + // write failed + void reap_spills(); // bytes held in RAM, by resident states only size_t size() const; From e3da841aa7427acee9954e2dd5a102a151dc7aa1 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 11:56:39 -0600 Subject: [PATCH 4/9] server: the disk tier's marker is published locked and a sweep never creates one; a restore reads exactly the admitted bytes (Codex's re-review of #124) - Claim/sweep race: a claim created its directory, then its .owner, so a concurrent sweeper could see a live instance unlocked, create its marker (O_CREAT) and delete it. Now the owner creates .owner.tmp exclusively, locks it, renames it to .owner (atomic; the lock stays on the open file) and only then creates /. A sweeper judges only final .owner markers, opens them without creating, and on taking the lock removes / and then the marker. A directory without a marker, a .tmp, or any other file is never touched. The sweep collects the directory first (removing while iterating is unspecified). Windows: an unshared handle (delete sharing lets the owner rename). - Admitted size: a restore requires the file to be exactly spill_size (the state's bytes, the sum of its blocks) plus one 8-byte length per block, before any block is read; the read is bounded by that, not by the file's size. Receipts (qwen35-0.8b, M5, 2026-11-16): test-server-spill-dir: an abandoned instance and its marker are swept; a directory with no marker is untouched and gets no marker; a .tmp claim is never judged; two live owners keep their own files; foreign files kept; an owner's directory leaves with it; a 2^62 length is refused before allocation. End to end: "1 abandoned instance directories swept", the marker-less directory and the foreign file kept, spills on the page-io pool, Aiko restored from disk (exact size) in 10.6 ms, a 22 ms request with 1,797 of 1,801 tokens from cache; this instance's directory and marker gone at exit. 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/test-server-spill-dir.cpp | 24 ++++++---- tools/server/server-spill-dir.h | 78 ++++++++++++++++++++++++--------- tools/server/server-task.cpp | 11 ++++- 3 files changed, 83 insertions(+), 30 deletions(-) diff --git a/tests/test-server-spill-dir.cpp b/tests/test-server-spill-dir.cpp index cb9dd8ecabf8..54b1c82da564 100644 --- a/tests/test-server-spill-dir.cpp +++ b/tests/test-server-spill-dir.cpp @@ -24,23 +24,31 @@ static void two_owners_never_touch_each_other() { const fs::path base = fs::temp_directory_path() / ("spill-dir-test-" + std::to_string(std::rand())); fs::remove_all(base); fs::create_directories(base); - { std::ofstream(base / "foreign.state") << "not ours"; } // a file in DIR that is no instance's - fs::create_directories(base / "notes"); // a directory that is no instance's - // an abandoned instance: its .owner exists but nobody holds the lock + { std::ofstream(base / "foreign.state") << "not ours"; } // a file in DIR that is no instance's + fs::create_directories(base / "notes"); // a directory that is no instance's + // an abandoned instance: its final marker exists and nobody holds its lock fs::create_directories(base / "instance-1-1"); - { std::ofstream(base / "instance-1-1" / ".owner") << ""; } + { std::ofstream(base / "instance-1-1.owner") << ""; } { std::ofstream(base / "instance-1-1" / "0.state") << "stale"; } + // an instance directory with NO marker (a claim before its marker, or anything unproven): untouched, + // and a sweeper never creates a marker for it (Codex on #124) + fs::create_directories(base / "instance-2-2"); + // a claim in progress: its .tmp marker exists (a live owner would hold it): never judged + { std::ofstream(base / "instance-3-3.owner.tmp") << ""; } std::error_code ec; auto a = std::make_unique(); - require(a->claim(base, ec) == 1 && a->ok(), "the first owner claims its directory and sweeps the abandoned one"); + require(a->claim(base, ec) == 1 && a->ok(), "the first owner claims its directory and sweeps the one abandoned instance"); { std::ofstream(a->path() / "0.state") << "a's spill"; } server_spill_dir b; - require(b.claim(base, ec) == 0 && b.ok(), "a second live owner sweeps nothing"); + require(b.claim(base, ec) == 0 && b.ok(), "a second live owner sweeps nothing: the first one's marker is locked"); require(a->path() != b.path(), "each owner has its own directory"); require(fs::exists(a->path() / "0.state"), "the second owner never deletes the first owner's spill"); - require(fs::exists(base / "foreign.state") && fs::exists(base / "notes"), "nothing that is not an instance directory is touched"); - require(!fs::exists(base / "instance-1-1"), "an abandoned instance directory is swept"); + require(fs::exists(base / "foreign.state") && fs::exists(base / "notes"), "nothing that is not an instance is touched"); + require(!fs::exists(base / "instance-1-1") && !fs::exists(base / "instance-1-1.owner"), "an abandoned instance and its marker are swept"); + require(fs::exists(base / "instance-2-2") && !fs::exists(base / "instance-2-2.owner"), + "a directory without a marker is never swept, and no sweeper creates a marker for it"); + require(fs::exists(base / "instance-3-3.owner.tmp"), "a claim in progress (.tmp) is never judged"); const fs::path a_dir = a->path(); a.reset(); require(!fs::exists(a_dir), "an owner's directory leaves with it"); diff --git a/tools/server/server-spill-dir.h b/tools/server/server-spill-dir.h index 87eacab6d301..4428bc579ed4 100644 --- a/tools/server/server-spill-dir.h +++ b/tools/server/server-spill-dir.h @@ -39,16 +39,18 @@ class server_owner_lock { server_owner_lock & operator=(const server_owner_lock &) = delete; ~server_owner_lock() { release(); } - // true when this process now holds the lock on `path` (created if absent) - bool try_take(const std::filesystem::path & path) { + // true when this process now holds the lock on `path`. `create`: make the file (exclusively: it + // must not exist yet); otherwise open only an existing file, never creating a marker for anyone. + bool try_take(const std::filesystem::path & path, bool create) { release(); #if defined(_WIN32) - // no sharing: a second open of a file another process holds open fails - handle = CreateFileW(path.wstring().c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, nullptr); + // no read/write sharing: a second open of a file another process holds open fails (delete + // sharing lets the owner rename its own marker) + handle = CreateFileW(path.wstring().c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_DELETE, nullptr, + create ? CREATE_NEW : OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); return handle != INVALID_HANDLE_VALUE; #else - fd = ::open(path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600); + fd = ::open(path.c_str(), O_RDWR | O_CLOEXEC | (create ? (O_CREAT | O_EXCL) : 0), 0600); if (fd < 0) { return false; } @@ -83,10 +85,17 @@ class server_owner_lock { #endif }; +// The instance directory's protocol. The marker is published before the directory and only while +// locked, so a sweeper can never see a live owner unlocked (Codex on #124: a claim raced a sweep): +// owner: create .owner.tmp exclusively, lock it, rename it to .owner (atomic; the lock +// stays on the open file), then create /; +// sweeper: for each final .owner (never a .tmp, never anything else), open it WITHOUT creating +// and try the lock; taken means its owner is gone: remove /, then the marker. A +// directory without a marker, a .tmp, or any other file is never touched. class server_spill_dir { public: - // Claims an instance directory under `base` and sweeps instance directories whose owner is gone. - // Returns the number swept; `ok()` says whether this instance holds its directory. + // Claims an instance directory under `base` and sweeps instances whose owner is gone. Returns the + // number swept; `ok()` says whether this instance holds its directory. size_t claim(const std::filesystem::path & base, std::error_code & ec) { std::filesystem::create_directories(base, ec); if (ec) { @@ -98,26 +107,53 @@ class server_spill_dir { #else const long pid = (long) ::getpid(); #endif - dir = base / ("instance-" + std::to_string(pid) + "-" + std::to_string(ns)); + const std::string name = "instance-" + std::to_string(pid) + "-" + std::to_string(ns); + const auto tmp = base / (name + ".owner.tmp"); + const auto marker = base / (name + ".owner"); + if (!owner.try_take(tmp, /*create=*/true)) { + return 0; + } + std::filesystem::rename(tmp, marker, ec); + if (ec) { + owner.release(); + std::error_code rm; + std::filesystem::remove(tmp, rm); + return 0; + } + dir = base / name; std::filesystem::create_directories(dir, ec); - if (ec || !owner.try_take(dir / ".owner")) { + if (ec) { + owner.release(); + std::error_code rm; + std::filesystem::remove(marker, rm); dir.clear(); return 0; } - size_t swept = 0; + owner_marker = marker; + // collect first: removing entries while iterating the same directory is unspecified + std::vector markers; for (const auto & entry : std::filesystem::directory_iterator(base, ec)) { - const auto name = entry.path().filename().string(); - if (!entry.is_directory() || name.rfind("instance-", 0) != 0 || entry.path() == dir) { - continue; // anything that is not an instance directory is never ours to touch + markers.push_back(entry.path()); + } + size_t swept = 0; + for (const auto & path : markers) { + const auto file = path.filename().string(); + const std::string suffix = ".owner"; + if (file.rfind("instance-", 0) != 0 || file.size() <= suffix.size() || + file.compare(file.size() - suffix.size(), suffix.size(), suffix) != 0 || path == marker) { + continue; // only a final owner marker names an instance a sweeper may judge } server_owner_lock probe; - if (!probe.try_take(entry.path() / ".owner")) { - continue; // a live owner holds it + if (!probe.try_take(path, /*create=*/false)) { + continue; // a live owner holds it (or it vanished meanwhile) } - probe.release(); + const auto instance = base / file.substr(0, file.size() - suffix.size()); std::error_code rm; - std::filesystem::remove_all(entry.path(), rm); - swept += rm ? 0 : 1; + std::filesystem::remove_all(instance, rm); + if (!rm) { + std::filesystem::remove(path, rm); // the marker last: a crash in between is swept again + swept += rm ? 0 : 1; + } } return swept; } @@ -127,14 +163,16 @@ class server_spill_dir { ~server_spill_dir() { if (ok()) { - owner.release(); std::error_code ec; std::filesystem::remove_all(dir, ec); // this instance's files leave with it + std::filesystem::remove(owner_marker, ec); + owner.release(); } } private: std::filesystem::path dir; + std::filesystem::path owner_marker; server_owner_lock owner; }; diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index 0c6f82396009..c6dc835799d6 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1923,9 +1923,16 @@ bool server_prompt_cache::unspill(server_prompt_cache_state & state) { SRV_ERR("prompt cache disk tier: cannot open %s\n", state.spill_path.c_str()); return false; } + // the file must be exactly what this instance admitted when it spilled: the state's bytes plus one + // 8-byte length per block; anything else is refused before a single block is read or allocated + // (Codex on #124: the file size alone could exceed the admitted state) + const uint64_t n_blocks = 2 + 3 * (uint64_t) state.prompt.checkpoints.size(); + const uint64_t expected = (uint64_t) state.spill_size + n_blocks * sizeof(uint64_t); std::error_code size_ec; - uint64_t remaining = std::filesystem::file_size(state.spill_path, size_ec); - bool ok = !size_ec && server_spill_read_block(f, state.data.main, remaining) && server_spill_read_block(f, state.data.drft, remaining); + const uint64_t file_bytes = std::filesystem::file_size(state.spill_path, size_ec); + uint64_t remaining = expected; + bool ok = !size_ec && file_bytes == expected && + server_spill_read_block(f, state.data.main, remaining) && server_spill_read_block(f, state.data.drft, remaining); for (auto & ckpt : state.prompt.checkpoints) { ok = ok && server_spill_read_block(f, ckpt.data_tgt, remaining) && server_spill_read_block(f, ckpt.data_dft, remaining) && server_spill_read_block(f, ckpt.data_spec, remaining); From 4ce3337ff81935162d3818d7e000f288a0696c3d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 12:05:57 -0600 Subject: [PATCH 5/9] server: the disk tier's OS calls move to server-spill-dir.cpp; its header includes no platform header (Codex on #124: windows.h in a public header pulled winsock.h ahead of Winsock2, the Windows CI's sockaddr redefinition) The lock is an opaque handle in the header; the .cpp holds the flock / CreateFileW calls and the process id (WIN32_LEAN_AND_MEAN there). Logic unchanged: test-server-spill-dir ok on macOS, 0 warnings; Windows is proven by its CI on this push. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/CMakeLists.txt | 2 +- tools/server/CMakeLists.txt | 1 + tools/server/server-spill-dir.cpp | 63 +++++++++++++++++++++++++++++ tools/server/server-spill-dir.h | 67 +++++-------------------------- 4 files changed, 75 insertions(+), 58 deletions(-) create mode 100644 tools/server/server-spill-dir.cpp diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 67cb4b102bdc..10ba8253c36f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -2,7 +2,7 @@ llama_add_compile_flags() # Model-free scheduling validator: compile the same traversal used by server-context. # Model-free: the disk tier's instance custody and bounded reads (llama.cpp#124). -add_executable(test-server-spill-dir test-server-spill-dir.cpp) +add_executable(test-server-spill-dir test-server-spill-dir.cpp ../tools/server/server-spill-dir.cpp) target_compile_features(test-server-spill-dir PRIVATE cxx_std_17) add_test(NAME test-server-spill-dir COMMAND test-server-spill-dir) set_tests_properties(test-server-spill-dir PROPERTIES LABELS "main") diff --git a/tools/server/CMakeLists.txt b/tools/server/CMakeLists.txt index 67fb03964d7c..600489c90b13 100644 --- a/tools/server/CMakeLists.txt +++ b/tools/server/CMakeLists.txt @@ -8,6 +8,7 @@ add_library(${TARGET} STATIC server-chat.cpp server-chat.h server-task.cpp + server-spill-dir.cpp server-task.h server-queue.cpp server-queue.h diff --git a/tools/server/server-spill-dir.cpp b/tools/server/server-spill-dir.cpp new file mode 100644 index 000000000000..ba2fb90cd5b5 --- /dev/null +++ b/tools/server/server-spill-dir.cpp @@ -0,0 +1,63 @@ +// The disk tier's only platform-specific lines (server-spill-dir.h): an exclusive file lock and the process +// id. Logic lives in the header; this file holds just the OS calls. +#include "server-spill-dir.h" + +#if defined(_WIN32) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#include +#include +#endif + +bool server_owner_lock::try_take(const std::filesystem::path & path, bool create) { + release(); +#if defined(_WIN32) + // no read/write sharing: a second open of a file another process holds open fails (delete sharing + // lets the owner rename its own marker) + HANDLE h = CreateFileW(path.wstring().c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_DELETE, nullptr, + create ? CREATE_NEW : OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + return false; + } + handle = (intptr_t) h; + return true; +#else + const int fd = ::open(path.c_str(), O_RDWR | O_CLOEXEC | (create ? (O_CREAT | O_EXCL) : 0), 0600); + if (fd < 0) { + return false; + } + if (::flock(fd, LOCK_EX | LOCK_NB) != 0) { + ::close(fd); + return false; + } + handle = fd; + return true; +#endif +} + +void server_owner_lock::release() { + if (handle == -1) { + return; + } +#if defined(_WIN32) + CloseHandle((HANDLE) handle); +#else + ::close((int) handle); // closing releases the flock +#endif + handle = -1; +} + +uint64_t server_process_id() { +#if defined(_WIN32) + return (uint64_t) GetCurrentProcessId(); +#else + return (uint64_t) ::getpid(); +#endif +} diff --git a/tools/server/server-spill-dir.h b/tools/server/server-spill-dir.h index 4428bc579ed4..1d8f323b81a6 100644 --- a/tools/server/server-spill-dir.h +++ b/tools/server/server-spill-dir.h @@ -20,18 +20,10 @@ #include #include -#if defined(_WIN32) -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#else -#include -#include -#include -#endif -// An exclusive, non-blocking lock on one file, released when this object or its process ends. +// An exclusive, non-blocking lock on one file, released when this object or its process ends. The OS calls +// live in server-spill-dir.cpp: this header includes no platform header (Codex on #124: windows.h here +// pulled winsock.h in ahead of Winsock2 for every includer). class server_owner_lock { public: server_owner_lock() = default; @@ -41,50 +33,16 @@ class server_owner_lock { // true when this process now holds the lock on `path`. `create`: make the file (exclusively: it // must not exist yet); otherwise open only an existing file, never creating a marker for anyone. - bool try_take(const std::filesystem::path & path, bool create) { - release(); -#if defined(_WIN32) - // no read/write sharing: a second open of a file another process holds open fails (delete - // sharing lets the owner rename its own marker) - handle = CreateFileW(path.wstring().c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_DELETE, nullptr, - create ? CREATE_NEW : OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); - return handle != INVALID_HANDLE_VALUE; -#else - fd = ::open(path.c_str(), O_RDWR | O_CLOEXEC | (create ? (O_CREAT | O_EXCL) : 0), 0600); - if (fd < 0) { - return false; - } - if (::flock(fd, LOCK_EX | LOCK_NB) != 0) { - ::close(fd); - fd = -1; - return false; - } - return true; -#endif - } - - void release() { -#if defined(_WIN32) - if (handle != INVALID_HANDLE_VALUE) { - CloseHandle(handle); - handle = INVALID_HANDLE_VALUE; - } -#else - if (fd >= 0) { - ::close(fd); // closing releases the flock - fd = -1; - } -#endif - } + bool try_take(const std::filesystem::path & path, bool create); + void release(); private: -#if defined(_WIN32) - HANDLE handle = INVALID_HANDLE_VALUE; -#else - int fd = -1; -#endif + intptr_t handle = -1; // a POSIX descriptor or a Windows HANDLE; -1 = none }; +// This process's id (server-spill-dir.cpp). +uint64_t server_process_id(); + // The instance directory's protocol. The marker is published before the directory and only while // locked, so a sweeper can never see a live owner unlocked (Codex on #124: a claim raced a sweep): // owner: create .owner.tmp exclusively, lock it, rename it to .owner (atomic; the lock @@ -102,12 +60,7 @@ class server_spill_dir { return 0; } const auto ns = std::chrono::steady_clock::now().time_since_epoch().count(); -#if defined(_WIN32) - const unsigned long pid = GetCurrentProcessId(); -#else - const long pid = (long) ::getpid(); -#endif - const std::string name = "instance-" + std::to_string(pid) + "-" + std::to_string(ns); + const std::string name = "instance-" + std::to_string(server_process_id()) + "-" + std::to_string(ns); const auto tmp = base / (name + ".owner.tmp"); const auto marker = base / (name + ".owner"); if (!owner.try_take(tmp, /*create=*/true)) { From c40fa64443c2c5c5e66c3eaa4e6a5c109ce484ea Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 12:52:42 -0600 Subject: [PATCH 6/9] server: disk-tier spills are admitted against the one page-IO budget and stay charged until their write lands (Codex's review of #124) A spill moved its bytes into a shared buffer while size() counted the entry's now-empty vectors, the write queue was unbounded, and an erase left the worker holding uncounted RAM: on a slow or paused disk repeated spills grew past the cache budget (toward swap, not just a slow disk). - server_page_admission::try_admit: admits now or refuses, never parks. A spill is admitted against #118's one page-IO budget (the core's measured host room) before anything moves; one that does not fit beside the bytes in flight is refused and its entry dropped, exactly as with no disk tier. - The spill buffer holds a server_page_reservation for its bytes; the worker releases it when the write lands or fails, so an entry erased meanwhile still counts until then. - The RAM tier's size() counts spill_in_flight (bytes whose write has not landed), so eviction never believes them free early. - Spill writes honour #118's page-IO test gate, so a test pauses them like page IO. Receipt (qwen35-0.8b, M5, LLAMA_SERVER_TEST_FAULTS build, page-IO gate held, a 30 MiB RAM tier, four ~79 MiB minds in turn): the first eviction's spill was admitted and held unwritten; the next two were refused ("does not fit the page-IO budget beside the bytes in flight; the entry is dropped"), so RAM never stacked; opening the gate landed the held one (78.950 MiB in 53.2 ms). 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context.cpp | 3 ++- tools/server/server-page-io.h | 11 +++++++++++ tools/server/server-task.cpp | 31 +++++++++++++++++++++++++++---- tools/server/server-task.h | 16 +++++++++++++--- 4 files changed, 53 insertions(+), 8 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 85b75ae6a7fa..250175805cee 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1553,7 +1553,8 @@ 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); - if (!params_base.cache_disk_dir.empty() && !prompt_cache->set_disk(params_base.cache_disk_dir, params_base.cache_disk_mib, page_io.get())) { + if (!params_base.cache_disk_dir.empty() && !prompt_cache->set_disk(params_base.cache_disk_dir, params_base.cache_disk_mib, page_io.get(), &page_io_bytes, + server_test_faults::enabled ? server_test_faults::from_env().page_io_gate : std::string())) { SRV_ERR("%s", "the prompt cache disk tier could not be set up, refusing to start without it\n"); return false; } diff --git a/tools/server/server-page-io.h b/tools/server/server-page-io.h index fb1d6cc8ce57..b0db047e37fb 100644 --- a/tools/server/server-page-io.h +++ b/tools/server/server-page-io.h @@ -176,6 +176,17 @@ class server_page_admission { return false; } + // Admits `bytes` now or refuses: never parks (a caller that cannot wait, e.g. a prompt-cache spill + // that must free RAM now, drops instead of queueing behind the budget). + bool try_admit(uint64_t bytes) { + std::lock_guard lock(m); + if (closed || !waiting.empty() || !fits(bytes)) { + return false; + } + in_flight += bytes; + return true; + } + void release(uint64_t bytes) { std::vector> run; { diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index c6dc835799d6..1d30dd66b0da 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1,4 +1,5 @@ #include "server-task.h" +#include "server-test-faults.h" #include "build-info.h" #include "server-chat.h" @@ -1752,7 +1753,9 @@ json learn_outcome::to_json() const { // server_prompt_cache // size_t server_prompt_cache::size() const { - size_t res = 0; + // resident bytes plus spills whose write has not landed (their entries' vectors are empty while the + // bytes sit in the write's buffer; an erased entry's in-flight bytes still count until it lands) + size_t res = (size_t) spill_in_flight->load(std::memory_order_relaxed); for (const auto & state : states) { res += state.size(); @@ -1785,16 +1788,19 @@ size_t server_prompt_cache::n_tokens() const { server_prompt_cache::~server_prompt_cache() = default; // spill_dir removes this instance's directory -bool server_prompt_cache::set_disk(const std::string & dir, int32_t limit_mib, server_page_io_pool * pool) { +bool server_prompt_cache::set_disk(const std::string & dir, int32_t limit_mib, server_page_io_pool * pool, + server_page_admission * admission_, std::string io_gate_) { std::error_code ec; const size_t swept = spill_dir.claim(dir, ec); - if (!spill_dir.ok() || pool == nullptr) { + if (!spill_dir.ok() || pool == nullptr || admission_ == nullptr) { SRV_ERR("prompt cache disk tier: cannot claim an instance directory under %s: %s\n", dir.c_str(), ec ? ec.message().c_str() : (pool ? "its owner lock is held" : "no page-io pool")); return false; } disk_dir = spill_dir.path().string(); io = pool; + admission = admission_; + io_gate = std::move(io_gate_); disk_limit = 1024ull*1024ull*(limit_mib < 0 ? 0 : limit_mib); SRV_INF("prompt cache disk tier: %s, size limit: %d MiB (%zu abandoned instance directories swept)\n", disk_dir.c_str(), limit_mib, swept); @@ -1818,9 +1824,19 @@ bool server_prompt_cache::spill(server_prompt_cache_state & state) { erase(oldest); } + // admitted against the one page-IO budget before anything moves, never parked: a spill that does not + // fit beside the bytes in flight is refused and the entry is dropped (as with no disk tier), so a slow + // or paused disk can never stack spills past the budget (Codex on #124) + if (!admission->try_admit(bytes)) { + SRV_WRN(" - disk tier: %.3f MiB does not fit the page-IO budget beside the bytes in flight; the entry is dropped\n", + bytes / (1024.0 * 1024.0)); + return false; + } // the task loop only MOVES the bytes into the spill buffer; the file is written on the page-io pool const std::string path = disk_dir + "/" + std::to_string(spill_seq++) + ".state"; auto buf = std::make_shared(); + buf->reservation.hold(admission, bytes); + spill_in_flight->fetch_add(bytes, std::memory_order_relaxed); buf->blocks.reserve(2 + 3 * state.prompt.checkpoints.size()); buf->blocks.push_back(std::move(state.data.main)); buf->blocks.push_back(std::move(state.data.drft)); @@ -1841,7 +1857,10 @@ bool server_prompt_cache::spill(server_prompt_cache_state & state) { state.spilling = buf; const int n_tokens = state.prompt.n_tokens(); - io->submit(path, [buf, path, bytes, n_tokens] { + io->submit(path, [buf, path, bytes, n_tokens, in_flight = spill_in_flight, gate = io_gate] { + if constexpr (server_test_faults::enabled) { + server_test_faults::hold(gate); // a test holds spill writes as it holds page IO + } const auto t0 = std::chrono::steady_clock::now(); FILE * f = fopen(path.c_str(), "wb"); bool ok = f != nullptr; @@ -1859,6 +1878,10 @@ bool server_prompt_cache::spill(server_prompt_cache_state & state) { n_tokens, bytes / (1024.0 * 1024.0), ms); } buf->status.store(ok ? 1 : -1, std::memory_order_release); + // landed (or failed): its bytes leave the budget and the RAM tier's count here, even when its + // entry was erased meanwhile; a failed write's bytes return to the entry as resident data + buf->reservation.release(); + in_flight->fetch_sub(bytes, std::memory_order_relaxed); }); return true; } diff --git a/tools/server/server-task.h b/tools/server/server-task.h index a5d86bf23e29..858976686ef1 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -781,6 +781,9 @@ struct server_prompt_data { struct server_spill_buffer { std::vector> blocks; std::atomic status{0}; + // its bytes, charged to the one page-IO budget from the move until the write lands, whoever + // finishes first (the worker, or an erase that dropped the entry meanwhile) + server_page_reservation reservation; }; struct server_prompt_cache_state { @@ -841,14 +844,21 @@ struct server_prompt_cache { // this instance's directory under the configured one (server-spill-dir.h: another engine's files are // never touched), and the pool its files are written on (the task loop only moves the bytes) - server_spill_dir spill_dir; - server_page_io_pool * io = nullptr; + server_spill_dir spill_dir; + server_page_io_pool * io = nullptr; + server_page_admission * admission = nullptr; + // RAM still held by spills whose write has not landed, entries erased meanwhile included: the + // RAM tier counts it (size()) so eviction never believes it free early (Codex on #124) + std::shared_ptr> spill_in_flight = std::make_shared>(0); + // a test hook: the page-IO gate (server-test-faults.h), so a test pauses spill writes like page IO + std::string io_gate; ~server_prompt_cache(); // enable the disk tier under `dir` (this instance's own directory; instance directories whose owner // is gone are swept), writing on `pool` - bool set_disk(const std::string & dir, int32_t limit_mib, server_page_io_pool * pool); + bool set_disk(const std::string & dir, int32_t limit_mib, server_page_io_pool * pool, server_page_admission * admission, + std::string io_gate); // on the task loop: drop the bytes of spills whose write landed, and keep resident the ones whose // write failed From c46ce4f79d2c88090263ff5c2594a2ff99c7208d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 12:57:12 -0600 Subject: [PATCH 7/9] server: a spill's bytes stay charged until the buffer is freed; the RAM tier refuses an entry rather than breach its cap (Codex's second review of #124) - server_spill_buffer releases its page-IO reservation and the RAM tier's in-flight count in its destructor, i.e. when the last owner lets the bytes go (the write's job, or the entry until reaped or erased), never at the write's completion while the blocks still sit in RAM. - alloc: after every resident is evicted, if bytes in flight still leave no room under the limit, the new state is not cached (Codex's case: cap 100, 80 held, a new 50 -> 130). Receipt (qwen35-0.8b, M5, test-faults build, page-IO gate held, --cache-ram 100, six ~79 MiB minds in turn): RSS 1,095 -> 1,174 MiB after the first and flat through the other five; four allocs refused ("78.950 MiB in flight to disk leave no room under the 100.000 MiB limit"), none allocated past the cap. Gate opened: the held spill landed (78.950 MiB, 17.2 ms), was reaped, and the next mind was cached with no refusal. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-task.cpp | 17 ++++++++++++----- tools/server/server-task.h | 20 +++++++++++++++++--- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index 1d30dd66b0da..5092b202202a 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1836,6 +1836,8 @@ bool server_prompt_cache::spill(server_prompt_cache_state & state) { const std::string path = disk_dir + "/" + std::to_string(spill_seq++) + ".state"; auto buf = std::make_shared(); buf->reservation.hold(admission, bytes); + buf->counted = spill_in_flight; + buf->bytes = bytes; spill_in_flight->fetch_add(bytes, std::memory_order_relaxed); buf->blocks.reserve(2 + 3 * state.prompt.checkpoints.size()); buf->blocks.push_back(std::move(state.data.main)); @@ -1857,7 +1859,7 @@ bool server_prompt_cache::spill(server_prompt_cache_state & state) { state.spilling = buf; const int n_tokens = state.prompt.n_tokens(); - io->submit(path, [buf, path, bytes, n_tokens, in_flight = spill_in_flight, gate = io_gate] { + io->submit(path, [buf, path, bytes, n_tokens, gate = io_gate] { if constexpr (server_test_faults::enabled) { server_test_faults::hold(gate); // a test holds spill writes as it holds page IO } @@ -1878,10 +1880,8 @@ bool server_prompt_cache::spill(server_prompt_cache_state & state) { n_tokens, bytes / (1024.0 * 1024.0), ms); } buf->status.store(ok ? 1 : -1, std::memory_order_release); - // landed (or failed): its bytes leave the budget and the RAM tier's count here, even when its - // entry was erased meanwhile; a failed write's bytes return to the entry as resident data - buf->reservation.release(); - in_flight->fetch_sub(bytes, std::memory_order_relaxed); + // the bytes stay charged until the buffer itself is freed (its destructor): when this job lets + // go and the entry is reaped or erased, whichever is last }); return true; } @@ -2058,6 +2058,13 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro const size_t room_needed = state_size_new > limit_size ? 0 : state_size_new; while (size() + room_needed > limit_size && evict_oldest_resident()) { } + // every resident evicted and still over: bytes in flight to disk hold the rest, so this entry is + // not cached rather than breaching the cap (Codex on #124: cap 100, 80 in flight, a new 50) + if (size() + room_needed > limit_size) { + SRV_WRN(" - prompt state of %.3f MiB not cached: %.3f MiB in flight to disk leave no room under the %.3f MiB limit\n", + state_size_new / (1024.0 * 1024.0), size() / (1024.0 * 1024.0), limit_size / (1024.0 * 1024.0)); + return nullptr; + } } std::vector state_data_tgt; diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 858976686ef1..21e41e02d108 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -781,9 +781,23 @@ struct server_prompt_data { struct server_spill_buffer { std::vector> blocks; std::atomic status{0}; - // its bytes, charged to the one page-IO budget from the move until the write lands, whoever - // finishes first (the worker, or an erase that dropped the entry meanwhile) - server_page_reservation reservation; + // Its bytes stay charged (to the one page-IO budget and to the RAM tier's count) for exactly as long + // as they exist: released here, when the last owner (the write, or the entry until it is reaped or + // erased) lets the buffer go, never at the write's completion while the bytes are still in RAM + // (Codex on #124). + server_page_reservation reservation; + std::shared_ptr> counted; + uint64_t bytes = 0; + + server_spill_buffer() = default; + server_spill_buffer(const server_spill_buffer &) = delete; + server_spill_buffer & operator=(const server_spill_buffer &) = delete; + ~server_spill_buffer() { + reservation.release(); + if (counted) { + counted->fetch_sub(bytes, std::memory_order_relaxed); + } + } }; struct server_prompt_cache_state { From c2a530e743b9ea5672ae9a754573974566eee41a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 13:09:20 -0600 Subject: [PATCH 8/9] server: restoring an in-flight spill takes its bytes back by move, never a deep copy; the buffer frees its bytes before releasing its charge (Codex's third review of #124) - server_spill_buffer status: queued -> writing -> written|failed, or queued -> claimed. A restore before the write starts claims the buffer (CAS) and MOVES the blocks back; the worker sees the claim and skips the write. - A write already running keeps its buffer: load() applies the target/draft KV from it by reference and only the checkpoints (which the slot must own) are copied; the buffer is dropped after apply. - The destructor frees the blocks first, then releases the reservation and the RAM-tier count, so a release that admits queued IO finds the RAM already free. Receipt (qwen35-0.8b, M5, test-faults build, page-IO gate held, --cache-ram 100): Aiko spilled (write paused), then Aiko again: "restored ... from its in-flight spill: 1802 tokens, 78.950 MiB in 0.0 ms", cache_n 1797 of 1801, RSS flat at 1,174 MiB; gate opened: no file written (claimed). The running-write by-reference path is by reading only (no gate inside the write to hold it mid-file). Still open: the cold restore from disk reads synchronously on the loop; it moves onto #118's page-IO completion path next. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-task.cpp | 62 ++++++++++++++++++++++++------------ tools/server/server-task.h | 8 ++++- 2 files changed, 48 insertions(+), 22 deletions(-) diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index 5092b202202a..0d8741f276a3 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1863,6 +1863,10 @@ bool server_prompt_cache::spill(server_prompt_cache_state & state) { if constexpr (server_test_faults::enabled) { server_test_faults::hold(gate); // a test holds spill writes as it holds page IO } + int expected = server_spill_buffer::queued; + if (!buf->status.compare_exchange_strong(expected, server_spill_buffer::writing, std::memory_order_acq_rel)) { + return; // claimed: the entry was restored before this write started; its blocks went back to it + } const auto t0 = std::chrono::steady_clock::now(); FILE * f = fopen(path.c_str(), "wb"); bool ok = f != nullptr; @@ -1879,7 +1883,7 @@ bool server_prompt_cache::spill(server_prompt_cache_state & state) { SRV_INF(" - spilled prompt cache entry to disk: %d tokens, %.3f MiB in %.1f ms (page-io pool)\n", n_tokens, bytes / (1024.0 * 1024.0), ms); } - buf->status.store(ok ? 1 : -1, std::memory_order_release); + buf->status.store(ok ? server_spill_buffer::written : server_spill_buffer::failed, std::memory_order_release); // the bytes stay charged until the buffer itself is freed (its destructor): when this job lets // go and the entry is reaped or erased, whichever is last }); @@ -1892,9 +1896,9 @@ void server_prompt_cache::reap_spills() { continue; } const int status = state.spilling->status.load(std::memory_order_acquire); - if (status == 1) { + if (status == server_spill_buffer::written) { state.spilling.reset(); // written: the RAM copy goes - } else if (status == -1) { + } else if (status == server_spill_buffer::failed) { // the write failed: the bytes come back and the entry stays resident auto & blocks = state.spilling->blocks; size_t b = 0; @@ -1918,18 +1922,34 @@ bool server_prompt_cache::unspill(server_prompt_cache_state & state) { } const auto t0 = std::chrono::steady_clock::now(); if (state.spilling) { - // its bytes are still in RAM (the write is running, landed unreaped, or failed): copy them back - // from the buffer the write reads, never the disk - const auto & blocks = state.spilling->blocks; - size_t b = 0; - state.data.main = blocks[b++]; - state.data.drft = blocks[b++]; + // its bytes are still in RAM, never read back from disk. A write not started yet is claimed and the + // blocks MOVE back (no copy; the worker skips the write). A write running or landed keeps its buffer + // (the worker may be reading it): load() applies the KV from it by reference, and only the + // checkpoints, which the slot must own, are copied (Codex on #124: no full deep copy). + auto & buf = *state.spilling; + int expected = server_spill_buffer::queued; + const bool took = buf.status.compare_exchange_strong(expected, server_spill_buffer::claimed, std::memory_order_acq_rel); + auto & blocks = buf.blocks; + size_t b = 2; // main and drft stay in the buffer unless taken + if (took) { + state.data.main = std::move(blocks[0]); + state.data.drft = std::move(blocks[1]); + } for (auto & ckpt : state.prompt.checkpoints) { - ckpt.data_tgt = blocks[b++]; - ckpt.data_dft = blocks[b++]; - ckpt.data_spec = blocks[b++]; + if (took) { + ckpt.data_tgt = std::move(blocks[b++]); + ckpt.data_dft = std::move(blocks[b++]); + ckpt.data_spec = std::move(blocks[b++]); + } else { + ckpt.data_tgt = blocks[b++]; + ckpt.data_dft = blocks[b++]; + ckpt.data_spec = blocks[b++]; + } + } + if (took) { + state.spilling.reset(); // the moved-from buffer is empty; its charge is released with it } - state.spilling.reset(); + // else: load() reads main/drft from state.spilling and drops it after applying them // the file is removed after its write, in order, on the pool const std::string path = state.spill_path; io->submit(path, [path] { std::error_code rm; std::filesystem::remove(path, rm); }); @@ -2158,8 +2178,11 @@ bool server_prompt_cache::load(server_prompt & prompt, const lora_active_set & l return false; } + // the KV comes from the entry's own vectors, or by reference from its in-flight spill's buffer + const auto & src_main = it_best->spilling ? it_best->spilling->blocks[0] : it_best->data.main; + const auto & src_drft = it_best->spilling ? it_best->spilling->blocks[1] : it_best->data.drft; { - auto & data = it_best->data.main; + const auto & data = src_main; const size_t size = data.size(); const size_t n = llama_state_seq_set_data_ext(ctx_tgt, data.data(), size, id_slot, 0); @@ -2168,13 +2191,10 @@ bool server_prompt_cache::load(server_prompt & prompt, const lora_active_set & l return false; } - - data.clear(); - data.shrink_to_fit(); } { - auto & data = it_best->data.drft; + const auto & data = src_drft; if (!data.empty()) { GGML_ASSERT(ctx_dft); @@ -2186,11 +2206,11 @@ bool server_prompt_cache::load(server_prompt & prompt, const lora_active_set & l return false; } - - data.clear(); - data.shrink_to_fit(); } } + std::vector().swap(it_best->data.main); + std::vector().swap(it_best->data.drft); + it_best->spilling.reset(); // applied: the write (if running) keeps the buffer alive until it finishes prompt = std::move(it_best->prompt); diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 21e41e02d108..a8b347c8ea8c 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -779,8 +779,11 @@ struct server_prompt_data { // A spill in flight: the state's bytes in file order (sequence state main, draft; then each checkpoint's // target, draft, speculative). `status`: 0 writing, 1 written, -1 failed. struct server_spill_buffer { + // status: queued -> writing -> written | failed; or queued -> claimed (the entry was restored before its + // write started: the loop took the blocks back by move and the worker skips the write) + enum : int { queued = 0, written = 1, failed = -1, writing = 2, claimed = 3 }; std::vector> blocks; - std::atomic status{0}; + std::atomic status{queued}; // Its bytes stay charged (to the one page-IO budget and to the RAM tier's count) for exactly as long // as they exist: released here, when the last owner (the write, or the entry until it is reaped or // erased) lets the buffer go, never at the write's completion while the bytes are still in RAM @@ -793,6 +796,9 @@ struct server_spill_buffer { server_spill_buffer(const server_spill_buffer &) = delete; server_spill_buffer & operator=(const server_spill_buffer &) = delete; ~server_spill_buffer() { + // the bytes are freed first: a release can admit queued page IO, which must find the RAM already free + // (Codex on #124) + std::vector>().swap(blocks); reservation.release(); if (counted) { counted->fetch_sub(bytes, std::memory_order_relaxed); From 46e2c07e124822fe801aea639de037081170bc4d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 13:13:23 -0600 Subject: [PATCH 9/9] server: a save never evicts the cache entry the arriving request is about to load (two minds, a RAM tier that holds one) The slot's state is saved before load() takes the arriving mind's entry out of the cache. Making room evicted the oldest resident, which was the arriving mind itself: her spill went in flight, the leaving mind was refused ("not cached"), and she was claimed back from her own unwritten spill. The leaving mind re-prefilled every turn. prompt_save passes the arriving request's tokens and adapters; alloc protects the resident load() will take (the same cheap prefix test, load's 0.25 floor) from eviction and counts it as leaving. The swap holds both for the moment between save and apply, bounded by one entry; update() right after restores the cap if load took another. Receipt (qwen35-0.8b, M5, --cache-ram 100, ~79 MiB minds): two minds alternating, each return 10-24 ms (cache_n 1797/1798) instead of 731-853 ms of full re-prefill before; 0 refusals; RSS 1,253 MiB. Three minds round-robin: disk restores 78.95 MiB in 5.4-6.4 ms; still 2 refusals while a write is in flight (a save waits behind no write yet) and two returns at ~340 ms for 4 tokens, not yet explained: both open, next. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context.cpp | 10 +++++---- tools/server/server-task.cpp | 36 +++++++++++++++++++++++++++------ tools/server/server-task.h | 9 ++++++++- 3 files changed, 44 insertions(+), 11 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 250175805cee..357d5cd75881 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -317,7 +317,9 @@ struct server_slot { server_prompt prompt; - bool prompt_save(server_prompt_cache & prompt_cache) const { + // `next` / `next_lora`: the request about to load from the cache after this save, when there is one + bool prompt_save(server_prompt_cache & prompt_cache, const server_tokens * next = nullptr, + const lora_active_set * next_lora = nullptr) const { if (prompt.tokens.size() == 0) { return false; } @@ -330,7 +332,7 @@ struct server_slot { SRV_TRC(" - saving prompt with length %d, total state size = %.3f MiB (draft: %.3f MiB)\n", (int) prompt.tokens.size(), cur_size / (1024.0 * 1024.0), cur_size_dft / (1024.0 * 1024.0)); - auto * cur = prompt_cache.alloc(prompt, lora_active(lora), cur_size_tgt, cur_size_dft); + auto * cur = prompt_cache.alloc(prompt, lora_active(lora), cur_size_tgt, cur_size_dft, next, next_lora); if (cur == nullptr) { return false; } @@ -1852,10 +1854,10 @@ struct server_context_impl { const int64_t t_start = ggml_time_us(); - ret->prompt_save(*prompt_cache); - const auto task_lora = task.params.lora.empty() ? params_base.lora_adapters : construct_lora_list(task.params.lora); + const auto next_lora = lora_active(task_lora); + ret->prompt_save(*prompt_cache, &task.tokens, &next_lora); if (!ret->prompt_load(*prompt_cache, task.tokens, task_lora)) { ret->prompt_clear(); } diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index 0d8741f276a3..299d6fadac65 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -2010,10 +2010,10 @@ bool server_prompt_cache::evict_oldest_resident() { // a state larger than the whole RAM tier leaves first: it cannot stay, so evicting older // states for it would only push them to disk as well auto oldest = std::find_if(states.begin(), states.end(), [this](const server_prompt_cache_state & s) { - return !s.spilled() && limit_size > 0 && s.size() > limit_size; + return !s.spilled() && &s != keep && limit_size > 0 && s.size() > limit_size; }); if (oldest == states.end()) { - oldest = std::find_if(states.begin(), states.end(), [](const server_prompt_cache_state & s) { return !s.spilled(); }); + oldest = std::find_if(states.begin(), states.end(), [this](const server_prompt_cache_state & s) { return !s.spilled() && &s != keep; }); } if (oldest == states.end()) { return false; @@ -2027,8 +2027,29 @@ bool server_prompt_cache::evict_oldest_resident() { return true; } -server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & prompt, const lora_active_set & lora, size_t state_size_tgt, size_t state_size_dft) { +const server_prompt_cache_state * server_prompt_cache::leaving(const server_tokens & next, const lora_active_set & lora) const { + const server_prompt_cache_state * best = nullptr; + int lcp_best = 0; + for (const auto & s : states) { + if (s.lora != lora || s.prompt.tokens.size() == 0) { + continue; + } + const int lcp = s.prompt.tokens.get_common_prefix(next); + if (float(lcp) / s.prompt.tokens.size() >= 0.25f && lcp > lcp_best) { // load()'s "don't trash" floor + lcp_best = lcp; + best = &s; + } + } + return best; +} + +server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & prompt, const lora_active_set & lora, size_t state_size_tgt, size_t state_size_dft, + const server_tokens * next, const lora_active_set * next_lora) { reap_spills(); + // the resident the incoming request is about to load: evicting it to make room for this save would push + // the very mind arriving to disk and refuse the one leaving (two minds, a tier that holds one) + keep = next != nullptr && next_lora != nullptr ? leaving(*next, *next_lora) : nullptr; + struct keep_reset { const server_prompt_cache_state *& k; ~keep_reset() { k = nullptr; } } keep_reset_ { keep }; // first check if the current state is contained fully in the cache for (auto it = states.begin(); it != states.end(); ++it) { if (it->lora != lora) { @@ -2075,12 +2096,15 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro if (limit_size > 0) { // make room before allocating the new vectors to avoid breaching the limit; an entry // larger than the whole RAM tier goes to disk itself in `update`, displacing nothing + // The protected entry leaves with the load that follows this save (update() restores the cap right + // after if it does not), so it counts as gone: the swap holds both for that moment, bounded by one entry. const size_t room_needed = state_size_new > limit_size ? 0 : state_size_new; - while (size() + room_needed > limit_size && evict_oldest_resident()) { + auto kept = [this] { return keep != nullptr ? keep->size() : 0; }; + while (size() - kept() + room_needed > limit_size && evict_oldest_resident()) { } - // every resident evicted and still over: bytes in flight to disk hold the rest, so this entry is + // every other resident evicted and still over: bytes in flight to disk hold the rest, so this entry is // not cached rather than breaching the cap (Codex on #124: cap 100, 80 in flight, a new 50) - if (size() + room_needed > limit_size) { + if (size() - kept() + room_needed > limit_size) { SRV_WRN(" - prompt state of %.3f MiB not cached: %.3f MiB in flight to disk leave no room under the %.3f MiB limit\n", state_size_new / (1024.0 * 1024.0), size() / (1024.0 * 1024.0), limit_size / (1024.0 * 1024.0)); return nullptr; diff --git a/tools/server/server-task.h b/tools/server/server-task.h index a8b347c8ea8c..ec3605e9231e 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -899,13 +899,20 @@ struct server_prompt_cache { // read a spilled state's bytes back into RAM and remove its file bool unspill(server_prompt_cache_state & state); + // the resident the incoming request will load (load()'s own choice, by the same cheap prefix test) + const server_prompt_cache_state * leaving(const server_tokens & next, const lora_active_set & lora) const; + const server_prompt_cache_state * keep = nullptr; // set only for the duration of one alloc + // remove a state, and its file if it has one std::list::iterator erase(std::list::iterator it); // make room in RAM: the oldest resident state goes to disk, or is dropped without a disk tier bool evict_oldest_resident(); - server_prompt_cache_state * alloc(const server_prompt & prompt, const lora_active_set & lora, size_t state_size_main, size_t state_size_drft); + // `next`: the tokens of the request about to load from this cache (nullptr when none). The resident that + // request will take is never evicted to make room for this save: it is leaving the cache anyway. + server_prompt_cache_state * alloc(const server_prompt & prompt, const lora_active_set & lora, size_t state_size_main, size_t state_size_drft, + const server_tokens * next = nullptr, const lora_active_set * next_lora = nullptr); bool load(server_prompt & prompt, const lora_active_set & lora, const server_tokens & tokens_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot);