Skip to content

Count only active replicas when distributing Kafka partition locks in StorageKafka2 - #120111

Merged
alexey-milovidov merged 31 commits into
ClickHouse:masterfrom
JingYanchao:johnjing/add-kafka-balance-consumption
Sep 23, 2026
Merged

alexey-milovidov merged 31 commits into
ClickHouse:masterfrom
JingYanchao:johnjing/add-kafka-balance-consumption

Conversation

@JingYanchao

@JingYanchao JingYanchao commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Bug Fix

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

StorageKafka2 now counts only live replicas when distributing partition locks, so a replica that lost its Keeper session no longer leaves some partitions unconsumed.

Description

StorageKafka2 (the Keeper-based Kafka engine) splits partition locks across replicas by dividing the partition count by the number of replicas. It counted every znode under replicas, but those are persistent and outlive a dead replica. After a replica lost its Keeper session, its znode remained, so survivors kept dividing the quota by a count that included dead replicas, and some partitions were never locked or consumed.

The count now comes from the ephemeral is_active node, so only live replicas are counted.


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

Version info

  • Merged into: 26.10.1.551-master (included in 26.10 and later)

@clickhouse-gh clickhouse-gh Bot added the comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). label Sep 15, 2026
@JingYanchao

Copy link
Copy Markdown
Contributor Author

Hi @antaljanosbenjamin, would you mind taking a look at this one when you have a moment? It's a small improve in StorageKafka2: partition locks were distributed by counting all replicas znodes, but since those are persistent they outlive a dead replica, so a replica that lost its Keeper session would still be counted and some partitions could stop being consumed. The count now comes from the ephemeral is_active node instead. Thanks!

@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 16, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 19, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c907f34]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 4/6) FAIL Performance dashboard
and_compare_chain_derived #2 FAIL dashboard
polymorphic_parts_s #0 unstable query history
timeseries_to_grid_scalar_add #2 unstable query history

AI Review

Summary

This PR changes StorageKafka2 to count only replicas with an is_active node when distributing partition locks, and it adds focused integration coverage for both the plain and shard-affinity paths. I did not find a correctness, safety, or coverage issue in the current head: the remaining code matches the stated bug fix, and the tests now make the stale-replica case visible before the first lock assignment on both paths.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit c907f34.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +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-improvement Pull request with some product improvements label Sep 19, 2026
alexey-milovidov and others added 3 commits September 19, 2026 18:02
…ment

The previous version of `test_inactive_replica_not_counted` created the
dead replica znode only after `r1` had already acquired all four
permanent locks. `prepareToPoll` keeps an existing assignment for
`LOCKS_REFRESH_POLLS` polls, so the pre-fix code could consume the whole
test workload without ever re-running `getActiveReplicasInfo`, and the
test passed without exercising the broken path.

Now the materialized view is attached only after the ghost replica
exists, so the very first lock assignment has to decide whether to count
a replica without an `is_active` node. Without the fix the node quota
would be `num_partitions / 2`, so `r1` could never own the whole lock
set.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov and others added 4 commits September 19, 2026 23:22
…ghost replica

The bot review pointed out that `getActiveReplicasInfo` now has a distinct
`shard_count > 0` branch, but the new regression only exercised
`shard_count == 0`. Add `test_inactive_replica_not_counted_with_shard_affinity`:
a same-shard replica znode without `is_active` (plus a live replica of another
shard) is created before the first lock assignment, and the live replica must
still own every partition of its own shard.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The keeper client rejects `create <path> ''` with `Syntax error at position 0`;
only the existence of `is_active` matters, so write a placeholder value.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, the only red on this PR was Build profile diff (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120111&sha=62464fe8c82f18d233a4caeacbd68962a4be2ff2&name_0=PR&name_1=Build%20profile%20diff) failing with CI logs cluster query failed, which is unrelated to this change and is tracked by #120462 with the fix in flight in #121048. I merged master (branch was 345 commits behind) and pushed 397767330675 to re-run CI.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default and removed pr-improvement Pull request with some product improvements labels Sep 20, 2026
… ones

`getActiveReplicasInfo` clamped the active replica count to 1 when the
`is_active` probe found no live replica at all. As pointed out in review,
that count can only be zero if our own registration is gone from Keeper:
`StorageKafka2::activate` creates `replicas/<name>/is_active` before the
reader tasks are started and `partialShutdown` only removes it after they
have been stopped, and `prepareToPoll` returns `KeeperSessionEnded` before
reaching here when the session is expired.

Defaulting to 1 made this replica keep claiming a full quota of partition
locks while every peer left it out of its own quota, which hid the broken
Keeper state instead of surfacing it. Throw `ABORTED` instead - the same
"replica is not active" outcome that `StorageKafka2::assertActive` produces
- so the failure is logged by the streaming task and the periodic activation
check can re-register the replica.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit c907f341b2199a8ac19112478e11ac5865c64422 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, the only red on this PR is 05227_storage_settings_unknown_name, which fails 100% of runs in Stateless tests (amd_debug, parallel) and Stateless tests (arm_binary, parallel) and is unrelated to this Kafka change:

It looks like it is already being handled by #121163 (Stop 05227_storage_settings_unknown_name pinning where a SETTINGS reset is stored), with #121144 in the same area. Both are still open, so the fix is not on master yet and merging master here would not clear the red. Could you confirm #121163 is the right fix and land it? I will re-merge master here once it is in.

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed: #121163 is the right fix, and #121144 (the revert of #118423) is not needed for this red.

The test is mine (#120898). Three of its expected lines pinned, through a full SHOW CREATE TABLE echo, where an accepted name = DEFAULT query-setting reset is stored. #118423 moved that deliberately in df3cad127e7e (InterpreterSetQuery::applySettingsFromQuery now applies such a reset to the query context and erases it from the clause), and that placement already has its own test travelling with it, 05099_create_database_with_inline_disk, so the stale expectation is mine. #121163 touches only those three read-backs, keeps every CREATE statement and every serverError UNKNOWN_SETTING arm unchanged, and is green both on master and against a tree with df3cad127e7e reverted, so it clears the red either way.

#121163 finished its CI green: 05227 is OK in both Stateless tests (amd_debug, parallel) and (arm_binary, parallel), 250/250 across the five flaky-check flavours, zero failing tests in CIDB, and the branch is MERGEABLE/CLEAN with your review already requested there. I cannot merge it myself, so approval is the step left; once it is on master, re-merging master here clears this red.

Comment thread src/Storages/Kafka/StorageKafka2.cpp Resolved
…er session

The payload `StorageKafka2` stores in its `replicas/<self>/is_active` node
(`active_node_identifier`) is readable from Keeper, so another client can
delete the node and re-create it as its own ephemeral node with the same
bytes. Both liveness checks then still took the node for our registration
and the replica kept consuming while the peers counted the foreign client
under its name; once the real session died later, the replica stayed
counted as live and the quota bug this PR fixes came back.

Ownership is now proven by the session, which cannot be replayed:
`KeeperHandlingConsumer::getActiveReplicasInfo` and
`StorageKafka2::isReplicaRegistrationValid` require
`stat.ephemeralOwner == getClientID()` of the shared session on top of the
payload, the same check `ZooKeeperLock::isLocked` uses. `activate` applies
the same rule when it decides whether the node holder may remove the node,
and the re-registration step no longer fast-deletes a same-payload node of a
foreign live session: `StorageKafka2` remembers the session that created its
latest node (`own_is_active_session_id`, kept across `partialShutdown` and
the retries with backoff), so only a leftover of that session or a node of
the current one is removed by payload and everything else is reported as
`REPLICA_IS_ALREADY_ACTIVE`. Before the first registration of the process
the payload is all there is to go by, as for every other replicated storage.

New test `test_replayed_is_active_payload_triggers_reactivation` replaces
our node with a node of a kazoo session carrying our own payload and requires
the locks to be released while the foreign node is left in place, then the
re-registration with a node of our own session once the foreign one ends.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Storages/Kafka/StorageKafka2.cpp Resolved
…ion, never to the path or payload

The reactivation path in `StorageKafka2::activate` validated
`replicas/<self>/is_active` (payload and owner session) and then still
removed it by path or by payload alone: the old `EphemeralNodeHolder`
dropped by `partialShutdown` removes whatever node is at its path, and
`deleteEphemeralNodeIfContentMatches` removes any node whose payload
matches `active_node_identifier`. A node that another Keeper client
created between the check and either removal was therefore deleted and
this replica registered over it, which is exactly the split-brain the
ownership checks are meant to prevent.

Now the old holder is always marked as already removed in the
registration-lost branch, and the node is removed there only when it is
ours and only with `tryRemove(path, version)` of the version that was
validated (`ZBADVERSION` leaves it in place). The leftover removal in
`activate_in_keeper` is version-bound the same way, and a `ZBADVERSION`
there reports `REPLICA_IS_ALREADY_ACTIVE` so the retry with backoff waits
for the foreign node to disappear.

Two pauseable failpoints, `kafka2_activate_pause_before_partial_shutdown`
and `kafka2_activate_pause_before_is_active_removal`, sit right after the
respective checks. The new integration tests pause there, plant a foreign
ephemeral node with the replica's own payload, resume, and require the
planted node to survive with its original owner session while the locks
are released, and the replica to re-register only once the foreign
session is closed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@antaljanosbenjamin antaljanosbenjamin left a comment

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.

I think this is way too complex. Count is_active should be fine, but all the rest seems too complex or I don't understand something.

Handling a non ephemeral is_active is super unnecessary. Please simplify the PR.

@antaljanosbenjamin

Copy link
Copy Markdown
Member

@alexey-milovidov could you please get rid of the changes that you introduced and blew up PR by completely unnecessary complexity? Fixing cases when there is not active replica and when is_active node is created as a permanent one doesn't make sense: they are useful only when some things are went really sideways, probably somebody manually modified keeper. It doesn't worth the extra copmlexity.

@antaljanosbenjamin antaljanosbenjamin self-assigned this Sep 22, 2026
alexey-milovidov and others added 2 commits September 22, 2026 15:20
…e the `releaseLocks` thread-safety comment precise

Per the maintainer's review, a persistent `is_active` node is not a case
worth handling: `KeeperHandlingConsumer::getActiveReplicasInfo` no longer
skips markers with `ephemeralOwner == 0`,
`StorageKafka2::isReplicaRegistrationValid` no longer treats them as a
broken registration (the owner-session check already does not accept
them as ours), and `restoreReplicaRegistration` no longer removes them.
The test `test_persistent_is_active_marker_not_counted` is removed with
the feature.

The comment on `KeeperHandlingConsumer::releaseLocks` now states exactly
which state is protected by `topic_partition_locks_mutex`, which is not,
and from where the method may therefore be called.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks @antaljanosbenjamin. Two things are done in 5962fa5: the handling of a non-ephemeral is_active is gone (the ephemeralOwner == 0 checks in getActiveReplicasInfo and isReplicaRegistrationValid, the removal in restoreReplicaRegistration, and its test), and the thread-safety comment on releaseLocks now says exactly which state is protected by which mutex and from where the method may be called.

On "the rest is too complex": agreed, the PR has grown far beyond the counting change. Everything beyond it was added in response to the automated review, and each layer can be dropped independently. This is the inventory, so you can say which ones to keep and I will strip the rest, tests included (cc @JingYanchao as the author):

  1. Core: count only replicas that have an is_active node when distributing the partition locks (getActiveReplicasInfo).
  2. Own liveness check: when our own is_active is missing, prepareToPoll returns ReplicaNotActive, the consumer releases its locks, and streamToViews schedules activate, whose registration_lost branch re-registers us. Without this, a replica whose node vanished is counted by nobody but keeps its locks forever, because activate short-circuits on is_active && !expired() and never re-creates the node.
  3. Registration repair: re-create the persistent replicas/<self> znode or fix its shard-num data when they were removed or edited from outside (restoreReplicaRegistration).
  4. Ownership of is_active: our node must carry our payload and be owned by our Keeper session (own_is_active_session_id); a foreign or replayed node is never removed (REPLICA_IS_ALREADY_ACTIVE plus backoff instead of deleteEphemeralNodeIfContentMatches, version-bound removals, the two pauseable failpoints and their tests).
  5. Other poll paths: a direct SELECT throws ABORTED and KeeperSessionEnded triggers the reactivation right away instead of waiting for the 60 s tick.

My suggestion would be to keep 1 and 2 and drop 3, 4 and 5. Layer 2 is what makes layer 1 safe to ship; the rest guards against Keeper state edited from outside the server. I will leave the code as it is until you say which layers to remove, since stripping is quick but the choice is yours.

Comment thread src/Storages/Kafka/StorageKafka2.cpp Resolved
The Kafka code owner asked to remove the layers added on top of the
original change, which had grown to cover Keeper state edited from
outside the server. This drops all of them and leaves only the fix in
`KeeperHandlingConsumer::getActiveReplicasInfo`: count a replica for
the partition-lock quota only when its `replicas/<name>/is_active`
node exists, so a dead replica that left its persistent `replicas/<name>`
znode behind no longer takes a share of the partitions.

Removed: the `ReplicaNotActive` poll outcome and the reactivation of
the table when its own `is_active` node is missing, the release of the
partition locks on that path, the repair of the `replicas/<self>` znode
and its shard number, the Keeper-session and payload ownership checks
on `is_active` with the version-bound removals, the two pauseable
failpoints, the `ABORTED` on direct reads, the reactivation on
`KeeperSessionEnded`, and the integration tests for all of the above.
The count is clamped to 1 so a transiently missing own `is_active`
node cannot divide by zero in `updatePermanentLocksLocked`.

The two regression tests for the counting change stay:
`test_inactive_replica_not_counted` and
`test_inactive_replica_not_counted_with_shard_affinity`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Done in 1411f18, @antaljanosbenjamin. Everything beyond the counting change is removed: the ReplicaNotActive poll outcome and the reactivation on a missing own is_active, the lock release on that path, the replicas/<self> znode repair, the session/payload ownership checks with the version-bound removals, the two failpoints, the ABORTED on direct reads, the KeeperSessionEnded reactivation, and all their tests. Kafka2Source.cpp, KeeperHandlingConsumer.h, StorageKafka2.cpp, StorageKafka2.h and FailPoint.cpp are back to master.

What is left is the diff against master of KeeperHandlingConsumer::getActiveReplicasInfo (count only replicas whose is_active node exists, with the same shard-num filter as before, batched tryGet/exists) plus the two regression tests test_inactive_replica_not_counted and test_inactive_replica_not_counted_with_shard_affinity. The count is clamped to 1 only to avoid a division by zero in updatePermanentLocksLocked when our own node is transiently missing. All four tests in test_zookeeper_locks.py pass locally on the new binary.

@alexey-milovidov

alexey-milovidov commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: Performance Comparison (arm_release, master_head, 3/6) - bitmap_cardinality #1 reported slower. This PR only touches KeeperHandlingConsumer::getActiveReplicasInfo in StorageKafka2, and bitmap_cardinality is flagged slower in 13 PRs and unstable in 26 PRs on 2026-09-22 alone (checks table on play), so it is fleet-wide noise. Provide a fix in a separate PR; if it is already covered by #121090 / #121189, link it here.

The AI Review blockers re-ask for the ownership checks and the fail-closed reactivation path; these were removed on purpose at the request of the StorageKafka2 code owner (#120111 (review)) and are not going back in this PR.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. Not attributable to this PR, and it is covered by #121189 (mine, open). #121090 does not cover it on its own, and the reason is specific enough to be worth stating.

What failed the shard. Only the dashboard arm. status is forced to OK in this job ("always green mode") unless the message contains errors, the report's own 1 slower is far under SLOWER_QUERIES_FAIL_THRESHOLD = 10, and master_head mode gates on the dashboard verdict, so that single row is the whole red:

Dashboard slowdown: bitmap_cardinality #1 0.3333 -> 0.4376 (+31.2%), tier [confirmed_regression]
Fail [Performance Comparison (arm_release, master_head, 3/6)]
  | 3 too long, 1 slower, 2 unstable; 1 confirmed regression(s) on the performance dashboard

Why the query was published as slower. This shard judged every query against the bare floors, because the learned per-query thresholds were never fetched:

[2026-09-22 19:29:08] > Start execution for [Select historical data]
[2026-09-22 19:29:18] WARNING: CIDB query failed with exception: HTTPSConnectionPool(host='play.clickhouse.com', port=443): Read timed out. (read timeout=10)
[2026-09-22 19:29:28] WARNING: CIDB query failed with exception: ... Read timed out. (read timeout=10)
[2026-09-22 19:29:38] WARNING: CIDB query failed with exception: ... Read timed out. (read timeout=10)
[2026-09-22 19:29:38] ERROR: Failed to do select query CIDB
[2026-09-22 19:29:38] WARNING: Failed to fetch historical thresholds, will proceed without them
[2026-09-22 19:29:38] Run command: [touch .../ci/tmp/perf_wd/historical-thresholds.tsv]

All 550 client_time rows of all-query-metrics.tsv carry changed_threshold = 0.15 and unstable_threshold = 0.25, the hardcoded floors with nothing contributed by the historical_thresholds join. The row in question:

client_time  left 0.3333  right 0.4376  diff 0.312  stat_threshold 0.312  changed_threshold 0.15  unstable_threshold 0.25

changed_fail is abs(diff) > changed_threshold and abs(diff) >= stat_threshold, so it passes on the floor alone.

What the learned bar would have been. Running GET_HISTORICAL_TRESHOLDS_QUERY for this query over its own window on play: 992 master measurements, quantileExact(0.99)(abs(diff)) * 1.5 = 0.453, and query_display_name matches this shard's byte for byte, so the join would have hit. changed_threshold would have been ceil(greatest(0.15, 0.453), 2) = 0.46, and the observed 0.312 is below it. With the fetch working, the row is not slower at all and the dashboard gate never looks at it.

That is also why the query is spread so widely: its own 99th-percentile abs(diff) on master is about 0.30, just above the 0.15 floor and well under its learned bar. The checks table for 2026-09-22 agrees with your count (13 PRs with bitmap_cardinality slower, 28 unstable); 12 of them are #1, and 5 of those shards actually went red.

Coverage.

  • Perf CI: do not judge a shard on the 0.15/0.25 floors when no learned thresholds were fetched #121189 fixes exactly this. The missing-threshold branch above also writes historical-thresholds-missing.flag; compare.sh then zeroes changed_fail and unstable_fail, writes report/not-judged, and performance_tests.py skips the dashboard gate and reports SKIPPED instead of a verdict computed on floors. It also replaces that timeout=10 with Settings.CI_DB_QUERY_TIMEOUT_SEC (60 s), which is the proximate cause here: every shard I checked lost its thresholds the same way, including shards 1/6 and 4/6 of this same head and a shard from 2026-09-21.
  • Perf CI: fail a master_head shard only when its own report also calls the query slower #121090 alone would not have cleared it. Its gate fails a master_head query only when the shard's own report also published it as slower, and that check passes here precisely because the floors-based judgment did publish it. The two are complementary rather than alternatives.

So no new PR from me. #121189 is the one that clears this red, and it is still open and unreviewed.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 23, 2026
Merged via the queue into ClickHouse:master with commit 8ab8ab5 Sep 23, 2026
175 of 177 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

Closing the loop on the abstention I said I would add: #121189 was closed in favour of #121847, which takes the threshold-fetch timeout fix and the workflow warnings but not the abstention, so a fetch that still fails judges the shard on the bare floors, now with a warning attached.

I measured what that costs before re-raising it, and it is less than when you asked. The only wired perf jobs are master_head, where performance_tests.py discards the report status and gates on the dashboard verdict, so the shard's own slower count decides nothing; the count-based gate exists only in the cumulative release_base mode, which no workflow wires today (its last CIDB rows are from 2026-09-08). Over the last 7 days, 1767 master_head shards published a shard-side slower with no dashboard confirmation and every one passed. With #121090 closed too, nothing reads the shard-side verdict as a gate. So the floors now cost report honesty (an unjudged shard reads as judged) rather than a red, and I am leaving it there unless you want it in.

The query_display_name half you raised on #119196 is on master in #121278.

@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

blocker This issue / pr blocks a new release 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... external Author is not a member of the ClickHouse organization 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.

5 participants