From 8c7ef1e7913a41391d1fbce008b565b4ad53c020 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 11:16:26 -0600 Subject: [PATCH 1/3] server: one step's sequences sample at once on lanes (528.6 -> 123.2 us per step at six minds, same tokens); the server is C++20 Every sequence a decode step produced was sampled one after another on the main thread while the GPU waited for the next submit. Each slot's sampler is its own state, so they need not wait on each other. - common_sampler_row: one output row's pointers, gathered by the thread that owns the context (one synchronize). common_sampler_sample_row / _and_accept_rows read only the sampler and the row, never the context; common_sampler_sample(ctx, idx) is gather + sample_row, so there is one path. - presample(): at the head of post_decode it finds every slot this view samples (plain or the MTP verify, the same predicate as the loops), gathers rows, and samples and accepts all of them at once on the lanes; the loops then emit in slot order exactly as before (an assert keeps the predicate in step). A sampling error is carried to its own slot's step, as the serial path raised it. - server_lanes (server-lanes.h): claims are lock-free from one (run id << 32 | index) word, so a lane finishing an earlier run can never claim in a new one; each lane has its own wake word, and a run wakes only as many lanes as it has jobs beyond the caller's (atomic notify: a futex, not a mutex and condition variable); the caller runs jobs and never sleeps; idle lanes burn nothing; on macOS lanes run at user-interactive QoS (performance cores). Lanes = min(slots - 1, cores the OS reports - 1). - The server targets C++20 (atomic wait/notify); u8path, deprecated in C++20, becomes a char8_t path. Receipts (qwen35-0.8b, M5, 2026-11-16): test-server-lanes: every job runs once at 1..1000 jobs, a job's exception reaches the caller; one decode of six sequences, 400 reps alternating order: serial 528.6 us/step, laned 123.2 us/step (4.29x), the same token every rep. Six concurrent MTP streams at temperature 0: text identical to the serial build on every stream. End-to-end tok/s on the M5 is not a receipt here: the live residents share the GPU, and serial runs alone ranged 72-219 tok/s. 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo (cherry picked from commit cc21b09659d0fc6aeb39a3fbe11843fd0b2dd1cd) --- tests/CMakeLists.txt | 2 + tests/test-server-lanes.cpp | 142 +++++++++++++++++++++++++++++++ tools/server/CMakeLists.txt | 5 +- tools/server/server-context.cpp | 110 +++++++++++++++++++++--- tools/server/server-lanes.h | 144 ++++++++++++++++++++++++++++++++ tools/server/server-tools.cpp | 3 +- 6 files changed, 394 insertions(+), 12 deletions(-) create mode 100644 tests/test-server-lanes.cpp create mode 100644 tools/server/server-lanes.h diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 192cb1b63e46..fec30b164427 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -182,6 +182,8 @@ endif () llama_build(test-recurrent-state-rollback.cpp) llama_build_and_test(test-sampler-penalties.cpp) +llama_build(test-server-lanes.cpp) # needs -m : laned sampling picks the serial tokens; the step's us serial vs laned +target_compile_features(test-server-lanes PRIVATE cxx_std_20) llama_build(test-sampler-coarse.cpp) # needs -m : ballpark sampling picks exactly the full path's token # GGML_TENSOR_FLAG_GRAD: a leaf whose gradient the backward computes, never optimized (the walk reads the cached prefix K/V gradient) diff --git a/tests/test-server-lanes.cpp b/tests/test-server-lanes.cpp new file mode 100644 index 000000000000..7b1b00220e5f --- /dev/null +++ b/tests/test-server-lanes.cpp @@ -0,0 +1,142 @@ +// what this catches: sampling one step's sequences on the lanes (server-lanes.h, CONTINUUM-ENGINE 4.7.14) +// choosing a different token than sampling them one after another, a lane run that loses or repeats a +// job, a job exception that does not reach the caller; and it reports the step's sampling time serial vs +// laned on real logits (needs -m ; the receipt is the per-step microseconds it prints). +#include "../tools/server/server-lanes.h" + +#include "arg.h" +#include "common.h" +#include "llama.h" +#include "sampling.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +static void require(bool condition, const char * message) { + if (!condition) { + std::fprintf(stderr, "FAILED: %s\n", message); + std::exit(1); + } +} + +static double now_us() { + return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +// the lanes alone: every job once, any count, exceptions carried back +static void lanes_run_every_job_once() { + server_lanes lanes(5); + for (size_t n : { (size_t) 1, (size_t) 2, (size_t) 6, (size_t) 64, (size_t) 1000 }) { + for (int rep = 0; rep < 200; ++rep) { + std::vector> hits(n); + lanes.run(n, [&](size_t i) { hits[i].fetch_add(1, std::memory_order_relaxed); }); + for (auto & h : hits) { + require(h.load() == 1, "every job runs exactly once"); + } + } + } + bool caught = false; + try { + lanes.run(6, [](size_t i) { if (i == 3) { throw std::runtime_error("job 3"); } }); + } catch (const std::runtime_error & e) { + caught = std::string(e.what()) == "job 3"; + } + require(caught, "a job's exception reaches the caller"); + std::atomic after{0}; + lanes.run(6, [&](size_t) { after++; }); + require(after.load() == 6, "the lanes run normally after a failed run"); +} + +int main(int argc, char ** argv) { + lanes_run_every_job_once(); + + common_params params; + if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) { + return 1; + } + const int n_seq = 6; + params.n_parallel = n_seq; + params.kv_unified = true; + common_init(); + llama_backend_init(); + auto init = common_init_from_params(params); + llama_model * model = init->model(); + llama_context * ctx = init->context(); + require(model && ctx, "model loads"); + const llama_vocab * vocab = llama_model_get_vocab(model); + + // one decode of six sequences, one output row each: the shape of a serving step + const char * topics[n_seq] = { "the ledger", "a merge queue", "a kv cache", "the grid", "a resident", "a checkpoint" }; + llama_batch batch = llama_batch_init(512, 0, n_seq); + std::vector out_idx(n_seq); + for (int s = 0; s < n_seq; ++s) { + const auto toks = common_tokenize(vocab, std::string("Write about ") + topics[s] + ".", true, true); + for (size_t i = 0; i < toks.size(); ++i) { + const bool last = i + 1 == toks.size(); + if (last) { + out_idx[s] = batch.n_tokens; + } + common_batch_add(batch, toks[i], (llama_pos) i, { s }, last); + } + } + require(llama_decode(ctx, batch) == 0, "decode"); + + common_params_sampling sp; + sp.top_k = 40; + sp.penalty_last_n = 256; + sp.penalty_repeat = 1.1f; + std::vector base(n_seq); + for (int s = 0; s < n_seq; ++s) { + base[s] = common_sampler_init(model, sp); + } + std::vector rows(n_seq); + for (int s = 0; s < n_seq; ++s) { + rows[s] = common_sampler_row_ith(ctx, out_idx[s]); + } + + server_lanes lanes(n_seq - 1); + const int reps = 400; + double t_serial = 0, t_laned = 0; + std::vector a(n_seq), b(n_seq); + for (int rep = 0; rep < reps; ++rep) { + std::vector s1(n_seq), s2(n_seq); + for (int s = 0; s < n_seq; ++s) { + s1[s] = common_sampler_clone(base[s]); + s2[s] = common_sampler_clone(base[s]); + } + // alternate which goes first, so neither always meets a warm or cold cache + auto serial = [&] { + const double t0 = now_us(); + for (int s = 0; s < n_seq; ++s) { + a[s] = common_sampler_sample_row(s1[s], rows[s]); + } + t_serial += now_us() - t0; + }; + auto laned = [&] { + const double t0 = now_us(); + lanes.run(n_seq, [&](size_t s) { b[s] = common_sampler_sample_row(s2[s], rows[s]); }); + t_laned += now_us() - t0; + }; + if (rep % 2 == 0) { serial(); laned(); } else { laned(); serial(); } + for (int s = 0; s < n_seq; ++s) { + require(a[s] == b[s], "a laned sample picks exactly the serial token"); + common_sampler_free(s1[s]); + common_sampler_free(s2[s]); + } + } + std::printf("one step, %d sequences, %d reps: serial %.1f us/step, laned (%zu lanes) %.1f us/step, %.2fx\n", + n_seq, reps, t_serial / reps, lanes.size(), t_laned / reps, t_serial / t_laned); + + for (auto * s : base) { + common_sampler_free(s); + } + llama_batch_free(batch); + std::printf("test-server-lanes: ok\n"); + return 0; +} diff --git a/tools/server/CMakeLists.txt b/tools/server/CMakeLists.txt index 67fb03964d7c..e19fa5847231 100644 --- a/tools/server/CMakeLists.txt +++ b/tools/server/CMakeLists.txt @@ -33,6 +33,9 @@ endif() target_include_directories(${TARGET} PRIVATE ../mtmd) target_include_directories(${TARGET} PRIVATE ${CMAKE_SOURCE_DIR}) target_link_libraries(${TARGET} PUBLIC llama-common mtmd ${CMAKE_THREAD_LIBS_INIT}) +# Continuum fork: the server is C++20 (atomic wait/notify for the sampling lanes, CONTINUUM-ENGINE 4.7.14); +# PUBLIC so every target that includes the server's headers compiles them as written +target_compile_features(${TARGET} PUBLIC cxx_std_20) # the faults tools/server/tests inject (server-test-faults.h); only the server test build sets it option(LLAMA_SERVER_TEST_FAULTS "llama-server: compile in the test fault injection (tests only, never a release)" OFF) @@ -69,4 +72,4 @@ add_executable(${TARGET} main.cpp) install(TARGETS ${TARGET} RUNTIME) target_link_libraries(${TARGET} PRIVATE llama-server-impl) -target_compile_features(${TARGET} PRIVATE cxx_std_17) +target_compile_features(${TARGET} PRIVATE cxx_std_20) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index ff006fd0abe1..b810c802c2cf 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1,5 +1,6 @@ #include #include "server-context.h" +#include "server-lanes.h" #include "../../src/llama-ext.h" #include "server-train.h" #include "server-adapter-file.h" @@ -375,6 +376,14 @@ struct server_slot { common_sampler_ptr smpl; + // Continuum fork (CONTINUUM-ENGINE 4.7.14): this step's sample, made on a lane before the loop that + // emits it; a sampling error is carried here and raised in this slot's own step + bool presampled = false; + llama_token presampled_id = LLAMA_TOKEN_NULL; + common_sampler_ptr presampled_save; // the speculative save point, cloned before the verify + std::vector presampled_accepted; // the speculative verify's accepted tokens + std::string presample_error; + llama_token sampled; // in speculative mode, this is the last accepted token // for TTS models, this is the embd generated from prev step, decode this to generate next hidden state @@ -984,6 +993,10 @@ struct server_context_impl { // whether any configured drafter reads the prompt's tokens (the n-gram family); set at load bool spec_reads_prompt = false; + // the lanes one step's slots sample on at once (CONTINUUM-ENGINE 4.7.14); sized at load from the + // slot count and the cores the OS reports, never more lanes than slots + std::unique_ptr sample_lanes; + common_init_result_ptr llama_init; llama_context * ctx_tgt = nullptr; @@ -1419,6 +1432,12 @@ struct server_context_impl { n_swa = params_base.swa_full ? 0 : llama_model_n_swa(model_tgt); + { + const size_t cores = std::max(1, std::thread::hardware_concurrency()); + const size_t workers = std::min(params_base.n_parallel > 1 ? params_base.n_parallel - 1 : 0, cores - 1); + sample_lanes = std::make_unique(workers); + } + spec_reads_prompt = std::any_of(params_base.speculative.types.begin(), params_base.speculative.types.end(), [](common_speculative_type t) { return t == COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE || t == COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K || @@ -4366,6 +4385,71 @@ struct server_context_impl { return true; } + // Continuum fork (CONTINUUM-ENGINE 4.7.14): every slot that samples in this view samples at once. + // Gather on this thread (one synchronize; a row is raw pointers into the context's outputs, so + // sampling from it never calls into the context), sample on the lanes (each slot's sampler is its + // own state), and the loops in post_decode then emit in slot order exactly as before. Same tokens: + // each sampler sees the same rows and its own RNG in the same order. + void presample(int32_t off, int32_t n_batch_tokens) { + auto inside = [&](int32_t idx) { return idx >= off && idx < off + n_batch_tokens; }; + struct sample_job { + server_slot * slot; + bool verify; // speculative verify (MTP), else one plain sample + std::vector rows; + }; + std::vector jobs; + for (auto & slot : slots) { + slot.presampled = false; + slot.presample_error.clear(); + if (!slot.task) { + continue; + } + const bool drafting = slot.can_speculate() && !slot.spec_draft.empty(); + if (slot.state == SLOT_STATE_GENERATING && drafting && !slot.spec_i_batch.empty()) { + GGML_ASSERT(slot.spec_i_batch.size() == slot.spec_draft.size() + 1); + jobs.push_back({ &slot, true, {} }); + continue; + } + if (!inside(slot.i_batch) || drafting) { + continue; + } + const bool done_prompt = slot.state == SLOT_STATE_DONE_PROMPT && + slot.task->type != SERVER_TASK_TYPE_EMBEDDING && slot.task->type != SERVER_TASK_TYPE_RERANK; + if (slot.state == SLOT_STATE_GENERATING || done_prompt) { + jobs.push_back({ &slot, false, {} }); + } + } + if (jobs.empty()) { + return; + } + for (auto & job : jobs) { + if (job.verify) { + for (const int idx : job.slot->spec_i_batch) { + job.rows.push_back(common_sampler_row_ith(ctx_tgt, idx)); + } + } else { + job.rows.push_back(common_sampler_row_ith(ctx_tgt, job.slot->i_batch - off)); + } + } + scoped_timer timer(t_sampl, n_sampl); + sample_lanes->run(jobs.size(), [&](size_t j) { + auto & job = jobs[j]; + auto & slot = *job.slot; + try { + if (job.verify) { + slot.presampled_save.reset(common_sampler_clone(slot.smpl.get())); + slot.presampled_accepted = common_sampler_sample_and_accept_rows(slot.smpl.get(), job.rows, slot.spec_draft); + } else { + slot.presampled_id = common_sampler_sample_row(slot.smpl.get(), job.rows[0]); + common_sampler_accept(slot.smpl.get(), slot.presampled_id, true); + } + slot.presampled = true; + } catch (const std::exception & e) { + slot.presample_error = e.what(); // raised in this slot's own step, as the serial path did + } + }); + } + void post_decode(int32_t n_batch_tokens, int32_t off, llama_batch & batch_view) { // for checking if a given batch index is inside batch_view auto is_inside_view = [&](int32_t idx) { @@ -4382,6 +4466,8 @@ struct server_context_impl { } }); + presample(off, n_batch_tokens); + auto accept_special_token = [&](server_slot & slot, llama_token token) { return params_base.special || slot.task->params.sampling.preserved_tokens.find(token) != slot.task->params.sampling.preserved_tokens.end(); @@ -4435,16 +4521,16 @@ struct server_context_impl { // shifted according to the current sub-batch const int tok_idx = slot.i_batch - off; - llama_token id; - { - scoped_timer timer(t_sampl, n_sampl); - id = common_sampler_sample(slot.smpl.get(), slot.ctx_tgt, tok_idx); + // sampled and accepted on a lane by presample(); the predicate there mirrors this loop + if (!slot.presample_error.empty()) { + throw std::runtime_error(std::exchange(slot.presample_error, {})); } + GGML_ASSERT(slot.presampled && "presample() must cover every slot this loop samples"); + const llama_token id = slot.presampled_id; + slot.presampled = false; slot.i_batch = -1; - common_sampler_accept(slot.smpl.get(), id, true); - // here we have synchronized the llama_context (due to the sampling above), so we can do time measurement const int64_t t_now = ggml_time_us(); @@ -4497,10 +4583,14 @@ struct server_context_impl { // verify and try to accept the draft { - common_sampler_ptr smpl_save(common_sampler_clone(slot.smpl.get())); - - GGML_ASSERT(slot.spec_i_batch.size() == n_draft + 1); - auto accepted = common_sampler_sample_and_accept_n(slot.smpl.get(), slot.ctx_tgt, slot.spec_i_batch, slot.spec_draft); + // cloned, verified and accepted on a lane by presample() + if (!slot.presample_error.empty()) { + throw std::runtime_error(std::exchange(slot.presample_error, {})); + } + GGML_ASSERT(slot.presampled && "presample() must cover every slot this loop verifies"); + slot.presampled = false; + common_sampler_ptr smpl_save = std::move(slot.presampled_save); + auto accepted = std::move(slot.presampled_accepted); slot.spec_i_batch.clear(); GGML_ASSERT(accepted.size() >= 1); diff --git a/tools/server/server-lanes.h b/tools/server/server-lanes.h new file mode 100644 index 000000000000..7085c84c99d4 --- /dev/null +++ b/tools/server/server-lanes.h @@ -0,0 +1,144 @@ +#pragma once + +// Continuum fork: a fixed set of lanes that run one step's independent jobs at once (CONTINUUM-ENGINE +// 4.7.14). Built for jobs of tens to hundreds of microseconds, every few milliseconds: +// - a job is claimed lock-free from one 64-bit word (run id << 32 | next index), so a lane finishing an +// earlier run can never claim in a new one; +// - each lane has its own wake word: a run wakes only as many lanes as it has jobs beyond the caller's, +// with an atomic notify (a futex: __ulock on macOS), never a mutex and condition variable; +// - the caller is a lane and never sleeps: it runs jobs, then spins on the done count for the last few +// microseconds of the slowest lane (no syscall, no core clocking down before the next GPU submit); +// - an idle lane sleeps on its wake word and burns nothing. +// A job's exception is carried back to the caller. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__APPLE__) +#include +#endif + +// The one OS-specific line: lanes run where the step's latency is decided (macOS: performance cores). +inline void server_lane_priority() { +#if defined(__APPLE__) + pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0); +#endif +} + +class server_lanes { +public: + explicit server_lanes(size_t n_workers) : lanes(n_workers) { + for (size_t i = 0; i < n_workers; ++i) { + lanes[i].thread = std::thread([this, i] { work(lanes[i]); }); + } + } + + server_lanes(const server_lanes &) = delete; + server_lanes & operator=(const server_lanes &) = delete; + + ~server_lanes() { + stop.store(true, std::memory_order_release); + for (auto & lane : lanes) { + lane.wake.fetch_add(1, std::memory_order_release); + lane.wake.notify_one(); + } + for (auto & lane : lanes) { + lane.thread.join(); + } + } + + size_t size() const { return lanes.size() + 1; } + + // Run fn(i) for every i in [0, n) across the caller and up to n - 1 lanes; return when all have run. + // The first job exception is rethrown here. + void run(size_t n, const std::function & fn) { + if (n == 0) { + return; + } + const size_t helpers = std::min(n - 1, lanes.size()); + if (helpers == 0) { + for (size_t i = 0; i < n; ++i) { + fn(i); + } + return; + } + job.store(&fn, std::memory_order_relaxed); + n_jobs.store(n, std::memory_order_relaxed); + done.store(0, std::memory_order_relaxed); + failure = nullptr; + // published with this release: job and n_jobs are visible to whoever claims in this run + next.store(++run_id << 32, std::memory_order_release); + for (size_t i = 0; i < helpers; ++i) { + lanes[i].wake.fetch_add(1, std::memory_order_release); + lanes[i].wake.notify_one(); + } + take(); + while (done.load(std::memory_order_acquire) != n) { + std::this_thread::yield(); // the slowest lane's last microseconds; the caller never sleeps + } + if (failure) { + std::rethrow_exception(failure); + } + } + +private: + struct lane { + std::thread thread; + std::atomic wake{0}; + }; + + // claim and run the current run's jobs until none are left + void take() { + uint64_t claim = next.load(std::memory_order_acquire); + while (true) { + const size_t i = (size_t) (claim & 0xffffffffu); + // a lane holding an older word may read a newer n_jobs here; its compare-exchange then fails + if ((claim >> 32) == 0 || i >= n_jobs.load(std::memory_order_relaxed)) { + return; + } + if (!next.compare_exchange_weak(claim, claim + 1, std::memory_order_acq_rel, std::memory_order_acquire)) { + continue; // another lane claimed it, or a new run began: `claim` holds the current word + } + try { + (*job.load(std::memory_order_relaxed))(i); + } catch (...) { + std::lock_guard lock(failure_mutex); + if (!failure) { + failure = std::current_exception(); + } + } + done.fetch_add(1, std::memory_order_acq_rel); + claim = next.load(std::memory_order_acquire); + } + } + + void work(lane & self) { + server_lane_priority(); + uint64_t seen = self.wake.load(std::memory_order_acquire); + while (true) { + self.wake.wait(seen, std::memory_order_acquire); + seen = self.wake.load(std::memory_order_acquire); + if (stop.load(std::memory_order_acquire)) { + return; + } + take(); + } + } + + std::vector lanes; + std::atomic stop{false}; + std::atomic next{0}; + uint64_t run_id = 0; // the caller's only + std::atomic done{0}; + std::atomic n_jobs{0}; + std::atomic *> job{nullptr}; + std::mutex failure_mutex; // only when a job throws + std::exception_ptr failure; +}; diff --git a/tools/server/server-tools.cpp b/tools/server/server-tools.cpp index 12e9dbb8cfa9..6a8a68dad8df 100644 --- a/tools/server/server-tools.cpp +++ b/tools/server/server-tools.cpp @@ -99,7 +99,8 @@ enum class list_kind { // a narrow path uses the active code page on Windows, so every crossing between // a std::string (always UTF-8 here) and fs::path is converted explicitly static fs::path path_from_utf8(const std::string & s) { - return fs::u8path(s); + // C++20: a path built from char8_t is UTF-8 by type (u8path is deprecated) + return fs::path(std::u8string(reinterpret_cast(s.data()), s.size())); } // '/' separators on every platform: Windows accepts them, the web UI needs them From 0a81e995cbd75e3541c1cbfe8f200e18ac3e9332 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 12:00:56 -0600 Subject: [PATCH 2/3] server lanes: one record per run published before its claim word, and stop checked before every sleep (Codex's review of #125) - A lane holding an earlier run's claim word could read the next run's job count (stored before the new claim word) and claim against the old word, running one of the new run's jobs twice. Now each run's job, count and id are one record, published (release) BEFORE the run's claim word; a lane reads the claim word, then the record, and claims only when the word's run id equals the record's. Records alternate in two places with atomic fields: one is rewritten only two runs later, when a stale lane's claim word is two runs old and its compare-exchange fails. - A lane started from a load of its wake word and never checked stop before its first wait, so a destructor that signalled before the lane ran was missed and the join hung. Now a lane starts from 0 and checks stop before every sleep. Receipts (M5, 2026-11-16): a ThreadSanitizer build of the lanes alone (500 construct/destroy, then 20,000 back-to-back runs of 2-7 jobs, each job checked exactly once): clean, every job once; the same harness against the previous header hangs until a 120 s alarm. test-server-lanes adds the regression (2,000 construct/destroy; 50,000 back-to-back runs exactly once) and still picks the serial token every rep (3.79x-4.89x per step across runs on the shared M5). 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/test-server-lanes.cpp | 21 +++++++++++++++++ tools/server/server-lanes.h | 45 ++++++++++++++++++++++++++++--------- 2 files changed, 55 insertions(+), 11 deletions(-) diff --git a/tests/test-server-lanes.cpp b/tests/test-server-lanes.cpp index 7b1b00220e5f..e5f4e6c3700a 100644 --- a/tests/test-server-lanes.cpp +++ b/tests/test-server-lanes.cpp @@ -53,8 +53,29 @@ static void lanes_run_every_job_once() { require(after.load() == 6, "the lanes run normally after a failed run"); } +// regressions for Codex's review of #125: a stop signalled before a lane's first wait was missed (the +// join hung); and a lane holding an earlier run's claim word could claim against the next run's jobs +static void lanes_never_hang_and_never_cross_runs() { + for (int i = 0; i < 2000; ++i) { + server_lanes lanes(5); // destroyed at once: a lane may not have reached its first wait yet + } + server_lanes lanes(5); + std::vector> hits(8); + for (int run = 0; run < 50000; ++run) { + const size_t n = 2 + (size_t) (run % 6); + for (size_t i = 0; i < n; ++i) { + hits[i].store(0, std::memory_order_relaxed); + } + lanes.run(n, [&](size_t i) { hits[i].fetch_add(1, std::memory_order_relaxed); }); + for (size_t i = 0; i < n; ++i) { + require(hits[i].load() == 1, "back to back, every job of every run runs exactly once"); + } + } +} + int main(int argc, char ** argv) { lanes_run_every_job_once(); + lanes_never_hang_and_never_cross_runs(); common_params params; if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) { diff --git a/tools/server/server-lanes.h b/tools/server/server-lanes.h index 7085c84c99d4..9f20d87ae3d9 100644 --- a/tools/server/server-lanes.h +++ b/tools/server/server-lanes.h @@ -69,12 +69,17 @@ class server_lanes { } return; } - job.store(&fn, std::memory_order_relaxed); - n_jobs.store(n, std::memory_order_relaxed); done.store(0, std::memory_order_relaxed); failure = nullptr; - // published with this release: job and n_jobs are visible to whoever claims in this run - next.store(++run_id << 32, std::memory_order_release); + // one immutable record per run, published BEFORE the run's claim word: a lane claims only when the + // word's run id matches the record's, so a word from an earlier run can never pair with this + // run's jobs or bounds (Codex on #125) + run_record & rec = runs[++run_id % 2]; + rec.fn.store(&fn, std::memory_order_relaxed); + rec.n.store(n, std::memory_order_relaxed); + rec.id.store(run_id, std::memory_order_release); + record.store(&rec, std::memory_order_release); + next.store(run_id << 32, std::memory_order_release); for (size_t i = 0; i < helpers; ++i) { lanes[i].wake.fetch_add(1, std::memory_order_release); lanes[i].wake.notify_one(); @@ -98,16 +103,19 @@ class server_lanes { void take() { uint64_t claim = next.load(std::memory_order_acquire); while (true) { + // read after the claim word: a word of run r implies run r's record is published (it was + // stored first, with release), so a mismatch can only mean the word is stale + const run_record * run = record.load(std::memory_order_acquire); const size_t i = (size_t) (claim & 0xffffffffu); - // a lane holding an older word may read a newer n_jobs here; its compare-exchange then fails - if ((claim >> 32) == 0 || i >= n_jobs.load(std::memory_order_relaxed)) { - return; + if (run == nullptr || (claim >> 32) != run->id.load(std::memory_order_acquire) || + i >= run->n.load(std::memory_order_relaxed)) { + return; // no run, a stale word, or this run's jobs are all claimed } if (!next.compare_exchange_weak(claim, claim + 1, std::memory_order_acq_rel, std::memory_order_acquire)) { continue; // another lane claimed it, or a new run began: `claim` holds the current word } try { - (*job.load(std::memory_order_relaxed))(i); + (*run->fn.load(std::memory_order_relaxed))(i); } catch (...) { std::lock_guard lock(failure_mutex); if (!failure) { @@ -121,8 +129,14 @@ class server_lanes { void work(lane & self) { server_lane_priority(); - uint64_t seen = self.wake.load(std::memory_order_acquire); + // from 0, never from a load at start: a wake (or the destructor's) that came before this thread + // ran is still seen; and stop is checked before every sleep (Codex on #125: a stop signalled before + // the first wait was missed, and the join hung) + uint64_t seen = 0; while (true) { + if (stop.load(std::memory_order_acquire)) { + return; + } self.wake.wait(seen, std::memory_order_acquire); seen = self.wake.load(std::memory_order_acquire); if (stop.load(std::memory_order_acquire)) { @@ -137,8 +151,17 @@ class server_lanes { std::atomic next{0}; uint64_t run_id = 0; // the caller's only std::atomic done{0}; - std::atomic n_jobs{0}; - std::atomic *> job{nullptr}; + struct run_record { + std::atomic id{0}; + std::atomic *> fn{nullptr}; + std::atomic n{0}; + }; + // two records alternate. A record is rewritten only two runs later, after its run's every job was + // done; a lane that was descheduled across that can read mixed fields, but its claim word is then two + // runs stale and its compare-exchange fails, so it never runs a job. The fields are atomic so that + // read is never a data race. + run_record runs[2]; + std::atomic record{nullptr}; std::mutex failure_mutex; // only when a job throws std::exception_ptr failure; }; From 229c7856420f3f25043329c479043ea1230deadf Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 13:02:05 -0600 Subject: [PATCH 3/3] server-lanes: a lane that fails to start stops and joins the lanes already started before the error leaves (Codex's review of #129) A std::thread construction that threw after earlier lanes started destroyed joinable threads (std::terminate). The constructor now catches, runs the same shutdown the destructor does (stop, wake, join every joinable lane), and rethrows. Lane threads start through an injectable spawn (std::thread by default) so the test fails the third start: the error reaches the caller after the two started lanes are joined. TSan-clean header unchanged otherwise; test-server-lanes ok (6 sequences: 5.37x on the M5). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/test-server-lanes.cpp | 21 +++++++++++++++++++ tools/server/server-lanes.h | 42 +++++++++++++++++++++++++------------ 2 files changed, 50 insertions(+), 13 deletions(-) diff --git a/tests/test-server-lanes.cpp b/tests/test-server-lanes.cpp index e5f4e6c3700a..42f8ee6fb651 100644 --- a/tests/test-server-lanes.cpp +++ b/tests/test-server-lanes.cpp @@ -10,6 +10,7 @@ #include "sampling.h" #include +#include #include #include #include @@ -73,7 +74,27 @@ static void lanes_never_hang_and_never_cross_runs() { } } +// what this catches: a lane thread that fails to start after others did destroyed joinable threads +// (std::terminate); the started lanes must be stopped and joined and the error reach the caller +static void lanes_failed_start_joins_the_started() { + size_t started = 0; + bool threw = false; + try { + server_lanes lanes(4, [&](std::function f) { + if (started == 2) { + throw std::system_error(std::make_error_code(std::errc::resource_unavailable_try_again)); + } + ++started; + return std::thread(std::move(f)); + }); + } catch (const std::system_error &) { + threw = true; + } + require(threw && started == 2, "a failed lane start reaches the caller after the started lanes are joined"); +} + int main(int argc, char ** argv) { + lanes_failed_start_joins_the_started(); lanes_run_every_job_once(); lanes_never_hang_and_never_cross_runs(); diff --git a/tools/server/server-lanes.h b/tools/server/server-lanes.h index 9f20d87ae3d9..21398ac17c8f 100644 --- a/tools/server/server-lanes.h +++ b/tools/server/server-lanes.h @@ -34,25 +34,27 @@ inline void server_lane_priority() { class server_lanes { public: - explicit server_lanes(size_t n_workers) : lanes(n_workers) { - for (size_t i = 0; i < n_workers; ++i) { - lanes[i].thread = std::thread([this, i] { work(lanes[i]); }); + // `spawn` starts one lane's thread (std::thread by default; a test injects a failure). If starting any + // lane throws, the lanes already started are stopped and joined before the exception leaves, so no + // joinable std::thread is ever destroyed (Codex on #129: that is std::terminate). + using spawn_fn = std::function)>; + + explicit server_lanes(size_t n_workers, const spawn_fn & spawn = [](std::function f) { return std::thread(std::move(f)); }) + : lanes(n_workers) { + try { + for (size_t i = 0; i < n_workers; ++i) { + lanes[i].thread = spawn([this, i] { work(lanes[i]); }); + } + } catch (...) { + shutdown(); + throw; } } server_lanes(const server_lanes &) = delete; server_lanes & operator=(const server_lanes &) = delete; - ~server_lanes() { - stop.store(true, std::memory_order_release); - for (auto & lane : lanes) { - lane.wake.fetch_add(1, std::memory_order_release); - lane.wake.notify_one(); - } - for (auto & lane : lanes) { - lane.thread.join(); - } - } + ~server_lanes() { shutdown(); } size_t size() const { return lanes.size() + 1; } @@ -94,6 +96,20 @@ class server_lanes { } private: + // stop every started lane, wake it, and join it; lanes never started have no thread + void shutdown() { + stop.store(true, std::memory_order_release); + for (auto & lane : lanes) { + lane.wake.fetch_add(1, std::memory_order_release); + lane.wake.notify_one(); + } + for (auto & lane : lanes) { + if (lane.thread.joinable()) { + lane.thread.join(); + } + } + } + struct lane { std::thread thread; std::atomic wake{0};