diff --git a/CMakeLists.txt b/CMakeLists.txt index 5aee5b3ad2..2798951f00 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -235,7 +235,7 @@ if(STRATA_BUILD_CONVERSATION_TESTS) target_compile_features(park_pool_policy_test PRIVATE cxx_std_17) add_test(NAME park_pool_policy_test COMMAND park_pool_policy_test) # the conversation cache's SSD tier: one folder per engine process (a lock), dead ones cleaned, and its budget (header-only) - add_executable(conversation_spill_test src/core/conversation_spill_test.cpp) + add_executable(conversation_spill_test src/core/conversation_spill_test.cpp src/core/conversation_file.cpp) target_include_directories(conversation_spill_test PRIVATE include) target_compile_features(conversation_spill_test PRIVATE cxx_std_17) add_test(NAME conversation_spill_test COMMAND conversation_spill_test) diff --git a/include/strata/core/conversation_spill.hpp b/include/strata/core/conversation_spill.hpp index bb0b4f94d3..853596e6d3 100644 --- a/include/strata/core/conversation_spill.hpp +++ b/include/strata/core/conversation_spill.hpp @@ -13,12 +13,16 @@ // Budget: min(32 GiB, 25% of the free space), never below the free-space floor; a write reserves its estimate first and // the reservation counts until the write ends (temporary files included). +#include "strata/core/conversation_cache.hpp" +#include "strata/core/conversation_file.hpp" + #include #include #include #include #include #include +#include #if defined(_WIN32) #ifndef NOMINMAX @@ -167,4 +171,115 @@ private: spill_detail::LockHandle lock_ = spill_detail::no_lock(); }; +/// The SSD tier's entries: parked conversations written as session files into this process's namespace, oldest first. +/// What stays in RAM per entry is only what matching needs: the token ids and picture keys of its live state and of each +/// checkpoint (no running state, no K/V). put() deletes the oldest entries when the budget needs the room, and never +/// leaves a partial file behind; take() reads an entry back under the caller's read limits and removes it either way (a +/// file that does not read back is not tried again). +class ConversationSpill { +public: + struct Entry { + uint64_t serial = 0; + std::filesystem::path file; + uint64_t bytes = 0; + bool cvec = false; + ConversationCheckpoint live; // ids and images only + std::vector checkpoints; // ids and images only + }; + + bool open(const std::filesystem::path& root, uint64_t cap, std::string& error, size_t* cleaned = nullptr) { + entries_.clear(); + budget_ = SpillBudget{cap, 0, 0}; + return ns_.open(root, error, cleaned); + } + bool enabled() const { return ns_.is_open() && budget_.cap > 0; } + size_t size() const { return entries_.size(); } + uint64_t bytes() const { return budget_.used; } + const SpillBudget& budget() const { return budget_; } + const Entry& entry(size_t i) const { return entries_.at(i); } + const std::filesystem::path& dir() const { return ns_.dir(); } + + /// Writes `image` as an entry. False (with `error`) when the tier is off, the image is larger than the whole tier, or the + /// write failed; nothing of this call is then left on the disk. + bool put(const SavedConversation& image, const SessionFileIdentity& id, std::string& error) { + if (!enabled()) { error = "the SSD tier is off"; return false; } + const uint64_t need = (uint64_t) image.bytes() + (uint64_t(1) << 20); // the payload and the file's own tables + if (need > budget_.cap) { error = "larger than the whole SSD tier"; return false; } + while (!budget_.reserve(need)) { + if (entries_.empty()) { error = "no room in the SSD tier"; return false; } + drop(0); + } + const uint64_t serial = next_serial_++; + const std::filesystem::path f = ns_.file_for(serial); + size_t written = 0; + const bool ok = session_file_write(f.string(), image, id, written, error); + budget_.finish(need, ok ? written : 0); + if (!ok) { + std::error_code ec; + std::filesystem::remove(f, ec); + return false; + } + Entry e; + e.serial = serial; e.file = f; e.bytes = written; e.cvec = image.cvec; + e.live = stub(image.live); + for (const auto& c : image.checkpoints) e.checkpoints.push_back(stub(c)); + entries_.push_back(std::move(e)); + while (budget_.over() && entries_.size() > 1) drop(0); // (a file larger than its estimate) + return true; + } + + /// The entry and the prefix it gives `prompt`, by the RAM cache's rule (ConversationCache::best): its live state or a + /// checkpoint, same pictures, same steering; ties prefer the newest. + template + ConversationCache::Match best(const std::vector& prompt, const std::vector& images, bool cvec) const { + ConversationCache::Match m; + for (size_t i = entries_.size(); i-- > 0;) { + const Entry& e = entries_[i]; + if (e.cvec != cvec) continue; + auto consider = [&](const ConversationCheckpoint& c, bool live) { + const int64_t n = conversation_prefix(c, prompt, images); + if (n > m.tokens) m = {i, n, live, e.serial}; + }; + consider(e.live, true); + for (const auto& c : e.checkpoints) consider(c, false); + } + return m; + } + + /// Reads entry `i` back into `out` (bounded by `limits`, the identity checked) and removes the entry. False: `out` is + /// unchanged and the entry is gone. + bool take(size_t i, const SessionFileIdentity& id, const SessionReadLimits& limits, SavedConversation& out, std::string& error) { + if (i >= entries_.size()) { error = "no such SSD entry"; return false; } + SavedConversation image; + size_t read = 0; + const bool ok = session_file_read(entries_[i].file.string(), id, image, read, error, limits); + drop(i); + if (ok) out = std::move(image); + return ok; + } + + void drop(size_t i) { + std::error_code ec; + std::filesystem::remove(entries_.at(i).file, ec); + budget_.drop(entries_[i].bytes); + entries_.erase(entries_.begin() + (std::ptrdiff_t) i); + } + void close() { + while (!entries_.empty()) drop(entries_.size() - 1); + ns_.close(); + } + +private: + static ConversationCheckpoint stub(const ConversationCheckpoint& c) { + ConversationCheckpoint s; + s.ids = c.ids; + s.imgs = c.imgs; + return s; + } + SpillNamespace ns_; + SpillBudget budget_; + std::vector entries_; + uint64_t next_serial_ = 1; +}; + } // namespace strata::core diff --git a/src/core/conversation_spill_test.cpp b/src/core/conversation_spill_test.cpp index 8bc1701431..a62cf3f526 100644 --- a/src/core/conversation_spill_test.cpp +++ b/src/core/conversation_spill_test.cpp @@ -85,6 +85,60 @@ int main() { check(fs::exists(root) && !fs::exists(root / "4242-0123456789abcdef"), "both engines ended"); std::string err; check(!SpillNamespace().open(root / "notes.txt" / "sub", err) && !err.empty(), "a root that cannot be a folder is refused with a reason"); + + // the entries: written as session files, the oldest go first, matched like the RAM cache, read back exactly + { + auto img = [](std::vector ids, uint8_t fill, std::vector ckpt = {}) { + SavedConversation s; + s.live.ids = ids; + s.live.gdn.assign(1 << 20, fill); // 1 MiB of running state + s.cvec = true; + if (!ckpt.empty()) { ConversationCheckpoint c; c.ids = ckpt; c.gdn.assign(4096, (uint8_t) (fill + 1)); s.checkpoints.push_back(c); } + return s; + }; + const SessionFileIdentity id{11, 22}; + ConversationSpill sp; + // room for two entries of ~2 MiB each (1 MiB payload + the 1 MiB margin per write) + check(sp.open(root, (uint64_t(7) << 19), err) && sp.enabled(), "the tier opens"); + check(sp.put(img({1, 2, 3, 4}, 7, {1, 2}), id, err) && sp.put(img({5, 6, 7}, 9), id, err) && sp.size() == 2, "two entries written"); + const fs::path first = sp.entry(0).file; + check(fs::exists(first) && fs::exists(sp.entry(1).file), "their files exist"); + check(sp.bytes() == sp.entry(0).bytes + sp.entry(1).bytes && sp.budget().reserved == 0, "the budget counts what is written"); + check(sp.put(img({8, 9}, 3), id, err) && sp.size() == 2 && !fs::exists(first), "a third pushes out the oldest, its file deleted"); + auto m = sp.best(std::vector{5, 6, 7, 1}, {}, true); + check(m.tokens == 3 && m.live && sp.entry(m.index).live.ids == std::vector({5, 6, 7}), "a prompt finds the entry it continues"); + check(sp.best(std::vector{1, 2, 3, 4}, {}, true).tokens == 0, "a dropped entry is not found"); + check(sp.best(std::vector{5, 6, 7, 1}, {}, false).tokens == 0, "other steering: not found"); + SavedConversation back; + const fs::path taken = sp.entry(m.index).file; + check(sp.take(m.index, id, {}, back, err) && back.live.ids == std::vector({5, 6, 7}) && + back.live.gdn == std::vector(1 << 20, 9), "taken back byte for byte"); + check(sp.size() == 1 && !fs::exists(taken) && sp.bytes() == sp.entry(0).bytes, "a taken entry leaves the tier"); + // a checkpoint match + check(sp.put(img({20, 21, 22, 23}, 5, {20, 21}), id, err), "an entry with a checkpoint"); + auto mc = sp.best(std::vector{20, 21, 99}, {}, true); + check(mc.tokens == 2 && !mc.live, "a prompt that shares only the checkpoint finds it"); + // another model's identity: refused, the entry goes, out unchanged + SavedConversation keep = img({1}, 1); + check(!sp.take(mc.index, SessionFileIdentity{11, 23}, {}, keep, err) && keep.live.ids == std::vector({1}), "another identity: refused"); + check(sp.size() == 1, "the refused entry is gone"); + // a cut file: refused by the bounded read + { + const fs::path f = sp.entry(0).file; + fs::resize_file(f, fs::file_size(f) / 2, ec); + SavedConversation x; + check(!ec && !sp.take(0, id, {}, x, err) && sp.size() == 0 && !fs::exists(f), "a cut file is refused and removed"); + } + // larger than the whole tier: refused, nothing written + ConversationSpill small; + std::string e2; + check(small.open(root, 1 << 20, e2) && !small.put(img({1, 2}, 4), id, e2) && !e2.empty(), "an image larger than the tier is refused"); + size_t files = 0; + for (auto& x : fs::directory_iterator(small.dir())) if (x.path().filename() != ".lock") ++files; + check(files == 0, "nothing of a refused put is left on the disk"); + small.close(); + sp.close(); + } fs::remove_all(root, ec); std::printf("conversation_spill_test: %d checks, %d failed\n", checks, failures); return failures == 0 ? 0 : 1;