Skip to content

Reduce the Kafka streaming batch size after a memory limit error instead of retrying the same size - #116522

Open
groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:kafka-adaptive-batch-size-on-memory-limit
Open

groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:kafka-adaptive-batch-size-on-memory-limit

Conversation

@groeneai

@groeneai groeneai commented Aug 26, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

A Kafka table streaming into materialized views now halves kafka_max_block_size and kafka_poll_max_batch_size after a cycle fails with MEMORY_LIMIT_EXCEEDED or CANNOT_ALLOCATE_MEMORY, so consumption keeps running at reduced throughput instead of failing on every cycle. The reduced sizes stay until the table is re-attached. A memory limit is also no longer reported as a bad message: with kafka_handle_error_mode = 'stream' or 'dead_letter_queue' it used to replace a well-formed message with an error row and commit its offset, and the message is redelivered instead. Tables with kafka_commit_every_batch = 1 are unchanged in both respects. Closes #116167.

Description

A Kafka table whose block does not fit under the server memory limit raises Code: 241, and the next cycle attempts the same work: nothing records that the size was too large.

streamToViews now keeps a per-table reduction level and halves both kafka_max_block_size and kafka_poll_max_batch_size by it, each from its own configured value, floored at 1, as #98810 does for S3Queue. Both must shrink: KafkaSource never cuts a block short of a polled batch, so the poll size is a block's floor. A compare-and-swap on the level the failing cycle used makes concurrent cycles failing at the same size halve once between them, not once each. The error is rethrown unchanged; no inner retry.

Two deliberate limits. The reduction is never restored: consumers are pooled, so a success cannot be attributed to the cycle that failed. kafka_commit_every_batch = 1 is untouched in every handle-error mode: its offsets are committed mid-block and not rewound, so neither a smaller size nor a rethrow would bring back a message that never reached the views.

KafkaSource also rethrows a memory error out of its on_error callback: StreamingFormatExecutor routes every exception except cancellation there, so a memory limit became an error row and committed an undelivered message's offset. The consumer is marked dirty instead and the block is redelivered. StorageKafka2 is left out: nothing rewinds an aborted cycle there, so a rethrow would skip messages it had already consumed. #116485 fixes that and this guard can follow it. NATS, RabbitMQ and FileLog swallow a memory limit the same way and each needs its own redelivery analysis.

Adds ProfileEvent KafkaBatchSizeReductions. No new setting, default or format change.

Validated by test_storage_kafka/test_memory_limit_batch_reduction.py: ten cases, each reddened by a mutant that disables only the property it pins, the timing-exposed ones repeated five to ten times.


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

groeneai and others added 8 commits August 25, 2026 20:47
A Kafka table whose steady-state block does not fit under the server memory
limit raises MEMORY_LIMIT_EXCEEDED on its background streaming thread, and the
next cycle attempts the same amount of work. streamToViews recomputes the block
size from settings on every entry and the throw reaches the blanket catch in
threadFunc, which only logs and reschedules, so nothing records that a size was
too large and the table fails on every cycle indefinitely. Reported in ClickHouse#116167.

streamToViews now keeps a per-storage reduction level and derives both
kafka_max_block_size and kafka_poll_max_batch_size from it, each halved from its
own configured value and floored at 1. Both have to shrink: the accumulation
loop in KafkaSource::generateImpl guards its break with
!consumer->hasMorePolledMessages(), so it cannot stop mid-poll and the poll size
is the floor of a block. Halving the block alone would change the peak by
nothing.

The poll cap is installed as state on KafkaConsumer rather than passed to
consume(), because subscribe() ends with its own doPoll() and a failure calls
markDirty(), which invalidates the subscription. Every adaptive retry therefore
re-subscribes, and a per-call cap would leave that first poll draining a
full-size batch, which is exactly the retry the reduction targets.

The level is raised by a compare-and-swap on the level the failing cycle used.
With kafka_thread_per_consumer several cycles read the same level and can fail
concurrently; fetch_add would apply N halvings for one too-large size, and since
the level is never lowered that over-reduction would be permanent. The error is
rethrown unchanged, so the redelivery and offset-commit behaviour is untouched
and delivery stays at-least-once as before. The halving factor and the floor of
1 follow ClickHouse#98810, which does the same for S3Queue.

Two deliberate limits. The reduction is not restored automatically: consumers
are pooled and handed to whichever source asks for one, so a success cannot be
attributed to the work that failed and no success-driven rule converges.
kafka_commit_every_batch = 1 does not adapt, because markDirty() only calls
cleanUnprocessed() and rewindToLastCommitted() is reached solely from the
cancellation branch, so mid-block commits are not rewound on a pipeline throw
and the messages that never reached the views are already gone.

StorageKafka2 is untouched: it is experimental-gated, commits through Keeper,
and has no kafka_commit_every_batch equivalent, so it does not inherit these
failure semantics.

Adds the ProfileEvent KafkaBatchSizeReductions and an integration test with five
arms. Each arm was also run against a mutant disabling the property it pins, and
each failed on its own assertion.
`StreamingFormatExecutor::execute` forwards every non-cancel exception to the
`on_error` callback as a per-input parse error, and the allocation from the
report in ClickHouse#116167 happens inside that try block. `KafkaSource`'s callback
switched on `kafka_handle_error_mode` alone, so with `stream` or
`dead_letter_queue` a `MEMORY_LIMIT_EXCEEDED` replaced a well-formed message
with an error row, `executor.execute` returned normally and the offset was
committed. The adaptive batch reduction added in this branch never fired in
those two modes either, because nothing was thrown out of the pipeline.

A memory limit describes the state of the server rather than the message being
read, so the callback now rethrows it before the mode switch. The redelivery
path is unchanged: the error leaves the pipeline exactly as it already did
under the default mode.

`isMemoryLimitError` moves from an anonymous namespace in `StorageKafka.cpp`
into `StorageKafkaUtils` so both call sites share one list of codes.

The new integration arm fails without this change with 33 memory errors
counted as bad messages, and a mutant that keeps the helper referenced while
disabling only the rethrow reddens it on the same assertion.
…ine either

StorageKafka2's on_error had no memory-code guard, so under
kafka_handle_error_mode = 'stream' or 'dead_letter_queue' a MEMORY_LIMIT_EXCEEDED
raised while inserting a well-formed message was recorded as an error record and
the message's offset was then committed, losing it. The v1 engine received this
guard in the previous commit; isMemoryLimitError already lives in the shared
StorageKafkaUtils, so the same rethrow is transplanted. The Keeper engine keeps
no reduction state: it has its own consumer and commit protocol and the batch
size adaptation is deliberately not extended to it.

Install the poll cap where the consumer is handed out, in popConsumer under the
pool lock, rather than in the caller between popConsumer and subscribe. subscribe
ends with a poll of its own, so the previous placement made correctness depend on
an ordering enforced only by a comment, and a consumer whose subscription was
marked dirty re-subscribes on every adaptive retry. Setting it unconditionally
also resets a pooled consumer for its next user instead of relying on the
previous holder having left a usable value.

Tests: the delivery of rows at a reduced size while the memory is still pinned is
now asserted, which is the property the change exists for and which the suite
previously observed only after the pressure was released. The rethrow arm covers
both non-default handle-error modes, a new arm asserts the reduction is reset by
DETACH/ATTACH, the concurrent arm asserts one halving per size used so an
unconditional per-failure increment cannot satisfy it, and the persistence arm
waits for a new cycle with a bounded waiter instead of a fixed sleep that an idle
cycle can outlast.
…ency oracle

Parametrizes test_memory_error_is_not_a_bad_message over the engine as well as the
handle-error mode, so the memory-error guard added to StorageKafka2::pollConsumer's
on_error is exercised rather than only compiled. The instance gains with_zookeeper
and the Keeper-backed table is created the way test_system_stop.py does it. On the
parent commit the two new arms fail, one on KafkaMessagesFailed reaching 51 and one
because the rethrow never happens at all; a mutant that removes only the
StorageKafka2 guard reddens exactly those two and leaves the StorageKafka arms green.

The Keeper arms deliberately do not assert that every message arrives. A StorageKafka2
cycle that throws in the middle of a block drops the messages it had already consumed:
rollbackToCommittedOffsets re-assigns the partition to RD_KAFKA_OFFSET_INVALID when
nothing has committed yet, so the read position does not rewind, and a later cycle
commits past them. That predates this change and its own default handle-error mode
reaches it: on the parent commit, in that mode, the same fixture delivered 16 of 256
messages, against 256 of 256 for StorageKafka on the same binary. The arms assert that
rows arrive at all, which is also what keeps the error-record checks from holding over
an empty table.

Replacing the compare-and-swap with fetch_add was run ten times against the concurrency
arm instead of once, to turn its probabilistic witness into a measured rate: it reddens
10 of 10, nine times because several levels were skipped before the first reduced cycle
logged anything.

Also moves the limits include to the top of StorageKafka.cpp, where .clang-format's
first include category puts it. The binary is bit-identical afterwards.

Co-Authored-By: Claude Opus 5 <[email protected]>
…n the batch

The comment above the arrived > 0 guard named a mechanism that does not run on the
path the arm creates. KeeperHandlingConsumer::poll constructs its OffsetGuard only
inside if (message_sink(...)), after the sink returns true, and there is no try/catch
or scope guard anywhere in the function, so a throw out of the sink - which is what
the new StorageKafka2 guard does - escapes with no guard in existence and nothing
rolls back. The value_or(INVALID_OFFSET) rewind the old text described is real but
belongs to a guard that was built and then dropped uncommitted, e.g. a failing
materialized-view push. Both paths lose already-consumed messages, which is why the
earlier measurement did not separate them. The replacement states both and stays
true whichever one runs.

The guard itself no longer depends on one of the original 256 messages surviving the
aborted cycles that the same comment documents as lossy. Four messages are produced
after SYSTEM FREE MEMORY, so the two error-record checks below are kept off an empty
table by data that arrives under no memory pressure. The check_callback and the
assertion are unchanged, and deliberately not tightened to >= 4: that would trade
one timing bet for another.

Both edits are confined to the keeper branch. Stripping comment lines leaves the
file byte-identical to the previous commit apart from the single produce call, and no
compiled file is touched. The four mode x keeper cases pass five times each; with
only the StorageKafka2 guard removed the two Keeper arms red at their own assertions
and both StorageKafka arms stay green, and the same two red on the commit that
predates that guard. Both failures land upstream of the four extra messages, so they
cannot mask a broken build.

Co-Authored-By: Claude Opus 5 <[email protected]>
`KeeperHandlingConsumer::poll` builds its rollback only on the success path:
`saveIntentSize` and the returned `OffsetGuard` both sit inside
`if (message_sink(...))`, with no `try`/`catch` and no scope guard around it. A
throw out of the sink, which is what the rethrow added earlier in this branch
introduces, escapes with no guard in existence, so nothing rewinds:
`KafkaConsumer2::getNextMessage` has already advanced `current` before it
returns the buffer, and `prepareToPoll` early-returns while the assignment is
still fresh, so a later cycle commits past the messages the aborted one had
consumed.

Measured on the parent of the commit that added it, which contains no part of
this change, in the default `kafka_handle_error_mode` that this branch does not
touch: 16 of 256 rows delivered by `StorageKafka2` against 256 of 256 by
`StorageKafka` on the same binary. So in that engine the rethrow has no benefit
to deliver. It trades one message's content for the whole in-flight set, and
the property it is named after, that a well-formed message is neither dropped
nor its offset committed, is not reached there at all.

The rollback gap itself is a separate pre-existing defect and is not fixed
here. Once it is, this rethrow becomes safe and can be added on top, losing
nothing by being sequenced after it.

`isMemoryLimitError` stays in `StorageKafkaUtils` rather than moving back into
`KafkaSource.cpp` now that one caller is left: that is the engine's utils home,
and moving it would churn two more files.

Co-Authored-By: Claude Opus 5 <[email protected]>
…y_batch`

The rethrow added earlier in this branch is only correct where the discarded
block is redelivered, and with `kafka_commit_every_batch` it is not.
`KafkaConsumer::consume` commits the preceding poll before fetching the next
one, while `KafkaSource::generateImpl` accumulates one output block across many
polls and breaks only on `!consumer->hasMorePolledMessages`. So a block
routinely spans polls whose offsets are already committed. On a throw the block
is discarded and `~KafkaSource` calls `markDirty`, which only calls
`cleanUnprocessed` and does not rewind; `rewindToLastCommitted` is reached
solely from the cancellation branch. Those rows are committed and never
delivered.

Before the rethrow they were delivered: in `stream` and `dead_letter_queue` the
memory error did not leave the callback, a row was substituted and the block
completed. This is the same setting the batch reduction already refuses to act
on, for the same reason, three lines away in `streamToViews`; the rethrow is a
new throw and was not given the same exclusion. It has one now, so with
`kafka_commit_every_batch = 1` this branch is the previous behaviour in all
three handle-error modes.

The new arm asserts `KafkaMessagesFailed` moves. `on_error` is its only
increment site and the rethrow sits immediately ahead of that increment, so a
rethrown memory error leaves it untouched; no message in the arm is malformed,
so any increment is a memory error handled as a bad message. It deliberately
does not assert a delivered row count or a surviving error row: both need a
block to complete while the memory is pinned, and the limit is enforced on
resident memory, which the arms ahead of it leave near the ceiling. A mutant
bypassing only the new condition, and a control removing only the setting, both
redden it on that assertion with the count at zero.

Co-Authored-By: Claude Opus 5 <[email protected]>
`query_with_retry` returns the last result whenever any attempt succeeded, and
raises only if every attempt threw (`helpers/cluster.py:5241-5271`), so a
`check_callback` that never succeeds is a silent 180-second no-op. The two
lifecycle arms called it and discarded the result, so each carried a wait that
could not fail. Both now capture and assert it, the way `drain_topic` already
did.

That also moves the re-attach arm's positive control into the arm. Until now the
only evidence that a wrong reset would be caught lived in a mutant log: the arm's
oracle is the absence of a reduced-size line, and an inactive re-attached table
satisfies it just as well as a correct reset does. The arm now also asserts that
the rows it waited for arrived, so "nothing was logged" can no longer be
satisfied by a table that never ran a cycle.

Three doc comments called `poll_batch_size_override` a cap. `KafkaConsumer.cpp:459`
selects it instead of `batch_size`, so it replaces the poll size rather than
clamping it, and a value above the configured `kafka_poll_max_batch_size` would
raise it. The only caller halves that setting and so cannot produce one, which is
why the wording changes and the code does not.

The `popConsumer` comment claimed `subscribe` polls before the caller regains
control. It does not: `popConsumer` returns to `KafkaSource::generateImpl`, which
only then calls `subscribe` (`KafkaSource.cpp:96-104`). The reason the write
belongs there is different, and now stated: `subscribe` ends with a poll of its
own (`KafkaConsumer.cpp:357`), so the size has to be installed before the caller
subscribes.

Arm 1's delivery assertion needs a block to complete while the memory is pinned,
which only holds while that arm runs first, because the limit is enforced on
resident memory and the later arms leave it at the ceiling. That is now stated in
the arm, where a reader inserting another case above it will see it.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal review: one known test weakness left in, remedy below (click to expand)

Six review rounds against an independent second-model gate. Everything agreed was fixed except the
item below, which I am declaring rather than leaving for CI to find.

Left in, with the remedy

# Finding State
❌ In test_batch_size_is_reduced_after_memory_limit, assert polled, "no poll was observed after the reduction" reads the log once without waiting, and it is anchored on a line that is logged before the poll it looks for: StorageKafka.cpp logs the reduced sizes before the sources exist, and Polled batch of N comes later from doPoll. Real. It failed 1 of 5 executions last round (1 failed, 8 passed at load average 68; green in the other full-file run and in 3 solo runs; 0 firings in 13 earlier full-file runs and in a 25-run repeat). The fix is one line and changes no assertion: wrap the read in the deadline loop this file already uses for every other in-window observation, like wait_for_delivery_at_reduced_size. The bound max(polled) <= POLL_SIZE // 2 stays as it is. I will push it as soon as anyone confirms they would rather have it here than in a follow-up.

Declined, with the evidence

# Finding Evidence against
💡 Cover the CANNOT_ALLOCATE_MEMORY arm of the error-code test It is raised by Allocator when mmap/malloc itself fails, not by the memory tracker the fixture pins, so no integration arm can reach it without a new production failpoint at the callback boundary. Both alternatives cost more than the token they protect. Removing the code from the predicate would be worse behaviour, not better coverage: an outright allocation failure is a state of the server exactly as the tracked limit is.
💡 Restore the size automatically after a successful cycle popConsumer hands out the first consumer that is not in use, so a success is not attributable to the work that failed, and an idle table succeeds constantly with nothing to consume, so a success-driven reset would fire on nothing. Under persistent pressure it would alternate between failing and succeeding forever. #98810 clears the S3Queue override on a successful commit because there the goal is isolating one bad file. Say the word if you want a decay rule instead and I will add one.
💡 Bug Fix rather than Improvement, since a memory limit could previously cost a message Defensible for the on_error half, but the subject of the PR is the adaptive reduction, and the changelog entry states the old behaviour explicitly, so nothing is hidden by the label. Happy to switch it.
💡 The new module's cases must run in file order (the first one asserts a delivery while memory is pinned, which needs a server that is not already at the ceiling) Holds under every CI path: --dist=loadfile normally and --dist=each for the flaky and targeted checks both preserve collection order, and --random-order is only ever passed next to --count, which no job configuration uses. Noted because a local run with --count would reorder them.

Session id: cron:clickhouse-review-slot-8:20260826-133900

@clickhouse-gh clickhouse-gh Bot closed this Aug 26, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. tests/integration/test_storage_kafka/test_memory_limit_batch_reduction.py pins the server memory limit to 2 GB, leaves 200 MB of headroom with SYSTEM ALLOCATE MEMORY, and produces 256 messages of 512 KB against kafka_max_block_size = 256, kafka_poll_max_batch_size = 64. A full-size block cannot fit, so cycle 1 raises Code: 241 on every run.
b Root cause explained? Yes. streamToViews recomputes block_size from settings on every entry, so nothing records that a size was too large. The exception reaches the blanket catch (...) in threadFunc, which only logs and reschedules, and the next cycle attempts an identically sized unit of work. The throw itself is correct; the memorylessness is the defect.
c Fix matches root cause? Yes. It adds the missing memory: a per-storage reduction level that both size limits are derived from. It is not a guard at the allocation site, and it does not widen or suppress the memory limit.
d Test intent preserved / new tests added? New tests only; no existing test was modified or weakened. Nine cases (eight functions, one of them parametrized over two handle-error modes) cover the reduction, the poll half of it, the error-code gate, the kafka_commit_every_batch exclusion of the reduction and separately of the rethrow, the persistence of the reduction across a success, its reset on re-attach, the concurrent single-step property, and that a memory limit is not reported as a bad message under kafka_handle_error_mode = 'stream' or 'dead_letter_queue'.
e Both directions demonstrated? Yes. All nine cases pass on the fix, three consecutive full-file runs plus five repeats of the four cases the last round touched (9/9, 9/9, 9/9 and 20/20). Every case was also run against a mutant disabling only the property it pins, each failing on its own assertion: predicate never matches gives assert 0 >= 1; block-only halving leaves the poll at 64 (assert 64 <= 32); a neutered error-code gate makes the parse-error arm reduce (assert [128] == []); a dropped intermediate_commit exclusion reduces in that mode (assert [128, 128, 64, ...] == []); resetting the level after a successful cycle stops the reduced sizes being used (assert 3 > 3); making the level static leaves it reduced across a re-attach (assert [32] == []); disabling the memory-error rethrow makes the stream arm count memory errors as bad messages; keeping that rethrow in stream only reddens the dead_letter_queue arm while stream correctly survives; and bypassing only the new kafka_commit_every_batch condition reddens its arm with assert 0 > 0, as does a control that removes only the setting. Replacing the compare-and-swap with fetch_add was run ten consecutive times against the concurrency arm and reddened 10 of 10: nine times because the first reduced size logged was already 16, 32 or 64 instead of 128, once on the contiguity assertion (assert [128, 16, 8, 4, 2, 1] == [128, 64, 32, 16, 8, 4]). Two properties are measured over repeated runs rather than asserted once, because a single run of either mutant is not evidence of the rate. One qualification, so this row is not read as a claim of uniform green: in the last round one of the two full-file runs ended 1 failed, 8 passed, on the first case, at an assertion that reads the log once without waiting for the poll it looks for. That is a known weakness of the test rather than of the fix, and it is described with its remedy in the review comment on this PR.
f Fix is general across code paths? Yes, and the enumeration is in the description. Both size carriers are covered: streamToViews derives the block size, and the poll cap is installed as consumer state so subscribe's own terminal doPoll honours it too (a consume-only argument would leave the first poll after a failure uncapped, which is precisely the retry it targets). The cap is installed in popConsumer under the pool lock rather than by the caller, so no call site can install it after subscribe. A second carrier was found during review: StreamingFormatExecutor forwards every non-cancel exception to KafkaSource's on_error, which switched on the handle-error mode alone, so under stream and dead_letter_queue a memory limit was reported as a malformed message and the reduction never fired; all three modes now treat it the same way. StorageKafka2 was examined and is deliberately left unchanged, which is a scope decision rather than an omission: it is not a carrier of the size adaptation (experimental-gated, commits through Keeper with offset_guard, no intermediate_commit equivalent, different consumer class), and it cannot take the rethrow either, because KeeperHandlingConsumer::poll builds its rollback only inside if (message_sink(...)), so a throw out of the sink leaves no guard in existence and skips the messages the cycle had consumed. Measured on a commit containing no part of this change, in the default mode this branch does not touch: 16 of 256 rows delivered there against 256 of 256 for StorageKafka. kafka_commit_every_batch is excluded from both halves for one shared reason, that its offsets are committed mid-block and never rewound. Direct SELECT from Kafka is a non-carrier (hardcoded block size 1, no view push).
g Fix generalizes across inputs? Yes. The reduction is a shift on a row count, so it is independent of column types and formats. Boundaries are covered in code: each limit is floored at 1 rather than allowed to reach 0 (a zero-message poll would stall consumption), the shift is guarded against std::numeric_limits<size_t>::digits, and the stop condition is both derived limits reaching 1 rather than a hand-picked level cap, so it converges for an arbitrarily large configured value. kafka_num_consumers > 1 and kafka_thread_per_consumer = 1 are both exercised (test_concurrent_failures_reduce_one_step_at_a_time uses four consumers and a thread per consumer).
h Backward compatible? Yes. No new setting, no default change, no format or serialization change, so no SettingsChangesHistory.cpp entry is required. The configured values are unchanged and are what the reduction is derived from; a table that never hits the memory limit behaves exactly as before. Two behaviour changes, both in the changelog entry: a table which previously failed forever now runs at reduced throughput until it is re-attached, and under kafka_handle_error_mode = 'stream' or 'dead_letter_queue' a memory limit is redelivered instead of becoming an error row with its offset committed.
i Invariants and contracts preserved? Yes. The level only ever increases, by a compare-and-swap on the level the failing cycle actually used, so N concurrent cycles failing at one size produce one halving rather than 2^N of over-reduction (which would be permanent, since there is no automatic recovery). The reduction path allocates nothing before the rethrow. The error is rethrown unchanged, so the existing ~KafkaSource/markDirty redelivery contract and the offset-commit ordering are untouched, and delivery stays at-least-once exactly as before. kafka_commit_every_batch = 1 is excluded rather than assumed safe, because markDirty() calls only cleanUnprocessed() and rewindToLastCommitted() is reached only from the cancellation branch, so mid-block commits are not rewound on a pipeline throw.

Session id: cron:clickhouse-review-slot-8:20260826-133900

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2104b48]

Summary: ❌

job_name test_name status info comment
Stress test (arm_debug) FAIL
Logical error: 'Inconsistent AST formatting: the query: (STID: 1941-26fa) FAIL cidb

AI Review

Summary

This PR teaches StorageKafka to halve kafka_max_block_size and kafka_poll_max_batch_size after memory-limit failures, keeps memory-limit exceptions from being treated as bad messages in the non-default Kafka error modes, and adds focused integration coverage around the retry path. The core retry and redelivery logic looks coherent, but the new persistent throttling state is not surfaced clearly enough for operators.

Findings

⚠️ Majors

  • [src/Storages/Kafka/StorageKafka.cpp:823] reduction_level now survives every successful cycle until DETACH/ATTACH, but the only runtime hint is a per-cycle LOG_DEBUG message and a global KafkaBatchSizeReductions counter. On a normal log level, a transient memory spike can leave one Kafka table permanently slower with no table-specific explanation of the active reduced sizes or the recovery action. Emit a normal-level message when the CAS succeeds, or expose the current reduction in a per-table system surface.
Final Verdict
  • Status: ⚠️ Request changes
  • Add a normal-level, table-specific signal when the reduction level changes so operators can discover and reverse the persistent throttling state.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.30% 87.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 91/94 (96.81%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @NIKTONIKTO717 @kssenii, could you review this? A Kafka table whose block does not fit under the server memory limit used to retry the identical size on every cycle, so streamToViews now keeps a per-table reduction level and halves both kafka_max_block_size and kafka_poll_max_batch_size by it. A memory limit is also no longer reported as a bad message under kafka_handle_error_mode = 'stream' or 'dead_letter_queue', where it replaced a well-formed message with an error row and committed its offset.

`polled_batch_sizes(after=REDUCTION_LINE)` was the only in-window observation in
this file read without a deadline loop. The marker it anchors on is logged when a
reduced cycle starts, before that cycle builds its sources, so `Polled batch of N`
reaches the log later: 0.24 to 1.35 s later across twelve rotated logs here.
`wait_for_reductions` returns within its one-second cadence of the marker, so the
single read landed inside that window and the arm failed on an empty list even
though the poll had shrunk.

Both assertions are unchanged; only the read waits now, with the loop shape
`wait_for_delivery_at_reduced_size` already uses. The log is append-only and the
read happens no earlier than before, so it sees a superset of the polls the old
one saw and cannot assert over less.
Comment thread src/Storages/Kafka/KafkaSource.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2104b48e1 with master 6e6a2a508 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 712.30 MiB 709.24 MiB -3.05 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse ProfileEvents::global_counters_storage 12.06 MiB 12.12 MiB +64.00 KiB (+0.52%)
programs/clickhouse-keeper ProfileEvents::global_counters_storage 12.06 MiB 12.12 MiB +64.00 KiB (+0.52%)

Job report

A memory limit reaching KafkaSource's error callback was rethrown ahead of the
switch, so it skipped the `default` handling that names the topic, partition and
offset on the exception and records it in the per-consumer buffer that
system.kafka_consumers exposes. The background cycle still logs a generic
exception through StorageKafka::threadFunc, but a direct SELECT has no such
outer catch: the exception it raises is the only report, and it no longer said
which message was being read.

Handling a memory limit as `default` instead of bypassing the switch restores
both. KafkaMessagesFailed stays uncounted, since a memory limit is a state of
the server rather than a malformed message, and the callback is now identical to
before this pull request whenever kafka_handle_error_mode is already `default`.

Measured on the published head: `SELECT sum(length(value))` from a Kafka table
under `max_memory_usage` below one polled batch raised `Query memory limit
exceeded ... While executing Kafka` with no topic, partition or offset, and the
stack showed the limit was raised in StreamingFormatExecutor::insertChunk, which
is inside the callback.
Six of the ten cases failed in Integration tests (amd_asan_ubsan, flaky).

`max_server_memory_usage` was a fixed 2 GB and the headroom was computed against
tracked memory alone, but the global limit is also enforced against resident
memory. On the sanitizer build resident memory passes 2 GB during the second
case and does not come back down, so every later allocation on the global
tracker is refused: the job log shows 4.13 MiB tracked against 1.88 GiB resident
under a 1.86 GiB limit, rising to 2.6 GiB by the end of the module. The cases'
own reads got `Code: 241` and consumption stalled at 51 of 256 rows.

The limit is now pinned at runtime over whichever of tracked and resident memory
is larger, and released before anything the test reads for itself. It is applied
on `SYSTEM RELOAD CONFIG`, which is served even while the server is over its
limit.

Two related weaknesses of the same fixture: the headroom was larger than a full
block's payload (200 MiB against 128 MiB), so whether a block fit came down to
allocator overhead, and it is now half the payload; and a reading of resident
memory taken right after a heavy case can be several times the settled figure
(2.76 GiB decaying to 314 MB within three seconds), so the lowest of several
readings is taken.

`test_batch_size_is_reduced_after_memory_limit` also required a cycle at the
halved block size to deliver at most half a block. A block is only measured
against its size once the polled batch it is filling is drained, so it can
overshoot by almost a whole batch: the job log shows 155 rows at a block size of
128 with a poll batch of 32.
@groeneai

Copy link
Copy Markdown
Collaborator Author

The Integration tests (amd_asan_ubsan, flaky) red was mine, and the fixture was at fault rather than the change under test.

max_server_memory_usage was a fixed 2 GB and the headroom was computed against tracked memory alone, but the global limit is enforced against resident memory too. On the sanitizer build resident memory passes 2 GB during the second case and does not come back down: the job log shows 4.13 MiB tracked against 1.88 GiB resident under a 1.86 GiB limit, rising to 2.6 GiB by the end of the module. That is why the cases' own reads got Code: 241 and consumption stalled at 51 of 256 rows. The limit is now pinned at runtime over whichever of tracked and resident memory is larger, and released before anything the test reads for itself.

Two related weaknesses of the same fixture: the headroom was larger than a full block's payload (200 MiB against 128 MiB), so whether a block fit came down to allocator overhead, and it is now half the payload; and a reading of resident memory taken right after a heavy case can be several times the settled figure, so the lowest of several readings is taken.

One assertion was also wrong on its own terms: a cycle at the halved block size had to deliver at most half a block, but a block is only measured against its size once the polled batch it is filling is drained, so it can overshoot by almost a whole batch. The job log shows 155 rows at a block size of 128 with a poll batch of 32.

Full file green four times running locally, against one failure in five with the old headroom, and with the pin disabled no reduction is observed at all. I also merged master for the revert in #116566, which is what the Docs examples failure needed.

/// A concurrent cycle (`kafka_thread_per_consumer`) may have already halved the size this
/// one used; then the failure is about a size nobody uses any more and must not halve again.
size_t expected_level = used_level;
if (reduction_level.compare_exchange_strong(expected_level, used_level + 1))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reduction_level becomes persistent table state here: after one MEMORY_LIMIT_EXCEEDED the table keeps using smaller batches on every later cycle until DETACH/ATTACH. The only runtime hint is the LOG_DEBUG message earlier in streamToViews, and KafkaBatchSizeReductions is a global counter that does not tell an operator which table is still throttled or what sizes are active. On a normal log level, a transient memory spike can therefore leave one Kafka table permanently slower with no visible explanation or recovery hint.

Please emit a one-shot LOG_INFO/LOG_WARNING when this compare_exchange_strong succeeds (old/new block and poll sizes, table name, and that DETACH/ATTACH resets it), or expose the current reduction in a per-table system surface.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default log level is trace, so this line is visible in a stock install: programs/server/config.xml ships <level>trace</level>, and Loggers.cpp:124 falls back to trace when nothing is configured. Measured on a config with no <level> element: system.server_settings reports logger.level = trace and the log carries Debug lines.

What the line prints, taken from this PR's own integration-test server log:

<Debug> StorageKafka (test.kafka): Reading with reduced batch sizes after a memory limit error: block size 128, poll batch size 32. Re-attach the table to go back to the configured sizes.

It names the table, both active sizes and the reset action, and it is re-emitted every reduced cycle, so it is a standing indicator rather than a one-shot. The error that caused the reduction is separately logged at Error level by threadFunc and pushed into the per-consumer exception buffer system.kafka_consumers exposes, so a deployment hardened to information still gets a per-table explanation:

<Error> StorageKafka (test.kafka): void DB::StorageKafka::threadFunc(size_t) Code: 241. DB::Exception: (total) memory limit exceeded ... while parsing Kafka message (topic: ..., partition: 0, offset: ...)

So I am not switching to a one-shot line: it is weaker for the case described, because a single line at the transition rotates out of the log, after which nothing reports that the table is still throttled, while the per-cycle line stays in the recent window.

The second half of the suggestion is a real gap: there is no queryable per-table "currently reduced" state, system.kafka_consumers has no such column. That is a new surface rather than a correction to this change, so I leave it, and the log level, to a human reviewer. This is my third round on this PR and I stop here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2104b48

Every failure below has an owner: a fixing PR (ours 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
Stress test (arm_debug) / Logical error: 'Inconsistent AST formatting' (STID 1941-26fa) Trunk logical error, not caused by this PR: the server-side AST fuzzer inside the stress job emits a table-level PRIMARY KEY tuple(a) as an inline column attribute, which cannot parse back. 115 rows across 82 distinct PRs and 3 true-master commits over 30 days; this PR touches only src/Storages/Kafka #116645 (ours, open)

Session id: cron:our-pr-ci-monitor:20260827-140000

@clickhouse-gh clickhouse-gh Bot added the comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). label Sep 4, 2026
buggins added a commit to buggins/ClickHouse that referenced this pull request Sep 9, 2026
Review: ClickHouse#118544

`TableSettingOrigin::Runtime` is declared but nothing assigns it, which a reader
of a new user-facing enum is entitled to ask about. It is deliberate, so it now
says so.

It exists because a value that drifts while the server runs is the case
`SHOW CREATE TABLE` fundamentally cannot serve - that AST is only rewritten by
DDL - which is a large part of why this surface exists at all. The intended first
producer is ClickHouse#116522, which halves
`StorageKafka`'s `kafka_max_block_size` after a memory limit error and computes
the effective value at the use site instead of storing it. That pull request is
open, so the value is reserved rather than added afterwards: appending it later
would give it a number out of step with the order the enum documents, which is
the order the sources are applied in.

Also fills in a promise the statement documentation was already making.
`SHOW TABLE SETTINGS` describes its `source` column as "see `system.table_settings`
for the full list", and that table described the column only as "Where the value
came from" - the full list existed nowhere. It now enumerates all eight values,
and records three things a user would otherwise have to find out by experiment:

- `definition` covers `CREATE` and `ALTER` alike, because `ALTER ... MODIFY
  SETTING` rewrites the stored `CREATE` query and the two cannot be told apart;
- `shared_metadata` is what the table actually uses, even when its own `CREATE`
  query says otherwise;
- which origins an engine can report depends on the engine - only the `MergeTree`
  family reports `config` and `compatibility`, only `S3Queue` and `AzureQueue`
  report `shared_metadata`, and an engine that keeps no settings struct reports
  only `definition`.

Documentation only; no behaviour change. Note that no test asserts these
descriptions - `05056` captures column names and types, not comments - so the
text was verified by reading it back from `system.columns.comment` on a running
server.

Related: ClickHouse#116543

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DGgpj9TmsDY7PSPWevjpUM
buggins added a commit to buggins/ClickHouse that referenced this pull request Sep 20, 2026
`SettingOrigin::Runtime` was declared for a value an engine adjusts while it runs, with no producer and no test:
the case it was meant for, `StorageKafka` halving `kafka_max_block_size`, belongs to
ClickHouse#116522, which is not merged. Every other value of the enum has an
engine that reports it and a test that pins it, and a reserved value only invites the question why it is there.

It is reported as `other` until an engine reports it as its own source. The comment on `Other` says so, and
where such a value belongs when it returns: before `Other`, in the order the sources are applied in.

`other` becomes 6 rather than 7. Nothing stores these numbers - the enum exists to render the `source` column of
`system.table_settings`, `system.engine_settings` and `system.merge_tree_settings` - so the renumbering costs
only the generated column type in three test references.

Related: ClickHouse#59913
Related: ClickHouse#116543

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-kafka Kafka table engine: consumers and producers on librdkafka, the Kafka2 engine that keeps offsets i... and removed comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). labels Nov 19, 2026

This branch has not been deployed

No deployments
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 comp-kafka Kafka table engine: consumers and producers on librdkafka, the Kafka2 engine that keeps offsets i... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

KafkaEngine INSERTs on low memory systems (adaptive kafka_poll_max_batch_size)

1 participant