Repository navigation
fix(jobs): bound price_aggregates with a retention prune (#691) - #810
Open
Neziahtech wants to merge 2 commits into
Open
Neziahtech wants to merge 2 commits into
Neziahtech wants to merge 2 commits into
Conversation
…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.
|
@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! 🚀 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #691
The problem
price_aggregateshad no retention at all.src/jobs/aggregateRefresh.tsupserts 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 answersORDER BY bucket DESC LIMIT nfor one(network, pair_key, window)series,ncapped atHISTORY_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 rawprice_pointsolder than 30 days into hour-aligned1hrows in this same table, withON 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:
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.KEEPdefaults toHISTORY_MAX_LIMITand 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.PRICE_AGGREGATES_RETENTION_DAYS(default 30, the horizon every other retention job here publishes), so a caller naming a recent range — GraphQLpriceHistorywithfrom/to, the screener's newest24hrow — 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.1hrow. The shapewindow = '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-hour1hrow 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-aligned1m/5m/24hbucket is a rolling row and is pruned when it ages out.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/metricssignals) and indocs/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.examplewith 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, followingsnapshotRetention.tsandlendingRateRetention.tsrather 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-processsetIntervaland 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 andlimit ∈ {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 theNOT (window = '1h' AND bucket = date_trunc('hour', bucket))exemption, usesFOR UPDATE SKIP LOCKED, and takesLIMIT $6. And the Redis-down path:runs hourly and once on startup, per-networkAggregateErrorthat still prunes the other network, and defaults checked againstHISTORY_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 anddocs/what-lens-knows.mdare untouched.Local verification
npx tsc --noEmitclean.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
price_aggregatesis not partitioned and partitioning it is a separate decision (andprice_pointsalready has its own partition job).pool_snapshotsalone even though it grows the same way — that ispool_snapshotsgets a new row on every poll and nothing ever deletes one #689's table, and there is an open PR for it.