Skip to content

Split an oversized chunk across several Arrow record batches - #117754

Merged
alexey-milovidov merged 18 commits into
masterfrom
fix-arrow-big-string
Nov 3, 2026
Merged

alexey-milovidov merged 18 commits into
masterfrom
fix-arrow-big-string

Conversation

@Avogar

@Avogar Avogar commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

Closes: #65723

Arrow addresses its Utf8, Binary and List buffers with 32-bit offsets, so a chunk
holding 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:

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 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 done
separately behind its own setting.

RecordBatchEncoder encodes a row range rather than a whole column, so a split batch reads
its rows out of the chunk instead of copying a slice of it. That cuts the peak memory of
writing a 2 GiB String column from 10.4 GB to 4.4 GB. As a side effect, a chunk's dictionary
messages 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 ArrowFlight table
engine's insert path and DeltaLake writes, so all three get the fix.

Parquet and ORC were already unaffected — they no longer go through Arrow.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed Arrow, ArrowStream and Arrow Flight output failing with Capacity error: array cannot contain more than 2147483646 bytes or Arrow IPC string offset exceeds 32 bits when a block held more than 2 GiB of String data. Such a block is now written as several Arrow record batches.


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

Version info

  • Merged into: 26.11.1.1178-master (included in 26.11 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d54a60b]

Summary: ✅


AI Review

Summary

The PR splits oversized chunks into multiple Arrow record batches, encodes row ranges without copying whole slices, and preserves the batches through Vortex and Delta Lake consumers. Review of the current code and all prior discussion found no remaining actionable findings; the earlier concerns are addressed at d54a60b458ac231475b1e60cb83027585dcd6069.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or configured build was available. The current Praktika report indicates success, but its dedicated unit and stateless job entries expose no individual results. Execution results for the added split regressions would complete independent runtime validation.
Final Verdict

Status: ✅ Approve. No further code changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 2, 2026
@Avogar Avogar added pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed pr-performance Pull request with some performance improvements labels Sep 2, 2026
@zlareb1

zlareb1 commented Sep 2, 2026

Copy link
Copy Markdown
Member

Read the head (b33b28ee) end to end against the encoders — the split arithmetic itself looks exact (strict upper_bound against base + limit agrees with the encoders throwing only above MAX_ARROW_BUFFER_SIZE, the last partial batch is always emitted, progress is at least one row per iteration, and the ArrowIPC path's cut rebuilds String/Array offsets and LC dictionaries per batch). Two gaps, both fail-loud:

1. LowCardinality(FixedString(n)) is exempted from the split but is still written through int32 offsets when output_format_arrow_fixed_string_as_fixed_byte_array = 0. maxRowsForLowCardinality returns num_rows for any non-String dictionary type (ArrowBatchRowLimit.cpp:47-48) and never receives fixed_string_as_fixed_byte_array, but the encoder materializes the LC column (RecordBatchEncoder.cpp:595-601) and the offsets-mode FixedString arm then emits int32 offsets totalling num_rows * n and throws throwValueDoesNotFitArrowBuffer past the cap (RecordBatchEncoder.cpp:432-448). So a perfectly splittable multi-row LowCardinality(FixedString(n)) batch over 2 GiB still throws instead of splitting — the same error class the PR fixes — and the new "a single value cannot be larger than…" message plus the "only reachable for a single oversized row" comment are both wrong for this shape. Plain FixedString handles exactly this at ArrowBatchRowLimit.cpp:163-169 (capped at MAX / n in offsets mode); only the LC wrapper bypasses it, because the isString screen exits before the mode is consulted. The library/flight path is immune (it strips LC before estimating). Suggest threading fixed_string_as_fixed_byte_array into maxRowsForLowCardinality and applying the plain-FixedString cap to the materialized width; a test with LowCardinality(FixedString) over the threshold under output_format_arrow_fixed_string_as_fixed_byte_array = 0 would pin it.

2. The ArrowIPC caller runs the estimator on un-normalized columns. ArrowBatchRowLimit.h documents that ColumnConst and the sparse/replicated representations are not handled and callers materialize first; the CHColumn caller complies, but ArrowIPCBlockOutputFormat::consume estimates straight off the chunk. Today that is safe only via the pipeline invariant (MaterializingTransform from expectMaterializedColumns), while encodeField itself keeps defensive const/replicated materialization for exactly this class of caller (RecordBatchEncoder.cpp:576-593). If any future caller feeds a const String/Array/Variant column, the estimator's assert_cast is a bad-cast exception in debug and an unchecked cast in release, where the encoder alone would have handled it. Cheap to align: materialize (or unwrap const) before estimating, mirroring the encoder.

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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d54a60b45 with master e8ca7d358 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

525 object files changed (+129.18 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/ArrowBatchRowLimit.cpp.o new 22.36 KiB +22.36 KiB
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/CHColumnToArrowColumn.cpp.o 701.97 KiB 721.79 KiB +19.82 KiB (+2.82%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

3349 translation units recompiled, 17767 s compile time in total, 3347 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.5 s

Job report

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]>
protomn pushed a commit to protomn/ClickHouse that referenced this pull request Sep 16, 2026
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]>
Avogar and others added 2 commits September 16, 2026 13:11
`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]>

@nihalzp nihalzp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good.

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]>
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 3, 2026
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 3, 2026
alexey-milovidov added a commit that referenced this pull request Nov 4, 2026
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]>
alexey-milovidov added a commit that referenced this pull request Nov 4, 2026
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]>
robot-clickhouse-ci-2 added a commit that referenced this pull request Nov 4, 2026
Cherry pick #117754 to 26.8: Split an oversized chunk across several Arrow record batches
robot-clickhouse added a commit that referenced this pull request Nov 4, 2026
robot-clickhouse added a commit that referenced this pull request Nov 4, 2026
Cherry pick #117754 to 26.3: Split an oversized chunk across several Arrow record batches
robot-clickhouse added a commit that referenced this pull request Nov 4, 2026
robot-clickhouse added a commit that referenced this pull request Nov 4, 2026
Cherry pick #117754 to 26.9: Split an oversized chunk across several Arrow record batches
robot-clickhouse added a commit that referenced this pull request Nov 4, 2026
robot-clickhouse added a commit that referenced this pull request Nov 4, 2026
Cherry pick #117754 to 26.10: Split an oversized chunk across several Arrow record batches
robot-clickhouse added a commit that referenced this pull request Nov 4, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 4, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 4, 2026
Backport #117754 to 26.9: Split an oversized chunk across several Arrow record batches
clickhouse-gh Bot added a commit that referenced this pull request Nov 4, 2026
Backport #117754 to 26.10: Split an oversized chunk across several Arrow record batches
PedroTadim added a commit that referenced this pull request Nov 4, 2026
Backport #117754 to 26.3: Split an oversized chunk across several Arrow record batches
clickhouse-gh Bot added a commit that referenced this pull request Nov 7, 2026
Backport #117754 to 26.8: Split an oversized chunk across several Arrow record batches
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Missing way of dealing with out of capacity in Arrow and ArrowStream formats

7 participants