Skip to content

Parallelize query execution in the Prometheus query API - #112108

Merged
nikitamikhaylov merged 2 commits into
masterfrom
promql-api-async-executor-and-ts-codecs
Jul 28, 2026
Merged

nikitamikhaylov merged 2 commits into
masterfrom
promql-api-async-executor-and-ts-codecs

Conversation

@nikitamikhaylov

@nikitamikhaylov nikitamikhaylov commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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 to PullingAsyncPipelineExecutor lets 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:

path wall CPU peak threads ConcurrencyControlSlotsAcquired
HTTP /api/v1/query_range (before) 336.6 s 314 s 5 0
native protocol, same SQL 9.9 s 272.6 s 34 31

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

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

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)
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [105b1d8]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, s3 storage, parallel, 3/3) FAIL
04493_correlated_subquery_join_runtime_filter_dup_column FAIL cidb IGNORED

AI Review

Summary

This PR swaps the Prometheus HTTP query endpoints over to PullingAsyncPipelineExecutor and strengthens the integration test so CI reliably exercises the chunked-stream abort path. The performance motivation is clear, but the executor swap still changes the API's observable error ordering for smaller result sets, so I do not think the patch is safe to merge as-is.

Findings

❌ Blockers

  • [dismissed by author -- https://github.com/Parallelize query execution in the Prometheus query API #112108#issuecomment-5097217081] [src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp:95] Switching /api/v1/query and /api/v1/query_range to PullingAsyncPipelineExecutor changes mid-stream error semantics. PullingAsyncPipelineExecutor::pull rethrows producer exceptions before it drains the two-slot LazyOutputFormat queue, so a query that throws after producing only one or two result blocks now fails before writeQueryResponseHeader runs. PrometheusRequestHandler then sees response.sent() == false and emits a 400 Prometheus error envelope instead of the previous 200 + truncated chunked success body with an __exception__ trailer. The new stream_error fixture only pushes the exception later; it does not preserve the existing contract for smaller result sets. Suggested fix: either drain buffered chunks before surfacing the exception, or keep this HTTP path on the synchronous executor until that ordering is preserved.
Final Verdict
  • Status: ❌ Block

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 27, 2026
@nikitamikhaylov nikitamikhaylov added comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... and removed pr-performance Pull request with some performance improvements labels Jul 27, 2026
@nikitamikhaylov
nikitamikhaylov force-pushed the promql-api-async-executor-and-ts-codecs branch from db24fd0 to eebf5f9 Compare July 27, 2026 14:11
@nikitamikhaylov nikitamikhaylov changed the title Parallelize the Prometheus query API and add time-series codecs to TimeSeries samples columns Parallelize query execution in the Prometheus query API Jul 27, 2026
@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 27, 2026
@mintlify

mintlify Bot commented Jul 27, 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 Jul 27, 2026, 2:35 PM

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 9 not_sure 354 390 +10.3% <0.0001 Off-path for this PR (Prometheus HTTP executor swap only); the +10.3% shift on Q9 is variance, and its measurements were noisy at small sample size.

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: 06557df9-f289-4b13-a47b-6b95a699c391
  • MIRAI run: d5df775b-f4c4-459f-893f-6080146da2ee
  • PR check IDs:
    • clickbench_662391_1785242298
    • clickbench_662401_1785242298
    • clickbench_662408_1785242298
    • tpch_adapted_1_official_662419_1785242298
    • tpch_adapted_1_official_662433_1785242298
    • tpch_adapted_1_official_662459_1785242298

@nikitamikhaylov

Copy link
Copy Markdown
Member Author

@groeneai help investigate test_prometheus_protocols/test_query_api.py::test_query_after_response_sent and suggest a fix. Also, link and issue or a PR for "Not-ready set" problem.

@groeneai

Copy link
Copy Markdown
Collaborator

1. test_prometheus_protocols/test_query_api.py::test_query_after_response_sent

This one is caused by the switch to PullingAsyncPipelineExecutor, and it is a race, not a deterministic behaviour change. That is why only 1 of the 5 integration flavours on eebf5f94 shows it (amd_msan, 7/8 FAIL; amd_tsan 4/6, amd_llvm_coverage 2/8, amd_asan_ubsan ... 4/6, arm_binary ... 4/4 all OK), and why #111697 at a74d317e, which already carries the same executor switch, was green on it.

Mechanism

PullingAsyncPipelineExecutor::pull() rethrows the producer thread's exception at the top of the call, before it drains what the producer already handed over:

  1. threadFunction catches TOO_MANY_ROWS_OR_BYTES (thrown from LimitsCheckingTransform::transform, LimitsCheckingTransform.cpp:45), stores it, sets has_exception, and calls data.lazy_format->finalize() (PullingAsyncPipelineExecutor.cpp:83-87). finalizeImpl is just queue.finish() (LazyOutputFormat.h:38-41): the queue is marked finished but its elements are kept. Only onCancel clears them.
  2. The consumer enters pull() and hits data->rethrowExceptionIfHas() at PullingAsyncPipelineExecutor.cpp:117, which throws before line 137 (chunk = lazy_format->getChunk(...)) ever runs. The first result chunk is still in the queue, and it is dropped.

So in writeQueryResponse the very first pull() throws, has_output is never set, writeQueryResponseHeader is never reached, and the handler emits the 400 error envelope instead of the 200 head plus chunked abort that the test pins. The eager rethrow at line 117 is the whole difference: if it is not taken, lines 119-137 deliver that buffered chunk on their own, because lazy_format->isFinished() is isFinishedAndEmpty() and the queue is not empty.

With the sync executor this cannot happen: PullingPipelineExecutor::pull runs executeStep on the caller thread, so chunk 1 is returned by the first pull() and the throw happens on a later step.

Measurements

Unmodified master 1d4408f7, via clickhouse local (it drives the same executor through LocalConnection), SELECT number FROM numbers(100) SETTINGS max_block_size=1, result_overflow_mode='throw', 20 runs each, pinned to one CPU to make the scheduling reproducible:

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.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112108&sha=eebf5f9447f29ee267b5dc197f5d3c05163c6948&name_0=PR&name_1=Integration%20tests%20%28amd_msan%2C%207%2F8%29

2. "Not-ready set"

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.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112108&sha=eebf5f9447f29ee267b5dc197f5d3c05163c6948&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29

@nikitamikhaylov

Copy link
Copy Markdown
Member Author

@groeneai I'd better not touch the PullingAsyncPipelineExecutor. Suggest a reliable fix for test, verify it and report back.

@groeneai

Copy link
Copy Markdown
Collaborator

Done. Reliable test-side fix below, with the measurements.

First: a settings-only edit cannot work, and I confirmed why. foo has 3 series, so the query has 3 result rows. On your head, max_result_rows=1 gives 400 current rows: 2.00, =2 gives 400 current rows: 3.00, and =3 and =4 both return 200 success with no throw at all. The limit that still throws and the limit that clears the race do not overlap for a 3-series fixture, so the fixture has to grow.

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 test_query_after_response_sent only, query wide_abort with max_result_rows=10 instead of foo with max_result_rows=1. Both assertions stay exactly as they are.

I deliberately did not touch foo: it is asserted verbatim by test_error_after_first_block and test_table_query_param, and it is also used by test_evaluation.py and test_upgrade_from_prealpha.py.

Verification (real server, your head's prebuilt build_amd_debug, Build ID ee8166f0... confirmed against buildId() on every arm; the prometheus handler config and TimeSeries table mirror the integration test). Each cell is N HTTP requests:

server pinned to 1 core test as it stands (foo, limit 1) proposed (100 series, limit 10)
idle 39/100 pass 200/200 pass
4 competing spinners on that core 5/40 pass 40/40 pass
16 spinners (starvation) 0/30 pass 30/30 pass

I also ran the proposed test body verbatim, assertions included, against the new fixture: 60/60 pass. Pointing that same body back at foo with max_result_rows=1 fails 56 of 60, so the fixture and the limit are doing the work, not a rewrite of the assertions.

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 200 with a clean terminating chunk 10/10, so the ChunkedEncodingError the test expects really is the mid-stream throw and not an artifact.

One caveat worth knowing, because it rules out the tempting minimal version. LazyOutputFormat's queue capacity is 2, so the obvious argument is "any 3rd row makes the producer block on a full queue, so block 1 must survive". That is not a guarantee. With 12 series and max_result_rows=3 I still lost 7 of 50 runs, and the error body said current rows: 4.00, so the producer had produced 4 rows and the consumer still reached the rethrow before draining. Blocks are one row each here (598/1948/16692 single-byte chunks for the 3/12/100-series metrics at max_block_size=1), so that is not a block-size effect. Hence the comfortable margin rather than the bare minimum.

That margin is why this is a stopgap that hides the race rather than removing it: the consumer-side drain in PullingAsyncPipelineExecutor::pull is still the general fix if you ever want it, but it is your call and I am not pushing it here.

Happy to open a PR with just this test change if you want it landed separately from yours.

@vitlibar

Copy link
Copy Markdown
Member

I'll try to fix the test

try
{
PullingPipelineExecutor executor(io.pipeline);
PullingAsyncPipelineExecutor executor(io.pipeline);

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.

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?

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.

It's OK to emit a 400 Prometheus error envelope with no data after an exception, nothing to fix here

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 80.60% 86.30% +5.70%
Functions 91.50% 92.10% +0.60%
Branches 72.60% 78.40% +5.80%

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

Full report · Diff report

@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Jul 28, 2026
@nikitamikhaylov

Copy link
Copy Markdown
Member Author

@groeneai investigate the test failure and provide a link to existing PR or just fix it yourself.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. CI on 105b1d8c is finished: 175 check runs, 155 success, 19 skipped, 1 failure, and that failure does not come from your diff.

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 105b1d8c did its job.

The one remaining failure is 04493_correlated_subquery_join_runtime_filter_dup_column in Stateless tests (amd_tsan, s3 storage, parallel, 3/3). That is my test (I added it in #109114) and it is a settings-randomization flaky unrelated to this PR: your diff is three files (PrometheusHTTPProtocolAPI.{cpp,h} plus the prometheus integration test) and touches nothing on the runtime-filter path. It has hit 8 other unrelated PRs in the last week and has 0 hits on master.

The existing PR is #111691, yours, open since 23 July. It adds SET join_runtime_filter_min_probe_rows = 0 to exactly this test file. So there is nothing for me to write here; it only needs to land.

I checked that it really covers this run rather than assuming it. There is a single guard, src/Processors/QueryPlan/Optimizations/joinRuntimeFilter.cpp:249-256: the filter is skipped when the probe side's row estimate is at or below join_runtime_filter_min_probe_rows. query_plan_optimize_join_order_randomize replaces real statistics with random cardinalities, so that estimate becomes random and can fall under the threshold. Both settings have to line up, and pinning either one closes it. Your run drew --query_plan_optimize_join_order_randomize 1 --join_runtime_filter_min_probe_rows 4883.

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 .sql), over 20 explicit join-order seeds:

arm result
join_runtime_filter_min_probe_rows = 4883 (your run's value) 3 of 20 seeds return 0: 90710, 590222, 71129
join_runtime_filter_min_probe_rows = 0 (what #111691 adds) 20/20 return 1
those 3 seeds with join-order randomization off 3/3 return 1

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 Runs: 34, Failed: 0 and concluded "not reproducible (likely a transient issue)". That is a structural artifact, not evidence the failure is transient. Per Settings.cpp, query_plan_optimize_join_order_randomize = 1 means "generate a random seed", and only a value above 1 is used as the seed directly, so a rerun with the same recorded settings draws a fresh seed every time. 10 back-to-back runs at = 1 with the same threshold all returned 1 for me. Any 04493 or 04327_runtime_filter_nested_variant row whose diagnosis says "not reproducible" should be read that way.

Also worth flagging so the file does not mislead you: it already has a SET query_plan_join_swap_table = 'false' pin whose comment blames a join side swap. That rationale is wrong, no side swap is involved, and the pin does not prevent this failure. I will correct the comment in a small follow-up once #111691 lands; I am holding it back only because it touches the same SETTINGS block and would conflict.

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.

Merged via the queue into master with commit 4b700dc Jul 28, 2026
177 of 179 checks passed
@nikitamikhaylov
nikitamikhaylov deleted the promql-api-async-executor-and-ts-codecs branch July 28, 2026 17:38
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.

4 participants