diff --git a/.env.example b/.env.example index d28eb381..1fc1cc50 100644 --- a/.env.example +++ b/.env.example @@ -615,6 +615,37 @@ PRICE_POINTS_RETENTION_DAYS=30 # Default: 1000. PRICE_POINTS_PRUNE_BATCH_SIZE=1000 +# ─── price_aggregates retention ──────────────────────────────────────────── +# Rows older than this many days are pruned from price_aggregates by +# src/jobs/priceAggregatesRetention.ts. The refresher writes one row per window +# (1m, 5m, 1h, 24h) for every watched pair on every network every minute, so +# without this the table only ever grows. +# +# What the prune never touches: +# - the 1-hour rollups written from raw price_points before those points are +# deleted (window='1h' with an hour-aligned bucket) — that is the permanent +# long-term history, and +# - the newest PRICE_AGGREGATES_KEEP_ROWS rows of every +# (network, pair_key, window) series, whatever their age, because +# GET /price/:assetA/:assetB/history answers with the newest `limit` rows of +# one series and has no time bound of its own. +# +# Default: 30 days, the horizon every other retention job here publishes. +PRICE_AGGREGATES_RETENTION_DAYS=30 + +# Maximum rows removed by one database statement during a retention run. The +# job deletes in bounded batches per series, skipping locked rows and pausing +# between batches, so it never holds a long lock or out-runs the refresher. +# Default: 1000. +PRICE_AGGREGATES_PRUNE_BATCH_SIZE=1000 + +# How many of the newest rows of each (network, pair_key, window) series are +# kept regardless of age. Must stay at or above the history route's maximum page +# size (HISTORY_MAX_LIMIT, src/api/rest.ts) for the prune to be invisible to +# that route; a test asserts the two are equal at the default. +# Default: 1000. +PRICE_AGGREGATES_KEEP_ROWS=1000 + # --- Subscription fan-out benchmark (scripts/benchmarkSubscriptions.ts) --- # Only read by the benchmark script, not by the server. A label stamped into # the script's JSON result so separate runs can be told apart. diff --git a/docs/RUNBOOK.md b/docs/RUNBOOK.md index f2ee5778..d7e3d2b8 100644 --- a/docs/RUNBOOK.md +++ b/docs/RUNBOOK.md @@ -22,7 +22,7 @@ worker, ingester or scheduler process: | WebSocket server | `graphql-transport-ws` subscriptions on `/graphql`; local fan-out plus cross-instance fan-out over Redis pub/sub | `src/ws/fanout.ts`, `src/ws/` | | Venue ingesters | One infinite poll loop per (venue × enabled network) for **SDEX**, **Horizon AMM**, **Soroswap**, **Aquarius** | registry `src/ingest/venues/index.ts`, started in `main()` (`src/index.ts`) via `startVenueAdapter` (`src/ingest/venues/runner.ts`) | | Snapshot ingester | Appends one `price_snapshots` row per active pair at every minute boundary, per network | `src/ingest/snapshot.ts` | -| BullMQ workers | `aggregate-refresh` (one queue/worker per network), `snapshot-retention` (hourly), `price_points` partition maintenance (hourly) — **in the same process** | `src/jobs/aggregateRefresh.ts`, `src/jobs/snapshotRetention.ts`, `src/jobs/pricePointsPartitionJob.ts` | +| BullMQ workers | `aggregate-refresh` (one queue/worker per network), `snapshot-retention` (hourly), `price_points` partition maintenance (hourly), `price_aggregates` retention (hourly) — **in the same process** | `src/jobs/aggregateRefresh.ts`, `src/jobs/snapshotRetention.ts`, `src/jobs/pricePointsPartitionJob.ts`, `src/jobs/priceAggregatesRetention.ts` | | Webhook dispatcher | Threshold alerts, delivered inline after each ingested price write | `src/webhookDispatcher.ts`, `src/alerts/delivery.ts` | | Schema migration | `prisma migrate deploy` runs **at every boot, before the API listens** — committed migrations only, never a diff of the live schema (#233). On a database that predates the migration history the baseline is recorded as applied first, without running it | `applyMigrations()` in `src/db/migrate.ts`, called from `main()` (`src/index.ts`) — doc: [`docs/database-migrations.md`](database-migrations.md) | | Middleware | Network selector, API-key auth, per-key/IP rate limits, the per-instance global request ceiling (`GLOBAL_RATE_LIMIT_MAX`, sheds with 503), x402 payment gate, cache policy, HTTP metrics | `src/app.ts` registration order | @@ -44,13 +44,86 @@ worker, ingester or scheduler process: 8. Snapshot retention: prune once, then schedule hourly — on Redis failure warn `falling back to an in-process hourly prune` and install an in-process `setInterval`. 9. Price-points partition maintenance: same pattern, same in-process hourly fallback. -10. Ingesters started per network through `restartIngester`: a crash is logged +10. `price_aggregates` retention: same pattern, same in-process hourly fallback + (prune once, then schedule hourly; on failure warn + `price_aggregates retention worker unavailable; falling back to hourly + in-process prune`) — policy in §1a. +11. Ingesters started per network through `restartIngester`: a crash is logged (`ingester crashed; restarting in 10s`) and restarted after 10 s, isolated per `(venue, network)` — one dying ingester does not affect the others. -11. `markBootComplete()` — **last**, and only once every ingester above is +12. `markBootComplete()` — **last**, and only once every ingester above is running: until that line `GET /ready` answers 503, keeping a starting instance out of the load balancer (`src/index.ts`, `src/health.ts`). +### 1a. Data retention policy + +Four tables gain rows as long as the service is up, whatever anyone asks of them, +and Lens bounds each of them. The rule for every one of them is the same: +**delete in bounded batches, per network, only what no answer can still depend +on, and never let the job take the service down.** + +| Table | What grows | What is deleted | What is never deleted | Job | +|---|---|---|---|---| +| `price_snapshots` | 1 row/pair/network/min | rows older than `SNAPSHOT_RETENTION_DAYS` (30) | — | `src/jobs/snapshotRetention.ts` | +| `price_points` | 1 row/trade | rows older than `PRICE_POINTS_RETENTION_DAYS` (30), **after** rolling them up | the rollups it writes | `src/jobs/pricePointsRetention.ts`, partitions by `src/jobs/pricePointsPartitionJob.ts` | +| `price_aggregates` | 4 rows/pair/network/min (`1m`, `5m`, `1h`, `24h`, one bucket per minute per window) | rows older than `PRICE_AGGREGATES_RETENTION_DAYS` (30) **and** older than the series' keep floor | hour-aligned `1h` rows (the long-term hourly rollups); the newest `PRICE_AGGREGATES_KEEP_ROWS` (1000) rows of every series | `src/jobs/priceAggregatesRetention.ts` | +| `lending_rates` | history rows per rate update | rows past `RATE_RETENTION_DAYS` (30) | — | `src/jobs/lendingRateRetention.ts` | + +**`price_aggregates` in detail (#691).** `aggregateRefresh.ts` upserts one row +per window per pair every minute, and each upsert lands on a bucket that is the +current minute — so four new primary keys appear every minute and nothing was +ever removed. That is 172,800 rows per pair per network per month, on every +network, forever. + +The job prunes per `(network, pair_key, window)` series, and a row is deleted +only when **all** of these hold: + +- it is older than the series' **keep floor**: the bucket of the + `PRICE_AGGREGATES_KEEP_ROWS`-th newest row of that same series. This is the + bound that makes the prune invisible to readers — `GET + /price/:assetA/:assetB/history` has **no time predicate at all** (`ORDER BY + bucket DESC LIMIT n`, `src/api/rest.ts`), so its answer for a series is simply + that series' newest `n` rows, `n ≤ HISTORY_MAX_LIMIT` (1000). Keeping 1000 + means no page can come back shorter or different because the job ran, even for + a pair whose ingestion broke months ago and whose every row is therefore old. + A series with fewer rows than the keep count is not touched at all. +- it is older than `PRICE_AGGREGATES_RETENTION_DAYS`, so a caller naming a + recent range (`from`/`to` in the GraphQL `priceHistory`, 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 the per-minute rows, which is the whole point of + keeping them. +- it is **not** an hour-aligned `1h` row. `rollupOldPricePoints` + (`src/jobs/pricePointsRetention.ts`) writes one `1h` row per + `(network, pair_key, hour)` from the raw `price_points` it is about to delete, + and that row is the only copy of history older than 30 days — so the shape + `window = '1h' AND bucket = date_trunc('hour', bucket)` is exempt whatever its + age. In the live table the refresher's top-of-hour `1h` row and the rollup's + row are the *same* primary key, so this exempts the hourly history itself, not + a duplicate of it; an hour-aligned `1m`/`5m`/`24h` bucket is a rolling row and + is pruned once it ages out. +- 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 the lock footprint stays inside + one series. + +Settings: `PRICE_AGGREGATES_RETENTION_DAYS`, `PRICE_AGGREGATES_PRUNE_BATCH_SIZE`, +`PRICE_AGGREGATES_KEEP_ROWS` (`.env.example`). Counter: +`price_aggregates_pruned_total{network}`. One cost to expect: the run starts by +listing the network's `(pair_key, window)` series, which is a `DISTINCT` scan of +the table — bounded output (pairs × 4), unbounded read. Batching bounds the +deletes, not that scan, so the first run after a long stretch of growth is the +slow one and `db_query_duration_seconds` will show it. + +If Redis is down the schedule fails over to an hourly in-process prune (§2), so +the table stays bounded with no queue; if the in-process prune itself fails it is +logged (`price_aggregates prune failed`) and retried on the next tick — +**startup never exits over it**. `PRICE_AGGREGATES_KEEP_ROWS` is only a promise +while the history route caps its page there: +`src/__tests__/priceAggregatesRetention.test.ts` asserts the two are equal, so +raising the route limit without the env default fails a test rather than +silently truncating someone's chart. + ### Supporting services (`docker-compose.yml`) | Service | Notes | @@ -268,6 +341,7 @@ Public Prometheus exposition (`src/metrics.ts`, route in `src/app.ts`). | `api_key_auth_failures_total{reason}`, `admin_auth_failures_total` | Auth failures by bounded reason (`missing`/`malformed`/`unknown`/`revoked`/`expired`; admin counted separately) | | `rate_limit_rejections_total{scope}`, `global_shed_requests_total` | Per-key/IP limiter 429s (`key`/`ip`) and per-instance ceiling sheds (503) | | `x402_payments_received_total`, `price_requests_total` | Payment/request counters | +| `price_points_pruned_total{network}`, `price_points_rolled_up_total{network}`, `price_aggregates_pruned_total{network}` | Retention counters, per network (§1a). Flat while ingestion is healthy = the prune is not running (Redis fallback, or a failing job in the logs) | **Known blind spots:** no gauge for Redis state, no gauge for the pg pool (see #339 in §4), no queue-lag metric, no webhook-delivery metric. diff --git a/docs/database-schema.md b/docs/database-schema.md index 9dbafdb2..0657155a 100644 --- a/docs/database-schema.md +++ b/docs/database-schema.md @@ -29,6 +29,49 @@ To ensure that running code never crashes at request time due to missing columns - If an expected table or column is absent, it fails fast and names the missing entities. - `/ready` and `/status` can query `verifyDatabaseSchema()` to isolate instances before they receive live traffic. +## Retention policy (#691) + +Every table here is append/upsert-only at ingest time, so each one is bounded by +a job rather than by a workload. The operational half — settings, what you see +when a prune stops running, Redis-down behaviour — is in +[`docs/RUNBOOK.md` §1a](RUNBOOK.md#1a-data-retention-policy); this section +records the schema-level facts the jobs are written against. + +| Table | Written by | Row that appears unprompted | Bounded by | +|---|---|---|---| +| `price_points` | venue ingesters | one row per trade | `pricePointsRetention.ts` (rollup, then prune past `PRICE_POINTS_RETENTION_DAYS`) + `pricePointsPartitionJob.ts` | +| `price_snapshots` | snapshot ingester | 1 row/pair/network/minute | `snapshotRetention.ts` | +| `lending_rates` | rate ingesters | 1 row/pair/update | `lendingRateRetention.ts` | +| `price_aggregates` | `aggregateRefresh.ts` | **4 rows/pair/network/minute** | `priceAggregatesRetention.ts` | + +`price_aggregates` is the one that grows without anyone asking. Its primary key +is `[network, pair_key, window, bucket]` and the refresher upserts all four +windows (`1m`, `5m`, `1h`, `24h`) every minute with `bucket` set to the current +minute — four new keys per minute per pair per network, 172,800 rows per pair per +month, with nothing removing any of them. + +The retention job deletes a row only when it is older than the retention +horizon, **and** older than the newest-`N` floor of its own +`(network, pair_key, window)` series, **and** not an hour-aligned `1h` row: + +- The series floor exists because `bucket` is a `timestamp(3) without time + zone` and the history route imposes no time predicate of its own + (`ORDER BY bucket DESC LIMIT n`): a page is by definition the newest `n` rows + of the series, so the newest `N` rows of every series are kept whatever their + age and no request can tell that a prune happened. `N` defaults to + `HISTORY_MAX_LIMIT` (1000) and a test asserts the two stay equal. +- The hour-aligned `1h` rows are the long-term record. `rollupOldPricePoints` + writes one per `(network, pair_key, hour)` from the raw `price_points` it is + about to delete, under `ON CONFLICT (network, pair_key, window, bucket) DO + UPDATE` — after 30 days that row is the only surviving copy of that hour, and + it shares its primary key with the refresher's top-of-hour `1h` row, so the + hourly series is one row per hour, kept forever (24/pair/day, versus the + 5,760/pair/day minute rows above it). + +No migration is needed for this: the job deletes rows through the existing +primary key, and `FOR UPDATE SKIP LOCKED` keeps a batch's locks inside one +series so the refresher never waits on the prune. + ## Path Forward: Transitioning to `prisma migrate` When moving to formal multi-region enterprise production deployments: diff --git a/src/__tests__/priceAggregatesRetention.test.ts b/src/__tests__/priceAggregatesRetention.test.ts new file mode 100644 index 00000000..31678e58 --- /dev/null +++ b/src/__tests__/priceAggregatesRetention.test.ts @@ -0,0 +1,597 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' + +const { mockQuery } = vi.hoisted(() => ({ mockQuery: vi.fn() })) + +vi.mock('../db', () => ({ + prisma: {}, + pgPool: { query: mockQuery }, +})) + +// bullmq pulls in ioredis at import time; stub it so the unit under test loads +// without a live Redis connection. +vi.mock('bullmq', () => { + class QueueStub { + async add() { + return {} + } + async close() {} + } + class WorkerStub { + on() {} + async close() {} + } + return { Queue: QueueStub, Worker: WorkerStub } +}) + +vi.mock('../redis', () => ({ + redis: { get: vi.fn(), set: vi.fn(), del: vi.fn(), on: vi.fn(), ping: vi.fn() }, + getCachedPrice: vi.fn().mockResolvedValue(null), + setCachedPrice: vi.fn(), +})) + +import { + pruneOldAggregates, + pruneAllAggregateNetworks, + listAggregateSeries, + readSeriesKeepFloor, + isPermanentAggregateRow, + schedulePriceAggregatesRetention, + PRICE_AGGREGATES_RETENTION_DAYS, + PRICE_AGGREGATES_PRUNE_BATCH_SIZE, + PRICE_AGGREGATES_KEEP_ROWS, + AGGREGATE_WINDOWS, +} from '../jobs/priceAggregatesRetention' +import { price_aggregates_pruned_total } from '../metrics' +import { activeNetwork } from '../config' +import { HISTORY_DEFAULT_LIMIT, HISTORY_MAX_LIMIT } from '../api/rest' + +const HOUR = 60 * 60 * 1000 +const DAY = 24 * HOUR + +/** The rows one pair's series holds, newest first, as the refresher writes them. */ +const NOW = new Date('2026-11-23T12:34:00.000Z') + +function minuteRows(count: number, spacingMs: number, endAt: Date = NOW) { + return Array.from({ length: count }, (_, i) => new Date(endAt.getTime() - i * spacingMs)) +} + +/** The statements the mocked driver was asked to run, split by role. */ +function statements() { + const select = (needle: string) => + mockQuery.mock.calls.filter(call => (call[0] as string).includes(needle)) + return { + series: select('SELECT DISTINCT pair_key, window'), + floors: select('LIMIT 1 OFFSET'), + deletes: select('DELETE FROM price_aggregates'), + } +} + +describe('priceAggregatesRetention configuration & defaults', () => { + it('defaults to a 30-day window, 1000-row batches and a 1000-row keep floor', () => { + expect(PRICE_AGGREGATES_RETENTION_DAYS).toBe(30) + expect(PRICE_AGGREGATES_PRUNE_BATCH_SIZE).toBe(1000) + expect(PRICE_AGGREGATES_KEEP_ROWS).toBe(1000) + }) + + // The keep count is only a promise while the history route caps its page at + // the same number: the route returns the newest `limit` rows of a series, so + // keeping that many is what makes a prune invisible to it. + it('keeps at least the history route\'s maximum page', () => { + expect(PRICE_AGGREGATES_KEEP_ROWS).toBe(HISTORY_MAX_LIMIT) + }) + + it('covers the four windows the refresher writes', () => { + expect(AGGREGATE_WINDOWS).toEqual(['1m', '5m', '1h', '24h']) + }) + + it('rejects invalid bounds before querying', async () => { + await expect(pruneOldAggregates(30, activeNetwork, 0)).rejects.toThrow(/positive integer/) + await expect(pruneOldAggregates(30, activeNetwork, 1000, 1.5)).rejects.toThrow(/positive integer/) + await expect(pruneOldAggregates(-1, activeNetwork)).rejects.toThrow(/non-negative/) + expect(mockQuery).not.toHaveBeenCalled() + }) +}) + +describe('isPermanentAggregateRow', () => { + // Built from local components, because that is what the rule reads: the + // bucket arrives as a wall-clock hour in whatever timezone the driver + // assumed, and a UTC-literal date would not be hour-aligned everywhere. + const localHour = (day: number) => new Date(2026, 0, day, 5, 0, 0, 0) + const localMinute = (day: number, minute: number) => new Date(2026, 0, day, 5, minute, 0, 0) + + it('protects the hour-aligned 1h rollups the price_points job writes', () => { + expect(isPermanentAggregateRow({ window: '1h', bucket: localHour(4) })).toBe(true) + }) + + it('does not protect a rolling 1h row that is not on the hour', () => { + expect(isPermanentAggregateRow({ window: '1h', bucket: localMinute(4, 34) })).toBe(false) + }) + + // The rollup is identified by shape, and only the '1h' window is a rollup. An + // hour-aligned 1m bucket is a minute row and is fair game once it ages out. + it('does not protect an hour-aligned row of another window', () => { + expect(isPermanentAggregateRow({ window: '1m', bucket: localHour(4) })).toBe(false) + expect(isPermanentAggregateRow({ window: '24h', bucket: localHour(4) })).toBe(false) + }) + + it('refuses a bucket that carries seconds or milliseconds', () => { + expect(isPermanentAggregateRow({ window: '1h', bucket: new Date(2026, 0, 4, 5, 0, 1, 0) })).toBe(false) + expect(isPermanentAggregateRow({ window: '1h', bucket: new Date(2026, 0, 4, 5, 0, 0, 500) })).toBe(false) + }) +}) + +describe('the reads the prune is built from', () => { + beforeEach(() => { + mockQuery.mockReset() + }) + + it('lists a network\'s series and nothing from another network', async () => { + mockQuery.mockResolvedValueOnce({ + rows: [ + { pair_key: 'USDC/XLM', window: '1m' }, + { pair_key: 'USDC/XLM', window: '1h' }, + ], + }) + + const series = await listAggregateSeries('mainnet') + + expect(series).toEqual([ + { pairKey: 'USDC/XLM', window: '1m' }, + { pairKey: 'USDC/XLM', window: '1h' }, + ]) + const [sql, params] = mockQuery.mock.calls[0] + expect(params).toEqual(['mainnet']) + expect(sql).toMatch(/FROM price_aggregates/i) + expect(sql).toMatch(/WHERE network = \$1/i) + // A window is only ever pruned as part of its own series, so a mainnet + // delete can never reach a testnet row of the same pair. + expect(sql).toMatch(/DISTINCT pair_key, window/i) + }) + + it('reads the keep-th newest bucket of one series', async () => { + const floor = new Date('2026-10-01T00:00:00.000Z') + mockQuery.mockResolvedValueOnce({ rows: [{ floor }] }) + + const result = await readSeriesKeepFloor('testnet', 'USDC/XLM', '1m', 1000) + + expect(result).toEqual(floor) + const [sql, params] = mockQuery.mock.calls[0] + expect(params).toEqual(['testnet', 'USDC/XLM', '1m', 999]) + expect(sql).toMatch(/ORDER BY bucket DESC/i) + expect(sql).toMatch(/LIMIT 1 OFFSET \$4/i) + }) + + it('reports no floor for a series shorter than the keep count', async () => { + mockQuery.mockResolvedValueOnce({ rows: [] }) + expect(await readSeriesKeepFloor('testnet', 'USDC/XLM', '1m', 1000)).toBeNull() + }) + + it('turns a timestamp string back into a Date', async () => { + mockQuery.mockResolvedValueOnce({ rows: [{ floor: '2026-10-01T00:00:00.000Z' }] }) + const result = await readSeriesKeepFloor('testnet', 'USDC/XLM', '1m', 10) + expect(result).toBeInstanceOf(Date) + expect(result?.toISOString()).toBe('2026-10-01T00:00:00.000Z') + }) +}) + +describe('pruneOldAggregates', () => { + beforeEach(() => { + mockQuery.mockReset() + }) + + function seriesListing(entries: Array<{ pairKey: string; window: string }>) { + mockQuery.mockResolvedValueOnce({ + rows: entries.map(e => ({ pair_key: e.pairKey, window: e.window })), + }) + } + + it('deletes one series in bounded batches and stops on an empty batch', async () => { + seriesListing([{ pairKey: 'USDC/XLM', window: '1m' }]) + const floor = new Date('2026-10-20T00:00:00.000Z') + mockQuery + .mockResolvedValueOnce({ rows: [{ floor }] }) + .mockResolvedValueOnce({ rowCount: 1000 }) + .mockResolvedValueOnce({ rowCount: 400 }) + .mockResolvedValueOnce({ rowCount: 0 }) + + const result = await pruneOldAggregates(30, 'testnet', 1000, 1000, 0) + + expect(result).toEqual({ + network: 'testnet', + pruned: 1400, + batches: 2, + series: 1, + kept: 0, + }) + const deletes = statements().deletes + expect(deletes).toHaveLength(3) + expect(deletes[0][1]).toEqual(['testnet', 'USDC/XLM', '1m', floor, 30, 1000]) + }) + + it('bounds every delete by the series floor, the age horizon and the batch size', async () => { + seriesListing([{ pairKey: 'USDC/XLM', window: '5m' }]) + mockQuery + .mockResolvedValueOnce({ rows: [{ floor: new Date('2026-10-01T00:00:00.000Z') }] }) + .mockResolvedValueOnce({ rowCount: 0 }) + + await pruneOldAggregates(30, 'testnet', 500, 1000, 0) + + const [sql] = statements().deletes[0] + expect(sql).toMatch(/WITH batch AS/i) + expect(sql).toMatch(/WHERE network = \$1 AND pair_key = \$2 AND window = \$3/i) + expect(sql).toMatch(/bucket < \$4/i) + expect(sql).toMatch(/bucket < NOW\(\) - \(\$5 \|\| ' days'\)::interval/i) + expect(sql).toMatch(/LIMIT \$6/i) + // The same locking discipline the other retention jobs use: locked rows are + // left for the next run instead of stalling the refresher. + expect(sql).toMatch(/FOR UPDATE SKIP LOCKED/i) + expect(sql).toMatch(/DELETE FROM price_aggregates AS aggregates\s+USING batch\s+WHERE aggregates\.ctid = batch\.ctid/i) + }) + + // The one rule that cannot be got wrong: the hour rollups are the only copy of + // history older than the raw price_points, and this is the job that deletes + // from the same table they live in. + it('exempts the hour-aligned 1h rollups in the delete itself', async () => { + seriesListing([{ pairKey: 'USDC/XLM', window: '1h' }]) + mockQuery + .mockResolvedValueOnce({ rows: [{ floor: new Date('2026-10-01T00:00:00.000Z') }] }) + .mockResolvedValueOnce({ rowCount: 0 }) + + await pruneOldAggregates(30, 'testnet', 1000, 1000, 0) + + const [sql] = statements().deletes[0] + expect(sql).toMatch(/NOT \(window = '1h' AND bucket = date_trunc\('hour', bucket\)\)/i) + }) + + it('leaves a series shorter than the keep count completely alone', async () => { + seriesListing([{ pairKey: 'BTC/XLM', window: '1m' }]) + mockQuery.mockResolvedValueOnce({ rows: [] }) + + const result = await pruneOldAggregates(30, 'testnet', 1000, 1000, 0) + + expect(result).toEqual({ network: 'testnet', pruned: 0, batches: 0, series: 1, kept: 1 }) + expect(statements().deletes).toHaveLength(0) + }) + + it('visits every series of the network it was given', async () => { + seriesListing([ + { pairKey: 'USDC/XLM', window: '1m' }, + { pairKey: 'USDC/XLM', window: '5m' }, + { pairKey: 'USDC/XLM', window: '1h' }, + { pairKey: 'USDC/XLM', window: '24h' }, + ]) + mockQuery.mockImplementation(async (sql: string) => { + if (sql.includes('LIMIT 1 OFFSET')) return { rows: [{ floor: new Date('2026-09-01T00:00:00.000Z') }] } + return { rowCount: 0 } + }) + + const result = await pruneOldAggregates(30, 'mainnet', 1000, 1000, 0) + + expect(result.series).toBe(4) + expect(result.kept).toBe(4) + const pairs = statements().floors.map(call => `${call[1][1]}/${call[1][2]}`) + expect(pairs).toEqual(['USDC/XLM/1m', 'USDC/XLM/5m', 'USDC/XLM/1h', 'USDC/XLM/24h']) + for (const call of [...statements().floors, ...statements().deletes]) { + expect(call[1][0]).toBe('mainnet') + } + }) + + it('reports batch progress and counts the rows it removed as a metric', async () => { + seriesListing([{ pairKey: 'USDC/XLM', window: '1m' }]) + mockQuery + .mockResolvedValueOnce({ rows: [{ floor: new Date('2026-10-01T00:00:00.000Z') }] }) + .mockResolvedValueOnce({ rowCount: 700 }) + .mockResolvedValueOnce({ rowCount: 300 }) + .mockResolvedValueOnce({ rowCount: 0 }) + + const onProgress = vi.fn() + const metric = vi.spyOn(price_aggregates_pruned_total, 'inc') + try { + await pruneOldAggregates(30, 'testnet', 1000, 1000, 0, onProgress) + + expect(metric).toHaveBeenCalledWith({ network: 'testnet' }, 700) + expect(metric).toHaveBeenCalledWith({ network: 'testnet' }, 300) + expect(onProgress).toHaveBeenLastCalledWith({ + network: 'testnet', + pairKey: 'USDC/XLM', + window: '1m', + batch: 2, + batchRows: 300, + totalPruned: 1000, + }) + } finally { + // Asserted inside the run: restoring the counter clears the spy's calls. + metric.mockRestore() + } + }) + + it('yields between batches through the injected function', async () => { + seriesListing([{ pairKey: 'USDC/XLM', window: '1m' }]) + mockQuery + .mockResolvedValueOnce({ rows: [{ floor: new Date('2026-10-01T00:00:00.000Z') }] }) + .mockResolvedValueOnce({ rowCount: 10 }) + .mockResolvedValueOnce({ rowCount: 0 }) + + const yields: number[] = [] + await pruneOldAggregates( + 30, + 'testnet', + 10, + 10, + 0, + undefined, + async () => { + yields.push(yields.length + 1) + } + ) + + expect(yields).toEqual([1]) + }) + + it('surfaces a series whose floor it cannot measure rather than skipping it', async () => { + seriesListing([ + { pairKey: 'BAD/XLM', window: '1m' }, + { pairKey: 'GOOD/XLM', window: '1m' }, + ]) + mockQuery.mockImplementation(async (sql: string, params: unknown[]) => { + if (sql.includes('LIMIT 1 OFFSET')) { + if (params[1] === 'BAD/XLM') throw new Error('series scan timed out') + return { rows: [{ floor: new Date('2026-10-01T00:00:00.000Z') }] } + } + return { rowCount: 0 } + }) + + // The floor read of a series is part of that series' work: if it cannot be + // measured, nothing about it is safe to delete, and the run reports it rather + // than quietly skipping the one series nobody checked. + await expect(pruneOldAggregates(30, 'testnet', 1000, 1000, 0)).rejects.toThrow(/series scan timed out/) + }) +}) + +describe('pruneAllAggregateNetworks', () => { + const saved = process.env.ENABLED_NETWORKS + + beforeEach(() => { + mockQuery.mockReset() + }) + + afterEach(() => { + if (saved === undefined) delete process.env.ENABLED_NETWORKS + else process.env.ENABLED_NETWORKS = saved + }) + + it('prunes every enabled network and reports per network', async () => { + process.env.ENABLED_NETWORKS = 'testnet,mainnet' + // Two batches of 7 rows on each network, then an empty batch ends the drain. + const deletes: Record = { testnet: 0, mainnet: 0 } + mockQuery.mockImplementation(async (sql: string, params: unknown[]) => { + if (sql.includes('DISTINCT pair_key')) return { rows: [{ pair_key: 'USDC/XLM', window: '1m' }] } + if (sql.includes('LIMIT 1 OFFSET')) return { rows: [{ floor: new Date('2026-10-01T00:00:00.000Z') }] } + const network = params[0] as string + deletes[network] = (deletes[network] ?? 0) + 1 + return { rowCount: deletes[network] <= 2 ? 7 : 0 } + }) + + const results = await pruneAllAggregateNetworks(30) + + expect(results.testnet?.pruned).toBe(14) + expect(results.mainnet?.pruned).toBe(14) + expect(results.testnet?.network).toBe('testnet') + expect(results.mainnet?.network).toBe('mainnet') + + const networks = [...new Set(mockQuery.mock.calls.map(call => call[1]?.[0]))] + expect(networks).toEqual(['testnet', 'mainnet']) + }) + + it('still prunes the other network when one fails, then throws AggregateError', async () => { + process.env.ENABLED_NETWORKS = 'testnet,mainnet' + mockQuery.mockImplementation(async (_sql: string, params: unknown[]) => { + if (params[0] === 'testnet') throw new Error('testnet connection lost') + if (_sql.includes('DISTINCT pair_key')) return { rows: [] } + return { rowCount: 0 } + }) + + await expect(pruneAllAggregateNetworks(30)).rejects.toThrow(/testnet: testnet connection lost/) + + const networks = [...new Set(mockQuery.mock.calls.map(call => call[1]?.[0]))] + expect(networks).toEqual(['testnet', 'mainnet']) + }) +}) + +describe('scheduling', () => { + it('runs hourly and once on startup', async () => { + const add = vi.fn().mockResolvedValue({}) + await schedulePriceAggregatesRetention({ add } as never) + + expect(add).toHaveBeenNthCalledWith( + 1, + 'prune', + {}, + { repeat: { every: HOUR }, jobId: 'price-aggregates-retention:prune' } + ) + expect(add).toHaveBeenNthCalledWith(2, 'prune', {}) + }) +}) + +/** + * #691's done-when is a promise about answers, not about row counts: for any + * request `GET /price/:assetA/:assetB/history` could serve, the response is the + * same before the prune as after it. + * + * The route has no time predicate — `ORDER BY bucket DESC LIMIT n` — so its + * answer for a series is that series' newest `n` rows. What follows models the + * rule the delete statement encodes, using the module's own permanence + * predicate, and checks that promise against a table that has been growing for + * months. + */ +describe('history answers do not move', () => { + interface Row { + pairKey: string + window: string + bucket: Date + } + + const KEEP = PRICE_AGGREGATES_KEEP_ROWS + const PAIRS = ['USDC/XLM', 'BTC/XLM'] + /** Rows past the horizon in every series: the part that accumulates forever. */ + const OLD_ROWS = 500 + /** Rollups kept per pair: three days of hourly history, as the rollup job leaves it. */ + const ROLLUP_HOURS = 72 + + // The top of NOW's hour, from the local components the permanence rule reads: + // `bucket` is a timestamp without time zone, so an hour is a wall-clock hour. + const hourAnchor = new Date( + NOW.getFullYear(), + NOW.getMonth(), + NOW.getDate(), + NOW.getHours(), + 0, + 0, + 0 + ) + /** Well past the horizon, so the rollups sit inside the delete's own range. */ + const rollupStart = hourAnchor.getTime() - (PRICE_AGGREGATES_RETENTION_DAYS + 70) * DAY + const rollupBuckets = Array.from({ length: ROLLUP_HOURS }, (_, hours) => + new Date(rollupStart - hours * HOUR) + ) + + /** A pair whose refresher has run for months: a dense recent block, a long old tail. */ + function growingTable(): Row[] { + const rows: Row[] = [] + for (const pairKey of PAIRS) { + for (const window of AGGREGATE_WINDOWS) { + // `KEEP` buckets of recent minutes — every page the route reads from. + for (const bucket of minuteRows(KEEP, 60_000, NOW)) rows.push({ pairKey, window, bucket }) + // Then a tail well past the retention horizon. It is spaced from NOW, not + // from the top of an hour, so none of these rows takes the rollup's + // exemption by accident and the tail is genuinely prunable. + const tailStart = new Date(NOW.getTime() - (PRICE_AGGREGATES_RETENTION_DAYS + 5) * DAY) + for (const bucket of minuteRows(OLD_ROWS, DAY, tailStart)) rows.push({ pairKey, window, bucket }) + } + // The permanent rollups, older than everything above. + for (const bucket of rollupBuckets) rows.push({ pairKey, window: '1h', bucket }) + } + return rows + } + + /** The rows the prune took: `prune` filters, so object identity survives it. */ + function goneRows(table: Row[], pruned: Row[]): Row[] { + const kept = new Set(pruned) + return table.filter(row => !kept.has(row)) + } + + /** What `GET /price/:assetA/:assetB/history` answers from a set of rows. */ + function route(rows: Row[], pairKey: string, window: string, limit: number) { + return rows + .filter(r => r.pairKey === pairKey && r.window === window) + .sort((a, b) => b.bucket.getTime() - a.bucket.getTime()) + .slice(0, limit) + .map(r => r.bucket.toISOString()) + } + + /** + * The delete statement's rule, applied in JS: per-series floor, the age + * horizon, the rollup exemption, nothing else. The floor is measured once per + * series exactly as `readSeriesKeepFloor` measures it. + */ + function prune(rows: Row[], keepRows: number, retentionDays: number, now: Date): Row[] { + const cutoff = now.getTime() - retentionDays * DAY + const floors = new Map() + const bySeries = new Map() + for (const row of rows) { + const key = `${row.pairKey}|${row.window}` + const series = bySeries.get(key) ?? [] + series.push(row) + bySeries.set(key, series) + } + for (const [key, series] of bySeries) { + series.sort((a, b) => b.bucket.getTime() - a.bucket.getTime()) + const floor = series[keepRows - 1] + if (floor) floors.set(key, floor.bucket) + } + return rows.filter(row => { + if (isPermanentAggregateRow(row)) return true + const floor = floors.get(`${row.pairKey}|${row.window}`) + if (!floor) return true + return !(row.bucket < floor && row.bucket.getTime() < cutoff) + }) + } + + it('deletes the old tail of every series and nothing else', () => { + const table = growingTable() + const pruned = prune(table, KEEP, PRICE_AGGREGATES_RETENTION_DAYS, NOW) + const gone = goneRows(table, pruned) + + expect(pruned).toHaveLength(table.length - PAIRS.length * AGGREGATE_WINDOWS.length * OLD_ROWS) + expect(gone).toHaveLength(PAIRS.length * AGGREGATE_WINDOWS.length * OLD_ROWS) + + for (const pairKey of PAIRS) { + for (const window of AGGREGATE_WINDOWS) { + const inSeries = (rows: Row[]) => + rows.filter(r => r.pairKey === pairKey && r.window === window) + // The series' keep floor is its KEEP-th newest bucket — the oldest row + // that still appears in a page of any size the route answers. + const floor = new Date(NOW.getTime() - (KEEP - 1) * 60_000) + // Nothing the route could still answer with is gone. The `1h` series + // holds hour-aligned buckets among them, and they are exempt too: in a + // live table an hour-aligned `1h` bucket is the rollup's own primary + // key, written by the refresher an hour early and overwritten by the + // rollup at 30 days — one row, kept on purpose. + expect(inSeries(pruned).filter(r => r.bucket >= floor)).toHaveLength(KEEP) + expect(inSeries(gone).every(r => r.bucket < floor)).toBe(true) + } + } + }) + + it('answers every request the history route can make exactly as before', () => { + const table = growingTable() + const pruned = prune(table, KEEP, PRICE_AGGREGATES_RETENTION_DAYS, NOW) + + for (const pairKey of PAIRS) { + for (const window of AGGREGATE_WINDOWS) { + for (const limit of [1, 2, HISTORY_DEFAULT_LIMIT, HISTORY_MAX_LIMIT, KEEP]) { + expect(route(pruned, pairKey, window, limit), `limit=${limit} window=${window} pair=${pairKey}`).toEqual( + route(table, pairKey, window, limit) + ) + } + } + } + }) + + it('keeps the hour rollups of a series whose old minute rows all go', () => { + const table = growingTable() + const pruned = prune(table, KEEP, PRICE_AGGREGATES_RETENTION_DAYS, NOW) + const gone = goneRows(table, pruned) + const horizon = NOW.getTime() - PRICE_AGGREGATES_RETENTION_DAYS * DAY + + // The rollups are what the exemption is for, and they sat inside the range + // the delete covered: same series, same window, older than the horizon. + const rollups = table.filter(row => rollupBuckets.includes(row.bucket)) + expect(rollups).toHaveLength(PAIRS.length * ROLLUP_HOURS) + expect(rollups.every(row => isPermanentAggregateRow(row))).toBe(true) + expect(Math.max(...rollups.map(r => r.bucket.getTime()))).toBeLessThan(horizon) + + const survivors = new Set(pruned) + expect(rollups.every(row => survivors.has(row))).toBe(true) + + // What did go was old, and none of it was a rollup. + expect(gone.length).toBeGreaterThan(0) + expect(gone.every(row => !isPermanentAggregateRow(row))).toBe(true) + expect(gone.every(row => row.bucket.getTime() < horizon)).toBe(true) + }) + + it('leaves a sparse series untouched however old it is', () => { + // A pair whose ingestion stopped two thirds of a year ago holds fewer rows + // than the keep count. Every one of them is inside the newest page a caller + // could ask for, so the whole series survives and the route still answers. + const sparse: Row[] = minuteRows(20, 7 * DAY, new Date(NOW.getTime() - 200 * DAY)).map(bucket => ({ + pairKey: 'OLD/XLM', + window: '1m', + bucket, + })) + const pruned = prune(sparse, KEEP, PRICE_AGGREGATES_RETENTION_DAYS, NOW) + + expect(pruned).toHaveLength(sparse.length) + expect(route(pruned, 'OLD/XLM', '1m', HISTORY_MAX_LIMIT)).toEqual(route(sparse, 'OLD/XLM', '1m', HISTORY_MAX_LIMIT)) + }) +}) diff --git a/src/index.ts b/src/index.ts index c716e619..9b7f8712 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,6 +28,13 @@ import { runPricePointsMaintenance, PRICE_POINTS_RETENTION_DAYS, } from './jobs/pricePointsPartitionJob' +import { + createPriceAggregatesRetentionQueue, + startPriceAggregatesRetentionWorker, + schedulePriceAggregatesRetention, + pruneAllAggregateNetworks, + PRICE_AGGREGATES_RETENTION_DAYS, +} from './jobs/priceAggregatesRetention' import { loadPersistedPairs, getActivePairs } from './pairsRegistry' import { markHealthy, recordCrash } from './ingester/restart' import { markBootComplete } from './health' @@ -287,6 +294,48 @@ async function main() { } } + // ── price_aggregates retention ──────────────────────────────────────────── + // The refresher writes four rows per pair per network per minute and nothing + // removed them, so the table grew forever (#691). The prune keeps what the + // history route can still answer with — the newest rows of every series — and + // never touches the 1-hour rollups that raw price_points were compressed into. + // + // Same rule as snapshot retention: BullMQ is only how the prune gets scheduled, + // so a missing Redis falls back to a timer in this process rather than to a + // table nobody ever trims. + const safePruneAggregates = async () => { + try { + const results = await pruneAllAggregateNetworks() + for (const [network, res] of Object.entries(results)) { + if (res && res.pruned > 0) { + log.info( + { network, pruned: res.pruned, retentionDays: PRICE_AGGREGATES_RETENTION_DAYS }, + 'pruned aggregate rows older than the retention window' + ) + } + } + } catch (err) { + log.error({ err }, 'price_aggregates prune failed') + } + } + + await safePruneAggregates() + + { + let aggregatesRetentionQueue: ReturnType | undefined + let aggregatesRetentionWorker: ReturnType | undefined + try { + aggregatesRetentionQueue = createPriceAggregatesRetentionQueue() + aggregatesRetentionWorker = startPriceAggregatesRetentionWorker() + await schedulePriceAggregatesRetention(aggregatesRetentionQueue) + log.info('price_aggregates retention worker started') + } catch (err) { + log.warn({ err }, 'price_aggregates retention worker unavailable; falling back to hourly in-process prune') + await Promise.allSettled([aggregatesRetentionQueue?.close(), aggregatesRetentionWorker?.close()]) + setInterval(() => { void safePruneAggregates() }, 60 * 60 * 1000).unref() + } + } + // ── Ingesters (run in background — infinite loops) ──────────────────────── // Each ingester is independently fault-isolated via restartIngester, keyed by diff --git a/src/jobs/priceAggregatesRetention.ts b/src/jobs/priceAggregatesRetention.ts new file mode 100644 index 00000000..85b5e67b --- /dev/null +++ b/src/jobs/priceAggregatesRetention.ts @@ -0,0 +1,367 @@ +import { Queue, Worker } from 'bullmq' +import { pgPool } from '../db' +import { activeNetwork, type NetworkName } from '../config' +import { getEnabledNetworks } from '../network/enabledNetworks' +import { price_aggregates_pruned_total } from '../metrics' +import { createLogger } from '../logger' + +const log = createLogger('job:price-aggregates-retention') + +const QUEUE_NAME = `${activeNetwork}:price-aggregates-retention` + +/** + * Retention window for the aggregate rows the refresher writes. + * + * `src/jobs/aggregateRefresh.ts` upserts one row per window (`1m`, `5m`, `1h`, + * `24h`) for every watched pair, every minute, on every network. Each of those + * four upserts lands on a bucket that is the current minute, so a minute that + * passes creates four brand-new primary keys and deletes nothing. Nothing ever + * removed them: the table grew by 4 rows per pair per network per minute + * forever — 172,800 rows per pair per month. + * + * Defaults to 30 days because that is the horizon every other retention job in + * this service publishes (`SNAPSHOT_RETENTION_DAYS`, `PRICE_POINTS_RETENTION_DAYS`), + * and because the raw points a row was computed from are themselves rolled into + * 1-hour aggregates at 30 days. Rows older than the horizon still have an + * answer to offer, and that answer is the hour rollup, which this job never + * deletes. + */ +export const PRICE_AGGREGATES_RETENTION_DAYS = Number(process.env.PRICE_AGGREGATES_RETENTION_DAYS ?? 30) + +/** Maximum rows removed by one database statement during a retention run. */ +export const PRICE_AGGREGATES_PRUNE_BATCH_SIZE = Number(process.env.PRICE_AGGREGATES_PRUNE_BATCH_SIZE ?? 1_000) + +/** + * How many of the newest rows of a single `(network, pair_key, window)` series + * are kept whatever their age. + * + * `GET /price/:assetA/:assetB/history` answers with `ORDER BY bucket DESC + * LIMIT $n` and no time bound at all, so its answer for a series is the newest + * `n` rows of that series, `n` capped at the route's maximum page size. Keeping + * that many rows per series is what makes the prune invisible to the route: a + * page can never come back shorter because the job ran, even for a pair whose + * ingestion has been broken for months and whose rows are therefore all old. + * + * The default mirrors `HISTORY_MAX_LIMIT` in `src/api/rest.ts`; a test asserts + * the two stay equal, because this constant is only a promise while the route + * still caps its limit there. + */ +export const PRICE_AGGREGATES_KEEP_ROWS = Number(process.env.PRICE_AGGREGATES_KEEP_ROWS ?? 1_000) + +/** Default pause in milliseconds between deletion batches to yield database locks. */ +export const DEFAULT_AGGREGATES_PRUNE_PAUSE_MS = 50 + +/** The windows `aggregateRefresh.ts` writes, and the rollup window it preserves. */ +export const AGGREGATE_WINDOWS = ['1m', '5m', '1h', '24h'] as const + +export interface AggregateSeries { + pairKey: string + window: string +} + +export interface AggregatePruneProgress { + network: NetworkName + pairKey: string + window: string + batch: number + batchRows: number + totalPruned: number +} + +export interface AggregatePruneResult { + network: NetworkName + pruned: number + batches: number + /** Series this network has rows for. */ + series: number + /** Series with no prunable row: too young, or shorter than the keep count. */ + kept: number +} + +function redisConnection() { + const url = process.env.REDIS_URL + if (url) return { url } + return { host: 'localhost', port: 6379 } +} + +export function createPriceAggregatesRetentionQueue() { + return new Queue(QUEUE_NAME, { connection: redisConnection() }) +} + +/** + * The rows this job must never delete: the permanent 1-hour history. + * + * `rollupOldPricePoints` writes one row per `(network, pair_key, '1h', + * date_trunc('hour', timestamp))` from raw price_points it is about to delete. + * That rollup is the long-term record — once the raw points are gone it is the + * only copy — so a row of that shape is kept whatever its age. + * + * The rule is shape-based rather than provenance-based, and in the live table + * that is the same thing: the refresher's `1h` row for a top-of-hour bucket and + * the rollup's row for that hour share the primary key + * `(network, pair_key, '1h', hour)`, so the protected rows are exactly the + * hourly history — one row per pair per hour, which is the record this table is + * meant to keep forever. An hour-aligned `1m`, `5m` or `24h` bucket is a rolling + * row and is pruned once it ages out. + * + * The delete statement below carries the same rule in SQL, and that is the + * authoritative one: `date_trunc('hour', bucket)` is a wall-clock truncation on + * a `timestamp without time zone` column, whereas this function has to read the + * same instant through whatever timezone the driver assumed. The tests assert + * both forms, and the model test uses this one to state the guarantee. + */ +export function isPermanentAggregateRow(row: { window: string; bucket: Date }): boolean { + if (row.window !== '1h') return false + return ( + row.bucket.getMinutes() === 0 && + row.bucket.getSeconds() === 0 && + row.bucket.getMilliseconds() === 0 + ) +} + +/** + * The `(pair_key, window)` series one network actually has rows for. + * + * Every later statement is scoped to one series, which keeps each delete able to + * use the primary key `(network, pair_key, window, bucket)` and keeps a batch's + * lock footprint inside one series rather than across the table. + */ +export async function listAggregateSeries(network: NetworkName): Promise { + const result = await pgPool.query( + `SELECT DISTINCT pair_key, window + FROM price_aggregates + WHERE network = $1 + ORDER BY pair_key, window`, + [network] + ) + return result.rows.map((row: { pair_key: string; window: string }) => ({ + pairKey: row.pair_key, + window: row.window, + })) +} + +/** + * The bucket of the `keepRows`-th newest row in one series, or null when the + * series is shorter than that. + * + * Everything strictly older than this bucket is outside any page the history + * route can ask for, so it is the count side of the prune boundary. A null means + * the series is entirely inside the kept window and is not touched at all. + */ +export async function readSeriesKeepFloor( + network: NetworkName, + pairKey: string, + window: string, + keepRows: number = PRICE_AGGREGATES_KEEP_ROWS +): Promise { + const result = await pgPool.query( + `SELECT bucket AS floor + FROM price_aggregates + WHERE network = $1 AND pair_key = $2 AND window = $3 + ORDER BY bucket DESC + LIMIT 1 OFFSET $4`, + [network, pairKey, window, keepRows - 1] + ) + const floor = result.rows[0]?.floor + if (floor === undefined || floor === null) return null + return floor instanceof Date ? floor : new Date(floor) +} + +/** + * Prune one series in bounded batches. + * + * A row is deleted only when all four hold: + * - it is older than the series' keep floor, so no page of the history route + * could have reached it; + * - it is older than the retention horizon, so a request naming a recent range + * is untouched whatever the counts do; + * - it is not a permanent 1-hour rollup; + * - and it is not locked by a concurrent writer, which `SKIP LOCKED` leaves for + * the next run rather than making the refresher wait. + */ +async function pruneAggregateSeries( + network: NetworkName, + series: AggregateSeries, + floorBucket: Date, + retentionDays: number, + batchSize: number, + pauseMs: number, + onProgress?: (progress: AggregatePruneProgress) => void, + yieldFn?: () => Promise +): Promise<{ pruned: number; batches: number }> { + let totalPruned = 0 + let batchNumber = 0 + + while (true) { + const result = await pgPool.query( + `WITH batch AS ( + SELECT ctid + FROM price_aggregates + WHERE network = $1 AND pair_key = $2 AND window = $3 + AND bucket < $4 + AND bucket < NOW() - ($5 || ' days')::interval + AND NOT (window = '1h' AND bucket = date_trunc('hour', bucket)) + ORDER BY bucket + LIMIT $6 + FOR UPDATE SKIP LOCKED + ) + DELETE FROM price_aggregates AS aggregates + USING batch + WHERE aggregates.ctid = batch.ctid`, + [network, series.pairKey, series.window, floorBucket, retentionDays, batchSize] + ) + + const pruned = result.rowCount ?? 0 + if (pruned === 0) break + + totalPruned += pruned + batchNumber += 1 + price_aggregates_pruned_total.inc({ network }, pruned) + + log.info( + { network, pairKey: series.pairKey, window: series.window, batch: batchNumber, batchRows: pruned, totalPruned }, + 'pruned a batch of aggregate rows' + ) + onProgress?.({ network, pairKey: series.pairKey, window: series.window, batch: batchNumber, batchRows: pruned, totalPruned }) + + if (yieldFn) { + await yieldFn() + } else if (pauseMs > 0) { + await new Promise(resolve => setTimeout(resolve, pauseMs)) + } else { + await new Promise(resolve => setImmediate(resolve)) + } + } + + return { pruned: totalPruned, batches: batchNumber } +} + +/** + * Prune one network's aggregate rows, series by series. + * + * `keepRows` is a floor on what is retained, not a target: a series shorter than + * it is left completely alone, which is what keeps the route's answers identical + * for a pair that has stopped being refreshed. + */ +export async function pruneOldAggregates( + retentionDays: number = PRICE_AGGREGATES_RETENTION_DAYS, + network: NetworkName = activeNetwork, + batchSize: number = PRICE_AGGREGATES_PRUNE_BATCH_SIZE, + keepRows: number = PRICE_AGGREGATES_KEEP_ROWS, + pauseMs: number = DEFAULT_AGGREGATES_PRUNE_PAUSE_MS, + onProgress?: (progress: AggregatePruneProgress) => void, + yieldFn?: () => Promise +): Promise { + if (!Number.isFinite(retentionDays) || retentionDays < 0) { + throw new RangeError('Retention days must be a non-negative number') + } + if (!Number.isSafeInteger(batchSize) || batchSize <= 0) { + throw new RangeError('Price aggregates prune batch size must be a positive integer') + } + if (!Number.isSafeInteger(keepRows) || keepRows <= 0) { + throw new RangeError('Price aggregates keep rows must be a positive integer') + } + + const seriesList = await listAggregateSeries(network) + let pruned = 0 + let batches = 0 + let kept = 0 + + for (const series of seriesList) { + const floor = await readSeriesKeepFloor(network, series.pairKey, series.window, keepRows) + // No floor means fewer than `keepRows` rows exist: every one of them is + // inside the newest page the route could ask for. + if (!floor) { + kept += 1 + continue + } + const result = await pruneAggregateSeries( + network, + series, + floor, + retentionDays, + batchSize, + pauseMs, + onProgress, + yieldFn + ) + pruned += result.pruned + batches += result.batches + if (result.pruned === 0) kept += 1 + } + + if (pruned > 0) { + log.info( + { network, pruned, batches, series: seriesList.length, retentionDays, keepRows }, + 'pruned aggregate rows older than the retention window' + ) + } + + return { network, pruned, batches, series: seriesList.length, kept } +} + +/** + * Prune every network in `getEnabledNetworks()`. + * + * A failure on one network does not stop the others; the failures are collected + * and thrown together once every network has been tried, so a broken testnet + * prune cannot hide a mainnet one. + */ +export async function pruneAllAggregateNetworks( + retentionDays: number = PRICE_AGGREGATES_RETENTION_DAYS +): Promise>> { + const results: Partial> = {} + const errors: Error[] = [] + + for (const network of getEnabledNetworks()) { + try { + results[network] = await pruneOldAggregates(retentionDays, network) + } catch (err) { + errors.push(new Error(`${network}: ${(err as Error).message}`)) + } + } + + if (errors.length > 0) { + throw new AggregateError(errors, errors.map(e => e.message).join('; ')) + } + + return results +} + +export function startPriceAggregatesRetentionWorker() { + const worker = new Worker( + QUEUE_NAME, + async () => { + try { + const results = await pruneAllAggregateNetworks() + for (const [network, res] of Object.entries(results)) { + if (res && res.pruned > 0) { + log.info( + { network, pruned: res.pruned, retentionDays: PRICE_AGGREGATES_RETENTION_DAYS }, + 'price_aggregates retention run complete' + ) + } + } + } catch (err) { + log.error({ err }, 'price_aggregates prune failed') + } + }, + { connection: redisConnection(), concurrency: 1 } + ) + + worker.on('failed', (_job, err) => { + log.error({ err }, 'price_aggregates retention job failed') + }) + + return worker +} + +/** Schedules the retention prune to run hourly (and once on startup). */ +export async function schedulePriceAggregatesRetention(queue: Queue) { + await queue.add( + 'prune', + {}, + { repeat: { every: 60 * 60 * 1000 }, jobId: 'price-aggregates-retention:prune' } + ) + await queue.add('prune', {}) +} diff --git a/src/metrics.ts b/src/metrics.ts index 501b3314..dcfc8df3 100644 --- a/src/metrics.ts +++ b/src/metrics.ts @@ -106,6 +106,15 @@ export const price_points_rolled_up_total = new Counter({ registers: [register] }) +// Bounded like every other series here: one child per enabled network, so the +// retention job's progress is visible without an unbounded dimension. +export const price_aggregates_pruned_total = new Counter({ + name: 'price_aggregates_pruned_total', + help: 'Total number of aggregate rows pruned by the price_aggregates retention job', + labelNames: ['network'], + registers: [register] +}) + export const price_requests_total = new Counter({ name: 'price_requests_total', help: 'Total number of price API requests served',