Skip to content

Fix DROP TABLE hang on Kafka tables due to unbounded rd_kafka_assign wait - #101158

Closed
alexey-milovidov wants to merge 33 commits into
masterfrom
fix-kafka-drop-table-hang-rdkafka
Closed

alexey-milovidov wants to merge 33 commits into
masterfrom
fix-kafka-drop-table-hang-rdkafka

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 30, 2026 •

Copy link
Copy Markdown
Member

Fix DROP TABLE hang on Kafka tables when a rebalance is in progress and the broker is temporarily unreachable.

The root cause is inside librdkafka: rd_kafka_assign, called from the rebalance callback during poll_batch, sends an RD_KAFKA_OP_ASSIGN op to the consumer-group background thread and waits with RD_POLL_INFINITE via rd_kafka_op_req → rd_kafka_q_pop. If the cgrp thread is blocked (e.g. waiting for a coordinator while the broker is unreachable after a network interruption), poll_batch never returns — regardless of its own timeout — because the block happens inside a callback dispatched during queue serving. This makes pipeline cancellation impossible, causing DROP TABLE to hang for 600+ seconds until the client times out.

poll_batch(timeout=500ms)
  → rd_kafka_consume_batch_queue()
    → rd_kafka_q_serve_rkmessages()
      → rd_kafka_poll_cb()            // serves rebalance callback
        → Consumer::handle_rebalance()
          → Consumer::assign()
            → rd_kafka_assign()
              → rd_kafka_assign0()
                → rd_kafka_op_req(cgrp_ops, rko, RD_POLL_INFINITE)
                  → rd_kafka_q_pop(recvq, INFINITE)  ← blocks forever

Updates both contrib/librdkafka and contrib/cppkafka:

This was identified as the cause of frequent Kafka integration test failures in CI (cascade failures in test_batch_fast due to test_kafka_consumer_hang timing out).

Same hang stack trace as in the issue closed by #100604, which only addressed the consumer-destructor path; the broader fix here also handles the unbounded wait during normal poll_batch.

Refs:

Existing test coverage: test_kafka_consumer_hang in tests/integration/test_storage_kafka/test_batch_fast.py exercises this exact code path (heartbeat error → REBALANCE_IN_PROGRESS → DROP TABLE).

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 into CHANGELOG.md):

Fix DROP TABLE hang on Kafka tables when a rebalance coincides with broker unavailability, caused by an unbounded wait inside librdkafka's rd_kafka_assign.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

…gn wait

When a Kafka consumer experiences a heartbeat error followed by a
rebalance (e.g. after broker becomes temporarily unreachable),
DROP TABLE can hang indefinitely.  The root cause is inside
librdkafka: rd_kafka_assign(), called from the rebalance callback
during poll_batch(), sends an op to the consumer-group thread and
waits with RD_POLL_INFINITE.  If the cgrp thread is blocked waiting
for the coordinator, poll_batch() never returns, making pipeline
cancellation impossible regardless of the cancel callback.

This updates both contrib/librdkafka and contrib/cppkafka:
- librdkafka: replace RD_POLL_INFINITE with 30s timeout in
  rd_kafka_assign0 (ClickHouse/librdkafka#18)
- cppkafka: catch HandleException from assign/unassign in
  handle_rebalance to prevent throwing from a C callback
  (ClickHouse/cppkafka#7)

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

clickhouse-gh Bot commented Mar 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a428f19]

Summary: ⏳

job_name test_name status info comment
Integration tests (amd_asan_ubsan, targeted) FAIL
test_storage_kafka/test_batch_slow_4.py::test_kafka_consumer_failover[generate_new_create_table_query] FAIL cidb
test_storage_kafka/test_batch_slow_6.py::test_kafka_rebalance[generate_new_create_table_query-{}.*Saved offset] FAIL cidb
Integration tests (amd_llvm_coverage, 2/5) FAIL
test_storage_kafka/test_batch_slow_6.py::test_kafka_rebalance[generate_new_create_table_query-{}.*Saved offset] FAIL cidb
test_storage_kafka/test_batch_slow_4.py::test_kafka_consumer_failover[generate_new_create_table_query] FAIL cidb

AI Review

Summary

This PR updates only contrib/librdkafka and contrib/cppkafka submodule pointers to carry the Kafka DROP TABLE hang fix. The cppkafka bump looks aligned with the intended exception-safety improvement, but the selected librdkafka tip also pulls in two later commits that are already bisected to persistent Kafka integration timeouts on this PR branch, so the current submodule target should not merge as-is.

Findings

❌ Blockers

  • [contrib/librdkafka:1] The bumped pointer ae43f47 includes e6ba87c7 and 61aa9022, which are identified (in PR CI bisect evidence) as the breakpoint for persistent DROP DATABASE ... SYNC timeouts in Kafka tests on this branch.
    • Suggested fix: pin to the last known-good commit containing the bounded wait fix but excluding the regressing pair (for example 54df05ab / merge e610ebfe), or include a librdkafka follow-up that fixes the regression before updating this pointer.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ⚠️ Submodule bump affects Kafka core behavior indirectly via librdkafka; selected revision is linked to persistent Kafka integration failures.
No test removal ✅
Experimental gate ➖
No magic constants ➖
Backward compatibility ⚠️ New pointer introduces a behavioral regression in Kafka shutdown/test flows compared to prior branch state.
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ❌ Current librdkafka target is not rollout-safe due to reproducible CI regressions.
Compilation time ✅
No large/binary files ✅
Performance & Safety
  • The regression manifests as long blocking behavior during Kafka shutdown/test setup (DROP DATABASE ... SYNC timing out at 600s), which is an operational safety issue for Kafka table lifecycle paths.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    1. Update contrib/librdkafka to a regression-free commit (or add the upstream fix commit that resolves the bisected timeout regression).

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default submodule changed At least one submodule changed in this PR. labels Mar 30, 2026
Comment thread contrib/cppkafka Resolved
alexey-milovidov and others added 3 commits March 30, 2026 05:14
Address review feedback: catch `std::exception` and `...` in addition
to `HandleException` in `handle_rebalance`, since this function runs
from a C callback where any escaping exception is undefined behavior.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@alexey-milovidov
alexey-milovidov force-pushed the fix-kafka-drop-table-hang-rdkafka branch from 56239a9 to 4a70e1c Compare March 30, 2026 08:00
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is interesting. The code in cppkafka is good. The changes in librdkafka are a little bit risky (30 sec timeout), but we can see how it goes.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Make the PR in ClickHouse/librdkafka#18 based on the branch, that we currently use. It should be one of clickhouse-* branches, if we use them.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Retargeted ClickHouse/librdkafka#18 to ClickHouse/release-2.8.0 (the branch we currently use for the librdkafka submodule). The PR's HEAD already sat directly on top of ClickHouse/release-2.8.0, so no rebase was required — just a base-branch change. Mergeable state is now clean.

The companion cppkafka change is already merged: ClickHouse/cppkafka#7.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

After we merged both PRs for submodules and one more, update the submodules in this PR.

alexey-milovidov and others added 3 commits April 29, 2026 14:13
Bump `contrib/cppkafka` and `contrib/librdkafka` to the heads of their
ClickHouse release branches now that the dependent fork PRs are merged:

- cppkafka: bump to merge of ClickHouse/cppkafka#7
  (Catch exceptions from `assign`/`unassign` in `handle_rebalance`).
- librdkafka: bump to merge of ClickHouse/librdkafka#18
  (Use bounded timeout in `rd_kafka_assign0` instead of `RD_POLL_INFINITE`)
  and ClickHouse/librdkafka#17
  (Fix use-after-free in consumer lag timer).

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

Copy link
Copy Markdown
Member Author

CI bisect of the persistent kafka-test failures on this PR:

Symptom: every recent run has these timing out at 600 s on DROP DATABASE IF EXISTS test SYNC in the per-test setup:

  • test_storage_kafka/test_batch_slow_4.py::test_kafka_consumer_failover[generate_new_create_table_query]
  • test_storage_kafka/test_batch_slow_6.py::test_kafka_rebalance[generate_new_create_table_query-{}.*Saved offset]

On master vs PR (CIDB, last 30 days):

Bisect via timestamps: test_kafka_rebalance on the PR was 10 passes (2026-04-26), 5 passes (2026-04-28), then 0 passes / 12 failures (2026-04-29). Clean breakpoint at commit 8451f40d184 (Update submodules to merged commits on release branches, 2026-04-29 14:13), which bumped:

  • librdkafka: 54df05ab → ae43f47a (added e6ba87c7 + 61aa9022, two consumer-lag-timer UAF fixes)
  • cppkafka: 3556f3e9 → 107d5b1a (added 6c7302d, catch all exceptions in handle_rebalance)

The original 30 s rd_kafka_assign timeout was already on the branch from 2026-03-30 and CI was green for ~4 weeks with that change in place — so the timeout itself is not the cause. The regression is in the consumer-lag-timer UAF fixes (rd_kafka_topic_partitions_remove / rd_kafka_cgrp_partition_del). Most likely a refcount path that hangs DROP TABLE shutdown for the new analyzer Kafka tables.

Just refreshed the master merge — next CI run will be against today's master, but the underlying fix is in librdkafka and not addressed by this push.

Restore `.github/workflows/create_release.yml` and
`.github/workflows/vectorsearchstress.yml` to byte-identical content
of `origin/master` so the `Check Workflows` step in `Config Workflow`
no longer reports them as outdated. The previous restore-to-PR-tip
workaround left the YAMLs stale relative to master, which made the
check fail.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread contrib/librdkafka
@@ -1 +1 @@
Subproject commit cd9a80837602fe0f97c146beff752e705f40cb0a
Subproject commit ae43f47aa7a3bb82bbc4ab3a336d542923fa6ae8

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 librdkafka pointer here includes e6ba87c7 and 61aa9022. On this PR branch, CI bisect shows those two commits correlate with persistent Kafka integration timeouts after 2026-04-29, while the earlier timeout fix (54df05ab) was green for weeks.

Please avoid advancing to ae43f47 until the follow-up in ClickHouse/librdkafka resolves that regression; otherwise this PR carries a known blocker for Kafka tests.

alexey-milovidov pushed a commit that referenced this pull request Jul 12, 2026
`LimitTransform::makeChunkWithPreviousRow` asserts `row < chunk.getNumRows()`
and is called from `preparePair` with `data.current_chunk.getNumRows() - 1`
whenever `with_ties && rows_read == offset + limit`. This silently assumes the
current chunk has at least one row.

The read-in-order pipeline violates that assumption. With settings
`optimize_read_in_order = 1`, `read_in_order_use_virtual_row = 1` and
`read_in_order_use_virtual_row_per_block = 1`, `VirtualRowTransform` emits
zero-row chunks carrying `MergeTreeReadInfo` as sort-key markers for
`MergingSortedTransform`. In the single-stream case there is no merging, so
`RemoveVirtualRowTransform` is inserted to clean up — but it only stripped the
`ChunkInfo` and left the empty chunk on the pipeline. When such a chunk
arrived at `LimitTransform` after the previous data chunk had pushed
`rows_read` to exactly `offset + limit`, the call became
`makeChunkWithPreviousRow(empty_chunk, 0 - 1)` and the `UInt64` underflow
tripped the assertion (server abort in debug builds; surfaces as a
`LOGICAL_ERROR` in release builds). The AST fuzzer hit this on master across
multiple unrelated PRs (#99495, #104268, #101158) over the past 30 days.

Minimal reproducer:

  CREATE TABLE t (id UInt64, m Map(String, String),
                  INDEX idx_mk mapKeys(m) TYPE bloom_filter GRANULARITY 1)
  ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1;
  INSERT INTO t VALUES (1, {'1':'1'});
  INSERT INTO t VALUES (2, {'2':'2'});
  INSERT INTO t VALUES (3, {'3':'3'});

  SELECT id FROM t PREWHERE mapContains(m, toFixedString('1', 1))
  ORDER BY id ASC LIMIT 1 WITH TIES
  SETTINGS optimize_read_in_order = 1,
           read_in_order_use_virtual_row = 1,
           read_in_order_use_virtual_row_per_block = 1;

Two fixes:

1. `LimitTransform.cpp`: skip the `makeChunkWithPreviousRow` call when the
   current chunk has zero rows. There is no row to remember and the
   `previous_row_chunk` saved from the prior non-empty chunk is still the
   correct tie key for the boundary.

2. `RemoveVirtualRowTransform` (`SortingStep.cpp`): actually consume the
   virtual-row chunk — `chunk.clear()` it and enable `skip_empty_chunks` on
   the base `ISimpleTransform` so it is not re-emitted. This matches the
   existing comment ("we need to remove virtual row before output") and
   protects other downstream transforms from receiving these pointless
   markers.

Regression test `04247_99495_limit_with_ties_virtual_row_empty_chunk` aborts
master in debug builds and passes after this change.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/99495/b699481fd40feb67d515e47725de159f20dd1ff0/ast_fuzzer_amd_debug/
Related: #99495 (sighting PR)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`LimitTransform::makeChunkWithPreviousRow` asserts `row < chunk.getNumRows()`
and is called from `preparePair` with `data.current_chunk.getNumRows() - 1`
whenever `with_ties && rows_read == offset + limit`. This silently assumes the
current chunk has at least one row.

The read-in-order pipeline violates that assumption. With settings
`optimize_read_in_order = 1`, `read_in_order_use_virtual_row = 1` and
`read_in_order_use_virtual_row_per_block = 1`, `VirtualRowTransform` emits
zero-row chunks carrying `MergeTreeReadInfo` as sort-key markers for
`MergingSortedTransform`. In the single-stream case there is no merging, so
`RemoveVirtualRowTransform` is inserted to clean up — but it only stripped the
`ChunkInfo` and left the empty chunk on the pipeline. When such a chunk
arrived at `LimitTransform` after the previous data chunk had pushed
`rows_read` to exactly `offset + limit`, the call became
`makeChunkWithPreviousRow(empty_chunk, 0 - 1)` and the `UInt64` underflow
tripped the assertion (server abort in debug builds; surfaces as a
`LOGICAL_ERROR` in release builds). The AST fuzzer hit this on master across
multiple unrelated PRs (ClickHouse#99495, ClickHouse#104268, ClickHouse#101158) over the past 30 days.

Minimal reproducer:

  CREATE TABLE t (id UInt64, m Map(String, String),
                  INDEX idx_mk mapKeys(m) TYPE bloom_filter GRANULARITY 1)
  ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1;
  INSERT INTO t VALUES (1, {'1':'1'});
  INSERT INTO t VALUES (2, {'2':'2'});
  INSERT INTO t VALUES (3, {'3':'3'});

  SELECT id FROM t PREWHERE mapContains(m, toFixedString('1', 1))
  ORDER BY id ASC LIMIT 1 WITH TIES
  SETTINGS optimize_read_in_order = 1,
           read_in_order_use_virtual_row = 1,
           read_in_order_use_virtual_row_per_block = 1;

Two fixes:

1. `LimitTransform.cpp`: skip the `makeChunkWithPreviousRow` call when the
   current chunk has zero rows. There is no row to remember and the
   `previous_row_chunk` saved from the prior non-empty chunk is still the
   correct tie key for the boundary.

2. `RemoveVirtualRowTransform` (`SortingStep.cpp`): actually consume the
   virtual-row chunk — `chunk.clear()` it and enable `skip_empty_chunks` on
   the base `ISimpleTransform` so it is not re-emitted. This matches the
   existing comment ("we need to remove virtual row before output") and
   protects other downstream transforms from receiving these pointless
   markers.

Regression test `04247_99495_limit_with_ties_virtual_row_empty_chunk` aborts
master in debug builds and passes after this change.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/99495/b699481fd40feb67d515e47725de159f20dd1ff0/ast_fuzzer_amd_debug/
Related: ClickHouse#99495 (sighting PR)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant