Skip to content

TimeSeries selector: filter out empty sample slices only when the time range is shorter than a bucket - #131766

Merged
vitlibar merged 3 commits into
ClickHouse:masterfrom
groeneai:timeseries-selector-empty-slice-filter
Nov 15, 2026
Merged

vitlibar merged 3 commits into
ClickHouse:masterfrom
groeneai:timeseries-selector-empty-slice-filter

Conversation

@groeneai

@groeneai groeneai commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #131678
Related: #122919
Related: #131459

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

A selector over a TimeSeries table with buckets of samples reads timeSeriesSliceSortedArray(samples, a, b) and filters it with WHERE notEmpty(samples). The filter goes to PREWHERE, so the raw samples becomes a PREWHERE-only column, and since #122919 the block-size predictor counts it on top of the slice copy. Tables with granules under 512 KiB are read in about 2x more blocks (2836 vs 1215 at 262144 bytes), so promql_selector_id_range_row_cost #0 and #1 are 1.3x slower on #131678.

A row holds the samples of one bucket and matches the range by min_time and max_time, so its slice can be empty only if the range lies strictly between them, which needs a range shorter than a bucket. The selector now emits the filter only for such ranges, so results do not change. Edge: a row written directly with min_time/max_time looser than its samples now appears as an empty array in timeSeriesSelector(..., 'samples') over a long range; PromQL drops such series. Doubling preferred_block_size_bytes for these reads (#131459) also restores the speed, but enlarges the blocks of every bucketed read.

Validation: new test 05770_time_series_selector_empty_slice_filter (fails on master and on three mutations of the compare), the TimeSeries/PromQL tests, and a new perf test promql_selector_small_granules (131072-byte granules, as in the recent samples table). Release build, master vs this PR on byte-identical parts, 2 x 25 interleaved runs, ratio of medians (PR / master):

row_cost query 131072 262144 524288
#0 whole metric 0.86 / 0.81 0.81 / 0.76 0.93 / 0.84
#1 PromQL 0.88 / 0.83 0.79 / 0.73 0.99 / 0.91
#2 one dc 0.90 / 0.88 0.92 / 0.84 0.94 / 0.87

promql_selector_old_short_window (#131678): 0.94-0.97.

Not for changelog: version 11 (#117344) is only on master.


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

Version info

  • Merged into: 26.11.1.2393-master (included in 26.11 and later)

groeneai and others added 2 commits November 15, 2026 06:40
…shorter than a bucket

The selector of a table with buckets of samples wrapped every read in
`WHERE notEmpty(samples)` over `timeSeriesSliceSortedArray(samples, a, b)`.
Filter push-down moves that condition into PREWHERE, which reads the raw
`samples`, computes the slice and drops the raw column, so the raw column
is PREWHERE-only. Since ClickHouse#122919 `MergeTreeBlockSizePredictor` counts such a
column at its part estimate on top of the measured slice copy: for a long
window (the slice is the whole array) bytes per row double, and with
granules under 512 KiB a block holds about one granule instead of two or
three. Whole-metric selectors then process about twice as many blocks
(`promql_selector_id_range_row_cost` #0/ClickHouse#1 1.3x slower with 262144-byte
granules, ClickHouse#131678).

The filter is a no-op unless the range is shorter than a bucket: every
sample of a row lies in [bucket, bucket + step), `min_time`/`max_time` are
the smallest/largest of them, and the inner query keeps a row only if
`max_time >= a AND min_time <= b`. If `min_time >= a` the sample at
`min_time` is in the range, if `max_time <= b` the sample at `max_time` is,
so an empty slice needs `min_time < a AND b < max_time`, i.e.
`b - a < max_time - min_time < step`. With a bound absent the same holds for
the other bound. So the filter is now emitted only when both bounds are set
and `b - a < step` in the units of the table being read (the samples table
or the recent samples table, each with its own step). The difference is
computed in Int128: the bounds of a DateTime64 table can be anywhere in
[INT64_MIN, INT64_MAX]. For long windows nothing on `samples` goes to
PREWHERE, the raw column is read by the main step and measured once, and
the slice is computed after it.

The bucket step at the table scale is moved into `getBucketStep`, shared
with `makeBucketedSamplesTimeRangeConditions`.

Measured (release build, master vs this change concurrently on identical
parts, 2 x 25 interleaved runs, max_threads = 4): row_cost #0 0.81/0.76 at
262144, 0.86/0.81 at 131072, 0.93/0.84 at 524288; ClickHouse#1 0.79/0.73,
0.88/0.83, 0.99/0.91; promql_selector_old_short_window 0.94-0.97. Results
identical.

Edge: a row written directly with `min_time`/`max_time` looser than its
samples (against the documented contract) can now be returned as an empty
array by `timeSeriesSelector(..., 'samples')` for a long range. PromQL drops
series whose merged array is empty, as it does for rows emptied by the
stale-marker filter.

Tests: 05770_time_series_selector_empty_slice_filter checks both sides of the
bucket boundary and the plan shape (no-parallel-replicas: without a local
plan the initiator's EXPLAIN does not show the replicas' filters). New perf
test promql_selector_small_granules: the row_cost shape at 131072-byte
granules, the default of the recent samples table.

Related: ClickHouse#131678
Related: ClickHouse#122919

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The "shorter than a bucket" case used [700.001, 1199.998], 499.997 s, so any
threshold above 499.997 s and up to 600 s passed the test. The bucket-600 row
now starts at its bucket (sample 600) and the range is [600.001, 1199.998],
599.997 s, still strictly between the row's two samples. A threshold of
599 s now fails the first and third lines. The reference is unchanged.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (rounds 1-2): 1 finding fixed, 1 nit kept, round 2 clean
Finding Verdict
⚠️ 05770: the "shorter than a bucket" case was 499.997 s, so a wrong threshold between 500 and 600 s would pass AGREE, fixed: the range is now 599.997 s, the widest range that can still give an empty slice, and a threshold of 599 s fails the test
💡 05770 line 2 (one bucket exactly) cannot fail under a threshold change Kept: it checks that the results are unchanged in the case whose filter is removed

Round 2 (the test fix): no findings.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master the selector's EXPLAIN always ends PREWHERE with notEmpty(CAST(timeSeriesSliceSortedArray(samples, ...))), and the row_cost whole-metric query at 262144-byte granules always gives FunctionExecute 33258 and 2836 blocks (CI arm: 33269). 05770_time_series_selector_empty_slice_filter fails on master on every run.
b Root cause explained? makeSelectQuery wrapped every bucketed read in WHERE notEmpty(samples) over the slice. It is pushed into PREWHERE, which makes the raw samples PREWHERE-only, and since #122919 the block-size predictor counts it on top of the slice copy. Bytes per row double and blocks halve in size for granules under 512 KiB.
c Fix matches root cause? Yes. The filter can drop a row only for a range shorter than a bucket (a row's samples lie in one bucket and min_time/max_time are exact), so it is emitted only then. Nothing is tuned: no setting, no block size, no predictor change.
d Test intent preserved / new tests added? New stateless test (599.997 s and 600 s ranges around a 600 s bucket, plus the plan shape) and a new perf test at 131072-byte granules. No existing test, reference or perf query changed.
e Both directions demonstrated? Test: master FAIL (last line 1), this PR OK. Mutations of the compare: an unscaled step and a 599 s threshold fail lines 1 and 3, <= fails line 4. Blocks at 262144: 2836 -> 1215; FunctionExecute 33258 -> 13600. Timing table in the description.
f Fix is general across code paths? Covers timestamp_and_value (HTTP API, arrayJoin) and samples (PromQL, remote read) modes, the samples and recent samples tables (each with its own step). Tables of earlier versions never had the filter. The step helper is shared with the existing bucket conditions.
g Fix generalizes across inputs (params/datatypes/wrappers)? Ranges below, at and above one step, one bound absent (no filter, covered by the same argument), bounds near the Int64 limits including a difference that overflows Int64 (the compare is in Int128). Timestamp scales use the same helper as the bucket condition.
h Backward compatible? (maintainer-approved exception only) Yes: only the generated internal query changes; no setting, format or stored definition.
i Invariants and contracts preserved? Result rows are identical (12 benchmark queries compared, TimeSeries/PromQL stateless tests green); column types unchanged. The only edge is a directly written row whose min_time/max_time break the documented contract, stated in the description.

Session id: cron:clickhouse-impl-slot-5:20261115-053300

@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a7efc57]

Summary: ✅


AI Review

Summary

Reviewed PR head a7efc571a54b61e25525b48ffc6d4bf12ead5926, the full diff, surrounding code, and all prior discussion. The change removes redundant empty-slice filtering for TimeSeries ranges spanning at least one bucket and computes the scaled bucket step once. No actionable findings. The focused regression covers the threshold and generated plan; the prior revision passed 50 targeted ASan/UBSan runs, and the description supplies before/after performance measurements. No tests were run locally.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog can be tested Allows running workflows for external contributors comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... labels Nov 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a7efc571a with master b8fc8d44b (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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 38144e9

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 4/6) infra, not from this PR: killed at the 7200 s job timeout, because the coverage-based test selection picked a coverage run that collected no test (cohort 79929b2c), so every test of the shard ran in full (--max-queries 0 on all 142 tests; this PR's new perf test is not in this shard). Performance Comparison shards timed out the same way on 26 other PRs since 05:00Z #131772 (mine, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log the upgraded server retried Code: 47 ... Unknown expression identifier b on part all_1_1_1_2, the empty DETACH PART part of 04653: the stress phase runs the previous release's tests (v26.10.4.207-stable), whose 04653 does not have the fix yet; 22 other PRs in 10 days #125293 (external, merged)
Mergeable Check, PR praktika rollups of the rows above #131772 (mine, open), #125293 (external, merged)

CIDB has no other FAIL or ERROR row on this head (the Config Workflow / Pre Hooks rows are the run before the can be tested label).

Session id: cron:our-pr-ci-monitor:20261115-113011

@vitlibar vitlibar self-assigned this Nov 15, 2026
readImpl now converts the bucket step of the table being read to a
Decimal64 at the scale of its timestamp type once, and passes it down
instead of the step in seconds; getBucketStep is removed. Every use is
either a zero check or wants the value at the table's timestamp scale.
Decimal64 matches TimeSeriesSink, which stores the steps the same way.
The product fits in Int64: check_bucket_step caps the step at
UInt32::max seconds and the scale of DateTime64 is at most 9.

No behaviour change: 05770 passes, and fails under four mutations
(an unscaled step and a 599 s threshold in the compare, `<=` instead
of `<`, and an unscaled step at the conversion in readImpl).

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

clickhouse-gh Bot commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master b8fc8d44b

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

@vitlibar
vitlibar added this pull request to the merge queue Nov 15, 2026
Merged via the queue into ClickHouse:master with commit e11b4f4 Nov 15, 2026
192 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 15, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 16, 2026
CI builds the merge commit with master, which now contains ClickHouse#131766, so the
performance comparisons measure this PR's defaults with the selector fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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... 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.

3 participants