Skip to content

Retry delete_topics RPC in kafka_delete_topic to fix flaky teardown - #108635

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-flaky-kafka-delete-topic-teardown-retry
Jun 27, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-flaky-kafka-delete-topic-teardown-retry

Conversation

@groeneai

@groeneai groeneai commented Jun 26, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #83683

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Description

The Kafka integration test helper kafka_delete_topic() called admin_client.delete_topics([topic]) with no retry on the RPC, unlike its sibling kafka_create_topic() which retries create_topics() up to max_retries times. A transient broker/controller error during test teardown (delete_topics -> _send_request_to_controller raising) therefore failed an otherwise-passing test. This wraps the delete_topics() call in the same retry-on-exception loop, mirroring kafka_create_topic(). Persistent failures still raise after exhausting max_retries; the happy path is unchanged.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108567&sha=2e30a6b9ae669015526971d597f7ea0b204183ed&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%201%2F4%29

Failure stack (teardown):

test_kafka_bad_messages/test.py:122 - in bad_messages_parsing_mode
    k.kafka_delete_topic(admin_client, f"{topic_name}")
helpers/kafka/common.py:82 - in kafka_delete_topic
    result = admin_client.delete_topics([topic])
kafka/admin/client.py:480 - in delete_topics
    response = self._send_request_to_controller(request)

Version info

  • Merged into: 26.7.1.145

The Kafka integration test helper kafka_delete_topic() called
admin_client.delete_topics([topic]) with no retry on the RPC itself,
unlike its sibling kafka_create_topic() which retries create_topics()
up to max_retries times. A transient broker/controller error during
test teardown (delete_topics -> _send_request_to_controller raising)
therefore failed an otherwise-passing test.

The existing post-delete list_topics() verification loop only handled
"delete accepted but not yet visible", not "delete RPC raised". Wrap the
delete_topics() call in the same retry-on-exception loop used by
kafka_create_topic(). Persistent failures still raise after exhausting
max_retries; the happy path is unchanged (single call).

Observed in CI on Integration tests teardown of
test_kafka_bad_messages/test.py::test_bad_messages_parsing_stream
(delete_topics -> _send_request_to_controller).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, at the function level (the CI failure is a non-deterministic broker race). A fake admin client whose delete_topics raises a transient _send_request_to_controller-style error once deterministically makes the old helper raise.
b Root cause explained? kafka_delete_topic() called admin_client.delete_topics([topic]) with no retry on the RPC. Its sibling kafka_create_topic() retries create_topics() up to max_retries. A transient broker/controller error during teardown (delete_topics -> _send_request_to_controller raising) propagated out and failed an otherwise-passing test. The existing post-delete list_topics() verify loop only handled "delete accepted but not yet visible", not "delete RPC raised".
c Fix matches root cause? Yes. Wraps the delete_topics() call in the same retry-on-exception loop kafka_create_topic() already uses. Directly addresses the unguarded RPC, not a symptom.
d Test intent preserved / new tests added? Yes. Test assertions (the parsing-mode body checks) are untouched; this is pure teardown robustness. No no-* tag, no weakened assertion. This is a shared test-helper change (no product code), so no new regression test is added; the helper's behavior was verified both directions.
e Both directions demonstrated? Yes. Without fix: transient delete raises (reproduces CI). With fix: survives, retries the RPC, topic deleted. Persistent failure still raises after exhausting max_retries (no infinite loop / no masking). Happy path: exactly 1 call, no behavior change.
f Fix is general across code paths? The other delete_topics( callsite (clean_test_database_and_topics) is a different helper, NOT on the reproduced failure stack and not observed failing, so it is left unchanged (avoiding a speculative change to a non-failing path). All topic context managers (kafka_topic, existing_kafka_topic) route through the fixed kafka_delete_topic.
g Fix generalizes across inputs? N/A (test-helper resilience fix, not a product code bug).
h Backward compatible? N/A (test-helper only; no settings/format/product behavior change).
i Invariants and contracts preserved? Yes. result is read only after a successful break, so it is never unbound. The two-phase structure (retry the RPC, then re-init retries=0 and run the existing verify loop) mirrors kafka_create_topic exactly.

Session id: cron:clickhouse-worker-slot-0:20260626-171800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin — could you review this? It adds a retry loop around admin_client.delete_topics() in the kafka_delete_topic integration-test helper (mirroring the existing retry in kafka_create_topic), so a transient broker/controller error during teardown no longer fails an otherwise-passing test.

@clickhouse-gh

clickhouse-gh Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dc6b564]

Summary: ✅


AI Review

Summary

The PR retries Kafka delete_topics teardown RPCs in the shared helpers and removes duplicate cleanup implementations from the affected integration tests. I found no unresolved correctness, safety, or test-contract issues in the current diff; the prior bot-authored finding about the duplicate unprotected delete path has been addressed and the thread was resolved.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jun 26, 2026
The previous commit added a retry-on-exception loop only to the shared
single-topic helper kafka_delete_topic. The same unprotected delete_topics
RPC existed in two other teardown paths, so a transient broker/controller
error during cleanup could still fail an otherwise-passing test:

- test_produce_http_interface.py defined its own duplicate kafka_create_topic
  and kafka_delete_topic; the local kafka_delete_topic called delete_topics
  once with no retry. Dropped both duplicates and reused the shared helpers
  in helpers.kafka.common (single source of truth).

- The shared bulk helper clean_test_database_and_topics issued an unprotected
  bulk delete_topics(topics). Wrapped it in the same retry loop.

- Eleven test_storage_kafka tests inlined a byte-identical copy of that bulk
  teardown. Converged them onto the now-retry-protected
  clean_test_database_and_topics so every Kafka delete_topics RPC in the
  integration suite goes through a retry path. Removed imports left unused
  after the convergence.

Net 30 insertions / 337 deletions. After the change the only delete_topics
call sites in tests/integration are the two retry-protected helpers.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (updated for the duplicate-coverage change)

This update generalizes the original single-helper fix to every Kafka teardown delete_topics path, per the bot review.

Pre-PR validation gate (click to expand)
# Check Status
a Deterministic repro? The CI failure is a non-deterministic broker race, but the fix is validated deterministically at function level (see e): a fake admin client whose delete_topics raises reproduces a teardown failure on the old single-call path.
b Root cause explained? Three teardown paths called admin_client.delete_topics(...) exactly once. A transient broker/controller error (RequestTimedOutError from _send_request_to_controller) during cleanup raised and failed an otherwise-passing test. kafka_create_topic already retried; the delete paths did not.
c Fix matches root cause? Yes: each delete RPC is wrapped in the same retry-on-exception loop kafka_create_topic uses (retry, time.sleep(0.5), raise after 50 attempts).
d Test intent preserved? Yes: only teardown robustness changes. No test body / assertion is touched. clean_test_database_and_topics keeps its post-delete verify loop; the parsing/format assertions are untouched.
e Demonstrated in both directions? Function-level harness (fake admin, delete_topics raises N times): OLD single-call path raises on the first transient error (reproduces the CI failure); NEW path survives one transient failure and retries (2 calls), still raises after max_retries on persistent failure (no infinite loop), and is a single call on the happy path. Verified for BOTH the single-topic kafka_delete_topic AND the bulk clean_test_database_and_topics.
f Fix is general, not a narrow patch? Yes — this is exactly the generalization the bot requested. grep -rn '\.delete_topics(' tests/integration now returns only the two retry-protected helpers. Removed the duplicate kafka_delete_topic/kafka_create_topic in test_produce_http_interface.py, retried the bulk helper, and converged 11 inlined teardown copies onto it. Net 30 insertions / 337 deletions.
g Generalizes across inputs/types? N/A (test-helper retry change, not a code/type bug).
h Backward compatible? N/A (integration-test helpers only; no server behavior, settings, or formats changed).
i Invariants/contracts preserved? Yes: the (instance, cluster) signature of clean_test_database_and_topics is unchanged; all 12 converged files have module-level instance/cluster; the DROP DATABASE IF EXISTS test SYNC; CREATE DATABASE test; reset is byte-identical to what the inlined fixtures used; py_compile passes on all 14 files.

Session id: cron:clickhouse-worker-slot-2:20260626-190800

@clickhouse-gh

clickhouse-gh Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.50% -0.10%

Changed lines: No C/C++ source files changed — skipping uncovered code analysis.

Newly covered by added/modified tests: 311 line(s), 22 function(s) across 122 file(s) · Details

Top files
  • src/Storages/StorageReplicatedMergeTree.cpp: 31 line(s)
  • src/IO/AzureBlobStorage/copyAzureBlobStorageFile.cpp: 12 line(s)
  • src/Parsers/parseFieldFromCastedLiteral.cpp: 10 line(s), 11 function(s)
  • src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp: 8 line(s)
  • src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp: 8 line(s)

Full report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — dc6b564

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
CH Inc sync private fork mirror CH Inc sync (private, not actionable by us)

All test/build/stress/integration jobs passed on this head (the generalized kafka_delete_topic / clean_test_database_and_topics teardown-retry de-duplication, addressing the bot change request). No PR-caused failures; no non-exempt red checks.

Session id: cron:our-pr-ci-monitor:20260626-233000

@alexey-milovidov alexey-milovidov self-assigned this Jun 27, 2026
@alexey-milovidov
alexey-milovidov merged commit 8ff46ce into ClickHouse:master Jun 27, 2026
168 of 169 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 27, 2026
pull Bot pushed a commit to Lobinson1/ClickHouse that referenced this pull request Jul 27, 2026
kafka_delete_topic, the shared single-topic teardown helper for the whole Kafka
integration family, retried a *successful* delete as if it had failed and could
never converge, so an otherwise fully passing test was reported FAILED from
teardown.

UnknownTopicOrPartitionError (error code 3) on a DeleteTopicsRequest means "that
topic does not exist", which for a delete is exactly the requested end state. It
landed in the helper's generic `except Exception: retry`, so the helper asked the
broker 49 more times to delete something already gone, burned ~23 s, and then
raised.

Read off the failing job's kafka-python client log (2026-07-24, topic
Native_stream_err_1784918653): attempt 1's request was sent at 18:44:18.560; at
18:44:48.570 the client gave up on the response after its 30 s request timeout
(the shard runs three xdist workers under TSan); the reconnect's metadata refresh
at 18:44:49.077 reported ClusterMetadata(brokers: 1, topics: 3, groups: 0), i.e.
only the three internal topics, proving the delete had in fact landed broker-side
and only its response was lost; every attempt from 18:44:49.078 on returned
error_code 3, which kafka/admin/client.py:409 raises on.

So this is a classification bug, not a missing retry. More retries provably
cannot help: each error-3 response came back in 1-4 ms, and the condition is
permanent. Rather than adding a guard, remove the incorrect classification, which
makes the teardown operation idempotent - the correct property for a delete.
UnknownTopicOrPartitionError is now caught ahead of the generic handler and
treated as the absent-topic path. It is not a blind return: it falls through to
the helper's existing post-verification loop, which independently confirms the
topic is no longer listed and still raises otherwise. The generic retry is
untouched, since it is load-bearing for the transient RequestTimedOutError.

kafka.errors marks UnknownTopicOrPartitionError retriable, but that describes
stale-client-metadata semantics on the produce/fetch paths, where a later
metadata refresh can make the topic appear. On the delete path the same code
means the opposite, so keying the retry on that flag would preserve the bug.

Not a single-test flake: since the retry loop was added (ClickHouse#108635, 2026-06-27) the
signature accounts for 4 CI hits across 4 unrelated PRs, 3 test modules and 3
sanitizer flavours, all through this one frame. It also makes a routine operation
of tests/casa_del_dolor/catalogs/kafkatest.py, which deletes randomly chosen
topic names, stop burning the full 50-attempt loop.

The regression test drives the helper with a stub admin client replaying that
exact RPC sequence. A broker cannot be made to drop exactly one
DeleteTopicsResponse on demand, and the passing path is byte-identical to today's,
so a broker-driven test of this interleaving could only be non-deterministic -
which is the property this change removes.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111572&sha=43ca40c8c0beb217e3edc66236a546332bb3c000&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%204%2F6%29
Related: ClickHouse#111572

Co-Authored-By: Claude Opus 4.8 <[email protected]>
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
kafka_delete_topic, the shared single-topic teardown helper for the whole Kafka
integration family, retried a *successful* delete as if it had failed and could
never converge, so an otherwise fully passing test was reported FAILED from
teardown.

UnknownTopicOrPartitionError (error code 3) on a DeleteTopicsRequest means "that
topic does not exist", which for a delete is exactly the requested end state. It
landed in the helper's generic `except Exception: retry`, so the helper asked the
broker 49 more times to delete something already gone, burned ~23 s, and then
raised.

Read off the failing job's kafka-python client log (2026-07-24, topic
Native_stream_err_1784918653): attempt 1's request was sent at 18:44:18.560; at
18:44:48.570 the client gave up on the response after its 30 s request timeout
(the shard runs three xdist workers under TSan); the reconnect's metadata refresh
at 18:44:49.077 reported ClusterMetadata(brokers: 1, topics: 3, groups: 0), i.e.
only the three internal topics, proving the delete had in fact landed broker-side
and only its response was lost; every attempt from 18:44:49.078 on returned
error_code 3, which kafka/admin/client.py:409 raises on.

So this is a classification bug, not a missing retry. More retries provably
cannot help: each error-3 response came back in 1-4 ms, and the condition is
permanent. Rather than adding a guard, remove the incorrect classification, which
makes the teardown operation idempotent - the correct property for a delete.
UnknownTopicOrPartitionError is now caught ahead of the generic handler and
treated as the absent-topic path. It is not a blind return: it falls through to
the helper's existing post-verification loop, which independently confirms the
topic is no longer listed and still raises otherwise. The generic retry is
untouched, since it is load-bearing for the transient RequestTimedOutError.

kafka.errors marks UnknownTopicOrPartitionError retriable, but that describes
stale-client-metadata semantics on the produce/fetch paths, where a later
metadata refresh can make the topic appear. On the delete path the same code
means the opposite, so keying the retry on that flag would preserve the bug.

Not a single-test flake: since the retry loop was added (ClickHouse#108635, 2026-06-27) the
signature accounts for 4 CI hits across 4 unrelated PRs, 3 test modules and 3
sanitizer flavours, all through this one frame. It also makes a routine operation
of tests/casa_del_dolor/catalogs/kafkatest.py, which deletes randomly chosen
topic names, stop burning the full 50-attempt loop.

The regression test drives the helper with a stub admin client replaying that
exact RPC sequence. A broker cannot be made to drop exactly one
DeleteTopicsResponse on demand, and the passing path is byte-identical to today's,
so a broker-driven test of this interleaving could only be non-deterministic -
which is the property this change removes.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111572&sha=43ca40c8c0beb217e3edc66236a546332bb3c000&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%204%2F6%29
Related: ClickHouse#111572

Co-Authored-By: Claude Opus 4.8 <[email protected]>
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Aug 30, 2026
get_admin_client retries a broker that is not up yet, but its except named only
kafka.errors.NoBrokersAvailable. Constructing a KafkaAdminClient runs several
readiness probes, and kafka-python chooses the exception class by whether the
probe names a node: a cluster-wide probe raises NoBrokersAvailable, while the
controller probe (admin/client.py:219 -> _refresh_controller_id -> :279, node id
given) raises NodeNotReadyError. KafkaClient.check_version documents the split in
its own docstring (client_async.py:887-891); the leaf swallows NodeNotReadyError
and keeps looping only when node_id is None (:918-922), and the raise is
conn.py:990-992, reached when the socket to the controller does not come up
inside api_version_auto_timeout_ms, which defaults to 2000 ms.

So the loop covered half the class it was written for. I added that loop in
ClickHouse#107337 and narrowed it to one class there deliberately; that was wrong about the
class.

Surfaced as test_partition_affinity.py::test_partition_affinity_settings_validation
erroring out of the autouse fixture in Integration tests (amd_asan_ubsan, db
disk, old analyzer, 4/6):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115294&sha=47d8d03a62c562bfc1e9a4adb9c2091d2f4a02fd&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%204%2F6%29

CIDB over 365 days at this call, split at the instant ClickHouse#107337 merged: before it,
10 NoBrokersAvailable and 1 NodeNotReadyError; after it, 0 NoBrokersAvailable and
2 NodeNotReadyError, against 23.3M Kafka integration test rows after versus 22.8M
before. The retry works, and the uncaught sibling class is all that is left. This
also corrects the "0 master failures" claim in ClickHouse#107337's own message: one master
row exists, 2026-06-02, on test_batch_slow_7.py.

Seventeen places constructed a KafkaAdminClient directly and had no retry at all.
Four of them, test_kafka_bad_messages/test.py:68,229,290 and test_1.py:29, are in
modules with no autouse fixture, so there that construction is the module's first
admin client. All seventeen now call the helper, following ClickHouse#108635, which
converged this suite's delete_topics calls onto the retrying helper the same way.
Exactly one KafkaAdminClient construction is left under tests/integration, inside
get_admin_client.

Deliberately not a bare except Exception: IncompatibleBrokerVersion and
UnrecognizedBrokerVersion are both retriable=False and must keep failing fast
instead of stalling for 15 seconds with a useless message.

Validated by injecting each exception at the constructor seam, with the fix
reverted as a negative control: NodeNotReadyError propagates on the first attempt
without the fix and is retried with it, NoBrokersAvailable is retried in both,
and both non-retriable classes propagate in both.

Co-Authored-By: Claude Opus 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…lete-topic-teardown-retry

Retry delete_topics RPC in kafka_delete_topic to fix flaky teardown
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 pr-ci 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