Skip to content

Do not retry a Kafka topic delete that already succeeded - #112039

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-kafka-delete-topic-already-gone
Jul 27, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-kafka-delete-topic-already-gone

Conversation

@groeneai

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

kafka_delete_topic (tests/integration/helpers/kafka/common.py), the shared
single-topic teardown helper for the whole Kafka integration family, retries a
successful delete as if it had failed, and can never converge. An otherwise fully
passing test is then 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, not a
failure. Today it lands in the helper's generic except Exception: retry, so the helper
asks the broker 49 more times to delete something that is already gone, burns ~23 s, and
then raises.

The interleaving, read off the failing job's own kafka-python client log (topic
Native_stream_err_1784918653, all timestamps 2026-07-24):

18:44:18.560  DeleteTopicsRequest_v3(topics=['Native_stream_err_1784918653'], timeout=30000) sent
18:44:48.570  BrokerConnection ... timed out after 30000 ms. Closing connection. [Error 7] RequestTimedOutError
18:44:49.077  <BrokerConnection ...> Updated cluster metadata to ClusterMetadata(brokers: 1, topics: 3, groups: 0)
18:44:49.078  DeleteTopicsResponse_v3(throttle_time_ms=0, topic_error_codes=[(topic='Native_...', error_code=3)])
              ... x49

Attempt 1 succeeded broker-side and only its response was lost to the kafka-python
30 s request timeout (the shard runs three xdist workers under TSan). The reconnect's
metadata refresh proves it: topics: 3 is only the three internal topics
(_schemas, __confluent.support.metrics, __consumer_offsets) — the topic is already
gone. Every later attempt therefore returns error code 3, and
kafka/admin/client.py:409 raises on any non-NoError code.

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. This PR
does not add a guard — it removes an incorrect failure classification, making the
teardown operation idempotent, which is the correct property for a delete.

The fix

UnknownTopicOrPartitionError is 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
topic not in admin_client.list_topics() and still raises if the broker claims the topic
is absent while continuing to list it. The generic except Exception retry is untouched
— it is load-bearing for the transient RequestTimedOutError in step 1.

The result.topic_error_codes reporting block is now guarded (result can legitimately
be unset on the absent-topic path), and its loop variable is renamed so it no longer
shadows the topic parameter that the listing loop reads.

kafka.errors.UnknownTopicOrPartitionError carries retriable = True, but that flag
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, and the refresh above confirms it — so keying the retry on the library's flag
would preserve the bug.

Blast radius

Not a single-test flake. CIDB, window strictly after the retry loop was added
(#108635, merged 2026-06-27T00:27:38Z), filtered on
position(test_context_raw, 'kafka_delete_topic') > 0:

test PR check
test_kafka_bad_messages/test.py::test_bad_messages_parsing_stream #111572 Integration tests (amd_tsan, 4/6)
test_storage_kafka/test_poll_timeout_after_assignment.py::test_kafka_poll_timeout_restored_after_assignment #110292 Integration tests (amd_tsan, 4/6)
test_kafka_bad_messages/test.py::test_bad_messages_parsing_dead_letter_queue #94695 Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/6)
test_storage_kafka/test_batch_slow_5.py::test_formats_errors #110166 Integration tests (amd_msan, 4/8)

4 hits / 4 unrelated PRs / 3 modules / 3 sanitizer flavours / 0 master, all through the
same frame — two via a direct kafka_delete_topic call, two via the kafka_topic
context manager's finally. Over the same window, of all 363 kafka-named FAIL/ERROR
rows, every delete-topic teardown failure is this one signature (via_helper = 4,
any_delete_topics = 4, unknown_topic_any = 4, listing_loop_fail = 0) — one
mechanism, no residue.

There is a second, independent motivation. tests/casa_del_dolor/catalogs/kafkatest.py
also calls this helper, and KafkaTable.update_table deletes a randomly chosen topic
name t{random.randint(0, 19)}, so deleting a topic that does not exist is that caller's
routine case. Today each such call burns the full 50-attempt / ~23 s loop before the
exception is swallowed by its broad except Exception, making a normal fuzzer operation
both slow and log-noisy.

Tests

The regression test drives kafka_delete_topic directly with a stub admin client and
needs neither a ClickHouse instance nor a broker. That shape is deliberate: a real 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 would be
non-deterministic — which is the property this PR exists to remove. The stub replays the
exact RPC sequence quoted above. It lives under
tests/integration/test_kafka_bad_messages/ because that is the module which owns the
reported failure, and because no other in-tree pytest harness covers
tests/integration/helpers; that path is also what makes the flaky check select and
repeat the module.

The five tests are: the observed interleaving now succeeds; a delete of an already-absent
topic succeeds without retrying; a topic that is still listed after error 3 still makes
the helper raise; a transient error followed by success still succeeds; and a permanently
failing delete RPC is still raised once max_retries is exhausted. The first two also
assert a bounded attempt count — so a fix that merely looped to max_retries and then
gave up would not pass — and that the listing check is reached rather than bypassed.

Verification:

  • Against pristine origin/master: 2 failed, 3 passed — the two new oracles fail with
    the exact CIDB signature kafka.errors.UnknownTopicOrPartitionError: [Error 3], and
    the three existing-behaviour assertions pass, so the test is discriminating rather
    than uniformly red. With the fix: 5 passed.
  • Two mutations, two distinct assertions. Removing only the error-3 branch re-breaks the
    two oracles. Replacing it with an unconditional return that skips the listing check
    breaks the still-listed negative control. Both halves are load-bearing.
  • 50 repeats of the new module: 250/250 passed (5 tests x 50).
  • The three previously-observed victim modules pass on the fixed tree against a real
    broker: test_kafka_bad_messages/test.py (4 passed),
    test_storage_kafka/test_poll_timeout_after_assignment.py,
    test_storage_kafka/test_batch_slow_5.py.
  • Liveness of the unchanged happy path: on test_bad_messages_parsing_stream the
    post-verification loop is reached the same number of times before and after the change
    (TOPICS LISTED 24 vs 24, Topic ... deleted 24 vs 24), and the new branch never
    fires there (0 occurrences) — the fix does not short-circuit the authoritative check.

CI report for the #111572 occurrence:
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

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Before opening this PR I reviewed the change independently of the author, and a second
model re-reviewed it cold against the frozen PR description. Findings and how each was
resolved:

💡 Nits (noted, not blocking)

  • Test docstrings duplicate incident detail from the commit message. AGREE, and
    measured rather than eyeballed: the module docstring is 17 lines with 0.88
    content-word overlap against the commit message plus this description, and three of
    its four timestamped transcript lines are byte-duplicated in both. That is the
    "motivation belongs in the commit message" concern. I kept the transcript because it
    is what motivates the stub's scripted outcomes sequence in-file — this is a
    cluster-free stub module, so without it the replayed sequence reads as arbitrary — but
    the re-stated root-cause narrative in the per-test docstrings is genuinely redundant
    and I am happy to trim it if a reviewer prefers.

  • kafka.errors.UnknownTopicOrPartitionError is written without backticks in the new
    in-file comment.
    I raised this against the repo's comment convention and then
    withdrew it after measuring: across every # comment line in tests/integration/*.py
    mentioning a library class or helper name, 0 are backticked and 81 are not — including
    the two pre-existing lines in this same function. Backticking one line would make the
    three-line block internally inconsistent, so the new comment follows local practice.
    The commit message and this description do backtick these names.

  • First cluster-free module under tests/integration/. Of 1039 tracked
    tests/integration/test_*/test*.py modules, all 1039 reference ClickHouseCluster and
    none use a stub, so the placement deserves an explicit justification rather than
    silence. I added one to the description: the module owns the reported failure, no other
    in-tree pytest harness covers tests/integration/helpers, and this path shape is what
    makes the flaky check select and repeat the module.

Verified clean during review (each traced in code, not assumed): the specific handler
correctly precedes the generic except Exception, which is required because the MRO ends
in Exception; kafka.errors contains exactly one class with errno == 3 and it has no
subclasses, so the catch cannot silently widen; kafka/admin/client.py raises exactly
that class for the observed response on the CI-pinned kafka-python-ng==2.2.3; the new
path is not a blind return, since it falls into the unchanged post-verification loop whose
list_topics performs a live MetadataRequest; the previously unconditional
result.topic_error_codes block is now guarded, closing an UnboundLocalError that the
new break path would otherwise have introduced; the renamed loop variable keys the listing
loop on the original topic argument on every path; the three delete_topics RPC sites
under tests/ were enumerated independently and match the fix's scope, with the bulk
helper's separate defect (its post-verification loop never re-lists) correctly left to its
own change rather than bundled here; the new test is discriminating rather than uniformly
red on master, and the two mutations break two different assertion sets, so both halves of
the fix are separately pinned; and the CI Fix or Improvement category is load-bearing —
a Bug Fix category would demand a per-arch Bugfix Validation that cannot reproduce a
lost-response interleaving.

One claim I could not re-verify at review time: the CIDB breadth table's row counts. The
play quota was exhausted (read_rows 300046388571/300000000000). It is a
breadth/motivation claim rather than a correctness one, the per-row occurrences are each
individually recorded, and both named victim modules reproduce locally.

Session id: cron:clickhouse-review-slot-48:20260727-070900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. cd tests/integration && CLICKHOUSE_TESTS_BASE_CONFIG_DIR=<repo>/programs/server/ python3 -m pytest test_kafka_bad_messages/test_delete_topic_helper.py -v — 5-7 s, no cluster, no broker, no binary (test_kafka_bad_messages/__init__.py is 0 bytes, so importing the module starts nothing). Not a "~1%" reproduction.
b Root cause explained? Yes. A DeleteTopicsRequest succeeds broker-side but its response is lost to the kafka-python 30 s request timeout; the helper's generic except Exception: retry correctly retries, but every retry now returns topic_error_codes=[(topic, 3)] — UnknownTopicOrPartitionError, "the topic does not exist", which for a delete is the requested end state. kafka/admin/client.py:409 raises on any non-NoError code, that raise lands in the same generic handler, and the helper asks the broker 49 more times to delete something already gone before re-raising out of test teardown. The failing job's own client log confirms the delete had landed: the reconnect's metadata refresh reports ClusterMetadata(brokers: 1, topics: 3, groups: 0) — the three internal topics only.
c Fix matches root cause? Yes — it removes an incorrect failure classification rather than adding a guard. No timeout bump, no retry-count bump, no widened bound, no size reduction, no tag. Both band-aids were rejected as provably ineffective: all 49 error-3 responses arrived in 1-4 ms (permanent, not transient), so more retries cannot converge; and keying the retry on the library's retriable = True flag would preserve the bug, because that flag describes stale-client-metadata produce/fetch semantics while on the delete path the same code means the opposite.
d Test intent preserved / new tests added? Yes. No assertion weakened; the helper's authoritative list_topics post-verification loop is untouched and still raises when the topic really is still present. New regression module tests/integration/test_kafka_bad_messages/test_delete_topic_helper.py (5 tests) added. Its path satisfies Targeting.is_integration_test_file (ci/jobs/scripts/find_tests.py:172-181), so the flaky check selects and repeats it.
e Both directions demonstrated? Yes. Against pristine origin/master (helper restored via git show origin/master:tests/integration/helpers/kafka/common.py): 2 failed, 3 passed — the two new oracles fail with the exact CIDB signature kafka.errors.UnknownTopicOrPartitionError: [Error 3], while the three existing-behaviour assertions pass, so the test is discriminating rather than uniformly red. With the fix: 5 passed. Two mutations confirm both halves are load-bearing: removing only the error-3 branch re-breaks the two oracles; replacing it with an unconditional return that skips the listing check breaks the still-listed negative control. 50 repeats: 250/250.
f Fix is general across code paths? Yes. All three delete_topics RPC sites under tests/integration/ were enumerated. The fixed function is the single owning helper for "make this topic not exist", and every observed carrier funnels through it — two via a direct call, two via the kafka_topic context manager's finally; existing_kafka_topic and tests/casa_del_dolor/catalogs/kafkatest.py inherit it for free. The two sites left alone are documented, not silently skipped: the bulk helper clean_test_database_and_topics has a second, independent root cause (its post-verification loop fetches its topic list outside the while, so it never re-lists) with zero CI evidence in 90 days, and the hand-rolled teardown in test_storage_kafka/test_system_stop.py should only be converged onto that helper after the loop is fixed — both are tracked separately rather than bundled here. The mirror direction (kafka_create_topic / TopicAlreadyExistsError) has 0 occurrences in 90 days and is deliberately untouched.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes for the input space that exists here — there are no type wrappers or numeric domains. The parameter space is (which exception the RPC raises) x (whether the topic is listed afterwards) x (attempt index), and the tests cover: error 3 on attempt 1; error 3 after a lost response; transient-then-success; transient to exhaustion (asserting exactly max_retries attempts, the boundary); and error-3-but-still-listed. Both an empty list_topics and a realistic internal-topics-only list are exercised.
h Backward compatible? (maintainer-approved exception only) N/A — test infrastructure only. No settings (so no SettingsChangesHistory.cpp), no serialization format, no protocol, no product code. The helper's signature and success/failure contract are unchanged for every existing caller, verified by running three real-broker Kafka modules on the fixed tree.
i Invariants and contracts preserved? Yes, and the main postcondition is strengthened rather than weakened: "returns iff the topic is absent, per list_topics" — the new path routes through that check instead of returning blind (proven by the mutation that skips it). Two concrete hazards handled: result can now legitimately be unset, so the result.topic_error_codes reporting block is guarded (an unguarded UnboundLocalError would have been a new failure mode); and that loop no longer rebinds the topic parameter that the listing loop reads, so the listing loop is keyed on the original argument on every path. The generic retry's error path is unchanged and still re-raises after max_retries. Liveness of the unchanged happy path measured on test_bad_messages_parsing_stream: the post-verification loop is reached the same number of times before and after the change (TOPICS LISTED 24 vs 24, Topic ... deleted 24 vs 24) and the new branch never fires there.

Session id: cron:clickhouse-impl-slot-41:20260727-061400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin — could you review this? It is a test-only fix to the shared Kafka teardown helper: kafka_delete_topic was retrying UnknownTopicOrPartitionError (error code 3), which for a delete means the topic is already gone, so a delete whose response was lost to the client request timeout could never converge and raised out of teardown on unrelated PRs.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [770cf0e]

Summary: ✅


AI Review

Summary

This PR makes kafka_delete_topic treat UnknownTopicOrPartitionError as the "topic is already absent" path and then still verify the end state through list_topics, while adding focused regression coverage for the lost-response interleaving and the negative control where the topic is still listed. I did not find any blocking or major issues in the current diff.

Final Verdict

✅ No actionable findings.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 27, 2026

@alexey-milovidov alexey-milovidov 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.

Good.

@alexey-milovidov alexey-milovidov self-assigned this Jul 27, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 27, 2026
Merged via the queue into ClickHouse:master with commit 9c42bac Jul 27, 2026
178 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 27, 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 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.

3 participants