Skip to content

Avoid a 4 KiB allocation per value when building a large literal IN list - #132227

Merged
Blargian merged 3 commits into
ClickHouse:masterfrom
groeneai:reserve-one-row-in-create-column-const
Nov 17, 2026
Merged

Blargian merged 3 commits into
ClickHouse:masterfrom
groeneai:reserve-one-row-in-create-column-const

Conversation

@groeneai

@groeneai groeneai commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #132144

Changelog category (leave one):

  • Performance Improvement

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

Building the constant of a large literal list such as x IN (v1, ..., vN) no longer allocates a 4 KiB buffer per value: a query with 10000 values in the list runs about 17% faster and uses about 38 MiB less memory.

Description

A literal list such as x IN (v1, ..., vN) becomes one Tuple constant with N one-row element columns. IDataType::createColumnConst created an empty column and then inserted the value, so the first push_back into every nested PODArray allocated its 4 KiB initial chunk: N allocations, about 40 MB for N = 10000, freed again with the query tree. DataTypeNullable::createColumnConst did the same for its nested column and null map. The analysis is from #132144.

The change reserves exactly one row before the insert (IColumn::reserve already recurses into tuple elements and nullable, array, map and low-cardinality parts) and creates the null map with its single value. Only the capacity of the one-row column changes.

Release build, 4M-row MergeTree tables, PR / master (95% CI), peak memory:

  • 10000 UInt64 keys in a primary key window: 0.825 (0.804-0.847), 51.0 -> 13.2 MiB
  • 10000 String keys: 0.813 (0.794-0.833), 58.1 -> 16.4 MiB
  • 1000 UInt64 keys: 0.880 (0.853-0.908)
  • set_index.xml doc: fix typo #4 (10000 String literals): 0.738 (0.717-0.760), 50.6 -> 12.9 MiB; Add Dockerfiles for client and server #8 (10000 pairs): 0.657 (0.648-0.666), 100.1 -> 24.1 MiB
  • controls: fix docs #6 (Array literal) 0.995 (0.984-1.006); 100 keys 0.972 (0.948-0.996)

Timing: one Release binary that switches the code path at runtime (measurement-only, not part of this PR), 12 fresh server processes per side in a crossover over 3 data directories, median of 25 runs per process; ratios PR / master with 95% CI over the 12 processes; an A/A pair on the same code path was within +-2.3%. The perf comparison covers this through tests/performance/set_index.xml queries #4/#5 (10000 literals) and #8/#9 (10000 pairs), with #6/#7 (Array literals) as controls.

No new test: no query result can change. About 1700 related stateless tests and an equivalence script over constants of 20 types gave the same results as master.


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

Version info

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

groeneai and others added 2 commits November 17, 2026 02:18
A literal list such as `x IN (v1, ..., vN)` becomes one `Tuple` constant with N
one-row element columns. `IDataType::createColumnConst` created an empty column and
inserted the value, so the first `push_back` of every nested `PODArray` went through
`reserveForNextSize` and allocated the 4 KiB initial chunk: N allocations, ~40 MB for
N = 10000, freed again with the query tree. `DataTypeNullable::createColumnConst` did
the same for the nested column and the null map.

Reserve exactly one row before the insert (`IColumn::reserve` recurses into tuple
elements, nullable/array/map/low-cardinality/object/dynamic parts), and create the
null map with its single value. Only the capacity of the one-row column changes.

Peak query memory (Release, median of 5): 10000 UInt64 keys in a PK window
51.0 -> 13.2 MiB, 10000 String keys 58.1 -> 16.4 MiB, set_index.xml ClickHouse#4
50.6 -> 12.9 MiB, ClickHouse#8 100.1 -> 24.1 MiB; queries without a literal list unchanged.

Closes ClickHouse#132144

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Rewrite the createColumnConst comment as an exact invariant (only PODArrays that grow by push_back get the 4 KiB initial chunk).

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding).

# Sev Finding Verdict Evidence / action
1 ❌ For an empty Array/Map constant, reserve(1) also reserves one nested element (ColumnArray::reserve -> getData().reserve(n)), e.g. 16 MiB for CAST([], 'Array(FixedString(16777215))') DISAGREE Mechanism right; not a regression outside one corner. Master: an empty array takes the 4 KiB offsets chunk. Change: exact offsets (~136 B) plus one element (~128-136 B per leaf column), less memory for every element type except FixedString(N) with N above ~3.8 KiB (or tuples of more than ~30 columns). The extra is at most one value of the type; master needs 32 MiB for any non-empty FixedString(16777215) value (chars.resize rounds up), the empty case takes 16 MiB with the change. A Field-driven reserve would be new machinery for this corner.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261117-041900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. system.query_log.memory_usage of the 10000 UInt64 key query is 51.02 MiB on master and 13.21 MiB with the change, identical on every one of 201 runs.
b Root cause explained? The literal list becomes one Tuple constant of N one-row columns built by createColumnConst (empty column, then insert); the first push_back into each empty PODArray allocates its 4 KiB initial chunk, so N values cost N x 4 KiB.
c Fix matches root cause? Yes. One row is reserved before the single insert with the existing IColumn::reserve; no global PODArray change, no guard.
d Test intent preserved / new tests added? No new test: the change is capacity-only, so no query result can change. Covered by tests/performance/set_index.xml #4/#5/#8/#9 (10000 literals / pairs) with #6/#7 (Array literals) as controls.
e Both directions demonstrated? Yes. Memory master vs PR as in (a); timing with one binary switching the code path at runtime, 12 fresh processes per side: 0.825 / 0.813 for 10000 UInt64 / String keys, A/A calibration 28/28.
f Fix is general across code paths? Both createColumnConst implementations that build the row by insert (IDataType, DataTypeNullable both branches and the null map). DataTypeObject delegates to IDataType for non-empty objects.
g Fix generalizes across inputs (params/datatypes/wrappers)? An equivalence script over constants of 20 types (Nullable value and NULL, Tuple, LowCardinality, Array, Map, JSON, Variant, Dynamic, Enum, Decimal, dates, UUID, IP, transform_null_in) returns byte-identical output on master and with the change.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or serialization change; only the capacity of a one-row column.
i Invariants and contracts preserved? A constant's nested column still holds exactly its one row with the same value and type; later appends grow by the normal doubling; if insert throws, the column is discarded as before.

Session id: cron:clickhouse-impl-slot-6:20261117-035800

@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [187d4a0]

Summary: ✅


AI Review

Summary

The PR reserves one row before inserting constant values in IDataType::createColumnConst and DataTypeNullable::createColumnConst, reducing allocation overhead for large literal IN lists. The reported timing and memory measurements support the performance claim. No actionable findings remain after reviewing the current code, diff, and prior discussion.

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 comp-data-types Type system & core datatypes used across query planning/execution. labels Nov 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2161730

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
Upgrade check (amd_release) / Logical error: Context has expired (STID: 1805-3f9b) not from this PR: the server that aborted is the previous release 26.10.4.207 in the stress phase, in FunctionKQLMultiply::executeImpl (FunctionKQLMultiply.cpp:83) on a 02366_kql_extend query with parallel replicas. Master has the fix (#131363), 26.10 does not yet. The same abort hit 18 other PRs in the last 7 days #132081 (external, open)
Upgrade check (amd_release) / Cannot count the mutations left unfinished by the stress phase, Cannot list the mutations left unfinished by the stress phase, Cannot list the row policies left by the stress phase, Cannot run the mutation entries left behind by the killed mutations, Cannot submit the mutation that has to survive the upgrade cascade of the abort above: the old server is gone (Connection refused on port 9000) #132081 (external, open)
Build profile diff infra, not from this PR (no ci/ file in the diff): all 8 readiness probes to the CI logs cluster hit Read timed out. (read timeout=3), so has_pr_data raised LogClusterNotReady: the endpoint never became ready. The same job errored on 49 PRs in the last 24 hours #129675 (mine, open)
Mergeable Check praktika rollup of the Upgrade check rows #132081 (external, open)
PR praktika rollup of the rows above #132081 (external, open), #129675 (mine, open)

The other CIDB FAIL row on this head is Config Workflow / Pre Hooks of the run before the can be tested label. CH Inc sync is green.

Session id: cron:our-pr-ci-monitor:20261117-073017

@Algunenano Algunenano self-assigned this Nov 17, 2026

@Algunenano Algunenano 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.

Really good improvement for such simple fix. Nice

@Algunenano
Algunenano enabled auto-merge November 17, 2026 11:20
@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 187d4a0a6 with master 72bf27d8f (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.

Compile time of recompiled translation units

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

Job report

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-data-types Type system & core datatypes used across query planning/execution. pr-performance Pull request with some performance improvements 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.

Large literal IN lists allocate 4 KiB per value when the analyzer builds the Tuple constant

4 participants