okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaconversation cache: best() skips checkpoints no longer than what the request already reuses (the disk tier's compares grew with every saved conversation: ~20 ms at 180)b92a29537

main
53.8 KiB819 linesraw
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;
13    if (!value) { std::fprintf(stderr, "FAIL: %s\n", description); std::exit(1); }
14}
15SavedConversation image(std::initializer_list<int32_t> ids, bool cvec = true) {
16    SavedConversation s;
17    s.live.ids = ids;
18    s.live.gdn.resize(64, 7);
19    s.cvec = cvec;
20    return s;
21}
22}
23
24int main() {
25    {
26        ConversationBuffer bytes;
27        const size_t first = ConversationBuffer::segment_bytes + 17;
28        const size_t peak = bytes.allocation_peak(first);
29        bytes.resize(first, 7);
30        check(bytes.bytes() <= peak, "segmented payload and directory fit admitted bytes");
31        uint8_t* original = nullptr;
32        bytes.visit(0, 1, [&](uint8_t* p, size_t, size_t) { original = p; return true; });
33        const size_t grown_peak = bytes.allocation_peak(first + 99);
34        bytes.resize(first + 99, 9);
35        bytes.visit(0, 1, [&](uint8_t* p, size_t, size_t) {
36            check(p == original, "appending preserves existing payload addresses"); return true;
37        });
38        check(bytes.bytes() <= grown_peak, "growth including transient directory fits admission");
39        std::vector<uint8_t> tail(116);
40        check(bytes.read(tail.data(), ConversationBuffer::segment_bytes, tail.size()), "read spans segment boundaries");
41        check(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");
43        auto copy = bytes;
44        bytes.resize(ConversationBuffer::segment_bytes + 10);
45        bytes.resize(first, 7); bytes.resize(first + 99, 9);
46        check(bytes == copy, "equality ignores differing segmentation after rewind and regrowth");
47        check(!bytes.read(tail.data(), bytes.size()-1, 2), "range check rejects a truncated payload");
48        check(bytes.allocation_peak(SIZE_MAX) == SIZE_MAX, "allocation estimate rejects overflow");
49    }
50    {
51        ConversationBuffer bytes;
52        for (size_t n=1;n<=4096;++n) {
53            const size_t peak = bytes.allocation_peak(n*17);
54            bytes.resize(n*17,7);
55            check(bytes.bytes() <= peak,"small append stays within the predicted allocation peak");
56        }
57        size_t segments = 0;
58        bytes.visit(0,bytes.size(),[&](const uint8_t*,size_t,size_t){++segments;return true;});
59        check(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
64        ConversationBuffer bytes;
65        bytes.resize(ConversationBuffer::segment_bytes, 3);
66        const size_t captured = bytes.bytes();
67        check(captured - bytes.size() < 1024, "a fresh capture reserves nothing");
68        const size_t turn = 1 << 20;
69        const size_t peak = bytes.allocation_peak(bytes.size() + turn);
70        bytes.resize(bytes.size() + turn, 4);
71        check(bytes.bytes() <= peak, "a turn's growth stays within the predicted allocation peak");
72        check(bytes.bytes() - captured <= turn + ConversationBuffer::segment_bytes / 8 + 1024,
73              "the reserve for later turns is at most an eighth of the buffer");
74        const size_t reserved = bytes.bytes();
75        bytes.resize(bytes.size() + turn / 2, 5);
76        check(bytes.bytes() == reserved, "the next small turn fills the reserve instead of allocating");
77        size_t segments = 0;
78        bytes.visit(0, bytes.size(), [&](const uint8_t*, size_t, size_t) { ++segments; return true; });
79        check(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
84        ConversationBuffer bytes;
85        bytes.resize(ConversationBuffer::segment_bytes, 1);
86        for (int k = 0; k < 256; ++k) {
87            const size_t before = bytes.size();
88            const size_t peak = bytes.allocation_peak(before + (1 << 20));
89            bytes.resize(before + (1 << 20), 2);
90            check(bytes.bytes() <= peak, "each turn stays within the predicted allocation peak");
91            check(bytes.bytes() - bytes.size() <= before / 8 + 4096, "the reserve stays within an eighth");
92        }
93        size_t segments = 0;
94        bytes.visit(0, bytes.size(), [&](const uint8_t*, size_t, size_t) { ++segments; return true; });
95        check(segments <= 64, "256 turns of 1 MiB take far fewer than 256 segments");
96    }
97    {
98        ConversationKv layer;
99        layer.k.resize(400);
100        std::vector<ConversationKv> layers;
101        layers.push_back(std::move(layer));
102        const size_t retained = layers.capacity()*sizeof(ConversationKv) + layers[0].bytes();
103        const size_t parked = image({1,2,3}).bytes();
104        ConversationCache cache(retained + parked, 4);
105        check(cache.put(image({1,2,3})), "park before retaining active storage");
106        cache.retain(std::move(layers), 16);
107        check(cache.bytes() == retained + parked && cache.size() == 1, "active retained storage consumes bytes but no parked slot");
108        cache.limit_reuse(9); cache.limit_reuse(12);
109        auto reuse = cache.take_reuse();
110        check(reuse.unchanged_tokens == 9, "a later continuation cannot undo a rewind's dirty boundary");
111        check(cache.bytes() == parked, "taking retained buffers releases their budget accounting");
112        cache.retain(std::move(reuse.kv), 16);
113        check(!cache.can_fit(parked),"retained storage is counted when checking a capture without eviction");
114        check(cache.retained_bytes() == retained && cache.size() == 1 && cache.evictions() == 0,
115              "optional reuse admission does not evict or release anything");
116        check(!cache.can_fit(SIZE_MAX) && !cache.can_fit(1,SIZE_MAX),"non-mutating reservation rejects overflow");
117        check(cache.make_room(parked), "reservation can discard optional active buffers");
118        check(cache.retained_bytes() == 0 && cache.size() == 1 && cache.evictions() == 0,
119              "pressure drops retained storage before evicting parked conversations");
120    }
121    const std::vector<int64_t> a = {1, 2, 3, 4}, b = {9, 8, 7, 6};
122    {
123        ConversationCache cache(1024, 2);
124        check(cache.put(image({1, 2, 3})), "park A");
125        check(cache.put(image({9, 8, 7})), "park B");
126        auto match = cache.best(a, {}, true);
127        check(match.tokens == 3 && match.live, "A/B/A: recover A");
128        auto restored = cache.take(match.index);
129        check(restored.live.ids == std::vector<int32_t>({1, 2, 3}), "taking selected A preserves identity");
130        check(cache.size() == 1 && cache.best(b, {}, true).tokens == 3, "B remains parked");
131        check(cache.bytes() == image({9,8,7}).bytes(), "byte accounting after take");
132        check(cache.put(std::move(restored)), "park returned A as newest");
133        check(cache.put(image({5, 6})), "evict oldest by slot limit");
134        check(cache.best(b, {}, true).tokens == 0 && cache.best(a, {}, true).tokens == 3, "B evicted before A");
135        check(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.
141        ConversationCache cache(4096, 4);
142        cache.put(image({1, 2, 3}));
143        cache.put(image({9, 8, 7}));
144        check(cache.size() == 2 && cache.slots() == 4, "slots() reports the configured limit");
145        const size_t both = cache.bytes();
146        check(cache.evict_oldest(), "evict_oldest reports an eviction");
147        check(cache.size() == 1 && cache.evictions() == 1, "evict_oldest drops exactly one, oldest first");
148        check(cache.best(a, {}, true).tokens == 0 && cache.best(b, {}, true).tokens == 3,
149              "the oldest conversation went, the newest stayed");
150        check(cache.bytes() == both - image({1, 2, 3}).bytes(), "evict_oldest releases the entry's bytes");
151        cache.evict_oldest();
152        check(cache.size() == 0 && cache.bytes() == 0, "evicting the last parked conversation empties the cache");
153        check(!cache.evict_oldest(), "the gate's loop can reach an empty cache: false");
154        check(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)
157        ConversationCache cache(1 << 20, 4);
158        auto pinned = image({1, 2, 3});
159        pinned.checkpoints.push_back(ConversationCheckpoint{});
160        pinned.checkpoints.back().ids = {1, 2};
161        pinned.checkpoints.back().pinned = true;
162        pinned.checkpoints.back().gdn.resize(64, 1);
163        cache.put(std::move(pinned));
164        cache.put(image({9, 8, 7}));
165        check(cache.evict_oldest() && cache.size() == 1, "the oldest unpinned conversation went (the pinned one is older)");
166        check(!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
168        cache.put(image({4, 5, 6}));
169        std::vector<ConversationKv> kv(1);
170        kv[0].cells = 3;
171        kv[0].k.resize(64, 1);
172        cache.retain(std::move(kv), 3);
173        check(cache.retained_bytes() > 0, "a retained K/V before clear()");
174        check(cache.clear() == 2, "clear() reports how many were parked");
175        check(cache.size() == 0 && cache.bytes() == 0 && cache.retained_bytes() == 0, "clear() leaves nothing parked");
176        check(cache.best(std::vector<int64_t>{1, 2, 3, 4}, {}, true).tokens == 0, "a cleared cache matches nothing");
177        check(cache.clear() == 0, "clear() on an empty cache");
178    }
179    {
180        auto s = image({1, 2, 3});
181        ConversationCheckpoint cp;
182        cp.ids = {1, 2};
183        s.checkpoints.push_back(cp);
184        ConversationCache cache(4096, 4);
185        cache.put(std::move(s));
186        auto match = cache.best(std::vector<int64_t>{1, 2, 9, 4}, {}, true);
187        check(match.tokens == 2 && !match.live, "edited suffix falls back to parked checkpoint");
188        check(cache.best(a, {}, true).tokens == 3, "live prefix beats shorter checkpoint");
189        check(cache.best(a, {}, false).tokens == 0, "steering mode is isolated");
190        check(cache.best(std::vector<int64_t>{1, 2}, {}, true).tokens == 0, "equal-length checkpoint cannot consume last token");
191        check(cache.best(std::vector<int64_t>{1}, {}, true).tokens == 0, "short prompt cannot match");
192        check(cache.best(std::vector<int64_t>{}, {}, true).tokens == 0, "empty prompt cannot match");
193        check(cache.best(std::vector<int64_t>{1, 2, 9, 4}, {}, true, 1).tokens == 2, "a floor below the match keeps it");
194        check(cache.best(std::vector<int64_t>{1, 2, 9, 4}, {}, true, 2).tokens == 0, "a floor at the match leaves nothing");
195        check(cache.best(a, {}, true, 2).tokens == 3 && cache.best(a, {}, true, 2).live, "a floor skips only shorter ones");
196        cache.put(image({1, 2, 3}));
197        check(cache.best(a, {}, true).index == 1, "ties prefer most recently parked");
198    }
199    {
200        auto s = image({1, 2, 3});
201        s.live.imgs = {{1, 123}};
202        ConversationCache cache(1024, 3);
203        cache.put(std::move(s));
204        check(cache.best(a, {{1,123}}, true).tokens == 3, "same image can resume");
205        check(cache.best(a, {{1,124}}, true).tokens == 0, "different image pixels invalidate same pad tokens");
206        check(cache.best(a, {}, true).tokens == 0, "missing image invalidates prefix");
207        check(cache.best(a, {{1,123},{2,45}}, true).tokens == 0, "additional image in cached prefix invalidates");
208        check(cache.best(a, {{1,123},{3,45}}, true).tokens == 3, "image after cached prefix does not invalidate");
209    }
210    {
211        const size_t one = image({1,2,3}).bytes();
212        ConversationCache cache(one*2, 8);
213        cache.put(image({1,2,3})); cache.put(image({9,8,7}));
214        check(cache.bytes() == one*2, "budget holds two exact-sized images");
215        auto held = cache.take(cache.best(a, {}, true).index);
216        check(cache.make_room(one, held.bytes()), "count in-flight image when reserving outgoing snapshot");
217        check(cache.size() == 0, "in-flight reservation evicts otherwise fitting B");
218        check(cache.put(image({5,6,7}), held.bytes()), "insert with in-flight accounting");
219        check(cache.bytes()+held.bytes() <= one*2, "exchange obeys byte budget");
220        check(!cache.make_room(one+1, one), "oversized exchange rejected");
221        check(cache.size() == 1, "oversized snapshot does not evict useful entries");
222        auto huge = image({1}); huge.live.gdn.resize(one*3);
223        check(!cache.put(std::move(huge)), "oversized image rejected");
224        check(cache.size() == 1, "oversized put leaves cache unchanged");
225        check(!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.
231        auto cp = [](std::vector<int32_t> ids) { ConversationCheckpoint c; c.ids = std::move(ids); return c; };
232        auto with = [](std::vector<int32_t> prefix, std::initializer_list<int32_t> more) {
233            prefix.insert(prefix.end(), more); return prefix;
234        };
235        const std::vector<int32_t> root = {1, 2, 3, 4};
236        SavedConversation main = image({});
237        main.live.ids = with(with(root, {10, 11, 12}), {13, 14});
238        main.checkpoints = {cp(root), cp(with(root, {10, 11, 12}))};
239        const size_t big = 1 << 20;
240        ConversationCache cache(big, 4);
241        check(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)};
244        for (int turn = 1; turn <= 9; ++turn) {
245            chain.push_back(cp(history));                        // the turn boundary the next request resumes from
246            SavedConversation sub = image({});
247            sub.live.ids = with(history, {900, (int32_t) turn});   // + the reply with its thinking (stale tail)
248            sub.checkpoints = chain;
249            check(cache.put(std::move(sub)), "park SUB turn");
250            check(cache.size() <= 2, "one parked copy of SUB at a time");
251            history = with(history, {30, (int32_t) turn});       // the reply as the next request renders it
252        }
253        check(cache.evictions() == 0 && cache.superseded() == 8, "8 superseded copies dropped, nothing evicted");
254        const auto m = cache.best(with(with(root, {10, 11, 12}), {13, 14, 15}), {}, true);
255        check(m.tokens == 9 && m.live, "MAIN still restores in full");
256        const auto s = cache.best(with(history, {40}), {}, true);
257        check(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)
261        auto s = image({1, 2, 3, 4, 5});
262        ConversationCheckpoint cp;
263        cp.ids = {1, 2, 3};
264        s.checkpoints.push_back(cp);
265        ConversationCache cache(4096, 4);
266        cache.put(std::move(s));
267        check(cache.holds(std::vector<int32_t>{1, 2, 3, 4, 5}, {}, true), "the parked live state itself");
268        check(cache.holds(std::vector<int32_t>{1, 2, 3, 4}, {}, true), "a prefix of the parked live state");
269        check(cache.holds(std::vector<int32_t>{1, 2}, {}, true), "a prefix of a parked checkpoint");
270        check(!cache.holds(std::vector<int32_t>{1, 2, 3, 4, 5, 6}, {}, true), "a longer state is not held");
271        check(!cache.holds(std::vector<int32_t>{1, 2, 9}, {}, true), "a diverging state is not held");
272        check(!cache.holds(std::vector<int32_t>{}, {}, true), "an empty state is never held");
273        check(!cache.holds(std::vector<int32_t>{1, 2, 3}, {}, false), "steering mode is isolated");
274        check(!cache.holds(std::vector<int32_t>{1, 2, 3}, {{1, 77}}, true), "a slot with pictures is not held by a text image");
275        auto p = image({1, 2, 3, 4});
276        p.live.imgs = {{1, 77}, {3, 78}};
277        cache.put(std::move(p));
278        check(cache.holds(std::vector<int32_t>{1, 2, 3}, {{1, 77}}, true), "pictures below the state must match");
279        check(!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
292        auto replay = [&](bool slot_parks, bool checks_back) {
293            std::vector<std::vector<int32_t>> full(4);
294            for (int c = 0; c < 4; ++c) {
295                for (int32_t t = 1; t <= 8; ++t) full[(size_t) c].push_back(c * 100 + t);
296                for (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            }
298            auto 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); };
299            auto cp = [&](int c, size_t n) { ConversationCheckpoint k; k.ids = st(c, n); return k; };
300            auto park = [&](ConversationCache& cache, int c, size_t n, const std::vector<size_t>& cks) {
301                SavedConversation s = image({});
302                s.live.ids = st(c, n);
303                for (size_t k : cks) s.checkpoints.push_back(cp(c, k));
304                check(cache.put(std::move(s)), "the replay's parks all fit the budget");
305            };
306            auto restore = [&](ConversationCache& cache, int c, size_t prompt) -> int64_t {
307                const auto m = cache.best(st(c, prompt), {}, true);
308                if (m.tokens > 0) cache.take(m.index);
309                return m.tokens;
310            };
311            // the main chain after a slot gave "all it holds" back: its checkpoints, or none
312            auto back = [&](const std::vector<size_t>& slot_cks) { return checks_back ? slot_cks : std::vector<size_t>{}; };
313            auto slot_park = [&](ConversationCache& cache, int c, size_t n, const std::vector<size_t>& cks) {
314                if (slot_parks && !cache.holds(st(c, n), {}, true)) park(cache, c, n, cks);
315            };
316            enum { A, B, C, D };
317            ConversationCache 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)
320            park(cache, B, 9, {4});
321            park(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
325            park(cache, A, 12, chain_a);
326            std::vector<size_t> chain_b = back({4});
327            chain_b.push_back(12);
328            // (a request takes its parked conversation before it parks the one it displaces)
329            check(restore(cache, A, 14) == 12, "A's second turn resumes from its parked solo state");
330            park(cache, B, 15, chain_b);
331            chain_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
334            park(cache, A, 14, chain_a);
335            slot_park(cache, B, 17, {12});
336            park(cache, D, 9, {4});
337            slot_park(cache, A, 17, {12});
338            park(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)
342            chain_c.push_back(12);
343            park(cache, C, 15, chain_c);
344            std::vector<size_t> chain_d = back({4});
345            chain_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
349            const int64_t a_found = restore(cache, A, 21);
350            park(cache, D, 14, chain_d);
351            slot_park(cache, C, 17, {12});
352            park(cache, A, 22, {12, 20});
353            const int64_t b_found = restore(cache, B, 21);
354            return std::pair<int64_t, int64_t>(a_found, b_found);
355        };
356        const auto baseline = replay(false, false);
357        check(baseline.first == 14 && baseline.second == 0, "baseline: A returns to its prompt-read state, B to nothing (as measured)");
358        const auto parks_only = replay(true, false);
359        check(parks_only.first == 17 && parks_only.second == 0, "slot parks alone: A whole, B's copy evicted by a stale initial image");
360        const auto both = replay(true, true);
361        check(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
366        auto cp = [](std::vector<int32_t> ids) { ConversationCheckpoint c; c.ids = std::move(ids); return c; };
367        ConversationCache cache(1 << 20, 8);
368        SavedConversation other = image({1, 2, 3, 4, 50, 51, 52});
369        other.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 50, 51})};
370        cache.put(std::move(other));
371        cache.put(image({1, 2, 3, 4, 7, 7}));                    // no checkpoints
372        SavedConversation steered = image({1, 2, 3, 4, 60, 61}, false);
373        steered.checkpoints = {cp({1, 2, 3, 4, 60})};
374        cache.put(std::move(steered));
375        SavedConversation branch = image({1, 2, 3, 4, 60, 70, 71});
376        branch.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 60, 70})};
377        cache.put(std::move(branch));
378        SavedConversation incoming = image({1, 2, 3, 4, 60, 80, 81});
379        incoming.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 60})};
380        check(cache.put(std::move(incoming)), "park a conversation sharing roots with all of them");
381        check(cache.size() == 5 && cache.superseded() == 0, "none of them is superseded");
382        SavedConversation same_state = image({1, 2, 3, 4, 60, 70});   // live equal to the branch's deepest point
383        same_state.checkpoints = {cp({1, 2, 3, 4})};
384        check(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");
386        SavedConversation huge = image({1, 2, 3, 4, 60, 80});
387        huge.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 60})};
388        huge.live.gdn.resize(2 << 20);
389        check(!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.
396        auto cp = [](std::vector<int32_t> ids) { ConversationCheckpoint c; c.ids = std::move(ids); return c; };
397        ConversationCache cache(1 << 20, 8);
398        check(cache.parked_prefix_tokens({1, 2, 3}, {}, {}, true) == 0, "an empty cache supersedes nothing");
399
400        const std::vector<int32_t> live_ids = {1, 2, 3, 4, 60, 70};
401        const std::vector<ConversationCheckpoint> chain = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 60})};
402        SavedConversation same = image({1, 2, 3, 4, 60, 70});
403        same.checkpoints = chain;
404        check(cache.put(std::move(same)), "park a conversation with a checkpoint chain");
405        check(cache.parked_prefix_tokens(live_ids, {}, chain, true) == 5,
406              "the entry the outgoing chain supersedes is reported by its deepest checkpoint");
407
408        const std::vector<ConversationCheckpoint> other_chain = {cp({1, 2, 3})};
409        check(cache.parked_prefix_tokens({1, 2, 3, 40, 50}, {}, other_chain, true) == 0,
410              "a conversation sharing only the root supersedes nothing");
411        check(cache.parked_prefix_tokens(live_ids, {}, chain, false) == 0,
412              "the other steering mode is a different entry");
413        check(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");
415        SavedConversation no_cp = image({1, 2, 3, 9});
416        check(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
423        auto cp = [](std::vector<int32_t> ids) { ConversationCheckpoint c; c.ids = std::move(ids); return c; };
424        SavedConversation a = image({});
425        a.live.ids = {1, 2, 3, 4, 10, 11, 12, 13};
426        a.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 10, 11})};
427        ConversationCache cache(1 << 20, 2);
428        check(cache.put(std::move(a)), "park subagent A");
429        const auto sib = cache.best(std::vector<int64_t>{1, 2, 3, 4, 20, 21}, {}, true);
430        check(sib.tokens == 4 && !sib.live && sib.serial != 0 && cache.borrows(sib), "a sibling on A's root borrows");
431        const auto again = cache.best(std::vector<int64_t>{1, 2, 3, 4, 10, 11, 30}, {}, true);
432        check(again.tokens == 6 && !again.live && !cache.borrows(again),
433              "A re-rendered at its deepest checkpoint is taken");
434        const auto cont = cache.best(std::vector<int64_t>{1, 2, 3, 4, 10, 11, 12, 13, 14}, {}, true);
435        check(cont.live && !cache.borrows(cont), "A going on is taken");
436        check(!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
438        cache.guard(sib.serial);
439        check(cache.put(image({7, 7, 7})) && cache.put(image({8, 8, 8})), "two outgoing conversations park");
440        check(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");
442        check(cache.best(std::vector<int64_t>{7, 7, 7, 1}, {}, true).tokens == 0, "the other one went");
443        SavedConversation rewritten = image({1, 2, 3, 4, 10, 11, 40});   // holds A's deepest checkpoint: supersedes A
444        rewritten.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 10, 11})};
445        check(cache.put(std::move(rewritten)) && cache.find(sib.serial) != nullptr && cache.superseded() == 0,
446              "a guarded donor is not dropped as superseded");
447        cache.unguard();
448        // identity survives index shifts: take an older entry, the donor's serial still finds it
449        const auto donor_index = cache.index_of(sib.serial);
450        check(donor_index != SIZE_MAX, "donor indexed by its serial");
451        check(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
456        auto cp = [](std::vector<int32_t> ids) { ConversationCheckpoint c; c.ids = std::move(ids); return c; };
457        SavedConversation a = image({1, 2, 3, 4, 10, 11});
458        a.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 10})};
459        const size_t a_bytes = a.bytes();
460        const size_t out_bytes = image({9, 9, 9}).bytes();
461        ConversationCache tight(a_bytes + out_bytes - 1, 4);
462        check(tight.put(std::move(a)), "park the donor");
463        const auto m = tight.best(std::vector<int64_t>{1, 2, 3, 4, 50}, {}, true);
464        check(tight.borrows(m), "a sibling would borrow");
465        tight.guard(m.serial);
466        check(!tight.put(image({9, 9, 9})) && tight.guard_blocked(), "no room beside the guarded donor: refused");
467        check(tight.size() == 1 && tight.evictions() == 0, "nothing evicted by the refusal");
468        tight.unguard();
469        auto taken = tight.take(tight.index_of(m.serial));   // what the caller does then: take it, as before
470        check(taken.live.ids.size() == 6 && taken.checkpoints.size() == 2 && tight.size() == 0,
471              "the taken donor is whole");
472        ConversationCache one_slot(1 << 20, 1);
473        SavedConversation b = image({1, 2, 3, 4, 10, 11});
474        b.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 10})};
475        check(one_slot.put(std::move(b)), "park in a single slot");
476        const auto mb = one_slot.best(std::vector<int64_t>{1, 2, 3, 4, 50}, {}, true);
477        one_slot.guard(mb.serial);
478        check(!one_slot.put(image({9, 9, 9})) && one_slot.guard_blocked() && one_slot.size() == 1,
479              "one slot: the guarded donor blocks, nothing evicted");
480        one_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)
485        auto cp = [](std::vector<int32_t> ids, bool pinned = false) {
486            ConversationCheckpoint c; c.ids = std::move(ids); c.pinned = pinned; return c;
487        };
488        SavedConversation doc = image({1, 2, 3, 4, 5, 6, 30, 31});
489        doc.checkpoints = {cp({1, 2, 3, 4, 5, 6}, true), cp({1, 2, 3, 4, 5, 6, 30})};
490        SavedConversation donor = image({1, 2, 10, 11, 12});
491        donor.checkpoints = {cp({1, 2}), cp({1, 2, 10, 11})};
492        ConversationCache cache(1 << 20, 3);
493        check(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");
495        const auto m = cache.best(std::vector<int64_t>{1, 2, 40, 41}, {}, true);
496        check(cache.borrows(m), "a sibling on the donor's root borrows");
497        cache.guard(m.serial);
498        check(cache.put(image({8, 8, 8})) && !cache.guard_blocked() && cache.size() == 3 && cache.evictions() == 1,
499              "the outgoing conversation parks");
500        check(cache.find(m.serial) != nullptr &&
501              cache.best(std::vector<int64_t>{1, 2, 3, 4, 5, 6, 9}, {}, true).tokens == 6 &&
502              cache.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");
504        check(cache.put(image({9, 9, 9})) && cache.size() == 3 && cache.evictions() == 2 &&
505              cache.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");
507        cache.unguard();
508        ConversationCache two(1 << 20, 2);
509        SavedConversation doc2 = image({1, 2, 3, 4, 5, 6, 30});
510        doc2.checkpoints = {cp({1, 2, 3, 4, 5, 6}, true)};
511        SavedConversation donor2 = image({1, 2, 10, 11, 12});
512        donor2.checkpoints = {cp({1, 2}), cp({1, 2, 10, 11})};
513        check(two.put(std::move(doc2)) && two.put(std::move(donor2)), "pinned document and donor fill two slots");
514        const auto m2 = two.best(std::vector<int64_t>{1, 2, 40}, {}, true);
515        two.guard(m2.serial);
516        check(!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");
518        two.unguard();
519        // a match that reaches the pinned prefix is taken, not borrowed: one conversation keeps holding the pin
520        const auto on_pin = two.best(std::vector<int64_t>{1, 2, 3, 4, 5, 6, 77}, {}, true);
521        check(on_pin.tokens == 6 && !on_pin.live && !two.borrows(on_pin), "a pinned prefix is taken, not borrowed");
522        ConversationCache three(1 << 20, 3);
523        SavedConversation doc3 = image({1, 2, 3, 4, 5, 6, 30, 31, 32});
524        doc3.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})};
525        check(three.put(std::move(doc3)), "a conversation past its pinned prefix is parked");
526        const auto past_pin = three.best(std::vector<int64_t>{1, 2, 3, 4, 5, 6, 30, 99}, {}, true);
527        check(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    {
531        ConversationCache disabled(0,4), no_slots(1024,0);
532        check(!disabled.enabled() && !no_slots.enabled(), "both disable switches");
533        check(!disabled.put(image({1,2,3})) && !no_slots.put(image({1,2,3})), "disabled cache stores nothing");
534        check(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).
540        ConversationCache any(1024, 4, 0), floor(1024, 4, 12288);
541        check(any.enabled() && floor.enabled(), "the minimum does not disable the cache");
542        check(any.wants(0) && any.wants(1) && any.wants(1 << 20), "0 parks every length, as before the flag");
543        check(!floor.wants(0) && !floor.wants(1) && !floor.wants(12287), "below the minimum is not parked");
544        check(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
546        ConversationCache negative(1024, 4, -1);
547        check(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
550        ConversationCache disabled_min(0, 4, 12288);
551        check(!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
555        auto running = [](std::initializer_list<int32_t> ids, uint8_t salt, size_t parts) {
556            ConversationCheckpoint c;
557            c.ids = ids;
558            c.gdn.assign(256, salt);
559            c.tails.assign(32, uint8_t(salt + 1));
560            c.used = salt;
561            for (size_t k = 0; k < parts; ++k) {
562                ConversationCheckpoint p;
563                p.gdn.assign(128, uint8_t(salt + 10 + k));
564                c.stage_parts.push_back(std::move(p));
565            }
566            return c;
567        };
568        std::vector<ConversationCheckpoint> checks;
569        checks.push_back(running({1, 2}, 3, 2));
570        checks.push_back(running({1, 2, 3}, 5, 1));       // an incomplete set: kept aside, put back in place
571        checks.push_back(running({1, 2, 3, 4}, 7, 2));
572        const auto original = checks;
573        const uint8_t* gdn0 = checks[0].gdn.data();
574        const uint8_t* part1 = checks[2].stage_parts[1].gdn.data();
575        auto split = conversation_checkpoints_split(std::move(checks), 2);
576        check(checks.empty() && split.stage0.size() == 2 && split.rest.size() == 1 && split.parts.size() == 2 &&
577              split.parts[0].size() == 2 && split.parts[1].size() == 2, "split: complete checkpoints apart, the other aside");
578        check(split.stage0[0].stage_parts.empty() && split.parts[1][1].ids == original[2].ids &&
579              split.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");
581        check(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;
584        check(conversation_checkpoints_merge(std::move(split), back) && back.size() == 3, "merge puts them back");
585        bool same = true;
586        for (size_t j = 0; j < back.size(); ++j) {
587            same = same && back[j].ids == original[j].ids && back[j].gdn == original[j].gdn &&
588                   back[j].tails == original[j].tails && back[j].used == original[j].used &&
589                   back[j].stage_parts.size() == original[j].stage_parts.size();
590            for (size_t k = 0; same && k < back[j].stage_parts.size(); ++k)
591                same = back[j].stage_parts[k].gdn == original[j].stage_parts[k].gdn;
592        }
593        check(same, "merge(split(x)) == x, in the original order");
594        check(back[0].gdn.data() == gdn0 && back[2].stage_parts[1].gdn.data() == part1, "merge moves them back too");
595
596        auto torn = conversation_checkpoints_split(std::vector<ConversationCheckpoint>(original), 2);
597        torn.parts[1].pop_back();
598        check(!conversation_checkpoints_merge(std::move(torn), back) && back.empty(), "a stage short of a part is refused");
599        auto mixed = conversation_checkpoints_split(std::vector<ConversationCheckpoint>(original), 2);
600        mixed.parts[0][0].ids = {9, 9};
601        check(!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
603        ConversationCheckpointSplit restored;
604        restored.stage0.push_back(running({4, 5}, 11, 0));
605        restored.parts.resize(2);
606        for (auto& p : restored.parts) { auto c = running({4, 5}, 12, 0); p.push_back(std::move(c)); }
607        check(conversation_checkpoints_merge(std::move(restored), back) && back.size() == 1 &&
608              back[0].stage_parts.size() == 2, "a restored image's parts are all whole");
609        auto none = conversation_checkpoints_split({}, 3);
610        check(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)
615        auto kv = [](size_t n) {
616            std::vector<ConversationKv> v(2);
617            for (auto& l : v) l.k.resize(n, 1);
618            return v;
619        };
620        ConversationCache cache(1 << 20, 4);
621        const 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;
623        st.push_back(kv(100));
624        cache.retain(kv(500), 16, std::move(st), a);
625        std::vector<int32_t> b(16, 99);
626        auto other = cache.take_reuse_for(b);
627        check(other.kv.empty() && other.stages.empty() && other.unchanged_tokens == 0,
628              "another conversation never gets the retained K/V");
629        check(cache.retained_bytes() == 0, "the retained K/V is dropped once refused");
630        cache.retain(kv(500), 16, {}, a);
631        check(cache.retained_tokens() == 16, "the retained extent is reported");
632        std::vector<int32_t> cont(a.begin(), a.begin() + 10);
633        cont.push_back(42);
634        cont.push_back(43);
635        auto partly = cache.take_reuse_for(cont);
636        check(partly.unchanged_tokens == 10 && !partly.kv.empty(), "a conversation that diverges reuses only the shared prefix");
637        std::vector<std::vector<ConversationKv>> st2;
638        st2.push_back(kv(100));
639        cache.retain(kv(500), 16, std::move(st2), a);
640        cache.limit_reuse(9);
641        auto same = cache.take_reuse_for(a);
642        check(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");
644        cache.retain(kv(500), 16);
645        check(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
650        const std::vector<int32_t> p = {7, 7, 7, 7, 100, 101, 102, 103, 104, 105};
651        const std::vector<int32_t> q = {7, 7, 7, 7, 200, 201, 202, 203, 204, 205, 206, 207};
652        std::vector<std::vector<ConversationKv>> stp;
653        stp.push_back(kv(100));
654        cache.retain(kv(500), 10, std::move(stp), p);
655        (void) cache.take_reuse();   // copy_from_slot
656        check(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;
658        stp2.push_back(kv(100));
659        cache.retain(kv(500), 10, std::move(stp2), p);
660        auto sys_only = cache.take_reuse_for(q);
661        check(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");
663        check(cache.retained_bytes() == 0, "taken once");
664        // a conversation that is a strict extension of the retained one keeps the whole extent
665        cache.retain(kv(500), 10, {}, p);
666        std::vector<int32_t> p_more = p;
667        p_more.push_back(300);
668        check(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
672        auto kv = [](size_t n) {
673            std::vector<ConversationKv> v(2);
674            for (auto& l : v) l.k.resize(n, 1);
675            return v;
676        };
677        ConversationCache cache(1 << 20, 4);
678        std::vector<std::vector<ConversationKv>> stage_kv;
679        stage_kv.push_back(kv(1000));
680        stage_kv.push_back(kv(2000));
681        cache.retain(kv(500), 40, std::move(stage_kv));
682        check(cache.retained_bytes() >= 2 * (500 + 1000 + 2000), "retained bytes count every stage");
683        cache.limit_reuse(30);
684        auto r = cache.take_reuse();
685        check(r.kv.size() == 2 && r.stages.size() == 2 && r.unchanged_tokens == 30 &&
686              r.stages[0].unchanged_tokens == 30 && r.stages[1].unchanged_tokens == 30 &&
687              r.stages[1].captured_tokens == 40, "every stage's reuse is limited to the first rewrite");
688        check(cache.retained_bytes() == 0, "taken once");
689        std::vector<std::vector<ConversationKv>> big;
690        big.push_back(kv(1 << 20));
691        cache.retain(kv(500), 40, std::move(big));
692        check(cache.retained_bytes() == 0, "a stage's K/V over the budget drops the whole reuse");
693        std::vector<std::vector<ConversationKv>> one;
694        one.push_back(kv(100));
695        cache.retain(kv(500), 40, std::move(one));
696        cache.limit_reuse(0);
697        check(cache.retained_bytes() == 0, "a rewrite from the start drops every stage's reuse");
698        cache.retain(kv(500), 40);
699        r = cache.take_reuse();
700        check(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
703        const size_t one = image({1,2,3}).bytes();
704        auto pinned = image({1,2,3});
705        pinned.checkpoints.push_back(ConversationCheckpoint{});
706        pinned.checkpoints.back().ids = {1,2};
707        pinned.checkpoints.back().pinned = true;
708        pinned.checkpoints.back().gdn.resize(64, 1);
709        const size_t pinned_bytes = pinned.bytes();
710        ConversationCache big(pinned_bytes + one * 2 + 64, 3);
711        check(pinned.pinned() && !image({1,2,3}).pinned(), "a conversation is pinned when one of its checkpoints is");
712        check(big.put(std::move(pinned)), "the pinned conversation is parked first (the oldest)");
713        check(big.put(image({7,8,9})) && big.put(image({4,5,6})) && big.size() == 3, "two more fill the slots");
714        check(big.put(image({10,11,12})) && big.size() == 3 && big.evictions() == 1,
715              "a fourth evicts the oldest unpinned one");
716        check(big.best(std::vector<int32_t>{1,2,9,9}, {}, true).tokens == 2, "the pinned prefix is still found");
717        ConversationCache tiny(pinned_bytes + 8, 2);
718        auto p2 = image({1,2,3});
719        p2.checkpoints.push_back(ConversationCheckpoint{});
720        p2.checkpoints.back().ids = {1,2};
721        p2.checkpoints.back().pinned = true;
722        p2.checkpoints.back().gdn.resize(64, 1);
723        check(tiny.put(std::move(p2)), "a pinned one fits an empty cache");
724        check(!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
730        auto cp = [](std::vector<int32_t> ids) { ConversationCheckpoint c; c.ids = std::move(ids); return c; };
731        SavedConversation main_copy = image({1, 2, 3, 4, 10, 11, 12});
732        main_copy.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 10, 11})};
733        ConversationCache cache(1 << 20, 4);
734        check(cache.put(std::move(main_copy)), "park the main session's copy with its root and turn checkpoints");
735        const std::vector<int32_t> slot_ids{1, 2, 3, 4, 10, 11, 12, 20, 21};          // the slot decoded the reply
736        const std::vector<ConversationCheckpoint> slot_chain{cp({1, 2, 3, 4, 10, 11})};   // the admission's only one
737        check(cache.supersedes_richer(slot_ids, {}, slot_chain, true), "the slot's park would drop the root checkpoint");
738        const std::vector<ConversationCheckpoint> full_chain{cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 10, 11})};
739        check(!cache.supersedes_richer(slot_ids, {}, full_chain, true), "a chain that holds both loses nothing");
740        check(!cache.supersedes_richer(slot_ids, {}, slot_chain, false), "steering mode is isolated");
741        check(!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");
744        check(cache.size() == 1 && cache.superseded() == 0, "the predicate changes nothing");
745        const auto sib = cache.best(std::vector<int64_t>{1, 2, 3, 4, 40}, {}, true);
746        check(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
748        check(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
754        struct FakePool final : SegmentPoolBudget {
755            size_t idle = 0, shrinks = 0, shrunk = 0;
756            size_t idle_bytes() const override { return idle; }
757            size_t shrink(size_t want) override { ++shrinks; const size_t g = std::min(want, idle); idle -= g; shrunk += g; return g; }
758        };
759        auto sized = [](int32_t id, size_t bytes) { SavedConversation s = image({id}); s.live.gdn.resize(bytes, 7); return s; };
760        {
761            FakePool pool;
762            ConversationCache cache(10000, 8);
763            cache.set_pool(&pool);
764            check(cache.put(sized(1, 4000)) && cache.put(sized(2, 4000)), "two images of about 4000 bytes");
765            const size_t images = cache.bytes();
766            pool.idle = 1800;
767            check(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");
769            check(images + 1800 <= 10000, "(the images and the idle bytes fit the budget)");
770            const size_t room = 10000 - images - 400;   // an incoming image that fits beside the images only if idle bytes go
771            check(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");
772            check(pool.shrinks >= 1 && pool.shrunk == 1800 - 400 && pool.idle == 400, "the pool gave back exactly the excess");
773            check(cache.resident_bytes() + room <= 10000, "images + idle + the incoming image fit the budget");
774            pool.idle = 9000;   // far more idle than the budget leaves: all of it is shrinkable, nothing else is touched
775            check(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");
777            check(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
783            struct Lcg { uint64_t s; uint64_t next() { s = s * 6364136223846793005ull + 1442695040888963407ull; return s >> 33; } };
784            Lcg rng{12345};
785            const size_t budget = 24000;
786            ConversationCache plain(budget, 5), pooled(budget, 5);
787            FakePool pool;
788            pooled.set_pool(&pool);
789            int32_t id = 100;
790            size_t refused = 0, evicted_any = 0;
791            for (int step = 0; step < 4000; ++step) {
792                pool.idle = size_t(rng.next() % (budget / 2));
793                const uint64_t op = rng.next() % 4;
794                if (op <= 1) {
795                    const size_t n = 300 + size_t(rng.next() % 9000);
796                    const bool a = plain.put(sized(id, n)), b = pooled.put(sized(id, n));
797                    ++id;
798                    check(a == b, "put answers the same with and without a pool");
799                    refused += !a;
800                } else if (op == 2) {
801                    const size_t incoming = size_t(rng.next() % (budget + 3000)), held = size_t(rng.next() % 3) == 0 ? size_t(rng.next() % 4000) : 0;
802                    const bool a = plain.make_room(incoming, held), b = pooled.make_room(incoming, held);
803                    check(a == b, "make_room answers the same with and without a pool");
804                    refused += !a;
805                    if (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) {
807                    const size_t at = size_t(rng.next() % plain.size());
808                    SavedConversation x = plain.take(at), y = pooled.take(at);
809                    check(x.live.ids == y.live.ids, "take returns the same entry");
810                }
811                check(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");
813                evicted_any += plain.evictions() > 0;
814            }
815            check(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}