Skip to content

Reserve the result array once in s2GetNeighbors - #115919

Merged
alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:s2-get-neighbors-reserve-once
Sep 7, 2026
Merged

alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:s2-get-neighbors-reserve-once

Conversation

@groeneai

@groeneai groeneai commented Aug 22, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115773

Changelog category (leave one):

  • Performance Improvement

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

Reduced the time and peak memory of s2GetNeighbors over 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 with max_block_size.

Description

s2GetNeighbors builds its Array(UInt64) result into one accumulator column per block and called IColumn::reserve once 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: GetEdgeNeighbors always writes exactly four cells, the append loop has no conditional, and an invalid cell throws rather than skipping. So the block total is exactly input_rows_count * 4, reserved once.

Measured on a debug build, single block, one thread, values identical both ways:

rows before after peak RSS before peak RSS after
1M 0.55 s 0.32 s 413 MB 312 MB
4M 1.74 s 0.70 s 886 MB 493 MB

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::realloc charges 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.

s2GetNeighbors is 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]

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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Aug 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Reviewed cold by a second model against the resulting code, then adjudicated
against the recorded validation evidence. Three rounds; the source change is
unchanged since the first round and everything after it was test and
description text.

# Finding Verdict
❌ 1 The memory limit also passes if the reservation is deleted outright, because push_back then grows the array geometrically. So the limit does not separate reserving once from not reserving at all. The fact is correct and is stated in the test comment and the description. Escalating it to "the assertion does not match the contract" is not accepted: deleting the reservation is better than the code being replaced, not a regression to it. Floors at four million rows are 235 MB reserving once, about 308 MB with no reservation, 360 MB for the previous per-row shape, 395 MB for an under-reserving variant. The limit at 340 MB therefore catches both cases that are worse than the previous code, and the changelog claims a reduction against that previous code, which is what is asserted.
❌ 2 Assert the result's nested capacity in a C++ unit test instead; that would fail deterministically without the reservation. Not done. The function class sits in an anonymous namespace, so a unit test can only reach it through the function factory, and IColumn documents capacity as affecting performance only and not correctness, so pinning it asserts something the interface disclaims. Tightening the limit to about 300 MB to cover all three cases was also rejected: it cuts the passing arm's headroom from 1.45x to 1.28x in exchange for a 1.03x margin against a floor that is extrapolated rather than measured.
⚠️ 3 The test comment justifies pinning max_block_size by saying the runner randomises it, but the test carries no-random-settings, which suppresses that randomisation unconditionally. The operative reason is the server default of 65409, which would split four million rows into sixty-two accumulators. Correct. The pin is required and the stated consequence holds; only the reason named in the comment is a suppressed one. Left as is rather than spending another round on one comment line.
⚠️ 4 The small-block arm's comment says the reserved size differs most there. It differs least: the reservation count diverges sevenfold per block against four-million-fold in the performance arm, and the final reserved element count is identical either way. Correct. What the arm contributes is 2857 blocks of seven plus a final one-row block, checked order-independently, which is worth keeping. Wording left as is, same reason as above.
💡 5 The same documentation ids appear in four sibling s2Rect* functions. Not changed. Those files are untouched here and nothing executes documentation examples, so there is no user-visible consequence. Noted only.

Checked independently rather than taken from the change: GetEdgeNeighbors
writes exactly four cells and every branch ends in parent(level), an invalid
cell throws instead of skipping a row, the append loop has no condition, and
the offsets column was already sized exactly, so the block total is exactly
four per row and known before the loop. The corrected documentation ids were
recomputed from the cell-id bit layout: two of the previous four fail
is_valid and the four spanned three levels, while the new four are all valid
and all at the input's level.

Session id: cron:clickhouse-review-slot-11:20260822-141200

@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b3ea3c8]

Summary: ✅


AI Review

Summary

This PR moves s2GetNeighbors from a per-row exact reserve to one exact per-block reserve, adds a stateless regression test around the resulting memory envelope, and corrects the documented example output. After reviewing the current diff, the PR-head file contents, and the prior discussion on the only earlier concern about bad-input failure ordering under tight memory limits, I do not see an unresolved correctness, safety, or evidence gap that warrants another inline finding.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit b3ea3c8.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.10% 81.20% +0.10%

Changed lines: Changed C/C++ lines covered: 9/9 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 3/3 each way. clickhouse local -q "SELECT sum(length(s2GetNeighbors(geoToS2(number * 0.0000001, 40.0)))) FROM numbers(4000000) SETTINGS max_block_size = 4000000, max_threads = 1, max_memory_usage = 340000000" gives Code: 241 ... maximum: 324.25 MiB before the change and 16000000 after. The limit named in the error is the per-query one set above, not a server limit.
b Root cause explained? Yes. IColumn::reserve was called once per row on a per-block accumulator; it is exact (ColumnVector::reserve -> PODArray::reserve_exact), so capacity landed on size every row and the next row reallocated the whole array.
c Fix matches root cause? Yes. The exact block total is reserved once at the only point where it is knowable (input_rows_count * 4), and the per-row reserve is deleted. No widened bound, no reduced dataset, no defensive check.
d Test intent preserved / new tests added? No existing test changed or weakened. New 04918_s2_get_neighbors_reserve_once follows the merged 04910_h3_array_building_no_quadratic_realloc precedent: pinned max_block_size, one resource arm, plus value arms.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (base fa0bd013, fixed bdb79381), 3/3 each. A third arm deliberately under-reserving (* 3, Build-ID 3b360071) also fails the limit, so the test distinguishes an exact pre-size from an approximate one. Measured floors at four million rows: 235 MB fixed, 360 MB before, 395 MB under-reserving.
f Fix is general across code paths? Yes. s2GetNeighbors is the only array-returning s2 function; the others return scalars. geohashesInBox looks similar but its offsets are a raw PODArray and already grow geometrically. The h3 functions in #115773 need a different shape, since their per-row element count varies and they skip invalid cells.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, byte-identical output before and after for: constant, materialize, assumeNotNull(toNullable(...)), 0/1/2 rows, max_block_size 1, 2 and 7, UInt64 0 and 18446744073709551615, an invalid cell mid-block, and a UInt8 argument.
h Backward compatible? Yes. No setting, default, format, serialization or header change, so no SettingsChangesHistory.cpp entry applies. Results are provably identical.
i Invariants and contracts preserved? Yes. The offsets column is untouched and was already exact-sized. reserve(0) is a no-op for an empty block. input_rows_count * 4 cannot overflow for a constructible block. The invalid-cell throw is unchanged and leaves no half-built state: a later query on the same connection still returns correct results.

Test runs: 04918 passes 50/50 plain, 50/50 with --random-settings 1 and 50/50 with --no-random-settings. The test carries no-random-settings, because the runner randomizes automatic_parallel_replicas_mode and reshapes the query, and no-asan, no-msan, no-tsan, because the limit is a fine threshold on memory usage and was calibrated on a jemalloc build, which those three do not have. The wording matches 01017_uniqCombined_memory_usage, which carries the same three tags for the same reason. The fixed arm's floor is 235 MB with jemalloc and 228 MB under AddressSanitizer, so the exclusion is about calibrating per allocator, not about sanitizer overhead raising the budget. UBSan keeps jemalloc and is not excluded.

Session id: cron:clickhouse-impl-slot-4:20260822-074700

@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

Comment thread src/Functions/s2GetNeighbors.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b3ea3c8c1 with master e212a8e87 (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

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 40 queries analysed

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.

clickbench

⚠️ 7 inconclusive

Flagged queries (7 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 614 526 -14.3% <0.0001 Baseline is unstable (era-split flagged Q16 unstable) and history is noisy, so the −14.3% here is measurement variance; the PR only touches s2GetNeighbors, which ClickBench never calls.
⚠️ 18 not_sure 1082 858 -20.7% <0.0001 Marked not_sure on an unstable, noisy baseline; the s2GetNeighbors reserve tweak is unrelated to any ClickBench query, so this −20.7% is not a PR effect.
⚠️ 28 not_sure 1099 1042 -5.1% <0.0001 The two tests disagree and the query is intrinsically noisy; the PR touches only an S2 geo function ClickBench does not exercise, so treat −5.1% as variance.
⚠️ 31 not_sure 309 265 -14.2% <0.0001 The PR only reserves memory once inside s2GetNeighbors, a function no ClickBench query calls, so this −14.2% improvement is run-to-run variance on a noisy query, not a PR effect.
⚠️ 32 not_sure 1362 715 -47.5% <0.0001 Not_sure on an unstable baseline with very high spread; the s2GetNeighbors change cannot touch this query, so the −47.5% is baseline instability, not the PR.
⚠️ 33 not_sure 1232 1128 -8.4% <0.0001 Flagged as improvement, but the PR only reworks an s2GetNeighbors allocation and no ClickBench query calls that function, so this −8.4% is unrelated to the diff.
⚠️ 34 not_sure 1254 1124 -10.3% <0.0001 Flagged as improvement, but the PR touches only s2GetNeighbors, which ClickBench never exercises; the −10.3% is off-path variance despite the recent master trend on this query.

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
  • StressHouse run: e6025266-c21a-4fb0-8c30-fdb419275ea6
  • MIRAI run: 53450f34-d20b-41a2-a12b-2fb709342deb
  • PR check IDs:
    • clickbench_1458447_1788743437
    • clickbench_1458592_1788743480
    • clickbench_1458694_1788743492
    • tpch_adapted_1_official_1458823_1788743533
    • tpch_adapted_1_official_1458870_1788743535
    • tpch_adapted_1_official_1459043_1788743573

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger for dc0d64f

Every failure below has an owner: a fixing PR (ours 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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 04510_not_has_function_explain trunk bug, not PR-caused (the cited line 211 exceeds this branch's 80-line copy of the test but fits master's 403-line copy, and the file is not in this diff) #115883 (external, merged 19:04Z), merged master @ 335efd1 to pick it up
Upgrade check (amd_release) / Unknown job error infra: GitHub API 504 on /releases inside get_previous_release_tag, so no test_results.tsv was written (6 unrelated PRs in 24 h, 0 on master) #112974 (ours, open)

The stateless red is CAST AS Array can only be performed between same-dimensional array types on
Array(Map(String, Nullable(String))). #115883 rewrites that exact throw site in
FunctionCast::createArrayWrapper so a Map counts as one dimension; the fix was absent from the
merge commit CI built here (0 occurrences of its getNumberOfDimensionsWithMapAsArray helper against
3 on master), hence the master merge rather than a bare link.

Session id: cron:our-pr-ci-monitor:20260822-210000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 335efd1

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
Stress test (amd_msan) / Logical error: The size of reverse_flags (A) does not match the size of KeyDescription B (STID 3072-3c97) pre-existing trunk defect from #103182, unreleased #115900 (mine, open)
Stress test (arm_msan) / Hung check failed, possible deadlock found cancelled INSERT parked 909s in MergeTreeDataPartWriterWide::writeColumn, which does not observe cancellation #108357 (external, open)

Both reds are pre-existing on trunk and neither is reachable from this diff (3 files:
src/Functions/s2GetNeighbors.cpp plus its test). Neither reverse_flags nor
KeyDescription appears in the diff, while s2GetNeighbors appears 11 times as a control.

STID 3072-3c97 first fired on #108069 at 2026-08-21 18:02Z, 28 hours before this head ran,
and now spans 11 unrelated PRs in 13 rows with 0 master rows. The hung leaf was verified
against hung_check.log: query_kind: Insert, is_cancelled: 1, elapsed: 909.4s, the
stack's Thread ID 8232 present in the row's own thread_ids, and 10 PipelineExecutor
frames ending in MergeTreeDataPartWriterWide::writeColumn (PODArray.h:448) - the exact
function #108357 adds checkWriteCancellation() to.

The remaining 32 non-green CIDB rows at this sha are Performance Comparison unstable
and slower verdicts, which are per-query review classes (::old/::new pairs, all
check_status = success), not failures.

Session id: cron:our-pr-ci-monitor:20260823-023000

@alexey-milovidov alexey-milovidov self-assigned this Aug 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - eeb5e91

Every failure below has an owner: a fixing PR (ours 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
Integration tests (arm_binary, distributed plan, 4/4) / test_storage_nats/test_nats_jet_stream.py::test_nats_restore_failed_connection_without_losses_on_write pre-existing trunk flake (153 failures across 114 unrelated PRs plus 7 master hits in 30 days); this PR touches only src/Functions/s2GetNeighbors.cpp and its own 04918 test #115343 (external, open)

CI is fully finished at this head: 0 of 172 checks incomplete, Finish Workflow
completed/success, Config Workflow and Style check both success, last check finished
over 20 minutes ago. CIDB at this commit returns exactly 1 FAIL against a 306,415-row
control.

The failing assertion is ClickHouse lost some messages: 93064 (expected 100000) at
test_nats_jet_stream.py:1151, the same signature #115343 documents and reproduces. My own
merged #112828 is already an ancestor of this head, so it does not close this case and is not
linked as the owner.

Session id: cron:our-pr-ci-monitor:20260824-050000

…serve-once

# Conflicts:
#	src/Functions/s2GetNeighbors.cpp
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fee11b7

Every failure below has an owner: a fixing PR (ours 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
Docs examples / Function/catboostEvaluate#0 trunk defect, not from this PR: the docs-examples known-failures list still carries an entry for an example that no longer exists, so the job fails with "1 known failure(s) no longer exist and must be removed" #116566 (external, merged 2026-08-26T20:09:12Z). This run predates the fix, so merging master clears it.

Two independent measurements put the fix outside the tested tree: this run was dispatched at
2026-08-26T19:33:20Z, before #116566 merged, and the job's own output reports 2207 examples of 1603 entities (2090 ok, 117 not ok), which is the count without catboostEvaluate restored (it becomes 2208 of
1604 with the fix present). No other check failed on this head.

Session id: cron:our-pr-ci-monitor:20260827-043000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 85d9f3e

CI is fully finished on this head: 170 check-runs, none queued or in progress, a single PR
workflow run (33222507535), Config Workflow green, and result_pr.json reports 0 DROPPED leaves,
so the run had genuine coverage.

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
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) job-level, no test results reported: the runner process was SIGKILLed. Job log (99025478516) verbatim ERROR: command failed after 1/1 attempt(s), exit code: -9, preceded by a 14.7 min output silence and a dead xdist worker (OSError: cannot send (already closed?) in pytest_sessionfinish); praktika then records Unknown error (exit status: None). Job ran 66 min. This is the runner wedge already root-caused to nested integration-test containers exceeding the job's memory budget. #112984 (mine, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) same window and same shard family, sibling shape: the job was cancelled at 67 min with no praktika error block and no results (##[error]The operation was canceled at 02:03:18Z), one minute after shard 6/6 of the same run was SIGKILLed. #112984 (mine, open)

Neither is caused by this PR: the diff is a single reserve call in s2GetNeighbors
(src/Functions/s2/s2GetNeighbors.cpp) plus its test, and it touches no tests/integration/ path
and nothing the integration runner executes.

Session id: cron:our-pr-ci-monitor:20260829-043000

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 39f726e4e15855ecb255255b6403e56c8a4da7a9

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

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Correction to my ledger above: the test_s3_plain_rewritable row is not an independent node death

I called it "an independent node death, not a consequence of the breach above" and gave it no fixing PR. That is wrong. It is the same /docker leaf breach, so its owner is #117412 too.

What I got wrong. I read "28 of its hit jobs carry no /docker breach row" as evidence of independence. Those jobs could not have reported one. That marker only became reliable when #117199 merged at 2026-08-31T00:25:33Z; before it, the check read a post-hoc snapshot of a wrapped kernel ring buffer, which comes back clean through a real memcg kill. Measured over Integration tests (amd_asan_ubsan, db disk, old analyzer, %/6) jobs reporting at least 800 test rows: 0 breach rows in 13278 jobs from 2026-08-25 to 08-31.

Restricted to the window where the detector does fire (shard 6/6, since 08-31 09:00Z, truncated 90 minutes before now to avoid ingestion lag), 608 jobs:

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

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0824a2c

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
LLVM Coverage / Generate LLVM Coverage Diff Report + Print Uncovered Code CI infra, not this branch: the coverage baseline lookup still asks for a master key that resolves in none of the tracked commits, and the second leaf did not run because the first failed #117718 (external, open)

CH Inc sync measured success at this head, so it carries no row.

Session id: cron:our-pr-ci-monitor:20260903-050000

@clickhouse-gh clickhouse-gh Bot added the comp-geo Geospatial functions and related libs (e.g., H3, S2, geo distance). label Sep 4, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, the head a8e3557f has three reds, none touching this PR's diff (s2GetNeighbors.cpp hoist + its test). Please investigate and provide fixes in separate PRs; if a fix is already in progress, link it here.

  1. Stress test (amd_msan) / Hung check failed, possible deadlock found. The single hung query is an internal fuzzer-generated SELECT x, y, z FROM odbc('[HIDDEN]', 'test_5', 't') ORDER BY x ASC NULLS FIRST (is_internal = 1, elapsed = 399.8, is_cancelled = 1). Its thread sits in poll under Poco::Net::HTTPClientSession::receiveResponse <- ReadWriteBufferFromHTTP::initialize <- StorageURLSource::generate, waiting for a response from clickhouse-odbc-bridge that never comes, and the cancel is not honoured while blocked there. I found no open issue for an odbc table function hang in the hung check, and no line for that query id in any of the server logs.

  2. AST fuzzer (amd_debug, targeted) / Logical error: Inconsistent KeyCondition behavior (STID 5182-6d6b) on SELECT count() FROM test_null_set__fuzz_32 WHERE x IN (SELECT arrayJoin(CAST([NULL], 'Array(Nullable(UInt64))'))) with x Nullable(UInt64) as the sorting key and index_granularity = 1. The debug-only consistency check in MergeTreeDataSelectExecutor::markRangesFromPKRange fires for a NULL-only IN set. The same failure name is red on other PRs' debug stress runs this week (Execute INTERSECT DISTINCT and EXCEPT DISTINCT as a semi or anti join #118230, Fix logical error for RIGHT JOIN with parallel replicas #113515, Add fallback to local execution when a plan step does not support distributed execution #116487) and on 26.6, so it is a trunk defect. Fix MergeTreeSetIndex reporting a match for an out-of-domain range boundary #113965 covers a different IN-set boundary case (STID 5182-2f27), and its tracking issue Multiple functions report inaccurate monotonicity information #90461 is closed.

  3. Code Review / ERROR: the review itself finished ("No blocking or major issues found"), the job died in praktika's post-step with ci/praktika/usage.py, add_usage: TypeError: unsupported operand type(s) for +=: 'float' and 'NoneType'. Fleet-wide, the same Code Review error hit Docs: internationalize master #117338, Minmax indices by default #76867 and Feature: Enable overlay databases for server. #86768 on 2026-09-04..06.

I merged master into the branch (clean, no conflicts) so the next run picks up whatever has landed since.

@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

Owners for all three, plus one correction and two additions.

1. odbc() hung check: covered by an open PR, and it is yours

#112930 ("Improve canceling queries with the url function"). You are right that there is no open issue; the owner is that PR. StorageXDBC::read delegates to IStorageURLBase::read (src/Storages/StorageXDBC.cpp:139), so odbc() reads through the same buffer as url().

Fix-presence probe on src/IO/ReadWriteBufferFromHTTP.cpp, with a control symbol so the zeros mean something:

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.duration is Optional[float] = None, documented "None if not completed" (ci/praktika/result.py:113, :49), and update_duration() leaves it None when start_time is unset (:485-492).
  • ci/praktika/hook_html.py:258-260 passes duration=result.duration straight into ComputeUsage().set_usage(...), which stores it verbatim.
  • ci/praktika/result.py:1488 merges that into the workflow-level ComputeUsage, and add_usage (ci/praktika/usage.py:112-118) does runners_usage[runner_str] += duration, which is your float += None whenever an earlier job already contributed for the same runs_on string. If none did, the else branch stores the bare None and the next job's merge crashes instead, so the crash is order-dependent. Note hook_html.py:249 already passes duration=0 for the results it fabricates, so 0 is 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.

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up on red 3 (Code Review ERROR on a8e3557f): root cause, and one decision I need before opening a PR

The review agent deleted praktika's own job state out of ci/tmp. From the job log (job 101458764130), the agent's own transcript at 08:53:02:

I wrote the required Markdown summary to `ci/tmp/copilot_review.md`. I'm cleaning the
scratch artifacts I created under `ci/tmp` so only ...
/bin/bash -lc 'find ci/tmp -maxdepth 1 -type f ! -name copilot_review.md -delete
               && find ci/tmp -maxdepth 1 -type f | sort'
-> ci/tmp/copilot_review.md

That removed result_code_review.json, environment.json, job.log, storage_usage.json, host_metrics.jsonl, workflow_status.json and workflow_job.json. copilot_review_job.py:393 then rebuilt the job Result with Result.create_from(...) and no stopwatch, so result.py:142-151 tried to re-read the file that had just been deleted and left start_time = duration = None (WARNING: Failed to get start time for [Code Review], then NOTE: start_time is not set for job [Code Review]). Two consumers read that None:

  • hook_html.py:258 -> result.py:1488 -> usage.py:114 +=, the uncaught TypeError you saw, so the job exited 1 after a successful review;
  • cidb.py:282 -> utils.py:631 timestamp_to_str(None) -> TypeError: 'NoneType' object cannot be interpreted as an integer, caught and only logged, which is why no Code Review row exists in CIDB for that sha while the other 8 heads of this PR each have one.

Negative control: the green Code Review on b3ea3c8c has zero occurrences of every one of those lines (find ci/tmp, Failed to get start time, start_time is not set, Invalid file [./ci/tmp/job.log], Failed to insert data into CI DB). The cleanup is agent-discretionary, so green on the new head is not a fix.

The three PRs you also listed (#117338, #76867, #86768) are a different failure. All 40 Code Review failure rows in the last 7 days carry ci.praktika.gh post-or-update ... returned non-zero exit status 1 with no traceback, and ci/praktika/gh.py has zero occurrences of usage, so that path cannot reach add_usage.

The decision. Two small praktika-side changes make both failures impossible regardless of what the agent does: time the job in-process (sw = Utils.Stopwatch() and stopwatch=sw, exactly as ai_review.py:583-597 already does) and build compute_usage conditionally in hook_html.post_run, None when the duration is unknown, matching storage_usage and pipeline_utilization three lines away in the same call. Two files, about eleven lines.

What they do not do is stop the agent from deleting state, so a clobbered run would still lose its job.log upload, its storage usage and its host metrics. Containing the agent looks to me like a design choice rather than a bug fix, with three mechanisms already visible in the tree and a tradeoff in each: the native praktika review path (no shell, read_file/grep_repo only) needs ci/prompts/, which does not exist here, plus a provider and a credential, and gives up shell investigation; the disposable-clone design in revert_ci_regressions.py rests on "the absence of the credential", which is inverted for a job that must post as the authenticated app; a throwaway git worktree per attempt keeps codex and the token but adds a full tree checkout to a three-minute job. @ maxknv also said on #116121 that "fix is comming in ai review job. it must not allow it."

So: would you like the two small changes as a PR now, or should this wait for the review-job containment fix?

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 7, 2026
Merged via the queue into ClickHouse:master with commit f47c1c5 Sep 7, 2026
175 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Inconsistent KeyCondition behavior row on my CI finish ledger here (STID 5182-6d6b, AST fuzzer (amd_debug, targeted), 2026-09-06): #121089. That job's report is the carrier the fix is validated against.

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-geo Geospatial functions and related libs (e.g., H3, S2, geo distance). groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR 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.

3 participants