Repository navigation
PromQL: run the generated SQL with the analyzer on the HTTP API - #114261
Conversation
…points The PromQL-to-SQL converter marks a subquery referenced by more than one plan step AS MATERIALIZED so it is evaluated once, and that mark is honored by the analyzer only. The two PromQL entry points disagreed about the analyzer: StoragePrometheusQuery::readImpl builds InterpreterSelectQueryAnalyzer directly, so the table functions always run the analyzer, while PrometheusHTTPProtocolAPI::executePromQLQuery passes the generated SQL to executeQuery(), which honors the caller's enable_analyzer. With the analyzer off /api/v1/query and /api/v1/query_range rescanned the shared subquery once per referencing step, and the enable_materialized_cte default set next to that call had nothing to act on. Reachable both as a URL parameter, since isSettingLikeParameter turns any non-reserved query parameter into a setting, and through the user profile, which is how the old-analyzer CI configuration reaches it. Force allow_experimental_analyzer on the request context before the single executeQuery call so the HTTP path matches the table-function path. The setting is written in place on the per-request context, deliberately without a context copy: 6190f34 removed exactly such a copy from this function on review and switched the class to WithMutableContext. Spelled allow_experimental_analyzer rather than the enable_analyzer alias, matching the other setSetting sites. Measured with read_rows from system.query_log on 2 metrics x 16 series x 8 samples, analyzer off via the profile: `a or b` read 880 rows before and 624 after, while `sum(a)`, which shares no subquery, read 288 either way. On a larger fixture the or, topk and bottomk-or shapes read 1.49x, 1.97x and 2.47x too many rows. Results are unchanged between the two modes, byte-identical except for row order on two of ten pairs, which PromQL leaves unordered. Because results are identical, the regression test asserts on read_rows and on the analyzer setting recorded for the generated query rather than on results, which would pass either way. It covers both endpoints and both affected shapes, plus a control that shares no subquery and a guard against the assertions going vacuous, and creates the node with use_old_analyzer=True.
Two review findings, both in the new integration test. The system.query_log read assumed the QueryFinish row exists once the HTTP response has been received. It need not: finishExecutedQuery flushes the response in query_finish_callback() and only then calls io.onFinish(), which writes the QueryLog element, and SYSTEM FLUSH LOGS is not a barrier against a row that has not been queued yet. The read now waits for the row with assert_eq_with_retry, the idiom test_prometheus_query_log.py already uses for the same rows. It waits on count() = 1, so the exactly-one-row guarantee is kept. The vacuity guard covered only the `or` shape. Post-fix all measurements run with the analyzer forced on, so the equality assertions hold by construction and would survive `topk` silently losing its MATERIALIZED_TABLE mark. `or` and `topk` acquire that mark through independent code paths, so the guard is now parametrized over both, each with a read_rows ceiling between its materialized and unmaterialized measurements: 2.5x a single scan for `or` (624 against 880), 1.5x for `topk` (320 against 576). Verified with the setting assertion removed on an unpatched binary, which is what forces the counters to be the only gate: 8 of 10 cases fail on the counters, up from 6 of 8, with the two new topk cases failing on the ceiling itself. The two no-shared-subquery controls pass on both arms, as they should.
Internal second-model reviewTwo rounds. Round 1 on
Also checked and clean, with no finding: the endpoint pair has exactly one SQL-executing site |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260811-000600 |
|
cc @vitlibar, could you review this? |
|
Workflow [PR], commit [4f077cf] Summary: ❌
AI ReviewSummaryThis PR forces the Prometheus HTTP query endpoints to execute their generated SQL with Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: This PR only forces the analyzer (and enable_materialized_cte) on the Prometheus/PromQL HTTP handler, plus an integration test — it does not touch the query-execution path that ClickBench or TPC-H exercise. None of the flagged improvements, including the ×8.1 faster reading on TPC-H Q7, can plausibly be caused by this change, so they are downgraded to not-sure as run-to-run/environment variance. The no_change verdict on ClickBench Q18 is consistent with that off-path reasoning. 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_officialFlagged queries (2 of 22)
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. Debug info
|
CI finish ledger - 6036352CI is fully finished on this head (0 checks incomplete,
Per-arch reports: amd_asan_ubsan, arm_debug, arm_msan, amd_tsan. The three hung checks are one event each: the root query is Session id: cron:our-pr-ci-monitor:20260811-123000 |
|
Fixing PR for the hung |
| assert shared < bound * single_scan, ( | ||
| f"{promql!r} on {path} read {shared} rows against {single_scan} for a single scan, " | ||
| f"over the {bound}x ceiling that separates a materialized plan from a rescanning one" | ||
| ) |
There was a problem hiding this comment.
@groeneai Fix is right, but this test looks like a big overkill: try to replace it by adding the following test to test_query_api.py:
def test_generated_sql_always_runs_with_analyzer():
# The SQL generated for PromQL marks shared subqueries AS MATERIALIZED, which only the
# analyzer honors, so the handler forces the analyzer and enable_materialized_cte
# regardless of the caller's enable_analyzer. The materialization itself is covered by
# 04816_promql_shared_subqueries_materialized; here it is enough to check the settings
# the generated query ran with.
for path, time_params in (
("/api/v1/query", "time=1000"),
("/api/v1/query_range", "start=999&end=1002&step=1"),
):
query_id = f"promql-analyzer-{uuid.uuid4()}"
url = (
f"http://{node.ip_address}:9093{path}"
f"?query=post_body_metric&{time_params}&enable_analyzer=0"
)
response = requests.get(url, headers={"X-ClickHouse-Query-Id": query_id})
extract_data_from_http_api_response(response) # raises unless a success envelope
node.query("SYSTEM FLUSH LOGS query_log")
assert_eq_with_retry(
node,
"SELECT Settings['allow_experimental_analyzer'], "
"Settings['enable_materialized_cte'] "
f"FROM system.query_log WHERE type = 'QueryFinish' AND query_id = '{query_id}'",
"1\t1\n",
)
There was a problem hiding this comment.
Agreed. Once #114409 is merged I will add your test_generated_sql_always_runs_with_analyzer to test_query_api.py and delete test_query_api_analyzer.py.
The only coverage that drops is the per-shape read_rows bound, and 04816_promql_shared_subqueries_materialized covers that as you say (it comes back with #114409, which also restores the AS MATERIALIZED marking this test depends on).
There was a problem hiding this comment.
Replaced in 4f077cf, essentially as you wrote it. Two changes: import uuid and assert_eq_with_retry were not imported in test_query_api.py, and I passed retry_count=30, sleep_time=1 (matching test_prometheus_query_log.py) because that instance does not install the 300 ms query-log config, so the default 10 s budget sat only 2.5 s above the 7.5 s background flush interval. Measured: the row lands 0.23 s after the flush in 12 of 12 requests, and the longer wait does not mask anything, since the unpatched binary still fails on '1\t1' != '0\t1'.
|
@groeneai update the PR, merge the master and implement what you was asked. |
…ttp-force-analyzer
…ed for in review Drops the standalone test_query_api_analyzer.py and folds test_generated_sql_always_runs_with_analyzer into test_query_api.py, as requested by @vitlibar on the PR. The new test asserts the two settings the generated query ran with, which is what the source change controls. The per-shape read_rows liveness bound the standalone test carried is dropped with it. 04816_promql_shared_subqueries_materialized covers the materialization itself, and it is back on master with ClickHouse#114409. Verified both directions on a debug build: the test passes with the fix (15/15 repeats, and the whole file green under the default, old-analyzer and distributed-plan integration flavours) and fails without it on the assertion under test, reporting '1\t1' != '0\t1'. Co-Authored-By: Claude Fable 5 <[email protected]>
test_query_api.py's instance does not install the 300 ms query-log configuration the standalone test had, so the default 10 second retry budget sat only 2.5 seconds above the server's 7.5 second background flush interval. The response is flushed to the client before the QueryFinish row is queued, so a flush can precede the row. Retry for 30 seconds, matching the sibling test in the same directory. The row appears 0.23 s after the flush in 12 of 12 measured requests, and the wait does not mask the defect: the unpatched binary still fails on the assertion under test. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Done in 4f077cf: merged master (which now carries #114409, so Verified both directions on a debug build: the new test passes with the fix and fails without it on the assertion under test, reporting |
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. Compile time of recompiled translation units7 translation units recompiled, 11 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - 4f077cfEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix
Session id: cron:our-pr-ci-monitor:20260814-043000 |
|
@groeneai who broke |
|
Nobody needs a revert; the fix is already on master. Root cause: My #113333 (merged 2026-08-12 19:00 UTC) is the exposer, not the bug: it stopped keyless aggregations from stamping keys, and those were the callers that used to create the cache first with the real capacity. Reverting it would re-hide the defect instead of fixing it, so I do not suggest a revert. The actual fix is #114597 (merged today at 00:51 UTC): The red build on this PR simply predates it. The newest master commit in that job's tree is 8e84012 (2026-08-13 21:53 UTC), and #114597's merge commit is not in it, which is what my ledger recorded as rule 3b. This branch picks the fix up at its next push. |
89de3f7
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The Prometheus HTTP API endpoints
/api/v1/queryand/api/v1/query_rangenow evaluate a PromQL subquery shared by several plan steps once, as theprometheusQueryandprometheusQueryRangetable functions already did. Previously a request made withenable_analyzer = 0, or by a user whose profile sets it, rescanned the shared subquery once per referencing step.Description
Related: #113772, which marks a PromQL subquery referenced by more than one plan step
AS MATERIALIZEDso it is evaluated once.AS MATERIALIZEDis honored by the analyzer only, and the two PromQL entry points disagreed about the analyzer.StoragePrometheusQuery::readImplbuildsInterpreterSelectQueryAnalyzerdirectly, so the table functions always run the analyzer.PrometheusHTTPProtocolAPI::executePromQLQueryhands the generated SQL toexecuteQuery(), which honors the caller'senable_analyzer. With the analyzer off, the endpoints rescanned the shared subquery and theenable_materialized_ctedefault that #113772 added there had nothing to act on.Reachable two ways, both measured: as a URL parameter, since
isSettingLikeParameterturns any non-reserved query parameter into a setting, and through the user profile, which is how the old-analyzer CI configuration reaches it.The fix forces
allow_experimental_analyzeron the request context immediately before the singleexecuteQuerycall, so the HTTP path matches the table-function path. The generated SQL is machine-built for the analyzer, and the caller'senable_analyzershould not change the plan of SQL they did not write. No setting default changes and results are unchanged.Measured with
read_rowsfromsystem.query_log, analyzer off via the profile:last_over_time(a) or last_over_time(b)read 880 rows before and 624 after, whilesum(last_over_time(a)), which shares nothing, read 288 either way.Results are identical in both modes, so a results-based test would pass either way.
test_generated_sql_always_runs_with_analyzerintest_query_api.pytherefore asserts the two settings the generated query ran with, over both endpoints, withenable_analyzer=0on the request. The materialization itself is covered by04816_promql_shared_subqueries_materialized.Validation
The new test passes with the fix and fails without it on the assertion under test, reporting
'1\t1' != '0\t1': the first column is what the fix sets, the second shows the request reached the handler. 10 of 10 repeats pass with the fix, and the wholetest_query_api.pyfile is green under the default, old-analyzer and distributed-plan integration flavours; on the unpatched binary the other 10 tests in the file still pass, so only the new assertion moves.The
system.query_logread waits withassert_eq_with_retry(retry_count=30, sleep_time=1): the response is flushed to the client before theQueryFinishrow is queued, so a single flush can precede the row and leave it waiting for the background interval. Measured on this instance the row appears 0.23s after the flush in 12 of 12 requests, and the longer retry does not mask the defect, since the unpatched arm still fails on the assertion.An earlier revision of this PR carried a larger standalone test with a per-shape
read_rowsbound. It was replaced at review request.