From 0d7745dde8bb01061345d94b3d78088d55ce3473 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Thu, 3 Dec 2026 11:12:48 +0000 Subject: [PATCH 1/4] feat(cloud): receive retained backup growth reports --- .github/workflows/test.yml | 1 + .../0101_exomem_cloud_backup_growth.sql | 38 +++ src/app/api/cron/exomem-key-watcher/route.ts | 16 +- .../api/exomem/backup-growth/[token]/route.ts | 37 +++ ...backup-growth-postgres.integration.test.ts | 295 ++++++++++++++++++ src/lib/exomem-hosted/alert-receiver.ts | 7 +- .../exomem-hosted/backup-growth-receiver.ts | 280 +++++++++++++++++ src/lib/exomem-hosted/observability.ts | 2 + 8 files changed, 672 insertions(+), 4 deletions(-) create mode 100644 migrations/0101_exomem_cloud_backup_growth.sql create mode 100644 src/app/api/exomem/backup-growth/[token]/route.ts create mode 100644 src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts create mode 100644 src/lib/exomem-hosted/backup-growth-receiver.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index db0081cc..e901329e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -49,6 +49,7 @@ jobs: src/lib/exomem-hosted/__tests__/migration-runner.integration.test.ts src/lib/exomem-hosted/__tests__/postgres.integration.test.ts src/lib/exomem-hosted/__tests__/alert-receiver-postgres.integration.test.ts + src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/access-recovery.test.ts - name: Hosted Backup version-commit and lifecycle PostgreSQL authority, shared driver env: diff --git a/migrations/0101_exomem_cloud_backup_growth.sql b/migrations/0101_exomem_cloud_backup_growth.sql new file mode 100644 index 00000000..82c64e13 --- /dev/null +++ b/migrations/0101_exomem_cloud_backup_growth.sql @@ -0,0 +1,38 @@ +-- A claimed UUID can never open another window. Keep only the identity for old runs. +CREATE TABLE exomem_cloud_backup_growth_runs ( + run_id uuid PRIMARY KEY +); + +-- The singleton fences writers and holds the last accepted receipt across a successor's scan. +CREATE TABLE exomem_cloud_backup_growth_window ( + singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton), + run_id uuid REFERENCES exomem_cloud_backup_growth_runs (run_id), + opened_at timestamptz, + accepted_run_id uuid REFERENCES exomem_cloud_backup_growth_runs (run_id), + accepted_at timestamptz, + accepted_batch_count integer, + scan_complete boolean, + resume_after text CHECK (resume_after ~ '^[a-z2-7]{16}$'), + accepted_observed_through timestamptz, + crossed_count integer +); + +INSERT INTO exomem_cloud_backup_growth_window DEFAULT VALUES; + +-- A report updates operator state only after its complete set of batches arrives. +CREATE TABLE exomem_cloud_backup_growth_batches ( + ordinal integer PRIMARY KEY CHECK (ordinal > 0), + observations jsonb NOT NULL CHECK (jsonb_typeof(observations) = 'array') +); + +CREATE TABLE exomem_cloud_backup_growth_state ( + cell_id text COLLATE "C" PRIMARY KEY CHECK (cell_id ~ '^[a-z2-7]{16}$'), + retained_bytes bigint NOT NULL CHECK (retained_bytes >= 0), + ceiling_bytes bigint NOT NULL CHECK (ceiling_bytes > 0), + observed_from timestamptz NOT NULL, + observed_through timestamptz NOT NULL CHECK (observed_through >= observed_from), + active boolean NOT NULL CHECK (active = (retained_bytes > ceiling_bytes)) +); + +CREATE INDEX exomem_cloud_backup_growth_active + ON exomem_cloud_backup_growth_state (cell_id) WHERE active; diff --git a/src/app/api/cron/exomem-key-watcher/route.ts b/src/app/api/cron/exomem-key-watcher/route.ts index d76e1399..028dec53 100644 --- a/src/app/api/cron/exomem-key-watcher/route.ts +++ b/src/app/api/cron/exomem-key-watcher/route.ts @@ -1,4 +1,4 @@ -import { NextRequest, NextResponse } from "next/server"; +import { NextRequest, NextResponse, after } from "next/server"; import { verifyCronAuth } from "@/lib/hosted-backup/cron-auth"; import { emitAccessEvent, newRequestId } from "@/lib/exomem-hosted/http"; import { @@ -7,6 +7,7 @@ import { evaluateKeyWatcherHeartbeat, runAlertNotificationPass, } from "@/lib/exomem-hosted/alert-receiver"; +import { pruneExpiredBackupGrowthBatches } from "@/lib/exomem-hosted/backup-growth-receiver"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; @@ -25,6 +26,19 @@ export async function GET(req: NextRequest): Promise { emitAccessEvent({ event: "alerts.key_watcher.check", outcome: "denied", requestId, errorCode: "CRON_AUTH_REJECTED" }); return NextResponse.json({ success: false }, { status: 401, headers: { "cache-control": "no-store" } }); } + const logPruneFailure = () => { + emitAccessEvent({ + event: "alerts.backup_growth.prune", + outcome: "failed", + requestId, + errorCode: "BACKUP_GROWTH_PRUNE_UNAVAILABLE", + }); + }; + try { + after(() => pruneExpiredBackupGrowthBatches().catch(logPruneFailure)); + } catch { + logPruneFailure(); + } try { const heartbeat = await evaluateKeyWatcherHeartbeat(new Date()); if (!heartbeat.enabled) { diff --git a/src/app/api/exomem/backup-growth/[token]/route.ts b/src/app/api/exomem/backup-growth/[token]/route.ts new file mode 100644 index 00000000..57d23a07 --- /dev/null +++ b/src/app/api/exomem/backup-growth/[token]/route.ts @@ -0,0 +1,37 @@ +import { NextRequest, NextResponse } from "next/server"; +import { alertEndpointNotFound, verifyAlertToken } from "@/lib/exomem-hosted/alert-receiver"; +import { + BACKUP_GROWTH_MAX_BODY_BYTES, + receiveBackupGrowth, +} from "@/lib/exomem-hosted/backup-growth-receiver"; +import { newRequestId, readBoundedJsonRequest } from "@/lib/exomem-hosted/http"; +import { + capabilityEndpointNotFoundResponse, + safeErrorResponse, +} from "@/lib/exomem-hosted/next-error-response"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +export async function POST( + request: NextRequest, + { params }: { params: Promise<{ token: string }> } +): Promise { + const requestId = newRequestId(); + try { + const { token } = await params; + if (verifyAlertToken(token) !== "key-watcher") throw alertEndpointNotFound(); + const payload = await readBoundedJsonRequest(request, BACKUP_GROWTH_MAX_BODY_BYTES); + return NextResponse.json(await receiveBackupGrowth(payload), { + headers: { "cache-control": "no-store" }, + }); + } catch (error) { + return safeErrorResponse(error, requestId); + } +} + +export const GET = capabilityEndpointNotFoundResponse; +export const PUT = capabilityEndpointNotFoundResponse; +export const PATCH = capabilityEndpointNotFoundResponse; +export const DELETE = capabilityEndpointNotFoundResponse; +export const OPTIONS = capabilityEndpointNotFoundResponse; diff --git a/src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts new file mode 100644 index 00000000..d9ee863e --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts @@ -0,0 +1,295 @@ +import assert from "node:assert/strict"; +import { createHash, randomUUID } from "node:crypto"; +import { after, before, beforeEach, describe, it } from "node:test"; +import { NextRequest } from "next/server"; +import { Pool } from "pg"; +import { POST } from "@/app/api/exomem/backup-growth/[token]/route"; +import { closePgSqlPool } from "@/lib/db/pg-sql"; +import { applyMigrations } from "../../../../scripts/migrate"; +import { pruneExpiredBackupGrowthBatches } from "../backup-growth-receiver"; +import { __closeExomemTransactionPoolForTests } from "../db"; +import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; + +const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +const token = "growth-test-capability"; +const schedulerToken = "scheduler-test-capability"; +const firstCell = "2".repeat(16); +const secondCell = "a".repeat(16); +let pool: Pool; +let schema: string; + +function post(runId: string, action: Record, capability = token) { + const url = `http://localhost/api/exomem/backup-growth/${capability}`; + return POST( + new NextRequest(url, { + method: "POST", + body: JSON.stringify({ schema_version: 1, run_id: runId, ...action }), + }), + { params: Promise.resolve({ token: capability }) } + ); +} + +function measurement(cell_id: string, retained_bytes = "101") { + return { cell_id, retained_bytes, ceiling_bytes: "100" }; +} + +describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { + before(async () => { + schema = `backup_growth_it_${randomUUID().replaceAll("-", "")}`; + await ensureExomemPostgresTestExtensions(databaseUrl!); + const admin = new Pool({ connectionString: databaseUrl }); + await admin.query(`CREATE SCHEMA "${schema}"`); + await admin.end(); + const scoped = new URL(databaseUrl!); + scoped.searchParams.set("options", `-c search_path=${schema},public`); + await applyMigrations({ databaseUrl: scoped.toString() }); + pool = new Pool({ connectionString: scoped.toString() }); + process.env.DATABASE_URL = scoped.toString(); + process.env.EXOMEM_KEY_WATCHER_ALERT_TOKEN_SHA256 = createHash("sha256") + .update(token) + .digest("hex"); + process.env.EXOMEM_HOSTED_ALERT_TOKEN_SHA256 = createHash("sha256") + .update(schedulerToken) + .digest("hex"); + }); + + after(async () => { + await __closeExomemTransactionPoolForTests(); + await closePgSqlPool(); + await pool?.end(); + if (schema) { + const admin = new Pool({ connectionString: databaseUrl }); + await admin.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`); + await admin.end(); + } + }); + + beforeEach(async () => { + await pool.query(`TRUNCATE exomem_cloud_backup_growth_runs, exomem_cloud_backup_growth_window, + exomem_cloud_backup_growth_batches, exomem_cloud_backup_growth_state, + exomem_hosted_alert_transitions`); + await pool.query("INSERT INTO exomem_cloud_backup_growth_window DEFAULT VALUES"); + }); + + it("checks the key-watcher capability before reading a body and bounds valid bodies", async () => { + const oversizedBody = "x".repeat(256 * 1024 + 1); + async function send(capability: string) { + return POST( + new NextRequest("http://localhost/api/exomem/backup-growth/token", { + method: "POST", + body: oversizedBody, + headers: { "content-length": String(oversizedBody.length) }, + }), + { params: Promise.resolve({ token: capability }) } + ); + } + assert.equal((await send(schedulerToken)).status, 404); + assert.equal((await send(token)).status, 413); + assert.equal((await post(randomUUID(), { action: "open", extra: true })).status, 400); + }); + + it("fences an expired run, rejects incomplete and conflicting staging, and replays its accepted receipt", async () => { + const expired = randomUUID(); + const run = randomUUID(); + const successor = randomUUID(); + assert.equal((await post(expired, { action: "active", after: null })).status, 409); + assert.deepEqual(await (await post(expired, { action: "open" })).json(), { + success: true, + resume_after: null, + }); + assert.equal((await post(run, { action: "open" })).status, 409); + const firstBatch = { action: "batch", ordinal: 1, observations: [measurement(firstCell)] }; + assert.equal((await post(expired, firstBatch)).status, 200); + await pool.query(`UPDATE exomem_cloud_backup_growth_window + SET opened_at = clock_timestamp() - interval '16 minutes'`); + assert.equal((await post(expired, firstBatch)).status, 409); + await pruneExpiredBackupGrowthBatches(); + assert.deepEqual( + (await pool.query("SELECT ordinal FROM exomem_cloud_backup_growth_batches")).rows, + [] + ); + assert.equal((await post(run, { action: "open" })).status, 200); + assert.equal((await post(expired, { action: "open" })).status, 409); + assert.equal((await post(expired, { action: "active", after: null })).status, 409); + assert.deepEqual(await (await post(run, { action: "open" })).json(), { + success: true, + resume_after: null, + }); + const accept = { + action: "accept", + batch_count: 2, + complete: false, + resume_after: firstCell, + observed_through: new Date().toISOString(), + }; + assert.equal((await post(run, accept)).status, 409); + const secondBatch = { action: "batch", ordinal: 2, observations: [measurement(secondCell)] }; + assert.equal( + ( + await post(run, { + ...firstBatch, + observations: [measurement(firstCell, "9223372036854775808")], + }) + ).status, + 400 + ); + assert.equal( + ( + await post(run, { + ...firstBatch, + observations: [measurement(firstCell), measurement(firstCell)], + }) + ).status, + 409 + ); + assert.equal((await post(run, firstBatch)).status, 200); + assert.equal((await post(run, firstBatch)).status, 200); + assert.equal((await post(run, { ...secondBatch, ordinal: 1 })).status, 409); + assert.equal((await post(run, { ...firstBatch, ordinal: 2 })).status, 409); + assert.equal((await post(run, secondBatch)).status, 200); + await pruneExpiredBackupGrowthBatches(); + assert.equal((await post(run, { ...accept, batch_count: 1 })).status, 409); + assert.equal( + (await post(run, { ...accept, observed_through: "2000-01-01T00:00:00Z" })).status, + 400 + ); + assert.deepEqual(await (await post(run, { action: "active", after: null })).json(), { + success: true, + cells: [], + next_after: null, + }); + const receipt = { success: true, crossed_count: 2 }; + assert.deepEqual(await (await post(run, accept)).json(), receipt); + assert.deepEqual(await (await post(run, accept)).json(), receipt); + assert.equal((await post(run, { ...accept, complete: true })).status, 409); + assert.deepEqual(await (await post(successor, { action: "open" })).json(), { + success: true, + resume_after: firstCell, + }); + assert.deepEqual(await (await post(run, accept)).json(), receipt); + assert.equal((await post(expired, { ...accept, batch_count: 0 })).status, 409); + assert.deepEqual(await (await post(successor, { action: "active", after: null })).json(), { + success: true, + cells: [firstCell, secondCell], + next_after: null, + }); + assert.deepEqual(await (await post(successor, { action: "active", after: firstCell })).json(), { + success: true, + cells: [secondCell], + next_after: null, + }); + assert.equal( + (await post(successor, { ...firstBatch, observations: [measurement(firstCell, "100")] })) + .status, + 200 + ); + assert.deepEqual( + await ( + await post(successor, { + ...accept, + complete: true, + batch_count: 1, + resume_after: null, + observed_through: new Date().toISOString(), + }) + ).json(), + { success: true, crossed_count: 0 } + ); + assert.deepEqual( + ( + await pool.query( + "SELECT cell_id, active FROM exomem_cloud_backup_growth_state ORDER BY cell_id" + ) + ).rows, + [ + { cell_id: firstCell, active: false }, + { cell_id: secondCell, active: true }, + ] + ); + const { rows } = await pool.query( + "SELECT job, alert, notification_state FROM exomem_hosted_alert_transitions" + ); + assert.deepEqual(rows, [ + { job: "b2-key-watcher", alert: `BACKUP_GROWTH:${run}:2`, notification_state: "pending" }, + ]); + }); + + it("commits an empty report and advances the cursor without enqueueing an alert", async () => { + const run = randomUUID(); + const next = randomUUID(); + assert.equal((await post(run, { action: "open" })).status, 200); + assert.deepEqual( + await ( + await post(run, { + action: "accept", + batch_count: 0, + complete: false, + resume_after: firstCell, + observed_through: new Date().toISOString(), + }) + ).json(), + { success: true, crossed_count: 0 } + ); + assert.deepEqual(await (await post(next, { action: "open" })).json(), { + success: true, + resume_after: firstCell, + }); + assert.deepEqual( + (await pool.query("SELECT transition_id FROM exomem_hosted_alert_transitions")).rows, + [] + ); + }); + + it("accepts and pages the maximum-size report within the ten-second request budget", async (t) => { + const run = randomUUID(); + assert.equal((await post(run, { action: "open" })).status, 200); + const alphabet = "234567abcdefghijklmnopqrstuvwxyz"; + const cells = Array.from({ length: 20_000 }, (_, index) => { + const suffix = [10, 5, 0].map((shift) => alphabet[(index >> shift) & 31]).join(""); + return `b${"2".repeat(12)}${suffix}`; + }); + await pool.query( + `INSERT INTO exomem_cloud_backup_growth_state + (cell_id, retained_bytes, ceiling_bytes, observed_from, observed_through, active) + SELECT cell_id, 101, 100, now(), now(), true FROM unnest($1::text[]) AS cell_id`, + [cells.slice(0, 10_000)] + ); + for (let ordinal = 1; ordinal <= 20; ordinal++) { + const observations = cells + .slice((ordinal - 1) * 1000, ordinal * 1000) + .map((cellId) => measurement(cellId, "9223372036854775807")); + assert.equal((await post(run, { action: "batch", ordinal, observations })).status, 200); + } + const started = performance.now(); + const response = await post(run, { + action: "accept", + batch_count: 20, + complete: true, + resume_after: null, + observed_through: new Date().toISOString(), + }); + const elapsed = performance.now() - started; + t.diagnostic(`20,000-cell acceptance took ${elapsed.toFixed(1)} ms`); + assert.ok(elapsed < 10_000); + assert.deepEqual(await response.json(), { success: true, crossed_count: 10_000 }); + const { rows } = await pool.query( + "SELECT count(*)::int AS count FROM exomem_hosted_alert_transitions" + ); + assert.deepEqual(rows, [{ count: 1 }]); + const next = randomUUID(); + assert.deepEqual(await (await post(next, { action: "open" })).json(), { + success: true, + resume_after: null, + }); + assert.deepEqual(await (await post(next, { action: "active", after: null })).json(), { + success: true, + cells: cells.slice(0, 1000), + next_after: cells[999], + }); + assert.deepEqual(await (await post(next, { action: "active", after: cells[19_998] })).json(), { + success: true, + cells: [cells[19_999]], + next_after: null, + }); + }); +}); diff --git a/src/lib/exomem-hosted/alert-receiver.ts b/src/lib/exomem-hosted/alert-receiver.ts index 08ee4404..e2111c2e 100644 --- a/src/lib/exomem-hosted/alert-receiver.ts +++ b/src/lib/exomem-hosted/alert-receiver.ts @@ -1,7 +1,7 @@ import { createHash, timingSafeEqual } from "node:crypto"; import { sendTransactionalEmail } from "@/lib/brevo"; import { EXOMEM_SENDER } from "@/lib/exomem-hosted/mail-sender"; -import { executeExomemSql } from "./db"; +import { executeExomemSql, type ExomemSql } from "./db"; import { alertEndpointNotFound, ExomemHostedError } from "./errors"; /** The K3s scheduler alert sender is a fixed contract we do not control. @@ -200,9 +200,10 @@ export function parseAlertTransition(payload: unknown, headerTransitionId: strin * caller must run the notification pass either way. */ export async function recordAlertTransition( - transition: AlertTransition + transition: AlertTransition, + sql: ExomemSql = executeExomemSql ): Promise<{ accepted: boolean }> { - const { rows } = await executeExomemSql` + const { rows } = await sql` /* exomem:record-alert-transition */ INSERT INTO exomem_hosted_alert_transitions (transition_id, job, alert, active) VALUES (${transition.transitionId}, ${transition.job}, ${transition.alert}, ${transition.active}) diff --git a/src/lib/exomem-hosted/backup-growth-receiver.ts b/src/lib/exomem-hosted/backup-growth-receiver.ts new file mode 100644 index 00000000..e4fb5631 --- /dev/null +++ b/src/lib/exomem-hosted/backup-growth-receiver.ts @@ -0,0 +1,280 @@ +import { z } from "zod"; +import { KEY_WATCHER_JOB, recordAlertTransition, storedTransitionId } from "./alert-receiver"; +import { CLOUD_CELL_ID_PATTERN } from "./cloud-config"; +import { + createExomemWaitBudget, + executeExomemSql, + withExomemTransaction, + type ExomemSql, +} from "./db"; +import { exomemErrors, ExomemHostedError } from "./errors"; + +export const BACKUP_GROWTH_MAX_BODY_BYTES = 256 * 1024; +const MAX_BATCHES = 20; +const PAGE_SIZE = 1000; +const LEASE_SECONDS = 15 * 60; +const MAX_SIGNED_BIGINT = BigInt("9223372036854775807"); + +const cellId = z.string().regex(CLOUD_CELL_ID_PATTERN); +const byteCount = z + .string() + .refine((value) => /^(?:0|[1-9][0-9]{0,18})$/.test(value) && BigInt(value) <= MAX_SIGNED_BIGINT); +const observedThrough = z.iso + .datetime({ offset: true }) + .regex(/T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|\+00:00)$/); +const report = { + schema_version: z.literal(1), + run_id: z.uuid().transform((value) => value.toLowerCase()), +}; +const requestSchema = z.discriminatedUnion("action", [ + z.strictObject({ ...report, action: z.literal("open") }), + z.strictObject({ ...report, action: z.literal("active"), after: cellId.nullable() }), + z.strictObject({ + ...report, + action: z.literal("batch"), + ordinal: z.number().int().min(1).max(MAX_BATCHES), + observations: z + .array( + z.strictObject({ + cell_id: cellId, + retained_bytes: byteCount, + ceiling_bytes: byteCount.refine((value) => value !== "0"), + }) + ) + .min(1) + .max(PAGE_SIZE), + }), + z.strictObject({ + ...report, + action: z.literal("accept"), + batch_count: z.number().int().min(0).max(MAX_BATCHES), + complete: z.boolean(), + resume_after: cellId.nullable(), + observed_through: observedThrough, + }), +]); + +type GrowthRequest = z.output; +type GrowthWindow = { + run_id: string | null; + accepted_run_id: string | null; + accepted_batch_count: number | null; + scan_complete: boolean | null; + resume_after: string | null; + crossed_count: number; + live: boolean; + through_in_window: boolean; + same_through: boolean; +}; + +function windowClosed() { + return new ExomemHostedError({ + code: "BACKUP_GROWTH_WINDOW_CLOSED", + status: 409, + message: "start the report with a fresh run ID", + }); +} + +function reportConflict() { + return new ExomemHostedError({ + code: "BACKUP_GROWTH_REPORT_CONFLICT", + status: 409, + message: "retry with the original payload and every declared batch", + }); +} + +async function lockWindow(tx: ExomemSql, observedThrough: string | null): Promise { + // Read the database clock after acquiring the lock, so a queued request cannot use an expired lease. + const { rows } = await tx` + WITH locked AS MATERIALIZED ( + SELECT * FROM exomem_cloud_backup_growth_window WHERE singleton FOR UPDATE + ) + SELECT *, checked_at < opened_at + make_interval(secs => ${LEASE_SECONDS}) AS live, + ${observedThrough}::timestamptz BETWEEN opened_at - interval '30 seconds' + AND checked_at + interval '30 seconds' + AS through_in_window, + ${observedThrough}::timestamptz = accepted_observed_through AS same_through + FROM (SELECT *, clock_timestamp() AS checked_at FROM locked) AS checked + `; + return rows[0] as unknown as GrowthWindow; +} + +async function openWindow(tx: ExomemSql, window: GrowthWindow, runId: string) { + const committed = window.run_id === window.accepted_run_id; + if (window.run_id === runId) { + if (!window.live && !committed) throw windowClosed(); + } else { + if (window.live && !committed) { + throw new ExomemHostedError({ + code: "BACKUP_GROWTH_WINDOW_BUSY", + status: 409, + message: "retry when the current report completes or its lease expires", + retryable: true, + }); + } + const claimed = await tx` + INSERT INTO exomem_cloud_backup_growth_runs (run_id) VALUES (${runId}) + ON CONFLICT DO NOTHING RETURNING run_id + `; + if (claimed.rows.length === 0) throw windowClosed(); + await tx`DELETE FROM exomem_cloud_backup_growth_batches`; + await tx` + UPDATE exomem_cloud_backup_growth_window SET run_id = ${runId}, opened_at = clock_timestamp() + WHERE singleton + `; + } + return { success: true, resume_after: window.resume_after }; +} + +async function activePage(tx: ExomemSql, after: string | null) { + const { rows } = await tx` + SELECT cell_id FROM exomem_cloud_backup_growth_state + WHERE active AND cell_id > coalesce(${after}::text, '') + ORDER BY cell_id LIMIT ${PAGE_SIZE + 1} + `; + const cells = rows.slice(0, PAGE_SIZE).map((row) => row.cell_id as string); + return { success: true, cells, next_after: rows.length > PAGE_SIZE ? cells.at(-1)! : null }; +} + +async function stageBatch( + tx: ExomemSql, + input: Extract, + committed: boolean +) { + const cellIds = input.observations.map((observation) => observation.cell_id); + if (new Set(cellIds).size !== cellIds.length) throw reportConflict(); + const body = JSON.stringify(input.observations); + const existing = await tx` + SELECT observations = ${body}::jsonb AS same + FROM exomem_cloud_backup_growth_batches WHERE ordinal = ${input.ordinal} + `; + if (existing.rows.length > 0) { + if (existing.rows[0].same !== true) throw reportConflict(); + return { success: true }; + } + if (committed) throw windowClosed(); + const inserted = await tx` + INSERT INTO exomem_cloud_backup_growth_batches (ordinal, observations) + SELECT ${input.ordinal}, ${body}::jsonb + WHERE NOT EXISTS ( + SELECT 1 FROM exomem_cloud_backup_growth_batches AS batch + CROSS JOIN LATERAL jsonb_to_recordset(batch.observations) AS previous(cell_id text) + WHERE previous.cell_id = ANY(${cellIds}::text[]) + ) + RETURNING ordinal + `; + if (inserted.rows.length === 0) throw reportConflict(); + return { success: true }; +} + +async function acceptReport( + tx: ExomemSql, + window: GrowthWindow, + input: Extract +) { + if (window.accepted_run_id === input.run_id) { + if ( + !window.same_through || + window.accepted_batch_count !== input.batch_count || + window.scan_complete !== input.complete || + window.resume_after !== input.resume_after + ) + throw reportConflict(); + return { success: true, crossed_count: window.crossed_count }; + } + if (window.run_id !== input.run_id || !window.live) throw windowClosed(); + if (!window.through_in_window) throw exomemErrors.invalidRequest(); + const staged = await tx` + SELECT count(*) = ${input.batch_count} AND coalesce(max(ordinal), 0) = ${input.batch_count} AS ready + FROM exomem_cloud_backup_growth_batches + `; + if (staged.rows[0].ready !== true) throw reportConflict(); + + // Accept up to 30 seconds of sender/receiver clock skew. Keep the reported timestamp + // in the receipt and use the opening instant as the lower bound for each observation. + const { rows } = await tx` + WITH measured AS MATERIALIZED ( + SELECT measurement.*, retained_bytes > ceiling_bytes AS active + FROM exomem_cloud_backup_growth_batches AS batch + CROSS JOIN LATERAL jsonb_to_recordset(batch.observations) + AS measurement(cell_id text, retained_bytes bigint, ceiling_bytes bigint) + ), applied AS ( + INSERT INTO exomem_cloud_backup_growth_state ( + cell_id, retained_bytes, ceiling_bytes, observed_from, observed_through, active + ) + SELECT cell_id, retained_bytes, ceiling_bytes, opened_at, + greatest(opened_at, ${input.observed_through}::timestamptz), active + FROM measured CROSS JOIN exomem_cloud_backup_growth_window WHERE singleton + ON CONFLICT (cell_id) DO UPDATE SET + retained_bytes = excluded.retained_bytes, + ceiling_bytes = excluded.ceiling_bytes, + observed_from = excluded.observed_from, + observed_through = excluded.observed_through, + active = excluded.active + ) + SELECT count(*)::int AS crossed_count + FROM measured LEFT JOIN exomem_cloud_backup_growth_state AS before USING (cell_id) + WHERE measured.active AND before.active IS DISTINCT FROM true + `; + const crossedCount = rows[0].crossed_count as number; + await tx` + UPDATE exomem_cloud_backup_growth_window + SET accepted_run_id = run_id, accepted_at = clock_timestamp(), + accepted_batch_count = ${input.batch_count}, + scan_complete = ${input.complete}, resume_after = ${input.resume_after}, + accepted_observed_through = ${input.observed_through}, crossed_count = ${crossedCount} + WHERE singleton + `; + if (crossedCount > 0) { + await recordAlertTransition( + { + transitionId: storedTransitionId(KEY_WATCHER_JOB, `backup-growth:${input.run_id}`), + job: KEY_WATCHER_JOB, + // Each accepted run has a distinct summary and must pass normal repeat suppression. + alert: `BACKUP_GROWTH:${input.run_id}:${crossedCount}`, + active: true, + }, + tx + ); + } + return { success: true, crossed_count: crossedCount }; +} + +export async function receiveBackupGrowth(payload: unknown) { + const validated = requestSchema.safeParse(payload); + if (!validated.success) throw exomemErrors.invalidRequest(); + const input = validated.data; + const budget = createExomemWaitBudget({ + lockTimeoutMs: 1000, + statementTimeoutMs: 4000, + signal: AbortSignal.timeout(8000), + }); + return budget.run(() => + withExomemTransaction(async (tx) => { + const window = await lockWindow( + tx, + input.action === "accept" ? input.observed_through : null + ); + if (input.action === "open") return openWindow(tx, window, input.run_id); + if (input.action === "accept") return acceptReport(tx, window, input); + const committed = window.run_id === window.accepted_run_id; + if (window.run_id !== input.run_id || (!window.live && !committed)) throw windowClosed(); + if (input.action === "batch") return stageBatch(tx, input, committed); + if (committed) throw windowClosed(); + return activePage(tx, input.after); + }) + ); +} + +/** The daily watcher check reclaims an expired stage even if no successor opens. */ +export async function pruneExpiredBackupGrowthBatches(): Promise { + await executeExomemSql` + WITH locked AS MATERIALIZED ( + SELECT run_id, accepted_run_id, opened_at + FROM exomem_cloud_backup_growth_window WHERE singleton FOR UPDATE SKIP LOCKED + ) + DELETE FROM exomem_cloud_backup_growth_batches USING locked + WHERE locked.run_id IS DISTINCT FROM locked.accepted_run_id + AND locked.opened_at + make_interval(secs => ${LEASE_SECONDS}) <= clock_timestamp() + `; +} diff --git a/src/lib/exomem-hosted/observability.ts b/src/lib/exomem-hosted/observability.ts index 476f69d7..f5b6053c 100644 --- a/src/lib/exomem-hosted/observability.ts +++ b/src/lib/exomem-hosted/observability.ts @@ -30,6 +30,7 @@ const EVENT_NAMES = new Set([ "alerts.notification.failed", "alerts.backlog.undelivered", "alerts.key_watcher.check", + "alerts.backup_growth.prune", "whats_new_digest.select", "whats_new_digest.owner_turned_on", "exomem.cell-deletions.read", @@ -86,6 +87,7 @@ const ERROR_CODES = new Set([ "CRON_AUTH_REJECTED", "KEY_WATCHER_NOT_CONFIGURED", "KEY_WATCHER_CHECK_UNAVAILABLE", + "BACKUP_GROWTH_PRUNE_UNAVAILABLE", "WHATS_NEW_DIGEST_RUN_FAILED", "WHATS_NEW_RELEASES_NOT_READ", "WHATS_NEW_GITHUB_NOT_CONFIGURED", From 979bf17c612cc84d6ad4a82c0f60666355190e81 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Thu, 3 Dec 2026 11:18:17 +0000 Subject: [PATCH 2/4] fix(cloud): retain growth report coverage and identity --- .../0101_exomem_cloud_backup_growth.sql | 5 +++ ...backup-growth-postgres.integration.test.ts | 35 +++++++++++++++---- .../exomem-hosted/backup-growth-receiver.ts | 21 ++++++++--- 3 files changed, 50 insertions(+), 11 deletions(-) diff --git a/migrations/0101_exomem_cloud_backup_growth.sql b/migrations/0101_exomem_cloud_backup_growth.sql index 82c64e13..4e1a3be8 100644 --- a/migrations/0101_exomem_cloud_backup_growth.sql +++ b/migrations/0101_exomem_cloud_backup_growth.sql @@ -12,6 +12,7 @@ CREATE TABLE exomem_cloud_backup_growth_window ( accepted_at timestamptz, accepted_batch_count integer, scan_complete boolean, + scan_has_gaps boolean NOT NULL DEFAULT false, resume_after text CHECK (resume_after ~ '^[a-z2-7]{16}$'), accepted_observed_through timestamptz, crossed_count integer @@ -31,8 +32,12 @@ CREATE TABLE exomem_cloud_backup_growth_state ( ceiling_bytes bigint NOT NULL CHECK (ceiling_bytes > 0), observed_from timestamptz NOT NULL, observed_through timestamptz NOT NULL CHECK (observed_through >= observed_from), + last_run_id uuid NOT NULL REFERENCES exomem_cloud_backup_growth_runs (run_id), active boolean NOT NULL CHECK (active = (retained_bytes > ceiling_bytes)) ); CREATE INDEX exomem_cloud_backup_growth_active ON exomem_cloud_backup_growth_state (cell_id) WHERE active; + +CREATE INDEX exomem_cloud_backup_growth_active_run + ON exomem_cloud_backup_growth_state (last_run_id, cell_id) WHERE active; diff --git a/src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts index d9ee863e..0632a1d2 100644 --- a/src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts @@ -96,6 +96,7 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { assert.deepEqual(await (await post(expired, { action: "open" })).json(), { success: true, resume_after: null, + prior_gaps: false, }); assert.equal((await post(run, { action: "open" })).status, 409); const firstBatch = { action: "batch", ordinal: 1, observations: [measurement(firstCell)] }; @@ -114,11 +115,13 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { assert.deepEqual(await (await post(run, { action: "open" })).json(), { success: true, resume_after: null, + prior_gaps: false, }); const accept = { action: "accept", batch_count: 2, complete: false, + has_gaps: false, resume_after: firstCell, observed_through: new Date().toISOString(), }; @@ -165,6 +168,7 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { assert.deepEqual(await (await post(successor, { action: "open" })).json(), { success: true, resume_after: firstCell, + prior_gaps: false, }); assert.deepEqual(await (await post(run, accept)).json(), receipt); assert.equal((await post(expired, { ...accept, batch_count: 0 })).status, 409); @@ -198,12 +202,12 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { assert.deepEqual( ( await pool.query( - "SELECT cell_id, active FROM exomem_cloud_backup_growth_state ORDER BY cell_id" + "SELECT cell_id, active, last_run_id FROM exomem_cloud_backup_growth_state ORDER BY cell_id" ) ).rows, [ - { cell_id: firstCell, active: false }, - { cell_id: secondCell, active: true }, + { cell_id: firstCell, active: false, last_run_id: successor }, + { cell_id: secondCell, active: true, last_run_id: run }, ] ); const { rows } = await pool.query( @@ -214,7 +218,7 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { ]); }); - it("commits an empty report and advances the cursor without enqueueing an alert", async () => { + it("preserves an earlier coverage gap at the wrap without enqueueing an alert", async () => { const run = randomUUID(); const next = randomUUID(); assert.equal((await post(run, { action: "open" })).status, 200); @@ -224,6 +228,7 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { action: "accept", batch_count: 0, complete: false, + has_gaps: true, resume_after: firstCell, observed_through: new Date().toISOString(), }) @@ -233,6 +238,20 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { assert.deepEqual(await (await post(next, { action: "open" })).json(), { success: true, resume_after: firstCell, + prior_gaps: true, + }); + const wrap = { + action: "accept", + batch_count: 0, + resume_after: null, + observed_through: new Date().toISOString(), + }; + assert.equal((await post(next, { ...wrap, complete: true, has_gaps: false })).status, 409); + assert.equal((await post(next, { ...wrap, complete: false, has_gaps: true })).status, 200); + assert.deepEqual(await (await post(randomUUID(), { action: "open" })).json(), { + success: true, + resume_after: null, + prior_gaps: false, }); assert.deepEqual( (await pool.query("SELECT transition_id FROM exomem_hosted_alert_transitions")).rows, @@ -250,9 +269,9 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { }); await pool.query( `INSERT INTO exomem_cloud_backup_growth_state - (cell_id, retained_bytes, ceiling_bytes, observed_from, observed_through, active) - SELECT cell_id, 101, 100, now(), now(), true FROM unnest($1::text[]) AS cell_id`, - [cells.slice(0, 10_000)] + (cell_id, retained_bytes, ceiling_bytes, observed_from, observed_through, last_run_id, active) + SELECT cell_id, 101, 100, now(), now(), $2, true FROM unnest($1::text[]) AS cell_id`, + [cells.slice(0, 10_000), run] ); for (let ordinal = 1; ordinal <= 20; ordinal++) { const observations = cells @@ -265,6 +284,7 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { action: "accept", batch_count: 20, complete: true, + has_gaps: false, resume_after: null, observed_through: new Date().toISOString(), }); @@ -280,6 +300,7 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { assert.deepEqual(await (await post(next, { action: "open" })).json(), { success: true, resume_after: null, + prior_gaps: false, }); assert.deepEqual(await (await post(next, { action: "active", after: null })).json(), { success: true, diff --git a/src/lib/exomem-hosted/backup-growth-receiver.ts b/src/lib/exomem-hosted/backup-growth-receiver.ts index e4fb5631..c04d3a4d 100644 --- a/src/lib/exomem-hosted/backup-growth-receiver.ts +++ b/src/lib/exomem-hosted/backup-growth-receiver.ts @@ -49,6 +49,7 @@ const requestSchema = z.discriminatedUnion("action", [ action: z.literal("accept"), batch_count: z.number().int().min(0).max(MAX_BATCHES), complete: z.boolean(), + has_gaps: z.boolean(), resume_after: cellId.nullable(), observed_through: observedThrough, }), @@ -60,6 +61,7 @@ type GrowthWindow = { accepted_run_id: string | null; accepted_batch_count: number | null; scan_complete: boolean | null; + scan_has_gaps: boolean; resume_after: string | null; crossed_count: number; live: boolean; @@ -123,7 +125,11 @@ async function openWindow(tx: ExomemSql, window: GrowthWindow, runId: string) { WHERE singleton `; } - return { success: true, resume_after: window.resume_after }; + return { + success: true, + resume_after: window.resume_after, + prior_gaps: window.resume_after !== null && window.scan_has_gaps, + }; } async function activePage(tx: ExomemSql, after: string | null) { @@ -177,6 +183,7 @@ async function acceptReport( !window.same_through || window.accepted_batch_count !== input.batch_count || window.scan_complete !== input.complete || + window.scan_has_gaps !== input.has_gaps || window.resume_after !== input.resume_after ) throw reportConflict(); @@ -184,6 +191,11 @@ async function acceptReport( } if (window.run_id !== input.run_id || !window.live) throw windowClosed(); if (!window.through_in_window) throw exomemErrors.invalidRequest(); + if ( + input.complete !== (input.resume_after === null && !input.has_gaps) || + (window.resume_after !== null && window.scan_has_gaps && !input.has_gaps) + ) + throw reportConflict(); const staged = await tx` SELECT count(*) = ${input.batch_count} AND coalesce(max(ordinal), 0) = ${input.batch_count} AS ready FROM exomem_cloud_backup_growth_batches @@ -200,16 +212,17 @@ async function acceptReport( AS measurement(cell_id text, retained_bytes bigint, ceiling_bytes bigint) ), applied AS ( INSERT INTO exomem_cloud_backup_growth_state ( - cell_id, retained_bytes, ceiling_bytes, observed_from, observed_through, active + cell_id, retained_bytes, ceiling_bytes, observed_from, observed_through, last_run_id, active ) SELECT cell_id, retained_bytes, ceiling_bytes, opened_at, - greatest(opened_at, ${input.observed_through}::timestamptz), active + greatest(opened_at, ${input.observed_through}::timestamptz), run_id, active FROM measured CROSS JOIN exomem_cloud_backup_growth_window WHERE singleton ON CONFLICT (cell_id) DO UPDATE SET retained_bytes = excluded.retained_bytes, ceiling_bytes = excluded.ceiling_bytes, observed_from = excluded.observed_from, observed_through = excluded.observed_through, + last_run_id = excluded.last_run_id, active = excluded.active ) SELECT count(*)::int AS crossed_count @@ -221,7 +234,7 @@ async function acceptReport( UPDATE exomem_cloud_backup_growth_window SET accepted_run_id = run_id, accepted_at = clock_timestamp(), accepted_batch_count = ${input.batch_count}, - scan_complete = ${input.complete}, resume_after = ${input.resume_after}, + scan_complete = ${input.complete}, scan_has_gaps = ${input.has_gaps}, resume_after = ${input.resume_after}, accepted_observed_through = ${input.observed_through}, crossed_count = ${crossedCount} WHERE singleton `; From 0bf8184645001a82c75ae45c1736c6c13cb49421 Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Thu, 3 Dec 2026 11:21:48 +0000 Subject: [PATCH 3/4] fix(cloud): preserve the evidence behind growth alerts --- .../0101_exomem_cloud_backup_growth.sql | 13 +++++++--- ...backup-growth-postgres.integration.test.ts | 26 ++++++++++++++----- .../exomem-hosted/backup-growth-receiver.ts | 23 ++++++++++------ 3 files changed, 45 insertions(+), 17 deletions(-) diff --git a/migrations/0101_exomem_cloud_backup_growth.sql b/migrations/0101_exomem_cloud_backup_growth.sql index 4e1a3be8..33027b71 100644 --- a/migrations/0101_exomem_cloud_backup_growth.sql +++ b/migrations/0101_exomem_cloud_backup_growth.sql @@ -32,12 +32,19 @@ CREATE TABLE exomem_cloud_backup_growth_state ( ceiling_bytes bigint NOT NULL CHECK (ceiling_bytes > 0), observed_from timestamptz NOT NULL, observed_through timestamptz NOT NULL CHECK (observed_through >= observed_from), - last_run_id uuid NOT NULL REFERENCES exomem_cloud_backup_growth_runs (run_id), active boolean NOT NULL CHECK (active = (retained_bytes > ceiling_bytes)) ); CREATE INDEX exomem_cloud_backup_growth_active ON exomem_cloud_backup_growth_state (cell_id) WHERE active; -CREATE INDEX exomem_cloud_backup_growth_active_run - ON exomem_cloud_backup_growth_state (last_run_id, cell_id) WHERE active; +-- Later observations can replace state before an alert is delivered. Keep each alert's crossing evidence. +CREATE TABLE exomem_cloud_backup_growth_crossings ( + run_id uuid NOT NULL REFERENCES exomem_cloud_backup_growth_runs (run_id), + cell_id text COLLATE "C" NOT NULL, + retained_bytes bigint NOT NULL CHECK (retained_bytes > ceiling_bytes), + ceiling_bytes bigint NOT NULL CHECK (ceiling_bytes > 0), + observed_from timestamptz NOT NULL, + observed_through timestamptz NOT NULL CHECK (observed_through >= observed_from), + PRIMARY KEY (run_id, cell_id) +); diff --git a/src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts index 0632a1d2..eff8419d 100644 --- a/src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts @@ -67,6 +67,7 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { beforeEach(async () => { await pool.query(`TRUNCATE exomem_cloud_backup_growth_runs, exomem_cloud_backup_growth_window, exomem_cloud_backup_growth_batches, exomem_cloud_backup_growth_state, + exomem_cloud_backup_growth_crossings, exomem_hosted_alert_transitions`); await pool.query("INSERT INTO exomem_cloud_backup_growth_window DEFAULT VALUES"); }); @@ -202,12 +203,25 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { assert.deepEqual( ( await pool.query( - "SELECT cell_id, active, last_run_id FROM exomem_cloud_backup_growth_state ORDER BY cell_id" + "SELECT cell_id, active FROM exomem_cloud_backup_growth_state ORDER BY cell_id" ) ).rows, [ - { cell_id: firstCell, active: false, last_run_id: successor }, - { cell_id: secondCell, active: true, last_run_id: run }, + { cell_id: firstCell, active: false }, + { cell_id: secondCell, active: true }, + ] + ); + assert.deepEqual( + ( + await pool.query( + `SELECT cell_id, retained_bytes, ceiling_bytes FROM exomem_cloud_backup_growth_crossings + WHERE run_id = $1 ORDER BY cell_id`, + [run] + ) + ).rows, + [ + { cell_id: firstCell, retained_bytes: "101", ceiling_bytes: "100" }, + { cell_id: secondCell, retained_bytes: "101", ceiling_bytes: "100" }, ] ); const { rows } = await pool.query( @@ -269,9 +283,9 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { }); await pool.query( `INSERT INTO exomem_cloud_backup_growth_state - (cell_id, retained_bytes, ceiling_bytes, observed_from, observed_through, last_run_id, active) - SELECT cell_id, 101, 100, now(), now(), $2, true FROM unnest($1::text[]) AS cell_id`, - [cells.slice(0, 10_000), run] + (cell_id, retained_bytes, ceiling_bytes, observed_from, observed_through, active) + SELECT cell_id, 101, 100, now(), now(), true FROM unnest($1::text[]) AS cell_id`, + [cells.slice(0, 10_000)] ); for (let ordinal = 1; ordinal <= 20; ordinal++) { const observations = cells diff --git a/src/lib/exomem-hosted/backup-growth-receiver.ts b/src/lib/exomem-hosted/backup-growth-receiver.ts index c04d3a4d..79cccee0 100644 --- a/src/lib/exomem-hosted/backup-growth-receiver.ts +++ b/src/lib/exomem-hosted/backup-growth-receiver.ts @@ -206,28 +206,35 @@ async function acceptReport( // in the receipt and use the opening instant as the lower bound for each observation. const { rows } = await tx` WITH measured AS MATERIALIZED ( - SELECT measurement.*, retained_bytes > ceiling_bytes AS active + SELECT measurement.*, retained_bytes > ceiling_bytes AS active, run_id, + opened_at AS observed_from, greatest(opened_at, ${input.observed_through}::timestamptz) AS observed_through FROM exomem_cloud_backup_growth_batches AS batch CROSS JOIN LATERAL jsonb_to_recordset(batch.observations) AS measurement(cell_id text, retained_bytes bigint, ceiling_bytes bigint) + CROSS JOIN exomem_cloud_backup_growth_window WHERE singleton ), applied AS ( INSERT INTO exomem_cloud_backup_growth_state ( - cell_id, retained_bytes, ceiling_bytes, observed_from, observed_through, last_run_id, active + cell_id, retained_bytes, ceiling_bytes, observed_from, observed_through, active ) - SELECT cell_id, retained_bytes, ceiling_bytes, opened_at, - greatest(opened_at, ${input.observed_through}::timestamptz), run_id, active - FROM measured CROSS JOIN exomem_cloud_backup_growth_window WHERE singleton + SELECT cell_id, retained_bytes, ceiling_bytes, observed_from, observed_through, active FROM measured ON CONFLICT (cell_id) DO UPDATE SET retained_bytes = excluded.retained_bytes, ceiling_bytes = excluded.ceiling_bytes, observed_from = excluded.observed_from, observed_through = excluded.observed_through, - last_run_id = excluded.last_run_id, active = excluded.active + ), crossings AS ( + INSERT INTO exomem_cloud_backup_growth_crossings ( + run_id, cell_id, retained_bytes, ceiling_bytes, observed_from, observed_through + ) + SELECT measured.run_id, measured.cell_id, measured.retained_bytes, measured.ceiling_bytes, + measured.observed_from, measured.observed_through + FROM measured LEFT JOIN exomem_cloud_backup_growth_state AS before USING (cell_id) + WHERE measured.active AND before.active IS DISTINCT FROM true + RETURNING 1 ) SELECT count(*)::int AS crossed_count - FROM measured LEFT JOIN exomem_cloud_backup_growth_state AS before USING (cell_id) - WHERE measured.active AND before.active IS DISTINCT FROM true + FROM crossings `; const crossedCount = rows[0].crossed_count as number; await tx` From 11e4f861feffaa45375b2bc1fd6ca509ce4b71fe Mon Sep 17 00:00:00 2001 From: Artexis10 Date: Thu, 3 Dec 2026 11:42:54 +0000 Subject: [PATCH 4/4] fix: bound concurrent backup growth reports --- ...backup-growth-postgres.integration.test.ts | 47 +++++++++++++- .../exomem-hosted/backup-growth-receiver.ts | 61 +++++++++++++------ src/lib/exomem-hosted/rate-limit.ts | 6 ++ 3 files changed, 94 insertions(+), 20 deletions(-) diff --git a/src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts index eff8419d..ef20b8d5 100644 --- a/src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/backup-growth-postgres.integration.test.ts @@ -6,8 +6,10 @@ import { Pool } from "pg"; import { POST } from "@/app/api/exomem/backup-growth/[token]/route"; import { closePgSqlPool } from "@/lib/db/pg-sql"; import { applyMigrations } from "../../../../scripts/migrate"; +import { KEY_WATCHER_JOB } from "../alert-receiver"; import { pruneExpiredBackupGrowthBatches } from "../backup-growth-receiver"; import { __closeExomemTransactionPoolForTests } from "../db"; +import { EXOMEM_RATE_LIMITS, hashRateLimitKey } from "../rate-limit"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; @@ -45,6 +47,7 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { await applyMigrations({ databaseUrl: scoped.toString() }); pool = new Pool({ connectionString: scoped.toString() }); process.env.DATABASE_URL = scoped.toString(); + process.env.EXOMEM_CONTROL_PLANE_KEY = Buffer.alloc(32, 1).toString("base64url"); process.env.EXOMEM_KEY_WATCHER_ALERT_TOKEN_SHA256 = createHash("sha256") .update(token) .digest("hex"); @@ -68,7 +71,7 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { await pool.query(`TRUNCATE exomem_cloud_backup_growth_runs, exomem_cloud_backup_growth_window, exomem_cloud_backup_growth_batches, exomem_cloud_backup_growth_state, exomem_cloud_backup_growth_crossings, - exomem_hosted_alert_transitions`); + exomem_hosted_alert_transitions, exomem_rate_limit_buckets`); await pool.query("INSERT INTO exomem_cloud_backup_growth_window DEFAULT VALUES"); }); @@ -89,6 +92,48 @@ describe("Backup growth PostgreSQL receiver", { skip: !databaseUrl }, () => { assert.equal((await post(randomUUID(), { action: "open", extra: true })).status, 400); }); + it("refuses contending reports before they fill the shared pool and admits a retry", async () => { + const holder = await pool.connect(); + const run = randomUUID(); + try { + await holder.query("BEGIN"); + await holder.query("SELECT singleton FROM exomem_cloud_backup_growth_window FOR UPDATE"); + const responses = await Promise.all( + Array.from({ length: 8 }, () => post(run, { action: "open" })) + ); + for (const response of responses) { + assert.equal(response.status, 503); + const { error } = await response.json(); + assert.deepEqual([error.code, error.retryable, error.retryAfterMs], [ + "CAPACITY_UNAVAILABLE", true, 1000, + ]); + } + const { rows } = await pool.query("SELECT admitted_count FROM exomem_rate_limit_buckets"); + assert.deepEqual(rows, [{ admitted_count: 1 }]); + } finally { + await holder.query("ROLLBACK"); + holder.release(); + } + assert.equal((await post(run, { action: "open" })).status, 200); + }); + + it("honors the shared publisher rate limit without opening a growth window", async () => { + const rule = EXOMEM_RATE_LIMITS.backupGrowthReports; + const key = hashRateLimitKey(rule, KEY_WATCHER_JOB); + await pool.query( + `INSERT INTO exomem_rate_limit_buckets + (scope, key_digest, window_started_at, admitted_count, updated_at) + VALUES ($1, $2, now(), $3, now())`, + [rule.scope, key, rule.limit] + ); + const blocked = await post(randomUUID(), { action: "open" }); + assert.equal(blocked.status, 429); + const { error } = await blocked.json(); + assert.deepEqual([error.code, error.retryAfterMs], ["RATE_LIMITED", rule.windowSeconds * 1000]); + const { rows } = await pool.query("SELECT run_id FROM exomem_cloud_backup_growth_window"); + assert.deepEqual(rows, [{ run_id: null }]); + }); + it("fences an expired run, rejects incomplete and conflicting staging, and replays its accepted receipt", async () => { const expired = randomUUID(); const run = randomUUID(); diff --git a/src/lib/exomem-hosted/backup-growth-receiver.ts b/src/lib/exomem-hosted/backup-growth-receiver.ts index 79cccee0..a6931b53 100644 --- a/src/lib/exomem-hosted/backup-growth-receiver.ts +++ b/src/lib/exomem-hosted/backup-growth-receiver.ts @@ -8,12 +8,14 @@ import { type ExomemSql, } from "./db"; import { exomemErrors, ExomemHostedError } from "./errors"; +import { EXOMEM_RATE_LIMITS, takeExomemRateLimit } from "./rate-limit"; export const BACKUP_GROWTH_MAX_BODY_BYTES = 256 * 1024; const MAX_BATCHES = 20; const PAGE_SIZE = 1000; const LEASE_SECONDS = 15 * 60; const MAX_SIGNED_BIGINT = BigInt("9223372036854775807"); +let reportInFlight = false; const cellId = z.string().regex(CLOUD_CELL_ID_PATTERN); const byteCount = z @@ -86,10 +88,10 @@ function reportConflict() { } async function lockWindow(tx: ExomemSql, observedThrough: string | null): Promise { - // Read the database clock after acquiring the lock, so a queued request cannot use an expired lease. + // Refuse contention immediately. Read the database clock only while holding the lock. const { rows } = await tx` WITH locked AS MATERIALIZED ( - SELECT * FROM exomem_cloud_backup_growth_window WHERE singleton FOR UPDATE + SELECT * FROM exomem_cloud_backup_growth_window WHERE singleton FOR UPDATE NOWAIT ) SELECT *, checked_at < opened_at + make_interval(secs => ${LEASE_SECONDS}) AS live, ${observedThrough}::timestamptz BETWEEN opened_at - interval '30 seconds' @@ -261,29 +263,50 @@ async function acceptReport( } export async function receiveBackupGrowth(payload: unknown) { + if (reportInFlight) throw exomemErrors.capacityUnavailable(); const validated = requestSchema.safeParse(payload); if (!validated.success) throw exomemErrors.invalidRequest(); const input = validated.data; + const signal = AbortSignal.timeout(8000); const budget = createExomemWaitBudget({ - lockTimeoutMs: 1000, + lockTimeoutMs: 350, statementTimeoutMs: 4000, - signal: AbortSignal.timeout(8000), + signal, }); - return budget.run(() => - withExomemTransaction(async (tx) => { - const window = await lockWindow( - tx, - input.action === "accept" ? input.observed_through : null - ); - if (input.action === "open") return openWindow(tx, window, input.run_id); - if (input.action === "accept") return acceptReport(tx, window, input); - const committed = window.run_id === window.accepted_run_id; - if (window.run_id !== input.run_id || (!window.live && !committed)) throw windowClosed(); - if (input.action === "batch") return stageBatch(tx, input, committed); - if (committed) throw windowClosed(); - return activePage(tx, input.after); - }) - ); + // All valid versions of the capability share one bucket, even across instances. + const rule = EXOMEM_RATE_LIMITS.backupGrowthReports; + reportInFlight = true; + try { + return await budget.run(async () => { + if (!(await takeExomemRateLimit(rule, KEY_WATCHER_JOB))) { + throw new ExomemHostedError({ + code: "RATE_LIMITED", + status: 429, + message: "retry the backup growth report after the rate window resets", + retryable: true, + retryAfterMs: rule.windowSeconds * 1000, + }); + } + return withExomemTransaction(async (tx) => { + const window = await lockWindow( + tx, + input.action === "accept" ? input.observed_through : null + ); + if (input.action === "open") return openWindow(tx, window, input.run_id); + if (input.action === "accept") return acceptReport(tx, window, input); + const committed = window.run_id === window.accepted_run_id; + if (window.run_id !== input.run_id || (!window.live && !committed)) throw windowClosed(); + if (input.action === "batch") return stageBatch(tx, input, committed); + if (committed) throw windowClosed(); + return activePage(tx, input.after); + }); + }); + } catch (error) { + if (budget.timedOut || signal.aborted) throw exomemErrors.capacityUnavailable(); + throw error; + } finally { + reportInFlight = false; + } } /** The daily watcher check reclaims an expired stage even if no successor opens. */ diff --git a/src/lib/exomem-hosted/rate-limit.ts b/src/lib/exomem-hosted/rate-limit.ts index 7df3544c..67aa735a 100644 --- a/src/lib/exomem-hosted/rate-limit.ts +++ b/src/lib/exomem-hosted/rate-limit.ts @@ -86,6 +86,12 @@ export const EXOMEM_RATE_LIMITS = { limit: 120, windowSeconds: 60, }, + // One report uses about 40 requests at the full window size. Leave room for retries. + backupGrowthReports: { + scope: "exomem:backup-growth:reports", + limit: 120, + windowSeconds: 60, + }, oauthAuthorizeIp: { scope: "exomem:oauth-authorize:ip", limit: 60,