Skip to content

Fix StorageKafka2 per-consumer partition lock quota for kafka_num_consumers>1 - #116843

Merged
antaljanosbenjamin merged 11 commits into
ClickHouse:masterfrom
aparajita31pandey:fix/kafka2-per-consumer-partition-quota
Sep 7, 2026
Merged

antaljanosbenjamin merged 11 commits into
ClickHouse:masterfrom
aparajita31pandey:fix/kafka2-per-consumer-partition-quota

Conversation

@aparajita31pandey

@aparajita31pandey aparajita31pandey commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

Fixed uneven partition distribution in StorageKafka2 when kafka_num_consumers is greater than 1. A node running N consumers could claim N times its fair share of the topic's partitions and hold them indefinitely, leaving other replicas idle.

Description

We ran a 256-partition topic across 16 nodes with kafka_num_consumers = 16. Two or three nodes were doing all the ingestion and the rest were idle. Partition counts per node looked like 106 / 50 / 100 / 0 / 0 / …. Restarting the busy nodes just moved the problem to whichever node came back first.

size_t can_lock_partitions   = std::max<size_t>(topic_partitions_count / active_replica_count, 1);

if (can_lock_partitions == permanent_locks.size())
    return;  // "I already hold my share"

active_replica_count counts nodes, but permanent_locks and early return below it are per consumer. Each consumer on a node can fills up to node's entire quota and the node lands on N * (P / R).
StorageKafka2's Keeper-based partition lock quota is computed per consumer but divided only by the replica count.

can_lock_partitions = 256/16  = 16

Right now, 1 consumer handles 16 partitions.   16 consumers in one replica, 
all 256 partitions are consumed by one replica itself.

Ideal state for max throughput: Distribute across 16 nodes (16 consumers per node) . Each consumer, consuming from 1 partition, so partition ingestion is spread evenly without bottlenecking a single node.

Nothing corrects it afterwards. Permanent locks are released on consumer shutdown not on topology change, so first node up wins and keeps winning. The losers fall through to he temporary-lock path, which hands out at most one partition per round , enough took alive in the logs, nowhere near enough to catch up. That's why this reads as a
throughput problem rather than an obvious failure, and why it survived in production for as long as it did.

This is evaluated per consumer, so each consumer sees itself as satisfied and never releases the surplus. Once a node wins the initial race it keeps those partitions indefinitely.

Example from production

256-partition topic, 16 nodes, kafka_num_consumers = 16:

Before After
Per-consumer quota 256 / 16 = 16 node_quota 16 / 16 consumers = 1
Per-node total 16 × 16 = 256 16 × 1 = 16
Result one node locks the entire topic each node locks its fair share

Observed impact

Metric Before (bug) After (fix)
Nodes actively ingesting 2–3 out of 16 16 out of 16
Cluster throughput ~500K rows/sec ~866K rows/sec
Partition distribution 106, 50, 100, 0, 0, 0, 0, 0, 0, 0… 16, 16, 16, 16, 16, 16, 16, 16…

Proposal

Compute the node's quota first, then split it across the node's consumers, distributing the remainder by consumer index:

const size_t node_quota = std::max<size_t>(topic_partitions_count / active_replica_count, 1);
const size_t can_lock_partitions = node_quota / num_consumers
                                 + (idx < node_quota % num_consumers ? 1 : 0);

Two properties:

  • The max(…, 1) clamp belongs on the node, not the consumer. Clamping per consumer gives a node a floor of N partitions, so whenever P < R × N the monopoly returns. With 64 partitions on the same 16×16 cluster, a per-consumer clamp lets four nodes take the whole topic (16 each against a fair share of 4); clamping node_quota yields 4.
  • The remainder is distributed, not discarded. The per-consumer shares sum to exactly node_quota, so cluster-wide permanent coverage stays R × floor(P/R) — the same as the original single-consumer design. Dividing by R × N instead would strand up to R×N − 1 partitions on the temporary-lock path.

idx is already a member, so each consumer derives its slice with no cross-consumer coordination and the split is stable across rounds.

Behaviour when N = 1

Unchanged : node_quota / 1 == node_quota, node_quota % 1 == 0, and idx == 0, so can_lock_partitions == max(P/R, 1), identical to the previous code. No existing single-consumer test is affected.

Tests

Test Setup Expected
fair_distribution P=12, R=2, N=3 6 locks per replica
small_topic_p_less_than_rn P=4, R=2, N=3 2 per replica (fails without the node-level
remainder_distribution P=7, R=1, N=3 all 7 held; split 3/2/2
single_consumer_unchanged P=6, R=3, N=1 2 per replica
with_partition_affinity P=8, shard_count=2, 2 replicas/shard, N=4 4 per shard, 2 per replica

The affinity case is included because affinity divides P by shard_count while leaving N unchanged, which can push a cluster into the P < R × N .


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

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c49fc43]

Summary: ✅


AI Review

Summary

This PR changes StorageKafka2 to split a replica's permanent partition-lock quota across its local consumers instead of letting each consumer claim the full replica quota. The quota arithmetic in KeeperHandlingConsumer matches the intended steady-state formula, but the new integration tests now pre-register every replica before any consumer starts polling and only assert that every replica eventually gets some work. That leaves the late-joining-replica rebalancing path from the PR description unproven, so I would keep this in review until that regression is covered.

Missing context / blind spots
  • ⚠️ On 2026-09-04 the only visible Praktika report for this PR was Build profile diff; I could not validate a successful integration run for tests/integration/test_storage_kafka/test_multi_consumer_quota.py.
Findings

⚠️ Majors

  • [tests/integration/test_storage_kafka/test_multi_consumer_quota.py:310] The updated test strategy no longer exercises the branch that has to release surplus permanent locks after another replica appears. By waiting for /replicas to contain every peer before any materialized view starts, the test only proves the steady-state formula with active_replicas == R on the first poll, not the production case from the PR body where one replica starts first and must later shed locks when active_replica_count increases.
    Suggested fix: keep one focused staggered-start case that starts one replica streaming first, waits until it owns the topic, then attaches the peer and checks that the first replica drops back to its fair node_quota.
Tests
  • ⚠️ Add one focused staggered-start regression that forces a replica to over-claim first and then proves updatePermanentLocksLocked releases the surplus after the peer joins.
Final Verdict

⚠️ Changes requested: the code change looks directionally correct, but the regression described in the PR body still needs focused end-to-end coverage.

LLVM Coverage Report

Measured on commit c49fc43.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 32/32 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 28, 2026
@aparajita31pandey
aparajita31pandey marked this pull request as draft August 28, 2026 10:49
@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c49fc43c6 with master 79fc79271 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

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.

Compile time of recompiled translation units

12 translation units recompiled, 44 s compile time in total, 12 of them have a recent master baseline.

Job report

@aparajita31pandey aparajita31pandey changed the title Fix StorageKafka2 per-consumer partition lock quota to account for `n… Fix StorageKafka2 per-consumer partition lock quota Aug 28, 2026
@aparajita31pandey
aparajita31pandey force-pushed the fix/kafka2-per-consumer-partition-quota branch from c33696c to 883d30c Compare August 28, 2026 16:40
Comment thread src/Storages/Kafka/StorageKafka2.cpp Resolved
@aparajita31pandey aparajita31pandey changed the title Fix StorageKafka2 per-consumer partition lock quota Fix StorageKafka2 per-consumer partition lock quota for kafka_num_consumers>1 Aug 28, 2026
- Make num_consumers const (set at construction, never changes)
- Tighten test bounds to match exact formula expectations (6/6, 2/2, 3/4, 2/2)
- Use parameterized test for all quota cases
Keeper lock znodes include both permanent and temporary locks, making
exact bound assertions unreliable.  Parse the server trace log instead,
which prints the computed permanent-lock quota for each consumer with
all formula inputs (node_quota, active_replicas, num_consumers, idx).
@aparajita31pandey
aparajita31pandey force-pushed the fix/kafka2-per-consumer-partition-quota branch from 4688ed5 to 073637e Compare August 29, 2026 07:27
The log-based assertions check what the quota code *computed*; they never
check what it actually holds. Add wait_for_consumer_assignments(), which
reads per-consumer partition counts from system.kafka_consumers, so a
regression where the quota is computed correctly but not enforced is caught.

- acceptable_consumer_counts added to the matrix: [2,2,2], [0,1,1],
  [1,1,1]/[1,1,2], [2]. The [0,1,1] row is the valuable one -- it proves the
  third consumer correctly idles and no single consumer hoards the replica's
  share, which nothing previously verified.
- Two multisets are accepted where P mod R != 0, because getStat() merges
  permanent and temporary locks, so a consumer may transiently hold the
  floating partition.
- Restore test_multi_consumer_with_partition_affinity, dropped in the
  Keeper->log rewrite. Affinity shrinks P without shrinking N, which is what
  drives a cluster into the P < R*N regime, so it is the case most worth
  covering. kafka_partition_shard_num is a KafkaSettingsString: passing an
  int makes create_settings_string emit it unquoted and CREATE TABLE fails
  with "Code: 170. Bad get: has UInt64, requested String" -- hence str().
- 240s timeout on the assignment poll. Unlike the log assertions this waits
  for the distribution to CONVERGE: a replica registering first sees
  active_replicas=1, takes the whole node_quota, and sheds the surplus only
  on a later refresh round. That exceeded 90s under asan/ubsan -- see the
  9/3-instead-of-6/6 failure in the flaky check on ef41915.
- Fix F541 (f-string without placeholders) reported by the style check.

Verified locally against a branch-built binary: 5 passed in 693.85s.
test_multi_consumer_with_partition_affinity failed 2 of 3 runs in the flaky
check on 5a0a15a:

  Per-consumer assignments for kafka_aff_s1_r1 never matched any of
  [[0, 0, 1, 1]]; last seen: [0,0,1,2]

[0,0,1,2] sums to 3 against a node_quota of 2. The extra partition is a
temporary lock: getStat() merges permanent_locks and tmp_locks into one
assignments list, and while the replica that registered first sheds its
surplus (it saw active_replicas=1 and took node_quota=4), the partitions it
releases are briefly picked up as temporary locks by its shard peer.

The exact multiset was the wrong assertion for this test. The parametrized
cases already prove enforcement -- they now pass 12/12 -- and the log
assertions above already prove the whole affinity contract: node_quota=2
(P_shard 4 / R_shard 2), active_replicas=2 (only same-shard replicas
counted), and the per-consumer split summing to node_quota.

What is left to check is affinity's own contract, which no other test covers:
a replica must only ever hold partitions of its own shard. That holds from the
moment a partition is locked, because the affinity filter runs before locking,
so it does not depend on catching a converged instant.

Verified locally against a branch-built binary: 1 passed in 124.81s, down from
~4 minutes since it no longer polls for a converged count.
test_permanent_lock_quota[even] failed on arm_binary (distributed plan, 3/4):

  Per-consumer assignments for kafka_quota_12p_2r_3c_r2 never matched any of
  [[2, 2, 2]]; last seen: [1,2,3]

[1,2,3] sums to 6, so the replica held exactly its node_quota -- only the split
across its three consumers had not settled. One consumer held 2 permanent locks
plus a temporary one; its starved sibling could not advance because all 12
partitions were locked cluster-wide, so it had to wait for the temporary lock to
be released on a later refresh round. That is a per-round race which does not
reliably resolve inside the timeout.

The exact multiset asserted a stronger property than the code guarantees. The
node-level contract this PR fixes was satisfied throughout. Replace it with the
bounds that hold immediately rather than only at a quiet instant:

  node_quota <= sum(counts) <= node_quota + P % R   node holds its own share
  max(counts) <= ceil(node_quota / N) + 1           no consumer exceeds its share
                                                    plus one temporary lock
  count(c > 0) >= min(N, node_quota)                the share is spread, which is
                                                    what rules out "one consumer
                                                    keeps all of the replica's
                                                    assignments"

The third bound matters: `max` alone cannot reject a hoarding [0,0,2] when
node_quota is 2 and the ceiling is 1, because that is indistinguishable from a
legitimate temporary lock. Requiring the share to be spread rejects it.

Verified offline that the bounds accept the ideal split and the observed [1,2,3],
and reject a hoarding [0,0,node_quota] on every multi-consumer row. Per-consumer
quotas are still asserted exactly from the trace log, so computation remains
covered; this check now covers enforcement only.

Verified locally against a branch-built binary: 5 passed in 517.94s.
@aparajita31pandey
aparajita31pandey marked this pull request as ready for review August 30, 2026 04:26
@aparajita31pandey
aparajita31pandey marked this pull request as draft August 30, 2026 04:58
@aparajita31pandey
aparajita31pandey marked this pull request as ready for review August 31, 2026 04:35
@aparajita31pandey

aparajita31pandey commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov @antaljanosbenjamin Can you help review this PR please ?

@antaljanosbenjamin antaljanosbenjamin self-assigned this Sep 3, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). label Sep 4, 2026
@aparajita31pandey
aparajita31pandey force-pushed the fix/kafka2-per-consumer-partition-quota branch from 7472b51 to a8f4869 Compare September 4, 2026 17:56
@aparajita31pandey
aparajita31pandey force-pushed the fix/kafka2-per-consumer-partition-quota branch from a8f4869 to c49fc43 Compare September 4, 2026 17:58

# End-to-end: the quota was enforced, not just computed. Every replica gets work
# and the topic is fully claimed -- on master one replica takes everything.
held = wait_for_partitions_claimed(

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 two-phase setup removes the exact rebalance path the PR description says is broken. Because every replica is registered before any consumer polls, this test never drives updatePermanentLocksLocked() from “one replica already owns too many permanent locks” to can_lock_partitions < permanent_locks.size() after a late peer appears. The wait_for_partitions_claimed check then only proves that every replica eventually gets some work, not that an early replica actually sheds its surplus down to node_quota.

Please keep one focused staggered-start regression here: start one replica streaming first, wait until it hoards the topic, then attach the peer and verify that the first replica releases locks once active_replica_count grows.

@antaljanosbenjamin
antaljanosbenjamin added this pull request to the merge queue Sep 7, 2026
Merged via the queue into ClickHouse:master with commit 03d782a Sep 7, 2026
175 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
aparajita31pandey added a commit to aparajita31pandey/ClickHouse that referenced this pull request Sep 17, 2026
The test failed at ~0.06% in CI with "never acquired any partition within
240s" (ClickHouse#119632). Every genuine failure was this test alone in an otherwise
healthy job, on sanitizer builds.

The assertion was a liveness property, not an invariant. A replica can
legitimately hold nothing for a long time: the fairness guard in
lockTemporaryLocksLocked only restrains a consumer that already holds a
temporary lock (tmp_locks_quota > 0 && has_replica_without_locks), so a
sibling consumer on the same replica holding none skips the guard and
re-takes the partition its peer just released. With 8 partitions, shard
count 2 and 4 consumers, one replica could hold its whole shard (2
permanent + 2 temporary locks against a shard of 4) and keep it, leaving
the peer empty for the length of the test.

Drop both lower bounds -- the "holds no partitions" assert and the
pytest.fail in wait_for_shard_partitions -- and assert an upper bound
instead: a replica holds at most node_quota permanent locks plus one
temporary lock per consumer.

For that ceiling to be meaningful it has to sit below the shard size, so
the topic grows to 16 partitions with 2 consumers: node_quota becomes 4
and the ceiling 4 + 2 = 6 against a shard of 8. Before ClickHouse#116843 a single
replica takes all 8 and trips it. At the old sizing the ceiling would have
been 6 against a shard of 4, which no distribution can exceed.

What remains asserted -- shard membership, the ceiling, and the quota
values read from the log -- holds at any instant, so a slow build cannot
fail the test.
@clickhouse-gh clickhouse-gh Bot added comp-kafka Kafka table engine: consumers and producers on librdkafka, the Kafka2 engine that keeps offsets i... and removed comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-kafka Kafka table engine: consumers and producers on librdkafka, the Kafka2 engine that keeps offsets i... pr-bugfix Pull request with bugfix, not backported by default 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