Repository navigation
Reserve the result array once in s2GetNeighbors - #115919
Conversation
s2GetNeighbors built its Array(UInt64) result into one accumulator per block and called IColumn::reserve once per row. That reserve is exact (ColumnVector::reserve -> PODArray::reserve_exact), so capacity landed precisely on size on every row and the next row reallocated the whole accumulated array, discarding the geometric growth push_back would otherwise provide. GetEdgeNeighbors always writes exactly four cells, the append loop has no conditional, and an invalid cell throws rather than skipping a row, so the block total is exactly input_rows_count * 4 and is known before the loop. Reserving it once there replaces n reallocations with one. Measured on a debug build at two million rows in a single block: 0.96 s -> 0.44 s and 573 MB -> 376 MB of peak RSS; at four million rows the peak drops 44 percent. Values are unchanged. The cost is a constant factor rather than a complexity change, because jemalloc grows a large extent in place. Peak memory is affected on any allocator, since Allocator::realloc charges the new size before releasing the old one, and that is what the new test asserts.
…ample Move the perf arm from two million rows under a 340 MB budget at four million instead. The absolute cushion, not the ratio, is what an extra intermediate column consumes, and unlike the ratio it scales with the row count: floors measured on this build are 235 MB for the reserving code, 360 MB for the previous per-row shape and 395 MB for a deliberately under-reserving variant. Add no-random-settings, matching the two in-tree tests of this shape. The runner randomizes automatic_parallel_replicas_mode to 2 a quarter of the time and then reshapes the query, which a fixed memory budget cannot absorb. Add no-asan, no-msan and no-tsan too: those builds have no jemalloc, and the reserving arm's floor there is 228 MB, two thirds of the budget. UBSan keeps jemalloc and is not excluded. The test's comment now names what the budget separates, which is the exact block total from both a per-row exact reserve and an approximate one. It does not separate reserving once from not reserving at all, since push_back would then grow the array geometrically. The documented example output was not reachable output: two of its four ids fail S2CellId::is_valid because lsb bit 13 is outside the valid mask, and the four span three levels although every GetEdgeNeighbors branch ends in parent(level). It is replaced with what the function returns.
The mutant the memory limit rejects under-reserves rather than over-reserves, and the limit does not separate reserving once from not reserving at all, since push_back grows the array geometrically. State both. The exclusions stay; their reason was wrong. The passing arm's floor is 235 MB with jemalloc and 228 MB under AddressSanitizer, so allocator overhead does not raise the budget. The budget is calibrated per allocator and only the jemalloc builds were calibrated, which is how 01017_uniqCombined_memory_usage words the same three tags.
Internal second-model reviewReviewed cold by a second model against the resulting code, then adjudicated
Checked independently rather than taken from the change: Session id: cron:clickhouse-review-slot-11:20260822-141200 |
|
Workflow [PR], commit [b3ea3c8] Summary: ✅
AI ReviewSummaryThis PR moves Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit b3ea3c8.
Changed lines: Changed C/C++ lines covered: 9/9 (100.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
Test runs: Session id: cron:clickhouse-impl-slot-4:20260822-074700 |
|
cc @nikitamikhaylov @george-larionov, could you review this? s2GetNeighbors called IColumn::reserve once per row on a per-block accumulator, and that reserve is exact, so capacity landed on size every row and the next row reallocated the whole array; the block total is exactly four per row and is now reserved once before the loop. It also corrects the documented example output, two of whose four ids are not valid cell ids. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 8 s compile time in total, 7 of them have a recent master baseline. |
|
📊 Cloud Performance Report
This PR changes a single line in s2GetNeighbors — reserving the result array once per block instead of growing it four elements at a time — plus a new stateless test. None of the ClickBench queries call any S2 geo function, so the changed code path is never executed by this benchmark. The flagged deltas (improvements on Q31/Q33/Q34 and not_sure rows on Q16/Q18/Q28/Q32) all sit on queries the diff cannot touch, several of them on noisy or era-unstable baselines, so we downgraded the flagged improvements to not_sure and read the rest as baseline variance rather than a real PR effect. clickbenchFlagged queries (7 of 43)
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. tpch_adapted_1_official🟢 No significant changes Debug info
|
Picks up the merged fix for the CAST of an Array(Map) constant sent to a remote server, so 04510_not_has_function_explain is exercised with it present.
CI finish ledger for dc0d64fEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
The stateless red is Session id: cron:our-pr-ci-monitor:20260822-210000 |
CI finish ledger - 335efd1Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Both reds are pre-existing on trunk and neither is reachable from this diff (3 files: STID 3072-3c97 first fired on #108069 at 2026-08-21 18:02Z, 28 hours before this head ran, The remaining 32 non-green CIDB rows at this sha are Performance Comparison Session id: cron:our-pr-ci-monitor:20260823-023000 |
CI finish ledger - eeb5e91Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
CI is fully finished at this head: 0 of 172 checks incomplete, The failing assertion is Session id: cron:our-pr-ci-monitor:20260824-050000 |
…serve-once # Conflicts: # src/Functions/s2GetNeighbors.cpp
CI finish ledger - fee11b7Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Two independent measurements put the fix outside the tested tree: this run was dispatched at Session id: cron:our-pr-ci-monitor:20260827-043000 |
CI finish ledger - 85d9f3eCI is fully finished on this head: 170 check-runs, none queued or in progress, a single Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Neither is caused by this PR: the diff is a single Session id: cron:our-pr-ci-monitor:20260829-043000 |
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) |
the shard's nested containers breach the /docker cgroup leaf, the kernel OOM-kills processes inside it and the job errors with no test attributed |
#117412 (external, merged 2026-09-01T11:31:33Z) |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / Container memory budget exceeded (/docker) |
the shard's nested containers breach the /docker cgroup leaf, the kernel OOM-kills processes inside it and the job errors with no test attributed |
#117412 (external, merged 2026-09-01T11:31:33Z) |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / test_s3_plain_rewritable/test.py::test[s3_plain_rewritable_with_metadata_cache-data_with_cache/] |
node.query("OPTIMIZE TABLE test FINAL") fails Code: 210. DB::NetException: Connection refused (172.16.5.10:9000) at test.py:138; an independent node death, not a consequence of the breach above |
a fix task is moved to pending (investigating at full effort - fixing-PR link to follow on this PR) |
The /docker breach is a job-level condition, not a test result. I measured #117412 ABSENT from the tree that ran, from the job's own environment rather than from git ancestry: this job was launched with CI_DIND_INIT_RESERVE=17179869184 (the 16 GiB share #117412 replaces), and so were all ten failing legs I read this tick. The probe discriminates, with a positive control: two shards launched at 14:53Z and 14:59Z carry CI_DIND_INIT_RESERVE=8589934592 (the flat 8 GiB reserve #117412 introduces) and both passed. So this is rule 3c and not rule 3d, and #117411 is not a co-owner: it was closed unmerged at 11:11:48Z in favour of #117412, whose own diff comment states the causal link.
The test_s3_plain_rewritable row needed its own owner, and I tested that rather than assuming it was collateral of the breach. The signature is homogeneous (Code: 210, OPTIMIZE TABLE test FINAL, test.py:138) across 26 jobs in 30 days, including 2 true-master runs on 2026-08-29 and 2026-08-31, and 28 of its hit jobs carry no /docker breach row at all. So #117412 does not own it and I have not linked it there.
I have not merged master to pick those fixes up yet. It would not clear Mergeable Check on this head, because the node death has no merged fix and would still fail this shard, so a merge now would cost a full CI cycle and leave the head red on the same count. One master merge picks everything up once the remaining fixes land.
Mergeable Check reports Failed: 2, Dropped: 106 at this head, which counts only the jobs it gates on. The table above is the complete non-OK, non-SKIPPED node set of the head's praktika report, so it also covers the rows Mergeable Check does not gate.
CH Inc sync was success; completed with 2 known failures ignored at this head.
Session id: cron:our-pr-ci-monitor:20260901-163000
Correction to my ledger above: the
|
| jobs | with a node death | |
|---|---|---|
| breach row reported | 477 (78.5%) | 22 |
| breach row absent | 131 | 0 |
The breach rate is 78.5% and not ~100%, so the no-breach arm is 131 jobs and does have the power to discriminate. It is empty. All 22 deaths sit on breach-reporting jobs, including the true-master run 25dfbdb6c5dd.
Why one condition produces two different-looking rows. The kernel kills the largest task in the leaf. While a shutdown gdb attach is still smaller than an ASan server it takes a server instead, and the query in flight then fails with Code: 209 or Code: 210 according to whether the container outlived it. Once gdb has grown past the servers it becomes the victim, every test passes, and only the job-level row is left.
Owner: #117412 (external, merged 2026-09-01T11:31:33Z), with #117202 (external, merged 2026-08-31T11:05:36Z) which bounded the concurrent gdb attaches. The reason I gave for holding the master merge back, that this row had no merged fix, therefore no longer holds: a master merge now picks up every row on this head.
Session id: cron:clickhouse-plan-slot-0:20260901-170604
CI finish ledger - 0824a2cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260903-050000 |
|
🕵 @groeneai, the head
I merged master into the branch (clean, no conflicts) so the next run picks up whatever has landed since. |
|
Owners for all three, plus one correction and two additions. 1.
|
| ref | isQueryTimeLimitReached |
isReadCancelled |
control doWithRetries |
|---|---|---|---|
#112930 head feefe922 |
7 | 4 | 5 |
master e212a8e8 |
0 | 0 | 4 |
this PR's a8e3557f |
0 | 0 | 4 |
One mechanism detail, because it decides whether #112930 covers this row: it is the retry loop, not a single blocked read. Master's doWithRetries never consults cancellation (the only cancel tokens in that file are the ReadBufferSeekCancelConnection profile event and an is_canceled flag in the copy path), a Poco timeout lands in its catch (Poco::Exception &) arm, which clears is_retriable only for POCO_EMFILE (:358-361), and the backoff is a plain sleepForMilliseconds (:398). On the two earlier occurrences of this signature that I measured (#112177 7107b479, elapsed 393.95 s; #112313 14dc7645, elapsed 397.99 s), the hung row's own ProfileEvents showed ReadWriteBufferFromHTTPRequestsSent at 16 and 17 with read_rows = 0, while http_receive_timeout was 60 s, so one receive cannot reach 400 s. #112930 checks cancellation before each attempt, on retry, on the final attempt and inside the retry wait, so it does cover this.
2. STID 5182-6d6b: no fixing PR exists
A fix task is moved to pending, and I will post the fixing-PR link here. I agree with your read; #113965's mechanism needs a set boundary at the key column type's own limit (its own matrix: UInt8 255 aborts, 254 and 0 are clean), which this carrier does not have, so #113965 must not be cited as the fix.
Two additions. Your reproducer sits exactly on the only path that can turn the check on: find_exact_ranges has a single non-false initializer in src/, optimizeUseAggregateProjection.cpp:1216, !candidates.only_count_column.empty(), so a count-only aggregate-projection candidate is what makes markRangesFromPKRange compute exact ranges at all. That also bounds the severity: the canary is inside #ifndef NDEBUG (MergeTreeDataSelectExecutor.cpp:2522, throw at :2550), so a release build drops the exact range silently. CI signal loss plus a lost exact-count optimization, not wrong results.
A loose end on the tracking: MergeTreeDataSelectExecutor.cpp:2520 still says TODO: Remove the #ifndef and always throw after ... issues/90461 is fixed, and the error text at :2544 still points readers at #90461, but #90461 was closed as completed on 2026-02-08. Trunk's own gate still treats the class as open while the issue reads as closed.
3. Code Review: no owner existed
A fix task is created, and I will post the fixing-PR link here. Root cause of your traceback, on master e212a8e8:
Result.durationisOptional[float] = None, documented "None if not completed" (ci/praktika/result.py:113,:49), andupdate_duration()leaves itNonewhenstart_timeis unset (:485-492).ci/praktika/hook_html.py:258-260passesduration=result.durationstraight intoComputeUsage().set_usage(...), which stores it verbatim.ci/praktika/result.py:1488merges that into the workflow-levelComputeUsage, andadd_usage(ci/praktika/usage.py:112-118) doesrunners_usage[runner_str] += duration, which is yourfloat += Nonewhenever an earlier job already contributed for the sameruns_onstring. If none did, theelsebranch stores the bareNoneand the next job's merge crashes instead, so the crash is order-dependent. Notehook_html.py:249already passesduration=0for the results it fabricates, so0is this accumulator's own convention for "no duration".
Correction on the breadth: #117338, #76867 and #86768 are a different defect. All 40 Code Review rows with check_status = 'failure' in CIDB over the last 7 days belong to exactly those three PRs, and the 20 of them that carry a context carry one single 171-character line, with no traceback:
ERROR: Command '['/usr/bin/python3', '-m', 'ci.praktika.gh', 'post-or-update', '--tag', 'review', '--file', './ci/tmp/copilot_review.md']' returned non-zero exit status 1.
ci/praktika/gh.py contains no reference to usage, so post-or-update cannot reach add_usage; that signature is the review-comment posting step failing. It is not on this PR and I have not reproduced it, so I am not raising it.
Two more measured points on the one that is here: a8e3557f produced no Code Review row in CIDB at all, while its Stress test (amd_msan) and AST fuzzer rows landed, which fits the job dying in the post-step that also performs the CIDB insert; and Code Review is green again on b3ea3c8c (22:40:47Z), consistent with the order-dependence.
On b3ea3c8c the 12 builds, Fast test, Style check, Quick functional tests and Code Review are green so far, and the stress and fuzzer jobs have not reported yet. I have not pushed or rebased anything.
Follow-up on red 3 (
|
|
Fixing PR for the |
Related: #115773
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reduced the time and peak memory of
s2GetNeighborsover many rows by reserving its result array once per block instead of once per row. Peak memory at four million rows in a single block drops by about 44%, and the gain grows withmax_block_size.Description
s2GetNeighborsbuilds itsArray(UInt64)result into one accumulator column per block and calledIColumn::reserveonce per row. That reserve is exact (ColumnVector::reserve->PODArray::reserve_exact), so capacity landed on size every row and the next row reallocated the whole accumulated array.The size is known before the loop:
GetEdgeNeighborsalways writes exactly four cells, the append loop has no conditional, and an invalid cell throws rather than skipping. So the block total is exactlyinput_rows_count * 4, reserved once.Measured on a debug build, single block, one thread, values identical both ways:
The time saving is a constant factor, not a complexity change, because jemalloc expands a large extent in place. Peak memory is affected on any allocator:
Allocator::realloccharges the new size before releasing the old, so each per-row reserve transiently accounts for both. The new test asserts this with a limit that both the previous code and a deliberately under-reserving variant exceed. Without jemalloc (the sanitizers) every row copies the whole accumulator, so the effect is larger there; the budget is calibrated for jemalloc, so those builds are excluded outside the stress lanes, which ignore build tags.The documented example output was not reachable output (two of its four ids are not valid cell ids, and they span three levels); it is corrected to what the function returns.
s2GetNeighborsis the only array-returning s2 function. The h3 functions in #115773 need a different shape: their per-row element count varies and they skip invalid cells, so no exact total is available before the loop.Workflow [PR]
Sync PR [sync-upstream/pr/115919]