Skip to content

Do not walk the geohashesInBox grid when one axis has no items - #112976

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-geohashes-in-box-degenerate-span
Aug 3, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-geohashes-in-box-degenerate-span

Conversation

@groeneai

@groeneai groeneai commented Aug 2, 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):

Fixed geohashesInBox spending an unbounded amount of time on a box of zero area, such as geohashesInBox(0., 0., 180., 0., 12). Such a query returned the correct single geohash but burned roughly 5e8 empty loop iterations per row and ignored both max_execution_time and KILL QUERY.

Description

geohashesInBoxPrepare rejects reversed and NaN boxes, but not a box of zero area whose bounds are merely equal: latitude_max < latitude_min is false when the two are equal, and also for -0.0 < 0.0. Such a box aligns one axis to a single grid line, so that axis' item count is zero while the other stays enormous. For (0., 0., 180., 0.) at precision 12 that is lon_items = 536870912, lat_items = 0: items_count is 1, yet geohashesInBox still walks the outer axis in full with a zero-trip inner loop, 536 million iterations to produce one geohash.

The row loop's cancellation checkpoint, added in #112273, cannot help: it is throttled on accumulated items and each such row contributes a single unit, so a whole block stays far below the threshold and checkTimeLimit is never consulted. Neither the deadline nor a KILL is observed. That is how the query in the CI report below sat in this loop for 714 s with is_cancelled already set, reddening Stress test (arm_asan_ubsan).

The fix skips the nested loops when either item count is zero, letting the existing items == 0 fallback emit the same single geohash, so results are unchanged. The non-degenerate path costs two added integer comparisons per row.

Validated on a debug build: under max_execution_time = 10, 200 rows of the degenerate block overrun to ~28 s unfixed and honour the deadline in 0.11 s fixed. The same numbers hold against the current items_between_cancellation_checks = 100'000. A 1875-case sweep over boxes and precisions is byte-identical before and after. The new test 04694_geohashes_in_box_degenerate_span asserts termination only, leaving the result of a line-degenerate box to the existing 00972_geohashesInBox invariants; it reddens with TIMEOUT_EXCEEDED when the guard alone is reverted, and passed 50 of 50 randomized runs.

No related open issue. CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112668&sha=3f7020cf4114402a81c9d3dd6e7bef755802e34b&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29

`geohashesInBoxPrepare` rejects reversed and NaN boxes, but not a box of zero
area whose bounds are merely equal: `latitude_max < latitude_min` is false when
the two are equal, and also for `-0.0 < 0.0`. Such a box aligns one axis to a
single grid line, so that axis' item count is zero while the other stays
enormous. For `(0., 0., 180., 0.)` at precision 12 that is
`longitude_items = 536870912` and `latitude_items = 0`, which makes
`items_count` `max(1, 536870912 * 0)` = 1 while `geohashesInBox` still walks
the outer axis in full with a zero-trip inner loop: 536 million iterations to
produce one geohash.

The row loop's cancellation checkpoint cannot help, because it is throttled on
accumulated items and each of these rows contributes a single unit. A whole
block of them stays orders of magnitude below the threshold, currently
`items_between_cancellation_checks = 100'000`, so `checkTimeLimit` is never
consulted and neither `max_execution_time` nor `KILL QUERY` is observed. That
is how a Stress test run sat in this loop for 714 s with `is_cancelled` already
set.

Reachable without a fuzzer: `SELECT geohashesInBox(0., 0., 180., 0., 12)` burns
the same ~5e8 iterations per row.

Skip the loops when either item count is zero and let the existing `items == 0`
fallback emit the single geohash the box degenerates to, so results are
unchanged. Measured on a debug build: 200 rows of the degenerate block go from
28.0 s to 0.11 s, and the unfixed arm overruns a `max_execution_time` deadline
by that same margin under either throttle value. A 1875-case sweep over boxes
and precisions is byte-identical before and after. The non-degenerate path is
untouched.
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold
read of the resulting code. One fix round.

# Sev Finding Verdict Evidence / action
1 ⚠️ The commit message asserted the row loop's cancellation checkpoint is throttled to fire at 1'000'000 accumulated items. That is the value at this branch point, not on master: 3f0e190150e2090 lowered it to 100'000. AGREE, fixed @ 68f57a0e Message rewritten to argue threshold-independently and to name the current value. The conclusion is unchanged and was measured against the new constant too: unguarded, the degenerate block still overruns a 1 s deadline at 27857 ms.
2 💡 The description quoted the same stale constant, and the #112273 provenance was visible only inside a non-rendering HTML comment. AGREE, fixed Both corrected in the description before publication.
3 ⚠️ Normalising the item counts in geohashesInBoxPrepare would be the tidier place for the guard. DISAGREE Behaviour-identical, so it buys nothing observable: longitude_items and latitude_items have no reader in the tree besides the loops now guarded. It would also sit beside the precision == 0 || step <= 0 early return, which yields zero items where this path must yield one, so merging the two conditions would silently change reversed and NaN boxes. Guarding the consumer keeps the 1875-case byte-identical result proof valid.
4 💡 The new test's timing oracle could be flaky, as 04648's latency assertions were. DROPPED on re-derivation Not the same class. The separation here is roughly 250x (28.0 s against 0.11 s under a 10 s deadline), not the 1.2x that was deflaked out of 04648, and neither max_execution_time nor timeout_overflow_mode is randomized by the test runner, so the oracle cannot be tuned away. 50 of 50 randomized runs passed.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-48:20260802-034600

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on demand: SELECT sum(length(geohashesInBox(materialize(0.), materialize(0.), 180., 0., toUInt8(12)))) FROM numbers(200) SETTINGS max_block_size = 200, max_threads = 1, max_execution_time = 1, timeout_overflow_mode = 'throw' returns Code: 159 ... elapsed 28013.728 ms, maximum: 1000 ms on a Debug build.
b Root cause explained? Equal bounds pass the reversed/NaN guard in geohashesInBoxPrepare (latitude_max < latitude_min is false for equal values, and for -0.0 < 0.0), so one axis collapses to a single grid line and its item count is 0. items_count becomes max(1, 536870912 * 0) = 1 while geohashesInBox still walks the outer axis ~2^29 times with a zero-trip inner loop. The caller's checkpoint is throttled on accumulated items_count and each such row contributes a single unit, so a whole block stays orders of magnitude below the threshold (currently items_between_cancellation_checks = 100'000) and checkQueryTimeLimit is never consulted.
c Fix matches root cause? Yes: the useless work is removed where it happens. Not a band-aid. Lowering the throttle was rejected (it would only make ~1e12 pointless iterations cancellable), as was rejecting equal-bounds boxes in geohashesInBoxPrepare (a user-visible behaviour change).
d Test intent preserved / new tests added? New test 04694_geohashes_in_box_degenerate_span pins both the timing contract and the result contract. No existing test weakened or removed.
e Both directions demonstrated? Yes. 200 rows: 28.35 s unfixed vs 0.11 s fixed; with max_execution_time = 10 the unfixed binary overruns to ~28 s while the fixed one honours the deadline. Mutation arm: reverting the guard reddens the three degenerate cases (Code: 159) while the four control cases stay green, so the test is not vacuous.
f Fix is general across code paths? geohashesInBox has exactly one caller (in FunctionGeohashesInBox::execute, src/Functions/geohashesInBox.cpp), so the fix covers the whole function, and both instantiations (Float64 and Float32) share these bodies. geohashEncode and geohashDecode have no nested item loops, so there is no analogous carrier. Fixed at the source, not guarded at the symptom site.
g Fix generalizes across inputs (params/datatypes/wrappers)? Carriers covered: zero latitude items (the bug), zero longitude items (symmetric, asserted as a liveness control), both zero, both non-zero, reversed/NaN (still []), invalid precision/step (untouched return 0 branch, deliberately not merged with the new condition), negative zero, Float32, precisions 1 to 12. A 1875-case sweep is byte-identical before and after. Nullable/LowCardinality do not apply: the change is in a numeric leaf helper that never sees a column.
h Backward compatible? (maintainer-approved exception only) Yes. No setting (so no SettingsChangesHistory.cpp entry), no serialization format, no error code, and no result change. A previously slow and uncancellable query becomes fast and cancellable.
i Invariants and contracts preserved? Yes. geohashesInBox still returns the number of items written and writes exactly that many precision-byte geohashes. Caller buffer accounting is unchanged: items_count was already 1 for these boxes and the items == 0 fallback already wrote exactly 1 item, so the resize/offsets arithmetic and both post-loop size-mismatch checks still hold. No allocation, ownership, locking or error path is touched.

Session id: cron:clickhouse-impl-slot-46:20260802-015300

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nikitamikhaylov @scanhex12, could you review this? A box of zero area passes the reversed and NaN guard in geohashesInBoxPrepare, which collapses one axis' item count to zero while the other stays at 2^29, so geohashesInBox walked 536 million iterations with a zero-trip inner loop to emit one geohash, below the caller's cancellation throttle the whole time. The fix skips the loops in that case and leaves the result byte-identical.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 2, 2026
@PedroTadim PedroTadim self-assigned this Aug 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [163657b]

Summary: ✅


AI Review

Summary

This PR fixes the geohashesInBox degenerate-axis liveness bug by skipping the nested grid walk when one axis has zero items and relying on the existing single-geohash fallback. I reviewed the current diff, the full PR discussion and review threads, the touched code paths, and the current CI state; I did not find a remaining correctness, cancellation, or test-oracle issue in the patch as it stands. Residual note: the function's line-degenerate result semantics still look preexisting and underspecified relative to the current docs, but the updated test now correctly avoids hardening that behavior.

Final Verdict

No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.80% +0.10%

Changed lines: Changed C/C++ lines covered: 11/11 (100.00%) · 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 2, 2026
… only

The review pointed out that asserting `['s00000000000']` for
`geohashesInBox(0., 0., 180., 0., 12)` freezes a preexisting result
question into the test contract. That box is a line segment, not a point,
so a precision-12 cover is not one cell, and both the documentation and
`FunctionDocumentation::ReturnedValue` state that non-strict bounds return
an empty array. Pinning the current output would make a later semantics
fix read as a regression against this reference file.

Measured on a debug build: that row passes unchanged with the guard
reverted (0.43 s, byte-identical output), so it never carried the oracle
and is pure surplus commitment. The liveness rows are what redden, at
~28 s against a 10 s deadline.

`sum(length(...))` carried the same claim less visibly, since a length of
1 per row is exactly the one-cell assertion. Both now use `ignore`, which
forces evaluation while asserting nothing about the result, so the test
reddens only on the behaviour this change actually fixes.

Re-verified both directions: green on the fixed binary, TIMEOUT_EXCEEDED
on the pristine one, and 50 of 50 randomized runs pass.
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 3, 2026
Merged via the queue into ClickHouse:master with commit 0738604 Aug 3, 2026
179 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 Aug 3, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @PedroTadim — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

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