Repository navigation
Cherry pick #117754 to 26.9: Split an oversized chunk across several Arrow record batches - #128905
Merged
Merged
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]>
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]>
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]>
`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]>
`appendOpaqueColumnData` passed each serialized value straight to `arrow::StringBuilder`/`arrow::BinaryBuilder` through `Append(std::string_view)`. Those 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 value with no error. `checkStringSizeFitsArrowOffsets` already covered `String` and offsets-mode `FixedString`; it now also runs here, on the UTF-8-validated view in text mode and on the raw one in binary mode. It moved above its first user, which is earlier in the file. The row limit cannot help with this: it reports the whole range for a type with no Arrow equivalent, because only serializing its values reveals their encoded size. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The split had no test that fails without it. Reaching Arrow's own bound
needs more than 2 GiB of string data in one block, and the stateless
environment caps a process at 4.50 GiB total while a 2.1475 GB `chars`
array doubles into a 4 GiB allocation, so the old test could only be
killed:
05055_arrow_split_large_record_batch
Code: 241. (total) memory limit exceeded: would use 5.98 GiB
(attempt to allocate chunk of 4.00 GiB), current RSS: 2.19 GiB,
maximum: 4.50 GiB
`output_format_arrow_max_record_batch_size_bytes` lowers the bound, so
the same splitting runs on kilobytes. It defaults to Arrow's limit and
is capped there, which leaves behavior unchanged, and it joins the
`output_format_arrow_record_batch_size*` targets added in 26.9 - those
combine small blocks, this one splits large blocks, so a byte target can
now build a chunk that needs splitting.
Only the buffers Arrow addresses with 32-bit offsets are bounded. A
fixed-width column has none and stays in one batch, which the test pins
alongside the shapes that do split.
The gtest covers the Apache Arrow library writer, which no stateless
test can reach - it serves `ArrowFlight`, `StorageArrowFlight` and Delta
Lake writes. It asserts that every batch re-addresses its values from
zero, the property a row range not starting at row 0 depends on.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
# Conflicts: # src/Processors/Formats/Impl/CHColumnToArrowColumn.h
…rrent version 26.11 The setting is new in this PR and the branch is now on the 26.11 development cycle, so the `settings_changes_history` style check requires its history record to be under `26.11` rather than `26.10`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117754&sha=b0bfd667af1cb03007f85459387bc854c9fcf647&name_0=PR&name_1=Style%20check #117754 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…Batches` `arrow::ListArray::value_slice` returns a new `shared_ptr` by value; binding a reference to the dereferenced temporary left it dangling once the full expression ended, which ASan, TSan and MSan reported in the unit tests. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117754&sha=latest&name_0=PR&name_1=Unit%20tests%20(asan_ubsan) #117754 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Both writers measured the whole remainder of a chunk for every record batch. For a `Variant` (and `LowCardinality` with a large dictionary) that measure is linear in the rows given, so a chunk split into many batches cost quadratic time even when another column decided the split. The row limit of the next batch is now found over a window that starts at 8192 rows and doubles until it does not fit entirely: the limit of a prefix is the limit of the whole range capped at the prefix length, so the work stays proportional to the rows emitted. The `LowCardinality` shortcut uses the total dictionary size, which is O(1), instead of scanning the dictionary for its largest value on every call. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…Lake commits `VortexBlockOutputFormat::consume` and the Delta Lake commit recombined the table returned by `CHColumnToArrowColumn::chChunkToArrowTable` with `CombineChunksToBatch`. For a chunk split because it exceeds the 32-bit Arrow offsets that either fails to concatenate or keeps only the first chunk, so the split did not help these consumers. They now iterate the table's record batches: `Vortex` writes each one, and the Delta Lake commit adds each one to the transaction (an empty table still adds one empty batch, as before). `Vortex` also honours `output_format_arrow_max_record_batch_size_bytes`, which lets a test force the split at this consumer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Split an oversized chunk across several Arrow record batches
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Original pull-request #117754
Do not merge this PR manually
This pull-request is a first step of an automated backporting.
It contains changes similar to calling
git cherry-picklocally.If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.
The check results does not matter at this step - you can safely ignore them.
Before you resolve anything
Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.
Troubleshooting
If the conflicts were resolved in a wrong way
If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:
pr-cherrypicklabel from the PRYou also need to check the Original pull-request for
pr-backports-createdlabel, and delete if it's presented thereThe PR source
The PR is created in the CI job