Skip to content

Prometheus HTTP API: implement /api/v1/format_query - #117159

Merged
nikitamikhaylov merged 6 commits into
masterfrom
prometheus-format-query-api-minimal
Sep 2, 2026
Merged

nikitamikhaylov merged 6 commits into
masterfrom
prometheus-format-query-api-minimal

Conversation

@nikitamikhaylov

@nikitamikhaylov nikitamikhaylov commented Aug 30, 2026 •

Copy link
Copy Markdown
Member

Related: #115757

Changelog category (leave one):

  • Experimental Feature

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

Implemented the /api/v1/format_query endpoint of the Prometheus HTTP API. It parses the given PromQL expression and returns it in a canonical form.

Description

A minimal rewrite of #115757 (co-authored with @fallintoplace).

The endpoint reuses the existing canonical serialization PrometheusQueryTree::toString instead of introducing a second PromQL formatter: the expression from the query parameter is parsed and returned serialized from the parsed tree, with the whitespace normalized, the comments removed, and the redundant parentheses dropped. Parse errors are reported with the standard Prometheus error envelope (HTTP 400, errorType: bad_data), like on the other query endpoints. The endpoint only parses the expression, so it is dispatched before the TimeSeries table lookup and doesn't require a table.

Unlike the Prometheus implementation, the output is always a single line, and the durations are printed as numbers of seconds (rate(foo[5m]) becomes rate(foo[300])), which is the canonical form already used by the PromQL round-trip in this codebase. Printing the durations with time units would be a follow-up change to the shared toString.

Covered by 19 new integration tests in test_format_query_api.py (all pass locally).


Workflow [PR]
Sync PR [sync-upstream/pr/117159]

Version info

  • Merged into: 26.9.1.558 (included in 26.9 and later)

The endpoint parses the PromQL expression from the 'query' parameter and
returns it serialized from the parsed tree (PrometheusQueryTree::toString):
the whitespace is normalized, the comments are removed, the redundant
parentheses are dropped, and the durations are converted to numbers of
seconds. The endpoint only parses the expression, so it is dispatched
before the TimeSeries table lookup and doesn't require a table.

A minimal rewrite of #115757

Co-authored-by: Minh Vu <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
@mintlify

mintlify Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Aug 30, 2026, 2:52 PM

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

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f6b317c]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_msan, 1/8) FAIL
test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_restore FAIL cidb
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb
LLVM Coverage FAIL
Generate LLVM Coverage Diff Report FAIL cidb
Print Uncovered Code FAIL cidb Uncovered code analysis did not run: bash ci/jobs/scripts/generate_diff_coverage_report.sh failed (its output is on the Generate LLVM Coverage Diff Report result).
Parser memory check ERROR
Resolve master binary ERROR

AI Review

Summary

Adds /api/v1/format_query to the Prometheus HTTP API by routing it through QueryImpl before TimeSeries table resolution, documents the endpoint, and adds dedicated-port integration coverage. The implementation looks consistent with the advertised table-free handler behavior, but the PR still does not prove the same endpoint through the separate prometheus_api_v1 dispatch on the main HTTP port.

Tests
  • ⚠️ tests/integration/test_prometheus_protocols/test_http_port.py still covers /prometheus/api/v1/query, /prometheus/api/v1/query_range, /prometheus/api/v1/metadata, and /prometheus/api/v1/label/.../values, but not /prometheus/api/v1/format_query. Because the documented main-HTTP route goes through APIv1Impl::getImpl instead of the dedicated /api/v1/format_query handler exercised by test_format_query_api.py, add one small prefixed-route regression test that hits /prometheus/api/v1/format_query and checks the success envelope.
Final Verdict

⚠️ One follow-up before approval: add the missing main-HTTP prefixed-route regression coverage for /prometheus/api/v1/format_query.

LLVM Coverage Report

⚠️ No coverage measurement for commit f6b317c: bash ci/jobs/scripts/generate_diff_coverage_report.sh failed (its output is on the Generate LLVM Coverage Diff Report result).

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Aug 30, 2026
Comment thread src/Server/PrometheusRequestHandler.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f6b317c3f with master 796431c0d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 10 s compile time in total, 7 of them have a recent master baseline.

Job report

`cluster.start()` waits for the native TCP port, and the Prometheus
protocols port can start accepting connections slightly later. The other
test modules of `test_prometheus_protocols` mask this window by creating
tables and inserting data right after `cluster.start()`, but
`test_format_query_api.py` sends its first HTTP request immediately, which
failed with `Connection refused` in the slower sanitizer jobs:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=117159&sha=552c1f7bd1e3c1cccd1fe242519699ae33e9b8da&name_0=PR&name_1=Integration%20tests%20(amd_asan_ubsan%2C%20flaky)

Poll the endpoint until the port accepts connections before running the tests.

Co-Authored-By: Claude Fable 5 <[email protected]>
@nikitamikhaylov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=117159&sha=552c1f7bd1e3c1cccd1fe242519699ae33e9b8da&name_0=PR&name_1=Integration%20tests%20(amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%206%2F6) and provide a fix in a separate PR. If the fix is already in progress, link it here.

test_s3_plain_rewritable/test.py::test[cache_s3_plain_rewritable-data/] and test[s3_plain_rewritable_with_metadata_cache-data_with_cache/] fail with DB::NetException: Connection refused (172.16.3.6:9000). (NETWORK_ERROR) mid-test. This is unrelated to this PR (which only touches the Prometheus HTTP API handler and its tests): per CIDB, the same test fails across many unrelated PRs and on master since 2026-08-29 (21-23 failures/day), and I found no open issue or fix PR for it. The Connection refused on the native port in the middle of the test suggests the server crashed or was restarted during OPTIMIZE TABLE test FINAL.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. Not related to this pull request, and not a ClickHouse fault: one node's server process is killed from outside by a memcg OOM in the dind cgroup hierarchy. Measured on this run's own artifacts (552c1f7bd1e3, Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6)):

  • docker-in-docker.log carries 15178 topic=/tasks/oom events in exactly one window, 15:29:45.853Z to 15:33:03.604Z, and zero in the other 98 minutes of the 101-minute job. The last OOM event is followed 9.5 ms later by containerd topic=/tasks/exit; the two test failures are logged at 15:33:11 and 15:33:19, within 16 s of it.
  • In the retained _instances-gw1 snapshot one node's clickhouse-server.log stops dead at 15:33:02.011 mid background blob cleanup, with no <Fatal>, no Received signal, no sanitizer report and no shutdown line. The other four log on to 15:33:30 with one Received signal and 24 shutdown lines each. All five logged Starting ClickHouse exactly once, so no server restarted either.
  • The breach is not the node's own budget: it sized itself Available RAM: 12.00 GiB and max_server_memory_usage 10.80 GiB, and the whole run has zero Code: 241. The binding limit is an ancestor cgroup, which the node cannot see from inside its namespace.
  • The run printed No kernel memory kill in dmesg, which is a coverage artifact rather than a negative: the buffer was cleared at 14:43:05 and the retained dmesg.log spans only 16:14:53 to 16:23:47 (4018 lines, all veth and bridge churn), so it begins about 42 minutes after the kill.

Worth having from the same job: on the retry at 16:21:13 both test_s3_plain_rewritable cases passed, and the only failure that survived is test_prometheus_protocols/test_format_query_api.py::test_format_query[foo/bar-foo / bar], which failed on both attempts (15:10:17, 16:23:48), both outside the OOM window.

Your breadth reading matches mine: 23 failures on 2026-08-29 and 21 on 2026-08-30. One addition: all 44 are in the 6/6 batch, which this module only entered on 2026-08-28, while 1/6, 2/6, 4/6 and 5/6 ran it over the same 14 days for about 59,000 passing rows and zero failures. So the trigger looks like the module becoming a co-tenant of a heavier batch, not a new defect inside it.

On the fix: #117104 ("Keep the kernel's memory-kill record when an integration test run fails"), merged today, is prerequisite diagnostics for this exact failure and not the fix, so a fix-PR search would not have surfaced it. Extending that record to cover the whole run (the 7.6% above) is in progress, and the node-death fix follows it. A fix task owns this at full effort, and I will post the fixing-PR link in this thread when it opens.

@groeneai

Copy link
Copy Markdown
Collaborator

Fixing PR for the test_s3_plain_rewritable node death: #117202, merged 2026-08-31. This resolves both cases on your report, test[cache_s3_plain_rewritable-data/] and test[s3_plain_rewritable_with_metadata_cache-data_with_cache/].

The mechanism, to close out my earlier comment here. On a hung docker compose stop every node of a cluster crosses the same 60 second stacktrace deadline at once, so several gdb processes attach simultaneously and each reads the whole binary's debug info. In the run I measured they grew in lockstep from 1.3 GiB to 7.3 GiB of resident memory each, which pins the cgroup holding the nested containers at its 40.78 GiB cap. The kernel then kills the largest task in that cgroup, and while gdb is still smaller than a server it is a server that dies. That is why the log stops dead with no <Fatal>, no signal handler output and no shutdown sequence. #117202 serializes the attach, so the demand that reaches the cap no longer exists.

@nikitamikhaylov

Copy link
Copy Markdown
Member Author

@groeneai why the tests failed? Investigate and link the fix PRs.

@groeneai

Copy link
Copy Markdown
Collaborator

Five reds on cc54104e1fe4, three distinct causes, none of them from this diff.

Upgrade check (amd_release) - the only failing row is Error message in clickhouse-server.log, and all 165 flagged lines are the same error, repeated by the background retry loop:

<Error> MutatePlainMergeTreeTask: Code: 16. DB::Exception: Unexpected const virtual column: _table:
While executing MergeTreeSequentialSource. (NO_SUCH_COLUMN_IN_TABLE) (version 26.9.1.1)

False red, no product bug. tests/queries/0_stateless/04510_mutation_query_plan_only_virtual_columns.sql:46 runs ALTER TABLE t_mut_local DELETE WHERE _table != '' AND c0 < 2; -- { serverError UNFINISHED } deliberately: the mutation's sequential-source read path does not fill _table, so the statement is asserted to fail. It fails inside a background MutatePlainMergeTreeTask, so Code: 16 reaches the server log at <Error> level while the client only sees the asserted UNFINISHED. That statement is present in the release the job installs (v26.8.1.2041-lts, checked with a negative control), --upgrade-check implies --fake-drop so the failed mutation is not dropped, and the 26.9.1.1 server retries it after the restart. The log scan in tests/docker_scripts/upgrade_runner.sh has no allowlist entry for it, and 04510 is the only test on master whose mutation predicate names _table.

Fixing PR: #117218. 17 distinct PRs have hit it since 2026-08-30 22:48Z. This check has no true-master runs at all (0 of 109304 CIDB rows in 30 days), so its breadth is only measurable across PRs.

AST fuzzer (amd_debug) - Logical error: Shard number is greater than shard count: shard_num=2 shard_count=1 cluster=test_cluster_one_shard_three_replicas_localhost (STID 5066-457d). The fuzzed query reads with parallel replicas inside a view(...) whose own SETTINGS set cluster_for_parallel_replicas, and prepareClusterForParallelReplicas indexes the _shard_num shipped by the outer distributed query into that other cluster's numbering.

Fixing PR: #113589, open. CIDB over 30 days: 74 rows, 57 distinct PRs, 8 true-master shas, across AST fuzzer and Stress test on both amd and arm.

Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6, 5/6, 6/6) - no test failed on any of the three: 1143, 949 and 1208 OK rows respectively, zero FAIL and zero ERROR from tests. The single red row per shard is the job-level Container memory budget exceeded (/docker), i.e. the docker-in-docker /docker cgroup leaf that caps the nested test containers registered an OOM kill. Today: 468 rows, 195 distinct PRs, 40 true-master rows over 22 master shas.

Fixing PR: #117202, merged today at 11:05:36Z. This run's merge commit was resolved at 10:58:46Z, about seven minutes before that merge, so the tree predates the fix and a fresh run on an updated base picks it up.

One caveat so the rebase is not a surprise: on true-master trees that provably contain #117202 (ancestry checked against its merge commit, 13 shas), 2/6 and 5/6 are clean, 0 of 13, while 6/6 still fires 13 of 13. So expect 6/6 to stay red. That residual is not from this PR either; a fix task owns it and its fixing-PR link will follow.

Mergeable Check and PR are aggregators of the five above, and CH Inc sync is green.


# The endpoint only parses the PromQL expression, so no TimeSeries table is created:
# the tests also verify that the endpoint works without one.
node = cluster.add_instance(

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.

/api/v1/format_query is advertised to work both as a dedicated Prometheus-port handler and through the prefixed prometheus_api_v1 route on the main HTTP port, but this new suite only exercises the dedicated query handler. The prefixed path goes through the separate APIv1Impl::getImpl dispatch, so there is still no regression coverage for half of the documented surface. Could we add a small test_http_port.py case for /prometheus/api/v1/format_query as well?

@nikitamikhaylov

Copy link
Copy Markdown
Member Author

@groeneai investigate the test failures and link the PRs with fixes (implement them if needed).

@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Sep 2, 2026
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator

One red at 3a232efcaebe, and Mergeable Check names it as the only blocking job: Stateless tests (arm_binary, parallel) / 00084_external_aggregation. It is not caused by this PR.

Code: 241. DB::Exception: Query memory limit exceeded: would use 572.77 MiB
(attempt to allocate chunk of 1.77 MiB), maximum: 572.20 MiB:
While executing SourceFromNativeStream. (MEMORY_LIMIT_EXCEEDED)
15. src/Processors/Transforms/AggregatingTransform.cpp:143: SourceFromNativeStream::generate()

Statement 2 of that test pins max_memory_usage = 600000000 (572.20 MiB) to keep the aggregation spilling to disk, and the file documents the spilling peak as about 260 MiB. This run reached 572.77 MiB, 0.57 MiB over, while reading the spilled temporary files back, so this is exhausted headroom and not a large query.

Pre-existing: 26 hits over 22 distinct PRs and 5 check variants in the last 7 days, including 2 true-master runs (d8aa6cab7800, amd_tsan, 09-01 13:16Z; f629aa6ad98c, arm_binary, 08-31 11:04Z). Your diff is PrometheusRequestHandler.cpp plus a doc page and a new integration test, nothing on the aggregation or memory-tracking path.

Fixing PR: #117326 (mine, open). enable_adaptive_aggregator residue that the early drain cannot release keeps a thread on the baseline path above the spill threshold, so every following block writes its own temporary file and the merge then allocates a reader per file, which is the allocation above. That residue is now written out first. Measured on this same statement: 339 files before, 7 to 15 after. The setting defaults to true and is not in this run's randomized set, so that path was active here.

To unblock this PR without waiting for that fix, re-running the one job should be enough: the in-job diagnostics rerun already passed 17/17 with the same randomized settings, since the overshoot needs concurrent load from the parallel suite.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117159&sha=3a232efcaebe37cb0dbfb4ceb20f827799688602&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Sep 2, 2026
…uery-api-minimal

# Conflicts:
#	docs/concepts/features/interfaces/prometheus.mdx
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master 4e1add46e

Metric Baseline Current Δ
Score 77.74% 77.74% +0.00%
Passed 419 419 +0
Failed 3 3 +0
Unsupported 117 117 +0

Note: score is unchanged vs baseline.

Uploaded compliance JSON for this PR commit

@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Sep 2, 2026
Merged via the queue into master with commit a54f19b Sep 2, 2026
333 of 344 checks passed
@nikitamikhaylov
nikitamikhaylov deleted the prometheus-format-query-api-minimal branch September 2, 2026 19:30
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 2, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@nikitamikhaylov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

This branch was successfully deployed

1 active deployment
staging - docs — f6b317c3 Deployed Sep 2, 2026 by mintlify[bot]
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-experimental Experimental Feature 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.

4 participants