Skip to content

keeper-bench: go faster - #100670

Merged
al13n321 merged 12 commits into
masterfrom
kbslow
Apr 4, 2026
Merged

al13n321 merged 12 commits into
masterfrom
kbslow

Conversation

@al13n321

@al13n321 al13n321 commented Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

keeper-bench could do ~500K requests/s, which is less than what keeper can handle (for small reads). This PR gets rid of the pointless queue and the stats mutex. This takes it to 12M iterations/s, if keeper requests are replaced with no-op. That's comfortably more than the 1.2M requests/s that keeper can do before getting bottlenecked on ConcurrentBoundedQueue's mutex.

Version info

  • Merged into: 26.4.1.562

@al13n321
al13n321 requested a review from antonio2368 March 25, 2026 02:16
@clickhouse-gh

clickhouse-gh Bot commented Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0d5e10a]

Summary: ❌
Keeper Stress Tests (PR): Grafana: Run details (this run), Grafana: 1vs1 Comparison, Grafana: Historical progression

job_name test_name status info comment
Stress test (arm_tsan) failure
Hung check failed, possible deadlock found FAIL cidb, issue

AI Review

Summary

This PR refactors keeper-bench generated mode to remove the producer queue and collect per-thread stats. The performance direction is good, but there are correctness issues in request accounting/timing and a reproducibility regression in generator seeding. Verdict: request changes before merge because benchmark results can be inaccurate or non-reproducible.

Missing context
  • ⚠️ No CI logs or benchmark result artifacts were provided in the review context.
Findings

❌ Blockers

  • [programs/keeper-bench/Runner.cpp:349-353] requests_started is incremented before the max_iterations cutoff check. This can overcount and can report more "executed" requests than were actually submitted.
    Suggested fix: reserve only accepted iterations (CAS/rollback) or keep separate counters (requests_reserved, requests_submitted, requests_completed) and report completed/submitted explicitly.

  • [programs/keeper-bench/Runner.cpp:1266-1272 and 340-353] Warmup reset is racy with worker-side fetch_add: workers can increment around the reset boundary and then be counted as post-warmup requests.
    Suggested fix: switch to a monotonic total counter plus measurement_start snapshot, or gate reservation/accounting on an explicit measurement phase flag with ordering that prevents boundary leakage.

  • [programs/keeper-bench/Runner.cpp:1217-1236] Worker threads start before measurement timers are reset (elapsed, total_watch, start_timestamp_ms). With warmup_seconds=0, early operations can be counted while excluded from elapsed/time-limit accounting.
    Suggested fix: initialize measurement clocks before scheduling workers, or block workers on a measurement_started latch.

⚠️ Majors

  • [programs/keeper-bench/Generator.cpp:700-714, programs/keeper-bench/README.md:291-293] Reproducibility regression when generator.seed is omitted: each worker gets an independent random seed, but only one seed is printed.
    Suggested fix: generate one base seed once, print it, and derive per-thread seeds deterministically (for example base_seed + thread_idx) for all workers.
Tests
  • ⚠️ Add a deterministic concurrency test for iterations enforcement in generated mode (concurrency > 1, pipeline_depth > 1) to verify submitted/completed counts never exceed configured limits.
  • ⚠️ Add a warmup-boundary test ensuring requests generated before measurement start are never counted in measured totals.
  • ⚠️ Add a reproducibility test for omitted generator.seed that validates identical workloads across reruns with the same printed seed.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ➖
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Fix iteration/accounting correctness around max_iterations and warmup boundary.
  2. Fix measurement start ordering so timing/throughput windows are consistent.
  3. Restore reproducibility semantics for omitted generator.seed (single reproducible printed seed that fully defines all worker streams).

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Mar 25, 2026
Comment thread programs/keeper-bench/Runner.cpp Resolved
Comment thread programs/keeper-bench/Runner.h Resolved
Comment thread src/Coordination/KeeperReadThreadPool.h Resolved
Comment thread programs/keeper-bench/Stats.cpp Resolved
Comment thread programs/keeper-bench/Runner.h Resolved
Comment thread programs/keeper-bench/Runner.h Resolved
Comment thread programs/keeper-bench/Runner.cpp Resolved
@al13n321

Copy link
Copy Markdown
Contributor Author

max_iterations is no longer enforced strictly

It already wasn't, and also keeper-bench used to get stuck instead of quitting after the limit is reached.

info->clear();
for (auto & t : threads)
t.thread_info.clear();
requests_started = 0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

requests_started is reset while worker threads are still running and still doing fetch_add(1) unconditionally. Because warmup_complete is switched to true only after this reset, there is a window where warmup requests can increment the counter after reset and then be counted as measured requests.

This breaks the documented warmup semantics and can make iterations terminate early/non-deterministically.

Could we gate incrementing on warmup_complete (e.g. branch before fetch_add), or flip to a two-counter scheme (requests_started_total + measurement_start) so post-warmup accounting is race-free?

Comment thread programs/keeper-bench/Stats.cpp Resolved

try
{
for (size_t i = 0; i < concurrency; ++i)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

runBenchmarkWithGenerator starts worker threads before resetting info->elapsed, total_watch, and start_timestamp_ms. With warmup_seconds = 0, workers can already generate and complete requests in that window, so those requests are counted in thread_info but excluded from elapsed/time-limit accounting. This biases throughput upward and can also make timelimit/iterations accounting inconsistent at startup.

Could you move the timer reset block before scheduling workers, or gate worker loops on a measurement_started flag that is flipped only after timers are reset?

@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label Mar 26, 2026
void Generator::startup(Coordination::ZooKeeper & zookeeper)
{
std::cerr << "---- Initializing generators ----" << std::endl;
if (thread_idx == 0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the per-thread generators, runs without generator.seed are no longer reproducible: every worker picks its own random seed, but only thread 0 logs one seed.

README.md still states that when seed is omitted, a random seed is generated and printed for reproducibility. After this change, that printed value is insufficient to replay the same workload across all threads.

Could we generate one base seed once (in Runner), log it, and derive each worker seed deterministically (e.g. base_seed + thread_idx) even when generator.seed is absent?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this seed just seems PITA, we can remove it if you think there is no value in it.

collect_request(slot);
return;
}
size_t iteration_idx = requests_started.fetch_add(1);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

requests_started is incremented before the max_iterations guard, so this counter includes iterations that are never submitted/executed (iteration_idx >= max_iterations path). The final/periodic Requests executed: output can therefore exceed the configured limit and misreport benchmark results.

A minimal trace with max_iterations = 10:

  • one worker does iteration_idx = 10 via fetch_add (counter becomes 11),
  • then immediately hits iteration_idx >= max_iterations, sets shutdown = true, and skips submission,
  • final print reports at least 11 "executed" requests although only 10 were started.

Could you either:

  1. reserve slots only when accepted (CAS loop / fetch-add rollback), or
  2. track two counters (requests_reserved vs requests_completed) and print the actually completed one?

@antonio2368

Copy link
Copy Markdown
Member

You can merge anytime you think it's okay.
You can ignore comment for the seed, I will probably just remove it.

@al13n321

al13n321 commented Apr 3, 2026

Copy link
Copy Markdown
Contributor Author

I'm in CI hell again, all PRs are blocked on flaky tests, and I have to merge master into everything every day and hope to win the lottery :(

@clickhouse-gh

clickhouse-gh Bot commented Apr 4, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% (739,625/879,756) 84.10% (739,486/879,748) +0.00% (-139)
Functions 90.90% (798,420/878,613) 90.90% (798,315/878,596) +0.00% (-105)
Branches 76.60% (239,806/312,996) 76.60% (239,764/312,978) +0.00% (-42)

Changed lines: 0.00% (0/213) · Uncovered code

Full report · Diff report

@al13n321
al13n321 added this pull request to the merge queue Apr 4, 2026
Merged via the queue into master with commit 18dfe15 Apr 4, 2026
158 of 159 checks passed
@al13n321
al13n321 deleted the kbslow branch April 4, 2026 01:43
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 4, 2026
@al13n321

al13n321 commented Apr 4, 2026

Copy link
Copy Markdown
Contributor Author

Ooh, the PR check doesn't have to fully succeed, that's better.

@filimonov

filimonov commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

@al13n321 it is broken!

keeper-bench throws ZNONODE errors for Get requests on children_of: "/test" when running against a working Keeper cluster. The old binary works fine.

Root cause: commit 75a0d71b9b5 ("keeper-bench: go faster") changed the threading model. Each thread now creates its OWN Generator and calls PathGetter::initialize independently. The children_of resolver lists children at startup and caches the paths. When concurrent Multi requests (with remove_factor: 0.8) create and immediately remove children under /test, different threads see different transient children during their initialization. Some threads cache paths to nodes that are removed before the Get requests execute.

The OLD version used a single shared Generator initialized once before any benchmark mutations, so the cached paths matched the stable setup data

Patch by claude which solves the problem:

git diff --staged
diff --git a/programs/keeper-bench/Runner.cpp b/programs/keeper-bench/Runner.cpp
index 3b8470264dc..a23389f6a1e 100644
--- a/programs/keeper-bench/Runner.cpp
+++ b/programs/keeper-bench/Runner.cpp
@@ -257,6 +257,11 @@ void Runner::thread(std::vector<std::shared_ptr<Coordination::ZooKeeper>> zookee
     auto generator = std::make_shared<Generator>();
     generator->startup(*config_ptr, *zookeepers[0], thread_state.thread_idx);
 
+    /// Wait for all threads to finish initializing their generators before
+    /// any thread starts executing requests. This prevents early threads from
+    /// mutating the tree while late threads are still resolving `children_of` paths.
+    generator_init_barrier->arrive_and_wait();
+
     /// Randomly choosing connection index
     pcg64 rng(randomSeed());
     std::uniform_int_distribution<size_t> distribution(0, zookeepers.size() - 1);
@@ -1212,6 +1217,10 @@ void Runner::runBenchmarkWithGenerator()
     int64_t start_timestamp_ms = 0;
     threads = std::vector<ThreadState>(concurrency);
 
+    /// All threads must finish generator initialization (which resolves
+    /// `children_of` paths) before any thread starts executing requests.
+    generator_init_barrier = std::make_unique<std::barrier<>>(concurrency);
+
     try
     {
         for (size_t i = 0; i < concurrency; ++i)
diff --git a/programs/keeper-bench/Runner.h b/programs/keeper-bench/Runner.h
index 2579502a4ff..1a790848050 100644
--- a/programs/keeper-bench/Runner.h
+++ b/programs/keeper-bench/Runner.h
@@ -13,6 +13,7 @@
 #include <Generator.h>
 #include <Stats.h>
 
+#include <barrier>
 #include <filesystem>
 
 using Ports = std::vector<UInt16>;
@@ -138,6 +139,12 @@ private:
 
     std::vector<ThreadState> threads;
 
+    /// Barrier so all threads finish generator initialization (which resolves
+    /// `children_of` paths via ZooKeeper listing) before any thread starts
+    /// executing requests. Without this, early threads mutate the tree while
+    /// late threads are still initializing, causing stale path caches.
+    std::unique_ptr<std::barrier<>> generator_init_barrier;
+
     std::mutex mutex; // for writing to stdout
 
     std::mutex connection_mutex;

@al13n321

Copy link
Copy Markdown
Contributor Author

Adding this fix to #101801

zlareb1 added a commit to zlareb1/ClickHouse that referenced this pull request May 6, 2026
Example 2 in `SKILL.md` walked through "What changed in Keeper
between 2026-04-01 and 2026-05-01?" and parenthetically said
"none if 2026-04-01 → 2026-05-01; both bench changes were
earlier". That was wrong — both bench-harness confounds documented
in `references/known_confounds.md` (and elsewhere in `SKILL.md`)
land **inside** the example window:

- `ClickHouse#100670` "keeper-bench: go faster" — `2026-04-04`
- `ClickHouse#101801` "keeper-bench: more features" — `2026-04-11`

A user trusting the parenthetical would skip confound handling
exactly when both confounds matter. The next line of the example
already says to "always include the bench-harness confound notes
from known_confounds.md if any of those PR dates fall in the
window", so the parenthetical also self-contradicted.

Replace the false claim with the correct list. The example now
spells out both in-window confounds and what they affect.

Addresses review comment
ClickHouse#104118 (comment).
raimannma pushed a commit to raimannma/ClickHouse that referenced this pull request May 7, 2026
Captures the workflow used to validate Keeper PRs against the keeper-stress
Grafana dashboard (sourced from play.clickhouse.com / keeper_stress_tests).
Without this skill, every Keeper-stress validation question re-derives
methodology, data sources, and known confounds from scratch.

The skill bundles:
  - 6 SQL queries for the staging tables (bench / prom rates / prom gauges /
    mntr / container / pr_branches), with a {{TS_FILTER}} placeholder for
    arbitrary date windows
  - 7 Python scripts that join the staging files into per-PR + per-nightly
    delta tables, cumulative window-vs-window gains, and PR-branch isolation
  - rebuild.sh orchestrator that fetches data and runs the pipeline end-to-end
  - 4 reference docs (methodology, known_confounds, metric_glossary,
    slack_templates) carrying the hard-earned lessons:
      * KeeperApproximateDataSize is the right Keeper memory metric, NOT
        container_memory_bytes (cgroup includes page cache)
      * ClickHouse#100670 keeper-bench:go-faster (bench harness PR, not Keeper) caused
        the 2026-04-04 step in cgroup memory and bench-counted error rates
      * ClickHouse#101801 keeper-bench:more-features caused the 2026-04-11 rocks-side
        write-multi memory step
      * Per-PR effects below ±5 % rps are below the dataset's noise floor
        (typos PR ClickHouse#102739 measures at -5 % via PR-branch isolation)
      * p95_cpu_cores is the right CPU metric, not max_cpu_cores
        (which has counter discontinuities)
  - 4 sample outputs (PERFORMANCE_GAINS.md, PR_PERF_TABLE.md, PR_PROGRESS.md,
    INDEX.md) showing the expected deliverable formats

Triggers on terms like "keeper stress", "keeper PR", "keeper p99", "keeper
memory", "keeper validation", or any mention of the keeper-stress Grafana
dashboard.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants