okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b92a29537
main
1#include "strata/core/conversation_cache.hpp" 2 3#include <cstdio> 4#include <cstdlib> 5#include <vector> 6 7using namespace strata::core ; 8 9namespace { 10int checks = 0 ; 11void check (bool value ,const char * description ) { 12++ checks ; 13if (!value ) { std::fprintf (stderr ,"FAIL: %s\n" ,description ); std::exit (1 ); } 14} 15SavedConversation image (std::initializer_list < int32_t > ids ,bool cvec = true) { 16SavedConversation s ; 17s .live .ids = ids ; 18s .live .gdn .resize (64 ,7 ); 19s .cvec = cvec ; 20return s ; 21} 22} 23 24int main () { 25 { 26ConversationBuffer bytes ; 27const size_t first = ConversationBuffer ::segment_bytes + 17 ; 28const size_t peak = bytes .allocation_peak (first ); 29bytes .resize (first ,7 ); 30check (bytes .bytes () <=peak ,"segmented payload and directory fit admitted bytes" ); 31uint8_t * original = nullptr ; 32bytes .visit (0 ,1 , [& ](uint8_t * p ,size_t ,size_t ) {original = p ;return true; }); 33const size_t grown_peak = bytes .allocation_peak (first + 99 ); 34bytes .resize (first + 99 ,9 ); 35bytes .visit (0 ,1 , [& ](uint8_t * p ,size_t ,size_t ) { 36check (p == original ,"appending preserves existing payload addresses" );return true; 37 }); 38check (bytes .bytes () <=grown_peak ,"growth including transient directory fits admission" ); 39 std::vector < uint8_t > tail (116 ); 40check (bytes .read (tail .data (),ConversationBuffer ::segment_bytes ,tail .size ()),"read spans segment boundaries" ); 41check (std::all_of (tail .begin (),tail .begin ()+ 17 , [](auto v ){return v == 7 ;})&& 42 std::all_of (tail .begin ()+ 17 ,tail .end (), [](auto v ){return v == 9 ;}),"growth preserves prefix and initializes only suffix" ); 43auto copy = bytes ; 44bytes .resize (ConversationBuffer ::segment_bytes + 10 ); 45bytes .resize (first ,7 );bytes .resize (first + 99 ,9 ); 46check (bytes == copy ,"equality ignores differing segmentation after rewind and regrowth" ); 47check (!bytes .read (tail .data (),bytes .size ()- 1 ,2 ),"range check rejects a truncated payload" ); 48check (bytes .allocation_peak (SIZE_MAX )== SIZE_MAX ,"allocation estimate rejects overflow" ); 49 } 50 { 51ConversationBuffer bytes ; 52for (size_t n = 1 ;n <=4096 ;++ n ) { 53const size_t peak = bytes .allocation_peak (n * 17 ); 54bytes .resize (n * 17 ,7 ); 55check (bytes .bytes () <=peak ,"small append stays within the predicted allocation peak" ); 56 } 57size_t segments = 0 ; 58bytes .visit (0 ,bytes .size (),[& ](const uint8_t * ,size_t ,size_t ){++ segments ;return true;}); 59check (segments <=4 ,"thousands of small turns do not create thousands of restore transfers" ); 60 } 61 { 62// a parked conversation's K/V buffer (16 MiB, as captured) grows by one turn: the reserve for later turns is 63// an eighth of the buffer at most, not another 16 MiB segment 64ConversationBuffer bytes ; 65bytes .resize (ConversationBuffer ::segment_bytes ,3 ); 66const size_t captured = bytes .bytes (); 67check (captured - bytes .size ()< 1024 ,"a fresh capture reserves nothing" ); 68const size_t turn = 1 <<20 ; 69const size_t peak = bytes .allocation_peak (bytes .size ()+ turn ); 70bytes .resize (bytes .size ()+ turn ,4 ); 71check (bytes .bytes () <=peak ,"a turn's growth stays within the predicted allocation peak" ); 72check (bytes .bytes ()- captured <=turn + ConversationBuffer ::segment_bytes /8 + 1024 , 73"the reserve for later turns is at most an eighth of the buffer" ); 74const size_t reserved = bytes .bytes (); 75bytes .resize (bytes .size ()+ turn /2 ,5 ); 76check (bytes .bytes ()== reserved ,"the next small turn fills the reserve instead of allocating" ); 77size_t segments = 0 ; 78bytes .visit (0 ,bytes .size (), [& ](const uint8_t * ,size_t ,size_t ) {++ segments ;return true; }); 79check (segments == 2 ,"the reserve extends the turn's segment" ); 80 } 81 { 82// many turns of 1 MiB onto a 16 MiB buffer: the reserve grows with the buffer, so the segments do not 83// multiply one per turn, and the reserve never exceeds an eighth of the buffer 84ConversationBuffer bytes ; 85bytes .resize (ConversationBuffer ::segment_bytes ,1 ); 86for (int k = 0 ;k < 256 ;++ k ) { 87const size_t before = bytes .size (); 88const size_t peak = bytes .allocation_peak (before + (1 <<20 )); 89bytes .resize (before + (1 <<20 ),2 ); 90check (bytes .bytes () <=peak ,"each turn stays within the predicted allocation peak" ); 91check (bytes .bytes ()- bytes .size () <=before /8 + 4096 ,"the reserve stays within an eighth" ); 92 } 93size_t segments = 0 ; 94bytes .visit (0 ,bytes .size (), [& ](const uint8_t * ,size_t ,size_t ) {++ segments ;return true; }); 95check (segments <=64 ,"256 turns of 1 MiB take far fewer than 256 segments" ); 96 } 97 { 98ConversationKv layer ; 99layer .k .resize (400 ); 100 std::vector < ConversationKv > layers ; 101layers .push_back (std::move (layer )); 102const size_t retained = layers .capacity ()* sizeof (ConversationKv )+ layers [0 ].bytes (); 103const size_t parked = image ({1 ,2 ,3 }).bytes (); 104ConversationCache cache (retained + parked ,4 ); 105check (cache .put (image ({1 ,2 ,3 })),"park before retaining active storage" ); 106cache .retain (std::move (layers ),16 ); 107check (cache .bytes ()== retained + parked && cache .size ()== 1 ,"active retained storage consumes bytes but no parked slot" ); 108cache .limit_reuse (9 );cache .limit_reuse (12 ); 109auto reuse = cache .take_reuse (); 110check (reuse .unchanged_tokens == 9 ,"a later continuation cannot undo a rewind's dirty boundary" ); 111check (cache .bytes ()== parked ,"taking retained buffers releases their budget accounting" ); 112cache .retain (std::move (reuse .kv ),16 ); 113check (!cache .can_fit (parked ),"retained storage is counted when checking a capture without eviction" ); 114check (cache .retained_bytes ()== retained && cache .size ()== 1 && cache .evictions ()== 0 , 115"optional reuse admission does not evict or release anything" ); 116check (!cache .can_fit (SIZE_MAX )&& !cache .can_fit (1 ,SIZE_MAX ),"non-mutating reservation rejects overflow" ); 117check (cache .make_room (parked ),"reservation can discard optional active buffers" ); 118check (cache .retained_bytes ()== 0 && cache .size ()== 1 && cache .evictions ()== 0 , 119"pressure drops retained storage before evicting parked conversations" ); 120 } 121const std::vector < int64_t > a = {1 ,2 ,3 ,4 },b = {9 ,8 ,7 ,6 }; 122 { 123ConversationCache cache (1024 ,2 ); 124check (cache .put (image ({1 ,2 ,3 })),"park A" ); 125check (cache .put (image ({9 ,8 ,7 })),"park B" ); 126auto match = cache .best (a , {}, true); 127check (match .tokens == 3 && match .live ,"A/B/A: recover A" ); 128auto restored = cache .take (match .index ); 129check (restored .live .ids == std::vector < int32_t > ({1 ,2 ,3 }),"taking selected A preserves identity" ); 130check (cache .size ()== 1 && cache .best (b , {}, true).tokens == 3 ,"B remains parked" ); 131check (cache .bytes ()== image ({9 ,8 ,7 }).bytes (),"byte accounting after take" ); 132check (cache .put (std::move (restored )),"park returned A as newest" ); 133check (cache .put (image ({5 ,6 })),"evict oldest by slot limit" ); 134check (cache .best (b , {}, true).tokens == 0 && cache .best (a , {}, true).tokens == 3 ,"B evicted before A" ); 135check (cache .evictions ()== 1 ,"eviction counter" ); 136 } 137 { 138// evict_oldest(): the physical-RAM admission gate in generate.cpp frees parked conversations 139// one at a time and re-checks the host's free memory, so this has to be exactly the oldest-first 140// step make_room() takes - same accounting, same counters - and it has to stop at empty. 141ConversationCache cache (4096 ,4 ); 142cache .put (image ({1 ,2 ,3 })); 143cache .put (image ({9 ,8 ,7 })); 144check (cache .size ()== 2 && cache .slots ()== 4 ,"slots() reports the configured limit" ); 145const size_t both = cache .bytes (); 146check (cache .evict_oldest (),"evict_oldest reports an eviction" ); 147check (cache .size ()== 1 && cache .evictions ()== 1 ,"evict_oldest drops exactly one, oldest first" ); 148check (cache .best (a , {}, true).tokens == 0 && cache .best (b , {}, true).tokens == 3 , 149"the oldest conversation went, the newest stayed" ); 150check (cache .bytes ()== both - image ({1 ,2 ,3 }).bytes (),"evict_oldest releases the entry's bytes" ); 151cache .evict_oldest (); 152check (cache .size ()== 0 && cache .bytes ()== 0 ,"evicting the last parked conversation empties the cache" ); 153check (!cache .evict_oldest (),"the gate's loop can reach an empty cache: false" ); 154check (cache .size ()== 0 && cache .evictions ()== 2 ,"evict_oldest on an empty cache is a no-op" ); 155 } 156 {// the RAM gate's eviction skips a conversation that holds a pinned shared prefix, and says so (false) 157ConversationCache cache (1 <<20 ,4 ); 158auto pinned = image ({1 ,2 ,3 }); 159pinned .checkpoints .push_back (ConversationCheckpoint {}); 160pinned .checkpoints .back ().ids = {1 ,2 }; 161pinned .checkpoints .back ().pinned = true; 162pinned .checkpoints .back ().gdn .resize (64 ,1 ); 163cache .put (std::move (pinned )); 164cache .put (image ({9 ,8 ,7 })); 165check (cache .evict_oldest ()&& cache .size ()== 1 ,"the oldest unpinned conversation went (the pinned one is older)" ); 166check (!cache .evict_oldest ()&& cache .size ()== 1 ,"only a pinned one is left: nothing more can go" ); 167// #879: after non-finite logits every parked conversation goes, the pinned one too 168cache .put (image ({4 ,5 ,6 })); 169 std::vector < ConversationKv > kv (1 ); 170kv [0 ].cells = 3 ; 171kv [0 ].k .resize (64 ,1 ); 172cache .retain (std::move (kv ),3 ); 173check (cache .retained_bytes ()> 0 ,"a retained K/V before clear()" ); 174check (cache .clear ()== 2 ,"clear() reports how many were parked" ); 175check (cache .size ()== 0 && cache .bytes ()== 0 && cache .retained_bytes ()== 0 ,"clear() leaves nothing parked" ); 176check (cache .best (std::vector < int64_t > {1 ,2 ,3 ,4 }, {}, true).tokens == 0 ,"a cleared cache matches nothing" ); 177check (cache .clear ()== 0 ,"clear() on an empty cache" ); 178 } 179 { 180auto s = image ({1 ,2 ,3 }); 181ConversationCheckpoint cp ; 182cp .ids = {1 ,2 }; 183s .checkpoints .push_back (cp ); 184ConversationCache cache (4096 ,4 ); 185cache .put (std::move (s )); 186auto match = cache .best (std::vector < int64_t > {1 ,2 ,9 ,4 }, {}, true); 187check (match .tokens == 2 && !match .live ,"edited suffix falls back to parked checkpoint" ); 188check (cache .best (a , {}, true).tokens == 3 ,"live prefix beats shorter checkpoint" ); 189check (cache .best (a , {}, false).tokens == 0 ,"steering mode is isolated" ); 190check (cache .best (std::vector < int64_t > {1 ,2 }, {}, true).tokens == 0 ,"equal-length checkpoint cannot consume last token" ); 191check (cache .best (std::vector < int64_t > {1 }, {}, true).tokens == 0 ,"short prompt cannot match" ); 192check (cache .best (std::vector < int64_t > {}, {}, true).tokens == 0 ,"empty prompt cannot match" ); 193check (cache .best (std::vector < int64_t > {1 ,2 ,9 ,4 }, {}, true,1 ).tokens == 2 ,"a floor below the match keeps it" ); 194check (cache .best (std::vector < int64_t > {1 ,2 ,9 ,4 }, {}, true,2 ).tokens == 0 ,"a floor at the match leaves nothing" ); 195check (cache .best (a , {}, true,2 ).tokens == 3 && cache .best (a , {}, true,2 ).live ,"a floor skips only shorter ones" ); 196cache .put (image ({1 ,2 ,3 })); 197check (cache .best (a , {}, true).index == 1 ,"ties prefer most recently parked" ); 198 } 199 { 200auto s = image ({1 ,2 ,3 }); 201s .live .imgs = {{1 ,123 }}; 202ConversationCache cache (1024 ,3 ); 203cache .put (std::move (s )); 204check (cache .best (a , {{1 ,123 }}, true).tokens == 3 ,"same image can resume" ); 205check (cache .best (a , {{1 ,124 }}, true).tokens == 0 ,"different image pixels invalidate same pad tokens" ); 206check (cache .best (a , {}, true).tokens == 0 ,"missing image invalidates prefix" ); 207check (cache .best (a , {{1 ,123 },{2 ,45 }}, true).tokens == 0 ,"additional image in cached prefix invalidates" ); 208check (cache .best (a , {{1 ,123 },{3 ,45 }}, true).tokens == 3 ,"image after cached prefix does not invalidate" ); 209 } 210 { 211const size_t one = image ({1 ,2 ,3 }).bytes (); 212ConversationCache cache (one * 2 ,8 ); 213cache .put (image ({1 ,2 ,3 }));cache .put (image ({9 ,8 ,7 })); 214check (cache .bytes ()== one * 2 ,"budget holds two exact-sized images" ); 215auto held = cache .take (cache .best (a , {}, true).index ); 216check (cache .make_room (one ,held .bytes ()),"count in-flight image when reserving outgoing snapshot" ); 217check (cache .size ()== 0 ,"in-flight reservation evicts otherwise fitting B" ); 218check (cache .put (image ({5 ,6 ,7 }),held .bytes ()),"insert with in-flight accounting" ); 219check (cache .bytes ()+ held .bytes () <=one * 2 ,"exchange obeys byte budget" ); 220check (!cache .make_room (one + 1 ,one ),"oversized exchange rejected" ); 221check (cache .size ()== 1 ,"oversized snapshot does not evict useful entries" ); 222auto huge = image ({1 });huge .live .gdn .resize (one * 3 ); 223check (!cache .put (std::move (huge )),"oversized image rejected" ); 224check (cache .size ()== 1 ,"oversized put leaves cache unchanged" ); 225check (!cache .make_room (0 ,one * 2 + 1 ),"held larger than budget cannot underflow" ); 226 } 227 { 228// #342: MAIN -> SUB (9 turns) -> MAIN with 4 slots. Every SUB turn parks the previous turn's live state 229// (its reply as generated, which the next request re-rendered) with a chain that holds that turn's 230// boundary checkpoint; the copy a turn back adds only that stale tail and is dropped, so MAIN survives. 231auto cp = [](std::vector < int32_t > ids ) {ConversationCheckpoint c ;c .ids = std::move (ids );return c ; }; 232auto with = [](std::vector < int32_t > prefix , std::initializer_list < int32_t > more ) { 233prefix .insert (prefix .end (),more );return prefix ; 234 }; 235const std::vector < int32_t > root = {1 ,2 ,3 ,4 }; 236SavedConversation main = image ({}); 237main .live .ids = with (with (root , {10 ,11 ,12 }), {13 ,14 }); 238main .checkpoints = {cp (root ),cp (with (root , {10 ,11 ,12 }))}; 239const size_t big = 1 <<20 ; 240ConversationCache cache (big ,4 ); 241check (cache .put (std::move (main )),"park MAIN" ); 242 std::vector < int32_t > history = with (root , {20 });// SUB's conversation so far, re-rendered 243 std::vector < ConversationCheckpoint > chain = {cp (root )}; 244for (int turn = 1 ;turn <=9 ;++ turn ) { 245chain .push_back (cp (history ));// the turn boundary the next request resumes from 246SavedConversation sub = image ({}); 247sub .live .ids = with (history , {900 , (int32_t )turn });// + the reply with its thinking (stale tail) 248sub .checkpoints = chain ; 249check (cache .put (std::move (sub )),"park SUB turn" ); 250check (cache .size () <=2 ,"one parked copy of SUB at a time" ); 251history = with (history , {30 , (int32_t )turn });// the reply as the next request renders it 252 } 253check (cache .evictions ()== 0 && cache .superseded ()== 8 ,"8 superseded copies dropped, nothing evicted" ); 254const auto m = cache .best (with (with (root , {10 ,11 ,12 }), {13 ,14 ,15 }), {}, true); 255check (m .tokens == 9 && m .live ,"MAIN still restores in full" ); 256const auto s = cache .best (with (history , {40 }), {}, true); 257check (s .tokens == (int64_t )history .size ()- 2 ,"SUB resumes from its last turn boundary" ); 258 } 259 { 260// holds(): what an idle batch slot holds is parked already (or a continuation of it is) 261auto s = image ({1 ,2 ,3 ,4 ,5 }); 262ConversationCheckpoint cp ; 263cp .ids = {1 ,2 ,3 }; 264s .checkpoints .push_back (cp ); 265ConversationCache cache (4096 ,4 ); 266cache .put (std::move (s )); 267check (cache .holds (std::vector < int32_t > {1 ,2 ,3 ,4 ,5 }, {}, true),"the parked live state itself" ); 268check (cache .holds (std::vector < int32_t > {1 ,2 ,3 ,4 }, {}, true),"a prefix of the parked live state" ); 269check (cache .holds (std::vector < int32_t > {1 ,2 }, {}, true),"a prefix of a parked checkpoint" ); 270check (!cache .holds (std::vector < int32_t > {1 ,2 ,3 ,4 ,5 ,6 }, {}, true),"a longer state is not held" ); 271check (!cache .holds (std::vector < int32_t > {1 ,2 ,9 }, {}, true),"a diverging state is not held" ); 272check (!cache .holds (std::vector < int32_t > {}, {}, true),"an empty state is never held" ); 273check (!cache .holds (std::vector < int32_t > {1 ,2 ,3 }, {}, false),"steering mode is isolated" ); 274check (!cache .holds (std::vector < int32_t > {1 ,2 ,3 }, {{1 ,77 }}, true),"a slot with pictures is not held by a text image" ); 275auto p = image ({1 ,2 ,3 ,4 }); 276p .live .imgs = {{1 ,77 }, {3 ,78 }}; 277cache .put (std::move (p )); 278check (cache .holds (std::vector < int32_t > {1 ,2 ,3 }, {{1 ,77 }}, true),"pictures below the state must match" ); 279check (!cache .holds (std::vector < int32_t > {1 ,2 ,3 ,4 }, {{1 ,77 }}, true),"a picture inside the state that the slot lacks" ); 280 } 281 { 282// The 2026-10-14 four-conversation measurement replayed at policy level: two batch slots, four parked 283// entries, conversations A..D. Each has a prompt P (8 tokens; the read's periodic checkpoint at 4), a first 284// reply R1 (3 tokens; the slot holds P + 2 of them), the next turn as the client renders it (P + R1 + end + 285// header: 14 tokens, the read's turn checkpoint at 12), a second reply R2 (4 tokens; the slot holds 17) and 286// a third turn (21 tokens). The engine parks the MAIN session (the prompt as read, plus the admission's 287// token) whenever another conversation displaces it; the replies are decoded in the slots. Measured: 288// A's third turn found 199584 of 199839 held tokens (its prompt-read state), B found nothing. 289// slot_parks: an idle slot parks what it holds before an admission overwrites it 290// checks_back: a slot that gives "all it holds" back to the main session gives its checkpoints with it, 291// so the chain still supersedes (#342) the parked copies a turn back 292auto replay = [& ](bool slot_parks ,bool checks_back ) { 293 std::vector < std::vector < int32_t >> full (4 ); 294for (int c = 0 ;c < 4 ;++ c ) { 295for (int32_t t = 1 ;t <=8 ;++ t )full [(size_t )c ].push_back (c * 100 + t ); 296for (int32_t t : {21 ,22 ,23 ,9 ,31 ,32 ,41 ,42 ,43 ,44 ,9 ,51 ,52 })full [(size_t )c ].push_back (c * 100 + t ); 297 } 298auto st = [& ](int c ,size_t n ) {return std::vector < int32_t > (full [(size_t )c ].begin (),full [(size_t )c ].begin ()+ (std::ptrdiff_t )n ); }; 299auto cp = [& ](int c ,size_t n ) {ConversationCheckpoint k ;k .ids = st (c ,n );return k ; }; 300auto park = [& ](ConversationCache & cache ,int c ,size_t n ,const std::vector < size_t >& cks ) { 301SavedConversation s = image ({}); 302s .live .ids = st (c ,n ); 303for (size_t k :cks )s .checkpoints .push_back (cp (c ,k )); 304check (cache .put (std::move (s )),"the replay's parks all fit the budget" ); 305 }; 306auto restore = [& ](ConversationCache & cache ,int c ,size_t prompt )-> int64_t { 307const auto m = cache .best (st (c ,prompt ), {}, true); 308if (m .tokens > 0 )cache .take (m .index ); 309return m .tokens ; 310 }; 311// the main chain after a slot gave "all it holds" back: its checkpoints, or none 312auto back = [& ](const std::vector < size_t >& slot_cks ) {return checks_back ?slot_cks : std::vector < size_t > {}; }; 313auto slot_park = [& ](ConversationCache & cache ,int c ,size_t n ,const std::vector < size_t >& cks ) { 314if (slot_parks && !cache .holds (st (c ,n ), {}, true))park (cache ,c ,n ,cks ); 315 }; 316enum {A ,B ,C ,D }; 317ConversationCache cache (1 <<20 ,4 ); 318// initial-AB: B solo then admitted (its prompt + the first token parked when A's request came), A 319// admitted directly, then alone: solo again from its slot (A's prompt-read state parked first) 320park (cache ,B ,9 , {4 }); 321park (cache ,A ,8 , {4 }); 322 std::vector < size_t > chain_a = back ({4 });// slot 1 gave back A's 10 tokens 323// resident1-AB: B's request displaces A's solo state; B's slot gives back 10; B admitted with the turn 324// checkpoint; A's request restores A's solo state from RAM and is admitted beside B 325park (cache ,A ,12 ,chain_a ); 326 std::vector < size_t > chain_b = back ({4 }); 327chain_b .push_back (12 ); 328// (a request takes its parked conversation before it parks the one it displaces) 329check (restore (cache ,A ,14 )== 12 ,"A's second turn resumes from its parked solo state" ); 330park (cache ,B ,15 ,chain_b ); 331chain_a .push_back (12 ); 332// both decode: slot 0 holds B's 17, slot 1 holds A's 17 333// initial-CD: C's request displaces A's main state; D admitted into slot 0 (B's reply), C into slot 1 334park (cache ,A ,14 ,chain_a ); 335slot_park (cache ,B ,17 , {12 }); 336park (cache ,D ,9 , {4 }); 337slot_park (cache ,A ,17 , {12 }); 338park (cache ,C ,8 , {4 });// C alone: solo again from its slot 339 std::vector < size_t > chain_c = back ({4 }); 340// resident1-CD: C continues from the main session (no park), D's request displaces it (slot 1 held C's 341// own earlier state: covered, no slot park), D's slot gives back 10 (covered as well) 342chain_c .push_back (12 ); 343park (cache ,C ,15 ,chain_c ); 344 std::vector < size_t > chain_d = back ({4 }); 345chain_d .push_back (12 ); 346// both decode: slot 0 holds D's 17, slot 1 holds C's 17 347// exchange1-AB: A's request takes A's parked state, displaces D's main state, is admitted into slot 1 348// (C's reply); B's request displaces A's state 349const int64_t a_found = restore (cache ,A ,21 ); 350park (cache ,D ,14 ,chain_d ); 351slot_park (cache ,C ,17 , {12 }); 352park (cache ,A ,22 , {12 ,20 }); 353const int64_t b_found = restore (cache ,B ,21 ); 354return std::pair < int64_t ,int64_t > (a_found ,b_found ); 355 }; 356const auto baseline = replay (false, false); 357check (baseline .first == 14 && baseline .second == 0 ,"baseline: A returns to its prompt-read state, B to nothing (as measured)" ); 358const auto parks_only = replay (true, false); 359check (parks_only .first == 17 && parks_only .second == 0 ,"slot parks alone: A whole, B's copy evicted by a stale initial image" ); 360const auto both = replay (true, true); 361check (both .first == 17 && both .second == 17 ,"slot parks + checkpoints back: both return whole" ); 362 } 363 { 364// what is NOT superseded: another conversation sharing only the root, an entry without checkpoints, the 365// other steering mode, a branch whose deepest checkpoint the new chain does not hold 366auto cp = [](std::vector < int32_t > ids ) {ConversationCheckpoint c ;c .ids = std::move (ids );return c ; }; 367ConversationCache cache (1 <<20 ,8 ); 368SavedConversation other = image ({1 ,2 ,3 ,4 ,50 ,51 ,52 }); 369other .checkpoints = {cp ({1 ,2 ,3 ,4 }),cp ({1 ,2 ,3 ,4 ,50 ,51 })}; 370cache .put (std::move (other )); 371cache .put (image ({1 ,2 ,3 ,4 ,7 ,7 }));// no checkpoints 372SavedConversation steered = image ({1 ,2 ,3 ,4 ,60 ,61 }, false); 373steered .checkpoints = {cp ({1 ,2 ,3 ,4 ,60 })}; 374cache .put (std::move (steered )); 375SavedConversation branch = image ({1 ,2 ,3 ,4 ,60 ,70 ,71 }); 376branch .checkpoints = {cp ({1 ,2 ,3 ,4 }),cp ({1 ,2 ,3 ,4 ,60 ,70 })}; 377cache .put (std::move (branch )); 378SavedConversation incoming = image ({1 ,2 ,3 ,4 ,60 ,80 ,81 }); 379incoming .checkpoints = {cp ({1 ,2 ,3 ,4 }),cp ({1 ,2 ,3 ,4 ,60 })}; 380check (cache .put (std::move (incoming )),"park a conversation sharing roots with all of them" ); 381check (cache .size ()== 5 && cache .superseded ()== 0 ,"none of them is superseded" ); 382SavedConversation same_state = image ({1 ,2 ,3 ,4 ,60 ,70 });// live equal to the branch's deepest point 383same_state .checkpoints = {cp ({1 ,2 ,3 ,4 })}; 384check (cache .put (std::move (same_state ))&& cache .superseded ()== 1 && cache .size ()== 5 , 385"the live state equal to an entry's deepest checkpoint supersedes it" ); 386SavedConversation huge = image ({1 ,2 ,3 ,4 ,60 ,80 }); 387huge .checkpoints = {cp ({1 ,2 ,3 ,4 }),cp ({1 ,2 ,3 ,4 ,60 })}; 388huge .live .gdn .resize (2 <<20 ); 389check (!cache .put (std::move (huge ))&& cache .size ()== 5 && cache .superseded ()== 1 , 390"an oversized put drops nothing" ); 391 } 392 { 393// --conversation-cache-park-gain N: parked_prefix_tokens reports what a park now would supersede, so a 394// conversation that advanced fewer than N tokens since that copy keeps it instead of writing the whole 395// snapshot again for the next turn to drop. It must name exactly the entries drop_superseded() would remove. 396auto cp = [](std::vector < int32_t > ids ) {ConversationCheckpoint c ;c .ids = std::move (ids );return c ; }; 397ConversationCache cache (1 <<20 ,8 ); 398check (cache .parked_prefix_tokens ({1 ,2 ,3 }, {}, {}, true)== 0 ,"an empty cache supersedes nothing" ); 399 400const std::vector < int32_t > live_ids = {1 ,2 ,3 ,4 ,60 ,70 }; 401const std::vector < ConversationCheckpoint > chain = {cp ({1 ,2 ,3 ,4 }),cp ({1 ,2 ,3 ,4 ,60 })}; 402SavedConversation same = image ({1 ,2 ,3 ,4 ,60 ,70 }); 403same .checkpoints = chain ; 404check (cache .put (std::move (same )),"park a conversation with a checkpoint chain" ); 405check (cache .parked_prefix_tokens (live_ids , {},chain , true)== 5 , 406"the entry the outgoing chain supersedes is reported by its deepest checkpoint" ); 407 408const std::vector < ConversationCheckpoint > other_chain = {cp ({1 ,2 ,3 })}; 409check (cache .parked_prefix_tokens ({1 ,2 ,3 ,40 ,50 }, {},other_chain , true)== 0 , 410"a conversation sharing only the root supersedes nothing" ); 411check (cache .parked_prefix_tokens (live_ids , {},chain , false)== 0 , 412"the other steering mode is a different entry" ); 413check (cache .parked_prefix_tokens ({1 ,2 ,3 ,4 ,60 ,70 ,71 }, {},chain , true)== 5 , 414"an appended tail keeps the reported depth at the parked one" ); 415SavedConversation no_cp = image ({1 ,2 ,3 ,9 }); 416check (cache .put (std::move (no_cp ))&& cache .parked_prefix_tokens ({1 ,2 ,3 ,9 }, {}, {}, true)== 0 , 417"an entry without checkpoints is never reported" ); 418 } 419 { 420// borrowing: a NEW conversation that starts with a checkpoint inside a parked one (a sibling subagent with 421// the same system prompt and tools) restores from it and leaves it parked; the same conversation going on 422// (its live state, or its deepest checkpoint after the client re-rendered the last reply) is still taken 423auto cp = [](std::vector < int32_t > ids ) {ConversationCheckpoint c ;c .ids = std::move (ids );return c ; }; 424SavedConversation a = image ({}); 425a .live .ids = {1 ,2 ,3 ,4 ,10 ,11 ,12 ,13 }; 426a .checkpoints = {cp ({1 ,2 ,3 ,4 }),cp ({1 ,2 ,3 ,4 ,10 ,11 })}; 427ConversationCache cache (1 <<20 ,2 ); 428check (cache .put (std::move (a )),"park subagent A" ); 429const auto sib = cache .best (std::vector < int64_t > {1 ,2 ,3 ,4 ,20 ,21 }, {}, true); 430check (sib .tokens == 4 && !sib .live && sib .serial != 0 && cache .borrows (sib ),"a sibling on A's root borrows" ); 431const auto again = cache .best (std::vector < int64_t > {1 ,2 ,3 ,4 ,10 ,11 ,30 }, {}, true); 432check (again .tokens == 6 && !again .live && !cache .borrows (again ), 433"A re-rendered at its deepest checkpoint is taken" ); 434const auto cont = cache .best (std::vector < int64_t > {1 ,2 ,3 ,4 ,10 ,11 ,12 ,13 ,14 }, {}, true); 435check (cont .live && !cache .borrows (cont ),"A going on is taken" ); 436check (!cache .borrows (cache .best (std::vector < int64_t > {5 ,6 ,7 }, {}, true)),"no match, nothing to borrow" ); 437// while the outgoing conversations are parked, the guarded donor is neither evicted nor dropped 438cache .guard (sib .serial ); 439check (cache .put (image ({7 ,7 ,7 }))&& cache .put (image ({8 ,8 ,8 })),"two outgoing conversations park" ); 440check (cache .find (sib .serial )!= nullptr && cache .size ()== 2 && cache .evictions ()== 1 && !cache .guard_blocked (), 441"the slot limit evicts the other entry, not the guarded donor" ); 442check (cache .best (std::vector < int64_t > {7 ,7 ,7 ,1 }, {}, true).tokens == 0 ,"the other one went" ); 443SavedConversation rewritten = image ({1 ,2 ,3 ,4 ,10 ,11 ,40 });// holds A's deepest checkpoint: supersedes A 444rewritten .checkpoints = {cp ({1 ,2 ,3 ,4 }),cp ({1 ,2 ,3 ,4 ,10 ,11 })}; 445check (cache .put (std::move (rewritten ))&& cache .find (sib .serial )!= nullptr && cache .superseded ()== 0 , 446"a guarded donor is not dropped as superseded" ); 447cache .unguard (); 448// identity survives index shifts: take an older entry, the donor's serial still finds it 449const auto donor_index = cache .index_of (sib .serial ); 450check (donor_index != SIZE_MAX ,"donor indexed by its serial" ); 451check (cache .best (std::vector < int64_t > {1 ,2 ,3 ,4 ,10 ,11 ,12 ,13 ,14 }, {}, true).serial == sib .serial , 452"matches report the entry's serial" ); 453 } 454 { 455// the outgoing conversation fits only in the guarded donor's room: make_room refuses before evicting anything 456auto cp = [](std::vector < int32_t > ids ) {ConversationCheckpoint c ;c .ids = std::move (ids );return c ; }; 457SavedConversation a = image ({1 ,2 ,3 ,4 ,10 ,11 }); 458a .checkpoints = {cp ({1 ,2 ,3 ,4 }),cp ({1 ,2 ,3 ,4 ,10 })}; 459const size_t a_bytes = a .bytes (); 460const size_t out_bytes = image ({9 ,9 ,9 }).bytes (); 461ConversationCache tight (a_bytes + out_bytes - 1 ,4 ); 462check (tight .put (std::move (a )),"park the donor" ); 463const auto m = tight .best (std::vector < int64_t > {1 ,2 ,3 ,4 ,50 }, {}, true); 464check (tight .borrows (m ),"a sibling would borrow" ); 465tight .guard (m .serial ); 466check (!tight .put (image ({9 ,9 ,9 }))&& tight .guard_blocked (),"no room beside the guarded donor: refused" ); 467check (tight .size ()== 1 && tight .evictions ()== 0 ,"nothing evicted by the refusal" ); 468tight .unguard (); 469auto taken = tight .take (tight .index_of (m .serial ));// what the caller does then: take it, as before 470check (taken .live .ids .size ()== 6 && taken .checkpoints .size ()== 2 && tight .size ()== 0 , 471"the taken donor is whole" ); 472ConversationCache one_slot (1 <<20 ,1 ); 473SavedConversation b = image ({1 ,2 ,3 ,4 ,10 ,11 }); 474b .checkpoints = {cp ({1 ,2 ,3 ,4 }),cp ({1 ,2 ,3 ,4 ,10 })}; 475check (one_slot .put (std::move (b )),"park in a single slot" ); 476const auto mb = one_slot .best (std::vector < int64_t > {1 ,2 ,3 ,4 ,50 }, {}, true); 477one_slot .guard (mb .serial ); 478check (!one_slot .put (image ({9 ,9 ,9 }))&& one_slot .guard_blocked ()&& one_slot .size ()== 1 , 479"one slot: the guarded donor blocks, nothing evicted" ); 480one_slot .unguard (); 481 } 482 { 483// pin=N beside a borrow: the guarded donor and a conversation holding a pinned shared prefix both stay; the 484// oldest other entry is the one evicted (the case midhatn tested on #1164) 485auto cp = [](std::vector < int32_t > ids ,bool pinned = false) { 486ConversationCheckpoint c ;c .ids = std::move (ids );c .pinned = pinned ;return c ; 487 }; 488SavedConversation doc = image ({1 ,2 ,3 ,4 ,5 ,6 ,30 ,31 }); 489doc .checkpoints = {cp ({1 ,2 ,3 ,4 ,5 ,6 }, true),cp ({1 ,2 ,3 ,4 ,5 ,6 ,30 })}; 490SavedConversation donor = image ({1 ,2 ,10 ,11 ,12 }); 491donor .checkpoints = {cp ({1 ,2 }),cp ({1 ,2 ,10 ,11 })}; 492ConversationCache cache (1 <<20 ,3 ); 493check (cache .put (std::move (doc ))&& cache .put (std::move (donor ))&& cache .put (image ({7 ,7 ,7 })), 494"pinned document, donor and an ordinary conversation parked" ); 495const auto m = cache .best (std::vector < int64_t > {1 ,2 ,40 ,41 }, {}, true); 496check (cache .borrows (m ),"a sibling on the donor's root borrows" ); 497cache .guard (m .serial ); 498check (cache .put (image ({8 ,8 ,8 }))&& !cache .guard_blocked ()&& cache .size ()== 3 && cache .evictions ()== 1 , 499"the outgoing conversation parks" ); 500check (cache .find (m .serial )!= nullptr && 501cache .best (std::vector < int64_t > {1 ,2 ,3 ,4 ,5 ,6 ,9 }, {}, true).tokens == 6 && 502cache .best (std::vector < int64_t > {7 ,7 ,7 ,1 }, {}, true).tokens == 0 , 503"only the ordinary entry was evicted: the donor and the pinned document stay" ); 504check (cache .put (image ({9 ,9 ,9 }))&& cache .size ()== 3 && cache .evictions ()== 2 && 505cache .find (m .serial )!= nullptr && cache .best (std::vector < int64_t > {8 ,8 ,8 ,1 }, {}, true).tokens == 0 , 506"the next outgoing one evicts the previous outgoing one, still not the donor or the document" ); 507cache .unguard (); 508ConversationCache two (1 <<20 ,2 ); 509SavedConversation doc2 = image ({1 ,2 ,3 ,4 ,5 ,6 ,30 }); 510doc2 .checkpoints = {cp ({1 ,2 ,3 ,4 ,5 ,6 }, true)}; 511SavedConversation donor2 = image ({1 ,2 ,10 ,11 ,12 }); 512donor2 .checkpoints = {cp ({1 ,2 }),cp ({1 ,2 ,10 ,11 })}; 513check (two .put (std::move (doc2 ))&& two .put (std::move (donor2 )),"pinned document and donor fill two slots" ); 514const auto m2 = two .best (std::vector < int64_t > {1 ,2 ,40 }, {}, true); 515two .guard (m2 .serial ); 516check (!two .put (image ({9 ,9 ,9 }))&& two .guard_blocked ()&& two .size ()== 2 && two .evictions ()== 0 , 517"no slot beside the donor and the pinned document: refused before evicting anything" ); 518two .unguard (); 519// a match that reaches the pinned prefix is taken, not borrowed: one conversation keeps holding the pin 520const auto on_pin = two .best (std::vector < int64_t > {1 ,2 ,3 ,4 ,5 ,6 ,77 }, {}, true); 521check (on_pin .tokens == 6 && !on_pin .live && !two .borrows (on_pin ),"a pinned prefix is taken, not borrowed" ); 522ConversationCache three (1 <<20 ,3 ); 523SavedConversation doc3 = image ({1 ,2 ,3 ,4 ,5 ,6 ,30 ,31 ,32 }); 524doc3 .checkpoints = {cp ({1 ,2 ,3 ,4 ,5 ,6 }, true),cp ({1 ,2 ,3 ,4 ,5 ,6 ,30 }),cp ({1 ,2 ,3 ,4 ,5 ,6 ,30 ,31 })}; 525check (three .put (std::move (doc3 )),"a conversation past its pinned prefix is parked" ); 526const auto past_pin = three .best (std::vector < int64_t > {1 ,2 ,3 ,4 ,5 ,6 ,30 ,99 }, {}, true); 527check (past_pin .tokens == 7 && !three .borrows (past_pin ), 528"a match past the pinned prefix (the copy would carry the pin) is taken, not borrowed" ); 529 } 530 { 531ConversationCache disabled (0 ,4 ),no_slots (1024 ,0 ); 532check (!disabled .enabled ()&& !no_slots .enabled (),"both disable switches" ); 533check (!disabled .put (image ({1 ,2 ,3 }))&& !no_slots .put (image ({1 ,2 ,3 })),"disabled cache stores nothing" ); 534check (disabled .best (a ,{},true).tokens == 0 ,"disabled cache has no matches" ); 535 } 536 { 537// --conversation-cache-min-tokens: a conversation shorter than the minimum is not worth one of the slots. 538// Parking is a switch-time decision, so without this a client's short side requests park themselves and, 539// once the cache is full, evict the long conversation they were interleaved with (oldest first). 540ConversationCache any (1024 ,4 ,0 ),floor (1024 ,4 ,12288 ); 541check (any .enabled ()&& floor .enabled (),"the minimum does not disable the cache" ); 542check (any .wants (0 )&& any .wants (1 )&& any .wants (1 <<20 ),"0 parks every length, as before the flag" ); 543check (!floor .wants (0 )&& !floor .wants (1 )&& !floor .wants (12287 ),"below the minimum is not parked" ); 544check (floor .wants (12288 )&& floor .wants (12289 ),"the minimum itself and above are parked" ); 545// the CLI rejects a negative, but the predicate must not invert for one that reaches it another way 546ConversationCache negative (1024 ,4 ,-1 ); 547check (negative .wants (0 )&& negative .wants (1 ),"a negative minimum parks everything, like 0" ); 548// wants() answers for the length alone; the gate is enabled() && wants(), so a disabled cache parks 549// nothing whatever the length - keep the two independent rather than folding one into the other 550ConversationCache disabled_min (0 ,4 ,12288 ); 551check (!disabled_min .enabled ()&& disabled_min .wants (1 <<20 ),"a disabled cache still answers for length" ); 552 } 553 { 554// layer-split parking: checkpoints moved apart into stage parts and put back, no running state copied 555auto running = [](std::initializer_list < int32_t > ids ,uint8_t salt ,size_t parts ) { 556ConversationCheckpoint c ; 557c .ids = ids ; 558c .gdn .assign (256 ,salt ); 559c .tails .assign (32 ,uint8_t (salt + 1 )); 560c .used = salt ; 561for (size_t k = 0 ;k < parts ;++ k ) { 562ConversationCheckpoint p ; 563p .gdn .assign (128 ,uint8_t (salt + 10 + k )); 564c .stage_parts .push_back (std::move (p )); 565 } 566return c ; 567 }; 568 std::vector < ConversationCheckpoint > checks ; 569checks .push_back (running ({1 ,2 },3 ,2 )); 570checks .push_back (running ({1 ,2 ,3 },5 ,1 ));// an incomplete set: kept aside, put back in place 571checks .push_back (running ({1 ,2 ,3 ,4 },7 ,2 )); 572const auto original = checks ; 573const uint8_t * gdn0 = checks [0 ].gdn .data (); 574const uint8_t * part1 = checks [2 ].stage_parts [1 ].gdn .data (); 575auto split = conversation_checkpoints_split (std::move (checks ),2 ); 576check (checks .empty ()&& split .stage0 .size ()== 2 && split .rest .size ()== 1 && split .parts .size ()== 2 && 577split .parts [0 ].size ()== 2 && split .parts [1 ].size ()== 2 ,"split: complete checkpoints apart, the other aside" ); 578check (split .stage0 [0 ].stage_parts .empty ()&& split .parts [1 ][1 ].ids == original [2 ].ids && 579split .parts [1 ][1 ].used == original [2 ].used && split .parts [0 ][0 ].gdn == original [0 ].stage_parts [0 ].gdn , 580"split: every stage part carries its checkpoint's ids and LRU stamp" ); 581check (split .stage0 [0 ].gdn .data ()== gdn0 && split .parts [1 ][1 ].gdn .data ()== part1 , 582"split moves the running state (same buffers, no copy)" ); 583 std::vector < ConversationCheckpoint > back ; 584check (conversation_checkpoints_merge (std::move (split ),back )&& back .size ()== 3 ,"merge puts them back" ); 585bool same = true; 586for (size_t j = 0 ;j < back .size ();++ j ) { 587same = same && back [j ].ids == original [j ].ids && back [j ].gdn == original [j ].gdn && 588back [j ].tails == original [j ].tails && back [j ].used == original [j ].used && 589back [j ].stage_parts .size ()== original [j ].stage_parts .size (); 590for (size_t k = 0 ;same && k < back [j ].stage_parts .size ();++ k ) 591same = back [j ].stage_parts [k ].gdn == original [j ].stage_parts [k ].gdn ; 592 } 593check (same ,"merge(split(x)) == x, in the original order" ); 594check (back [0 ].gdn .data ()== gdn0 && back [2 ].stage_parts [1 ].gdn .data ()== part1 ,"merge moves them back too" ); 595 596auto torn = conversation_checkpoints_split (std::vector < ConversationCheckpoint > (original ),2 ); 597torn .parts [1 ].pop_back (); 598check (!conversation_checkpoints_merge (std::move (torn ),back )&& back .empty (),"a stage short of a part is refused" ); 599auto mixed = conversation_checkpoints_split (std::vector < ConversationCheckpoint > (original ),2 ); 600mixed .parts [0 ][0 ].ids = {9 ,9 }; 601check (!conversation_checkpoints_merge (std::move (mixed ),back )&& back .empty (),"a part of another checkpoint is refused" ); 602// a restored image: stage 0's checkpoints and each stage's, with no record of an incomplete one 603ConversationCheckpointSplit restored ; 604restored .stage0 .push_back (running ({4 ,5 },11 ,0 )); 605restored .parts .resize (2 ); 606for (auto & p :restored .parts ) {auto c = running ({4 ,5 },12 ,0 );p .push_back (std::move (c )); } 607check (conversation_checkpoints_merge (std::move (restored ),back )&& back .size ()== 1 && 608back [0 ].stage_parts .size ()== 2 ,"a restored image's parts are all whole" ); 609auto none = conversation_checkpoints_split ({},3 ); 610check (conversation_checkpoints_merge (std::move (none ),back )&& back .empty (),"no checkpoints: nothing to do" ); 611 } 612 { 613// #1503, the cross-conversation leak: the retained K/V of a restored conversation must never be reused to 614// park ANOTHER conversation the main session later holds (a batch slot gave its conversation back) 615auto kv = [](size_t n ) { 616 std::vector < ConversationKv > v (2 ); 617for (auto & l :v )l .k .resize (n ,1 ); 618return v ; 619 }; 620ConversationCache cache (1 <<20 ,4 ); 621const std::vector < int32_t > a = {1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 ,12 ,13 ,14 ,15 ,16 }; 622 std::vector < std::vector < ConversationKv >> st ; 623st .push_back (kv (100 )); 624cache .retain (kv (500 ),16 , std::move (st ),a ); 625 std::vector < int32_t > b (16 ,99 ); 626auto other = cache .take_reuse_for (b ); 627check (other .kv .empty ()&& other .stages .empty ()&& other .unchanged_tokens == 0 , 628"another conversation never gets the retained K/V" ); 629check (cache .retained_bytes ()== 0 ,"the retained K/V is dropped once refused" ); 630cache .retain (kv (500 ),16 , {},a ); 631check (cache .retained_tokens ()== 16 ,"the retained extent is reported" ); 632 std::vector < int32_t > cont (a .begin (),a .begin ()+ 10 ); 633cont .push_back (42 ); 634cont .push_back (43 ); 635auto partly = cache .take_reuse_for (cont ); 636check (partly .unchanged_tokens == 10 && !partly .kv .empty (),"a conversation that diverges reuses only the shared prefix" ); 637 std::vector < std::vector < ConversationKv >> st2 ; 638st2 .push_back (kv (100 )); 639cache .retain (kv (500 ),16 , std::move (st2 ),a ); 640cache .limit_reuse (9 ); 641auto same = cache .take_reuse_for (a ); 642check (same .unchanged_tokens == 9 && same .stages .size ()== 1 && same .stages [0 ].unchanged_tokens == 9 , 643"the same conversation keeps the first rewrite's limit, on every stage" ); 644cache .retain (kv (500 ),16 ); 645check (cache .take_reuse_for (a ).kv .empty (),"retained K/V of unknown identity is never reused" ); 646 647// the sequence of the report: P restored (retained), a slot hands Q to the main session, Q is parked. Q shares 648// only the system prompt with P (4 tokens): with the slot's drop, nothing is reused; without it (the ids check 649// alone), at most the shared system prompt 650const std::vector < int32_t > p = {7 ,7 ,7 ,7 ,100 ,101 ,102 ,103 ,104 ,105 }; 651const std::vector < int32_t > q = {7 ,7 ,7 ,7 ,200 ,201 ,202 ,203 ,204 ,205 ,206 ,207 }; 652 std::vector < std::vector < ConversationKv >> stp ; 653stp .push_back (kv (100 )); 654cache .retain (kv (500 ),10 , std::move (stp ),p ); 655 (void )cache .take_reuse ();// copy_from_slot 656check (cache .take_reuse_for (q ).kv .empty (),"a slot that gave its conversation back drops the retained K/V" ); 657 std::vector < std::vector < ConversationKv >> stp2 ; 658stp2 .push_back (kv (100 )); 659cache .retain (kv (500 ),10 , std::move (stp2 ),p ); 660auto sys_only = cache .take_reuse_for (q ); 661check (sys_only .unchanged_tokens == 4 && sys_only .stages .size ()== 1 && sys_only .stages [0 ].unchanged_tokens == 4 , 662"without the drop, only the shared system prompt is reused, on every stage" ); 663check (cache .retained_bytes ()== 0 ,"taken once" ); 664// a conversation that is a strict extension of the retained one keeps the whole extent 665cache .retain (kv (500 ),10 , {},p ); 666 std::vector < int32_t > p_more = p ; 667p_more .push_back (300 ); 668check (cache .take_reuse_for (p_more ).unchanged_tokens == 10 ,"the conversation's own continuation reuses all of it" ); 669 } 670 { 671// the later stages' retained K/V, kept with the first stage's and limited together 672auto kv = [](size_t n ) { 673 std::vector < ConversationKv > v (2 ); 674for (auto & l :v )l .k .resize (n ,1 ); 675return v ; 676 }; 677ConversationCache cache (1 <<20 ,4 ); 678 std::vector < std::vector < ConversationKv >> stage_kv ; 679stage_kv .push_back (kv (1000 )); 680stage_kv .push_back (kv (2000 )); 681cache .retain (kv (500 ),40 , std::move (stage_kv )); 682check (cache .retained_bytes () >=2 * (500 + 1000 + 2000 ),"retained bytes count every stage" ); 683cache .limit_reuse (30 ); 684auto r = cache .take_reuse (); 685check (r .kv .size ()== 2 && r .stages .size ()== 2 && r .unchanged_tokens == 30 && 686r .stages [0 ].unchanged_tokens == 30 && r .stages [1 ].unchanged_tokens == 30 && 687r .stages [1 ].captured_tokens == 40 ,"every stage's reuse is limited to the first rewrite" ); 688check (cache .retained_bytes ()== 0 ,"taken once" ); 689 std::vector < std::vector < ConversationKv >> big ; 690big .push_back (kv (1 <<20 )); 691cache .retain (kv (500 ),40 , std::move (big )); 692check (cache .retained_bytes ()== 0 ,"a stage's K/V over the budget drops the whole reuse" ); 693 std::vector < std::vector < ConversationKv >> one ; 694one .push_back (kv (100 )); 695cache .retain (kv (500 ),40 , std::move (one )); 696cache .limit_reuse (0 ); 697check (cache .retained_bytes ()== 0 ,"a rewrite from the start drops every stage's reuse" ); 698cache .retain (kv (500 ),40 ); 699r = cache .take_reuse (); 700check (r .kv .size ()== 2 && r .stages .empty (),"no layer split: no stage reuse, as before" ); 701 } 702 {// pin=N: a parked conversation that holds a pinned shared prefix is not the one evicted 703const size_t one = image ({1 ,2 ,3 }).bytes (); 704auto pinned = image ({1 ,2 ,3 }); 705pinned .checkpoints .push_back (ConversationCheckpoint {}); 706pinned .checkpoints .back ().ids = {1 ,2 }; 707pinned .checkpoints .back ().pinned = true; 708pinned .checkpoints .back ().gdn .resize (64 ,1 ); 709const size_t pinned_bytes = pinned .bytes (); 710ConversationCache big (pinned_bytes + one * 2 + 64 ,3 ); 711check (pinned .pinned ()&& !image ({1 ,2 ,3 }).pinned (),"a conversation is pinned when one of its checkpoints is" ); 712check (big .put (std::move (pinned )),"the pinned conversation is parked first (the oldest)" ); 713check (big .put (image ({7 ,8 ,9 }))&& big .put (image ({4 ,5 ,6 }))&& big .size ()== 3 ,"two more fill the slots" ); 714check (big .put (image ({10 ,11 ,12 }))&& big .size ()== 3 && big .evictions ()== 1 , 715"a fourth evicts the oldest unpinned one" ); 716check (big .best (std::vector < int32_t > {1 ,2 ,9 ,9 }, {}, true).tokens == 2 ,"the pinned prefix is still found" ); 717ConversationCache tiny (pinned_bytes + 8 ,2 ); 718auto p2 = image ({1 ,2 ,3 }); 719p2 .checkpoints .push_back (ConversationCheckpoint {}); 720p2 .checkpoints .back ().ids = {1 ,2 }; 721p2 .checkpoints .back ().pinned = true; 722p2 .checkpoints .back ().gdn .resize (64 ,1 ); 723check (tiny .put (std::move (p2 )),"a pinned one fits an empty cache" ); 724check (!tiny .put (image ({7 ,8 ,9 }))&& tiny .size ()== 1 ,"nothing else fits beside it: parking is refused, the pin stays" ); 725 } 726 { 727// #4420: a batch slot's chain holds one checkpoint (its admission's): parking it must not drop (#342) the main session's copy of the 728// same conversation that also holds the root a sibling borrows from (an agent's system prompt and tools) - supersedes_richer() 729// names that case, so the slot is not parked 730auto cp = [](std::vector < int32_t > ids ) {ConversationCheckpoint c ;c .ids = std::move (ids );return c ; }; 731SavedConversation main_copy = image ({1 ,2 ,3 ,4 ,10 ,11 ,12 }); 732main_copy .checkpoints = {cp ({1 ,2 ,3 ,4 }),cp ({1 ,2 ,3 ,4 ,10 ,11 })}; 733ConversationCache cache (1 <<20 ,4 ); 734check (cache .put (std::move (main_copy )),"park the main session's copy with its root and turn checkpoints" ); 735const std::vector < int32_t > slot_ids {1 ,2 ,3 ,4 ,10 ,11 ,12 ,20 ,21 };// the slot decoded the reply 736const std::vector < ConversationCheckpoint > slot_chain {cp ({1 ,2 ,3 ,4 ,10 ,11 })};// the admission's only one 737check (cache .supersedes_richer (slot_ids , {},slot_chain , true),"the slot's park would drop the root checkpoint" ); 738const std::vector < ConversationCheckpoint > full_chain {cp ({1 ,2 ,3 ,4 }),cp ({1 ,2 ,3 ,4 ,10 ,11 })}; 739check (!cache .supersedes_richer (slot_ids , {},full_chain , true),"a chain that holds both loses nothing" ); 740check (!cache .supersedes_richer (slot_ids , {},slot_chain , false),"steering mode is isolated" ); 741check (!cache .supersedes_richer (std::vector < int32_t > {1 ,2 ,3 ,4 ,30 ,31 }, {}, 742 std::vector < ConversationCheckpoint > {cp ({1 ,2 ,3 ,4 ,30 })}, true), 743"another conversation on the same root supersedes nothing" ); 744check (cache .size ()== 1 && cache .superseded ()== 0 ,"the predicate changes nothing" ); 745const auto sib = cache .best (std::vector < int64_t > {1 ,2 ,3 ,4 ,40 }, {}, true); 746check (sib .tokens == 4 && cache .borrows (sib ),"a sibling still borrows the root" ); 747// what drop_superseded does with the slot's chain (the park this rule prevents): the root goes 748check (cache .drop_superseded (slot_ids , {},slot_chain , true)== 1 && cache .size ()== 0 , 749"the slot's chain supersedes the richer copy" ); 750 } 751 { 752// STRATA_PARK_SEGPOOL_MIB: the segment pool's idle bytes count against the budget beside the images, are given back 753// first, and never change what the cache evicts, refuses or parks 754struct FakePool final :SegmentPoolBudget { 755size_t idle = 0 ,shrinks = 0 ,shrunk = 0 ; 756size_t idle_bytes ()const override {return idle ; } 757size_t shrink (size_t want )override {++ shrinks ;const size_t g = std::min (want ,idle );idle -= g ;shrunk += g ;return g ; } 758 }; 759auto sized = [](int32_t id ,size_t bytes ) {SavedConversation s = image ({id });s .live .gdn .resize (bytes ,7 );return s ; }; 760 { 761FakePool pool ; 762ConversationCache cache (10000 ,8 ); 763cache .set_pool (& pool ); 764check (cache .put (sized (1 ,4000 ))&& cache .put (sized (2 ,4000 )),"two images of about 4000 bytes" ); 765const size_t images = cache .bytes (); 766pool .idle = 1800 ; 767check (cache .bytes ()== images && cache .pool_idle_bytes ()== 1800 && cache .resident_bytes ()== images + 1800 , 768"bytes() is the images'; resident_bytes() adds the pool's idle bytes" ); 769check (images + 1800 <=10000 ,"(the images and the idle bytes fit the budget)" ); 770const size_t room = 10000 - images - 400 ;// an incoming image that fits beside the images only if idle bytes go 771check (cache .make_room (room )&& cache .size ()== 2 && cache .evictions ()== 0 ,"an image that fits beside the images needs no eviction, the idle bytes are the ones that go" ); 772check (pool .shrinks >=1 && pool .shrunk == 1800 - 400 && pool .idle == 400 ,"the pool gave back exactly the excess" ); 773check (cache .resident_bytes ()+ room <=10000 ,"images + idle + the incoming image fit the budget" ); 774pool .idle = 9000 ;// far more idle than the budget leaves: all of it is shrinkable, nothing else is touched 775check (cache .make_room (500 )&& cache .size ()== 2 && cache .evictions ()== 0 && cache .resident_bytes ()+ 500 <=10000 , 776"a pool holding more than the budget leaves is trimmed to fit, no image goes" ); 777check (cache .make_room (5500 )&& cache .size ()== 1 && cache .evictions ()== 1 , 778"an incoming image that does not fit beside the images evicts the oldest, as without a pool" ); 779 } 780 { 781// the same random workload against a cache with no pool and one whose pool holds a different idle amount before every step: 782// every answer, size, eviction count and byte count is the same, and the pool's bytes never push the total past the budget 783struct Lcg {uint64_t s ;uint64_t next () {s = s * 6364136223846793005ull + 1442695040888963407ull ;return s >>33 ; } }; 784Lcg rng {12345 }; 785const size_t budget = 24000 ; 786ConversationCache plain (budget ,5 ),pooled (budget ,5 ); 787FakePool pool ; 788pooled .set_pool (& pool ); 789int32_t id = 100 ; 790size_t refused = 0 ,evicted_any = 0 ; 791for (int step = 0 ;step < 4000 ;++ step ) { 792pool .idle = size_t (rng .next () % (budget /2 )); 793const uint64_t op = rng .next () %4 ; 794if (op <=1 ) { 795const size_t n = 300 + size_t (rng .next () %9000 ); 796const bool a = plain .put (sized (id ,n )),b = pooled .put (sized (id ,n )); 797++ id ; 798check (a == b ,"put answers the same with and without a pool" ); 799refused += !a ; 800 }else if (op == 2 ) { 801const size_t incoming = size_t (rng .next () % (budget + 3000 )),held = size_t (rng .next () %3 )== 0 ?size_t (rng .next () %4000 ) :0 ; 802const bool a = plain .make_room (incoming ,held ),b = pooled .make_room (incoming ,held ); 803check (a == b ,"make_room answers the same with and without a pool" ); 804refused += !a ; 805if (b )check (pooled .resident_bytes ()+ incoming + held <=budget ,"a successful make_room leaves images + idle + incoming inside the budget" ); 806 }else if (plain .size ()> 0 ) { 807const size_t at = size_t (rng .next () %plain .size ()); 808SavedConversation x = plain .take (at ),y = pooled .take (at ); 809check (x .live .ids == y .live .ids ,"take returns the same entry" ); 810 } 811check (plain .size ()== pooled .size ()&& plain .evictions ()== pooled .evictions ()&& plain .bytes ()== pooled .bytes (), 812"entries, evictions and bytes are the same with and without a pool" ); 813evicted_any += plain .evictions ()> 0 ; 814 } 815check (refused > 0 && evicted_any > 0 && pool .shrinks > 0 ,"the workload refused, evicted and trimmed the pool at least once" ); 816 } 817 } 818 std::printf ("conversation_cache_test: %d checks passed\n" ,checks ); 819}