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