Repository navigation
Split an oversized chunk across several Arrow record batches - #117754
Conversation
Arrow addresses its `Utf8`, `Binary` and `List` buffers with 32-bit
offsets, so a chunk holding more than 2 GiB of string data (or more than
2^31 list elements) cannot be written as a single record batch. Both
writers used one batch per chunk and failed on such a chunk:
SELECT randomString(40000) FROM numbers(60000) FORMAT ArrowStream
Arrow IPC string offset exceeds 32 bits. (TOO_LARGE_ARRAY_SIZE)
SELECT count() FROM arrowFlight('127.0.0.1:8890',
'(SELECT randomString(40000) AS s FROM numbers(60000))')
Error with a Arrow column "String": Capacity error:
array cannot contain more than 2147483646 bytes, have 2147520000.
Both now split such a chunk into as many batches as it needs, which is
transparent to readers and keeps the schema on 32-bit offsets, so the
output stays readable by every Arrow implementation.
`maxRowsFittingOneArrowBatch` computes how many rows fit one batch. It
walks the column structure rather than the data: a binary search over
`ColumnString` offsets, an offsets translation plus recursion for
`Array`/`Map`, `min` over `Tuple` elements, and nothing at all for the
fixed-width types. `LowCardinality` and `Variant` need a row scan, but
of integers only. Two top-level columns never share a buffer, so the
smallest per-column limit is the batch's limit.
The `String` encoder no longer assembles the data buffer in a temporary
when the column has no null map: the bytes of the range are contiguous
in `ColumnString::getChars()` and the ClickHouse offsets already are the
Arrow ones, so they go straight into the body. With a null map the
temporary is reserved up front instead of grown by doubling. This cuts
the peak memory of writing a 2 GiB String column from 10.4 GB to 6.3 GB.
Closes: #65723
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [d54a60b] Summary: ✅
AI ReviewSummaryThe PR splits oversized chunks into multiple Missing context / blind spots
Final VerdictStatus: ✅ Approve. No further code changes requested. |
|
Read the head ( 1. 2. The ArrowIPC caller runs the estimator on un-normalized columns. |
The previous wording claimed the result is only ever conservative. That is wrong when `LowCardinality` is written as an Arrow dictionary: the emitted dictionary bytes do not depend on the row count, because `ColumnLowCardinality::insertRangeFrom` keeps a shared source dictionary whole, so every slice re-emits all of it. A chunk whose dictionary alone exceeds one buffer is therefore not covered by splitting - as it was not before splitting existed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`LowCardinality(FixedString(n))` was exempted from the row limit because
only a `String` dictionary can hold a variable-width value. But a writer
materializes the column, and with
`output_format_arrow_fixed_string_as_fixed_byte_array = 0` the resulting
`FixedString` goes through 32-bit offsets, so a multi-row batch over the
cap threw instead of splitting:
SELECT toFixedString(toString(number % 3), 100000)
::LowCardinality(FixedString(100000))
FROM numbers(21475)
SETTINGS output_format_arrow_fixed_string_as_fixed_byte_array = 0
FORMAT ArrowStream
Cannot write a value of 2147500000 bytes to Arrow IPC ...
`maxRowsForLowCardinality` now receives the mode and applies the plain
`FixedString` cap to the materialized width.
`buildArrowListArrayWithArrayColumnData` narrowed the *absolute*
`ColumnArray` offsets to int32 before rebasing them against
`values_start`. That was equivalent while every range started at row 0,
but a split feeds it a non-zero start, so offsets `[1500000000,
2300000000]` rejected the second batch even though its rebased slice
`[0, 800000000]` fits one `List` buffer. The offsets stay 64-bit and the
limit is now checked on the rebased value, where it applies.
The error message and the comment above it claimed only a single
oversized row could reach the throw, which the `LowCardinality` shape
above disproves.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes525 object files changed (+129.18 KiB total), 1 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units3349 translation units recompiled, 17767 s compile time in total, 3347 of them have a recent master baseline. Translation units without a recent master baseline:
|
Splitting an oversized chunk cut every column for each batch, because
`RecordBatchEncoder` could only encode a whole column from row 0. For a
2 GiB `String` column that held three copies of the data at once - the
chunk, the cut, and the body - and the stateless test hit the container
memory limit in CI:
05055_arrow_split_large_record_batch.sh: line 18: Killed
SELECT number, repeat('x', 100000) FROM numbers(21475)
FORMAT ArrowStream
The encoder now takes `[begin, end)` throughout, so a batch reads its
rows straight out of the chunk. Peak memory for that test drops from
10.4 GB before any of this work, to 6.3 GB, to 4.4 GB.
Offsets have to be rebased against the row before the range: `String`
against `offs[begin - 1]`, `List`/`Map` against `ch_offsets[begin - 1]`
(and the range translated into the child's element range), and a dense
union's offsets against each alternative's own start, which comes from
the same per-discriminator scan `ColumnVariant::updateHashWithValueRange`
uses. Only `Const`, `ColumnReplicated` and `LowCardinality` still cut,
which is cheap: those cuts resize a constant or slice indexes without
copying values.
`consume` now substitutes dictionaries once per chunk rather than once
per batch, so a chunk's dictionary messages precede all of its record
batches instead of interleaving with them.
Verified by building with `MAX_ARROW_BUFFER_SIZE = 24` to force splits on
small data and round-tripping the whole type matrix, checking the batch
counts with pyarrow.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
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]>
`fillArrowArrayWithStringColumnData` passed `static_cast<int>(size)` to
the builder. Arrow's `Utf8`/`Binary` builders take an int32 length and
`BaseBinaryBuilder::Append` guards the copy with `if (length > 0)`, so a
value above the int32 range narrowed to a negative length, skipped both
`ValidateOverflow` and the copy, and was then marked valid - the row was
written as an empty string with no error.
A single value over the limit is reachable from SQL, e.g.
`concat(repeat(repeat('x', 2048), 524288), repeat(repeat('y', 2048), 524288))`
is 2147483648 bytes, and the row limit cannot split one row, so the
`Arrow` library path needs the check. There is no `Append` overload that
preserves the length: the `std::string_view` one narrows identically.
`String` and offsets-mode `FixedString` share the helper, so both are
covered. The comment claiming Arrow rejects such a row is corrected.
Also pin `max_block_size` in the regression test. The harness randomizes
it over `randint(8000, 100000)`, and a value below 21475 splits the
source into smaller ClickHouse blocks, so no Arrow batch exceeds the
limit and the round-trip passes without exercising a split.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Upstream replaced the writer's fallback for types with no Arrow mapping: `encodeAsBinary`, which copied `IColumn::getDataAt` bytes, became `encodeAsOpaque`, which serializes each value through `ISerialization` and picks `Utf8` or `Binary` via `arrowOpaqueValueIsText`. The setting `output_format_arrow_unsupported_types_as_binary` became the enum `output_format_arrow_unsupported_types`. Resolved by keeping the row range this branch threads through the encoder and taking upstream's serialization logic on top, indexing `begin + i` in the loop. `maxRowsFittingOneArrowBatch` no longer measures that bucket. Its `getDataAt` loop would now throw for the columns upstream's comment names - `ColumnObject`, `ColumnVariant` and `ColumnQBit` - which `serializeText` handles, and the `haveMaximumSizeOfValue` shortcut under-counts in text mode, where a fixed-width value can serialize to more characters than it occupies. Bounding the encoded size means serializing twice, so the range is reported whole and the encoder rejects a batch that overflows. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Resolve conflicts by applying only the intent of #117754 on top of the 26.8 tree: - `output_format_arrow_max_record_batch_size_bytes` is declared in the 26.8 style and recorded in `SettingsChangesHistory.cpp` under 26.8. - 26.8 has `output_unsupported_types_as_binary` and `encodeAsBinary` instead of the master `ArrowUnsupportedTypes` / `encodeAsOpaque`; `encodeAsBinary` now takes a row range. - `CHColumnToArrowColumn::Settings::output_max_record_batch_bytes` is the last member, so existing designated initializers stay valid. - The `Vortex` output format does not exist in 26.8: drop its change and the `05484_vortex_record_batch_split` test. - The DeltaLake per-batch commit drops the master-only `delta_lake_commit_fail_before_log_write` failpoint. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve conflicts of the backport of #117754 against the 26.9 release: - `output_format_arrow_max_record_batch_size_bytes` is declared without the inline history entry (26.9 keeps it in `SettingsChangesHistory.cpp`, added there under 26.9), and without the mention of `Vortex`. - `Vortex` does not exist in 26.9: drop the `VortexBlockOutputFormat.cpp` change and the `05484_vortex_record_batch_split` test. - 26.9 has no opaque (`output_format_arrow_unsupported_types`) writer, so the row-range change is applied to its `encodeAsBinary` in `RecordBatchEncoder` and the per-value size check to `fillArrowArrayWithRawColumnData` in `CHColumnToArrowColumn`. - `CHColumnToArrowColumn::Settings` gets `output_max_record_batch_bytes` next to the 26.9 fields. - `WriteTransaction::commit` adds each record batch on its own, keeping the 26.9 code around it (no failpoint). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cherry pick #117754 to 26.8: Split an oversized chunk across several Arrow record batches
Cherry pick #117754 to 26.3: Split an oversized chunk across several Arrow record batches
Cherry pick #117754 to 26.9: Split an oversized chunk across several Arrow record batches
Cherry pick #117754 to 26.10: Split an oversized chunk across several Arrow record batches
Backport #117754 to 26.9: Split an oversized chunk across several Arrow record batches
Backport #117754 to 26.10: Split an oversized chunk across several Arrow record batches
Backport #117754 to 26.3: Split an oversized chunk across several Arrow record batches
Backport #117754 to 26.8: Split an oversized chunk across several Arrow record batches
Closes: #65723
Arrow addresses its
Utf8,BinaryandListbuffers with 32-bit offsets, so a chunkholding more than 2 GiB of string data cannot be written as a single record batch. Both Arrow
writers used one batch per chunk and failed on such a chunk:
Both now split such a chunk into as many record batches as it needs. This keeps the schema on
32-bit offsets, so the output stays readable by every Arrow implementation — unlike switching
to
LargeUtf8/LargeBinary, which the issue also asks for and which is better doneseparately behind its own setting.
RecordBatchEncoderencodes a row range rather than a whole column, so a split batch readsits rows out of the chunk instead of copying a slice of it. That cuts the peak memory of
writing a 2 GiB
Stringcolumn from 10.4 GB to 4.4 GB. As a side effect, a chunk's dictionarymessages are now emitted once for the chunk rather than once per batch.
The Apache Arrow library writer is shared by the Arrow Flight server, the
ArrowFlighttableengine's insert path and DeltaLake writes, so all three get the fix.
ParquetandORCwere already unaffected — they no longer go through Arrow.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
Arrow,ArrowStreamand Arrow Flight output failing withCapacity error: array cannot contain more than 2147483646 bytesorArrow IPC string offset exceeds 32 bitswhen a block held more than 2 GiB ofStringdata. Such a block is now written as several Arrow record batches.Workflow [PR]
Sync PR [sync-upstream/pr/117754]
Version info
26.11.1.1178-master(included in26.11and later)