Repository navigation
Compare nested Field containers in linear time - #116455
alexey-milovidov merged 4 commits into
Conversation
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
Internal second-model reviewTwo rounds. Round 1 raised two test-liveness findings against
💡 Also corrected: two off-by-one source citations and one mis-pointed citation in the commit message, Two fix-plan items were deliberately not carried out, both recorded with measurements. The plan's Session id: cron:clickhouse-review-slot-10:20260826-072500 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260826-062900 |
|
Workflow [PR], commit [7d560a8] Summary: ✅
AI ReviewSummaryThis PR replaces the container branches of Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 7d560a8.
Changed lines: Changed C/C++ lines covered: 131/146 (89.73%) · Uncovered code |
|
cc @alexey-milovidov @yariks5s, could you review this? Ordering two nested containers held in a |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units7 translation units recompiled, 8 s compile time in total, 7 of them have a recent master baseline. |
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.
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`.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Comparing two deeply nested
Array,Tuple,MaporObjectvalues 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 asmin,max,argMin,groupArraySortedor an-ArgMincombinator over a 30-level nested argument therefore ran for minutes on a few hundred rows, and could not be interrupted bymax_execution_time. Such a comparison now visits each element once.Description
Related: #110393 (same campaign, made
Fieldcopy 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/Mapaggregate values are stored as aField, andSingleValueDataGeneric::setIfSmaller/setIfGreaterorder them withField::operator<, whose container cases delegated to the container's own comparison. ClickHouse builds C++23, sostd::vector'soperator<=>islexicographical_compare_three_waywithstd::__synth_three_way;Fieldhas nooperator<=>, so that helper takes its fallback and probes each element twice. On an element that compares equal both probes recurse to full depth, givingT(d) = 2*T(d-1):2^(d+1)-1calls whereoperator==needsd+1. BecausePipelineExecutorchecks cancellation only betweenworkcalls, a whole aggregation that fits in one block is one uninterruptibleadd, which is why the timeout never fired and the joining thread parked.Change. A file-local three-way comparison in
Field.cppthat visits each element once; the container cases ofoperator<andoperator<=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
Field::operator<Field::operator<=operator<was, and this removes the remaining second traversalField::operator>/operator>=rhs < *this/rhs <= *this, fixed transitively, no separate definitionField::operator==Object(std::map)SingleValueDataGenericper-row and state-merge overloadsgroupArraySortedFields, fixed transitively, has its own test arm (neitherORDER BYnorGROUP BYreaches it)TopKThresholdTracker::compareFieldsoperator<twice, fixed transitively; reachable by default for a nested fixed-sizeTuplesort column. Results verified identical with the optimization on and offFieldVisitorAccurateLess(index andKeyCondition)Field::operator<: flat in depth, a factor of 2 where it was2^depth. Rows andEXPLAIN indexes = 1granule counts verified identicalmin,max,argMin,argMax,-ArgMin/-ArgMaxany,anyLast,anyHeavyanyHeavycompares only for equalitysingleValueOrNullrejects 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
26.10.1.235-master(included in26.10and later)