Skip to content

perf(promql): reuse scalar range-function argument vectors - #19389

Merged
bwplotka merged 1 commit into
prometheus:mainfrom
perfloop-oss:perfloop-pr-open-948xkz1wbx
Nov 2, 2026
Merged

bwplotka merged 1 commit into
prometheus:mainfrom
perfloop-oss:perfloop-pr-open-948xkz1wbx

Conversation

@perfloop-agent

@perfloop-agent perfloop-agent commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Which issue(s) does the PR fix:

N/A.

Release notes for end users (ALL commits must be considered).

Reviewers should verify clarity and quality.

[PERF] PromQL: Reuse scalar argument vectors across range-function steps.

Range-function evaluation created a one-sample Vector for each scalar argument, selected series, and query step. This change initializes each scalar slot once and overwrites the complete Sample before each call. The FunctionCall contract now states that these inputs must not be retained or modified. Changing-scalar tests cover all three affected built-ins: predict_linear, double_exponential_smoothing, and quantile_over_time.

Benchmark

No new benchmark is needed. The existing BenchmarkRangeQuery measures the changed evaluator path. It already includes double_exponential_smoothing(a_X[1d], 0.3, 0.3) at 1 and 100 series, with 1 and 1,000 steps. The removed API benchmark duplicated this coverage.

I compiled promql.test at current upstream main (d15adb9ad7e5d9fbde3a9a8f30200593a5a14d86) and this PR (e2e7e2dad82db9a6abcc196eda1c23424e476b98). I ran all 207 PromQL benchmark cases six times per revision in fresh processes, with three baseline-first pairs and three Candidate-first pairs:

go test -c -o /tmp/promql.test ./promql
/tmp/promql.test -test.run='^$' -test.bench='.' -test.benchmem -test.count=1
benchstat baseline.txt candidate.txt

Host: Apple M3 Max, darwin/arm64, Go 1.26.4. The host was busy, so timing varied. The affected 100-series, 1,000-step row has no statistically supported timing change:

metric       baseline          candidate        change
sec/op       7.540 ± 44%       8.140 ± 42%      ~ (p=0.818 n=6)
B/op         17.588 MiB ± 2%   8.404 MiB ± 3%   -52.22% (p=0.002 n=6)
allocs/op    225.79k ± 0%      25.59k ± 0%      -88.67% (p=0.002 n=6)

The full sweep flagged two unrelated timing rows and one unrelated allocation row. The changed scalar-argument path cannot execute for those expressions. A focused rerun of those exact rows used ten fresh samples per revision with alternating order:

row                                      metric       baseline   candidate   benchstat
changes(a_hundred[1d]), steps=1000       sec/op       2.086      2.177       ~ (p=1.000 n=10)
                                          B/op         5.183 MiB  5.183 MiB   ~ (p=0.564 n=10)
                                          allocs/op    24.74k     24.74k      ~ (p=0.617 n=10)
rate(a_one[1d]), steps=1000              sec/op       12.41 ms   12.06 ms    ~ (p=0.796 n=10)
rate(a_hundred[1d]), steps=1             sec/op       29.82 ms   30.24 ms    ~ (p=0.912 n=10)

No unrelated regression reproduced. This PR makes no latency claim.

Checks

go test ./promql/... -count=1

Generated by Perfloop. Human sponsor: Tomas Senart. Case and evidence.

@bboreham bboreham left a comment

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.

Thanks for this. Your results show an improvement in memory allocation but no speed improvement. We may not want to add 100 lines of code for that.

Since an improvement in one place might trigger a slowdown elsewhere, please run all the existing PromQL benchmarks and post the comparison using benchstat.

Also please comment on why a new benchmark is needed.

Comment thread promql/engine.go Resolved
Comment thread promql/engine.go Resolved
@tsenart
tsenart force-pushed the perfloop-pr-open-948xkz1wbx branch from cdf2720 to e2e7e2d Compare August 21, 2026 18:10
@perfloop-agent

Copy link
Copy Markdown
Contributor Author

@bboreham Addressed in e2e7e2dad and the updated PR body. I removed the 120-line API benchmark because existing BenchmarkRangeQuery already covers the exact evaluator path. I ran all 207 PromQL benchmark cases six times per revision. The 100-series, 1,000-step case uses 52.22% fewer bytes and 88.67% fewer allocations, with no supported timing change. A ten-pair focused rerun also disproved the unrelated flags from the full sweep.

@roidelapluie

Copy link
Copy Markdown
Member

LGTM, needs rebase

@perfloop-agent
perfloop-agent force-pushed the perfloop-pr-open-948xkz1wbx branch from e2e7e2d to 3859b80 Compare October 28, 2026 14:43
@perfloop-agent

Copy link
Copy Markdown
Contributor Author

Some flaky network caused the CI failure.

@github-actions github-actions Bot removed the stale label Oct 31, 2026
@bwplotka
bwplotka merged commit 2845a00 into prometheus:main Nov 2, 2026
38 of 39 checks passed
daverigby added a commit to daverigby/prometheus that referenced this pull request Nov 4, 2026
quantile_over_time allocates a new sample slice for every selected
series and evaluation step, then discards it after sorting. Keep the
values slice in the existing EvalNodeHelper, reset its length and
overwrite every active sample on each call. The quantile calculation and
result representation are unchanged.

The scratch belongs to one node evaluation. Results contain only the
computed float and do not retain the slice. The largest capacity remains
live until that node finishes, so this exchanges repeated allocations
for query-local retention. The change adds no pool, dependency or
runtime option.

Original Linux/Arm measurements used Go 1.27.3, GOARM64=v8.0,
CGO_ENABLED=0 and netgo,builtinassets tags, with normal optimisation and
no PGO. Baseline:

4a933f8

The unchanged quantile_over_time range benchmark used 100 series, 1,000
steps, a changing scalar quantile and a fixed one-minute subquery. Five
baseline/candidate fixed-100-query pairs reduced median elapsed from
23.048 to 11.716 ms/query (-49.2%), bytes from 31.54 to 2.69 MB/query
(-91.5%) and allocations from 204,123 to 103,995/query. Whole-process
user+system CPU, including fixture setup, fell from 8.09 to 5.68 seconds
(-29.8%).

Five adapted normal-server rounds, each with 50 complete HTTP requests
after warm-up, reduced one-hour quantile target CPU from 0.2196 to
0.0800 seconds/request (-63.6%). The changing-quantile five-minute case
fell from 0.0254 to 0.0100 (-60.6%). The fixture has ten gauge series
and 1,001 query steps. Full response hashes matched in every round.
Client CPU is excluded; this is synthetic validation, not a
production-frequency or fleet-savings estimate.

Arm Performix 1.24.0 profiles identified the changed hot path. Profile
shares are diagnostic; the elapsed and CPU figures above come from
separate unprofiled runs.

Fresh review measurements were rerun on daver-whale-boat-5, Ubuntu
26.04.1 Linux/arm64, with 16 Neoverse-V2 CPUs and Go 1.27.3. Both builds
use CGO_ENABLED=0, GOARM64=v8.0 and netgo,builtinassets tags, normal
optimisation/inlining and default runtime settings. Six serial
equal-work pairs alternate baseline/candidate order, with 100 fixed
queries per process. Both binaries contain identical added tests. Builds
and tests completed before measurement; no other benchmark or server was
run concurrently.

    metric                    baseline       candidate
    elapsed ms/query           22.759376       11.470171
    bytes/query               31542333.5       2693695.0
    allocations/query           204124.0        103996.0
    whole-job CPU seconds       7.865017        5.606228

These medians show 49.60% lower query elapsed and 28.72% lower whole-job
user+system CPU. Query ns/op excludes fixture setup; whole-job CPU
includes fixture setup and process startup, so the CPU row is per
process, not per query. Raw samples, binary hashes, commands and
benchstat output are retained in the Linux review evidence packet.

The six-pair benchstat elapsed comparison is -49.60% (p=0.002, n=6).

Fresh normal server binaries were built on the same VM using the
supported make/promu prebuilt-assets route, identical published
v3.16.0-rc.2 UI asset bytes and matching static/netgo/builtinassets
settings. The older published assets are a held-fixed packaging
difference. Six alternating fresh-server pairs used 50 complete requests
per case after warm-up. The reused synthetic TSDB has ten series and
1,001 query steps. Target-process user+system CPU is sampled directly
around the HTTP loop and excludes setup and client CPU. Complete
response bytes match across every measured request and both builds.

    adapted server case      baseline CPU-s/req  candidate CPU-s/req
    quantile_1h                        0.211000             0.080000  (-62.09%)
    quantile_5m_dynamic                0.024000             0.009900  (-58.75%)

These Linux reruns replace the earlier Mac review measurements. The
original Linux hunt results above remain separate historical
observations. This is a focused synthetic comparison; production
frequency and fleet savings are unknown.

The maintained benchmark is unchanged:

    BenchmarkRangeQuery/expr=quantile_over_time(time()_%_100_/_100,_a_hundred[1m:10s]_@_86400),steps=1000

Reproduce each sample using the baseline and candidate promql.test
binaries with the following flags and an exact match for that case:

    CGO_ENABLED=0 GOARM64=v8.0 \
      go test -p 4 -c -tags=netgo,builtinassets \
      -o promql.test ./promql
    ./promql.test -test.run='^$' \
      -test.bench='^BenchmarkRangeQuery$/^expr=quantile_over_time\(time\(\)_%_100_$/^_100,_a_hundred\[1m:10s\]_@_86400\),steps=1000$' \
      -test.benchmem -test.benchtime=100x -test.count=1

Add range cases to the existing query corpus with multiple sparse
series, differing window lengths and changing scalar quantiles. Their
expected outputs pass on both the unmodified evaluator and this branch.
Existing mixed-histogram and exceptional-number cases also pass.

Fresh checks passed on this branch on the Linux worker VM:

    CGO_ENABLED=0 GOARM64=v8.0 \
      go test -p 4 -tags=netgo,builtinassets ./promql/... -count=1
    git diff --check

The three production source files still match the original benchmark
baseline before applying this patch. The review branch is based on:

798401c

Related allocation reuse appears in PRs prometheus#19389 and prometheus#19040. Those reuse
scalar argument vectors and MAD values within one call, respectively;
this change reuses quantile sample scratch across series and steps.
Novelty has only been checked in bounded searches.

This is an independent review branch. A complete PromQL benchmark sweep,
full-repository tests, race checks and lint have not been rerun for this
review. These focused Linux measurements do not establish absence of
regressions across all workloads.

Release note: [PERF] PromQL: Reuse quantile_over_time scratch across
series and steps.
aknuds1 added a commit to grafana/mimir that referenced this pull request Nov 5, 2026
The mimir-prometheus update adds upstream promqltest cases for scalar
arguments to range-vector functions being refreshed every step
(prometheus/prometheus#19389). Mirror them in
pkg/streamingpromql/testdata/upstream/functions.test to keep
TestOurUpstreamTestCasesAreInSyncWithUpstream passing.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants