Skip to content

Add skip indices to query log - #87862

Merged
grantholly-clickhouse merged 66 commits into
ClickHouse:masterfrom
grantholly-clickhouse:add_skip_indexes_to_query_log
Mar 12, 2026
Merged

grantholly-clickhouse merged 66 commits into
ClickHouse:masterfrom
grantholly-clickhouse:add_skip_indexes_to_query_log

Conversation

@grantholly-clickhouse

@grantholly-clickhouse grantholly-clickhouse commented Sep 29, 2025 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Improvement

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

We now track any data skipping indices that were used during query execution in the query_log table in a new column named skip_indices. Fixes #78676. Original author @pheepa

Documentation entry for user-facing changes

Adds a new Array[String] column to system.query_log for any data skipping indexes used during query execution

Details

Here I am trying to add the list of skip indexes used during execution to the query_log table. I want to add the skip index to the QueryAccessInfo if we actually used the skip index to further filter down granules. I don't want to add the skip index if it is only considered during planning. The new query_log table should have an array column where we keep all the skip indexes that were used during the query. I'm grabbing the index name from the index condition type, and I hope, because I'm not sure, that this should match the name we use for the data_skipping_indexes.name column.

I borrowed heavily from the way that we track projections and views, hence the new method, and array type column.

My hope is that this will provide another way to troubleshoot ClickHouse queries and index utilization.


Note

Medium Risk
Adds a new system.query_log column and populates it from MergeTree skip-index filtering, which changes query log schema and touches MergeTree index analysis paths. Risk is mostly around correctness/compatibility of log output and potential overhead when collecting index names.

Overview
Adds a new skip_indices Array(LowCardinality(String)) column to system.query_log and documents it in query_log.md.

Plumbs skip-index usage through Context::QueryAccessInfo and QueryLogElement, and records fully-qualified skip index names when MergeTree skip indexes are actually used to filter ranges (MergeTreeDataSelectExecutor). Includes a new stateless test validating skip_indices output for simple filters and JOIN scenarios.

Written by Cursor Bugbot for commit b235a3b. This will update automatically on new commits. Configure here.

@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b235a3b]

Summary: ✅


AI Review

1) Summary

This PR adds skip_indices into system.query_log by collecting skip-index usage from MergeTree read planning and wiring it through Context, QueryLogElement, and docs/tests. The implementation is close, but I found two correctness issues in how index names are encoded and when an index is considered “used”, so the current version should not be merged as-is.

2) Missing context (if any)

  • No CI report links/logs were provided in the review request.
  • No benchmark/perf report was provided for potential overhead in query-log collection on index-heavy queries.

3) Findings (by severity)

Blockers

  • None.

Majors

  • [src/Interpreters/Context.cpp:2578] skip_index_name is appended without backQuoteIfNeed, unlike other query-access fields. For quoted identifiers (including names with dots/reserved words), query_log.skip_indices can be ambiguous or incorrect.
    • Suggested fix: use query_access_info->skip_indices.emplace(full_table_name + "." + backQuoteIfNeed(skip_index_name));.
  • [src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp:1092-1093] Logging uses all skip_indexes.useful_indices before per-part checks (can_use_index, early-empty-range short-circuit). This can report indices as “used” even when they were never actually applied to any part.
    • Suggested fix: collect used index names from final runtime evidence (e.g., skip_index_used_in_part / per-index stats) and log only those with actual application.

4) Tests & Evidence

  • Positive coverage: new stateless test verifies empty/single/multiple index names and JOIN case are propagated to query_log.skip_indices.
  • Negative/error-path coverage: missing for quoted skip-index identifiers and for candidate-but-not-applied indexes.
  • Add tests for: (1) quoted index name like `idx.with.dot` and `select`; (2) scenario where index is in candidate set but skipped for all parts (e.g., per-part exclusion path) to ensure it is not logged.

5) ClickHouse Compliance Checklist (Yes/No + short note)

  • Data deletions logged? Yes — no deletion behavior changed.
  • Serialization formats versioned? No — system.query_log schema changed additively; no explicit versioning in scope.
  • Experimental setting gate present? No (not required) — additive observability field.
  • Settings exposed for constants/thresholds? Yes — no new constants introduced.
  • Backward compatibility preserved? Mostly yes — additive column; existing readers selecting explicit columns are unaffected.
  • SettingsHistory.cpp updated for new/changed settings? Yes (N/A) — no setting changes.
  • Existing tests untouched (only additions)? Yes — one new stateless test added.
  • Docs/user-facing notes updated? Yes — query_log docs include skip_indices.
  • Core-area change got extra scrutiny? Yes — reviewed MergeTree index filtering + query log wiring.

6) Performance & Safety Notes

The extra query-log collection is low overhead (std::set insertions per used index), but current placement may over-report usage and add unnecessary inserts for unused candidates. No memory/lifetime or concurrency exceptions were found in the added locking path; QueryAccessInfo mutex usage is consistent.

7) User-Lens Review

The feature is useful and intuitive for observability, but users may be misled by incorrect naming/usage semantics in skip_indices for edge cases. Error/log quality is otherwise unchanged and actionable.

8) Final Verdict

  • Status: Request changes
  • Minimum required actions:
    1. Quote skip-index identifiers in Context::addSkipIndexAccessInfo.
    2. Log only actually applied skip indexes, not all candidates from useful_indices.
    3. Add targeted tests for quoted index names and non-applied candidate indexes.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Sep 29, 2025
@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 30, 2025
@grantholly-clickhouse

grantholly-clickhouse commented Oct 1, 2025 •

Copy link
Copy Markdown
Contributor Author

As of now, this PR will record any skip indexes picked in MergeTreeDataSelectExecutor::filterPartsByPrimaryKeyAndSkipIndexes.

Here's an example of how it works

SHOW CREATE TABLE users

Query id: 1e7c7600-2229-4dfd-9863-dd06ea258d75

   ┌─statement───────────────────────────────────────────────────────┐
1. │ CREATE TABLE test.users                                        ↴│
   │↳(                                                              ↴│
   │↳    `uid` Int16,                                               ↴│
   │↳    `name` String,                                             ↴│
   │↳    `age` Int16,                                               ↴│
   │↳    `parent_id` Int16,                                         ↴│
   │↳    INDEX age_i age TYPE set(10) GRANULARITY 2,                ↴│
   │↳    INDEX name_i name TYPE tokenbf_v1(8192, 1, 0) GRANULARITY 1↴│
   │↳)                                                              ↴│
   │↳ENGINE = MergeTree                                             ↴│
   │↳ORDER BY uid                                                   ↴│
   │↳SETTINGS index_granularity = 8192                               │
   └─────────────────────────────────────────────────────────────────┘

EXPLAIN indexes = 1
SELECT count()
FROM users
WHERE name LIKE 'G%'

Query id: 9f6fe29e-3305-40b4-b665-14beff639815

    ┌─explain────────────────────────────────────────────────────────────┐
 1. │ Expression ((Project names + Projection))                          │
 2. │   Aggregating                                                      │
 3. │     Expression (Before GROUP BY)                                   │
 4. │       Filter ((WHERE + Change column names to column identifiers)) │
 5. │         ReadFromMergeTree (test.users)                             │
 6. │         Indexes:                                                   │
 7. │           PrimaryKey                                               │
 8. │             Condition: true                                        │
 9. │             Parts: 1/1                                             │
10. │             Granules: 123/123                                      │
11. │           Skip                                                     │
12. │             Name: name_i                                           │
13. │             Description: tokenbf_v1 GRANULARITY 1                  │
14. │             Parts: 1/1                                             │
15. │             Granules: 123/123                                      │
16. │           Ranges: 1                                                │
    └────────────────────────────────────────────────────────────────────┘

SELECT count()
FROM users
WHERE name LIKE 'G%'

Query id: af9026b2-3621-4fce-8d3e-a47ee6bfc88b

   ┌─count()─┐
1. │    9481 │
   └─────────┘

SELECT skip_indexes
FROM system.query_log
WHERE query_id = 'af9026b2-3621-4fce-8d3e-a47ee6bfc88b'

Query id: c452e765-ad3b-4a57-a8dd-b60fdbc9fbf6

   ┌─skip_indexes─┐
1. │ ['name_i']   │
2. │ ['name_i']   │
   └──────────────┘

While there are cases where a skip index could be selected as useful by this point and yet not filter any granules or ranges, I think I want to soften my original goal and intent of only reporting skip indexes that actually filtered ranges or granules. I think this makes more sense to the user if a skip index is shown in EXPLAIN indexes=1 SELECT ... and that index shows up in the query_log table. It would be confusing to see a skip index as being used in the explain, but then it doesn't show up in the query_log table. This would be the case if, for example, a query uses a skip index, but the skip index doesn't remove any granules because it only changes the ranges to read.

Here's that scenario

SHOW CREATE TABLE users

Query id: 1e7c7600-2229-4dfd-9863-dd06ea258d75

   ┌─statement───────────────────────────────────────────────────────┐
1. │ CREATE TABLE test.users                                        ↴│
   │↳(                                                              ↴│
   │↳    `uid` Int16,                                               ↴│
   │↳    `name` String,                                             ↴│
   │↳    `age` Int16,                                               ↴│
   │↳    `parent_id` Int16,                                         ↴│
   │↳    INDEX age_i age TYPE set(10) GRANULARITY 2,                ↴│
   │↳    INDEX name_i name TYPE tokenbf_v1(8192, 1, 0) GRANULARITY 1↴│
   │↳)                                                              ↴│
   │↳ENGINE = MergeTree                                             ↴│
   │↳ORDER BY uid                                                   ↴│
   │↳SETTINGS index_granularity = 8192                               │
   └─────────────────────────────────────────────────────────────────┘

1 row in set. Elapsed: 0.001 sec. 


EXPLAIN indexes = 1
SELECT count()
FROM users
WHERE name LIKE 'Z%'

Query id: 7922cfab-0be9-4b9f-9b1b-16553f20c6ea

    ┌─explain────────────────────────────────────────────────────────────┐
 1. │ Expression ((Project names + Projection))                          │
 2. │   Aggregating                                                      │
 3. │     Expression (Before GROUP BY)                                   │
 4. │       Filter ((WHERE + Change column names to column identifiers)) │
 5. │         ReadFromMergeTree (test.users)                             │
 6. │         Indexes:                                                   │
 7. │           PrimaryKey                                               │
 8. │             Condition: true                                        │
 9. │             Parts: 1/1                                             │
10. │             Granules: 123/123                                      │
11. │           Skip                                                     │
12. │             Name: name_i                                           │
13. │             Description: tokenbf_v1 GRANULARITY 1                  │
14. │             Parts: 1/1                                             │
15. │             Granules: 123/123                                      │
16. │           Ranges: 1                                                │
    └────────────────────────────────────────────────────────────────────┘

SELECT count()
FROM users
WHERE name LIKE 'Z%'

Query id: 621544ac-3121-484a-9fb7-e2baac20f0b3

   ┌─count()─┐
1. │    9605 │
   └─────────┘

SELECT skip_indexes
FROM system.query_log
WHERE query_id = '621544ac-3121-484a-9fb7-e2baac20f0b3'

Query id: b314ec48-d17b-4728-ba20-b0f3488daf14

   ┌─skip_indexes─┐
1. │ []           │
2. │ []           │
   └──────────────┘

I think it would be more appropriate to have skip index utilization broken down by granules dropped or ranges added as metrics with their own counters.

Comment thread src/Interpreters/Context.cpp Resolved
@azat azat self-assigned this Oct 6, 2025
Comment thread src/Interpreters/Context.cpp Resolved

@azat azat left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In general looks ok, I've adjusted title and description and wrote couple of comments, PTAL

Also, it will be nice to support amount of filtered out granules, but this has some complexity due to recently added use_skip_indexes_on_data_read (though it should not be hard to do), what do you think?

Also, maybe we need to add Co-authored-by for the author from #79635, to give him credits?

Comment thread src/Interpreters/Context.cpp Resolved
Comment thread src/Interpreters/Context.h Resolved
Comment thread src/Interpreters/Context.cpp Resolved
after `useful_indices` has been built.  I've added some checks make sure
we have a valid query context
@grantholly-clickhouse

Copy link
Copy Markdown
Contributor Author

Also, maybe we need to add Co-authored-by for the author from #79635, to give him credits?

I think it would be great to add that to ensure the original contributor gets credit. Do we add the contributor's name to a git commit? How do we do this?

@alexey-milovidov

alexey-milovidov commented Mar 9, 2026 •

Copy link
Copy Markdown
Member

Mention in the changelog entry, e.g., "Original author: @..."
No need to edit commits.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

@alexbakharew

Copy link
Copy Markdown
Contributor

Hi @grantholly-clickhouse,
could you please merge master into your branch? It will resolve LLVM Coverage issue

throw Exception(ErrorCodes::LOGICAL_ERROR, "Global context cannot have query access info");

std::lock_guard lock(query_access_info->mutex);
query_access_info->skip_indices.emplace(full_table_name + "." + skip_index_name);

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.

addSkipIndexAccessInfo concatenates <db.table>. and skip_index_name without quoting. For quoted index identifiers (for example names with dots or reserved words), system.query_log.skip_indices can become ambiguous or incorrect. Please use backQuoteIfNeed(skip_index_name) here, consistent with other query access info fields.

if (!skip_indexes.useful_indices.empty() && context->hasQueryContext())
{
auto query_context = context->getQueryContext();
for (const auto & idx : skip_indexes.useful_indices)

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.

This logs every entry from skip_indexes.useful_indices before per-part checks. Some of these can be skipped for all parts by can_use_index/short-circuiting, so query_log.skip_indices may report an index as used even when it filtered nothing. Please log only indices actually applied (for example, based on skip_index_used_in_part or final per-index stats).

@clickhouse-gh

clickhouse-gh Bot commented Mar 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.80% 83.80% +0.00%
Functions 23.90% 23.90% +0.00%
Branches 76.30% 76.30% +0.00%

PR changed lines: PR changed-lines coverage: 92.31% (72/78)
Diff coverage report
Uncovered code

@grantholly-clickhouse
grantholly-clickhouse added this pull request to the merge queue Mar 12, 2026
Merged via the queue into ClickHouse:master with commit ecac6cc Mar 12, 2026
787 of 796 checks passed
@grantholly-clickhouse
grantholly-clickhouse deleted the add_skip_indexes_to_query_log branch March 12, 2026 15:55
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 12, 2026
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-improvement Pull request with some product 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.

system.query_log should record if the query used skip indexes

6 participants