Skip to content

Fix flaky test_kafka_flush_by_time by reusing one Kafka producer - #112004

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-kafka-flush-by-time-producer-reuse
Jul 27, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-kafka-flush-by-time-producer-reuse

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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

test_storage_kafka/test_batch_fast.py::test_kafka_flush_by_time asserts

SELECT uniqExact(ts), count() >= 15 FROM test.{kafka_table}_view

after an 18 second window. The first column, the number of flushes, is what the test is named
for and it is correct in every failure I looked at. The second column is the one that fails:
fewer than 15 rows arrive in time.

The produce loop sent one message per k.kafka_produce call, and that helper builds a new
KafkaProducer on every call, so every single message paid a full client bootstrap including
kafka-python's broker-version probe. In the failing CI run that probe took 2.1 s on one
iteration (3.023 s for the whole iteration, against 0.107-0.113 s for the other 17), which cost
about 3 messages out of a budget that had roughly half a message of slack. Result: 5 + 9 = 14
rows with uniqExact(ts) = 2, i.e. the flush behaviour was correct and only the row count was
short. Both engines flushed on schedule (7841/7599 ms, versus 7537/7535 ms in the run of the
other parametrization that passed 21 seconds earlier on the same server), so this is not a
StorageKafka/StorageKafka2 flush race.

This hoists one producer out of the loop, using the existing k.get_kafka_producer and
k.producer_serializer helpers that five other producers in the same file already use, and
closes it after the producer thread is joined. The per-iteration cost drops from 0.107-3.02 s to
a single send plus flush round trip.

The assertion, the >= 15 threshold, the 18 second window and the 0.8 s message rate are
unchanged. Nothing is weakened: no threshold lowered, no sleep lengthened, no retry wrapper, no
determinism tag.

Measurements on the fixed test, locally:

  • Producer constructions per run go from 17 (one per message) to 1.
  • Exactly 2 in-window flushes in 25 out of 25 runs, never 3, so uniqExact(ts) == 2 stays a
    live assertion and the flush cadence stays on the stream_flush_interval_ms default
    (measured 7514-9020 ms).
  • In-window row totals are now 19 to 21 against the threshold of 15, instead of 14.
  • 50 executions (--count 25, both parametrizations) pass.

Verified in both directions by injecting the measured 2.9 s stall into the produce path: on
master the test fails with assert 2\t0 == 2\t1, matching the CI signature exactly, and with
this change it passes even when the stall fires inside the loop. Reverting only the hoist and
keeping the injected stall brings the failure back.

One behaviour note: retries=15 now guards producer construction once at test start instead of
per iteration, so a transient broker outage surfaces as a clear setup error rather than a silent
under-count. That matches how the other call sites in this file already use the helper.

CI report for the failure this addresses:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110344&sha=006dde1db1b596687365eddd7a30586f45c4f332&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%204%2F6%29

No related open issue found for this test.

The kafka_setup_teardown / DROP DATABASE IF EXISTS test SYNC failures filed under the same
test name are a different root cause and are not addressed here.

`test_kafka_flush_by_time` asserts `uniqExact` over the insert timestamp plus a
row count of at least 15 after an 18 second window. The flush count, which the
test is named for, is correct in every failure; the row count is what falls
short.

The produce loop sent one message per `k.kafka_produce` call, and that helper
constructs a new `KafkaProducer` on every call, so every message paid a full
client bootstrap including the `kafka-python` broker-version probe. In the
failing CI run that probe took 2.1 s on one iteration (3.023 s for the whole
iteration, against 0.107-0.113 s for the other 17), which cost about 3 messages
out of a budget that had roughly half a message of slack. The result was
5 + 9 = 14 rows over 2 distinct flush timestamps, so the flush-by-time
behaviour was correct and only the total was short. Both engines flushed on
schedule (7841/7599 ms, versus 7537/7535 ms in the parametrization that passed
on the same server 21 seconds earlier), so this is not a `StorageKafka` or
`StorageKafka2` flush race.

Hoist one producer out of the loop, reusing the existing `k.get_kafka_producer`
and `k.producer_serializer` helpers that five other producers in this file
already use, and close it after the producer thread is joined. Per-iteration
cost drops from 0.107-3.02 s to a single send plus flush round trip.

The assertion, the threshold of 15, the 18 second window and the 0.8 s message
rate are unchanged. Measured after the change: producer constructions per run
drop from 17 to 1; there are still exactly 2 in-window flushes in 25 of 25 runs
and never 3, so the distinct-timestamp assertion stays live and the cadence
stays on the `stream_flush_interval_ms` default at 7514-9020 ms; in-window row
totals are 19 to 21 against the threshold of 15, instead of 14. 50 executions
across both parametrizations pass.

Verified in both directions by injecting the measured 2.9 s stall into the
produce path: on master the test fails with the CI signature, with this change
it passes even when the stall fires inside the loop, and reverting only the
hoist under the same stall brings the failure back.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds) - 3 findings adjudicated, 2 fixed

An independent model reviewed this change against the ClickHouse review skill and the
repository instruction file, and I reviewed it separately without reading the
implementation notes first. Round 1 raised three findings; two were fixed and the change
was re-reviewed, which returned no findings.

# Severity Finding Verdict
1 ⚠️ major Show both-direction evidence that producer reuse removes the flake, since the unchanged assertion cannot distinguish reuse from the per-message path on a fast run DISAGREE (evidence already recorded, no code change)
2 💡 nit The new comment does not wrap k.kafka_produce in inline code AGREE, fixed
3 💡 nit The commit message does not wrap literal names in inline code AGREE, fixed

1 - both-direction evidence (DISAGREE). The premise is correct and I do not dispute
it: a green fast run proves Kafka flush behaviour, not the mechanism. The evidence the
finding asks for was already recorded, and I verified each element against the raw
instrumentation reports rather than accepting the write-up. Producer constructions per
run, per parametrization: 17 constructions for 17 produce iterations on master, 1
construction for 20 to 23 iterations with this change, for both
generate_old_create_table_query and generate_new_create_table_query. Under the
measured 2.9 s stall injected into the produce path: master fails both parametrizations
with AssertionError: assert 2\t0 == 2\t1 at test_batch_fast.py:2289, the exact CI
signature; this change passes both; and reverting only the hoist while keeping the stall
in the identical place brings the failure back. That last control is the load-bearing
one, and it is stronger than what the finding asked for: in connection-setup mode the
stall physically cannot fire on the fixed body, since only one constructor call exists,
so the stall was also injected into KafkaProducer.flush, which runs exactly once per
iteration in both bodies. Rows three and four of that matrix therefore differ only by
the hoist. Plus 50 passes across both parametrizations from --count 25.

2 and 3 - inline code for literal names (AGREE). .claude/CLAUDE.md requires
literal class and function names in comments and commit messages to be wrapped in inline
code. The added comment wrote k.kafka_produce bare, and the commit message contained no
inline code at all. Both are fixed: the comment now inline-codes the helper name, and the
commit body wraps every occurrence of all ten literals it mentions, with no
f()-with-parentheses forms. I did not touch the one pre-existing unbackticked comment
elsewhere in the file, to keep this change to a single root cause. That round changed only
comment text, which I confirmed rather than asserted: the executable token streams of the
two revisions are identical, checked twice by different mechanisms and with mutation
controls proving the checker is not vacuous, so the earlier measurements still describe
this revision and were not re-run.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The bare 18 s window passes on an idle box, so the repro is injected: a pytest plugin sleeps 2.9 s (the stall measured in the failing CI run) inside the 6th producer construction. On master the test then fails 2/2 parametrizations every time with AssertionError: assert 2\t0 == 2\t1, the exact CI signature. The plugin records that the stall actually fired, so the claim is not vacuous.
b Root cause explained? Yes. The produce loop sent one message per k.kafka_produce call, and that helper constructs a new KafkaProducer per call, so every message paid a full client bootstrap. One kafka-python broker-version probe took 2.1 s in CI (3.023 s for that iteration, versus 0.107-0.113 s for the other 17), costing about 3 messages out of a budget with roughly half a message of slack against count() >= 15. Failure was 5 + 9 = 14 rows with uniqExact(ts) = 2, so the flush behaviour was correct and only the row count was short.
c Fix matches root cause? Yes. It removes the unbounded per-message connection cost by reusing one producer. Not a band-aid: the threshold, the 18 s window, the 0.8 s rate and the assertion are unchanged, and no retry wrapper or determinism tag was added. Lowering the threshold, lengthening the sleep, wrapping the SELECT in a retry and pinning kafka_flush_interval_ms were all considered and rejected, each of them either weakens the test or changes what it measures.
d Test intent preserved / new tests added? Yes, preserved. assert TSV(result) == TSV("2\t1"), the >= 15 threshold, the window and the message rate are byte-identical. Measured on the fixed test: exactly 2 in-window flushes in 25 out of 25 runs, never 3, so uniqExact(ts) == 2 remains a live assertion, and the cadence stays on the stream_flush_interval_ms default at 7514-9020 ms. No new test is added, the deliverable is the stabilisation of an existing one.
e Both directions demonstrated? Yes, four runs. Master with the injected stall fails both parametrizations at 6 + 8 = 14 rows. Fixed passes both, at 10 + 10 = 20 rows, and still passes when the stall is injected inside the loop instead, at 7 + 9 = 16. Mutation test: reverting only the hoist with the identical stall brings the failure back, at 6 + 8 = 14. Producer constructions per run go from 17 to 1. Plus 50 executions (--count 25, both parametrizations) all passing.
f Fix is general across code paths? Yes. All five produce loops in the Kafka integration family were enumerated (grep -rn "while not cancel.is_set()" tests/integration/test_storage_kafka/). This is the only one that sends a single message per kafka_produce call and asserts a count against a fixed window. The other four batch 100, 101, 113 and 3N messages per connection, so the bootstrap cost is amortised, and they assert through wait_for_log_line or query_with_retry, which are unbounded waits. Changing them would be unrelated scope.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes on the axis that applies. Both parametrizations, generate_old_create_table_query (StorageKafka) and generate_new_create_table_query (StorageKafka2), are covered because the fix is in the shared test body, and both were measured failing on master and passing with the fix. Type wrappers, settings matrices and boundary values do not apply, this is a Python test-harness change with no data-type surface.
h Backward compatible? (maintainer-approved exception only) N/A, test-only change. No setting, no SettingsChangesHistory.cpp entry, no serialization format, no user-visible behaviour.
i Invariants and contracts preserved? Yes. KafkaProducer is thread-safe and only one thread calls send/flush. producer.close() is placed after kafka_thread.join(), never inside the loop, so no iteration can touch a closed client, and no KafkaError or AssertionError appeared across the 50 runs. The helpers are used read-only, so no other call site changes. One semantic note: retries=15 now guards construction once at test start rather than per iteration, so a transient broker outage becomes a clear setup error instead of a silent under-count, matching the other call sites in this file.

Session id: cron:clickhouse-impl-slot-42:20260727-004100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin — could you review this? test_kafka_flush_by_time produced one message per k.kafka_produce call, and that helper builds a new KafkaProducer every call, so a single slow broker-version probe (2.1 s in the failing run) cost enough messages to miss the count() >= 15 assertion while the flush count itself was correct; this hoists one producer out of the loop and leaves the assertion, threshold, window and message rate unchanged.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dce0ed2]

Summary: ✅


AI Review

Summary

This PR stabilizes test_kafka_flush_by_time by reusing a single KafkaProducer instead of reconnecting on every loop iteration. I did not find a correctness or regression issue in the current change: the test still exercises the same flush-by-time contract, the helper usage is consistent with existing Kafka tests, and the available Praktika report shows no failed checks.

Final Verdict

Status: ✅ Approve

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

LGTM, appreciate the work!

@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 c74e4d4 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.

4 participants