Skip to content

Do not skip already-consumed Kafka messages when a StorageKafka2 streaming cycle fails - #116485

Merged
antaljanosbenjamin merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-kafka2-rollback-on-throw
Sep 3, 2026
Merged

antaljanosbenjamin merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-kafka2-rollback-on-throw

Conversation

@groeneai

@groeneai groeneai commented Aug 26, 2026 •

Copy link
Copy Markdown
Collaborator

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

A Kafka table with kafka_keeper_path set (StorageKafka2) no longer skips messages it had already consumed when a streaming cycle fails part-way through; previously those messages were never delivered to the materialized views and a later cycle committed an offset past them. As a consequence, with the default kafka_handle_error_mode an unparseable message now blocks the table instead of being silently skipped, matching StorageKafka. kafka_handle_error_mode = 'stream', kafka_handle_error_mode = 'dead_letter_queue' and kafka_skip_broken_messages remain the ways to skip such a message.

Description

Related: #116167, where this defect was found and is out of scope.

KeeperHandlingConsumer::poll consumes messages one at a time, and each consume advances the consumer past the message it returns. The OffsetGuard that owns the rollback was built only after the message sink declared the batch complete, and poll had no try/catch, so any throw in between escaped with no guard in existence and nothing rewound the consumer. prepareToPoll returns early while the assignment is fresh, so its own rollback did not run either, and the next successful batch committed past the skipped messages.

Measured on an unmodified build: after committing keys 0 and 1, a batch of 2, 3, <unparseable>, 4, 5 left the destination holding [0, 1, 4, 5].

The fix arms the rollback before the work rather than after it, as StorageKafka already does (KafkaSource::broken is true from construction and cleared only in commit). poll now wraps its consuming loop in catch (...) { rollback; throw; }. prepareToPoll also fails closed now: it repopulates the assignment before rewinding, so a throwing rewind left behind an assignment the fast path would poll on; it is cleared instead. The rollback wrapper is noexcept and takes LockMemoryExceptionInThread, because it runs inside a catch handler where the memory tracker may still raise, and because ~OffsetGuard already ran it during unwinding.

Kafka2Source (direct SELECT) and StorageKafka2 need no change: both go through the same consumer. StorageKafka is unaffected. Not fixed here: with no offset committed in Keeper the rewind resolves through the consumer group's stored offset and then auto.offset.reset (earliest), so an aborted first batch can be re-read from the start of the partition. That is duplication rather than loss, and it matches StorageKafka.

Most of both hunks is the reindent the try blocks force. New regression test: test_system_stop.py::test_kafka2_parse_error_does_not_skip_consumed_messages.


Workflow [PR]
Sync PR [sync-upstream/pr/116485]

Version info

  • Merged into: 26.9.1.576 (included in 26.9 and later)

…e fails

`KeeperHandlingConsumer::poll` consumes messages one at a time, and every
`consume` advances the consumer past the message it returns:
`KafkaConsumer2::consume` returns `getNextMessage` straight out of the buffered
batch, and `getNextMessage` increments `current` before the allocation that hands
the buffer out. The `OffsetGuard` that owns the rollback was constructed only
inside `if (message_sink(...))`, after the sink had declared the batch complete,
and `poll` had no try/catch.

So any throw in between escaped with no guard in existence and nothing rewound
the consumer: the default-mode rethrow for an unparseable message, a
`MEMORY_LIMIT_EXCEEDED` raised while parsing, or a Keeper failure while saving the
intent size. `prepareToPoll` returns early while the assignment is still fresh, so
its own rollback did not run on the next cycle either, and the next successful
batch committed `last_read_offset + 1` past messages that had been consumed but
never delivered to the materialized views.

Measured on an unmodified build: after committing keys 0 and 1, feeding one batch
of 2, 3, <unparseable>, 4, 5 left the destination table holding [0, 1, 4, 5].

Arm the rollback before the work instead of after it, as `StorageKafka` already
does: `KafkaSource::broken` is true from construction and is cleared only in
`commit`. `poll` now wraps its consuming loop in a catch-all that rolls back and
rethrows. The rollback is unconditional rather than guarded on a consumed-message
counter, because the position can advance while that counter is still 0.

The rollback wrapper is `noexcept` and takes `LockMemoryExceptionInThread`,
because it runs from inside a catch handler where `memoryTrackerCanThrow` is no
longer suppressed by `std::uncaught_exceptions`, and because `~OffsetGuard`
already ran the rollback during unwinding, where a throw out of a destructor
would terminate the server. That destructor now uses the non-throwing variant too.

`Kafka2Source` (direct SELECT) and `StorageKafka2` need no change: both reach the
same `poll`. `StorageKafka` is unaffected.

One user-visible consequence: with the default `kafka_handle_error_mode` an
unparseable message now blocks the table instead of being silently skipped. That
matches `StorageKafka`, and `kafka_handle_error_mode = 'stream'`,
`kafka_handle_error_mode = 'dead_letter_queue'` and `kafka_skip_broken_messages`
remain the ways to skip such a message.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Aug 26, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex; 3 findings) plus my own cold review
of the resulting code. No finding required a code change; the two rows below marked
noted-not-blocking are real observations I am recording rather than acting on.

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test does not prove the already-consumed prefix is rewound: a rewind to the malformed message's own offset would also satisfy count(key >= 4) == 0 and the repeated-parse-error arm, while abandoning keys 2 and 3 DISAGREE on the remedy, AGREE on the observation The remedy asked for is not expressible: with a permanent poison the correct behaviour IS a permanent wedge, so keys 2 and 3 are never delivered on a fixed build and an "assert retry delivers every valid key" arm would fail on the fix rather than on the bug. A transient in-poll failure would need injection that does not exist (the only Kafka failpoints, FailPoint.cpp:161-162, are both in the DROP path), and a failure staged outside poll exercises ~OffsetGuard, not the new catch. What the finding wants pinned is already pinned by test_kafka2_stop_aborts_inflight_block_pause_commits_it in the same file: it aborts an in-flight 5-row block before the guard commits and asserts all 5 are redelivered after SYSTEM START, through the same and only rollback primitive (KeeperHandlingConsumer.cpp:486-499) that poll's catch calls. A rewind landing on the current position would deliver 0 of 5 there. The new test pins that this path rewinds at all: the mutation arm that keeps the try and replaces the catch body with a bare throw; fails it. Residual, stated rather than hidden: that sibling has no committed offset, so the rewind TARGET is pinned only on the value_or branch
2 💡 The changelog category should be Critical Bug Fix because the defect loses messages DISAGREE I do not select that category proactively; it is reserved for cases a senior maintainer explicitly asks for, and none has been asked for here. The data-loss nature of the defect is stated plainly in the changelog entry, so the recategorisation is easy to request if wanted
3 💡 The visible Related: #116167 line does not use a full GitHub URL DISAGREE Both conventions are satisfied on different lines: the template's linked-issues comment block is present and unchanged with the full URL, and the additional visible line uses the short form for readability in the rendered body
4 💡 wait_for_log_line(..., repetitions=3) tails 10000 lines by default, so its three matches are already in the log from the preceding stability window AGREE, noted-not-blocking Found in my own review. The arm therefore asserts "at least 3 throws happened" rather than "the cycle is alive right now". Still non-vacuous: a build that threw once and stopped rescheduling yields one match and the arm times out

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-9:20260826-102000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One pytest command: test_storage_kafka/test_system_stop.py::test_kafka2_parse_error_does_not_skip_consumed_messages. Deterministic FAIL on the unmodified build, 10/10 PASS on the fix. Not a rate-based repro.
b Root cause explained? Yes. KeeperHandlingConsumer::poll advances the consumer on every consume, but the OffsetGuard that owns the rollback was built only after the sink accepted the batch and poll had no try/catch. A throw in between escapes with no guard in existence, prepareToPoll early-returns while the assignment is fresh so its own rollback does not run, and the next successful batch commits last_read_offset + 1 past the skipped messages.
c Fix matches root cause? Yes. It arms the existing rollback when the position becomes dirty instead of after the batch is accepted. No widened bound, no no-random-* tag, no reduced dataset, no guard at the throw site. rollbackToCommittedOffsets itself is unchanged.
d Test intent preserved / new tests added? Yes. No existing test modified or weakened; the only shared-code edit is a default-valued where="1" parameter on assert_dst_count_stable, so all 20 existing call sites keep byte-identical behaviour. One new regression test; this behaviour was previously uncovered in either direction.
e Both directions demonstrated? Yes. Base 8a01520 FAILS (assert 2 == 0, destination held [0,1,4,5] with keys 2 and 3 lost); fix fee366c5 PASSES. A mutant that keeps the try but replaces the catch body with a bare throw; FAILS identically, binding the test to this change.
f Fix is general across code paths? Yes, measured: poll has exactly one caller (StorageKafka2::pollConsumer), which has exactly two (Kafka2Source direct SELECT, and streaming). Both paths are fixed by the single change; neither needs its own guard. A throw out of saveIntentSize is inside the same try. prepareToPoll keeps the throwing variant deliberately.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes for the axes that exist: this is control flow, not type dispatch, so the throw source, partition count and error mode are the relevant axes and one unconditional catch (...) covers all. Deliberately not conditioned on consumed_messages > 0, because getNextMessage increments current before the allocation that returns the buffer, so the first message of a batch can advance the position while that counter is still 0. Multi-partition is covered because the rollback walks every assigned partition.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting, no changed default (so no SettingsChangesHistory.cpp row), nothing new written to Keeper (so no node format change). The engine stays behind allow_experimental_kafka_offsets_storage_in_keeper. The one deliberate behaviour change (default kafka_handle_error_mode now blocks on an unparseable message instead of silently skipping it) is disclosed in the changelog entry and the description; it matches StorageKafka, and stream / dead_letter_queue / kafka_skip_broken_messages are the documented opt-outs.
i Invariants and contracts preserved? Yes; three hazards checked in source. No deadlock: every topic_partition_locks_mutex acquisition inside the try is a scoped guard that unwinds before the handler runs. No use-after-free: poll's buf is a non-owning ReadBufferFromMemory into the discarded message buffer, and no frame on the exception path (pollConsumer to streamFromConsumer to streamToViews to threadFunc) reads consumer-derived state after the rollback. poll's chassert cannot fire, because clearing the assignment makes prepareToPoll take the full path and return NoPartitions if it rebuilds empty. The new wrapper's noexcept contract holds on all paths, which is why the memory-tracker lock is taken at function entry (matching TransactionLog::rollbackTransaction).

Session id: cron:clickhouse-impl-slot-40:20260826-082300

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a65b1fc]

Summary: ❌

job_name test_name status info comment
LLVM Coverage FAIL
Generate LLVM Coverage Diff Report FAIL cidb IGNORED
Print Uncovered Code FAIL cidb IGNORED
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) ERROR
Container memory budget exceeded (/docker) ERROR cidb IGNORED
Stress test (arm_asan_ubsan) ERROR IGNORED

AI Review

Summary

This PR moves the StorageKafka2 rollback point so that exceptions raised after a message is consumed but before an OffsetGuard exists rewind the consumer instead of letting a later cycle commit past undelivered rows, and it also clears the assignment when prepareToPoll cannot complete its rewind so the fast path cannot reuse a stale assignment. I did not find a remaining correctness, safety, or PR-metadata issue in the current diff.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

⚠️ No coverage measurement for commit a65b1fc: bash ci/jobs/scripts/generate_diff_coverage_report.sh failed (its output is on the Generate LLVM Coverage Diff Report result).

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @kssenii @antaljanosbenjamin, could you review this? KeeperHandlingConsumer::poll built its OffsetGuard only after the message sink had accepted the whole batch and had no try/catch, so a throw in between left the consumer advanced past messages that were never delivered and a later batch committed an offset past them; poll now rolls back to the committed offsets and rethrows, which is what StorageKafka already does via KafkaSource::broken. One deliberate consequence is called out in the changelog entry: with the default kafka_handle_error_mode an unparseable message now blocks the table instead of being silently skipped.

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a65b1fc6f with master b4e1ae991 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 2da63c1b4; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

4 object files changed (+232.25 KiB total), 1 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/parseISO8601Duration.cpp.o new 230.68 KiB +230.68 KiB

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

12 translation units recompiled, 47 s compile time in total, 12 of them have a recent master baseline.

Job report

@antaljanosbenjamin antaljanosbenjamin self-assigned this Aug 26, 2026

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

I want to check this before merging it.

prepareToPoll repopulates assigned_topic_partitions and resets poll_count to 0
before it rewinds the consumer to the committed offsets. If the rewind throws,
the assignment is left non-empty with poll_count == 0, so the next cycle takes
the fast path at the top of the function and never retries it: StorageKafka2
only logs an exception escaping prepareToPoll and reschedules, and nothing else
clears the assignment. A consumer already advanced past undelivered messages
then keeps consuming, and the next successful batch commits past them.

That is the window the rollback in poll was added to close. Its fallback clears
the assignment precisely so that prepareToPoll rebuilds it and rewinds, which
only helps if prepareToPoll does not leave a fresh assignment behind itself.

Measured on a debug build with both rollback attempts forced to fail with
MEMORY_LIMIT_EXCEEDED, the class the allocations in rollbackToCommittedOffsets
raise: without this change two consumed messages were skipped and the two
behind them delivered, and the unparseable message was read once. With it the
consumer re-read the same batch and delivered nothing past the failure.

The guard starts before the repopulation, not just before the rewind, because a
throw between the two leaves the same fresh-but-not-rewound assignment.
@groeneai

Copy link
Copy Markdown
Collaborator Author

@antaljanosbenjamin heads up before you start: the head moved after your review, so the commit to check is 774a3f2, not 9f72177.

The AI reviewer found a second path into the same loss window: prepareToPoll repopulates the assignment and resets poll_count before it rewinds, so a rewind that throws leaves behind an assignment the fast path will poll on. I agreed and fixed it in that commit; the forced-failure measurement is in the review thread. Nothing else is pending from me, and no rush.

@antaljanosbenjamin

Copy link
Copy Markdown
Member

@groeneai Why the checks haven't started? can you merge master to start a CI run?

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master and pushed 8bf9a139bec4. CI has started: https://github.com/ClickHouse/ClickHouse/actions/runs/33636858323

On why nothing ran before: the previous head had no workflow run at all, so there was nothing waiting for approval and nothing to re-run.

GET /repos/ClickHouse/ClickHouse/actions/runs?head_sha=774a3f2554326945519ecb308700a4bf2d9d11a4
  -> {"total_count": 0, "workflow_runs": []}          # same on groeneai/ClickHouse
GET /repos/ClickHouse/ClickHouse/commits/774a3f2.../check-runs
  -> {"total_count": 0}                               # combined status: pending

So the synchronize event from the push on Aug 26 never produced a run, and a new push was the only way to get one. That push itself timed out client side after 600s and landed only on a retry, which is the window I would suspect, but I cannot confirm it from outside.

The merge did not change the diff: still the same 3 files, +119/-34, and git diff master..HEAD has the same patch-id (77935a5b8660) as the head you approved, so there is nothing new to re-read.

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8bf9a13

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Parser memory check / Resolve master binary CI infra, not caused by this diff: the job asks for a hand-spelled master clickhouse-examples S3 key that resolves in none of the tracked commits #117701 (mine, merged 2026-09-02T16:49:23Z), measured absent from the tree that ran (this build finished 18:22Z but the branch was last updated 13:19Z, before that merge), so I merged master @ a65b1fc to pick it up

Session id: cron:our-pr-ci-monitor:20260902-183000

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a65b1fc

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
LLVM Coverage / Generate LLVM Coverage Diff Report + Print Uncovered Code CI infra, not this branch: the coverage baseline lookup still asks for a master key that resolves in none of the tracked commits, and the second leaf did not run because the first failed #117718 (external, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) resource guard, not a test result: praktika's own verdict on the leaf reads infrastructure/resource failure, not bug reproduction, and the nested-container cgroup leaf reached its cap. This is the residual that survives merged #117412, and post-#117412 it is confined to the 6/6 shard #117564 (mine, open)
Stress test (arm_asan_ubsan) host memory exhaustion in an unbounded stress container, not reachable from this diff. From 00:15:52Z every control query returns 241: Random mutation kill failed ... non-zero exit status 241, SYSTEM STOP VIEWS exited 241, Failed to run SYSTEM START VIEWS after 3 attempts. The stream then stalls 19 min while the harness's own clock keeps moving (runner 00:16:08Z to 00:35:52Z, carrying inner lines stamped 02:16:08, 02:27:28 and 02:35:50), SYSTEM START MERGES degrades to 210, and the job is cancelled during teardown at 00:36:13Z, 66 min into a 3 h budget, so praktika published no result and the CI database holds 0 rows for this check at this head. Control: the same check has 5595 success rows over 1076 other commits in 3 d, and no --memory bound is passed at the stress call site a fix task is created (investigating at full effort, fixing-PR link to follow on this pull request)

Parser memory check, the sole red of the previous ledger, passes on this head: the master merge that ledger promised carried in merged #117701.

Not one of the three is attributable to this diff, which touches src/Storages/Kafka/KeeperHandlingConsumer.{cpp,h} and one Kafka integration test. Two are job-level resource guards on unrelated shards and the third is a coverage-report script. Both Bugfix validation (integration tests, *) checks SUCCEEDED; their 68 FAIL rows in the CI database are the expected master-binary leg, which is what proves the new tests catch the bug.

Session id: cron:our-pr-ci-monitor:20260903-020000

@antaljanosbenjamin
antaljanosbenjamin added this pull request to the merge queue Sep 3, 2026
Merged via the queue into ClickHouse:master with commit 21ec3b2 Sep 3, 2026
171 of 175 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 3, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (arm_asan_ubsan) runner-agent loss in my CI finish ledger above: #118057.

get_run_command in ci/jobs/stress_job.py passed no --memory, so the container was bounded only by the host and the starved process was the runner agent outside it, which is why that check published no result and no artifacts. Job 100462891406 is the instance I measured it on.

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 groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default 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