From 3a4da82f2b7669248bbb8ed7b26fccea5a2f16ea Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 08:35:27 -0600 Subject: [PATCH 1/7] server: one pattern for streams of frames and moving bytes by reference (frame_ring, buffer_ref, memory_mover) Joel 2026-11-16: "Fast tokenless memory transfer and DMA must be encoded into a pattern or parent class, reused"; "Streaming not promises"; "pass references and ids ... do in parallel, don't wait." - frame_ring: lock-free single-producer/single-consumer ring of frames; T must be trivially copyable (ids, references, counters, never a payload with an owner). Fixed power-of-two capacity allocated once. A full ring is backpressure the producer sees at once; wait_for_room / wait_for_frames are atomic waits (futex), never a lock, timer or promise. The closed flag is the top bit of the tail word, because an atomic wait returns only when its word changes (a first version kept it separate and a closing producer never woke the consumer; found by the validator hanging). - buffer_ref: bytes named, never carried (domain, pool, buffer, offset, length). - memory_mover: the one base for every byte mover. It drains a stream of transfer frames and starts each on its backend's own engine without waiting; a move within one physical domain is ALIASED (nothing copied); an unsupported pair is REFUSED typed (never a silent CPU copy). Completions come from two producers, each with its own SPSC ring (the pumping thread settles aliased/refused, the backend's completion context finishes moves) and one doorbell counter wakes the consumer: lock-free fan-in. (A first version shared one ring between both producers; ThreadSanitizer caught the race.) A backend implements only start() and aliases(). test-server-frames: 2,000,000 frames through a 64-slot ring in order; 8 rings x 250,000 frames at once; backpressure; close wakes a sleeping consumer; 900 transfers (moved on the engine, aliased, refused) streamed back exactly once from two producers. ok 3x under TSan (no reports) and 3x under ASan/UBSan; 0 warnings from the cmake build. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo (cherry picked from commit 0a5a1df024f1c1937bff83d842e8dde4e8c991d4) --- tests/CMakeLists.txt | 6 + tests/test-server-frames.cpp | 178 ++++++++++++++++++++++++++ tools/server/server-frames.h | 240 +++++++++++++++++++++++++++++++++++ 3 files changed, 424 insertions(+) create mode 100644 tests/test-server-frames.cpp create mode 100644 tools/server/server-frames.h 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..38e649f0b7f0 --- /dev/null +++ b/tests/test-server-frames.cpp @@ -0,0 +1,178 @@ +// 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 + +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), 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); + } + bool start(const transfer_frame & t) override { + if (!(t.src.domain == memory_domain::disk && t.dst.domain == memory_domain::host)) { + return false; + } + while (!work_.push(t)) { + work_.wait_for_room(); + } + return true; // started, not finished: the caller never waits here + } + 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(batch[i].ticket, transfer_status::moved); // the engine's completion 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, 4096 }; + const buffer_ref host{ memory_domain::host, 0, 3, 0, 4096 }; + const buffer_ref dev{ memory_domain::device, 2, 9, 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 + 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"); +} + +int main() { + 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(); + 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..011a31b8f040 --- /dev/null +++ b/tools/server/server-frames.h @@ -0,0 +1,240 @@ +#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 + +// ---- 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. + bool push(const T & frame) { + const 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); + if (tail - head_cache_ >= slots_.size()) { + return false; + } + } + slots_[tail & mask_] = frame; + tail_.store(tail + 1, std::memory_order_release); + 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); + 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_.store(head + n, std::memory_order_release); + head_.notify_one(); // a producer waiting for room wakes + } + return n; + } + + // Producer side: sleep until there is room for one frame (an atomic wait on the consumer's head). + void wait_for_room() const { + const uint64_t tail = tail_.load(std::memory_order_relaxed); + uint64_t head = head_.load(std::memory_order_acquire); + while (tail - head >= slots_.size()) { + head_.wait(head, std::memory_order_acquire); + head = head_.load(std::memory_order_acquire); + } + } + + // 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); + } + } + + // The producer ends the stream; a waiting consumer wakes (the word it sleeps on changes). + void close() { + tail_.fetch_or(CLOSED, std::memory_order_release); + tail_.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); } + +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 writes + 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 +}; + +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 + uint64_t offset = 0; + uint64_t bytes = 0; +}; +static_assert(std::is_trivially_copyable_v); + +// ---- 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, // the backend cannot move between these domains (typed, never a silent CPU copy) + failed, // the backend reported an error +}; + +struct transfer_done_frame { + uint64_t ticket = 0; + transfer_status status = transfer_status::moved; +}; + +// The one base for every byte mover. A subclass is only the diff: how its engine starts a move and +// when that move completes. Completions come from TWO producers, each with its own single-producer +// ring: the pumping thread settles what needs no engine (aliased, refused), and the backend's own +// completion context finishes real moves. One doorbell counter, bumped by both, wakes the consumer: +// fan-in without a lock. +class memory_mover { +public: + memory_mover(frame_ring & in, size_t done_capacity) : in_(in), settled_(done_capacity), finished_(done_capacity) {} + virtual ~memory_mover() = default; + + // Drain every pending transfer frame and start each on the backend's engine without waiting on + // any of them. Returns how many were started on the engine. + size_t pump() { + transfer_frame batch[64]; + size_t started = 0; + for (size_t n; (n = in_.drain(batch)) > 0;) { + for (size_t i = 0; i < n; ++i) { + if (aliases(batch[i].src, batch[i].dst)) { + settle(batch[i].ticket, transfer_status::aliased); + } else if (!start(batch[i])) { + settle(batch[i].ticket, transfer_status::refused); + } else { + started++; + } + } + } + return started; + } + + // Consumer side: take completions from both producers; returns how many. + size_t drain_done(std::span out) { + const size_t a = settled_.drain(out); + return a + finished_.drain(out.subspan(a)); + } + + // Consumer side: sleep until either producer rings the doorbell (an atomic wait, no lock). + 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: + // Enqueue the move on this backend's own engine; false when it cannot move between these domains. + virtual bool start(const transfer_frame & t) = 0; + + // Whether dst can simply name src's bytes (one physical domain): no copy at all. + virtual bool aliases(const buffer_ref & src, const buffer_ref & dst) const = 0; + + // The backend's ONE completion context reports a finished move. + void complete(uint64_t ticket, transfer_status status) { publish(finished_, ticket, status); } + +private: + void settle(uint64_t ticket, transfer_status status) { publish(settled_, ticket, status); } + + void publish(frame_ring & ring, uint64_t ticket, transfer_status status) { + while (!ring.push(transfer_done_frame{ ticket, status })) { + // the consumer of completions is behind: counted, then sleep until it drains (no spin) + backpressured_.fetch_add(1, std::memory_order_relaxed); + ring.wait_for_room(); + } + doorbell_.fetch_add(1, std::memory_order_release); + doorbell_.notify_all(); + } + + frame_ring & in_; + frame_ring settled_; // producer: the pumping thread + frame_ring finished_; // producer: the backend's completion context + std::atomic doorbell_{0}; + std::atomic backpressured_{0}; +}; From 0560a92bb07fe9b0f6dce715b92e5fc6e7036f7b Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 08:51:45 -0600 Subject: [PATCH 2/7] server: memory_mover moves in PARALLEL (lanes, chunks, per-lane completion rings) and pump never waits Joel 2026-11-16: "Memory transfer is usually not a serial system though. Remember DMA and that we have 20 cores?" The first memory_mover had one pump and one completion context. - memory_mover: N completion contexts (lanes: CPU copy threads, GPU blit queues, disk readers), each completing into its own SPSC ring, plus the pump's settled ring; one doorbell fans them in. pump() starts what the engines have room for and RETURNS (start_result::would_block keeps the transfer pending, the backend remembers its progress, the next pump resumes); the caller drains completions in between. A first parallel version blocked inside pump on a full lane ring while the lanes blocked publishing completions the same thread had to drain: a deadlock the validator exposed. - parallel_copier (host backend): a transfer splits into chunks round-robin across lanes, many transfers in flight (bounded by owner-sized in-flight slots), the LAST chunk to land publishes the completion; size mismatches and disk pairs refused typed. Lane count and chunk size are inputs from the node's measured copy curve. Measured on this M5 Pro (18 cores: 6P + 12E, live engine sharing the machine): plain memcpy 1 GiB 61 GB/s on 1 thread, 116 on 8, 119 on 12, 109 on 18. parallel_copier, 16 x 64 MiB transfers, 4 MiB chunks: 1 lane 39.1 GB/s, 4 lanes 83.5, 8 lanes 98.0, 12 lanes 118.9 (3.0x). test-server-frames ok 3x under TSan and 3x under ASan/UBSan (200 x 1 MiB through 6 lanes byte-exact, every ticket once); 0 warnings from the cmake build. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo (cherry picked from commit 5f22d26d74192583ec55dcdd012ab03bacf010cd) --- tests/test-server-frames.cpp | 82 ++++++++++-- tools/server/server-frames.h | 235 ++++++++++++++++++++++++++++++----- 2 files changed, 275 insertions(+), 42 deletions(-) diff --git a/tests/test-server-frames.cpp b/tests/test-server-frames.cpp index 38e649f0b7f0..9fa78f9150ea 100644 --- a/tests/test-server-frames.cpp +++ b/tests/test-server-frames.cpp @@ -12,6 +12,8 @@ #include #include #include +#include +#include #include static void require(bool condition, const char * message) { @@ -93,7 +95,7 @@ static void close_wakes_a_waiting_consumer() { class test_mover final : public memory_mover { public: test_mover(frame_ring & in, size_t done_capacity) - : memory_mover(in, done_capacity), engine_([this](std::stop_token stop) { run(stop); }) {} + : memory_mover(in, done_capacity, 1), engine_([this](std::stop_token stop) { run(stop); }) {} ~test_mover() override { engine_.request_stop(); work_.close(); @@ -105,21 +107,19 @@ class test_mover final : public memory_mover { const auto physical = [](memory_domain d) { return d == memory_domain::disk ? 1 : 0; }; return physical(a.domain) == physical(b.domain); } - bool start(const transfer_frame & t) override { + start_result start(const transfer_frame & t) override { if (!(t.src.domain == memory_domain::disk && t.dst.domain == memory_domain::host)) { - return false; + return start_result::refused; } - while (!work_.push(t)) { - work_.wait_for_room(); - } - return true; // started, not finished: the caller never waits here + // 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(batch[i].ticket, transfer_status::moved); // the engine's completion context + complete(0, batch[i].ticket, transfer_status::moved); // the engine's one completion context } if (n == 0) { if (work_.closed()) break; @@ -149,6 +149,7 @@ static void a_mover_streams_moves_without_waiting() { } 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) { @@ -167,12 +168,75 @@ static void a_mover_streams_moves_without_waiting() { require(moved == 300 && aliased == 300 && refused == 300, "every transfer completed exactly once"); } -int main() { +// 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 + auto resolve = [&](const buffer_ref & r) -> std::byte * { + auto & v = r.pool == 0 ? src : dst; + return r.buffer < v.size() ? v[r.buffer].data() + r.offset : nullptr; + }; + 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, bytes_each }; + const buffer_ref d{ memory_domain::host, 1, (uint32_t) i, 0, bytes_each }; + require(in.push({ i + 1, s, d }), "queued"); + } + const buffer_ref bad_s{ memory_domain::host, 0, 0, 0, bytes_each }; + const buffer_ref bad_d{ memory_domain::host, 1, 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, 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"); +} + +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(); + 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 index 011a31b8f040..940aa3718c3c 100644 --- a/tools/server/server-frames.h +++ b/tools/server/server-frames.h @@ -26,6 +26,12 @@ #include #include #include +#include +#include +#include +#include +#include +#include #include #include #include @@ -164,42 +170,60 @@ struct transfer_done_frame { transfer_status status = transfer_status::moved; }; -// The one base for every byte mover. A subclass is only the diff: how its engine starts a move and -// when that move completes. Completions come from TWO producers, each with its own single-producer -// ring: the pumping thread settles what needs no engine (aliased, refused), and the backend's own -// completion context finishes real moves. One doorbell counter, bumped by both, wakes the consumer: -// fan-in without a lock. +// 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) : in_(in), settled_(done_capacity), finished_(done_capacity) {} + 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; - // Drain every pending transfer frame and start each on the backend's engine without waiting on - // any of them. Returns how many were started on the engine. + // 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() { - transfer_frame batch[64]; size_t started = 0; - for (size_t n; (n = in_.drain(batch)) > 0;) { - for (size_t i = 0; i < n; ++i) { - if (aliases(batch[i].src, batch[i].dst)) { - settle(batch[i].ticket, transfer_status::aliased); - } else if (!start(batch[i])) { - settle(batch[i].ticket, transfer_status::refused); - } else { - started++; + while (true) { + 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::would_block: return started; // engines full: drain completions, pump again } } - return started; } - // Consumer side: take completions from both producers; returns how many. + // A transfer is waiting for engine room (the caller should drain completions, then pump again). + bool blocked() const { return pending_.has_value(); } + + // Consumer side: take completions from every producer; returns how many. size_t drain_done(std::span out) { - const size_t a = settled_.drain(out); - return a + finished_.drain(out.subspan(a)); + size_t n = settled_.drain(out); + for (auto & ring : finished_) { + n += ring->drain(out.subspan(n)); + } + return n; } - // Consumer side: sleep until either producer rings the doorbell (an atomic wait, no lock). + // 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); @@ -210,31 +234,176 @@ class memory_mover { uint64_t backpressured() const { return backpressured_.load(std::memory_order_relaxed); } protected: - // Enqueue the move on this backend's own engine; false when it cannot move between these domains. - virtual bool start(const transfer_frame & t) = 0; + enum class start_result : uint8_t { started, refused, would_block }; + + // 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. virtual bool aliases(const buffer_ref & src, const buffer_ref & dst) const = 0; - // The backend's ONE completion context reports a finished move. - void complete(uint64_t ticket, transfer_status status) { publish(finished_, ticket, status); } + // Completion context `context` (one lane) reports a finished move. + void complete(size_t context, uint64_t ticket, transfer_status status) { publish(*finished_[context], ticket, status); } private: void settle(uint64_t ticket, transfer_status status) { publish(settled_, ticket, status); } void publish(frame_ring & ring, uint64_t ticket, transfer_status status) { while (!ring.push(transfer_done_frame{ ticket, status })) { - // the consumer of completions is behind: counted, then sleep until it drains (no spin) backpressured_.fetch_add(1, std::memory_order_relaxed); - ring.wait_for_room(); + ring.wait_for_room(); // the consumer is behind: sleep until it drains (no spin) } doorbell_.fetch_add(1, std::memory_order_release); doorbell_.notify_all(); } - frame_ring & in_; - frame_ring settled_; // producer: the pumping thread - frame_ring finished_; // producer: the backend's completion context - std::atomic doorbell_{0}; - std::atomic backpressured_{0}; + frame_ring & in_; + std::optional pending_; // 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. +class parallel_copier final : public memory_mover { +public: + using resolver = std::function; // a pool's id -> its bytes + + parallel_copier(frame_ring & in, resolver resolve, size_t lanes, size_t chunk_bytes, size_t in_flight) + : memory_mover(in, in_flight, 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); }); + } + } + + ~parallel_copier() override { + 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}; + std::atomic remaining{0}; + uint64_t ticket = 0; + }; + + bool aliases(const buffer_ref & a, const buffer_ref & b) const override { + return a.domain == b.domain && a.pool == b.pool && a.buffer == b.buffer && a.offset == b.offset; + } + + 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 + } + std::byte * src = resolve_(t.src); + std::byte * dst = resolve_(t.dst); + if (src == nullptr || dst == nullptr) { + return start_result::refused; + } + const auto s = claim_slot(); + if (!s) { + return start_result::would_block; // every in-flight slot is busy + } + const uint64_t n_chunks = std::max(1, (t.src.bytes + chunk_ - 1) / chunk_); + slots_[*s].ticket = t.ticket; + slots_[*s].remaining.store((uint32_t) n_chunks, std::memory_order_release); + progress_ = progress{ *s, src, dst, 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) { + const uint64_t ticket = s.ticket; + s.in_use.store(false, std::memory_order_release); + complete(index, ticket, transfer_status::moved); + } + } + 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 }; From a891d0a3cff1597f6d8707d16296456a10c6066f Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 09:01:56 -0600 Subject: [PATCH 3/7] server: the first guess for copy lanes is the node's efficiency-core count (Joel; matches the measured knee: 12 lanes = 118.9 GB/s on the M5 Pro's 12 E-cores), read from the OS, refined by measurement Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo (cherry picked from commit 64fb16317392f8811038fa96c2dfd2fbb0bff972) --- tools/server/server-frames.h | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tools/server/server-frames.h b/tools/server/server-frames.h index 940aa3718c3c..6b69bb3e84c4 100644 --- a/tools/server/server-frames.h +++ b/tools/server/server-frames.h @@ -407,3 +407,24 @@ class parallel_copier final : public memory_mover { 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 +} From 0dffc1014f59a8a765f6da0c6a96c78da61f92e2 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 09:08:04 -0600 Subject: [PATCH 4/7] server: measure_copy_lanes: the node confirms its copy-lane knee at startup, holding to the efficiency-core guess against noise Joel: "your first guess should be near the number of efficiency cores." The guess (efficiency_cores()) is then MEASURED on the node: copy a probe buffer with the guess and a few neighbors (best of three each) and keep the guess unless another count beats it by more than the caller's margin. A first version kept the smallest count within 95% of the best and flipped between 12 and 16 lanes run to run on the M5 (the live engine shares the machine; observed spread 94.7-117.9 GB/s, about +-10%), so the margin is hysteresis toward the guess: noise never moves the choice, a real knee elsewhere does. Receipt, M5 Pro (12 E-cores), margin 0.90, 256 MiB probe, candidates 6/8/12/16/18: 12 lanes on 5 of 5 runs at 94.7-113.6 GB/s; the probe takes 65-84 ms, once at startup, off the decode thread. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo (cherry picked from commit 92796c60efcccb8497e991afef6d5d286e1a274d) --- tools/server/server-frames.h | 39 ++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tools/server/server-frames.h b/tools/server/server-frames.h index 6b69bb3e84c4..0b8335b164df 100644 --- a/tools/server/server-frames.h +++ b/tools/server/server-frames.h @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -428,3 +429,41 @@ inline std::optional efficiency_cores() { #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; +} From 95843948d930d3efcae21383c4dbdfa42eec6f54 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 13:23:35 -0600 Subject: [PATCH 5/7] frames: pump never blocks, lanes never wait on the consumer, every ticket ends once, aliases and overlaps validated; buffer refs carry a generation (Codex's review of #134) - pump: a settlement that does not fit the settled ring is held for the caller's drain (same thread) and pump takes nothing new until it drains: bounded backpressure, never a sleep inside pump (capacity 2 + 3 aliases deadlocked). - Completions are bounded by slots: a copier slot is retired only when its completion is DRAINED, and every lane's ring holds every slot, so a lane's push can never find its ring full (a broken bound aborts loudly; it is never a wait). The destructor no longer joins lanes blocked on completion. - shutdown(): every transfer queued or pending that no lane holds is settled `cancelled` (nothing written); one part-handed ends once, `failed` (a partial destination) from its last landed chunk; after it every pushed ticket has exactly one terminal frame, and the closed ring takes nothing more. - buffer_ref.generation + the custody contract (the owning pool keeps a buffer live and unrecycled until its transfer's completion is drained; the resolver refuses a stale generation, an unknown buffer or bytes out of bounds). An alias requires equal generation, offset AND length and a resolved reference. - Overlapping ranges in one buffer are refused (independent parallel chunks over them race: UB). Tests (one regression each): a full completion ring is backpressure, not a deadlock; unequal-length and stale-generation aliases, overlap and out-of-bounds refused while a disjoint copy in one buffer moves; teardown with 64 transfers outstanding on two slots ends every ticket (moved/failed/cancelled, some cancelled) and the destructor joins. Receipt (M5): test-server-frames ok; under -fsanitize=thread 5 of 5 runs ok with 0 reports; under -fsanitize=address,undefined ok. -Wall -Wextra -Werror. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/test-server-frames.cpp | 113 +++++++++++++++++++++++--- tools/server/server-frames.h | 151 +++++++++++++++++++++++++++++------ 2 files changed, 231 insertions(+), 33 deletions(-) diff --git a/tests/test-server-frames.cpp b/tests/test-server-frames.cpp index 9fa78f9150ea..7e39a0f07305 100644 --- a/tests/test-server-frames.cpp +++ b/tests/test-server-frames.cpp @@ -119,7 +119,7 @@ class test_mover final : public memory_mover { 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); // the engine's one completion context + complete(0, batch[i].ticket, transfer_status::moved, transfer_done_frame::NO_SLOT); // its one context } if (n == 0) { if (work_.closed()) break; @@ -137,9 +137,9 @@ static void a_mover_streams_moves_without_waiting() { std::map done; { test_mover mover(in, 1024); - const buffer_ref disk{ memory_domain::disk, 1, 7, 0, 4096 }; - const buffer_ref host{ memory_domain::host, 0, 3, 0, 4096 }; - const buffer_ref dev{ memory_domain::device, 2, 9, 0, 4096 }; + 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 @@ -180,7 +180,8 @@ static void run_copies(size_t lanes, size_t chunk, size_t n_transfers, size_t by // pool 0 = sources, pool 1 = destinations; buffer = index auto resolve = [&](const buffer_ref & r) -> std::byte * { auto & v = r.pool == 0 ? src : dst; - return r.buffer < v.size() ? v[r.buffer].data() + r.offset : nullptr; + // the custody contract: a live generation (0 here) and in bounds, else refused + return r.generation == 0 && r.buffer < v.size() && r.offset + r.bytes <= v[r.buffer].size() ? v[r.buffer].data() + r.offset : nullptr; }; frame_ring in(n_transfers + 8); std::map done; @@ -188,14 +189,14 @@ static void run_copies(size_t lanes, size_t chunk, size_t n_transfers, size_t by { 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, bytes_each }; - const buffer_ref d{ memory_domain::host, 1, (uint32_t) i, 0, bytes_each }; + 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, bytes_each }; - const buffer_ref bad_d{ memory_domain::host, 1, 0, 0, bytes_each - 1 }; + 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, bytes_each } }), "queued"); // disk pair + 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 @@ -217,6 +218,95 @@ static void run_copies(size_t lanes, size_t chunk, size_t n_transfers, size_t by require(done[n_transfers + 2] == transfer_status::refused, "a disk pair is refused by the host copier"); } +// 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); + auto resolve = [&](const buffer_ref & r) -> std::byte * { + auto & v = r.buffer == 0 ? a : b; + return r.generation == 0 && r.offset + r.bytes <= v.size() ? v.data() + r.offset : nullptr; + }; + 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); + auto resolve = [&](const buffer_ref & r) -> std::byte * { + return r.generation == 0 && r.offset + r.bytes <= a.size() ? a.data() + r.offset : nullptr; + }; + 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 + done_map done; + drain_all(mover, done, 5); + 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"); +} + +// what this catches: the destructor joined lanes blocked on full completion rings, and tickets never handed +// to a lane had no terminal outcome +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)); + auto resolve = [&](const buffer_ref & r) -> std::byte * { + auto & v = r.pool == 0 ? src : dst; + return r.generation == 0 && r.buffer < v.size() && r.offset + r.bytes <= v[r.buffer].size() ? v[r.buffer].data() + r.offset : nullptr; + }; + 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(!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); } @@ -236,6 +326,9 @@ int main(int argc, char ** argv) { a_full_ring_is_backpressure(); close_wakes_a_waiting_consumer(); a_mover_streams_moves_without_waiting(); + a_full_completion_ring_is_backpressure_not_a_deadlock(); + invalid_aliases_and_overlaps_are_refused(); + 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 index 0b8335b164df..9263d62a9991 100644 --- a/tools/server/server-frames.h +++ b/tools/server/server-frames.h @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -142,12 +143,17 @@ enum class memory_domain : uint8_t { 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 - uint64_t offset = 0; - uint64_t bytes = 0; + 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); @@ -162,13 +168,17 @@ struct transfer_frame { 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, // the backend cannot move between these domains (typed, never a silent CPU copy) + 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 @@ -193,6 +203,9 @@ class memory_mover { 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) { @@ -213,17 +226,44 @@ class memory_mover { } // A transfer is waiting for engine room (the caller should drain completions, then pump again). - bool blocked() const { return pending_.has_value(); } + bool blocked() const { return pending_.has_value() || !unsettled_.empty(); } - // Consumer side: take completions from every producer; returns how many. + // 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); + } // 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) { @@ -242,26 +282,48 @@ class memory_mover { // 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. + // 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; - // Completion context `context` (one lane) reports a finished move. - void complete(size_t context, uint64_t ticket, transfer_status status) { publish(*finished_[context], ticket, status); } + // 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; } -private: - void settle(uint64_t ticket, transfer_status status) { publish(settled_, ticket, status); } + // A drained completion's slot may be reused. + virtual void retire(uint32_t /*slot*/) {} - void publish(frame_ring & ring, uint64_t ticket, transfer_status status) { - while (!ring.push(transfer_done_frame{ ticket, status })) { + // 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). + void settle(uint64_t ticket, transfer_status status) { + if (!settled_.push(transfer_done_frame{ ticket, status })) { backpressured_.fetch_add(1, std::memory_order_relaxed); - ring.wait_for_room(); // the consumer is behind: sleep until it drains (no spin) + unsettled_.push_back(transfer_done_frame{ ticket, status }); } + ring(); + } + + 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}; @@ -279,7 +341,9 @@ class parallel_copier final : public memory_mover { using resolver = std::function; // a pool's id -> its bytes parallel_copier(frame_ring & in, resolver resolve, size_t lanes, size_t chunk_bytes, size_t in_flight) - : memory_mover(in, in_flight, lanes), resolve_(std::move(resolve)), chunk_(std::max(chunk_bytes, 4096)), + // 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)); @@ -289,7 +353,11 @@ class parallel_copier final : public memory_mover { } } + // 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(); } @@ -313,24 +381,61 @@ class parallel_copier final : public memory_mover { std::jthread worker; }; struct slot { - std::atomic in_use{false}; + 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; }; + // The same live bytes named twice: same domain, pool, buffer, generation, offset AND length, and the + // resolver vouches for them (live generation, in bounds). bool aliases(const buffer_ref & a, const buffer_ref & b) const override { - return a.domain == b.domain && a.pool == b.pool && a.buffer == b.buffer && a.offset == b.offset; + return a.domain == b.domain && a.pool == b.pool && a.buffer == b.buffer && a.generation == b.generation && + a.offset == b.offset && a.bytes == b.bytes && a.domain != memory_domain::disk && resolve_(a) != nullptr; + } + + static bool overlapping(const buffer_ref & a, const buffer_ref & b) { + return a.domain == b.domain && a.pool == b.pool && a.buffer == b.buffer && + a.offset < b.offset + b.bytes && b.offset < a.offset + a.bytes; + } + + 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) { + s.in_use.store(false, std::memory_order_release); // no chunk handed: nothing written, slot free + 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 + s.in_use.store(false, std::memory_order_release); + return transfer_status::failed; + } + return std::nullopt; } + void retire(uint32_t s) override { slots_[s].in_use.store(false, std::memory_order_release); } + 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 } + if (overlapping(t.src, t.dst)) { + return start_result::refused; // independent parallel chunks over overlapping ranges race (UB) + } std::byte * src = resolve_(t.src); std::byte * dst = resolve_(t.dst); if (src == nullptr || dst == nullptr) { - return start_result::refused; + return start_result::refused; // stale generation, unknown buffer or out of bounds } const auto s = claim_slot(); if (!s) { @@ -338,6 +443,7 @@ class parallel_copier final : public memory_mover { } 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, dst, t.src.bytes, n_chunks, 0 }; } @@ -378,9 +484,8 @@ class parallel_copier final : public memory_mover { 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) { - const uint64_t ticket = s.ticket; - s.in_use.store(false, std::memory_order_release); - complete(index, ticket, transfer_status::moved); + // 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) { From f8d694f89281b11453ebcafac2dc1d42825a78f9 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 13:33:52 -0600 Subject: [PATCH 6/7] frames: a close is never erased and never strands an accepted frame; the owning pool's pins are held until drain; alias and overlap are decided on physical ranges (Codex's second review of #134) - frame_ring: push publishes by CAS on the tail word, so a frame is accepted iff it lands before a close; the closed bit lives on BOTH words (head advances by fetch_add, close is fetch_or), so neither side's update erases it; wait_for_room wakes on close and returns false. - buffer_pin: the owning pool's custody of a resolved reference (address + the pool's own unpin, RAII, move-only). parallel_copier takes a resolver returning pins (no std::function), holds a transfer's src and dst pins in its slot from start until its completion is DRAINED, and returns them on cancel paths. Nothing new owns memory: the pool does. - Aliasing and overlap are decided on the resolved PHYSICAL ranges: the same address is `aliased` (pins returned at once), any other overlap is refused, so two ids naming the same bytes are caught. Tests: a close racing a producer (2,000 rounds): the closed bit survives and every push that returned true is drained; a transfer holds both pins after its completion is published and returns them only on drain; two ids over the same bytes alias, over overlapping bytes are refused; every test pool ends with 0 pins out. Receipt (M5): test-server-frames ok; -Wall -Wextra -Werror under -fsanitize=thread 5 of 5 ok, under -fsanitize=address,undefined ok. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/test-server-frames.cpp | 96 +++++++++++++++++++--- tools/server/server-frames.h | 152 +++++++++++++++++++++++++---------- 2 files changed, 197 insertions(+), 51 deletions(-) diff --git a/tests/test-server-frames.cpp b/tests/test-server-frames.cpp index 7e39a0f07305..9d10fea8f08f 100644 --- a/tests/test-server-frames.cpp +++ b/tests/test-server-frames.cpp @@ -168,6 +168,16 @@ static void a_mover_streams_moves_without_waiting() { 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) { @@ -178,10 +188,12 @@ static void run_copies(size_t lanes, size_t chunk, size_t n_transfers, size_t by 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 - auto resolve = [&](const buffer_ref & r) -> std::byte * { + 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 refused - return r.generation == 0 && r.buffer < v.size() && r.offset + r.bytes <= v[r.buffer].size() ? v[r.buffer].data() + r.offset : nullptr; + // 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; @@ -216,6 +228,34 @@ static void run_copies(size_t lanes, size_t chunk, size_t n_transfers, size_t by } 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. @@ -237,9 +277,11 @@ static void drain_all(memory_mover & mover, done_map & done, size_t want) { // 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); - auto resolve = [&](const buffer_ref & r) -> std::byte * { + pin_pool pool; + auto resolve = [&](const buffer_ref & r) -> buffer_pin { auto & v = r.buffer == 0 ? a : b; - return r.generation == 0 && r.offset + r.bytes <= v.size() ? v.data() + r.offset : nullptr; + 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); @@ -256,8 +298,11 @@ static void a_full_completion_ring_is_backpressure_not_a_deadlock() { // overlapping ranges in one buffer reached parallel memcpy (UB) static void invalid_aliases_and_overlaps_are_refused() { std::vector a(1 << 16); - auto resolve = [&](const buffer_ref & r) -> std::byte * { - return r.generation == 0 && r.offset + r.bytes <= a.size() ? a.data() + r.offset : nullptr; + 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); @@ -267,22 +312,50 @@ static void invalid_aliases_and_overlaps_are_refused() { 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, 5); + 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"); +} + 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)); - auto resolve = [&](const buffer_ref & r) -> std::byte * { + pin_pool pool; + auto resolve = [&](const buffer_ref & r) -> buffer_pin { auto & v = r.pool == 0 ? src : dst; - return r.generation == 0 && r.buffer < v.size() && r.offset + r.bytes <= v[r.buffer].size() ? v[r.buffer].data() + r.offset : nullptr; + 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); { @@ -300,6 +373,7 @@ static void teardown_with_work_outstanding_ends_every_ticket() { 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 { @@ -326,8 +400,10 @@ int main(int argc, char ** argv) { 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(); teardown_with_work_outstanding_ends_every_ticket(); the_parallel_copier_moves_many_at_once(); std::cout << "test-server-frames: ok\n"; diff --git a/tools/server/server-frames.h b/tools/server/server-frames.h index 9263d62a9991..c0e9995a03d5 100644 --- a/tools/server/server-frames.h +++ b/tools/server/server-frames.h @@ -54,27 +54,31 @@ class frame_ring { 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) { - const uint64_t raw = tail_.load(std::memory_order_relaxed); + 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); + head_cache_ = head_.load(std::memory_order_acquire) & COUNT; if (tail - head_cache_ >= slots_.size()) { return false; } } slots_[tail & mask_] = frame; - tail_.store(tail + 1, std::memory_order_release); + 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); + 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; @@ -84,20 +88,22 @@ class frame_ring { out[i] = slots_[(head + i) & mask_]; } if (n > 0) { - head_.store(head + n, std::memory_order_release); + 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 (an atomic wait on the consumer's head). - void wait_for_room() const { - const uint64_t tail = tail_.load(std::memory_order_relaxed); - uint64_t head = head_.load(std::memory_order_acquire); - while (tail - head >= slots_.size()) { - head_.wait(head, std::memory_order_acquire); - head = head_.load(std::memory_order_acquire); + // 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 @@ -112,16 +118,19 @@ class frame_ring { } } - // The producer ends the stream; a waiting consumer wakes (the word it sleeps on changes). + // 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_release); + 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); } + uint64_t taken() const { return head_.load(std::memory_order_acquire) & COUNT; } private: static constexpr uint64_t CLOSED = uint64_t(1) << 63; @@ -129,7 +138,7 @@ class frame_ring { std::vector slots_; const uint64_t mask_; - alignas(64) std::atomic head_{0}; // consumer writes + 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 @@ -157,6 +166,53 @@ struct buffer_ref { }; 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 { @@ -220,6 +276,7 @@ class memory_mover { 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); pending_.reset(); break; case start_result::would_block: return started; // engines full: drain completions, pump again } } @@ -275,7 +332,8 @@ class memory_mover { uint64_t backpressured() const { return backpressured_.load(std::memory_order_relaxed); } protected: - enum class start_result : uint8_t { started, refused, would_block }; + // 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 @@ -336,11 +394,14 @@ class memory_mover { // 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: - using resolver = std::function; // a pool's id -> its bytes - - parallel_copier(frame_ring & in, resolver resolve, size_t lanes, size_t chunk_bytes, size_t in_flight) + 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)), @@ -385,18 +446,16 @@ class parallel_copier final : public memory_mover { 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 }; - // The same live bytes named twice: same domain, pool, buffer, generation, offset AND length, and the - // resolver vouches for them (live generation, in bounds). - bool aliases(const buffer_ref & a, const buffer_ref & b) const override { - return a.domain == b.domain && a.pool == b.pool && a.buffer == b.buffer && a.generation == b.generation && - a.offset == b.offset && a.bytes == b.bytes && a.domain != memory_domain::disk && resolve_(a) != nullptr; - } + // Decided in start() on the resolved physical ranges, never on ids. + bool aliases(const buffer_ref &, const buffer_ref &) const override { return false; } - static bool overlapping(const buffer_ref & a, const buffer_ref & b) { - return a.domain == b.domain && a.pool == b.pool && a.buffer == b.buffer && - a.offset < b.offset + b.bytes && b.offset < a.offset + a.bytes; + 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 { @@ -407,7 +466,7 @@ class parallel_copier final : public memory_mover { progress_.reset(); slot & s = slots_[p.slot]; if (p.next == 0) { - s.in_use.store(false, std::memory_order_release); // no chunk handed: nothing written, slot free + free_slot(s); // no chunk handed: nothing written; the pins go back to their pools return transfer_status::cancelled; } // part-handed: its handed chunks land and the last one reports `failed` (a partial destination); @@ -416,36 +475,47 @@ class parallel_copier final : public memory_mover { 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 - s.in_use.store(false, std::memory_order_release); + free_slot(s); return transfer_status::failed; } return std::nullopt; } - void retire(uint32_t s) override { slots_[s].in_use.store(false, std::memory_order_release); } + 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 } - if (overlapping(t.src, t.dst)) { - return start_result::refused; // independent parallel chunks over overlapping ranges race (UB) - } - std::byte * src = resolve_(t.src); - std::byte * dst = resolve_(t.dst); - if (src == nullptr || dst == nullptr) { + 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) { + return start_result::aliased; // the same bytes: nothing to move (the pins go back now) + } + if (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 + return start_result::would_block; // every in-flight slot is busy (the pins go back; re-resolved next pump) } + 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, dst, t.src.bytes, n_chunks, 0 }; + 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) { @@ -497,7 +567,7 @@ class parallel_copier final : public memory_mover { } } - resolver resolve_; + Resolver resolve_; size_t chunk_; std::vector slots_; std::vector> lanes_; From 2042f0d62e16880c317c058707811749d688dd4d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 13:43:18 -0600 Subject: [PATCH 7/7] frames: every terminal frame keeps its transfer's pins until it is drained, aliases and late cancels included (Codex's third review of #134) - An alias claims a slot and holds both pins there; it settles `aliased` with that slot, so the pins return only when the frame is drained (they were returned at once). - cancel_pending keeps the slot (and its pins) for a transfer cancelled with nothing handed, or whose handed chunks had all landed: the base settles that terminal with the slot (terminal_slot_), retired on drain. - Overlap still refused, now checked before the slot claim; equal addresses are the alias. Test: an alias across two ids over the same bytes holds both pins after it settles and returns them only on drain. Receipt (M5): test-server-frames ok; -Wall -Wextra -Werror under -fsanitize=thread 5 of 5 ok, under -fsanitize=address,undefined 3 of 3 ok. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/test-server-frames.cpp | 19 +++++++++++++++++ tools/server/server-frames.h | 41 +++++++++++++++++++++++++----------- 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/tests/test-server-frames.cpp b/tests/test-server-frames.cpp index 9d10fea8f08f..a27f9cc783ae 100644 --- a/tests/test-server-frames.cpp +++ b/tests/test-server-frames.cpp @@ -348,6 +348,24 @@ static void a_transfer_holds_its_pins_until_drained() { 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)); @@ -404,6 +422,7 @@ int main(int argc, char ** argv) { 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"; diff --git a/tools/server/server-frames.h b/tools/server/server-frames.h index c0e9995a03d5..3b28e4b86e49 100644 --- a/tools/server/server-frames.h +++ b/tools/server/server-frames.h @@ -276,7 +276,7 @@ class memory_mover { 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); 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 } } @@ -311,7 +311,7 @@ class memory_mover { in_.close(); if (pending_) { if (const auto ended = cancel_pending()) { - settle(pending_->ticket, *ended); + settle(pending_->ticket, *ended, take_terminal_slot()); } // else an engine holds part of it and reports its one terminal frame pending_.reset(); } @@ -352,6 +352,11 @@ class memory_mover { // 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. @@ -366,14 +371,21 @@ class memory_mover { 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). - void settle(uint64_t ticket, transfer_status status) { - if (!settled_.push(transfer_done_frame{ ticket, status })) { + // `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 }); + 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(); @@ -466,7 +478,7 @@ class parallel_copier final : public memory_mover { progress_.reset(); slot & s = slots_[p.slot]; if (p.next == 0) { - free_slot(s); // no chunk handed: nothing written; the pins go back to their pools + 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); @@ -474,8 +486,9 @@ class parallel_copier final : public memory_mover { 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 - free_slot(s); + // 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; @@ -497,16 +510,20 @@ class parallel_copier final : public memory_mover { const std::byte * a = src.data(); const std::byte * b = dst.data(); const uint64_t n = t.src.bytes; - if (a == b) { - return start_result::aliased; // the same bytes: nothing to move (the pins go back now) - } - if (a < b + n && b < a + n) { + 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);