Repository navigation
PromQL: evaluate subqueries shared by multiple plan steps once - #113772
Conversation
|
Workflow [PR], commit [5daaace] Summary: ✅
AI ReviewSummaryThis PR makes the PromQL SQL generator mark the Findings
Tests
Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 63/63 (100.00%) · Uncovered code |
| if (!getContext()->getSettingsRef()[Setting::enable_materialized_cte].changed) | ||
| getContext()->setSetting("enable_materialized_cte", true); | ||
|
|
||
| auto [ast, io] = executeQuery(sql_query->formatWithSecretsOneLine(), getContext(), {}, QueryProcessingStage::Complete); |
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 sizes7 object files changed (+10.42 KiB total), 1 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units39 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. |
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (3 of 43)
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
|
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]>
3f4d824 to
2e8f608
Compare
| 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}); |
There was a problem hiding this comment.
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.
|
@groeneai looks like this PR surfaces a problem with the materialized view. Investigate this, fix and send a PR. |
|
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. 2. The chronic materialized-CTE gate abort ( 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 |
|
#114261, for reading (1). It forces Measured with Nothing new on reading (2): still no CI occurrence of that abort with PromQL-generated SQL. |
|
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 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? |
I see no conflicts in src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp |
|
I have problems rebasing |
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]>
… 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]>
Changelog category (leave one):
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/limitkoperand, the left side ofor) once instead of twice: the SQL generated from PromQL now materializes shared subqueries. This removes a duplicated scan of the samples table;topkoverrategets ~2x faster cold, and kubernetes-mixin rule queries improve by 10–29%.Problem
The PromQL converter emits each evaluation step as a named
WITHsubquery, and ClickHouse inlinesWITHsubqueries per use. Two plan shapes reference a step twice: thetopk/bottomk/limitkoperand feeds both the group-selecting aggregation and the value-masking join, and the left side oforfeeds 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 (theprometheusQuery/prometheusQueryRangetable functions and the Prometheus HTTP API) enableenable_materialized_cteunless 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.
topk(10, sum by (ns,pod) (rate(…[5m]))), 30 m rangetopk by (1, max(kube_pod_info))topk by (1, max(kube_pod_info))topk by (1, max(…owner))topk by (1, max(kube_pod_owner))orprobeorsum byover the same metric) is unchanged: same rows read, noAS MATERIALIZEDin its plan.Note: the measured binaries include streaming topk (#113656), where the topk operand is multi-referenced. On current master (pre-#113656) the fix benefits the
orshape; the reference count picks up topk automatically when #113656 lands.Tests
The new stateless test
04816_promql_shared_subqueries_materializedasserts the plan shape (shared operand read once,MaterializingCTEsstep present, single-use subqueries untouched) and identical results withenable_materialized_cte = 0. All 45 timeseries/prometheus/promql stateless tests pass.🤖 Generated with Claude Code
Version info
26.8.1.1070(included in26.8and later)