Skip to content

Hypothetical (WHAT-IF) indexes - #104608

Merged
yariks5s merged 89 commits into
masterfrom
yarik/whatif-index
Jun 22, 2026
Merged

yariks5s merged 89 commits into
masterfrom
yarik/whatif-index

Conversation

@yariks5s

@yariks5s yariks5s commented May 11, 2026 •

Copy link
Copy Markdown
Member

Adds hypothetical (what-if) indexes: virtual, session-scoped skip indexes you can attach to a MergeTree table to see how a real skip index would affect a query, without actually building it on disk.

CREATE HYPOTHETICAL INDEX idx_b ON t (b) TYPE minmax GRANULARITY 1;
EXPLAIN WHATIF SELECT * FROM t WHERE b = 42;

EXPLAIN WHATIF runs the index over the baseline-pruned granules in memory and reports the exact skip ratio plus estimated marks and bytes. If empirical is disabled (empirical = 0) or can't produce a result, the estimator falls back to column statistics; if neither is available it reports an applicability-only summary.

Defined indexes are inspectable through the new system.hypothetical_indexes table and discarded when the session ends. Existing queries against the table are unaffected.

Changelog category (leave one):

  • New Feature

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

Added hypothetical (what-if) skip indexes. Use CREATE HYPOTHETICAL INDEX ... ON t (expr) TYPE ... to define a session-scoped virtual skip index, then EXPLAIN WHATIF SELECT ... to estimate its skip ratio and cost without materializing it. Defined indexes are visible in the new system.hypothetical_indexes table.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.1139

@clickhouse-gh

clickhouse-gh Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [11b78f5]

Summary: ✅


AI Review

Summary

This PR adds session-scoped hypothetical skip indexes through CREATE HYPOTHETICAL INDEX, DROP HYPOTHETICAL INDEX, EXPLAIN WHATIF, system.hypothetical_indexes, docs, and stateless coverage. The surface is coherent, but the estimator still has correctness, security, and resource-accounting issues in paths where it reads or summarizes data outside the normal MergeTree read pipeline.

Findings

❌ Blockers

  • [src/Storages/MergeTree/WhatIfIndexEstimator.cpp:303,390] [dismissed by author -- https://github.com/Hypothetical (WHAT-IF) indexes #104608#discussion_r3428030734] EXPLAIN WHATIF still does not honor row policies for either estimate source. The empirical scan is built without query_info.row_level_filter / prewhere_info, and the statistical fallback estimates directly from part statistics and the query predicate. A user with column-level SELECT can infer distributions for rows hidden by a row policy through skip_ratio / marks. The author compared this to EXPLAIN indexes=1, but this feature actively reads indexed columns and reports candidate-specific estimates, so it should either apply the effective row-policy predicate or return an unsupported/applicability-only result when a row policy is present.

⚠️ Majors

  • [src/Storages/MergeTree/WhatIfIndexEstimator.cpp:350] max_rows_to_read / max_bytes_to_read are enforced by counters local to one tryEstimateEmpirical call, but run invokes that call once per hypothetical index. A query with multiple candidates can therefore read the configured limit once per candidate, while users expect the settings to cap the whole EXPLAIN WHATIF query. Keep shared counters across candidate evaluations, or leave normal size limits attached so the progress path enforces the aggregate limit.
  • [src/Storages/MergeTree/WhatIfIndexEstimator.cpp:390] The empirical scan passes apply_deleted_mask = false to createMergeTreeSequentialSource, so lightweight-deleted rows remain in the blocks used to build the hypothetical granule. That makes the estimate depend on rows the real SELECT would not see. Pass the effective deleted-mask behavior through, or mark such parts unsupported.
  • [src/Storages/MergeTree/WhatIfIndexEstimator.cpp:519] sampled_marks is reported against data.getTotalMarksCount, which can include non-active parts, while the numerator comes from the query's active snapshot. After merges or mutations, the sampled fraction can be wrong. Derive the denominator from the same active/query-visible parts snapshot as analysis.parts_with_ranges.
  • [src/Storages/MergeTree/WhatIfIndexEstimator.cpp:372] [dismissed by author -- https://github.com/Hypothetical (WHAT-IF) indexes #104608#discussion_r3304600935] Empirical mode still constructs RangesInDataPart part_for_read(part), so selective queries read whole selected parts instead of only baseline mark ranges. On large tables with several candidates, EXPLAIN WHATIF can become a full-part scan even when the baseline is tiny. Either read only the baseline ranges or report empirical mode as unsupported when safe ranged reading is not available.
Final Verdict

❌ Changes requested. The estimator should be fixed before merge so EXPLAIN WHATIF respects row visibility, lightweight deletes, and query-level resource limits, and so its reported sampling denominator matches the active query snapshot.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 11, 2026
@nihalzp nihalzp self-assigned this May 11, 2026
@yariks5s yariks5s changed the title Hypothetical indexes Hypothetical (WHAT-IF) indexes May 11, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

index_columns,
std::nullopt,
std::make_shared<std::atomic<size_t>>(0),
false,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

EXPLAIN WHATIF should build the empirical candidate over the same row set that the SELECT would read, but this call hard-disables the lightweight-delete mask. The normal MergeTree read path uses apply_deleted_mask (true by default) to add the _row_exists filter when a part or patch has deleted rows; here those deleted rows remain in the block used by the hypothetical index aggregator. For example, after DELETE FROM t WHERE b = 42, a candidate on b can still see 42 from rows that are no longer visible to the query and report a different skip ratio/mark count than the real read contract. Please pass the effective apply_deleted_mask setting through to this source (or mark such parts unsupported) so the estimate does not depend on deleted rows.

result.index_name = index_desc.name;
result.index_type = index_desc.type;
result.total_parts = data.getActivePartsCount();
result.total_marks = data.getTotalMarksCount();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

total_marks is paired with sampled_marks in the output as sampled_marks: <baseline> / <total>, but this denominator comes from MergeTreeData::getTotalMarksCount, which iterates data_parts_by_info and includes non-active parts. After merges or mutations leave outdated parts in memory, the numerator is computed from the query's active snapshot while the denominator can include inactive marks, so the reported sampled fraction is wrong.

Please derive this from the same active/query-visible parts snapshot as the baseline analysis, or add an active-only marks helper so sampled_marks and sampled_parts use consistent denominators.

@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR is purely additive: it introduces a new EXPLAIN WHATIF variant plus CREATE/DROP HYPOTHETICAL INDEX statements, backed by a new session-scoped store and a separate estimator, alongside documentation. None of this touches the execution path that a normal ClickBench SELECT runs, so neither the flagged improvements (Q4 -18%, Q15 -13.5%) nor the flagged regressions (Q13 +12.6%, Q18 +6.2%) can plausibly be attributed to the change. All four flags have been downgraded to inconclusive as run-to-run variance. No action needed.

clickbench

⚠️ 4 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 266 217 -18.4% <0.0001 PR only adds EXPLAIN WHATIF/hypothetical-index DDL; plain SELECT hot path untouched, so this -18% is run-to-run variance
⚠️ 13 not_sure 493 555 +12.6% <0.0001 New WHATIF/hypothetical-index code is off the SELECT execution path; +12.6% not plausibly caused by this PR
⚠️ 15 not_sure 237 205 -13.5% <0.0001 Feature-only PR (new EXPLAIN variant + DDL); SELECT execution unchanged, so -13.5% is noise not a PR effect
⚠️ 18 not_sure 1334 1416 +6.2% 0.0001 Marginal +6.2% with noisy underlying measurements; PR adds only new DDL/EXPLAIN paths a SELECT never executes

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: 58353117-09c7-4e8a-a65d-a24b7d729989
  • MIRAI run: 834385b1-6f40-4396-9ddc-d5272247cc48
  • PR check IDs:
    • clickbench_66294_1782153675
    • clickbench_66300_1782153675
    • clickbench_66310_1782153675
    • tpch_adapted_1_official_66321_1782153675
    • tpch_adapted_1_official_66330_1782153675
    • tpch_adapted_1_official_66346_1782153675

@yariks5s
yariks5s added this pull request to the merge queue Jun 19, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jun 19, 2026
@yariks5s
yariks5s added this pull request to the merge queue Jun 19, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jun 19, 2026
@yariks5s
yariks5s added this pull request to the merge queue Jun 22, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jun 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.60% 92.50% -0.10%
Branches 77.60% 77.50% -0.10%

Changed lines: Changed C/C++ lines covered by tests: 675/865 (78.03%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 4 line(s) · Uncovered code

Full report · Diff report

@yariks5s
yariks5s added this pull request to the merge queue Jun 22, 2026
Merged via the queue into master with commit 7ef8534 Jun 22, 2026
329 of 330 checks passed
@yariks5s
yariks5s deleted the yarik/whatif-index branch June 22, 2026 22:34
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature 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