diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 10ec890fe2af..ee695dd04b09 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -32,6 +32,12 @@ 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 validator: streams of frames and moving bytes by reference (rings, doorbell, memory_mover). +add_executable(test-server-frames test-server-frames.cpp) +target_compile_features(test-server-frames PRIVATE cxx_std_20) +add_test(NAME test-server-frames COMMAND test-server-frames) +set_tests_properties(test-server-frames PROPERTIES LABELS "main") + function(llama_build source) set(TEST_SOURCES ${source} ${ARGN}) diff --git a/tests/test-server-frames.cpp b/tests/test-server-frames.cpp new file mode 100644 index 000000000000..a27f9cc783ae --- /dev/null +++ b/tests/test-server-frames.cpp @@ -0,0 +1,430 @@ +// what this catches: the frames-and-references pattern (server-frames.h) without a model: a +// single-producer/single-consumer ring delivers every frame once and in order across threads with no +// lock; many rings run at once; a full ring is backpressure (push refuses, the producer sleeps on an +// atomic until the consumer drains); close wakes a sleeping consumer; and a memory_mover starts every +// transfer without waiting on any, aliases a move within one physical domain (nothing copied), +// refuses an unsupported pair typed (never a silent copy), and streams completions back from two +// producers (the pumping thread and the backend's engine) through two rings and one doorbell. +#include "../tools/server/server-frames.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +static void require(bool condition, const char * message) { + if (!condition) { + std::cerr << "FAILED: " << message << '\n'; + std::exit(1); + } +} + +// One producer and one consumer over `n` frames through a small ring: order and completeness. +static void stream(frame_ring & ring, uint64_t n) { + std::thread producer([&] { + for (uint64_t i = 0; i < n; ++i) { + while (!ring.push(i)) { + ring.wait_for_room(); // backpressure: sleep until the consumer drains + } + } + ring.close(); + }); + uint64_t expect = 0; + uint64_t batch[256]; + while (true) { + const size_t got = ring.drain(batch); + for (size_t i = 0; i < got; ++i) { + require(batch[i] == expect++, "every frame once, in order"); + } + if (got == 0) { + if (ring.closed() && ring.pushed() == ring.taken()) { + break; + } + ring.wait_for_frames(); + } + } + producer.join(); + require(expect == n, "the consumer saw every frame"); +} + +static void one_stream_delivers_every_frame_in_order() { + frame_ring ring(64); + stream(ring, 2'000'000); +} + +static void many_streams_run_at_once() { + std::vector>> rings; + for (int i = 0; i < 8; ++i) { + rings.push_back(std::make_unique>(128)); + } + std::vector pairs; + for (auto & r : rings) { + pairs.emplace_back([&r] { stream(*r, 250'000); }); + } + for (auto & t : pairs) { + t.join(); + } +} + +static void a_full_ring_is_backpressure() { + frame_ring ring(4); + for (uint64_t i = 0; i < 4; ++i) { + require(ring.push(i), "fits"); + } + require(!ring.push(99), "a full ring refuses the push at once: backpressure is visible"); + uint64_t out[2]; + require(ring.drain(out) == 2 && out[0] == 0 && out[1] == 1, "the consumer drains in order"); + require(ring.push(4) && ring.push(5), "room returns as soon as it drains"); +} + +static void close_wakes_a_waiting_consumer() { + frame_ring ring(8); + std::thread consumer([&] { ring.wait_for_frames(); }); + ring.close(); + consumer.join(); + require(ring.closed(), "the stream ended and the consumer woke"); +} + +// A stand-in backend: host and device are one physical domain (unified memory), so a move between +// them aliases; a disk -> host move runs on its own engine (a worker standing in for DMA) and +// completes later from that one context; anything else is refused. +class test_mover final : public memory_mover { +public: + test_mover(frame_ring & in, size_t done_capacity) + : memory_mover(in, done_capacity, 1), engine_([this](std::stop_token stop) { run(stop); }) {} + ~test_mover() override { + engine_.request_stop(); + work_.close(); + engine_.join(); + } + +private: + bool aliases(const buffer_ref & a, const buffer_ref & b) const override { + const auto physical = [](memory_domain d) { return d == memory_domain::disk ? 1 : 0; }; + return physical(a.domain) == physical(b.domain); + } + start_result start(const transfer_frame & t) override { + if (!(t.src.domain == memory_domain::disk && t.dst.domain == memory_domain::host)) { + return start_result::refused; + } + // started, not finished; a full engine queue is would_block, never a wait + return work_.push(t) ? start_result::started : start_result::would_block; + } + void run(std::stop_token stop) { + transfer_frame batch[32]; + while (!stop.stop_requested() || work_.pushed() != work_.taken()) { + const size_t n = work_.drain(batch); + for (size_t i = 0; i < n; ++i) { + complete(0, batch[i].ticket, transfer_status::moved, transfer_done_frame::NO_SLOT); // its one context + } + if (n == 0) { + if (work_.closed()) break; + work_.wait_for_frames(); + } + } + } + + frame_ring work_{ 64 }; + std::jthread engine_; +}; + +static void a_mover_streams_moves_without_waiting() { + frame_ring in(1024); + std::map done; + { + test_mover mover(in, 1024); + const buffer_ref disk{ memory_domain::disk, 1, 7, 0, 0, 4096 }; + const buffer_ref host{ memory_domain::host, 0, 3, 0, 0, 4096 }; + const buffer_ref dev{ memory_domain::device, 2, 9, 0, 0, 4096 }; + uint64_t ticket = 0; + for (int i = 0; i < 300; ++i) { + require(in.push({ ++ticket, disk, host }), "a page read is queued"); // moved later + require(in.push({ ++ticket, host, dev }), "a host->device move is queued"); // aliased now + require(in.push({ ++ticket, dev, disk }), "a device->disk move is queued"); // refused (unsupported here) + mover.pump(); + } + while (done.size() < 900) { + const uint64_t bell = mover.doorbell(); // read BEFORE draining: a ring after it wakes us + mover.pump(); // resume anything that was waiting for room + transfer_done_frame batch[64]; + const size_t n = mover.drain_done(batch); + for (size_t i = 0; i < n; ++i) { + require(done.emplace(batch[i].ticket, batch[i].status).second, "each completion once"); + } + if (n == 0) mover.wait_done(bell); + } + } + size_t moved = 0, aliased = 0, refused = 0; + for (auto & [t, s] : done) { + const int kind = (int) ((t - 1) % 3); + if (kind == 0) { require(s == transfer_status::moved, "a disk read moves on the engine"); moved++; } + if (kind == 1) { require(s == transfer_status::aliased, "within one physical domain nothing is copied"); aliased++; } + if (kind == 2) { require(s == transfer_status::refused, "an unsupported pair is refused typed, never copied by the CPU"); refused++; } + } + require(moved == 300 && aliased == 300 && refused == 300, "every transfer completed exactly once"); +} + +// A test pool: issues pins on its bytes and counts the ones out (the custody a mover must hold and return). +struct pin_pool { + std::atomic out{0}; + static void unpin(void * pool, uint64_t) noexcept { static_cast(pool)->out.fetch_sub(1); } + buffer_pin pin(std::byte * data, uint64_t bytes) { + out.fetch_add(1); + return buffer_pin(data, bytes, this, &unpin, 0); + } +}; + +// The parallel copier: many transfers in flight, each split across lanes; bytes arrive exactly; every +// ticket completes once; a size mismatch and a disk pair are refused typed. +static void run_copies(size_t lanes, size_t chunk, size_t n_transfers, size_t bytes_each, double * gbps) { + std::vector> src(n_transfers), dst(n_transfers); + for (size_t i = 0; i < n_transfers; ++i) { + src[i].resize(bytes_each); + dst[i].assign(bytes_each, std::byte{0}); + for (size_t b = 0; b < bytes_each; b += 4096) src[i][b] = std::byte(uint8_t(i * 31 + b / 4096)); + } + // pool 0 = sources, pool 1 = destinations; buffer = index + pin_pool pool; + auto resolve = [&](const buffer_ref & r) -> buffer_pin { + auto & v = r.pool == 0 ? src : dst; + // the custody contract: a live generation (0 here) and in bounds, else no pin + if (r.generation != 0 || r.buffer >= v.size() || r.offset + r.bytes > v[r.buffer].size()) return {}; + return pool.pin(v[r.buffer].data() + r.offset, v[r.buffer].size() - r.offset); + }; + frame_ring in(n_transfers + 8); + std::map done; + const auto t0 = std::chrono::steady_clock::now(); + { + parallel_copier mover(in, resolve, lanes, chunk, 64); + for (size_t i = 0; i < n_transfers; ++i) { + const buffer_ref s{ memory_domain::host, 0, (uint32_t) i, 0, 0, bytes_each }; + const buffer_ref d{ memory_domain::host, 1, (uint32_t) i, 0, 0, bytes_each }; + require(in.push({ i + 1, s, d }), "queued"); + } + const buffer_ref bad_s{ memory_domain::host, 0, 0, 0, 0, bytes_each }; + const buffer_ref bad_d{ memory_domain::host, 1, 0, 0, 0, bytes_each - 1 }; + require(in.push({ n_transfers + 1, bad_s, bad_d }), "queued"); // size mismatch + require(in.push({ n_transfers + 2, bad_s, { memory_domain::disk, 9, 0, 0, 0, bytes_each } }), "queued"); // disk pair + while (done.size() < n_transfers + 2) { + const uint64_t bell = mover.doorbell(); + mover.pump(); // starts what the lanes have room for and returns: never waits + transfer_done_frame batch[64]; + const size_t n = mover.drain_done(batch); + for (size_t i = 0; i < n; ++i) { + require(done.emplace(batch[i].ticket, batch[i].status).second, "each ticket completes once"); + } + if (n == 0) mover.wait_done(bell); + } + } + const double secs = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + if (gbps) *gbps = (double) n_transfers * (double) bytes_each / secs / 1e9; + for (size_t i = 0; i < n_transfers; ++i) { + require(done[i + 1] == transfer_status::moved, "every copy moved"); + require(std::memcmp(src[i].data(), dst[i].data(), bytes_each) == 0, "the bytes arrived exactly"); + } + require(done[n_transfers + 1] == transfer_status::refused, "a size mismatch is refused, never truncated"); + require(done[n_transfers + 2] == transfer_status::refused, "a disk pair is refused by the host copier"); + require(pool.out.load() == 0, "every pin returned"); +} + +// what this catches (Codex on #134): a consumer's close raced the producer's tail store, erasing the closed +// bit or stranding a frame whose push returned true; and a producer waiting for room never woke on close +static void a_close_never_strands_an_accepted_frame() { + for (int round = 0; round < 2000; ++round) { + frame_ring ring(8); + std::atomic accepted{0}; + std::atomic producer_done{false}; + std::thread producer([&] { + for (uint64_t i = 1; i < 1000; ++i) { + if (ring.push(i)) { + accepted.fetch_add(1); + } else if (ring.closed() || !ring.wait_for_room()) { + break; // closed: wait_for_room returns false rather than sleeping forever + } + } + producer_done = true; + }); + uint64_t drained = 0, buf[8]; + for (int k = 0; k < round % 7; ++k) drained += ring.drain(buf); + ring.close(); + producer.join(); + while (size_t n = ring.drain(buf)) drained += n; + require(ring.closed(), "the closed bit survives a racing push"); + require(drained == accepted.load(), "every frame whose push returned true is drained"); + } +} + +// Codex's #134 review, one regression each. +using done_map = std::map; +static void drain_all(memory_mover & mover, done_map & done, size_t want) { + while (done.size() < want) { + const uint64_t bell = mover.doorbell(); + mover.pump(); + transfer_done_frame batch[4]; + const size_t n = mover.drain_done(batch); + for (size_t i = 0; i < n; ++i) { + require(done.emplace(batch[i].ticket, batch[i].status).second, "each ticket has exactly one terminal frame"); + } + if (n == 0) mover.wait_done(bell); + } +} + +// what this catches: settlements published into a full completion ring slept inside pump, while the same +// caller could only drain after pump returned (capacity 2 + 3 aliases deadlocked) +static void a_full_completion_ring_is_backpressure_not_a_deadlock() { + std::vector a(4096), b(4096); + pin_pool pool; + auto resolve = [&](const buffer_ref & r) -> buffer_pin { + auto & v = r.buffer == 0 ? a : b; + if (r.generation != 0 || r.offset + r.bytes > v.size()) return {}; + return pool.pin(v.data() + r.offset, v.size() - r.offset); + }; + frame_ring in(16); + parallel_copier mover(in, resolve, 2, 4096, 2); + const buffer_ref x{ memory_domain::host, 0, 0, 0, 0, 4096 }; + for (uint64_t t = 1; t <= 5; ++t) require(in.push({ t, x, x }), "queued"); + mover.pump(); // must return with settlements held, never sleep + require(mover.blocked(), "unsettled frames are reported as backpressure"); + done_map done; + drain_all(mover, done, 5); + for (auto & [t, s] : done) require(s == transfer_status::aliased, "each alias settles once"); +} + +// what this catches: an alias succeeded before validation (unequal lengths, a stale generation), and +// overlapping ranges in one buffer reached parallel memcpy (UB) +static void invalid_aliases_and_overlaps_are_refused() { + std::vector a(1 << 16); + pin_pool pool; + auto resolve = [&](const buffer_ref & r) -> buffer_pin { + if (r.generation != 0 || r.offset + r.bytes > a.size()) return {}; + // buffers 0 and 1 are two ids over the SAME bytes (a physical alias the ids do not show) + return pool.pin(a.data() + r.offset, a.size() - r.offset); + }; + frame_ring in(16); + parallel_copier mover(in, resolve, 4, 4096, 8); + const auto ref = [](uint32_t gen, uint64_t off, uint64_t n) { return buffer_ref{ memory_domain::host, 0, 0, gen, off, n }; }; + require(in.push({ 1, ref(0, 0, 4096), ref(0, 0, 8192) }), "q"); // same start, unequal lengths + require(in.push({ 2, ref(1, 0, 4096), ref(1, 0, 4096) }), "q"); // stale generation named twice + require(in.push({ 3, ref(0, 0, 8192), ref(0, 4096, 8192) }), "q"); // overlapping ranges + require(in.push({ 4, ref(0, 0, 4096), ref(0, 1 << 16, 4096) }), "q"); // out of bounds + require(in.push({ 5, ref(0, 0, 4096), ref(0, 8192, 4096) }), "q"); // disjoint: a real copy + const auto other = [](uint64_t off, uint64_t n) { return buffer_ref{ memory_domain::host, 0, 1, 0, off, n }; }; + require(in.push({ 6, ref(0, 0, 4096), other(0, 4096) }), "q"); // another id, the SAME bytes + require(in.push({ 7, ref(0, 0, 4096), other(2048, 4096) }), "q"); // another id, overlapping bytes + done_map done; + drain_all(mover, done, 7); + require(done[1] == transfer_status::refused && done[2] == transfer_status::refused, "an alias is never unvalidated"); + require(done[3] == transfer_status::refused, "overlap is refused, never raced"); + require(done[4] == transfer_status::refused, "out of bounds is refused"); + require(done[5] == transfer_status::moved, "a disjoint copy in one buffer moves"); + require(done[6] == transfer_status::aliased, "two ids over the same physical bytes alias, decided on addresses"); + require(done[7] == transfer_status::refused, "two ids over overlapping physical bytes are refused"); + require(pool.out.load() == 0, "every pin went back to its pool once its completion was drained"); +} + +// what this catches: the destructor joined lanes blocked on full completion rings, and tickets never handed +// to a lane had no terminal outcome +// what this catches (Codex on #134): a generation alone did not keep the pool's custody; the pins must be +// held from start until the completion is DRAINED, then returned +static void a_transfer_holds_its_pins_until_drained() { + std::vector a(1 << 20), b(1 << 20); + pin_pool pool; + auto resolve = [&](const buffer_ref & r) -> buffer_pin { + auto & v = r.buffer == 0 ? a : b; + return pool.pin(v.data(), v.size()); + }; + frame_ring in(4); + parallel_copier mover(in, resolve, 2, 64 * 1024, 2); + require(in.push({ 1, { memory_domain::host, 0, 0, 0, 0, 1 << 20 }, { memory_domain::host, 0, 1, 0, 0, 1 << 20 } }), "q"); + mover.pump(); + while (mover.doorbell() == 0) mover.wait_done(0); // the copy landed and was published... + require(pool.out.load() == 2, "...yet both pins stay out until the completion is drained"); + done_map done; + drain_all(mover, done, 1); + require(done[1] == transfer_status::moved && pool.out.load() == 0, "drained: moved, and both pins returned"); +} + +// what this catches (Codex on #134): an immediate alias returned its pins before its terminal frame was +// drained, so the pool could recycle bytes a consumer was still told were aliased +static void an_alias_holds_its_pins_until_drained() { + std::vector a(4096); + pin_pool pool; + auto resolve = [&](const buffer_ref &) -> buffer_pin { return pool.pin(a.data(), a.size()); }; + frame_ring in(4); + parallel_copier mover(in, resolve, 1, 4096, 2); + const buffer_ref x{ memory_domain::host, 0, 0, 0, 0, 4096 }; + const buffer_ref y{ memory_domain::host, 0, 1, 0, 0, 4096 }; // another id over the same bytes + require(in.push({ 1, x, y }), "q"); + mover.pump(); + require(pool.out.load() == 2, "settled aliased, both pins still held"); + done_map done; + drain_all(mover, done, 1); + require(done[1] == transfer_status::aliased && pool.out.load() == 0, "drained: aliased, pins returned"); +} + +static void teardown_with_work_outstanding_ends_every_ticket() { + const size_t n = 64, bytes = 1 << 20; + std::vector> src(n, std::vector(bytes)), dst(n, std::vector(bytes)); + pin_pool pool; + auto resolve = [&](const buffer_ref & r) -> buffer_pin { + auto & v = r.pool == 0 ? src : dst; + if (r.generation != 0 || r.buffer >= v.size() || r.offset + r.bytes > v[r.buffer].size()) return {}; + return pool.pin(v[r.buffer].data() + r.offset, v[r.buffer].size() - r.offset); + }; + frame_ring in(n); + { + parallel_copier mover(in, resolve, 3, 64 * 1024, 2); // two slots: most transfers stay queued + for (uint64_t i = 0; i < n; ++i) { + require(in.push({ i + 1, { memory_domain::host, 0, (uint32_t) i, 0, 0, bytes }, { memory_domain::host, 1, (uint32_t) i, 0, 0, bytes } }), "q"); + } + mover.pump(); + mover.shutdown(); + done_map done; + drain_all(mover, done, n); // every ticket ends: moved/failed by a lane, or cancelled unhanded + size_t cancelled = 0; + for (auto & [t, s] : done) { + require(s == transfer_status::moved || s == transfer_status::failed || s == transfer_status::cancelled, "a terminal status"); + cancelled += s == transfer_status::cancelled; + } + require(cancelled > 0, "transfers no lane took are cancelled, typed"); + require(pool.out.load() == 0, "after every terminal frame is drained, no pin is held"); + require(!in.push({ n + 1, {}, {} }), "a shut-down mover takes nothing more"); + } // the destructor joins without hanging + { + parallel_copier mover(in, resolve, 3, 64 * 1024, 2); + } // and a fresh mover over the closed ring tears down at once +} + +static void the_parallel_copier_moves_many_at_once() { + run_copies(/*lanes=*/6, /*chunk=*/64 * 1024, /*transfers=*/200, /*bytes=*/1 << 20, nullptr); +} + +int main(int argc, char ** argv) { + if (argc > 1 && std::strcmp(argv[1], "--bandwidth") == 0) { + // the receipt: one lane against the lanes at the measured knee, same transfers + for (size_t lanes : { (size_t) 1, (size_t) 4, (size_t) 8, (size_t) 12 }) { + double g = 0; + run_copies(lanes, 4 << 20, 16, 64 << 20, &g); + std::printf("parallel_copier lanes %2zu: %6.1f GB/s (16 x 64 MiB)\n", lanes, g); + } + return 0; + } + one_stream_delivers_every_frame_in_order(); + many_streams_run_at_once(); + a_full_ring_is_backpressure(); + close_wakes_a_waiting_consumer(); + a_mover_streams_moves_without_waiting(); + a_close_never_strands_an_accepted_frame(); + a_full_completion_ring_is_backpressure_not_a_deadlock(); + invalid_aliases_and_overlaps_are_refused(); + a_transfer_holds_its_pins_until_drained(); + an_alias_holds_its_pins_until_drained(); + teardown_with_work_outstanding_ends_every_ticket(); + the_parallel_copier_moves_many_at_once(); + std::cout << "test-server-frames: ok\n"; + return 0; +} diff --git a/tools/server/server-frames.h b/tools/server/server-frames.h new file mode 100644 index 000000000000..3b28e4b86e49 --- /dev/null +++ b/tools/server/server-frames.h @@ -0,0 +1,661 @@ +#pragma once + +// Continuum fork: STREAMS OF FRAMES and MOVING BYTES BY REFERENCE, one pattern reused everywhere +// (CONTINUUM-ENGINE 4.7.12). Joel, 2026-11-16: "Fast tokenless memory transfer and DMA must be encoded +// into a pattern or parent class"; "Streaming not promises"; "pass references and ids, don't +// tokenize, do in parallel, don't wait. Run many things simultaneously." +// +// frame_ring a lock-free single-producer / single-consumer ring of FRAMES. A frame is small and +// trivially copyable (ids, references, counters), never a payload. A full ring is +// backpressure the producer sees at once (push returns false); an empty ring sleeps +// the consumer on an atomic wait (a futex), never a lock, a timer or a promise. Work +// flows as streams: requests in one ring, results out another, many rings at once. +// +// buffer_ref bytes NAMED, never carried: a memory domain, the owning pool, a buffer id, an +// offset and a length. What crosses a ring, a thread or a process is the reference. +// +// memory_mover the one base class for moving bytes between domains. It consumes a stream of +// transfer frames and produces a stream of completion frames; a backend implements +// only `start` (enqueue the move on its own engine: a GPU blit, a backend async copy, +// a disk read into a pool buffer) and reports completion. Within one physical domain +// (unified memory) a "move" is a new reference: nothing is copied. Nothing is ever +// encoded or decoded on the way. +// +// Pure and header-only, proven by tests/test-server-frames.cpp without a model. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ---- the stream ------------------------------------------------------------------------------------ + +template +class frame_ring { + static_assert(std::is_trivially_copyable_v, "a frame is ids and references, never a payload with an owner"); + +public: + // `capacity` rounds up to a power of two; the ring is allocated once. + explicit frame_ring(size_t capacity) : slots_(std::bit_ceil(capacity < 2 ? size_t(2) : capacity)), mask_(slots_.size() - 1) {} + + frame_ring(const frame_ring &) = delete; + frame_ring & operator=(const frame_ring &) = delete; + + // Producer side. False when full: backpressure, decided by the producer, never hidden. + // A frame is accepted iff its publication (a CAS on the tail word) lands before a close: a close can + // never be erased by a racing push, and a push that returned true is always drained (Codex on #134). + bool push(const T & frame) { + uint64_t raw = tail_.load(std::memory_order_relaxed); + if (raw & CLOSED) { + return false; // a closed stream takes nothing more + } + const uint64_t tail = raw; + if (tail - head_cache_ >= slots_.size()) { + head_cache_ = head_.load(std::memory_order_acquire) & COUNT; + if (tail - head_cache_ >= slots_.size()) { + return false; + } + } + slots_[tail & mask_] = frame; + if (!tail_.compare_exchange_strong(raw, tail + 1, std::memory_order_release, std::memory_order_relaxed)) { + return false; // closed between the check and the publication: not accepted + } + tail_.notify_one(); + return true; + } + + // Consumer side: take up to out.size() frames at once; returns how many. + size_t drain(std::span out) { + const uint64_t head = head_.load(std::memory_order_relaxed) & COUNT; + uint64_t tail = tail_cache_; + if (tail == head) { + tail = tail_cache_ = tail_.load(std::memory_order_acquire) & COUNT; + } + const size_t n = (size_t) std::min(tail - head, out.size()); + for (size_t i = 0; i < n; ++i) { + out[i] = slots_[(head + i) & mask_]; + } + if (n > 0) { + head_.fetch_add(n, std::memory_order_release); // an RMW: a racing close's bit is never erased + head_.notify_one(); // a producer waiting for room wakes + } + return n; + } + + // Producer side: sleep until there is room for one frame or the stream is closed (an atomic wait on the + // consumer's head word, which carries the closed bit too). False: closed, nothing more will be taken. + bool wait_for_room() const { + const uint64_t tail = tail_.load(std::memory_order_relaxed) & COUNT; + uint64_t raw = head_.load(std::memory_order_acquire); + while (!(raw & CLOSED) && tail - (raw & COUNT) >= slots_.size()) { + head_.wait(raw, std::memory_order_acquire); + raw = head_.load(std::memory_order_acquire); + } + return !(raw & CLOSED); + } + + // Consumer side: sleep until a frame is pushed or the stream is closed. An atomic wait returns only + // when the watched WORD changes, so the closed flag lives in the same word as the count (its top + // bit): closing changes the word the consumer sleeps on. + void wait_for_frames() const { + const uint64_t head = head_.load(std::memory_order_relaxed); + uint64_t seen = tail_.load(std::memory_order_acquire); + while ((seen & COUNT) == head && !(seen & CLOSED)) { + tail_.wait(seen, std::memory_order_acquire); + seen = tail_.load(std::memory_order_acquire); + } + } + + // Either side ends the stream; both words carry the bit, so a waiting consumer AND a producer waiting + // for room wake (the word each sleeps on changes). Frames accepted before it are still drained. + void close() { + tail_.fetch_or(CLOSED, std::memory_order_acq_rel); + head_.fetch_or(CLOSED, std::memory_order_acq_rel); + tail_.notify_all(); + head_.notify_all(); + } + bool closed() const { return (tail_.load(std::memory_order_acquire) & CLOSED) != 0; } + + size_t capacity() const { return slots_.size(); } + uint64_t pushed() const { return tail_.load(std::memory_order_acquire) & COUNT; } + uint64_t taken() const { return head_.load(std::memory_order_acquire) & COUNT; } + +private: + static constexpr uint64_t CLOSED = uint64_t(1) << 63; + static constexpr uint64_t COUNT = CLOSED - 1; + + std::vector slots_; + const uint64_t mask_; + alignas(64) std::atomic head_{0}; // consumer advances (fetch_add): count | CLOSED + alignas(64) std::atomic tail_{0}; // producer writes: count | CLOSED + alignas(64) uint64_t head_cache_ = 0; // producer's view of head + alignas(64) uint64_t tail_cache_ = 0; // consumer's view of tail +}; + +// ---- bytes by reference ---------------------------------------------------------------------------- + +enum class memory_domain : uint8_t { + host, // host-addressable memory + device, // backend (GPU) buffers; on unified memory the same physical pages as host + disk, // a page file +}; + +// Custody (Codex on #134): the pool that owns `buffer` keeps it live and unrecycled from the push of a +// transfer naming it until that transfer's completion frame is DRAINED; `generation` is the buffer's +// incarnation in its pool, bumped on every reuse, so a reference that outlived its buffer is refused by +// the resolver, never resolved to the next occupant's bytes. +struct buffer_ref { + memory_domain domain = memory_domain::host; + uint32_t pool = 0; // the owning pool (the host pool, a device pool, a page store) + uint32_t buffer = 0; // the buffer within that pool + uint32_t generation = 0; // the buffer's incarnation (see custody above) + uint64_t offset = 0; + uint64_t bytes = 0; +}; +static_assert(std::is_trivially_copyable_v); + +// The owning pool's custody of a resolved reference (Codex on #134: a raw pointer plus a generation does +// not keep the bytes live). A pool resolves a buffer_ref into a pin: the bytes' address, held live and +// unrecycled until the pin is released (its destructor calls the pool's own unpin with the pool's token). +// A mover holds a transfer's pins until its completion is drained. Nothing here owns memory: the pool does. +class buffer_pin { +public: + using unpin_fn = void (*)(void * pool, uint64_t token) noexcept; + + buffer_pin() = default; + buffer_pin(std::byte * data, uint64_t bytes, void * pool, unpin_fn unpin, uint64_t token) + : data_(data), bytes_(bytes), pool_(pool), unpin_(unpin), token_(token) {} + buffer_pin(buffer_pin && o) noexcept { take(o); } + buffer_pin & operator=(buffer_pin && o) noexcept { + if (this != &o) { + release(); + take(o); + } + return *this; + } + buffer_pin(const buffer_pin &) = delete; + buffer_pin & operator=(const buffer_pin &) = delete; + ~buffer_pin() { release(); } + + explicit operator bool() const { return data_ != nullptr; } + std::byte * data() const { return data_; } + uint64_t bytes() const { return bytes_; } + + void release() noexcept { + if (unpin_ != nullptr) { + unpin_(pool_, token_); + } + data_ = nullptr; bytes_ = 0; pool_ = nullptr; unpin_ = nullptr; token_ = 0; + } + +private: + void take(buffer_pin & o) noexcept { + data_ = o.data_; bytes_ = o.bytes_; pool_ = o.pool_; unpin_ = o.unpin_; token_ = o.token_; + o.data_ = nullptr; o.bytes_ = 0; o.pool_ = nullptr; o.unpin_ = nullptr; o.token_ = 0; + } + + std::byte * data_ = nullptr; + uint64_t bytes_ = 0; + void * pool_ = nullptr; + unpin_fn unpin_ = nullptr; + uint64_t token_ = 0; +}; + +// ---- moving bytes ---------------------------------------------------------------------------------- + +struct transfer_frame { + uint64_t ticket = 0; + buffer_ref src; + buffer_ref dst; +}; + +enum class transfer_status : uint8_t { + moved, // the backend moved the bytes + aliased, // same physical domain: dst now names src's bytes, nothing was copied + refused, // invalid (stale, out of bounds, unequal lengths, overlapping) or an unsupported pair: + // typed, never a silent CPU copy + failed, // the backend reported an error + cancelled, // the mover shut down before the transfer was handed to an engine: nothing was written +}; + +struct transfer_done_frame { + uint64_t ticket = 0; + transfer_status status = transfer_status::moved; + uint32_t slot = NO_SLOT; // the backend's in-flight slot, retired when this frame is drained + static constexpr uint32_t NO_SLOT = UINT32_MAX; +}; + +// The one base for every byte mover. A subclass is only the diff: how its engines start a move and +// when each part completes. Moving is PARALLEL: a backend owns several completion contexts (lanes: CPU +// copy threads, GPU blit queues, disk readers), each completing into its OWN single-producer ring, and +// the pumping thread settles what needs no engine (aliased, refused) into one more. One doorbell +// counter, bumped by every producer, wakes the consumer: fan-in without a lock. +class memory_mover { +public: + memory_mover(frame_ring & in, size_t done_capacity, size_t completion_contexts) + : in_(in), settled_(done_capacity) { + for (size_t i = 0; i < std::max(completion_contexts, 1); ++i) { + finished_.push_back(std::make_unique>(done_capacity)); + } + } + virtual ~memory_mover() = default; + + // Start as many queued transfers as the engines have room for, and RETURN: pump never waits. A + // transfer the engines cannot take yet stays pending here (the backend remembers how far it got) + // and resumes on the next pump; the caller drains completions in between, which is what makes + // room. Returns how many transfers were fully handed to an engine. + size_t pump() { + size_t started = 0; + while (true) { + if (!unsettled_.empty()) { + return started; // settlements wait for the caller's drain: take nothing new (bounded) + } + if (!pending_) { + transfer_frame f; + if (in_.drain(std::span(&f, 1)) == 0) { + return started; + } + if (aliases(f.src, f.dst)) { + settle(f.ticket, transfer_status::aliased); + continue; + } + pending_ = f; + } + switch (start(*pending_)) { + case start_result::started: started++; pending_.reset(); break; + case start_result::refused: settle(pending_->ticket, transfer_status::refused); pending_.reset(); break; + case start_result::aliased: settle(pending_->ticket, transfer_status::aliased, take_terminal_slot()); pending_.reset(); break; + case start_result::would_block: return started; // engines full: drain completions, pump again + } + } + } + + // A transfer is waiting for engine room (the caller should drain completions, then pump again). + bool blocked() const { return pending_.has_value() || !unsettled_.empty(); } + + // Consumer side, on the pumping thread: take completions from every producer; returns how many. A + // drained frame retires its backend slot, which is what bounds the completions outstanding. + size_t drain_done(std::span out) { + size_t n = settled_.drain(out); + while (n < out.size() && !unsettled_.empty()) { + out[n++] = unsettled_.front(); + unsettled_.erase(unsettled_.begin()); + } + for (auto & ring : finished_) { + n += ring->drain(out.subspan(n)); + } + for (size_t i = 0; i < n; ++i) { + if (out[i].slot != transfer_done_frame::NO_SLOT) { + retire(out[i].slot); + } + } + return n; + } + + // Shutdown, on the pumping thread: every transfer still queued or part-handed that no engine took is + // settled `cancelled` (nothing written); transfers an engine took complete as they land. After it, + // every ticket pushed has exactly one terminal frame to drain. Pushing more is refused (closed). + void shutdown() { + in_.close(); + if (pending_) { + if (const auto ended = cancel_pending()) { + settle(pending_->ticket, *ended, take_terminal_slot()); + } // else an engine holds part of it and reports its one terminal frame + pending_.reset(); + } + transfer_frame f; + while (in_.drain(std::span(&f, 1)) == 1) { + settle(f.ticket, transfer_status::cancelled); + } + } + + // Consumer side: sleep until any producer rings the doorbell (read doorbell() BEFORE draining). + void wait_done(uint64_t seen) const { + while (doorbell_.load(std::memory_order_acquire) == seen) { + doorbell_.wait(seen, std::memory_order_acquire); + } + } + uint64_t doorbell() const { return doorbell_.load(std::memory_order_acquire); } + + uint64_t backpressured() const { return backpressured_.load(std::memory_order_relaxed); } + +protected: + // aliased: the backend found both references resolve to the same physical bytes (nothing to move) + enum class start_result : uint8_t { started, refused, would_block, aliased }; + + // Hand the move to this backend's engines, as much as they have room for, without waiting. + // would_block: called again with the same frame on the next pump (the backend keeps its own + // progress); refused: it cannot move between these domains. + virtual start_result start(const transfer_frame & t) = 0; + + // Whether dst can simply name src's bytes (one physical domain): no copy at all. Only after both + // references are validated (live generation, in bounds, equal lengths): an alias never vouches for + // a reference the backend would refuse to copy. + virtual bool aliases(const buffer_ref & src, const buffer_ref & dst) const = 0; + + // The transfer pending when shutdown came: the backend stops handing it out. Its terminal status when + // no engine holds any of it (settled here), or nullopt when an engine does (that engine reports it). + virtual std::optional cancel_pending() { return transfer_status::cancelled; } + + // A drained completion's slot may be reused. + virtual void retire(uint32_t /*slot*/) {} + + // Set by a backend, on the pumping thread, when the terminal it hands back (start's `aliased`, or the status + // cancel_pending returns) still holds a slot with custody: the base settles that frame with the slot, so the + // pins return only when the frame is drained (Codex on #134). + uint32_t terminal_slot_ = transfer_done_frame::NO_SLOT; + + // Completion context `context` (one lane) reports a finished move. The backend guarantees room: its + // completions outstanding never exceed the ring's capacity (a slot is retired only on drain), so a + // lane never waits on the consumer. + void complete(size_t context, uint64_t ticket, transfer_status status, uint32_t slot) { + const bool pushed = finished_[context]->push(transfer_done_frame{ ticket, status, slot }); + if (!pushed) { + std::abort(); // the slot bound above is the contract; breaking it is a bug, never a wait + } + ring(); + } + +private: + // On the pumping thread: into the settled ring, or held for the caller's drain when it is full + // (never a wait: the same thread drains). + // `slot`: the backend slot that still holds the transfer's custody (pins), retired when this frame is drained. + void settle(uint64_t ticket, transfer_status status, uint32_t slot = transfer_done_frame::NO_SLOT) { + if (!settled_.push(transfer_done_frame{ ticket, status, slot })) { + backpressured_.fetch_add(1, std::memory_order_relaxed); + unsettled_.push_back(transfer_done_frame{ ticket, status, slot }); + } + ring(); + } + + uint32_t take_terminal_slot() { + const uint32_t s = terminal_slot_; + terminal_slot_ = transfer_done_frame::NO_SLOT; + return s; + } + + void ring() { + doorbell_.fetch_add(1, std::memory_order_release); + doorbell_.notify_all(); + } + + frame_ring & in_; + std::optional pending_; // pumping thread only + std::vector unsettled_; // pumping thread only + frame_ring settled_; // producer: the pumping thread + std::vector>> finished_; // producer: one lane each + std::atomic doorbell_{0}; + std::atomic backpressured_{0}; +}; + +// ---- the host backend: a parallel copier ------------------------------------------------------------ + +// Host-to-host (and file-mapped) moves done by CPU lanes in parallel: a transfer is split into chunks +// spread across the lanes, every lane copies its chunks at once, and the LAST chunk of a transfer to +// land publishes its completion. Lane count and chunk size come from the node's measured copy +// bandwidth curve (where adding a lane stops adding bandwidth), never a constant here. +// +// `Resolver`: callable (const buffer_ref &) -> buffer_pin, the owning pool's own resolution: an empty pin +// for a stale generation, an unknown buffer or bytes out of bounds. Aliasing and overlap are decided on the +// resolved PHYSICAL ranges, so two different ids naming the same bytes are caught. +template +class parallel_copier final : public memory_mover { +public: + parallel_copier(frame_ring & in, Resolver resolve, size_t lanes, size_t chunk_bytes, size_t in_flight) + // every lane's completion ring holds every slot: a slot is retired only when its completion is + // drained, so a lane can never find its ring full + : memory_mover(in, std::max(in_flight, 1), lanes), resolve_(std::move(resolve)), chunk_(std::max(chunk_bytes, 4096)), + slots_(std::max(in_flight, 1)) { + for (size_t i = 0; i < std::max(lanes, 1); ++i) { + lanes_.push_back(std::make_unique(in_flight * 4)); + } + for (size_t i = 0; i < lanes_.size(); ++i) { + lanes_[i]->worker = std::jthread([this, i](std::stop_token stop) { run_lane(i, stop); }); + } + } + + // Teardown never hangs: shutdown() cancels what no lane took, the lanes land the chunks they hold + // (their completion pushes cannot block), then they are joined. Completions not drained go with the + // mover; the caller drains before destroying it when it needs every terminal frame. + ~parallel_copier() override { + shutdown(); + for (auto & l : lanes_) { + l->work.close(); + } + for (auto & l : lanes_) { + l->worker.join(); + } + } + + size_t lanes() const { return lanes_.size(); } + +private: + struct chunk_frame { + uint32_t slot; + const std::byte * src; + std::byte * dst; + uint64_t bytes; + }; + struct lane { + explicit lane(size_t capacity) : work(capacity) {} + frame_ring work; + std::jthread worker; + }; + struct slot { + std::atomic in_use{false}; // claimed at start; free again only when its completion is drained + std::atomic remaining{0}; + std::atomic status{0}; // moved, or failed when shutdown cut it part-handed + uint64_t ticket = 0; + buffer_pin src, dst; // the pools' custody, held until the completion is drained + }; + + // Decided in start() on the resolved physical ranges, never on ids. + bool aliases(const buffer_ref &, const buffer_ref &) const override { return false; } + + void free_slot(slot & s) { + s.src.release(); + s.dst.release(); + s.in_use.store(false, std::memory_order_release); + } + + std::optional cancel_pending() override { + if (!progress_) { + return transfer_status::cancelled; // never claimed a slot + } + const auto p = *progress_; + progress_.reset(); + slot & s = slots_[p.slot]; + if (p.next == 0) { + terminal_slot_ = p.slot; // no chunk handed, nothing written; the pins go back when this frame is drained + return transfer_status::cancelled; + } + // part-handed: its handed chunks land and the last one reports `failed` (a partial destination); + // the chunks never handed are subtracted so that last one is found + s.status.store((uint8_t) transfer_status::failed, std::memory_order_relaxed); + const uint32_t not_handed = (uint32_t) (p.n_chunks - p.next); + if (s.remaining.fetch_sub(not_handed, std::memory_order_acq_rel) == not_handed) { + // every handed chunk already landed before the subtraction: none will report it, so it ends here, + // still holding its pins until the frame is drained + terminal_slot_ = p.slot; + return transfer_status::failed; + } + return std::nullopt; + } + + void retire(uint32_t s) override { free_slot(slots_[s]); } + + start_result start(const transfer_frame & t) override { + if (!progress_) { + if (t.src.domain == memory_domain::disk || t.dst.domain == memory_domain::disk || t.src.bytes != t.dst.bytes) { + return start_result::refused; // disk moves belong to a reader backend; a size mismatch is never truncated + } + buffer_pin src = resolve_(t.src); + buffer_pin dst = resolve_(t.dst); + if (!src || !dst || src.bytes() < t.src.bytes || dst.bytes() < t.dst.bytes) { + return start_result::refused; // stale generation, unknown buffer or out of bounds + } + // physical ranges, whatever ids named them + const std::byte * a = src.data(); + const std::byte * b = dst.data(); + const uint64_t n = t.src.bytes; + if (a != b && a < b + n && b < a + n) { + return start_result::refused; // independent parallel chunks over overlapping ranges race (UB) + } + const auto s = claim_slot(); + if (!s) { + return start_result::would_block; // every in-flight slot is busy (the pins go back; re-resolved next pump) + } + if (a == b) { + // the same bytes: nothing to move, but the pins are held in the slot until the frame is drained + slots_[*s].src = std::move(src); + slots_[*s].dst = std::move(dst); + terminal_slot_ = *s; + return start_result::aliased; + } + std::byte * src_bytes = src.data(); + std::byte * dst_bytes = dst.data(); + slots_[*s].src = std::move(src); + slots_[*s].dst = std::move(dst); + const uint64_t n_chunks = std::max(1, (t.src.bytes + chunk_ - 1) / chunk_); + slots_[*s].ticket = t.ticket; + slots_[*s].status.store((uint8_t) transfer_status::moved, std::memory_order_relaxed); + slots_[*s].remaining.store((uint32_t) n_chunks, std::memory_order_release); + progress_ = progress{ *s, src_bytes, dst_bytes, t.src.bytes, n_chunks, 0 }; + } + // push the remaining chunks, round robin across lanes, as far as the lanes have room + while (progress_->next < progress_->n_chunks) { + const uint64_t off = progress_->next * chunk_; + const chunk_frame f{ progress_->slot, progress_->src + off, progress_->dst + off, + std::min(chunk_, progress_->bytes - off) }; + if (!lanes_[next_lane_ % lanes_.size()]->work.push(f)) { + return start_result::would_block; // that lane is full; resume here next pump + } + next_lane_++; + progress_->next++; + } + progress_.reset(); + return start_result::started; + } + + // A free in-flight slot, or none (never waits); the lane that lands a transfer's last chunk frees it. + std::optional claim_slot() { + for (size_t i = 0; i < slots_.size(); ++i) { + const uint32_t s = (uint32_t) ((cursor_ + i) % slots_.size()); + bool free = false; + if (slots_[s].in_use.compare_exchange_strong(free, true, std::memory_order_acq_rel)) { + cursor_ = s + 1; + return s; + } + } + return std::nullopt; + } + + void run_lane(size_t index, std::stop_token) { + auto & l = *lanes_[index]; + chunk_frame batch[32]; + while (true) { + const size_t n = l.work.drain(batch); + for (size_t i = 0; i < n; ++i) { + std::memcpy(batch[i].dst, batch[i].src, batch[i].bytes); + slot & s = slots_[batch[i].slot]; + if (s.remaining.fetch_sub(1, std::memory_order_acq_rel) == 1) { + // the slot stays claimed until this completion is drained (retire): that is the bound + complete(index, s.ticket, (transfer_status) s.status.load(std::memory_order_relaxed), batch[i].slot); + } + } + if (n == 0) { + if (l.work.closed() && l.work.pushed() == l.work.taken()) { + return; + } + l.work.wait_for_frames(); + } + } + } + + Resolver resolve_; + size_t chunk_; + std::vector slots_; + std::vector> lanes_; + struct progress { + uint32_t slot; + const std::byte * src; + std::byte * dst; + uint64_t bytes; + uint64_t n_chunks; + uint64_t next; + }; + std::optional progress_; // pumping thread only: a transfer part-handed out + size_t next_lane_ = 0; // pumping thread only + size_t cursor_ = 0; // pumping thread only +}; + +// ---- how many copy lanes: the first guess, then the measurement ------------------------------------ + +// The first guess for CPU copy lanes is the node's EFFICIENCY core count: copying is bandwidth-bound, +// the efficiency cores reach the memory ceiling (measured on the M5 Pro: 12 lanes = 118.9 GB/s, the +// knee; 18 = 109) and the performance cores stay free for the decode thread. Read from the OS; empty +// when the OS does not report core classes (then the probe below starts from the core count it can +// see). measure_copy_lanes() refines it on the node's own bandwidth curve. +#if defined(__APPLE__) +#include +#endif +inline std::optional efficiency_cores() { +#if defined(__APPLE__) + int n = 0; + size_t len = sizeof(n); + if (sysctlbyname("hw.perflevel1.physicalcpu", &n, &len, nullptr, 0) == 0 && n > 0) { + return (size_t) n; + } +#endif + return std::nullopt; // Linux/Windows core classes: the host adapter's job (continuum-host), not guessed here +} + +// The node's copy-lane count, MEASURED: copy `probe_bytes` with each candidate lane count (best of three, +// the probe shares the machine) and keep the FIRST GUESS (the efficiency-core count) unless another count +// beats it by more than the margin `1/knee`: noise never moves the choice, a real knee elsewhere does. +// Runs once at startup, off the decode thread. Returns the chosen count and its GB/s. +struct copy_lane_measurement { + size_t lanes = 1; + double gbps = 0.0; +}; +inline copy_lane_measurement measure_copy_lanes(size_t guess, std::span others, size_t probe_bytes, double knee) { + std::vector src(probe_bytes, std::byte{1}), dst(probe_bytes); + auto measure = [&](size_t lanes) { + lanes = std::max(lanes, 1); + double best = 0.0; + for (int rep = 0; rep < 3; ++rep) { + const auto t0 = std::chrono::steady_clock::now(); + { + std::vector ws; + const size_t chunk = probe_bytes / lanes; + for (size_t i = 0; i < lanes; ++i) { + const size_t off = i * chunk, n = i + 1 == lanes ? probe_bytes - off : chunk; + ws.emplace_back([&, off, n] { std::memcpy(dst.data() + off, src.data() + off, n); }); + } + } // joins + const double secs = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + best = std::max(best, (double) probe_bytes / secs / 1e9); + } + return copy_lane_measurement{ lanes, best }; + }; + copy_lane_measurement pick = measure(guess); + for (size_t lanes : others) { + const auto m = measure(lanes); + if (m.gbps * knee > pick.gbps) { + pick = m; // clearly better than the guess, not noise + } + } + return pick; +}