From aa17fe86480cbe409eeba6f7f1af9a74522e5ac9 Mon Sep 17 00:00:00 2001 From: Maurizio Verde <141346846+maverde73@users.noreply.github.com> Date: Fri, 2 Oct 2026 21:35:34 +0200 Subject: [PATCH] Session files: save and restore a conversation to disk (SAVE/RESTORE, POST /slots/0?action=save|restore) A conversation the engine holds (what a parked snapshot holds) goes to one file and comes back, also after a restart, so a long prompt is not read again: - engine: `SAVE ` / `RESTORE ` between requests, answered `SAVED|RESTORED ` or `ERR `; single GPU only (refused with --layer-split) and needs --prompt-cache > 0. - format v1 (src/core/conversation_file.cpp): 64-byte header bound to a model fingerprint (name, size, first and last MiB of each weight file) and a config fingerprint (engine version, --kv, STRATA_KV_ROT, --kv-resident, --max-context, --mtp-window, control vectors), the payload, a payload hash and an end marker; written to `.tmp` and renamed over `path` (MoveFileExW on Windows). - fail-closed restore: size, header, both fingerprints, every count against the bytes left, the payload hash and the usual snapshot validation all run before any device write; a refused file leaves the session untouched. - only the deepest checkpoint is saved (the next turn's resume point) and the K/V is streamed from the pools straight into the file's 16 MiB blocks, without a full host capture; Linux uses O_DIRECT when the filesystem takes it (buffered otherwise or with STRATA_SESSION_BUFFERED=1), Windows buffered Win32 I/O. - serve/server.py: llama-server's `POST /slots/0?action=save|restore {"filename": NAME}` with --slot-save-path DIR (or "slot_save_path" in the config); NAME must be a plain file name inside DIR. RTX 4070 Ti, IQ3_XXS, a 63,025-token conversation: file 1.20 GB, save 0.72 s, restore 0.89 s, the next 32-token turn after a restore 1.15 s (first token 0.55 s) with the same output tokens as without saving. Tests: conversation_file_test (CPU, no model; also built for Windows and run under Wine), conversation_snapshot_test, serve/test_slots.py, serve/test_security.py. --- CMakeLists.txt | 3 + include/strata/core/conversation_file.hpp | 66 ++ include/strata/core/conversation_snapshot.hpp | 11 + serve/server.py | 68 ++ serve/test_security.py | 19 + serve/test_slots.py | 169 +++++ src/core/conversation_file.cpp | 631 ++++++++++++++++++ src/core/conversation_file_test.cpp | 303 +++++++++ src/core/conversation_snapshot.cpp | 19 + src/core/conversation_snapshot_test.cpp | 41 ++ src/core/conversation_state.cpp | 21 + src/program/generate.cpp | 102 +++ 12 files changed, 1453 insertions(+) create mode 100644 include/strata/core/conversation_file.hpp create mode 100644 serve/test_slots.py create mode 100644 src/core/conversation_file.cpp create mode 100644 src/core/conversation_file_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index f810e344..bd8cb892 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -104,6 +104,9 @@ if(STRATA_BUILD_CONVERSATION_TESTS) add_executable(conversation_memory_test src/core/conversation_memory_test.cpp src/core/conversation_memory.cpp) target_include_directories(conversation_memory_test PRIVATE include) add_test(NAME conversation_memory_test COMMAND conversation_memory_test) + 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) endif() if(STRATA_HIP_GFX906) diff --git a/include/strata/core/conversation_file.hpp b/include/strata/core/conversation_file.hpp new file mode 100644 index 00000000..d4f7b965 --- /dev/null +++ b/include/strata/core/conversation_file.hpp @@ -0,0 +1,66 @@ +// On-disk persistence of a parked conversation (SavedConversation): one file that holds the running state, +// the checkpoint chain, every QSA layer's authoritative K/V and the draft layer's K/V. Pure host code: no CUDA. +// Format and the fail-closed read order are in docs/DETAILS.md (Session files). +#pragma once + +#include "strata/core/conversation_cache.hpp" + +#include +#include +#include +#include +#include +#include + +namespace strata::core { + +// What the file is bound to: the model files it was computed with, and the engine options that change what the +// saved bytes mean. A read with any other identity is refused. +struct SessionFileIdentity { + uint64_t model = 0, config = 0; +}; + +// Non-cryptographic 64-bit hash (corruption and identity, not adversarial input). Streaming and one-shot agree. +class SessionHasher { +public: + explicit SessionHasher(uint64_t seed = 0); + void update(const void* data, size_t n); + uint64_t digest() const; +private: + void block(const uint8_t* p); + uint64_t lane_[4]; + uint8_t pending_[32]; + size_t npending_ = 0; + uint64_t total_ = 0; +}; +uint64_t session_hash64(const void* data, size_t n, uint64_t seed); + +// Sampled fingerprint of model files: base name, size, first and last MiB of each, in the given order. +bool session_model_fingerprint(const std::vector& paths, uint64_t& fingerprint, std::string& error); + +// Writes `.tmp` then renames it over `path`; on failure no file is left at either name. +bool session_file_write(const std::string& path, const SavedConversation& image, const SessionFileIdentity& id, + size_t& bytes, std::string& error); + +// One K/V layer read straight from where it lives (device or pinned host pool) into the file's staging buffer, +// without a full host copy first. `read(part, offset, dst, n)` copies bytes [offset, offset+n) of part +// 0..4 = k, v, k_scale, v_scale, pooled. The file bytes are identical to writing a captured ConversationKv. +struct SessionKvSource { + int format = 0; + int64_t cells = 0, heads = 0, head_dim = 0, page_size = 0, pooled_rows = 0, idx_dim = 0; + std::array sizes{}; + std::function read; +}; +// `meta` carries everything but the K/V (meta.kv must be empty); `kv` supplies the layers in order. +bool session_file_write(const std::string& path, const SavedConversation& meta, const std::vector& kv, + const SessionFileIdentity& id, size_t& bytes, std::string& error); + +// The checkpoints worth a disk write: the deepest one (the next turn's resume point when the live tail was +// rewritten). Earlier checkpoints only serve edits further back and cost ~118 MB each at this geometry. +std::vector session_checkpoints_to_save(const std::vector& chain); +// Full validation (size, header, identity, bounded parse, payload hash) before `image` is replaced. +// On failure `image` is unchanged. +bool session_file_read(const std::string& path, const SessionFileIdentity& id, SavedConversation& image, + size_t& bytes, std::string& error); + +} // namespace strata::core diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hpp index 1a56680d..e7bfdf4b 100644 --- a/include/strata/core/conversation_snapshot.hpp +++ b/include/strata/core/conversation_snapshot.hpp @@ -1,6 +1,7 @@ #pragma once #include "strata/core/conversation_cache.hpp" +#include "strata/core/conversation_file.hpp" #include "strata/core/layer.hpp" #include "strata/core/session.hpp" @@ -29,6 +30,10 @@ bool conversation_kv_restore(const ConversationKv& image, const QsaState& state, // fingerprints the authoritative payload only. Never changes model state. bool conversation_kv_verify(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, int64_t upto, bool include_index, uint64_t& fingerprint, std::string& error); +// Disk save without a host copy: the layer's authoritative K/V as a streamed source (same bytes and metadata as +// conversation_kv_save). Caller synchronizes the device first and keeps the state untouched while it is read. +bool conversation_kv_source(SessionKvSource& source, const QsaState& state, const ModelGeometry& g, + int64_t upto, bool include_index, std::string& error); struct ConversationStateSizes { size_t gdn = 0, ple = 0, tail = 0, dead = 0, block_pos = 0; @@ -67,6 +72,12 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView const SessionState& session, const ModelGeometry& g, const QsaState& draft, std::string& error, ConversationKvReuse reuse = {}, size_t* reused_bytes = nullptr); +// Disk save without capturing the K/V on the host: `meta` gets everything but the K/V (running state copied, +// checkpoints as given by the view), `sources` one streamed source per QSA layer then the draft. Caller has +// synchronized and must not run the session until the file is written. +bool conversation_snapshot_sources(SavedConversation& meta, std::vector& sources, + const ConversationView& view, const SessionState& session, + const ModelGeometry& g, const QsaState& draft, std::string& error); bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& session, const ModelGeometry& g, const QsaState& draft, std::string& error); enum class ConversationRestore { restored, invalid, transfer_failed }; diff --git a/serve/server.py b/serve/server.py index 34e85059..94bfed14 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1380,6 +1380,24 @@ class StrataEngine: pass return EngineSilent(f"{what}; the server ended the engine") + def session_file(self, action: str, path: str) -> dict: + """Disk sessions: `SAVE ` / `RESTORE ` between requests (the caller holds the service FIFO). + -> {"tokens", "bytes", "ms"}; ValueError with the engine's reason when it refuses the file.""" + try: + self.proc.stdin.write(f"{'SAVE' if action == 'save' else 'RESTORE'} {path}\n") + self.proc.stdin.flush() + except OSError: + raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") from None + while True: + line = self.lines.get() + if line is None: + raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") + if line.startswith("ERR"): + raise ValueError(line[4:].strip()) + if line.startswith(("SAVED ", "RESTORED ")): + f = line.split() + return {"tokens": int(f[1]), "bytes": int(f[2]), "ms": float(f[3])} + def close(self): """End the engine process: QUIT first (the engine frees its memory itself - unpinning tens of GB can take a while), then terminate, then kill, each given 20 s. Raises EngineStuck when it still runs after all three.""" @@ -1939,6 +1957,7 @@ class Service: self.shared = {} # the web app's Chat settings for every client (POST /settings) self.shared_path = None # where they are kept between starts (next to the config) self.fifo = threading.Lock() + self.slot_save_path = None # --slot-save-path: /slots/0?action=save|restore (off when None) self.embeddings = threading.local() # the current request's image embeddings file (GENI) self.api_key = "" # when set, /v1/* needs it (Bearer or x-api-key) # #458 (opt-in, the config's "effort_position": "end"): a non-default reasoning effort goes in a short system @@ -1994,6 +2013,37 @@ class Service: def loaded(self) -> bool: return not hasattr(self.engine, "alive") or self.engine.alive() + def slot_action(self, slot: str, action: str, filename) -> tuple[int, dict]: + """llama-server's POST /slots/{id}?action=save|restore {"filename": ...}: the conversation the engine holds, + to or from a file in slot_save_path. -> (HTTP status, body).""" + def error(code, message): + return code, {"error": {"code": code, "message": message, + "type": "invalid_request_error" if code < 500 else "server_error"}} + if not self.slot_save_path or not hasattr(self.engine, "session_file"): + return error(501, "slot save/restore is disabled (start the server with --slot-save-path DIR)") + if slot != "0": + return error(400, "this server has one slot: 0") + if action not in ("save", "restore"): + return error(400, "action must be save or restore") + if (not isinstance(filename, str) or not filename or filename in (".", "..") or "/" in filename + or "\\" in filename or any(ord(c) < 32 for c in filename)): + return error(400, "filename must be a plain file name inside the slot save path") + path = os.path.join(self.slot_save_path, filename) + if action == "restore" and not os.path.isfile(path): + return error(404, f"no saved session named {filename}") + with self.fifo: + if not self.loaded(): + return error(503, "the model is not loaded") + try: + r = self.engine.session_file(action, path) + except ValueError as e: + return error(400, str(e)) + if action == "save": + return 200, {"id_slot": 0, "filename": filename, "n_saved": r["tokens"], "n_written": r["bytes"], + "timings": {"save_ms": r["ms"]}} + return 200, {"id_slot": 0, "filename": filename, "n_restored": r["tokens"], "n_read": r["bytes"], + "timings": {"restore_ms": r["ms"]}} + def set_aliases(self, aliases) -> None: """#297: the config's `aliases` - a list of names (or one comma-separated string), like llama-server's --alias. ValueError for anything else.""" @@ -3606,6 +3656,9 @@ def make_handler(svc: Service): # JSON from Strata's own page only, as /settings: else a plain form POST from any site unloads the model if path in ("/unload", "/load") and not self._own_page("the model can be loaded or unloaded"): return + # the same for the slot files: else any site could overwrite a saved conversation or replace the live one + if path.startswith("/slots/") and not self._own_page("conversations can be saved or restored"): + return if path == "/unload": # give the GPU back now (between requests) try: r = svc.unload() @@ -3668,6 +3721,14 @@ def make_handler(svc: Service): self.record = svc.begin_request(path, req) if path == "/v1/responses": self._responses(req) + elif path.startswith("/slots/"): + query = parse_qs(self.path.partition("?")[2]) + try: + code, body = svc.slot_action(path[len("/slots/"):], (query.get("action") or [""])[0], + req.get("filename")) + except EngineDied as e: + code, body = 500, {"error": {"code": 500, "message": str(e), "type": "server_error"}} + self._json(code, body) elif path == "/v1/chat/completions": self._openai(req) elif path == "/v1/messages": @@ -4486,6 +4547,9 @@ def main() -> int: "\"min_free_vram_mib\" in the config; default: always load)") ap.add_argument("--before-load", help="a command run before the model is loaded again (e.g. to unload another " "server's model; also \"before_load\" in the config, a string or a list)") + ap.add_argument("--slot-save-path", default=None, metavar="DIR", + help="enable POST /slots/0?action=save|restore {\"filename\": NAME} (llama-server's API): the " + "conversation the engine holds, to or from DIR/NAME (also \"slot_save_path\" in the config)") a = ap.parse_args() cfg = json.loads(Path(a.config).read_text(encoding="utf-8-sig")) if a.config else {} # Notepad adds a BOM if a.gpu is not None: @@ -4603,6 +4667,10 @@ def main() -> int: svc.min_free_vram_mib = a.min_free_vram_mib if a.min_free_vram_mib is not None else \ int(cfg.get("min_free_vram_mib") or 0) svc.before_load = a.before_load or cfg.get("before_load") or None + svc.slot_save_path = a.slot_save_path or cfg.get("slot_save_path") or None + if svc.slot_save_path: + os.makedirs(svc.slot_save_path, exist_ok=True) + print(f"[strata] slot save/restore on: {svc.slot_save_path}", flush=True) mode = str(cfg.get("anthropic_thinking") or "model") # #278: "on_request" = only when the request asks if mode not in ("model", "on_request"): raise SystemExit(f"[strata] config anthropic_thinking must be \"model\" or \"on_request\", not {mode!r}") diff --git a/serve/test_security.py b/serve/test_security.py index 429c7162..0e8f260b 100644 --- a/serve/test_security.py +++ b/serve/test_security.py @@ -275,6 +275,25 @@ class OverHttp(unittest.TestCase): self.assertEqual(self.req("POST", "/load", {}, {"Content-Type": "application/json", "Origin": f"http://127.0.0.1:{self.port}"})[0], 200) + # --- /slots/0?action=save|restore (session files) + def test_slots_need_json_from_the_own_page(self): + self.start() + body = {"filename": "a.bin"} + for action in ("save", "restore"): + path = f"/slots/0?action={action}" + self.assertEqual(self.req("POST", path, b"filename=a.bin", + {"Content-Type": "application/x-www-form-urlencoded"})[0], 415, path) + self.assertEqual(self.req("POST", path, body, {"Content-Type": "text/plain"})[0], 415, path) + for origin in ("http://evil.example.com", "null"): + self.assertEqual(self.req("POST", path, body, {"Content-Type": "application/json", + "Origin": origin})[0], 403, (path, origin)) + # JSON without an Origin (curl, scripts) or from the own page reaches the slot API: off here, so 501 + self.assertEqual(self.req("POST", path, body, {"Content-Type": "application/json"})[0], 501, path) + self.assertEqual(self.req("POST", path, body, {"Content-Type": "application/json", + "Origin": f"http://127.0.0.1:{self.port}"})[0], 501, path) + self.assertEqual(self.req("POST", "/slots/0?action=save", body, {"Content-Type": "application/json"}, + host="rebind.example.com")[0], 403) + if __name__ == "__main__": unittest.main() diff --git a/serve/test_slots.py b/serve/test_slots.py new file mode 100644 index 00000000..eb239411 --- /dev/null +++ b/serve/test_slots.py @@ -0,0 +1,169 @@ +"""serve/test_slots.py - llama-server compatible /slots/0?action=save|restore over the engine's SAVE/RESTORE lines +(mock engine: no GPU, no pack). + + python -m unittest serve.test_slots -v +""" +from __future__ import annotations + +import json +import queue +import sys +import tempfile +import threading +import unittest +import urllib.error +import urllib.request +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from serve.frontend import ChatTemplate # noqa: E402 +from serve.server import ByteTokenizer, Service, StrataEngine, serve # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] + + +class FakeProc: + """Stands in for the engine process: answers SAVE / RESTORE lines like `strata --serve` does.""" + + def __init__(self, engine): + self.engine = engine + self.stdin = self + self.sent: list[str] = [] + + def write(self, s): + self.sent.append(s) + cmd, _, path = s.strip().partition(" ") + if cmd == "SAVE": + if self.engine.fail: + self.engine.lines.put("ERR no complete session to save\n") + else: + Path(path).write_bytes(b"x" * 1234) + self.engine.lines.put("SAVED 62993 1234 401.5\n") + elif cmd == "RESTORE": + if not Path(path).exists() or self.engine.fail: + self.engine.lines.put("ERR session file: saved with another model (model fingerprint differs)\n") + else: + self.engine.lines.put("RESTORED 62993 1234 560.2\n") + elif cmd == "DIE": + self.engine.lines.put(None) + + def flush(self): + pass + + def poll(self): + return None + + +class FakeEngine(StrataEngine): + def __init__(self): + super().__init__("strata", ["--max-context", "65536"], lazy=True) + self.max_context = 65536 + self.unloaded, self.ended = False, False + self.lines = queue.Queue() + self.fail = False + self.proc = FakeProc(self) + + +class Slots(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.dir = tempfile.TemporaryDirectory() + tok = ByteTokenizer() + cls.engine = FakeEngine() + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.svc.slot_save_path = cls.dir.name + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + cls.dir.cleanup() + + def setUp(self): + self.engine.fail = False + self.engine.proc.sent.clear() + + def post(self, path, body, headers=None): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), + headers=headers or {"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def test_a_foreign_page_or_a_form_never_reaches_the_engine(self): + for action in ("save", "restore"): + for headers, code in (({"Content-Type": "application/json", "Origin": "http://evil.example.com"}, 403), + ({"Content-Type": "text/plain"}, 415), + ({"Content-Type": "application/x-www-form-urlencoded"}, 415)): + s, b = self.post(f"/slots/0?action={action}", {"filename": "x.bin"}, headers) + self.assertEqual(s, code, (action, headers, b)) + self.assertEqual(self.engine.proc.sent, []) + self.assertFalse(Path(self.dir.name, "x.bin").exists()) + + def test_save_writes_into_the_slot_save_path(self): + s, b = self.post("/slots/0?action=save", {"filename": "a.bin"}) + self.assertEqual(s, 200, b) + self.assertEqual(self.engine.proc.sent, [f"SAVE {Path(self.dir.name, 'a.bin')}\n"]) + self.assertEqual((b["id_slot"], b["filename"], b["n_saved"], b["n_written"]), (0, "a.bin", 62993, 1234)) + self.assertAlmostEqual(b["timings"]["save_ms"], 401.5) + + def test_restore_answers_like_llama_server(self): + self.post("/slots/0?action=save", {"filename": "b.bin"}) + s, b = self.post("/slots/0?action=restore", {"filename": "b.bin"}) + self.assertEqual(s, 200, b) + self.assertEqual((b["id_slot"], b["filename"], b["n_restored"], b["n_read"]), (0, "b.bin", 62993, 1234)) + self.assertAlmostEqual(b["timings"]["restore_ms"], 560.2) + + def test_refused_file_is_an_error_not_a_success(self): + self.post("/slots/0?action=save", {"filename": "c.bin"}) + self.engine.fail = True + s, b = self.post("/slots/0?action=restore", {"filename": "c.bin"}) + self.assertEqual(s, 400, b) + self.assertIn("fingerprint", b["error"]["message"]) + + def test_missing_file_is_not_found(self): + s, b = self.post("/slots/0?action=restore", {"filename": "never-saved.bin"}) + self.assertEqual(s, 404, b) + self.assertEqual(self.engine.proc.sent, []) + + def test_filename_cannot_leave_the_directory(self): + for bad in ("../x.bin", "/etc/passwd", "a/b.bin", "", ".", "..", "x\ny.bin"): + s, b = self.post("/slots/0?action=save", {"filename": bad}) + self.assertEqual(s, 400, (bad, b)) + self.assertEqual(self.engine.proc.sent, []) + + def test_only_slot_zero_and_known_actions(self): + self.assertEqual(self.post("/slots/1?action=save", {"filename": "d.bin"})[0], 400) + self.assertEqual(self.post("/slots/0?action=erase_all", {"filename": "d.bin"})[0], 400) + self.assertEqual(self.engine.proc.sent, []) + + def test_disabled_without_a_slot_save_path(self): + saved = self.svc.slot_save_path + self.svc.slot_save_path = None + try: + s, b = self.post("/slots/0?action=save", {"filename": "e.bin"}) + finally: + self.svc.slot_save_path = saved + self.assertEqual(s, 501, b) + + def test_waits_for_a_running_request(self): + """A save never interleaves with a generation: it takes the same FIFO.""" + self.svc.fifo.acquire() + out = {} + t = threading.Thread(target=lambda: out.update(r=self.post("/slots/0?action=save", {"filename": "f.bin"}))) + t.start() + t.join(0.5) + self.assertTrue(t.is_alive()) + self.assertEqual(self.engine.proc.sent, []) + self.svc.fifo.release() + t.join(10) + self.assertEqual(out["r"][0], 200) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/core/conversation_file.cpp b/src/core/conversation_file.cpp new file mode 100644 index 00000000..bacdf30a --- /dev/null +++ b/src/core/conversation_file.cpp @@ -0,0 +1,631 @@ +#include "strata/core/conversation_file.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#else +#include +#include +#endif + +namespace strata::core { +namespace { +constexpr char kMagic[8] = {'S', 'T', 'R', 'S', 'E', 'S', 'S', '\x01'}; +constexpr char kEnd[8] = {'S', 'T', 'R', 'S', 'E', 'N', 'D', '\x01'}; +constexpr uint32_t kVersion = 1; +constexpr size_t kHeader = 64, kTrailer = 16; + +constexpr uint64_t P1 = 0x9E3779B185EBCA87ull, P2 = 0xC2B2AE3D27D4EB4Full, P3 = 0x165667B19E3779F9ull, + P4 = 0x85EBCA77C2B2AE63ull, P5 = 0x27D4EB2F165667C5ull; +uint64_t rotl(uint64_t x, int r) { return (x << r) | (x >> (64 - r)); } +uint64_t round1(uint64_t acc, uint64_t w) { return rotl(acc + w * P2, 31) * P1; } +uint64_t load64(const uint8_t* p) { uint64_t v; std::memcpy(&v, p, 8); return v; } + +struct FileCloser { void operator()(std::FILE* f) const { if (f) std::fclose(f); } }; +using File = std::unique_ptr; + +// ---- file I/O in aligned 16 MiB blocks. Linux: O_DIRECT when the filesystem takes it (no page cache, so a +// 1.2 GB session neither evicts other files nor is charged to the engine's memory cgroup), buffered I/O otherwise +// (tmpfs, or STRATA_SESSION_BUFFERED=1). Windows and other systems: ordinary buffered I/O, same blocks. +constexpr size_t kAlign = 4096, kBlock = 16u << 20; +#ifdef _WIN32 +struct AlignedFree { void operator()(uint8_t* p) const { _aligned_free(p); } }; +using Aligned = std::unique_ptr; +Aligned aligned_block() { return Aligned(static_cast(_aligned_malloc(kBlock, kAlign))); } +#else +struct AlignedFree { void operator()(uint8_t* p) const { std::free(p); } }; +using Aligned = std::unique_ptr; +Aligned aligned_block() { return Aligned(static_cast(std::aligned_alloc(kAlign, kBlock))); } +#endif + +#ifdef _WIN32 +// paths reach the engine as UTF-8 (the server writes its commands as UTF-8) +std::wstring wide(const std::string& s) { + const int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int) s.size(), nullptr, 0); + if (n <= 0) return {}; + std::wstring w((size_t) n, L'\0'); + MultiByteToWideChar(CP_UTF8, 0, s.data(), (int) s.size(), w.data(), n); + return w; +} + +std::string last_error() { + const DWORD code = GetLastError(); + char msg[256] = {}; + const DWORD n = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, code, 0, msg, + sizeof msg, nullptr); + std::string s(msg, n); + while (!s.empty() && (s.back() == '\n' || s.back() == '\r' || s.back() == ' ' || s.back() == '.')) s.pop_back(); + return s.empty() ? "error " + std::to_string(code) : s; +} + +class RawFile { +public: + ~RawFile() { close(); } + bool open_write(const std::string& path) { + return open(path, GENERIC_WRITE, 0, CREATE_ALWAYS); + } + bool open_read(const std::string& path) { + return open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING); + } + bool is_open() const { return h_ != INVALID_HANDLE_VALUE; } + bool direct() const { return false; } + bool write_all(const uint8_t* p, size_t n) { + while (n) { + DWORD w = 0; + const DWORD want = (DWORD) std::min(n, size_t(1) << 30); + if (!WriteFile(h_, p, want, &w, nullptr) || w == 0) { error_ = last_error(); return false; } + p += w; n -= w; + } + return true; + } + // bytes read, 0 at the end of the file, -1 on error + long long read_some(uint8_t* p, size_t n) { + DWORD r = 0; + if (!ReadFile(h_, p, (DWORD) std::min(n, size_t(1) << 30), &r, nullptr)) { + error_ = last_error(); + return -1; + } + return (long long) r; + } + bool truncate(uint64_t n) { + LARGE_INTEGER at{}; + at.QuadPart = (LONGLONG) n; + if (SetFilePointerEx(h_, at, nullptr, FILE_BEGIN) && SetEndOfFile(h_)) return true; + error_ = last_error(); + return false; + } + bool close() { + if (h_ == INVALID_HANDLE_VALUE) return true; + const bool ok = CloseHandle(h_) != 0; + if (!ok) error_ = last_error(); + h_ = INVALID_HANDLE_VALUE; + return ok; + } + const std::string& error() const { return error_; } +private: + bool open(const std::string& path, DWORD access, DWORD share, DWORD disposition) { + h_ = CreateFileW(wide(path).c_str(), access, share, nullptr, disposition, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, nullptr); + if (h_ == INVALID_HANDLE_VALUE) error_ = last_error(); + return h_ != INVALID_HANDLE_VALUE; + } + HANDLE h_ = INVALID_HANDLE_VALUE; + std::string error_; +}; + +// std::rename does not replace an existing file on Windows: MoveFileExW does, atomically on one volume +bool replace_file(const std::string& from, const std::string& to, std::string& error) { + if (MoveFileExW(wide(from).c_str(), wide(to).c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) + return true; + error = last_error(); + return false; +} +void remove_file(const std::string& path) { DeleteFileW(wide(path).c_str()); } +std::filesystem::path fs_path(const std::string& path) { return std::filesystem::path(wide(path)); } +#else +#ifndef O_DIRECT +#define O_DIRECT 0 // not offered by this system: buffered I/O +#endif + +bool buffered_forced() { + const char* e = std::getenv("STRATA_SESSION_BUFFERED"); + return e != nullptr && e[0] == '1'; +} + +class RawFile { +public: + ~RawFile() { close(); } + bool open_write(const std::string& path) { return open(path, O_WRONLY | O_CREAT | O_TRUNC); } + bool open_read(const std::string& path) { return open(path, O_RDONLY); } + bool is_open() const { return fd_ >= 0; } + bool direct() const { return direct_; } + bool write_all(const uint8_t* p, size_t n) { + while (n) { + const ssize_t w = ::write(fd_, p, n); + if (w < 0 && errno == EINTR) continue; + if (w <= 0) { error_ = w < 0 ? std::strerror(errno) : "short write"; return false; } + p += w; n -= (size_t) w; + } + return true; + } + // bytes read, 0 at the end of the file, -1 on error + long long read_some(uint8_t* p, size_t n) { + for (;;) { + const ssize_t r = ::read(fd_, p, n); + if (r < 0 && errno == EINTR) continue; + if (r < 0) error_ = std::strerror(errno); + return (long long) r; + } + } + bool truncate(uint64_t n) { + if (::ftruncate(fd_, (off_t) n) == 0) return true; + error_ = std::strerror(errno); + return false; + } + bool close() { + if (fd_ < 0) return true; + const bool ok = ::close(fd_) == 0; + if (!ok) error_ = std::strerror(errno); + fd_ = -1; + return ok; + } + const std::string& error() const { return error_; } +private: + bool open(const std::string& path, int flags) { + const bool buffered = O_DIRECT == 0 || buffered_forced(); + fd_ = buffered ? -1 : ::open(path.c_str(), flags | O_DIRECT | O_CLOEXEC, 0644); + direct_ = fd_ >= 0; + // EINVAL: this filesystem refuses O_DIRECT (tmpfs): buffered I/O instead + if (fd_ < 0 && (buffered || errno == EINVAL)) fd_ = ::open(path.c_str(), flags | O_CLOEXEC, 0644); + if (fd_ < 0) error_ = std::strerror(errno); + return fd_ >= 0; + } + int fd_ = -1; + bool direct_ = false; + std::string error_; +}; + +bool replace_file(const std::string& from, const std::string& to, std::string& error) { + if (std::rename(from.c_str(), to.c_str()) == 0) return true; + error = std::strerror(errno); + return false; +} +void remove_file(const std::string& path) { std::remove(path.c_str()); } +std::filesystem::path fs_path(const std::string& path) { return std::filesystem::path(path); } +#endif + +class FileSink { +public: + explicit FileSink(const std::string& path) : buf_(aligned_block()) { + if (buf_) f_.open_write(path); + } + bool is_open() const { return f_.is_open(); } + std::string error() const { return buf_ ? f_.error() : std::string("out of memory for the write buffer"); } + // room in the block for in-place production (avoids a staging copy) + uint8_t* span(size_t& room) { room = kBlock - used_; return buf_.get() + used_; } + bool commit(size_t n) { used_ += n; total_ += n; return used_ < kBlock || drain(); } + bool write(const void* p, size_t n) { + const uint8_t* s = static_cast(p); + while (n) { + size_t room = 0; + uint8_t* d = span(room); + const size_t c = std::min(room, n); + std::memcpy(d, s, c); + if (!commit(c)) return false; + s += c; n -= c; + } + return true; + } + // last block padded to the alignment for direct I/O, then the file cut back to its exact size + bool finish() { + if (!f_.is_open()) return false; + const size_t padded = f_.direct() ? (used_ + kAlign - 1) / kAlign * kAlign : used_; + std::memset(buf_.get() + used_, 0, padded - used_); + bool ok = f_.write_all(buf_.get(), padded); + ok = ok && (padded == used_ || f_.truncate(total_)); + ok = f_.close() && ok; + return ok; + } +private: + bool drain() { + if (!f_.write_all(buf_.get(), used_)) return false; + used_ = 0; + return true; + } + Aligned buf_; + RawFile f_; + size_t used_ = 0; + uint64_t total_ = 0; +}; + +class FileSource { +public: + explicit FileSource(const std::string& path) : buf_(aligned_block()) { + if (buf_) f_.open_read(path); + } + bool is_open() const { return f_.is_open(); } + std::string error() const { return buf_ ? f_.error() : std::string("out of memory for the read buffer"); } + bool read(void* p, size_t n) { + uint8_t* d = static_cast(p); + while (n) { + if (at_ == have_ && !fill()) return false; + const size_t c = std::min(n, have_ - at_); + std::memcpy(d, buf_.get() + at_, c); + at_ += c; d += c; n -= c; + } + return true; + } +private: + bool fill() { + at_ = have_ = 0; + while (have_ < kBlock) { + const long long r = f_.read_some(buf_.get() + have_, kBlock - have_); + if (r < 0) return false; + if (r == 0) break; + have_ += (size_t) r; + if (f_.direct() && have_ % kAlign) break; // short aligned read: end of file + } + return have_ > 0; + } + Aligned buf_; + RawFile f_; + size_t at_ = 0, have_ = 0; +}; + +// ---- serialization: the same walk counts (f == nullptr) and writes +struct Out { + FileSink* f = nullptr; + SessionHasher* hash = nullptr; + uint64_t n = 0; + bool ok = true; + void raw(const void* p, size_t c) { + n += c; + if (!f || !ok || !c) return; + if (hash) hash->update(p, c); + ok = f->write(p, c); + } + void u64(uint64_t v) { raw(&v, 8); } + void i64(int64_t v) { raw(&v, 8); } + template void vec(const std::vector& v) { u64(v.size()); raw(v.data(), v.size() * sizeof(T)); } + void buffer(const ConversationBuffer& b) { + u64(b.size()); + b.visit(0, b.size(), [&](const uint8_t* p, size_t c, size_t) { raw(p, c); return ok; }); + } + // a K/V part pulled from its owner straight into the file block (sizing pass: counted, never read) + void source(const SessionKvSource& s, size_t part) { + const size_t size = s.sizes[part]; + u64(size); + if (!f) { n += size; return; } + for (size_t at = 0; at < size && ok;) { + size_t room = 0; + uint8_t* d = f->span(room); + const size_t c = std::min(room, size - at); + if (!s.read || !s.read(part, at, d, c)) { ok = false; read_failed = true; return; } + if (hash) hash->update(d, c); + n += c; + ok = f->commit(c); + at += c; + } + } + bool read_failed = false; +}; + +void put_kv_header(Out& o, int format, int64_t cells, int64_t heads, int64_t head_dim, int64_t page_size, + int64_t pooled_rows, int64_t idx_dim) { + for (int64_t v : {int64_t(format), cells, heads, head_dim, page_size, pooled_rows, idx_dim}) o.i64(v); +} + +void put_checkpoint(Out& o, const ConversationCheckpoint& c) { + o.vec(c.ids); + o.u64(c.imgs.size()); + for (const auto& k : c.imgs) { o.i64(k.start); o.u64(k.hash); } + o.vec(c.gdn); o.vec(c.ple); o.vec(c.tails); o.vec(c.dead); o.vec(c.block_pos); + o.u64(c.used); +} + +void put_payload(Out& o, const SavedConversation& s, const std::vector* sources = nullptr) { + for (int64_t g : s.geometry) o.i64(g); + o.i64(s.layer_lo); o.i64(s.layer_hi); o.u64(s.cvec ? 1 : 0); + put_checkpoint(o, s.live); + o.u64(s.checkpoints.size()); + for (const auto& c : s.checkpoints) put_checkpoint(o, c); + if (sources) { + o.u64(sources->size()); + for (const auto& k : *sources) { + put_kv_header(o, k.format, k.cells, k.heads, k.head_dim, k.page_size, k.pooled_rows, k.idx_dim); + for (size_t part = 0; part < 5; ++part) o.source(k, part); + } + return; + } + o.u64(s.kv.size()); + for (const auto& k : s.kv) { + put_kv_header(o, k.format, k.cells, k.heads, k.head_dim, k.page_size, k.pooled_rows, k.idx_dim); + o.buffer(k.k); o.buffer(k.v); o.buffer(k.k_scale); o.buffer(k.v_scale); o.buffer(k.pooled); + } +} + +// ---- parsing: every count is checked against the bytes left before anything is allocated +struct In { + FileSource* f; + SessionHasher hash; + uint64_t left; + std::string& error; + bool fail(const std::string& m) { if (error.empty()) error = "session file: " + m; return false; } + bool raw(void* p, size_t c) { + if (c > left) return fail("payload ends early"); + if (c && !f->read(p, c)) return fail("read error"); + hash.update(p, c); + left -= c; + return true; + } + bool u64(uint64_t& v) { return raw(&v, 8); } + bool i64(int64_t& v) { return raw(&v, 8); } + bool count(uint64_t& n, size_t elem) { + if (!u64(n)) return false; + if (elem && n > left / elem) return fail("element count exceeds the payload"); + return true; + } + template bool vec(std::vector& v) { + uint64_t n = 0; + if (!count(n, sizeof(T))) return false; + v.resize((size_t) n); + return raw(v.data(), (size_t) n * sizeof(T)); + } + bool buffer(ConversationBuffer& b) { + uint64_t n = 0; + if (!count(n, 1)) return false; + b = {}; + b.resize((size_t) n); + return b.visit(0, b.size(), [&](uint8_t* p, size_t c, size_t) { return raw(p, c); }); + } +}; + +bool get_checkpoint(In& in, ConversationCheckpoint& c) { + if (!in.vec(c.ids)) return false; + uint64_t n = 0; + if (!in.count(n, 16)) return false; + c.imgs.resize((size_t) n); + for (auto& k : c.imgs) if (!in.i64(k.start) || !in.u64(k.hash)) return false; + return in.vec(c.gdn) && in.vec(c.ple) && in.vec(c.tails) && in.vec(c.dead) && in.vec(c.block_pos) && + in.u64(c.used); +} + +bool get_payload(In& in, SavedConversation& s) { + for (auto& g : s.geometry) if (!in.i64(g)) return false; + uint64_t cvec = 0; + if (!in.i64(s.layer_lo) || !in.i64(s.layer_hi) || !in.u64(cvec)) return false; + if (cvec > 1) return in.fail("invalid cvec flag"); + s.cvec = cvec == 1; + if (!get_checkpoint(in, s.live)) return false; + uint64_t n = 0; + // a checkpoint is at least 8 counts + used = 72 bytes; a K/V layer at least 7 + 5 = 96 + if (!in.count(n, 72)) return false; + s.checkpoints.resize((size_t) n); + for (auto& c : s.checkpoints) if (!get_checkpoint(in, c)) return false; + if (!in.count(n, 96)) return false; + s.kv.resize((size_t) n); + for (auto& k : s.kv) { + int64_t format = 0; + if (!in.i64(format) || !in.i64(k.cells) || !in.i64(k.heads) || !in.i64(k.head_dim) || + !in.i64(k.page_size) || !in.i64(k.pooled_rows) || !in.i64(k.idx_dim)) return false; + if (format < INT32_MIN || format > INT32_MAX) return in.fail("invalid K/V format"); + k.format = (int) format; + if (!in.buffer(k.k) || !in.buffer(k.v) || !in.buffer(k.k_scale) || !in.buffer(k.v_scale) || + !in.buffer(k.pooled)) return false; + } + return true; +} + +bool has_stage_parts(const SavedConversation& s) { + if (!s.live.stage_parts.empty()) return true; + for (const auto& c : s.checkpoints) if (!c.stage_parts.empty()) return true; + return false; +} + +void header_bytes(uint8_t* h, const SessionFileIdentity& id, uint64_t payload) { + std::memset(h, 0, kHeader); + std::memcpy(h, kMagic, 8); + const uint32_t version = kVersion, size = kHeader; + std::memcpy(h + 8, &version, 4); + std::memcpy(h + 12, &size, 4); + std::memcpy(h + 16, &id.model, 8); + std::memcpy(h + 24, &id.config, 8); + std::memcpy(h + 32, &payload, 8); + const uint64_t hh = session_hash64(h, 56, 0); + std::memcpy(h + 56, &hh, 8); +} +} // namespace + +SessionHasher::SessionHasher(uint64_t seed) + : lane_{seed + P1 + P2, seed + P2, seed, seed - P1}, pending_{} {} + +void SessionHasher::block(const uint8_t* p) { + for (int i = 0; i < 4; ++i) lane_[i] = round1(lane_[i], load64(p + 8 * i)); +} + +void SessionHasher::update(const void* data, size_t n) { + const uint8_t* p = static_cast(data); + total_ += n; + if (npending_) { + const size_t take = std::min(n, sizeof pending_ - npending_); + std::memcpy(pending_ + npending_, p, take); + npending_ += take; p += take; n -= take; + if (npending_ < sizeof pending_) return; + block(pending_); + npending_ = 0; + } + for (; n >= 32; p += 32, n -= 32) block(p); + std::memcpy(pending_, p, n); + npending_ = n; +} + +uint64_t SessionHasher::digest() const { + uint64_t h = rotl(lane_[0], 1) + rotl(lane_[1], 7) + rotl(lane_[2], 12) + rotl(lane_[3], 18); + for (uint64_t l : lane_) { h ^= round1(0, l); h = h * P1 + P4; } + h += total_; + size_t i = 0; + for (; i + 8 <= npending_; i += 8) { h ^= round1(0, load64(pending_ + i)); h = rotl(h, 27) * P1 + P4; } + for (; i < npending_; ++i) { h ^= pending_[i] * P5; h = rotl(h, 11) * P1; } + h ^= h >> 33; h *= P2; h ^= h >> 29; h *= P3; h ^= h >> 32; + return h; +} + +uint64_t session_hash64(const void* data, size_t n, uint64_t seed) { + SessionHasher h(seed); + h.update(data, n); + return h.digest(); +} + +bool session_model_fingerprint(const std::vector& paths, uint64_t& fingerprint, std::string& error) { + namespace fs = std::filesystem; + SessionHasher h(0x5354524154414d44ull); + std::vector buf(1u << 20); + auto add_file = [&](const fs::path& p, const std::string& name) -> bool { + std::error_code ec; + const uint64_t size = fs::file_size(p, ec); + if (ec) { error = "session fingerprint: " + p.string() + ": " + ec.message(); return false; } + h.update(name.data(), name.size()); + h.update(&size, 8); + File f(std::fopen(p.string().c_str(), "rb")); + if (!f) { error = "session fingerprint: cannot open " + p.string(); return false; } + const uint64_t head = std::min(size, buf.size()); + if (std::fread(buf.data(), 1, head, f.get()) != head) { error = "session fingerprint: read " + p.string(); return false; } + h.update(buf.data(), head); + if (size > buf.size()) { + const uint64_t tail = std::min(size - head, buf.size()); + if (std::fseek(f.get(), -(long) tail, SEEK_END) != 0 || + std::fread(buf.data(), 1, tail, f.get()) != tail) { error = "session fingerprint: read " + p.string(); return false; } + h.update(buf.data(), tail); + } + return true; + }; + for (const auto& s : paths) { + const fs::path p(s); + std::error_code ec; + if (fs::is_directory(p, ec)) { + std::vector files; + for (auto it = fs::recursive_directory_iterator(p, ec); !ec && it != fs::recursive_directory_iterator(); + it.increment(ec)) + if (it->is_regular_file()) files.push_back(it->path()); + if (ec) { error = "session fingerprint: " + s + ": " + ec.message(); return false; } + std::sort(files.begin(), files.end()); + for (const auto& f : files) + if (!add_file(f, fs::relative(f, p).generic_string())) return false; + } else if (!add_file(p, p.filename().string())) { + return false; + } + } + fingerprint = h.digest(); + return true; +} + +namespace { +bool write_impl(const std::string& path, const SavedConversation& image, const std::vector* sources, + const SessionFileIdentity& id, size_t& bytes, std::string& error) { + if (has_stage_parts(image)) { error = "session file: layer-split state cannot be saved"; return false; } + if (sources && !image.kv.empty()) { error = "session file: K/V given both in the image and as sources"; return false; } + Out sizing; + put_payload(sizing, image, sources); + const uint64_t payload = sizing.n; + const std::string tmp = path + ".tmp"; + FileSink f(tmp); + if (!f.is_open()) { error = "session file: cannot create " + tmp + ": " + f.error(); return false; } + uint8_t h[kHeader]; + header_bytes(h, id, payload); + bool ok = f.write(h, kHeader); + SessionHasher hash(0); + Out out{&f, &hash}; + if (ok) put_payload(out, image, sources); + ok = ok && out.ok && out.n == payload; + if (ok) { + const uint64_t ph = hash.digest(); + ok = f.write(&ph, 8) && f.write(kEnd, 8); + } + ok = f.finish() && ok; + std::string why = out.read_failed ? std::string("K/V source read") : f.error(); + if (ok && replace_file(tmp, path, why)) { + bytes = kHeader + payload + kTrailer; + return true; + } + error = "session file: writing " + path + " failed" + (why.empty() ? std::string() : ": " + why); + remove_file(tmp); + return false; +} +} // namespace + +std::vector session_checkpoints_to_save(const std::vector& chain) { + const ConversationCheckpoint* deepest = nullptr; + for (const auto& c : chain) + if (!deepest || c.ids.size() > deepest->ids.size()) deepest = &c; + if (!deepest) return {}; + return {*deepest}; +} + +bool session_file_write(const std::string& path, const SavedConversation& meta, const std::vector& kv, + const SessionFileIdentity& id, size_t& bytes, std::string& error) { + return write_impl(path, meta, &kv, id, bytes, error); +} + +bool session_file_write(const std::string& path, const SavedConversation& image, const SessionFileIdentity& id, + size_t& bytes, std::string& error) { + return write_impl(path, image, nullptr, id, bytes, error); +} + +bool session_file_read(const std::string& path, const SessionFileIdentity& id, SavedConversation& image, + size_t& bytes, std::string& error) { + error.clear(); + std::error_code ec; + const uint64_t size = std::filesystem::file_size(fs_path(path), ec); + if (ec) { error = "session file: " + path + ": " + ec.message(); return false; } + if (size < kHeader + kTrailer) { error = "session file: size " + std::to_string(size) + " is below the minimum"; return false; } + FileSource f(path); + if (!f.is_open()) { error = "session file: cannot open " + path + ": " + f.error(); return false; } + uint8_t h[kHeader]; + if (!f.read(h, kHeader)) { error = "session file: header read error"; return false; } + uint32_t version = 0, hsize = 0; + uint64_t model = 0, config = 0, payload = 0, r0 = 0, r1 = 0, hh = 0; + std::memcpy(&version, h + 8, 4); std::memcpy(&hsize, h + 12, 4); + std::memcpy(&model, h + 16, 8); std::memcpy(&config, h + 24, 8); std::memcpy(&payload, h + 32, 8); + std::memcpy(&r0, h + 40, 8); std::memcpy(&r1, h + 48, 8); std::memcpy(&hh, h + 56, 8); + if (std::memcmp(h, kMagic, 8) != 0) { error = "session file: not a Strata session file (magic)"; return false; } + if (hh != session_hash64(h, 56, 0)) { error = "session file: header checksum mismatch"; return false; } + if (version != kVersion) { error = "session file: unsupported version " + std::to_string(version); return false; } + if (hsize != kHeader || r0 || r1) { error = "session file: invalid header fields"; return false; } + if (model != id.model) { error = "session file: saved with another model (model fingerprint differs)"; return false; } + if (config != id.config) { error = "session file: saved with another engine configuration (config fingerprint differs)"; return false; } + if (payload > size || size - kHeader - kTrailer != payload) { + error = "session file: size " + std::to_string(size) + " does not match the header (" + + std::to_string(kHeader + payload + kTrailer) + ")"; + return false; + } + SavedConversation parsed; + In in{&f, SessionHasher(0), payload, error}; + if (!get_payload(in, parsed)) return false; + if (in.left) { error = "session file: payload has " + std::to_string(in.left) + " unparsed bytes"; return false; } + uint8_t t[kTrailer]; + if (!f.read(t, kTrailer)) { error = "session file: trailer read error"; return false; } + uint64_t ph = 0; + std::memcpy(&ph, t, 8); + if (ph != in.hash.digest()) { error = "session file: payload checksum mismatch"; return false; } + if (std::memcmp(t + 8, kEnd, 8) != 0) { error = "session file: bad end marker"; return false; } + image = std::move(parsed); + bytes = (size_t) size; + return true; +} + +} // namespace strata::core diff --git a/src/core/conversation_file_test.cpp b/src/core/conversation_file_test.cpp new file mode 100644 index 00000000..b819546f --- /dev/null +++ b/src/core/conversation_file_test.cpp @@ -0,0 +1,303 @@ +// 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 +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace strata::core; +namespace fs = std::filesystem; + +namespace { +void set_env(const char* name, const char* value) { +#ifdef _WIN32 + _putenv_s(name, value ? value : ""); +#else + if (value) setenv(name, value, 1); else unsetenv(name); +#endif +} +int checks = 0; +void check(bool ok, const char* label) { + ++checks; + if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); } +} + +ConversationBuffer pattern(size_t n, uint8_t seed) { + ConversationBuffer b; + b.resize(n); + b.visit(0, n, [&](uint8_t* p, size_t c, size_t at) { + for (size_t i = 0; i < c; ++i) p[i] = uint8_t((at + i) * 131u + seed); + return true; + }); + return b; +} + +std::vector bytes_of(size_t n, uint8_t seed) { + std::vector v(n); + for (size_t i = 0; i < n; ++i) v[i] = uint8_t(i * 7u + seed); + return v; +} + +ConversationCheckpoint checkpoint(size_t tokens, uint8_t seed) { + ConversationCheckpoint c; + for (size_t i = 0; i < tokens; ++i) c.ids.push_back(int32_t(1000 + i)); + c.imgs = {{3, 0x1234567890abcdefull ^ seed}}; + c.gdn = bytes_of(4099, seed); + c.ple = bytes_of(77, seed + 1); + c.tails = bytes_of(301, seed + 2); + c.dead = bytes_of(64, seed + 3); + c.block_pos = bytes_of(8, seed + 4); + c.used = 42 + seed; + return c; +} + +SavedConversation sample() { + SavedConversation s; + for (size_t i = 0; i < s.geometry.size(); ++i) s.geometry[i] = int64_t(100 + i); + s.layer_lo = 0; s.layer_hi = 48; + s.cvec = false; + s.live = checkpoint(1000, 1); + s.checkpoints.push_back(checkpoint(10, 2)); + s.checkpoints.push_back(checkpoint(500, 3)); + for (int layer = 0; layer < 3; ++layer) { + ConversationKv kv; + kv.format = 2 + layer; kv.cells = 1024; kv.heads = 2; kv.head_dim = 256; + kv.page_size = 64; kv.pooled_rows = layer == 2 ? 0 : 9; kv.idx_dim = 128; + // > 16 MiB so the buffer spans several segments + kv.k = pattern(layer == 0 ? (17u << 20) + 5 : 4096, uint8_t(layer)); + kv.v = pattern(4096 + layer, uint8_t(layer + 10)); + kv.k_scale = pattern(layer == 1 ? 0 : 512, uint8_t(layer + 20)); + kv.v_scale = pattern(512, uint8_t(layer + 30)); + kv.pooled = pattern(layer == 2 ? 0 : 9 * 128 * 4, uint8_t(layer + 40)); + s.kv.push_back(std::move(kv)); + } + return s; +} + +bool same_checkpoint(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 && b.stage_parts.empty(); +} + +bool same(const SavedConversation& a, const SavedConversation& b) { + if (a.geometry != b.geometry || a.layer_lo != b.layer_lo || a.layer_hi != b.layer_hi || a.cvec != b.cvec || + !same_checkpoint(a.live, b.live) || a.checkpoints.size() != b.checkpoints.size() || a.kv.size() != b.kv.size()) + return false; + for (size_t i = 0; i < a.checkpoints.size(); ++i) + if (!same_checkpoint(a.checkpoints[i], b.checkpoints[i])) return false; + for (size_t i = 0; i < a.kv.size(); ++i) { + const auto& x = a.kv[i]; const auto& y = b.kv[i]; + if (x.format != y.format || x.cells != y.cells || x.heads != y.heads || x.head_dim != y.head_dim || + x.page_size != y.page_size || x.pooled_rows != y.pooled_rows || x.idx_dim != y.idx_dim || + !(x.k == y.k) || !(x.v == y.v) || !(x.k_scale == y.k_scale) || !(x.v_scale == y.v_scale) || + !(x.pooled == y.pooled)) return false; + } + return true; +} + +std::vector slurp(const fs::path& p) { + std::ifstream f(p, std::ios::binary); + return std::vector((std::istreambuf_iterator(f)), std::istreambuf_iterator()); +} +void spit(const fs::path& p, const std::vector& d) { + std::ofstream f(p, std::ios::binary | std::ios::trunc); + f.write(d.data(), (std::streamsize) d.size()); +} + +bool rejects(const fs::path& p, const SessionFileIdentity& id, const char* expect = nullptr) { + SavedConversation out; + size_t bytes = 0; + std::string error; + const bool ok = session_file_read(p.string(), id, out, bytes, error); + if (!ok && expect && error.find(expect) == std::string::npos) { + std::fprintf(stderr, " unexpected error text: %s (wanted %s)\n", error.c_str(), expect); + return false; + } + return !ok && !error.empty(); +} +} // namespace + +int main() { + const fs::path dir = fs::temp_directory_path() / ("strata-session-test-" + std::to_string( + std::chrono::steady_clock::now().time_since_epoch().count())); + fs::create_directories(dir); + const SessionFileIdentity id{0x1111222233334444ull, 0x5555666677778888ull}; + const SavedConversation original = sample(); + const fs::path good = dir / "good.bin"; + + // round trip + size_t written = 0; + std::string error; + check(session_file_write(good.string(), original, id, written, error), "write succeeds"); + check(error.empty(), "write leaves no error"); + check(written == fs::file_size(good), "write reports the file size"); + check(!fs::exists(dir / "good.bin.tmp"), "no temporary left behind"); + { + SavedConversation back; + size_t read = 0; + check(session_file_read(good.string(), id, back, read, error), "read succeeds"); + check(read == written, "read reports the file size"); + check(same(original, back), "round trip is identical"); + } + // writing twice produces the same bytes (deterministic format) + { + const fs::path again = dir / "again.bin"; + check(session_file_write(again.string(), original, id, written, error), "second write"); + check(slurp(again) == slurp(good), "format is deterministic"); + } + // saving over an existing file replaces it (MoveFileExW on Windows, rename elsewhere) + { + const fs::path over = dir / "over.bin"; + spit(over, std::vector(100, 'o')); + check(session_file_write(over.string(), original, id, written, error), "write over an existing file"); + check(slurp(over) == slurp(good), "existing file replaced by the session"); + check(!fs::exists(dir / "over.bin.tmp"), "no temporary left behind after replace"); + } + // buffered I/O (the path taken where direct I/O is refused or unavailable) writes and reads the same bytes + { + set_env("STRATA_SESSION_BUFFERED", "1"); + const fs::path p = dir / "buffered.bin"; + check(session_file_write(p.string(), original, id, written, error), "buffered write"); + check(slurp(p) == slurp(good), "buffered write equals the default write"); + SavedConversation back; + size_t read = 0; + check(session_file_read(good.string(), id, back, read, error) && same(original, back), "buffered read"); + set_env("STRATA_SESSION_BUFFERED", nullptr); + } + + const std::vector image = slurp(good); + // truncation at every structural boundary and in the middle + for (size_t cut : {size_t(0), size_t(7), size_t(63), size_t(64), size_t(65), size_t(200), image.size() / 2, + image.size() - 17, image.size() - 16, image.size() - 8, image.size() - 1}) { + const fs::path p = dir / "cut.bin"; + spit(p, std::vector(image.begin(), image.begin() + (std::ptrdiff_t) cut)); + check(rejects(p, id), "truncated file rejected"); + } + // trailing garbage + { + auto d = image; d.push_back('x'); + const fs::path p = dir / "tail.bin"; spit(p, d); + check(rejects(p, id, "size"), "file with trailing bytes rejected"); + } + // flipped payload byte (inside the big K buffer), flipped header byte, flipped trailer + for (size_t at : {size_t(64 + 300), image.size() / 2, size_t(20), image.size() - 12, image.size() - 3}) { + auto d = image; d[at] ^= 0x40; + const fs::path p = dir / "flip.bin"; spit(p, d); + check(rejects(p, id), "corrupted byte rejected"); + } + // other model or other configuration + check(rejects(good, {id.model ^ 1, id.config}, "model"), "different model fingerprint rejected"); + check(rejects(good, {id.model, id.config ^ 1}, "config"), "different configuration rejected"); + // wrong version: header field patched and header hash recomputed so only the version differs + { + auto d = image; + uint32_t v = 2; std::memcpy(d.data() + 8, &v, 4); + const uint64_t h = session_hash64(d.data(), 56, 0); std::memcpy(d.data() + 56, &h, 8); + const fs::path p = dir / "ver.bin"; spit(p, d); + check(rejects(p, id, "version"), "unknown version rejected"); + } + // a corrupted element count with a recomputed payload hash must fail on bounds, not allocate + { + auto d = image; + // payload starts at 64: geometry 18*8, layer_lo, layer_hi, cvec = 21*8 bytes, then live.ids count + const size_t at = 64 + 21 * 8; + uint64_t huge = 0x0fffffffffffffffull; std::memcpy(d.data() + at, &huge, 8); + uint64_t payload = 0; std::memcpy(&payload, d.data() + 32, 8); + const uint64_t h = session_hash64(d.data() + 64, payload, 0); + std::memcpy(d.data() + 64 + payload, &h, 8); + const fs::path p = dir / "count.bin"; spit(p, d); + check(rejects(p, id, "count"), "oversized count rejected before allocation"); + } + // missing file + check(rejects(dir / "absent.bin", id), "missing file rejected"); + // a failed read leaves the destination untouched + { + SavedConversation keep = sample(); + size_t b = 0; + check(!session_file_read((dir / "absent.bin").string(), id, keep, b, error), "missing read fails"); + check(same(keep, original), "failed read does not modify the destination"); + } + // layer-split images are not written; no file appears + { + SavedConversation split = sample(); + split.live.stage_parts.push_back(checkpoint(1, 9)); + const fs::path p = dir / "split.bin"; + check(!session_file_write(p.string(), split, id, written, error), "layer-split image refused"); + check(!fs::exists(p) && !fs::exists(dir / "split.bin.tmp"), "refused write leaves no file"); + } + // a write into a missing directory fails cleanly + check(!session_file_write((dir / "nope" / "x.bin").string(), original, id, written, error), + "write into a missing directory fails"); + // the hash is position-sensitive and seed-sensitive + { + const char a[] = "abcdefghijklmnopqrstuvwxyz0123456789", b[] = "bacdefghijklmnopqrstuvwxyz0123456789"; + check(session_hash64(a, sizeof a, 0) != session_hash64(b, sizeof b, 0), "hash sees swapped bytes"); + check(session_hash64(a, sizeof a, 0) != session_hash64(a, sizeof a, 1), "hash sees the seed"); + SessionHasher h; h.update(a, 5); h.update(a + 5, sizeof a - 5); + check(h.digest() == session_hash64(a, sizeof a, 0), "streaming hash equals one-shot hash"); + } + // model fingerprint: changes with content at the head of a file and with the file list + { + const fs::path m1 = dir / "m1.bin", m2 = dir / "m2.bin"; + spit(m1, std::vector(3u << 20, 'a')); + spit(m2, std::vector(100, 'b')); + uint64_t f1 = 0, f2 = 0, f3 = 0, f4 = 0; + check(session_model_fingerprint({m1.string(), m2.string()}, f1, error), "fingerprint ok"); + check(session_model_fingerprint({m1.string()}, f2, error), "fingerprint subset ok"); + auto d = slurp(m1); d[10] = 'z'; spit(m1, d); + check(session_model_fingerprint({m1.string(), m2.string()}, f3, error), "fingerprint after edit ok"); + check(f1 != f2 && f1 != f3, "fingerprint follows files and content"); + check(!session_model_fingerprint({(dir / "absent").string()}, f4, error), "fingerprint of a missing file fails"); + } + + // only the deepest checkpoint is worth a disk write: the next turn resumes from it + { + std::vector chain; + check(session_checkpoints_to_save(chain).empty(), "no checkpoints, none saved"); + chain.push_back(checkpoint(10, 2)); + chain.push_back(checkpoint(700, 3)); + chain.push_back(checkpoint(500, 4)); + const auto kept = session_checkpoints_to_save(chain); + check(kept.size() == 1 && same_checkpoint(kept[0], chain[1]), "deepest checkpoint kept, alone"); + } + // K/V streamed from its owner (no host copy): the same bytes as writing the captured image + { + SavedConversation meta = original; + meta.kv.clear(); + std::vector sources; + for (const auto& k : original.kv) { + SessionKvSource s; + s.format = k.format; s.cells = k.cells; s.heads = k.heads; s.head_dim = k.head_dim; + s.page_size = k.page_size; s.pooled_rows = k.pooled_rows; s.idx_dim = k.idx_dim; + const std::array parts = {&k.k, &k.v, &k.k_scale, &k.v_scale, &k.pooled}; + for (size_t i = 0; i < 5; ++i) s.sizes[i] = parts[i]->size(); + s.read = [parts](size_t part, size_t offset, void* dst, size_t n) { + return parts[part]->read(dst, offset, n); + }; + sources.push_back(std::move(s)); + } + const fs::path p = dir / "streamed.bin"; + check(session_file_write(p.string(), meta, sources, id, written, error), "streamed write succeeds"); + check(slurp(p) == image, "streamed write equals the captured-image write"); + // a failing source leaves no file + auto broken = sources; + broken[1].read = [](size_t, size_t, void*, size_t) { return false; }; + const fs::path q = dir / "broken.bin"; + check(!session_file_write(q.string(), meta, broken, id, written, error), "failing source fails the write"); + check(!fs::exists(q) && !fs::exists(dir / "broken.bin.tmp"), "failed streamed write leaves no file"); + // K/V in the image and as sources at once is ambiguous: refused + check(!session_file_write((dir / "both.bin").string(), original, sources, id, written, error), + "image K/V plus sources refused"); + } + + fs::remove_all(dir); + std::printf("conversation_file_test: %d checks passed\n", checks); + return 0; +} diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp index 8b74fc6c..c1d2e2ff 100644 --- a/src/core/conversation_snapshot.cpp +++ b/src/core/conversation_snapshot.cpp @@ -224,6 +224,25 @@ bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, co return false; } +bool conversation_kv_source(SessionKvSource& out, const QsaState& st, const ModelGeometry& g, + int64_t upto, bool index, std::string& error) { + Layout l{}; + if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return false; + SessionKvSource s; + s.format = l.format; s.cells = l.cells; s.heads = g.n_head_kv; s.head_dim = g.head_dim; + s.page_size = l.page_size; s.pooled_rows = l.pooled_rows; s.idx_dim = g.idx_key_dim; + s.sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; + const auto src = pools(st); + const auto sizes = s.sizes; + s.read = [src, sizes](size_t part, size_t offset, void* dst, size_t n) { + if (part >= 5 || offset > sizes[part] || n > sizes[part] - offset) return false; + std::string ignored; + return transfer(dst, src[part] ? static_cast(src[part]) + offset : nullptr, n, ignored); + }; + out = std::move(s); + return true; +} + bool conversation_kv_verify(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, uint64_t& fingerprint, std::string& error) { if (!conversation_kv_validate(image, st, g, upto, index, error)) return false; diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp index 1f1de53c..e0dcc29e 100644 --- a/src/core/conversation_snapshot_test.cpp +++ b/src/core/conversation_snapshot_test.cpp @@ -1,4 +1,5 @@ #include "strata/core/conversation_snapshot.hpp" +#include "strata/core/conversation_file.hpp" #include "strata/kernels/kv_q4.hpp" #include @@ -145,6 +146,27 @@ void full_session(int fmt, int mode, int experts) { check(a.checkpoints[0].used == 17,"upstream checkpoint LRU stamp survives capture"); fill(177); check(conversation_snapshot_save(b,view,ss,g,draft.state,err),"capture complete B"); + { + // disk save path: metadata + streamed K/V give the same file as the captured image + SavedConversation meta; + std::vector sources; + check(conversation_snapshot_sources(meta,sources,view,ss,g,draft.state,err),"disk-save sources"); + check(meta.kv.empty() && sources.size()==b.kv.size(),"one source per K/V layer, none captured"); + const SessionFileIdentity id{1,2}; + const std::string p1="/tmp/strata-snap-src-"+std::to_string(experts)+".bin", p2=p1+".ref"; + size_t n1=0,n2=0; + check(session_file_write(p1,meta,sources,id,n1,err),"streamed session write"); + check(session_file_write(p2,b,id,n2,err),"captured session write"); + SavedConversation x,y; + check(session_file_read(p1,id,x,n1,err) && session_file_read(p2,id,y,n2,err) && n1==n2,"both files read"); + check(x.live.gdn==y.live.gdn && x.live.dead==y.live.dead && x.live.ids==y.live.ids && + x.checkpoints.size()==y.checkpoints.size() && equal(x.kv[0],y.kv[0]) && equal(x.kv.back(),y.kv.back()), + "streamed file equals captured file"); + std::remove(p1.c_str()); std::remove(p2.c_str()); + auto empty_ids=std::vector{}; + const ConversationView none{empty_ids,images,checkpoints,true}; + check(!conversation_snapshot_sources(meta,sources,none,ss,g,draft.state,err),"empty session refused"); + } check(a.live.dead!=b.live.dead,"different opening-state spare keys in regression fixture"); auto bad=a; bad.kv.back().k.pop_back(); check(conversation_snapshot_restore(bad,ss,g,draft.state,err)==ConversationRestore::invalid, @@ -278,6 +300,25 @@ int main() { check(equal(a,restored),"A/B/A byte-exact K/V and indexer state"); uint64_t fingerprint = 0; check(conversation_kv_verify(a,f.state,f.g,upto,index,fingerprint,err),"verify restored authoritative and resident bytes without rewriting them"); + { + // disk save streams the same bytes as a captured image, without the host copy + SessionKvSource src; + check(conversation_kv_source(src,f.state,f.g,upto,index,err),"K/V source for a disk save"); + check(src.format==a.format && src.cells==a.cells && src.heads==a.heads && src.head_dim==a.head_dim && + src.page_size==a.page_size && src.pooled_rows==a.pooled_rows && src.idx_dim==a.idx_dim, + "K/V source metadata equals the captured image"); + const std::array parts={&a.k,&a.v,&a.k_scale,&a.v_scale,&a.pooled}; + for (size_t i=0;i<5;++i) { + check(src.sizes[i]==parts[i]->size(),"K/V source part size"); + std::vector got(src.sizes[i]), want(src.sizes[i]); + const size_t half=src.sizes[i]/2; // two reads: offsets are honoured + check(src.read(i,0,got.data(),half) && src.read(i,half,got.data()+half,src.sizes[i]-half), + "K/V source reads"); + check(parts[i]->read(want.data(),0,want.size()) && got==want,"K/V source bytes equal the image"); + } + SessionKvSource none; + check(!conversation_kv_source(none,f.state,f.g,-1,index,err),"K/V source rejects an invalid extent"); + } if (mode==1) { std::vector table((size_t)f.state.n_pages); cuda_check(cudaMemcpy(table.data(),f.state.page_table,table.size()*4,cudaMemcpyDeviceToHost)); diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp index 981beca1..eef6454f 100644 --- a/src/core/conversation_state.cpp +++ b/src/core/conversation_state.cpp @@ -273,6 +273,27 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView return true; } +bool conversation_snapshot_sources(SavedConversation& meta, std::vector& sources, + const ConversationView& view, const SessionState& ss, const ModelGeometry& g, + const QsaState& draft, std::string& error) { + if (!view_validate(view, ss, g, error) || !sync(error)) return false; + SavedConversation captured; + captured.geometry = geometry_key(g); + captured.layer_lo = ss.layer_lo; captured.layer_hi = ss.layer_hi; + captured.live.ids = view.ids; captured.live.imgs = view.images; + captured.cvec = view.cvec; captured.checkpoints = view.checkpoints; + if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false; + const int64_t upto = (int64_t) view.ids.size(); + const size_t layers = owned_qsa(ss); + std::vector out(layers + 1); + for (size_t j = 0; j < layers; ++j) + if (!conversation_kv_source(out[j], owned(ss, j), g, upto, true, error)) return false; + if (!conversation_kv_source(out.back(), draft, g, upto, false, error)) return false; + meta = std::move(captured); + sources = std::move(out); + return true; +} + bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& ss, const ModelGeometry& g, const QsaState* draft, std::string& error) { if (!image.live.stage_parts.empty()) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 04d50256..7bd5eead 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -19,6 +19,7 @@ #include "strata/core/remote_expert_opt.hpp" #include "strata/core/expert_cache.hpp" #include "strata/core/conversation_snapshot.hpp" +#include "strata/core/conversation_file.hpp" #include "strata/core/conversation_memory.hpp" #include "strata/core/coupled_draft.hpp" #include "strata/core/expert_source.hpp" @@ -6091,6 +6092,28 @@ int main(int argc, char** argv) { strata::core::ConversationCache conversations( o.prompt_cache > 0 ? (size_t) o.conversation_cache_mib * 1024 * 1024 : 0, (size_t) o.conversation_cache_slots); + // Disk sessions: what a session file is bound to. The model fingerprint samples the weight files once + // (conversation_file.hpp); the config fingerprint covers the options that change what the saved bytes mean. + std::optional model_fp; + auto session_identity = [&](strata::core::SessionFileIdentity& id, std::string& e) -> bool { + if (!model_fp) { + std::vector files = o.native_shards; + for (const std::string* p : {&o.pack, &o.ple_gguf, &o.mtp}) if (!p->empty()) files.push_back(*p); + uint64_t fp = 0; + if (!strata::core::session_model_fingerprint(files, fp, e)) return false; + model_fp = fp; + } + const char* rot = std::getenv("STRATA_KV_ROT"); + std::string cfg = std::string("engine=") + STRATA_VERSION + ";kv=" + o.kv + + ";max_context=" + std::to_string(o.max_context) + + ";kv_resident=" + std::to_string(o.kv_resident) + + ";mtp_window=" + std::to_string(o.mtp_window) + + ";kv_rot=" + (rot != nullptr && rot[0] == '1' ? "1" : "0") + ";cvec="; + for (const auto& c : o.cvec_files) cfg += c.first + ":" + std::to_string(c.second) + ","; + id.model = *model_fp; + id.config = strata::core::session_hash64(cfg.data(), cfg.size(), 0x434f4e464947ull); + return true; + }; // Save only on a switch/rewind, not on each continuing request. No graph // addresses change: all parked images live in ordinary host vectors. auto park_current_body = [&](size_t held) -> bool { @@ -7481,6 +7504,85 @@ int main(int argc, char** argv) { } busy_scope; stop_req.store(false); // a STOP that arrived between requests is stale err.clear(); + // Disk sessions: SAVE | RESTORE , between requests. The file holds + // what a parked conversation holds (conversation_file.hpp); a refused file leaves the session untouched. + if (line.rfind("SAVE ", 0) == 0 || line.rfind("RESTORE ", 0) == 0) { + const bool save = line[0] == 'S'; + const std::string path = line.substr(save ? 5 : 8); + const auto t0 = Clock::now(); + auto ms = [&] { return std::chrono::duration(Clock::now() - t0).count(); }; + auto refuse = [&](const std::string& why) { + std::fprintf(stderr, "strata serve: session %s %s: %s\n", save ? "save" : "restore", path.c_str(), + why.c_str()); + std::printf("ERR %s\n", why.c_str()); + std::fflush(stdout); + err.clear(); + }; + if (path.empty()) { refuse("missing path"); continue; } + if (!stages.empty() || multi_gpu) { refuse("session files do not support --layer-split"); continue; } + if (o.prompt_cache <= 0) { refuse("session files need --prompt-cache > 0"); continue; } + if (!ver.wait_commit(err)) { + std::printf("ERR %s\n", err.c_str()); + return 1; + } + strata::core::SessionFileIdentity id; + if (!session_identity(id, err)) { refuse(err); continue; } + if (save) { + if (!live_ok || live.empty()) { refuse("no complete session to save"); continue; } + // only the deepest checkpoint goes to disk (the next turn's resume point); the K/V is streamed + // from the authoritative pools straight into the file, without a full host capture + const auto disk_checks = strata::core::session_checkpoints_to_save(checks); + const strata::core::ConversationView view{live, live_imgs, disk_checks, cvec_cached}; + strata::core::SavedConversation meta; + std::vector sources; + size_t bytes = 0; + try { + if (!strata::core::conversation_snapshot_sources(meta, sources, view, ss, g, mtp.kv_state(), + err)) { + refuse(err); + continue; + } + } catch (const std::bad_alloc&) { refuse("not enough RAM for the snapshot"); continue; } + const double capture_ms = ms(); + if (!strata::core::session_file_write(path, meta, sources, id, bytes, err)) { refuse(err); continue; } + std::fprintf(stderr, "strata serve: session saved %zu tokens, %zu of %zu checkpoints, %zu bytes to %s " + "in %.1f ms (state %.1f ms)\n", live.size(), disk_checks.size(), checks.size(), bytes, + path.c_str(), ms(), capture_ms); + std::printf("SAVED %zu %zu %.1f\n", live.size(), bytes, ms()); + } else { + strata::core::SavedConversation image; + size_t bytes = 0; + try { + if (!strata::core::session_file_read(path, id, image, bytes, err)) { refuse(err); continue; } + } catch (const std::bad_alloc&) { refuse("not enough RAM to read the session"); continue; } + const double read_ms = ms(); + // the whole image against this engine, still without any CUDA write + if (!strata::core::conversation_snapshot_validate(image, ss, g, mtp.kv_state(), err)) { + refuse(err); + continue; + } + conversations.take_reuse(); // retained K/V described the outgoing session + live_ok = false; + if (strata::core::conversation_snapshot_restore(image, ss, g, mtp.kv_state(), err) != + strata::core::ConversationRestore::restored) { + // validated above: a failure here is a transfer failure - never decode from a partial state + std::printf("ERR restoring session file: %s\n", err.c_str()); + return 1; + } + live = std::move(image.live.ids); + live_imgs = std::move(image.live.imgs); + checks = std::move(image.checkpoints); + for (const ConvCheckpoint& c : checks) check_clock = std::max(check_clock, c.used); + cvec_cached = image.cvec; + live_ok = true; + std::fprintf(stderr, "strata serve: session restored %zu tokens, %zu checkpoints, %zu bytes from %s " + "in %.1f ms (read+check %.1f ms)\n", live.size(), checks.size(), bytes, path.c_str(), + ms(), read_ms); + std::printf("RESTORED %zu %zu %.1f\n", live.size(), bytes, ms()); + } + std::fflush(stdout); + continue; + } const bool geni = line.rfind("GENI ", 0) == 0; if (!geni && line.rfind("GEN ", 0) != 0) { std::printf("ERR expected: GEN or GENI \n");