Repository navigation
Fix quadratic reallocation while building h3 array results - #115773
alexey-milovidov merged 3 commits into
Conversation
h3kRing, h3ToChildren, h3PolygonToCells and h3PolygonToCellsWithContainment
reserved the result accumulator once per row:
dst_data.reserve(dst_data.size() + vec_size);
dst_data is a ColumnUInt64 &, and ColumnVector::reserve is reserve_exact,
which reallocs to exactly the requested size. Capacity therefore landed
exactly on the current size at every row, the next row reallocated, and the
whole accumulated array was copied each time: Theta(n^2).
A Stress test (amd_asan_ubsan) hung check caught this with one query at
elapsed 838 s against its own max_execution_time = 10, having written 0
rows, with the working thread inside __memmove_sse2_unaligned_erms under
asan_realloc under FunctionH3KRing::executeImpl. That is about 11.6 TB of
memmove for the 196 227 rows involved, which matches the 838 s. Peak memory
was only 102 MB, so the query was never short of memory.
Reserving through PODArray::reserve rounds capacity up to a power of two,
so the copying is amortized O(n). IColumn::reserve is documented as
affecting performance only, and reserve_exact is the right semantics for
the many callers that reserve a final size once, so the four per-row
callers are the defect rather than the primitive.
Cancellation was already delivered on the reported query (is_cancelled = 1)
and ExpressionTransform already checks it once per action, but the whole
838 s sat inside a single IFunction::executeImpl, so no action boundary was
reached again. Removing the quadratic factor is what lets that existing
check fire.
Validated under ASAN, which is where the defect is measurable: a Debug
build is linear on the same query because glibc realloc can extend the
block in place, consistent with every occurrence in CI being a sanitizer
job. Unfixed, the reported query does not finish in 400 s; fixed it returns
the same result in 4.8 s, and unfixed scaling is a clean quadratic (2.7 /
6.2 / 21.1 / 81.7 s as rows double from 2 000 to 16 000). All four
functions were measured in both directions, and reverting only the h3kRing
line returns that arm to a timeout. Results are byte-identical before and
after, including invalid cells, mixed valid and invalid rows, Nullable,
LowCardinality and zero, one and two row inputs. Peak memory rises about
1.45x, the expected cost of geometric growth.
The new test fails on unfixed master with TIMEOUT_EXCEEDED and passes in
25 s. Its oracle is completion under a per-statement max_execution_time
rather than an elapsed-time assertion.
s2GetNeighbors.cpp has the same shape but reserves a constant 4 elements
per row, a much weaker exposure in a different area, so it is left alone.
The last arm of 04910 was introduced to show that a row producing no cells does not shift the offsets of its neighbours, but both cells it passed were valid, so no row was empty and the arm only repeated the earlier length() assertions. Pass an invalid cell index on either side of a valid one under functions_h3_default_if_invalid, which makes h3kRing take the `continue` branch that writes dst_offsets[row] without appending to the accumulator. The expected 0, 7, 0 then distinguishes correct offset bookkeeping from a shift. The setting is required: without it an invalid cell throws INCORRECT_DATA instead of yielding an empty row, which was verified so the arm cannot silently degrade into an exception test.
The regression test gave all four carriers a max_execution_time arm at 40 s. Two of them cannot support a timing claim: the polygon functions spend far more compute per output cell, so reaching a useful unfixed/fixed ratio costs tens of seconds of fixed time on its own. Keep the oracle on h3kRing and h3ToChildren, which reach it cheaply, and let the two polygon arms assert values only, at sizes that run in well under a second. Each polygon arm asserts a non-zero sum, so it still has to grow the accumulator to pass. The whole file drops from 24.9 s to 1.3 s. The limit is 15 s rather than 40 s because max_execution_time is only observed at a block boundary: the unfixed arm aborts after its first 65 409-row block at about 63 s, not at the 126 s the statement would take, and that time is flat in the limit (measured at 5, 10 and 20 s). Redden margin is therefore 63/L, which leaves only 1.6x at 40 s. At 15 s the fixed arms use 0.14-0.21 s, so the margins are 73x against a flaky pass and 4.2x against failing to redden. max_block_size stays pinned on the timing arms: the accumulator is rebuilt per block, so the cost is linear in the block size and the runner randomizes it between 8000 and 100000. Reverting only the h3kRing line on the otherwise-fixed tree reddens the first arm while the second still passes, so the two arms are independent oracles.
Internal second-model review (click to expand)Three review rounds against an independent model, plus my own cold read of the tree each round.
Both prior rounds' timing-margin concern was raised twice and is fixed rather than overridden. The Session id: cron:clickhouse-review-slot-10:20260821-104700 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260821-095200 |
|
Workflow [PR], commit [b86bdb0] Summary: ✅
AI ReviewSummaryThis PR switches the four touched H3 array builders from exact Missing context / blind spots
Findings
Final VerdictChanges requested: the H3 fix looks good, but the already-open LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 16/20 (80.00%) · Uncovered code |
|
cc @nikitamikhaylov @scanhex12, could you review this? The four h3 array-building functions call |
|
|
||
| dst_data.reserve(dst_data.size() + vec_size); | ||
| /// Go through PODArray::reserve: it grows capacity geometrically, IColumn::reserve sizes it exactly. | ||
| dst_data.getData().reserve(dst_data.size() + vec_size); |
There was a problem hiding this comment.
The new invariant here is that one-row-per-input array accumulators must not go through ColumnVector::reserve, because exact sizing turns repeated appends into quadratic copying. src/Functions/s2GetNeighbors.cpp:102 still does dst_data.reserve(dst_data.size() + 4), and a constant +4 does not make that pattern bounded: after n rows it still copies 4 * (1 + ... + (n - 1)) = O(n^2) elements. I think this PR should either apply the same dst_data.getData().reserve(...) fix there as part of the same defect-class sweep, or narrow the scope/evidence so it no longer treats that sibling as safe to leave behind.
There was a problem hiding this comment.
You are right, and I have corrected the PR: the claim that a constant per-row delta made
s2GetNeighbors bounded was wrong. A constant +4 lowers the factor, not the complexity, since
ColumnVector::reserve is reserve_exact and the accumulator is reallocated on every row either
way.
I measured it rather than leave it as arithmetic, ASAN, one block, max_threads = 1:
SELECT sum(length(s2GetNeighbors(geoToS2(number * 0.0000001, 40.0)))) FROM numbers(N)
SETTINGS max_block_size = N, max_threads = 1
| N | current | with getData().reserve |
|---|---|---|
| 25 000 | 6.30 s | 1.07 s |
| 50 000 | 22.50 s | 1.26 s |
| 100 000 | 84.30 s | 0.96 s |
Doubling the row count multiplies the current cost by about 3.6x, so it is quadratic as you say;
the patched arm is flat and returns identical values. geoToS2 alone is flat at ~1 s, so the
quadratic term is entirely in s2GetNeighbors. One caveat for anyone reproducing this: with a
literal cell id the argument is constant-folded and the cost is flat, which looks like a refutation.
I am not folding the fix into this PR. It is a different function and area, the PR is already
reviewed and approved at this head, and a push here would restart several hours of CI for a change
that is better judged on its own. I have taken the false wording out of the description instead, and
I am opening a separate change for s2GetNeighbors with the measurement above.
|
|
||
| dst_data.reserve(dst_data.size() + vec_size); | ||
| /// Go through PODArray::reserve: it grows capacity geometrically, IColumn::reserve sizes it exactly. | ||
| dst_data.getData().reserve(dst_data.size() + vec_size); |
There was a problem hiding this comment.
dst_data.getData().reserve is the right fix for these H3 builders, but the same exact-reserve-per-row pattern is still left in src/Functions/s2GetNeighbors.cpp:102:
dst_data.reserve(dst_data.size() + 4);That still goes through ColumnVector::reserve, so capacity is exact-sized on every row and the accumulator remains O(rows^2) copies. With the same 65409-row block size used to reproduce this PR, that path still copies about 64 GiB per block before the S2 work itself. If the invariant here is "row-wise array builders must grow geometrically", this sibling needs the same getData().reserve change or a proof that it cannot hit large scans.
There was a problem hiding this comment.
You are right, and I have corrected the PR: the claim that a constant per-row delta made
s2GetNeighbors bounded was wrong. A constant +4 lowers the factor, not the complexity, since
ColumnVector::reserve is reserve_exact and the accumulator is reallocated on every row either
way.
I measured it rather than leave it as arithmetic, ASAN, one block, max_threads = 1:
SELECT sum(length(s2GetNeighbors(geoToS2(number * 0.0000001, 40.0)))) FROM numbers(N)
SETTINGS max_block_size = N, max_threads = 1
| N | current | with getData().reserve |
|---|---|---|
| 25 000 | 6.30 s | 1.07 s |
| 50 000 | 22.50 s | 1.26 s |
| 100 000 | 84.30 s | 0.96 s |
Doubling the row count multiplies the current cost by about 3.6x, so it is quadratic as you say;
the patched arm is flat and returns identical values. geoToS2 alone is flat at ~1 s, so the
quadratic term is entirely in s2GetNeighbors. One caveat for anyone reproducing this: with a
literal cell id the argument is constant-folded and the cost is flat, which looks like a refutation.
I am not folding the fix into this PR. It is a different function and area, the PR is already
reviewed and approved at this head, and a push here would restart several hours of CI for a change
that is better judged on its own. I have taken the false wording out of the description instead, and
I am opening a separate change for s2GetNeighbors with the measurement above.
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 units10 translation units recompiled, 25 s compile time in total, 10 of them have a recent master baseline. |
|
📊 Cloud Performance Report
This PR only changes the H3 geospatial functions (h3kRing, h3ToChildren, h3PolygonToCells and the containment variant) to route array growth through geometric PODArray reserve, plus a new regression test. None of that code runs in the TPCH workload, so the two flagged queries (Q7 +17.9%, Q17 +59.4%) cannot be caused by this change. Both were already marked not_sure on an unstable baseline, and Q17's underlying measurements were very noisy; treat both as baseline variance, not a real shift. No perf-relevant impact expected on the benchmarked queries. clickbench🟢 No significant changes tpch_adapted_1_officialFlagged queries (2 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
c62aa4f
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed quadratic time when the functions
h3kRing,h3ToChildren,h3PolygonToCellsandh3PolygonToCellsWithContainmentbuild their result over many rows. A query over 196 000 rows spent 838 seconds copying memory in a CI stress run; it now takes about 5 seconds.Description
Related: #112897 (same defect class, merged)
A
Stress test (amd_asan_ubsan)hung check aborted with one query atelapsed = 838 sagainst itsown
max_execution_time = 10, having written 0 rows. Itsstacktracesshows the working thread in__memmove_sse2_unaligned_ermsunderasan_reallocunderFunctionH3KRing::executeImpl: runningflat out, not stuck. Report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114559&sha=7698f8b0d63a71a717fb84a0ffb58a701e12223a&name_0=PR&name_1=Stress%20test%20%28amd_asan_ubsan%29
These four functions reserve the result accumulator once per row, e.g.
dst_data.reserve(dst_data.size() + vec_size)ath3kRing.cpp:132.dst_datais aColumnUInt64 &andColumnVector::reserveisreserve_exact, so capacity lands exactly on thecurrent size every row and the next row reallocs, copying the whole accumulated array:
Θ(n²),about 11.6 TB of memmove here (peak memory was only 102 MB).
Reserving through
PODArray::reserverounds capacity up to a power of two, making the copyingamortized
O(n).IColumn::reserveaffects performance only, andreserve_exactsuits the manycallers reserving a final size once, so the four per-row callers are the bug, not the primitive.
Cancellation had already been delivered, but the existing per-action check cannot fire inside one
IFunction::executeImpl; removing the quadratic factor is what lets it run.Validated under ASAN, where the defect shows (a Debug build is linear, because glibc
reallocextends in place; every CI occurrence is a sanitizer job). Unfixed the query does not finish in
400 s; fixed it returns the same result in 4.8 s. All four functions were measured in both
directions, results are byte-identical, and peak memory rises ~1.45x, the expected cost of geometric
growth. The new test aborts on unfixed master with
TIMEOUT_EXCEEDEDon its first statement andpasses in 1.3 s; the 59 existing h3 tests pass.
Two sites share the shape with a constant per-row amount, which lowers the factor without
bounding the total; each is left for its own change:
s2GetNeighbors.cpp:102(4 per row) andAggregateFunctionCategoricalInformationValue.cpp:138(the function's arity).Workflow [PR]
Sync PR [sync-upstream/pr/115773]
Version info
26.8.1.1878(included in26.8and later)