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
58.2 KiB1311 linesraw
1#include "strata/core/conversation_file.hpp"
2
3#include <algorithm>
4#include <bit>
5#include <cerrno>
6#include <chrono>
7#include <climits>
8#include <cstdio>
9#include <cstdlib>
10#include <cstring>
11#include <new>
12#include <unordered_map>
13#include <optional>
14#include <filesystem>
15#include <limits>
16#include <memory>
17#include <random>
18#include <string>
19#include <system_error>
20#ifdef _WIN32
21#ifndef WIN32_LEAN_AND_MEAN
22#define WIN32_LEAN_AND_MEAN
23#endif
24#ifndef NOMINMAX
25#define NOMINMAX
26#endif
27#include <windows.h>
28#include <malloc.h>
29#include <process.h>
30#else
31#include <fcntl.h>
32#include <sys/stat.h>
33#include <sys/statvfs.h>
34#include <sys/types.h>
35#include <unistd.h>
36#endif
37
38// Format v1 stores integers and floats as this machine holds them in memory; it is defined as little-endian with
39// IEEE-754 floats, so a build where that is not the memory layout is refused rather than writing another format.
40static_assert(std::endian::native == std::endian::little, "session files (format v1) are little-endian only");
41static_assert(std::numeric_limits<float>::is_iec559 && std::numeric_limits<double>::is_iec559,
42              "session files (format v1) need IEEE-754 floats");
43
44namespace strata::core {
45namespace {
46constexpr char kMagic[8] = {'S', 'T', 'R', 'S', 'E', 'S', 'S', '\x01'};
47constexpr char kEnd[8] = {'S', 'T', 'R', 'S', 'E', 'N', 'D', '\x01'};
48constexpr uint32_t kVersion = 1;
49// v2: a layer split's file - the v1 payload of the first stage, then the count of later stages and one v1 payload
50// for each (its own geometry, layer range, running state and K/V).  A single-GPU file stays v1.
51constexpr uint32_t kVersionStages = 2;
52constexpr size_t kHeader = 64, kTrailer = 16;
53
54// Progress for a transfer: one report after every block that was handed to (or read from) the OS, whatever its size
55// - the last, partial block included - so a small file reports too, and each report follows real movement.
56class Ticker {
57public:
58    explicit Ticker(const SessionProgress& fn) : fn_(fn) {}
59    void operator()(uint64_t done, uint64_t total) { if (fn_) fn_(done, total); }
60private:
61    SessionProgress fn_;
62};
63
64SessionError errno_kind(int e) {
65    switch (e) {
66        case ENOSPC:
67#ifdef EDQUOT
68        case EDQUOT:
69#endif
70        case EFBIG: return SessionError::storage;
71        case ENOMEM: return SessionError::memory;
72        default: return SessionError::io;
73    }
74}
75
76constexpr uint64_t P1 = 0x9E3779B185EBCA87ull, P2 = 0xC2B2AE3D27D4EB4Full, P3 = 0x165667B19E3779F9ull,
77                   P4 = 0x85EBCA77C2B2AE63ull, P5 = 0x27D4EB2F165667C5ull;
78uint64_t rotl(uint64_t x, int r) { return (x << r) | (x >> (64 - r)); }
79uint64_t round1(uint64_t acc, uint64_t w) { return rotl(acc + w * P2, 31) * P1; }
80uint64_t load64(const uint8_t* p) { uint64_t v; std::memcpy(&v, p, 8); return v; }
81
82// ---- file I/O in aligned 16 MiB blocks.  Linux: O_DIRECT when the filesystem takes it (no page cache, so a
83// 1.2 GB session neither evicts other files nor is charged to the engine's memory cgroup), buffered I/O otherwise
84// (tmpfs, a filesystem that refuses an aligned direct transfer, or STRATA_SESSION_BUFFERED=1).  Windows and other
85// systems: ordinary buffered I/O, same blocks.
86constexpr size_t kAlign = 4096, kBlock = 16u << 20;
87#ifdef _WIN32
88struct AlignedFree { void operator()(uint8_t* p) const { _aligned_free(p); } };
89using Aligned = std::unique_ptr<uint8_t, AlignedFree>;
90Aligned aligned_block() { return Aligned(static_cast<uint8_t*>(_aligned_malloc(kBlock, kAlign))); }
91#else
92struct AlignedFree { void operator()(uint8_t* p) const { std::free(p); } };
93using Aligned = std::unique_ptr<uint8_t, AlignedFree>;
94Aligned aligned_block() { return Aligned(static_cast<uint8_t*>(std::aligned_alloc(kAlign, kBlock))); }
95#endif
96
97uint64_t random64() {
98    std::random_device rd;
99    uint64_t r = (uint64_t(rd()) << 32) ^ rd();
100    r ^= (uint64_t) std::chrono::steady_clock::now().time_since_epoch().count() * P1;
101#ifdef _WIN32
102    r ^= (uint64_t) _getpid() * P2;
103#else
104    r ^= (uint64_t) ::getpid() * P2;
105#endif
106    return r;
107}
108
109// The temporary name beside the destination: hidden (a leading dot, which the server never accepts as a session
110// name), unique, and short enough for any filesystem whatever the destination's length.
111std::string temp_name(const std::string& leaf) {
112    size_t keep = std::min<size_t>(leaf.size(), 64);
113    while (keep > 0 && keep < leaf.size() && (uint8_t(leaf[keep]) & 0xC0) == 0x80) --keep;   // whole UTF-8 chars
114    char hex[17];
115    std::snprintf(hex, sizeof hex, "%016llx", (unsigned long long) random64());
116    return "." + leaf.substr(0, keep) + "." + hex + ".tmp";
117}
118
119// a test's injected failure at `step`: its errno value (0 = none)
120int injected(const std::function<int(const char*)>* fault, const char* step) {
121    return fault && *fault ? (*fault)(step) : 0;
122}
123
124bool split_path(const std::string& path, std::string& dir, std::string& leaf, std::string& error) {
125    const size_t cut = path.find_last_of(
126#ifdef _WIN32
127        "/\\"
128#else
129        "/"
130#endif
131    );
132    dir = cut == std::string::npos ? std::string() : path.substr(0, cut == 0 ? 1 : cut);
133    leaf = cut == std::string::npos ? path : path.substr(cut + 1);
134    if (leaf.empty() || leaf == "." || leaf == "..") { error = "session file: " + path + " names no file"; return false; }
135    return true;
136}
137
138#ifdef _WIN32
139// paths reach the engine as UTF-8 (the server writes its commands as UTF-8); invalid UTF-8 is refused, not replaced
140bool wide(const std::string& s, std::wstring& w) {
141    w.clear();
142    if (s.empty()) return true;
143    if (s.size() > (size_t) INT_MAX) return false;
144    const int n = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), (int) s.size(), nullptr, 0);
145    if (n <= 0) return false;
146    w.assign((size_t) n, L'\0');
147    return MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), (int) s.size(), w.data(), n) == n;
148}
149
150SessionError win_kind(DWORD code) {
151    switch (code) {
152        case ERROR_DISK_FULL: case ERROR_HANDLE_DISK_FULL: case ERROR_FILE_TOO_LARGE: return SessionError::storage;
153        case ERROR_NOT_ENOUGH_MEMORY: case ERROR_OUTOFMEMORY: return SessionError::memory;
154        default: return SessionError::io;
155    }
156}
157
158std::string last_error(DWORD code = GetLastError()) {
159    char msg[256] = {};
160    const DWORD n = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, code, 0, msg,
161                                   sizeof msg, nullptr);
162    std::string s(msg, n);
163    while (!s.empty() && (s.back() == '\n' || s.back() == '\r' || s.back() == ' ' || s.back() == '.')) s.pop_back();
164    return s.empty() ? "error " + std::to_string(code) : s;
165}
166
167class RawFile {
168public:
169    ~RawFile() { close(); }
170    // a new file that did not exist (CREATE_NEW: never an existing file or link)
171    bool create_new(const std::wstring& path) {
172        h_ = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW,
173                         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
174        if (h_ == INVALID_HANDLE_VALUE) { { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); } return false; }
175        return true;
176    }
177    // a session to restore: the name itself is opened, never what a link or reparse point there points to; it must be
178    // an ordinary disk file with one name
179    bool open_session(const std::string& path, uint64_t& size) {
180        std::wstring w;
181        if (!wide(path, w)) { refused_ = true; error_ = "the path is not valid UTF-8"; return false; }
182        h_ = CreateFileW(w.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
183                         FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
184        if (h_ == INVALID_HANDLE_VALUE) { { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); } return false; }
185        BY_HANDLE_FILE_INFORMATION info{};
186        if (!GetFileInformationByHandle(h_, &info)) { { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); } return false; }
187        if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { refused_ = true; error_ = "a link or reparse point, not a file"; return false; }
188        if ((info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || GetFileType(h_) != FILE_TYPE_DISK) {
189            refused_ = true;
190            error_ = "not a regular file";
191            return false;
192        }
193        if (info.nNumberOfLinks != 1) { refused_ = true; error_ = "the file has more than one name (hard link)"; return false; }
194        size = (uint64_t(info.nFileSizeHigh) << 32) | info.nFileSizeLow;
195        return true;
196    }
197    // a model input: links followed (model folders are often linked)
198    bool open_model(const std::string& path, uint64_t& size) {
199        std::wstring w;
200        if (!wide(path, w)) { refused_ = true; error_ = "the path is not valid UTF-8"; return false; }
201        h_ = CreateFileW(w.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
202                         nullptr);
203        if (h_ == INVALID_HANDLE_VALUE) {
204            const DWORD code = GetLastError();
205            missing_ = code == ERROR_FILE_NOT_FOUND || code == ERROR_PATH_NOT_FOUND;
206            kind_ = win_kind(code); error_ = last_error(code);
207            return false;
208        }
209        LARGE_INTEGER s{};
210        if (!GetFileSizeEx(h_, &s)) { { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); } return false; }
211        size = (uint64_t) s.QuadPart;
212        return true;
213    }
214    bool is_open() const { return h_ != INVALID_HANDLE_VALUE; }
215    bool direct() const { return false; }
216    bool write_all(const uint8_t* p, size_t n) {
217        while (n) {
218            DWORD w = 0;
219            const DWORD want = (DWORD) std::min<size_t>(n, size_t(1) << 30);
220            if (!WriteFile(h_, p, want, &w, nullptr) || w == 0) { { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); } return false; }
221            p += w; n -= w;
222        }
223        return true;
224    }
225    // bytes read, 0 at the end of the file, -1 on error
226    long long read_some(uint8_t* p, size_t n) {
227        DWORD r = 0;
228        if (!ReadFile(h_, p, (DWORD) std::min<size_t>(n, size_t(1) << 30), &r, nullptr)) {
229            { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); }
230            return -1;
231        }
232        return (long long) r;
233    }
234    bool read_at(uint64_t offset, uint8_t* p, size_t n) {
235        LARGE_INTEGER at{};
236        at.QuadPart = (LONGLONG) offset;
237        if (!SetFilePointerEx(h_, at, nullptr, FILE_BEGIN)) { { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); } return false; }
238        while (n) {
239            const long long r = read_some(p, n);
240            if (r <= 0) { if (r == 0) error_ = "file ends early"; return false; }
241            p += r; n -= (size_t) r;
242        }
243        return true;
244    }
245    bool truncate(uint64_t n) {
246        LARGE_INTEGER at{};
247        at.QuadPart = (LONGLONG) n;
248        if (SetFilePointerEx(h_, at, nullptr, FILE_BEGIN) && SetEndOfFile(h_)) return true;
249        { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); }
250        return false;
251    }
252    bool sync() {
253        if (FlushFileBuffers(h_)) return true;
254        { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); }
255        return false;
256    }
257    bool close() {
258        if (h_ == INVALID_HANDLE_VALUE) return true;
259        const bool ok = CloseHandle(h_) != 0;
260        if (!ok) { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); }
261        h_ = INVALID_HANDLE_VALUE;
262        return ok;
263    }
264    const std::string& error() const { return error_; }
265    bool missing() const { return missing_; }
266    SessionError kind() const { return kind_; }
267    // a validation refusal (a link, not a regular file, ...): bad input, not an I/O failure
268    bool refused() const { return refused_; }
269private:
270    HANDLE h_ = INVALID_HANDLE_VALUE;
271    SessionError kind_ = SessionError::io;
272    bool refused_ = false;
273    bool missing_ = false;
274    std::string error_;
275};
276
277// Where the file is published.  MoveFileExW replaces an existing destination (std::rename does not on Windows); the
278// replacement is a rename on one volume, but Windows promises no transaction on every filesystem.  A directory cannot
279// be flushed on Windows: the file's data was flushed (FlushFileBuffers) before the move, and the move is write-through.
280class Publisher {
281public:
282    bool open(const std::string& path, std::string& error) {
283        std::string dir, leaf;
284        if (!split_path(path, dir, leaf, error)) return false;
285        std::wstring wdir, wleaf;
286        if (!wide(dir, wdir) || !wide(leaf, wleaf)) { error = "session file: the path is not valid UTF-8"; return false; }
287        prefix_ = wdir.empty() ? std::wstring() : (wdir.back() == L'\\' || wdir.back() == L'/' ? wdir : wdir + L"\\");
288        final_ = prefix_ + wleaf;
289        leaf_ = leaf;
290        return true;
291    }
292    bool create_temp(RawFile& f, std::string& error) {
293        for (int attempt = 0; attempt < 8; ++attempt) {
294            std::wstring name;
295            wide(temp_name(leaf_), name);
296            temp_ = prefix_ + name;
297            if (f.create_new(temp_)) { own_ = true; return true; }
298            if (GetLastError() != ERROR_FILE_EXISTS && GetLastError() != ERROR_ALREADY_EXISTS) break;
299        }
300        error = f.error();
301        return false;
302    }
303    bool publish(std::string& error, bool, SessionStatus& st, const std::function<int(const char*)>* fault) {
304        if (const int e = injected(fault, "rename")) { error = std::strerror(e); st.error = errno_kind(e); return false; }
305        if (MoveFileExW(temp_.c_str(), final_.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
306            own_ = false;
307            st.published = true;
308            // Windows has no folder flush; a test can still make this step fail after the move
309            if (const int e = injected(fault, "dir_flush")) {
310                error = std::string("flushing the directory: ") + std::strerror(e);
311                st.error = errno_kind(e);
312                return false;
313            }
314            return true;
315        }
316        const DWORD c = GetLastError();
317        st.error = win_kind(c);
318        error = last_error(c);
319        return false;
320    }
321    SessionError kind() const { return SessionError::io; }
322    ~Publisher() { if (own_) DeleteFileW(temp_.c_str()); }   // only the temporary file this call created
323private:
324    std::wstring prefix_, final_, temp_;
325    std::string leaf_;
326    bool own_ = false;
327};
328
329bool free_space(const std::string& path, uint64_t& out) {
330    std::wstring w;
331    if (!wide(session_free_space_dir(path, true), w)) return false;
332    ULARGE_INTEGER avail{};
333    if (!GetDiskFreeSpaceExW(w.empty() ? nullptr : w.c_str(), &avail, nullptr, nullptr)) return false;
334    out = avail.QuadPart;
335    return true;
336}
337#else
338#ifndef O_DIRECT
339#define O_DIRECT 0            // not offered by this system: buffered I/O
340#endif
341
342bool buffered_forced() {
343    const char* e = std::getenv("STRATA_SESSION_BUFFERED");
344    return e != nullptr && e[0] == '1';
345}
346
347static_assert(sizeof(off_t) >= 8, "session files need 64-bit file offsets (large-file support)");
348
349class RawFile {
350public:
351    ~RawFile() { close(); }
352    // a new file that did not exist (O_CREAT|O_EXCL: never an existing file or link), readable by its owner only
353    bool create_new(int dirfd, const std::string& name) {
354        fd_ = ::openat(dirfd, name.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);
355        if (fd_ < 0) { kind_ = errno_kind(errno); error_ = std::strerror(errno); return false; }
356        try_direct();
357        return true;
358    }
359    // a session to restore: the name itself is opened, never what a symbolic link there points to; it must be a
360    // regular file with one name (no hard link to a file elsewhere).  Checked on the opened descriptor.
361    bool open_session(const std::string& path, uint64_t& size) {
362        fd_ = ::open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);   // NONBLOCK: a FIFO cannot hang
363        if (fd_ < 0) {
364            refused_ = errno == ELOOP;
365            kind_ = errno_kind(errno);
366            error_ = errno == ELOOP ? std::string("a symbolic link, not a file") : std::string(std::strerror(errno));
367            return false;
368        }
369        struct stat st {};
370        if (::fstat(fd_, &st) != 0) { error_ = std::strerror(errno); return false; }
371        if (!S_ISREG(st.st_mode)) { refused_ = true; error_ = "not a regular file"; return false; }
372        if (st.st_nlink != 1) { refused_ = true; error_ = "the file has more than one name (hard link)"; return false; }
373        const int fl = ::fcntl(fd_, F_GETFL);
374        if (fl >= 0) ::fcntl(fd_, F_SETFL, fl & ~O_NONBLOCK);
375        size = (uint64_t) st.st_size;
376        try_direct();
377        return true;
378    }
379    // a model input: links followed (model folders are often linked)
380    bool open_model(const std::string& path, uint64_t& size) {
381        fd_ = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
382        if (fd_ < 0) { missing_ = errno == ENOENT; kind_ = errno_kind(errno); error_ = std::strerror(errno); return false; }
383        struct stat st {};
384        if (::fstat(fd_, &st) != 0) { error_ = std::strerror(errno); return false; }
385        if (!S_ISREG(st.st_mode)) { error_ = "not a regular file"; return false; }
386        size = (uint64_t) st.st_size;
387        return true;
388    }
389    bool is_open() const { return fd_ >= 0; }
390    bool direct() const { return direct_; }
391    bool write_all(const uint8_t* p, size_t n) {
392        while (n) {
393            const ssize_t w = ::write(fd_, p, n);
394            if (w < 0 && errno == EINTR) continue;
395            // a filesystem that took O_DIRECT at open but refuses this transfer: nothing was written, go buffered
396            if (w < 0 && errno == EINVAL && direct_ && leave_direct()) continue;
397            if (w <= 0) { kind_ = w < 0 ? errno_kind(errno) : SessionError::io; error_ = w < 0 ? std::strerror(errno) : "short write"; return false; }
398            p += w; n -= (size_t) w;
399        }
400        return true;
401    }
402    // bytes read, 0 at the end of the file, -1 on error
403    long long read_some(uint8_t* p, size_t n) {
404        for (;;) {
405            const ssize_t r = ::read(fd_, p, n);
406            if (r < 0 && errno == EINTR) continue;
407            if (r < 0 && errno == EINVAL && direct_ && leave_direct()) continue;
408            if (r < 0) { kind_ = errno_kind(errno); error_ = std::strerror(errno); }
409            return (long long) r;
410        }
411    }
412    bool read_at(uint64_t offset, uint8_t* p, size_t n) {
413        while (n) {
414            const ssize_t r = ::pread(fd_, p, n, (off_t) offset);
415            if (r < 0 && errno == EINTR) continue;
416            if (r <= 0) { kind_ = r < 0 ? errno_kind(errno) : SessionError::io; error_ = r < 0 ? std::strerror(errno) : "file ends early"; return false; }
417            p += r; n -= (size_t) r; offset += (uint64_t) r;
418        }
419        return true;
420    }
421    bool truncate(uint64_t n) {
422        if (::ftruncate(fd_, (off_t) n) == 0) return true;
423        kind_ = errno_kind(errno);
424        error_ = std::strerror(errno);
425        return false;
426    }
427    bool sync() {
428        if (::fsync(fd_) == 0) return true;
429        kind_ = errno_kind(errno);
430        error_ = std::strerror(errno);
431        return false;
432    }
433    bool close() {
434        if (fd_ < 0) return true;
435        const bool ok = ::close(fd_) == 0;
436        if (!ok) { kind_ = errno_kind(errno); error_ = std::strerror(errno); }
437        fd_ = -1;
438        return ok;
439    }
440    const std::string& error() const { return error_; }
441    bool missing() const { return missing_; }
442    SessionError kind() const { return kind_; }
443    // a validation refusal (a link, not a regular file, ...): bad input, not an I/O failure
444    bool refused() const { return refused_; }
445private:
446    // O_DIRECT is switched on the open descriptor: a filesystem that refuses it (EINVAL, e.g. tmpfs) keeps buffered
447    // I/O, and the file is never opened twice
448    void try_direct() {
449        if (O_DIRECT == 0 || buffered_forced()) return;
450        const int fl = ::fcntl(fd_, F_GETFL);
451        direct_ = fl >= 0 && ::fcntl(fd_, F_SETFL, fl | O_DIRECT) == 0;
452    }
453    bool leave_direct() {
454        const int fl = ::fcntl(fd_, F_GETFL);
455        if (fl < 0 || ::fcntl(fd_, F_SETFL, fl & ~O_DIRECT) != 0) return false;
456        direct_ = false;
457        return true;
458    }
459    int fd_ = -1;
460    bool direct_ = false, missing_ = false, refused_ = false;
461    SessionError kind_ = SessionError::io;
462    std::string error_;
463};
464
465// The destination directory is opened once; the temporary file is created in it exclusively, renamed over the
466// final name in the same directory (a symbolic link at the final name is replaced, never written through), and the
467// directory is flushed after the rename so the new name survives a power loss.
468class Publisher {
469public:
470    bool open(const std::string& path, std::string& error) {
471        std::string dir;
472        if (!split_path(path, dir, leaf_, error)) return false;
473        dirfd_ = ::open(dir.empty() ? "." : dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
474        if (dirfd_ < 0) {
475            kind_ = errno_kind(errno);
476            error = "session file: cannot open the directory of " + path + ": " + std::strerror(errno);
477            return false;
478        }
479        return true;
480    }
481    bool create_temp(RawFile& f, std::string& error) {
482        for (int attempt = 0; attempt < 8; ++attempt) {
483            temp_ = temp_name(leaf_);
484            if (f.create_new(dirfd_, temp_)) { own_ = true; return true; }
485            if (errno != EEXIST) break;
486        }
487        error = f.error();
488        return false;
489    }
490    bool publish(std::string& error, bool durable, SessionStatus& st, const std::function<int(const char*)>* fault) {
491        int e = injected(fault, "rename");
492        if (e || ::renameat(dirfd_, temp_.c_str(), dirfd_, leaf_.c_str()) != 0) {
493            if (!e) e = errno;
494            error = std::strerror(e);
495            st.error = errno_kind(e);
496            return false;
497        }
498        own_ = false;
499        st.published = true;   // the new file is at its name now: a failure below cannot bring the old one back
500        if (!durable) return true;
501        e = injected(fault, "dir_flush");
502        if (!e && ::fsync(dirfd_) != 0) e = errno;
503        if (e == EINVAL) { st.dir_flush_unsupported = true; return true; }   // this filesystem cannot flush a folder
504        if (e) {
505            error = std::string("flushing the directory: ") + std::strerror(e);
506            st.error = errno_kind(e);
507            return false;
508        }
509        return true;
510    }
511    SessionError kind() const { return kind_; }
512    ~Publisher() {
513        if (own_) ::unlinkat(dirfd_, temp_.c_str(), 0);   // only the temporary file this call created
514        if (dirfd_ >= 0) ::close(dirfd_);
515    }
516private:
517    int dirfd_ = -1;
518    std::string leaf_, temp_;
519    bool own_ = false;
520    SessionError kind_ = SessionError::io;
521};
522
523bool free_space(const std::string& path, uint64_t& out) {
524    struct statvfs s {};
525    if (::statvfs(session_free_space_dir(path, false).c_str(), &s) != 0) return false;
526    out = (uint64_t) s.f_bavail * (uint64_t) s.f_frsize;
527    return true;
528}
529#endif
530
531class FileSink {
532public:
533    explicit FileSink(RawFile& f) : buf_(aligned_block()), f_(f) {}
534    bool ok() const { return buf_ != nullptr; }
535    std::string error() const {
536        if (!buf_) return "out of memory for the write buffer";
537        return fault_ ? fault_msg_ : f_.error();
538    }
539    SessionError kind() const { return buf_ ? (fault_ ? fault_kind_ : f_.kind()) : SessionError::memory; }
540    // room in the block for in-place production (avoids a staging copy)
541    uint8_t* span(size_t& room) { room = kBlock - used_; return buf_.get() + used_; }
542    bool commit(size_t n) { used_ += n; total_ += n; return used_ < kBlock || drain(); }
543    bool write(const void* p, size_t n) {
544        const uint8_t* s = static_cast<const uint8_t*>(p);
545        while (n) {
546            size_t room = 0;
547            uint8_t* d = span(room);
548            const size_t c = std::min(room, n);
549            std::memcpy(d, s, c);
550            if (!commit(c)) return false;
551            s += c; n -= c;
552        }
553        return true;
554    }
555    // last block padded to the alignment for direct I/O, then the file cut back to its exact size and flushed
556    bool finish(bool durable) {
557        if (!f_.is_open()) return false;
558        if (fault_) { f_.close(); return false; }
559        const size_t padded = f_.direct() ? (used_ + kAlign - 1) / kAlign * kAlign : used_;
560        std::memset(buf_.get() + used_, 0, padded - used_);
561        bool ok = f_.write_all(buf_.get(), padded);
562        if (ok && used_ && progress) (*progress)(total_, expected);   // the last, partial block
563        ok = ok && (padded == used_ || f_.truncate(total_));
564        if (ok && durable && phase) phase("flush", total_);
565        if (ok && durable && flush_fault) { fail_with(flush_fault); ok = false; }
566        ok = ok && (!durable || f_.sync());
567        ok = f_.close() && ok;
568        return ok;
569    }
570    std::optional<Ticker> progress;
571    SessionPhase phase;
572    uint64_t expected = 0;
573    int write_fault = 0, flush_fault = 0;   // tests: errno values injected at the first block write / the file flush
574private:
575    void fail_with(int e) { fault_ = true; fault_kind_ = errno_kind(e); fault_msg_ = std::strerror(e); }
576    bool drain() {
577        if (write_fault) { fail_with(write_fault); return false; }
578        if (!f_.write_all(buf_.get(), used_)) return false;
579        used_ = 0;
580        if (progress) (*progress)(total_, expected);
581        return true;
582    }
583    Aligned buf_;
584    RawFile& f_;
585    bool fault_ = false;
586    SessionError fault_kind_ = SessionError::io;
587    std::string fault_msg_;
588    size_t used_ = 0;
589    uint64_t total_ = 0;
590};
591
592class FileSource {
593public:
594    explicit FileSource(RawFile& f) : buf_(aligned_block()), f_(f) {}
595    bool ok() const { return buf_ != nullptr; }
596    std::string error() const { return buf_ ? f_.error() : std::string("out of memory for the read buffer"); }
597    SessionError kind() const { return buf_ ? f_.kind() : SessionError::memory; }
598    bool read(void* p, size_t n) {
599        uint8_t* d = static_cast<uint8_t*>(p);
600        while (n) {
601            if (at_ == have_ && !fill()) return false;
602            const size_t c = std::min(n, have_ - at_);
603            std::memcpy(d, buf_.get() + at_, c);
604            at_ += c; d += c; n -= c;
605        }
606        return true;
607    }
608    std::optional<Ticker> progress;
609    uint64_t expected = 0;
610private:
611    bool fill() {
612        at_ = have_ = 0;
613        while (have_ < kBlock) {
614            const long long r = f_.read_some(buf_.get() + have_, kBlock - have_);
615            if (r < 0) return false;
616            if (r == 0) break;
617            have_ += (size_t) r;
618            if (f_.direct() && have_ % kAlign) break;   // short aligned read: end of file
619        }
620        const uint64_t before = total_;
621        total_ += have_;
622        if (progress && total_ > before) (*progress)(total_, expected);
623        return have_ > 0;
624    }
625    Aligned buf_;
626    RawFile& f_;
627    size_t at_ = 0, have_ = 0;
628    uint64_t total_ = 0;
629};
630
631// ---- serialization: the same walk counts (f == nullptr) and writes
632struct Out {
633    FileSink* f = nullptr;
634    SessionHasher* hash = nullptr;
635    uint64_t n = 0;
636    bool ok = true, overflow = false;
637    void count(uint64_t c) {
638        if (c > UINT64_MAX - n) { overflow = true; ok = false; return; }
639        n += c;
640    }
641    void raw(const void* p, size_t c) {
642        count(c);
643        if (!f || !ok || !c) return;
644        if (hash) hash->update(p, c);
645        ok = f->write(p, c);
646    }
647    void u64(uint64_t v) { raw(&v, 8); }
648    void i64(int64_t v) { raw(&v, 8); }
649    template<class T> void vec(const std::vector<T>& v) { u64(v.size()); raw(v.data(), v.size() * sizeof(T)); }
650    void buffer(const ConversationBuffer& b) {
651        u64(b.size());
652        b.visit(0, b.size(), [&](const uint8_t* p, size_t c, size_t) { raw(p, c); return ok; });
653    }
654    // a K/V part pulled from its owner straight into the file block (sizing pass: counted, never read)
655    void source(const SessionKvSource& s, size_t part) {
656        const size_t size = s.sizes[part];
657        u64(size);
658        if (!f) { count(size); return; }
659        for (size_t at = 0; at < size && ok;) {
660            size_t room = 0;
661            uint8_t* d = f->span(room);
662            const size_t c = std::min(room, size - at);
663            if (!s.read || !s.read(part, at, d, c)) {
664                ok = false;
665                read_failed = true;
666                if (s.error) read_error = s.error();
667                return;
668            }
669            if (hash) hash->update(d, c);
670            count(c);
671            ok = ok && f->commit(c);
672            at += c;
673        }
674    }
675    bool read_failed = false;
676    std::string read_error;
677};
678
679void put_kv_header(Out& o, int format, int64_t cells, int64_t heads, int64_t head_dim, int64_t page_size,
680                   int64_t pooled_rows, int64_t idx_dim) {
681    for (int64_t v : {int64_t(format), cells, heads, head_dim, page_size, pooled_rows, idx_dim}) o.i64(v);
682}
683
684void put_checkpoint(Out& o, const ConversationCheckpoint& c) {
685    o.vec(c.ids);
686    o.u64(c.imgs.size());
687    for (const auto& k : c.imgs) { o.i64(k.start); o.u64(k.hash); }
688    o.vec(c.gdn); o.vec(c.ple); o.vec(c.tails); o.vec(c.dead); o.vec(c.block_pos);
689    o.u64(c.used);
690}
691
692void put_payload(Out& o, const SavedConversation& s, const std::vector<SessionKvSource>* sources = nullptr) {
693    for (int64_t g : s.geometry) o.i64(g);
694    o.i64(s.layer_lo); o.i64(s.layer_hi); o.u64(s.cvec ? 1 : 0);
695    put_checkpoint(o, s.live);
696    o.u64(s.checkpoints.size());
697    for (const auto& c : s.checkpoints) put_checkpoint(o, c);
698    if (sources) {
699        o.u64(sources->size());
700        for (const auto& k : *sources) {
701            put_kv_header(o, k.format, k.cells, k.heads, k.head_dim, k.page_size, k.pooled_rows, k.idx_dim);
702            for (size_t part = 0; part < 5; ++part) o.source(k, part);
703        }
704        return;
705    }
706    o.u64(s.kv.size());
707    for (const auto& k : s.kv) {
708        put_kv_header(o, k.format, k.cells, k.heads, k.head_dim, k.page_size, k.pooled_rows, k.idx_dim);
709        o.buffer(k.k); o.buffer(k.v); o.buffer(k.k_scale); o.buffer(k.v_scale); o.buffer(k.pooled);
710    }
711}
712
713// the whole file payload: the first stage's, then (v2 only) the later stages' own payloads
714void put_image(Out& o, const SavedConversation& s, const std::vector<SessionKvSource>* sources) {
715    put_payload(o, s, sources);
716    if (s.stage_images.empty()) return;
717    o.u64(s.stage_images.size());
718    for (const auto& stage : s.stage_images) put_payload(o, stage);
719}
720
721// ---- parsing: every count is checked against the bytes left and the caller's limits before anything is allocated
722struct In {
723    FileSource* f;
724    SessionHasher hash;
725    uint64_t left;
726    std::string& error;
727    const SessionReadLimits* lim;   // the stage being parsed: the file's limits, then each later stage's
728    SessionError kind = SessionError::invalid;
729    size_t kv_layer = 0;
730    bool fail(const std::string& m) { if (error.empty()) error = "session file: " + m; return false; }
731    bool raw(void* p, size_t c) {
732        if (c > left) return fail("payload ends early");
733        if (c && !f->read(p, c)) { kind = f->kind(); return fail("read error: " + f->error()); }
734        hash.update(p, c);
735        left -= c;
736        return true;
737    }
738    bool u64(uint64_t& v) { return raw(&v, 8); }
739    bool i64(int64_t& v) { return raw(&v, 8); }
740    // `elem`: the fewest file bytes one element takes; `limit`: the most elements the caller accepts
741    bool count(uint64_t& n, size_t elem, uint64_t limit = UINT64_MAX) {
742        if (!u64(n)) return false;
743        if (elem && n > left / elem) return fail("element count exceeds the payload");
744        if (n > limit) return fail("element count " + std::to_string(n) + " exceeds this engine's limit " +
745                                   std::to_string(limit));
746        if (n > (uint64_t) std::numeric_limits<size_t>::max() / (elem ? elem : 1)) return fail("element count too large");
747        return true;
748    }
749    template<class T> bool vec(std::vector<T>& v, uint64_t limit = UINT64_MAX) {
750        uint64_t n = 0;
751        if (!count(n, sizeof(T), limit)) return false;
752        v.resize((size_t) n);
753        return raw(v.data(), (size_t) n * sizeof(T));
754    }
755    bool buffer(ConversationBuffer& b, size_t part) {
756        uint64_t n = 0;
757        const uint64_t limit = kv_layer < lim->max_kv_bytes.size() ? lim->max_kv_bytes[kv_layer][part] : UINT64_MAX;
758        if (!count(n, 1, limit)) return false;
759        b = {};
760        b.resize((size_t) n);
761        return b.visit(0, b.size(), [&](uint8_t* p, size_t c, size_t) { return raw(p, c); });
762    }
763};
764
765bool get_checkpoint(In& in, ConversationCheckpoint& c) {
766    if (!in.vec(c.ids, in.lim->max_tokens)) return false;
767    uint64_t n = 0;
768    if (!in.count(n, 16, in.lim->max_tokens)) return false;
769    c.imgs.resize((size_t) n);
770    for (auto& k : c.imgs) if (!in.i64(k.start) || !in.u64(k.hash)) return false;
771    const auto& m = in.lim->max_state_bytes;   // byte arrays: element and byte counts are the same
772    return in.vec(c.gdn, m[0]) && in.vec(c.ple, m[1]) && in.vec(c.tails, m[2]) && in.vec(c.dead, m[3]) &&
773           in.vec(c.block_pos, m[4]) && in.u64(c.used);
774}
775
776bool get_payload(In& in, SavedConversation& s) {
777    for (auto& g : s.geometry) if (!in.i64(g)) return false;
778    // checked before any state array is read: a file of another geometry allocates nothing
779    if (in.lim->geometry && *in.lim->geometry != s.geometry)
780        return in.fail("saved with another model geometry than this runtime's");
781    uint64_t cvec = 0;
782    if (!in.i64(s.layer_lo) || !in.i64(s.layer_hi) || !in.u64(cvec)) return false;
783    if (in.lim->layer_range &&
784        (in.lim->layer_range->first != s.layer_lo || in.lim->layer_range->second != s.layer_hi))
785        return in.fail("saved with another layer range than this runtime's");
786    if (cvec > 1) return in.fail("invalid cvec flag");
787    s.cvec = cvec == 1;
788    if (!get_checkpoint(in, s.live)) return false;
789    uint64_t n = 0;
790    // a checkpoint is at least 8 counts + used = 72 bytes; a K/V layer at least 7 + 5 = 96
791    if (!in.count(n, 72, in.lim->max_checkpoints)) return false;
792    s.checkpoints.resize((size_t) n);
793    for (auto& c : s.checkpoints) if (!get_checkpoint(in, c)) return false;
794    if (!in.count(n, 96, in.lim->max_kv_layers)) return false;
795    s.kv.resize((size_t) n);
796    for (auto& k : s.kv) {
797        in.kv_layer = (size_t) (&k - s.kv.data());
798        int64_t format = 0;
799        if (!in.i64(format) || !in.i64(k.cells) || !in.i64(k.heads) || !in.i64(k.head_dim) ||
800            !in.i64(k.page_size) || !in.i64(k.pooled_rows) || !in.i64(k.idx_dim)) return false;
801        if (format < INT32_MIN || format > INT32_MAX) return in.fail("invalid K/V format");
802        k.format = (int) format;
803        if (!in.buffer(k.k, 0) || !in.buffer(k.v, 1) || !in.buffer(k.k_scale, 2) || !in.buffer(k.v_scale, 3) ||
804            !in.buffer(k.pooled, 4)) return false;
805    }
806    return true;
807}
808
809// the later stages of a v2 file, each parsed against that stage's own limits
810bool get_stages(In& in, SavedConversation& s, const SessionReadLimits& file_limits) {
811    uint64_t n = 0;
812    if (!in.count(n, 1, file_limits.stage_limits.size())) return false;
813    if (n != file_limits.stage_limits.size())
814        return in.fail("saved with " + std::to_string(n + 1) + " GPUs, this runtime splits the layers over " +
815                       std::to_string(file_limits.stage_limits.size() + 1));
816    s.stage_images.resize((size_t) n);
817    for (size_t i = 0; i < s.stage_images.size(); ++i) {
818        in.lim = &file_limits.stage_limits[i];
819        in.kv_layer = 0;
820        if (!get_payload(in, s.stage_images[i])) return false;
821    }
822    in.lim = &file_limits;
823    return true;
824}
825
826bool has_stage_parts(const SavedConversation& s) {
827    if (!s.live.stage_parts.empty()) return true;
828    for (const auto& c : s.checkpoints) if (!c.stage_parts.empty()) return true;
829    for (const auto& stage : s.stage_images) if (has_stage_parts(stage) || !stage.stage_images.empty()) return true;
830    return false;
831}
832
833// header v1, little-endian: magic[8] version:u32 header_size:u32 model:u64 config:u64 payload:u64 reserved:u64[2]
834// header_hash:u64 (session_hash64 of bytes 0..55, seed 0)
835void header_bytes(uint8_t* h, const SessionFileIdentity& id, uint64_t payload, uint32_t version) {
836    std::memset(h, 0, kHeader);
837    std::memcpy(h, kMagic, 8);
838    const uint32_t size = kHeader;
839    std::memcpy(h + 8, &version, 4);
840    std::memcpy(h + 12, &size, 4);
841    std::memcpy(h + 16, &id.model, 8);
842    std::memcpy(h + 24, &id.config, 8);
843    std::memcpy(h + 32, &payload, 8);
844    const uint64_t hh = session_hash64(h, 56, 0);
845    std::memcpy(h + 56, &hh, 8);
846}
847} // namespace
848
849SessionHasher::SessionHasher(uint64_t seed)
850    : lane_{seed + P1 + P2, seed + P2, seed, seed - P1}, pending_{} {}
851
852void SessionHasher::block(const uint8_t* p) {
853    for (int i = 0; i < 4; ++i) lane_[i] = round1(lane_[i], load64(p + 8 * i));
854}
855
856void SessionHasher::update(const void* data, size_t n) {
857    const uint8_t* p = static_cast<const uint8_t*>(data);
858    total_ += n;
859    if (npending_) {
860        const size_t take = std::min(n, sizeof pending_ - npending_);
861        std::memcpy(pending_ + npending_, p, take);
862        npending_ += take; p += take; n -= take;
863        if (npending_ < sizeof pending_) return;
864        block(pending_);
865        npending_ = 0;
866    }
867    for (; n >= 32; p += 32, n -= 32) block(p);
868    if (n) std::memcpy(pending_, p, n);
869    npending_ = n;
870}
871
872uint64_t SessionHasher::digest() const {
873    uint64_t h = rotl(lane_[0], 1) + rotl(lane_[1], 7) + rotl(lane_[2], 12) + rotl(lane_[3], 18);
874    for (uint64_t l : lane_) { h ^= round1(0, l); h = h * P1 + P4; }
875    h += total_;
876    size_t i = 0;
877    for (; i + 8 <= npending_; i += 8) { h ^= round1(0, load64(pending_ + i)); h = rotl(h, 27) * P1 + P4; }
878    for (; i < npending_; ++i) { h ^= pending_[i] * P5; h = rotl(h, 11) * P1; }
879    h ^= h >> 33; h *= P2; h ^= h >> 29; h *= P3; h ^= h >> 32;
880    return h;
881}
882
883uint64_t session_hash64(const void* data, size_t n, uint64_t seed) {
884    SessionHasher h(seed);
885    h.update(data, n);
886    return h.digest();
887}
888
889void SessionIdentityBuilder::field(const std::string& tag, uint8_t type, const void* data, uint64_t n) {
890    const uint64_t tn = tag.size();
891    hash_.update(&tn, 8);
892    hash_.update(tag.data(), tag.size());
893    hash_.update(&type, 1);
894    hash_.update(&n, 8);
895    if (n) hash_.update(data, (size_t) n);
896}
897void SessionIdentityBuilder::str(const std::string& tag, const std::string& v) { field(tag, 's', v.data(), v.size()); }
898void SessionIdentityBuilder::i64(const std::string& tag, int64_t v) { field(tag, 'i', &v, 8); }
899void SessionIdentityBuilder::u64(const std::string& tag, uint64_t v) { field(tag, 'u', &v, 8); }
900void SessionIdentityBuilder::f64(const std::string& tag, double v) {
901    uint64_t bits = 0;
902    std::memcpy(&bits, &v, 8);
903    field(tag, 'f', &bits, 8);
904}
905void SessionIdentityBuilder::bytes(const std::string& tag, const void* data, size_t n) { field(tag, 'b', data, n); }
906
907uint64_t session_config_fingerprint(const SessionConfig& c) {
908    SessionIdentityBuilder b(0x434f4e4649473031ull);   // "CONFIG01"
909    b.str("engine", c.engine_version);
910    b.str("backend", c.backend);
911    b.str("kv", c.kv);
912    b.i64("max_context", c.max_context);
913    b.i64("kv_resident", c.kv_resident);
914    b.i64("mtp_window", c.mtp_window);
915    b.i64("kv_rot", c.kv_rot ? 1 : 0);
916    b.i64("rope.type", c.rope.type);
917    b.f64("rope.freq_base", c.rope.freq_base);
918    b.f64("rope.factor", c.rope.factor);
919    b.f64("rope.freq_scale", c.rope.freq_scale);
920    b.f64("rope.orig_ctx", c.rope.orig_ctx);
921    b.f64("rope.ext_factor", c.rope.ext_factor);
922    b.f64("rope.attn_factor", c.rope.attn_factor);
923    b.f64("rope.beta_fast", c.rope.beta_fast);
924    b.f64("rope.beta_slow", c.rope.beta_slow);
925    b.u64("cvec", c.cvec);
926    b.u64("switches", c.switches.size());
927    for (const auto& [name, value] : c.switches) b.i64("switch." + name, value);
928    return b.digest();
929}
930
931const char* session_error_name(SessionError e) {
932    switch (e) {
933        case SessionError::none: return "none";
934        case SessionError::invalid: return "invalid";
935        case SessionError::storage: return "storage";
936        case SessionError::memory: return "memory";
937        case SessionError::io: return "io";
938    }
939    return "io";
940}
941
942std::string session_free_space_dir(const std::string& path, bool windows_rules) {
943    if (!windows_rules) {
944        const size_t cut = path.find_last_of('/');
945        if (cut == std::string::npos) return ".";
946        return path.substr(0, cut == 0 ? 1 : cut);
947    }
948    std::string p = path;
949    for (char& c : p) if (c == '/') c = '\\';
950    const size_t cut = p.find_last_of('\\');
951    if (cut == std::string::npos) {
952        // "C:chat.bin" (drive-relative): the drive root answers for the same volume
953        if (p.size() >= 2 && p[1] == ':') return p.substr(0, 2) + "\\";
954        return std::string();   // the current folder
955    }
956    return p.substr(0, cut + 1);   // with its trailing backslash: "\\server\share\dir\", "C:\"
957}
958
959std::vector<SessionModelFile> session_model_inputs(const SessionInputs& in) {
960    std::vector<SessionModelFile> f;
961    for (size_t i = 0; i < in.native_shards.size(); ++i) f.push_back({"native shard " + std::to_string(i), in.native_shards[i]});
962    for (size_t i = 0; i < in.native_dense.size(); ++i) f.push_back({"native dense " + std::to_string(i), in.native_dense[i]});
963    for (size_t i = 0; i < in.native_head.size(); ++i) f.push_back({"native head " + std::to_string(i), in.native_head[i]});
964    if (!in.embedding.empty()) f.push_back({"embedding", in.embedding});
965    if (!in.ple.empty()) f.push_back({"ple", in.ple});
966    if (!in.mtp.empty()) f.push_back({"mtp", in.mtp});
967    if (!in.pack.empty()) f.push_back({"pack native_experts.txt", in.pack + "/native_experts.txt", true});
968    for (const auto& [role, path] : in.experts) f.push_back({role, path});
969    return f;
970}
971
972bool session_model_fingerprint(const std::vector<SessionModelFile>& files, uint64_t& fingerprint, std::string& error,
973                               const std::function<void()>& beat) {
974    SessionIdentityBuilder h(0x5354524154414d44ull);
975    std::vector<uint8_t> buf(1u << 20);
976    // a file in several roles is read once; its sample enters the fingerprint under every role
977    std::unordered_map<std::string, std::pair<bool, uint64_t>> seen;   // path -> (present, sample digest)
978    h.u64("files", files.size());
979    for (const auto& file : files) {
980        auto it = seen.find(file.path);
981        if (it == seen.end()) {
982            RawFile f;
983            uint64_t size = 0;
984            std::pair<bool, uint64_t> d{false, 0};
985            if (!f.open_model(file.path, size)) {
986                if (!(file.optional && f.missing())) {
987                    error = "session fingerprint: " + file.role + " " + file.path + ": " + f.error();
988                    return false;
989                }
990            } else {
991                SessionIdentityBuilder one(0x46494c4553414d50ull);   // "FILESAMP"
992                one.u64("size", size);
993                const uint64_t head = std::min<uint64_t>(size, buf.size());
994                if (!f.read_at(0, buf.data(), (size_t) head)) {
995                    error = "session fingerprint: reading " + file.path + ": " + f.error();
996                    return false;
997                }
998                one.bytes("head", buf.data(), (size_t) head);
999                if (size > buf.size()) {
1000                    const uint64_t tail = std::min<uint64_t>(size - head, buf.size());
1001                    if (!f.read_at(size - tail, buf.data(), (size_t) tail)) {
1002                        error = "session fingerprint: reading " + file.path + ": " + f.error();
1003                        return false;
1004                    }
1005                    one.bytes("tail", buf.data(), (size_t) tail);
1006                }
1007                d = {true, one.digest()};
1008            }
1009            it = seen.emplace(file.path, d).first;
1010            if (beat) beat();
1011        }
1012        if (!it->second.first) {
1013            if (!file.optional) { error = "session fingerprint: " + file.role + " " + file.path + " is missing"; return false; }
1014            h.str("absent", file.role);
1015            continue;
1016        }
1017        h.str("role", file.role);
1018        h.u64("sample", it->second.second);
1019    }
1020    fingerprint = h.digest();
1021    return true;
1022}
1023
1024namespace {
1025uint64_t sat_add(uint64_t a, uint64_t b) { return a > UINT64_MAX - b ? UINT64_MAX : a + b; }
1026uint64_t sat_mul(uint64_t a, uint64_t b) { return a && b > UINT64_MAX / a ? UINT64_MAX : a * b; }
1027} // namespace
1028
1029uint64_t session_read_max_file_bytes(const SessionReadLimits& l) {
1030    const uint64_t open = UINT64_MAX;
1031    if (l.max_tokens == open || l.max_checkpoints == open || l.max_kv_layers == open) return l.max_file_bytes;
1032    for (uint64_t b : l.max_state_bytes) if (b == open) return l.max_file_bytes;
1033    if (l.max_kv_bytes.size() < l.max_kv_layers) return l.max_file_bytes;
1034    // one checkpoint: ids (8 + 4 per token), images (8 + 16 per image), five state arrays (8 + bytes), used (8)
1035    uint64_t cp = sat_add(16, sat_mul(l.max_tokens, 4 + 16));
1036    for (uint64_t b : l.max_state_bytes) cp = sat_add(cp, sat_add(8, b));
1037    cp = sat_add(cp, 8);
1038    uint64_t n = kHeader + kTrailer + 18 * 8 + 3 * 8;             // geometry, layer range, cvec
1039    n = sat_add(n, cp);                                            // live
1040    n = sat_add(n, sat_add(8, sat_mul(l.max_checkpoints, cp)));    // checkpoints
1041    n = sat_add(n, 8);
1042    for (uint64_t i = 0; i < l.max_kv_layers; ++i) {
1043        n = sat_add(n, 7 * 8);
1044        for (uint64_t b : l.max_kv_bytes[(size_t) i]) n = sat_add(n, sat_add(8, b));
1045    }
1046    if (!l.stage_limits.empty()) {   // v2: the stage count, then each later stage's payload (without its own framing)
1047        n = sat_add(n, 8);
1048        for (const auto& s : l.stage_limits) {
1049            const uint64_t m = session_read_max_file_bytes(s);
1050            if (m == UINT64_MAX) return l.max_file_bytes;
1051            n = sat_add(n, m - kHeader - kTrailer);
1052        }
1053    }
1054    return std::min(n, l.max_file_bytes);
1055}
1056
1057uint64_t session_read_peak_bytes(uint64_t file_bytes) {
1058    const uint64_t segments = file_bytes / kBlock + 1;
1059    // the parsed image (about the payload), the read buffer, a page per buffer segment, the small vectors
1060    return sat_add(sat_add(sat_add(file_bytes, kBlock), sat_mul(segments, 4096)), uint64_t(1) << 20);
1061}
1062
1063namespace {
1064bool write_impl(const std::string& path, const SavedConversation& image, const std::vector<SessionKvSource>* sources,
1065                const SessionFileIdentity& id, size_t& bytes, std::string& error, const SessionWriteOptions& opt,
1066                SessionStatus& st) {
1067    st = {};
1068    st.error = SessionError::invalid;   // refusals before any disk access
1069    if (has_stage_parts(image)) {
1070        error = "session file: a checkpoint's stage parts belong in the stage images";
1071        return false;
1072    }
1073    if (sources && !image.stage_images.empty()) {
1074        error = "session file: a layer split's state is written from the captured image, not from K/V sources";
1075        return false;
1076    }
1077    if (sources && !image.kv.empty()) { error = "session file: K/V given both in the image and as sources"; return false; }
1078    Out sizing;
1079    put_image(sizing, image, sources);
1080    if (sizing.overflow || sizing.n > UINT64_MAX - kHeader - kTrailer ||
1081        sizing.n + kHeader + kTrailer > (uint64_t) std::numeric_limits<size_t>::max()) {
1082        error = "session file: the state is too large for this build";
1083        return false;
1084    }
1085    const uint64_t payload = sizing.n, total = kHeader + payload + kTrailer;
1086    st.error = SessionError::io;
1087    if (opt.min_free_bytes) {
1088        uint64_t avail = 0;
1089        if (!free_space(path, avail)) { error = "session file: cannot read the free disk space for " + path; return false; }
1090        if (avail < total || avail - total < opt.min_free_bytes) {
1091            st.error = SessionError::storage;
1092            error = "session file: not enough disk space (" + std::to_string(total >> 20) + " MiB plus a reserve of " +
1093                    std::to_string(opt.min_free_bytes >> 20) + " MiB needed, " + std::to_string(avail >> 20) +
1094                    " MiB free)";
1095            return false;
1096        }
1097    }
1098    Publisher pub;
1099    if (!pub.open(path, error)) { st.error = pub.kind(); return false; }
1100    RawFile raw;
1101    if (!pub.create_temp(raw, error)) {
1102        st.error = raw.kind();
1103        error = "session file: cannot create a temporary file beside " + path + ": " + error;
1104        return false;
1105    }
1106    FileSink f(raw);
1107    if (!f.ok()) { st.error = SessionError::memory; error = "session file: " + f.error(); return false; }
1108    if (opt.progress) f.progress.emplace(opt.progress);
1109    f.phase = opt.phase;
1110    f.expected = total;
1111    if (f.progress) (*f.progress)(0, total);   // the temporary file exists: the transfer starts
1112    const std::function<int(const char*)>* fault = opt.fault ? &opt.fault : nullptr;
1113    f.write_fault = injected(fault, "write");
1114    f.flush_fault = injected(fault, "file_flush");
1115    uint8_t h[kHeader];
1116    header_bytes(h, id, payload, image.stage_images.empty() ? kVersion : kVersionStages);
1117    bool ok = f.write(h, kHeader);
1118    SessionHasher hash(0);
1119    Out out;
1120    out.f = &f;
1121    out.hash = &hash;
1122    if (ok) put_image(out, image, sources);
1123    ok = ok && out.ok && out.n == payload;
1124    if (ok) {
1125        const uint64_t ph = hash.digest();
1126        ok = f.write(&ph, 8) && f.write(kEnd, 8);
1127    }
1128    ok = f.finish(opt.durable) && ok;
1129    std::string why;
1130    if (!ok) {
1131        why = out.read_failed ? "K/V source read" + (out.read_error.empty() ? std::string() : ": " + out.read_error)
1132                              : f.error();
1133        st.error = out.read_failed ? SessionError::io : f.kind();
1134    } else {
1135        if (opt.phase) opt.phase("publish", total);
1136        if (pub.publish(why, opt.durable, st, fault)) {
1137            st.error = SessionError::none;
1138            bytes = (size_t) total;
1139            return true;
1140        }
1141    }
1142    error = "session file: writing " + path + " failed" + (why.empty() ? std::string() : ": " + why);
1143    if (st.published) error += " (the new file has already replaced the old one; its folder entry may not survive a power loss)";
1144    return false;   // Publisher removes this call's temporary file, and only that
1145}
1146
1147bool write_guarded(const std::string& path, const SavedConversation& image, const std::vector<SessionKvSource>* sources,
1148                   const SessionFileIdentity& id, size_t& bytes, std::string& error, const SessionWriteOptions& opt,
1149                   SessionStatus* status) {
1150    SessionStatus st;
1151    bool ok = false;
1152    try {
1153        ok = write_impl(path, image, sources, id, bytes, error, opt, st);
1154    } catch (const std::bad_alloc&) {
1155        error = "session file: out of memory while writing " + path;
1156        st.error = SessionError::memory;
1157        ok = false;
1158    }
1159    if (status) *status = st;
1160    return ok;
1161}
1162} // namespace
1163
1164std::vector<ConversationCheckpoint> session_checkpoints_to_save(const std::vector<ConversationCheckpoint>& chain) {
1165    const ConversationCheckpoint* deepest = session_deepest_checkpoint(chain);
1166    if (!deepest) return {};
1167    return {*deepest};
1168}
1169
1170const ConversationCheckpoint* session_deepest_checkpoint(const std::vector<ConversationCheckpoint>& chain) {
1171    // A pinned shared prefix (pin=N) is the resume point the next queries want, so with one in the chain the file
1172    // keeps the deepest PINNED checkpoint, not a deeper periodic one a long private suffix made past it.  No pin:
1173    // the deepest, as before.
1174    const ConversationCheckpoint* deepest = nullptr;
1175    bool any_pinned = false;
1176    for (const auto& c : chain) any_pinned = any_pinned || c.pinned;
1177    for (const auto& c : chain)
1178        if ((!any_pinned || c.pinned) && (!deepest || c.ids.size() > deepest->ids.size())) deepest = &c;
1179    return deepest;
1180}
1181
1182uint64_t session_save_peak_bytes(const ConversationCheckpoint* deepest, const SessionSaveLive& live) {
1183    uint64_t n = sat_add(kBlock, uint64_t(1) << 20);                          // write buffer, small vectors
1184    if (deepest) n = sat_add(n, sat_mul(2, deepest->bytes()));                // the list and the image's copy
1185    n = sat_add(n, live.state_bytes);                                         // the live running state
1186    n = sat_add(n, sat_mul(live.tokens, sizeof(int32_t)));                    // its token list
1187    n = sat_add(n, sat_mul(live.images, sizeof(ConversationImageKey)));       // its images
1188    n = sat_add(n, sat_mul(live.kv_layers, sizeof(SessionKvSource) + 256));   // the K/V source directory
1189    return n;
1190}
1191
1192bool session_save_checkpoints(const std::vector<ConversationCheckpoint>& chain, const SessionSaveLive& live,
1193                              const std::function<bool(uint64_t need_bytes, std::string& why)>& admit,
1194                              std::vector<ConversationCheckpoint>& out, std::string& why) {
1195    out.clear();
1196    const ConversationCheckpoint* deepest = session_deepest_checkpoint(chain);
1197    if (admit && !admit(session_save_peak_bytes(deepest, live), why)) return false;
1198    if (deepest) out.push_back(*deepest);
1199    return true;
1200}
1201
1202int64_t session_phase_limit_s(uint64_t bytes) {
1203    return std::min<int64_t>(3600, 60 + (int64_t) std::min<uint64_t>(bytes >> 22, 3600));
1204}
1205
1206bool session_file_write(const std::string& path, const SavedConversation& meta, const std::vector<SessionKvSource>& kv,
1207                        const SessionFileIdentity& id, size_t& bytes, std::string& error,
1208                        const SessionWriteOptions& options, SessionStatus* status) {
1209    return write_guarded(path, meta, &kv, id, bytes, error, options, status);
1210}
1211
1212bool session_file_write(const std::string& path, const SavedConversation& image, const SessionFileIdentity& id,
1213                        size_t& bytes, std::string& error, const SessionWriteOptions& options, SessionStatus* status) {
1214    return write_guarded(path, image, nullptr, id, bytes, error, options, status);
1215}
1216
1217namespace {
1218bool read_impl(const std::string& path, const SessionFileIdentity& id, SavedConversation& image,
1219               size_t& bytes, std::string& error, const SessionReadLimits& limits, SessionStatus& st) {
1220    error.clear();
1221    st = {};
1222    st.error = SessionError::invalid;   // every refusal below, unless the step says otherwise
1223    RawFile raw;
1224    uint64_t size = 0;
1225    if (!raw.open_session(path, size)) {
1226        st.error = raw.refused() ? SessionError::invalid : raw.kind();
1227        error = "session file: " + path + ": " + raw.error();
1228        return false;
1229    }
1230    if (size < kHeader + kTrailer) { error = "session file: size " + std::to_string(size) + " is below the minimum"; return false; }
1231    const uint64_t max_size = session_read_max_file_bytes(limits);
1232    if (size > max_size || size > (uint64_t) std::numeric_limits<size_t>::max()) {
1233        error = "session file: size " + std::to_string(size) + " exceeds this engine's limit" +
1234                (max_size == UINT64_MAX ? std::string() : " of " + std::to_string(max_size));
1235        return false;
1236    }
1237    FileSource f(raw);
1238    if (!f.ok()) { st.error = SessionError::memory; error = "session file: " + f.error(); return false; }
1239    // installed before the first block (the header's) is read: every block reports, the first one included
1240    if (limits.progress) f.progress.emplace(limits.progress);
1241    f.expected = size;
1242    uint8_t h[kHeader];
1243    if (!f.read(h, kHeader)) { st.error = f.kind(); error = "session file: header read error: " + f.error(); return false; }
1244    uint32_t version = 0, hsize = 0;
1245    uint64_t model = 0, config = 0, payload = 0, r0 = 0, r1 = 0, hh = 0;
1246    std::memcpy(&version, h + 8, 4); std::memcpy(&hsize, h + 12, 4);
1247    std::memcpy(&model, h + 16, 8); std::memcpy(&config, h + 24, 8); std::memcpy(&payload, h + 32, 8);
1248    std::memcpy(&r0, h + 40, 8); std::memcpy(&r1, h + 48, 8); std::memcpy(&hh, h + 56, 8);
1249    if (std::memcmp(h, kMagic, 8) != 0) { error = "session file: not a Strata session file (magic)"; return false; }
1250    if (hh != session_hash64(h, 56, 0)) { error = "session file: header checksum mismatch"; return false; }
1251    if (version != kVersion && version != kVersionStages) {
1252        error = "session file: unsupported version " + std::to_string(version);
1253        return false;
1254    }
1255    if ((version == kVersionStages) != !limits.stage_limits.empty()) {
1256        error = version == kVersionStages ? "session file: saved with a layer split, this runtime runs on one GPU"
1257                                          : "session file: saved on one GPU, this runtime splits the layers";
1258        return false;
1259    }
1260    if (hsize != kHeader || r0 || r1) { error = "session file: invalid header fields"; return false; }
1261    if (model != id.model) { error = "session file: saved with another model (model fingerprint differs)"; return false; }
1262    if (config != id.config) { error = "session file: saved with another engine configuration (config fingerprint differs)"; return false; }
1263    if (payload > size || size - kHeader - kTrailer != payload) {
1264        error = "session file: size " + std::to_string(size) + " does not match the header (" +
1265                std::to_string(kHeader + payload + kTrailer) + ")";
1266        return false;
1267    }
1268    if (limits.admit) {
1269        std::string why;
1270        if (!limits.admit(session_read_peak_bytes(size), why)) {
1271            st.error = SessionError::memory;
1272            error = "session file: " + why;
1273            return false;
1274        }
1275    }
1276    SavedConversation parsed;
1277    In in{&f, SessionHasher(0), payload, error, &limits};
1278    if (!get_payload(in, parsed) || (version == kVersionStages && !get_stages(in, parsed, limits))) {
1279        st.error = in.kind;
1280        return false;
1281    }
1282    if (in.left) { error = "session file: payload has " + std::to_string(in.left) + " unparsed bytes"; return false; }
1283    uint8_t t[kTrailer];
1284    if (!f.read(t, kTrailer)) { st.error = f.kind(); error = "session file: trailer read error: " + f.error(); return false; }
1285    uint64_t ph = 0;
1286    std::memcpy(&ph, t, 8);
1287    if (ph != in.hash.digest()) { error = "session file: payload checksum mismatch"; return false; }
1288    if (std::memcmp(t + 8, kEnd, 8) != 0) { error = "session file: bad end marker"; return false; }
1289    image = std::move(parsed);
1290    bytes = (size_t) size;
1291    st.error = SessionError::none;
1292    return true;
1293}
1294} // namespace
1295
1296bool session_file_read(const std::string& path, const SessionFileIdentity& id, SavedConversation& image,
1297                       size_t& bytes, std::string& error, const SessionReadLimits& limits, SessionStatus* status) {
1298    SessionStatus st;
1299    bool ok = false;
1300    try {
1301        ok = read_impl(path, id, image, bytes, error, limits, st);
1302    } catch (const std::bad_alloc&) {
1303        error = "session file: out of memory while reading " + path;
1304        st.error = SessionError::memory;
1305        ok = false;
1306    }
1307    if (status) *status = st;
1308    return ok;
1309}
1310
1311} // namespace strata::core