Skip to content

keeper-bench: dynamic path sets and don't OOM on many nodes - #111155

Merged
al13n321 merged 20 commits into
masterfrom
kbgen
Sep 15, 2026
Merged

al13n321 merged 20 commits into
masterfrom
kbgen

Conversation

@al13n321

@al13n321 al13n321 commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

This PR is stacked on top of #108583

  • Previously keeper-bench would use lots of memory when there are many nodes, because the list of paths was stored many times in memory (for each generator x thread, and with a lot of overhead in the setup tree). Now paths are stored once, and bench memory usage is lower than server memory usage.
  • Previously you couldn't do anything with nodes created by create generators at runtime. Things like children_of and tagged used an immutable list of paths taken at startup, so you couldn't e.g. do get or set on nodes produced by create during the bench. Now you can: add tag to the create and use tagged on other generators to refer to the nodes. keeper-bench will keep track of the set of existing paths for the tag. The same tag may appear in setup and in creates.
  • create's remove_factor seems like a wrong approach: the number of nodes would continuously grow or drift during the test, so results from test runs wouldn't be meaningfully comparable because they had different number of nodes. Added keep_count - use it instead of remove_factor to keep number of nodes (with the given tag) approximately constant (doing Remove more often if there are too many and doing Create more often if there are too few). Use keep_count: auto to keep the number of nodes about the same as on startup (after setup).
  • create can now do RemoveRecursive (use remove_recursive flag in config). So you can have a create generator for tag A with remove_recursive and another create generator for children of tag A (with no output tag), to do nontrivial RemoveRecursive requests continuously.

The first 6 commits can be reviewed separately one by one.


Workflow [PR]
Sync PR [sync-upstream/pr/111155]

Version info

  • Merged into: 26.9.1.1521 (included in 26.9 and later)

al13n321 and others added 8 commits July 18, 2026 19:43
- `GeneratedRunner` (generated mode) and `LogRunner` (replay and
  setup-nodes-collection modes) replace the two-mode `Runner`.
- `--input-request-log` now always selects replay mode, taking precedence
  over the config's `generator` section instead of being silently ignored.
- `BenchmarkContext` is renamed to `NodesSetup` and moved to its own file;
  the setup tree walk now emits `Create` requests into a callback, which
  `StorageRunner` reuses instead of a hand-rolled tree walk.
- Shared helpers are extracted to `RunnerCommon`: `getOption` (command
  line > config > default), `ConnectionFactory`, `BenchmarkOutput`.
  `StorageRunner` uses `getOption` too.
- Generators are initialized sequentially up front in `GeneratedRunner`,
  removing `generator_init_barrier`.
- SIGINT is now blocked process-wide at program entry, so Ctrl+C is always
  seen by the `InterruptListener` polls instead of sometimes terminating
  the process via a global-thread-pool thread that didn't block it.
  `StorageRunner` and `LogRunner` now also shut down gracefully on SIGINT
  and print the final report.

Co-Authored-By: Claude Fable 5 <[email protected]>
Previously, when a write multi failed, all sub-request callbacks received
nullptr, losing the per-op error codes. Now each sub-op callback receives
its own sub-response. Sub-ops of a failed transaction whose own check
passed (reported as `ZOK` even though nothing was applied) receive a
synthesized response with `ZRUNTIMEINCONSISTENCY` so they are not taken
for applied ones.

This is preparation for dynamic path sets, where Create/Remove callbacks
need to distinguish "node is really gone" (`ZNONODE`) from "operation was
not applied" to keep the set contents correct.

Co-Authored-By: Claude Fable 5 <[email protected]>
Generators used to be constructed per worker thread, each re-parsing the
config and building its own copy of every path list (including the results
of `children_of` listings), multiplying memory usage by the concurrency.
Now a single `Generator` is built once on the main thread and shared; the
only per-call mutable state is the rng, passed in via `GenerateContext`
(`{rng, thread_idx}`) by each thread.

This also deletes the `setSeed`/`setSeedImpl` cascade with its per-component
seed offsets: with a fixed `generator.seed`, each thread's rng is simply
seeded with `seed + thread_idx`. `children_of` parents are now listed once
instead of once per thread, and the workload description is printed once.

Co-Authored-By: Claude Fable 5 <[email protected]>
…red sets

Each `PathGetter` now draws from exactly one `PathSet` — a literal path
list, one `tagged` reference, or one `children_of` reference (mixing
sources in one `path` is no longer supported). Sets are registered in
`NodesSetup` while parsing the setup and generator configs, so generators
referencing the same tag or parent share one in-memory copy of the paths
instead of each generator merging its own copy.

The initialization sequence is reordered accordingly: parse generators
(registering sets), create the setup tree (populating tag sets on the
fly), resolve `children_of` sets by listing each distinct parent once,
then validate. Tag sets nobody reads are not populated at all.

The setup tree now stores `repeat` counts unexpanded, mirroring the
config; instances are expanded during the creation traversal (root names
are recorded for cleanup). For repeated subtrees this removes the
per-instance child pointers from memory.

Co-Authored-By: Claude Fable 5 <[email protected]>
Path sets that a `create` generator outputs to are now dynamic: created
nodes are added to the set on success and `remove_factor` removes take
nodes out of it (before sending; put back unless the outcome shows the
node is gone). The output set is the explicit `tag` from the create
generator's config, the `children_of` set of its fixed parent, or an
anonymous set when only `remove_factor` needs one; it is only populated
if some generator reads it. This allows pointing e.g. a `set` generator
at nodes produced by a `create` generator, and replaces the old
per-generator `paths_created` bookkeeping (along with the name
uniqueness enforcement, which never worked across threads anyway).

Dynamic sets are sharded by worker thread, so each thread reads and
updates only its own shard (shard mutexes still guard against response
callbacks running on client/commit threads). Since a dynamic set may lag
behind the real state, requests drawing paths from one report `ZNONODE`/
`ZNODEEXISTS` results as a separate `ignored_errors` counter instead of
failing, even without `continue_on_errors`. Generators whose input set
is currently empty decline, and another generator is picked instead.

Co-Authored-By: Claude Fable 5 <[email protected]>
`keep_count: <n>` (or `auto`) on a create generator keeps its output path
set at a roughly constant size, so the dataset doesn't drift over a long
benchmark: each operation chooses between Create and Remove with a
probability based on the current shard size — 0.5 at the target,
approaching 0/1 as the size deviates (logistic curve, 5% of the target as
the scale). The last path in a shard is never removed, so a set can only
be empty if it started empty. `auto` snapshots the size at the end of
setup as the target. Mutually exclusive with `remove_factor`.

Sizes and targets of dynamic path sets are now printed with each periodic
report in both the generated and storage modes.

Co-Authored-By: Claude Fable 5 <[email protected]>
Two forms:
- `remove_recursive: true` (with `remove_nodes_limit`) on a create
  generator makes its `remove_factor`/`keep_count` removes use
  `RemoveRecursive` requests, removing whole subtrees. Needed when other
  generators create children under the removable nodes, where a plain
  `Remove` would fail with `ZNOTEMPTY`.
- a standalone `remove_recursive` request generator that recursively
  removes random nodes drawn from a path set (making it dynamic). Only
  the removed root is taken out of the set; descendants tracked in other
  sets go stale and surface as ignored errors. Since it competes with
  creates purely by weights, the node count random-walks; `keep_count`
  with `remove_recursive: true` is the count-stable alternative.

Example workload this enables: one create maintains ~N tagged nodes
(removing recursively), a second create makes children under the tagged
nodes, gets read them — total node count stays stable in steady state.

Co-Authored-By: Claude Fable 5 <[email protected]>
Base automatically changed from kref to master July 20, 2026 23:57
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1cb4b19]

Summary: ✅


AI Review

Summary

This PR splits keeper-bench into generated, replay, and storage runners, adds shared dynamic PathSets, keep_count, and recursive removes, and re-enables lsmt in keeper stress PR jobs. The current head still breaks several parts of that contract: dynamic path sets are misclassified in mixed-source and multi cases, replay and storage mode still miss new request semantics, and generated mode now aborts the whole process on the default stop-on-first-error path.

Findings

❌ Blockers

  • [programs/keeper-bench/GeneratedRunner.cpp:131-135, 182-185, 329-338] continue_on_error = false is supposed to stop cleanly on the first Keeper exception, but handle_request_exception now rethrows into a wrapper that immediately calls std::abort(). A normal ZNONODE or ZBADVERSION therefore skips the final report and destructor cleanup of the setup roots.
  • [programs/keeper-bench/NodesSetup.cpp:465-470] keep_count is a total target, but it is truncated to max(1, total_target / num_shards) per shard. Small targets or non-multiples of concurrency silently change the requested dataset size, and keep_count: auto on an empty set becomes a target of concurrency live nodes.
  • [programs/keeper-bench/Generator.cpp:440-448] explicit tag and children_of conflict detection still only works for a single literal parent. A create over several fixed parents, or any non-literal source that expands to fixed parents, can still output to a tag while another generator reads children_of one of those parents, so the created nodes are tracked in one set and read from a stale one.
  • [programs/keeper-bench/Generator.cpp:459-469, 511-517] a shared output PathSet still accepts mixed producer policies. One create can set keep_count while another writer to the same set has no balancing or uses remove_factor, so the set-level target printed in stats is not actually enforced by every producer.
  • [programs/keeper-bench/Generator.cpp:207-229] PathGetter::getPath treats a nonzero relaxed approximateSize as proof that samplePath will succeed. If a dynamic shard is emptied between the size read and the lock in samplePath, the generator declines even though other sets in the same union still have candidates.
  • [programs/keeper-bench/Generator.cpp:562-575, 607-616, 641-655, 679-695] dynamic-path error classification is still based on PathGetter::isDynamic(), which only says that some source in the union is dynamic. Mixed static and dynamic path unions therefore hide fixed-path ZNONODE or ZNODEEXISTS failures, and create also ignores ZNODEEXISTS even when it comes from a child-name collision rather than a stale parent set.
  • [programs/keeper-bench/Generator.cpp:721-732, 754-805; programs/keeper-bench/GeneratedRunner.cpp:234-245] multi still collapses per-subrequest ignore_missing_nodes into one bool and lets the top-level MultiResponse::error decide whether the whole transaction was an ignored dynamic-set miss. Once one nested request is dynamic, fixed-path sibling errors can be hidden as ignored as well.
  • [programs/keeper-bench/StorageRunner.h:53-61; programs/keeper-bench/StorageRunner.cpp:301-307, 397-408, 467-468] storage mode still drops ignore_missing_nodes when it enqueues the request and never classifies response->error afterward. Dynamic-set ZNONODE or ZNODEEXISTS are not counted as ignored_errors, and ordinary Keeper errors are still invisible in --storage mode.
  • [programs/keeper-bench/LogRunner.cpp:263-387, 448-525] replay and setup-node collection still do not understand OpNum::RemoveRecursive. Any request log containing the new recursive removes still fails with Unsupported operation, and --setup-nodes-snapshot-path cannot infer initial state for those workloads.

💡 Nits

  • [programs/keeper-bench/README.md:343-363] the create section still documents the old remove_factor-only behavior. It omits keep_count, remove_recursive, and remove_nodes_limit, and it now says the default name_length is 5 even though Generator.cpp defaults it to 10.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: fix the still-open dynamic-path-set correctness bugs, add RemoveRecursive handling to replay and setup-node collection, restore graceful stop-on-first-error behavior in GeneratedRunner, and update the README create section to match the shipped options.

LLVM Coverage Report

Measured on commit 1cb4b19.

Metric Baseline Current Δ
Lines 89.10% 89.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.50% +0.00%

Changed lines: Changed C/C++ lines covered: 621/1543 (40.25%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 1, 2026
{
size_t num_shards = set->shards.size();
size_t total_target = *set->keep_count == 0 ? set->totalSize() : *set->keep_count;
set->target_count_per_shard = std::max<size_t>(1, total_target / num_shards);

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.

keep_count is a total target, but this turns it into max(1, total_target / num_shards) per shard. With concurrency = 32, keep_count: 1 (or keep_count: auto on an initially empty set) becomes a target of 32 live nodes, and any non-multiple of concurrency is silently rounded down. That breaks the new contract that keep_count keeps the set "about the same as on startup". This needs a global target, or at least validation that the requested total can be represented by the sharded algorithm.

Comment thread programs/keeper-bench/Generator.cpp Outdated
/// Resolve the set that tracks the created nodes: an explicit output `tag`,
/// the `children_of` set of a fixed parent, or an anonymous set if the
/// removes need one.
auto fixed_parent = parent_path.pathSet()->singleStagedPath();

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.

singleStagedPath only covers the one-parent literal case. If a create uses path: ["/a", "/b"] together with tag: kids, another generator can still read children_of: "/a" and validatePathSets never rejects it. New children under /a then go only into the tag-backed dynamic set while the children_of set stays frozen at startup, which recreates the stale-path bug this PR is trying to remove. We need to register/check conflicts for every fixed parent in the source set, or reject tag + multi-parent sources outright.


return request_from_log;
}
default:

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.

The PR adds remove_recursive to generated workloads, but replay still has no Coordination::OpNum::RemoveRecursive branch here. Any request log that contains those operations now falls through to Unsupported operation ..., so the new workload cannot be replayed or fed into --setup-nodes-snapshot-path. Please deserialize RemoveRecursive here too, and extend SetupNodeCollector once that request can reach replay mode.

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 0/1529 (0.00%) · Uncovered code

Full report · Diff report

@al13n321
al13n321 enabled auto-merge September 3, 2026 17:50
@al13n321
al13n321 disabled auto-merge September 3, 2026 17:50
@clickhouse-gh clickhouse-gh Bot added the comp-keeper ClickHouse Keeper (Raft-based coordination layer; ZooKeeper replacement) and ZooKeeper client lib... label Sep 4, 2026
al13n321 and others added 4 commits September 4, 2026 14:12
A `PathGetter` can now reference several `tagged` sets; paths are drawn
uniformly from their union by first picking a set with probability
proportional to its size and then a path within it. Sizes are read from a
new per-shard atomic `cached_size` (relaxed loads) instead of locking the
shard mutex, so the weights can lag slightly behind concurrent updates of
dynamic sets, which is acceptable.

`PathGetter::takePath` was unused and is removed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Literal paths, `children_of` and `tagged` entries can be combined freely in
one `path` section, as on master. Sets are weighted by an estimate of their
total size: the calling thread's shard size scaled by the number of shards,
so a per-thread sharded dynamic set is not underweighted against an
unsharded one.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@al13n321
al13n321 enabled auto-merge September 4, 2026 22:21
if (output_set->keep_count && *output_set->keep_count != keep_count)
throw DB::Exception(
DB::ErrorCodes::BAD_ARGUMENTS, "Multiple create generators set different keep_count for {} (key '{}')", output_set->name, key);
output_set->keep_count = keep_count;

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.

This only rejects conflicting keep_count values. Another create can still write the same output_set with no balancing or with remove_factor, and at runtime only generators whose own config had keep_count consult the target (generateImpl looks at the member, not output_set->keep_count). The set-level target reported for the shared tag / children_of set then stops being enforceable. Please either reject mixed producer policies for one PathSet, or drive every producer from a set-level balance policy.

return;
ops.push_back(std::move(request_with_callbacks.request));
inner_callbacks.push_back(std::move(request_with_callbacks.callback));
ignore_missing_nodes |= request_with_callbacks.ignore_missing_nodes;

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.

ignore_missing_nodes is a per-subrequest property, but multi collapses it to one bool here. Once any nested request draws from a dynamic PathSet, GeneratedRunner treats a top-level ZNONODE/ZNODEEXISTS as an ignored dynamic-set miss for the whole transaction, so the same errors from fixed-path siblings get hidden as well. Please keep this flag per subrequest and classify ignored errors from the actual subresponses instead of the aggregate MultiResponse::error.

@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1cb4b19dc with master 2615840f7 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 8d780d797; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

8 object files changed (+1.03 MiB total), 5 added.

Object file Master PR Δ
programs/keeper-bench/CMakeFiles/clickhouse-keeper-bench-lib.dir/LogRunner.cpp.o new 429.78 KiB +429.78 KiB
programs/keeper-bench/CMakeFiles/clickhouse-keeper-bench-lib.dir/NodesSetup.cpp.o new 278.89 KiB +278.89 KiB
programs/keeper-bench/CMakeFiles/clickhouse-keeper-bench-lib.dir/GeneratedRunner.cpp.o new 221.44 KiB +221.44 KiB
programs/keeper-bench/CMakeFiles/clickhouse-keeper-bench-lib.dir/RunnerCommon.cpp.o new 98.83 KiB +98.83 KiB
programs/keeper-bench/CMakeFiles/clickhouse-keeper-bench-lib.dir/PathSet.cpp.o new 45.27 KiB +45.27 KiB
programs/keeper-bench/CMakeFiles/clickhouse-keeper-bench-lib.dir/Generator.cpp.o 338.40 KiB 316.80 KiB -21.61 KiB (-6.38%)
programs/keeper-bench/CMakeFiles/clickhouse-keeper-bench-lib.dir/KeeperBench.cpp.o 243.68 KiB 260.88 KiB +17.20 KiB (+7.06%)

717 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

15 translation units recompiled, 49 s compile time in total, 10 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper-bench/LogRunner.cpp: 8.3 s
  • programs/keeper-bench/GeneratedRunner.cpp: 5.5 s
  • programs/keeper-bench/NodesSetup.cpp: 5.3 s

Job report


auto callback = [&, candidate = std::move(node_candidate)](const Coordination::Response * response) mutable
ZooKeeperRequestWithCallbacks result{.request = request};
result.ignore_missing_nodes = parent_path.isDynamic();

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.

parent_path.isDynamic() only tells us that some source in the PathGetter is dynamic. After path started allowing mixed literal/children_of/tagged sources again, that is too coarse for error classification: a create that actually picked a fixed parent from the literal half of the union will still ignore ZNONODE, and any create under a dynamic parent will also ignore ZNODEEXISTS even though that error is about the generated child-name collision, not stale parent membership. The same path.isDynamic() pattern below does the same thing for set/get/list. Please return the chosen-set metadata from PathGetter::getPath and decide ignored errors from that specific source; for create, this should probably only forgive ZNONODE.


path_picker = std::uniform_int_distribution<size_t>(0, paths.size() - 1);
initialized = true;
return chosen->samplePath(ctx.rng, ctx.thread_idx);

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.

getPath assumes a nonzero approximateSize guarantees that samplePath will succeed, but dynamic sets only expose that size through a relaxed cached_size load. If path is a union of a dynamic set and another non-empty source, a remove callback can empty the chosen dynamic shard after the size read and before samplePath locks it. In that case this returns nullopt even though the union still has candidates, so the generator can decline or even trip the "all generators declined" exception while valid paths remain. Please retry with the remaining sets when samplePath comes back empty, or choose only from sets proven non-empty under the relevant lock.

try
{
request_with_callbacks = generator.generate();
request_with_callbacks = generator->generate(ctx);

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.

After switching storage mode to generator->generate(ctx), this runner now receives ignore_missing_nodes for dynamic-set requests but never carries it forward. generatorThread enqueues only the request and callback, and drain_reads / commitThread later count every Keeper response as a committed op without looking at response->error. A ZNONODE / ZNODEEXISTS from a dynamic set in --storage mode is therefore silently treated as success instead of an ignored_error, and fixed-path Keeper errors are still invisible too. Please propagate the flag through QueueItem and classify responses the same way GeneratedRunner does.

catch (...)
{
DB::tryLogCurrentException("Unexpected exception in bench thread");
std::abort();

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.

handle_request_exception intentionally rethrows when continue_on_error is false so the benchmark stops on the first Keeper error. Wrapping thread in a catch-all that immediately calls std::abort() turns that normal stop path into a hard process abort: a single ZNONODE/ZBADVERSION now skips the final report and prevents GeneratedRunner's destructor from cleaning the setup roots.

The local ThreadPool already catches job exceptions and rethrows them from wait(), so this wrapper should not abort on ordinary request failures.

create:
path: "/bench/creates" # PathGetter
path: "/bench/creates" # PathGetter (parent for created nodes)
name_length: 10 # IntegerGetter, default: 5

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.

This create section still describes the old remove_factor-only behavior. The PR adds keep_count, remove_recursive, and remove_nodes_limit, but none of them are documented here, and the inline default for name_length is now wrong: Generator.cpp defaults it to 10, not 5.

Since these knobs change how dynamic PathSets are maintained and are part of the user-facing workload contract, the README should document them in this section and show a minimal example.

@al13n321
al13n321 added this pull request to the merge queue Sep 15, 2026
Merged via the queue into master with commit e52381d Sep 15, 2026
348 of 349 checks passed
@al13n321
al13n321 deleted the kbgen branch September 15, 2026 11:27
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 15, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@al13n321 @antonio2368 — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-keeper ClickHouse Keeper (Raft-based coordination layer; ZooKeeper replacement) and ZooKeeper client lib... 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants