Skip to content

Compare nested Field containers in linear time - #116455

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix/nested-field-comparison-linear
Sep 19, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix/nested-field-comparison-linear

Conversation

@groeneai

@groeneai groeneai commented Aug 26, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Comparing two deeply nested Array, Tuple, Map or Object values doubled the work for every nesting level, because the ordering asked each equal element both whether it was less and whether it was greater. A single-value aggregate such as min, max, argMin, groupArraySorted or an -ArgMin combinator over a 30-level nested argument therefore ran for minutes on a few hundred rows, and could not be interrupted by max_execution_time. Such a comparison now visits each element once.

Description

Related: #110393 (same campaign, made Field copy and destroy linear in depth)

Found by CI: Stress test (amd_tsan) hung check, where one cancelled query sat for 464 s in PullingAsyncPipelineExecutor::cancel.

Root cause. Array/Tuple/Map aggregate values are stored as a Field, and SingleValueDataGeneric::setIfSmaller/setIfGreater order them with Field::operator<, whose container cases delegated to the container's own comparison. ClickHouse builds C++23, so std::vector's operator<=> is lexicographical_compare_three_way with std::__synth_three_way; Field has no operator<=>, so that helper takes its fallback and probes each element twice. On an element that compares equal both probes recurse to full depth, giving T(d) = 2*T(d-1): 2^(d+1)-1 calls where operator== needs d+1. Because PipelineExecutor checks cancellation only between work calls, a whole aggregation that fits in one block is one uninterruptible add, which is why the timeout never fired and the joining thread parked.

Change. A file-local three-way comparison in Field.cpp that visits each element once; the container cases of operator< and operator<= read its sign. Scalar branches are untouched, so every per-type rule (NaN placement, decimal rescaling, the types whose ordering throws) stays where it was. operator== is deliberately not routed through it: an aggregate-function state implements equality while refusing to be ordered, and a test arm pins that. No setting, no header change, no serialization change.

Validation. Reproduced and fixed on 25.8.33.6 and 26.8.1.2008 as well as master. Timing is now flat from depth 26 to 60. The aggregate-state wire format is byte-identical and reads across builds in both directions. A 339-test sweep over the aggregate, index and Top-K suites produced no output difference, and shallow-value timings are unchanged.

Which comparison paths were checked
carrier disposition
Field::operator< fixed (container cases)
Field::operator<= fixed (container cases); it shares the same recursion, so it was already linear once operator< was, and this removes the remaining second traversal
Field::operator> / operator>= defined as rhs < *this / rhs <= *this, fixed transitively, no separate definition
Field::operator== already linear, and deliberately left alone: equality and ordering are different relations for an aggregate-function state
Object (std::map) covered, its ordering is lexicographical over (key, value) pairs
SingleValueDataGeneric per-row and state-merge overloads both reach the fix, both have their own test arm
groupArraySorted sorts stored Fields, fixed transitively, has its own test arm (neither ORDER BY nor GROUP BY reaches it)
TopKThresholdTracker::compareFields probes operator< twice, fixed transitively; reachable by default for a nested fixed-size Tuple sort column. Results verified identical with the optimization on and off
FieldVisitorAccurateLess (index and KeyCondition) its same-type arm compares the raw containers, so the outermost pair is probed twice, while everything below it goes through the fixed Field::operator<: flat in depth, a factor of 2 where it was 2^depth. Rows and EXPLAIN indexes = 1 granule counts verified identical
min, max, argMin, argMax, -ArgMin/-ArgMax all order through the same holder, one fix covers them
any, anyLast, anyHeavy checked, not carriers: the first two store without comparing, anyHeavy compares only for equality

singleValueOrNull rejects nested arrays outright, so it cannot reach this shape.

No SQL path compares two Fields with <=, so that operator is covered by a unit test rather than a query.


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

Version info

  • Merged into: 26.10.1.235-master (included in 26.10 and later)

Ordering two nested `Array`/`Tuple`/`Map`/`Object` values doubled the work for
every nesting level, so a value 30 levels deep took minutes to compare and the
query holding it could not be interrupted.

Aggregate values of those types are stored as a `Field`, and
`SingleValueDataGeneric::setIfSmaller`/`setIfGreater` order them with
`Field::operator<` (`SingleValueData.cpp:1519`, `:1530`, `:1548`, `:1559`), whose
container cases delegated to the container's own comparison. This repository
builds C++23 (`CMakeLists.txt:327`), so `std::vector` exposes `operator<=>` as
`lexicographical_compare_three_way` with `std::__synth_three_way`; `Field` has no
`operator<=>`, so that helper takes its fallback branch
(`__compare/synth_three_way.h:36-41`) and asks each element both `t < u` and
`u < t`. On an element that compares equal both probes recurse to full depth,
giving T(d) = 2*T(d-1): 2^(d+1)-1 calls where `Field::operator==` needs d+1.
A task runs one `work` call at a time (`ExecutionThreadContext.cpp:58`) and
cancellation is observed only between those calls, so an aggregation that fits in
a single block becomes one uninterruptible add. That is why `max_execution_time`
(`PipelineExecutor.cpp:270-285`) did not fire in that shape, and why a cancelling
thread's `join` (`PullingAsyncPipelineExecutor.cpp:189`) parked for 464 seconds.

A file-local three-way comparison now visits each element once, and the container
cases of `operator<` and `operator<=` read its sign. `operator<` is the recursion
vehicle for all of them, so fixing it alone already makes the others linear;
`operator<=` is changed as well to drop the remaining second traversal and keep
both relational operators on one path. Scalar branches are untouched, so NaN
placement, decimal rescaling and the types whose ordering throws keep a single
definition, which is also why the helper's non-container arm still probes both
directions. `operator==` is deliberately not routed through it: an
aggregate-function state implements equality while its ordering operators throw,
and conflating the two would either break a working query or make a deliberately
unordered value orderable.

The unit test counts the probes a comparison makes on one leaf, separately per
container arm, so it pins one visit per direction at any depth rather than merely
rejecting the exponential shape, and it pins the equality-versus-ordering
contract over a container of aggregate states.

Reproduced and fixed on 25.8.33.6 and 26.8.1.2008 as well as master. Timing is
flat from depth 26 to 60, the `Array(AggregateFunction)` state stays byte
identical and readable across builds in both directions, and sort results and
`EXPLAIN indexes = 1` granule counts are unchanged.

No SQL path compares two `Field`s with `<=`, so that operator is covered by the
unit test rather than a query.

Found by the amd_tsan stress hung check on
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116173&sha=8088404fcca82c830153c78795093e1edc97da0d&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Aug 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two rounds. Round 1 raised two test-liveness findings against ca5d430; both agreed and fixed. Round
2 raised none.

⚠️ The complexity oracle was weaker than the contract. Completion at a fixed nesting depth
rejects the exponential comparison but admits any sub-exponential one, and only the Array chain was
depth-tested, so a doubling reintroduced in the Tuple, Map or Object arm alone would have
escaped. Replaced by a probe-counting CustomType leaf: the ordering probes reaching the leaf are now
asserted to be exactly 2, independently of depth, for all four container types and for both < and
<=. Two controls. Restoring the doubling reddens all 8 assertions at exactly 1048576 probes
(Array/Tuple/Object at depth 20, Map at depth 10, since a Map level pairs with a Tuple
level). Reintroducing it in the Object arm alone reddens that assertion at the same count while the
other three stay at 2, and on that binary the old completion test still reports [ OK ] in 0 ms
while the probe test reports [ FAILED ]. So the gap was real, not hypothetical.

⚠️ One SQL arm did not reach the code it claimed to pin. min([sumState(...)]) throws while the
aggregate function is constructed, because Array(AggregateFunction(...)) is not comparable
(IDataType::isComparable defaults false, DataTypeArray delegates to its nested type,
AggregateFunctionMinMax's constructor rejects it), so it never entered Field ordering. The
equality half was genuinely covered by the anyHeavy arm, which does reach Field::operator==; the
ordering half was covered by nothing. Added a unit test asserting that a container of aggregate states
compares for equality while < and <= throw ILLEGAL_TYPE_OF_ARGUMENT, and corrected the SQL
test's comment to state what its arm actually pins. Control: routing operator== through the ordering
helper fails exactly one test, the new one, on its equality assertion.

💡 Also corrected: two off-by-one source citations and one mis-pointed citation in the commit message,
and inline-code formatting of identifiers per the repository's agent rulebook.

Two fix-plan items were deliberately not carried out, both recorded with measurements. The plan's
stated reason for changing operator<= was wrong: operator< is the recursion vehicle, so <= was
already linear once < was. The change is kept for the second traversal it removes and for keeping
both operators on one path, and the description claims nothing more. Two prescribed KeyCondition and
Top-K arms were dropped after being built and shown to have no detection power, since the ordering
break they were meant to catch is caught by the arms that ship and escapes those two byte-identically.
Their consumers are listed in the description instead.

Session id: cron:clickhouse-review-slot-10:20260826-072500

@clickhouse-gh clickhouse-gh Bot closed this Aug 26, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on demand: SET max_block_size = 1; SELECT sumArgMin(1, materialize([[...30 levels...1]])) FROM numbers(200). Never finishes without the change (>90 s already at depth 26), 0.41 s with it. Reproduced on the official 25.8.33.6 and 26.8.1.2008 builds as well as a master debug build.
b Root cause explained? SingleValueDataGeneric::setIfSmaller/setIfGreater order stored container values with Field::operator<, whose container cases delegated to std::vector's comparison. Under C++23 that is lexicographical_compare_three_way with std::__synth_three_way, and Field has no operator<=>, so the helper falls back to asking each element both t < u and u < t. On an element that compares equal both probes recurse to full depth: T(d) = 2*T(d-1), counted as 2^(d+1)-1 calls against d+1 for operator==.
c Fix matches root cause? Yes. The recurrence is removed where it arises, by comparing each element once. Not a widened bound, not a no-random-* tag, not a smaller dataset, and not a guard at the PullingAsyncPipelineExecutor::cancel site where the symptom appeared. A cancellation checkpoint inside the aggregate loop was considered and rejected: the cost sits inside a single add call that a between-rows checkpoint cannot preempt.
d Test intent preserved / new tests added? No existing test weakened or removed. New stateless test 05044_deeply_nested_field_comparison_linear (12 arms) plus three unit tests in src/Core/tests/gtest_field.cpp. Every arm was justified by building a mutant: reverting operator< makes the stateless test produce zero output, inverting the length tiebreak changes one arm's result, and writing <= 0 as < 0 fails the unit test. Completion at a fixed depth only rejects the exponential shape, so a second unit test counts the probes a comparison makes on one leaf and requires exactly one per direction, per container arm, at any depth. That count is what catches a doubling reintroduced in a single arm: with the Object arm alone made to probe both directions, the probe test fails at 1048576 probes while the completion test still passes in 0 ms. Two further arms were prepared and then dropped because a mutant proved them strictly weaker than the arms already present.
e Both directions demonstrated? Yes, per arm. Without the change, five of the six deep arms do not finish and the sixth takes 14.32 s; with it the whole file runs in 0.64 s. Timing is flat from depth 26 through 60.
f Fix is general across code paths? operator< and operator<= both changed; operator>/operator>= are defined in terms of them and have no separate definition; Object (a std::map) is covered. Both SingleValueDataGeneric overloads, per row and on state merge, reach the change and each has its own arm. operator== is deliberately excluded, because an aggregate-function state implements equality while refusing to be ordered. A unit test pins that split directly, over a flat and a nested container: equality succeeds, and both < and <= throw ILLEGAL_TYPE_OF_ARGUMENT. Routing operator=='s container cases through the new helper makes only that test fail, on the equality assertion. The stateless min([sumState(...)]) arm does not pin it, because a non-comparable type is refused while the aggregate function is constructed, before any comparison runs. Downstream consumers verified unchanged: groupArraySorted, TopKThresholdTracker::compareFields, and FieldVisitorAccurateLess on the index path.
g Fix generalizes across inputs (params/datatypes/wrappers)? Array, Tuple, Map, Object; Nullable and NULL elements; nan; LowCardinality elements; elements of differing types, ordered by type tag; differing and empty lengths; depths 26, 30, 40, 60; and shallow depth 1 to 2. singleValueOrNull rejects nested arrays outright, so it cannot reach this shape.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no default change and no format change, so no SettingsChangesHistory.cpp entry applies. The Array(AggregateFunction) state is byte-identical before and after (0101080200000000000000) and reads across builds in both directions. Ordering results are unchanged, so sort output and index pruning are stable: an 11-arm comparison over Top-K and KeyCondition is byte-identical, including EXPLAIN indexes = 1 granule counts.
i Invariants and contracts preserved? The comparison remains a strict weak ordering; antisymmetry and the equal case are asserted directly for equal, greater and shared-prefix pairs. Pure comparison: no allocation, no locking, no ownership change and no new error path, and the only throw is the pre-existing one on an unreachable default. Recursion depth is unchanged from the code it replaces. Scalar branches are untouched, so NaN placement, decimal rescaling and the types whose ordering throws keep a single definition.

Session id: cron:clickhouse-impl-slot-6:20260826-062900

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7d560a8]

Summary: ✅


AI Review

Summary

This PR replaces the container branches of Field::operator< and Field::operator<= with an explicit one-pass comparator so nested Array/Tuple/Map/Object values no longer pay the C++23 double-probe recursion cost at every level. The change preserves the existing scalar ordering rules, keeps equality separate from ordering for aggregate-function states, and adds focused unit plus stateless coverage for the aggregate and merge paths that motivated the fix. I did not find a remaining correctness, compatibility, or validation gap in the current code.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 7d560a8.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.80% +0.10%

Changed lines: Changed C/C++ lines covered: 131/146 (89.73%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @yariks5s, could you review this? Ordering two nested containers held in a Field was exponential in nesting depth: this repository builds C++23, Field has no operator<=>, so std::vector's comparison falls back to std::__synth_three_way, which asks each element both t < u and u < t, and on an equal element both probes recurse to full depth. A file-local three-way comparison now visits each element once; the scalar branches are untouched, so NaN placement, decimal rescaling and the types whose ordering throws keep a single definition.

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7d560a81d with master b8cd25afc (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
Binary Master PR Δ
programs/clickhouse-stripped 712.33 MiB 709.27 MiB -3.06 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

The `min` arm of `05044_deeply_nested_field_comparison_linear` expects
`ILLEGAL_TYPE_OF_ARGUMENT`, but `min([sumState(toUInt64(6))])` nests one
aggregate function inside another. That shape is rejected by
`assertNoAggregates` with `ILLEGAL_AGGREGATION` (thrown at
`src/Interpreters/GetAggregatesVisitor.h:68`) while the query tree is
rewritten, before `AggregateFunctionMinMax` is constructed, so with the old
analyzer the comparability check at
`src/AggregateFunctions/AggregateFunctionsMinMax.cpp:31-36` was never reached
and the arm got code 184 instead of 43.

Reading the state from a subquery removes the nesting. The arm then reaches
the comparability check with the same message everywhere, which also makes the
comment above it accurate: the type is refused while the aggregate function is
constructed, before any row is compared.

Verified with one binary, Build-ID `07510793e8c42c136c5b44f6a8cc0701031602f4`.
On an old-analyzer server the shipped arm fails with the exact CI message and
the new arm passes; 20 runs with randomized settings pass under each analyzer;
the output stays byte-identical to the `.reference`. Expecting
`ILLEGAL_AGGREGATION` instead, or dropping the annotation, both fail, so the
assertion is live.
Comment thread src/Core/Field.cpp Resolved
@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

The PR run on 45ac748 was cancelled: 21 of 175 lanes finished with no
verdict, including Build (arm_release), Unit tests (msan) and three
integration shards, so that head cannot produce a result. Re-running the
workflow via the API returns HTTP 403 for this account, so a new head is the
only way to re-dispatch. The merge also picks up ClickHouse#116566, which fixes the
Docs examples failure that the previous head reported.
`Bugfix validation (unit tests)` runs a PR's touched unit tests against the
merge-base binary, where at least one must fail to prove it catches the bug.
Ordering a nested `Field` costs 2^levels there, and both new tests nested past
the point that terminates: the `Field` suite ran for 4 hours and the job was
killed (exit -15) instead of reporting a reproduction.

Depth 12 in both. The `Map` chain adds a `Map` and a `Tuple` level per step, so
that arm costs 2^24 probes on the merge-base binary, where depth 30 meant 2^60.

`DeeplyNestedComparisonVisitsEachElementOnce` asserted nothing about the cost it
was named after (at depth 60 the only signal was that the comparison never
returned), so shrinking it would have left the name claiming a property nothing
checks. Renamed to `NestedContainerOrdering`, which is what it does assert; the
visit count stays with `DeeplyNestedComparisonProbesEachLeafOnce`, which counts
probes on one leaf and so does not depend on timing at all.

Measured, debug, one build dir: the merge-base `Field.cpp` at depth 12/12 runs
the whole `Field` suite in 296 ms and fails exactly the probe test (Array 4096,
Tuple 4096, Map 16777216, Object 4096 probes against the expected 2); the fixed
`Field.cpp` passes 10/10 in 91 ms. The two tests catch disjoint regressions:
reverting the container arms reddens only the probe test, and flipping the sign
of the size-mismatch branch reddens only `NestedContainerOrdering`.
@clickhouse-gh clickhouse-gh Bot added the comp-data-types Type system & core datatypes used across query planning/execution. label Sep 4, 2026

@alexey-milovidov alexey-milovidov 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.

Very good!

@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit c92bd75 Sep 19, 2026
180 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
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. groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-bugfix Pull request with bugfix, not backported by default 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.

4 participants