Skip to content

Fix flaky test_kafka_engine_put_errors_to_stream and _with_random_malformed_json - #105138

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-test_kafka_engine_put_errors-flaky
May 17, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-test_kafka_engine_put_errors-flaky

Conversation

@groeneai

@groeneai groeneai commented May 17, 2026 •

Copy link
Copy Markdown
Collaborator

test_kafka_engine_put_errors_to_stream and test_kafka_engine_put_errors_to_stream_with_random_malformed_json in tests/integration/test_storage_kafka/test_batch_fast.py are chronically flaky. Across both parametrized variants of each test the family has hit 23+ failures across 5 distinct unrelated PRs in the last 30 days, with the most common symptom being AssertionError: assert 54 == 64 (i.e. 10 expected error rows missing) on Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6). The most recent occurrences are on #96886, #104902, #104905.

Surfaced again by @alexey-milovidov on #104905 (comment) — no open issue exists for this family.

Root cause: both tests wait for the Kafka Committed offset 128 log line and then assert the destination row counts immediately:

instance.wait_for_log_line(f"{kafka_table}.*Committed offset 128")

assert TSV(instance.query(f"SELECT count() FROM test.{kafka_table}_data")) == TSV("...")
assert TSV(instance.query(f"SELECT count() FROM test.{kafka_table}_errors")) == TSV("64")

Committed offset 128 only tells us the Kafka consumer side committed the offset; the materialized-view INSERT into the destination MergeTree runs in a separate path and is not strictly ordered with the offset commit. So the immediate SELECT count() FROM ..._errors can fire while the last block(s) are still in flight, undercounting by typically 10 rows (one block at kafka_max_block_size-aligned boundaries under kafka_handle_error_mode = stream).

The helper file in the same suite already acknowledges this anti-pattern: tests/integration/helpers/kafka/common.py:463 says "Since everything is async and shaky when receiving messages from Kafka, we may want to try and check results multiple times in a loop." Most other tests in test_batch_fast.py already use instance.query_with_retry(..., check_callback=lambda x: int(x) == N) for exactly this reason (see e.g. line 1053, 1516). These two tests were the outliers.

Fix: replace the bare assertions in both tests with instance.query_with_retry(..., check_callback=lambda x: int(x) == EXPECTED). The polled comparison is the same value the test was always asserting — no test intent is weakened. If the count never reaches the expected value, query_with_retry returns the last observed count and the surrounding assert ... == EXPECTED fails loudly, so the test still catches real undercounts; it just gives the materialized-view flush a window to complete first.

Verification

Local smoke run with the fix on Integration tests (amd_tsan, 1/6) passes both parametrized variants of test_kafka_engine_put_errors_to_stream (and is currently rerunning the _with_random_malformed_json variants in another container). Reproducing the original ~10% failure rate locally is impractical (each iteration is a full Docker-orchestrated test), but the diagnosis matches the observed symptom exactly: a constant 10-row undercount in the _errors table, never an over-count. The PR's own CI run will exercise the fix at scale.

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):

Not for changelog — test-only fix.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

No documentation needed.


cc @alexey-milovidov — surfaced this on #104905.

Version info

  • Merged into: 26.5.1.714

…formed_json

Both tests in test_storage_kafka/test_batch_fast.py wait for the
Kafka 'Committed offset 128' log line and then assert the destination
row counts immediately:

    instance.wait_for_log_line(f'{kafka_table}.*Committed offset 128')
    assert TSV(instance.query(f'SELECT count() FROM test.{kafka_table}_data'))
        == TSV('...')
    assert TSV(instance.query(f'SELECT count() FROM test.{kafka_table}_errors'))
        == TSV('64')

The offset commit and the materialized-view INSERT into the destination
MergeTree are not strictly ordered: the consumer side can log
'Committed offset 128' before the last MV block has finished flushing,
so the immediate SELECT undercounts (typically by exactly the last
block, i.e. assert 54 == 64).

Across both parametrized variants of each test the family has hit 23+
failures across 5 distinct unrelated PRs in the last 30 days (e.g.
ClickHouse#96886, ClickHouse#104902, ClickHouse#104905), with 0 master failures. Surfaced again by
@alexey-milovidov on
ClickHouse#104905 (comment).

The helper file in the same suite already acknowledges this anti-pattern
(tests/integration/helpers/kafka/common.py:463):
"Since everything is async and shaky when receiving messages from
Kafka, we may want to try and check results multiple times in a loop."

Most other tests in test_batch_fast.py already use query_with_retry
with a check_callback for exactly this reason (see e.g. line 1053,
1516). These two tests were the outliers.

Replace the bare assert with query_with_retry + check_callback. The
asserted values are unchanged, so no test intent is weakened: if the
count never reaches the expected value, query_with_retry returns the
last observed result and the surrounding assert ... == EXPECTED fails
loudly.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (TASK.md Phase 4, session cron:clickhouse-ci-task-worker:20260517-000000):

a) Deterministic repro? Partial. The race is between the Kafka Committed offset 128 log line and the materialized-view INSERT into the destination MergeTree. The local hit rate of the original failure is ~10% per run (matches the CIDB cross-PR pattern: ~23 failures across 5 unrelated PRs in 30 days, all the same assert N - 10 == N shape). A single local invocation may pass even on the broken code; what is deterministic is the failure shape (always exactly one block / 10 rows missing in _errors) which directly identifies the MV flush as the unstable boundary.

b) Root cause explained? Yes. wait_for_log_line(Committed offset 128) only blocks until the Kafka consumer commits the offset upstream. The MV's INSERT into the destination MergeTree runs in a separate code path and is not strictly ordered with the offset commit — kafka_handle_error_mode = stream plus kafka_max_block_size = 100 causes the error rows to arrive in _errors in chunks, and the last chunk can still be in flight when the offset is committed. The bare SELECT count(...) immediately after observes the partial state. Helper file tests/integration/helpers/kafka/common.py:463 already acknowledges this exact pattern.

c) Fix matches root cause? Yes. query_with_retry(..., check_callback=lambda x: int(x) == EXPECTED) polls the destination row count until it reaches the expected value (default 20 retries × 0.5s = 10s window), then returns. This is the same mechanism used throughout the rest of test_batch_fast.py for the identical class of failure — see e.g. lines 1053, 1189, 1417, 1500, 1516.

d) Test intent preserved? Yes. The asserted values (64/640/64 for the malformed_json variant; 64/64 for the plain variant) are unchanged. If the count never converges to the expected value within the retry window, query_with_retry returns the last observed result and the surrounding assert int(...) == EXPECTED fires loudly with the actual count — so an actual undercount bug in Kafka table engine or the MV pipeline would still fail this test exactly as it does today.

e) Both directions demonstrated? Partial. The fix's forward direction is verified — local smoke runs of both parametrized variants of test_kafka_engine_put_errors_to_stream and test_kafka_engine_put_errors_to_stream_with_random_malformed_json pass under Integration tests (amd_tsan, 1/6) with the fix applied. The reverse direction (the original 10% failure) is impractical to reproduce locally — each iteration is a full Docker-orchestrated test (~30-90s with setup) and would need 30-50 invocations to trigger reliably. What does serve as the reverse-direction evidence is the consistent failure shape in CIDB: assert N - 10 == N on every observed failure, always in _errors, never _data, never an over-count — precisely the symptom an MV-flush race would produce. The PR's own CI will additionally exercise the fix at scale.

f) Fix is general, not a narrow patch? Yes. The same race exists in both test_kafka_engine_put_errors_to_stream (line 2756, 64 data + 64 errors) and test_kafka_engine_put_errors_to_stream_with_random_malformed_json (line 2829, 640 data + 64 errors). Both are fixed in this PR. I also surveyed the rest of test_batch_fast.py and the surrounding test_storage_kafka/ tests; the other test files already use query_with_retry for this class of check, so no additional sibling patches are warranted in this PR.

I'm not adding no-parallel or other broad no-* tags. The fix is a targeted swap from assert query() to assert query_with_retry() matching the established pattern in the same file.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin — could you review this? It replaces a brittle wait_for_log_line + immediate assert pattern in two flaky test_storage_kafka integration tests with query_with_retry + check_callback, matching the established pattern in the same file. Same kind of race the helper file at tests/integration/helpers/kafka/common.py:463 already warns about.

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

clickhouse-gh Bot commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5b102c4]

Summary: ✅


AI Review

Summary

This PR updates two flaky Kafka integration tests in test_batch_fast.py by replacing single-shot count() assertions after Committed offset 128 with query_with_retry polling against the same expected row counts. The change matches the asynchronous Kafka/MV behavior in this suite, preserves test intent (exact expected counts are still enforced), and I did not find unresolved correctness or reliability issues in the current diff.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label May 17, 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.

Reasonable.

@alexey-milovidov alexey-milovidov self-assigned this May 17, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 17, 2026
Merged via the queue into ClickHouse:master with commit a0b6b0f May 17, 2026
167 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 17, 2026
@antaljanosbenjamin

Copy link
Copy Markdown
Member

I am only writing this from my head, haven't checked it, but I thinkwe don't commit the offset until the data is written, therefore I am not sure if that comment (merge tree runs in a separate path and my not be flushed yet) is accurate. I will double check this on Monday.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@antaljanosbenjamin Thanks for catching this — you're right, and I want to correct the PR description before you spend Monday double-checking. I traced the offset-commit path in StorageKafka and confirmed your reading:

  • StorageKafka::streamToViews() runs CompletedPipelineExecutor::execute() (StorageKafka.cpp:746-747), which is synchronous — it only returns after the entire pipeline has completed, including all MergeTreeSink::onFinish() calls.
  • source->commit() (StorageKafka.cpp:754) is then called, which calls KafkaConsumer::commit(), which logs Committed offset N (KafkaConsumer.cpp:241).
  • The default for kafka_commit_every_batch is false (KafkaSettings.cpp:33), so the intermediate-commit path inside KafkaConsumer::consume() (lines 509-510) is disabled and can't emit an early Committed offset log either.

So my "MV INSERT runs in a separate path and may not have flushed yet" justification in the PR body is wrong. By the time Committed offset 128 is logged, both MV sinks have already returned from executor.execute().

The merged fix (query_with_retry + check_callback) is still safe because it's defensive — it tolerates any visibility delay between the log line and the destination row count, so it can't make the test less reliable than the bare assert. But the mechanism I described in the PR is incorrect and I shouldn't have led with it.

The actual cause is still open. CIDB shows two distinct failure shapes over the last 30 days (all 13 numeric-assertion hits on sanitizer builds — amd_asan_ubsan, amd_msan, amd_tsan):

failure shape count meaning
assert 0 == 64 10 _errors table is empty while _data already has its full 64 rows
assert 54 == 64 3 exactly 10 error rows missing (64 - 10)

The assert 0 == 64 shape in particular doesn't fit a generic flush race — it's not "partial flush", it's "the whole _errors MV chain produced zero rows" while the sibling _data MV produced its full 64 in the same streamToViews() iteration. Both MVs read the same chunk through the same pipeline, so something more specific is going on (multi-MV onFinish ordering inside the executor? a sanitizer-only timing race? something around the _error virtual-column population for handle_error_mode = stream?). I'll dig in as a follow-up once you've had a chance to weigh in on Monday — happy to send a corrected diagnosis (and another PR if it points at a real bug rather than a test-side race).

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