Skip to content

Batch JSON and Dynamic columns in merges with merge_use_batch_sorting_queue - #131486

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/merge-batch-dynamic-json
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/merge-batch-dynamic-json

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #127826
Related: #108468

Changelog category (leave one):

  • Performance Improvement

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

Merges with merge_use_batch_sorting_queue enabled now insert runs of rows of JSON and Dynamic columns at once instead of one row at a time, still respecting merge_max_block_size_bytes, whenever the values keep their storage in the merged part (no value moves between dynamic paths or variants and the shared data). A merge of interleaved parts of a table with a 20-path JSON column takes about 0.7 of the time.

Description

#127826 lets the batch sorting queue batch LowCardinality columns under merge_max_block_size_bytes; columns with a dynamic structure stayed row by row because the source rows' byteSizeAt can underestimate how much the merged block grows. Its review asked for a safe upper bound for JSON / Dynamic (#127826 (review)).

A merge fixes the dynamic structure of the merged column (chooseDynamicStructureForMerge). When every path and variant of a source chunk is in the merged column, its rows are copied as they are and the merged column only adds a default, a 1-byte discriminator and an 8-byte offset, to each dynamic path the source lacks. extraBytesPerInsertedRow returns that bound for a column pair. It returns nullopt, which keeps the row-by-row insertion, when a value could move to or from the shared data or the shared variant, or when a JSON value inside a Dynamic column lacks a path. The bound is computed once per source chunk in MergingSortedAlgorithm, and per batch only after a destination column was wrapped in ColumnReplicated. It is exact, so merged parts are byte-identical to master unless the table also has a LowCardinality column, whose estimate from #127826 can end blocks at other rows.

Validation: gtests (the 9-byte default by equality; batch == row-by-row; 1,000 paths with 8,000 empty objects batch 1,165 rows at 10 MiB; the fallback shapes stay at 1 row; per-chunk refresh; late replicated chunk) and a performance test. Release build, OPTIMIZE ... DRY RUN, ratio PR / master over 15 rounds: 20-path JSON 0.69, parts with 5 of 20 paths 0.66, Dynamic 0.79, arrays of objects 0.68, 1,000 paths 0.86 (same peak memory as the default queue), runs of 3 / 2 rows 0.81 / 0.92, shapes that fall back 0.85-1.02.


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

groeneai and others added 3 commits November 13, 2026 22:24
…ueue sizes a batch

`MergedData::rowsToInsertBeforeFlush` inserted every row of a merge with a `JSON` or `Dynamic`
column one by one when `merge_max_block_size_bytes` is set, because the sum of the source rows'
`byteSizeAt` can underestimate the growth of the merged block. A merge fixes the dynamic structure
of the merged column (`chooseDynamicStructureForMerge`), so when every path and variant of the
source is in the merged column the rows are copied as they are, and the merged column only adds
a default (a 1-byte discriminator and an 8-byte offset) to each dynamic path the source lacks.
`extraBytesPerInsertedRow` returns that bound for a (merged, source) column pair, recursing into
typed and dynamic paths, variants, `Array` (exact only), `Map`, `Nullable` and `Tuple`, and
nullopt when a value could move between the regular storage and the shared data or the shared
variant, which keeps the row-by-row insertion for those sources. In the bounded case the bound is
exact, so blocks end at the same rows as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The bound from `extraBytesPerInsertedRow` depends only on the structure of the merged column, which a
merge fixes in `initialize`, and on the structure of the source chunk, which does not change while the
chunk lives. Evaluating it for every batch cost more than batching saved when parts interleave in runs
of 2 or 3 rows (merges 1.12x and 1.37x slower than master), and for every row of a run whose source
falls back to row-by-row insertion (up to 1.29x).

`MergingSortedAlgorithm` now keeps the bound per source in `source_extra_bytes_per_row`, refreshed in
`initialize` and `consume` where `source_row_filter_masks` is, only for the batch queue with a byte
limit (the default queue and query-time merges never read it), and passes it to
`rowsToInsertBeforeFlush`. A destination column can still be wrapped in `ColumnReplicated` during a
merge, so once `may_have_replicated_columns` is set the bound is recomputed for every batch.

`OPTIMIZE ... DRY RUN PARTS`, release build, ratio to master over 15 paired rounds: runs of 3 / 2 rows
0.81 / 0.92 (were 1.12 / 1.37), shapes that fall back 0.85-1.02 (were up to 1.29), 20-path JSON 0.69.
Merged parts are byte-identical to master.

The keys of the late-replicated-chunk test interleave so that neither queue passes a chunk through
whole: wrapping an empty destination in `ColumnReplicated` gives it 8-byte indexes
(`ColumnIndex::insertIndexesRange(0, 0)`), which would make the two queues' blocks differ for a reason
unrelated to the bound.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A row of a `Dynamic` column fills one variant (NULL rows none), so taking
the maximum of the variants' bounds charged a growing variant's defaults to
the rows of every other variant. Reachable with a `JSON` variant whose
values lack a path of the merged `JSON` variant (the merge fixes the
structure of variants too): the bound was conservative, so the batch queue
ended blocks earlier than row-by-row insertion. Return 0 only when no source
variant grows, nullopt (row by row) otherwise.

The new gtest builds a `Dynamic` column alternating `Int64` and `JSON`
values: with a missing path the batch is 1 row (row by row 46, the old
maximum gave 38); with all paths the batch equals row by row (44).

Remove 05632_merge_batch_sorting_queue_dynamic: it compared batch-on and
batch-off merge results, which are equal with or without this change, so it
could not fail. The batching is covered by the MergedData gtests and the
performance test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds)
Finding Verdict
⚠️ Round 1: the Dynamic bound took the maximum over variants, so rows of a variant that does not grow were charged another variant's defaults (conservative, not exact) Agreed, fixed: a Dynamic pair is bounded only when no variant grows, otherwise row by row; new gtest DynamicVariantsThatGrowDifferentlyAreInsertedOneByOne
⚠️ Round 1: the stateless test compared batch-on and batch-off results, which are equal with or without this change Agreed, removed: batching is covered by the gtests (batch == row-by-row, red on master) and the performance test
⚠️ Round 1: the branch conflicted with #127826 after it was merged Fixed: rebased; its predicate rename and its LowCardinality estimate are kept
Round 2 (rebased head, full re-review) No findings

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: on master rowsToInsertBeforeFlush returns 1 for every batch with a JSON/Dynamic column; the gtests fail there (1 row vs 2 / 8 / 13 / 476 / 1,165 rows inserted one by one before the flush).
b Root cause explained? Yes: the source rows' byteSizeAt can underestimate the merged block's growth, so the special case returned 1. A merge fixes the merged column's dynamic structure, so when values keep their storage the growth is exactly byteSizeAt plus 9 bytes per dynamic path the source lacks.
c Fix matches root cause? Yes: the bound is applied only where it holds (values keep their storage); every other shape keeps the row-by-row path. The byte limit is honoured with the same block boundaries.
d Test intent preserved / new tests added? Yes: gtests (9-byte default by equality, batch == row-by-row, 1,000 paths, moving shapes and a growing Dynamic variant stay at 1 row, per-chunk refresh, late replicated chunk) and a performance test.
e Both directions demonstrated? Yes: master red, PR green; 8 mutations (zero default size, dropped guards, no refresh in consume, no recompute after a replicated wrap, a per-variant maximum for Dynamic) each turn their test red, and controls stay green.
f Fix is general across code paths? Yes: both chunk-arrival sites refresh the bound, the replicated wrap recomputes it, and every caller of rowsToInsertBeforeFlush must pass it (no default value).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes: Object typed and dynamic paths, Dynamic variants, Array (exact only), Map, Nullable, Tuple; LowCardinality, AggregateFunction, ColumnReplicated and unknown kinds keep today's path.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, default or format change; merged parts are byte-identical to master unless the table also has a LowCardinality column (batched by #127826's estimate); the default queue and query-time merges are unchanged.
i Invariants and contracts preserved? Yes: the bound is exact for every bounded pair (a Dynamic pair is bounded only when no variant grows), and the bound used for a batch equals the one computed from that batch's columns (fixed merged structure, immutable source chunks, refresh on every chunk, recompute after a replicated wrap).

Session id: cron:clickhouse-impl-slot-7:20261113-222100

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5b2c1b5]

Summary: ✅


AI Review

Summary

This PR batches JSON and Dynamic rows when their destination growth can be bounded, preserving the byte limit and row-by-row insertion for storage conversions. No actionable findings. The focused regression tests and reported before/after benchmarks support the change; local tests were not run because this checkout has no build.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors labels Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5b2c1b56f with master d011c6b84 (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

19 object files changed (+36.67 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Merges/Algorithms/MergedData.cpp.o 74.04 KiB 96.20 KiB +22.16 KiB (+29.93%)

711 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

34 translation units recompiled, 417 s compile time in total, 34 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.14 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +57.3 s (+16%) in total before that adjustment.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Nov 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b58e76b

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, iceberg_local, 1/3) / Insert historical data perf CI harness, the same signature in all six Iceberg jobs: this PR adds tests/performance/merge_batch_sorting_queue_dynamic.xml, so these jobs run only that test, no query of it is measured on both servers, and compare.sh stops before it writes report/all-query-metrics.tsv (FileNotFoundError, Errors while building the report.) #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_local, 2/3) / Insert historical data same as the first row #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_local, 3/3) / Insert historical data same as the first row #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_s3, 1/3) / Insert historical data same as the first row #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_s3, 2/3) / Insert historical data same as the first row #129874 (mine, open)
Performance Comparison (arm_release, master_head, iceberg_s3, 3/3) / Insert historical data same as the first row #129874 (mine, open)

The Config Workflow / Pre Hooks failure in CIDB comes from the run before the can be tested label was added. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261114-043009

groeneai and others added 2 commits November 16, 2026 15:58
…h-dynamic-json

Resolve the conflicts with the `[[nodiscard]]` attributes of ClickHouse#126158 in
`MergedData.h` and `MergingSortedAlgorithm.h`, and mark the new const getters
`extraBytesPerRow` and `maxBlockSizeBytes` `[[nodiscard]]` as well, since
master now enables `modernize-use-nodiscard`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…iguration

The test measures merges of MergeTree parts with `JSON` and `Dynamic` columns,
which the Iceberg rewrite of `perf.py --table-engine` cannot keep
(`Column json of type JSON has no Iceberg equivalent`), so the six
`Performance Comparison (*, iceberg_*)` jobs it scheduled measured nothing.
Opt it out with `<test iceberg="0">` rather than the skip list, which is one
of `ICEBERG_PERFORMANCE_PATHS` and would run the whole Iceberg suite instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@clickhouse-gh clickhouse-gh Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AI review approves this commit, see the AI Review comment.

@clickhouse-gh clickhouse-gh Bot added comp-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 20, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant