Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
serve: a new conversation that starts with a checkpoint of a parked one borrows it, the parked conversation stays (#1164)
Niko1221c9e571e057ca
diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex 49392e821..a75509f8b 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -1037,7 +1037,14 @@ buffer (and at most 16 MiB), which the budget counts like the rest of the snapshRewinds refresh the affected pages, and running state andcheckpoints are captured again. Retained active K/V counts against the same bytebudget and is discarded before evicting parked entries under memory pressure.-Oldest parked entries are evicted first.+Oldest parked entries are evicted first. A new conversation that starts with a+checkpoint inside a parked one (subagents that share a system prompt and tool+list, a compacted history) restores that prefix and leaves the parked+conversation where it is, so its next turn still resumes in full; the engine+log says "borrowed". A match on a parked conversation's live state or its newest+checkpoint is that conversation going on and moves it into the session as+before. When the outgoing conversation fits only in the parked one's room, it+keeps its place and the parked one is moved in whole, as before.Oversized snapshots or host allocation failures fall back to ordinary prompt processing.`--conversation-cache-min-tokens N` (default 0 = park every conversation) parks only conversations of at least Ntokens. A parked conversation costs one of the slots whatever its length, and parking is a switch-time decision, so adiff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hppindex 948986a13..7d09e53bb 100644--- a/include/strata/core/conversation_cache.hpp+++ b/include/strata/core/conversation_cache.hpp@@ -194,6 +194,7 @@ public:size_t index = 0;int64_t tokens = 0;bool live = false;+ uint64_t serial = 0; // the entry's identity; its index shifts when entries before it go};ConversationCache(size_t budget, size_t slots, int64_t min_tokens = 0)@@ -246,7 +247,7 @@ public:if (e.cvec != cvec) continue;auto consider = [&](const ConversationCheckpoint& c, bool live) {const int64_t n = conversation_prefix(c, prompt, images);- if (n > best.tokens) best = {i, n, live};+ if (n > best.tokens) best = {i, n, live, serials_[i]};};consider(e.live, true);for (const auto& c : e.checkpoints) consider(c, false);@@ -257,14 +258,50 @@ public:SavedConversation take(size_t index) {SavedConversation out = std::move(entries_.at(index));bytes_ -= out.bytes();- entries_.erase(entries_.begin() + (std::ptrdiff_t) index);+ erase(index);return out;}+ // A checkpoint inside a parked conversation that a NEW conversation starts with - a sibling subagent sharing the+ // system prompt and tool list, a compacted history - is borrowed: restored from the entry, which stays parked.+ // take() would move the whole conversation into the session and the new request would overwrite everything after+ // that checkpoint, so the other conversation's next turn would read its history again. A match on the entry's+ // live state or on its deepest checkpoint is the same conversation going on (the deepest one: its client+ // re-rendered the last reply), whose tail is stale: that is still taken.+ bool borrows(const Match& m) const {+ if (m.tokens <= 0 || m.live || m.index >= entries_.size() || serials_[m.index] != m.serial) return false;+ size_t deepest = 0;+ for (const auto& c : entries_[m.index].checkpoints) deepest = std::max(deepest, c.ids.size());+ return (size_t) m.tokens < deepest;+ }+ // The entry with this identity: its index (SIZE_MAX: gone), or the entry itself (nullptr: gone; the pointer is+ // valid until the cache changes).+ size_t index_of(uint64_t serial) const {+ for (size_t i = 0; i < entries_.size(); ++i)+ if (serials_[i] == serial) return i;+ return SIZE_MAX;+ }+ const SavedConversation* find(uint64_t serial) const {+ const size_t i = index_of(serial);+ return i == SIZE_MAX ? nullptr : &entries_[i];+ }+ // While a borrowed entry is being restored, parking the outgoing conversation must not evict or drop it. When+ // the outgoing image fits only without it, make_room refuses before evicting anything and pin_blocked() says so:+ // the caller then takes the entry as before, so the conversation that was active a moment ago keeps its place.+ void pin(uint64_t serial) { pinned_ = serial; pin_blocked_ = false; }+ void unpin() { pinned_ = 0; }+ bool pin_blocked() const { return pin_blocked_; }+ size_t borrowed() const { return borrowed_; }+ void count_borrow() { ++borrowed_; }+// Reserve before allocating a snapshot. held is an incoming image removed// with take() but still alive during the exchange; count it against RAM too.bool make_room(size_t incoming, size_t held = 0) {if (!enabled() || held > budget_ || incoming > budget_ - held) return false;+ if (const SavedConversation* p = pinned_ != 0 ? find(pinned_) : nullptr) {+ // with everything else gone, would it fit beside the pinned entry? If not, evict nothing+ if (slots_ < 2 || p->bytes() > budget_ - held - incoming) { pin_blocked_ = true; return false; }+ }if (bytes() > budget_ - held - incoming) reuse_ = {};while (!entries_.empty() && (entries_.size() >= slots_ || bytes_ > budget_ - held - incoming)) {// the oldest entry that does not hold a pinned shared prefix leaves; with only pinned ones left the new@@ -281,12 +318,15 @@ public:// to the kernel at once - the next admission check reads it back from /proc/meminfo.// False when none can go (empty, or only entries that hold a pinned shared prefix are left).bool evict_oldest() {- auto victim = std::find_if(entries_.begin(), entries_.end(), [](const SavedConversation& e) { return !e.pinned(); });- if (victim == entries_.end()) return false;- bytes_ -= victim->bytes();- entries_.erase(victim);- ++evictions_;- return true;+ // the oldest entry that holds no pinned shared prefix and is not the borrowed (pinned) one+ for (size_t i = 0; i < entries_.size(); ++i) {+ if (entries_[i].pinned() || (pinned_ != 0 && serials_[i] == pinned_)) continue;+ bytes_ -= entries_[i].bytes();+ erase(i);+ ++evictions_;+ return true;+ }+ return false;}// #879: every parked conversation (pinned ones too) and the retained K/V go - after non-finite logits any of them@@ -294,6 +334,7 @@ public:size_t clear() {const size_t n = entries_.size();entries_.clear();+ serials_.clear();bytes_ = 0;reuse_ = {};return n;@@ -323,9 +364,10 @@ public:const ConversationCheckpoint* deepest = nullptr;for (const auto& c : e.checkpoints)if (!deepest || c.ids.size() > deepest->ids.size()) deepest = &c;- if (e.cvec == cvec && deepest && !deepest->ids.empty() && held(*deepest)) {+ if (e.cvec == cvec && deepest && !deepest->ids.empty() && held(*deepest) &&+ !(pinned_ != 0 && serials_[i] == pinned_)) {bytes_ -= e.bytes();- entries_.erase(entries_.begin() + (std::ptrdiff_t) i);+ erase(i);++dropped;continue;}@@ -362,14 +404,22 @@ public:drop_superseded(image.live.ids, image.live.imgs, image.checkpoints, image.cvec);if (!make_room(n, held)) return false;entries_.push_back(std::move(image));+ serials_.push_back(next_serial_++);bytes_ += n;return true;}private:- size_t budget_ = 0, slots_ = 0, bytes_ = 0, evictions_ = 0, superseded_ = 0;+ void erase(size_t index) {+ entries_.erase(entries_.begin() + (std::ptrdiff_t) index);+ serials_.erase(serials_.begin() + (std::ptrdiff_t) index);+ }+ size_t budget_ = 0, slots_ = 0, bytes_ = 0, evictions_ = 0, superseded_ = 0, borrowed_ = 0;int64_t min_tokens_ = 0; // --conversation-cache-min-tokens: 0 parks every conversation, whatever its sizestd::deque<SavedConversation> entries_; // least recently active first+ std::deque<uint64_t> serials_; // entries_[i]'s identity, never reused+ uint64_t next_serial_ = 1, pinned_ = 0;+ bool pin_blocked_ = false;ConversationKvReuse reuse_;};diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hppindex 80b1de8ba..d3ded85e7 100644--- a/include/strata/core/conversation_snapshot.hpp+++ b/include/strata/core/conversation_snapshot.hpp@@ -25,6 +25,12 @@ bool conversation_kv_validate(const ConversationKv& image, const QsaState& stateint64_t upto, bool include_index, std::string& error);bool conversation_kv_restore(const ConversationKv& image, const QsaState& state, const ModelGeometry& g,int64_t upto, bool include_index, std::string& error);+// The first `upto` tokens of an image captured at `captured` tokens: the leading bytes of each buffer (cells come+// first in the identity layout, as conversation_kv_save takes them), the image untouched. Cells and indexer rows+// past `upto` in the restored pages hold the image's later tokens until a request writes them, as after a whole+// restore followed by a rewind to a checkpoint.+bool conversation_kv_restore_prefix(const ConversationKv& image, const QsaState& state, const ModelGeometry& g,+ int64_t captured, int64_t upto, bool include_index, std::string& error);// Diagnostic read-back after a synchronized restore. Uses 64 KiB of stack// workspace, compares authoritative bytes and resident draft-ring pages, and// fingerprints the authoritative payload only. Never changes model state.@@ -95,6 +101,12 @@ enum class ConversationRestore { restored, invalid, transfer_failed };ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& session,const ModelGeometry& g, const QsaState& draft,std::string& error);+// The K/V of the image's first `upto` tokens (main layers and the draft layer), not its running state: the caller+// mounts a checkpoint taken at `upto`. For a checkpoint of a parked conversation that a new conversation starts+// with, while the parked one stays where it is (ConversationCache::borrows). Same failure contract as above.+ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation& image, int64_t upto,+ SessionState& session, const ModelGeometry& g,+ const QsaState& draft, std::string& error);// The same with `draft == nullptr`: an image WITHOUT the draft layer's K/V (kv holds the session's own QSA layers// only). A layer split's later stages park this way; the draft ring is saved once, with the first stage's image.@@ -112,5 +124,8 @@ bool conversation_snapshot_validate(const SavedConversation& image, const Sessioconst ModelGeometry& g, const QsaState* draft, std::string& error);ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& session,const ModelGeometry& g, const QsaState* draft, std::string& error);+ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation& image, int64_t upto,+ SessionState& session, const ModelGeometry& g,+ const QsaState* draft, std::string& error);} // namespace strata::corediff --git a/src/core/conversation_cache_test.cpp b/src/core/conversation_cache_test.cppindex 6b6b2defc..f49038fe8 100644--- a/src/core/conversation_cache_test.cpp+++ b/src/core/conversation_cache_test.cpp@@ -309,6 +309,69 @@ int main() {check(cache.put(std::move(no_cp)) && cache.parked_prefix_tokens({1, 2, 3, 9}, {}, {}, true) == 0,"an entry without checkpoints is never reported");}+ {+ // borrowing: a NEW conversation that starts with a checkpoint inside a parked one (a sibling subagent with+ // the same system prompt and tools) restores from it and leaves it parked; the same conversation going on+ // (its live state, or its deepest checkpoint after the client re-rendered the last reply) is still taken+ auto cp = [](std::vector<int32_t> ids) { ConversationCheckpoint c; c.ids = std::move(ids); return c; };+ SavedConversation a = image({});+ a.live.ids = {1, 2, 3, 4, 10, 11, 12, 13};+ a.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 10, 11})};+ ConversationCache cache(1 << 20, 2);+ check(cache.put(std::move(a)), "park subagent A");+ const auto sib = cache.best(std::vector<int64_t>{1, 2, 3, 4, 20, 21}, {}, true);+ check(sib.tokens == 4 && !sib.live && sib.serial != 0 && cache.borrows(sib), "a sibling on A's root borrows");+ const auto again = cache.best(std::vector<int64_t>{1, 2, 3, 4, 10, 11, 30}, {}, true);+ check(again.tokens == 6 && !again.live && !cache.borrows(again),+ "A re-rendered at its deepest checkpoint is taken");+ const auto cont = cache.best(std::vector<int64_t>{1, 2, 3, 4, 10, 11, 12, 13, 14}, {}, true);+ check(cont.live && !cache.borrows(cont), "A going on is taken");+ check(!cache.borrows(cache.best(std::vector<int64_t>{5, 6, 7}, {}, true)), "no match, nothing to borrow");+ // while the outgoing conversations are parked, the pinned donor is neither evicted nor dropped+ cache.pin(sib.serial);+ check(cache.put(image({7, 7, 7})) && cache.put(image({8, 8, 8})), "two outgoing conversations park");+ check(cache.find(sib.serial) != nullptr && cache.size() == 2 && cache.evictions() == 1 && !cache.pin_blocked(),+ "the slot limit evicts the other entry, not the pinned donor");+ check(cache.best(std::vector<int64_t>{7, 7, 7, 1}, {}, true).tokens == 0, "the unpinned one went");+ SavedConversation rewritten = image({1, 2, 3, 4, 10, 11, 40}); // holds A's deepest checkpoint: supersedes A+ rewritten.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 10, 11})};+ check(cache.put(std::move(rewritten)) && cache.find(sib.serial) != nullptr && cache.superseded() == 0,+ "a pinned donor is not dropped as superseded");+ cache.unpin();+ // identity survives index shifts: take an older entry, the donor's serial still finds it+ const auto donor_index = cache.index_of(sib.serial);+ check(donor_index != SIZE_MAX, "donor indexed by its serial");+ check(cache.best(std::vector<int64_t>{1, 2, 3, 4, 10, 11, 12, 13, 14}, {}, true).serial == sib.serial,+ "matches report the entry's serial");+ }+ {+ // the outgoing conversation fits only in the pinned donor's room: make_room refuses before evicting anything+ auto cp = [](std::vector<int32_t> ids) { ConversationCheckpoint c; c.ids = std::move(ids); return c; };+ SavedConversation a = image({1, 2, 3, 4, 10, 11});+ a.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 10})};+ const size_t a_bytes = a.bytes();+ const size_t out_bytes = image({9, 9, 9}).bytes();+ ConversationCache tight(a_bytes + out_bytes - 1, 4);+ check(tight.put(std::move(a)), "park the donor");+ const auto m = tight.best(std::vector<int64_t>{1, 2, 3, 4, 50}, {}, true);+ check(tight.borrows(m), "a sibling would borrow");+ tight.pin(m.serial);+ check(!tight.put(image({9, 9, 9})) && tight.pin_blocked(), "no room beside the pinned donor: refused");+ check(tight.size() == 1 && tight.evictions() == 0, "nothing evicted by the refusal");+ tight.unpin();+ auto taken = tight.take(tight.index_of(m.serial)); // what the caller does then: take it, as before+ check(taken.live.ids.size() == 6 && taken.checkpoints.size() == 2 && tight.size() == 0,+ "the taken donor is whole");+ ConversationCache one_slot(1 << 20, 1);+ SavedConversation b = image({1, 2, 3, 4, 10, 11});+ b.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 10})};+ check(one_slot.put(std::move(b)), "park in a single slot");+ const auto mb = one_slot.best(std::vector<int64_t>{1, 2, 3, 4, 50}, {}, true);+ one_slot.pin(mb.serial);+ check(!one_slot.put(image({9, 9, 9})) && one_slot.pin_blocked() && one_slot.size() == 1,+ "one slot: the pinned donor blocks, nothing evicted");+ one_slot.unpin();+ }{ConversationCache disabled(0,4), no_slots(1024,0);check(!disabled.enabled() && !no_slots.enabled(), "both disable switches");diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cppindex 1468dc652..ac29b3fa4 100644--- a/src/core/conversation_snapshot.cpp+++ b/src/core/conversation_snapshot.cpp@@ -203,11 +203,25 @@ bool conversation_kv_validate(const ConversationKv& image, const QsaState& st, cbool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,int64_t upto, bool index, std::string& error) {- if (!conversation_kv_validate(image, st, g, upto, index, error)) return false;+ return conversation_kv_restore_prefix(image, st, g, upto, upto, index, error);+}++bool conversation_kv_restore_prefix(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,+ int64_t captured, int64_t upto, bool index, std::string& error) {+ if (upto < 0 || upto > captured) {+ error = "conversation snapshot: prefix beyond the captured K/V";+ return false;+ }+ if (!conversation_kv_validate(image, st, g, captured, index, error)) return false;+ Layout l{}; // the prefix's extent; validation above checked the image against the captured one+ if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return false;+ const std::array<size_t,5> sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};const std::array<const ConversationBuffer*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};+ for (size_t i = 0; i < src.size(); ++i)+ if (sizes[i] > src[i]->size()) { error = "conversation snapshot: prefix beyond the K/V payload"; return false; }const auto dst = pools(st);for (size_t i = 0; i < src.size(); ++i)- if (!src[i]->visit(0, src[i]->size(), [&](const uint8_t* p, size_t n, size_t at) {+ if (!src[i]->visit(0, sizes[i], [&](const uint8_t* p, size_t n, size_t at) {return transfer(static_cast<uint8_t*>(dst[i]) + at, p, n, error);})) return false;// VRAM slots still contain the outgoing conversation. Resolve must refilldiff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cppindex b71e8a933..074a3ae9d 100644--- a/src/core/conversation_snapshot_test.cpp+++ b/src/core/conversation_snapshot_test.cpp@@ -193,6 +193,37 @@ void full_session(int fmt, int mode, int experts) {restored.live.dead==a.live.dead && restored.live.block_pos==a.live.block_pos &&equal(restored.kv[0],a.kv[0]) && equal(restored.kv[1],a.kv[1]),"whole-session A/B/A exactness including spare key");check(ss.ple_prev[0]==64 && ss.ple_prev[1]==65,"PLE token window reconstructed");+ {+ // a borrowed prefix (ConversationCache::borrows): the K/V of A's first tokens and A's checkpoint there, A+ // untouched - the same bytes as restoring A whole and rewinding to that checkpoint+ const int64_t at = (int64_t) a.checkpoints[0].ids.size();+ check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore A whole");+ check(conversation_checkpoint_restore(a.checkpoints[0],ss,g,err),"rewind it to its checkpoint");+ ConversationKv want_main,want_draft,got_main,got_draft;+ ConversationCheckpoint want_state,got_state;+ want_state.ids=got_state.ids=a.checkpoints[0].ids;+ check(conversation_kv_save(want_main,main.state,g,at,true,err) &&+ conversation_kv_save(want_draft,draft.state,g,at,false,err) &&+ conversation_checkpoint_save(want_state,ss,g,err),"capture the rewound prefix");+ fill(201); // another conversation in the session+ const SavedConversation untouched=a;+ check(conversation_snapshot_restore_prefix(a,(int64_t)a.live.ids.size()+1,ss,g,draft.state,err)==+ ConversationRestore::invalid &&+ conversation_snapshot_restore_prefix(a,0,ss,g,draft.state,err)==ConversationRestore::invalid,+ "a prefix outside the image is refused");+ check(conversation_snapshot_restore_prefix(a,at,ss,g,draft.state,err)==ConversationRestore::restored,+ "restore A's prefix only");+ check(conversation_checkpoint_restore(a.checkpoints[0],ss,g,err),"mount the checkpoint over it");+ check(conversation_kv_save(got_main,main.state,g,at,true,err) &&+ conversation_kv_save(got_draft,draft.state,g,at,false,err) &&+ conversation_checkpoint_save(got_state,ss,g,err),"capture the borrowed prefix");+ check(equal(got_main,want_main) && equal(got_draft,want_draft),+ "borrowed K/V equals the whole restore's prefix");+ check(got_state.gdn==want_state.gdn && got_state.ple==want_state.ple && got_state.tails==want_state.tails &&+ got_state.dead==want_state.dead && got_state.block_pos==want_state.block_pos,"the same running state");+ check(untouched.live.ids==a.live.ids && equal(untouched.kv[0],a.kv[0]) && equal(untouched.kv[1],a.kv[1]),+ "the parked image is unchanged");+ }for (int64_t dirty : {65, 3, 0}) {check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore growth fixture base");ConversationKvReuse reuse{a.kv,65,dirty};diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cppindex a93715dde..6870e4bb6 100644--- a/src/core/conversation_state.cpp+++ b/src/core/conversation_state.cpp@@ -404,4 +404,31 @@ ConversationRestore conversation_snapshot_restore(const SavedConversation& imageconst ModelGeometry& g, const QsaState& draft, std::string& error) {return conversation_snapshot_restore(image, ss, g, &draft, error);}+ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation& image, int64_t upto,+ SessionState& ss, const ModelGeometry& g,+ const QsaState& draft, std::string& error) {+ return conversation_snapshot_restore_prefix(image, upto, ss, g, &draft, error);+}+ConversationRestore conversation_snapshot_restore_prefix(const SavedConversation& image, int64_t upto,+ SessionState& ss, const ModelGeometry& g,+ const QsaState* draft, std::string& error) {+ // a layer split's image (stage images) is restored stage by stage, never in part+ if (!image.stage_images.empty()) {+ fail(error, "a layer split's image restored as a single session");+ return ConversationRestore::invalid;+ }+ if (!conversation_snapshot_validate(image, ss, g, draft, error)) return ConversationRestore::invalid;+ const int64_t captured = (int64_t) image.live.ids.size();+ if (upto < 1 || upto > captured) {+ fail(error, "the borrowed prefix is not inside the parked conversation");+ return ConversationRestore::invalid;+ }+ if (!sync(error)) return ConversationRestore::transfer_failed;+ for (size_t j = 0; j < owned_qsa(ss); ++j)+ if (!conversation_kv_restore_prefix(image.kv[j], owned(ss, j), g, captured, upto, true, error))+ return ConversationRestore::transfer_failed;+ if (draft && !conversation_kv_restore_prefix(image.kv.back(), *draft, g, captured, upto, false, error))+ return ConversationRestore::transfer_failed;+ return ConversationRestore::restored;+}} // namespace strata::corediff --git a/src/program/generate.cpp b/src/program/generate.cppindex da9637ea9..d6fe2b049 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -11005,8 +11005,16 @@ int main(int argc, char** argv) {}const auto parked = conversations.best(ids, req_imgs, want_cvec);std::optional<strata::core::SavedConversation> incoming;- if (parked.tokens > std::max(resume, slot_tokens)) incoming.emplace(conversations.take(parked.index));- if (incoming) slot_source = -1;+ // A checkpoint inside ANOTHER parked conversation (a sibling subagent's system prompt and tools, say) is+ // borrowed: its K/V up to there and the checkpoint come over, and that conversation stays parked for its+ // own next turn (ConversationCache::borrows). Everything else is taken whole, as before.+ // (a layer split restores whole stage images only, so it never borrows; a batch slot that holds a longer+ // start of this prompt wins as before)+ bool borrow = stages.empty() && parked.tokens > std::max(resume, slot_tokens) &&+ conversations.borrows(parked);+ if (parked.tokens > std::max(resume, slot_tokens) && !borrow)+ incoming.emplace(conversations.take(parked.index));+ if (incoming || borrow) slot_source = -1;// Reject the entire image before parking/overwriting the outgoing// state. Invalid entries can safely fall back to its existing prefix.if (incoming && incoming->stage_images.size() != stages.size()) {@@ -11030,6 +11038,17 @@ int main(int argc, char** argv) {incoming.reset();err.clear();}+ if (borrow) {+ const strata::core::SavedConversation* donor = conversations.find(parked.serial);+ if (donor == nullptr ||+ !strata::core::conversation_snapshot_validate(*donor, ss, g, use_mtp ? &mtp.kv_state() : nullptr,+ err)) {+ std::fprintf(stderr, "strata serve: conversation cache: cannot borrow from a parked conversation "+ "(%s)\n", err.empty() ? "gone" : err.c_str());+ borrow = false;+ err.clear();+ }+ }// Preserve the outgoing branch before any checkpoint rewind, reset,// or incoming restore overwrites the positional state it requires.// pin=N: this request resumes exactly at the pinned shared prefix of the conversation the session holds@@ -11050,8 +11069,30 @@ int main(int argc, char** argv) {: 0;const bool park_worth = o.conversation_cache_park_gain <= 0 || park_held == 0 ||(int64_t) live.size() >= (int64_t) park_held + o.conversation_cache_park_gain;- if ((!from_live || incoming || slot_source >= 0) && !pin_sibling && park_worth &&- !park_current(incoming ? incoming->bytes() : 0)) {+ if (borrow && !pin_sibling && park_worth) {+ conversations.pin(parked.serial); // parking the outgoing conversation must not evict the donor+ const bool parked_ok = park_current(0);+ const bool blocked = conversations.pin_blocked();+ conversations.unpin();+ if (!parked_ok) {+ std::printf("ERR %s\n", err.c_str());+ return 1;+ }+ if (blocked) {+ // the outgoing conversation fits only in the donor's room: it keeps its place, the donor is+ // taken whole as before (it was validated above)+ std::fprintf(stderr, "strata serve: conversation cache: no room beside the parked conversation "+ "this request starts with; taking it instead of borrowing\n");+ borrow = false;+ if (const size_t at = conversations.index_of(parked.serial); at != SIZE_MAX)+ incoming.emplace(conversations.take(at));+ if (!park_current(incoming ? incoming->bytes() : 0)) {+ std::printf("ERR %s\n", err.c_str());+ return 1;+ }+ }+ } else if ((!from_live || incoming || slot_source >= 0) && !pin_sibling && park_worth &&+ !park_current(incoming ? incoming->bytes() : 0)) {std::printf("ERR %s\n", err.c_str());return 1;}@@ -11097,6 +11138,34 @@ int main(int argc, char** argv) {std::printf("ERR the K/V cannot grow to the parked conversation: no VRAM is left\n");return 1;}+ if (borrow) {+ const auto t0 = Clock::now();+ const strata::core::SavedConversation* donor = conversations.find(parked.serial); // still parked+ if (donor == nullptr ||+ strata::core::conversation_snapshot_restore_prefix(*donor, parked.tokens, ss, g,+ use_mtp ? &mtp.kv_state() : nullptr, err) !=+ strata::core::ConversationRestore::restored) {+ // validated above and pinned while parking: a failure here is fatal, as for a whole restore+ std::printf("ERR restoring a borrowed conversation prefix: %s\n",+ err.empty() ? "gone" : err.c_str());+ return 1;+ }+ // the donor's checkpoints on this prompt's path, copied: the donor keeps its own (the one at+ // parked.tokens is mounted below, as for any checkpoint resume)+ checks.clear();+ for (const ConvCheckpoint& c : donor->checkpoints)+ if ((int64_t) c.ids.size() <= parked.tokens && starts_with(c.ids, c.imgs)) checks.push_back(c);+ for (const ConvCheckpoint& c : checks)+ if ((int64_t) c.ids.size() == parked.tokens) { live = c.ids; live_imgs = c.imgs; }+ cvec_cached = donor->cvec;+ resume = parked.tokens;+ from_live = false;+ conversations.count_borrow();+ std::fprintf(stderr, "strata serve: conversation cache: borrowed %lld tokens from a parked "+ "conversation, which stays parked, in %.1f ms; parked=%zu bytes=%zu borrowed=%zu\n",+ (long long) resume, std::chrono::duration<double, std::milli>(Clock::now() - t0).count(),+ conversations.size(), conversations.bytes(), conversations.borrowed());+ }if (incoming) {const auto t0 = Clock::now();if (strata::core::conversation_snapshot_restore(*incoming, ss, g,