Repository navigation
Conversation
ArrowIPCBlockOutputFormat::consume wrote exactly one record batch per incoming
chunk, and nothing squashes on the SELECT ... FORMAT path:
markOutputFormatPrefersLargeBlocks("ArrowStream") is only consulted through
IStorage::prefersLargeBlocks() on the INSERT path. A selective query therefore
emitted one small batch per scanned block, and the fixed FlatBuffers metadata
and buffer padding of each batch dominated the payload. On the reported example,
SELECT number FROM numbers(268435456) WHERE number % 65536 = 0 FORMAT
ArrowStream produced 721,040 bytes in 4,096 one-row batches; at
output_format_arrow_record_batch_size = 65409 and
output_format_arrow_record_batch_size_bytes = 1048576 it produces 16,728 bytes
in one batch, byte-identical to a hand-written single-batch encoding of the
same rows.
consume becomes a staging front end and its former body moves verbatim into
writeChunk, which is also the seam PR ClickHouse#117754 rewrites to split an oversized
chunk, so either merge order is a mechanical rebase and the two compose in the
right order: accumulate up to the target, then split what a single batch still
cannot address.
Sub-target chunks are appended into one accumulator built from
cloneEmptyColumns() rather than from the first chunk: FilterTransform passes
result_size_hint = -1, so ColumnVector::filter reserves the whole source block
and resize_exact does not release it, and adopting the first chunk would make
the accumulator carry that reservation for the lifetime of every batch. A chunk
that already reaches a target flushes what is staged and is then written
un-copied, which keeps a large block out of the accumulator and bounds a
combined batch below twice the target; gating that branch on an empty
accumulator instead would let a few staged rows absorb a 1,048,449-row INSERT
block.
The size is measured on the materialized chunk because ColumnConst::byteSize
reports one stored value, and materializeChunk is a precondition of appending
at all: MessageQueueSink drives this writer through IOutputFormat::write with
no MaterializingTransform in front of it, and appending into an accumulator
cloned from a ColumnConst would advance the row count without copying values.
The targets bound the accumulated data as Chunk::bytes() measures it, on the
same terms as min_insert_block_size_bytes, not retained memory: a
LowCardinality shared dictionary and an aggregate state's foreign arenas sit
outside that measure. Measured against blocks made equally large with
max_block_size instead, the accumulator adds between -1.0 and +1.7 MiB for a
1 MiB target.
The precedent and the refuted alternative, for the record:
output_format_parquet_row_group_size_bytes stages on the cruder
chunk.allocatedBytes() (ParquetBlockOutputFormat.cpp:121) and under-counts
LowCardinality the same way, because byteSize() counts the deduplicated
dictionary once while the encoder writes one value per row unless
output_format_arrow_low_cardinality_as_dictionary is set. Summing each incoming
chunk's bytes as Squashing does was rejected, not overlooked:
ColumnLowCardinality::filter keeps the whole source dictionary and filters only
the indexes (ColumnLowCardinality.h:126-130), so over the 4,096 one-row chunks
this change exists to combine, that sum over-counts by about the chunk count and
would flush at the first one. The byte setting's description states the measure
and advises pairing it with the row criterion.
Both settings default to 0, which is byte-identical to the previous behaviour,
and SettingsChangesHistory records 0 -> 0 so compatibility below 26.9 keeps it.
Closes: ClickHouse#119815
Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model reviewAn independent cold review plus a second model reviewed this change over two rounds before it was ❌ Fixed: the byte target published a bound it did not deliver for
💡 Noted, not blocking: the byte setting's wording covers the private-dictionary case only. Both 💡 Noted, not blocking. The dictionary-delta and |
|
Workflow [PR], commit [b54c79b] Summary: ❌
AI ReviewSummaryThis PR adds Findings
Final Verdict
LLVM Coverage ReportMeasured on commit b54c79b.
Changed lines: Changed C/C++ lines covered: 78/79 (98.73%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260913-232400 |
`ColumnLowCardinality::byteSize` counts one index per row plus each distinct value once, and nothing at all for the values while the dictionary is still shared with the block the column came from (ColumnLowCardinality.h:196-197, and the empty-plus-shared adoption at ColumnLowCardinality.cpp:245-250). That has two consequences for `output_format_arrow_record_batch_size_bytes` and only one of them was documented: - a batch of repeated values encodes to more than the target, because the record batch writes one value per row; - a block filtered out of a larger one keeps that block's dictionary, so it can reach the target on its own. Measured on a four-block fixture with one surviving row per block: the byte target ends every batch at that single row and combines nothing, and since whichever target is reached first ends a batch, it also ends the batches a paired row target would have combined. This is the accounting of `min_insert_block_size_bytes`, which the setting documents itself against: `Squashing::oneMinReached` uses the same `Chunk::bytes` measure, the same per-chunk pre-check and the same disjunction of the two criteria (Squashing.cpp:395-411), and it produces identical block counts on that fixture in all three configurations. The behaviour is therefore unchanged; the setting now states what it counts, and 05211 pins both halves with a `String` control and the row-target remedy beside them. The `staged` comment no longer claims the accumulator holds none of the source block's allocations, which the shared-dictionary path would falsify.
Build profile diff (arm_release)Comparing commit See the job log for details. |
| if (!staged.getNumRows()) | ||
| /// Empty columns rather than the chunk itself: a filtered column keeps the capacity reserved for | ||
| /// its whole source block, which the accumulator would then hold for the lifetime of every batch. | ||
| staged.setColumns(chunk.cloneEmptyColumns(), 0); | ||
| staged.append(chunk); |
There was a problem hiding this comment.
Why not just staged = std::move(chunk) when the accumulator is empty, and staged.append(chunk) otherwise? Neither reason in the comment seems to justify copying the first chunk of every batch. The capacity a filtered column retains is one source block's worth, and Chunk::bytes sums byteSize, not allocatedBytes, so it never affects the flush criterion. And where an inherited size does end a batch early, the result is one record batch per block, which is the previous behaviour and exactly what the early-out above already accepts for a LowCardinality block keeping its source dictionary. Cloning empty does not reliably prune that dictionary either: ColumnLowCardinality::insertRangeFrom adopts the source dictionary wholesale when the target is empty and the source dictionary is shared and structurally compatible, which is the usual case for a column read from storage, so the accumulator ends up holding the same bytes a moved-in chunk would. Moving instead drops a full copy of the first chunk, which is up to half the copied volume when blocks sit just under the target, plus that chunk's per-row dictionary remap. It looks safe: Chunk::append goes through mutateColumns, which clones only a genuinely shared column, and insertRangeFrom calls compactIfSharedDictionary before mutating a shared dictionary.
There was a problem hiding this comment.
Adopted in 8483e2a: staged = std::move(chunk) on the empty path, staged.append(chunk) otherwise, and both stated reasons are out of the comment.
Your two refutations hold by measurement, not only by reading:
- Output unchanged. 18 fixtures (both targets, dictionary-encoded output, filtered / nested / nullable
LowCardinality, a table-backedWidepart written with one dictionary for the whole part, and theArrowfile footer) produce byte-identical payloads with identical batch boundaries before and after. - An inherited size does not move the criterion. Worst case I could build for the retained reservation: 8 blocks of 8192 rows x 10 KB, materialized and then filtered to one surviving row each, with a row target no accumulation reaches, so the first surviving chunk is held for the whole query. Peak RSS 344,988 KiB before vs 345,160 KiB after, and the
max_memory_usagethreshold is the same on both (each completes at 100 MiB and each throwsCode: 241at 80 MiB). - No write-through. Checked on the reachable shape where the producer keeps the columns, a
Memorytable whose source hands the chunk the stored block's own columns: contents unchanged after its rows are dumped as one combined batch, and a second dump byte-identical to the first.
What it buys, on the shape where the dropped copy is a per-row dictionary remap rather than a memcpy (high-cardinality LowCardinality(String), blocks one row under the row target, 4M rows): 0.38 s against 0.43 s wall and 0.39 s against 0.46 s CPU, best of 7 alternating runs, debug build. On a wide String result the difference is below the noise floor, the copy there being a bulk memcpy next to the constant expansion and the encode.
The matching sentence in the description is updated as well.
`consume` cloned empty columns and appended the first chunk of every batch into them; it now takes that chunk itself and appends only the chunks that follow. Neither reason for the copy holds: the capacity a filtered column retains is one source block's worth, and `Chunk::bytes` sums `byteSize`, not `allocatedBytes`, so it never reaches the flush criterion; where an inherited size does end a batch early, the result is one record batch per block, which is the previous behaviour and what the early-out above already accepts for a `LowCardinality` block keeping its source dictionary. The output is unchanged. 18 fixtures covering both targets, the dictionary-encoded path, filtered, nested and table-backed `LowCardinality` (including a wide part written with one dictionary for the whole part) and the `Arrow` file footer produce byte-identical payloads before and after, with the same batch boundaries. Appending into the adopted chunk cannot write through to another holder, because `Chunk::append` mutates through `IColumn::mutate`, which clones a column that is still shared. Checked on the reachable shape rather than by reading: a `Memory` table, whose source hands the chunk the stored block's own columns, is unchanged after its rows are dumped as one combined batch, and a second dump is identical to the first. On a high-cardinality `LowCardinality(String)` result with blocks one row under the row target, where the dropped copy is a per-row dictionary remap rather than a memcpy, 4M rows take 0.38 s instead of 0.43 s (best of 7 alternating runs, debug build). On a wide `String` result the difference is below the noise floor.
|
I’ve cleaned up the setting docs and added the streaming/memory caveat in this commit. Could you cherry-pick it into this branch? Documentation only; no behavior changes. |
|
@groeneai see my comment above and also resolve conflicts with master |
Describe buffering, streaming latency, and `LowCardinality` size caveats. Carried over unchanged from EmeraldShift/ClickHouse@88d7dbf, requested in ClickHouse#119873 (comment). Every statement was checked against the shipped behaviour before carrying it. Co-authored-by: Michael Jarrett <[email protected]>
The repository asks for `f` rather than `f()` where the text names a function itself instead of applying it (.claude/CLAUDE.md). `numbers`, `numbers_mt` and `ColumnLowCardinality::byteSize` are named, not called, in these three comments. Co-Authored-By: Claude Opus 5 <[email protected]>
…-batch-coalescing-119815 # Conflicts: # src/Core/SettingsChangesHistory.cpp
|
Both done, in Your docs commit is carried over in Master is merged in |
|
@Avogar or @tavplubix, any chance this PR can be backported to stable or LTS releases? It's a rather nice fix for some bad performance regression when we switched to using |
I am ok to nackport it, it's a small isolated change, the only complication is backporting settings, but I will take care of it. |
CI finish ledger - 3faa2b6Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260915-013207 |
CI finish ledger - b54c79bEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task CI is fully finished on this head: 176 checks, 153 pass, 20 skipped, 2 failed,
Session id: cron:our-pr-ci-monitor:20260915-190256 |
fbf1886
|
It will be hard to backport to 26.3 and 26.6 because there is no Arrow IPC writer there, and it will require porting this ris to the legacy Arrow writer, which I don't want to do. |
|
26.7+ is perfectly fine -- we run 26.7 for the cluster most impacted by this change. |
The only conflict is `src/Core/SettingsChangesHistory.cpp`: master records
the two new settings under `26.9`, a block that does not exist on this
release branch. Drop the incoming block and record
output_format_arrow_record_batch_size
output_format_arrow_record_batch_size_bytes
under `26.8` instead, the branch's current version block, which is what
`check_settings_changes_history` in ci/jobs/check_style.py requires.
Everything else applies unchanged: the resulting diff against the release
branch is the original change, entry for entry.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…onflicts `src/Core/FormatFactorySettings.h`, `src/Formats/FormatFactory.cpp` and `src/Formats/FormatSettings.h`: both sides add lines at the same place. Keep both - 26.7 still selects between the two Arrow writers through `input_format_arrow_use_native_reader` and `output_format_arrow_use_native_writer`, which master has since removed. `src/Processors/Formats/Impl/ArrowIPC/ArrowIPCBlockInputFormat.cpp`: take the release branch's version. 26.7 does not yet embed the format documentation in the source, so the two rows the change adds to the `Arrow` and `ArrowStream` settings tables have nowhere to go. `src/Core/SettingsChangesHistory.cpp`: master records the two new settings under `26.9`, a block that does not exist here. Drop the incoming block and record them under `26.7`, the branch's current version block, which is what `check_settings_changes_history` in ci/jobs/check_style.py requires. The writer itself applies unchanged. Note that the record batch targets only take effect with the native writer, so they are ignored when `output_format_arrow_use_native_writer = 0`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Cherry pick #119873 to 26.7: Combine small blocks into one Arrow IPC record batch on output
Cherry pick #119873 to 26.8: Combine small blocks into one Arrow IPC record batch on output
Backport #119873 to 26.7: Combine small blocks into one Arrow IPC record batch on output
Backport #119873 to 26.8: Combine small blocks into one Arrow IPC record batch on output
Closes: #119815
Related: #117754
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added
output_format_arrow_record_batch_sizeandoutput_format_arrow_record_batch_size_bytes, which make theArrowandArrowStreamoutput formats combine consecutive blocks that are individually smaller than the target into a single record batch. A selectiveSELECTproduced one small record batch per scanned block, and the fixed metadata and buffer padding of each batch then dominated the payload. Both settings default to0, which keeps the previous behavior of one record batch per block. Closes #119815.Description
ArrowIPCBlockOutputFormat::consumewrote one record batch per incoming chunk, and nothing squashes on theSELECT ... FORMATpath:markOutputFormatPrefersLargeBlocks("ArrowStream")is consulted only on the INSERT path, throughIStorage::prefersLargeBlocks. On the reported example,SELECT number FROM numbers(268435456) WHERE number % 65536 = 0 FORMAT ArrowStreamproduces 721,040 bytes in 4,096 one-row batches; atoutput_format_arrow_record_batch_size = 65409, output_format_arrow_record_batch_size_bytes = 1048576, 16,728 bytes in 1 batch, byte-identical to a hand-written single batch.consumenow stages sub-target chunks into one accumulator, and its former body moved verbatim intowriteChunk. A chunk that already reaches a target flushes what is staged and is then written as it stands, so a large block is never copied or merged and a combined batch holds fewer than twice the target rows. The byte target measures the accumulated block, asmin_insert_block_size_bytesdoes, not the encoded batch, and for aLowCardinalitycolumn the two differ by the deduplication factor in both directions; the setting documents that and points at the row target. The first chunk of a batch becomes the accumulator itself, so assembling one costs a copy less.#117754 adds a maximum on the same seam and rewrites the body this moves into
writeChunk, so either merge order rebases mechanically.Both default to
0, where the output is byte-identical to before (cmp). Measured at 1 MiB: the repro's first batch reaches the client after 186 ms instead of 1 ms, while its total drops from 262 to 186 ms; peak memory rises by up to 7 MiB where blocks already filled a batch, the cost of the bigger batch rather than of the accumulator.If you would rather have it on by default (65409 / 1 MiB), say so.
Workflow [PR]
Sync PR [sync-upstream/pr/119873]
Version info
26.8.7.6,26.7.11.7