diff --git a/include/strata/core/conversation_file.hpp b/include/strata/core/conversation_file.hpp index d4f7b965..c62324a5 100644 --- a/include/strata/core/conversation_file.hpp +++ b/include/strata/core/conversation_file.hpp @@ -1,26 +1,32 @@ -// 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). +// On-disk persistence of a conversation's state (SavedConversation): one file holding the running state, the +// checkpoints the caller passes (the engine passes only the deepest one), every QSA layer's authoritative K/V and +// the draft layer's K/V. Pure host code: no CUDA. Format v1 and the fail-closed read order are in +// docs/DETAILS.md (Session files). +// +// Format v1 is little-endian, with fixed-width integers and IEEE-754 floats; a big-endian build is refused at +// compile time. The hashes detect accidental corruption; they do not authenticate a file: restore trusted files only. #pragma once #include "strata/core/conversation_cache.hpp" #include #include -#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. +// What the file is bound to: the model files it was computed with, and the engine settings that change what the +// saved bytes mean. A read with any other identity is refused before the payload is parsed. struct SessionFileIdentity { uint64_t model = 0, config = 0; }; -// Non-cryptographic 64-bit hash (corruption and identity, not adversarial input). Streaming and one-shot agree. +// Non-cryptographic 64-bit hash with xxHash64-style rounds (NOT the standard XXH64 stream): corruption and identity +// checks, not adversarial input. Streaming and one-shot agree. class SessionHasher { public: explicit SessionHasher(uint64_t seed = 0); @@ -35,12 +41,71 @@ private: }; 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); +// Typed, length-delimited fields for an identity hash: each field is (tag, type, length, bytes), so two different +// field lists never give the same byte stream, and a double is hashed by its exact bits (no decimal rounding). +class SessionIdentityBuilder { +public: + explicit SessionIdentityBuilder(uint64_t seed) : hash_(seed) {} + void str(const std::string& tag, const std::string& value); + void i64(const std::string& tag, int64_t value); + void u64(const std::string& tag, uint64_t value); + void f64(const std::string& tag, double value); + void bytes(const std::string& tag, const void* data, size_t n); + uint64_t digest() const { return hash_.digest(); } +private: + void field(const std::string& tag, uint8_t type, const void* data, uint64_t n); + SessionHasher hash_; +}; -// Writes `.tmp` then renames it over `path`; on failure no file is left at either name. +// The RESOLVED rope configuration (rope_scaling.hpp, after the CLI flags and the model file's keys met). The cached +// K is post-RoPE, so a different rotation makes the saved K mean something else. +struct SessionRope { + int64_t type = 0; + double freq_base = 0, factor = 0, freq_scale = 0, orig_ctx = 0, ext_factor = 0, attn_factor = 0, beta_fast = 0, + beta_slow = 0; +}; + +// Every engine setting that changes what the saved state means. Sampling, seeds, draft tuning, the expert tier and +// the prompt-reading chunk are not here: they change what is computed next, not what the saved cells hold. +struct SessionConfig { + std::string engine_version; // a file is bound to one engine version + std::string backend; // "cuda" or "hip": no cross-backend restore + std::string kv; // --kv + int64_t max_context = 0, kv_resident = 0, mtp_window = 0; + bool kv_rot = false; // STRATA_KV_ROT + SessionRope rope; + // the control vectors as loaded: a digest of the tables the engine uploaded (every file's content x its exact + // scale, summed), the mode, the layer range and the direction; 0 when none is loaded + uint64_t cvec = 0; + // the arithmetic switches that change the computed state (name, value), in a fixed order + std::vector> switches; +}; +uint64_t session_config_fingerprint(const SessionConfig& config); + +// One model input the engine loaded and the role it plays ("native shard 1", "pack dense.bin", ...). The role, not +// the path, enters the fingerprint, so a moved model folder still matches. `optional`: a missing file is recorded +// as absent instead of failing (a pack without experts.bin). +struct SessionModelFile { + std::string role, path; + bool optional = false; +}; +// Sampled fingerprint of the model inputs: role, size, first and last MiB of each file, in the given order. Paths +// are UTF-8 (wide APIs on Windows; invalid UTF-8 is refused). An edit in the middle of a file that keeps its size is +// NOT detected: model files must not change while sessions saved with them are kept. +bool session_model_fingerprint(const std::vector& files, uint64_t& fingerprint, std::string& error); + +// Optional knobs of a write. +struct SessionWriteOptions { + uint64_t min_free_bytes = 0; // refuse when the disk would keep less than this free after the file + bool durable = true; // flush the file before the rename and the directory after it + std::function progress; // about every 256 MiB +}; + +// Writes a temporary file beside `path` (a unique name, created exclusively: never an existing file or link; mode +// 0600 on POSIX), flushes it to the disk, renames it over `path` and flushes the directory. On failure an existing +// file at `path` is kept and only this call's own temporary file is removed. bool session_file_write(const std::string& path, const SavedConversation& image, const SessionFileIdentity& id, - size_t& bytes, std::string& error); + size_t& bytes, std::string& error, const SessionWriteOptions& options = {}); // 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 @@ -53,14 +118,27 @@ struct SessionKvSource { }; // `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); + const SessionFileIdentity& id, size_t& bytes, std::string& error, + const SessionWriteOptions& options = {}); // 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. + +// What a read checks before it allocates. `admit(file_bytes, why)` is asked once the header and identity match and +// before any payload allocation (the parsed image is about as large as the file); false refuses the file. +struct SessionReadLimits { + uint64_t max_file_bytes = UINT64_MAX; + uint64_t max_tokens = UINT64_MAX; // token and image counts of the live state and of each checkpoint + uint64_t max_checkpoints = UINT64_MAX; + uint64_t max_kv_layers = UINT64_MAX; + std::function admit; + std::function progress; // about every 256 MiB +}; +// Full validation (a regular file with one link, size, header, identity, bounded parse, payload hash) before `image` +// is replaced. The file is opened without following a symbolic link (or a reparse point) at its name, and the checks +// are made on the opened handle. On failure `image` is unchanged. bool session_file_read(const std::string& path, const SessionFileIdentity& id, SavedConversation& image, - size_t& bytes, std::string& error); + size_t& bytes, std::string& error, const SessionReadLimits& limits = {}); } // namespace strata::core diff --git a/serve/server.py b/serve/server.py index 94bfed14..477faf16 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1382,21 +1382,47 @@ class StrataEngine: 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.""" + -> {"tokens", "bytes", "ms"}. ValueError with the engine's reason when it refused the file and the session is + as it was; EngineDied when the engine ended (a restore transfer that failed after the device state changed + ends it on purpose: FATAL), and EngineSilent (#481) when it printed nothing - no SESSION progress line either - + for engine_silence_s.""" + if action not in ("save", "restore") or any(c in path for c in "\r\n\0"): + raise ValueError("invalid session command") 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 + silence = float(self.silence_s or 0) + heard = time.monotonic() + want = "SAVED " if action == "save" else "RESTORED " while True: - line = self.lines.get() + left = silence - (time.monotonic() - heard) if silence > 0 else None + try: + if left is not None and left <= 0: + raise queue.Empty + line = self.lines.get(timeout=left) + except queue.Empty: + raise self._silent(f"the engine said nothing for {silence:.0f} s during a session {action}") from None if line is None: raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") + heard = time.monotonic() + if line.startswith("SESSION "): # a large file moving: progress, also a heartbeat + continue + if line.startswith("FATAL"): + raise EngineDied(line[6:].strip() or "the engine ended during a session restore") if line.startswith("ERR"): raise ValueError(line[4:].strip()) - if line.startswith(("SAVED ", "RESTORED ")): + if line.startswith(want): f = line.split() - return {"tokens": int(f[1]), "bytes": int(f[2]), "ms": float(f[3])} + try: + if len(f) != 4: + raise ValueError + return {"tokens": int(f[1]), "bytes": int(f[2]), "ms": float(f[3])} + except ValueError: + raise EngineDied(f"the engine answered a session {action} with {line.strip()!r}") from None + if line.startswith(("SAVED ", "RESTORED ", "T ", "DONE")): + raise EngineDied(f"the engine answered a session {action} with {line.strip()!r}") def close(self): """End the engine process: QUIT first (the engine frees its memory itself - unpinning tens of GB can take @@ -1946,6 +1972,50 @@ class StopMatcher: return held + +# Windows names that open a device whatever their extension or folder (Microsoft, "Naming Files, Paths, and Namespaces") +_WIN_DEVICES = {"con", "prn", "aux", "nul", "conin$", "conout$", *(f"com{i}" for i in "123456789\u00b9\u00b2\u00b3"), + *(f"lpt{i}" for i in "123456789\u00b9\u00b2\u00b3")} + + +def slot_filename_problem(name) -> str | None: + """/slots/0 {"filename": NAME}: why NAME is not one plain file name inside the slot save path, on Linux and on + Windows alike (None when it is). No separator or drive (`D:x`), no stream (`a:b`), no device (`NUL.txt`), no + trailing dot or space (Windows drops them), no control character, no leading dot (temporary files use it).""" + if not isinstance(name, str) or not name: + return "must be a non-empty string" + if len(name.encode("utf-8", "surrogatepass")) > 200: + return "is too long (at most 200 bytes)" + if any(ord(c) < 32 or ord(c) == 127 for c in name): + return "must not contain control characters" + if any(c in name for c in '/\\:*?"<>|'): + return "must be a plain file name (no / \\ : * ? \" < > |)" + if name.startswith("."): + return "must not start with a dot" + if name.endswith((".", " ")): + return "must not end with a dot or a space" + if name.split(".")[0].rstrip(" ").lower() in _WIN_DEVICES: + return "names a Windows device" + try: + name.encode("utf-8") + except UnicodeEncodeError: + return "is not valid Unicode" + return None + + +def slot_save_dir(value, base: str | None = None) -> str: + """The slot save path as one absolute, normalized directory (relative to `base`, else the server's working + directory), created private to this user when missing. ValueError for anything else.""" + if not isinstance(value, str) or not value.strip(): + raise ValueError("slot_save_path must be a directory path (a string)") + if any(ord(c) < 32 for c in value): + raise ValueError("slot_save_path must not contain control characters") + path = os.path.abspath(os.path.join(base, value) if base and not os.path.isabs(value) else value) + os.makedirs(path, mode=0o700, exist_ok=True) + if not os.path.isdir(path): + raise ValueError(f"slot_save_path {path} is not a directory") + return path + class Service: def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name: str = "qwen3.8-flash-next", vision: Vision | None = None, sampling_defaults: dict | None = None, @@ -2025,19 +2095,43 @@ class Service: 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") + why = slot_filename_problem(filename) + if why: + return error(400, f"filename {why}") 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") + if action == "restore": try: - r = self.engine.session_file(action, path) - except ValueError as e: - return error(400, str(e)) + os.lstat(path) # the engine opens it without following a link + except OSError: + return error(404, f"no saved session named {filename}") + self.last_request_at = time.time() # the idle unload counts this as activity + with self.status_lock: + self.status["queued"] += 1 + waiting = True + try: + with self.fifo: + with self.status_lock: + self.status["queued"] -= 1 + waiting = False + if not self.loaded(): + return error(503, "the model is not loaded") + with self.status_lock: + self.status.update(busy=True, phase="saving the session" if action == "save" + else "restoring a session", started=time.time(), first_token=None, + prompt_tokens=None, generated=None, max_tokens=None) + try: + r = self.engine.session_file(action, path) + except ValueError as e: + msg = str(e) + return error(507 if "disk space" in msg else 503 if "RAM" in msg else 400, msg) + finally: + with self.status_lock: + self.status["busy"] = False + self.last_request_at = time.time() + finally: + if waiting: # never reached the FIFO (an exception while waiting) + with self.status_lock: + self.status["queued"] -= 1 if action == "save": return 200, {"id_slot": 0, "filename": filename, "n_saved": r["tokens"], "n_written": r["bytes"], "timings": {"save_ms": r["ms"]}} @@ -3726,8 +3820,9 @@ def make_handler(svc: Service): 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"}} + except EngineDied as e: # EngineSilent included: the engine was ended + code, body = 500, {"error": {"code": 500, "message": str(e) + "; the next request starts " + "the engine again", "type": "server_error"}} self._json(code, body) elif path == "/v1/chat/completions": self._openai(req) @@ -4667,10 +4762,16 @@ 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) + # --slot-save-path is relative to the working directory the server was started in; the config's slot_save_path + # to the config's "cwd" (the engine's folder) when it has one. Either way the engine gets an absolute path. + if a.slot_save_path or cfg.get("slot_save_path"): + try: + svc.slot_save_path = slot_save_dir(a.slot_save_path) if a.slot_save_path else \ + slot_save_dir(cfg["slot_save_path"], cfg.get("cwd")) + except (ValueError, OSError) as e: + raise SystemExit(f"[strata] {e}") + print(f"[strata] slot save/restore on: {svc.slot_save_path} (session files are kept until deleted: " + "about 1.2 GB per 63K-token conversation; restore only files this server wrote)", 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_slots.py b/serve/test_slots.py index eb239411..e8251925 100644 --- a/serve/test_slots.py +++ b/serve/test_slots.py @@ -6,10 +6,12 @@ from __future__ import annotations import json +import os import queue import sys import tempfile import threading +import time import unittest import urllib.error import urllib.request @@ -17,7 +19,8 @@ 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 +from serve.server import (ByteTokenizer, Service, StrataEngine, serve, slot_filename_problem, # noqa: E402 + slot_save_dir) ROOT = Path(__file__).resolve().parents[1] @@ -33,6 +36,14 @@ class FakeProc: def write(self, s): self.sent.append(s) cmd, _, path = s.strip().partition(" ") + script = self.engine.script + if script is not None: # a scripted answer: a list of lines, None = the process ends + for line in script: + if isinstance(line, float): + time.sleep(line) + else: + self.engine.lines.put(line) + return if cmd == "SAVE": if self.engine.fail: self.engine.lines.put("ERR no complete session to save\n") @@ -51,7 +62,15 @@ class FakeProc: pass def poll(self): - return None + return -9 if self.killed else None + + killed = False + + def kill(self): + self.killed = True + + def wait(self, timeout=None): + return -9 class FakeEngine(StrataEngine): @@ -61,6 +80,7 @@ class FakeEngine(StrataEngine): self.unloaded, self.ended = False, False self.lines = queue.Queue() self.fail = False + self.script = None self.proc = FakeProc(self) @@ -83,7 +103,11 @@ class Slots(unittest.TestCase): def setUp(self): self.engine.fail = False - self.engine.proc.sent.clear() + self.engine.script = None + self.engine.silence_s = 300.0 + self.engine.ended = False + self.engine.proc = FakeProc(self.engine) + self.svc.slot_save_path = self.dir.name def post(self, path, body, headers=None): req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), @@ -132,11 +156,132 @@ class Slots(unittest.TestCase): 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"): + for bad in ("../x.bin", "/etc/passwd", "a/b.bin", "", ".", "..", "x\ny.bin", + # Windows: another drive, a stream, devices with and without an extension, names Windows trims + "D:escape.bin", "C:\\x.bin", "a.bin:stream", "NUL", "nul.txt", "CON.bin", "com1.x", "LPT9", + "a.bin.", "a.bin ", ".hidden", ".a.bin.0123456789abcdef.tmp", "x\x7fy", "a*b", "a?b", 'a"b', + "ab", "a|b", "x" * 201, None, 5, ["a"]): s, b = self.post("/slots/0?action=save", {"filename": bad}) self.assertEqual(s, 400, (bad, b)) self.assertEqual(self.engine.proc.sent, []) + def test_ordinary_names_are_accepted(self): + for good in ("a.bin", "chat-2026-10-03.bin", "a.bin.tmp", "consul.bin", "nullable", "caf\u00e9.bin", + "\u4f1a\u8bdd.bin", "x" * 200): + self.assertIsNone(slot_filename_problem(good), good) + + def test_relative_save_dir_becomes_absolute(self): + with tempfile.TemporaryDirectory() as base: + got = slot_save_dir("sessions", base) + self.assertEqual(got, os.path.join(base, "sessions")) + self.assertTrue(os.path.isabs(got) and os.path.isdir(got)) + if os.name != "nt": + self.assertEqual(os.stat(got).st_mode & 0o777, 0o700) + self.assertEqual(slot_save_dir(got, "/elsewhere"), got) # an absolute path stays as it is + cwd = os.getcwd() + try: + os.chdir(base) + self.assertEqual(slot_save_dir("rel"), os.path.join(os.path.realpath(base), "rel")) + finally: + os.chdir(cwd) + for bad in ("", " ", None, 3, "a\nb"): + with self.assertRaises(ValueError): + slot_save_dir(bad, base) + + def test_engine_gets_an_absolute_path_on_one_line(self): + self.post("/slots/0?action=save", {"filename": "abs.bin"}) + line = self.engine.proc.sent[0] + self.assertTrue(line.endswith("\n") and line.count("\n") == 1) + self.assertTrue(os.path.isabs(line[len("SAVE "):-1])) + + def test_restore_of_a_link_reaches_the_engine_which_decides(self): + """The server only checks the name exists (lstat); the engine opens it without following a link.""" + if os.name == "nt": + self.skipTest("symlinks need privileges on Windows") + target = Path(self.dir.name, "real.bin") + target.write_bytes(b"x") + link = Path(self.dir.name, "link.bin") + link.symlink_to(target) + dangling = Path(self.dir.name, "dangling.bin") + dangling.symlink_to(Path(self.dir.name, "nothing")) + self.engine.script = ["ERR session file: x: a symbolic link, not a file\n"] + for name in ("link.bin", "dangling.bin"): + s, b = self.post("/slots/0?action=restore", {"filename": name}) + self.assertEqual(s, 400, b) + self.assertIn("symbolic link", b["error"]["message"]) + + def test_progress_lines_keep_a_long_save_alive(self): + self.engine.silence_s = 0.3 + self.engine.script = [0.2, "SESSION 268435456 1198691396\n", 0.2, "SESSION 536870912 1198691396\n", 0.2, + "SAVED 63000 1198691396 2000.0\n"] + s, b = self.post("/slots/0?action=save", {"filename": "long.bin"}) + self.assertEqual(s, 200, b) + self.assertEqual(b["n_written"], 1198691396) + self.assertFalse(self.engine.ended) + + def test_a_silent_engine_is_ended_not_waited_for(self): + self.engine.silence_s = 0.3 + self.engine.script = [] # the engine never answers + t0 = time.monotonic() + s, b = self.post("/slots/0?action=save", {"filename": "silent.bin"}) + self.assertEqual(s, 500, b) + self.assertLess(time.monotonic() - t0, 5) + self.assertIn("said nothing", b["error"]["message"]) + self.assertTrue(self.engine.ended and self.engine.proc.killed) + self.assertTrue(self.svc.fifo.acquire(blocking=False)) # the FIFO was released + self.svc.fifo.release() + self.assertEqual(self.svc.status["queued"], 0) + self.assertFalse(self.svc.status["busy"]) + + def test_engine_death_is_a_server_error(self): + self.engine.script = [None] + s, b = self.post("/slots/0?action=save", {"filename": "dead.bin"}) + self.assertEqual(s, 500, b) + + def test_failed_restore_transfer_is_a_server_error(self): + Path(self.dir.name, "t.bin").write_bytes(b"x") + self.engine.script = ["SESSION 268435456 1198691396\n", + "FATAL restoring the session file failed after the device state was changed: copy\n"] + s, b = self.post("/slots/0?action=restore", {"filename": "t.bin"}) + self.assertEqual(s, 500, b) + self.assertIn("device state", b["error"]["message"]) + + def test_malformed_or_mismatched_reply_is_a_server_error(self): + for script in (["RESTORED 1 2 3\n"], ["SAVED x y z\n"], ["SAVED 1 2\n"], ["T 5\n"]): + self.engine.script = script + s, b = self.post("/slots/0?action=save", {"filename": "m.bin"}) + self.assertEqual(s, 500, (script, b)) + + def test_disk_and_ram_refusals_have_their_own_codes(self): + self.engine.script = ["ERR session file: not enough disk space (1143 MiB plus a reserve of 4096 MiB needed, " + "10 MiB free)\n"] + self.assertEqual(self.post("/slots/0?action=save", {"filename": "d.bin"})[0], 507) + Path(self.dir.name, "r.bin").write_bytes(b"x") + self.engine.script = ["ERR session file: not enough RAM to read it (1143 MiB plus a floor of 2560 MiB needed, " + "900 MiB available)\n"] + self.assertEqual(self.post("/slots/0?action=restore", {"filename": "r.bin"})[0], 503) + + def test_slot_work_counts_as_activity_and_shows_in_status(self): + seen = {} + + def during(): + time.sleep(0.15) + with self.svc.status_lock: + seen.update(self.svc.status) + self.engine.script = [0.4, "SAVED 1 2 3.0\n"] + self.svc.last_request_at = 0 + t = threading.Thread(target=during) + t.start() + s, _ = self.post("/slots/0?action=save", {"filename": "act.bin"}) + t.join() + self.assertEqual(s, 200) + self.assertTrue(seen.get("busy")) + self.assertEqual(seen.get("phase"), "saving the session") + self.assertGreater(self.svc.last_request_at, time.time() - 5) + self.assertFalse(self.svc.status["busy"]) + self.assertEqual(self.svc.status["queued"], 0) + self.assertEqual(self.svc.unload(idle_for=60), "busy") # just active: the idle unload waits + 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) diff --git a/src/core/conversation_file.cpp b/src/core/conversation_file.cpp index bacdf30a..3af4dcc4 100644 --- a/src/core/conversation_file.cpp +++ b/src/core/conversation_file.cpp @@ -1,12 +1,17 @@ #include "strata/core/conversation_file.hpp" #include +#include #include +#include +#include #include #include #include #include +#include #include +#include #include #include #ifdef _WIN32 @@ -18,17 +23,28 @@ #endif #include #include +#include #else #include +#include +#include +#include #include #endif +// Format v1 stores integers and floats as this machine holds them in memory; it is defined as little-endian with +// IEEE-754 floats, so a build where that is not the memory layout is refused rather than writing another format. +static_assert(std::endian::native == std::endian::little, "session files (format v1) are little-endian only"); +static_assert(std::numeric_limits::is_iec559 && std::numeric_limits::is_iec559, + "session files (format v1) need IEEE-754 floats"); + 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 kProgressEvery = 256ull << 20; constexpr uint64_t P1 = 0x9E3779B185EBCA87ull, P2 = 0xC2B2AE3D27D4EB4Full, P3 = 0x165667B19E3779F9ull, P4 = 0x85EBCA77C2B2AE63ull, P5 = 0x27D4EB2F165667C5ull; @@ -36,12 +52,10 @@ 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. +// (tmpfs, a filesystem that refuses an aligned direct transfer, 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); } }; @@ -53,18 +67,55 @@ using Aligned = std::unique_ptr; Aligned aligned_block() { return Aligned(static_cast(std::aligned_alloc(kAlign, kBlock))); } #endif +uint64_t random64() { + std::random_device rd; + uint64_t r = (uint64_t(rd()) << 32) ^ rd(); + r ^= (uint64_t) std::chrono::steady_clock::now().time_since_epoch().count() * P1; #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; + r ^= (uint64_t) _getpid() * P2; +#else + r ^= (uint64_t) ::getpid() * P2; +#endif + return r; } -std::string last_error() { - const DWORD code = GetLastError(); +// The temporary name beside the destination: hidden (a leading dot, which the server never accepts as a session +// name), unique, and short enough for any filesystem whatever the destination's length. +std::string temp_name(const std::string& leaf) { + size_t keep = std::min(leaf.size(), 64); + while (keep > 0 && keep < leaf.size() && (uint8_t(leaf[keep]) & 0xC0) == 0x80) --keep; // whole UTF-8 chars + char hex[17]; + std::snprintf(hex, sizeof hex, "%016llx", (unsigned long long) random64()); + return "." + leaf.substr(0, keep) + "." + hex + ".tmp"; +} + +bool split_path(const std::string& path, std::string& dir, std::string& leaf, std::string& error) { + const size_t cut = path.find_last_of( +#ifdef _WIN32 + "/\\" +#else + "/" +#endif + ); + dir = cut == std::string::npos ? std::string() : path.substr(0, cut == 0 ? 1 : cut); + leaf = cut == std::string::npos ? path : path.substr(cut + 1); + if (leaf.empty() || leaf == "." || leaf == "..") { error = "session file: " + path + " names no file"; return false; } + return true; +} + +#ifdef _WIN32 +// paths reach the engine as UTF-8 (the server writes its commands as UTF-8); invalid UTF-8 is refused, not replaced +bool wide(const std::string& s, std::wstring& w) { + w.clear(); + if (s.empty()) return true; + if (s.size() > (size_t) INT_MAX) return false; + const int n = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), (int) s.size(), nullptr, 0); + if (n <= 0) return false; + w.assign((size_t) n, L'\0'); + return MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), (int) s.size(), w.data(), n) == n; +} + +std::string last_error(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); @@ -76,11 +127,48 @@ std::string last_error() { class RawFile { public: ~RawFile() { close(); } - bool open_write(const std::string& path) { - return open(path, GENERIC_WRITE, 0, CREATE_ALWAYS); + // a new file that did not exist (CREATE_NEW: never an existing file or link) + bool create_new(const std::wstring& path) { + h_ = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, nullptr); + if (h_ == INVALID_HANDLE_VALUE) { error_ = last_error(); return false; } + return true; } - bool open_read(const std::string& path) { - return open(path, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING); + // a session to restore: the name itself is opened, never what a link or reparse point there points to; it must be + // an ordinary disk file with one name + bool open_session(const std::string& path, uint64_t& size) { + std::wstring w; + if (!wide(path, w)) { error_ = "the path is not valid UTF-8"; return false; } + h_ = CreateFileW(w.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_SEQUENTIAL_SCAN, nullptr); + if (h_ == INVALID_HANDLE_VALUE) { error_ = last_error(); return false; } + BY_HANDLE_FILE_INFORMATION info{}; + if (!GetFileInformationByHandle(h_, &info)) { error_ = last_error(); return false; } + if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { error_ = "a link or reparse point, not a file"; return false; } + if ((info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || GetFileType(h_) != FILE_TYPE_DISK) { + error_ = "not a regular file"; + return false; + } + if (info.nNumberOfLinks != 1) { error_ = "the file has more than one name (hard link)"; return false; } + size = (uint64_t(info.nFileSizeHigh) << 32) | info.nFileSizeLow; + return true; + } + // a model input: links followed (model folders are often linked) + bool open_model(const std::string& path, uint64_t& size) { + std::wstring w; + if (!wide(path, w)) { error_ = "the path is not valid UTF-8"; return false; } + h_ = CreateFileW(w.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, + nullptr); + if (h_ == INVALID_HANDLE_VALUE) { + const DWORD code = GetLastError(); + missing_ = code == ERROR_FILE_NOT_FOUND || code == ERROR_PATH_NOT_FOUND; + error_ = last_error(code); + return false; + } + LARGE_INTEGER s{}; + if (!GetFileSizeEx(h_, &s)) { error_ = last_error(); return false; } + size = (uint64_t) s.QuadPart; + return true; } bool is_open() const { return h_ != INVALID_HANDLE_VALUE; } bool direct() const { return false; } @@ -102,6 +190,17 @@ public: } return (long long) r; } + bool read_at(uint64_t offset, uint8_t* p, size_t n) { + LARGE_INTEGER at{}; + at.QuadPart = (LONGLONG) offset; + if (!SetFilePointerEx(h_, at, nullptr, FILE_BEGIN)) { error_ = last_error(); return false; } + while (n) { + const long long r = read_some(p, n); + if (r <= 0) { if (r == 0) error_ = "file ends early"; return false; } + p += r; n -= (size_t) r; + } + return true; + } bool truncate(uint64_t n) { LARGE_INTEGER at{}; at.QuadPart = (LONGLONG) n; @@ -109,6 +208,11 @@ public: error_ = last_error(); return false; } + bool sync() { + if (FlushFileBuffers(h_)) return true; + error_ = last_error(); + return false; + } bool close() { if (h_ == INVALID_HANDLE_VALUE) return true; const bool ok = CloseHandle(h_) != 0; @@ -117,26 +221,64 @@ public: return ok; } const std::string& error() const { return error_; } + bool missing() const { return missing_; } 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; + bool missing_ = false; 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)) +// Where the file is published. MoveFileExW replaces an existing destination (std::rename does not on Windows); the +// replacement is a rename on one volume, but Windows promises no transaction on every filesystem. A directory cannot +// be flushed on Windows: the file's data was flushed (FlushFileBuffers) before the move, and the move is write-through. +class Publisher { +public: + bool open(const std::string& path, std::string& error) { + std::string dir, leaf; + if (!split_path(path, dir, leaf, error)) return false; + std::wstring wdir, wleaf; + if (!wide(dir, wdir) || !wide(leaf, wleaf)) { error = "session file: the path is not valid UTF-8"; return false; } + prefix_ = wdir.empty() ? std::wstring() : (wdir.back() == L'\\' || wdir.back() == L'/' ? wdir : wdir + L"\\"); + final_ = prefix_ + wleaf; + leaf_ = leaf; return true; - error = last_error(); - return false; + } + bool create_temp(RawFile& f, std::string& error) { + for (int attempt = 0; attempt < 8; ++attempt) { + std::wstring name; + wide(temp_name(leaf_), name); + temp_ = prefix_ + name; + if (f.create_new(temp_)) { own_ = true; return true; } + if (GetLastError() != ERROR_FILE_EXISTS && GetLastError() != ERROR_ALREADY_EXISTS) break; + } + error = f.error(); + return false; + } + bool publish(std::string& error, bool) { + if (MoveFileExW(temp_.c_str(), final_.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { + own_ = false; + return true; + } + error = last_error(); + return false; + } + ~Publisher() { if (own_) DeleteFileW(temp_.c_str()); } // only the temporary file this call created +private: + std::wstring prefix_, final_, temp_; + std::string leaf_; + bool own_ = false; +}; + +bool free_space(const std::string& path, uint64_t& out) { + std::string dir, leaf, e; + if (!split_path(path, dir, leaf, e)) return false; + std::wstring w; + if (!wide(dir.empty() ? std::string(".") : dir, w)) return false; + ULARGE_INTEGER avail{}; + if (!GetDiskFreeSpaceExW(w.c_str(), &avail, nullptr, nullptr)) return false; + out = avail.QuadPart; + return true; } -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 @@ -147,17 +289,54 @@ bool buffered_forced() { return e != nullptr && e[0] == '1'; } +static_assert(sizeof(off_t) >= 8, "session files need 64-bit file offsets (large-file support)"); + 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); } + // a new file that did not exist (O_CREAT|O_EXCL: never an existing file or link), readable by its owner only + bool create_new(int dirfd, const std::string& name) { + fd_ = ::openat(dirfd, name.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600); + if (fd_ < 0) { error_ = std::strerror(errno); return false; } + try_direct(); + return true; + } + // a session to restore: the name itself is opened, never what a symbolic link there points to; it must be a + // regular file with one name (no hard link to a file elsewhere). Checked on the opened descriptor. + bool open_session(const std::string& path, uint64_t& size) { + fd_ = ::open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC); // NONBLOCK: a FIFO cannot hang + if (fd_ < 0) { + error_ = errno == ELOOP ? std::string("a symbolic link, not a file") : std::string(std::strerror(errno)); + return false; + } + struct stat st {}; + if (::fstat(fd_, &st) != 0) { error_ = std::strerror(errno); return false; } + if (!S_ISREG(st.st_mode)) { error_ = "not a regular file"; return false; } + if (st.st_nlink != 1) { error_ = "the file has more than one name (hard link)"; return false; } + const int fl = ::fcntl(fd_, F_GETFL); + if (fl >= 0) ::fcntl(fd_, F_SETFL, fl & ~O_NONBLOCK); + size = (uint64_t) st.st_size; + try_direct(); + return true; + } + // a model input: links followed (model folders are often linked) + bool open_model(const std::string& path, uint64_t& size) { + fd_ = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd_ < 0) { missing_ = errno == ENOENT; error_ = std::strerror(errno); return false; } + struct stat st {}; + if (::fstat(fd_, &st) != 0) { error_ = std::strerror(errno); return false; } + if (!S_ISREG(st.st_mode)) { error_ = "not a regular file"; return false; } + size = (uint64_t) st.st_size; + return true; + } 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; + // a filesystem that took O_DIRECT at open but refuses this transfer: nothing was written, go buffered + if (w < 0 && errno == EINVAL && direct_ && leave_direct()) continue; if (w <= 0) { error_ = w < 0 ? std::strerror(errno) : "short write"; return false; } p += w; n -= (size_t) w; } @@ -168,15 +347,30 @@ public: for (;;) { const ssize_t r = ::read(fd_, p, n); if (r < 0 && errno == EINTR) continue; + if (r < 0 && errno == EINVAL && direct_ && leave_direct()) continue; if (r < 0) error_ = std::strerror(errno); return (long long) r; } } + bool read_at(uint64_t offset, uint8_t* p, size_t n) { + while (n) { + const ssize_t r = ::pread(fd_, p, n, (off_t) offset); + if (r < 0 && errno == EINTR) continue; + if (r <= 0) { error_ = r < 0 ? std::strerror(errno) : "file ends early"; return false; } + p += r; n -= (size_t) r; offset += (uint64_t) r; + } + return true; + } bool truncate(uint64_t n) { if (::ftruncate(fd_, (off_t) n) == 0) return true; error_ = std::strerror(errno); return false; } + bool sync() { + if (::fsync(fd_) == 0) return true; + error_ = std::strerror(errno); + return false; + } bool close() { if (fd_ < 0) return true; const bool ok = ::close(fd_) == 0; @@ -185,36 +379,80 @@ public: return ok; } const std::string& error() const { return error_; } + bool missing() const { return missing_; } 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; + // O_DIRECT is switched on the open descriptor: a filesystem that refuses it (EINVAL, e.g. tmpfs) keeps buffered + // I/O, and the file is never opened twice + void try_direct() { + if (O_DIRECT == 0 || buffered_forced()) return; + const int fl = ::fcntl(fd_, F_GETFL); + direct_ = fl >= 0 && ::fcntl(fd_, F_SETFL, fl | O_DIRECT) == 0; + } + bool leave_direct() { + const int fl = ::fcntl(fd_, F_GETFL); + if (fl < 0 || ::fcntl(fd_, F_SETFL, fl & ~O_DIRECT) != 0) return false; + direct_ = false; + return true; } int fd_ = -1; - bool direct_ = false; + bool direct_ = false, missing_ = 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; +// The destination directory is opened once; the temporary file is created in it exclusively, renamed over the +// final name in the same directory (a symbolic link at the final name is replaced, never written through), and the +// directory is flushed after the rename so the new name survives a power loss. +class Publisher { +public: + bool open(const std::string& path, std::string& error) { + std::string dir; + if (!split_path(path, dir, leaf_, error)) return false; + dirfd_ = ::open(dir.empty() ? "." : dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dirfd_ < 0) { error = "session file: cannot open the directory of " + path + ": " + std::strerror(errno); return false; } + return true; + } + bool create_temp(RawFile& f, std::string& error) { + for (int attempt = 0; attempt < 8; ++attempt) { + temp_ = temp_name(leaf_); + if (f.create_new(dirfd_, temp_)) { own_ = true; return true; } + if (errno != EEXIST) break; + } + error = f.error(); + return false; + } + bool publish(std::string& error, bool durable) { + if (::renameat(dirfd_, temp_.c_str(), dirfd_, leaf_.c_str()) != 0) { error = std::strerror(errno); return false; } + own_ = false; + if (durable && ::fsync(dirfd_) != 0 && errno != EINVAL) { // EINVAL: this filesystem cannot flush a directory + error = std::string("flushing the directory: ") + std::strerror(errno); + return false; + } + return true; + } + ~Publisher() { + if (own_) ::unlinkat(dirfd_, temp_.c_str(), 0); // only the temporary file this call created + if (dirfd_ >= 0) ::close(dirfd_); + } +private: + int dirfd_ = -1; + std::string leaf_, temp_; + bool own_ = false; +}; + +bool free_space(const std::string& path, uint64_t& out) { + std::string dir, leaf, e; + if (!split_path(path, dir, leaf, e)) return false; + struct statvfs s {}; + if (::statvfs(dir.empty() ? "." : dir.c_str(), &s) != 0) return false; + out = (uint64_t) s.f_bavail * (uint64_t) s.f_frsize; + return true; } -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(); } + explicit FileSink(RawFile& f) : buf_(aligned_block()), f_(f) {} + bool ok() const { return buf_ != nullptr; } 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_; } @@ -231,34 +469,36 @@ public: } return true; } - // last block padded to the alignment for direct I/O, then the file cut back to its exact size - bool finish() { + // last block padded to the alignment for direct I/O, then the file cut back to its exact size and flushed + bool finish(bool durable) { 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 = ok && (!durable || f_.sync()); ok = f_.close() && ok; return ok; } + std::function progress; + uint64_t expected = 0; private: bool drain() { if (!f_.write_all(buf_.get(), used_)) return false; used_ = 0; + if (progress && total_ / kProgressEvery != (total_ - kBlock) / kProgressEvery) progress(total_, expected); return true; } Aligned buf_; - RawFile f_; + 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(); } + explicit FileSource(RawFile& f) : buf_(aligned_block()), f_(f) {} + bool ok() const { return buf_ != nullptr; } 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); @@ -270,6 +510,8 @@ public: } return true; } + std::function progress; + uint64_t expected = 0; private: bool fill() { at_ = have_ = 0; @@ -280,11 +522,15 @@ private: have_ += (size_t) r; if (f_.direct() && have_ % kAlign) break; // short aligned read: end of file } + const uint64_t before = total_; + total_ += have_; + if (progress && total_ / kProgressEvery != before / kProgressEvery) progress(total_, expected); return have_ > 0; } Aligned buf_; - RawFile f_; + RawFile& f_; size_t at_ = 0, have_ = 0; + uint64_t total_ = 0; }; // ---- serialization: the same walk counts (f == nullptr) and writes @@ -292,9 +538,13 @@ struct Out { FileSink* f = nullptr; SessionHasher* hash = nullptr; uint64_t n = 0; - bool ok = true; - void raw(const void* p, size_t c) { + bool ok = true, overflow = false; + void count(uint64_t c) { + if (c > UINT64_MAX - n) { overflow = true; ok = false; return; } n += c; + } + void raw(const void* p, size_t c) { + count(c); if (!f || !ok || !c) return; if (hash) hash->update(p, c); ok = f->write(p, c); @@ -310,15 +560,15 @@ struct Out { void source(const SessionKvSource& s, size_t part) { const size_t size = s.sizes[part]; u64(size); - if (!f) { n += size; return; } + if (!f) { count(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); + count(c); + ok = ok && f->commit(c); at += c; } } @@ -359,30 +609,35 @@ void put_payload(Out& o, const SavedConversation& s, const std::vector left) return fail("payload ends early"); - if (c && !f->read(p, c)) return fail("read error"); + if (c && !f->read(p, c)) return fail("read error: " + f->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) { + // `elem`: the fewest file bytes one element takes; `limit`: the most elements the caller accepts + bool count(uint64_t& n, size_t elem, uint64_t limit = UINT64_MAX) { if (!u64(n)) return false; if (elem && n > left / elem) return fail("element count exceeds the payload"); + if (n > limit) return fail("element count " + std::to_string(n) + " exceeds this engine's limit " + + std::to_string(limit)); + if (n > (uint64_t) std::numeric_limits::max() / (elem ? elem : 1)) return fail("element count too large"); return true; } - template bool vec(std::vector& v) { + template bool vec(std::vector& v, uint64_t limit = UINT64_MAX) { uint64_t n = 0; - if (!count(n, sizeof(T))) return false; + if (!count(n, sizeof(T), limit)) return false; v.resize((size_t) n); return raw(v.data(), (size_t) n * sizeof(T)); } @@ -396,9 +651,9 @@ struct In { }; bool get_checkpoint(In& in, ConversationCheckpoint& c) { - if (!in.vec(c.ids)) return false; + if (!in.vec(c.ids, in.limits.max_tokens)) return false; uint64_t n = 0; - if (!in.count(n, 16)) return false; + if (!in.count(n, 16, in.limits.max_tokens)) 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) && @@ -414,10 +669,10 @@ bool get_payload(In& in, SavedConversation& s) { 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; + if (!in.count(n, 72, in.limits.max_checkpoints)) 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; + if (!in.count(n, 96, in.limits.max_kv_layers)) return false; s.kv.resize((size_t) n); for (auto& k : s.kv) { int64_t format = 0; @@ -437,6 +692,8 @@ bool has_stage_parts(const SavedConversation& s) { return false; } +// header v1, little-endian: magic[8] version:u32 header_size:u32 model:u64 config:u64 payload:u64 reserved:u64[2] +// header_hash:u64 (session_hash64 of bytes 0..55, seed 0) void header_bytes(uint8_t* h, const SessionFileIdentity& id, uint64_t payload) { std::memset(h, 0, kHeader); std::memcpy(h, kMagic, 8); @@ -470,7 +727,7 @@ void SessionHasher::update(const void* data, size_t n) { npending_ = 0; } for (; n >= 32; p += 32, n -= 32) block(p); - std::memcpy(pending_, p, n); + if (n) std::memcpy(pending_, p, n); npending_ = n; } @@ -491,43 +748,75 @@ uint64_t session_hash64(const void* data, size_t n, uint64_t seed) { return h.digest(); } -bool session_model_fingerprint(const std::vector& paths, uint64_t& fingerprint, std::string& error) { - namespace fs = std::filesystem; - SessionHasher h(0x5354524154414d44ull); +void SessionIdentityBuilder::field(const std::string& tag, uint8_t type, const void* data, uint64_t n) { + const uint64_t tn = tag.size(); + hash_.update(&tn, 8); + hash_.update(tag.data(), tag.size()); + hash_.update(&type, 1); + hash_.update(&n, 8); + if (n) hash_.update(data, (size_t) n); +} +void SessionIdentityBuilder::str(const std::string& tag, const std::string& v) { field(tag, 's', v.data(), v.size()); } +void SessionIdentityBuilder::i64(const std::string& tag, int64_t v) { field(tag, 'i', &v, 8); } +void SessionIdentityBuilder::u64(const std::string& tag, uint64_t v) { field(tag, 'u', &v, 8); } +void SessionIdentityBuilder::f64(const std::string& tag, double v) { + uint64_t bits = 0; + std::memcpy(&bits, &v, 8); + field(tag, 'f', &bits, 8); +} +void SessionIdentityBuilder::bytes(const std::string& tag, const void* data, size_t n) { field(tag, 'b', data, n); } + +uint64_t session_config_fingerprint(const SessionConfig& c) { + SessionIdentityBuilder b(0x434f4e4649473031ull); // "CONFIG01" + b.str("engine", c.engine_version); + b.str("backend", c.backend); + b.str("kv", c.kv); + b.i64("max_context", c.max_context); + b.i64("kv_resident", c.kv_resident); + b.i64("mtp_window", c.mtp_window); + b.i64("kv_rot", c.kv_rot ? 1 : 0); + b.i64("rope.type", c.rope.type); + b.f64("rope.freq_base", c.rope.freq_base); + b.f64("rope.factor", c.rope.factor); + b.f64("rope.freq_scale", c.rope.freq_scale); + b.f64("rope.orig_ctx", c.rope.orig_ctx); + b.f64("rope.ext_factor", c.rope.ext_factor); + b.f64("rope.attn_factor", c.rope.attn_factor); + b.f64("rope.beta_fast", c.rope.beta_fast); + b.f64("rope.beta_slow", c.rope.beta_slow); + b.u64("cvec", c.cvec); + b.u64("switches", c.switches.size()); + for (const auto& [name, value] : c.switches) b.i64("switch." + name, value); + return b.digest(); +} + +bool session_model_fingerprint(const std::vector& files, uint64_t& fingerprint, std::string& error) { + SessionIdentityBuilder 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; } + h.u64("files", files.size()); + for (const auto& file : files) { + RawFile f; + uint64_t size = 0; + if (!f.open_model(file.path, size)) { + if (file.optional && f.missing()) { h.str("absent", file.role); continue; } + error = "session fingerprint: " + file.role + " " + file.path + ": " + f.error(); + return false; + } + h.str("role", file.role); + h.u64("size", size); 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 (!f.read_at(0, buf.data(), (size_t) head)) { + error = "session fingerprint: reading " + file.path + ": " + f.error(); + return false; + } + h.bytes("head", buf.data(), (size_t) 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; + if (!f.read_at(size - tail, buf.data(), (size_t) tail)) { + error = "session fingerprint: reading " + file.path + ": " + f.error(); + return false; + } + h.bytes("tail", buf.data(), (size_t) tail); } } fingerprint = h.digest(); @@ -536,15 +825,35 @@ bool session_model_fingerprint(const std::vector& paths, uint64_t& namespace { bool write_impl(const std::string& path, const SavedConversation& image, const std::vector* sources, - const SessionFileIdentity& id, size_t& bytes, std::string& error) { + const SessionFileIdentity& id, size_t& bytes, std::string& error, const SessionWriteOptions& opt) { 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; } + if (sizing.overflow || sizing.n > UINT64_MAX - kHeader - kTrailer || + sizing.n + kHeader + kTrailer > (uint64_t) std::numeric_limits::max()) { + error = "session file: the state is too large for this build"; + return false; + } + const uint64_t payload = sizing.n, total = kHeader + payload + kTrailer; + if (opt.min_free_bytes) { + uint64_t avail = 0; + if (!free_space(path, avail)) { error = "session file: cannot read the free disk space for " + path; return false; } + if (avail < total || avail - total < opt.min_free_bytes) { + error = "session file: not enough disk space (" + std::to_string(total >> 20) + " MiB plus a reserve of " + + std::to_string(opt.min_free_bytes >> 20) + " MiB needed, " + std::to_string(avail >> 20) + + " MiB free)"; + return false; + } + } + Publisher pub; + if (!pub.open(path, error)) return false; + RawFile raw; + if (!pub.create_temp(raw, error)) { error = "session file: cannot create a temporary file beside " + path + ": " + error; return false; } + FileSink f(raw); + if (!f.ok()) { error = "session file: " + f.error(); return false; } + f.progress = opt.progress; + f.expected = total; uint8_t h[kHeader]; header_bytes(h, id, payload); bool ok = f.write(h, kHeader); @@ -556,15 +865,14 @@ bool write_impl(const std::string& path, const SavedConversation& image, const s const uint64_t ph = hash.digest(); ok = f.write(&ph, 8) && f.write(kEnd, 8); } - ok = f.finish() && ok; + ok = f.finish(opt.durable) && 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; + if (ok && pub.publish(why, opt.durable)) { + bytes = (size_t) total; return true; } error = "session file: writing " + path + " failed" + (why.empty() ? std::string() : ": " + why); - remove_file(tmp); - return false; + return false; // Publisher removes this call's temporary file, and only that } } // namespace @@ -577,24 +885,29 @@ std::vector session_checkpoints_to_save(const std::vecto } 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); + const SessionFileIdentity& id, size_t& bytes, std::string& error, + const SessionWriteOptions& options) { + return write_impl(path, meta, &kv, id, bytes, error, options); } 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); + size_t& bytes, std::string& error, const SessionWriteOptions& options) { + return write_impl(path, image, nullptr, id, bytes, error, options); } bool session_file_read(const std::string& path, const SessionFileIdentity& id, SavedConversation& image, - size_t& bytes, std::string& error) { + size_t& bytes, std::string& error, const SessionReadLimits& limits) { 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; } + RawFile raw; + uint64_t size = 0; + if (!raw.open_session(path, size)) { error = "session file: " + path + ": " + raw.error(); 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; } + if (size > limits.max_file_bytes || size > (uint64_t) std::numeric_limits::max()) { + error = "session file: size " + std::to_string(size) + " exceeds this engine's limit"; + return false; + } + FileSource f(raw); + if (!f.ok()) { error = "session file: " + 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; @@ -613,8 +926,14 @@ bool session_file_read(const std::string& path, const SessionFileIdentity& id, S std::to_string(kHeader + payload + kTrailer) + ")"; return false; } + if (limits.admit) { + std::string why; + if (!limits.admit(size, why)) { error = "session file: " + why; return false; } + } + f.progress = limits.progress; + f.expected = size; SavedConversation parsed; - In in{&f, SessionHasher(0), payload, error}; + In in{&f, SessionHasher(0), payload, error, limits}; 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]; diff --git a/src/core/conversation_file_test.cpp b/src/core/conversation_file_test.cpp index b819546f..33099aa2 100644 --- a/src/core/conversation_file_test.cpp +++ b/src/core/conversation_file_test.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -11,6 +12,11 @@ #include #include #include +#ifndef _WIN32 +#include +#include +#include +#endif using namespace strata::core; namespace fs = std::filesystem; @@ -111,11 +117,21 @@ void spit(const fs::path& p, const std::vector& d) { f.write(d.data(), (std::streamsize) d.size()); } -bool rejects(const fs::path& p, const SessionFileIdentity& id, const char* expect = nullptr) { +// no temporary file (any leftover of a write) in the directory +bool no_temp(const fs::path& dir) { + for (const auto& e : fs::directory_iterator(dir)) { + const std::string n = e.path().filename().string(); + if (n.size() > 4 && n.compare(n.size() - 4, 4, ".tmp") == 0 && n != "planted.bin.tmp") return false; + } + return true; +} + +bool rejects(const fs::path& p, const SessionFileIdentity& id, const char* expect = nullptr, + const SessionReadLimits& limits = {}) { SavedConversation out; size_t bytes = 0; std::string error; - const bool ok = session_file_read(p.string(), id, out, bytes, error); + const bool ok = session_file_read(p.string(), id, out, bytes, error, limits); 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; @@ -138,7 +154,7 @@ int main() { 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"); + check(no_temp(dir), "no temporary left behind"); { SavedConversation back; size_t read = 0; @@ -158,7 +174,7 @@ int main() { 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"); + check(no_temp(dir), "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 { @@ -168,7 +184,7 @@ int main() { 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"); + check(session_file_read(p.string(), id, back, read, error) && same(original, back), "buffered read"); set_env("STRATA_SESSION_BUFFERED", nullptr); } @@ -230,7 +246,7 @@ int main() { 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"); + check(!fs::exists(p) && no_temp(dir), "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), @@ -248,13 +264,27 @@ int main() { 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"); + uint64_t f1 = 0, f2 = 0, f3 = 0, f4 = 0, f5 = 0, f6 = 0, f7 = 0, f8 = 0; + const std::vector both = {{"a", m1.string()}, {"b", m2.string()}}; + check(session_model_fingerprint(both, f1, error), "fingerprint ok"); + check(session_model_fingerprint({{"a", m1.string()}}, f2, error), "fingerprint subset ok"); + check(session_model_fingerprint({{"b", m1.string()}, {"a", m2.string()}}, f5, error), "fingerprint roles ok"); + check(f1 != f5, "fingerprint follows the role each file plays"); + // a moved folder: same roles, same bytes, other paths + const fs::path moved = dir / "moved"; + fs::create_directories(moved); + fs::copy_file(m1, moved / "m1.bin"); fs::copy_file(m2, moved / "m2.bin"); + check(session_model_fingerprint({{"a", (moved / "m1.bin").string()}, {"b", (moved / "m2.bin").string()}}, f6, + error) && f6 == f1, "fingerprint does not follow the folder"); + // an optional input that is absent is recorded, not an error; a present one changes the fingerprint + check(session_model_fingerprint({{"a", m1.string()}, {"b", m2.string()}, {"c", (dir / "nothere").string(), true}}, + f7, error), "absent optional input ok"); + check(session_model_fingerprint({{"a", m1.string()}, {"b", m2.string()}, {"c", m2.string(), true}}, f8, error) && + f7 != f8 && f7 != f1, "optional input presence enters the fingerprint"); 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(session_model_fingerprint(both, 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"); + check(!session_model_fingerprint({{"x", (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 @@ -291,12 +321,128 @@ int main() { 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"); + check(!fs::exists(q) && no_temp(dir), "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"); } + // the configuration fingerprint: every field counts, doubles by their exact bits + { + SessionConfig c; + c.engine_version = "0.1.38"; c.backend = "cuda"; c.kv = "int8"; c.max_context = 65536; c.kv_resident = 0; + c.mtp_window = 4; c.rope.type = 0; c.rope.freq_base = 1e7; c.rope.factor = 1.0; c.rope.freq_scale = 1.0; + c.rope.orig_ctx = 262144; c.rope.attn_factor = 1.0; c.rope.beta_fast = 32; c.rope.beta_slow = 1; + c.switches = {{"STRATA_FAST_GDN", 0}}; + const uint64_t base = session_config_fingerprint(c); + check(session_config_fingerprint(c) == base, "config fingerprint is deterministic"); + auto differs = [&](auto edit) { SessionConfig d = c; edit(d); return session_config_fingerprint(d) != base; }; + check(differs([](SessionConfig& d) { d.engine_version = "0.1.39"; }), "engine version enters the config"); + check(differs([](SessionConfig& d) { d.backend = "hip"; }), "backend enters the config"); + check(differs([](SessionConfig& d) { d.kv = "fp16"; }), "kv enters the config"); + check(differs([](SessionConfig& d) { d.max_context = 65537; }), "max context enters the config"); + check(differs([](SessionConfig& d) { d.kv_resident = 1; }), "kv residency enters the config"); + check(differs([](SessionConfig& d) { d.mtp_window = 0; }), "mtp window enters the config"); + check(differs([](SessionConfig& d) { d.kv_rot = true; }), "kv rotation enters the config"); + check(differs([](SessionConfig& d) { d.rope.factor = std::nextafter(1.0, 2.0); }), + "a one-ulp rope change enters the config"); + check(differs([](SessionConfig& d) { d.rope.type = 2; }), "rope type enters the config"); + check(differs([](SessionConfig& d) { d.rope.beta_slow = 2; }), "rope beta enters the config"); + check(differs([](SessionConfig& d) { d.cvec = 7; }), "control vectors enter the config"); + check(differs([](SessionConfig& d) { d.switches[0].second = 1; }), "a switch value enters the config"); + check(differs([](SessionConfig& d) { d.switches.push_back({"X", 0}); }), "the switch list enters the config"); + // field boundaries: ("ab","c") and ("a","bc") hash differently + SessionIdentityBuilder x(1), y(1); + x.str("ab", "c"); y.str("a", "bc"); + check(x.digest() != y.digest(), "identity fields are length-delimited"); + SessionIdentityBuilder i(1), u(1); + i.i64("n", 5); u.u64("n", 5); + check(i.digest() != u.digest(), "identity fields are typed"); + } + // bounds a read checks before it allocates, and the caller's admission + { + SessionReadLimits l; + l.max_tokens = 999; // the live state holds 1000 + check(rejects(good, id, "limit", l), "token count over the limit refused"); + l = {}; l.max_checkpoints = 1; + check(rejects(good, id, "limit", l), "checkpoint count over the limit refused"); + l = {}; l.max_kv_layers = 2; + check(rejects(good, id, "limit", l), "K/V layer count over the limit refused"); + l = {}; l.max_file_bytes = image.size() - 1; + check(rejects(good, id, "limit", l), "file over the size limit refused"); + l = {}; + uint64_t asked = 0; + l.admit = [&](uint64_t n, std::string& why) { asked = n; why = "no room for it"; return false; }; + check(rejects(good, id, "no room", l) && asked == image.size(), "admission sees the file size and can refuse"); + l = {}; + bool admitted = false; + l.admit = [&](uint64_t, std::string&) { admitted = true; return true; }; + check(rejects(good, {id.model ^ 1, id.config}, "model", l) && !admitted, + "admission is not asked for a foreign file"); + SavedConversation back; + size_t n = 0; + check(session_file_read(good.string(), id, back, n, error, l) && admitted && same(back, original), + "admitted file reads"); + } + // free-space reserve: an impossible reserve refuses the write and leaves the existing file untouched + { + const fs::path p = dir / "reserve.bin"; + spit(p, std::vector(10, 'r')); + SessionWriteOptions opt; + opt.min_free_bytes = UINT64_MAX / 2; + check(!session_file_write(p.string(), original, id, written, error, opt) && + error.find("disk space") != std::string::npos, "write over the free-space reserve refused"); + check(slurp(p) == std::vector(10, 'r') && no_temp(dir), "refused write keeps the old file, no temporary"); + opt.min_free_bytes = 1; + uint64_t calls = 0; + opt.progress = [&](uint64_t, uint64_t) { ++calls; }; + check(session_file_write(p.string(), original, id, written, error, opt) && slurp(p) == image, + "write with a small reserve succeeds"); + } + // a failed write over an existing session keeps it, and touches no other file (a planted name of the old + // fixed temporary pattern included) + { + const fs::path p = dir / "keep.bin", planted = dir / "planted.bin.tmp"; + check(session_file_write(p.string(), original, id, written, error), "keep: first write"); + spit(planted, std::vector(5, 'p')); + SavedConversation meta = original; + meta.kv.clear(); + std::vector broken(1); + broken[0].sizes = {100, 0, 0, 0, 0}; + broken[0].read = [](size_t, size_t, void*, size_t) { return false; }; + check(!session_file_write(p.string(), meta, broken, id, written, error), "keep: failing write fails"); + check(slurp(p) == image, "keep: the previous session survives a failed write"); + check(slurp(planted) == std::vector(5, 'p') && no_temp(dir), "keep: no other file touched"); + } +#ifndef _WIN32 + // what restore will not open: a symbolic link, a hard-linked file, a FIFO, a directory + { + const fs::path link = dir / "link.bin"; + fs::create_symlink(good, link); + check(rejects(link, id, "symbolic link"), "a symbolic link is not followed"); + const fs::path hard = dir / "hard.bin"; + fs::create_hard_link(dir / "again.bin", hard); + check(rejects(hard, id, "hard link"), "a hard-linked file is refused"); + fs::remove(hard); + check(!rejects(dir / "again.bin", id), "the same file with one name again reads"); + const fs::path fifo = dir / "fifo.bin"; + check(::mkfifo(fifo.c_str(), 0600) == 0, "mkfifo"); + check(rejects(fifo, id, "regular"), "a FIFO is refused without blocking"); + check(rejects(dir / "moved", id, "regular"), "a directory is refused"); + } + // saving over a symbolic link replaces the link, never writes through it; the new file is the owner's only + { + const fs::path target = dir / "target.bin", link = dir / "out-link.bin"; + spit(target, std::vector(7, 't')); + fs::create_symlink(target, link); + check(session_file_write(link.string(), original, id, written, error), "write at a link name"); + check(!fs::is_symlink(link) && slurp(link) == image, "the link was replaced by the file"); + check(slurp(target) == std::vector(7, 't'), "the link's target is untouched"); + struct stat st {}; + check(::stat(link.c_str(), &st) == 0 && (st.st_mode & 0777) == 0600, "the session file is mode 0600"); + } +#endif + fs::remove_all(dir); std::printf("conversation_file_test: %d checks passed\n", checks); return 0; diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp index e0dcc29e..b71e8a93 100644 --- a/src/core/conversation_snapshot_test.cpp +++ b/src/core/conversation_snapshot_test.cpp @@ -4,7 +4,12 @@ #include #include +#include #include +#include +#include +#include +#include #include #include #include @@ -153,7 +158,13 @@ void full_session(int fmt, int mode, int experts) { 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"; + namespace fs=std::filesystem; + const fs::path dir=fs::temp_directory_path()/("strata-snap-test-"+std::to_string(experts)+"-"+ + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + fs::create_directories(dir); + const std::string p1=(dir/"streamed.bin").string(), p2=(dir/"captured.bin").string(); + auto slurp=[](const std::string& p){ std::ifstream f(p,std::ios::binary); + return std::vector((std::istreambuf_iterator(f)),std::istreambuf_iterator()); }; 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"); @@ -162,7 +173,9 @@ void full_session(int fmt, int mode, int experts) { 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()); + check(slurp(p1)==slurp(p2),"streamed file is byte-identical to the captured file"); + std::error_code ec; + fs::remove_all(dir,ec); 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"); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 7bd5eead..9ef552ae 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -577,6 +577,8 @@ struct Options { int64_t conversation_cache_mib = 0; // opt-in host RAM for independent conversations int conversation_cache_slots = 4; int64_t conversation_cache_min_free_mib = 2560; + /// --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; /// --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 @@ -713,7 +715,9 @@ void usage() { " of RAM each; 0 = read every prompt from the start)\n" " --conversation-cache-mib N --serve: RAM budget for parked conversations (default 0 = off)\n" " --conversation-cache-slots N --serve: at most N parked conversations (default 4)\n" - " --conversation-cache-min-free-mib N --serve: physical RAM floor when parking (default 2560)\n" + " --conversation-cache-min-free-mib N --serve: physical RAM floor when parking or restoring a\n" + " session file (default 2560)\n" + " --session-min-free-mib N --serve: disk space a SAVE must leave free (default 4096; 0 = no check)\n" " --vram-elastic --serve (#533, opt-in, NVIDIA): the expert cache in segments (--vram-segment-mib,\n" " default 512), so the command `VRAM ` (the server's POST /v1/vram) can\n" " give VRAM back to other programs between requests and take it back later\n" @@ -1308,8 +1312,10 @@ bool checkpoint_restore(const ConvCheckpoint& c, strata::core::SessionState& ss, // --control-vector-scaled: llama.cpp's `common_control_vector_load` (every file's `direction.` times its scale, // summed; layer 0 has none) and `llama_adapter_cvec::apply` with the projection-mode patch (project: the unit -// direction and its norm as the scale), into the tables `cvec_upload` takes. `summary` is what INFO reports. -bool load_control_vectors(const Options& o, const strata::core::ModelGeometry& g, std::string& summary, std::string& err) { +// direction and its norm as the scale), into the tables `cvec_upload` takes. `summary` is what INFO reports; +// `digest` identifies the uploaded tables, mode and range exactly (a session file is bound to it). +bool load_control_vectors(const Options& o, const strata::core::ModelGeometry& g, std::string& summary, + uint64_t& digest, std::string& err) { const int64_t L = g.n_layers, N = g.n_embd; std::vector data((size_t) (L * N), 0.0f); std::vector have((size_t) L, false); @@ -1372,6 +1378,17 @@ bool load_control_vectors(const Options& o, const strata::core::ModelGeometry& g } if (steered == 0) { err = "the control vector has no direction in layers " + std::to_string(first) + ".." + std::to_string(last); return false; } if (!strata::kernels::cvec_upload(dir, s, o.cvec_mode, first, last, N, g.hc, err)) return false; + { + strata::core::SessionIdentityBuilder b(0x43564543ull); // "CVEC" + b.i64("mode", o.cvec_mode); + b.i64("first", first); + b.i64("last", last); + b.i64("single", single); + b.bytes("dir", dir.data(), dir.size() * sizeof(float)); + b.bytes("scale", s.data(), s.size() * sizeof(float)); + digest = b.digest(); + if (digest == 0) digest = 1; // 0 means "none loaded" + } summary = std::string(o.cvec_mode == 0 ? "project" : "add") + ":" + std::to_string(first) + "-" + std::to_string(last) + (single >= 0 ? ":single" + std::to_string(single) : ""); // the line llama.cpp's patched build prints, so a log shows the same thing @@ -1656,7 +1673,7 @@ int main(int argc, char** argv) { else if (a == "--vision") o.vision = 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-free-mib" || a == "--session-min-free-mib") { const std::string value = next(a.c_str()); int64_t number = 0; const auto result = std::from_chars(value.data(), value.data() + value.size(), number); @@ -1667,6 +1684,7 @@ int main(int argc, char** argv) { } if (a == "--conversation-cache-mib") o.conversation_cache_mib = number; else if (a == "--conversation-cache-min-free-mib") o.conversation_cache_min_free_mib = number; + else if (a == "--session-min-free-mib") o.session_min_free_mib = number; else o.conversation_cache_slots = (int) number; } else if (a == "--prompt-cache-tail") o.prompt_cache_tail = true; @@ -2594,9 +2612,10 @@ int main(int argc, char** argv) { strata::kernels::ple_set_native_postops(o.native_ple_postops); // before session_init: every graph captured from here on has the vector's kernels where it applies std::string cvec_summary = "0"; + uint64_t cvec_digest = 0; // a session file is bound to the loaded vector (0: none) if (!o.cvec_files.empty()) { std::string ce; - if (!load_control_vectors(o, g, cvec_summary, ce)) { + if (!load_control_vectors(o, g, cvec_summary, cvec_digest, ce)) { std::fprintf(stderr, "strata generate: control vector: %s\n", ce.c_str()); return 2; } @@ -6092,26 +6111,72 @@ 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; + // Disk sessions: what a session file is bound to. The model fingerprint samples every model input this + // engine loaded, by role (conversation_file.hpp), once; the config fingerprint covers the RESOLVED settings + // that change what the saved bytes mean - the rope (K is cached post-RoPE), the loaded control vector, the + // K/V format and the arithmetic switches. Sampling, seeds, draft tuning and the expert tier are not in it. + std::optional model_fp, config_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); + std::vector files; + auto add = [&](const std::string& role, const std::string& path, bool optional = false) { + if (path.empty()) return; + for (const auto& f : files) if (f.path == path) return; // one file, hashed once (first role) + files.push_back({role, path, optional}); + }; + for (size_t i = 0; i < o.native_shards.size(); ++i) add("native shard " + std::to_string(i), o.native_shards[i]); + for (size_t i = 0; i < o.native_dense_gguf.size(); ++i) add("native dense " + std::to_string(i), o.native_dense_gguf[i]); + for (size_t i = 0; i < o.native_head_shards.size(); ++i) add("native head " + std::to_string(i), o.native_head_shards[i]); + add("embedding", o.embd_gguf); + add("ple", o.ple_gguf); + // the pack's files the loader reads (weights.cpp, expert_layout.cpp), not whatever else is in the folder + if (!o.pack.empty()) { + for (const char* n : {"index.txt", "dense.bin"}) add(std::string("pack ") + n, o.pack + "/" + n); + for (const char* n : {"embd.bin", "experts.bin", "extra.bin", "native_experts.txt", "manifest.json"}) + add(std::string("pack ") + n, o.pack + "/" + n, true); + } + if (!o.mtp.empty()) { + for (const char* n : {"dense.txt", "dense.bin", "experts.bin"}) add(std::string("mtp ") + n, o.mtp + "/" + n); + add("mtp draft_vocab.bin", o.mtp + "/draft_vocab.bin", true); + } 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) + ","; + if (!config_fp) { + strata::core::SessionConfig c; + c.engine_version = STRATA_VERSION; +#if defined(STRATA_USE_HIP) + c.backend = "hip"; +#else + c.backend = "cuda"; +#endif + c.kv = o.kv; + c.max_context = o.max_context; + c.kv_resident = o.kv_resident; + c.mtp_window = o.mtp.empty() ? -1 : o.mtp_window; + const char* rot = std::getenv("STRATA_KV_ROT"); + c.kv_rot = rot != nullptr && rot[0] == '1'; + c.rope = {(int64_t) rope_cfg.type, rope_cfg.freq_base, rope_cfg.factor, rope_cfg.freq_scale(), + rope_cfg.orig_ctx, rope_cfg.ext_factor, rope_cfg.attn_factor, rope_cfg.beta_fast, + rope_cfg.beta_slow}; + c.cvec = cvec_digest; + c.switches = { + {"no_ple", o.no_ple}, {"native_bf16", o.native_bf16}, {"native_bf16_extra", o.native_bf16_extra}, + {"native_ple_key", o.native_ple_key}, {"native_moe_combine", o.native_moe_combine}, + {"native_gdn", o.native_gdn}, {"native_flash_attn_short", o.native_flash_attn_short}, + {"native_qsa_indexer", o.native_qsa_indexer}, {"native_qsa", o.native_qsa}, + {"native_rope", o.native_rope}, {"native_ple_postops", o.native_ple_postops}, + {"native_router", o.native_router}, {"cpu_oracle_q8_0", o.cpu_oracle_q8_0}, + {"gr_fp32_activations", o.gr_fp32_activations}, {"gr_native_mmvf", o.gr_native_mmvf}, + {"native_preset", !o.native_preset.empty()}, {"shared_late", o.shared_late}, + {"keep_canonical", o.keep_canonical}, {"no_fused_gr", o.no_fused_gr}, + {"no_fast_attn", o.no_fast_attn}, {"no_fused_gdn", o.no_fused_gdn}, + {"no_fast_select", o.no_fast_select}, {"vision", o.vision}}; + config_fp = strata::core::session_config_fingerprint(c); + } id.model = *model_fp; - id.config = strata::core::session_hash64(cfg.data(), cfg.size(), 0x434f4e464947ull); + id.config = *config_fp; return true; }; // Save only on a switch/rewind, not on each continuing request. No graph @@ -7504,8 +7569,11 @@ 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. + // Disk sessions: SAVE | RESTORE , between requests (the path runs to the end of the line, + // UTF-8). The file holds what a parked conversation holds (conversation_file.hpp). Answers: SAVED / + // RESTORED ; ERR for a refusal that left the session as it was; + // FATAL (and the engine exits) for a restore transfer that failed after the device state was + // touched. While a large file moves, SESSION lines show it is moving (and beat the watchdog). 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); @@ -7518,45 +7586,80 @@ int main(int argc, char** argv) { std::fflush(stdout); err.clear(); }; + auto moving = [&](uint64_t done, uint64_t total) { + strata::core::progress_at(save ? "writing a session file, MiB" : "reading a session file, MiB", + (int64_t) (done >> 20)); + strata::core::progress_beat(); + std::printf("SESSION %llu %llu\n", (unsigned long long) done, (unsigned long long) total); + std::fflush(stdout); + }; + strata::core::progress_at(save ? "saving a session" : "restoring a session"); if (path.empty()) { refuse("missing path"); continue; } if (!stages.empty() || multi_gpu) { refuse("session files do not support --layer-split"); continue; } + if (o.peer_device >= 1) { refuse("session files do not support --peer-device"); 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; } + try { + if (!session_identity(id, err)) { refuse(err); continue; } + } catch (const std::exception& e) { refuse(std::string("session identity: ") + e.what()); 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; + size_t bytes = 0, kept = 0; + double capture_ms = 0; try { + // 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); + kept = disk_checks.size(); + const strata::core::ConversationView view{live, live_imgs, disk_checks, cvec_cached}; + strata::core::SavedConversation meta; + std::vector sources; 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; } + capture_ms = ms(); + strata::core::SessionWriteOptions wo; + wo.min_free_bytes = (uint64_t) o.session_min_free_mib << 20; + wo.progress = moving; + if (!strata::core::session_file_write(path, meta, sources, id, bytes, err, wo)) { + refuse(err); + continue; + } + } catch (const std::bad_alloc&) { refuse("not enough RAM to save the session"); 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, + "in %.1f ms (state %.1f ms)\n", live.size(), kept, 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; } + // bounds this engine can ever hold, checked before anything is allocated, and the RAM the + // parsed image needs (about the file's size) on top of the parking floor, asked first + strata::core::SessionReadLimits limits; + limits.max_tokens = (uint64_t) o.max_context; + limits.max_checkpoints = (uint64_t) std::max(o.prompt_cache, 1); + limits.max_kv_layers = (uint64_t) g.n_layers + 1; + limits.progress = moving; + const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20; + limits.admit = [floor, &o](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; + why = "not enough RAM to read it (" + std::to_string(need >> 20) + " MiB plus a floor of " + + std::to_string((long long) o.conversation_cache_min_free_mib) + " MiB needed, " + + (avail ? std::to_string(*avail >> 20) + " MiB available)" : "RAM telemetry unavailable)"); + return false; + }; + if (!strata::core::session_file_read(path, id, image, bytes, err, limits)) { 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 + // the whole image against this engine, still without any device write if (!strata::core::conversation_snapshot_validate(image, ss, g, mtp.kv_state(), err)) { refuse(err); continue; @@ -7565,8 +7668,13 @@ int main(int argc, char** argv) { 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()); + // validated above: a failure here is a transfer failure, after device writes began - never + // decode from a partial state; the server starts the engine again + std::fprintf(stderr, "strata serve: session restore %s: transfer failed: %s\n", path.c_str(), + err.c_str()); + std::printf("FATAL restoring the session file failed after the device state was changed: %s\n", + err.c_str()); + std::fflush(stdout); return 1; } live = std::move(image.live.ids);