Skip to content

Dynamic filter pushdown for PromQL group_left binary operations - #121107

Open
valerypetrov wants to merge 24 commits into
ClickHouse:masterfrom
valerypetrov:feature/promql-dynamic-filter-pushdown
Open

valerypetrov wants to merge 24 commits into
ClickHouse:masterfrom
valerypetrov:feature/promql-dynamic-filter-pushdown

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

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

Speed up PromQL binary operations with group_left by filtering the right-side series by the left-side join groups before evaluation. Applies when the right side is a selector or a chain of offset, subqueries and last_over_time over one, except for matching with on ().

Detailed description for reviewers:

The left side is materialized once, and join_group IN (SELECT join_group FROM left WHERE <the row has a value>) is added to the right side's selector and range-aggregation stages when every wrapper keeps group unchanged (selector, offset, subquery, last_over_time). on () is skipped, because its join group is always the same. group_right is unchanged. Duplicate series are still checked by master's code after the join, so results and errors are the same as on master: the 05233_* tests give the same output on this PR and on master, apart from one EXPLAIN check of the pushdown.

promql_group_left_dynamic_filter (50,000 target_info series, 2 match), CI performance comparison at 3eced9f: 0.46 s to 0.22 s (selector) and 0.39 s to 0.20 s (offset) on amd_release, 0.26 s to 0.17 s (both) on arm_release; peak memory about 870 MB to 70 MB.

🤖 Generated with Claude Code


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

@clickhouse-gh clickhouse-gh Bot added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Sep 20, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [30ca3ce]

Summary: ✅


AI Review

Summary

The PR filters eligible right-side series of PromQL group_left operations using the materialized left-side join groups. Its conservative wrapper allow-list preserves labels, and current master's duplicate validation remains in place. No unresolved findings remain after reviewing the current diff, surrounding code, and all prior discussion. The focused benchmark and reported before/after measurements support the performance claim.

Missing context / blind spots
  • ⚠️ Full build, stateless, and performance jobs for head 30ca3ce134df519066620eab32e64ffd2419e5b3 are still pending. On the preceding commit 3eced9fea8049b16b9ed1acc14985cdb3042ca8c, all four new stateless tests passed 50 runs each; the modified converter file is identical at the current head. Completion of current-head CI will close this gap.
Final Verdict

✅ Approve. No code changes requested. Current-head CI must complete before merging.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 20, 2026
`tables()` hands back an `ASTPtr`, so binding it to `auto *` did not compile, and
`getExpression` is private: the public reader for the WHERE clause is `where()`,
which is what the two call sites use now. `setExpression` is public and stays.

Both `getExpression` call sites are fixed, not only the one the log printed
first: the second sits in the branch that merges the pushed-down filter into an
existing WHERE.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QtEKPyQDMCBZfJkiJcs789
@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

This PR only changes how PromQL group_left binary operators are translated to SQL (it pushes the left side's join groups down into the right side) and adds PromQL tests. None of the clickbench or tpch_adapted_1_official queries call prometheusQuery, so none of them run the changed code. ClickBench Q20 shows a -43.2% improvement with CPU time roughly halved (125 ms against master's usual 213-236 ms). The shift is large enough that the verdict cannot be overridden, but it cannot come from this diff; the most likely cause is a different build base, and a rerun against the exact base commit should confirm it. Q33 (-6.2%) and Q34 (-5.3%) fall inside master's normal variance, have noisy histories, and were correctly left as no change.

clickbench

🟢 1 improved

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 220 125 -43.2% <0.0001 cpu: The verdict is locked by the size of the shift (-43.2%, with CPU time roughly halved). This PR only changes PromQL-to-SQL translation, which this query never runs, so the cause is probably a difference in the build base, not this diff.

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: 66d1c69a-617a-403b-ab03-2bf170fb4181
  • MIRAI run: 9df2940c-1395-481e-a5d7-e6217a98e9f3
  • PR check IDs:
    • clickbench_52082_1791929569
    • clickbench_52097_1791929569
    • clickbench_52106_1791929569
    • tpch_adapted_1_official_52145_1791929569
    • tpch_adapted_1_official_52166_1791929569
    • tpch_adapted_1_official_52187_1791929569

@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 30ca3ce13 with master c3124c7e8 (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.

Object file sizes

5 object files changed (+29.27 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/TimeSeries/PrometheusQueryToSQL/applySimpleBinaryOperator.cpp.o 202.64 KiB 231.90 KiB +29.26 KiB (+14.44%)

711 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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.71, programs/clickhouse-keeper ×0.91 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 5.0 s 9.1 s +5.5 s (+155%)
Compile time of recompiled translation units

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

Job report

valerypetrov and others added 2 commits September 20, 2026 21:16
Eight stateless jobs failed on 05233 with the same two-line diff, reproducible
77 out of 77 runs and unaffected by settings randomization.

Subquery case: a `[5m:1m]` subquery evaluated at t=110 has its steps on epoch
multiples of 60s, so the last step inside the lookback is t=60, before the
first `target_info` sample at t=100. The right side was empty, so `group_left`
returned nothing and the two expected rows never appeared. Using a 10s step
puts a step on a sample and restores them. Deleting the two reference lines
would also go green, but would leave the case degenerate: an empty right side
returns nothing whether or not the pushdown is correct.

Rate case: the expected 0.2 is not what the engine produces. Measured on a
build without this branch, `rate(requests{host="h1"}[50s])` at t=110 is 0.3 and
`rate(rate_target[50s])` is 0.06, so the product is 0.018. Prometheus agrees:
the 10s sampled span extrapolates by half an interval to 15s, giving
10 * 1.5 / 50 and 2 * 1.5 / 50.

Both corrected values were measured, not derived.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QtEKPyQDMCBZfJkiJcs789
@alexey-milovidov alexey-milovidov mentioned this pull request Sep 21, 2026
1 task done
valerypetrov and others added 2 commits September 24, 2026 19:22
With group_left the right side is now filtered by the join groups of the
left side. This test has 50000 right-side series and only two of them match,
so it measures the work the pushdown saves.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hat they still raise

The right side is filtered by the left side's join groups before the
duplicate check, so a duplicate in a group the left side lacks is not an
error. The comment now says so, and the test checks that a duplicate in a
matched group still raises, with and without offset.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@valerypetrov

Copy link
Copy Markdown
Contributor Author

Should be ready for review.

Filtering the right side by the left join groups before the duplicate
check hid duplicates in join groups that the left side does not have.
Prometheus reports them whenever both sides are non-empty. The check now
runs on the unfiltered right side and is skipped only when the left side
is empty.

The pushdown into the selector is kept. It also lets through the join
groups that have more than one series in the selector, found by an extra
read of the selector's groups, so every duplicate still reaches the check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov and others added 3 commits October 8, 2026 15:40
…mic-filter-pushdown

Master now checks duplicate series per step and builds both sides in one loop.
The pushdown now runs inside that loop on the right side of group_left,
and the empty-left rule became a WHERE on the right side.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With on () the join group is always the zero group, so the pushed filter
keeps every right series once the left side is not empty, while the
duplicate candidates still cost an extra read of the right selector.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The pushdown adds a read of the right selector to find duplicate candidates,
so a plan for on () must have fewer reads than the same query with on (dc).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov and others added 2 commits October 8, 2026 21:15
The flaky check runs one changed test in many copies at once, and 05233
took 180-260 s there, over the 180 s limit for a test. Every PromQL query
of it is planned for several seconds under that load. The duplicate and
empty-left cases now live in their own test, so each file stays well under
the limit. No case is changed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The duplicate check of the right side of group_left runs only when the left
side is not empty, as in Prometheus. The emptiness was a row count, but a
row of a filtered left side such as `requests > 1000` can stay with every
value NULL. Such a left side has no sample, so Prometheus returns an empty
result, while the check here still ran and raised on a right-side duplicate.
Now only rows with at least one value are counted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov and others added 3 commits October 9, 2026 09:46
Prometheus evaluates a range query step by step and returns nothing for a
step where the left side of a binary operator is empty, without checking the
right side for duplicates there. The right side was gated on the left side
having a sample at any step, so a range query raised on a right-side duplicate
that exists only at a step where the left side is empty. The right values are
now kept only at steps where the left side has a sample.

The pushed-down left join groups now come only from left rows that have a
value, so a left series removed by a filter no longer keeps its right-side
series in the join.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
In the asan flaky check (50 runs, 8 parallel jobs) 05233 took 141-190 s
per run, and 5 of 42 runs went over the 180 s limit for a test. Every
PromQL query in it is planned for several seconds there. The right-side
subquery, offset and fixed @ cases move with their EXPLAIN checks to
05233_promql_dynamic_filter_pushdown_group_left_wrappers, which leaves 10
queries in 05233 and 6 in the new file. No case is changed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@valerypetrov

Copy link
Copy Markdown
Contributor Author

@groeneai , check what's wrong with CI, prepare fix if applicable.

@groeneai

Copy link
Copy Markdown
Collaborator

The only red is Performance Comparison (amd_release, master_head, 3/6), and this PR did not cause it.

  • What blocks it is the dashboard verdict on uuid_ip_comparison #3 (SELECT count() FROM cmp_uuid_ip WHERE fs16_a < fs16_b): 66.1 -> 77.4 ms (+17.0%), and it reproduced after the server restart (+17.9%). That query never touches the PromQL/TimeSeries code. It hits the slow mode of the scalar 16-byte big-endian < kernel on amd, which also shows up on master-vs-master runs.
  • The fix is Vectorize <, >, <=, >= on IPv6 and FixedString(16) for CPUs with AVX-512 #125151, which vectorizes that comparison and was merged on 2026-10-11. It is not in the tree CI tested, because CI built 5110cf17 merged into ff584474. On master, this query went from ~64 ms to ~52 ms at the merge commit and has stayed there since.
  • Next step: merge master. Re-running only the failed job would test the same pre-fix tree.

Your own test looks good: promql_group_left_dynamic_filter #0 and #1 are 1.70x and 1.67x faster, and both reproduced after the restart. Report

valerypetrov and others added 2 commits October 13, 2026 10:55
Master now checks duplicate series of binary operators after the JOIN and
reports them only at steps where the matched series of the other side has
a value. That replaces this branch's own duplicate handling, so the extra
read of the right selector and the per-step mask of the right side are
dropped, and only the pushdown of the left join groups into the right side
is kept on top of master's vector matching.

The tests now expect master's rule: a duplicate in a join group the left
side does not have is not reported.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master c3124c7e8

Suite Baseline Current Delta
Prometheus compliance 100.00% 100.00% +0.00%
Extended support (upstream engine tests) 93.17% 93.17% +0.00%
Suite Passed Failed Unsupported
Prometheus compliance 539 -> 539 (+0) 0 -> 0 (+0) 0 -> 0 (+0)
Extended support (upstream engine tests) 682 -> 682 (+0) 16 -> 16 (+0) 34 -> 34 (+0)

Extended support (upstream engine tests): native-histogram exclusions: 149; excluded assertions: 248; upstream 3da2514eff5c.

Note: Prometheus compliance score is unchanged vs baseline.

Uploaded compliance JSON for this PR commit

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants