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