diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 598cd0dfa87e..968a9d240200 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -32,6 +32,18 @@ target_compile_features(test-server-learn-ledger PRIVATE cxx_std_17) add_test(NAME test-server-learn-ledger COMMAND test-server-learn-ledger) set_tests_properties(test-server-learn-ledger PROPERTIES LABELS "main") +# Model-free host-pool validator: one byte budget across prompt cache, checkpoints and pages. +add_executable(test-server-host-pool test-server-host-pool.cpp) +target_compile_features(test-server-host-pool PRIVATE cxx_std_23) +add_test(NAME test-server-host-pool COMMAND test-server-host-pool) +set_tests_properties(test-server-host-pool PROPERTIES LABELS "main") + +# Model-free validator: a resident's bytes as a pool-owned handle (RAII release, sharing by reference). +add_executable(test-server-host-bytes test-server-host-bytes.cpp) +target_compile_features(test-server-host-bytes PRIVATE cxx_std_23) +add_test(NAME test-server-host-bytes COMMAND test-server-host-bytes) +set_tests_properties(test-server-host-bytes PROPERTIES LABELS "main") + # Model-free engine-module validator: own thread, move-only jobs, typed refusals, snapshots that never wait. add_executable(test-server-module test-server-module.cpp) target_compile_features(test-server-module PRIVATE cxx_std_20) diff --git a/tests/test-server-host-bytes.cpp b/tests/test-server-host-bytes.cpp new file mode 100644 index 000000000000..e42f773cc618 --- /dev/null +++ b/tests/test-server-host-bytes.cpp @@ -0,0 +1,110 @@ +// what this catches: a resident's bytes as a pool-owned handle (server-host-bytes.h) without a model: +// the last handle releases its bytes to the pool from any thread, sharing a resident costs a reference +// and never its bytes twice, a writer reserves its peak before writing and rolls back if dropped or +// failed, a commit larger than its reservation is refused, and a resident outliving the pool is safe. +#include "../tools/server/server-host-bytes.h" + +#include +#include +#include +#include +#include + +static void require(bool condition, const char * message) { + if (!condition) { + std::cerr << "FAILED: " << message << '\n'; + std::exit(1); + } +} + +static const host_pool_instance ENGINE{ 7, 1794830000 }; + +static size_t committed(const std::shared_ptr & pool) { + return pool->with([](host_pool & p) { return p.committed_bytes(); }); +} +static size_t reserved(const std::shared_ptr & pool) { + return pool->with([](host_pool & p) { return p.reserved_bytes(); }); +} + +static host_bytes_handle write(const std::shared_ptr & pool, host_pool_kind kind, size_t n, uint8_t fill) { + std::vector evict; + auto writer = host_bytes_writer::reserve(pool, kind, n, evict); + require(writer.has_value(), "the reservation is admitted"); + auto buf = writer->buffer(); + std::memset(buf.data(), fill, buf.size()); + auto handle = std::move(*writer).finish(n, host_pool_value::unmeasured()); + require(handle.has_value(), "the bytes commit"); + return *handle; +} + +static void the_last_handle_releases_and_sharing_never_copies() { + auto pool = std::make_shared(ENGINE, 1000); + std::list slot; // a slot's checkpoints + std::list cached; // a cache entry's copy of them + slot.push_back(write(pool, host_pool_kind::checkpoint, 400, 0xAB)); + require(committed(pool) == 400, "one resident, its bytes charged once"); + cached = slot; // the cache takes the slot's checkpoints + require(committed(pool) == 400 && cached.front().get() == slot.front().get(), "sharing is a reference: no second copy, no second charge"); + require(cached.front()->bytes()[0] == 0xAB, "the cache reads the same bytes"); + slot.clear(); // the slot moves on + require(committed(pool) == 400, "still held while the cache holds it"); + cached.pop_front(); // the cache evicts it + require(committed(pool) == 0, "the last handle released it to the pool"); +} + +static void a_writer_reserves_first_and_rolls_back_unless_finished() { + auto pool = std::make_shared(ENGINE, 1000); + { + std::vector evict; + auto writer = host_bytes_writer::reserve(pool, host_pool_kind::cache, 700, evict); + require(writer.has_value(), "admitted"); + require(reserved(pool) == 700 && committed(pool) == 0, "the peak is reserved before any byte is written"); + std::vector evict2; + auto second = host_bytes_writer::reserve(pool, host_pool_kind::cache, 400, evict2); + require(!second && second.error() == host_bytes_refusal::pinned_pressure, "a reserved peak blocks an overflow: typed refusal"); + } // dropped unfinished + require(reserved(pool) == 0 && committed(pool) == 0, "a dropped writer rolls its reservation back"); + { + std::vector evict; + auto writer = host_bytes_writer::reserve(pool, host_pool_kind::cache, 300, evict); + std::move(*writer).fail(); + } + require(reserved(pool) == 0, "a failed copy returns its reservation"); + std::vector evict; + auto writer = host_bytes_writer::reserve(pool, host_pool_kind::page, 200, evict); + writer->buffer(); + auto over = std::move(*writer).finish(201, host_pool_value::unmeasured()); + require(!over && over.error() == host_bytes_refusal::larger_than_reserved, "more than reserved is refused"); + require(reserved(pool) == 0 && committed(pool) == 0, "...and its reservation returns"); +} + +static void releases_from_another_thread_are_safe() { + auto pool = std::make_shared(ENGINE, 1 << 20); + std::vector handles; + for (int i = 0; i < 200; ++i) { + handles.push_back(write(pool, host_pool_kind::checkpoint, 1000, (uint8_t) i)); + } + require(committed(pool) == 200 * 1000, "200 residents charged"); + std::thread t([moved = std::move(handles)]() mutable { moved.clear(); }); + t.join(); + require(committed(pool) == 0, "handles dropped on another thread release every byte"); +} + +static void a_resident_may_outlive_the_pool() { + host_bytes_handle survivor; + { + auto pool = std::make_shared(ENGINE, 1000); + survivor = write(pool, host_pool_kind::cache, 100, 1); + } + require(survivor->size() == 100, "the bytes stay readable after the pool is gone"); + survivor.reset(); // releasing into a gone pool is a no-op, never a crash +} + +int main() { + the_last_handle_releases_and_sharing_never_copies(); + a_writer_reserves_first_and_rolls_back_unless_finished(); + releases_from_another_thread_are_safe(); + a_resident_may_outlive_the_pool(); + std::cout << "test-server-host-bytes: ok\n"; + return 0; +} diff --git a/tests/test-server-host-pool.cpp b/tests/test-server-host-pool.cpp new file mode 100644 index 000000000000..e3993289cb1e --- /dev/null +++ b/tests/test-server-host-pool.cpp @@ -0,0 +1,254 @@ +// what this catches: the host pool's contract (server-host-pool.h, CONTINUUM-ENGINE 4.7.6) without a +// model, in milliseconds: committed + reserved never past the grant at any allocation; bytes reserved +// before a copy and returned on failure; oversized and pinned-pressure refusals typed; eviction by one +// value unit (unmeasured first, then lowest seconds-saved per byte, then least recently used); +// pinned residents never evicted; shrinks below pinned bytes pending, then applied as pins end; +// grants keyed by instance and a strictly rising generation, idempotent on repeat; an evicted +// resident stays charged until its owner physically releases it (regression for Codex's review of +// fork 84aba863e: make_room credited bytes before the owner freed them, so a grant read applied and a +// new reservation was admitted while the old buffers still existed). +#include "../tools/server/server-host-pool.h" + +#include +#include +#include + +static void require(bool condition, const char * message) { + if (!condition) { + std::cerr << "FAILED: " << message << '\n'; + std::exit(1); + } +} + +using K = host_pool_kind; +using O = host_pool_outcome_kind; + +static const host_pool_instance ENGINE{ 4242, 1794830000 }; + +// The accounting invariant, checked after every step of every scenario. +static void within(const host_pool & p, const char * where) { + if (p.outcome() == O::applied) { + require(p.committed_bytes() + p.reserved_bytes() <= p.target_bytes(), where); + } + require(p.pinned_bytes() <= p.committed_bytes(), "pinned bytes are a subset of committed"); + require(p.evicting_bytes() <= p.committed_bytes(), "evicting bytes are a subset of committed: still charged"); +} + +// The owner's protocol: reserve; physically free every resident the pool names and release() it; +// when refused only because those bytes were not freed yet, reserve again. The resident's id. +static uint64_t admit(host_pool & p, K kind, size_t bytes, host_pool_value value, std::vector & freed) { + auto r = p.reserve(kind, bytes); + for (uint64_t id : r.evict) { + p.release(id); + } + freed.insert(freed.end(), r.evict.begin(), r.evict.end()); + if (!r.admitted && r.admitted.error() == host_pool_refusal::awaiting_release) { + r = p.reserve(kind, bytes); + } + require(r.admitted.has_value(), "the allocation is admitted once the named residents are freed"); + require(p.commit(*r.admitted, bytes, value).has_value(), "the reservation commits"); + within(p, "admit stays within the grant"); + return r.admitted->id; +} + +static void eviction_order_is_one_value_unit() { + host_pool p(ENGINE, 1000); + std::vector freed; + const uint64_t cheap = admit(p, K::checkpoint, 300, host_pool_value::measured(1e-6), freed); + const uint64_t blind = admit(p, K::checkpoint, 300, host_pool_value::unmeasured(), freed); + const uint64_t prized = admit(p, K::cache, 300, host_pool_value::measured(5e-6), freed); + require(freed.empty(), "900 of 1000 bytes needs no eviction"); + + admit(p, K::checkpoint, 300, host_pool_value::unmeasured(), freed); + require(freed.size() == 1 && freed[0] == blind, "the unmeasured resident goes first"); + freed.clear(); + + admit(p, K::cache, 300, host_pool_value::measured(9e-6), freed); + require(freed.size() == 1, "one more eviction makes room"); + require(!p.holds(freed[0]) && p.holds(prized), "the higher value per byte is kept"); + require(freed[0] != cheap || !p.holds(cheap), "...and the lowest-valued measured one leaves once only unmeasured are gone"); + require(p.evicted(K::checkpoint) + p.evicted(K::cache) == 2, "each eviction is counted by kind"); +} + +static void reservations_bound_the_peak_and_roll_back() { + host_pool p(ENGINE, 1000); + auto a = p.reserve(K::checkpoint, 700); + require(a.admitted.has_value(), "the first reservation fits"); + within(p, "a reservation counts against the grant before any copy"); + auto b = p.reserve(K::cache, 400); + require(!b.admitted && b.admitted.error() == host_pool_refusal::pinned_pressure, "a reserved peak leaves no room: typed refusal, never an overflow"); + p.rollback(*a.admitted); + require(p.reserved_bytes() == 0 && p.committed_bytes() == 0, "a failed copy returns every reserved byte"); + auto c = p.reserve(K::cache, 400); + require(c.admitted.has_value(), "after the rollback the bytes are free again"); + require(!p.commit(*c.admitted, 401, host_pool_value::unmeasured()).has_value(), "a commit larger than its reservation is refused"); + require(p.commit(*c.admitted, 380, host_pool_value::unmeasured()).has_value(), "a commit at or under its reservation lands"); + require(p.committed_bytes() == 380 && p.reserved_bytes() == 0, "the actual bytes are charged, the rest returns"); + within(p, "commit"); +} + +static void oversized_and_pinned_are_typed_refusals() { + host_pool p(ENGINE, 1000); + std::vector freed; + auto big = p.reserve(K::cache, 1001); + require(!big.admitted && big.admitted.error() == host_pool_refusal::oversized, "larger than the whole grant: oversized"); + const uint64_t held = admit(p, K::checkpoint, 900, host_pool_value::measured(1e-6), freed); + require(p.pin(held), "a restore pins it"); + auto squeezed = p.reserve(K::cache, 200); + require(!squeezed.admitted && squeezed.admitted.error() == host_pool_refusal::pinned_pressure, "a pinned resident is never evicted for a newcomer"); + require(p.holds(held), "the pinned resident is still held"); + require(p.refused(host_pool_refusal::oversized) == 1 && p.refused(host_pool_refusal::pinned_pressure) == 1, "refusals are counted by cause"); + within(p, "refusals leave the accounting intact"); +} + +static void a_shrink_below_pinned_bytes_is_pending_then_applied() { + host_pool p(ENGINE, 1000); + std::vector freed; + const uint64_t pinned = admit(p, K::checkpoint, 600, host_pool_value::measured(2e-6), freed); + const uint64_t loose = admit(p, K::cache, 300, host_pool_value::measured(9e-6), freed); + p.pin(pinned); + auto shrink = p.set_budget(ENGINE, 1, 200); + require(shrink.outcome == O::pending, "pinned bytes above the new target: pending, never a false 'applied'"); + require(shrink.evict.size() == 1 && shrink.evict[0] == loose, "every unpinned resident is evicted toward the target at once"); + require(p.ceiling_bytes() == 900 && p.evicting_bytes() == 300, "the named resident is still charged until its owner frees it"); + p.release(loose); + require(p.ceiling_bytes() == 600 && p.target_bytes() == 200, "the ceiling names what is still held above the target"); + require(p.pinned_bytes() == 600 && p.pinned_bytes() <= p.committed_bytes(), "pinned is reported as a subset of committed"); + auto after = p.unpin(pinned); + require(after.size() == 1 && after[0] == pinned, "when custody ends the pending shrink names the last resident"); + require(p.outcome() == O::pending, "...and still reads pending until that resident is physically freed"); + p.release(pinned); + require(p.outcome() == O::applied && p.committed_bytes() == 0, "the same generation now reads applied"); + within(p, "shrink completed"); +} + +static void zero_budget_is_legal() { + host_pool p(ENGINE, 1000); + std::vector freed; + admit(p, K::cache, 400, host_pool_value::unmeasured(), freed); + admit(p, K::page, 400, host_pool_value::measured(1e-5), freed); + auto zero = p.set_budget(ENGINE, 1, 0); + require(zero.outcome == O::pending && zero.evict.size() == 2, "a zero grant names every unpinned resident, pending until freed"); + for (uint64_t id : zero.evict) { + p.release(id); + } + require(p.outcome() == O::applied && p.committed_bytes() == 0, "nothing is held under a zero grant once freed"); + auto next = p.reserve(K::checkpoint, 1); + require(!next.admitted && next.admitted.error() == host_pool_refusal::oversized, "under a zero grant every allocation is refused, typed"); +} + +static void grants_are_keyed_by_instance_and_generation() { + host_pool p(ENGINE, 1000); + const host_pool_instance other{ 4242, 1794830001 }; + auto foreign = p.set_budget(other, 1, 500); + require(!foreign.outcome && foreign.outcome.error() == host_pool_grant_refusal::wrong_instance, "a grant for another instance is refused"); + require(p.target_bytes() == 1000 && p.generation() == 0, "a refused grant leaves the state exactly as it was"); + require(p.set_budget(ENGINE, 2, 800).outcome == O::applied, "a newer generation applies"); + auto repeat = p.set_budget(ENGINE, 2, 800); + require(repeat.outcome == O::applied && repeat.evict.empty() && p.target_bytes() == 800, "the same generation and size is an idempotent repeat"); + auto conflict = p.set_budget(ENGINE, 2, 700); + require(!conflict.outcome && conflict.outcome.error() == host_pool_grant_refusal::generation_conflict, "the same generation with another size is refused"); + auto stale = p.set_budget(ENGINE, 1, 900); + require(!stale.outcome && stale.outcome.error() == host_pool_grant_refusal::stale_generation, "an older generation is refused"); + require(p.target_bytes() == 800 && p.generation() == 2, "refusals never move the grant"); +} + +static void a_delayed_release_keeps_the_charge() { + host_pool p(ENGINE, 1000); + std::vector freed; + const uint64_t old = admit(p, K::checkpoint, 800, host_pool_value::unmeasured(), freed); + auto r = p.reserve(K::cache, 500); + require(r.evict.size() == 1 && r.evict[0] == old, "the old resident is named for eviction"); + require(!r.admitted && r.admitted.error() == host_pool_refusal::awaiting_release, + "its bytes still exist: refused awaiting_release, never granted on top of them"); + require(!p.holds(old) && !p.pin(old), "a resident being freed is neither held nor pinnable"); + require(p.committed_bytes() == 800 && p.evicting_bytes() == 800, "readback keeps charging the unfreed bytes"); + auto again = p.reserve(K::cache, 500); + require(!again.admitted && again.admitted.error() == host_pool_refusal::awaiting_release && again.evict.empty(), + "asking again before the owner frees it changes nothing and names nothing twice"); + auto shrink = p.set_budget(ENGINE, 1, 900); + require(shrink.outcome == O::applied, "a grant still above the charged bytes applies"); + auto tighter = p.set_budget(ENGINE, 2, 500); + require(tighter.outcome == O::pending, "a grant below the unfreed bytes reads pending, never applied"); + p.release(old); // the owner finally freed it + require(p.outcome() == O::applied && p.committed_bytes() == 0 && p.evicting_bytes() == 0, "only the release credits the bytes"); + require(p.reserve(K::cache, 500).admitted.has_value(), "and now the reservation is admitted"); +} + +static void a_day_of_mixed_traffic_never_exceeds_the_grant() { + // a deterministic stand-in for the residents' traffic: saves, restores, value updates and shrinks + host_pool p(ENGINE, 4096); + std::vector live; + std::vector unfreed; // named for eviction, freed by the owner later (delayed custody) + uint64_t seed = 88172645463325252ull; + auto rnd = [&]() { seed ^= seed << 13; seed ^= seed >> 7; seed ^= seed << 17; return seed; }; + uint64_t generation = 0; + for (int step = 0; step < 20000; ++step) { + switch (rnd() % 6) { + case 0: case 1: case 2: { // a save: reserve, copy (sometimes fails), commit or roll back + const K kind = (K) (rnd() % HOST_POOL_KINDS); + const size_t bytes = 1 + rnd() % 1500; + auto r = p.reserve(kind, bytes); + for (uint64_t id : r.evict) { + require(!p.holds(id), "an evicted resident is no longer held"); + live.erase(std::remove(live.begin(), live.end(), id), live.end()); + unfreed.push_back(id); + } + if (r.admitted) { + if (rnd() % 10 == 0) { + p.rollback(*r.admitted); + } else { + const auto v = rnd() % 3 == 0 ? host_pool_value::unmeasured() : host_pool_value::measured((double) (rnd() % 1000) * 1e-9); + require(p.commit(*r.admitted, bytes - (bytes > 1 ? rnd() % (bytes / 2 + 1) : 0), v).has_value(), "commit within the reservation"); + live.push_back(r.admitted->id); + } + } + break; + } + case 3: { // a restore: pin, then unpin + if (live.empty()) break; + const uint64_t id = live[rnd() % live.size()]; + if (p.pin(id)) { + for (uint64_t gone : p.unpin(id)) { + live.erase(std::remove(live.begin(), live.end(), gone), live.end()); + unfreed.push_back(gone); + } + } + break; + } + case 4: { // the owner frees what was named (late), or a measured restore raises a value + if (!unfreed.empty() && rnd() % 2 == 0) { + const size_t i = rnd() % unfreed.size(); + p.release(unfreed[i]); + unfreed.erase(unfreed.begin() + (long) i); + break; + } + if (live.empty()) break; + p.set_value(live[rnd() % live.size()], host_pool_value::measured((double) (rnd() % 1000) * 1e-8)); + break; + } + case 5: { // the core moves the grant + auto g = p.set_budget(ENGINE, ++generation, 1024 + rnd() % 6000); + for (uint64_t gone : g.evict) { + live.erase(std::remove(live.begin(), live.end(), gone), live.end()); + unfreed.push_back(gone); + } + break; + } + } + within(p, "mixed traffic stays within the grant at every step"); + } +} + +int main() { + eviction_order_is_one_value_unit(); + reservations_bound_the_peak_and_roll_back(); + oversized_and_pinned_are_typed_refusals(); + a_shrink_below_pinned_bytes_is_pending_then_applied(); + zero_budget_is_legal(); + grants_are_keyed_by_instance_and_generation(); + a_delayed_release_keeps_the_charge(); + a_day_of_mixed_traffic_never_exceeds_the_grant(); + std::cout << "test-server-host-pool: ok\n"; + return 0; +} diff --git a/tools/server/server-host-bytes.h b/tools/server/server-host-bytes.h new file mode 100644 index 000000000000..58eb52f89921 --- /dev/null +++ b/tools/server/server-host-bytes.h @@ -0,0 +1,159 @@ +#pragma once + +// Continuum fork: a resident's bytes as a HANDLE the host pool owns (CONTINUUM-ENGINE 4.7.6, 4.7.7). +// +// A checkpoint or cache entry is an immutable, reference-counted buffer whose last handle releases it +// to the pool. Every list that holds residents (a slot's checkpoints, a cache entry's copy of them) +// holds handles, never vectors, so: +// - copying a checkpoint into the cache costs a reference, not a second copy of its bytes; +// - every erase, clear and pop at every call site releases correctly by construction (RAII), with +// no release call to forget; +// - a release may happen on any thread: the pool is reached through a thread-safe owner. +// +// The bytes are reserved before they are written (host_pool::reserve) and committed once complete; +// a reservation that is dropped without a commit rolls back. Pure and header-only, proven by +// tests/test-server-host-bytes.cpp without a model. + +#include "server-host-pool.h" + +#include +#include +#include +#include +#include +#include +#include + +// The pool, reachable from any thread. Every operation is one short critical section; the owner frees +// the residents it names outside the lock. +class host_pool_shared { +public: + host_pool_shared(host_pool_instance instance, size_t launch_budget) : pool_(instance, launch_budget) {} + + template + auto with(F && f) { + std::scoped_lock lock(mutex_); + return std::forward(f)(pool_); + } + +private: + std::mutex mutex_; + host_pool pool_; +}; + +// Committed bytes of one resident. Immutable once built; released to the pool when the last handle +// goes. Never copied: shared by handle. +class host_bytes { +public: + host_bytes(const host_bytes &) = delete; + host_bytes & operator=(const host_bytes &) = delete; + + ~host_bytes() { + if (auto pool = pool_.lock()) { + pool->with([&](host_pool & p) { p.release(id_); }); + } + } + + std::span bytes() const { return data_; } + size_t size() const { return data_.size(); } + uint64_t id() const { return id_; } + host_pool_kind kind() const { return kind_; } + +private: + friend class host_bytes_writer; + host_bytes(std::weak_ptr pool, uint64_t id, host_pool_kind kind, std::vector data) + : pool_(std::move(pool)), id_(id), kind_(kind), data_(std::move(data)) {} + + std::weak_ptr pool_; // weak: a resident never keeps the pool alive + uint64_t id_; + host_pool_kind kind_; + std::vector data_; +}; + +using host_bytes_handle = std::shared_ptr; + +// Why a write did not produce bytes. +enum class host_bytes_refusal : uint8_t { + oversized, // larger than the whole grant + pinned_pressure, // fits the grant, but pinned and reserved bytes leave no room + awaiting_release, // the room is named for eviction; free the returned residents, then retry + write_failed, // the copy into the reservation failed + larger_than_reserved, // the writer produced more than it reserved + pool_gone, // the engine is shutting down +}; + +// A reservation being filled. The writer reserves its whole peak up front, writes into the buffer, +// then finish() commits exactly what it wrote; dropping it unfinished rolls the reservation back. +class host_bytes_writer { +public: + // Reserve `peak` bytes of `kind`. `evict` receives the residents the owner must free now (even when + // the reservation is refused), so the pool's room is real before any byte is written. + static std::expected reserve( + const std::shared_ptr & pool, host_pool_kind kind, size_t peak, std::vector & evict) { + auto result = pool->with([&](host_pool & p) { return p.reserve(kind, peak); }); + evict.insert(evict.end(), result.evict.begin(), result.evict.end()); + if (!result.admitted) { + switch (result.admitted.error()) { + case host_pool_refusal::oversized: return std::unexpected(host_bytes_refusal::oversized); + case host_pool_refusal::pinned_pressure: return std::unexpected(host_bytes_refusal::pinned_pressure); + case host_pool_refusal::awaiting_release: return std::unexpected(host_bytes_refusal::awaiting_release); + } + return std::unexpected(host_bytes_refusal::pinned_pressure); + } + return host_bytes_writer(pool, *result.admitted); + } + + host_bytes_writer(host_bytes_writer && o) noexcept + : pool_(std::move(o.pool_)), reservation_(o.reservation_), data_(std::move(o.data_)), live_(std::exchange(o.live_, false)) {} + host_bytes_writer & operator=(host_bytes_writer &&) = delete; + host_bytes_writer(const host_bytes_writer &) = delete; + + ~host_bytes_writer() { abandon(); } + + // The buffer to write into: sized to the reservation; finish() keeps only `written` bytes. + std::span buffer() { + if (data_.size() != reservation_.bytes) { + data_.resize(reservation_.bytes); + } + return data_; + } + + // Commit the first `written` bytes as an immutable resident at `value`. + std::expected finish(size_t written, host_pool_value value) && { + auto pool = pool_.lock(); + if (!pool) { + live_ = false; + return std::unexpected(host_bytes_refusal::pool_gone); + } + auto committed = pool->with([&](host_pool & p) { return p.commit(reservation_, written, value); }); + if (!committed) { + abandon(); + return std::unexpected(host_bytes_refusal::larger_than_reserved); + } + live_ = false; + data_.resize(written); + data_.shrink_to_fit(); + return host_bytes_handle(new host_bytes(pool_, reservation_.id, reservation_.kind, std::move(data_))); + } + + // The copy failed: return the reservation. + void fail() && { abandon(); } + +private: + host_bytes_writer(std::weak_ptr pool, host_pool_reservation r) : pool_(std::move(pool)), reservation_(r) {} + + void abandon() { + if (!live_) { + return; + } + live_ = false; + if (auto pool = pool_.lock()) { + pool->with([&](host_pool & p) { p.rollback(reservation_); }); + } + } + + std::weak_ptr pool_; + host_pool_reservation reservation_; + std::vector data_; + bool live_ = true; +}; diff --git a/tools/server/server-host-pool.h b/tools/server/server-host-pool.h new file mode 100644 index 000000000000..22927c0bbc43 --- /dev/null +++ b/tools/server/server-host-pool.h @@ -0,0 +1,327 @@ +#pragma once + +// Continuum fork: the engine's host memory as ONE streaming pool (CONTINUUM-ENGINE 4.7.6). +// +// Prompt-cache entries, context checkpoints and RAM pages are kinds of resident in one pool with one +// byte budget, the way a game engine's texture streamer holds one pool. Bytes are RESERVED before a +// resident is serialized or copied (its whole peak), the reservation evicts the lowest-valued unpinned +// residents until it fits, and an allocation that cannot fit after that is a typed refusal, never an +// overflow. The pool decides; it holds no native memory: it names the residents to free and their +// owner frees them on the engine thread (server-context), then calls release(). An evicted resident +// stays CHARGED (state evicting) until that release: the pool never credits bytes that still exist, +// so neither a grant readback nor a new reservation counts memory the owner has not freed yet. +// +// Value is one unit across kinds: expected seconds of prefill saved per byte kept. A resident with no +// measured restore is UNMEASURED (explicit, never a guessed number). Eviction order: unmeasured first, +// least recently used first among them; then measured by ascending value per byte; ties by least +// recently used, then id. Pinned residents (a restore in progress, a save in flight) are never +// evicted. The budget is the core's grant, keyed by engine instance and a strictly rising generation. +// +// Pure and header-only so tests/test-server-host-pool.cpp proves it without a model. + +#include +#include +#include +#include +#include +#include +#include + +enum class host_pool_kind : uint8_t { cache = 0, checkpoint = 1, page = 2 }; +static constexpr size_t HOST_POOL_KINDS = 3; + +inline const char * host_pool_kind_name(host_pool_kind kind) { + switch (kind) { + case host_pool_kind::cache: return "cache"; + case host_pool_kind::checkpoint: return "checkpoint"; + case host_pool_kind::page: return "page"; + } + return "unknown"; +} + +// Why an allocation was not admitted. +enum class host_pool_refusal : uint8_t { + oversized = 0, // larger than the whole budget + pinned_pressure = 1, // would fit the budget, but pinned and reserved bytes leave no room + awaiting_release = 2, // the room is named for eviction but its bytes are not freed yet: free the + // returned residents, then reserve again +}; +static constexpr size_t HOST_POOL_REFUSALS = 3; + +inline const char * host_pool_refusal_name(host_pool_refusal refusal) { + switch (refusal) { + case host_pool_refusal::oversized: return "oversized"; + case host_pool_refusal::pinned_pressure: return "pinned_pressure"; + case host_pool_refusal::awaiting_release: return "awaiting_release"; + } + return "unknown"; +} + +// Expected seconds of prefill saved per byte kept, or unmeasured. +struct host_pool_value { + std::optional s_saved_per_byte; + + static host_pool_value unmeasured() { return {}; } + static host_pool_value measured(double s_saved_per_byte) { return { s_saved_per_byte }; } +}; + +struct host_pool_resident { + host_pool_kind kind; + size_t bytes = 0; + host_pool_value value; + int pins = 0; // restores / saves holding it + uint64_t last_use = 0; // the pool's logical clock + bool evicting = false; // named for eviction; still charged until the owner's release() +}; + +// Bytes granted for one resident not yet committed. +struct host_pool_reservation { + uint64_t id = 0; + host_pool_kind kind = host_pool_kind::cache; + size_t bytes = 0; +}; + +struct host_pool_reserve_result { + std::expected admitted; + std::vector evict; // residents the owner must free now (admitted or not) +}; + +// Why a commit did not land. +enum class host_pool_commit_refusal : uint8_t { + unknown_reservation, // never reserved, already committed, or rolled back + larger_than_reserved, // the copy grew past its reservation: the peak was not bounded +}; + +// The engine instance a grant is meant for. +struct host_pool_instance { + int64_t pid = 0; + int64_t started_s = 0; + + bool operator==(const host_pool_instance & o) const { return pid == o.pid && started_s == o.started_s; } +}; + +// Where a granted budget stands: reached, or still above it while pinned bytes drain. +enum class host_pool_outcome_kind : uint8_t { applied, pending }; + +enum class host_pool_grant_refusal : uint8_t { wrong_instance, stale_generation, generation_conflict }; + +inline const char * host_pool_grant_refusal_name(host_pool_grant_refusal r) { + switch (r) { + case host_pool_grant_refusal::wrong_instance: return "wrong_instance"; + case host_pool_grant_refusal::stale_generation: return "stale_generation"; + case host_pool_grant_refusal::generation_conflict: return "generation_conflict"; + } + return "unknown"; +} + +struct host_pool_grant_result { + std::expected outcome; + std::vector evict; // residents the owner must free now to move toward the target +}; + +class host_pool { +public: + host_pool(host_pool_instance instance, size_t launch_budget) + : instance_(instance), target_(launch_budget) {} + + // ---- the core's grant ------------------------------------------------------------------- + host_pool_grant_result set_budget(host_pool_instance instance, uint64_t generation, size_t bytes) { + // a refusal leaves the state exactly as it was + if (!(instance == instance_)) { + return { std::unexpected(host_pool_grant_refusal::wrong_instance), {} }; + } + if (generation < generation_) { + return { std::unexpected(host_pool_grant_refusal::stale_generation), {} }; + } + if (generation == generation_ && bytes != target_) { + return { std::unexpected(host_pool_grant_refusal::generation_conflict), {} }; + } + generation_ = generation; + target_ = bytes; + auto evict = make_room(0); + return { outcome(), std::move(evict) }; + } + + // ---- allocation --------------------------------------------------------------------------- + // Reserve `bytes` for a new resident of `kind`. The owner frees every id in `evict` (whether or + // not the reservation was admitted), then copies only inside an admitted reservation. + host_pool_reserve_result reserve(host_pool_kind kind, size_t bytes) { + if (bytes > target_) { + refused_[(size_t) host_pool_refusal::oversized]++; + return { std::unexpected(host_pool_refusal::oversized), {} }; + } + auto evict = make_room(bytes); + if (charged() + bytes > target_) { + // short either because pinned/reserved bytes leave no room, or only because evicted bytes + // are not freed yet: the two are different facts for the owner + const auto why = charged() - evicting_ + bytes <= target_ ? host_pool_refusal::awaiting_release + : host_pool_refusal::pinned_pressure; + refused_[(size_t) why]++; + return { std::unexpected(why), std::move(evict) }; + } + const uint64_t id = next_id_++; + reserved_ += bytes; + reservations_[id] = host_pool_reservation{ id, kind, bytes }; + return { reservations_[id], std::move(evict) }; + } + + // The copy succeeded: the reservation becomes a committed resident of its actual `bytes`, at most + // what was reserved (the rest returns to the pool). + std::expected commit(const host_pool_reservation & r, size_t bytes, host_pool_value value) { + auto it = reservations_.find(r.id); + if (it == reservations_.end()) { + return std::unexpected(host_pool_commit_refusal::unknown_reservation); + } + if (bytes > it->second.bytes) { + return std::unexpected(host_pool_commit_refusal::larger_than_reserved); + } + reserved_ -= it->second.bytes; + reservations_.erase(it); + residents_[r.id] = host_pool_resident{ r.kind, bytes, value, 0, ++clock_ }; + committed_[(size_t) r.kind] += bytes; + return {}; + } + + // The copy failed: the reservation's bytes return, nothing is committed. + void rollback(const host_pool_reservation & r) { + auto it = reservations_.find(r.id); + if (it == reservations_.end()) { + return; + } + reserved_ -= it->second.bytes; + reservations_.erase(it); + } + + // The owner PHYSICALLY freed resident `id` (after an eviction, or its own erase): only now does + // its charge end. + void release(uint64_t id) { + auto it = residents_.find(id); + if (it == residents_.end()) { + return; + } + committed_[(size_t) it->second.kind] -= it->second.bytes; + if (it->second.evicting) { + evicting_ -= it->second.bytes; + } + residents_.erase(it); + } + + // ---- use ---------------------------------------------------------------------------------- + // A resident named for eviction cannot be pinned: its owner is freeing it. + bool pin(uint64_t id) { + auto it = residents_.find(id); + if (it == residents_.end() || it->second.evicting) return false; + it->second.pins++; + it->second.last_use = ++clock_; + return true; + } + // Returns the residents to free now that a pin ended (a pending shrink proceeds). + std::vector unpin(uint64_t id) { + auto it = residents_.find(id); + if (it != residents_.end() && it->second.pins > 0) { + it->second.pins--; + } + return make_room(0); + } + void touch(uint64_t id) { + auto it = residents_.find(id); + if (it != residents_.end()) it->second.last_use = ++clock_; + } + void set_value(uint64_t id, host_pool_value value) { + auto it = residents_.find(id); + if (it != residents_.end()) it->second.value = value; + } + + // ---- report ------------------------------------------------------------------------------- + host_pool_outcome_kind outcome() const { + return charged() <= target_ ? host_pool_outcome_kind::applied : host_pool_outcome_kind::pending; + } + host_pool_instance instance() const { return instance_; } + uint64_t generation() const { return generation_; } + size_t target_bytes() const { return target_; } + // What is held now above which nothing new is admitted: the target, or while pending the bytes + // still held above it (falling as custody ends). + size_t ceiling_bytes() const { return charged() > target_ ? charged() : target_; } + size_t reserved_bytes() const { return reserved_; } + // Committed bytes named for eviction and not yet released by their owner (a subset of committed). + size_t evicting_bytes() const { return evicting_; } + size_t committed_bytes() const { size_t s = 0; for (size_t k : committed_) s += k; return s; } + size_t committed_bytes(host_pool_kind k) const { return committed_[(size_t) k]; } + size_t reserved_bytes(host_pool_kind k) const { + size_t s = 0; + for (const auto & [id, r] : reservations_) if (r.kind == k) s += r.bytes; + return s; + } + size_t pinned_bytes(std::optional k = std::nullopt) const { + size_t s = 0; + for (const auto & [id, r] : residents_) if (r.pins > 0 && (!k || r.kind == *k)) s += r.bytes; + return s; + } + size_t count(host_pool_kind k) const { + size_t n = 0; + for (const auto & [id, r] : residents_) if (r.kind == k) n++; + return n; + } + uint64_t evicted(host_pool_kind k) const { return evicted_[(size_t) k]; } + uint64_t refused(host_pool_refusal r) const { return refused_[(size_t) r]; } + // A live resident: committed and not named for eviction. + bool holds(uint64_t id) const { + auto it = residents_.find(id); + return it != residents_.end() && !it->second.evicting; + } + +private: + size_t charged() const { return committed_bytes() + reserved_; } + + // True when `a` should be evicted before `b`. + static bool evict_before(uint64_t a_id, const host_pool_resident & a, uint64_t b_id, const host_pool_resident & b) { + const bool a_measured = a.value.s_saved_per_byte.has_value(); + const bool b_measured = b.value.s_saved_per_byte.has_value(); + if (a_measured != b_measured) { + return !a_measured; // unmeasured first + } + if (a_measured && *a.value.s_saved_per_byte != *b.value.s_saved_per_byte) { + return *a.value.s_saved_per_byte < *b.value.s_saved_per_byte; + } + if (a.last_use != b.last_use) { + return a.last_use < b.last_use; + } + return a_id < b_id; + } + + // Name unpinned residents for eviction until `extra` more bytes WILL fit under the target once + // their owner frees them (or nothing unpinned is left). They stay charged until release(). + std::vector make_room(size_t extra) { + std::vector out; + while (charged() - evicting_ + extra > target_) { + auto victim = residents_.end(); + for (auto it = residents_.begin(); it != residents_.end(); ++it) { + if (it->second.pins > 0 || it->second.evicting) continue; + if (victim == residents_.end() || evict_before(it->first, it->second, victim->first, victim->second)) { + victim = it; + } + } + if (victim == residents_.end()) { + break; // only pinned residents and reservations remain + } + out.push_back(victim->first); + evicted_[(size_t) victim->second.kind]++; + victim->second.evicting = true; + evicting_ += victim->second.bytes; + } + return out; + } + + host_pool_instance instance_; + uint64_t generation_ = 0; + size_t target_ = 0; + size_t reserved_ = 0; + size_t evicting_ = 0; + size_t committed_[HOST_POOL_KINDS] = {0, 0, 0}; + uint64_t evicted_[HOST_POOL_KINDS] = {0, 0, 0}; + uint64_t refused_[HOST_POOL_REFUSALS] = {0, 0, 0}; + uint64_t next_id_ = 1; + uint64_t clock_ = 0; + std::map residents_; + std::map reservations_; +};