diff --git a/.github/workflows/server.yml b/.github/workflows/server.yml index 6d74e8bfd3af..3b952797d141 100644 --- a/.github/workflows/server.yml +++ b/.github/workflows/server.yml @@ -92,10 +92,10 @@ jobs: cmake -B build \ -DGGML_SCHED_NO_REALLOC=ON \ -DLLAMA_SERVER_TEST_FAULTS=ON - cmake --build build --config Release -j $(nproc) --target llama-server test-server-prefill + cmake --build build --config Release -j $(nproc) --target llama-server test-server-prefill test-server-page-io - - name: Prefill scheduling test - run: ctest --test-dir build -C Release -R ^test-server-prefill$ --output-on-failure --no-tests=error + - name: Model-free server validators (prefill scheduling, page IO) + run: ctest --test-dir build -C Release -R "^test-server-(prefill|page-io)$" --output-on-failure --no-tests=error - name: Dream adapter creation and snapshot parity timeout-minutes: 5 @@ -193,10 +193,10 @@ jobs: -DGGML_SCHED_NO_REALLOC=ON ^ -DLLAMA_SERVER_TEST_FAULTS=ON set /A NINJA_JOBS=%NUMBER_OF_PROCESSORS%-1 - cmake --build build --config Release -j %NINJA_JOBS% --target llama-server test-server-prefill + cmake --build build --config Release -j %NINJA_JOBS% --target llama-server test-server-prefill test-server-page-io - - name: Prefill scheduling test - run: ctest --test-dir build -C Release -R ^test-server-prefill$ --output-on-failure --no-tests=error + - name: Model-free server validators (prefill scheduling, page IO) + run: ctest --test-dir build -C Release -R "^test-server-(prefill|page-io)$" --output-on-failure --no-tests=error - name: Python setup id: setup_python diff --git a/include/llama.h b/include/llama.h index 84bdebaf771a..6ff7b047fd40 100644 --- a/include/llama.h +++ b/include/llama.h @@ -1033,6 +1033,17 @@ extern "C" { size_t n_token_capacity, size_t * n_token_count_out); + // Continuum fork: a sequence state file's BODY (the bytes llama_state_seq_save_file writes after + // its framing and tokens) moved between the context and host memory, so the caller can write or + // read the file on another thread while this context keeps decoding. get copies the sequence's + // state out into `dst` (size from file_body_size); set loads a body read from such a file into + // `dest_seq_id`. Each returns the bytes copied, 0 on failure (a failed set leaves the sequence empty). + LLAMA_API size_t llama_state_seq_file_body_size(struct llama_context * ctx, llama_seq_id seq_id); + LLAMA_API size_t llama_state_seq_get_file_body( + struct llama_context * ctx, llama_seq_id seq_id, uint8_t * dst, size_t size); + LLAMA_API size_t llama_state_seq_set_file_body( + struct llama_context * ctx, llama_seq_id dest_seq_id, const uint8_t * src, size_t size); + // Completed state-file IO bytes; returning false cancels the load. The callback // must be cheap and must not call back into the context. Existing API is unchanged. typedef bool (*llama_state_io_progress_callback)(uint64_t completed, uint64_t total, void * user_data); diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 83f195043c6c..c2d348884ce9 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -3304,6 +3304,46 @@ size_t llama_context::state_seq_save_file(llama_seq_id seq_id, const char * file return written; } +size_t llama_context::state_seq_file_body_size(llama_seq_id seq_id) { + llama_io_write_dummy io(false); + try { + return state_seq_write_data(io, seq_id, 0); + } catch (const std::exception & err) { + LLAMA_LOG_ERROR("%s: error sizing sequence state: %s\n", __func__, err.what()); + return 0; + } +} + +size_t llama_context::state_seq_get_file_body(llama_seq_id seq_id, uint8_t * dst, size_t size) { + try { + size_t n = 0; + { + // the host writer copies the tensors out when it goes out of scope + llama_io_write_host io(dst, size); + n = state_seq_write_data(io, seq_id, 0); + } + return n; + } catch (const std::exception & err) { + LLAMA_LOG_ERROR("%s: error copying sequence state: %s\n", __func__, err.what()); + return 0; + } +} + +size_t llama_context::state_seq_set_file_body(llama_seq_id seq_id, const uint8_t * src, size_t size) { + try { + size_t n = 0; + { + // the host reader copies the tensors in when it goes out of scope + llama_io_read_host io(src, size); + n = state_seq_read_data(io, seq_id, 0); + } + return n; + } catch (const std::exception & err) { + LLAMA_LOG_ERROR("%s: error loading sequence state: %s\n", __func__, err.what()); + return 0; + } +} + size_t llama_context::state_write_data(llama_io_write_i & io) { LLAMA_LOG_DEBUG("%s: writing state\n", __func__); @@ -4036,6 +4076,24 @@ size_t llama_state_seq_set_data_ext(llama_context * ctx, const uint8_t * src, si return ctx->state_seq_set_data(seq_id, src, size, flags); } +size_t llama_state_seq_file_body_size(llama_context * ctx, llama_seq_id seq_id) { + ctx->synchronize(); + + return ctx->state_seq_file_body_size(seq_id); +} + +size_t llama_state_seq_get_file_body(llama_context * ctx, llama_seq_id seq_id, uint8_t * dst, size_t size) { + ctx->synchronize(); + + return ctx->state_seq_get_file_body(seq_id, dst, size); +} + +size_t llama_state_seq_set_file_body(llama_context * ctx, llama_seq_id dest_seq_id, const uint8_t * src, size_t size) { + ctx->synchronize(); + + return ctx->state_seq_set_file_body(dest_seq_id, src, size); +} + size_t llama_state_seq_file_size(llama_context * ctx, llama_seq_id seq_id, const llama_token * tokens, size_t n_token_count) { ctx->synchronize(); try { diff --git a/src/llama-context.h b/src/llama-context.h index 645be5cf9e69..86bb220f765f 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -184,6 +184,11 @@ struct llama_context { size_t state_seq_file_size(llama_seq_id seq_id, const llama_token * tokens, size_t n_token_count); + // Continuum fork: the file body (state_seq_write_data at flags 0) through host memory + size_t state_seq_file_body_size(llama_seq_id seq_id); + size_t state_seq_get_file_body(llama_seq_id seq_id, uint8_t * dst, size_t size); + size_t state_seq_set_file_body(llama_seq_id seq_id, const uint8_t * src, size_t size); + size_t state_seq_save_file( llama_seq_id seq_id, const char * filepath, diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ec3dba14b023..4e1fd12b03dc 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -18,6 +18,14 @@ target_compile_features(test-server-page-adapters PRIVATE cxx_std_17) add_test(NAME test-server-page-adapters COMMAND test-server-page-adapters) set_tests_properties(test-server-page-adapters PROPERTIES LABELS "main") +# Model-free validator: KV page file IO off the task loop (a worker pool, one switch per file at a time). +add_executable(test-server-page-io test-server-page-io.cpp) +target_compile_features(test-server-page-io PRIVATE cxx_std_17) +find_package(Threads REQUIRED) +target_link_libraries(test-server-page-io PRIVATE Threads::Threads) +add_test(NAME test-server-page-io COMMAND test-server-page-io) +set_tests_properties(test-server-page-io PROPERTIES LABELS "main") + # Model-free learning-budget validator: the ledger every learning step debits. add_executable(test-server-learn-ledger test-server-learn-ledger.cpp) target_compile_features(test-server-learn-ledger PRIVATE cxx_std_17) diff --git a/tests/test-server-page-io.cpp b/tests/test-server-page-io.cpp new file mode 100644 index 000000000000..f7ddc4af04cf --- /dev/null +++ b/tests/test-server-page-io.cpp @@ -0,0 +1,310 @@ +#include "../tools/server/server-page-io.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Model-free validator of KV page IO off the task loop (server-page-io.h). No sleeps: every wait is +// on the event that proves the claim, with a deadline that only turns a hang into a failure. + +static void require(bool condition, const char * message) { + if (!condition) { + std::cerr << message << '\n'; + std::exit(1); + } +} + +using clock_type = std::chrono::steady_clock; +static constexpr auto deadline = std::chrono::seconds(60); // a hang fails, it never passes + +// A latch the test opens; jobs wait on it. +struct gate { + std::mutex m; + std::condition_variable cv; + bool open = false; + int waiting = 0; + + void wait() { + std::unique_lock lock(m); + ++waiting; + cv.notify_all(); + require(cv.wait_for(lock, deadline, [&] { return open; }), "a held job was never released"); + } + void wait_for_waiting(int n) { + std::unique_lock lock(m); + require(cv.wait_for(lock, deadline, [&] { return waiting >= n; }), "jobs never reached the gate"); + } + void release() { + { std::lock_guard lock(m); open = true; } + cv.notify_all(); + } +}; + +// what this catches: page switches on different files serialized behind each other (the pinned +// fork: one task loop, so four residents' saves cost the ~13.5 s sum, dyno 11b). Each job waits +// until all N are running at once, so a pool that ran them one at a time could never finish one: +// every save's interval contains the instant all N were in flight, so the wall time is one save's +// span and not the sum of N spans. Proven by the ordering of events, not by comparing durations +// (a clock's resolution and thread start-up made `wall < sum` flaky on Windows runners). +static void saves_of_different_files_overlap() { + const int n = 4; + server_page_io_pool pool(n); + gate all_running; + std::atomic running{0}, peak{0}; + std::vector started(n), ended(n); + std::mutex done_m; + std::condition_variable done_cv; + int done = 0; + for (int i = 0; i < n; ++i) { + pool.submit("slot" + std::to_string(i) + ".bin", [&, i] { + started[i] = clock_type::now(); + const int now = ++running; + for (int p = peak.load(); now > p && !peak.compare_exchange_weak(p, now);) {} + all_running.wait(); + --running; + ended[i] = clock_type::now(); + { std::lock_guard lock(done_m); ++done; } + done_cv.notify_all(); + }); + } + all_running.wait_for_waiting(n); // all four are inside their IO at once + const auto all_in_flight = clock_type::now(); + all_running.release(); + { + std::unique_lock lock(done_m); + require(done_cv.wait_for(lock, deadline, [&] { return done == n; }), "the saves never completed"); + } + require(peak.load() == n, "every save's IO ran at once"); + for (int i = 0; i < n; ++i) { + require(started[i] <= all_in_flight && all_in_flight <= ended[i], + "every save was in flight at one instant: the wall is one span, not the sum of them"); + } +} + +// what this catches: a restore reading a page file a save is still writing. Jobs naming one file run +// one at a time, in the order submitted; a job on another file is not held behind them. +static void one_file_has_one_writer_or_reader_at_a_time() { + server_page_io_pool pool(4); + gate first_held; + std::mutex m; + std::condition_variable cv; + std::vector order; + int in_flight = 0, max_in_flight = 0; + bool other_done = false; + auto on_page = [&](int id, bool hold) { + return [&, id, hold] { + { + std::lock_guard lock(m); + max_in_flight = std::max(max_in_flight, ++in_flight); + order.push_back(id); + } + if (hold) { + first_held.wait(); + } + { std::lock_guard lock(m); --in_flight; } + cv.notify_all(); + }; + }; + pool.submit("page.bin", on_page(1, true)); + first_held.wait_for_waiting(1); + pool.submit("page.bin", on_page(2, false)); + pool.submit("page.bin", on_page(3, false)); + pool.submit("other.bin", [&] { + { std::lock_guard lock(m); other_done = true; } + cv.notify_all(); + }); + { + std::unique_lock lock(m); + require(cv.wait_for(lock, deadline, [&] { return other_done; }), "another file's IO waited behind a held one"); + require(order.size() == 1, "nothing behind a held file ran before it finished"); + } + first_held.release(); + { + std::unique_lock lock(m); + require(cv.wait_for(lock, deadline, [&] { return order.size() == 3 && in_flight == 0; }), "the parked switches never ran"); + } + require(max_in_flight == 1, "one file never has two switches in flight"); + require(order == std::vector({ 1, 2, 3 }), "one file's switches run in the order submitted"); +} + +// what this catches: decode stalled while a page's file is written. A loop shaped like the server's +// (it takes events off its queue and decodes between them) keeps decoding while a save's IO is held +// on a worker, and the save's completion reaches it as an event, never polled. +static void decode_progresses_while_a_save_is_in_flight() { + std::mutex m; + std::condition_variable cv; + std::deque events; + gate disk; + server_page_io_pool pool(1); + pool.submit("slot0.bin", [&] { + disk.wait(); // the file write, held until the test has seen decode go on + { std::lock_guard lock(m); events.push_back("save done"); } + cv.notify_all(); + }); + disk.wait_for_waiting(1); + int decoded = 0; + bool save_done = false; + const int steps_while_held = 32; + while (!save_done) { + // a decode step for slot 1 + ++decoded; + if (decoded == steps_while_held) { + { + std::lock_guard held(disk.m); + require(disk.waiting == 1 && !disk.open, "the save's IO is still in flight"); + } + disk.release(); + } + std::unique_lock lock(m); + if (decoded >= steps_while_held) { + require(cv.wait_for(lock, deadline, [&] { return !events.empty(); }), "the save's completion never arrived"); + } + while (!events.empty()) { + save_done = save_done || events.front() == "save done"; + events.pop_front(); + } + } + require(decoded >= steps_while_held, "slot 1 decoded while slot 0's page was written"); +} + +// what this catches: a page file the library cannot read, or a defect read as a page. The framing is +// the library's (magic, version, token count, tokens, then the state body), so old pages restore. +static void a_page_file_round_trips_and_refuses_defects() { + const auto dir = std::filesystem::temp_directory_path() / ("page-io-" + std::to_string(std::rand())); + std::filesystem::create_directories(dir); + const std::string path = (dir / "page.bin").string(); + const server_page_file file { 0x67677371u, 3 }; + const std::vector tokens = { -1, 1, 84, 7, 8 }; + std::vector body(1 << 20); + for (size_t i = 0; i < body.size(); ++i) { + body[i] = (uint8_t) (i * 31); + } + std::string why; + const size_t written = file.write(path, tokens.data(), tokens.size(), body, why); + require(written == 12 + tokens.size() * 4 + body.size() && why.empty(), "the page is written whole"); + require(std::filesystem::file_size(path) == written, "the receipt's bytes are the file's"); + + uint64_t told = 0, total = 0; + auto page = file.read(path, [&](uint64_t done, uint64_t t) { told = done; total = t; return true; }, why); + require(page && page->tokens == tokens && page->body == body && page->n_bytes == written, "the page reads back as written"); + require(told == written && total == written, "progress ends at the file's size"); + + int calls = 0; + require(!file.read(path, [&](uint64_t, uint64_t) { return ++calls < 3; }, why) && why == "state file load cancelled", + "a cancel ends the read"); + require(!server_page_file{ 0x67677371u, 2 }.read(path, nullptr, why), "another version is refused"); + require(!file.read((dir / "missing.bin").string(), nullptr, why), "a missing page is refused"); + + // a token count past the end of the file + const std::vector none; + file.write(path, none.data(), 0, {}, why); + { + FILE * f = std::fopen(path.c_str(), "r+b"); + const uint32_t lie = 1000; + std::fseek(f, 8, SEEK_SET); + std::fwrite(&lie, sizeof(lie), 1, f); + std::fclose(f); + } + require(!file.read(path, nullptr, why), "a token count larger than the file is refused"); + std::filesystem::remove_all(dir); +} + +// what this catches: a save the core already sent dropped at shutdown. +static void stopping_runs_every_submitted_switch() { + std::atomic ran{0}; + { + server_page_io_pool pool(2); + for (int i = 0; i < 16; ++i) { + pool.submit(i % 2 ? "a.bin" : "b.bin", [&] { ++ran; }); + } + } + require(ran.load() == 16, "every submitted switch ran before the pool stopped"); +} + +// what this catches (Fable on #118: the M5 at 0.1 GB free): in-flight page bytes unbounded against +// host memory. Switches are admitted against one budget before they allocate; one that does not fit +// waits, in order, and the release that makes room admits it in that release's own call (an event). +static void page_bytes_are_admitted_against_one_budget() { + server_page_admission budget; + std::vector admitted; + auto later = [&](int id) { return [&admitted, id] { admitted.push_back(id); }; }; + + // unset (0): one switch at a time, however large; nothing ever starves + require(budget.admit_or_park(1600, later(1)), "with nothing in flight a switch is admitted, whatever its size"); + require(!budget.admit_or_park(10, later(2)), "with no budget a second switch waits"); + budget.release(1600); + require(admitted == std::vector({ 2 }), "the release admits the waiter at once"); + budget.release(10); + + // the core's budget: switches that fit run together + budget.set_budget(1000); + require(budget.admit_or_park(600, later(3)) && budget.admit_or_park(400, later(4)), "switches that fit are admitted together"); + require(!budget.admit_or_park(300, later(5)), "a switch past the budget waits"); + require(!budget.admit_or_park(1, later(6)), "and one behind it waits its turn, never jumps the queue"); + require(budget.snapshot().in_flight == 1000 && budget.snapshot().waiting == 2, "the budget counts what is held and waiting"); + budget.release(400); + require(admitted == std::vector({ 2, 5, 6 }), "one release admits every waiter that now fits, in order"); + budget.release(600 + 300 + 1); + + // a switch larger than the whole budget runs alone once the others are done + require(budget.admit_or_park(1, later(7)), "a small switch is admitted"); + require(!budget.admit_or_park(5000, later(8)), "a switch larger than the budget waits for an empty pipe"); + budget.release(1); + require(admitted.back() == 8 && budget.snapshot().in_flight == 5000, "then runs alone"); + budget.release(5000); + + // raising the budget admits at once; a re-measured reservation counts its new size + require(budget.admit_or_park(1000, later(9)), "a full budget"); + require(!budget.admit_or_park(500, later(10)), "waits"); + budget.set_budget(1500); + require(admitted.back() == 10, "raising the budget admits the waiter in the raise"); + budget.resize(1000, 1100); + require(budget.snapshot().in_flight == 1600, "a reservation re-measured when its switch runs counts its new size"); + budget.release(1100); + budget.release(500); + require(budget.snapshot().in_flight == 0 && budget.snapshot().waiting == 0, "everything returned"); +} + +// what this catches (Fable on #118): a restore buffered for a slot that is then given a different +// page (the mind left) holding its bytes until that slot's new turn ends. Dropping it returns its +// bytes at once, admitting the switch waiting behind it; the later release of the same reservation +// (its completion, its destructor) returns nothing twice. +static void a_dropped_restore_returns_its_bytes_at_once() { + server_page_admission budget; + budget.set_budget(1000); + bool next_admitted = false; + { + server_page_reservation restore; + require(budget.admit_or_park(900, [] {}), "the restore is admitted"); + restore.hold(&budget, 900); + require(!budget.admit_or_park(500, [&] { next_admitted = true; }), "the next switch waits behind the buffered restore"); + restore.release(); // its slot was given another task: dropped + require(next_admitted, "the drop admits the waiter at once, not when the slot frees"); + require(budget.snapshot().in_flight == 500, "only the admitted switch is held"); + restore.release(); // the completion arrives later and releases again + } // and the destructor + require(budget.snapshot().in_flight == 500, "a reservation is returned once"); + budget.release(500); +} + +int main() { + saves_of_different_files_overlap(); + one_file_has_one_writer_or_reader_at_a_time(); + decode_progresses_while_a_save_is_in_flight(); + a_page_file_round_trips_and_refuses_defects(); + stopping_runs_every_submitted_switch(); + page_bytes_are_admitted_against_one_budget(); + a_dropped_restore_returns_its_bytes_at_once(); + std::cout << "server page io: ok\n"; + return 0; +} diff --git a/tools/server/server-context-page.inc b/tools/server/server-context-page.inc new file mode 100644 index 000000000000..fa446543fc27 --- /dev/null +++ b/tools/server/server-context-page.inc @@ -0,0 +1,614 @@ +// Continuum fork: KV page switches (POST /slots/{id}?action=save|restore). The task loop only copies +// a sequence's state out of or into the context (bounded, proportional to its bytes); the page's +// files are written or read on page_io (server-page-io.h) while every other slot keeps decoding, +// and the IO's completion is a SERVER_TASK_TYPE_SLOT_PAGE_IO_DONE task back on the loop, which alone +// touches the slot. The HTTP contract and the files are unchanged; the receipt adds copy_ms (the +// loop's share) and io_ms (the worker's). + + // The checkpoints a saved page carries: the oldest (the head of the first user turn) and the + // newest `keep_newest_checkpoints`, in list order, or all of them when the caller asked for no + // subset. With `keep_view_checkpoints`, also the newest at or before the last prompt's view end + // (where its next prompt diverges) and those made for that prompt's end (a next prompt that + // resends it whole); a slot that has run no prompt since a restore keeps them all. The quote and + // the write share this list. + std::vector page_kept_checkpoints(const server_slot & slot, const server_task & task) const { + std::vector kept_checkpoints; + const auto & all = slot.prompt.checkpoints; + const int32_t keep = task.slot_action.keep_newest_checkpoints; + const bool by_view = task.slot_action.keep_view_checkpoints; + const int32_t view_end = slot.prompt.view_end; + const int32_t end_from = slot.prompt.end_from; + const bool keep_all = by_view ? end_from < 0 : keep < 0; + const common_prompt_checkpoint * at_view_end = nullptr; + for (const auto & c : all) { + if (by_view && view_end >= 0 && c.n_tokens <= view_end) { + at_view_end = &c; + } + } + const size_t n = all.size(); + size_t i = 0; + std::string kept_at; + for (const auto & c : all) { + const bool newest = keep > 0 && i + (size_t) keep >= n; + const bool viewed = by_view && (&c == at_view_end || c.n_tokens >= end_from); + if (keep_all || i == 0 || newest || viewed) { + kept_checkpoints.push_back(&c); + kept_at += (kept_at.empty() ? "" : ", ") + std::to_string(c.n_tokens); + } + ++i; + } + if (by_view && !task.slot_action.size_only) { + SLT_INF(slot, "page keeps %zu of %zu checkpoints at n_tokens = [%s] (view end = %d, prompt end from = %d)\n", + kept_checkpoints.size(), n, kept_at.c_str(), view_end, end_from); + } + return kept_checkpoints; + } + + // The `.ckpt` sidecar: the kept checkpoints, each with its target, draft and speculative state. + template + static void page_write_checkpoints(const std::vector & kept, Put && put) { + const uint32_t magic = 0x434B5054u; // 'CKPT' + const uint32_t version = 1; + const uint32_t n_ckpt = (uint32_t) kept.size(); + put(&magic, sizeof(magic)); put(&version, sizeof(version)); put(&n_ckpt, sizeof(n_ckpt)); + for (const auto * k : kept) { + const auto & c = *k; + const int64_t n_tokens = c.n_tokens; + const int32_t pos_min = c.pos_min; + const int32_t pos_max = c.pos_max; + const uint64_t sz_tgt = c.data_tgt.size(); + const uint64_t sz_dft = c.data_dft.size(); + const uint64_t sz_spec = c.data_spec.size(); + put(&n_tokens, sizeof(n_tokens)); put(&pos_min, sizeof(pos_min)); put(&pos_max, sizeof(pos_max)); + put(&sz_tgt, sizeof(sz_tgt)); put(&sz_dft, sizeof(sz_dft)); put(&sz_spec, sizeof(sz_spec)); + put(c.data_tgt.data(), c.data_tgt.size()); + put(c.data_dft.data(), c.data_dft.size()); + put(c.data_spec.data(), c.data_spec.size()); + } + } + + // The `.lora` sidecar: the adapters the state was computed under, each with its file revision. + template + static void page_write_adapters(const std::vector & lora, Put && put) { + const uint32_t magic = 0x4C4F5241u; // 'LORA' + const uint32_t version = 2; + const uint32_t n_lora = (uint32_t) lora.size(); + put(&magic, sizeof(magic)); put(&version, sizeof(version)); put(&n_lora, sizeof(n_lora)); + for (const auto & l : lora) { + const uint32_t n_path = (uint32_t) l.path.size(); + const auto rev = lora_file_revision(l.path); + put(&n_path, sizeof(n_path)); + put(l.path.data(), n_path); + put(&l.scale, sizeof(l.scale)); + put(&rev.first, sizeof(rev.first)); put(&rev.second, sizeof(rev.second)); + } + } + + // NOTE (Continuum fork): SLOT_SAVE does NOT defer on a live slot. Reaching this arm already + // guarantees is_yielding == false (process_single_task declines every task but METRICS/SLOT_GET + // while a decode is yielding), so no llama_decode is in flight and the sequence's KV is at a + // consistent inter-batch boundary; is_processing() means only "this slot has an assigned turn". + // A save is READ-ONLY against that KV, so snapshotting a mid-turn slot is safe, and it is the + // warm restore we want (resume mid-thought). Deferring bounced the save for the whole turn and a + // ~30k-token turn tripped the client's 10 s timeout. The snapshot is taken here, on the loop; the + // files are written on a worker. + void page_save(server_task && task) { + auto job = std::make_shared(); + if (task.slot_action.page_reserved > 0) { + // admitted after it waited: it holds its bytes, returned on any refusal below + job->reservation.hold(&page_io_bytes, task.slot_action.page_reserved); + } + const int id_slot = task.slot_action.id_slot; + server_slot * slot = get_slot_by_id(id_slot); + if (slot == nullptr) { + send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST); + return; + } + + std::vector packed; + try { + packed = slot->prompt.tokens.serialize(); + } catch (const std::exception & err) { + send_error(task, err.what(), ERROR_TYPE_NOT_SUPPORTED); + return; + } + GGML_ASSERT(packed.size() % sizeof(llama_token) == 0); + const auto kept = page_kept_checkpoints(*slot, task); + + if (task.slot_action.size_only || task.slot_action.has_byte_ceiling) { + size_t projected_bytes = llama_state_seq_file_size( + ctx_tgt, slot->id, reinterpret_cast(packed.data()), + packed.size() / sizeof(llama_token)); + if (projected_bytes == 0) { + send_error(task, "Unable to size slot state", ERROR_TYPE_SERVER); + return; + } + bool size_overflow = false; + auto count = [&](const void *, size_t n) { + if (n > std::numeric_limits::max() - projected_bytes) { + size_overflow = true; + } else { + projected_bytes += n; + } + }; + page_write_checkpoints(kept, count); + page_write_adapters(slot->lora, count); + if (size_overflow) { + send_error(task, "Slot file size overflow", ERROR_TYPE_SERVER); + return; + } + if (task.slot_action.size_only) { + auto res = std::make_unique(); + res->id = task.id; + res->id_slot = id_slot; + res->filename = task.slot_action.filename; + res->is_save = true; + res->size_only = true; + res->n_bytes = projected_bytes; + queue_results.send(std::move(res)); + return; + } + // Recheck at this task boundary: decode may have advanced after the quote. + if (task.slot_action.has_byte_ceiling && projected_bytes > task.slot_action.byte_ceiling) { + send_error(task, "Slot state exceeds admitted file bytes", ERROR_TYPE_INVALID_REQUEST); + return; + } + } + + // The bytes this switch will hold, admitted against the page IO budget before any is allocated. + const size_t n_body = llama_state_seq_file_body_size(ctx_tgt, slot->id); + if (n_body == 0) { + send_error(task, "Unable to save slot", ERROR_TYPE_SERVER); + return; + } + size_t n_ckpt = 0, n_lora = 0; + page_write_checkpoints(kept, [&](const void *, size_t n) { n_ckpt += n; }); + page_write_adapters(slot->lora, [&](const void *, size_t n) { n_lora += n; }); + const uint64_t bytes = (uint64_t) n_body + packed.size() + n_ckpt + n_lora; + if (task.slot_action.page_reserved == 0) { + task.slot_action.page_asked_us = ggml_time_us(); + auto parked = std::make_shared(std::move(task)); + parked->slot_action.page_reserved = bytes; + // admitted later: the release that made room posts it back to this loop, holding its bytes + if (!page_io_bytes.admit_or_park(bytes, [this, parked]() { queue_tasks.post(std::move(*parked)); })) { + SRV_DBG("slot %d: save of %" PRIu64 " bytes waits for the page IO budget, id_task = %d\n", id_slot, bytes, parked->id); + return; + } + task = std::move(*parked); + job->reservation.hold(&page_io_bytes, bytes); + } else { + job->reservation.resize(bytes); // decode may have grown the slot since it was admitted + } + job->bytes = bytes; + job->admit_ms = (ggml_time_us() - task.slot_action.page_asked_us) / 1000.0; + + // The loop's share: the slot's state, tokens and sidecars copied into the switch. Each buffer + // is sized once, so the copy is one pass over the bytes. + const int64_t t_copy = ggml_time_us(); + job->is_save = true; + job->id_task = task.id; + job->id_slot = id_slot; + job->filename = task.slot_action.filename; + job->filepath = task.slot_action.filepath; + job->n_tokens = slot->prompt.tokens.size(); + job->body.resize(n_body); + if (llama_state_seq_get_file_body(ctx_tgt, slot->id, job->body.data(), n_body) != n_body) { + send_error(task, "Unable to save slot", ERROR_TYPE_SERVER); + return; + } + job->tokens.resize(packed.size() / sizeof(llama_token)); + std::memcpy(job->tokens.data(), packed.data(), packed.size()); + job->ckpt_sidecar.reserve(n_ckpt); + page_write_checkpoints(kept, [&](const void * p, size_t n) { server_page_put(job->ckpt_sidecar, p, n); }); + page_write_adapters(slot->lora, [&](const void * p, size_t n) { server_page_put(job->lora_sidecar, p, n); }); + job->copy_ms = (ggml_time_us() - t_copy) / 1000.0; + + page_io_submit(task.id, std::move(job), page_write); + } + + // The worker's share of a save: the page and its sidecars on disk. + static void page_write(server_page_job & job) { + const server_page_file file { LLAMA_STATE_SEQ_MAGIC, LLAMA_STATE_SEQ_VERSION }; + job.n_bytes = file.write(job.filepath, job.tokens.data(), job.tokens.size(), job.body, job.error); + if (job.n_bytes == 0) { + return; + } + if (!server_page_write_bytes(job.filepath + ".ckpt", job.ckpt_sidecar)) { + SRV_WRN("slot %d: checkpoint sidecar could not be written: %s (the restore will be cold)\n", job.id_slot, job.filepath.c_str()); + } + if (!server_page_write_bytes(job.filepath + ".lora", job.lora_sidecar)) { + SRV_WRN("slot %d: adapter sidecar could not be written: %s (this page will not restore)\n", job.id_slot, job.filepath.c_str()); + } + // on disk now: the copy is freed here, and its bytes returned to the budget, not when the loop + // takes the completion + std::vector().swap(job.body); + std::vector().swap(job.ckpt_sidecar); + job.reservation.release(); + } + + // A restore reads its page on a worker at once, even while its slot finishes another turn (the + // read overlaps that turn's decode); it is applied on the loop when the read completes and the + // slot is free (the completion defers while the slot is_processing(): it mutates KV a live + // decode reads, and pop_deferred_task(id_slot) services it the instant that slot releases). + void page_restore(server_task && task) { + const int id_slot = task.slot_action.id_slot; + server_slot * slot = get_slot_by_id(id_slot); + if (slot == nullptr) { + send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST); + return; + } + auto progress = task.slot_action.progress; + if (progress) { + auto expected = server_restore_progress::queued; + if (!progress->phase.compare_exchange_strong(expected, server_restore_progress::state)) { + send_error(task, "Restore operation cancelled", ERROR_TYPE_INVALID_REQUEST); + return; + } + } + auto job = std::make_shared(); + job->is_save = false; + job->id_task = task.id; + job->id_slot = id_slot; + job->filename = task.slot_action.filename; + job->filepath = task.slot_action.filepath; + job->occupancy = slot->n_occupancy; + job->progress = std::move(progress); + // the bytes it will hold: the page and its sidecars as they are on disk (a missing file holds + // none and fails its read) + for (const char * suffix : { "", ".ckpt", ".lora" }) { + std::error_code ec; + const auto n = std::filesystem::file_size(job->filepath + suffix, ec); + job->bytes += ec ? 0 : (uint64_t) n; + } + // a later task or erase on this slot drops it (page_slot_reassigned) + auto & pending = pending_restores[id_slot]; + pending.erase(std::remove_if(pending.begin(), pending.end(), [](const auto & w) { return w.expired(); }), pending.end()); + pending.push_back(job); + + const int64_t asked = ggml_time_us(); + auto start = [this, job, asked]() { + job->reservation.hold(&page_io_bytes, job->bytes); + job->admit_ms = (ggml_time_us() - asked) / 1000.0; + page_io_submit(job->id_task, job, page_read); + }; + if (page_io_bytes.admit_or_park(job->bytes, start)) { + start(); + } else { + SRV_DBG("slot %d: restore of %" PRIu64 " bytes waits for the page IO budget, id_task = %d\n", id_slot, job->bytes, task.id); + } + } + + // A slot was given another task or erased: count it, and drop every restore buffered for it. + void page_slot_reassigned(server_slot & slot) { + ++slot.n_occupancy; + auto it = pending_restores.find(slot.id); + if (it == pending_restores.end()) { + return; + } + for (const auto & w : it->second) { + if (auto job = w.lock()) { + page_drop_restore(*job); + } + } + pending_restores.erase(it); + } + + // The restore's bytes return to the budget at once. A read in flight stops at its next part and + // frees its own buffers; a read already done is freed here and answered now, so a completion + // deferred behind the slot's new task never holds it. + void page_drop_restore(server_page_job & job) { + if (job.dropped.exchange(true)) { + return; + } + job.reservation.release(); + if (!job.io_done.load()) { + return; + } + page_free_buffers(job); + if (job.progress) { + job.progress->phase.store(server_restore_progress::failed, std::memory_order_relaxed); + } + send_page_refusal(job.id_task, page_reassigned_message, "slot_reassigned"); + job.answered = true; + } + + static constexpr const char * page_reassigned_message = + "Unable to restore slot: it was given another task or erased while its page was read; " + "its occupant is kept, the page is not applied"; + + static void page_free_buffers(server_page_job & job) { + std::vector().swap(job.body); + std::vector().swap(job.tokens); + job.checkpoints.clear(); + } + + // The worker's share of a restore: the adapter identity, the page and its checkpoints read. The + // identity is read first so a page whose identity is unknown is refused without reading the rest. + static void page_read(server_page_job & job) { + auto * progress = job.progress.get(); + { + const std::string lora_path = job.filepath + ".lora"; + server_page_reader in(lora_path); + uint32_t magic = 0, version = 0, n_lora = 0; + in.get(&magic, sizeof(magic)); in.get(&version, sizeof(version)); in.get(&n_lora, sizeof(n_lora)); + bool ok = in.ok && magic == 0x4C4F5241u && version == 2 && n_lora <= 4096; + for (uint32_t i = 0; ok && i < n_lora; ++i) { + uint32_t n_path = 0; + in.get(&n_path, sizeof(n_path)); + ok = in.ok && n_path <= 4096; + if (!ok) { + break; + } + server_page_adapter a { std::string(n_path, '\0'), 0.0f, 0, 0 }; + in.get(a.path.data(), n_path); + in.get(&a.scale, sizeof(a.scale)); + in.get(&a.size, sizeof(a.size)); in.get(&a.mtime, sizeof(a.mtime)); + ok = in.ok; + job.adapters.push_back(std::move(a)); + } + if (!ok) { + job.error = "the page's adapter identity is missing or unreadable: " + lora_path; + return; + } + } + + const server_page_file file { LLAMA_STATE_SEQ_MAGIC, LLAMA_STATE_SEQ_VERSION }; + auto page = file.read(job.filepath, [&job, progress](uint64_t done, uint64_t total) { + return !job.dropped.load(std::memory_order_relaxed) + && (progress == nullptr || server_restore_progress::on_state_io(done, total, progress)); + }, job.error); + if (!page) { + return; + } + job.tokens = std::move(page->tokens); + job.body = std::move(page->body); + job.n_bytes = page->n_bytes; + + // The checkpoints come back with the state. Any defect in the sidecar leaves the slot as a + // pre-fork restore left it: valid tokens + state, no checkpoints. + job.ckpt_path = job.filepath + ".ckpt"; + server_page_reader in(job.ckpt_path); + if (progress) { + progress->phase.store(server_restore_progress::sidecar, std::memory_order_relaxed); + if (in.ok) { + progress->sidecar_total.store(in.size, std::memory_order_relaxed); + } + } + bool cancelled = false; + auto get = [&](void * ptr, size_t n) { + if (job.dropped.load(std::memory_order_relaxed) + || (progress && progress->cancel_requested.load(std::memory_order_relaxed))) { + cancelled = true; + in.ok = false; + } + in.get(ptr, n); + if (progress && in.ok) { + progress->sidecar_bytes.fetch_add(n, std::memory_order_relaxed); + } + }; + uint32_t magic = 0, version = 0, n_ckpt = 0; + get(&magic, sizeof(magic)); get(&version, sizeof(version)); get(&n_ckpt, sizeof(n_ckpt)); + bool ok = in.ok && magic == 0x434B5054u && version == 1 && n_ckpt <= 4096; + for (uint32_t i = 0; ok && i < n_ckpt; ++i) { + int64_t n_tokens = 0; int32_t pos_min = 0, pos_max = 0; + uint64_t sz_tgt = 0, sz_dft = 0, sz_spec = 0; + get(&n_tokens, sizeof(n_tokens)); get(&pos_min, sizeof(pos_min)); get(&pos_max, sizeof(pos_max)); + get(&sz_tgt, sizeof(sz_tgt)); get(&sz_dft, sizeof(sz_dft)); get(&sz_spec, sizeof(sz_spec)); + // a checkpoint is at most one sequence state; refuse absurd sizes + ok = in.ok && sz_tgt < (1ull << 36) && sz_dft < (1ull << 36) && sz_spec < (1ull << 30); + if (!ok) { + break; + } + auto & c = job.checkpoints.emplace_back(); + c.update_pos(n_tokens, pos_min, pos_max); + c.id_task = -1; + c.data_tgt.resize(sz_tgt); get(c.data_tgt.data(), sz_tgt); + c.data_dft.resize(sz_dft); get(c.data_dft.data(), sz_dft); + c.data_spec.resize(sz_spec); get(c.data_spec.data(), sz_spec); + ok = in.ok; + if (progress && ok) { + progress->checkpoints.fetch_add(1, std::memory_order_relaxed); + } + } + if (cancelled) { + job.error = "Restore operation cancelled"; + return; + } + job.checkpoints_ok = ok; + if (!ok) { + job.checkpoints.clear(); + } + } + + // Hands a switch's file IO to page_io; its completion comes back to the loop as a task with the + // switch's own id, so its HTTP waiter receives the receipt. + void page_io_submit(int id_task, std::shared_ptr job, void (*io)(server_page_job &)) { + std::string gate; + if constexpr (server_test_faults::enabled) { + gate = test_faults.page_io_gate; + } + const std::string file = job->filepath; + page_io->submit(file, [this, job = std::move(job), id_task, io, gate]() { + if constexpr (server_test_faults::enabled) { + server_test_faults::hold(gate); + } + const int64_t t_io = ggml_time_us(); + try { + if (!job->dropped.load()) { + io(*job); + } + } catch (const std::exception & err) { + job->error = err.what(); + } + job->io_ms = (ggml_time_us() - t_io) / 1000.0; + if (job->dropped.load()) { + page_free_buffers(*job); // dropped while it read: nothing it read is applied + job->reservation.release(); + } + job->io_done.store(true); + server_task done(SERVER_TASK_TYPE_SLOT_PAGE_IO_DONE); + done.id = id_task; + done.id_slot = job->id_slot; // a deferred restore is serviced when ITS slot releases + done.slot_action.id_slot = job->id_slot; + done.slot_action.page = job; + queue_tasks.post(std::move(done)); + }); + } + + // A refusal the caller matches on by its typed `refusal`, never by its message. + void send_page_refusal(int id_task, const std::string & message, const char * refusal) { + SRV_WRN("task id = %d, refused (%s): %s\n", id_task, refusal, message.c_str()); + auto res = std::make_unique(); + res->id = id_task; + res->err_type = ERROR_TYPE_INVALID_REQUEST; + res->err_msg = message; + res->refusal = refusal; + queue_results.send(std::move(res)); + } + + void page_io_done(server_task && task) { + const auto job = task.slot_action.page; + if (job->is_save) { + if (!job->error.empty()) { + send_error(task, "Unable to save slot: " + job->error, ERROR_TYPE_SERVER); + return; + } + auto res = std::make_unique(); + res->id = task.id; + res->id_slot = job->id_slot; + res->filename = job->filename; + res->is_save = true; + res->n_tokens = job->n_tokens; + res->n_bytes = job->n_bytes; + res->copy_ms = job->copy_ms; + res->io_ms = job->io_ms; + res->t_ms = job->copy_ms + job->io_ms; + page_io_receipt(*res, *job); + queue_results.send(std::move(res)); + return; + } + if (job->answered) { + return; // dropped after its read and answered then (page_drop_restore) + } + page_apply_restore(std::move(task), *job); + } + + // The loop's share of a restore: the page read, checked, set into its slot. + void page_apply_restore(server_task && task, server_page_job & job) { + auto * progress = job.progress.get(); + auto fail = [&](const std::string & why) { + if (progress) { + progress->phase.store(progress->cancel_requested.load(std::memory_order_relaxed) + ? server_restore_progress::cancelled : server_restore_progress::failed, std::memory_order_relaxed); + } + send_error(task, "Unable to restore slot: " + why, ERROR_TYPE_INVALID_REQUEST); + }; + server_slot * slot = get_slot_by_id(job.id_slot); + if (slot == nullptr) { + fail("Invalid slot ID"); + return; + } + if (!job.error.empty()) { + fail(job.error); // the read failed: the slot was never touched + return; + } + if (slot->n_occupancy != job.occupancy || job.dropped.load()) { + if (progress) { + progress->phase.store(server_restore_progress::failed, std::memory_order_relaxed); + } + send_page_refusal(task.id, page_reassigned_message, "slot_reassigned"); + return; + } + if (slot->is_processing()) { + SRV_DBG("page read for slot %d, which is processing: defer its apply, id_task = %d\n", slot->id, task.id); + queue_tasks.defer(std::move(task)); + return; + } + if (progress && progress->cancel_requested.load(std::memory_order_relaxed)) { + fail("Restore operation cancelled"); + return; + } + + // The adapters the state was computed under, against those loaded now: a page whose identity + // is foreign never touches the KV (its identity is its ACTIVE adapters, server-page-adapters.h). + std::vector page_lora = params_base.lora_adapters; // copy: ptr, task_name, prompt_prefix + { + std::vector loaded; + loaded.reserve(page_lora.size()); + for (const auto & l : page_lora) { + const auto rev = lora_file_revision(l.path); + loaded.push_back({ l.path, rev.first, rev.second }); + } + std::string why; + const auto scales = server_page_adapter_scales(job.adapters, loaded, why); + if (!scales) { + fail("the page's adapter identity does not match the loaded adapters (" + why + "): " + job.filepath + ".lora"); + return; + } + for (size_t i = 0; i < page_lora.size(); ++i) { + page_lora[i].scale = (*scales)[i]; + } + } + + const int64_t t_copy = ggml_time_us(); + // the tokens are checked before the KV is touched + std::optional restored; + try { + restored = server_tokens::deserialize(job.tokens, mctx != nullptr); + } catch (const std::exception & err) { + fail(err.what()); + return; + } + if (restored->size() > (size_t) slot->n_ctx) { + fail("Restored prompt does not fit in the slot context"); + return; + } + if (!restored->validate(ctx_tgt)) { + fail("Invalid tokens in slot save file"); + return; + } + if (llama_state_seq_set_file_body(ctx_tgt, slot->id, job.body.data(), job.body.size()) == 0) { + slot->prompt_clear(); + fail("No available space in KV cache or invalid slot save file"); + return; + } + std::vector().swap(job.body); + + slot->prompt.clear(); + slot->prompt.tokens = std::move(*restored); + slot->lora = std::move(page_lora); + if (job.checkpoints_ok) { + slot->prompt.checkpoints = std::move(job.checkpoints); + SLT_INF(*slot, "restored %zu context checkpoints from the sidecar: %s\n", slot->prompt.checkpoints.size(), job.ckpt_path.c_str()); + } else { + slot->prompt.checkpoints.clear(); + SLT_WRN(*slot, "no usable checkpoint sidecar (%s): the restore is cold — the next divergence re-prefills from the head\n", job.ckpt_path.c_str()); + } + job.copy_ms = (ggml_time_us() - t_copy) / 1000.0; + job.reservation.release(); // its state is the slot's now: nothing of it is in flight + + if (progress) { + progress->phase.store(server_restore_progress::completed, std::memory_order_relaxed); + } + auto res = std::make_unique(); + res->id = task.id; + res->id_slot = job.id_slot; + res->filename = job.filename; + res->is_save = false; + res->n_tokens = slot->prompt.tokens.size(); + res->n_bytes = job.n_bytes; + res->copy_ms = job.copy_ms; + res->io_ms = job.io_ms; + res->t_ms = job.copy_ms + job.io_ms; + page_io_receipt(*res, job); + queue_results.send(std::move(res)); + } + + // The page IO budget as this switch's receipt reports it. + void page_io_receipt(server_task_result_slot_save_load & res, const server_page_job & job) const { + const auto budget = page_io_bytes.snapshot(); + res.admit_ms = job.admit_ms; + res.io_bytes = job.bytes; + res.io_bytes_in_flight = budget.in_flight; + res.io_budget_bytes = budget.budget; + } diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index a5ea94329965..ba7b2093053a 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -16,6 +16,8 @@ #include "server-learn-ledger.h" #include "server-learn-residency.h" #include "server-test-faults.h" +#include "server-page-io.h" +#include "server-page-job.h" #include "build-info.h" #include "common.h" @@ -32,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -280,6 +283,10 @@ struct server_slot { // used to determine the slot that has been used the longest int64_t t_last_used = -1; + // Continuum fork: counts every task given to this slot and every erase; a page restore records + // it when asked and is refused, typed, if it moved before the page was read (server-context-page.inc) + uint64_t n_occupancy = 0; + // generation props int32_t n_ctx = 0; // context size per slot int32_t n_keep = 0; @@ -930,6 +937,11 @@ struct server_context_impl { mtmd_context * mctx = nullptr; const llama_vocab * vocab = nullptr; + // the host bytes in-flight KV page switches hold, admitted against the budget the core sets at + // runtime (POST /page-io/budget; server-page-io.h); thread-safe, read by the routes directly. + // Declared before queue_tasks so it outlives every task holding a reservation. + server_page_admission page_io_bytes; + server_queue queue_tasks; server_response queue_results; @@ -943,6 +955,10 @@ struct server_context_impl { } ~server_context_impl() { + // page IO first: its last jobs release into the budget and post to the live queue; then no + // waiting switch is admitted into a queue being torn down + page_io.reset(); + page_io_bytes.close(); if (!sleeping) { // destroy() is already called when entering sleeping state // we don't call it again here to avoid double free @@ -1065,6 +1081,13 @@ struct server_context_impl { int slots_n_diff = 0; // env: LLAMA_SERVER_SLOTS_N_DIFF server_test_faults test_faults; // the server test build only (LLAMA_SERVER_TEST_FAULTS) + // KV page file IO off the task loop (server-page-io.h), a worker per slot so every slot's page + // can move at once within the page IO budget. Declared after queue_tasks and page_io_bytes so it + // is destroyed first: its jobs post to the one and release into the other. + std::unique_ptr page_io; + // the restores read for each slot and not yet applied, which a later task or erase on it drops + std::map>> pending_restores; + int n_empty_consecutive = 0; std::unique_ptr prompt_cache; @@ -1423,6 +1446,9 @@ struct server_context_impl { for (int i = 0; i < params_base.n_parallel; i++) { slots.emplace_back(); } + if (!page_io) { + page_io = std::make_unique((size_t) params_base.n_parallel); + } // try speculative decoding if (ctx_tgt_seq_rm_type != COMMON_CONTEXT_SEQ_RM_TYPE_NO) { @@ -1504,8 +1530,9 @@ struct server_context_impl { if constexpr (server_test_faults::enabled) { test_faults = server_test_faults::from_env(); if (test_faults.any()) { - SRV_WRN("test faults: prompt checkpoints = %d, speculative checkpoints = %d, prompt fills = %d\n", - test_faults.prompt_checkpoints, test_faults.spec_checkpoints, test_faults.prompt_fills); + SRV_WRN("test faults: prompt checkpoints = %d, speculative checkpoints = %d, prompt fills = %d, page io gate = '%s'\n", + test_faults.prompt_checkpoints, test_faults.spec_checkpoints, test_faults.prompt_fills, + test_faults.page_io_gate.c_str()); } } @@ -1884,6 +1911,7 @@ struct server_context_impl { } bool launch_slot_with_task(server_slot & slot, server_task && task) { + page_slot_reassigned(slot); // a restore buffered for this slot is dropped, never applied over it (server-context-page.inc) // process per-request lora adapters // Continuum fork: a task with no per-request adapters runs the server's own, and goes through // the SAME change check: upstream assigned them without it, so a slot whose KV was computed @@ -2266,6 +2294,7 @@ struct server_context_impl { #include "server-context-learn-residency.inc" #include "server-context-learn.inc" #include "server-context-learn-checkpoint.inc" +#include "server-context-page.inc" void send_final_response(server_slot & slot) { if (slot.task->params.learn_only) { @@ -2814,374 +2843,15 @@ struct server_context_impl { } break; case SERVER_TASK_TYPE_SLOT_SAVE: { - const int id_slot = task.slot_action.id_slot; - server_slot * slot = get_slot_by_id(id_slot); - if (slot == nullptr) { - send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST); - break; - } - // NOTE (Continuum fork): SLOT_SAVE does NOT defer on a live slot. - // Upstream defers save/restore/erase alike when is_processing(), - // out of conservatism — but for SAVE that defer is both needless - // and harmful. Reaching this arm already guarantees is_yielding == - // false (the whitelist at the top of process_single_task declines - // every task but METRICS/SLOT_GET while a decode is yielding), so - // we are on the main thread in the task phase with NO llama_decode - // in flight and the sequence's KV at a consistent inter-batch - // boundary. is_processing() here means only "this slot has an - // assigned turn", not "decode is executing". A save is READ-ONLY - // against that KV, so snapshotting a mid-turn slot is safe — and it - // is exactly the warm-restore we want ("don't miss a beat": resume - // mid-thought). Deferring instead bounced the save for the whole - // multi-second generation, so a ~30k-token turn always tripped the - // client's 10s timeout and the KV page was never captured. RESTORE - // and ERASE MUTATE KV a subsequent decode would then read, so THEY - // keep the is_processing() defer. - - const int64_t t_start = ggml_time_us(); - - std::string filename = task.slot_action.filename; - std::string filepath = task.slot_action.filepath; - - std::vector packed; - try { - packed = slot->prompt.tokens.serialize(); - } catch (const std::exception & err) { - send_error(task, err.what(), ERROR_TYPE_NOT_SUPPORTED); - break; - } - - GGML_ASSERT(packed.size() % sizeof(llama_token) == 0); - // The checkpoints this page carries: the oldest (the head of the first user - // turn) and the newest `keep_newest_checkpoints`, in list order, or all of them - // when the caller asked for no subset. With `keep_view_checkpoints`, also the - // newest at or before the last prompt's view end (where its next prompt - // diverges) and those made for that prompt's end (a next prompt that resends it - // whole); a slot that has run no prompt since a restore keeps them all. The quote - // and the write share this list. - std::vector kept_checkpoints; - { - const auto & all = slot->prompt.checkpoints; - const int32_t keep = task.slot_action.keep_newest_checkpoints; - const bool by_view = task.slot_action.keep_view_checkpoints; - const int32_t view_end = slot->prompt.view_end; - const int32_t end_from = slot->prompt.end_from; - const bool keep_all = by_view ? end_from < 0 : keep < 0; - const common_prompt_checkpoint * at_view_end = nullptr; - for (const auto & c : all) { - if (by_view && view_end >= 0 && c.n_tokens <= view_end) { - at_view_end = &c; - } - } - const size_t n = all.size(); - size_t i = 0; - std::string kept_at; - for (const auto & c : all) { - const bool newest = keep > 0 && i + (size_t) keep >= n; - const bool viewed = by_view && (&c == at_view_end || c.n_tokens >= end_from); - if (keep_all || i == 0 || newest || viewed) { - kept_checkpoints.push_back(&c); - kept_at += (kept_at.empty() ? "" : ", ") + std::to_string(c.n_tokens); - } - ++i; - } - if (by_view && !task.slot_action.size_only) { - SLT_INF(*slot, "page keeps %zu of %zu checkpoints at n_tokens = [%s] (view end = %d, prompt end from = %d)\n", - kept_checkpoints.size(), n, kept_at.c_str(), view_end, end_from); - } - } - auto write_checkpoints = [&](auto && put) { - const uint32_t magic = 0x434B5054u; // 'CKPT' - const uint32_t version = 1; - const uint32_t n_ckpt = (uint32_t) kept_checkpoints.size(); - put(&magic, sizeof(magic)); put(&version, sizeof(version)); put(&n_ckpt, sizeof(n_ckpt)); - for (const auto * kept : kept_checkpoints) { - const auto & c = *kept; - const int64_t n_tokens = c.n_tokens; - const int32_t pos_min = c.pos_min; - const int32_t pos_max = c.pos_max; - const uint64_t sz_tgt = c.data_tgt.size(); - const uint64_t sz_dft = c.data_dft.size(); - const uint64_t sz_spec = c.data_spec.size(); - put(&n_tokens, sizeof(n_tokens)); put(&pos_min, sizeof(pos_min)); put(&pos_max, sizeof(pos_max)); - put(&sz_tgt, sizeof(sz_tgt)); put(&sz_dft, sizeof(sz_dft)); put(&sz_spec, sizeof(sz_spec)); - put(c.data_tgt.data(), c.data_tgt.size()); - put(c.data_dft.data(), c.data_dft.size()); - put(c.data_spec.data(), c.data_spec.size()); - } - }; - auto write_adapters = [&](auto && put) { - const uint32_t magic = 0x4C4F5241u; // 'LORA' - const uint32_t version = 2; - const uint32_t n_lora = (uint32_t) slot->lora.size(); - put(&magic, sizeof(magic)); put(&version, sizeof(version)); put(&n_lora, sizeof(n_lora)); - for (const auto & l : slot->lora) { - const uint32_t n_path = (uint32_t) l.path.size(); - const auto rev = lora_file_revision(l.path); - put(&n_path, sizeof(n_path)); - put(l.path.data(), n_path); - put(&l.scale, sizeof(l.scale)); - put(&rev.first, sizeof(rev.first)); put(&rev.second, sizeof(rev.second)); - } - }; - if (task.slot_action.size_only || task.slot_action.has_byte_ceiling) { - size_t projected_bytes = llama_state_seq_file_size( - ctx_tgt, slot->id, reinterpret_cast(packed.data()), - packed.size() / sizeof(llama_token)); - if (projected_bytes == 0) { - send_error(task, "Unable to size slot state", ERROR_TYPE_SERVER); - break; - } - bool size_overflow = false; - auto count = [&](const void *, size_t n) { - if (n > std::numeric_limits::max() - projected_bytes) { - size_overflow = true; - } else { - projected_bytes += n; - } - }; - write_checkpoints(count); - write_adapters(count); - if (size_overflow) { - send_error(task, "Slot file size overflow", ERROR_TYPE_SERVER); - break; - } - if (task.slot_action.size_only) { - auto res = std::make_unique(); - res->id = task.id; - res->id_slot = id_slot; - res->filename = filename; - res->is_save = true; - res->size_only = true; - res->n_bytes = projected_bytes; - queue_results.send(std::move(res)); - break; - } - // Recheck at this task boundary: decode may have advanced after the quote. - if (task.slot_action.has_byte_ceiling && projected_bytes > task.slot_action.byte_ceiling) { - send_error(task, "Slot state exceeds admitted file bytes", ERROR_TYPE_INVALID_REQUEST); - break; - } - } - const size_t nwrite = llama_state_seq_save_file( - ctx_tgt, filepath.c_str(), slot->id, - reinterpret_cast(packed.data()), packed.size() / sizeof(llama_token)); - if (nwrite == 0) { - send_error(task, "Unable to save slot", ERROR_TYPE_SERVER); - break; - } - // Companion serialization is shared with the pre-write size quote. - { - std::ofstream out(filepath + ".ckpt", std::ios::binary | std::ios::trunc); - write_checkpoints([&](const void * ptr, size_t n) { out.write(reinterpret_cast(ptr), n); }); - if (!out) { - SLT_WRN(*slot, "checkpoint sidecar could not be written: %s (the restore will be cold)\n", filepath.c_str()); - } - } - { - std::ofstream out(filepath + ".lora", std::ios::binary | std::ios::trunc); - write_adapters([&](const void * ptr, size_t n) { out.write(reinterpret_cast(ptr), n); }); - if (!out) { - SLT_WRN(*slot, "adapter sidecar could not be written: %s (this page will not restore)\n", filepath.c_str()); - } - } - - const int64_t t_end = ggml_time_us(); - const double t_save_ms = (t_end - t_start) / 1000.0; - - auto res = std::make_unique(); - res->id = task.id; - res->id_slot = id_slot; - res->filename = filename; - res->is_save = true; - res->n_tokens = slot->prompt.tokens.size(); - res->n_bytes = nwrite; - res->t_ms = t_save_ms; - queue_results.send(std::move(res)); + page_save(std::move(task)); // server-context-page.inc } break; case SERVER_TASK_TYPE_SLOT_RESTORE: { - const int id_slot = task.slot_action.id_slot; - server_slot * slot = get_slot_by_id(id_slot); - if (slot == nullptr) { - send_error(task, "Invalid slot ID", ERROR_TYPE_INVALID_REQUEST); - break; - } - if (slot->is_processing()) { - // if requested slot is unavailable, we defer this task for processing later - SRV_DBG("requested slot is unavailable, defer task, id_task = %d\n", task.id); - queue_tasks.defer(std::move(task)); - break; - } - - auto progress = task.slot_action.progress; - if (progress) { - auto expected = server_restore_progress::queued; - if (!progress->phase.compare_exchange_strong(expected, server_restore_progress::state)) { - send_error(task, "Restore operation cancelled", ERROR_TYPE_INVALID_REQUEST); - break; - } - } - const int64_t t_start = ggml_time_us(); - - std::string filename = task.slot_action.filename; - std::string filepath = task.slot_action.filepath; - - size_t nread = 0; - try { - // Continuum fork: the adapters the state was computed under (see SLOT_SAVE), read - // FIRST so a page whose identity is unknown or foreign never touches the KV. A page - // without them cannot be reused safely, so it is refused: the caller's cold prefill - // is correct; a mislabelled reuse is not. Its identity is its ACTIVE adapters - // (server-page-adapters.h): an adapter it carried at 0.0 never refuses it. - std::vector page_lora = params_base.lora_adapters; // copy: ptr, task_name, prompt_prefix - { - const std::string lora_path = filepath + ".lora"; - std::ifstream in(lora_path, std::ios::binary); - bool ok = (bool) in; - auto get = [&](void * ptr, size_t n) { in.read(reinterpret_cast(ptr), n); ok = ok && (bool) in; }; - uint32_t magic = 0, version = 0, n_lora = 0; - get(&magic, sizeof(magic)); get(&version, sizeof(version)); get(&n_lora, sizeof(n_lora)); - ok = ok && magic == 0x4C4F5241u && version == 2 && n_lora <= 4096; - std::vector recorded; - for (uint32_t i = 0; ok && i < n_lora; ++i) { - uint32_t n_path = 0; - get(&n_path, sizeof(n_path)); - ok = ok && n_path <= 4096; - if (!ok) break; - server_page_adapter a { std::string(n_path, '\0'), 0.0f, 0, 0 }; - get(a.path.data(), n_path); - get(&a.scale, sizeof(a.scale)); - get(&a.size, sizeof(a.size)); get(&a.mtime, sizeof(a.mtime)); - recorded.push_back(std::move(a)); - } - if (!ok) { - throw std::runtime_error("the page's adapter identity is missing or unreadable: " + lora_path); - } - // the same file AS LOADED: a gene adopted in place (same path, new weights) is - // another adapter, and KV computed under the old weights is not its own; an - // unreadable file proves nothing, so it refuses (BigMama on #54) - std::vector loaded; - loaded.reserve(page_lora.size()); - for (const auto & l : page_lora) { - const auto rev = lora_file_revision(l.path); - loaded.push_back({ l.path, rev.first, rev.second }); - } - std::string why; - const auto scales = server_page_adapter_scales(recorded, loaded, why); - if (!scales) { - throw std::runtime_error("the page's adapter identity does not match the loaded adapters (" + why + "): " + lora_path); - } - for (size_t i = 0; i < page_lora.size(); ++i) { - page_lora[i].scale = (*scales)[i]; - } - } - - size_t n_packed = 0; - llama_tokens packed; - nread = llama_state_seq_load_file(ctx_tgt, filepath.c_str(), slot->id, nullptr, 0, &n_packed); - if (nread != 0) { - packed.resize(std::max(1, n_packed)); - nread = llama_state_seq_load_file_with_progress(ctx_tgt, filepath.c_str(), slot->id, - packed.data(), packed.size(), &n_packed, - progress ? server_restore_progress::on_state_io : nullptr, progress.get()); - } - if (nread == 0) { - throw std::runtime_error("No available space in KV cache or invalid slot save file"); - } - packed.resize(n_packed); - - server_tokens restored = server_tokens::deserialize(packed, mctx != nullptr); - - if (restored.size() > (size_t) slot->n_ctx) { - throw std::runtime_error("Restored prompt does not fit in the slot context"); - } - - if (!restored.validate(ctx_tgt)) { - throw std::runtime_error("Invalid tokens in slot save file"); - } - - slot->prompt.clear(); - slot->prompt.tokens = std::move(restored); - slot->lora = std::move(page_lora); - // Continuum fork: bring the context checkpoints back with the state (see - // SLOT_SAVE). Any defect in the sidecar leaves the slot exactly as a - // pre-fork restore left it — valid tokens + state, no checkpoints. - { - const std::string ckpt_path = filepath + ".ckpt"; - std::ifstream in(ckpt_path, std::ios::binary); - if (progress) { - progress->phase.store(server_restore_progress::sidecar, std::memory_order_relaxed); - if (in) { - in.seekg(0, std::ios::end); - const auto total = in.tellg(); - if (total >= 0) progress->sidecar_total.store(uint64_t(total), std::memory_order_relaxed); - in.seekg(0); - } - } - std::list loaded; - bool ok = (bool) in; - auto get = [&](void * ptr, size_t n) { - if (progress && progress->cancel_requested.load(std::memory_order_relaxed)) { - throw std::runtime_error("Restore operation cancelled"); - } - in.read(reinterpret_cast(ptr), n); - ok = ok && (bool) in; - if (progress && in.gcount() > 0) progress->sidecar_bytes.fetch_add(uint64_t(in.gcount()), std::memory_order_relaxed); - }; - if (ok) { - uint32_t magic = 0, version = 0, n_ckpt = 0; - get(&magic, sizeof(magic)); get(&version, sizeof(version)); get(&n_ckpt, sizeof(n_ckpt)); - ok = ok && magic == 0x434B5054u && version == 1 && n_ckpt <= 4096; - for (uint32_t i = 0; ok && i < n_ckpt; ++i) { - int64_t n_tokens = 0; int32_t pos_min = 0, pos_max = 0; - uint64_t sz_tgt = 0, sz_dft = 0, sz_spec = 0; - get(&n_tokens, sizeof(n_tokens)); get(&pos_min, sizeof(pos_min)); get(&pos_max, sizeof(pos_max)); - get(&sz_tgt, sizeof(sz_tgt)); get(&sz_dft, sizeof(sz_dft)); get(&sz_spec, sizeof(sz_spec)); - // a checkpoint is at most one sequence state; refuse absurd sizes - ok = ok && sz_tgt < (1ull << 36) && sz_dft < (1ull << 36) && sz_spec < (1ull << 30); - if (!ok) break; - auto & c = loaded.emplace_back(); - c.update_pos(n_tokens, pos_min, pos_max); - c.id_task = -1; - c.data_tgt.resize(sz_tgt); get(c.data_tgt.data(), sz_tgt); - c.data_dft.resize(sz_dft); get(c.data_dft.data(), sz_dft); - c.data_spec.resize(sz_spec); get(c.data_spec.data(), sz_spec); - if (progress && ok) progress->checkpoints.fetch_add(1, std::memory_order_relaxed); - } - } - if (ok) { - slot->prompt.checkpoints = std::move(loaded); - SLT_INF(*slot, "restored %zu context checkpoints from the sidecar: %s\n", slot->prompt.checkpoints.size(), ckpt_path.c_str()); - } else { - slot->prompt.checkpoints.clear(); - SLT_WRN(*slot, "no usable checkpoint sidecar (%s): the restore is cold — the next divergence re-prefills from the head\n", ckpt_path.c_str()); - } - } - if (progress && progress->cancel_requested.load(std::memory_order_relaxed)) { - throw std::runtime_error("Restore operation cancelled"); - } - } catch (const std::exception & err) { - if (progress) progress->phase.store(progress->cancel_requested.load(std::memory_order_relaxed) - ? server_restore_progress::cancelled : server_restore_progress::failed, std::memory_order_relaxed); - slot->prompt_clear(); - send_error(task, std::string("Unable to restore slot: ") + err.what(), ERROR_TYPE_INVALID_REQUEST); - break; - } - - if (progress) progress->phase.store(server_restore_progress::completed, std::memory_order_relaxed); - const int64_t t_end = ggml_time_us(); - const double t_restore_ms = (t_end - t_start) / 1000.0; - - auto res = std::make_unique(); - res->id = task.id; - res->id_slot = id_slot; - res->filename = filename; - res->is_save = false; - res->n_tokens = slot->prompt.tokens.size(); - res->n_bytes = nread; - res->t_ms = t_restore_ms; - queue_results.send(std::move(res)); + page_restore(std::move(task)); + } break; + case SERVER_TASK_TYPE_SLOT_PAGE_IO_DONE: + { + page_io_done(std::move(task)); } break; case SERVER_TASK_TYPE_SLOT_ERASE: { @@ -3202,6 +2872,7 @@ struct server_context_impl { const size_t n_erased = slot->prompt.tokens.size(); slot->prompt_clear(); + page_slot_reassigned(*slot); // a restore buffered for this slot is dropped, never applied over it auto res = std::make_unique(); res->id = task.id; @@ -6733,6 +6404,29 @@ void server_routes::init_routes() { if (result) { res->ok(result->to_json()); } return res; }; + // The host bytes in-flight KV page switches may hold (server-page-io.h): the core sets it from its + // live host room, one memory budget; raising it admits waiting switches at once. Read and set here, + // never through the task loop: the budget is thread-safe and a waiting switch must not wait on decode. + auto page_io_snapshot = [this]() { + const auto b = ctx_server.page_io_bytes.snapshot(); + return json {{"budget_bytes", b.budget}, {"in_flight_bytes", b.in_flight}, {"waiting", b.waiting}}; + }; + this->get_page_io = [this, page_io_snapshot](const server_http_req &) { + auto res = create_response(true); + res->ok(page_io_snapshot()); + return res; + }; + this->post_page_io_budget = [this, page_io_snapshot](const server_http_req & req) { + auto res = create_response(true); + const json body = req.body.empty() ? json::object() : json::parse(req.body); + if (!body.is_object() || !body.contains("budget_bytes") || !body.at("budget_bytes").is_number_integer() || body.at("budget_bytes").get() < 0) { + res->error(format_error_response("budget_bytes must be an unsigned integer: the host bytes in-flight page switches may hold", ERROR_TYPE_INVALID_REQUEST)); + return res; + } + ctx_server.page_io_bytes.set_budget(body.at("budget_bytes").get()); + res->ok(page_io_snapshot()); + return res; + }; this->post_learn_grants = [grant_route](const server_http_req & req) { return grant_route(req, "register"); }; this->revoke_learn_grant = [grant_route](const server_http_req & req) { return grant_route(req, "revoke"); }; diff --git a/tools/server/server-context.h b/tools/server/server-context.h index a5c5a59370fe..78d544aba9e1 100644 --- a/tools/server/server-context.h +++ b/tools/server/server-context.h @@ -179,6 +179,7 @@ struct server_routes { server_http_context::handler_t get_learn_grants, post_learn_grants, revoke_learn_grant, post_learn_preflight; server_http_context::handler_t get_learn_events; server_http_context::handler_t post_prompt_cache_limit; + server_http_context::handler_t get_page_io, post_page_io_budget; // the KV page IO budget (server-page-io.h) server_http_context::handler_t get_train; server_http_context::handler_t post_train; server_http_context::handler_t post_train_cancel; diff --git a/tools/server/server-page-io.h b/tools/server/server-page-io.h new file mode 100644 index 000000000000..fb1d6cc8ce57 --- /dev/null +++ b/tools/server/server-page-io.h @@ -0,0 +1,385 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Continuum fork: a KV page's file IO runs off the server's task loop. +// +// The pinned fork ran every page save and restore, disk IO included, as one task on the single +// task loop, so a save or restore stalled decode for every other slot while it ran and switches +// issued together waited for each other (the M5, 2026-11-14 00:18:13Z: Benchy's restore waited +// 1,024 ms behind Aris's 1,012 ms). Now the loop only copies a sequence's state out of or into +// the context (bounded, proportional to its bytes); the file write or read runs on this pool, and +// its completion is a task posted back to the loop. Like texture streaming: the render thread +// never blocks on IO. +// +// Model-free: nothing here knows llama, so tests/test-server-page-io.cpp exercises it alone. + +// Runs page file IO on a few worker threads. Jobs naming the same file run one at a time in the +// order submitted (a page has one writer or reader at a time, so a restore never reads a file a +// save is still writing); jobs on different files run at once. +// +// A job reports its own outcome (the server's posts its completion to the task loop); a job that +// throws ends the process rather than losing a page switch silently. Destruction runs every +// submitted job, then joins: a save the core already sent is never dropped at shutdown. +class server_page_io_pool { +public: + explicit server_page_io_pool(size_t n_workers) { + const size_t n = std::max(n_workers, 1); // a pool runs at least the job it is given + workers.reserve(n); + for (size_t i = 0; i < n; ++i) { + workers.emplace_back([this] { work(); }); + } + } + + server_page_io_pool(const server_page_io_pool &) = delete; + server_page_io_pool & operator=(const server_page_io_pool &) = delete; + + ~server_page_io_pool() { + { + std::lock_guard lock(mutex); + stopping = true; + } + cv.notify_all(); + for (auto & w : workers) { + w.join(); + } + } + + size_t n_workers() const { return workers.size(); } + + void submit(const std::string & file, std::function job) { + { + std::lock_guard lock(mutex); + auto it = parked.find(file); + if (it != parked.end()) { + it->second.push_back(std::move(job)); // the file is in flight: run after it, in order + return; + } + parked.emplace(file, std::deque>{}); + ready.push_back({ file, std::move(job) }); + } + cv.notify_one(); + } + +private: + struct runnable { + std::string file; + std::function job; + }; + + void work() { + std::unique_lock lock(mutex); + while (true) { + cv.wait(lock, [&] { return stopping || !ready.empty(); }); + if (ready.empty()) { + return; // stopping, and nothing left to run: a running job hands its successor to its own worker + } + runnable next = std::move(ready.front()); + ready.pop_front(); + lock.unlock(); + next.job(); + lock.lock(); + auto it = parked.find(next.file); + if (it->second.empty()) { + parked.erase(it); + } else { + ready.push_back({ next.file, std::move(it->second.front()) }); + it->second.pop_front(); + cv.notify_one(); + } + } + } + + std::mutex mutex; + std::condition_variable cv; + std::deque ready; + // every file with a job in flight, and the jobs waiting behind it + std::unordered_map>> parked; + bool stopping = false; + std::vector workers; +}; + +// Reads a file's fields in order, streaming (a checkpoint sidecar is parsed straight into the +// checkpoints, never held twice). `ok` turns false at the first short read and stays false; `size` +// is the file's (64-bit on every OS), `at` the bytes read so far. +struct server_page_reader { + FILE * f = nullptr; + uint64_t size = 0; + uint64_t at = 0; + bool ok = false; + + explicit server_page_reader(const std::string & path) { + std::error_code ec; + size = (uint64_t) std::filesystem::file_size(path, ec); + f = ec ? nullptr : std::fopen(path.c_str(), "rb"); + ok = f != nullptr; + } + server_page_reader(const server_page_reader &) = delete; + server_page_reader & operator=(const server_page_reader &) = delete; + ~server_page_reader() { + if (f != nullptr) { + std::fclose(f); + } + } + + uint64_t remaining() const { return size - at; } + + void get(void * dst, size_t n) { + ok = ok && n <= remaining() && (n == 0 || std::fread(dst, 1, n, f) == n); + if (ok) { + at += n; + } + } +}; + +// The bytes page switches hold in host memory, from their copy until their IO ends (a restore's +// until it is applied), admitted against ONE budget the core sets at runtime from its live host room +// (POST /page-io/budget). A switch is admitted before it allocates: at once when its bytes fit beside +// those in flight, or when nothing is in flight (a switch larger than the whole budget runs alone and +// never starves); otherwise it waits, in the order asked, and the release that makes room admits it +// (an event, never a poll). Until the core sets a budget it is 0: one switch's bytes at a time, still +// off the task loop. No number here is a guess: the budget is the core's measurement. +class server_page_admission { +public: + struct snapshot_t { + uint64_t budget = 0; + uint64_t in_flight = 0; + size_t waiting = 0; + }; + + // Admits `bytes` now (true: the caller proceeds, `admitted` is dropped) or parks `admitted`, which + // the release that makes room runs on its own thread, outside this lock. + bool admit_or_park(uint64_t bytes, std::function admitted) { + std::lock_guard lock(m); + if (waiting.empty() && fits(bytes)) { + in_flight += bytes; + return true; + } + if (!closed) { + waiting.push_back({ bytes, std::move(admitted) }); + } + return false; + } + + void release(uint64_t bytes) { + std::vector> run; + { + std::lock_guard lock(m); + in_flight -= std::min(bytes, in_flight); + drain(run); + } + for (auto & f : run) { + f(); + } + } + + // A held reservation re-measured when its switch runs (decode may have grown the slot since). + void resize(uint64_t from, uint64_t to) { + std::vector> run; + { + std::lock_guard lock(m); + in_flight = in_flight - std::min(from, in_flight) + to; + drain(run); + } + for (auto & f : run) { + f(); + } + } + + void set_budget(uint64_t bytes) { + std::vector> run; + { + std::lock_guard lock(m); + budget = bytes; + drain(run); + } + for (auto & f : run) { + f(); + } + } + + // At shutdown: waiting switches are dropped unrun, and no later release admits anything. + void close() { + std::deque dropped; + { + std::lock_guard lock(m); + closed = true; + dropped.swap(waiting); + } + } + + snapshot_t snapshot() const { + std::lock_guard lock(m); + return { budget, in_flight, waiting.size() }; + } + +private: + struct parked { + uint64_t bytes; + std::function admitted; + }; + + bool fits(uint64_t bytes) const { return in_flight == 0 || bytes <= budget - std::min(budget, in_flight); } + + void drain(std::vector> & run) { + while (!closed && !waiting.empty() && fits(waiting.front().bytes)) { + in_flight += waiting.front().bytes; + run.push_back(std::move(waiting.front().admitted)); + waiting.pop_front(); + } + } + + mutable std::mutex m; + uint64_t budget = 0; + uint64_t in_flight = 0; + std::deque waiting; + bool closed = false; +}; + +// The bytes one admitted switch holds, returned to the budget once, by whichever owner is done with +// them first (the worker after a write, the loop after an apply or a drop, or the destructor). +class server_page_reservation { +public: + server_page_reservation() = default; + server_page_reservation(const server_page_reservation &) = delete; + server_page_reservation & operator=(const server_page_reservation &) = delete; + ~server_page_reservation() { release(); } + + void hold(server_page_admission * a, uint64_t bytes) { + admission = a; + held.store(bytes); + } + void resize(uint64_t to) { + const uint64_t from = held.exchange(to); + if (admission != nullptr) { + admission->resize(from, to); + } + } + void release() { + const uint64_t bytes = held.exchange(0); + if (bytes > 0 && admission != nullptr) { + admission->release(bytes); + } + } + uint64_t bytes() const { return held.load(); } + +private: + server_page_admission * admission = nullptr; + std::atomic held{0}; +}; + +// A sequence state file: magic, version, token count, the tokens, then the state body (the bytes +// llama_state_seq_get_file_body copies out). The framing is the library's own +// (llama_state_seq_save_file), so pages written before this change restore and pages written by +// it restore on an engine without it. +struct server_page_file { + uint32_t magic; + uint32_t version; + + // Writes the page; returns its bytes, or 0 with `why`. + size_t write(const std::string & path, const int32_t * tokens, size_t n_tokens, + const std::vector & body, std::string & why) const { + FILE * f = std::fopen(path.c_str(), "wb"); + if (f == nullptr) { + why = "cannot open " + path + " for writing"; + return 0; + } + const uint32_t count = (uint32_t) n_tokens; + bool ok = n_tokens <= UINT32_MAX; + ok = ok && std::fwrite(&magic, sizeof(magic), 1, f) == 1; + ok = ok && std::fwrite(&version, sizeof(version), 1, f) == 1; + ok = ok && std::fwrite(&count, sizeof(count), 1, f) == 1; + ok = ok && (n_tokens == 0 || std::fwrite(tokens, sizeof(int32_t), n_tokens, f) == n_tokens); + ok = ok && (body.empty() || std::fwrite(body.data(), 1, body.size(), f) == body.size()); + ok = (std::fclose(f) == 0) && ok; + if (!ok) { + why = "short write to " + path; + return 0; + } + return sizeof(magic) + sizeof(version) + sizeof(count) + n_tokens * sizeof(int32_t) + body.size(); + } + + struct contents { + std::vector tokens; + std::vector body; + size_t n_bytes = 0; // the whole file + }; + + // Reads a page whole. `progress(done, total)` is told after each part of the body and returning + // false cancels the read. nullopt with `why` on any defect: an unknown framing, a token count + // larger than the file, a short read, a cancel. + std::optional read(const std::string & path, const std::function & progress, + std::string & why) const { + server_page_reader in(path); + if (!in.ok) { + why = "cannot open " + path; + return std::nullopt; + } + uint32_t head[3] = { 0, 0, 0 }; + in.get(head, sizeof(head)); + if (!in.ok) { + why = "truncated framing in " + path; + return std::nullopt; + } + if (head[0] != magic || head[1] != version) { + why = "unknown (magic, version) in " + path; + return std::nullopt; + } + if ((uint64_t) head[2] > in.remaining() / sizeof(int32_t)) { + why = "token count exceeds the file size in " + path; + return std::nullopt; + } + contents out; + out.tokens.resize(head[2]); + in.get(out.tokens.data(), out.tokens.size() * sizeof(int32_t)); + out.body.resize((size_t) in.remaining()); + // progress is told 64 times over the body: a cancel takes effect within 1/64 of the read + const size_t part = std::max(out.body.size() / 64, 1); + for (size_t done = 0; in.ok && done < out.body.size();) { + const size_t n = std::min(part, out.body.size() - done); + in.get(out.body.data() + done, n); + done += n; + if (in.ok && progress && !progress(in.at, in.size)) { + why = "state file load cancelled"; + return std::nullopt; + } + } + if (!in.ok) { + why = "short read in " + path; + return std::nullopt; + } + out.n_bytes = (size_t) in.size; + return out; + } +}; + +// A whole small buffer (a page's sidecar) out to a file; false when it cannot be written. +inline bool server_page_write_bytes(const std::string & path, const std::vector & bytes) { + FILE * f = std::fopen(path.c_str(), "wb"); + if (f == nullptr) { + return false; + } + const bool ok = bytes.empty() || std::fwrite(bytes.data(), 1, bytes.size(), f) == bytes.size(); + return (std::fclose(f) == 0) && ok; +} + +// Appends a sidecar's fields to a buffer. +inline void server_page_put(std::vector & out, const void * src, size_t n) { + const auto * p = (const uint8_t *) src; + out.insert(out.end(), p, p + n); +} diff --git a/tools/server/server-page-job.h b/tools/server/server-page-job.h new file mode 100644 index 000000000000..7e7272005ee7 --- /dev/null +++ b/tools/server/server-page-job.h @@ -0,0 +1,68 @@ +#pragma once + +#include "server-page-adapters.h" +#include "server-page-io.h" +#include "server-task.h" + +#include +#include +#include +#include +#include + +// Continuum fork: one KV page switch in flight between the task loop and its file IO worker +// (server-page-io.h). The loop fills the half it owns (a save's copied state; a restore's slot and +// occupancy), the worker the other (the file written; the page read), and the completion task +// carries it back to the loop, which alone touches the slot. +struct server_page_job { + bool is_save = true; + int id_slot = -1; + std::string filename; + std::string filepath; + + // the slot's occupancy when the switch was asked (server_slot::n_occupancy): a restore whose + // slot has since been given another task or erased is refused, never applied over it + uint64_t occupancy = 0; + + // save: what the loop copied out of the slot (the page body, its tokens, its sidecars) + size_t n_tokens = 0; // the slot's prompt tokens (the receipt's n_saved) + std::vector body; + std::vector tokens; + std::vector ckpt_sidecar; + std::vector lora_sidecar; + + // restore: what the worker read (the adapter identity is checked on the loop, against the + // adapters loaded when it applies) + std::vector adapters; + std::list checkpoints; + bool checkpoints_ok = false; + std::string ckpt_path; + + int id_task = -1; // the switch's HTTP waiter + + // the host bytes this switch holds, admitted against the one page IO budget (server-page-io.h) + server_page_reservation reservation; + uint64_t bytes = 0; // what it was admitted for + double admit_ms = 0; // asked to admitted + + // a restore whose slot was given another task or erased while it was buffered: its bytes are + // returned at once and its read stops (server-context-page.inc page_drop_restore) + std::atomic dropped{false}; + std::atomic io_done{false}; // the worker is done with the buffers; the loop owns them + bool answered = false; // its waiter already has its receipt + + std::string error; // the IO's failure; empty when it succeeded + size_t n_bytes = 0; // the page file's bytes, written or read + double copy_ms = 0; // the loop's share: the state copied out or in + double io_ms = 0; // the worker's share: the files written or read + + std::shared_ptr progress; + + // A switch dropped before it applied (its waiter left and its completion was cancelled, or the + // server stopped) never holds its slot's restore progress open. + ~server_page_job() { + if (progress && !progress->terminal()) { + progress->phase.store(server_restore_progress::cancelled, std::memory_order_relaxed); + } + } +}; diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index b531ba041379..e502d728cda1 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1529,6 +1529,9 @@ json server_task_result_rerank::to_json() { // json server_task_result_error::to_json() { json res = format_error_response(err_msg, err_type); + if (!refusal.empty()) { + res["refusal"] = refusal; + } if (err_type == ERROR_TYPE_EXCEED_CONTEXT_SIZE) { res["n_prompt_tokens"] = n_prompt_tokens; res["n_ctx"] = n_ctx; @@ -1661,14 +1664,23 @@ json server_task_result_slot_save_load::to_json() { if (size_only) { return json {{"id_slot", id_slot}, {"filename", filename}, {"projected_bytes", n_bytes}}; } + const json page_io = { + { "io_bytes", io_bytes }, + { "io_bytes_in_flight", io_bytes_in_flight }, + { "io_budget_bytes", io_budget_bytes }, + }; if (is_save) { return json { { "id_slot", id_slot }, { "filename", filename }, { "n_saved", n_tokens }, { "n_written", n_bytes }, + { "page_io", page_io }, { "timings", { - { "save_ms", t_ms } + { "save_ms", t_ms }, + { "copy_ms", copy_ms }, + { "io_ms", io_ms }, + { "admit_ms", admit_ms }, }}, }; } @@ -1678,8 +1690,12 @@ json server_task_result_slot_save_load::to_json() { { "filename", filename }, { "n_restored", n_tokens }, { "n_read", n_bytes }, + { "page_io", page_io }, { "timings", { - { "restore_ms", t_ms } + { "restore_ms", t_ms }, + { "copy_ms", copy_ms }, + { "io_ms", io_ms }, + { "admit_ms", admit_ms }, }}, }; } diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 681ee333c184..c757135afcc0 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -14,6 +14,8 @@ #include "server-common.h" +struct server_page_job; // server-page-job.h: one page switch between the task loop and its file IO + // One immutable operation identity with cheap counters. The route holds at most // one snapshot per configured slot; task ownership keeps an in-flight one alive. struct server_restore_progress { @@ -57,6 +59,7 @@ enum server_task_type { SERVER_TASK_TYPE_SLOT_SAVE, SERVER_TASK_TYPE_SLOT_RESTORE, SERVER_TASK_TYPE_SLOT_ERASE, + SERVER_TASK_TYPE_SLOT_PAGE_IO_DONE, // Continuum fork: a save's or restore's file IO finished on its worker SERVER_TASK_TYPE_SET_LORA, SERVER_TASK_TYPE_LOAD_LORA, SERVER_TASK_TYPE_SAVE_LORA, @@ -266,6 +269,11 @@ struct server_task { // checkpoint it holds, which is already a page's subset. bool keep_view_checkpoints = false; std::shared_ptr progress; + // SERVER_TASK_TYPE_SLOT_PAGE_IO_DONE: the switch whose file IO finished + std::shared_ptr page; + // a save the page IO budget admitted after it waited: the bytes it holds, and when it asked + uint64_t page_reserved = 0; + int64_t page_asked_us = 0; }; slot_action slot_action; @@ -601,6 +609,8 @@ struct server_task_result_rerank : server_task_result { struct server_task_result_error : server_task_result { error_type err_type = ERROR_TYPE_SERVER; std::string err_msg; + // Continuum fork: a refusal the caller matches on, never by message (e.g. "slot_reassigned") + std::string refusal; // for ERROR_TYPE_EXCEED_CONTEXT_SIZE int32_t n_prompt_tokens = 0; @@ -664,6 +674,16 @@ struct server_task_result_slot_save_load : server_task_result { size_t n_tokens; size_t n_bytes; double t_ms; + // Continuum fork: the task loop's share (the state copied out or in) and the IO worker's (the + // files written or read); t_ms is their sum, the engine's work without any wait for the slot + double copy_ms = 0; + double io_ms = 0; + // the page IO budget (server-page-io.h): this switch's admitted bytes, the wait to admit them, and + // the bytes all switches held and the budget when this receipt was made + double admit_ms = 0; + uint64_t io_bytes = 0; + uint64_t io_bytes_in_flight = 0; + uint64_t io_budget_bytes = 0; virtual json to_json() override; }; diff --git a/tools/server/server-test-faults.h b/tools/server/server-test-faults.h index a46bfc8bd86e..a96e9d905778 100644 --- a/tools/server/server-test-faults.h +++ b/tools/server/server-test-faults.h @@ -1,8 +1,10 @@ #pragma once #include +#include #ifdef LLAMA_SERVER_TEST_FAULTS #include +#include #endif // Continuum fork: failures the server tests inject through the environment, so a test can show @@ -20,6 +22,10 @@ struct server_test_faults { int32_t prompt_checkpoints = 0; // LLAMA_SERVER_TEST_FAIL_CHECKPOINTS: the next N prompt checkpoint copies fail to allocate int32_t spec_checkpoints = 0; // LLAMA_SERVER_TEST_FAIL_SPEC_CHECKPOINTS: the next N speculative checkpoint copies fail to allocate int32_t prompt_fills = 0; // LLAMA_SERVER_TEST_FAIL_PROMPT_FILLS: the next N prompt fills throw after adding their tokens + // LLAMA_SERVER_TEST_PAGE_IO_GATE: a path (a FIFO the test holds) each KV page switch's file IO + // reads one byte from before it starts, so a test holds IO in flight without sleeping: opening a + // FIFO's write end returns once the IO is waiting, and the byte written releases it + std::string page_io_gate; static server_test_faults from_env() { server_test_faults faults; @@ -27,12 +33,28 @@ struct server_test_faults { faults.prompt_checkpoints = read("LLAMA_SERVER_TEST_FAIL_CHECKPOINTS"); faults.spec_checkpoints = read("LLAMA_SERVER_TEST_FAIL_SPEC_CHECKPOINTS"); faults.prompt_fills = read("LLAMA_SERVER_TEST_FAIL_PROMPT_FILLS"); + if (const char * gate = std::getenv("LLAMA_SERVER_TEST_PAGE_IO_GATE")) { + faults.page_io_gate = gate; + } #endif return faults; } bool any() const { - return prompt_checkpoints || spec_checkpoints || prompt_fills; + return prompt_checkpoints || spec_checkpoints || prompt_fills || !page_io_gate.empty(); + } + + // Blocks the calling page IO worker until the test releases it through `gate` (see page_io_gate). + static void hold(const std::string & gate) { +#ifdef LLAMA_SERVER_TEST_FAULTS + if (!gate.empty()) { + std::ifstream in(gate, std::ios::binary); + char released = 0; + in.get(released); + } +#else + (void) gate; +#endif } // true when this occurrence is one to fail, counting it diff --git a/tools/server/server.cpp b/tools/server/server.cpp index bae64ebe1c3f..7724d41bfa04 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -228,6 +228,8 @@ int llama_server(common_params & params, int argc, char ** argv) { routes.post_learn_grants = models_routes->proxy_post; routes.post_learn_preflight = models_routes->proxy_post; routes.post_prompt_cache_limit = models_routes->proxy_post; + routes.get_page_io = models_routes->proxy_get; + routes.post_page_io_budget = models_routes->proxy_post; routes.post_learn_residency = models_routes->proxy_post; routes.release_learn_residency = models_routes->proxy_post; routes.revoke_learn_residency = models_routes->proxy_post; @@ -299,6 +301,8 @@ int llama_server(common_params & params, int argc, char ** argv) { ctx_http.post("/learn/grants", ex_wrapper(routes.post_learn_grants)); ctx_http.get ("/learn/events", ex_wrapper(routes.get_learn_events)); ctx_http.post("/prompt-cache/limit", ex_wrapper(routes.post_prompt_cache_limit)); + ctx_http.get ("/page-io", ex_wrapper(routes.get_page_io)); + ctx_http.post("/page-io/budget", ex_wrapper(routes.post_page_io_budget)); ctx_http.post("/learn/grants/revoke", ex_wrapper(routes.revoke_learn_grant)); ctx_http.get ("/train", ex_wrapper(routes.get_train)); ctx_http.post("/train", ex_wrapper(routes.post_train)); diff --git a/tools/server/tests/unit/test_slot_save.py b/tools/server/tests/unit/test_slot_save.py index 6851f03f4763..fe3601f78259 100644 --- a/tools/server/tests/unit/test_slot_save.py +++ b/tools/server/tests/unit/test_slot_save.py @@ -7,6 +7,7 @@ import time import uuid from pathlib import Path +from typing import IO # sequence state file: magic(4) version(4) payload_size(4), then payload_size llama_token words STATE_FILE_HEADER_SIZE = 12 @@ -242,6 +243,10 @@ def test_deferred_restore_is_bound_to_its_slot(): assert res.status_code == 200 res = server.make_request("POST", "/slots/0?action=save", data={"filename": "page.bin"}) assert res.status_code == 200 and res.body["n_saved"] > 0 + # Room for both restores' pages at once, as the core sets it from its host room: binding, not the + # page IO budget, is what this test is about (unset, the budget admits one switch at a time). + page_bytes = sum((Path(server.slot_save_path) / ("page.bin" + suffix)).stat().st_size for suffix in ("", ".ckpt", ".lora")) + assert server.make_request("POST", "/page-io/budget", data={"budget_bytes": 2 * page_bytes}).status_code == 200 done0 = threading.Event() done1 = threading.Event() @@ -794,3 +799,151 @@ def test_slot_restore_media_file_without_mmproj(mmproj_server): assert res.status_code == 200 assert res.body["timings"]["cache_n"] == 0 assert res.body["content"] == content + + +# Continuum fork: a page switch's file IO runs on a worker, off the task loop (server-page-io.h). +# LLAMA_SERVER_TEST_PAGE_IO_GATE names a FIFO each switch's IO reads one byte from before it starts: +# opening the FIFO's write end returns once that IO is waiting, and the byte written releases it, so +# these tests hold IO in flight without sleeping. + +class HeldPageIo: + def __init__(self, gate: str, request): + self.result: dict = {} + self.writer: IO[bytes] | None = None + either = threading.Event() + + def run(): + self.result["res"] = request() + either.set() + + def open_gate(): + self.writer = open(gate, "wb") # returns once the switch's IO opened the read end + either.set() + + self.thread = threading.Thread(target=run, daemon=True) + self.thread.start() + threading.Thread(target=open_gate, daemon=True).start() + assert either.wait(DEFAULT_HTTP_TIMEOUT), "the page switch neither reached the gate nor answered" + if self.writer is None: + # answered without waiting at the gate: the server was built without the test faults + os.close(os.open(gate, os.O_RDONLY | os.O_NONBLOCK)) # unblock the opener + pytest.skip("llama-server was built without -DLLAMA_SERVER_TEST_FAULTS=ON") + + def release(self): + assert self.writer is not None + self.writer.write(b"\x01") + self.writer.close() + self.thread.join(timeout=DEFAULT_HTTP_TIMEOUT) + assert not self.thread.is_alive(), "the page switch never answered after its IO was released" + return self.result["res"] + + +def start_with_page_io_gate(monkeypatch, tmp_path) -> str: + if not hasattr(os, "mkfifo"): + pytest.skip("the page IO gate is a FIFO") + gate = str(tmp_path / "page-io-gate") + os.mkfifo(gate) + monkeypatch.setenv("LLAMA_SERVER_TEST_PAGE_IO_GATE", gate) + server.server_slots = True + server.start() + return gate + + +def test_decode_continues_while_a_save_is_written(monkeypatch, tmp_path): + # what this catches (the M5 2026-11-14): a save's disk write stalling every other slot's decode. + # Slot 0's save is held in its file write; slot 1 runs a whole completion meanwhile, and the save + # answers once released, with the loop's copy and the worker's IO timed apart. + gate = start_with_page_io_gate(monkeypatch, tmp_path) + assert server.make_request("POST", "/completion", data={ + "prompt": "What is the capital of France?", "id_slot": 0, "cache_prompt": True, + }).status_code == 200 + + held = HeldPageIo(gate, lambda: server.make_request("POST", "/slots/0?action=save", data={"filename": "held.bin"})) + res = server.make_request("POST", "/completion", data={ + "prompt": "Tell me a story about a cat.", "id_slot": 1, "n_predict": 16, "cache_prompt": True, + }) + assert res.status_code == 200 and res.body["timings"]["predicted_n"] > 0 + assert held.thread.is_alive(), "the save answered before its file was written" + + saved = held.release() + assert saved.status_code == 200 and saved.body["n_saved"] == 84 + assert saved.body["page_io"]["io_bytes"] > 0 and saved.body["page_io"]["io_budget_bytes"] == 0 + assert saved.body["page_io"]["io_bytes_in_flight"] == 0, "a written save returns its bytes before its receipt" + timings = saved.body["timings"] + assert timings["copy_ms"] >= 0 and timings["io_ms"] >= 0 + assert abs(timings["save_ms"] - (timings["copy_ms"] + timings["io_ms"])) < 1e-6 + # the file it wrote is the library's own page: it restores + restore = HeldPageIo(gate, lambda: server.make_request("POST", "/slots/1?action=restore", data={"filename": "held.bin"})) + restored = restore.release() + assert restored.status_code == 200 and restored.body["n_restored"] == 84 + assert "copy_ms" in restored.body["timings"] and "io_ms" in restored.body["timings"] + + +def test_a_restore_into_a_slot_given_another_task_meanwhile_is_refused(monkeypatch, tmp_path): + # what this catches: a restore read on a worker applied over a slot that was given another task + # while the page was read, destroying that task's KV. It is refused, typed, and the occupant's + # cache is kept. + gate = start_with_page_io_gate(monkeypatch, tmp_path) + assert server.make_request("POST", "/completion", data={ + "prompt": "What is the capital of France?", "id_slot": 1, "cache_prompt": True, + }).status_code == 200 + saved = HeldPageIo(gate, lambda: server.make_request("POST", "/slots/1?action=save", data={"filename": "page.bin"})).release() + assert saved.status_code == 200 + + restore = HeldPageIo(gate, lambda: server.make_request("POST", "/slots/0?action=restore", data={"filename": "page.bin"})) + held = server.make_request("GET", "/page-io") + assert held.status_code == 200 and held.body["in_flight_bytes"] > 0, "the restore holds its page's bytes" + occupant = server.make_request("POST", "/completion", data={ + "prompt": "What is the capital of Germany?", "id_slot": 0, "cache_prompt": True, + }) + assert occupant.status_code == 200 + # Fable on #118: the slot was given another task, so the restore's bytes return at once, while its + # read is still held, not when it completes + dropped = server.make_request("GET", "/page-io") + assert dropped.body["in_flight_bytes"] == 0 and dropped.body["waiting"] == 0 + + refused = restore.release() + assert refused.status_code == 400 + assert refused.body["error"]["type"] == "invalid_request_error" + assert refused.body["error"]["refusal"] == "slot_reassigned" + + again = server.make_request("POST", "/completion", data={ + "prompt": "What is the capital of Germany?", "id_slot": 0, "cache_prompt": True, + }) + assert again.status_code == 200 + assert again.body["timings"]["prompt_n"] == 1, "the occupant's cache was kept, not overwritten by the page" + + +def test_page_io_budget_admits_a_waiting_switch_when_room_is_made(monkeypatch, tmp_path): + # what this catches (Fable on #118, the M5 at 0.1 GB free): page switches allocating without a + # bound. Unset, the budget admits one switch at a time: a second save waits, holding nothing, + # until the first returns its bytes; the core's budget is set at runtime and reported. + gate = start_with_page_io_gate(monkeypatch, tmp_path) + for slot in (0, 1): + assert server.make_request("POST", "/completion", data={ + "prompt": "What is the capital of France?", "id_slot": slot, "cache_prompt": True, + }).status_code == 200 + assert server.make_request("GET", "/page-io").body == {"budget_bytes": 0, "in_flight_bytes": 0, "waiting": 0} + + first = HeldPageIo(gate, lambda: server.make_request("POST", "/slots/0?action=save", data={"filename": "first.bin"})) + second_result: dict = {} + second = threading.Thread(target=lambda: second_result.update( + res=server.make_request("POST", "/slots/1?action=save", data={"filename": "second.bin"})), daemon=True) + second.start() + # the second save reaches the budget before the first's IO is released: it waits, holding nothing + # beyond the first's bytes (GET /page-io is answered off the task loop) + status = server.make_request("GET", "/page-io").body + held_bytes = status["in_flight_bytes"] + assert held_bytes > 0 + assert server.make_request("POST", "/page-io/budget", data={"budget_bytes": -1}).status_code == 400 + + saved = first.release() + assert saved.status_code == 200 + # the first's release admitted the second; its IO now waits at the gate in turn + with open(gate, "wb") as release: + release.write(b"\x01") + second.join(timeout=DEFAULT_HTTP_TIMEOUT) + assert second_result["res"].status_code == 200 and second_result["res"].body["n_saved"] == 84 + + raised = server.make_request("POST", "/page-io/budget", data={"budget_bytes": 4 * held_bytes}) + assert raised.status_code == 200 and raised.body == {"budget_bytes": 4 * held_bytes, "in_flight_bytes": 0, "waiting": 0}