Skip to content

Add a regression test for the const / variable NaN-endpoint monotonicity guard - #119461

Merged
alexey-milovidov merged 7 commits into
masterfrom
arithmetic-monotonicity-nan-const-dividend
Oct 10, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
arithmetic-monotonicity-nan-const-dividend

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #118468, which declined divide/multiply monotonicity when a range endpoint maps to NaN. The guard there covers both operand orders, but its test 05113_arithmetic_monotonicity_nan_endpoint only exercised variable / const.

The const / variable branch has its own false-pruning shape. For inf / k over a range whose right end is +inf, inf / inf is NaN; the transform is decreasing, so KeyCondition inverts the range and the transformed NaN becomes the left bound — the same "no point compares into the range, prune everything" outcome, reached from the other side.

Verified against a binary built from current master, with positive and negative controls:

  • with the guard, EXPLAIN indexes = 1 for WHERE inf / k = inf reports Granules: 100/100 (nothing pruned) and the query returns all matching rows;
  • a finite constant dividend, WHERE 100 / k > 2, still prunes to Granules: 49/100, so pruning for ranges that stay finite is unaffected.

The test also covers const * variable (0 * k) and each pruning layer — the primary key index and use_statistics_for_part_pruning — on its own. basic column statistics are pinned on both tables and materialized on insert, because clickhouse-test randomizes auto_statistics_types and materialize_statistics_on_insert and StatisticsPartPruner is inert without a materialized basic or minmax statistic; the test also asserts that the pruner actually analyzes these transforms rather than assuming it. Since filterPartsByStatistics records an IndexStat only when it drops a part, that probe has to be the same transform shape with endpoints that stay finite, so the guard does not fire and pruning is allowed: 100 / k > 200 over [1, +inf] and, for multiply, 0 * k = 5 over [1, 100] — both must report a Statistics entry in EXPLAIN indexes = 1, while inf / k = inf must report none. Granule counts are compared rather than pinned, since the test runner randomizes the settings they depend on. Test only; no behavior change.

Addresses the review comment on #118468 (comment)

Related: #118468
Related: #118121

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/119461]

Version info

  • Merged into: 26.10.1.2082-master (included in 26.10 and later)

The `NaN`-endpoint guard added in #118468 declines `divide`/`multiply`
monotonicity for both operand orders, but `05113_arithmetic_monotonicity_nan_endpoint`
only exercised `variable / const`. The `const / variable` branch has its own
false-pruning shape: for `inf / k` over a range whose right end is `+inf` the
transform is decreasing, so `KeyCondition` inverts the range and the
transformed `NaN` becomes the left bound.

Verified against the current binary with positive and negative controls: with
the guard, `EXPLAIN indexes = 1` for `inf / k = inf` reports `Granules: 100/100`
and the query returns all matching rows, while a finite constant dividend
(`100 / k > 2`) still prunes down to `Granules: 49/100`.

Related: #118468

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [21e1bdc]

Summary: ✅


AI Review

Summary

This PR adds a focused stateless regression test for the const / variable and const * variable NaN-endpoint monotonicity guard, including liveness probes that pin the randomized statistics settings and keep the pruning-path coverage explicit. After checking the current diff, the resolved review threads, and the current all-green CI report, I do not see any remaining correctness, determinism, or coverage issues in the test.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Sep 11, 2026
…r is really covered

`clickhouse-test` randomizes `auto_statistics_types` and `materialize_statistics_on_insert`, and only
a materialized `basic` (or `minmax`) statistic gives the pruner the column min/max it reads: without
one, `StatisticsPartPruner::isUseless` is true and `filterPartsByStatistics` hands back every part
untouched. So the `use_primary_key = 0` queries, which exist to isolate the statistics layer, covered
nothing in the runs where the randomizer dropped `basic`.

Pin `auto_statistics_types = 'basic'` on both tables and `materialize_statistics_on_insert = 1` for
the inserts, and assert the layer is live: a predicate outside the part's `[1, +inf]` statistics range
still prunes the part, so `EXPLAIN indexes = 1` reports a `Statistics` entry.

Measured against a binary built from `master`, which already carries the guard, that new assertion is
what fails in exactly the windows the review pointed at:

- `auto_statistics_types = 'uniq_v2'`: `system.parts_columns` shows `['UniqV2']` with a `NULL`
  `estimates.min`, no `Statistics` entry in `EXPLAIN`, and `inf / k = inf` still returns `3` - the
  test passed while exercising nothing;
- `auto_statistics_types = 'basic'` with `materialize_statistics_on_insert = 0`: the statistics array
  is empty, again no `Statistics` entry;
- pinned and materialized: `['Basic']` with min `1` and max `inf`, and the `Statistics` entry appears.

`SET parallel_replicas_local_plan = 1` keeps both `EXPLAIN indexes = 1` checks on the local plan when
the runner enables parallel replicas.

Addresses #119461 (comment)
…s, not just that statistics exist

The previous liveness probe used `k < 0`, a plain comparison. That proves the table has materialized
`basic` statistics, but not that `StatisticsPartPruner` builds a condition for the *arithmetic*
predicate under test: `getKeyConditionForEstimates` returns `nullptr` when the condition is
`alwaysUnknownOrTrue`, so if the monotonic-function chain stopped being recognized on the statistics
path, every `use_primary_key = 0` query would answer by full scan and pass while covering nothing.

Nothing positive can be asserted on `inf / k = inf` itself: `filterPartsByStatistics` records its
`IndexStat` only when it actually drops a part, so a held guard and an unanalyzed predicate both show
no `Statistics` entry. The probe therefore has to be the same transform shape with endpoints that stay
finite, so the guard does not fire and pruning is allowed:

- `100 / k > 200` over `[1, +inf]` transforms to `[0, 100]`, cannot match, and must prune - so a
  `Statistics` entry appears (verified: `Parts: 0/1`);
- `0 * k = 5` over `[1, 100]` is the `multiply` counterpart. It needs a range without `+inf`, since
  `0 * inf` is exactly the `NaN` the guard declines. A non-zero multiplier would not work at all: the
  overflow check in `FunctionBinaryArithmetic::getMonotonicityForRange` dispatches on the result type
  and has no `Float` case, falling through to `: true /* unknown type */`, so `multiply` monotonicity
  is always declined for a `Float` result.

Also assert the complement - no `Statistics` entry for `inf / k = inf` - so the "keeps every part"
half of the contract is pinned explicitly rather than only through the row count, and pin
`explain_query_plan_default = 'legacy'` so the `%Statistics%` and `Granules:` matches do not depend on
the default plan printer, as `04811_statistics_part_pruning_nan_negation` does.

Re-ran the whole test clean under `enable_analyzer` 0/1, `explain_query_plan_default`
legacy/pretty, `optimize_move_to_prewhere = 0`, `materialize_statistics_on_insert = 0` (the in-test
`SET` overrides it), `use_statistics = 0` + `use_statistics_cache = 0`, `query_plan_merge_filters = 0`
and `merge_tree_coarse_index_granularity = 32`.

Addresses #119461 (comment)
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed in d8e2351. The finding is right: k < 0 proved the table
has materialized basic statistics, not that StatisticsPartPruner builds a condition for the
arithmetic predicate. getKeyConditionForEstimates returns nullptr when the condition is
alwaysUnknownOrTrue, so if the monotonic chain stopped being recognized on the statistics path, every
use_primary_key = 0 query would answer by full scan and pass while covering nothing.

One correction to the suggested fix, though. Asserting on inf / k = inf itself cannot distinguish the
two cases: filterPartsByStatistics records its IndexStat only when it actually drops a part, so
"the guard held" and "the predicate was never analyzed" both show no Statistics entry. The probe has
to be the same transform shape with endpoints that stay finite, so the guard does not fire and pruning
is allowed:

  • 100 / k > 200 over [1, +inf] transforms to [0, 100], cannot match, and must prune — Parts: 0/1
    in a Statistics entry, verified.
  • 0 * k = 5 over [1, 100] is the multiply counterpart, on the finite table because 0 * inf is
    exactly the NaN the guard declines. Note a non-zero multiplier cannot work at all here: the overflow
    check in FunctionBinaryArithmetic::getMonotonicityForRange dispatches on the result type and has no
    Float case, falling through to : true /* unknown type */, so multiply monotonicity is always
    declined for a Float result.

I also kept the complement you were after — asserting there is no Statistics entry for
inf / k = inf — so the "keeps every part" half of the contract is pinned explicitly rather than only
through the row count. And explain_query_plan_default = 'legacy' is now pinned as you asked, matching
04811_statistics_part_pruning_nan_negation.

Re-ran the whole test clean under enable_analyzer 0/1, explain_query_plan_default legacy/pretty,
optimize_move_to_prewhere = 0, materialize_statistics_on_insert = 0 (the in-test SET overrides it),
use_statistics = 0 + use_statistics_cache = 0, query_plan_merge_filters = 0, and
merge_tree_coarse_index_granularity = 32.

(The trailing reference in that commit message is a placeholder anchor, not a real permalink; the review
it addresses is #119461 (comment).)

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Stress test (arm_tsan) failed with a pre-existing flake, unrelated to this PR:

Logical error: 'Shard number is greater than shard count: shard_num=5 shard_count=1
cluster=test_cluster_one_shard_three_replicas_localhost'
  src/Interpreters/ClusterProxy/executeQuery.cpp:814: DB::ClusterProxy::prepareClusterForParallelReplicas

Report

Evidence that it is not caused by this change, from default.checks on play:

  • This signature fails on 1-5 unrelated pull requests every day for the last 60 days, and on master itself (pull_request_number = 0, 2026-09-04).
  • The exact bucket of this occurrence, STID: 5066-3bb2, has fired 11 times across 11 distinct pull requests since 2026-08-03 — it predates this branch. The signature has six such buckets in that window; the largest, 5066-457d, has 102 hits across 82 pull requests.
  • This PR adds only two stateless test files. It creates no Distributed table and no cluster, and shard_num=5 can only arrive as a _shard_num scalar from a distributed initiator.

Tracked by #101325 (open; #101490 was closed as a duplicate of it). A fix is already in progress and targets exactly this function: #113589 — "prepareClusterForParallelReplicas indexes the _shard_num scalar into cluster_for_parallel_replicas as if both described the same cluster", which is precisely the shard_num=5 / shard_count=1 mismatch seen here. So no separate investigation is needed.

The one remaining red, CH Inc sync, is also not this PR: private master's ci/workflows/*.py currently fail ruff, which drops every job in the private workflow. Fixed by a separate private pull request; every other sync pull request shows the identical failure.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch (it was 4017 commits behind) and re-verified the test locally at the
merged head cf7f4549b545, with a binary built from that exact tree:
05182_arithmetic_monotonicity_nan_const_dividend passes.

Status of the two reds on the previous head:

  • Stress test (arm_tsan) — the known Logical error: 'Shard number is greater than shard count' flake
    from prepareClusterForParallelReplicas, tracked by Logical error: Shard number is greater than shard count: shard_num=A shard_count=B cluster=C (STID: 5066-564d) #101325
    with a fix in progress in Bind the parallel replicas shard scope to the cluster that produced it #113589. Unchanged analysis from my
    earlier comment; this PR adds no code and creates no cluster.

  • CH Inc sync — no longer the private ruff breakage I described earlier; the private run for this PR
    (ClickHouse/clickhouse-private#74236) now fails only in three stress jobs, all on the stress smoke set
    00001_select_1 00234_disjunctive_equality_chains_optimization, which the stress harness runs with memory
    fault injection enabled:

    [1 / 2] 00234_disjunctive_equality_chains_optimization: [ FAIL ] 1.34 sec.
    Code: 241. DB::Exception: Query memory tracker: fault injected. Would use 263.14 KiB ...
      While executing AggregatingTransform. (MEMORY_LIMIT_EXCEEDED)
    

    The same test passes in the immediately preceding and following iterations of the same job. This PR's own
    test is not part of that job's selection at all, so the failure cannot come from it.

Everything else is green and there are no unresolved review threads.

@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

This is a test-only change: it adds one new stateless regression test (05182_arithmetic_monotonicity_nan_const_dividend) covering the const/variable NaN-endpoint monotonicity guard, plus internal tooling documentation. No production/query-execution code is touched, so it cannot plausibly move any ClickBench median. The single flagged query (Q28, -5.5%) is therefore treated as run-to-run variance and downgraded to not_sure; its measurements were noisier than baseline and the two tests disagreed, consistent with noise rather than a real shift.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1104 1043 -5.5% <0.0001 This PR adds only a new stateless regression test (.sql/.reference) plus internal tooling docs; no query-execution code changes. ClickBench Q28's -5.5% is run-to-run variance, not a PR effect.

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: 5cfb72e6-2142-4008-95d9-013f8b793552
  • MIRAI run: 584ff631-5ac7-4aa7-8578-0e5d4ccdc35a
  • PR check IDs:
    • clickbench_809856_1789777155
    • clickbench_809958_1789777160
    • clickbench_810061_1789777182
    • tpch_adapted_1_official_810220_1789777246
    • tpch_adapted_1_official_810358_1789777426
    • tpch_adapted_1_official_810573_1789777551

alexey-milovidov and others added 3 commits September 25, 2026 02:19
… liveness probes to an integer key

Add an `EXPLAIN indexes = 1` liveness probe with `use_statistics_for_part_pruning = 0` showing that
`KeyCondition` still skips granules for `0 * k = 5`, and a matching check that it keeps every granule
for `0 * k = 0` over a range ending at `+inf`.

Also move the statistics liveness probes from the `Float64` table to a `UInt64` one: after #107074 the
statistics pruner declines every function chain over a `Float` column (its min/max can hide a `NaN`),
so the `Float64` probes could no longer report a `Statistics` entry on current master.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Oct 10, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 10, 2026
Merged via the queue into master with commit 59e5104 Oct 10, 2026
150 checks passed
@alexey-milovidov
alexey-milovidov deleted the arithmetic-monotonicity-nan-const-dividend branch October 10, 2026 23:08
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 10, 2026
@clickhouse-gh clickhouse-gh Bot added comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... and removed comp-testing Test content only (no production code). labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... pr-not-for-changelog This PR should not be mentioned in the changelog 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.

2 participants