okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

albedosession files: save and restore a layer split (format v2, one payload per stage)fcc6fb808

main
46.6 KiB809 linesraw
1// CPU-only tests for the on-disk session format (include/strata/core/conversation_file.hpp).
2// Built with -DSTRATA_BUILD_CONVERSATION_TESTS=ON; no CUDA, no model.
3#include "strata/core/conversation_file.hpp"
4#include "strata/core/session_save_reclaim.hpp"
5
6#include <array>
7#include <cerrno>
8#include <chrono>
9#include <cmath>
10#include <cstdio>
11#include <cstdlib>
12#include <cstring>
13#include <filesystem>
14#include <fstream>
15#include <string>
16#include <new>
17#include <utility>
18#include <vector>
19#ifndef _WIN32
20#include <sys/resource.h>
21#include <sys/stat.h>
22#include <sys/types.h>
23#include <sys/wait.h>
24#include <unistd.h>
25#endif
26
27using namespace strata::core;
28namespace fs = std::filesystem;
29
30namespace {
31void set_env(const char* name, const char* value) {
32#ifdef _WIN32
33    _putenv_s(name, value ? value : "");
34#else
35    if (value) setenv(name, value, 1); else unsetenv(name);
36#endif
37}
38int checks = 0;
39void check(bool ok, const char* label) {
40    ++checks;
41    if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); }
42}
43
44ConversationBuffer pattern(size_t n, uint8_t seed) {
45    ConversationBuffer b;
46    b.resize(n);
47    b.visit(0, n, [&](uint8_t* p, size_t c, size_t at) {
48        for (size_t i = 0; i < c; ++i) p[i] = uint8_t((at + i) * 131u + seed);
49        return true;
50    });
51    return b;
52}
53
54std::vector<uint8_t> bytes_of(size_t n, uint8_t seed) {
55    std::vector<uint8_t> v(n);
56    for (size_t i = 0; i < n; ++i) v[i] = uint8_t(i * 7u + seed);
57    return v;
58}
59
60ConversationCheckpoint checkpoint(size_t tokens, uint8_t seed) {
61    ConversationCheckpoint c;
62    for (size_t i = 0; i < tokens; ++i) c.ids.push_back(int32_t(1000 + i));
63    c.imgs = {{3, 0x1234567890abcdefull ^ seed}};
64    c.gdn = bytes_of(4099, seed);
65    c.ple = bytes_of(77, seed + 1);
66    c.tails = bytes_of(301, seed + 2);
67    c.dead = bytes_of(64, seed + 3);
68    c.block_pos = bytes_of(8, seed + 4);
69    c.used = 42 + seed;
70    return c;
71}
72
73SavedConversation sample() {
74    SavedConversation s;
75    for (size_t i = 0; i < s.geometry.size(); ++i) s.geometry[i] = int64_t(100 + i);
76    s.layer_lo = 0; s.layer_hi = 48;
77    s.cvec = false;
78    s.live = checkpoint(1000, 1);
79    s.checkpoints.push_back(checkpoint(10, 2));
80    s.checkpoints.push_back(checkpoint(500, 3));
81    for (int layer = 0; layer < 3; ++layer) {
82        ConversationKv kv;
83        kv.format = 2 + layer; kv.cells = 1024; kv.heads = 2; kv.head_dim = 256;
84        kv.page_size = 64; kv.pooled_rows = layer == 2 ? 0 : 9; kv.idx_dim = 128;
85        // > 16 MiB so the buffer spans several segments
86        kv.k = pattern(layer == 0 ? (17u << 20) + 5 : 4096, uint8_t(layer));
87        kv.v = pattern(4096 + layer, uint8_t(layer + 10));
88        kv.k_scale = pattern(layer == 1 ? 0 : 512, uint8_t(layer + 20));
89        kv.v_scale = pattern(512, uint8_t(layer + 30));
90        kv.pooled = pattern(layer == 2 ? 0 : 9 * 128 * 4, uint8_t(layer + 40));
91        s.kv.push_back(std::move(kv));
92    }
93    return s;
94}
95
96// format v1 golden: the file the fixed sample() gives (size and session_hash64 of all bytes, seed 0)
97constexpr size_t kGoldenSize = 17878535;
98constexpr uint64_t kGoldenHash = 0x70f812b350360d09ull;
99
100bool same_checkpoint(const ConversationCheckpoint& a, const ConversationCheckpoint& b) {
101    return a.ids == b.ids && a.imgs == b.imgs && a.gdn == b.gdn && a.ple == b.ple && a.tails == b.tails &&
102           a.dead == b.dead && a.block_pos == b.block_pos && a.used == b.used && b.stage_parts.empty();
103}
104
105bool same(const SavedConversation& a, const SavedConversation& b) {
106    if (a.geometry != b.geometry || a.layer_lo != b.layer_lo || a.layer_hi != b.layer_hi || a.cvec != b.cvec ||
107        !same_checkpoint(a.live, b.live) || a.checkpoints.size() != b.checkpoints.size() || a.kv.size() != b.kv.size())
108        return false;
109    for (size_t i = 0; i < a.checkpoints.size(); ++i)
110        if (!same_checkpoint(a.checkpoints[i], b.checkpoints[i])) return false;
111    if (a.stage_images.size() != b.stage_images.size()) return false;
112    for (size_t i = 0; i < a.stage_images.size(); ++i)
113        if (!same(a.stage_images[i], b.stage_images[i])) return false;
114    for (size_t i = 0; i < a.kv.size(); ++i) {
115        const auto& x = a.kv[i]; const auto& y = b.kv[i];
116        if (x.format != y.format || x.cells != y.cells || x.heads != y.heads || x.head_dim != y.head_dim ||
117            x.page_size != y.page_size || x.pooled_rows != y.pooled_rows || x.idx_dim != y.idx_dim ||
118            !(x.k == y.k) || !(x.v == y.v) || !(x.k_scale == y.k_scale) || !(x.v_scale == y.v_scale) ||
119            !(x.pooled == y.pooled)) return false;
120    }
121    return true;
122}
123
124std::vector<char> slurp(const fs::path& p) {
125    std::ifstream f(p, std::ios::binary);
126    return std::vector<char>((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
127}
128void spit(const fs::path& p, const std::vector<char>& d) {
129    std::ofstream f(p, std::ios::binary | std::ios::trunc);
130    f.write(d.data(), (std::streamsize) d.size());
131}
132
133// no temporary file (any leftover of a write) in the directory
134bool no_temp(const fs::path& dir) {
135    for (const auto& e : fs::directory_iterator(dir)) {
136        const std::string n = e.path().filename().string();
137        if (n.size() > 4 && n.compare(n.size() - 4, 4, ".tmp") == 0 && n != "keep.bin.tmp") return false;
138    }
139    return true;
140}
141
142bool rejects(const fs::path& p, const SessionFileIdentity& id, const char* expect = nullptr,
143             const SessionReadLimits& limits = {}) {
144    SavedConversation out;
145    size_t bytes = 0;
146    std::string error;
147    const bool ok = session_file_read(p.string(), id, out, bytes, error, limits);
148    if (!ok && expect && error.find(expect) == std::string::npos) {
149        std::fprintf(stderr, "  unexpected error text: %s (wanted %s)\n", error.c_str(), expect);
150        return false;
151    }
152    return !ok && !error.empty();
153}
154} // namespace
155
156int main() {
157    const fs::path dir = fs::temp_directory_path() / ("strata-session-test-" + std::to_string(
158        std::chrono::steady_clock::now().time_since_epoch().count()));
159    fs::create_directories(dir);
160    const SessionFileIdentity id{0x1111222233334444ull, 0x5555666677778888ull};
161    const SavedConversation original = sample();
162    const fs::path good = dir / "good.bin";
163
164    // round trip
165    size_t written = 0;
166    std::string error;
167    check(session_file_write(good.string(), original, id, written, error), "write succeeds");
168    check(error.empty(), "write leaves no error");
169
170    // golden: format v1 is frozen. The fixed sample must give these exact bytes (little-endian header fields at
171    // fixed offsets, and a fixed hash of the whole file); a format change must bump the version and this test.
172    {
173        const std::vector<char> g = slurp(good);
174        auto u32 = [&](size_t o) { uint32_t v = 0; for (int i = 3; i >= 0; --i) v = v << 8 | uint8_t(g[o + i]); return v; };
175        auto u64 = [&](size_t o) { uint64_t v = 0; for (int i = 7; i >= 0; --i) v = v << 8 | uint8_t(g[o + i]); return v; };
176        check(g.size() >= 80 && std::memcmp(g.data(), "STRSESS\x01", 8) == 0, "golden: magic");
177        check(u32(8) == 1 && u32(12) == 64, "golden: version 1, header 64 bytes (little-endian)");
178        check(u64(16) == id.model && u64(24) == id.config, "golden: fingerprints at offsets 16 and 24");
179        check(u64(32) == g.size() - 64 - 16, "golden: payload length at offset 32");
180        check(u64(40) == 0 && u64(48) == 0, "golden: reserved fields are zero");
181        check(std::memcmp(g.data() + g.size() - 8, "STRSEND\x01", 8) == 0, "golden: end marker");
182        const uint64_t h = session_hash64(g.data(), g.size(), 0);
183        const char* golden = std::getenv("STRATA_SESSION_GOLDEN_PRINT");
184        if (golden) std::printf("golden size %zu hash %016llx\n", g.size(), (unsigned long long)h);
185        check(g.size() == kGoldenSize && h == kGoldenHash, "golden: the fixed sample's file bytes are unchanged");
186    }
187    check(written == fs::file_size(good), "write reports the file size");
188    check(no_temp(dir), "no temporary left behind");
189    {
190        SavedConversation back;
191        size_t read = 0;
192        check(session_file_read(good.string(), id, back, read, error), "read succeeds");
193        check(read == written, "read reports the file size");
194        check(same(original, back), "round trip is identical");
195    }
196    // writing twice produces the same bytes (deterministic format)
197    {
198        const fs::path again = dir / "again.bin";
199        check(session_file_write(again.string(), original, id, written, error), "second write");
200        check(slurp(again) == slurp(good), "format is deterministic");
201    }
202    // saving over an existing file replaces it (MoveFileExW on Windows, rename elsewhere)
203    {
204        const fs::path over = dir / "over.bin";
205        spit(over, std::vector<char>(100, 'o'));
206        check(session_file_write(over.string(), original, id, written, error), "write over an existing file");
207        check(slurp(over) == slurp(good), "existing file replaced by the session");
208        check(no_temp(dir), "no temporary left behind after replace");
209    }
210    // buffered I/O (the path taken where direct I/O is refused or unavailable) writes and reads the same bytes
211    {
212        const char* inherited = std::getenv("STRATA_SESSION_BUFFERED");
213        const std::string kept = inherited ? inherited : "";
214        set_env("STRATA_SESSION_BUFFERED", "1");
215        const fs::path p = dir / "buffered.bin";
216        check(session_file_write(p.string(), original, id, written, error), "buffered write");
217        check(slurp(p) == slurp(good), "buffered write equals the default write");
218        SavedConversation back;
219        size_t read = 0;
220        check(session_file_read(p.string(), id, back, read, error) && same(original, back), "buffered read");
221        set_env("STRATA_SESSION_BUFFERED", inherited ? kept.c_str() : nullptr);   // the caller's choice again
222    }
223
224    const std::vector<char> image = slurp(good);
225    // truncation at every structural boundary and in the middle
226    for (size_t cut : {size_t(0), size_t(7), size_t(63), size_t(64), size_t(65), size_t(200), image.size() / 2,
227                       image.size() - 17, image.size() - 16, image.size() - 8, image.size() - 1}) {
228        const fs::path p = dir / "cut.bin";
229        spit(p, std::vector<char>(image.begin(), image.begin() + (std::ptrdiff_t) cut));
230        check(rejects(p, id), "truncated file rejected");
231    }
232    // trailing garbage
233    {
234        auto d = image; d.push_back('x');
235        const fs::path p = dir / "tail.bin"; spit(p, d);
236        check(rejects(p, id, "size"), "file with trailing bytes rejected");
237    }
238    // flipped payload byte (inside the big K buffer), flipped header byte, flipped trailer
239    for (size_t at : {size_t(64 + 300), image.size() / 2, size_t(20), image.size() - 12, image.size() - 3}) {
240        auto d = image; d[at] ^= 0x40;
241        const fs::path p = dir / "flip.bin"; spit(p, d);
242        check(rejects(p, id), "corrupted byte rejected");
243    }
244    // other model or other configuration
245    check(rejects(good, {id.model ^ 1, id.config}, "model"), "different model fingerprint rejected");
246    check(rejects(good, {id.model, id.config ^ 1}, "config"), "different configuration rejected");
247    // wrong version: header field patched and header hash recomputed so only the version differs
248    {
249        auto d = image;
250        uint32_t v = 99; std::memcpy(d.data() + 8, &v, 4);
251        const uint64_t h = session_hash64(d.data(), 56, 0); std::memcpy(d.data() + 56, &h, 8);
252        const fs::path p = dir / "ver.bin"; spit(p, d);
253        check(rejects(p, id, "version"), "unknown version rejected");
254    }
255    // a corrupted element count with a recomputed payload hash must fail on bounds, not allocate
256    {
257        auto d = image;
258        // payload starts at 64: geometry 18*8, layer_lo, layer_hi, cvec = 21*8 bytes, then live.ids count
259        const size_t at = 64 + 21 * 8;
260        uint64_t huge = 0x0fffffffffffffffull; std::memcpy(d.data() + at, &huge, 8);
261        uint64_t payload = 0; std::memcpy(&payload, d.data() + 32, 8);
262        const uint64_t h = session_hash64(d.data() + 64, payload, 0);
263        std::memcpy(d.data() + 64 + payload, &h, 8);
264        const fs::path p = dir / "count.bin"; spit(p, d);
265        check(rejects(p, id, "count"), "oversized count rejected before allocation");
266    }
267    // missing file
268    check(rejects(dir / "absent.bin", id), "missing file rejected");
269    // a failed read leaves the destination untouched
270    {
271        SavedConversation keep = sample();
272        size_t b = 0;
273        check(!session_file_read((dir / "absent.bin").string(), id, keep, b, error), "missing read fails");
274        check(same(keep, original), "failed read does not modify the destination");
275    }
276    // stage parts left inside a checkpoint are refused (they belong in the stage images); no file appears
277    {
278        SavedConversation split = sample();
279        split.live.stage_parts.push_back(checkpoint(1, 9));
280        const fs::path p = dir / "split.bin";
281        check(!session_file_write(p.string(), split, id, written, error), "stage parts in a checkpoint refused");
282        check(!fs::exists(p) && no_temp(dir), "refused write leaves no file");
283    }
284    // a layer split's image (format v2): the first stage's payload, then one per later stage
285    {
286        SavedConversation split = sample();
287        SavedConversation later = sample();
288        later.layer_lo = 3; later.layer_hi = 48;
289        later.live = checkpoint(1000, 7);
290        later.kv.pop_back();   // a later stage without the drafter holds no draft K/V
291        split.layer_hi = 3;
292        split.stage_images.push_back(later);
293        const fs::path p = dir / "split2.bin";
294        error.clear();
295        check(session_file_write(p.string(), split, id, written, error), "layer-split image written");
296        const std::vector<char> d = slurp(p);
297        uint32_t version = 0; std::memcpy(&version, d.data() + 8, 4);
298        check(version == 2, "layer-split file is format v2");
299        SessionReadLimits two;
300        two.stage_limits.emplace_back();
301        SavedConversation back;
302        size_t read = 0;
303        error.clear();
304        check(session_file_read(p.string(), id, back, read, error, two), "layer-split file reads back");
305        check(same(split, back), "layer-split round trip is identical");
306        check(rejects(p, id, "layer split"), "a one-GPU runtime refuses a layer-split file");
307        SessionReadLimits three;
308        three.stage_limits.resize(2);
309        check(rejects(p, id, "GPUs", three), "another number of stages refused");
310        SessionReadLimits range = two;
311        range.stage_limits[0].layer_range = std::make_pair(int64_t(24), int64_t(48));
312        check(rejects(p, id, "layer range", range), "a later stage's layer range is checked");
313        check(rejects(good, id, "one GPU", two), "a layer-split runtime refuses a one-GPU file");
314    }
315    // a write into a missing directory fails cleanly
316    check(!session_file_write((dir / "nope" / "x.bin").string(), original, id, written, error),
317          "write into a missing directory fails");
318    // the hash is position-sensitive and seed-sensitive
319    {
320        const char a[] = "abcdefghijklmnopqrstuvwxyz0123456789", b[] = "bacdefghijklmnopqrstuvwxyz0123456789";
321        check(session_hash64(a, sizeof a, 0) != session_hash64(b, sizeof b, 0), "hash sees swapped bytes");
322        check(session_hash64(a, sizeof a, 0) != session_hash64(a, sizeof a, 1), "hash sees the seed");
323        SessionHasher h; h.update(a, 5); h.update(a + 5, sizeof a - 5);
324        check(h.digest() == session_hash64(a, sizeof a, 0), "streaming hash equals one-shot hash");
325    }
326    // model fingerprint: changes with content at the head of a file and with the file list
327    {
328        const fs::path m1 = dir / "m1.bin", m2 = dir / "m2.bin";
329        spit(m1, std::vector<char>(3u << 20, 'a'));
330        spit(m2, std::vector<char>(100, 'b'));
331        uint64_t f1 = 0, f2 = 0, f3 = 0, f4 = 0, f5 = 0, f6 = 0, f7 = 0, f8 = 0;
332        const std::vector<SessionModelFile> both = {{"a", m1.string()}, {"b", m2.string()}};
333        check(session_model_fingerprint(both, f1, error), "fingerprint ok");
334        const std::vector<SessionModelFile> subset = {{"a", m1.string()}};
335        const std::vector<SessionModelFile> roles = {{"b", m1.string()}, {"a", m2.string()}};
336        check(session_model_fingerprint(subset, f2, error), "fingerprint subset ok");
337        check(session_model_fingerprint(roles, f5, error), "fingerprint roles ok");
338        check(f1 != f5, "fingerprint follows the role each file plays");
339        // a moved folder: same roles, same bytes, other paths
340        const fs::path moved = dir / "moved";
341        fs::create_directories(moved);
342        fs::copy_file(m1, moved / "m1.bin"); fs::copy_file(m2, moved / "m2.bin");
343        const std::vector<SessionModelFile> moved_list = {{"a", (moved / "m1.bin").string()}, {"b", (moved / "m2.bin").string()}};
344        check(session_model_fingerprint(moved_list, f6, error) && f6 == f1, "fingerprint does not follow the folder");
345        // an optional input that is absent is recorded, not an error; a present one changes the fingerprint
346        const std::vector<SessionModelFile> absent = {{"a", m1.string()}, {"b", m2.string()}, {"c", (dir / "nothere").string(), true}};
347        const std::vector<SessionModelFile> present = {{"a", m1.string()}, {"b", m2.string()}, {"c", m2.string(), true}};
348        check(session_model_fingerprint(absent, f7, error), "absent optional input ok");
349        check(session_model_fingerprint(present, f8, error) &&
350              f7 != f8 && f7 != f1, "optional input presence enters the fingerprint");
351        auto d = slurp(m1); d[10] = 'z'; spit(m1, d);
352        check(session_model_fingerprint(both, f3, error), "fingerprint after edit ok");
353        check(f1 != f2 && f1 != f3, "fingerprint follows files and content");
354        check(!session_model_fingerprint({{"x", (dir / "absent").string()}}, f4, error), "fingerprint of a missing file fails");
355    }
356
357    // only the deepest checkpoint is worth a disk write: the next turn resumes from it
358    {
359        std::vector<ConversationCheckpoint> chain;
360        check(session_checkpoints_to_save(chain).empty(), "no checkpoints, none saved");
361        chain.push_back(checkpoint(10, 2));
362        chain.push_back(checkpoint(700, 3));
363        chain.push_back(checkpoint(500, 4));
364        const auto kept = session_checkpoints_to_save(chain);
365        check(kept.size() == 1 && same_checkpoint(kept[0], chain[1]), "deepest checkpoint kept, alone");
366    }
367    // K/V streamed from its owner (no host copy): the same bytes as writing the captured image
368    {
369        SavedConversation meta = original;
370        meta.kv.clear();
371        std::vector<SessionKvSource> sources;
372        for (const auto& k : original.kv) {
373            SessionKvSource s;
374            s.format = k.format; s.cells = k.cells; s.heads = k.heads; s.head_dim = k.head_dim;
375            s.page_size = k.page_size; s.pooled_rows = k.pooled_rows; s.idx_dim = k.idx_dim;
376            const std::array<const ConversationBuffer*, 5> parts = {&k.k, &k.v, &k.k_scale, &k.v_scale, &k.pooled};
377            for (size_t i = 0; i < 5; ++i) s.sizes[i] = parts[i]->size();
378            s.read = [parts](size_t part, size_t offset, void* dst, size_t n) {
379                return parts[part]->read(dst, offset, n);
380            };
381            sources.push_back(std::move(s));
382        }
383        const fs::path p = dir / "streamed.bin";
384        check(session_file_write(p.string(), meta, sources, id, written, error), "streamed write succeeds");
385        check(slurp(p) == image, "streamed write equals the captured-image write");
386        // a failing source leaves no file
387        auto broken = sources;
388        broken[1].read = [](size_t, size_t, void*, size_t) { return false; };
389        const fs::path q = dir / "broken.bin";
390        check(!session_file_write(q.string(), meta, broken, id, written, error), "failing source fails the write");
391        check(!fs::exists(q) && no_temp(dir), "failed streamed write leaves no file");
392        // K/V in the image and as sources at once is ambiguous: refused
393        check(!session_file_write((dir / "both.bin").string(), original, sources, id, written, error),
394              "image K/V plus sources refused");
395    }
396
397    // the configuration fingerprint: every field counts, doubles by their exact bits
398    {
399        SessionConfig c;
400        c.engine_version = "0.1.38"; c.backend = "cuda"; c.kv = "int8"; c.max_context = 65536; c.kv_resident = 0;
401        c.mtp_window = 4; c.rope.type = 0; c.rope.freq_base = 1e7; c.rope.factor = 1.0; c.rope.freq_scale = 1.0;
402        c.rope.orig_ctx = 262144; c.rope.attn_factor = 1.0; c.rope.beta_fast = 32; c.rope.beta_slow = 1;
403        c.switches = {{"STRATA_FAST_GDN", 0}};
404        const uint64_t base = session_config_fingerprint(c);
405        check(session_config_fingerprint(c) == base, "config fingerprint is deterministic");
406        auto differs = [&](auto edit) { SessionConfig d = c; edit(d); return session_config_fingerprint(d) != base; };
407        check(differs([](SessionConfig& d) { d.engine_version = "0.1.39"; }), "engine version enters the config");
408        check(differs([](SessionConfig& d) { d.backend = "hip"; }), "backend enters the config");
409        check(differs([](SessionConfig& d) { d.kv = "fp16"; }), "kv enters the config");
410        check(differs([](SessionConfig& d) { d.max_context = 65537; }), "max context enters the config");
411        check(differs([](SessionConfig& d) { d.kv_resident = 1; }), "kv residency enters the config");
412        check(differs([](SessionConfig& d) { d.mtp_window = 0; }), "mtp window enters the config");
413        check(differs([](SessionConfig& d) { d.kv_rot = true; }), "kv rotation enters the config");
414        check(differs([](SessionConfig& d) { d.rope.factor = std::nextafter(1.0, 2.0); }),
415              "a one-ulp rope change enters the config");
416        check(differs([](SessionConfig& d) { d.rope.type = 2; }), "rope type enters the config");
417        check(differs([](SessionConfig& d) { d.rope.beta_slow = 2; }), "rope beta enters the config");
418        check(differs([](SessionConfig& d) { d.cvec = 7; }), "control vectors enter the config");
419        check(differs([](SessionConfig& d) { d.switches[0].second = 1; }), "a switch value enters the config");
420        check(differs([](SessionConfig& d) { d.switches.push_back({"X", 0}); }), "the switch list enters the config");
421        // field boundaries: ("ab","c") and ("a","bc") hash differently
422        SessionIdentityBuilder x(1), y(1);
423        x.str("ab", "c"); y.str("a", "bc");
424        check(x.digest() != y.digest(), "identity fields are length-delimited");
425        SessionIdentityBuilder i(1), u(1);
426        i.i64("n", 5); u.u64("n", 5);
427        check(i.digest() != u.digest(), "identity fields are typed");
428    }
429    // bounds a read checks before it allocates, and the caller's admission
430    {
431        SessionReadLimits l;
432        l.max_tokens = 999;   // the live state holds 1000
433        check(rejects(good, id, "limit", l), "token count over the limit refused");
434        l = {}; l.max_checkpoints = 1;
435        check(rejects(good, id, "limit", l), "checkpoint count over the limit refused");
436        l = {}; l.max_kv_layers = 2;
437        check(rejects(good, id, "limit", l), "K/V layer count over the limit refused");
438        l = {}; l.max_file_bytes = image.size() - 1;
439        check(rejects(good, id, "limit", l), "file over the size limit refused");
440        l = {};
441        uint64_t asked = 0;
442        l.admit = [&](uint64_t n, std::string& why) { asked = n; why = "no room for it"; return false; };
443        check(rejects(good, id, "no room", l) && asked == session_read_peak_bytes(image.size()) &&
444              asked > image.size(), "admission sees the parse's peak (more than the file) and can refuse");
445        l = {};
446        bool admitted = false;
447        l.admit = [&](uint64_t, std::string&) { admitted = true; return true; };
448        check(rejects(good, {id.model ^ 1, id.config}, "model", l) && !admitted,
449              "admission is not asked for a foreign file");
450        SavedConversation back;
451        size_t n = 0;
452        check(session_file_read(good.string(), id, back, n, error, l) && admitted && same(back, original),
453              "admitted file reads");
454    }
455    // free-space reserve: an impossible reserve refuses the write and leaves the existing file untouched
456    {
457        const fs::path p = dir / "reserve.bin";
458        spit(p, std::vector<char>(10, 'r'));
459        SessionWriteOptions opt;
460        opt.min_free_bytes = UINT64_MAX / 2;
461        check(!session_file_write(p.string(), original, id, written, error, opt) &&
462              error.find("disk space") != std::string::npos, "write over the free-space reserve refused");
463        check(slurp(p) == std::vector<char>(10, 'r') && no_temp(dir), "refused write keeps the old file, no temporary");
464        opt.min_free_bytes = 1;
465        uint64_t calls = 0;
466        opt.progress = [&](uint64_t, uint64_t) { ++calls; };
467        check(session_file_write(p.string(), original, id, written, error, opt) && slurp(p) == image,
468              "write with a small reserve succeeds");
469    }
470    // a failed write over an existing session keeps it, and touches no other file (a planted "<name>.tmp", the old
471    // fixed temporary pattern included)
472    {
473        const fs::path p = dir / "keep.bin", planted = dir / "keep.bin.tmp";
474        check(session_file_write(p.string(), original, id, written, error), "keep: first write");
475        spit(planted, std::vector<char>(5, 'p'));
476        SavedConversation meta = original;
477        meta.kv.clear();
478        std::vector<SessionKvSource> broken(1);
479        broken[0].sizes = {100, 0, 0, 0, 0};
480        broken[0].read = [](size_t, size_t, void*, size_t) { return false; };
481        check(!session_file_write(p.string(), meta, broken, id, written, error), "keep: failing write fails");
482        check(slurp(p) == image, "keep: the previous session survives a failed write");
483        check(slurp(planted) == std::vector<char>(5, 'p') && no_temp(dir), "keep: no other file touched");
484    }
485    // R1: the input list carries every expert file the loader resolved, per (layer, role) - a GGUF that only
486    // native_experts.txt names changes the fingerprint when it changes; one file in two roles is two entries
487    {
488        const fs::path g1 = dir / "ext-a.gguf", g2 = dir / "ext-b.gguf";
489        spit(g1, std::vector<char>(4096, 'g'));
490        spit(g2, std::vector<char>(4096, 'h'));
491        SessionInputs in;
492        in.native_shards = {g1.string()};
493        in.experts = {{"expert blk.0.ffn_gate", g1.string()}, {"expert blk.0.ffn_up", g2.string()},
494                      {"expert blk.0.ffn_down", g2.string()}};
495        const auto list = session_model_inputs(in);
496        check(list.size() == 4, "inputs: shard plus three expert roles, none merged");
497        uint64_t a = 0, b = 0, c = 0;
498        check(session_model_fingerprint(list, a, error), "inputs: fingerprint");
499        auto d = slurp(g2); d[0] = 'X'; spit(g2, d);   // the expert-only file changes; the CLI shard does not
500        check(session_model_fingerprint(list, b, error) && a != b, "inputs: an expert-only GGUF enters the fingerprint");
501        SessionInputs swapped = in;
502        std::swap(swapped.experts[0].second, swapped.experts[1].second);
503        check(session_model_fingerprint(session_model_inputs(swapped), c, error) && c != b,
504              "inputs: the role each expert file plays enters the fingerprint");
505    }
506    // R2: runtime limits bound every array before it is allocated, and the file size follows from them
507    {
508        auto exact = [&] {
509            SessionReadLimits l;
510            l.max_tokens = 1000; l.max_checkpoints = 2; l.max_kv_layers = 3;
511            l.geometry = original.geometry;
512            l.layer_range = std::make_pair(original.layer_lo, original.layer_hi);
513            l.max_state_bytes = {4099, 77, 301, 64, 8};
514            for (const auto& k : original.kv)
515                l.max_kv_bytes.push_back({k.k.size(), k.v.size(), k.k_scale.size(), k.v_scale.size(), k.pooled.size()});
516            return l;
517        };
518        SavedConversation back;
519        size_t n = 0;
520        check(session_file_read(good.string(), id, back, n, error, exact()) && same(back, original),
521              "limits: a file within the exact runtime limits reads");
522        check(session_read_max_file_bytes(exact()) >= image.size() &&
523              session_read_max_file_bytes(exact()) < UINT64_MAX, "limits: the runtime limits bound the file size");
524        check(session_read_max_file_bytes(SessionReadLimits{}) == UINT64_MAX, "limits: open limits leave it open");
525        auto l = exact(); l.max_state_bytes[0] = 4098;
526        check(rejects(good, id, "limit", l), "limits: a GDN state over the runtime size refused");
527        l = exact(); l.max_state_bytes[4] = 7;
528        check(rejects(good, id, "limit", l), "limits: block_pos over the runtime size refused");
529        l = exact(); l.max_kv_bytes[0][0] = original.kv[0].k.size() - 1;
530        check(rejects(good, id, "limit", l), "limits: a K buffer over the runtime size refused");
531        l = exact(); l.max_kv_bytes[2][1] = original.kv[2].v.size() - 1;
532        check(rejects(good, id, "limit", l), "limits: the draft's V over the runtime size refused");
533        l = exact(); (*l.geometry)[3] ^= 1;
534        check(rejects(good, id, "geometry", l), "limits: another geometry refused before the state is read");
535        l = exact(); l.layer_range = std::make_pair(int64_t(0), int64_t(24));
536        check(rejects(good, id, "layer", l), "limits: another layer range refused");
537        // a huge count in a state array with a recomputed hash: refused by the bound, nothing allocated
538        auto d = image;
539        // live: ids count (8) + 1000*4, imgs count (8) + 1*16, then the gdn byte count
540        const size_t at = 64 + 21 * 8 + 8 + 1000 * 4 + 8 + 16;
541        uint64_t was = 0; std::memcpy(&was, d.data() + at, 8);
542        check(was == 4099, "limits: test offset finds the GDN count");
543        uint64_t huge = 3ull << 30; std::memcpy(d.data() + at, &huge, 8);
544        uint64_t payload = 0; std::memcpy(&payload, d.data() + 32, 8);
545        const uint64_t h = session_hash64(d.data() + 64, payload, 0);
546        std::memcpy(d.data() + 64 + payload, &h, 8);
547        const fs::path p = dir / "bigstate.bin"; spit(p, d);
548        check(rejects(p, id, nullptr, exact()), "limits: an oversized state count refused before allocation");
549        // status kinds of a read
550        SessionStatus st;
551        check(!session_file_read(p.string(), id, back, n, error, exact(), &st) && st.error == SessionError::invalid,
552              "status: a bad file is 'invalid'");
553        l = exact();
554        l.admit = [](uint64_t, std::string& why) { why = "no RAM"; return false; };
555        check(!session_file_read(good.string(), id, back, n, error, l, &st) && st.error == SessionError::memory,
556              "status: the RAM preflight is 'memory'");
557    }
558    // R3/R5: injected failures at each write step - kind, publication and the old file
559    {
560        const fs::path p = dir / "fault.bin";
561        const std::vector<char> old(10, 'q');
562        struct Case { const char* step; int err; SessionError kind; bool published; };
563        for (const Case c : {Case{"write", ENOSPC, SessionError::storage, false},
564#ifdef EDQUOT
565                             Case{"write", EDQUOT, SessionError::storage, false},
566#endif
567                             Case{"write", EIO, SessionError::io, false},
568                             Case{"file_flush", EIO, SessionError::io, false},
569                             Case{"rename", EACCES, SessionError::io, false},
570                             Case{"dir_flush", EIO, SessionError::io, true}}) {
571            spit(p, old);
572            SessionWriteOptions opt;
573            const std::string want = c.step;
574            const int code = c.err;
575            opt.fault = [want, code](const char* step) { return want == step ? code : 0; };
576            SessionStatus st;
577            const bool ok = session_file_write(p.string(), original, id, written, error, opt, &st);
578            check(!ok && st.error == c.kind, "fault: the failure has its kind");
579            check(st.published == c.published, "fault: publication reported exactly");
580            if (c.published) {
581                check(slurp(p) == image && error.find("replaced") != std::string::npos,
582                      "fault: after a published failure the new file is there and the error says so");
583            } else {
584                check(slurp(p) == old, "fault: a failure before the rename keeps the old file");
585            }
586            check(no_temp(dir), "fault: no temporary left behind");
587        }
588#ifndef _WIN32
589        // a filesystem that cannot flush a folder: saved, and said
590        spit(p, old);
591        SessionWriteOptions opt;
592        opt.fault = [](const char* step) { return std::string(step) == "dir_flush" ? EINVAL : 0; };
593        SessionStatus st;
594        check(session_file_write(p.string(), original, id, written, error, opt, &st) && st.dir_flush_unsupported &&
595              slurp(p) == image, "fault: EINVAL on the folder flush is not a failure, and is reported");
596#endif
597        // the free-space preflight is 'storage'
598        SessionWriteOptions big;
599        big.min_free_bytes = UINT64_MAX / 2;
600        SessionStatus st2;
601        check(!session_file_write(p.string(), original, id, written, error, big, &st2) &&
602              st2.error == SessionError::storage, "status: the free-space preflight is 'storage'");
603        check(std::string(session_error_name(SessionError::storage)) == "storage" &&
604              std::string(session_error_name(SessionError::memory)) == "memory" &&
605              std::string(session_error_name(SessionError::invalid)) == "invalid" &&
606              std::string(session_error_name(SessionError::io)) == "io", "status: protocol names");
607    }
608    // B: progress after every block, the last partial one included (a file below 16 MiB reports too), and the
609    // blocking steps announced before they start
610    {
611        const fs::path p = dir / "progress.bin";
612        std::vector<std::pair<uint64_t, uint64_t>> seen;
613        std::vector<std::string> phases;
614        SessionWriteOptions opt;
615        opt.progress = [&](uint64_t d, uint64_t t) { seen.push_back({d, t}); };
616        opt.phase = [&](const char* ph, uint64_t b) { phases.push_back(std::string(ph) + ":" + std::to_string(b)); };
617        // a file below one block (the sample without its K/V layers) reports too: at the start and its one block
618        SavedConversation small = original;
619        small.kv.clear();
620        check(session_file_write(p.string(), small, id, written, error, opt), "progress: small write");
621        check(written > 0 && written < (16u << 20), "progress: the small file is below one block");
622        check(seen.size() == 2 && seen[0] == std::make_pair(uint64_t(0), uint64_t(written)) &&
623              seen[1] == std::make_pair(uint64_t(written), uint64_t(written)), "progress: start and the partial block");
624        check(phases.size() == 2 && phases[0] == "flush:" + std::to_string(written) &&
625              phases[1] == "publish:" + std::to_string(written), "progress: flush and publish announced, in order");
626        opt.durable = false;
627        phases.clear();
628        check(session_file_write(p.string(), small, id, written, error, opt) && phases.size() == 1 &&
629              phases[0].rfind("publish:", 0) == 0, "progress: no flush step announced without a flush");
630        // a read reports every block, the first (the header's) included
631        seen.clear();
632        SessionReadLimits l;
633        l.progress = [&](uint64_t d, uint64_t t) { seen.push_back({d, t}); };
634        SavedConversation back;
635        size_t n = 0;
636        check(session_file_read(p.string(), id, back, n, error, l) && seen.size() == 1 &&
637              seen[0] == std::make_pair(uint64_t(n), uint64_t(n)), "progress: a small read reports its one block");
638        // the fixed sample: one full block and a partial one, both reported on write and on read
639        seen.clear();
640        opt.durable = true;
641        check(session_file_write(p.string(), original, id, written, error, opt) && written > (16u << 20) &&
642              written < (32u << 20), "progress: sample write");
643        check(seen.size() == 3 && seen[1].first == (16u << 20) && seen[2].first == written,
644              "progress: the sample's full block and its partial last block");
645        seen.clear();
646        check(session_file_read(p.string(), id, back, n, error, l) && seen.size() == 2 &&
647              seen[0].first == (16u << 20) && seen[1].first == n, "progress: the sample's read reports both blocks");
648        // a multi-block streamed write: 16 MiB blocks then the partial one, never more than a block apart
649        SavedConversation meta = original;
650        meta.kv.clear();
651        std::vector<SessionKvSource> big(1);
652        big[0].sizes = {(40u << 20) + 123, 0, 0, 0, 0};
653        big[0].read = [](size_t, size_t, void* d, size_t c) { std::memset(d, 0x5a, c); return true; };
654        seen.clear();
655        opt.durable = true;
656        check(session_file_write(p.string(), meta, big, id, written, error, opt), "progress: 40 MiB write");
657        bool steps = seen.size() == 4 && seen.front().first == 0 && seen.back().first == written;
658        for (size_t i = 1; i < seen.size(); ++i)
659            steps = steps && seen[i].first > seen[i - 1].first && seen[i].first - seen[i - 1].first <= (16u << 20);
660        check(steps, "progress: every block reported, at most 16 MiB apart, the last one at the end");
661        // the allowance of a blocking step: bounded, growing with its size
662        check(session_phase_limit_s(0) == 60 && session_phase_limit_s(1198691396) == 60 + (1198691396 >> 22) &&
663              session_phase_limit_s(UINT64_MAX) == 3600, "phase limit: 60 s + 1 s per 4 MiB, at most an hour");
664    }
665    // A: the SAVE's RAM preflight comes BEFORE the checkpoint is copied
666    {
667        std::vector<ConversationCheckpoint> chain;
668        chain.push_back(checkpoint(10, 2));
669        chain.push_back(checkpoint(700, 3));
670        chain.back().gdn.assign(8u << 20, 0x11);   // the deepest: an 8 MiB running state
671        const auto before = chain;
672        SessionSaveLive live;
673        live.state_bytes = 5000; live.tokens = 1000; live.images = 1; live.kv_layers = 13;
674        check(session_deepest_checkpoint(chain) == &chain[1], "save: deepest chosen by reference");
675        {   // pin=N: the pinned checkpoint is the one kept, even when a deeper periodic one exists
676            auto pinned_chain = chain;
677            pinned_chain[0].pinned = true;
678            check(session_deepest_checkpoint(pinned_chain) == &pinned_chain[0], "save: a pinned shared prefix beats a deeper checkpoint");
679            check(session_deepest_checkpoint(chain) == &chain[1], "save: no pin, the deepest as before");
680        }
681        const uint64_t need = session_save_peak_bytes(&chain[1], live);
682        check(need >= 2 * (uint64_t) chain[1].bytes() + 5000 + 4000 + (16u << 20) &&
683              need <= 2 * (uint64_t) chain[1].bytes() + 5000 + 4000 + (18u << 20),
684              "save: the peak counts two checkpoint copies, the live state, tokens and the buffer");
685        SessionSaveLive huge = live;
686        huge.state_bytes = UINT64_MAX;
687        check(session_save_peak_bytes(&chain[1], huge) == UINT64_MAX, "save: the peak saturates");
688        std::vector<ConversationCheckpoint> out(1);
689        std::string why;
690        uint64_t asked = 0;
691        bool empty_when_asked = false;
692        const auto refuse = [&](uint64_t n, std::string& w) { asked = n; empty_when_asked = out.empty(); w = "low RAM"; return false; };
693        check(!session_save_checkpoints(chain, live, refuse, out, why) && why == "low RAM" && asked == need,
694              "save: the preflight is asked for the peak and can refuse");
695        check(empty_when_asked && out.empty(), "save: refused before any copy (nothing copied)");
696        bool same_chain = chain.size() == before.size();
697        for (size_t i = 0; same_chain && i < chain.size(); ++i) same_chain = same_checkpoint(chain[i], before[i]);
698        check(same_chain, "save: a refusal leaves the live checkpoints untouched");
699        const auto agree = [&](uint64_t, std::string&) { return true; };
700        check(session_save_checkpoints(chain, live, agree, out, why) && out.size() == 1 &&
701              same_checkpoint(out[0], chain[1]), "save: admitted, the deepest checkpoint is copied");
702        check(session_save_checkpoints({}, live, agree, out, why) && out.empty(), "save: no checkpoints, none copied");
703#if defined(__linux__) && !defined(__SANITIZE_ADDRESS__) && !defined(STRATA_NO_RLIMIT_TEST)
704        // under a real address-space limit that cannot hold one more copy: the refusal comes first, no bad_alloc;
705        // and the same limit with an admitting preflight does fail at the copy (the test can see the difference)
706        std::vector<ConversationCheckpoint> fat(1);
707        fat[0].ids = {1, 2, 3};
708        fat[0].gdn.assign(256u << 20, 0x22);
709        const fs::path old_file = dir / "old-session.bin";
710        spit(old_file, std::vector<char>(9, 'o'));
711        std::fflush(nullptr);
712        const pid_t pid = ::fork();
713        if (pid == 0) {
714            long pages = 0, rss = 0;
715            if (FILE* f = std::fopen("/proc/self/statm", "r")) { if (std::fscanf(f, "%ld %ld", &pages, &rss) != 2) pages = 0; std::fclose(f); }
716            struct rlimit rl {};
717            rl.rlim_cur = rl.rlim_max = (rlim_t) pages * (rlim_t) ::sysconf(_SC_PAGESIZE) + (64u << 20);
718            if (pages <= 0 || ::setrlimit(RLIMIT_AS, &rl) != 0) ::_exit(10);
719            std::vector<ConversationCheckpoint> o2;
720            std::string w;
721            const auto low = [](uint64_t n, std::string& m) { m = "need " + std::to_string(n); return false; };
722            bool refused = false;
723            try { refused = !session_save_checkpoints(fat, live, low, o2, w) && o2.empty(); } catch (...) { ::_exit(11); }
724            if (!refused) ::_exit(12);
725            try { session_save_checkpoints(fat, live, agree, o2, w); } catch (const std::bad_alloc&) { ::_exit(0); }
726            ::_exit(13);   // the copy fitted: the limit did not bite, the test proves nothing
727        }
728        int status = 0;
729        check(pid > 0 && ::waitpid(pid, &status, 0) == pid, "save: low-memory child ran");
730        check(WIFEXITED(status) && WEXITSTATUS(status) == 0,
731              "save: under a low address-space limit the preflight refuses before the copy (an admitted copy fails)");
732        check(fat[0].gdn.size() == (256u << 20) && fat[0].gdn[12345] == 0x22 &&
733              slurp(old_file) == std::vector<char>(9, 'o'), "save: live state and the old file intact");
734#endif
735    }
736    // Opt-in pressure reclamation does not change the selected file bytes, even with pin=N.
737    for (bool pin : {false, true}) {
738        auto source = sample();
739        source.checkpoints[0].pinned = pin;
740        const auto live_before = source.live;
741        auto expected = sample();
742        expected.checkpoints = session_checkpoints_to_save(source.checkpoints);
743        const fs::path before_path = dir / "reclaim-before.bin", after_path = dir / "reclaim-after.bin";
744        check(session_file_write(before_path.string(), expected, id, written, error), "reclaim: baseline file written");
745        ConversationCache parked(1u << 20, 4);
746        SessionSaveLive sl; sl.state_bytes = source.live.bytes(); sl.tokens = source.live.ids.size();
747        const auto freed = session_save_reclaim(source.checkpoints, parked, sl, 0,
748                                                [] { return std::optional<uint64_t>(0); });
749        check(freed.checkpoints == 1, "reclaim: a non-selected checkpoint released");
750        check(same_checkpoint(source.live, live_before), "reclaim: live state remains intact");
751        check(session_file_write(after_path.string(), source, id, written, error), "reclaim: file written after pressure");
752        check(slurp(before_path) == slurp(after_path), "reclaim: file byte-identical to original selection");
753        const auto old = slurp(after_path);
754        SessionWriteOptions opt;
755        opt.fault = [](const char* step) { return std::strcmp(step, "write") == 0 ? ENOSPC : 0; };
756        SessionStatus status;
757        check(!session_file_write(after_path.string(), source, id, written, error, opt, &status) &&
758              status.error == SessionError::storage && !status.published, "reclaim: later write failure reported");
759        check(slurp(after_path) == old && same_checkpoint(source.live, live_before) && no_temp(dir),
760              "reclaim: later failure preserves old file and live state, no temporary left");
761    }
762    // R6: the folder the free-space query is asked about
763    {
764        check(session_free_space_dir("\\\\server\\share\\sessions\\chat.bin", true) == "\\\\server\\share\\sessions\\",
765              "free space: UNC subfolder keeps its trailing backslash");
766        check(session_free_space_dir("\\\\server\\share\\chat.bin", true) == "\\\\server\\share\\",
767              "free space: UNC share root keeps its trailing backslash");
768        check(session_free_space_dir("//server/share/s/chat.bin", true) == "\\\\server\\share\\s\\",
769              "free space: forward slashes become backslashes");
770        check(session_free_space_dir("C:\\chat.bin", true) == "C:\\", "free space: drive root");
771        check(session_free_space_dir("C:chat.bin", true) == "C:\\", "free space: drive-relative name");
772        check(session_free_space_dir("chat.bin", true).empty(), "free space: bare name is the current folder");
773        check(session_free_space_dir("/a/b/chat.bin", false) == "/a/b", "free space: POSIX folder");
774        check(session_free_space_dir("/chat.bin", false) == "/", "free space: POSIX root");
775        check(session_free_space_dir("chat.bin", false) == ".", "free space: POSIX bare name");
776    }
777#ifndef _WIN32
778    // what restore will not open: a symbolic link, a hard-linked file, a FIFO, a directory
779    {
780        const fs::path link = dir / "link.bin";
781        fs::create_symlink(good, link);
782        check(rejects(link, id, "symbolic link"), "a symbolic link is not followed");
783        const fs::path hard = dir / "hard.bin";
784        fs::create_hard_link(dir / "again.bin", hard);
785        check(rejects(hard, id, "hard link"), "a hard-linked file is refused");
786        fs::remove(hard);
787        check(!rejects(dir / "again.bin", id), "the same file with one name again reads");
788        const fs::path fifo = dir / "fifo.bin";
789        check(::mkfifo(fifo.c_str(), 0600) == 0, "mkfifo");
790        check(rejects(fifo, id, "regular"), "a FIFO is refused without blocking");
791        check(rejects(dir / "moved", id, "regular"), "a directory is refused");
792    }
793    // saving over a symbolic link replaces the link, never writes through it; the new file is the owner's only
794    {
795        const fs::path target = dir / "target.bin", link = dir / "out-link.bin";
796        spit(target, std::vector<char>(7, 't'));
797        fs::create_symlink(target, link);
798        check(session_file_write(link.string(), original, id, written, error), "write at a link name");
799        check(!fs::is_symlink(link) && slurp(link) == image, "the link was replaced by the file");
800        check(slurp(target) == std::vector<char>(7, 't'), "the link's target is untouched");
801        struct stat st {};
802        check(::stat(link.c_str(), &st) == 0 && (st.st_mode & 0777) == 0600, "the session file is mode 0600");
803    }
804#endif
805
806    fs::remove_all(dir);
807    std::printf("conversation_file_test: %d checks passed\n", checks);
808    return 0;
809}