Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
serve: optionally reclaim host caches before SAVE admission
tuandat301973ed39ae8e0d
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 6e0ce1c49..a72ac9dda 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -114,6 +114,9 @@ if(STRATA_BUILD_CONVERSATION_TESTS)add_executable(conversation_file_test src/core/conversation_file_test.cpp src/core/conversation_file.cpp)target_include_directories(conversation_file_test PRIVATE include)add_test(NAME conversation_file_test COMMAND conversation_file_test)+ add_executable(session_save_reclaim_test src/core/session_save_reclaim_test.cpp src/core/conversation_file.cpp)+ target_include_directories(session_save_reclaim_test PRIVATE include)+ add_test(NAME session_save_reclaim_test COMMAND session_save_reclaim_test)endif()if(STRATA_HIP_GFX906)diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex d8fd0db35..235b3091b 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -980,6 +980,19 @@ NAME maynot contain a path, a drive, a stream (`:`), a Windows device name (`NUL`, `CON.bin`, `COM1`...), a control character,a leading dot or a trailing dot or space.+`--session-save-reclaim` (an engine argument in the config's `args`, off by default) lets a SAVE that fails its+RAM preflight first release reconstructible host caches: retained K/V buffers, oldest unpinned parked+conversations, then unpinned checkpoints other than the one selected for the file. It stops as soon as measured+available RAM meets the original allocation estimate plus `--conversation-cache-min-free-mib`; it does not lower+that floor or assume that freed allocations have reached the OS. Pinned prefixes and the selected checkpoint+stay intact, including their order and tie preference. Unknown RAM telemetry or an unknown allocation estimate+does not evict anything. The usual admission check still runs before copying state.++This can trade later prefix-cache hits for room to save. Released caches stay released even if admission or file+I/O later fails; the current tokens, images, steering and live device state are unchanged. It cannot guarantee a+SAVE under arbitrary memory pressure. With the option off, or enough RAM at the first probe, cache retention and+the session file format are unchanged. RESTORE is unchanged.+The request must be `Content-Type: application/json` (else `415`) and come from no browser page, Strata's own or atrusted origin (another site's `Origin` gets `403`, also with an API key); the Host and API-key checks apply aseverywhere. Errors: `501` without `--slot-save-path` or with parallel requests; `400` for a slot other than 0, an unknown action, a refuseddiff --git a/include/strata/core/session_save_reclaim.hpp b/include/strata/core/session_save_reclaim.hppnew file mode 100644index 000000000..da2e26c2f--- /dev/null+++ b/include/strata/core/session_save_reclaim.hpp@@ -0,0 +1,55 @@+// Optional SAVE admission: free reconstructible host caches, never the live device state.+#pragma once++#include "strata/core/conversation_file.hpp"+#include "strata/core/conversation_memory.hpp"++namespace strata::core {++struct SessionSaveReclaimed {+ size_t checkpoints = 0, parked = 0, bytes = 0;+};++// Called BEFORE session_save_checkpoints selects a pointer into chain. Probe after each+// eviction: freed capacity is not necessarily physical RAM returned by the allocator.+// No allocation is needed here. Unknown telemetry / sizes cannot justify cache eviction.+// Preserve every explicit pin and exactly the checkpoint the file would have selected.+template<class Probe>+SessionSaveReclaimed session_save_reclaim(std::vector<ConversationCheckpoint>& chain,+ ConversationCache& cache, const SessionSaveLive& live,+ uint64_t floor, Probe available) {+ SessionSaveReclaimed out;+ const auto* selected = session_deepest_checkpoint(chain);+ const uint64_t need = session_save_peak_bytes(selected, live);+ auto room = available();+ auto done = [&] { return !room || need == UINT64_MAX || conversation_memory_admit(room, need, floor); };+ if (done()) return out;+ if (cache.retained_bytes()) {+ out.bytes += cache.retained_bytes();+ { auto unused = cache.take_reuse(); }+ room = available();+ if (done()) return out;+ }+ while (true) {+ const size_t before = cache.bytes();+ if (!cache.evict_oldest()) break; // pinned conversations stay parked+ ++out.parked;+ out.bytes += before - cache.bytes();+ room = available();+ if (done()) return out;+ }+ size_t keep = selected ? size_t(selected - chain.data()) : chain.size();+ // Erase from the back to preserve order, ties and the selected checkpoint's storage.+ for (size_t i = chain.size(); i-- > 0;) {+ if (i == keep || chain[i].pinned) continue;+ out.bytes += chain[i].bytes();+ chain.erase(chain.begin() + static_cast<std::ptrdiff_t>(i));+ if (i < keep) --keep;+ ++out.checkpoints;+ room = available();+ if (done()) break;+ }+ return out;+}++} // namespace strata::corediff --git a/src/core/conversation_file_test.cpp b/src/core/conversation_file_test.cppindex 25f93b8a5..fd85f2cab 100644--- a/src/core/conversation_file_test.cpp+++ b/src/core/conversation_file_test.cpp@@ -1,6 +1,7 @@// CPU-only tests for the on-disk session format (include/strata/core/conversation_file.hpp).// Built with -DSTRATA_BUILD_CONVERSATION_TESTS=ON; no CUDA, no model.#include "strata/core/conversation_file.hpp"+#include "strata/core/session_save_reclaim.hpp"#include <array>#include <cerrno>@@ -698,6 +699,32 @@ int main() {slurp(old_file) == std::vector<char>(9, 'o'), "save: live state and the old file intact");#endif}+ // Opt-in pressure reclamation does not change the selected file bytes, even with pin=N.+ for (bool pin : {false, true}) {+ auto source = sample();+ source.checkpoints[0].pinned = pin;+ const auto live_before = source.live;+ auto expected = sample();+ expected.checkpoints = session_checkpoints_to_save(source.checkpoints);+ const fs::path before_path = dir / "reclaim-before.bin", after_path = dir / "reclaim-after.bin";+ check(session_file_write(before_path.string(), expected, id, written, error), "reclaim: baseline file written");+ ConversationCache parked(1u << 20, 4);+ SessionSaveLive sl; sl.state_bytes = source.live.bytes(); sl.tokens = source.live.ids.size();+ const auto freed = session_save_reclaim(source.checkpoints, parked, sl, 0,+ [] { return std::optional<uint64_t>(0); });+ check(freed.checkpoints == 1, "reclaim: a non-selected checkpoint released");+ check(same_checkpoint(source.live, live_before), "reclaim: live state remains intact");+ check(session_file_write(after_path.string(), source, id, written, error), "reclaim: file written after pressure");+ check(slurp(before_path) == slurp(after_path), "reclaim: file byte-identical to original selection");+ const auto old = slurp(after_path);+ SessionWriteOptions opt;+ opt.fault = [](const char* step) { return std::strcmp(step, "write") == 0 ? ENOSPC : 0; };+ SessionStatus status;+ check(!session_file_write(after_path.string(), source, id, written, error, opt, &status) &&+ status.error == SessionError::storage && !status.published, "reclaim: later write failure reported");+ check(slurp(after_path) == old && same_checkpoint(source.live, live_before) && no_temp(dir),+ "reclaim: later failure preserves old file and live state, no temporary left");+ }// R6: the folder the free-space query is asked about{check(session_free_space_dir("\\\\server\\share\\sessions\\chat.bin", true) == "\\\\server\\share\\sessions\\",diff --git a/src/core/session_save_reclaim_test.cpp b/src/core/session_save_reclaim_test.cppnew file mode 100644index 000000000..019a375ce--- /dev/null+++ b/src/core/session_save_reclaim_test.cpp@@ -0,0 +1,115 @@+// CPU only: pressure is injected through telemetry, not by exhausting the host.+#include "strata/core/session_save_reclaim.hpp"+#include <cstdio>+#include <cstdlib>+#include <new>++static bool deny_alloc = false;+void* operator new(std::size_t n) {+ if (deny_alloc) throw std::bad_alloc();+ if (void* p = std::malloc(n ? n : 1)) return p;+ throw std::bad_alloc();+}+void operator delete(void* p) noexcept { std::free(p); }+void operator delete(void* p, std::size_t) noexcept { std::free(p); }++using namespace strata::core;+static int checks_run = 0;+static void check(bool ok, const char* label) {+ ++checks_run;+ if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); }+}+static ConversationCheckpoint checkpoint(size_t n, bool pinned = false) {+ ConversationCheckpoint c;+ c.ids.assign(n, 42); c.imgs = {{1, 99}};+ c.gdn.assign(4096, 1); c.ple = {2}; c.tails = {3}; c.dead = {4}; c.block_pos = {5};+ c.used = n; c.pinned = pinned;+ return c;+}+static bool same(const ConversationCheckpoint& a, const ConversationCheckpoint& b) {+ return a.ids == b.ids && a.imgs == b.imgs && a.gdn == b.gdn && a.ple == b.ple &&+ a.tails == b.tails && a.dead == b.dead && a.block_pos == b.block_pos &&+ a.used == b.used && a.pinned == b.pinned && a.stage_parts.size() == b.stage_parts.size();+}+static void park(ConversationCache& cache, int tokens, bool pin = false) {+ SavedConversation c; c.live = checkpoint(tokens);+ c.checkpoints.push_back(checkpoint(tokens - 1, pin));+ // Distinct histories, so put() does not remove superseded entries.+ c.live.ids[0] = tokens; c.checkpoints[0].ids[0] = tokens;+ check(cache.put(std::move(c)), "fixture parked");+}+int main() {+ SessionSaveLive live; live.state_bytes = 1000; live.tokens = 100; live.images = 1; live.kv_layers = 2;+ const uint64_t floor = 1u << 20;+ // Every selected position, first-tie preference, and explicit pins (a pin can be shallower).+ for (size_t selected = 0; selected < 4; ++selected) for (bool pin : {false, true}) {+ std::vector<ConversationCheckpoint> chain;+ for (size_t i = 0; i < 4; ++i) chain.push_back(checkpoint(i == selected ? 300 : 100, pin && i == selected));+ if (pin) chain[(selected + 1) % 4].ids.resize(500); // deeper, unpinned+ auto before = *session_deepest_checkpoint(chain);+ const auto* storage = session_deepest_checkpoint(chain)->gdn.data();+ ConversationCache cache(1u << 20, 10);+ park(cache, 10); park(cache, 20, true); park(cache, 30);+ std::vector<ConversationKv> kv(1); kv[0].k.resize(16384); cache.retain(std::move(kv), 100);+ const size_t bytes_before = cache.bytes();+ size_t chain_bytes = 0; for (const auto& c : chain) chain_bytes += c.bytes();+ deny_alloc = true;+ auto freed = session_save_reclaim(chain, cache, live, floor, [] { return std::optional<uint64_t>(0); });+ deny_alloc = false;+ check(chain.size() == 1 && same(chain[0], before), "selected checkpoint unchanged under pressure");+ check(chain[0].gdn.data() == storage, "checkpoint moved without copying storage");+ check(freed.checkpoints == 3 && freed.parked == 2 && cache.size() == 1, "pins survive, other entries reclaimed");+ check(cache.evictions() == 2 && cache.retained_bytes() == 0, "cache accounting and retained buffers");+ check(freed.bytes == bytes_before - cache.bytes() + chain_bytes - chain[0].bytes(), "released byte accounting");+ check(session_deepest_checkpoint(chain)->ids == before.ids, "same file selection after reclaim");+ auto again = session_save_reclaim(chain, cache, live, floor, [] { return std::optional<uint64_t>(0); });+ check(again.bytes == 0 && again.checkpoints == 0 && again.parked == 0, "exhausted reclaim is idempotent");+ }+ // No-pressure path, unknown telemetry, overflowed estimate: no cache mutation.+ for (int mode = 0; mode < 4; ++mode) {+ std::vector<ConversationCheckpoint> chain{checkpoint(100), checkpoint(300)};+ ConversationCache cache(1u << 20, 10); park(cache, 10);+ const auto before = chain;+ const auto bytes = cache.bytes(); auto sl = live;+ if (mode == 2) sl.state_bytes = UINT64_MAX;+ const uint64_t need = session_save_peak_bytes(session_deepest_checkpoint(chain), sl);+ auto r = session_save_reclaim(chain, cache, sl, floor, [&]() -> std::optional<uint64_t> {+ if (mode == 1) return std::nullopt;+ return mode == 2 ? 0 : need + floor + (mode == 3 ? 1 : 0);+ });+ check(!r.bytes && !r.parked && !r.checkpoints && cache.bytes() == bytes, "no eviction without known pressure");+ check(chain.size() == 2 && same(chain[0], before[0]) && same(chain[1], before[1]), "unchanged order/content");+ }+ // Admit after any individual step; never clear the whole cache when one release suffices.+ for (int sufficient_after = 1; sufficient_after <= 4; ++sufficient_after) {+ std::vector<ConversationCheckpoint> chain{checkpoint(100), checkpoint(300), checkpoint(300)};+ auto* selected_storage = chain[1].gdn.data();+ ConversationCache cache(1u << 20, 10); park(cache, 10); park(cache, 20);+ std::vector<ConversationKv> kv(1); kv[0].v.resize(100); cache.retain(std::move(kv), 100);+ const auto need = session_save_peak_bytes(session_deepest_checkpoint(chain), live);+ int probes = 0;+ auto r = session_save_reclaim(chain, cache, live, floor, [&]() -> std::optional<uint64_t> {+ return probes++ >= sufficient_after ? need + floor : 0;+ });+ check(probes == sufficient_after + 1, "stop immediately once RAM meets unchanged floor");+ check(r.parked == size_t(std::min(sufficient_after - 1, 2)), "one-at-a-time parked eviction");+ check(r.checkpoints == size_t(sufficient_after == 4), "checkpoint eviction only after parked cache");+ check(session_deepest_checkpoint(chain)->gdn.data() == selected_storage, "first deepest tie retained");+ }+ {+ std::vector<ConversationCheckpoint> chain{checkpoint(100, true), checkpoint(300, true), checkpoint(500)};+ ConversationCache cache(0, 0);+ auto r = session_save_reclaim(chain, cache, live, floor, [] { return std::optional<uint64_t>(0); });+ check(r.checkpoints == 1 && chain.size() == 2 && chain[0].pinned && chain[1].pinned, "all pins survive in original order");+ std::vector<ConversationCheckpoint> out; std::string why;+ check(!session_save_checkpoints(chain, live, [](uint64_t, std::string& w) { w = "low RAM"; return false; }, out, why)+ && out.empty() && why == "low RAM", "still refused before copying when reclamation is insufficient");+ }+ {+ std::vector<ConversationCheckpoint> chain;+ ConversationCache cache(0, 0);+ auto r = session_save_reclaim(chain, cache, live, floor, [] { return std::optional<uint64_t>(0); });+ check(!r.bytes && !r.checkpoints && !r.parked, "empty chain and disabled cache");+ }+ std::printf("session_save_reclaim: %d checks passed\n", checks_run);+}diff --git a/src/program/generate.cpp b/src/program/generate.cppindex 13badec67..9374183ca 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -22,6 +22,7 @@#include "strata/core/expert_cache.hpp"#include "strata/core/conversation_snapshot.hpp"#include "strata/core/conversation_file.hpp"+#include "strata/core/session_save_reclaim.hpp"#include "strata/core/conversation_memory.hpp"#include "strata/core/coupled_draft.hpp"#include "strata/core/expert_source.hpp"@@ -597,6 +598,7 @@ struct Options {int64_t conversation_cache_min_tokens = 0;/// --serve SAVE: disk space a session file must leave free where it is written (MiB; 0 = no check)int64_t session_min_free_mib = 4096;+ bool session_save_reclaim = false;/// --serve: also keep a checkpoint every N freshly read prompt tokens (0 = only at the last turn boundary)int64_t prompt_cache_every = 16384;bool prompt_cache_tail = false; // optional extra checkpoint at an existing near-tail chunk boundary@@ -742,6 +744,7 @@ void usage() {" --conversation-cache-min-tokens N --serve: park only conversations of at least N tokens, so\n"" short side requests do not take the slots a long one needs (default 0 = park any)\n"" --session-min-free-mib N --serve: disk space a SAVE must leave free (default 4096; 0 = no check)\n"+ " --session-save-reclaim --serve: reclaim unpinned host caches if SAVE needs RAM (opt-in)\n"" --vram-elastic --serve (#533, opt-in, NVIDIA): the expert cache in segments (--vram-segment-mib,\n"" default 512), so the command `VRAM <reserve_mib>` (the server's POST /v1/vram) can\n"" give VRAM back to other programs between requests and take it back later\n"@@ -1818,6 +1821,7 @@ int main(int argc, char** argv) {else if (a == "--pcie-mode") o.pcie_mode = next("--pcie-mode");else if (a == "--serve") o.serve = true;else if (a == "--vision") o.vision = true;+ else if (a == "--session-save-reclaim") o.session_save_reclaim = true;else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache")));else if (a == "--conversation-cache-mib" || a == "--conversation-cache-slots" ||a == "--conversation-cache-min-free-mib" || a == "--conversation-cache-min-tokens" ||@@ -8809,6 +8813,19 @@ int main(int argc, char** argv) {sl.kv_layers = (uint64_t) std::max<int64_t>(ss.qsa_alloc, 0) + 1;}const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20;+ if (o.session_save_reclaim) {+ const auto freed = strata::core::session_save_reclaim(+ checks, conversations, sl, floor, strata::core::conversation_available_memory);+ if (freed.bytes || freed.checkpoints || freed.parked) {+ // A removed tail must not mark a later checkpoint at this length as a tail.+ if (tail_ckpt_len >= 0 && std::none_of(checks.begin(), checks.end(), [&](const auto& c) {+ return int64_t(c.ids.size()) == tail_ckpt_len;+ })) tail_ckpt_len = -1;+ std::fprintf(stderr, "strata serve: save reclaimed %zu checkpoints, %zu parked, "+ "%zu host bytes; checking RAM again\n",+ freed.checkpoints, freed.parked, freed.bytes);+ }+ }auto admit = [&](uint64_t need, std::string& why) {const auto avail = strata::core::conversation_available_memory();if (strata::core::conversation_memory_admit(avail, need, floor)) return true;