Repository navigation
Description
What type of bug is this?
Performance issue
What subsystems and features are affected?
Continuous aggregate
What happened?
When a real-time continuous aggregate (timescaledb.materialized_only = false) is three or more levels deep in a hierarchy (a cagg on a cagg on a cagg), refreshing it β or selecting from its internal partial view β re-aggregates the entire un-materialized tail of the base hypertable, regardless of the refresh/query window. A two-level cagg over the same data does not. All bucket widths involved are fixed-width (10 minutes β 1 day β 7 days), so this is not the (separate) calendar-month/variable-width limitation.
Setup
raw hypertable β cagg_10m (10 min) β cagg_1d (1 day) β cagg_7d (7 day), all real-time, all refreshed up to now() - 15 days (so each has a ~15-day un-materialized tail, exactly as a refresh policy with an end_offset would leave).
Observed
Forcing a refresh of a historical window (4β5 months in the past, far below every watermark), same window for both:
| Refreshed cagg | Levels above raw | Time |
|---|---|---|
cagg_1d |
2 | 10 ms |
cagg_7d |
3 | 445 ms (β45Γ slower) |
(On a larger dataset β 1000 rows/hour for 6 months β the 3-level refresh of the same historical month takes ~7.4 s vs ~0.12 s for the 2-level, β62Γ. The cost scales with the size of the un-materialized tail, not with the refresh window.)
The refresh executes (captured via pg_stat_statements with track = all):
INSERT INTO _timescaledb_internal._materialized_hypertable_<N>
SELECT * FROM _timescaledb_internal._partial_view_<N> AS I
WHERE I.<time_col> >= $1 AND I.<time_col> < $2;
so EXPLAIN-ing that inner SELECT reproduces the refresh's scan exactly.
Root cause (what the plans show)
The real-time cagg view is materialized_part UNION ALL realtime_part, where realtime_part recomputes everything >= cagg_watermark from the source. For a window below the watermark, the planner should be able to prove realtime_part is empty and prune it. It can β but only up to two nested time_bucket() levels.
-
2-level (
cagg_1d, GOOD): the real-time branch collapses toResult -> One-Time Filter: false; only the materialized hypertable is touched. The derivation turns the query'stime_bucket('1 day', time_bucket('10min', ts)) < <window_end>into a bound on the raw columnts, which contradicts the watermark lower boundts >= <watermark>β branch eliminated. -
3-level (
cagg_7d, BAD): the real-time branch is not pruned. It runs aGather β Parallel Append β Parallel Seq Scanover every chunk of the base hypertable newer than the watermark (the whole tail), aggregates 10minβ1dayβ7day, and discards 100% of the rows. The filter on a raw chunk looks like (note: the only bound that reaches the raw columntsis the watermark lower bound; every upper bound stays trapped on a triple-nestedtime_bucketexpression, so the hypertable gets no upper time bound and no chunk is excluded):Filter: (ts >= '<watermark>') -- lower bound only AND (time_bucket('10 min', ts) >= '<watermark>') AND (time_bucket('1 day', time_bucket('10 min', ts)) >= '<window_start>') AND (time_bucket('1 day', time_bucket('10 min', ts)) < '<window_end + 7d slack>') -- derived at 2-nested level... AND (time_bucket('7 days', time_bucket('1 day', time_bucket('10 min', ts))) >= '<window_start>') AND (time_bucket('7 days', time_bucket('1 day', time_bucket('10 min', ts))) < '<window_end>') Rows Removed by Filter: <all rows in every tail chunk>The planner inverts the outermost
time_bucket(producing the 2-nested< window_end + slackbound) but stops there; it never reduces the constraint to a bound ontsitself. With a third nesting layer the watermark contradiction can no longer be derived, so the branch is neither pruned nor chunk-excluded.
Where this seems to come from in the code
I tried to trace this back to the source, and, with the caveat that I may be missing context, the transform responsible looks like ts_transform_time_bucket_comparison() in src/planner/expand_hypertable.c (with its helper extract_time_bucket_qual()). As far as I can tell it does exactly one level of unwrapping: it takes the bucket's time argument (lsecond(time_bucket->args)) and rebuilds the comparison directly against it, e.g.
time_bucket(W, <arg>) < c --> <arg> < c + W
It doesn't seem to check whether <arg> is itself another time_bucket(...) call, and the result isn't fed back through the transform β so a single application only ever strips one level. The function is called once per qual at each of its call sites (process_quals, timebucket_annotate, get_simplified_restrictions, and ts_constify_restrictinfos in the chunk-append executor), and none of them re-apply it to their own output.
What seems to explains the exact 2-vs-3 threshold is that the transform ends up running at two separate points during planning, so its effective reach is two nesting levels:
- during qual collection,
process_qualsstrips one level and writes the result back into the qual list β that's the derived bound that shows up in the chunkFilter(the 2-nested< window_end + slackline above); then - during chunk exclusion,
get_simplified_restrictionsruns over those same restrictions and strips one more level to feed the hypertable's range exclusion (this second one isn't added to theFilter, so it's invisible in the plan).
So at 2 levels the two strips compose all the way down to a real bound on the raw column (ts < window_end + 1d + 10min), which contradicts ts >= watermark and lets the branch fold / chunks be excluded. At 3 levels the very same two strips only get from the triple-nested expression down to time_bucket('10 min', ts) < β¦ β one level short of ts β so no upper bound on ts is ever produced, and nothing can be pruned.
Expected
Refreshing / querying a window entirely below the watermark should prune the real-time branch (One-Time Filter: false) at any hierarchy depth, just as it does at two levels β i.e. the time_bucket β raw column constraint derivation should compose through arbitrarily nested time_bucket() calls. The 3-level refresh should be in the same ballpark as the 2-level one, not ~45β62Γ slower, and should not seq-scan the base hypertable.
A possible direction for a fix
I think the smallest change that seems to fit the existing design would be to let ts_transform_time_bucket_comparison() recurse: after it produces <arg> OP newvalue, if <arg> is itself a time_bucket() call, apply the same transform again β composing the width adjustments at each level (e.g. ts < window_end + 7d + 1d + 10min) β until the argument is no longer a bucket. The existing single-level call sites would then compose down to the raw column on their own, and the One-Time Filter: false / chunk-exclusion machinery that already works at two levels should kick in at any depth. Each step strips exactly one wrapper, so it should terminate naturally.
If this direction sounds reasonable, I'd be glad to put together a PR and to adjust the approach based on your feedback. And if I've misunderstood how the transform is meant to work or if this a known issue/duplicate, I'd really appreciate a pointer. Thanks for taking a look!
TimescaleDB version affected
2.28.0
PostgreSQL version used
18.4
What operating system did you use?
Alpine Linux (musl), aarch64 β official timescale Docker image; host macOS 15 (Apple Silicon)
What installation method did you use?
Docker
What platform did you run on?
On prem/Self-hosted
Relevant log output and stack trace
-- GOOD: 2-level cagg_1d, real-time branch pruned
GroupAggregate (actual rows=31 loops=1)
Buffers: shared hit=82
-> ... Append over _materialized_hypertable_<10m> January chunks (4464 rows) -- materialized side
-> HashAggregate (actual rows=0)
-> Result
One-Time Filter: false <-- real-time branch eliminated
Execution Time: ~4 ms
-- BAD: 3-level cagg_7d, real-time branch NOT pruned (same window)
GroupAggregate (actual rows=4 loops=1)
Buffers: shared hit=2759
-> Append
-> Append over _materialized_hypertable_<1d> January chunks (28 rows) -- materialized side (fine)
-> GroupAggregate (actual rows=0)
-> Finalize HashAggregate
-> Gather (Workers Planned: 5)
-> Parallel Append
-> Parallel Seq Scan on _hyper_<raw>_<chunk> <-- EVERY base chunk >= watermark
Filter: (ts >= '<watermark>' AND time_bucket(...nested...) ...)
Rows Removed by Filter: <entire chunk>
-> ... (one per tail chunk) ...
Execution Time: ~7.4 s on the 1000-rows/hour datasetHow can we reproduce the bug?
-- TimescaleDB 2.28.0 / PostgreSQL 18.4. Times are relative; refresh windows use now()
-- so the script is runnable at any time.
CREATE TABLE conditions (ts timestamptz NOT NULL, value double precision NOT NULL);
SELECT create_hypertable('conditions', by_range('ts', INTERVAL '1 day'));
-- ~6 months of data at 1-minute resolution (increase resolution/volume to amplify the effect)
INSERT INTO conditions
SELECT g, random() * 100
FROM generate_series(date_trunc('hour', now()) - INTERVAL '6 months',
date_trunc('hour', now()) - INTERVAL '1 minute',
INTERVAL '1 minute') AS g;
-- Level 1: 10-minute on the raw hypertable
CREATE MATERIALIZED VIEW cagg_10m
WITH (timescaledb.continuous, timescaledb.materialized_only = false) AS
SELECT time_bucket('10 minutes', ts) AS ts, count(*) AS cnt, sum(value) AS sum_value
FROM conditions GROUP BY 1 WITH NO DATA;
-- Level 2: 1-day on cagg_10m (2 levels -> real-time branch is pruned correctly)
CREATE MATERIALIZED VIEW cagg_1d
WITH (timescaledb.continuous, timescaledb.materialized_only = false) AS
SELECT time_bucket('1 day', ts) AS ts, sum(cnt) AS cnt, sum(sum_value) AS sum_value
FROM cagg_10m GROUP BY 1 WITH NO DATA;
-- Level 3: 7-day on cagg_1d (3 levels, ALL FIXED-WIDTH -> real-time branch NOT pruned = bug)
CREATE MATERIALIZED VIEW cagg_7d
WITH (timescaledb.continuous, timescaledb.materialized_only = false) AS
SELECT time_bucket('7 days', ts) AS ts, sum(cnt) AS cnt, sum(sum_value) AS sum_value
FROM cagg_1d GROUP BY 1 WITH NO DATA;
-- Materialize everything except the last 15 days -> leaves an un-materialized tail
CALL refresh_continuous_aggregate('cagg_10m', NULL, date_trunc('hour', now()) - INTERVAL '15 days');
CALL refresh_continuous_aggregate('cagg_1d', NULL, date_trunc('hour', now()) - INTERVAL '15 days');
CALL refresh_continuous_aggregate('cagg_7d', NULL, date_trunc('hour', now()) - INTERVAL '15 days');
-- Refresh a HISTORICAL window (4-5 months ago, far below the watermark), same window for both.
CALL refresh_continuous_aggregate('cagg_1d', date_trunc('hour', now()) - INTERVAL '5 months',
date_trunc('hour', now()) - INTERVAL '4 months', force => true); -- fast (~10 ms)
CALL refresh_continuous_aggregate('cagg_7d', date_trunc('hour', now()) - INTERVAL '5 months',
date_trunc('hour', now()) - INTERVAL '4 months', force => true); -- ~45x slower
-- Inspect the inner query the refresh runs (use a bucket-ALIGNED historical window, as
-- refresh_continuous_aggregate does internally). Replace <id> with cagg_7d 's mat_hypertable_id:
SELECT user_view_name, mat_hypertable_id, partial_view_name
FROM _timescaledb_catalog.continuous_agg WHERE user_view_name LIKE 'cagg_%';
-- 2-level (cagg_1d): folds to "One-Time Filter: false", touches only the materialized hypertable
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM _timescaledb_internal._partial_view_<cagg_1d_id>
WHERE ts >= date_trunc('month', now() - INTERVAL '5 months')
AND ts < date_trunc('month', now() - INTERVAL '4 months');
-- 3-level (cagg_7d): Parallel Seq Scans EVERY base-hypertable chunk newer than the watermark
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM _timescaledb_internal._partial_view_<cagg_7d_id>
WHERE ts >= date_trunc('month', now() - INTERVAL '5 months')
AND ts < date_trunc('month', now() - INTERVAL '4 months');
Activity
Prune real-time branch of deep hierarchical caggs
Reproducer test
Prune real-time branch of deep hierarchical caggs
Reproducer test
Prune real-time branch of deep hierarchical caggs
melihmutlu commentedon Jun 30, 2026
Thanks @viniciusrsouza for reporting the issue. I'm able to reproduce the issue and verify that it's a bug. As you pointed out, time_bucket() transformation does not work properly for nested time_bucket()'s. We're working on a fix.
Prune real-time branch of deep hierarchical caggs
Reproducer test
Prune real-time branch of deep hierarchical caggs
Reproducer test
Prune real-time branch of deep hierarchical caggs
Prune real-time branch of deep hierarchical caggs
Prune real-time branch of deep hierarchical caggs
Prune real-time branch of deep hierarchical caggs (#10175)
Prune real-time branch of deep hierarchical caggs (#10175)
Release 2.29.0
Release 2.29.0
Release 2.29.0