Skip to content

Revert "Revert the PromQL topk/limitk streaming plan and its shared-subquery materialization" - #114409

Merged
nikitamikhaylov merged 4 commits into
masterfrom
revert-114326-revert-promql-topk-streaming-deadlock
Aug 13, 2026
Merged

nikitamikhaylov merged 4 commits into
masterfrom
revert-114326-revert-promql-topk-streaming-deadlock

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

Reverts #114326
Depends on #113397

Version info

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

@alexey-milovidov
alexey-milovidov marked this pull request as draft August 12, 2026 01:15
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a6ed1e8]

Summary: ❌

job_name test_name status info comment
Stress test (arm_tsan) FAIL
Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (null map size = A, nested column size = B) (STID: 6726-6874) FAIL cidb IGNORED
Performance Comparison (arm_release, master_head, 3/6) FAIL Performance dashboard
polymorphic_parts_s #0::old FAIL query history IGNORED
polymorphic_parts_s #0::new FAIL query history IGNORED
polymorphic_parts_s #2::old FAIL query history IGNORED
polymorphic_parts_s #2::new FAIL query history IGNORED

AI Review

Summary

This PR re-lands the streaming PromQL topk / bottomk / limitk plan by introducing timeSeries{TopK,BottomK,LimitK}Masks and by marking shared PromQL subqueries AS MATERIALIZED. The direction is reasonable, but the current head still has one silent wrong-result case in the new public aggregate and one remaining entrypoint gap on the Prometheus HTTP API, so I do not think it is ready to merge as-is.

Findings

❌ Blockers

  • [src/AggregateFunctions/TimeSeries/AggregateFunctionTimeSeriesTopKMasks.h:143-156,264-300] The new aggregate ranks rows before it enforces any uniqueness on key, and insertResultInto only merges duplicates after those rows have already occupied heap slots. A minimal repro is timeSeriesTopKMasks(2, key, values) over (1, [10]), (1, [10]), (2, [9]): step 0 keeps both key = 1 rows, then finalization collapses them back to one output row, so the function returns fewer than k distinct series and silently drops the better distinct key. The public SQL contract and tests never establish "duplicate keys are invalid input", so this is a wrong-result case for the newly exposed aggregate API.
    Suggested fix: either reject repeated key values while aggregating / merging, or merge candidates by key before the top-k selection; add a focused regression case with duplicate keys.

⚠️ Majors

  • [src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp:124-130] This path only auto-enables enable_materialized_cte, but it still executes the generated SQL through executeQuery. When the request or profile sets enable_analyzer = 0 or allow_experimental_analyzer = 0, the old analyzer ignores AS MATERIALIZED, so shared PromQL operand grids for shapes like or and topk are still rescanned on the HTTP API path. The table-function path now avoids that by going through InterpreterSelectQueryAnalyzer, so the two PromQL entrypoints still diverge on the same query shape.
    Suggested fix: force the analyzer on for machine-generated PromQL SQL before executeQuery (or include the equivalent follow-up here) and add an integration test that asserts the HTTP API path does not re-read the shared operand grid.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Fix the duplicate-key handling in timeSeries{TopK,BottomK,LimitK}Masks and cover it with a focused regression test.
  • Make the Prometheus HTTP API execute the generated SQL with analyzer-based materialized CTE handling so it matches the table-function path.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 433/447 (96.87%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 12, 2026
Comment thread src/Storages/StoragePrometheusQuery.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 691.73 MiB 688.95 MiB -2.78 MiB (-0.40%)

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 sizes ⚠️

9 object files changed (+651.71 KiB total), 2 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/TimeSeries/AggregateFunctionTi… new 668.20 KiB +668.20 KiB
src/CMakeFiles/dbms.dir/Storages/TimeSeries/PrometheusQueryToSQL/applyLimitAggregationOperator.cpp.o 184.75 KiB 157.62 KiB -27.12 KiB (-14.68%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@nikitamikhaylov

Copy link
Copy Markdown
Member

We also need to merge this PR afterwards: #114261

…-114326-revert-promql-topk-streaming-deadlock
/// The generated SQL relies on `AS MATERIALIZED` to avoid evaluating subqueries referenced more than once
/// repeatedly (see SQLSubqueryType::MATERIALIZED_TABLE), and that mark has effect only with the setting
/// `enable_materialized_cte` enabled. Enable it unless the user set it explicitly.
if (!getContext()->getSettingsRef()[Setting::enable_materialized_cte].changed)

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.

With enable_analyzer = 0 / allow_experimental_analyzer = 0 (either from URL parameters or the user's profile), this still does not materialize the shared PromQL subquery on the HTTP path. executeQuery honors that setting, the old analyzer ignores AS MATERIALIZED, and shapes like or / topk fall back to rescanning the shared subquery once per use. The table-function path avoids that because StoragePrometheusQuery::readImpl always goes through InterpreterSelectQueryAnalyzer, so the two PromQL entry points still diverge here unless we also force the analyzer on before executeQuery (the follow-up in #114261).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Correct — the HTTP API path with the old analyzer is fixed separately in #114261, which forces the analyzer on for the machine-generated PromQL SQL before executeQuery and adds an integration test asserting on read_rows with enable_analyzer = 0. Per the maintainer's comment on this PR, #114261 is to be merged right after this re-land, keeping this PR a clean revert of the revert.


const size_t mask_begin = mask_data.size();
mask_data.resize_fill(mask_begin + num_steps, 0);
for (; i != selected.size() && selected[i].first == key; ++i)

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.

This collapses duplicate key values only after they have already occupied slots in the per-step heaps. A minimal repro is timeSeriesTopKMasks(2, key, values) over rows (1, [10]), (1, [10]), (2, [9]): step 0 keeps the two key = 1 entries, and this loop then merges them back into one mask row, so the function returns only series 1 even though there are two distinct series with values.

Because the new aggregate is public and documented only as "key identifies the series", duplicate keys need to be rejected while aggregating or merged by key before ranking. As written, the function can return fewer than k distinct series and drop a better distinct key silently.

@nikitamikhaylov

Copy link
Copy Markdown
Member

@groeneai help with tests here. Are they related to changes? Link (or implement first) the fixes for all of them in separate PRs.

…-114326-revert-promql-topk-streaming-deadlock
@groeneai

Copy link
Copy Markdown
Collaborator

Four distinct reds across the three earlier heads. One is caused by this PR; three are not. The run on the current head a6ed1e8e is still in flight (19 in_progress / 12 queued at the time of writing), and I checked the praktika reports for all three earlier heads: 0 DROPPED jobs, so each of those runs had real coverage.

1. Performance Comparison (arm_release) -- caused by this PR, and it is the only one that needs action here.

This is not noise, and it is not a regression: it is tests/performance/promql_topk.xml, the perf test this PR adds. It fails on all three heads, always in whichever shard picked it up (3/6, then 1/6, then 6/6), reported as 10 errors. The captured error is:

Code: 241. DB::Exception: (total) memory limit exceeded: would use 36.14 GiB
(attempt to allocate chunk of 35.76 GiB), current RSS: 41.14 GiB, maximum: 52.95 GiB
  while executing 'FUNCTION arrayBottomK(i UInt32 -> arrayElement(v, i), 5_UInt8, arrayEnumerate(v))'
  while executing 'FUNCTION arrayMap(... arrayTranspose(groupArray(__table6.values)) ...)'

The raw timings show which side dies. Connection 0 is the left/old server (master), connection 1 is the new one:

prewarm  promql_topk.query1.prewarm0  conn 0  10.666
prewarm  promql_topk.query1.prewarm0  conn 1   0.095
query    promql_topk.query1.run0      conn 0  10.228
query    promql_topk.query1.run0      conn 1   0.067
query    promql_topk.query1.run2      conn 1   0.067      <- conn 0 absent: it threw

So the new plan runs the query in 0.068 s while master takes ~10 s and then OOMs on a later run. That is expected: promql_topk.xml does not exist on master, so the old arm evaluates the same PromQL through the pre-PR arrayTranspose(groupArray(values)) path, which materializes the whole 4000 x 300 grid before arrayBottomK selects 5 rows. The fixture (4000 series x 300 points) is sized for the streaming plan this PR introduces, not for the plan it replaces.

Two consequences, both from the harness's own thresholds: get_allowed_single_run_time is 2 s for a non-benchmark test, so the ~10 s old-side run trips both "too slow to run as a whole" and "some query is too slow to run"; and the OOM on the old side aborts the comparison with a run error. A -150x ratio is also not a measurable comparison.

I will send a separate PR shrinking the fixture so the pre-PR plan stays inside the per-run budget while the query shapes and the thing being measured are unchanged, and will link it here. Nothing in src/ needs to change for this.

2. Stress test (amd_asan_ubsan) / Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (STID 6726-6444) -- not related.

Chronic trunk bug in skip-index deserialization. The stack is SerializationNullable::deserializeBinaryBulkWithMultipleStreams <- MergeTreeIndexGranuleSet::deserializeBinary <- MergeTreeIndexReader::read <- MergeTreeDataSelectExecutor::filterMarksUsingIndex, reached from optimizeUseAggregateProjections. No TimeSeries or PromQL frame, and this PR touches no file under src/Storages/MergeTree/ or src/DataTypes/.

Breadth over 7 days: 79 rows across 68 distinct PRs including 8 true master runs for this sub-signature alone, 297 rows / 207 PRs / 21 master runs for the whole error family.

Fixing PR: #112484 (mine, open) -- it changes MergeTreeIndices.cpp, which is frame 2 of that stack.

report

3. Stateless tests (amd_debug, parallel) / 04357_distributed_alias_same_expression -- not related.

Result diff of 300 300 2 vs two 300 300 1 rows: un-merged GROUP BY groups on duplicate-ALIAS GROUP BY over a Distributed table under two-level aggregation. Praktika's own rerun on this head declares it flaky, 17 of 73 reruns failed with the same randomized settings (group_by_two_level_threshold_bytes 1, prefer_localhost_replica 0). Breadth over 30 days: 154 rows across 132 PRs and 15 master runs.

Tracked as #112987; fixing PR #108855 (mine, open).

report

4. Integration tests (amd_tsan, 4/6) / test_drop_database_replica_with_tables_for_detached_db -- not related.

The test itself passed; it failed in cluster.shutdown() with Sanitizer assert found for instance zoo1. The Keeper container's stderr holds a TSAN vptr report whose top frame is DB::getRequestBytesCost at KeeperRequestDispatcher.cpp:92, via tryPopRequest on the dispatch thread. This PR touches no file under src/Coordination/, and the victim test is whichever one ran last in the shard.

Breadth over 14 days for this teardown signature: 283 rows across 272 distinct tests and 17 PRs, 0 master runs -- the incidental-victim pattern.

Fixing PR: #113552 (mine, open), which suppresses exactly that top frame.

report

I will re-check the a6ed1e8e run once it finishes and report anything new. Separately: #114261, which you asked to merge alongside this, is the HTTP-API analyzer fix and is open and ready.

@nikitamikhaylov

Copy link
Copy Markdown
Member

@groeneai check one more time.

@groeneai

Copy link
Copy Markdown
Collaborator

Rechecked at the current head a6ed1e8ecee789871631964f2e25315ae3fb742c. The run has progressed since my last comment: 141 success, 20 skipped, 12 still running, 2 failed. Coverage is real (praktika reports 0 dropped jobs; every skip carries a reason).

Two of the three unrelated reds re-ran green here: Stateless tests (amd_debug, parallel) and Stress test (amd_asan_ubsan) are both success at this head. Integration tests (amd_tsan, 4/6) is still running.

Still failing:

1. Performance Comparison (arm_release, master_head, 3/6) - caused by this PR, unchanged. All 10 run errors are promql_topk, the perf fixture this PR adds. The reference (master) arm is the one that dies: conn 0 (left/old) runs at 10.33-10.46s, conn 1 (new) at 0.070-0.074s, diff -0.993, and the error is Code: 241 ... would use 36.18 GiB (attempt to allocate chunk of 35.76 GiB) ... maximum: 53.11 GiB with arrayTopK / FunctionArrayMapped / ColumnReplicated frames. Master has no streaming plan, so it evaluates the same PromQL through applyLimitAggregationOperator, where the sort-key lambda captures the N-element values array and FunctionArrayMapped replicates that capture once per element: quadratic in the series count, and 8 * 300 * 4000^2 is 35.76 GiB, matching the requested chunk exactly. The fixture is sized for the new plan only.
report

I am sending a separate PR that adds tests/performance/promql_topk.xml at a series count both plans can run, query shapes unchanged, and will link it here. Once it is in, please drop the copy of that fixture from this PR.

2. Stress test (arm_tsan) - NEW at this head, not related. Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization. The offending query is EXPLAIN indexes = 1 SELECT count() FROM test_table WHERE value = '300' from 03702_alter_column_modify_secondary_index_*: a plain skip-index read after ALTER TABLE ... MODIFY COLUMN, with no PromQL or TimeSeries in it. Frames are SerializationNullable::deserializeBinaryBulkWithMultipleStreams <- MergeTreeIndexBulkGranulesSet::deserializeBinary <- MergeTreeIndexReader::read. This PR touches nothing under src/Storages/MergeTree/ or src/DataTypes/, and does not touch that test. Breadth over 7 days: 127 rows across 104 PRs plus 9 true master runs for this stack bucket, 306 rows across 209 PRs plus 23 master for the whole signature. Fixing PR: #112484 (mine, open), which gates skip-index deserialization on whether the part's bytes match the type about to decode them.
report

Fixes for the two that went green here, in case they come back: 04357_distributed_alias_same_expression -> #108855 (mine, open); test_drop_database_replica_with_tables_for_detached_db -> #113552 (mine, open), which suppresses the Keeper request-size vptr TSAN report at its top frame.

@nikitamikhaylov

Copy link
Copy Markdown
Member

Performance test OOMed on the master build, that's the subject of the PR.
GroeneAI suggested merging, I trust GroeneAI.

@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Aug 13, 2026
Merged via the queue into master with commit e7cd7b6 Aug 13, 2026
178 of 181 checks passed
@nikitamikhaylov
nikitamikhaylov deleted the revert-114326-revert-promql-topk-streaming-deadlock branch August 13, 2026 21:15
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 13, 2026
…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]>
alexey-milovidov added a commit that referenced this pull request Aug 24, 2026
Edited following .claude/skills/edit-changelog/SKILL.md, by hand on a
workstation: the editing step of the NightlyChangelog job has been failing
its own verification since 2026-08-12, so three raw blocks had accumulated
(47 + 84 + 628 entries).

Of the 759 raw entries, 482 are integrated into the in-progress 26.8 section
and 277 are dropped:

- Section 3: the 300 `NOT FOR CHANGELOG / INSIGNIFICANT` entries are dropped,
  except 41 that describe a user-visible change and are promoted into a real
  category, among them a server abort on a corrupt `ORC` stripe footer
  (#114924), `EXPLAIN ANALYZE` for streaming queries (#112445), `SELECT` from
  `TimeSeries` (#115622), streaming watermarks (#106169), and the
  `clickhouse-local` CORS overrides (#115129).
- Section 2: every revert in the range cancels out inside it, so neither side
  appears. Two are re-applications: #114912 re-applies the
  `accurateCastOrDefault` fix, so #109946 keeps its entry with both links and
  the intervening revert #114911 is gone; #114409 re-applies the PromQL
  streaming plan, recorded on the #113656 entry.
- Section 4: `Build/Testing/Packaging Improvement` keeps the seven entries a
  user, packager or from-source builder notices (musl `getaddrinfo` and
  `sched_getcpu`, signed macOS artifacts, Debian packages for release builds
  only, zstd-compressed Docker layers, `unit_tests_dbms` without the full
  library set, vendored Rust built with optimizations locally) and drops the
  CI plumbing.
- Sections 5 and 6: bare pull request URLs converted to links, settings put
  in backticks, four entries rewritten from developer notes into user-visible
  descriptions, and three moved into `Performance Improvement`.

No entry of a strict-retention category was deleted: the job's own
`verify_edit` passes on this edit.

Not done here, because the release manager does it at release time: the full
significance sort, the aggressive merging of sibling pull requests, and the
`FIXME` release date and presentation links.
@groeneai

Copy link
Copy Markdown
Collaborator

Closing the loop on the fixture PR I promised in this thread: I am not sending it, and the copy of tests/performance/promql_topk.xml that landed with this merge should stay as it is. Apologies for the late note.

Merging this removed the premise of the red. Master now takes the timeSeries{TopK,BottomK,LimitK}Masks path for topk/bottomk/limitk (applyLimitAggregationOperator.cpp:143-145), so the reference arm of a master_head comparison runs the streaming plan too and the quadratic arrayTopK capture that asked for 35.76 GiB is gone from that side. I measured the streaming plan at about 0.4 GiB at 4000 series, flat in the series count, so shrinking the fixture to a size both plans could run would now only strip 3.3x of the series load from a benchmark that passes comfortably: weaker measurement, no CI benefit.

The fixture has been green on master since: 9,822 recorded promql_topk runs over the last 30 days, zero FAIL or ERROR (2 rows flagged unstable, which is measurement noise rather than a failure).

One fragility worth recording: the fixture is committed at 4000 series, a size only the streaming plan can run, so any future PR that removes that plan again (it was reverted once in #114326 and restored here) will hit the same allocation on whichever arm lacks it. If a guard that does not depend on which plan master carries is wanted, say so and I will send one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog 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