Repository navigation
Parallelize query execution in the Prometheus query API - #112108
Conversation
PullingPipelineExecutor executes the whole pipeline on a single thread, so /api/v1/query and /api/v1/query_range never parallelized: a 30d range query over a scale-16 tsbench corpus (15.7B samples, 32 cores) ran in 336s via the HTTP API vs 9.9s for the identical generated SQL over the native protocol (ConcurrencyControlSlotsAcquired: 0 vs 31). Switching to PullingAsyncPipelineExecutor lets the query pipeline use the server's normal thread pool. Co-Authored-By: Claude Fable 5 <[email protected]> (cherry picked from commit 6cc2af6)
|
Workflow [PR], commit [105b1d8] Summary: ❌
AI ReviewSummaryThis PR swaps the Prometheus HTTP query endpoints over to Findings❌ Blockers
Final Verdict
|
db24fd0 to
eebf5f9
Compare
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
📊 Cloud Performance Report ✅ AI verdict: This PR only changes the Prometheus HTTP query path (swapping the pulling pipeline executor for the async variant) plus its integration tests. None of the flagged ClickBench queries (Q4, Q9, Q15) run that code, so their deltas cannot be attributed to this change. The envelope suppression is consistent with the diff: all three source medians land inside master's current variance band, and CPU time is essentially unchanged, so these are run-to-run variance rather than a real PR effect. No action needed. clickbenchFlagged queries (1 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
|
|
@groeneai help investigate |
1.
|
max_result_rows |
runs that delivered rows | runs that delivered nothing |
|---|---|---|
| 1 | 7 | 13 |
| 2 | 13 | 7 |
| 3 | 20 | 0 |
| 4 | 20 | 0 |
The limit exception fired in 20/20 runs in every row, so the difference is purely whether the already-produced rows survive.
Two controls confirm the mechanism rather than just correlating with it:
- Slowing the producer (
sleepEachRow(0.3),max_result_rows=1) gives 10/10 delivered: the chunk is produced either way, so the loss is on the consumer side, not a production failure. result_overflow_mode='break'(no exception at all) gives 10/10 delivered.
The step at 3 is predicted by the queue depth: LazyOutputFormat's queue capacity is 2 (LazyOutputFormat.cpp:13). With 1 or 2 rows produced before the throw, the producer never has to block, so it can reach the throw before the consumer's first pull(). From 3 rows on, pushing the third chunk blocks on a full queue until the consumer pops the first one, which makes delivery guaranteed. Loss is possible exactly while rows_before_throw <= 2, which is what the table shows.
Suggested fix
In PullingAsyncPipelineExecutor::pull(), drain before rethrowing: only take the rethrowExceptionIfHas() at line 117 when nothing is left buffered (lazy_format->isFinished()), otherwise fall through to getChunk() and let the next pull() surface the exception. The exception is still delivered exactly once (rethrowExceptionIfHas clears has_exception), and the async executor then matches the sync executor's ordering, which is what the HTTP handler's "pull first, then write the header" contract relies on.
One subtlety for whoever implements it: the drain has to happen before any cancel(), since onCancel does queue.clearAndFinish() and would throw the buffered chunks away.
I have not built that patch, so please treat the fix direction as a suggestion. Everything in the table above is measured on unmodified master.
If you would rather not touch the shared executor in a performance PR, a test-side stopgap is to raise max_result_rows above the queue depth. Note that this needs the fixture to still yield at least one more result row than the new limit, otherwise the limit never fires and the test stops exercising the path at all; foo currently has 3 series, so this is probably not a settings-only edit. I would prefer the executor fix: the test is pinning a real ordering contract, and the same drop applies to any PromQL response that hits a mid-stream error after the first block.
Unrelated: the older hit on this test (2026-07-19, PR 93757) carries a different error text (There is no query or query context has expired), so it is not the same mechanism.
2. "Not-ready set"
- Issue: Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) #107619
- Fix in flight: Not a fix: "Not-ready Set" exception when buildOrderedSetInplace fails #102192 (open, still a draft as of today)
This is unrelated to your diff. The abort comes from FunctionIn on a fuzzed 04545_analyzer_with_cte_over_distributed query, while the PR only touches PrometheusHTTPProtocolAPI.{cpp,h}. Breadth over the last 30 days: 258 rows across 201 distinct PRs plus 15 master rows for the family, of which this sub-STID (0250-4e52) is 74 rows over 67 PRs and 6 master rows.
Worth knowing before you count on #102192 closing it: the destructive fallback in PreparedSets.cpp stays reachable for sources that cannot be cloned, and DelayedCreatingSetsStep (CreatingSetsStep.h:57) and DelayedMaterializingCTEsStep (MaterializingCTEStep.h:59) still do not override clone() (that PR does not touch either header). So those shapes keep the pre-PR behaviour and the family may not be fully closed by it.
|
@groeneai I'd better not touch the |
|
Done. Reliable test-side fix below, with the measurements. First: a settings-only edit cannot work, and I confirmed why. A deterministic reproducer. Pin the server to one core. Unpinned on this 96-core box the test passed 20/20 and told me nothing; pinned it fails most runs with exactly the CI error. That single change is what made all of the below measurable. The fix I recommend: give this one test its own wide metric. # in send_test_data(), alongside the existing metrics:
# `wide_abort` is used only by test_query_after_response_sent: enough series that
# the producer is still generating rows when the result limit trips, so the first
# block is already flushed to the client before the exception surfaces.
send_to_clickhouse(
[
({"__name__": "wide_abort", "idx": str(i)}, {110: float(i), 130: float(i * 2)})
for i in range(100)
]
)and in I deliberately did not touch Verification (real server, your head's prebuilt
I also ran the proposed test body verbatim, assertions included, against the new fixture: 60/60 pass. Pointing that same body back at Controls: on master's sync executor the same pinned core gives 20/20 for both the current and the proposed settings, so the change does not depend on your diff and does not weaken trunk. With no result limit at all, both metrics return One caveat worth knowing, because it rules out the tempting minimal version. That margin is why this is a stopgap that hides the race rather than removing it: the consumer-side drain in Happy to open a PR with just this test change if you want it landed separately from yours. |
|
I'll try to fix the test |
| try | ||
| { | ||
| PullingPipelineExecutor executor(io.pipeline); | ||
| PullingAsyncPipelineExecutor executor(io.pipeline); |
There was a problem hiding this comment.
Switching this endpoint to PullingAsyncPipelineExecutor changes the HTTP API's observable error ordering for small partial-result queries. PullingAsyncPipelineExecutor::pull rethrows has_exception before it drains LazyOutputFormat (src/Processors/Executors/PullingAsyncPipelineExecutor.cpp:117-142), and that queue can already hold two chunks (src/Processors/Formats/LazyOutputFormat.cpp:12-37). A query that throws after producing only one or two result blocks therefore fails out of the first pull(block) here, before writeQueryResponseHeader runs, so PrometheusRequestHandler takes the response.sent() == false path and emits a 400 Prometheus error envelope instead of the old 200 + truncated chunked success body with __exception__ (src/Server/PrometheusRequestHandler.cpp:563-583).
The widened stream_error fixture only forces the exception later; it does not preserve that existing contract for smaller result sets. Could we either drain already-buffered chunks before surfacing the exception, or keep this endpoint on the synchronous executor until that ordering is fixed?
There was a problem hiding this comment.
It's OK to emit a 400 Prometheus error envelope with no data after an exception, nothing to fix here
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 3/3 (100.00%) · Uncovered code |
|
@groeneai investigate the test failure and provide a link to existing PR or just fix it yourself. |
|
Investigated. CI on The integration side is green on every flavour now, including all the prometheus ones (amd_msan 8/8, amd_tsan 6/6, amd_llvm_coverage 8/8, amd_asan_ubsan 6/6, arm_binary 4/4), so the test fix in The one remaining failure is The existing PR is #111691, yours, open since 23 July. It adds I checked that it really covers this run rather than assuming it. There is a single guard, Measured on a current-master debug build, against the assertion that actually failed in your run (the duplicated non-key column one, line 55 of the
Seeds 90710 and 71129 are two of the seeds CI recorded on earlier real failures of this test, so they are live carriers and not synthetic ones. One detail that matters for reading this row: the harness reported Also worth flagging so the file does not mislead you: it already has a If you would rather not wait for #111691, tell me and I will open the one-line pin for this file on its own today. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
The Prometheus query API (
/api/v1/query,/api/v1/query_range) of the experimental TimeSeries engine now executes queries in parallel instead of on a single thread.Documentation entry for user-facing changes
Extracted from #111697 (rebased onto master so it can be reviewed independently). Companion PR: time-series codecs for the samples table.
The HTTP PromQL endpoints executed the generated SQL through
PullingPipelineExecutor, which by design runs the whole pipeline on a single thread — so PromQL queries over the HTTP API never parallelized regardless of machine size. Switching toPullingAsyncPipelineExecutorlets them use the normal query thread pool. The pull loop and result-cache finalization are unchanged.Evidence (tsbench kube-mixin corpus, scale 16, ~15.7B samples, 32-core machine, debug build): a 30d
sum by (namespace) (rate(container_cpu_usage_seconds_total{...}[5m]))range query over the identical generated SQL:/api/v1/query_range(before)With this change the HTTP path matches the native path. Together with the codec companion PR, the full 24-query kube-mixin benchmark improved 2–9x per query group (cold), with identical results on all 24 queries.
🤖 Generated with Claude Code
Version info
26.8.1.290(included in26.8and later)