Repository navigation
Reduce the Kafka streaming batch size after a memory limit error instead of retrying the same size - #116522
Reduce the Kafka streaming batch size after a memory limit error instead of retrying the same size#116522groeneai wants to merge 12 commits into
Conversation
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]>
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 Left in, with the remedy
Declined, with the evidence
Session id: cron:clickhouse-review-slot-8:20260826-133900 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-8:20260826-133900 |
|
Workflow [PR], commit [2104b48] Summary: ❌
AI ReviewSummaryThis PR teaches Findings
Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 91/94 (96.81%) · Uncovered code |
|
cc @NIKTONIKTO717 @kssenii, could you review this? A |
`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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units17 translation units recompiled, 66 s compile time in total, 17 of them have a recent master baseline. Symbol sizes
|
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.
…aptive-batch-size-on-memory-limit
|
The
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 |
| /// 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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
CI finish ledger - 2104b48Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260827-140000 |
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
`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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A
Kafkatable streaming into materialized views now halveskafka_max_block_sizeandkafka_poll_max_batch_sizeafter a cycle fails withMEMORY_LIMIT_EXCEEDEDorCANNOT_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: withkafka_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 withkafka_commit_every_batch = 1are unchanged in both respects. Closes #116167.Description
A
Kafkatable whose block does not fit under the server memory limit raisesCode: 241, and the next cycle attempts the same work: nothing records that the size was too large.streamToViewsnow keeps a per-table reduction level and halves bothkafka_max_block_sizeandkafka_poll_max_batch_sizeby it, each from its own configured value, floored at 1, as #98810 does forS3Queue. Both must shrink:KafkaSourcenever 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 = 1is 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.KafkaSourcealso rethrows a memory error out of itson_errorcallback:StreamingFormatExecutorroutes 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.StorageKafka2is 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,RabbitMQandFileLogswallow a memory limit the same way and each needs its own redelivery analysis.Adds
ProfileEventKafkaBatchSizeReductions. 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]