Skip to content

PromQL: evaluate subqueries shared by multiple plan steps once - #113772

Merged
vitlibar merged 4 commits into
masterfrom
promql-materialize-shared-ctes
Aug 10, 2026
Merged

vitlibar merged 4 commits into
masterfrom
promql-materialize-shared-ctes

Conversation

@nikitamikhaylov

@nikitamikhaylov nikitamikhaylov commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Evaluate PromQL subexpressions shared by multiple plan steps (the topk/bottomk/limitk operand, the left side of or) once instead of twice: the SQL generated from PromQL now materializes shared subqueries. This removes a duplicated scan of the samples table; topk over rate gets ~2x faster cold, and kubernetes-mixin rule queries improve by 10–29%.

Problem

The PromQL converter emits each evaluation step as a named WITH subquery, and ClickHouse inlines WITH subqueries per use. Two plan shapes reference a step twice: the topk/bottomk/limitk operand feeds both the group-selecting aggregation and the value-masking join, and the left side of or feeds both the per-group counting step and the final merge join. Such steps were evaluated twice, including their full selector scan of the samples table.

Change

A new pass runs on the final generated SQL. It counts table-expression references of every named subquery and marks subqueries referenced more than once as MATERIALIZED. Both execution entry points (the prometheusQuery/prometheusQueryRange table functions and the Prometheus HTTP API) enable enable_materialized_cte unless the user set it explicitly, so the mark takes effect. Single-use subqueries stay inlined. Multi-referenced subqueries are per-series grids, so the materialization buffer is bounded by the series count, not the sample count.

Measured effect

Hardware: 32-core workstation (nikita-office). Corpus: tsbench, 62.5 B samples / 361 k series in one TimeSeries table. Cold = first run after server start, median of 3 interleaved baseline/patched rounds. The two binaries differ by this change only.

query shared step cold before cold after Δ cold
s08: topk(10, sum by (ns,pod) (rate(…[5m]))), 30 m range topk operand 4871 ms 2373 ms −51.3%
r04: working-set info join topk by (1, max(kube_pod_info)) 4086 ms 2923 ms −28.5%
r03: cpu sum-irate rule topk by (1, max(kube_pod_info)) 4345 ms 3441 ms −20.8%
r06: pod-owner relabel rule topk by (1, max(…owner)) 1523 ms 1307 ms −14.1%
r08: pod-not-ready alert topk by (1, max(kube_pod_owner)) 6773 ms 6062 ms −10.5%
r07: pod-owner Job or probe left side of or 57 ms 54 ms −6.6%
  • Geometric mean over the six target queries: cold −23.7%, CPU −23.4%.
  • The duplicate scan disappears exactly: s08 samples-table marks drop 51,208 → 25,604 (parts 4 → 2); r03/r04 read 25% fewer rows.
  • Peak memory does not grow: s08 drops 572 → 526 MB, because the buffer costs less than the second evaluation.
  • Single-use control (s11, 24 h sum by over the same metric) is unchanged: same rows read, no AS MATERIALIZED in its plan.
  • Results are identical: the six target queries are byte-identical to baseline in all rounds; s11 differs only by the known parallel float-sum nondeterminism (it also differs baseline-vs-baseline).
  • r07 returns an empty vector on this corpus, so its gain is plan overhead only.

Note: the measured binaries include streaming topk (#113656), where the topk operand is multi-referenced. On current master (pre-#113656) the fix benefits the or shape; the reference count picks up topk automatically when #113656 lands.

Tests

The new stateless test 04816_promql_shared_subqueries_materialized asserts the plan shape (shared operand read once, MaterializingCTEs step present, single-use subqueries untouched) and identical results with enable_materialized_cte = 0. All 45 timeseries/prometheus/promql stateless tests pass.

🤖 Generated with Claude Code

Version info

  • Merged into: 26.8.1.1070 (included in 26.8 and later)

@nikitamikhaylov nikitamikhaylov added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5daaace]

Summary: ✅


AI Review

Summary

This PR makes the PromQL SQL generator mark the or left operand and the topk/bottomk/limitk operand grids as AS MATERIALIZED, and it enables enable_materialized_cte at the execution entry points so shared subqueries are evaluated once instead of being inlined per use. The SQL-side change looks reasonable, but the HTTP endpoint still does not uphold that contract in supported enable_analyzer = 0 compatibility mode, so I would not merge as-is.

Findings

⚠️ Majors

  • [src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp:127-130] /api/v1/query and /api/v1/query_range still go through generic executeQuery after only setting enable_materialized_cte. Requests or profiles with enable_analyzer = 0 / allow_experimental_analyzer = 0 therefore take the old interpreter, where AS MATERIALIZED is ignored, so shared PromQL subqueries are still evaluated twice on the HTTP path even though the table-function path forces InterpreterSelectQueryAnalyzer. That breaks the PR's stated contract across a still-supported compatibility mode.
    Suggested fix: either force the analyzer here the same way StoragePrometheusQuery::readImpl does, or reject old-analyzer mode for this endpoint with a clear exception.
Tests
  • ⚠️ Add an HTTP regression under tests/integration/test_prometheus_protocols that hits /api/v1/query or /api/v1/query_range with enable_analyzer=0 and verifies the endpoint either still materializes shared subqueries or rejects the mode explicitly. The new stateless coverage only exercises the table-function path, so this gap is currently invisible to CI.
Final Verdict

⚠️ Changes requested: the HTTP Prometheus API still misses the promised one-evaluation behavior in enable_analyzer = 0 compatibility mode.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.90% +0.10%

Changed lines: Changed C/C++ lines covered: 63/63 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 7, 2026
Comment on lines +100 to 103
if (!getContext()->getSettingsRef()[Setting::enable_materialized_cte].changed)
getContext()->setSetting("enable_materialized_cte", true);

auto [ast, io] = executeQuery(sql_query->formatWithSecretsOneLine(), getContext(), {}, QueryProcessingStage::Complete);

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.

The table-function path forces InterpreterSelectQueryAnalyzer, but the HTTP path still goes through generic executeQuery(). That means any request or profile with enable_analyzer = 0 / allow_experimental_analyzer = 0 takes the old interpreter (InterpreterFactory.cpp), where AS MATERIALIZED is ignored entirely; we already document that in 04323_input_twice_cte_106672.sh. In that compatibility mode this PR does not make shared PromQL subqueries run once for /api/v1/query and /api/v1/query_range, even though the table-function path does.

Please either force the analyzer here as StoragePrometheusQuery::readImpl does, or reject/override old-analyzer mode for this endpoint and add an HTTP regression test that exercises enable_analyzer=0.

@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5daaace9d with master e493bf79b (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 2b2987cc1; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.67 MiB 687.65 MiB -3.02 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

7 object files changed (+10.42 KiB total), 1 added.

Object file Master PR Δ

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

39 translation units recompiled, 68 s compile time in total, 37 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.95 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -3.8 s (-5%) in total before that adjustment.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR changes only PromQL-to-SQL translation for the TimeSeries/Prometheus engine (materialized CTE marking for shared subqueries) plus a debug-only assertion; it does not touch the general SELECT execution path that ClickBench exercises. The three flagged improvements (Q16 -10.6%, Q17 -15.8%, Q18 -6.8%) are on queries the diff cannot plausibly affect, so all three were downgraded to not_sure as run-to-run variance rather than real PR effects. No query hits the hard trust threshold, and no cross-query pattern is present. Expect no measurable ClickBench impact from this change.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 793 709 -10.6% <0.0001 This PR only touches PromQL-to-SQL translation for the TimeSeries engine; a plain ClickBench SELECT never executes that path, so the -10.6% is run-to-run variance, not a PR effect.
⚠️ 17 not_sure 556 468 -15.8% <0.0001 The change is confined to Prometheus/TimeSeries query generation, which Q17 does not exercise, so the -15.8% delta cannot be attributed to this PR and reads as measurement noise.
⚠️ 18 not_sure 1298 1210 -6.8% <0.0001 Q18 runs entirely in the server's standard SELECT path, untouched by these Prometheus subquery-materialization edits, so the -6.8% is unrelated to this PR.

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: fa974bd1-d8ee-4c60-8960-f33197bf1bfc
  • MIRAI run: 3b61eef9-a9aa-4dad-80ee-28b7e4ef2d39
  • PR check IDs:
    • clickbench_529101_1786325113
    • clickbench_529107_1786325113
    • clickbench_529118_1786325112
    • tpch_adapted_1_official_529130_1786325113
    • tpch_adapted_1_official_529143_1786325112
    • tpch_adapted_1_official_529173_1786325113

@vitlibar vitlibar self-assigned this Aug 7, 2026
nikitamikhaylov and others added 2 commits August 8, 2026 23:13
The SQL generated from a PromQL query names each evaluation step as a
WITH subquery, and some plans reference a step more than once: the
topk/bottomk/limitk operand grid feeds both the group-selecting
aggregation and the value-masking join, and the left side of 'or' feeds
both the per-group counting step and the final merge join. ClickHouse
inlines WITH subqueries per use, so such steps - including their
selector scans - were evaluated twice.

Count table-expression references of every named subquery in the final
query and mark those referenced more than once as MATERIALIZED, and
enable the materialized-CTE machinery (setting enable_materialized_cte,
unless the user set it explicitly) at both execution entry points (the
prometheusQuery table functions and the Prometheus HTTP API).

Single-referenced subqueries are never marked and keep being inlined.

Co-Authored-By: Claude Fable 5 <[email protected]>
Asserts that the left side of 'or' is read once (and materialized), that
single-use subqueries (plain sum/rate, binary operators, today's topk
chain) stay inlined without materialization, that results are identical
with the materialization explicitly disabled, and that disabling
enable_materialized_cte restores the old inlined plan.

Co-Authored-By: Claude Fable 5 <[email protected]>
@nikitamikhaylov
nikitamikhaylov force-pushed the promql-materialize-shared-ctes branch from 3f4d824 to 2e8f608 Compare August 8, 2026 21:14
context.subqueries.emplace_back(SQLSubquery{context.subqueries.size(), std::move(left_argument.select_query), SQLSubqueryType::TABLE});
/// The left grid is read twice - by the per-group counting step (Step 1) and by the final merge join (Step 3) -
/// so it's added as a materialized CTE to be evaluated once.
context.subqueries.emplace_back(SQLSubquery{context.subqueries.size(), std::move(left_argument.select_query), SQLSubqueryType::MATERIALIZED_TABLE});

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.

I made PromQL shared-subquery materialization explicit, so now there is a value SQLSubqueryType::MATERIALIZED_TABLE which is specified while building SQL - because it seems better to build a correct SQL right away than to patch it afterwards.

@nikitamikhaylov

Copy link
Copy Markdown
Member Author

@groeneai looks like this PR surfaces a problem with the materialized view. Investigate this, fix and send a PR.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. Two candidates fit "a problem with the materialized view" here, and they need different fixes, so let me name both with what I measured.

1. The HTTP endpoints do not get this PR's benefit. StoragePrometheusQuery::readImpl builds its plan through InterpreterSelectQueryAnalyzer directly, so the table function always runs the analyzer. PrometheusHTTPProtocolAPI instead hands the generated SQL to generic executeQuery(), and the old interpreter ignores AS MATERIALIZED outright. Measured on master: with enable_analyzer = 1 the plan has 2 MaterializingCTE steps and 1 raw read, with enable_analyzer = 0 it has 0 and 2. So under a profile with the analyzer off, /api/v1/query and /api/v1/query_range still evaluate shared subqueries twice. This was raised in review before the merge and went in unaddressed.

2. The chronic materialized-CTE gate abort (Reading from materialized CTE '...' before its materialization completed, STID 2467-2c2d). Enabling enable_materialized_cte by default for PromQL widens exposure to it. It is a pre-existing trunk bug with fixes in flight (#113558, #113489). I checked 30 days of CI: no occurrence of that abort has PromQL-generated SQL in its query text, and the hit on your #113681 last night is the generic fuzzer shape (WITH t AS MATERIALIZED ... WHERE (x IN (t)) OR (x IN (t)) under parallel replicas), so I have no evidence yet that a PromQL shape reaches it.

I am treating (1) as the actionable one: I will send a PR forcing the analyzer on the HTTP path, matching the table-function path, plus an enable_analyzer = 0 regression test, and follow up here with the link. Redirect me if you meant (2), or an actual CREATE MATERIALIZED VIEW problem you saw elsewhere.

@groeneai

Copy link
Copy Markdown
Collaborator

#114261, for reading (1).

It forces allow_experimental_analyzer on the request context immediately before the single
executeQuery call in PrometheusHTTPProtocolAPI::executePromQLQuery, so the HTTP endpoints
match StoragePrometheusQuery::readImpl. +3 lines, no setting default changes.

Measured with read_rows from system.query_log, analyzer off via the profile:
last_over_time(a) or last_over_time(b) read 880 rows before and 624 after, topk(3, ...)
576 before and 320 after, while sum(last_over_time(a)), which shares nothing, read 288 either
way. Results are unchanged, so the regression test asserts on read_rows rather than on results.

Nothing new on reading (2): still no CI occurrence of that abort with PromQL-generated SQL.

@leshikus

leshikus commented Aug 11, 2026 •

Copy link
Copy Markdown
Collaborator

I cannot understand - there is a merge conflict regarding this PR in the private repo. The timeline is unclear: the pr was merged into private repo on Aug 7, and only yesterday it was merged in public, this is not a standard sync process.

The conflict is in src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp in multiple places.

Can I just take a master version in private, or is it outdated and requires to be synced? Or it is not the same as in public intentionally?

@vitlibar

Copy link
Copy Markdown
Member

The conflict is in src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp in multiple places.

I see no conflicts in src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp

@leshikus

Copy link
Copy Markdown
Collaborator

I have problems rebasing sync-upstream/pr/111201; I can try to merge master and squash

@groeneai groeneai mentioned this pull request Aug 12, 2026
1 task done
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Aug 12, 2026
This reverts pull request ClickHouse#113772 (merge commit
b9d4064).

Stress tests on `master` started reporting `Hung check failed, possible
deadlock found` on the first commit after this one, and have not stopped
since. The stuck query is `DROP TABLE prometheus` blocked in
`StorageTimeSeries::dropInnerTableIfAny` ->
`DatabaseCatalog::waitTableFinallyDropped`, in the PromQL `limitk` test
whose vector-grid subquery this change turned into a
`SQLSubqueryType::MATERIALIZED_TABLE`.

Related: ClickHouse#113772

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Aug 12, 2026
… plan"

This reverts pull request ClickHouse#113656 (merge commit
bf4fa22).

Reverted together with ClickHouse#113772, which built on the plan this change
introduced: the two touch the same function, so reverting only the newer
one would leave the older half of the feature in place.

Related: ClickHouse#113656

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... pr-performance Pull request with some performance 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.

5 participants