Skip to content

Fix set and text skip indexes and projections dropping rows for conditions with non-deterministic functions - #122787

Merged
PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-skip-index-non-deterministic-condition
Nov 13, 2026
Merged

PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-skip-index-non-deterministic-condition

Conversation

@groeneai

@groeneai groeneai commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #89615

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 wrong results for a query whose condition calls a non-deterministic function such as rand or generateUUIDv4 on a table with a set skip index, a text index on mapKeys or JSONAllPaths, an aggregate projection or a projection index: the function was computed on index values or projection rows instead of once per row, so WHERE rand() % 2 = 0 could return about a quarter of the rows instead of half, or keep or drop whole groups. Closes #89615.

Description

On 26.8.10.6, SELECT count() FROM t WHERE rand() % 2 = 0 over a table with a set skip index returns 20106 of 80000 rows instead of about 40000 (39969 with use_skip_indexes = 0; also 26.3 and 26.9).

Root cause. Some index and projection paths compute the query condition on rows that are not the table rows, so a non-deterministic function is drawn per stored value instead of per row:

  • the set index, on the distinct values of each granule (and checkDAGUseless counted a zero-argument rand() as usable);
  • the text index paths for mapKeys(m) and JSONAllPaths(j), once on the default value, checking determinism only on the root;
  • an aggregate projection, once per group for the filter and the GROUP BY keys, so whole groups were kept or dropped;
  • the projection index (INDEX b TYPE basic), on the projection rows before the read computes it again, so b = 5 AND rand() % 2 = 0 sampled twice.

Change. These paths now refuse a function that is not deterministic within the query (isDeterministicInScopeOfQuery, as KeyCondition does): the set index before matching an index column by name, analyzeAggregateProjection for keys and filter, and restrictFilterDAGToInputs, so the projection index still filters by b = 5. Constants folded from now(), getSetting or randConstant() keep pruning. A condition whose only indexed atom calls such a function no longer uses the index, so force_data_skipping_indices reports INDEX_NOT_USED for it. minmax, bloom_filter, tokenbf_v1, ngrambf_v1, the primary key and normal projections were measured unaffected.

Validation. Two tests check row and group counts within a tolerance (rand, rand(id), generateUUIDv4, lambdas, if, OR/AND, PREWHERE, DISTINCT, GROUP BY, a set index on a column named rand()) and index and projection usage in EXPLAIN, next to deterministic controls. On master every count row except the controls fails; 50/50 randomized runs pass.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2167-master (included in 26.11 and later)

groeneai and others added 2 commits September 28, 2026 18:13
The `set` skip index computes the query condition on the distinct values it
stores for each granule and skips a granule when none of them passes. A
function that can return another value on each evaluation, such as `rand`,
was copied into that computation like any other function, so it was drawn
once per stored value instead of once per row, and a granule was skipped when
that draw failed although about half of its rows pass their own draw. A plain
sampling filter `WHERE rand() % 2 = 0` on a table with a `set` index returned
about a quarter of the rows. `checkDAGUseless` also treated `rand()` as usable
because it has no arguments, so the index was applied to a condition that
references no indexed column at all.

The `text` index had the same defect on its `mapKeys(m)` and `JSONAllPaths(j)`
paths: they evaluate the whole atom once on the default value, skip every
granule without the key or path when the result is false, and checked
determinism only on the root node of the atom.

Refuse such a function where the index copies or evaluates it, with
`isDeterministicInScopeOfQuery`, the predicate `KeyCondition` and the
virtual-column filter already use. Constants folded from `now`, `getSetting`
or `randConstant` keep working, so no deterministic condition loses pruning.

The test pins `text_index_posting_list_block_size` to its default on the text
index tables: with the small block sizes the randomizer draws, the index
cannot skip granules for this data at all, so those rows could not tell a
fixed build from a broken one.

ClickHouse#89615

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…index

A function node is named like a column with that text (`rand()`), so on a
table with a set index over a column named `rand()` the query's `rand()` was
bound to the stored column before the determinism check ran. Check it first
in both `atomFromDAG` and `checkDAGUseless`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Sep 29, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex; round 1 full pass: 1 finding; round 2 delta recheck: 2 findings), plus my own review (1 nit).

# Sev Finding Verdict Evidence / action
1 ❌ A stored column named rand() under a set index was matched by name before the new check, so the query's rand() read the stored column (MergeTreeIndexSet.cpp, atomFromDAG / checkDAGUseless) AGREE, fixed @ 3843270 Both checks now run before the index-column name lookup; three test rows on a set index over a UInt32 column named rand()
2 💡 The test header says 35 standard deviations, the id = 1 AND rand window was about 28 AGREE, fixed @ 3843270 Window widened to 7500..12500
3 ❌ A deterministic call named like a stored column (plus(rand(), 1)) is still matched by name before its rand argument is looked at DISAGREE The same name match drops rows for a deterministic call too (set index over a column named plus(id, 1), WHERE id + 1 = 5: 0 rows vs 1 with the index off, also on master): the cause is binding a function to a stored column by name, not determinism. Not changed here.
4 ❌ With secondary_indices_enable_bulk_filtering = 0, the KeyCondition pre-check in mayBeTrueOnGranule still binds rand() to a stored column named rand() DISAGREE KeyCondition binds by name the same way for the primary key, deterministic call or not (column named rand(): 0 rows vs 40019; plus(id, 1): 0 vs 1, on master). Not changed here.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-self-slot-58:20260928-223100

@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a6d88cb]

Summary: ✅


AI Review

Summary

The PR prevents non-deterministic predicates from filtering index values or aggregate projection rows. Both added regression tests pass on the binary built from head a6d88cbe608d30fce5a1a4adf02a30cfe487c050. However, two previously dismissed column-name collisions still cause the set index to discard matching rows. These remain correctness findings; no duplicate inline comments were posted.

Findings

❌ Blockers

  1. A deterministic parent hides a non-deterministic child before index-column matching. MergeTreeIndexSet.cpp:669, also line 839. [dismissed by author -- https://github.com/Fix set and text skip indexes and projections dropping rows for conditions with non-deterministic functions #122787#issuecomment-5881328725]

    The checks inspect only the current function. A stored UInt8 column named modulo(rand(), 2), indexed with set(0) and filled with 1, matches the deterministic modulo node before either walk reaches its rand child. On 8000 rows, WHERE rand() % 2 = 0 returns 0 with either bulk-filtering mode, versus 4020 with use_skip_indexes = 0.

    The author classifies this as the older name-binding defect. It still bypasses the new determinism guard and violates the PR's explicit column-name collision coverage. Check the entire expression before accepting a computed node as an indexed column, in both atomFromDAG and checkDAGUseless, or explicitly track this remaining case outside the issue being closed.

  2. The per-granule pre-check can still bind rand to a stored column. MergeTreeIndexSet.cpp:437, bypassing the new guards at lines 669 and 839. [dismissed by author -- https://github.com/Fix set and text skip indexes and projections dropping rows for conditions with non-deterministic functions #122787#issuecomment-5881328725]

    With columns id UInt64, a stored UInt32 column named rand() containing 1, and a set(0) index on both columns, WHERE id < 10 AND rand() > 2147483647 still loses every row when secondary_indices_enable_bulk_filtering = 0. Using 8000 rows with id cycling through 0–3, the PR-head binary returns 0, versus 4007 with bulk filtering and 3962 with skip indexes disabled. condition.checkInHyperrectangle rejects the granule before the sanitized actions execute: KeyCondition matches the function name to the stored column before checking determinism.

    The author also dismissed this as the older name-binding defect. The current fix nevertheless leaves a supported set filtering mode returning wrong results for the directly tested rand() collision. Apply the same determinism restriction to the pre-check, or explicitly track this remaining case separately.

Tests
  • ⚠️ Add focused coverage for a deterministic expression containing rand whose name matches an indexed column, and for a direct rand() collision with an inequality and bulk filtering disabled. The current modulo-based direct-collision test does not exercise the failing KeyCondition pre-check.
Final Verdict

❌ Block. Close the two remaining pruning gaps and add their regressions, or link explicit follow-up issues and narrow the claimed fix. Existing projection, full skip-index, nested-lambda, and randConstant controls passed locally.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 29, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 29, 2026
…nd` condition

The `json path` row only counts rows, so a broken build can pass it by
chance: when its single planning-time draw of `rand` succeeds, or when rows
without the path are read from a granule the index cannot skip. Add an
`EXPLAIN indexes = 1` row that the `ji` index is not used for that condition,
as the map keys case already does.

ClickHouse#122787 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a6d88cbe6 with master a5578f1a8 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.68, programs/clickhouse-keeper ×0.69 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.5 s 14.5 s +10.7 s (+286%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.3 s 7.5 s +5.2 s (+236%)
Compile time of recompiled translation units

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

Job report

…maller

The flaky check runs eight copies of a new test at once with the thread
fuzzer on, and this test took 244-300 s per run there, over the 180 s limit.
Most of it was the inserts into the `set` index tables: the index aggregator
filters the whole inserted block once per granule, so with one granule per
8 rows the cost of an 80000-row insert grows with the square of the row count.

Use 8000 rows and scale the tolerance windows with them; each window is still
at least 11 standard deviations wide. The map and JSON rows use `rand() % 100`
so that about 40 rows without the key still pass on a correct build.
On master every non-control row still fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ba2a001

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
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) not caused by this PR: after the upgrade, the mutation of part 20150101_20150101_0_0_0_2 of the 04907 fixture table test_1.v0_r2 is not byte-identical to the replica that mutated on the previous release (CHECKSUM_DOESNT_MATCH on the compressed files, LZ4 on both servers); the same part failed this way on 3 other unrelated PRs since 2026-09-20 a fix task is created (investigating at full effort, fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260929-090225

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Upgrade check (amd_release) CHECKSUM_DOESNT_MATCH on the 04907 fixture in the CI finish ledger: #123376.

…deterministic-condition

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9cf5886

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
Fast test / 02317_distinct_in_order_optimization_explain flaky, not from this PR: the two max_threads = 0 checks lose their algorithm: Thread line. It failed on 8 other PRs and on master since 2026-10-14 02:40 UTC; this PR only changes skip-index conditions #125742 (mine, open)
Finish Workflow / Post Hooks, Mergeable Check, PR rollups of the row above: the Fast test failure dropped both Bugfix validation (functional tests) jobs, so the new-tests check finds no validated bug fix #125742 (mine, open)

The Fast test failure dropped 88 dependent jobs, so only the four Build (arm_tidy) shards, Style check and Fast test have results on this head.

Session id: cron:our-pr-ci-monitor:20261014-153008

@PedroTadim PedroTadim self-assigned this Nov 12, 2026
Two projection paths had the same defect as the `set` and `text` skip
indexes: they compute the query's filter on rows that are not the table
rows, so a function that can return another value on each evaluation,
such as `rand`, decides for many rows at once or is drawn twice.

- An aggregate projection computes the filter and the GROUP BY keys once
  per projection row, that is once per group. With
  `PROJECTION p (SELECT k, count() GROUP BY k)`, the query
  `SELECT k, count() FROM t WHERE rand() % 2 = 0 GROUP BY k` kept or
  dropped whole groups (56 of 100 groups, each with all of its rows),
  and `GROUP BY k, rand() % 2` returned 100 groups instead of 200. The
  same happened for PREWHERE and DISTINCT. Only the implicit
  `_minmax_count_projection` was excluded for such a filter. Now
  `analyzeAggregateProjection` rejects any aggregate projection whose
  keys or filter are not deterministic in the scope of the query.

- The projection index (`PROJECTION p INDEX b TYPE basic`) computes the
  part of the filter it can compute from the projection columns on the
  projection rows to find the table rows to read, and the read then
  computes the whole filter again, so `WHERE b = 5 AND rand() % 2 = 0`
  sampled twice: 2529 of 10000 rows instead of about 5000, and 72064 of
  200000 instead of about 100000 with default settings on a table of
  2000000 rows. `restrictFilterDAGToInputs`, used only for this, now
  treats such a function as not computable, so the projection keeps
  filtering by `b = 5` and the `rand` conjunct is computed once.

Measured on master 7a987ba (debug), which also confirms the other
skip index types (`minmax`, `bloom_filter`, `tokenbf_v1`, `ngrambf_v1`,
the other `text` index paths) and normal projections do not have it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Fix set and text skip indexes dropping rows for conditions with non-deterministic functions Fix set and text skip indexes and projections dropping rows for conditions with non-deterministic functions Nov 12, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit 44e71f9 Nov 13, 2026
203 checks passed
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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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.

Index set acts on rand function

3 participants