[Enhancement]: Preserve sparse locality in CAGG invalidations using natural partition boundaries
What type of enhancement is this?
Performance, Refactor
What subsystems and features will be improved?
Data ingestion, Continuous aggregate, Partitioning, Query planner, Policy
What does the enhancement do?
I would like to propose preserving sparse write locality further through the continuous-aggregate invalidation pipeline, so that sparse historical backfill/corrections remain sparse instead of being widened into substantially larger regions than were actually touched.
This is related to, but distinct from, granular refresh by GROUP BY / tenant key.
The specific problem here is broader:
A write path can know where changes landed in time, physical partitioning, and sometimes grouping dimensions, but if that locality is collapsed too early into a coarse invalidation range, later refresh planning cannot recover it.
The core idea is:
Preserve invalidation locality down to the finest natural boundary that refresh can actually exploit, and coarsen deterministically only when a bounded bookkeeping budget requires it.
This is deliberately different from picking an arbitrary representation such as "64 buckets" or "128 buckets". Timescale already has several natural boundaries that can guide both precision and fallback:
- physical chunk / hypercube boundaries;
- secondary-dimension partition boundaries;
- CAGG time-bucket boundaries;
- granular-refresh / group-by boundaries;
- refresh policy windows;
- memory/work limits already used by invalidation processing.
The desired behavior is simple:
- sparse writes remain sparse;
- dense writes naturally coalesce;
- bookkeeping remains bounded;
- coarsening follows real storage/refresh boundaries rather than jumping directly to one broad
[min,max]; - the representation and fallback behavior are deterministic and inspectable enough to guide refresh planning.
Why this matters for sparse backfill
Consider a transaction that corrects only a few old rows.
If those rows are widely separated in time but happen to share one transaction-side invalidation region, a broad [min,max] can make all intermediate buckets appear dirty even though they were never touched.
Later refresh processing can:
- align invalidations to CAGG bucket boundaries;
- merge overlapping/adjacent ranges;
- split/cut ranges at refresh-window boundaries;
- process recent and historical windows separately.
But none of those operations can reconstruct temporal sparsity that was discarded earlier.
This is exactly the kind of workload that appears repeatedly in historical CAGG reports: sparse historical corrections or devices delivering old data.
Important current behavior: the trigger-side path already has a natural per-chunk boundary
While looking at current source, one detail stood out.
In TimescaleDB 2.30.1, the trigger-side invalidation cache in
tsl/src/continuous_aggs/insert.c
is keyed by chunk_relid.
ContinuousAggsCacheInvalEntry stores, among other things:
chunk_relid;- hypertable id;
- open/time dimension metadata;
lowest_modified_value;greatest_modified_value.
continuous_agg_dml_invalidate() updates this per changed row, and the transaction callback later writes the accumulated invalidations.
That means current code is already more local than "one min/max for the entire hypertable transaction":
if one transaction touches different physical chunks, those chunks naturally get separate transaction-side cache entries.
This is a very useful existing boundary.
The remaining temporal loss is inside one touched chunk entry, where multiple sparse timestamps are still represented by one min/max.
When the ordinary invalidation is persisted, the standard log representation is essentially:
hypertable_id, lowest_modified_value, greatest_modified_value, seqnum
The trigger path knew the physical chunk_relid, but that physical identity is not part of the ordinary persisted range representation.
This suggests that a useful next step does not have to start from arbitrary global bucketing. It can start from a boundary that the current implementation already uses.
Example 1: sparse corrections inside one chunk
Assume:
- raw hypertable chunk interval: 7 days;
- CAGG bucket: 1 hour;
- one transaction corrects only two rows in the same physical chunk.
| Mutation | Timestamp |
|---|---|
| A | Monday 00:10 |
| B | Sunday 23:50 |
A min/max representation for that touched chunk becomes approximately:
[Monday 00:10, Sunday 23:50]
After CAGG bucket alignment, almost the whole week can become refresh work even though only two hourly buckets contain modified data.
If A and B had landed in different physical chunks, the current per-chunk_relid transaction cache already gives a better outcome.
So the natural opportunity is:
retain a bounded sparse representation within each already-existing per-chunk invalidation entry.
That could be a multirange, interval set, bitmap over meaningful subregions, or another compact structure. The exact data structure matters less than preserving sparsity until there is a principled reason to coarsen.
Example 2: secondary dimensions provide another natural boundary
A hypertable with a secondary/space dimension creates physical chunks/hypercubes representing the intersection of time and that secondary dimension.
The write path already knows which physical chunk/hypercube received the row.
That gives an additional real boundary for invalidation locality:
- time region;
- secondary-dimension partition;
- physical chunk/hypercube.
If a sparse historical correction touches only one space partition, downstream refresh planning should ideally retain enough information to avoid treating unrelated partitions as equally dirty where the query/CAGG shape can exploit that distinction.
This is related in spirit to the still-open #6148 — Continuous Aggregates: support for secondary dimension.
I am not suggesting #6148 and this proposal are the same feature. The point is that secondary partition boundaries are existing deterministic structure. They are a better fallback/coarsening boundary than an arbitrary synthetic slot count.
Example 3: granular refresh adds another orthogonal locality axis
#8132 — granular invalidation tracking for continuous aggregate refresh describes a closely related sparse-backfill problem: a small percentage of devices send old data, but the CAGG can end up refreshing a much larger time region for every device.
A maintainer described this as a "relatively frequent problem and especially common with users that backfill data" and explained that the WAL invalidation work in #8193 was intended as a foundation for tracking distinct GROUP BY values.
That work has since moved substantially forward:
- #8193 — Use logical decoding plugin for hypertable invalidations introduced a WAL/logical-decoding path to reduce the I/O footprint of invalidation tracking and explicitly left range combination as subsequent CPU work.
- #8360 — Continuous aggregate multi-hypertable invalidation processing introduced multi-range collection and bounded-memory flushing based on work-memory limits.
- #10427 — Granular refresh for continuous aggregates implemented granular refresh support.
- #10544 — Split invalidations along the tracking (late) window added further boundary-aware splitting for granular tracking.
Those changes demonstrate two principles that seem directly useful here:
- richer invalidation state than a single simple range is feasible;
- richer state can be bounded deterministically when memory/resource limits are approached.
Granular refresh solves the question:
Which group/tenant values actually need refreshing?
This proposal adds the complementary questions:
Which time regions and physical partitions actually need refreshing?
The dimensions should compose rather than compete.
Example 4: combine time, physical partition, and granular key
Assume:
- 7-day time chunks;
- a secondary hash/space dimension;
- hourly CAGG buckets;
- granular refresh on
device_id.
A transaction changes:
| Row | Time | Space partition | Device |
|---|---|---|---|
| A | Mon 00:10 | P3 | D17 |
| B | Mon 00:40 | P3 | D17 |
| C | Thu 15:05 | P3 | D17 |
| D | Sat 09:10 | P7 | D88 |
The useful refresh information is not simply:
Monday 00:10 .. Saturday 09:10
There are already meaningful boundaries available:
- A+B are in the same hourly CAGG bucket;
- C is another isolated hourly bucket;
- D is in another physical space partition/hypercube;
- D17 and D88 are distinct granular keys.
A locality-preserving invalidation representation could allow refresh planning to target approximately:
- P3 / D17 / Monday 00:00 hour;
- P3 / D17 / Thursday 15:00 hour;
- P7 / D88 / Saturday 09:00 hour.
The underlying timestamp and grouping indexes then have a much better chance of making those narrow recomputations genuinely cheap.
Chronology: how the invalidation problem has evolved
I think the history is important because this proposal is not asking to undo previous optimizations. It is trying to take advantage of the newer architecture to improve the trade-off.
2021: too many tiny invalidations
#2867 — TimescaleDB 2.x Continuous Aggregation long recalculation reported pathological refresh behavior from large numbers of tiny historical invalidations.
The resulting #2926 — Optimize cagg refresh for small invalidations made two important changes:
- expand invalidations to complete CAGG bucket boundaries so multiple changes in the same bucket can merge;
- historically, when too many non-mergeable ranges remained, collapse them into a broad range from the lowest to greatest invalidated timestamp.
That was a reasonable response to the cost of executing too many tiny materializations.
The current 2.30.1 implementation appears to have evolved beyond that old fixed >10 ranges => one min/max threshold behavior, so this proposal is not based on a claim that the old threshold still exists.
The historical lesson remains useful, though:
- keeping every microscopic invalidation can be expensive;
- collapsing too aggressively can make sparse backfill disproportionately expensive.
2023: secondary-dimension limitations made partition locality explicit
#6148 raised support for secondary dimensions in continuous aggregates.
That issue is broader than invalidation tracking, but it highlights an important fact: hypertables can have meaningful physical partition structure beyond time, and CAGG refresh can benefit from retaining enough locality to exploit it.
2025: sparse backfill became an explicit granular-refresh use case
#8132 described sparse old data from a small subset of devices invalidating months of aggregate history.
That discussion explicitly identified backfill as a frequent problem and proposed tracking distinct grouping values so refresh could avoid recomputing unrelated tenants/devices.
2025: WAL and multirange infrastructure changed the cost model
#8193 moved invalidation collection toward logical decoding/WAL to reduce write amplification from the trigger/invalidation-log-table model.
#8360 then added multi-range invalidation processing with a bounded-memory flush mechanism.
This seems especially relevant because the original reason to prefer extremely simple min/max bookkeeping is weaker once the invalidation engine already has machinery for:
- multiple ranges;
- range combination;
- work-memory accounting;
- bounded flushing.
2026: granular refresh added richer dimensional state
#10427 and #10544 added granular refresh and boundary-aware invalidation splitting.
Current source now has explicit per-tenant/group tracking, sequence numbers, late-arrival windows, and deterministic splitting across those windows.
That is a substantial evolution from the original simple invalidation model.
It seems like a good point to revisit whether temporal and physical-partition sparsity can also be retained for longer.
Proposed model: bounded locality with deterministic coarsening
I do not think the answer should be unbounded row-level invalidation tracking.
The proposal is to maintain a bounded sparse representation and use the system's existing hierarchy as the fallback path.
The key idea is:
When detail becomes too expensive, promote it to the nearest useful parent boundary.
That is different from asking an arbitrary heuristic:
Which 17 of these 100 little ranges should be merged together?
Instead, the system can make deterministic decisions using known structure.
Possible conceptual hierarchy:
- granular/group key + narrow time region;
- CAGG-relevant time bucket(s);
- secondary partition / physical hypercube;
- physical chunk;
- broader contiguous time range;
- current coarse fallback.
The exact order does not have to be this one. It may differ between trigger and WAL invalidation paths and between CAGG definitions.
What matters is that coarsening has defined parents and defined stopping signals.
Natural stopping signals instead of arbitrary bit counts
An earlier way to think about this would be "keep a 64-bit or 128-bit dirty bitmap per transaction/chunk".
That can work, but I think the stronger abstraction is to let existing structure tell us how deep useful precision goes.
Temporal precision
For pure time-axis invalidation, once precision is finer than the smallest refresh region a dependent CAGG can exploit, additional temporal detail stops buying much.
For example, if a CAGG materializes hourly buckets, two writes 5 minutes apart in the same hour ultimately require the same hourly bucket to be recomputed.
There is an implementation complication: one hypertable can feed multiple CAGGs with different bucket widths, origins and bucket functions.
So I am not proposing that the DML path should simply adopt one CAGG's bucket width.
A more general representation could retain sparse ranges independent of any one CAGG, then expand them to each dependent CAGG's bucket boundaries later.
The important point is that the dependent CAGGs provide real information about when extra temporal precision has no downstream value.
Physical precision
The existing chunk_relid is already a deterministic physical boundary in the trigger path.
With a second partitioning dimension, the physical chunk/hypercube is an even stronger boundary.
Granular/group precision
Where granular refresh is enabled, the tracked GROUP BY value is another natural boundary.
Deterministic bookkeeping can guide the optimizer / refresh planner
This is one of the parts I find most attractive about the approach.
If the invalidation engine retains a small amount of structured bookkeeping about how precise an invalidation still is, the refresh planner does not have to guess.
For example, an invalidation could carry enough metadata to know that it represents:
- exact sparse intervals inside one chunk;
- a whole CAGG bucket;
- a whole secondary partition;
- a whole physical chunk;
- a whole tenant/group within a time range;
- or an intentionally coarsened fallback region.
That gives the planner a deterministic statement of what is known and what has deliberately been discarded.
A bounded implementation could make promotion decisions using stable rules such as:
- number of retained ranges;
- bytes of invalidation state;
- number of distinct group keys;
- number of physical partitions/chunks;
- expected number of CAGG buckets affected;
- configured work-memory budget;
- whether a lower-level region can actually be pruned by the downstream CAGG/query.
If two candidate sibling regions must be coarsened, the system can promote them to their known parent rather than use an opaque distance heuristic.
With deterministic tie-breaking, the same write pattern and configuration should produce the same invalidation representation.
That makes the behavior:
- testable;
- explainable;
- inspectable;
- suitable as an input to cost-based refresh planning.
In other words, the bookkeeping is not merely overhead — it becomes information that the refresh optimizer can use.
Dense writes should collapse naturally
This proposal should not penalize genuinely dense backfills.
Suppose a transaction touches almost every hourly region in a 7-day chunk.
A sparse representation would quickly discover that retaining individual regions buys little. It can deterministically promote them to the chunk-level parent.
At that point the result approaches current behavior.
So the intended asymmetry is useful:
- a transaction touching 3 isolated regions should retain roughly 3 regions;
- a transaction touching 160 of 168 hourly regions should collapse to something close to the whole chunk.
This makes cost roughly proportional to actual sparsity.
Bounded fallback
A possible implementation principle would be:
Never allow invalidation detail to exceed a configured or existing work-memory/bookkeeping budget.
When the budget is approached:
- first coalesce exact overlaps/adjacency as today;
- promote sibling fine regions to a known parent when that reduces state enough;
- prefer parent boundaries that the refresh planner can prune/use efficiently;
- if the transaction is genuinely dense, collapse to chunk/partition or broad time-range state;
- finally fall back to the current coarse representation if necessary.
#8360 is an encouraging precedent here: invalidation range collection is already bounded by memory and can flush when approaching maintenance_work_mem.
A locality-aware implementation could use a similar resource-budget concept.
Persisted representation
I do not think the proposal requires one particular on-disk layout.
Options could include:
- several ordinary invalidation rows;
- PostgreSQL multirange values;
- compact bitmap-like state where boundaries are naturally aligned;
- a small relation keyed by chunk/partition/group;
- compressed/columnar representation if enough invalidation state is ever persisted to justify it.
The hot DML path should remain cheap. The most important change is avoiding premature information loss.
The WAL path may make richer collection especially attractive because #8193 was explicitly designed to avoid the old extra per-DML table-write cost.
Refresh-window cutting still works
The current refresh logic in
tsl/src/continuous_aggs/invalidation.c
already has sensible behavior for cutting invalidations at refresh-window boundaries.
If a pending range crosses a policy window, the inside region is processed and the outside piece(s) remain in the log.
That should continue to work.
The problem addressed here is earlier:
a refresh window can only cut the invalidation geometry it was given
Implementation challenges
No response
Source: timescale/timescaledb