Skip to content

fix(jobs): bound price_aggregates with a retention prune (#691) - #810

Open
Neziahtech wants to merge 2 commits into
Divinity-Labs:mainfrom
Neziahtech:fix/price-aggregates-retention-691
Open

Neziahtech wants to merge 2 commits into
Divinity-Labs:mainfrom
Neziahtech:fix/price-aggregates-retention-691

Conversation

@Neziahtech

Copy link
Copy Markdown
Contributor

Closes #691

The problem

price_aggregates had no retention at all. src/jobs/aggregateRefresh.ts upserts one row per window (1m, 5m, 1h, 24h) for every watched pair on every network, every minute, and each of those upserts lands on a bucket that is the current minute — so a minute that passes creates four brand-new primary keys and deletes nothing. That is 172,800 rows per pair per network per month, on every network, forever. Nothing pruned them and no job claimed to.

Two things made this awkward rather than mechanical:

  • GET /price/:assetA/:assetB/history (src/api/rest.ts:327) has no time predicate whatsoever. It answers ORDER BY bucket DESC LIMIT n for one (network, pair_key, window) series, n capped at HISTORY_MAX_LIMIT (1000). So the route's answer for a series is simply "that series' newest n rows" — including for a pair whose ingestion broke months ago, whose every row is therefore old.
  • rollupOldPricePoints (src/jobs/pricePointsRetention.ts) compresses raw price_points older than 30 days into hour-aligned 1h rows in this same table, with ON CONFLICT (network, pair_key, window, bucket) DO UPDATE. Once the raw points are gone, those rows are the only copy of history older than 30 days. A job that trims this table has to know not to eat them.

The retention policy (written, as the issue asks)

A row is deleted only when all four hold:

  1. It is older than the series' keep floor — the bucket of the PRICE_AGGREGATES_KEEP_ROWS-th (default 1000) newest row of that same (network, pair_key, window) series. This is the bound that makes the prune invisible to readers: no page the history route can ask for gets shorter or changes, even for a pair that stopped being refreshed long ago. A series with fewer rows than the keep count is not touched at all. KEEP defaults to HISTORY_MAX_LIMIT and a test asserts the two stay equal, so raising the route's cap without raising the default fails a test instead of silently truncating someone's chart.
  2. It is older than PRICE_AGGREGATES_RETENTION_DAYS (default 30, the horizon every other retention job here publishes), so a caller naming a recent range — GraphQL priceHistory with from/to, the screener's newest 24h row — is untouched whatever the row counts do. What the horizon does cost is granularity in the past: a range older than 30 days is answered by the hourly rollups instead of per-minute rows, which is the point of keeping them.
  3. It is not an hour-aligned 1h row. The shape window = '1h' AND bucket = date_trunc('hour', bucket) is exempt whatever its age, because that row is the long-term record. In the live table this is exactly the rollup set, not extra: the refresher's top-of-hour 1h row and the rollup's row for that hour share the same primary key, so the hourly history is one row per hour kept forever (24/pair/day against the 5,760/pair/day of minute rows above it). An hour-aligned 1m/5m/24h bucket is a rolling row and is pruned when it ages out.
  4. It is not locked. Batches use FOR UPDATE SKIP LOCKED, LIMIT PRICE_AGGREGATES_PRUNE_BATCH_SIZE (1000), and yield between batches, so a concurrent refresher is never made to wait and each batch's lock footprint stays inside one series.

The policy is documented in docs/RUNBOOK.md (new §1a "Data retention policy", plus the worker table, the startup order and the /metrics signals) and in docs/database-schema.md (a "Retention policy" section with the growth math and the schema facts the job is written against). The three settings are in .env.example with the same "what the prune never touches" list.

What I added

  • src/jobs/priceAggregatesRetention.ts — listAggregateSeries, readSeriesKeepFloor, pruneAggregateSeries, pruneOldAggregates, pruneAllAggregateNetworks, and the BullMQ queue/worker/schedule trio, following snapshotRetention.ts and lendingRateRetention.ts rather than inventing a shape. Range guards reject a bad batch size, keep count or horizon before any query runs.
  • src/metrics.ts — price_aggregates_pruned_total{network}, labelled by network only (bounded, like every other series here).
  • src/index.ts — started the same way the other retention jobs are: prune once at boot, then schedule hourly on BullMQ; if Redis is down the schedule fails over to an hourly in-process setInterval and the boot log says so. A failing prune is logged and retried on the next tick — startup never exits over it.
  • src/__tests__/priceAggregatesRetention.test.ts — 27 tests.

How the done-when is proved

The issue's real requirement is a promise about answers, not row counts, so the last group of tests models the delete rule against a table that has been growing for months (two pairs × four windows × 1000 recent minute rows + a 500-row tail past the horizon + three days of hour-aligned rollups):

  • deletes the old tail of every series and nothing else — exactly the tail went, and in every series all rows at or after the keep floor survived.
  • answers every request the history route can make exactly as before — for both pairs, all four windows and limit ∈ {1, 2, 100, 1000, KEEP}, the route's response is byte-identical before and after the prune.
  • keeps the hour rollups of a series whose old minute rows all go — every rollup is hour-aligned, every rollup is older than the horizon (so it sat inside the delete's own range and survived only because of the exemption), and none of the deleted rows was a rollup.
  • leaves a sparse series untouched however old it is — a 20-row series, all of it a year old, is not touched, because all of it is inside the newest page a caller could ask for.

Plus the SQL itself asserted directly: the delete is scoped network → pair_key → window, bounded by both the floor (bucket < $4) and the horizon, carries the NOT (window = '1h' AND bucket = date_trunc('hour', bucket)) exemption, uses FOR UPDATE SKIP LOCKED, and takes LIMIT $6. And the Redis-down path: runs hourly and once on startup, per-network AggregateError that still prunes the other network, and defaults checked against HISTORY_MAX_LIMIT.

No floating-point price maths is involved — the job only counts rows and compares buckets. Existing tests were not weakened. No route, no Prisma schema and no GraphQL surface changed, so openapi.yaml, schema.graphql, the generated client and docs/what-lens-knows.md are untouched.

Local verification

npx tsc --noEmit clean. npx vitest run src/__tests__/priceAggregatesRetention.test.ts src/__tests__/envDrift.test.ts src/__tests__/snapshotRetention.test.ts src/__tests__/pricePointsRetention.test.ts src/__tests__/lendingRateRetention.test.ts → 57 passed.

What I did not do

  • No migration. The job deletes through the existing primary key; price_aggregates is not partitioned and partitioning it is a separate decision (and price_points already has its own partition job).
  • I left pool_snapshots alone even though it grows the same way — that is pool_snapshots gets a new row on every poll and nothing ever deletes one #689's table, and there is an open PR for it.
  • The prune keeps the newest 1000 rows per series, so a watched pair costs 4,000 rows minimum regardless of age. That is deliberate (it is what buys the invisible-prune guarantee) and it is why the series floor, not the age horizon, is the interesting half of the policy.

…icy (Divinity-Labs#691)

The refresher upserts one row per window (1m, 5m, 1h, 24h) per pair per network
every minute, so four new primary keys appeared every minute and nothing removed
them -- 172,800 rows per pair per month, forever.

pruneOldAggregates deletes per (network, pair_key, window) series in bounded
FOR UPDATE SKIP LOCKED batches, and only rows that are both past the retention
horizon and older than the series' newest-keepRows floor. The floor is what
makes the prune invisible: GET /price/:assetA/:assetB/history has no time
predicate, so its answer is the newest n rows of a series, n capped at
HISTORY_MAX_LIMIT. Hour-aligned 1h rows -- the rollups raw price_points are
compressed into, the only copy of history past 30 days -- are exempt by shape.

Policy is written up in docs/RUNBOOK.md 1a and docs/database-schema.md; settings
in .env.example; started from src/index.ts with the same hourly in-process
fallback the other retention jobs use when Redis is away.
@drips-wave

drips-wave Bot commented Nov 23, 2026

Copy link
Copy Markdown

@Neziahtech Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

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.

price_aggregates gains four rows per pair every minute, for ever

1 participant