session files: resolved expert inputs, runtime read bounds, published-save status, typed errors, strict protocol, UNC free space (review R1-R6)
This commit is contained in:
1 parent
71faad4f4d
commit
796bb8fc9c
12 files changed
+895
-193
No files matched your search
+24
-12
@@ -767,17 +767,23 @@ a leading dot or a trailing dot or space.
|
||||
The request must be `Content-Type: application/json` (else `415`) and come from no browser page, Strata's own or a
|
||||
trusted origin (another site's `Origin` gets `403`, also with an API key); the Host and API-key checks apply as
|
||||
everywhere. Errors: `501` without `--slot-save-path`; `400` for a slot other than 0, an unknown action, a refused
|
||||
file name, or a file the engine refuses (the reason is in `error.message`; the session is as it was); `404` for a
|
||||
restore of a missing file; `503` while the model is not loaded or when the RAM to read the file is not there; `507`
|
||||
when the disk has no room; `500` when the engine ended (a restore transfer failure, below, or an engine that said
|
||||
nothing for `engine_silence_s`) - the next request starts it again. A save or restore waits for the running request
|
||||
file name, or a file the engine refuses as invalid (not a session file, corrupt, another model or configuration, over
|
||||
this session's limits; the session is as it was); `404` for a restore of a missing file; `503` while the model is not
|
||||
loaded, when the RAM to read the file is not there or an allocation failed; `507` when the disk has no room (the
|
||||
free-space reserve, or the OS reports no space or quota); `500` for any other I/O failure (permissions, read, write,
|
||||
flush, rename) and when the engine ended (a restore transfer failure, below, an engine that said nothing for
|
||||
`engine_silence_s`, or one that answered out of protocol) - the next request starts it again. The status follows the
|
||||
engine's category (`error.kind`: `invalid`, `memory`, `storage`, `io`), never the words of the message. A save that
|
||||
failed after its new file had replaced the old one says so with `error.published: true` (below). A save or restore waits for the running request
|
||||
(the same queue), shows in `/status` and counts as activity for the idle unload. A later request whose messages
|
||||
continue the restored conversation reuses the restored state or its checkpoint; a short tail may be read again (35
|
||||
tokens in the measurement below). Only the deepest checkpoint is saved, so an edit further back reads more again.
|
||||
Clients still send their messages (and images): the file holds engine state and token/image identity, not a chat
|
||||
export. Underneath, `strata --serve` takes `SAVE <path>` and `RESTORE <path>` on stdin between requests and answers
|
||||
`SAVED <tokens> <bytes> <ms>`, `RESTORED <tokens> <bytes> <ms>`, `ERR <reason>` (refused, nothing changed) or
|
||||
`FATAL <reason>` (then exits); `SESSION <done> <total>` lines report a large file as it moves (every 256 MiB).
|
||||
`SAVED <tokens> <bytes> <ms>`, `RESTORED <tokens> <bytes> <ms>`, `SERR <kind> <published 0|1> <reason>` (failed,
|
||||
the engine and the session as they were) or `FATAL <reason>` (then exits); `SESSION <done> <total>` lines report a large
|
||||
file as it moves (at most once a second and at every 256 MiB). The server checks every line: a malformed or unknown
|
||||
one, counts that are negative or go back, or a time that is not a finite number end the engine as out of step.
|
||||
|
||||
One file holds the running state, the deepest checkpoint, every QSA layer's K/V up to the conversation's length and
|
||||
the draft layer's K/V. Format v1, little-endian, fixed-width integers, IEEE-754 floats (a big-endian build does not
|
||||
@@ -790,8 +796,10 @@ this engine wrote. An unknown version is refused; a new format gets a new versio
|
||||
|
||||
A file is bound to the model inputs and to the settings that change what the saved bytes mean. The model fingerprint
|
||||
samples (size, first and last MiB) every file the engine loads, by its role: the GGUF shards (also
|
||||
`--native-dense-gguf`, the head shards and `--embd-gguf`), the PLE shard, the pack's index/dense/embedding/expert files
|
||||
and the MTP's files - not other files in those folders, and not the path, so a moved model folder still matches. A
|
||||
`--native-dense-gguf`, the head shards and `--embd-gguf`), the PLE shard, the pack's index/dense/embedding files and
|
||||
`native_experts.txt`, every file the expert source resolved - the pack's `experts.bin`, or for a pack read in place each
|
||||
layer's gate/up/down GGUF as `native_experts.txt` names it, also one outside the CLI shards - and the MTP's files; not
|
||||
other files in those folders, and not the path, so a moved model folder still matches. A
|
||||
change in the middle of a file that keeps its size is not seen: do not change model files while their sessions are
|
||||
kept. The config fingerprint covers the engine version (an update makes older files unrestorable), CUDA or HIP,
|
||||
`--kv`, `STRATA_KV_ROT`, `--kv-resident`, `--max-context`, `--mtp-window`, the resolved rope configuration (type,
|
||||
@@ -802,11 +810,15 @@ the expert tier are not in it: they change what comes next, not what the saved c
|
||||
|
||||
A save writes a temporary file with a new hidden name beside `path` (created exclusively, never an existing file or
|
||||
link), flushes it to the disk, renames it over `path` (`MoveFileExW` on Windows, which promises no transaction on
|
||||
every filesystem) and flushes the folder; a failed save keeps the old file at `path` and removes only its own
|
||||
temporary file. A restore opens `path` without following a symbolic link (or a Windows reparse point) and refuses
|
||||
every filesystem) and flushes the folder. A save that fails before the rename keeps the old file at `path` and removes
|
||||
only its own temporary file. Once the rename is done the old file is gone: if the folder flush then fails, the save
|
||||
fails with `published` set - the new file's bytes are complete and flushed, but its name may not survive a power loss.
|
||||
A filesystem that cannot flush a folder (`EINVAL`) is not a failure; the engine logs it. A restore opens `path` without following a symbolic link (or a Windows reparse point) and refuses
|
||||
anything but a regular file with one name; it checks the size, the header, both fingerprints (before the payload is
|
||||
read), that the parsed image fits in RAM above the parking floor (`--conversation-cache-min-free-mib`), every count
|
||||
against the bytes left and this engine's limits (context, checkpoints, layers) before allocating it, the payload hash
|
||||
read), that the parse's peak (the image, the read buffer, the per-segment overhead) fits in RAM above the parking
|
||||
floor (`--conversation-cache-min-free-mib`), the file's size against the largest this session can restore, the
|
||||
geometry and layer range before any state array, and every count against the bytes left and this session's exact
|
||||
limits (context and cells, checkpoints, layers, each running-state array, each K/V part) before allocating it, the payload hash
|
||||
and then the usual snapshot validation - all before any device write, and a refusal leaves the current session as it
|
||||
was. A transfer failure after the device writes began ends the engine (`FATAL`) rather than decode from a partial
|
||||
state; the server reports `500` and starts it again. A restore does not park the outgoing session. Not supported with
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
@@ -82,63 +83,128 @@ struct SessionConfig {
|
||||
};
|
||||
uint64_t session_config_fingerprint(const SessionConfig& config);
|
||||
|
||||
// One model input the engine loaded and the role it plays ("native shard 1", "pack dense.bin", ...). The role, not
|
||||
// the path, enters the fingerprint, so a moved model folder still matches. `optional`: a missing file is recorded
|
||||
// as absent instead of failing (a pack without experts.bin).
|
||||
// One model input the engine loaded and the role it plays ("native shard 1", "expert blk.3.ffn_up", ...). The role,
|
||||
// not the path, enters the fingerprint, so a moved model folder still matches. Every (role, file) pair counts: one
|
||||
// file in two roles is two entries (its bytes are read once). `optional`: a missing file is recorded as absent
|
||||
// instead of failing (a pack without experts.bin).
|
||||
struct SessionModelFile {
|
||||
std::string role, path;
|
||||
bool optional = false;
|
||||
};
|
||||
// Sampled fingerprint of the model inputs: role, size, first and last MiB of each file, in the given order. Paths
|
||||
// are UTF-8 (wide APIs on Windows; invalid UTF-8 is refused). An edit in the middle of a file that keeps its size is
|
||||
// NOT detected: model files must not change while sessions saved with them are kept.
|
||||
bool session_model_fingerprint(const std::vector<SessionModelFile>& files, uint64_t& fingerprint, std::string& error);
|
||||
// Sampled fingerprint of the model inputs: role, size, first and last MiB of each entry, in the given order (a file
|
||||
// listed under several roles is read once). Paths are UTF-8 (wide APIs on Windows; invalid UTF-8 is refused). An
|
||||
// edit in the middle of a file that keeps its size is NOT detected: model files must not change while sessions saved
|
||||
// with them are kept. `beat` (optional) is called after each distinct file is read.
|
||||
bool session_model_fingerprint(const std::vector<SessionModelFile>& files, uint64_t& fingerprint, std::string& error,
|
||||
const std::function<void()>& beat = {});
|
||||
|
||||
// What the engine loaded, as its loaders resolved it (generate.cpp fills it). `experts`: (role, file) of the expert
|
||||
// source - the pack's experts.bin, or every expert tensor read from a GGUF in place, per layer and role, as
|
||||
// native_experts.txt resolved it (ExpertSource::model_inputs).
|
||||
struct SessionInputs {
|
||||
std::vector<std::string> native_shards, native_dense, native_head;
|
||||
std::string embedding, ple, pack, mtp;
|
||||
std::vector<std::pair<std::string, std::string>> experts;
|
||||
};
|
||||
// The fingerprint's list: every role with its file, none merged (a path in two roles is two entries).
|
||||
std::vector<SessionModelFile> session_model_inputs(const SessionInputs& inputs);
|
||||
|
||||
// Why a session file operation failed, for the caller's answer (the server maps it to an HTTP status):
|
||||
// invalid refused: not a session file, corrupt, another model or configuration, over this engine's limits, a
|
||||
// link, nothing to save (400; nothing changed)
|
||||
// storage no room on the disk: the free-space preflight, or ENOSPC / EDQUOT / EFBIG (507)
|
||||
// memory the RAM preflight refused it, or an allocation failed (503)
|
||||
// io any other failure: permissions, read/write/flush/rename errors, a missing folder (500)
|
||||
enum class SessionError { none, invalid, storage, memory, io };
|
||||
const char* session_error_name(SessionError e);
|
||||
struct SessionStatus {
|
||||
SessionError error = SessionError::none;
|
||||
// write: the new file has replaced `path` (the rename happened). Together with a failure: the file's bytes are
|
||||
// complete and flushed, but the folder flush after the rename failed, so the new name may not survive a power loss
|
||||
bool published = false;
|
||||
// write (POSIX): this filesystem cannot flush a folder (fsync EINVAL); the save succeeded without that flush
|
||||
bool dir_flush_unsupported = false;
|
||||
};
|
||||
|
||||
// Optional knobs of a write.
|
||||
struct SessionWriteOptions {
|
||||
uint64_t min_free_bytes = 0; // refuse when the disk would keep less than this free after the file
|
||||
bool durable = true; // flush the file before the rename and the directory after it
|
||||
std::function<void(uint64_t done, uint64_t total)> progress; // about every 256 MiB
|
||||
// the free-space PREFLIGHT: refused when the disk has less than the new file plus this many bytes free before the
|
||||
// write starts. Not a reservation: other writers can take the space afterwards.
|
||||
uint64_t min_free_bytes = 0;
|
||||
bool durable = true; // flush the file before the rename and (POSIX) the folder after it
|
||||
// after a 16 MiB block at most once a second, and at least at every 256 MiB boundary
|
||||
std::function<void(uint64_t done, uint64_t total)> progress;
|
||||
// tests: return an errno value to make a step fail ("write", "file_flush", "rename", "dir_flush"), 0 to go on
|
||||
std::function<int(const char* step)> fault;
|
||||
};
|
||||
|
||||
// Writes a temporary file beside `path` (a unique name, created exclusively: never an existing file or link; mode
|
||||
// 0600 on POSIX), flushes it to the disk, renames it over `path` and flushes the directory. On failure an existing
|
||||
// file at `path` is kept and only this call's own temporary file is removed.
|
||||
// Writes a temporary file beside `path` (a unique hidden name, created exclusively: never an existing file or link;
|
||||
// mode 0600 on POSIX), flushes it, renames it over `path` and, on POSIX, flushes the folder (Windows has no folder
|
||||
// flush: the rename is MoveFileExW with MOVEFILE_WRITE_THROUGH). A failure BEFORE the rename keeps an existing file
|
||||
// at `path` and removes only this call's own temporary file. A failure of the folder flush AFTER the rename returns
|
||||
// false with `status->published`: the new file is at `path` (the old one is gone), its directory entry may not
|
||||
// survive a power loss. A filesystem that cannot flush a folder (EINVAL) is not a failure; `status` says so.
|
||||
bool session_file_write(const std::string& path, const SavedConversation& image, const SessionFileIdentity& id,
|
||||
size_t& bytes, std::string& error, const SessionWriteOptions& options = {});
|
||||
size_t& bytes, std::string& error, const SessionWriteOptions& options = {},
|
||||
SessionStatus* status = nullptr);
|
||||
|
||||
// One K/V layer read straight from where it lives (device or pinned host pool) into the file's staging buffer,
|
||||
// without a full host copy first. `read(part, offset, dst, n)` copies bytes [offset, offset+n) of part
|
||||
// 0..4 = k, v, k_scale, v_scale, pooled. The file bytes are identical to writing a captured ConversationKv.
|
||||
// 0..4 = k, v, k_scale, v_scale, pooled; after a failed read `error()` (optional) says why. The file bytes are
|
||||
// identical to writing a captured ConversationKv.
|
||||
struct SessionKvSource {
|
||||
int format = 0;
|
||||
int64_t cells = 0, heads = 0, head_dim = 0, page_size = 0, pooled_rows = 0, idx_dim = 0;
|
||||
std::array<size_t, 5> sizes{};
|
||||
std::function<bool(size_t part, size_t offset, void* dst, size_t n)> read;
|
||||
std::function<std::string()> error;
|
||||
};
|
||||
// `meta` carries everything but the K/V (meta.kv must be empty); `kv` supplies the layers in order.
|
||||
bool session_file_write(const std::string& path, const SavedConversation& meta, const std::vector<SessionKvSource>& kv,
|
||||
const SessionFileIdentity& id, size_t& bytes, std::string& error,
|
||||
const SessionWriteOptions& options = {});
|
||||
const SessionWriteOptions& options = {}, SessionStatus* status = nullptr);
|
||||
|
||||
// The checkpoints worth a disk write: the deepest one (the next turn's resume point when the live tail was
|
||||
// rewritten). Earlier checkpoints only serve edits further back and cost ~118 MB each at this geometry.
|
||||
std::vector<ConversationCheckpoint> session_checkpoints_to_save(const std::vector<ConversationCheckpoint>& chain);
|
||||
|
||||
// What a read checks before it allocates. `admit(file_bytes, why)` is asked once the header and identity match and
|
||||
// before any payload allocation (the parsed image is about as large as the file); false refuses the file.
|
||||
// What a read checks before it allocates. Every count is checked against the bytes left in the payload and against
|
||||
// these limits BEFORE its array is allocated; the defaults accept whatever the payload can hold. The engine sets all
|
||||
// of them from its runtime (conversation_session_read_limits), and then the file size is bounded too.
|
||||
struct SessionReadLimits {
|
||||
uint64_t max_file_bytes = UINT64_MAX;
|
||||
uint64_t max_tokens = UINT64_MAX; // token and image counts of the live state and of each checkpoint
|
||||
uint64_t max_checkpoints = UINT64_MAX;
|
||||
uint64_t max_kv_layers = UINT64_MAX;
|
||||
std::function<bool(uint64_t file_bytes, std::string& why)> admit;
|
||||
std::function<void(uint64_t done, uint64_t total)> progress; // about every 256 MiB
|
||||
// the runtime's geometry and layer range: a file with others is refused before its state arrays are read
|
||||
std::optional<std::array<int64_t, 18>> geometry;
|
||||
std::optional<std::pair<int64_t, int64_t>> layer_range;
|
||||
// the most bytes of each running-state array (gdn, ple, tails, dead, block_pos), live and per checkpoint
|
||||
std::array<uint64_t, 5> max_state_bytes{UINT64_MAX, UINT64_MAX, UINT64_MAX, UINT64_MAX, UINT64_MAX};
|
||||
// per K/V layer (the QSA layers, then the draft): the most bytes of each part (k, v, k_scale, v_scale, pooled).
|
||||
// A layer past the end of the list is bounded by the payload only.
|
||||
std::vector<std::array<uint64_t, 5>> max_kv_bytes;
|
||||
// the RAM PREFLIGHT: asked once the header and identity match and before any payload allocation, with what the
|
||||
// parse holds at its peak (session_read_peak_bytes); false refuses the file. Not a reservation.
|
||||
std::function<bool(uint64_t need_bytes, std::string& why)> admit;
|
||||
// after a 16 MiB block at most once a second, and at least at every 256 MiB boundary
|
||||
std::function<void(uint64_t done, uint64_t total)> progress;
|
||||
};
|
||||
// The largest file these limits admit (UINT64_MAX when one of them is open); session_file_read applies it.
|
||||
uint64_t session_read_max_file_bytes(const SessionReadLimits& limits);
|
||||
// What the RAM preflight is asked for a file of `file_bytes`: the parsed image (about the payload), the 16 MiB read
|
||||
// buffer, and the per-allocation overhead of its arrays (a page per 16 MiB segment plus the small vectors).
|
||||
uint64_t session_read_peak_bytes(uint64_t file_bytes);
|
||||
// Full validation (a regular file with one link, size, header, identity, bounded parse, payload hash) before `image`
|
||||
// is replaced. The file is opened without following a symbolic link (or a reparse point) at its name, and the checks
|
||||
// are made on the opened handle. On failure `image` is unchanged.
|
||||
// are made on the opened handle. On failure `image` is unchanged and `status->error` says what kind of failure.
|
||||
bool session_file_read(const std::string& path, const SessionFileIdentity& id, SavedConversation& image,
|
||||
size_t& bytes, std::string& error, const SessionReadLimits& limits = {});
|
||||
size_t& bytes, std::string& error, const SessionReadLimits& limits = {},
|
||||
SessionStatus* status = nullptr);
|
||||
|
||||
// The folder the free-space preflight asks about for `path`, by the rules of Windows or of POSIX (exposed so both can
|
||||
// be tested anywhere). Windows: backslashes and a trailing backslash, as GetDiskFreeSpaceExW requires for a UNC
|
||||
// folder (\\server\share\dir\) and gives a drive root (C:\); empty for a bare file name (the current folder).
|
||||
std::string session_free_space_dir(const std::string& path, bool windows_rules);
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -34,6 +34,15 @@ bool conversation_kv_verify(const ConversationKv& image, const QsaState& state,
|
||||
// conversation_kv_save). Caller synchronizes the device first and keeps the state untouched while it is read.
|
||||
bool conversation_kv_source(SessionKvSource& source, const QsaState& state, const ModelGeometry& g,
|
||||
int64_t upto, bool include_index, std::string& error);
|
||||
// The bytes of each K/V part (k, v, k_scale, v_scale, pooled) a snapshot of `upto` tokens holds: no state read.
|
||||
bool conversation_kv_part_sizes(const QsaState& state, const ModelGeometry& g, int64_t upto, bool include_index,
|
||||
std::array<uint64_t, 5>& sizes, std::string& error);
|
||||
// Disk sessions: the read limits this session can ever restore - its geometry and layer range, at most
|
||||
// min(max_tokens, its cells) tokens, `max_checkpoints` checkpoints, the exact running-state sizes and the K/V part
|
||||
// sizes at that many tokens - so session_file_read refuses an oversized or foreign file before it allocates.
|
||||
bool conversation_session_read_limits(SessionReadLimits& limits, const SessionState& session, const ModelGeometry& g,
|
||||
const QsaState& draft, uint64_t max_tokens, uint64_t max_checkpoints,
|
||||
std::string& error);
|
||||
|
||||
struct ConversationStateSizes {
|
||||
size_t gdn = 0, ple = 0, tail = 0, dead = 0, block_pos = 0;
|
||||
|
||||
@@ -159,6 +159,10 @@ public:
|
||||
/// stays valid for the layer it was asked in and the next one or two; a consumer that keeps a blob longer (the
|
||||
/// prompt path's stager queues a whole chunk) copies it with `copy_blob` instead.
|
||||
virtual bool transient(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return false; }
|
||||
/// Disk sessions: the files this source read its experts from, as (role, path), resolved by the loader itself
|
||||
/// - the pack's experts.bin, or every GGUF tensor native_experts.txt named, per layer and role
|
||||
/// ("expert blk.L.ffn_up"). Filled by open(); empty before.
|
||||
const std::vector<std::pair<std::string, std::string>>& model_inputs() const { return inputs_; }
|
||||
/// The blob's bytes into `dst` (blob_bytes(layer) of them). Safe from several threads for a source whose
|
||||
/// `transient` can be true.
|
||||
virtual bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst);
|
||||
@@ -174,6 +178,11 @@ public:
|
||||
virtual void warm(int64_t layer, const int64_t* experts, int64_t n) { (void) layer; (void) experts; (void) n; }
|
||||
/// Whether `warm` does anything (the predictor is not run otherwise).
|
||||
virtual bool warms() const { return false; }
|
||||
protected:
|
||||
/// What model_inputs() returns; set by a source's open().
|
||||
void record_inputs(const std::string& pack_experts, const std::string& gguf,
|
||||
const strata::kernels::cpu::ExpertLayout& lay, bool from_gguf);
|
||||
std::vector<std::pair<std::string, std::string>> inputs_;
|
||||
};
|
||||
|
||||
/// CS-T, routing-aware prefetch of the file tier: when the CPU pool starts layer `l`, a worker thread applies layer
|
||||
|
||||
+80
-19
@@ -29,6 +29,7 @@ import hmac
|
||||
import codecs
|
||||
import ctypes
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import queue
|
||||
import re
|
||||
@@ -260,6 +261,23 @@ class EngineSilent(EngineDied):
|
||||
EngineDied, so the request ends with an error and the next one starts the engine again."""
|
||||
|
||||
|
||||
class SessionRefused(ValueError):
|
||||
"""Disk sessions: the engine refused or failed a SAVE / RESTORE and is still in step (`SERR <kind> <published>
|
||||
<reason>`). `kind` is the engine's category - invalid (400), storage (507), memory (503), io (500); `published`:
|
||||
a save whose new file already replaced the old one before a later step (the folder flush) failed."""
|
||||
|
||||
STATUS = {"invalid": 400, "storage": 507, "memory": 503, "io": 500}
|
||||
|
||||
def __init__(self, kind: str, message: str, published: bool = False):
|
||||
super().__init__(message)
|
||||
self.kind = kind if kind in self.STATUS else "io"
|
||||
self.published = published
|
||||
|
||||
@property
|
||||
def status(self) -> int:
|
||||
return self.STATUS[self.kind]
|
||||
|
||||
|
||||
class EngineStuck(RuntimeError):
|
||||
"""The engine process did not end after QUIT, terminate and kill: the server keeps it (and says so) rather than
|
||||
reporting its GPU and RAM as given back."""
|
||||
@@ -1382,10 +1400,13 @@ class StrataEngine:
|
||||
|
||||
def session_file(self, action: str, path: str) -> dict:
|
||||
"""Disk sessions: `SAVE <path>` / `RESTORE <path>` between requests (the caller holds the service FIFO).
|
||||
-> {"tokens", "bytes", "ms"}. ValueError with the engine's reason when it refused the file and the session is
|
||||
as it was; EngineDied when the engine ended (a restore transfer that failed after the device state changed
|
||||
ends it on purpose: FATAL), and EngineSilent (#481) when it printed nothing - no SESSION progress line either -
|
||||
for engine_silence_s."""
|
||||
-> {"tokens", "bytes", "ms"}. SessionRefused (kind, published) when the engine refused or failed the file and
|
||||
is still in step (`SERR <kind> <0|1> <reason>`). Any line this exchange does not allow - an unknown or
|
||||
malformed one, a bare ERR, an answer with negative counts or a non-finite time - means the two sides lost
|
||||
step: the engine is ended (EngineDied) and the next request starts it again. EngineDied also when it ended
|
||||
by itself (a restore transfer that failed after the device state changed ends it on purpose: FATAL), and
|
||||
EngineSilent (#481) when it printed nothing valid - a SESSION progress line counts only when its numbers are
|
||||
- for engine_silence_s."""
|
||||
if action not in ("save", "restore") or any(c in path for c in "\r\n\0"):
|
||||
raise ValueError("invalid session command")
|
||||
try:
|
||||
@@ -1395,7 +1416,24 @@ class StrataEngine:
|
||||
raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") from None
|
||||
silence = float(self.silence_s or 0)
|
||||
heard = time.monotonic()
|
||||
want = "SAVED " if action == "save" else "RESTORED "
|
||||
want = "SAVED" if action == "save" else "RESTORED"
|
||||
|
||||
def out_of_step(line: str) -> EngineDied:
|
||||
self.ended = True # not alive from now: the next request restarts it
|
||||
try:
|
||||
self.proc.kill()
|
||||
self.proc.wait(timeout=20)
|
||||
except (OSError, AttributeError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
return EngineDied(f"the engine answered a session {action} with {line.strip()[:200]!r}; "
|
||||
"the server ended the engine")
|
||||
|
||||
def count(s: str) -> int:
|
||||
if not s.isdigit(): # no sign, no blank, no fraction
|
||||
raise ValueError
|
||||
return int(s)
|
||||
|
||||
last_done = -1
|
||||
while True:
|
||||
left = silence - (time.monotonic() - heard) if silence > 0 else None
|
||||
try:
|
||||
@@ -1406,23 +1444,41 @@ class StrataEngine:
|
||||
raise self._silent(f"the engine said nothing for {silence:.0f} s during a session {action}") from None
|
||||
if line is None:
|
||||
raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})")
|
||||
heard = time.monotonic()
|
||||
if line.startswith("SESSION "): # a large file moving: progress, also a heartbeat
|
||||
f = line.split()
|
||||
head = f[0] if f else ""
|
||||
if head == "SESSION": # a large file moving: progress, and a heartbeat
|
||||
try:
|
||||
if len(f) != 3:
|
||||
raise ValueError
|
||||
done, total = count(f[1]), count(f[2])
|
||||
if done > total or done < last_done:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
raise out_of_step(line) from None
|
||||
last_done = done
|
||||
heard = time.monotonic()
|
||||
continue
|
||||
if line.startswith("FATAL"):
|
||||
if head == "FATAL":
|
||||
raise EngineDied(line[6:].strip() or "the engine ended during a session restore")
|
||||
if line.startswith("ERR"):
|
||||
raise ValueError(line[4:].strip())
|
||||
if line.startswith(want):
|
||||
f = line.split()
|
||||
if head == "SERR":
|
||||
parts = line.rstrip("\r\n").split(" ", 3)
|
||||
if len(parts) != 4 or parts[1] not in SessionRefused.STATUS or parts[2] not in ("0", "1"):
|
||||
raise out_of_step(line)
|
||||
raise SessionRefused(parts[1], parts[3].strip(), parts[2] == "1")
|
||||
if head == want:
|
||||
try:
|
||||
if len(f) != 4:
|
||||
raise ValueError
|
||||
return {"tokens": int(f[1]), "bytes": int(f[2]), "ms": float(f[3])}
|
||||
tokens, size, ms = count(f[1]), count(f[2]), float(f[3])
|
||||
if not math.isfinite(ms) or ms < 0:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
raise EngineDied(f"the engine answered a session {action} with {line.strip()!r}") from None
|
||||
if line.startswith(("SAVED ", "RESTORED ", "T ", "DONE")):
|
||||
raise EngineDied(f"the engine answered a session {action} with {line.strip()!r}")
|
||||
raise out_of_step(line) from None
|
||||
return {"tokens": tokens, "bytes": size, "ms": ms}
|
||||
if head == "INFO" or head == "WARN": # engine log lines may interleave; they are not answers
|
||||
heard = time.monotonic()
|
||||
continue
|
||||
raise out_of_step(line)
|
||||
|
||||
def close(self):
|
||||
"""End the engine process: QUIT first (the engine frees its memory itself - unpinning tens of GB can take
|
||||
@@ -2121,9 +2177,14 @@ class Service:
|
||||
prompt_tokens=None, generated=None, max_tokens=None)
|
||||
try:
|
||||
r = self.engine.session_file(action, path)
|
||||
except ValueError as e:
|
||||
msg = str(e)
|
||||
return error(507 if "disk space" in msg else 503 if "RAM" in msg else 400, msg)
|
||||
except SessionRefused as e:
|
||||
body = error(e.status, str(e))
|
||||
body[1]["error"]["kind"] = e.kind
|
||||
if e.published:
|
||||
body[1]["error"]["published"] = True
|
||||
return body
|
||||
except ValueError as e: # the request itself (an invalid command)
|
||||
return error(400, str(e))
|
||||
finally:
|
||||
with self.status_lock:
|
||||
self.status["busy"] = False
|
||||
|
||||
+55
-7
@@ -46,13 +46,13 @@ class FakeProc:
|
||||
return
|
||||
if cmd == "SAVE":
|
||||
if self.engine.fail:
|
||||
self.engine.lines.put("ERR no complete session to save\n")
|
||||
self.engine.lines.put("SERR invalid 0 no complete session to save\n")
|
||||
else:
|
||||
Path(path).write_bytes(b"x" * 1234)
|
||||
self.engine.lines.put("SAVED 62993 1234 401.5\n")
|
||||
elif cmd == "RESTORE":
|
||||
if not Path(path).exists() or self.engine.fail:
|
||||
self.engine.lines.put("ERR session file: saved with another model (model fingerprint differs)\n")
|
||||
self.engine.lines.put("SERR invalid 0 session file: saved with another model (model fingerprint differs)\n")
|
||||
else:
|
||||
self.engine.lines.put("RESTORED 62993 1234 560.2\n")
|
||||
elif cmd == "DIE":
|
||||
@@ -204,7 +204,7 @@ class Slots(unittest.TestCase):
|
||||
link.symlink_to(target)
|
||||
dangling = Path(self.dir.name, "dangling.bin")
|
||||
dangling.symlink_to(Path(self.dir.name, "nothing"))
|
||||
self.engine.script = ["ERR session file: x: a symbolic link, not a file\n"]
|
||||
self.engine.script = ["SERR invalid 0 session file: x: a symbolic link, not a file\n"]
|
||||
for name in ("link.bin", "dangling.bin"):
|
||||
s, b = self.post("/slots/0?action=restore", {"filename": name})
|
||||
self.assertEqual(s, 400, b)
|
||||
@@ -249,16 +249,64 @@ class Slots(unittest.TestCase):
|
||||
def test_malformed_or_mismatched_reply_is_a_server_error(self):
|
||||
for script in (["RESTORED 1 2 3\n"], ["SAVED x y z\n"], ["SAVED 1 2\n"], ["T 5\n"]):
|
||||
self.engine.script = script
|
||||
self.engine.ended = False
|
||||
self.engine.proc = FakeProc(self.engine)
|
||||
s, b = self.post("/slots/0?action=save", {"filename": "m.bin"})
|
||||
self.assertEqual(s, 500, (script, b))
|
||||
self.assertTrue(self.engine.ended, script) # out of step: the engine is ended
|
||||
|
||||
def test_out_of_protocol_lines_end_the_engine(self):
|
||||
"""R4: a line this exchange does not allow is not a heartbeat, and an answer must hold valid numbers."""
|
||||
for script in (["SESSION nonsense\n"], ["SESSION 5\n"], ["SESSION -1 10\n"], ["SESSION 11 10\n"],
|
||||
["SESSION 8 10\n", "SESSION 4 10\n"], # progress going back
|
||||
["SAVED -1 -2 nan\n"], ["SAVED 1 2 nan\n"], ["SAVED 1 2 inf\n"], ["SAVED 1 2 -5\n"],
|
||||
["SAVED +1 2 3\n"], ["ERR bare refusal\n"], ["SERR weird 0 x\n"], ["SERR io 2 x\n"],
|
||||
["SERR io\n"], ["garbage\n"]):
|
||||
self.engine.script = script
|
||||
self.engine.ended = False
|
||||
self.engine.proc = FakeProc(self.engine)
|
||||
s, b = self.post("/slots/0?action=save", {"filename": "p.bin"})
|
||||
self.assertEqual(s, 500, (script, b))
|
||||
self.assertTrue(self.engine.ended and self.engine.proc.killed, script)
|
||||
json.dumps(b, allow_nan=False) # standard JSON
|
||||
|
||||
def test_log_lines_are_not_answers(self):
|
||||
self.engine.script = ["INFO something\n", "SAVED 1 2 3.0\n"]
|
||||
s, b = self.post("/slots/0?action=save", {"filename": "i.bin"})
|
||||
self.assertEqual(s, 200, b)
|
||||
self.assertFalse(self.engine.ended)
|
||||
|
||||
def test_typed_refusals_have_their_own_codes(self):
|
||||
"""R5: the engine's category decides the status, never the words of the message."""
|
||||
cases = [("storage", "No space left on device", 507), ("storage", "espace insuffisant", 507),
|
||||
("memory", "out of memory for the write buffer", 503), ("invalid", "not enough disk space", 400),
|
||||
("invalid", "saved with another model", 400), ("io", "Permission denied", 500),
|
||||
("io", "RAM", 500)]
|
||||
for kind, msg, code in cases:
|
||||
self.engine.script = [f"SERR {kind} 0 {msg}\n"]
|
||||
s, b = self.post("/slots/0?action=save", {"filename": "k.bin"})
|
||||
self.assertEqual(s, code, (kind, msg, b))
|
||||
self.assertEqual(b["error"]["kind"], kind)
|
||||
self.assertEqual(b["error"]["message"], msg)
|
||||
self.assertNotIn("published", b["error"])
|
||||
self.assertFalse(self.engine.ended) # a refusal keeps the engine
|
||||
|
||||
def test_published_failure_is_reported(self):
|
||||
"""R3: the folder flush failed after the rename - the new file replaced the old one; the answer says so."""
|
||||
self.engine.script = ["SERR io 1 flushing the directory: Input/output error (the new file has already "
|
||||
"replaced the old one)\n"]
|
||||
s, b = self.post("/slots/0?action=save", {"filename": "pub.bin"})
|
||||
self.assertEqual(s, 500, b)
|
||||
self.assertTrue(b["error"]["published"])
|
||||
self.assertIn("replaced", b["error"]["message"])
|
||||
|
||||
def test_disk_and_ram_refusals_have_their_own_codes(self):
|
||||
self.engine.script = ["ERR session file: not enough disk space (1143 MiB plus a reserve of 4096 MiB needed, "
|
||||
"10 MiB free)\n"]
|
||||
self.engine.script = ["SERR storage 0 session file: not enough disk space (1143 MiB plus a reserve of 4096 "
|
||||
"MiB needed, 10 MiB free)\n"]
|
||||
self.assertEqual(self.post("/slots/0?action=save", {"filename": "d.bin"})[0], 507)
|
||||
Path(self.dir.name, "r.bin").write_bytes(b"x")
|
||||
self.engine.script = ["ERR session file: not enough RAM to read it (1143 MiB plus a floor of 2560 MiB needed, "
|
||||
"900 MiB available)\n"]
|
||||
self.engine.script = ["SERR memory 0 session file: not enough RAM to read it (1143 MiB plus a floor of 2560 "
|
||||
"MiB needed, 900 MiB available)\n"]
|
||||
self.assertEqual(self.post("/slots/0?action=restore", {"filename": "r.bin"})[0], 503)
|
||||
|
||||
def test_slot_work_counts_as_activity_and_shows_in_status(self):
|
||||
|
||||
+365
-95
@@ -8,6 +8,9 @@
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
#include <unordered_map>
|
||||
#include <optional>
|
||||
#include <filesystem>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
@@ -46,6 +49,36 @@ constexpr uint32_t kVersion = 1;
|
||||
constexpr size_t kHeader = 64, kTrailer = 16;
|
||||
constexpr uint64_t kProgressEvery = 256ull << 20;
|
||||
|
||||
// Progress for a large transfer: after a block when a second has passed since the last report, and always at a
|
||||
// 256 MiB boundary - so a slow disk still reports (and beats the engine's watchdog) once per 16 MiB block.
|
||||
class Ticker {
|
||||
public:
|
||||
explicit Ticker(const std::function<void(uint64_t, uint64_t)>& fn) : fn_(fn), last_(Clock::now()) {}
|
||||
void operator()(uint64_t before, uint64_t done, uint64_t total) {
|
||||
if (!fn_) return;
|
||||
const auto now = Clock::now();
|
||||
if (done / kProgressEvery == before / kProgressEvery && now - last_ < std::chrono::seconds(1)) return;
|
||||
last_ = now;
|
||||
fn_(done, total);
|
||||
}
|
||||
private:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
std::function<void(uint64_t, uint64_t)> fn_;
|
||||
Clock::time_point last_;
|
||||
};
|
||||
|
||||
SessionError errno_kind(int e) {
|
||||
switch (e) {
|
||||
case ENOSPC:
|
||||
#ifdef EDQUOT
|
||||
case EDQUOT:
|
||||
#endif
|
||||
case EFBIG: return SessionError::storage;
|
||||
case ENOMEM: return SessionError::memory;
|
||||
default: return SessionError::io;
|
||||
}
|
||||
}
|
||||
|
||||
constexpr uint64_t P1 = 0x9E3779B185EBCA87ull, P2 = 0xC2B2AE3D27D4EB4Full, P3 = 0x165667B19E3779F9ull,
|
||||
P4 = 0x85EBCA77C2B2AE63ull, P5 = 0x27D4EB2F165667C5ull;
|
||||
uint64_t rotl(uint64_t x, int r) { return (x << r) | (x >> (64 - r)); }
|
||||
@@ -89,6 +122,11 @@ std::string temp_name(const std::string& leaf) {
|
||||
return "." + leaf.substr(0, keep) + "." + hex + ".tmp";
|
||||
}
|
||||
|
||||
// a test's injected failure at `step`: its errno value (0 = none)
|
||||
int injected(const std::function<int(const char*)>* fault, const char* step) {
|
||||
return fault && *fault ? (*fault)(step) : 0;
|
||||
}
|
||||
|
||||
bool split_path(const std::string& path, std::string& dir, std::string& leaf, std::string& error) {
|
||||
const size_t cut = path.find_last_of(
|
||||
#ifdef _WIN32
|
||||
@@ -115,6 +153,14 @@ bool wide(const std::string& s, std::wstring& w) {
|
||||
return MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), (int) s.size(), w.data(), n) == n;
|
||||
}
|
||||
|
||||
SessionError win_kind(DWORD code) {
|
||||
switch (code) {
|
||||
case ERROR_DISK_FULL: case ERROR_HANDLE_DISK_FULL: case ERROR_FILE_TOO_LARGE: return SessionError::storage;
|
||||
case ERROR_NOT_ENOUGH_MEMORY: case ERROR_OUTOFMEMORY: return SessionError::memory;
|
||||
default: return SessionError::io;
|
||||
}
|
||||
}
|
||||
|
||||
std::string last_error(DWORD code = GetLastError()) {
|
||||
char msg[256] = {};
|
||||
const DWORD n = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, code, 0, msg,
|
||||
@@ -131,42 +177,43 @@ public:
|
||||
bool create_new(const std::wstring& path) {
|
||||
h_ = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW,
|
||||
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
|
||||
if (h_ == INVALID_HANDLE_VALUE) { error_ = last_error(); return false; }
|
||||
if (h_ == INVALID_HANDLE_VALUE) { { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); } return false; }
|
||||
return true;
|
||||
}
|
||||
// a session to restore: the name itself is opened, never what a link or reparse point there points to; it must be
|
||||
// an ordinary disk file with one name
|
||||
bool open_session(const std::string& path, uint64_t& size) {
|
||||
std::wstring w;
|
||||
if (!wide(path, w)) { error_ = "the path is not valid UTF-8"; return false; }
|
||||
if (!wide(path, w)) { refused_ = true; error_ = "the path is not valid UTF-8"; return false; }
|
||||
h_ = CreateFileW(w.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
|
||||
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
|
||||
if (h_ == INVALID_HANDLE_VALUE) { error_ = last_error(); return false; }
|
||||
if (h_ == INVALID_HANDLE_VALUE) { { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); } return false; }
|
||||
BY_HANDLE_FILE_INFORMATION info{};
|
||||
if (!GetFileInformationByHandle(h_, &info)) { error_ = last_error(); return false; }
|
||||
if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { error_ = "a link or reparse point, not a file"; return false; }
|
||||
if (!GetFileInformationByHandle(h_, &info)) { { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); } return false; }
|
||||
if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { refused_ = true; error_ = "a link or reparse point, not a file"; return false; }
|
||||
if ((info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || GetFileType(h_) != FILE_TYPE_DISK) {
|
||||
refused_ = true;
|
||||
error_ = "not a regular file";
|
||||
return false;
|
||||
}
|
||||
if (info.nNumberOfLinks != 1) { error_ = "the file has more than one name (hard link)"; return false; }
|
||||
if (info.nNumberOfLinks != 1) { refused_ = true; error_ = "the file has more than one name (hard link)"; return false; }
|
||||
size = (uint64_t(info.nFileSizeHigh) << 32) | info.nFileSizeLow;
|
||||
return true;
|
||||
}
|
||||
// a model input: links followed (model folders are often linked)
|
||||
bool open_model(const std::string& path, uint64_t& size) {
|
||||
std::wstring w;
|
||||
if (!wide(path, w)) { error_ = "the path is not valid UTF-8"; return false; }
|
||||
if (!wide(path, w)) { refused_ = true; error_ = "the path is not valid UTF-8"; return false; }
|
||||
h_ = CreateFileW(w.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
|
||||
nullptr);
|
||||
if (h_ == INVALID_HANDLE_VALUE) {
|
||||
const DWORD code = GetLastError();
|
||||
missing_ = code == ERROR_FILE_NOT_FOUND || code == ERROR_PATH_NOT_FOUND;
|
||||
error_ = last_error(code);
|
||||
kind_ = win_kind(code); error_ = last_error(code);
|
||||
return false;
|
||||
}
|
||||
LARGE_INTEGER s{};
|
||||
if (!GetFileSizeEx(h_, &s)) { error_ = last_error(); return false; }
|
||||
if (!GetFileSizeEx(h_, &s)) { { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); } return false; }
|
||||
size = (uint64_t) s.QuadPart;
|
||||
return true;
|
||||
}
|
||||
@@ -176,7 +223,7 @@ public:
|
||||
while (n) {
|
||||
DWORD w = 0;
|
||||
const DWORD want = (DWORD) std::min<size_t>(n, size_t(1) << 30);
|
||||
if (!WriteFile(h_, p, want, &w, nullptr) || w == 0) { error_ = last_error(); return false; }
|
||||
if (!WriteFile(h_, p, want, &w, nullptr) || w == 0) { { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); } return false; }
|
||||
p += w; n -= w;
|
||||
}
|
||||
return true;
|
||||
@@ -185,7 +232,7 @@ public:
|
||||
long long read_some(uint8_t* p, size_t n) {
|
||||
DWORD r = 0;
|
||||
if (!ReadFile(h_, p, (DWORD) std::min<size_t>(n, size_t(1) << 30), &r, nullptr)) {
|
||||
error_ = last_error();
|
||||
{ const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); }
|
||||
return -1;
|
||||
}
|
||||
return (long long) r;
|
||||
@@ -193,7 +240,7 @@ public:
|
||||
bool read_at(uint64_t offset, uint8_t* p, size_t n) {
|
||||
LARGE_INTEGER at{};
|
||||
at.QuadPart = (LONGLONG) offset;
|
||||
if (!SetFilePointerEx(h_, at, nullptr, FILE_BEGIN)) { error_ = last_error(); return false; }
|
||||
if (!SetFilePointerEx(h_, at, nullptr, FILE_BEGIN)) { { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); } return false; }
|
||||
while (n) {
|
||||
const long long r = read_some(p, n);
|
||||
if (r <= 0) { if (r == 0) error_ = "file ends early"; return false; }
|
||||
@@ -205,25 +252,30 @@ public:
|
||||
LARGE_INTEGER at{};
|
||||
at.QuadPart = (LONGLONG) n;
|
||||
if (SetFilePointerEx(h_, at, nullptr, FILE_BEGIN) && SetEndOfFile(h_)) return true;
|
||||
error_ = last_error();
|
||||
{ const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); }
|
||||
return false;
|
||||
}
|
||||
bool sync() {
|
||||
if (FlushFileBuffers(h_)) return true;
|
||||
error_ = last_error();
|
||||
{ const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); }
|
||||
return false;
|
||||
}
|
||||
bool close() {
|
||||
if (h_ == INVALID_HANDLE_VALUE) return true;
|
||||
const bool ok = CloseHandle(h_) != 0;
|
||||
if (!ok) error_ = last_error();
|
||||
if (!ok) { const DWORD c_ = GetLastError(); kind_ = win_kind(c_); error_ = last_error(c_); }
|
||||
h_ = INVALID_HANDLE_VALUE;
|
||||
return ok;
|
||||
}
|
||||
const std::string& error() const { return error_; }
|
||||
bool missing() const { return missing_; }
|
||||
SessionError kind() const { return kind_; }
|
||||
// a validation refusal (a link, not a regular file, ...): bad input, not an I/O failure
|
||||
bool refused() const { return refused_; }
|
||||
private:
|
||||
HANDLE h_ = INVALID_HANDLE_VALUE;
|
||||
SessionError kind_ = SessionError::io;
|
||||
bool refused_ = false;
|
||||
bool missing_ = false;
|
||||
std::string error_;
|
||||
};
|
||||
@@ -254,14 +306,25 @@ public:
|
||||
error = f.error();
|
||||
return false;
|
||||
}
|
||||
bool publish(std::string& error, bool) {
|
||||
bool publish(std::string& error, bool, SessionStatus& st, const std::function<int(const char*)>* fault) {
|
||||
if (const int e = injected(fault, "rename")) { error = std::strerror(e); st.error = errno_kind(e); return false; }
|
||||
if (MoveFileExW(temp_.c_str(), final_.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
|
||||
own_ = false;
|
||||
st.published = true;
|
||||
// Windows has no folder flush; a test can still make this step fail after the move
|
||||
if (const int e = injected(fault, "dir_flush")) {
|
||||
error = std::string("flushing the directory: ") + std::strerror(e);
|
||||
st.error = errno_kind(e);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
error = last_error();
|
||||
const DWORD c = GetLastError();
|
||||
st.error = win_kind(c);
|
||||
error = last_error(c);
|
||||
return false;
|
||||
}
|
||||
SessionError kind() const { return SessionError::io; }
|
||||
~Publisher() { if (own_) DeleteFileW(temp_.c_str()); } // only the temporary file this call created
|
||||
private:
|
||||
std::wstring prefix_, final_, temp_;
|
||||
@@ -270,12 +333,10 @@ private:
|
||||
};
|
||||
|
||||
bool free_space(const std::string& path, uint64_t& out) {
|
||||
std::string dir, leaf, e;
|
||||
if (!split_path(path, dir, leaf, e)) return false;
|
||||
std::wstring w;
|
||||
if (!wide(dir.empty() ? std::string(".") : dir, w)) return false;
|
||||
if (!wide(session_free_space_dir(path, true), w)) return false;
|
||||
ULARGE_INTEGER avail{};
|
||||
if (!GetDiskFreeSpaceExW(w.c_str(), &avail, nullptr, nullptr)) return false;
|
||||
if (!GetDiskFreeSpaceExW(w.empty() ? nullptr : w.c_str(), &avail, nullptr, nullptr)) return false;
|
||||
out = avail.QuadPart;
|
||||
return true;
|
||||
}
|
||||
@@ -297,7 +358,7 @@ public:
|
||||
// a new file that did not exist (O_CREAT|O_EXCL: never an existing file or link), readable by its owner only
|
||||
bool create_new(int dirfd, const std::string& name) {
|
||||
fd_ = ::openat(dirfd, name.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);
|
||||
if (fd_ < 0) { error_ = std::strerror(errno); return false; }
|
||||
if (fd_ < 0) { kind_ = errno_kind(errno); error_ = std::strerror(errno); return false; }
|
||||
try_direct();
|
||||
return true;
|
||||
}
|
||||
@@ -306,13 +367,15 @@ public:
|
||||
bool open_session(const std::string& path, uint64_t& size) {
|
||||
fd_ = ::open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC); // NONBLOCK: a FIFO cannot hang
|
||||
if (fd_ < 0) {
|
||||
refused_ = errno == ELOOP;
|
||||
kind_ = errno_kind(errno);
|
||||
error_ = errno == ELOOP ? std::string("a symbolic link, not a file") : std::string(std::strerror(errno));
|
||||
return false;
|
||||
}
|
||||
struct stat st {};
|
||||
if (::fstat(fd_, &st) != 0) { error_ = std::strerror(errno); return false; }
|
||||
if (!S_ISREG(st.st_mode)) { error_ = "not a regular file"; return false; }
|
||||
if (st.st_nlink != 1) { error_ = "the file has more than one name (hard link)"; return false; }
|
||||
if (!S_ISREG(st.st_mode)) { refused_ = true; error_ = "not a regular file"; return false; }
|
||||
if (st.st_nlink != 1) { refused_ = true; error_ = "the file has more than one name (hard link)"; return false; }
|
||||
const int fl = ::fcntl(fd_, F_GETFL);
|
||||
if (fl >= 0) ::fcntl(fd_, F_SETFL, fl & ~O_NONBLOCK);
|
||||
size = (uint64_t) st.st_size;
|
||||
@@ -322,7 +385,7 @@ public:
|
||||
// a model input: links followed (model folders are often linked)
|
||||
bool open_model(const std::string& path, uint64_t& size) {
|
||||
fd_ = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
|
||||
if (fd_ < 0) { missing_ = errno == ENOENT; error_ = std::strerror(errno); return false; }
|
||||
if (fd_ < 0) { missing_ = errno == ENOENT; kind_ = errno_kind(errno); error_ = std::strerror(errno); return false; }
|
||||
struct stat st {};
|
||||
if (::fstat(fd_, &st) != 0) { error_ = std::strerror(errno); return false; }
|
||||
if (!S_ISREG(st.st_mode)) { error_ = "not a regular file"; return false; }
|
||||
@@ -337,7 +400,7 @@ public:
|
||||
if (w < 0 && errno == EINTR) continue;
|
||||
// a filesystem that took O_DIRECT at open but refuses this transfer: nothing was written, go buffered
|
||||
if (w < 0 && errno == EINVAL && direct_ && leave_direct()) continue;
|
||||
if (w <= 0) { error_ = w < 0 ? std::strerror(errno) : "short write"; return false; }
|
||||
if (w <= 0) { kind_ = w < 0 ? errno_kind(errno) : SessionError::io; error_ = w < 0 ? std::strerror(errno) : "short write"; return false; }
|
||||
p += w; n -= (size_t) w;
|
||||
}
|
||||
return true;
|
||||
@@ -348,7 +411,7 @@ public:
|
||||
const ssize_t r = ::read(fd_, p, n);
|
||||
if (r < 0 && errno == EINTR) continue;
|
||||
if (r < 0 && errno == EINVAL && direct_ && leave_direct()) continue;
|
||||
if (r < 0) error_ = std::strerror(errno);
|
||||
if (r < 0) { kind_ = errno_kind(errno); error_ = std::strerror(errno); }
|
||||
return (long long) r;
|
||||
}
|
||||
}
|
||||
@@ -356,30 +419,35 @@ public:
|
||||
while (n) {
|
||||
const ssize_t r = ::pread(fd_, p, n, (off_t) offset);
|
||||
if (r < 0 && errno == EINTR) continue;
|
||||
if (r <= 0) { error_ = r < 0 ? std::strerror(errno) : "file ends early"; return false; }
|
||||
if (r <= 0) { kind_ = r < 0 ? errno_kind(errno) : SessionError::io; error_ = r < 0 ? std::strerror(errno) : "file ends early"; return false; }
|
||||
p += r; n -= (size_t) r; offset += (uint64_t) r;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool truncate(uint64_t n) {
|
||||
if (::ftruncate(fd_, (off_t) n) == 0) return true;
|
||||
kind_ = errno_kind(errno);
|
||||
error_ = std::strerror(errno);
|
||||
return false;
|
||||
}
|
||||
bool sync() {
|
||||
if (::fsync(fd_) == 0) return true;
|
||||
kind_ = errno_kind(errno);
|
||||
error_ = std::strerror(errno);
|
||||
return false;
|
||||
}
|
||||
bool close() {
|
||||
if (fd_ < 0) return true;
|
||||
const bool ok = ::close(fd_) == 0;
|
||||
if (!ok) error_ = std::strerror(errno);
|
||||
if (!ok) { kind_ = errno_kind(errno); error_ = std::strerror(errno); }
|
||||
fd_ = -1;
|
||||
return ok;
|
||||
}
|
||||
const std::string& error() const { return error_; }
|
||||
bool missing() const { return missing_; }
|
||||
SessionError kind() const { return kind_; }
|
||||
// a validation refusal (a link, not a regular file, ...): bad input, not an I/O failure
|
||||
bool refused() const { return refused_; }
|
||||
private:
|
||||
// O_DIRECT is switched on the open descriptor: a filesystem that refuses it (EINVAL, e.g. tmpfs) keeps buffered
|
||||
// I/O, and the file is never opened twice
|
||||
@@ -395,7 +463,8 @@ private:
|
||||
return true;
|
||||
}
|
||||
int fd_ = -1;
|
||||
bool direct_ = false, missing_ = false;
|
||||
bool direct_ = false, missing_ = false, refused_ = false;
|
||||
SessionError kind_ = SessionError::io;
|
||||
std::string error_;
|
||||
};
|
||||
|
||||
@@ -408,7 +477,11 @@ public:
|
||||
std::string dir;
|
||||
if (!split_path(path, dir, leaf_, error)) return false;
|
||||
dirfd_ = ::open(dir.empty() ? "." : dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
||||
if (dirfd_ < 0) { error = "session file: cannot open the directory of " + path + ": " + std::strerror(errno); return false; }
|
||||
if (dirfd_ < 0) {
|
||||
kind_ = errno_kind(errno);
|
||||
error = "session file: cannot open the directory of " + path + ": " + std::strerror(errno);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool create_temp(RawFile& f, std::string& error) {
|
||||
@@ -420,15 +493,28 @@ public:
|
||||
error = f.error();
|
||||
return false;
|
||||
}
|
||||
bool publish(std::string& error, bool durable) {
|
||||
if (::renameat(dirfd_, temp_.c_str(), dirfd_, leaf_.c_str()) != 0) { error = std::strerror(errno); return false; }
|
||||
bool publish(std::string& error, bool durable, SessionStatus& st, const std::function<int(const char*)>* fault) {
|
||||
int e = injected(fault, "rename");
|
||||
if (e || ::renameat(dirfd_, temp_.c_str(), dirfd_, leaf_.c_str()) != 0) {
|
||||
if (!e) e = errno;
|
||||
error = std::strerror(e);
|
||||
st.error = errno_kind(e);
|
||||
return false;
|
||||
}
|
||||
own_ = false;
|
||||
if (durable && ::fsync(dirfd_) != 0 && errno != EINVAL) { // EINVAL: this filesystem cannot flush a directory
|
||||
error = std::string("flushing the directory: ") + std::strerror(errno);
|
||||
st.published = true; // the new file is at its name now: a failure below cannot bring the old one back
|
||||
if (!durable) return true;
|
||||
e = injected(fault, "dir_flush");
|
||||
if (!e && ::fsync(dirfd_) != 0) e = errno;
|
||||
if (e == EINVAL) { st.dir_flush_unsupported = true; return true; } // this filesystem cannot flush a folder
|
||||
if (e) {
|
||||
error = std::string("flushing the directory: ") + std::strerror(e);
|
||||
st.error = errno_kind(e);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
SessionError kind() const { return kind_; }
|
||||
~Publisher() {
|
||||
if (own_) ::unlinkat(dirfd_, temp_.c_str(), 0); // only the temporary file this call created
|
||||
if (dirfd_ >= 0) ::close(dirfd_);
|
||||
@@ -437,13 +523,12 @@ private:
|
||||
int dirfd_ = -1;
|
||||
std::string leaf_, temp_;
|
||||
bool own_ = false;
|
||||
SessionError kind_ = SessionError::io;
|
||||
};
|
||||
|
||||
bool free_space(const std::string& path, uint64_t& out) {
|
||||
std::string dir, leaf, e;
|
||||
if (!split_path(path, dir, leaf, e)) return false;
|
||||
struct statvfs s {};
|
||||
if (::statvfs(dir.empty() ? "." : dir.c_str(), &s) != 0) return false;
|
||||
if (::statvfs(session_free_space_dir(path, false).c_str(), &s) != 0) return false;
|
||||
out = (uint64_t) s.f_bavail * (uint64_t) s.f_frsize;
|
||||
return true;
|
||||
}
|
||||
@@ -453,7 +538,11 @@ class FileSink {
|
||||
public:
|
||||
explicit FileSink(RawFile& f) : buf_(aligned_block()), f_(f) {}
|
||||
bool ok() const { return buf_ != nullptr; }
|
||||
std::string error() const { return buf_ ? f_.error() : std::string("out of memory for the write buffer"); }
|
||||
std::string error() const {
|
||||
if (!buf_) return "out of memory for the write buffer";
|
||||
return fault_ ? fault_msg_ : f_.error();
|
||||
}
|
||||
SessionError kind() const { return buf_ ? (fault_ ? fault_kind_ : f_.kind()) : SessionError::memory; }
|
||||
// room in the block for in-place production (avoids a staging copy)
|
||||
uint8_t* span(size_t& room) { room = kBlock - used_; return buf_.get() + used_; }
|
||||
bool commit(size_t n) { used_ += n; total_ += n; return used_ < kBlock || drain(); }
|
||||
@@ -472,25 +561,33 @@ public:
|
||||
// last block padded to the alignment for direct I/O, then the file cut back to its exact size and flushed
|
||||
bool finish(bool durable) {
|
||||
if (!f_.is_open()) return false;
|
||||
if (fault_) { f_.close(); return false; }
|
||||
const size_t padded = f_.direct() ? (used_ + kAlign - 1) / kAlign * kAlign : used_;
|
||||
std::memset(buf_.get() + used_, 0, padded - used_);
|
||||
bool ok = f_.write_all(buf_.get(), padded);
|
||||
ok = ok && (padded == used_ || f_.truncate(total_));
|
||||
if (ok && durable && flush_fault) { fail_with(flush_fault); ok = false; }
|
||||
ok = ok && (!durable || f_.sync());
|
||||
ok = f_.close() && ok;
|
||||
return ok;
|
||||
}
|
||||
std::function<void(uint64_t, uint64_t)> progress;
|
||||
std::optional<Ticker> progress;
|
||||
uint64_t expected = 0;
|
||||
int write_fault = 0, flush_fault = 0; // tests: errno values injected at the first block write / the file flush
|
||||
private:
|
||||
void fail_with(int e) { fault_ = true; fault_kind_ = errno_kind(e); fault_msg_ = std::strerror(e); }
|
||||
bool drain() {
|
||||
if (write_fault) { fail_with(write_fault); return false; }
|
||||
if (!f_.write_all(buf_.get(), used_)) return false;
|
||||
used_ = 0;
|
||||
if (progress && total_ / kProgressEvery != (total_ - kBlock) / kProgressEvery) progress(total_, expected);
|
||||
if (progress) (*progress)(total_ - kBlock, total_, expected);
|
||||
return true;
|
||||
}
|
||||
Aligned buf_;
|
||||
RawFile& f_;
|
||||
bool fault_ = false;
|
||||
SessionError fault_kind_ = SessionError::io;
|
||||
std::string fault_msg_;
|
||||
size_t used_ = 0;
|
||||
uint64_t total_ = 0;
|
||||
};
|
||||
@@ -500,6 +597,7 @@ public:
|
||||
explicit FileSource(RawFile& f) : buf_(aligned_block()), f_(f) {}
|
||||
bool ok() const { return buf_ != nullptr; }
|
||||
std::string error() const { return buf_ ? f_.error() : std::string("out of memory for the read buffer"); }
|
||||
SessionError kind() const { return buf_ ? f_.kind() : SessionError::memory; }
|
||||
bool read(void* p, size_t n) {
|
||||
uint8_t* d = static_cast<uint8_t*>(p);
|
||||
while (n) {
|
||||
@@ -510,7 +608,7 @@ public:
|
||||
}
|
||||
return true;
|
||||
}
|
||||
std::function<void(uint64_t, uint64_t)> progress;
|
||||
std::optional<Ticker> progress;
|
||||
uint64_t expected = 0;
|
||||
private:
|
||||
bool fill() {
|
||||
@@ -524,7 +622,7 @@ private:
|
||||
}
|
||||
const uint64_t before = total_;
|
||||
total_ += have_;
|
||||
if (progress && total_ / kProgressEvery != before / kProgressEvery) progress(total_, expected);
|
||||
if (progress) (*progress)(before, total_, expected);
|
||||
return have_ > 0;
|
||||
}
|
||||
Aligned buf_;
|
||||
@@ -565,7 +663,12 @@ struct Out {
|
||||
size_t room = 0;
|
||||
uint8_t* d = f->span(room);
|
||||
const size_t c = std::min(room, size - at);
|
||||
if (!s.read || !s.read(part, at, d, c)) { ok = false; read_failed = true; return; }
|
||||
if (!s.read || !s.read(part, at, d, c)) {
|
||||
ok = false;
|
||||
read_failed = true;
|
||||
if (s.error) read_error = s.error();
|
||||
return;
|
||||
}
|
||||
if (hash) hash->update(d, c);
|
||||
count(c);
|
||||
ok = ok && f->commit(c);
|
||||
@@ -573,6 +676,7 @@ struct Out {
|
||||
}
|
||||
}
|
||||
bool read_failed = false;
|
||||
std::string read_error;
|
||||
};
|
||||
|
||||
void put_kv_header(Out& o, int format, int64_t cells, int64_t heads, int64_t head_dim, int64_t page_size,
|
||||
@@ -616,10 +720,12 @@ struct In {
|
||||
uint64_t left;
|
||||
std::string& error;
|
||||
const SessionReadLimits& limits;
|
||||
SessionError kind = SessionError::invalid;
|
||||
size_t kv_layer = 0;
|
||||
bool fail(const std::string& m) { if (error.empty()) error = "session file: " + m; return false; }
|
||||
bool raw(void* p, size_t c) {
|
||||
if (c > left) return fail("payload ends early");
|
||||
if (c && !f->read(p, c)) return fail("read error: " + f->error());
|
||||
if (c && !f->read(p, c)) { kind = f->kind(); return fail("read error: " + f->error()); }
|
||||
hash.update(p, c);
|
||||
left -= c;
|
||||
return true;
|
||||
@@ -641,9 +747,10 @@ struct In {
|
||||
v.resize((size_t) n);
|
||||
return raw(v.data(), (size_t) n * sizeof(T));
|
||||
}
|
||||
bool buffer(ConversationBuffer& b) {
|
||||
bool buffer(ConversationBuffer& b, size_t part) {
|
||||
uint64_t n = 0;
|
||||
if (!count(n, 1)) return false;
|
||||
const uint64_t limit = kv_layer < limits.max_kv_bytes.size() ? limits.max_kv_bytes[kv_layer][part] : UINT64_MAX;
|
||||
if (!count(n, 1, limit)) return false;
|
||||
b = {};
|
||||
b.resize((size_t) n);
|
||||
return b.visit(0, b.size(), [&](uint8_t* p, size_t c, size_t) { return raw(p, c); });
|
||||
@@ -656,14 +763,21 @@ bool get_checkpoint(In& in, ConversationCheckpoint& c) {
|
||||
if (!in.count(n, 16, in.limits.max_tokens)) return false;
|
||||
c.imgs.resize((size_t) n);
|
||||
for (auto& k : c.imgs) if (!in.i64(k.start) || !in.u64(k.hash)) return false;
|
||||
return in.vec(c.gdn) && in.vec(c.ple) && in.vec(c.tails) && in.vec(c.dead) && in.vec(c.block_pos) &&
|
||||
in.u64(c.used);
|
||||
const auto& m = in.limits.max_state_bytes; // byte arrays: element and byte counts are the same
|
||||
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]) &&
|
||||
in.vec(c.block_pos, m[4]) && in.u64(c.used);
|
||||
}
|
||||
|
||||
bool get_payload(In& in, SavedConversation& s) {
|
||||
for (auto& g : s.geometry) if (!in.i64(g)) return false;
|
||||
// checked before any state array is read: a file of another geometry allocates nothing
|
||||
if (in.limits.geometry && *in.limits.geometry != s.geometry)
|
||||
return in.fail("saved with another model geometry than this runtime's");
|
||||
uint64_t cvec = 0;
|
||||
if (!in.i64(s.layer_lo) || !in.i64(s.layer_hi) || !in.u64(cvec)) return false;
|
||||
if (in.limits.layer_range &&
|
||||
(in.limits.layer_range->first != s.layer_lo || in.limits.layer_range->second != s.layer_hi))
|
||||
return in.fail("saved with another layer range than this runtime's");
|
||||
if (cvec > 1) return in.fail("invalid cvec flag");
|
||||
s.cvec = cvec == 1;
|
||||
if (!get_checkpoint(in, s.live)) return false;
|
||||
@@ -675,13 +789,14 @@ bool get_payload(In& in, SavedConversation& s) {
|
||||
if (!in.count(n, 96, in.limits.max_kv_layers)) return false;
|
||||
s.kv.resize((size_t) n);
|
||||
for (auto& k : s.kv) {
|
||||
in.kv_layer = (size_t) (&k - s.kv.data());
|
||||
int64_t format = 0;
|
||||
if (!in.i64(format) || !in.i64(k.cells) || !in.i64(k.heads) || !in.i64(k.head_dim) ||
|
||||
!in.i64(k.page_size) || !in.i64(k.pooled_rows) || !in.i64(k.idx_dim)) return false;
|
||||
if (format < INT32_MIN || format > INT32_MAX) return in.fail("invalid K/V format");
|
||||
k.format = (int) format;
|
||||
if (!in.buffer(k.k) || !in.buffer(k.v) || !in.buffer(k.k_scale) || !in.buffer(k.v_scale) ||
|
||||
!in.buffer(k.pooled)) return false;
|
||||
if (!in.buffer(k.k, 0) || !in.buffer(k.v, 1) || !in.buffer(k.k_scale, 2) || !in.buffer(k.v_scale, 3) ||
|
||||
!in.buffer(k.pooled, 4)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -790,42 +905,136 @@ uint64_t session_config_fingerprint(const SessionConfig& c) {
|
||||
return b.digest();
|
||||
}
|
||||
|
||||
bool session_model_fingerprint(const std::vector<SessionModelFile>& files, uint64_t& fingerprint, std::string& error) {
|
||||
const char* session_error_name(SessionError e) {
|
||||
switch (e) {
|
||||
case SessionError::none: return "none";
|
||||
case SessionError::invalid: return "invalid";
|
||||
case SessionError::storage: return "storage";
|
||||
case SessionError::memory: return "memory";
|
||||
case SessionError::io: return "io";
|
||||
}
|
||||
return "io";
|
||||
}
|
||||
|
||||
std::string session_free_space_dir(const std::string& path, bool windows_rules) {
|
||||
if (!windows_rules) {
|
||||
const size_t cut = path.find_last_of('/');
|
||||
if (cut == std::string::npos) return ".";
|
||||
return path.substr(0, cut == 0 ? 1 : cut);
|
||||
}
|
||||
std::string p = path;
|
||||
for (char& c : p) if (c == '/') c = '\\';
|
||||
const size_t cut = p.find_last_of('\\');
|
||||
if (cut == std::string::npos) {
|
||||
// "C:chat.bin" (drive-relative): the drive root answers for the same volume
|
||||
if (p.size() >= 2 && p[1] == ':') return p.substr(0, 2) + "\\";
|
||||
return std::string(); // the current folder
|
||||
}
|
||||
return p.substr(0, cut + 1); // with its trailing backslash: "\\server\share\dir\", "C:\"
|
||||
}
|
||||
|
||||
std::vector<SessionModelFile> session_model_inputs(const SessionInputs& in) {
|
||||
std::vector<SessionModelFile> f;
|
||||
for (size_t i = 0; i < in.native_shards.size(); ++i) f.push_back({"native shard " + std::to_string(i), in.native_shards[i]});
|
||||
for (size_t i = 0; i < in.native_dense.size(); ++i) f.push_back({"native dense " + std::to_string(i), in.native_dense[i]});
|
||||
for (size_t i = 0; i < in.native_head.size(); ++i) f.push_back({"native head " + std::to_string(i), in.native_head[i]});
|
||||
if (!in.embedding.empty()) f.push_back({"embedding", in.embedding});
|
||||
if (!in.ple.empty()) f.push_back({"ple", in.ple});
|
||||
if (!in.mtp.empty()) f.push_back({"mtp", in.mtp});
|
||||
if (!in.pack.empty()) f.push_back({"pack native_experts.txt", in.pack + "/native_experts.txt", true});
|
||||
for (const auto& [role, path] : in.experts) f.push_back({role, path});
|
||||
return f;
|
||||
}
|
||||
|
||||
bool session_model_fingerprint(const std::vector<SessionModelFile>& files, uint64_t& fingerprint, std::string& error,
|
||||
const std::function<void()>& beat) {
|
||||
SessionIdentityBuilder h(0x5354524154414d44ull);
|
||||
std::vector<uint8_t> buf(1u << 20);
|
||||
// a file in several roles is read once; its sample enters the fingerprint under every role
|
||||
std::unordered_map<std::string, std::pair<bool, uint64_t>> seen; // path -> (present, sample digest)
|
||||
h.u64("files", files.size());
|
||||
for (const auto& file : files) {
|
||||
RawFile f;
|
||||
uint64_t size = 0;
|
||||
if (!f.open_model(file.path, size)) {
|
||||
if (file.optional && f.missing()) { h.str("absent", file.role); continue; }
|
||||
error = "session fingerprint: " + file.role + " " + file.path + ": " + f.error();
|
||||
return false;
|
||||
auto it = seen.find(file.path);
|
||||
if (it == seen.end()) {
|
||||
RawFile f;
|
||||
uint64_t size = 0;
|
||||
std::pair<bool, uint64_t> d{false, 0};
|
||||
if (!f.open_model(file.path, size)) {
|
||||
if (!(file.optional && f.missing())) {
|
||||
error = "session fingerprint: " + file.role + " " + file.path + ": " + f.error();
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
SessionIdentityBuilder one(0x46494c4553414d50ull); // "FILESAMP"
|
||||
one.u64("size", size);
|
||||
const uint64_t head = std::min<uint64_t>(size, buf.size());
|
||||
if (!f.read_at(0, buf.data(), (size_t) head)) {
|
||||
error = "session fingerprint: reading " + file.path + ": " + f.error();
|
||||
return false;
|
||||
}
|
||||
one.bytes("head", buf.data(), (size_t) head);
|
||||
if (size > buf.size()) {
|
||||
const uint64_t tail = std::min<uint64_t>(size - head, buf.size());
|
||||
if (!f.read_at(size - tail, buf.data(), (size_t) tail)) {
|
||||
error = "session fingerprint: reading " + file.path + ": " + f.error();
|
||||
return false;
|
||||
}
|
||||
one.bytes("tail", buf.data(), (size_t) tail);
|
||||
}
|
||||
d = {true, one.digest()};
|
||||
}
|
||||
it = seen.emplace(file.path, d).first;
|
||||
if (beat) beat();
|
||||
}
|
||||
if (!it->second.first) {
|
||||
if (!file.optional) { error = "session fingerprint: " + file.role + " " + file.path + " is missing"; return false; }
|
||||
h.str("absent", file.role);
|
||||
continue;
|
||||
}
|
||||
h.str("role", file.role);
|
||||
h.u64("size", size);
|
||||
const uint64_t head = std::min<uint64_t>(size, buf.size());
|
||||
if (!f.read_at(0, buf.data(), (size_t) head)) {
|
||||
error = "session fingerprint: reading " + file.path + ": " + f.error();
|
||||
return false;
|
||||
}
|
||||
h.bytes("head", buf.data(), (size_t) head);
|
||||
if (size > buf.size()) {
|
||||
const uint64_t tail = std::min<uint64_t>(size - head, buf.size());
|
||||
if (!f.read_at(size - tail, buf.data(), (size_t) tail)) {
|
||||
error = "session fingerprint: reading " + file.path + ": " + f.error();
|
||||
return false;
|
||||
}
|
||||
h.bytes("tail", buf.data(), (size_t) tail);
|
||||
}
|
||||
h.u64("sample", it->second.second);
|
||||
}
|
||||
fingerprint = h.digest();
|
||||
return true;
|
||||
}
|
||||
|
||||
namespace {
|
||||
uint64_t sat_add(uint64_t a, uint64_t b) { return a > UINT64_MAX - b ? UINT64_MAX : a + b; }
|
||||
uint64_t sat_mul(uint64_t a, uint64_t b) { return a && b > UINT64_MAX / a ? UINT64_MAX : a * b; }
|
||||
} // namespace
|
||||
|
||||
uint64_t session_read_max_file_bytes(const SessionReadLimits& l) {
|
||||
const uint64_t open = UINT64_MAX;
|
||||
if (l.max_tokens == open || l.max_checkpoints == open || l.max_kv_layers == open) return l.max_file_bytes;
|
||||
for (uint64_t b : l.max_state_bytes) if (b == open) return l.max_file_bytes;
|
||||
if (l.max_kv_bytes.size() < l.max_kv_layers) return l.max_file_bytes;
|
||||
// one checkpoint: ids (8 + 4 per token), images (8 + 16 per image), five state arrays (8 + bytes), used (8)
|
||||
uint64_t cp = sat_add(16, sat_mul(l.max_tokens, 4 + 16));
|
||||
for (uint64_t b : l.max_state_bytes) cp = sat_add(cp, sat_add(8, b));
|
||||
cp = sat_add(cp, 8);
|
||||
uint64_t n = kHeader + kTrailer + 18 * 8 + 3 * 8; // geometry, layer range, cvec
|
||||
n = sat_add(n, cp); // live
|
||||
n = sat_add(n, sat_add(8, sat_mul(l.max_checkpoints, cp))); // checkpoints
|
||||
n = sat_add(n, 8);
|
||||
for (uint64_t i = 0; i < l.max_kv_layers; ++i) {
|
||||
n = sat_add(n, 7 * 8);
|
||||
for (uint64_t b : l.max_kv_bytes[(size_t) i]) n = sat_add(n, sat_add(8, b));
|
||||
}
|
||||
return std::min(n, l.max_file_bytes);
|
||||
}
|
||||
|
||||
uint64_t session_read_peak_bytes(uint64_t file_bytes) {
|
||||
const uint64_t segments = file_bytes / kBlock + 1;
|
||||
// the parsed image (about the payload), the read buffer, a page per buffer segment, the small vectors
|
||||
return sat_add(sat_add(sat_add(file_bytes, kBlock), sat_mul(segments, 4096)), uint64_t(1) << 20);
|
||||
}
|
||||
|
||||
namespace {
|
||||
bool write_impl(const std::string& path, const SavedConversation& image, const std::vector<SessionKvSource>* sources,
|
||||
const SessionFileIdentity& id, size_t& bytes, std::string& error, const SessionWriteOptions& opt) {
|
||||
const SessionFileIdentity& id, size_t& bytes, std::string& error, const SessionWriteOptions& opt,
|
||||
SessionStatus& st) {
|
||||
st = {};
|
||||
st.error = SessionError::invalid; // refusals before any disk access
|
||||
if (has_stage_parts(image)) { error = "session file: layer-split state cannot be saved"; return false; }
|
||||
if (sources && !image.kv.empty()) { error = "session file: K/V given both in the image and as sources"; return false; }
|
||||
Out sizing;
|
||||
@@ -836,10 +1045,12 @@ bool write_impl(const std::string& path, const SavedConversation& image, const s
|
||||
return false;
|
||||
}
|
||||
const uint64_t payload = sizing.n, total = kHeader + payload + kTrailer;
|
||||
st.error = SessionError::io;
|
||||
if (opt.min_free_bytes) {
|
||||
uint64_t avail = 0;
|
||||
if (!free_space(path, avail)) { error = "session file: cannot read the free disk space for " + path; return false; }
|
||||
if (avail < total || avail - total < opt.min_free_bytes) {
|
||||
st.error = SessionError::storage;
|
||||
error = "session file: not enough disk space (" + std::to_string(total >> 20) + " MiB plus a reserve of " +
|
||||
std::to_string(opt.min_free_bytes >> 20) + " MiB needed, " + std::to_string(avail >> 20) +
|
||||
" MiB free)";
|
||||
@@ -847,13 +1058,20 @@ bool write_impl(const std::string& path, const SavedConversation& image, const s
|
||||
}
|
||||
}
|
||||
Publisher pub;
|
||||
if (!pub.open(path, error)) return false;
|
||||
if (!pub.open(path, error)) { st.error = pub.kind(); return false; }
|
||||
RawFile raw;
|
||||
if (!pub.create_temp(raw, error)) { error = "session file: cannot create a temporary file beside " + path + ": " + error; return false; }
|
||||
if (!pub.create_temp(raw, error)) {
|
||||
st.error = raw.kind();
|
||||
error = "session file: cannot create a temporary file beside " + path + ": " + error;
|
||||
return false;
|
||||
}
|
||||
FileSink f(raw);
|
||||
if (!f.ok()) { error = "session file: " + f.error(); return false; }
|
||||
f.progress = opt.progress;
|
||||
if (!f.ok()) { st.error = SessionError::memory; error = "session file: " + f.error(); return false; }
|
||||
if (opt.progress) f.progress.emplace(opt.progress);
|
||||
f.expected = total;
|
||||
const std::function<int(const char*)>* fault = opt.fault ? &opt.fault : nullptr;
|
||||
f.write_fault = injected(fault, "write");
|
||||
f.flush_fault = injected(fault, "file_flush");
|
||||
uint8_t h[kHeader];
|
||||
header_bytes(h, id, payload);
|
||||
bool ok = f.write(h, kHeader);
|
||||
@@ -866,14 +1084,36 @@ bool write_impl(const std::string& path, const SavedConversation& image, const s
|
||||
ok = f.write(&ph, 8) && f.write(kEnd, 8);
|
||||
}
|
||||
ok = f.finish(opt.durable) && ok;
|
||||
std::string why = out.read_failed ? std::string("K/V source read") : f.error();
|
||||
if (ok && pub.publish(why, opt.durable)) {
|
||||
std::string why;
|
||||
if (!ok) {
|
||||
why = out.read_failed ? "K/V source read" + (out.read_error.empty() ? std::string() : ": " + out.read_error)
|
||||
: f.error();
|
||||
st.error = out.read_failed ? SessionError::io : f.kind();
|
||||
} else if (pub.publish(why, opt.durable, st, fault)) {
|
||||
st.error = SessionError::none;
|
||||
bytes = (size_t) total;
|
||||
return true;
|
||||
}
|
||||
error = "session file: writing " + path + " failed" + (why.empty() ? std::string() : ": " + why);
|
||||
if (st.published) error += " (the new file has already replaced the old one; its folder entry may not survive a power loss)";
|
||||
return false; // Publisher removes this call's temporary file, and only that
|
||||
}
|
||||
|
||||
bool write_guarded(const std::string& path, const SavedConversation& image, const std::vector<SessionKvSource>* sources,
|
||||
const SessionFileIdentity& id, size_t& bytes, std::string& error, const SessionWriteOptions& opt,
|
||||
SessionStatus* status) {
|
||||
SessionStatus st;
|
||||
bool ok = false;
|
||||
try {
|
||||
ok = write_impl(path, image, sources, id, bytes, error, opt, st);
|
||||
} catch (const std::bad_alloc&) {
|
||||
error = "session file: out of memory while writing " + path;
|
||||
st.error = SessionError::memory;
|
||||
ok = false;
|
||||
}
|
||||
if (status) *status = st;
|
||||
return ok;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::vector<ConversationCheckpoint> session_checkpoints_to_save(const std::vector<ConversationCheckpoint>& chain) {
|
||||
@@ -886,30 +1126,39 @@ std::vector<ConversationCheckpoint> session_checkpoints_to_save(const std::vecto
|
||||
|
||||
bool session_file_write(const std::string& path, const SavedConversation& meta, const std::vector<SessionKvSource>& kv,
|
||||
const SessionFileIdentity& id, size_t& bytes, std::string& error,
|
||||
const SessionWriteOptions& options) {
|
||||
return write_impl(path, meta, &kv, id, bytes, error, options);
|
||||
const SessionWriteOptions& options, SessionStatus* status) {
|
||||
return write_guarded(path, meta, &kv, id, bytes, error, options, status);
|
||||
}
|
||||
|
||||
bool session_file_write(const std::string& path, const SavedConversation& image, const SessionFileIdentity& id,
|
||||
size_t& bytes, std::string& error, const SessionWriteOptions& options) {
|
||||
return write_impl(path, image, nullptr, id, bytes, error, options);
|
||||
size_t& bytes, std::string& error, const SessionWriteOptions& options, SessionStatus* status) {
|
||||
return write_guarded(path, image, nullptr, id, bytes, error, options, status);
|
||||
}
|
||||
|
||||
bool session_file_read(const std::string& path, const SessionFileIdentity& id, SavedConversation& image,
|
||||
size_t& bytes, std::string& error, const SessionReadLimits& limits) {
|
||||
namespace {
|
||||
bool read_impl(const std::string& path, const SessionFileIdentity& id, SavedConversation& image,
|
||||
size_t& bytes, std::string& error, const SessionReadLimits& limits, SessionStatus& st) {
|
||||
error.clear();
|
||||
st = {};
|
||||
st.error = SessionError::invalid; // every refusal below, unless the step says otherwise
|
||||
RawFile raw;
|
||||
uint64_t size = 0;
|
||||
if (!raw.open_session(path, size)) { error = "session file: " + path + ": " + raw.error(); return false; }
|
||||
if (!raw.open_session(path, size)) {
|
||||
st.error = raw.refused() ? SessionError::invalid : raw.kind();
|
||||
error = "session file: " + path + ": " + raw.error();
|
||||
return false;
|
||||
}
|
||||
if (size < kHeader + kTrailer) { error = "session file: size " + std::to_string(size) + " is below the minimum"; return false; }
|
||||
if (size > limits.max_file_bytes || size > (uint64_t) std::numeric_limits<size_t>::max()) {
|
||||
error = "session file: size " + std::to_string(size) + " exceeds this engine's limit";
|
||||
const uint64_t max_size = session_read_max_file_bytes(limits);
|
||||
if (size > max_size || size > (uint64_t) std::numeric_limits<size_t>::max()) {
|
||||
error = "session file: size " + std::to_string(size) + " exceeds this engine's limit" +
|
||||
(max_size == UINT64_MAX ? std::string() : " of " + std::to_string(max_size));
|
||||
return false;
|
||||
}
|
||||
FileSource f(raw);
|
||||
if (!f.ok()) { error = "session file: " + f.error(); return false; }
|
||||
if (!f.ok()) { st.error = SessionError::memory; error = "session file: " + f.error(); return false; }
|
||||
uint8_t h[kHeader];
|
||||
if (!f.read(h, kHeader)) { error = "session file: header read error"; return false; }
|
||||
if (!f.read(h, kHeader)) { st.error = f.kind(); error = "session file: header read error: " + f.error(); return false; }
|
||||
uint32_t version = 0, hsize = 0;
|
||||
uint64_t model = 0, config = 0, payload = 0, r0 = 0, r1 = 0, hh = 0;
|
||||
std::memcpy(&version, h + 8, 4); std::memcpy(&hsize, h + 12, 4);
|
||||
@@ -928,23 +1177,44 @@ bool session_file_read(const std::string& path, const SessionFileIdentity& id, S
|
||||
}
|
||||
if (limits.admit) {
|
||||
std::string why;
|
||||
if (!limits.admit(size, why)) { error = "session file: " + why; return false; }
|
||||
if (!limits.admit(session_read_peak_bytes(size), why)) {
|
||||
st.error = SessionError::memory;
|
||||
error = "session file: " + why;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
f.progress = limits.progress;
|
||||
if (limits.progress) f.progress.emplace(limits.progress);
|
||||
f.expected = size;
|
||||
SavedConversation parsed;
|
||||
In in{&f, SessionHasher(0), payload, error, limits};
|
||||
if (!get_payload(in, parsed)) return false;
|
||||
if (!get_payload(in, parsed)) { st.error = in.kind; return false; }
|
||||
if (in.left) { error = "session file: payload has " + std::to_string(in.left) + " unparsed bytes"; return false; }
|
||||
uint8_t t[kTrailer];
|
||||
if (!f.read(t, kTrailer)) { error = "session file: trailer read error"; return false; }
|
||||
if (!f.read(t, kTrailer)) { st.error = f.kind(); error = "session file: trailer read error: " + f.error(); return false; }
|
||||
uint64_t ph = 0;
|
||||
std::memcpy(&ph, t, 8);
|
||||
if (ph != in.hash.digest()) { error = "session file: payload checksum mismatch"; return false; }
|
||||
if (std::memcmp(t + 8, kEnd, 8) != 0) { error = "session file: bad end marker"; return false; }
|
||||
image = std::move(parsed);
|
||||
bytes = (size_t) size;
|
||||
st.error = SessionError::none;
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool session_file_read(const std::string& path, const SessionFileIdentity& id, SavedConversation& image,
|
||||
size_t& bytes, std::string& error, const SessionReadLimits& limits, SessionStatus* status) {
|
||||
SessionStatus st;
|
||||
bool ok = false;
|
||||
try {
|
||||
ok = read_impl(path, id, image, bytes, error, limits, st);
|
||||
} catch (const std::bad_alloc&) {
|
||||
error = "session file: out of memory while reading " + path;
|
||||
st.error = SessionError::memory;
|
||||
ok = false;
|
||||
}
|
||||
if (status) *status = st;
|
||||
return ok;
|
||||
}
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "strata/core/conversation_file.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
@@ -11,6 +12,7 @@
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#ifndef _WIN32
|
||||
#include <sys/stat.h>
|
||||
@@ -395,7 +397,8 @@ int main() {
|
||||
l = {};
|
||||
uint64_t asked = 0;
|
||||
l.admit = [&](uint64_t n, std::string& why) { asked = n; why = "no room for it"; return false; };
|
||||
check(rejects(good, id, "no room", l) && asked == image.size(), "admission sees the file size and can refuse");
|
||||
check(rejects(good, id, "no room", l) && asked == session_read_peak_bytes(image.size()) &&
|
||||
asked > image.size(), "admission sees the parse's peak (more than the file) and can refuse");
|
||||
l = {};
|
||||
bool admitted = false;
|
||||
l.admit = [&](uint64_t, std::string&) { admitted = true; return true; };
|
||||
@@ -436,6 +439,144 @@ int main() {
|
||||
check(slurp(p) == image, "keep: the previous session survives a failed write");
|
||||
check(slurp(planted) == std::vector<char>(5, 'p') && no_temp(dir), "keep: no other file touched");
|
||||
}
|
||||
// R1: the input list carries every expert file the loader resolved, per (layer, role) - a GGUF that only
|
||||
// native_experts.txt names changes the fingerprint when it changes; one file in two roles is two entries
|
||||
{
|
||||
const fs::path g1 = dir / "ext-a.gguf", g2 = dir / "ext-b.gguf";
|
||||
spit(g1, std::vector<char>(4096, 'g'));
|
||||
spit(g2, std::vector<char>(4096, 'h'));
|
||||
SessionInputs in;
|
||||
in.native_shards = {g1.string()};
|
||||
in.experts = {{"expert blk.0.ffn_gate", g1.string()}, {"expert blk.0.ffn_up", g2.string()},
|
||||
{"expert blk.0.ffn_down", g2.string()}};
|
||||
const auto list = session_model_inputs(in);
|
||||
check(list.size() == 4, "inputs: shard plus three expert roles, none merged");
|
||||
uint64_t a = 0, b = 0, c = 0;
|
||||
check(session_model_fingerprint(list, a, error), "inputs: fingerprint");
|
||||
auto d = slurp(g2); d[0] = 'X'; spit(g2, d); // the expert-only file changes; the CLI shard does not
|
||||
check(session_model_fingerprint(list, b, error) && a != b, "inputs: an expert-only GGUF enters the fingerprint");
|
||||
SessionInputs swapped = in;
|
||||
std::swap(swapped.experts[0].second, swapped.experts[1].second);
|
||||
check(session_model_fingerprint(session_model_inputs(swapped), c, error) && c != b,
|
||||
"inputs: the role each expert file plays enters the fingerprint");
|
||||
}
|
||||
// R2: runtime limits bound every array before it is allocated, and the file size follows from them
|
||||
{
|
||||
auto exact = [&] {
|
||||
SessionReadLimits l;
|
||||
l.max_tokens = 1000; l.max_checkpoints = 2; l.max_kv_layers = 3;
|
||||
l.geometry = original.geometry;
|
||||
l.layer_range = std::make_pair(original.layer_lo, original.layer_hi);
|
||||
l.max_state_bytes = {4099, 77, 301, 64, 8};
|
||||
for (const auto& k : original.kv)
|
||||
l.max_kv_bytes.push_back({k.k.size(), k.v.size(), k.k_scale.size(), k.v_scale.size(), k.pooled.size()});
|
||||
return l;
|
||||
};
|
||||
SavedConversation back;
|
||||
size_t n = 0;
|
||||
check(session_file_read(good.string(), id, back, n, error, exact()) && same(back, original),
|
||||
"limits: a file within the exact runtime limits reads");
|
||||
check(session_read_max_file_bytes(exact()) >= image.size() &&
|
||||
session_read_max_file_bytes(exact()) < UINT64_MAX, "limits: the runtime limits bound the file size");
|
||||
check(session_read_max_file_bytes(SessionReadLimits{}) == UINT64_MAX, "limits: open limits leave it open");
|
||||
auto l = exact(); l.max_state_bytes[0] = 4098;
|
||||
check(rejects(good, id, "limit", l), "limits: a GDN state over the runtime size refused");
|
||||
l = exact(); l.max_state_bytes[4] = 7;
|
||||
check(rejects(good, id, "limit", l), "limits: block_pos over the runtime size refused");
|
||||
l = exact(); l.max_kv_bytes[0][0] = original.kv[0].k.size() - 1;
|
||||
check(rejects(good, id, "limit", l), "limits: a K buffer over the runtime size refused");
|
||||
l = exact(); l.max_kv_bytes[2][1] = original.kv[2].v.size() - 1;
|
||||
check(rejects(good, id, "limit", l), "limits: the draft's V over the runtime size refused");
|
||||
l = exact(); (*l.geometry)[3] ^= 1;
|
||||
check(rejects(good, id, "geometry", l), "limits: another geometry refused before the state is read");
|
||||
l = exact(); l.layer_range = std::make_pair(int64_t(0), int64_t(24));
|
||||
check(rejects(good, id, "layer", l), "limits: another layer range refused");
|
||||
// a huge count in a state array with a recomputed hash: refused by the bound, nothing allocated
|
||||
auto d = image;
|
||||
// live: ids count (8) + 1000*4, imgs count (8) + 1*16, then the gdn byte count
|
||||
const size_t at = 64 + 21 * 8 + 8 + 1000 * 4 + 8 + 16;
|
||||
uint64_t was = 0; std::memcpy(&was, d.data() + at, 8);
|
||||
check(was == 4099, "limits: test offset finds the GDN count");
|
||||
uint64_t huge = 3ull << 30; std::memcpy(d.data() + at, &huge, 8);
|
||||
uint64_t payload = 0; std::memcpy(&payload, d.data() + 32, 8);
|
||||
const uint64_t h = session_hash64(d.data() + 64, payload, 0);
|
||||
std::memcpy(d.data() + 64 + payload, &h, 8);
|
||||
const fs::path p = dir / "bigstate.bin"; spit(p, d);
|
||||
check(rejects(p, id, nullptr, exact()), "limits: an oversized state count refused before allocation");
|
||||
// status kinds of a read
|
||||
SessionStatus st;
|
||||
check(!session_file_read(p.string(), id, back, n, error, exact(), &st) && st.error == SessionError::invalid,
|
||||
"status: a bad file is 'invalid'");
|
||||
l = exact();
|
||||
l.admit = [](uint64_t, std::string& why) { why = "no RAM"; return false; };
|
||||
check(!session_file_read(good.string(), id, back, n, error, l, &st) && st.error == SessionError::memory,
|
||||
"status: the RAM preflight is 'memory'");
|
||||
}
|
||||
// R3/R5: injected failures at each write step - kind, publication and the old file
|
||||
{
|
||||
const fs::path p = dir / "fault.bin";
|
||||
const std::vector<char> old(10, 'q');
|
||||
struct Case { const char* step; int err; SessionError kind; bool published; };
|
||||
for (const Case c : {Case{"write", ENOSPC, SessionError::storage, false},
|
||||
#ifdef EDQUOT
|
||||
Case{"write", EDQUOT, SessionError::storage, false},
|
||||
#endif
|
||||
Case{"write", EIO, SessionError::io, false},
|
||||
Case{"file_flush", EIO, SessionError::io, false},
|
||||
Case{"rename", EACCES, SessionError::io, false},
|
||||
Case{"dir_flush", EIO, SessionError::io, true}}) {
|
||||
spit(p, old);
|
||||
SessionWriteOptions opt;
|
||||
const std::string want = c.step;
|
||||
const int code = c.err;
|
||||
opt.fault = [want, code](const char* step) { return want == step ? code : 0; };
|
||||
SessionStatus st;
|
||||
const bool ok = session_file_write(p.string(), original, id, written, error, opt, &st);
|
||||
check(!ok && st.error == c.kind, "fault: the failure has its kind");
|
||||
check(st.published == c.published, "fault: publication reported exactly");
|
||||
if (c.published) {
|
||||
check(slurp(p) == image && error.find("replaced") != std::string::npos,
|
||||
"fault: after a published failure the new file is there and the error says so");
|
||||
} else {
|
||||
check(slurp(p) == old, "fault: a failure before the rename keeps the old file");
|
||||
}
|
||||
check(no_temp(dir), "fault: no temporary left behind");
|
||||
}
|
||||
#ifndef _WIN32
|
||||
// a filesystem that cannot flush a folder: saved, and said
|
||||
spit(p, old);
|
||||
SessionWriteOptions opt;
|
||||
opt.fault = [](const char* step) { return std::string(step) == "dir_flush" ? EINVAL : 0; };
|
||||
SessionStatus st;
|
||||
check(session_file_write(p.string(), original, id, written, error, opt, &st) && st.dir_flush_unsupported &&
|
||||
slurp(p) == image, "fault: EINVAL on the folder flush is not a failure, and is reported");
|
||||
#endif
|
||||
// the free-space preflight is 'storage'
|
||||
SessionWriteOptions big;
|
||||
big.min_free_bytes = UINT64_MAX / 2;
|
||||
SessionStatus st2;
|
||||
check(!session_file_write(p.string(), original, id, written, error, big, &st2) &&
|
||||
st2.error == SessionError::storage, "status: the free-space preflight is 'storage'");
|
||||
check(std::string(session_error_name(SessionError::storage)) == "storage" &&
|
||||
std::string(session_error_name(SessionError::memory)) == "memory" &&
|
||||
std::string(session_error_name(SessionError::invalid)) == "invalid" &&
|
||||
std::string(session_error_name(SessionError::io)) == "io", "status: protocol names");
|
||||
}
|
||||
// R6: the folder the free-space query is asked about
|
||||
{
|
||||
check(session_free_space_dir("\\\\server\\share\\sessions\\chat.bin", true) == "\\\\server\\share\\sessions\\",
|
||||
"free space: UNC subfolder keeps its trailing backslash");
|
||||
check(session_free_space_dir("\\\\server\\share\\chat.bin", true) == "\\\\server\\share\\",
|
||||
"free space: UNC share root keeps its trailing backslash");
|
||||
check(session_free_space_dir("//server/share/s/chat.bin", true) == "\\\\server\\share\\s\\",
|
||||
"free space: forward slashes become backslashes");
|
||||
check(session_free_space_dir("C:\\chat.bin", true) == "C:\\", "free space: drive root");
|
||||
check(session_free_space_dir("C:chat.bin", true) == "C:\\", "free space: drive-relative name");
|
||||
check(session_free_space_dir("chat.bin", true).empty(), "free space: bare name is the current folder");
|
||||
check(session_free_space_dir("/a/b/chat.bin", false) == "/a/b", "free space: POSIX folder");
|
||||
check(session_free_space_dir("/chat.bin", false) == "/", "free space: POSIX root");
|
||||
check(session_free_space_dir("chat.bin", false) == ".", "free space: POSIX bare name");
|
||||
}
|
||||
#ifndef _WIN32
|
||||
// what restore will not open: a symbolic link, a hard-linked file, a FIFO, a directory
|
||||
{
|
||||
|
||||
@@ -224,6 +224,14 @@ bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, co
|
||||
return false;
|
||||
}
|
||||
|
||||
bool conversation_kv_part_sizes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index,
|
||||
std::array<uint64_t, 5>& sizes, std::string& error) {
|
||||
Layout l{};
|
||||
if (!layout(st, g, upto, index, l, error)) return false;
|
||||
sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
|
||||
return true;
|
||||
}
|
||||
|
||||
bool conversation_kv_source(SessionKvSource& out, const QsaState& st, const ModelGeometry& g,
|
||||
int64_t upto, bool index, std::string& error) {
|
||||
Layout l{};
|
||||
@@ -234,11 +242,12 @@ bool conversation_kv_source(SessionKvSource& out, const QsaState& st, const Mode
|
||||
s.sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
|
||||
const auto src = pools(st);
|
||||
const auto sizes = s.sizes;
|
||||
s.read = [src, sizes](size_t part, size_t offset, void* dst, size_t n) {
|
||||
if (part >= 5 || offset > sizes[part] || n > sizes[part] - offset) return false;
|
||||
std::string ignored;
|
||||
return transfer(dst, src[part] ? static_cast<const uint8_t*>(src[part]) + offset : nullptr, n, ignored);
|
||||
auto why = std::make_shared<std::string>();
|
||||
s.read = [src, sizes, why](size_t part, size_t offset, void* dst, size_t n) {
|
||||
if (part >= 5 || offset > sizes[part] || n > sizes[part] - offset) { *why = "K/V read out of range"; return false; }
|
||||
return transfer(dst, src[part] ? static_cast<const uint8_t*>(src[part]) + offset : nullptr, n, *why);
|
||||
};
|
||||
s.error = [why] { return *why; };
|
||||
out = std::move(s);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -294,6 +294,37 @@ bool conversation_snapshot_sources(SavedConversation& meta, std::vector<SessionK
|
||||
return true;
|
||||
}
|
||||
|
||||
bool conversation_session_read_limits(SessionReadLimits& limits, const SessionState& ss, const ModelGeometry& g,
|
||||
const QsaState& draft, uint64_t max_tokens, uint64_t max_checkpoints,
|
||||
std::string& error) {
|
||||
ConversationStateSizes z;
|
||||
if (!conversation_session_sizes(g, ss, z, error)) return false;
|
||||
if (ss.max_cells < 0) return fail(error, "invalid session cells");
|
||||
const uint64_t tokens = std::min<uint64_t>(max_tokens, (uint64_t) ss.max_cells);
|
||||
const size_t layers = owned_qsa(ss);
|
||||
if ((owned_qsa(ss) && !ss.qsa_states)) return fail(error, "invalid session running-state targets");
|
||||
size_t tails = 0, dead = 0, block_pos = 0;
|
||||
if (!product(tails, {layers, z.tail}) || !product(dead, {layers, z.dead}) ||
|
||||
!product(block_pos, {layers, z.block_pos})) return fail(error, "indexer byte count overflow");
|
||||
SessionReadLimits l = limits; // keeps the caller's admit / progress / max_file_bytes
|
||||
l.max_tokens = tokens;
|
||||
l.max_checkpoints = max_checkpoints;
|
||||
l.max_kv_layers = layers + 1;
|
||||
l.geometry = geometry_key(g);
|
||||
l.layer_range = std::make_pair(ss.layer_lo, ss.layer_hi);
|
||||
l.max_state_bytes = {z.gdn, ss.ple_hist ? z.ple : 0, tails, dead, block_pos};
|
||||
l.max_kv_bytes.assign(layers + 1, {});
|
||||
for (size_t j = 0; j < layers; ++j) {
|
||||
const auto& st = owned(ss, j);
|
||||
const int64_t upto = (int64_t) std::min<uint64_t>(tokens, (uint64_t) std::max<int64_t>(st.max_cells, 0));
|
||||
if (!conversation_kv_part_sizes(st, g, upto, true, l.max_kv_bytes[j], error)) return false;
|
||||
}
|
||||
const int64_t dupto = (int64_t) std::min<uint64_t>(tokens, (uint64_t) std::max<int64_t>(draft.max_cells, 0));
|
||||
if (!conversation_kv_part_sizes(draft, g, dupto, false, l.max_kv_bytes.back(), error)) return false;
|
||||
limits = std::move(l);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& ss,
|
||||
const ModelGeometry& g, const QsaState* draft, std::string& error) {
|
||||
if (!image.live.stage_parts.empty())
|
||||
|
||||
@@ -495,6 +495,7 @@ bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64
|
||||
layer_offsets_ = std::move(layer_offsets);
|
||||
layer_blob_bytes_ = std::move(layer_blob_bytes);
|
||||
if (!open_gguf(err)) { close(); return false; }
|
||||
record_inputs(path, gguf_, layout, true);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -582,10 +583,12 @@ bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64
|
||||
mapped_bytes_ = want;
|
||||
layer_offsets_ = std::move(layer_offsets);
|
||||
layer_blob_bytes_ = std::move(layer_blob_bytes);
|
||||
record_inputs(path, gguf_, layout, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
void FileExpertSource::close() {
|
||||
inputs_.clear();
|
||||
if (complement_arena_ != nullptr) {
|
||||
if (complement_pinned_ && !complement_partial_) (void) cudaFreeHost(complement_arena_);
|
||||
else {
|
||||
@@ -2908,6 +2911,17 @@ std::string expert_gguf_file(const std::string& gguf, const strata::kernels::cpu
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void ExpertSource::record_inputs(const std::string& pack_experts, const std::string& gguf,
|
||||
const strata::kernels::cpu::ExpertLayout& lay, bool from_gguf) {
|
||||
static const char* roles[3] = {"gate", "up", "down"};
|
||||
inputs_.clear();
|
||||
if (!from_gguf) { inputs_.push_back({"pack experts.bin", pack_experts}); return; }
|
||||
// the same resolution open_gguf / load_experts_gguf use: every (layer, role) tensor and the file it is read from
|
||||
for (int64_t l = 0; l < lay.n_layers; ++l)
|
||||
for (int r = 0; r < 3; ++r)
|
||||
inputs_.push_back({"expert blk." + std::to_string(l) + ".ffn_" + roles[r], expert_gguf_file(gguf, lay, l, r)});
|
||||
}
|
||||
|
||||
bool check_experts_gguf(const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, std::string& err) {
|
||||
static const char* roles[3] = {"gate", "up", "down"};
|
||||
if (lay.gguf_off.size() != (size_t) (3 * lay.n_layers)) {
|
||||
@@ -3378,6 +3392,7 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6
|
||||
load_seconds_ = st.seconds;
|
||||
load_read_s_ = st.read_seconds;
|
||||
load_copy_s_ = st.copy_seconds;
|
||||
record_inputs(path, gguf_, lay, from_gguf);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -3387,6 +3402,7 @@ void ArenaExpertSource::close() {
|
||||
#endif
|
||||
map_ = nullptr;
|
||||
map_bytes_ = 0;
|
||||
inputs_.clear();
|
||||
if (arena_ != nullptr) {
|
||||
delete (PinnedArena*) arena_;
|
||||
arena_ = nullptr;
|
||||
|
||||
+63
-33
@@ -6118,29 +6118,32 @@ int main(int argc, char** argv) {
|
||||
std::optional<uint64_t> model_fp, config_fp;
|
||||
auto session_identity = [&](strata::core::SessionFileIdentity& id, std::string& e) -> bool {
|
||||
if (!model_fp) {
|
||||
std::vector<strata::core::SessionModelFile> files;
|
||||
auto add = [&](const std::string& role, const std::string& path, bool optional = false) {
|
||||
if (path.empty()) return;
|
||||
for (const auto& f : files) if (f.path == path) return; // one file, hashed once (first role)
|
||||
files.push_back({role, path, optional});
|
||||
};
|
||||
for (size_t i = 0; i < o.native_shards.size(); ++i) add("native shard " + std::to_string(i), o.native_shards[i]);
|
||||
for (size_t i = 0; i < o.native_dense_gguf.size(); ++i) add("native dense " + std::to_string(i), o.native_dense_gguf[i]);
|
||||
for (size_t i = 0; i < o.native_head_shards.size(); ++i) add("native head " + std::to_string(i), o.native_head_shards[i]);
|
||||
add("embedding", o.embd_gguf);
|
||||
add("ple", o.ple_gguf);
|
||||
// the pack's files the loader reads (weights.cpp, expert_layout.cpp), not whatever else is in the folder
|
||||
// what the loaders actually resolved: the CLI inputs, the pack's files and - from the expert source
|
||||
// itself - every file its experts were read from (native_experts.txt can name GGUFs per layer/role)
|
||||
strata::core::SessionInputs in;
|
||||
in.native_shards = o.native_shards;
|
||||
in.native_dense = o.native_dense_gguf;
|
||||
in.native_head = o.native_head_shards;
|
||||
in.embedding = o.embd_gguf;
|
||||
in.ple = o.ple_gguf;
|
||||
in.pack = o.pack;
|
||||
in.mtp = o.mtp.empty() ? std::string() : o.mtp + "/dense.bin";
|
||||
if (srcp != nullptr) in.experts = srcp->model_inputs();
|
||||
std::vector<strata::core::SessionModelFile> files = strata::core::session_model_inputs(in);
|
||||
// the pack's other files the loader reads (weights.cpp, expert_layout.cpp)
|
||||
if (!o.pack.empty()) {
|
||||
for (const char* n : {"index.txt", "dense.bin"}) add(std::string("pack ") + n, o.pack + "/" + n);
|
||||
for (const char* n : {"embd.bin", "experts.bin", "extra.bin", "native_experts.txt", "manifest.json"})
|
||||
add(std::string("pack ") + n, o.pack + "/" + n, true);
|
||||
for (const char* n : {"index.txt", "dense.bin"}) files.push_back({std::string("pack ") + n, o.pack + "/" + n});
|
||||
for (const char* n : {"embd.bin", "extra.bin", "manifest.json"})
|
||||
files.push_back({std::string("pack ") + n, o.pack + "/" + n, true});
|
||||
if (srcp == nullptr) files.push_back({"pack experts.bin", o.pack + "/experts.bin", true});
|
||||
}
|
||||
if (!o.mtp.empty()) {
|
||||
for (const char* n : {"dense.txt", "dense.bin", "experts.bin"}) add(std::string("mtp ") + n, o.mtp + "/" + n);
|
||||
add("mtp draft_vocab.bin", o.mtp + "/draft_vocab.bin", true);
|
||||
for (const char* n : {"dense.txt", "experts.bin"}) files.push_back({std::string("mtp ") + n, o.mtp + "/" + n});
|
||||
files.push_back({"mtp draft_vocab.bin", o.mtp + "/draft_vocab.bin", true});
|
||||
}
|
||||
uint64_t fp = 0;
|
||||
if (!strata::core::session_model_fingerprint(files, fp, e)) return false;
|
||||
if (!strata::core::session_model_fingerprint(files, fp, e, [] { strata::core::progress_beat(); }))
|
||||
return false;
|
||||
model_fp = fp;
|
||||
}
|
||||
if (!config_fp) {
|
||||
@@ -7579,10 +7582,13 @@ int main(int argc, char** argv) {
|
||||
const std::string path = line.substr(save ? 5 : 8);
|
||||
const auto t0 = Clock::now();
|
||||
auto ms = [&] { return std::chrono::duration<double, std::milli>(Clock::now() - t0).count(); };
|
||||
auto refuse = [&](const std::string& why) {
|
||||
auto refuse = [&](const std::string& why, strata::core::SessionError kind = strata::core::SessionError::invalid,
|
||||
bool published = false) {
|
||||
std::fprintf(stderr, "strata serve: session %s %s: %s\n", save ? "save" : "restore", path.c_str(),
|
||||
why.c_str());
|
||||
std::printf("ERR %s\n", why.c_str());
|
||||
std::string one = why; // one protocol line
|
||||
for (char& c : one) if (c == '\n' || c == '\r') c = ' ';
|
||||
std::printf("SERR %s %d %s\n", strata::core::session_error_name(kind), published ? 1 : 0, one.c_str());
|
||||
std::fflush(stdout);
|
||||
err.clear();
|
||||
};
|
||||
@@ -7604,8 +7610,14 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
strata::core::SessionFileIdentity id;
|
||||
try {
|
||||
if (!session_identity(id, err)) { refuse(err); continue; }
|
||||
} catch (const std::exception& e) { refuse(std::string("session identity: ") + e.what()); continue; }
|
||||
if (!session_identity(id, err)) { refuse(err, strata::core::SessionError::io); continue; }
|
||||
} catch (const std::bad_alloc&) {
|
||||
refuse("session identity: out of memory", strata::core::SessionError::memory);
|
||||
continue;
|
||||
} catch (const std::exception& e) {
|
||||
refuse(std::string("session identity: ") + e.what(), strata::core::SessionError::io);
|
||||
continue;
|
||||
}
|
||||
if (save) {
|
||||
if (!live_ok || live.empty()) { refuse("no complete session to save"); continue; }
|
||||
size_t bytes = 0, kept = 0;
|
||||
@@ -7620,18 +7632,25 @@ int main(int argc, char** argv) {
|
||||
std::vector<strata::core::SessionKvSource> sources;
|
||||
if (!strata::core::conversation_snapshot_sources(meta, sources, view, ss, g, mtp.kv_state(),
|
||||
err)) {
|
||||
refuse(err);
|
||||
refuse(err, strata::core::SessionError::io);
|
||||
continue;
|
||||
}
|
||||
capture_ms = ms();
|
||||
strata::core::SessionWriteOptions wo;
|
||||
wo.min_free_bytes = (uint64_t) o.session_min_free_mib << 20;
|
||||
wo.progress = moving;
|
||||
if (!strata::core::session_file_write(path, meta, sources, id, bytes, err, wo)) {
|
||||
refuse(err);
|
||||
strata::core::SessionStatus st;
|
||||
if (!strata::core::session_file_write(path, meta, sources, id, bytes, err, wo, &st)) {
|
||||
refuse(err, st.error, st.published);
|
||||
continue;
|
||||
}
|
||||
} catch (const std::bad_alloc&) { refuse("not enough RAM to save the session"); continue; }
|
||||
if (st.dir_flush_unsupported)
|
||||
std::fprintf(stderr, "strata serve: session saved to %s; this filesystem cannot flush a "
|
||||
"folder, so the new name is not flushed\n", path.c_str());
|
||||
} catch (const std::bad_alloc&) {
|
||||
refuse("not enough RAM to save the session", strata::core::SessionError::memory);
|
||||
continue;
|
||||
}
|
||||
std::fprintf(stderr, "strata serve: session saved %zu tokens, %zu of %zu checkpoints, %zu bytes to %s "
|
||||
"in %.1f ms (state %.1f ms)\n", live.size(), kept, checks.size(), bytes,
|
||||
path.c_str(), ms(), capture_ms);
|
||||
@@ -7640,12 +7659,10 @@ int main(int argc, char** argv) {
|
||||
strata::core::SavedConversation image;
|
||||
size_t bytes = 0;
|
||||
try {
|
||||
// bounds this engine can ever hold, checked before anything is allocated, and the RAM the
|
||||
// parsed image needs (about the file's size) on top of the parking floor, asked first
|
||||
// bounds this session can ever restore (geometry, layer range, tokens, checkpoints, every
|
||||
// state and K/V part), checked as the file is parsed and before each array is allocated; the
|
||||
// file size follows from them. The RAM the parse needs at its peak is asked first.
|
||||
strata::core::SessionReadLimits limits;
|
||||
limits.max_tokens = (uint64_t) o.max_context;
|
||||
limits.max_checkpoints = (uint64_t) std::max(o.prompt_cache, 1);
|
||||
limits.max_kv_layers = (uint64_t) g.n_layers + 1;
|
||||
limits.progress = moving;
|
||||
const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20;
|
||||
limits.admit = [floor, &o](uint64_t need, std::string& why) {
|
||||
@@ -7656,8 +7673,21 @@ int main(int argc, char** argv) {
|
||||
(avail ? std::to_string(*avail >> 20) + " MiB available)" : "RAM telemetry unavailable)");
|
||||
return false;
|
||||
};
|
||||
if (!strata::core::session_file_read(path, id, image, bytes, err, limits)) { refuse(err); continue; }
|
||||
} catch (const std::bad_alloc&) { refuse("not enough RAM to read the session"); continue; }
|
||||
if (!strata::core::conversation_session_read_limits(
|
||||
limits, ss, g, mtp.kv_state(), (uint64_t) o.max_context,
|
||||
(uint64_t) std::max(o.prompt_cache, 1), err)) {
|
||||
refuse(err, strata::core::SessionError::io);
|
||||
continue;
|
||||
}
|
||||
strata::core::SessionStatus st;
|
||||
if (!strata::core::session_file_read(path, id, image, bytes, err, limits, &st)) {
|
||||
refuse(err, st.error);
|
||||
continue;
|
||||
}
|
||||
} catch (const std::bad_alloc&) {
|
||||
refuse("not enough RAM to read the session", strata::core::SessionError::memory);
|
||||
continue;
|
||||
}
|
||||
const double read_ms = ms();
|
||||
// the whole image against this engine, still without any device write
|
||||
if (!strata::core::conversation_snapshot_validate(image, ss, g, mtp.kv_state(), err)) {
|
||||
|
||||
Reference in new issue
Block a user