Skip to content

Predicate statistics log (selectivity collection) - #98727

Merged
yariks5s merged 96 commits into
masterfrom
yarik/predicate-statistics-system-table
Apr 23, 2026
Merged

yariks5s merged 96 commits into
masterfrom
yarik/predicate-statistics-system-table

Conversation

@yariks5s

@yariks5s yariks5s commented Mar 4, 2026 •

Copy link
Copy Markdown
Member

Adds system.predicate_statistics_log — a new system log that records sampled filter selectivity and MergeTree index-granule reduction during query execution. Motivation: the upcoming physical-design advisor needs workload-driven signal on how selective real predicates are and which indexes actually prune granules, to recommend indexes and projections.

Controlled by a new server setting predicate_statistics_sample_rate (default 0 = disabled; 1 = every query; N > 1 = roughly 1/N of queries, hashed by query_id)
Two row shapes share the table and link via query_id:

  • Filter rows — one per prewhere/filter step: predicate_expression, input_rows, passed_rows, filter_selectivity, plus the whole-predicate total_* columns
  • Index rows — one per read step: arrays of per-stage index_names / index_types / total_granules / granules_after / index_selectivities

Example:

SET predicate_statistics_sample_rate = 1;
SELECT * FROM hits WHERE URL LIKE '%/product/%' AND EventDate >= today() - 7 FORMAT Null;
SYSTEM FLUSH LOGS predicate_statistics_log;

SELECT query_id, predicate_expression,
       round(filter_selectivity, 3) AS step_sel,
       round(total_selectivity, 3) AS query_sel,
       index_names, index_selectivities
FROM system.predicate_statistics_log
WHERE table = 'hits'
ORDER BY event_time DESC LIMIT 10;

Changelog category (leave one):

  • Improvement

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

Added system.predicate_statistics_log, a new sampled log of predicate filter selectivity and MergeTree index-granule pruning per query. Disabled by default; enable via the predicate_statistics_sample_rate server setting. Needed for automatic index and projection recommendations

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

Medium Risk
Adds new logging in hot query-execution paths (FilterTransform and ReadFromMergeTree) controlled by a new server setting; while default-disabled, enabling it could add CPU/memory overhead and increase system log write volume.

Overview
Introduces a new system log table, system.predicate_statistics_log, to record sampled selectivity data for query predicates and MergeTree index stages.

Adds server setting predicate_statistics_sample_rate (default 0/disabled) plus config stanzas to create/flush the new log, wires the log into SystemLog/Context, and implements collection in FilterTransform (per-predicate chunk selectivity via a new PredicateAtomExtractor) and ReadFromMergeTree (per-index granule selectivity arrays). Includes a stateless test that enables the setting via config reload and validates log output.

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

Version info

  • Merged into: 26.5.1.31

@clickhouse-gh

clickhouse-gh Bot commented Mar 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [efc1cdd]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_binary_excluded_from_llvm) FAIL
test_trace_log_memory_context/test.py::test_memory_context_in_trace_log FAIL cidb
Unit tests (msan) ERROR

AI Review

Summary

This PR introduces system.predicate_statistics_log and wires predicate/index selectivity logging into MergeTree read paths under predicate_statistics_sample_rate. Verdict: ⚠️ Request changes — there are still correctness and reliability issues in the emitted metrics and test/doc completeness.

Missing context
  • ⚠️ No CI logs or benchmark results were provided in this review context.
Findings
  • ❌ Blockers

    • [src/Interpreters/Context.cpp:6154] Context::getPredicateStatisticsLog dereferences shared before checking it. Neighboring getters in this area guard shared first; this path can hit invalid access during teardown/lifecycle edge paths.
      • Suggested fix: mirror the getAggregatedZooKeeperLog guard pattern (mutex_shared_context + if (!shared) return {};) before taking shared->mutex.
    • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:3354] The first index stage can get total_granules == stat.num_granules_after when no prior baseline was captured, so first-stage selectivity becomes 1.0 even when filtering happened.
      • Suggested fix: initialize baseline from pre-stage granule count (IndexType::None summary row or equivalent explicit input), and avoid fabricating denominator from post-stage value.
  • ⚠️ Majors

    • [tests/queries/0_stateless/04011_predicate_statistics_log.sh:84,92,102,110,128] Assertions are vulnerable to stale log rows because they only filter by deterministic query_id/table and do not isolate this test run by time window or pre-cleaning.
      • Suggested fix: truncate/isolate rows before running checks or constrain assertions to rows with event_time/event_date from this run.
    • [tests/queries/0_stateless/04011_predicate_statistics_log.sh:77-149] The test validates only filter-side fields and does not assert the index-side payload (index_names, index_types, total_granules, granules_after, index_selectivities) introduced by this PR.
      • Suggested fix: add explicit assertions for index rows and invariants (array sizes match, granules_after <= total_granules, 0 <= index_selectivities <= 1).
    • [docs/en/operations/system-tables/predicate_statistics_log.md:1-7] New docs page frontmatter is missing required sidebar_label and sidebar_position.
      • Suggested fix: add both fields to align with docs requirements for new pages.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ⚠️ Core execution paths touched; issues remain in sampling/logging correctness and lifecycle safety.
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ✅
PR metadata quality ✅
Safe rollout ⚠️ Default is disabled, but incorrect first-stage index selectivity can mislead downstream consumers.
Compilation time ✅
No large/binary files ✅
Performance & Safety
  • PredicateStatisticsLog sampling is gated, but logging still runs in hot read paths when enabled; incorrect denominator initialization in index-stage selectivity currently produces misleading telemetry for first-stage pruning.
  • Context::getPredicateStatisticsLog has a lifecycle-safety gap (shared dereference before null guard) that should be aligned with existing guarded accessors.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
  1. Add shared null-guarding in Context::getPredicateStatisticsLog before locking/dereferencing shared.
  2. Fix first-stage total_granules / index_selectivities computation in ReadFromMergeTree::logPredicateStatistics.
  3. Strengthen stateless test isolation and add index-row assertions.
  4. Add missing docs frontmatter fields sidebar_label and sidebar_position.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Mar 4, 2026

Copilot AI left a comment

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.

Pull request overview

This PR introduces a new system.predicate_statistics_log system table and adds optional collection of predicate selectivity statistics during query execution (in FilterTransform), intended to support workload-driven index/projection suggestions.

Changes:

  • Add PredicateStatisticsLog system log (schema + registration) and a predicate_statistics_sample_rate server setting to control collection.
  • Extend FilterTransform to extract predicate “atoms” from the filter DAG and emit selectivity stats into the new system log.
  • Add unit/stateless tests plus test/server config to enable the log and sampling.

Reviewed changes

Copilot reviewed 19 out of 19 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
src/Processors/Transforms/FilterTransform.h Adds members and header dependency to support predicate stats collection.
src/Processors/Transforms/FilterTransform.cpp Implements sampling, atom extraction hookup, and log emission from FilterTransform.
src/Interpreters/PredicateAtomExtractor.h Declares predicate atom extraction/classification utilities.
src/Interpreters/PredicateAtomExtractor.cpp Implements atom extraction from ActionsDAG and function-name classification.
src/Interpreters/PredicateStatisticsLog.h Declares the new system log element and log type.
src/Interpreters/PredicateStatisticsLog.cpp Defines the system table schema and block append logic.
src/Interpreters/SystemLog.h Registers predicate_statistics_log in the system logs list.
src/Interpreters/SystemLog.cpp Includes the new log header so it can be instantiated.
src/Interpreters/Context.h Adds getPredicateStatisticsLog() accessor.
src/Interpreters/Context.cpp Implements getPredicateStatisticsLog().
src/Common/SystemLogBase.h Adds the new log element to the system log element registry.
src/Common/SystemLogBase.cpp Includes the new log implementation header.
src/Core/ServerSettings.cpp Adds predicate_statistics_sample_rate server setting.
programs/server/config.d/predicate_statistics_log.xml Adds default server config for the new system log + sampling setting.
tests/config/config.d/predicate_statistics_log.xml Adds test config for the log + sampling setting.
tests/config/install.sh Installs the new test config file into the test server config.d.
tests/queries/0_stateless/04011_predicate_statistics_log.sql Adds a stateless test validating log population.
tests/queries/0_stateless/04011_predicate_statistics_log.reference Reference output for the new stateless test.
src/Interpreters/tests/gtest_predicate_atom_extractor.cpp Adds unit tests for predicate function classification and null handling.

Comment thread tests/config/install.sh Resolved

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 19 out of 19 changed files in this pull request and generated 3 comments.

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 19 out of 19 changed files in this pull request and generated 3 comments.

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 19 out of 19 changed files in this pull request and generated 3 comments.

Comment thread src/Interpreters/SystemLog.h Resolved
Comment on lines +497 to +509
const auto & counters = read_steps_performance_counters.getCounters();
std::vector<size_t> all_filter_indices;
std::vector<size_t> filter_step_indices;
for (size_t i = 0; i < prewhere_actions.steps.size(); ++i)
{
const auto & step = prewhere_actions.steps[i];
if (step->type == PrewhereExprStep::Filter)
{
all_filter_indices.push_back(i);
if (!step->predicate_expression.empty())
filter_step_indices.push_back(i);
}
}

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.

this is something strange - why not just do the same iteration like being done in dumpStatistics?

Comment thread src/Core/SettingsChangesHistory.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 94.18% (275/292) | lost baseline coverage: 7 line(s) · Uncovered code

Full report · Diff report

@yariks5s
yariks5s added this pull request to the merge queue Apr 23, 2026
Merged via the queue into master with commit a949f49 Apr 23, 2026
161 checks passed
@yariks5s
yariks5s deleted the yarik/predicate-statistics-system-table branch April 23, 2026 07:34
azat pushed a commit to azat/ClickHouse that referenced this pull request Apr 23, 2026
PR ClickHouse#101267 removed the 15-iteration retry loop with the claim that the new
caching-based sampling ensures a single pass produces all expected trace-log
rows. After the PR was merged to master, the test began failing on both
master (`Integration tests (amd_binary_excluded_from_llvm)`) and several
unrelated in-flight PRs (ClickHouse#98727, ClickHouse#101434, ClickHouse#103307), each at different
assertion lines in the single-pass test:

- `get_trace_events('Unknown', 'Global', 'JemallocSample') > 0`
- `get_trace_events('Unknown', 'Max', 'MemorySample', query_id) > 0`
- `get_trace_events('Global', 'Max', 'Memory'/'MemoryPeak') > 0`

The reason these events are not guaranteed in a single pass — even with
fully-propagated `sample_probability` — is that two of the trace types are
genuinely probabilistic relative to this test's workload:

- `JemallocSample` is emitted by `jemalloc`'s own profile sampler
  (`lg_prof_sample=20` ≈ one sample per 1 MiB). Ten `logTrace('foo')` calls
  plus a `SELECT * FROM numbers(100000) ORDER BY number` are not guaranteed
  to allocate enough `jemalloc`-tracked memory to trigger a sample inside a
  `MemoryTrackerBlockerInThread(Global)` scope.
- `Memory`/`MemoryPeak` with `memory_context = 'Global'` are only emitted
  when `total_memory_tracker` crosses its `total_memory_profiler_step`
  watermark (4 MiB default). Whether this happens inside a given test
  query depends on cumulative server-wide allocations including background
  activity, not just the query's own allocations.

The retry loop bounds the test runtime at ~15 s while letting these
events accumulate reliably. Restore it, and add a comment explaining
why it is required so it is not dropped again.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=fa205863ba68f05b529e2073defb5cf5df7cc832&name_0=MasterCI&name_1=Integration%20tests%20%28amd_binary_excluded_from_llvm%29

Session: cron:clickhouse-ci-task-worker:20260421-224500

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

8 participants