diff --git a/docs/contributing/disaster-recovery.md b/docs/contributing/disaster-recovery.md index 4e8d9c8b97..1c337a71da 100644 --- a/docs/contributing/disaster-recovery.md +++ b/docs/contributing/disaster-recovery.md @@ -49,10 +49,10 @@ administered **DR (“KCD”) Cloudflare account**: ```text Production worker (source account) Backup control plane (DR account) ─────────────────────────────── ──────────────────────────────── -Nightly */5 ticks 00:30–02:10 UTC 02:15 UTC: D1 export Workflow +Nightly */5 ticks 00:30–06:10 UTC 02:15 UTC: D1 export Workflow stage StorageRunner / R2 / artifacts → Hourly: D1 freshness + catch-up into staging/{day}/... Hourly: seal complete days - Admin UI: drill / production restore +06:15 UTC: staging watchdog → Sentry Admin UI: drill / production restore ``` ### Bucket layout @@ -95,6 +95,33 @@ Contract: `packages/shared/src/backup-staging.ts`. freshness also attempts to seal the last three complete days; the UI can seal a day on demand. +### Restore-safe row sizes + +D1's import path rejects individual SQL statements above its ~100 KB +statement-length limit (`statement too long: SQLITE_TOOBIG`), and D1 exports +write one INSERT per row — so a single oversized row makes the whole D1 backup +un-importable. This is not hypothetical: drills of the 2026-07-26 production +export failed on oversized `package_invocations.response_json` rows until the +rows were bounded. + +- Write paths bound large text columns via + `packages/shared/src/backup-restore-safety.ts` (64 KiB per column): + package-invocation replay caches are dropped when oversized, stored email + bodies are truncated (raw MIME in R2 stays canonical), and `value_set` rejects + oversized values (use durable storage instead). +- The control plane measures statement lengths while streaming every export and + writes `.stats.json` beside the SQL. A nonzero + `oversizedStatementCount` logs `backup-unrestorable-statements` (failure + status): the backup still lands, but treat that day as unrestorable via the + import API and fix the offending write path. + +`TRUSTED_RESTORE_BASELINE_SHA256` is the SHA-256 of the JSON array of sorted +migration filenames at the deployment commit; recompute when adding a migration: + +```sh +node -e "const fs=require('node:fs'),{createHash}=require('node:crypto');console.log(createHash('sha256').update(JSON.stringify(fs.readdirSync('packages/worker/migrations').filter(f=>f.endsWith('.sql')).sort())).digest('hex'))" +``` + ### Derived stores (not backed up) Restore rebuilds these; do not treat them as recovery media: @@ -236,14 +263,15 @@ config, and expect users to reauthorize OAuth and remote connectors. | When (UTC) | Who | What | | ------------------------ | ----------------- | -------------------------------------------------------------------------------------------------- | -| `*/5` during 00:30–02:10 | Production worker | Stage non-D1 stores for the current UTC day | +| `*/5` during 00:30–06:10 | Production worker | Stage non-D1 stores for the current UTC day (cheap no-op once the summary exists) | +| 06:15 | Production worker | Staging watchdog: a missing `exporter/summary.json` fails the lane → Sentry | | 02:15 | Control plane | Primary D1 export Workflow | | 02:45–05:45 hourly | Control plane | Catch-up create/restart of same-day D1 Workflow | | Hourly `:45` | Control plane | D1 freshness (identity, size ceiling, manifest age ≤26h, R2 size/ETag) + seal recent complete days | Hourly freshness does not SHA-256 the SQL bytes; drills do. Page yourself on -`freshness-stale`, size-ceiling hits, missing manifests, seal failures, or -unexpected disablement of the enable gates. +`freshness-stale`, size-ceiling hits, missing manifests, seal failures, +`backup-unrestorable-statements`, or unexpected disablement of the enable gates. ## Offline CLI fallback diff --git a/packages/backup-control-plane/backup-control-plane-test-support.ts b/packages/backup-control-plane/backup-control-plane-test-support.ts index 008b6a4601..5e092e85ad 100644 --- a/packages/backup-control-plane/backup-control-plane-test-support.ts +++ b/packages/backup-control-plane/backup-control-plane-test-support.ts @@ -325,7 +325,7 @@ export class CachedUploadStep implements BackupRuntimeStep { this.cache.set(name, value) if (name === 'stream-export-to-immutable-r2') this.afterUpload() if ( - name === 'verify-source-and-write-immutable-manifest' && + name === 'verify-stored-object-and-write-immutable-manifest' && this.afterFinalization ) { await this.afterFinalization() @@ -336,52 +336,6 @@ export class CachedUploadStep implements BackupRuntimeStep { async sleep(): Promise {} } -export class RetryFinalizationStep implements BackupRuntimeStep { - readonly finalizationAttempts: number[] = [] - private readonly cache = new Map() - - async do( - name: string, - config: unknown, - callback: () => Promise, - ): Promise - async do(name: string, callback: () => Promise): Promise - async do( - name: string, - configOrCallback: unknown, - callback?: () => Promise, - ): Promise { - if (this.cache.has(name)) return this.cache.get(name) as T - const execute = - typeof configOrCallback === 'function' - ? (configOrCallback as () => Promise) - : callback! - if (name === 'verify-source-and-write-immutable-manifest') { - for (let attempt = 1; attempt <= 2; attempt += 1) { - this.finalizationAttempts.push(attempt) - try { - const value = await execute() - this.cache.set(name, value) - return value - } catch (error) { - if ( - attempt === 2 || - !(error instanceof BackupError) || - !error.retryable - ) { - throw error - } - } - } - } - const value = await execute() - this.cache.set(name, value) - return value - } - - async sleep(): Promise {} -} - export class RetryUploadStep implements BackupRuntimeStep { readonly uploadAttempts: number[] = [] private readonly cache = new Map() diff --git a/packages/backup-control-plane/backup-runtime.node.test.ts b/packages/backup-control-plane/backup-runtime.node.test.ts index 0ab6379583..184dfa9b27 100644 --- a/packages/backup-control-plane/backup-runtime.node.test.ts +++ b/packages/backup-control-plane/backup-runtime.node.test.ts @@ -16,7 +16,6 @@ import { DATABASE_ID, MemoryBucket, RetryAfterCommitStep, - RetryFinalizationStep, RetryUploadStep, environment, exportEnvelope, @@ -74,7 +73,9 @@ test('source size gates block export for zero and oversize readings', async () = options, ) assert.equal(result.payload.sql.bytes, 5) - assert.equal(exportCalls, 3) + // One export start plus one upload-callback refresh; finalization never + // polls D1 again. + assert.equal(exportCalls, 2) consoleError.mockClear() const oversizeUrls: string[] = [] @@ -142,9 +143,8 @@ test('workflow retry reuses an upload committed before step persistence and writ assert.deepEqual(downloadUrls, [ 'https://download.example/url-2', 'https://download.example/url-3', - 'https://download.example/url-4', ]) - assert.equal(apiCalls.filter((url) => url.endsWith('/export')).length, 4) + assert.equal(apiCalls.filter((url) => url.endsWith('/export')).length, 3) assert.equal( result.payload.sql.objectKey, objectKeyForBookmark(payload.objectPrefix, 'bookmark-1'), @@ -153,6 +153,17 @@ test('workflow retry reuses an upload committed before step persistence and writ await readManifest(bucket as unknown as R2Bucket, payload.manifestKey), result, ) + // Statement stats are persisted next to the SQL object. + const statsObject = await (bucket as unknown as R2Bucket).get( + `${result.payload.sql.objectKey}.stats.json`, + ) + assert.notEqual(statsObject, null) + const stats = JSON.parse(await statsObject!.text()) as { + maxStatementBytes: number + oversizedStatementCount: number + } + assert.equal(stats.oversizedStatementCount, 0) + assert.ok(stats.maxStatementBytes > 0) }) test('initial upload ignores a stale cached signed URL and refreshes it in the callback', async () => { @@ -203,73 +214,59 @@ test('initial upload ignores a stale cached signed URL and refreshes it in the c assert.deepEqual(exportBodies, [ { output_format: 'polling' }, { output_format: 'polling', current_bookmark: 'bookmark-1' }, - { output_format: 'polling', current_bookmark: 'bookmark-1' }, - ]) - assert.deepEqual(downloadUrls, [ - 'https://download.example/fresh-upload', - 'https://download.example/fresh-finalization', ]) + // The stale initial URL is never used and finalization performs no D1 + // download at all: it verifies the stored object against the durable + // upload-step digest instead. + assert.deepEqual(downloadUrls, ['https://download.example/fresh-upload']) assert.deepEqual( await readManifest(bucket as unknown as R2Bucket, payload.manifestKey), result, ) }) -test('a finalization callback retry obtains another fresh signed URL', async () => { +test('a replayed finalization tolerates the already-written manifest and stats', async () => { + const consoleError = vi.spyOn(console, 'error') + consoleError.mockImplementation(() => undefined) const bucket = new MemoryBucket() const env = environment(bucket) const payload = backupPayload(env, new Date('2026-07-22T02:15:00Z')) - const step = new RetryFinalizationStep() - const downloadUrls: string[] = [] - let exportCalls = 0 - const result = await runBackupRuntime( - env, - { - instanceId: workflowInstanceId(DATABASE_ID, payload.day), - payload, - timestamp: new Date('2026-07-22T02:15:01Z'), - }, - step, - { - api: { - fetcher: async (input) => { - if (!String(input).endsWith('/export')) return identityEnvelope(1_000) - exportCalls += 1 - return exportEnvelope( - 'complete', - 'bookmark-1', - [ - 'https://download.example/initial', - 'https://download.example/refreshed-upload', - 'https://download.example/refreshed-once', - 'https://download.example/refreshed-twice', - ][exportCalls - 1], - ) - }, - sleep: async () => undefined, - }, - downloadFetcher: async (input) => { - const url = String(input) - downloadUrls.push(url) - if (url === 'https://download.example/refreshed-once') { - return new Response('', { status: 503 }) - } - return new Response('valid', { - headers: { 'content-length': '5' }, - }) - }, + const options = { + api: { + fetcher: async (input: RequestInfo | URL) => + String(input).endsWith('/export') + ? exportEnvelope('complete') + : identityEnvelope(1_000), + sleep: async () => undefined, }, + downloadFetcher: async () => + new Response('valid', { headers: { 'content-length': '5' } }), + } + const event = { + instanceId: workflowInstanceId(DATABASE_ID, payload.day), + payload, + timestamp: new Date('2026-07-22T02:15:01Z'), + } + const step = new CachedUploadStep(() => undefined) + const first = await runBackupRuntime(env, event, step, options) + // Replaying the same instance returns every cached step result without + // re-executing uploads or manifest writes. + const replay = await runBackupRuntime(env, event, step, options) + assert.deepEqual(replay, first) + + // A *new* execution over an already-manifested day fails closed on the + // immutable manifest instead of silently replacing it. + await new Promise((resolve) => setTimeout(resolve, 2)) + await assert.rejects( + runBackupRuntime(env, event, new CachedUploadStep(() => undefined), { + ...options, + }), + (error: unknown) => + error instanceof BackupError && error.code === 'manifest-conflict', ) - assert.equal(exportCalls, 4) - assert.deepEqual(step.finalizationAttempts, [1, 2]) - assert.deepEqual(downloadUrls, [ - 'https://download.example/refreshed-upload', - 'https://download.example/refreshed-once', - 'https://download.example/refreshed-twice', - ]) assert.deepEqual( await readManifest(bucket as unknown as R2Bucket, payload.manifestKey), - result, + first, ) }) @@ -317,7 +314,6 @@ test('zero-byte upload retries with a fresh URL before manifest success', async assert.deepEqual(downloadUrls, [ 'https://download.example/export-2', 'https://download.example/export-3', - 'https://download.example/export-4', ]) assert.equal(result.payload.sql.bytes, 5) assert.equal( @@ -335,9 +331,21 @@ test('tampered objects are rejected for retry and cached-upload paths without wr const consoleError = vi.spyOn(console, 'error') consoleError.mockImplementation(() => undefined) - for (const createStep of [ - (corrupt: () => void) => new RetryAfterCommitStep(corrupt), - (corrupt: () => void) => new CachedUploadStep(corrupt), + // Corruption surfaces at the layer that next touches the object: an + // upload-step retry compares the existing object against the signed + // source download, while a cached upload result is re-verified against + // the durable step digest at finalization (no D1 download). + for (const { createStep, expectedCode, expectedDownloads } of [ + { + createStep: (corrupt: () => void) => new RetryAfterCommitStep(corrupt), + expectedCode: 'existing-object-source-mismatch', + expectedDownloads: 2, + }, + { + createStep: (corrupt: () => void) => new CachedUploadStep(corrupt), + expectedCode: 'stored-object-mismatch', + expectedDownloads: 1, + }, ]) { consoleError.mockClear() const bucket = new MemoryBucket() @@ -375,10 +383,10 @@ test('tampered objects are rejected for retry and cached-upload paths without wr ), (error: unknown) => error instanceof BackupError && - error.code === 'existing-object-source-mismatch' && + error.code === expectedCode && error.retryable === false, ) - assert.equal(downloadCalls, 2) + assert.equal(downloadCalls, expectedDownloads) assert.equal( await readManifest(bucket as unknown as R2Bucket, payload.manifestKey), null, diff --git a/packages/backup-control-plane/backup-runtime.ts b/packages/backup-control-plane/backup-runtime.ts index bc66aa31a2..220934be5e 100644 --- a/packages/backup-control-plane/backup-runtime.ts +++ b/packages/backup-control-plane/backup-runtime.ts @@ -21,9 +21,64 @@ import { type BackupEnvironment, type BackupManifest, type BackupPayload, + type SqlStatementStats, } from './backup-types.ts' import { signBackupManifest } from './manifest-signing.ts' +/** + * Persist per-object statement-length statistics next to the SQL object and + * log them. An oversized statement means the object cannot be re-imported + * through the D1 import API (SQLITE_TOOBIG); the backup still completes, but + * the condition is logged with failure status so observability and health + * checks can alert on an un-restorable day. + */ +async function recordSqlStatementStats(input: { + env: BackupEnvironment + day: string + instanceId: string + objectKey: string + stats: SqlStatementStats | undefined +}): Promise { + const { stats } = input + // Step replays from pre-stats deployments have no measurements to record. + if (!stats) return + safeLog({ + event: 'backup-sql-stats', + status: stats.oversizedStatementCount > 0 ? 'failure' : 'success', + day: input.day, + instanceId: input.instanceId, + objectKey: input.objectKey, + maxStatementBytes: stats.maxStatementBytes, + oversizedStatementCount: stats.oversizedStatementCount, + }) + if (stats.oversizedStatementCount > 0) { + safeLog({ + event: 'backup-unrestorable-statements', + status: 'failure', + day: input.day, + instanceId: input.instanceId, + objectKey: input.objectKey, + maxStatementBytes: stats.maxStatementBytes, + oversizedStatementCount: stats.oversizedStatementCount, + }) + } + const body = JSON.stringify({ + schemaVersion: 1, + day: input.day, + objectKey: input.objectKey, + maxStatementBytes: stats.maxStatementBytes, + oversizedStatementCount: stats.oversizedStatementCount, + importStatementLimitBytes: stats.limit, + }) + // The stats object is advisory; an existing object from a replayed step + // wins and is left alone (the prefix is under the bucket's immutable + // lock, so overwrites are rejected anyway). + await input.env.BACKUP_BUCKET.put(`${input.objectKey}.stats.json`, body, { + onlyIf: { etagDoesNotMatch: '*' }, + httpMetadata: { contentType: 'application/json' }, + }) +} + interface BackupRuntimeEvent { instanceId: string payload: BackupPayload @@ -145,28 +200,23 @@ export async function runBackupRuntime( retentionTier: checkedPayload.retentionTier, } const manifest = await step.do( - 'verify-source-and-write-immutable-manifest', + 'verify-stored-object-and-write-immutable-manifest', { retries: { limit: 4, delay: '30 seconds', backoff: 'exponential' }, timeout: '15 minutes', }, async () => { - // Signed URL may come from a restarted export; content is verified - // against the already-stored object key from the upload step. - const refreshed = await refreshCompletedD1Export( - env, - stored.bookmark, - options.api, - ) + // Finalization verifies the stored object against the durable + // upload-step digest (size, ETag, full SHA-256 re-read). It must + // not re-download from D1: expired poll results can only be + // refreshed by starting a new export of a *newer* database + // state, whose bytes legitimately differ from the stored object + // whenever production wrote anything in between. await assertDuplicateMatchesManifest( env.BACKUP_BUCKET, checkedPayload.manifestKey, stored.objectKey, stored, - { - signedUrl: refreshed.signedUrl, - fetcher: options.downloadFetcher, - }, ) const signedManifest = await signBackupManifest(env, unsignedManifest) await putImmutableManifest( @@ -177,6 +227,18 @@ export async function runBackupRuntime( return signedManifest }, ) + await step.do( + 'record-statement-stats', + { retries: { limit: 2, delay: '10 seconds' }, timeout: '2 minutes' }, + async () => + recordSqlStatementStats({ + env, + day: checkedPayload.day, + instanceId: event.instanceId, + objectKey: stored.objectKey, + stats: stored.sqlStatementStats, + }), + ) safeLog({ event: 'backup-success', status: 'success', diff --git a/packages/backup-control-plane/backup-types.ts b/packages/backup-control-plane/backup-types.ts index 2bd672d9de..f84f387850 100644 --- a/packages/backup-control-plane/backup-types.ts +++ b/packages/backup-control-plane/backup-types.ts @@ -58,11 +58,28 @@ export interface ExportLost { export type ExportState = ExportReady | ExportPending | ExportLost +/** + * Statement-length statistics for one exported SQL object, measured while + * streaming during upload. `oversizedStatementCount > 0` means the object is + * not restorable through the D1 import API (statement too long: + * SQLITE_TOOBIG); the backup still lands, but the condition is logged as a + * failure-status event and persisted next to the object as + * `.stats.json` so dashboards and health checks can alert on it. + */ +export interface SqlStatementStats { + maxStatementBytes: number + oversizedStatementCount: number + /** The import statement-length limit the stats were measured against. */ + limit: number +} + export interface StoredBackup { bytes: number sha256: string r2Etag: string alreadyExisted: boolean + /** Absent only on step results cached by pre-stats deployments. */ + sqlStatementStats?: SqlStatementStats } export interface LogRecord { @@ -74,6 +91,8 @@ export interface LogRecord { | 'backup-restarted' | 'backup-success' | 'backup-failure' + | 'backup-sql-stats' + | 'backup-unrestorable-statements' | 'freshness-success' | 'freshness-stale' | 'source-size-success' @@ -110,4 +129,6 @@ export interface LogRecord { sourceBytes?: number maxSourceBytes?: number blobsVerified?: number + maxStatementBytes?: number + oversizedStatementCount?: number } diff --git a/packages/backup-control-plane/immutable-storage.node.test.ts b/packages/backup-control-plane/immutable-storage.node.test.ts index 25120f0133..fa08e152f2 100644 --- a/packages/backup-control-plane/immutable-storage.node.test.ts +++ b/packages/backup-control-plane/immutable-storage.node.test.ts @@ -6,6 +6,7 @@ import { test } from 'vitest' import { MAXIMUM_SINGLE_BACKUP_OBJECT_BYTES, assertDuplicateMatchesManifest, + createSqlStatementScanner, putImmutableManifest, readManifest, storeSignedDownload, @@ -47,46 +48,61 @@ test('streams once with an immutable conditional, checksum, byte count, and ETag assert.equal(duplicate.sha256, stored.sha256) }) -test('an existing object without a manifest is recoverable', async () => { +test('a missing manifest is finalized from the durable upload-step digest', async () => { const bucket = new MemoryBucket() const prefix = `daily/d1/${DATABASE_ID}/2026-07-22` const manifestKey = `${prefix}/manifest.json` - const orphanKey = objectKeyForBookmark(prefix, 'bookmark-1') - await storeSignedDownload( + const objectKey = objectKeyForBookmark(prefix, 'bookmark-1') + const stored = await storeSignedDownload( bucket as unknown as R2Bucket, - orphanKey, + objectKey, 'https://download.example', async () => new Response('valid', { headers: { 'content-length': '5' } }), ) - const duplicate = await storeSignedDownload( - bucket as unknown as R2Bucket, - orphanKey, - 'https://download.example', - async () => new Response('valid', { headers: { 'content-length': '5' } }), + // Finalization verifies the stored object against the upload-step + // result; it never re-downloads from D1 (an expired poll can only be + // refreshed by exporting a newer database state). + await assert.doesNotReject( + assertDuplicateMatchesManifest( + bucket as unknown as R2Bucket, + manifestKey, + objectKey, + stored, + ), ) await assert.rejects( assertDuplicateMatchesManifest( bucket as unknown as R2Bucket, manifestKey, - orphanKey, - duplicate, + `${prefix}/backup-missing.sql`, + stored, ), (error: unknown) => - error instanceof BackupError && - error.code === 'duplicate-object-manifest-missing', + error instanceof BackupError && error.code === 'stored-object-missing', ) - await assert.doesNotReject( + bucket.corrupt(objectKey, 'other') + await assert.rejects( assertDuplicateMatchesManifest( bucket as unknown as R2Bucket, manifestKey, - orphanKey, - duplicate, - { - signedUrl: 'https://download.example', - fetcher: async () => - new Response('valid', { headers: { 'content-length': '5' } }), - }, + objectKey, + stored, ), + (error: unknown) => + error instanceof BackupError && error.code === 'stored-object-mismatch', + ) +}) + +test('an orphaned object from a crashed run does not block a later manifest', async () => { + const bucket = new MemoryBucket() + const prefix = `daily/d1/${DATABASE_ID}/2026-07-22` + const manifestKey = `${prefix}/manifest.json` + const orphanKey = objectKeyForBookmark(prefix, 'bookmark-1') + await storeSignedDownload( + bucket as unknown as R2Bucket, + orphanKey, + 'https://download.example', + async () => new Response('valid', { headers: { 'content-length': '5' } }), ) const recoveryKey = objectKeyForBookmark(prefix, 'bookmark-2') const recovered = await storeSignedDownload( @@ -115,6 +131,39 @@ test('an existing object without a manifest is recoverable', async () => { assert.notEqual(await bucket.head(orphanKey), null) }) +test('sql statement stats measure quote-aware statement lengths during upload', async () => { + const bucket = new MemoryBucket() + // Two statements: the second hides semicolons and an escaped quote + // inside a string literal, and spans multiple lines. + const sql = `CREATE TABLE t (v TEXT);\nINSERT INTO t VALUES ('semi;colon''s\nnewline');\n` + const bytes = new TextEncoder().encode(sql) + const stored = await storeSignedDownload( + bucket as unknown as R2Bucket, + 'stats.sql', + 'https://download.example', + async () => + new Response(bytes, { + headers: { 'content-length': String(bytes.byteLength) }, + }), + ) + assert.deepEqual(stored.sqlStatementStats, { + maxStatementBytes: new TextEncoder().encode( + `\nINSERT INTO t VALUES ('semi;colon''s\nnewline');`, + ).byteLength, + oversizedStatementCount: 0, + limit: 100_000, + }) + + const scanner = createSqlStatementScanner(10) + scanner.update(new TextEncoder().encode("INSERT INTO t VALUES ('long")) + scanner.update(new TextEncoder().encode("er than limit');\nSELECT 1;")) + assert.deepEqual(scanner.finish(), { + maxStatementBytes: 43, + oversizedStatementCount: 1, + limit: 10, + }) +}) + test('truncated and interrupted downloads fail retryably, then a retry succeeds', async () => { const bucket = new MemoryBucket() await assert.rejects( diff --git a/packages/backup-control-plane/immutable-storage.ts b/packages/backup-control-plane/immutable-storage.ts index 78384c2c6a..93e2cd5421 100644 --- a/packages/backup-control-plane/immutable-storage.ts +++ b/packages/backup-control-plane/immutable-storage.ts @@ -2,12 +2,85 @@ import { parseBackupManifest, serializeBackupManifest, } from '@kody-internal/shared/backup-manifest.ts' +import { d1ImportMaxStatementBytes } from '@kody-internal/shared/backup-restore-safety.ts' import { BackupError } from './backup-policy.ts' -import { type BackupManifest, type StoredBackup } from './backup-types.ts' +import { + type BackupManifest, + type SqlStatementStats, + type StoredBackup, +} from './backup-types.ts' export const MAXIMUM_SINGLE_BACKUP_OBJECT_BYTES = 5 * 1024 * 1024 * 1024 +const SINGLE_QUOTE = 0x27 +const SEMICOLON = 0x3b + +/** + * Streaming, quote-aware SQL statement-length scanner. D1's import path + * rejects statements above {@link d1ImportMaxStatementBytes} with + * SQLITE_TOOBIG, so a backup containing one is not restorable through the + * D1 import API. Statement boundaries are semicolons outside single-quoted + * string literals (doubled `''` escapes toggle twice and cancel out; dumps + * do not contain comments). + */ +export function createSqlStatementScanner(limit = d1ImportMaxStatementBytes): { + update: (chunk: Uint8Array) => void + finish: () => SqlStatementStats +} { + let inString = false + let currentStatementBytes = 0 + let maxStatementBytes = 0 + let oversizedStatementCount = 0 + + function closeStatement() { + if (currentStatementBytes > maxStatementBytes) { + maxStatementBytes = currentStatementBytes + } + if (currentStatementBytes > limit) oversizedStatementCount += 1 + currentStatementBytes = 0 + } + + return { + update(chunk: Uint8Array) { + let index = 0 + while (index < chunk.length) { + if (inString) { + const quote = chunk.indexOf(SINGLE_QUOTE, index) + if (quote === -1) { + currentStatementBytes += chunk.length - index + return + } + currentStatementBytes += quote - index + 1 + inString = false + index = quote + 1 + continue + } + const quote = chunk.indexOf(SINGLE_QUOTE, index) + const semicolon = chunk.indexOf(SEMICOLON, index) + if (semicolon !== -1 && (quote === -1 || semicolon < quote)) { + currentStatementBytes += semicolon - index + 1 + closeStatement() + index = semicolon + 1 + continue + } + if (quote !== -1) { + currentStatementBytes += quote - index + 1 + inString = true + index = quote + 1 + continue + } + currentStatementBytes += chunk.length - index + return + } + }, + finish(): SqlStatementStats { + if (currentStatementBytes > 0) closeStatement() + return { maxStatementBytes, oversizedStatementCount, limit } + }, + } +} + function hex(buffer: ArrayBuffer): string { return [...new Uint8Array(buffer)] .map((byte) => byte.toString(16).padStart(2, '0')) @@ -17,13 +90,32 @@ function hex(buffer: ArrayBuffer): string { async function digestBody( body: ReadableStream, expectedBytes?: number, -): Promise<{ bytes: number; sha256: string }> { +): Promise<{ + bytes: number + sha256: string + sqlStatementStats: SqlStatementStats +}> { // DigestStream is a Workers runtime extension exposed on crypto, not a // bare global (verified live: `DigestStream is not defined`). const digest = new ( crypto as unknown as { DigestStream: typeof DigestStream } ).DigestStream('SHA-256') - await body.pipeTo(digest) + const scanner = createSqlStatementScanner() + const writer = digest.getWriter() + const reader = body.getReader() + try { + for (;;) { + const { done, value } = await reader.read() + if (done) break + if (value === undefined) continue + scanner.update(value) + await writer.write(value) + } + await writer.close() + } catch (error) { + await writer.abort(error).catch(() => undefined) + throw error + } const bytes = Number(digest.bytesWritten) if (expectedBytes !== undefined && bytes !== expectedBytes) { throw new BackupError( @@ -32,7 +124,11 @@ async function digestBody( true, ) } - return { bytes, sha256: hex(await digest.digest) } + return { + bytes, + sha256: hex(await digest.digest), + sqlStatementStats: scanner.finish(), + } } interface SignedDownload { @@ -138,7 +234,11 @@ async function inspectExisting( 'existing export is at or above the single-object backup size limit', ) } - let digest: { bytes: number; sha256: string } + let digest: { + bytes: number + sha256: string + sqlStatementStats: SqlStatementStats + } let sourceDigest: { bytes: number; sha256: string } try { ;[digest, sourceDigest] = await Promise.all([ @@ -163,12 +263,59 @@ async function inspectExisting( ) } return { - ...digest, + bytes: digest.bytes, + sha256: digest.sha256, + sqlStatementStats: digest.sqlStatementStats, r2Etag: object.etag, alreadyExisted: true, } } +/** + * Verify the immutable object still matches the durable upload-step result + * (size, ETag, and a full SHA-256 re-read). This is the finalization-time + * integrity check: the upload step already proved the object matches the + * signed export source, and D1 poll results are short-lived and may only be + * refreshable by starting a new export of a *newer* database state, so + * re-downloading from D1 cannot be used to re-verify the stored object. + */ +export async function verifyStoredObjectMatches( + bucket: R2Bucket, + objectKey: string, + stored: StoredBackup, +): Promise { + const object = await bucket.get(objectKey) + if (object === null) { + throw new BackupError( + 'stored-object-missing', + 'immutable backup object disappeared after the upload step', + ) + } + if (object.size !== stored.bytes || object.etag !== stored.r2Etag) { + throw new BackupError( + 'stored-object-mismatch', + 'immutable backup object no longer matches the upload step result', + ) + } + let digest: { bytes: number; sha256: string } + try { + digest = await digestBody(object.body, object.size) + } catch (error) { + if (error instanceof BackupError) throw error + throw new BackupError( + 'download-interrupted', + 'streaming the immutable object for finalization verification failed', + true, + ) + } + if (digest.sha256 !== stored.sha256) { + throw new BackupError( + 'stored-object-mismatch', + 'immutable backup object no longer matches the upload step result', + ) + } +} + export async function storeSignedDownload( bucket: R2Bucket, key: string, @@ -213,7 +360,9 @@ export async function storeSignedDownload( if (object === null) return inspectExisting(bucket, key, digestPromise) const digest = await digestPromise return { - ...digest, + bytes: digest.bytes, + sha256: digest.sha256, + sqlStatementStats: digest.sqlStatementStats, r2Etag: object.etag, alreadyExisted: false, } @@ -251,38 +400,10 @@ export async function assertDuplicateMatchesManifest( manifestKey: string, objectKey: string, stored: StoredBackup, - signedSource?: { - signedUrl: string - fetcher?: typeof fetch - }, ): Promise { const manifest = await readManifest(bucket, manifestKey) if (manifest === null) { - if (!signedSource) { - throw new BackupError( - 'duplicate-object-manifest-missing', - 'backup object has no manifest and no signed source verification', - ) - } - const download = await fetchSignedDownload( - signedSource.signedUrl, - signedSource.fetcher ?? fetch, - ) - const verified = await inspectExisting( - bucket, - objectKey, - digestBody(download.body, download.expectedBytes), - ) - if ( - verified.bytes !== stored.bytes || - verified.sha256 !== stored.sha256 || - verified.r2Etag !== stored.r2Etag - ) { - throw new BackupError( - 'duplicate-object-source-proof-mismatch', - 'signed source verification does not match the stored step result', - ) - } + await verifyStoredObjectMatches(bucket, objectKey, stored) return } if ( diff --git a/packages/backup-control-plane/readme.md b/packages/backup-control-plane/readme.md index 55a7bf42a5..2ded86b20d 100644 --- a/packages/backup-control-plane/readme.md +++ b/packages/backup-control-plane/readme.md @@ -19,17 +19,30 @@ key. If a process crashes after writing SQL but before its manifest, a later Workflow-step retry reuses the cached export bookmark and therefore inspects the same object before constructing the absent canonical manifest. The original one-hour signed URL returned by the durable export step is never used for -transfer. On every execution of both the retryable upload callback and the -retryable finalization callback, the runtime polls D1 with the cached bookmark -and requires a complete response for that same bookmark, obtaining a fresh -signed URL. Finalization then stream-compares exact byte count and SHA-256 with -R2. Pending refreshes retry; malformed responses and bookmark mismatches fail -closed. The final refresh, comparison, and immutable manifest write remain in -one Workflow step, so a callback retry performs another export API poll instead -of reusing a separately cached URL. This also applies when replay returns a -cached upload-step result and skips its callback. Without signed-source context -it fails with `duplicate-object-manifest-missing`. An existing manifest must -also match that object exactly. +transfer. On every execution of the retryable upload callback, the runtime polls +D1 with the cached bookmark and requires a complete response for that same +bookmark, obtaining a fresh signed URL; the upload stream-verifies exact byte +count and SHA-256 against R2 while writing. Finalization deliberately does +**not** poll D1 again: expired poll results can only be refreshed by starting a +new export of a _newer_ database state, whose bytes legitimately differ from the +stored object whenever production wrote anything in between (this exact mismatch +made roughly every other nightly backup fail terminally with +`existing-object-source-mismatch` before 2026-07-27). Instead, finalization +re-reads the stored object and requires its size, R2 ETag, and full SHA-256 to +match the durable upload-step result (`stored-object-mismatch` / +`stored-object-missing` fail closed), then signs and writes the manifest in the +same Workflow step. An existing manifest must match that object exactly. + +While streaming the upload, the runtime also measures SQL statement lengths +(quote-aware semicolon splitting). D1's import path rejects statements above its +~100 KB statement limit with `statement too long: SQLITE_TOOBIG`, so an +oversized statement means the object is not restorable through the D1 import +API. The measurements are persisted as `.stats.json` next to the SQL +object and logged as `backup-sql-stats`; an oversized count above zero +additionally logs `backup-unrestorable-statements` with failure status. The +backup itself still completes — application write paths bound row sizes (see +`packages/shared/src/backup-restore-safety.ts`), so a nonzero count indicates a +new unbounded write path that must be fixed. Every canonical manifest uses schema v2 and is an Ed25519-signed envelope. Its signature covers deterministic canonical JSON for the SQL key, bytes, SHA-256, diff --git a/packages/backup-control-plane/wrangler.jsonc b/packages/backup-control-plane/wrangler.jsonc index d72651ae7e..7622f52ba9 100644 --- a/packages/backup-control-plane/wrangler.jsonc +++ b/packages/backup-control-plane/wrangler.jsonc @@ -45,9 +45,10 @@ "BACKUP_MANIFEST_SIGNING_KEY_ID": "kody-dr-2026-07", "BACKUP_MANIFEST_VERIFYING_PUBLIC_KEY_SPKI_BASE64": "MCowBQYDK2VwAyEA3jqjPcGTzWefE5PGyRBdUQKAEj7FFGtFIz+223sbt9A=", // SHA-256 of the JSON array of sorted migration filenames at the - // deployment commit (see docs/contributing/disaster-recovery.md). + // deployment commit; recompute when adding a migration (recipe in + // docs/contributing/disaster-recovery.md). "TRUSTED_RESTORE_BASELINE_ID": "kody-migration-set-2026-07", - "TRUSTED_RESTORE_BASELINE_SHA256": "a132fab33e6a614e861af54ac9c82ba1493f36a5c9fe02c9004ea0e755b47ea2", + "TRUSTED_RESTORE_BASELINE_SHA256": "98fdc7b903645bad2df504f03ea6c6bd80a8ba0b7b28939cae515a408563c310", "BACKUP_MAX_AGE_HOURS": "26", // D1 GET file_size must remain strictly below this single-object ceiling. "BACKUP_MAX_SOURCE_BYTES": "4500000000", diff --git a/packages/shared/src/backup-restore-safety.node.test.ts b/packages/shared/src/backup-restore-safety.node.test.ts new file mode 100644 index 0000000000..3d3c731004 --- /dev/null +++ b/packages/shared/src/backup-restore-safety.node.test.ts @@ -0,0 +1,16 @@ +import { expect, test } from 'vitest' +import { truncateToUtf8Bytes, utf8ByteLength } from './backup-restore-safety.ts' + +test('truncateToUtf8Bytes bounds by bytes without splitting code points', () => { + expect(truncateToUtf8Bytes('plain ascii', 100)).toBe('plain ascii') + expect(truncateToUtf8Bytes('abcdef', 3)).toBe('abc') + + // '€' is 3 UTF-8 bytes; a 4-byte budget must not emit half a code point. + const truncated = truncateToUtf8Bytes('a€€', 4) + expect(truncated).toBe('a€') + expect(utf8ByteLength(truncated)).toBeLessThanOrEqual(4) + + const partial = truncateToUtf8Bytes('a€€', 5) + expect(partial).toBe('a€') + expect(utf8ByteLength(partial)).toBeLessThanOrEqual(5) +}) diff --git a/packages/shared/src/backup-restore-safety.ts b/packages/shared/src/backup-restore-safety.ts new file mode 100644 index 0000000000..3fb9017151 --- /dev/null +++ b/packages/shared/src/backup-restore-safety.ts @@ -0,0 +1,41 @@ +/** + * D1 disaster-recovery restore safety limits. + * + * Cloudflare D1's SQL import path rejects individual statements above its + * documented 100 KB statement-length limit with `statement too long: + * SQLITE_TOOBIG` (verified live 2026-07-27 against a production export: a + * dump filtered to statements <= 100,000 bytes imported cleanly while the + * same dump with 100–200 KB statements failed). D1's own export writes one + * INSERT per row, so any row whose serialized form exceeds that limit makes + * the whole backup un-importable. + * + * Every D1 write path that can store large text therefore bounds stored + * column sizes so a full row (all columns plus INSERT framing and SQL + * escaping overhead) stays comfortably below the import limit. + */ + +/** D1 import per-statement ceiling (bytes of SQL text). */ +export const d1ImportMaxStatementBytes = 100_000 + +/** + * Upper bound for any single large text column persisted to D1. Leaves + * headroom below {@link d1ImportMaxStatementBytes} for the other row + * columns, INSERT framing, and quote-escaping expansion in SQL dumps. + */ +export const maxRestorableTextColumnBytes = 65_536 + +export function utf8ByteLength(value: string): number { + return new TextEncoder().encode(value).byteLength +} + +/** + * Truncate to at most `maxBytes` UTF-8 bytes without splitting a code point. + */ +export function truncateToUtf8Bytes(value: string, maxBytes: number): string { + const encoded = new TextEncoder().encode(value) + if (encoded.byteLength <= maxBytes) return value + const sliced = encoded.slice(0, maxBytes) + return new TextDecoder('utf-8', { fatal: false }) + .decode(sliced) + .replace(/\uFFFD+$/, '') +} diff --git a/packages/worker/migrations/0105-restore-safe-row-sizes.sql b/packages/worker/migrations/0105-restore-safe-row-sizes.sql new file mode 100644 index 0000000000..bf95bdfff1 --- /dev/null +++ b/packages/worker/migrations/0105-restore-safe-row-sizes.sql @@ -0,0 +1,31 @@ +-- D1's SQL import path rejects statements above its ~100 KB statement-length +-- limit (statement too long: SQLITE_TOOBIG). D1 exports write one INSERT per +-- row, so any row whose serialized form exceeds that limit makes the whole +-- production backup un-importable — verified live 2026-07-27 with restore +-- drills of the 2026-07-26 production export. Bound the two write paths that +-- had already produced oversized rows (write-time caps now enforce this in +-- packages/worker/src/package-invocations/repo.ts and email/repo.ts): +-- +-- 1. package_invocations.response_json is an idempotency replay cache. +-- Dropping it keeps deduplication intact; replays of affected invocations +-- get the existing idempotency_response_unavailable outcome. +UPDATE package_invocations +SET response_json = NULL +WHERE response_json IS NOT NULL + AND LENGTH(CAST(response_json AS BLOB)) > 65536; + +-- 2. email_messages body columns are convenience copies; the canonical full +-- message stays in the R2 raw MIME object referenced by raw_mime_key. +-- substr counts characters, so 16000 keeps even fully multibyte content +-- under the 65536-byte column bound. +UPDATE email_messages +SET text_body = substr(text_body, 1, 16000) || ' +[truncated for backup-safe storage; the full message is retained in the raw MIME object]' +WHERE text_body IS NOT NULL + AND LENGTH(CAST(text_body AS BLOB)) > 65536; + +UPDATE email_messages +SET html_body = substr(html_body, 1, 16000) || ' +[truncated for backup-safe storage; the full message is retained in the raw MIME object]' +WHERE html_body IS NOT NULL + AND LENGTH(CAST(html_body AS BLOB)) > 65536; diff --git a/packages/worker/src/app/restore-safe-row-sizes-migration.node.test.ts b/packages/worker/src/app/restore-safe-row-sizes-migration.node.test.ts new file mode 100644 index 0000000000..76a6f8fc08 --- /dev/null +++ b/packages/worker/src/app/restore-safe-row-sizes-migration.node.test.ts @@ -0,0 +1,109 @@ +import { readdirSync, readFileSync } from 'node:fs' +import { DatabaseSync } from 'node:sqlite' +import { expect, test } from 'vitest' + +const migrationsDirectory = new URL('../../migrations/', import.meta.url) + +/** Upper bound (exclusive): only migrations before this file are applied as setup. */ +const restoreSafeRowSizesMigration = '0105-restore-safe-row-sizes.sql' + +/** D1 wraps each migration file in a transaction; mirror that here. */ +function applyMigrationLikeD1(db: DatabaseSync, fileName: string) { + const sql = readFileSync(new URL(fileName, migrationsDirectory), 'utf8') + db.exec('BEGIN') + try { + db.exec(sql) + db.exec('COMMIT') + } catch (error) { + db.exec('ROLLBACK') + throw error + } +} + +function applyMigrationsBefore(db: DatabaseSync) { + db.exec('PRAGMA foreign_keys = ON') + for (const fileName of readdirSync(migrationsDirectory) + .filter( + (file) => file.endsWith('.sql') && file < restoreSafeRowSizesMigration, + ) + .sort()) { + db.exec(readFileSync(new URL(fileName, migrationsDirectory), 'utf8')) + } +} + +function seedRows(db: DatabaseSync) { + db.exec(` + INSERT INTO users (username, email, password_hash, stable_user_id) + VALUES ('alice', 'alice@example.com', 'hash', 'stable-alice'); + `) + const insertInvocation = db.prepare( + `INSERT INTO package_invocations ( + id, user_id, token_id, package_id, package_kody_id, export_name, + idempotency_key, request_hash, status, response_json, + created_at, updated_at + ) VALUES (?, 'stable-alice', 'token-1', 'pkg-1', 'pkg-1', '.', ?, 'hash', + 'completed', ?, '2026-07-01T00:00:00.000Z', '2026-07-01T00:00:00.000Z')`, + ) + insertInvocation.run('inv-small', 'key-small', '{"status":200,"body":{}}') + insertInvocation.run( + 'inv-oversized', + 'key-oversized', + `{"status":200,"body":{"blob":"${'x'.repeat(70_000)}"}}`, + ) + const insertEmail = db.prepare( + `INSERT INTO email_messages ( + id, direction, user_id, from_address, raw_mime_key, raw_size, + processing_status, text_body, html_body, created_at, updated_at + ) VALUES (?, 'inbound', 'stable-alice', 'sender@example.com', + ?, 128, 'stored', ?, ?, + '2026-07-01T00:00:00.000Z', '2026-07-01T00:00:00.000Z')`, + ) + insertEmail.run( + 'email-small', + 'email-raw:v1:stable-alice/email-small', + 'short text', + '

short html

', + ) + insertEmail.run( + 'email-oversized', + 'email-raw:v1:stable-alice/email-oversized', + 'short text', + `

${'y'.repeat(70_000)}

`, + ) +} + +test('restore-safe row sizes migration bounds oversized rows and keeps small ones', () => { + const db = new DatabaseSync(':memory:') + applyMigrationsBefore(db) + seedRows(db) + + applyMigrationLikeD1(db, restoreSafeRowSizesMigration) + + const invocations = db + .prepare(`SELECT id, response_json FROM package_invocations ORDER BY id`) + .all() as Array<{ id: string; response_json: string | null }> + expect(invocations).toEqual([ + { id: 'inv-oversized', response_json: null }, + { id: 'inv-small', response_json: '{"status":200,"body":{}}' }, + ]) + + const emails = db + .prepare( + `SELECT id, text_body, html_body, + LENGTH(CAST(html_body AS BLOB)) AS html_bytes + FROM email_messages ORDER BY id`, + ) + .all() as Array<{ + id: string + text_body: string | null + html_body: string | null + html_bytes: number + }> + const oversized = emails.find((row) => row.id === 'email-oversized') + const small = emails.find((row) => row.id === 'email-small') + expect(small?.html_body).toBe('

short html

') + expect(oversized?.text_body).toBe('short text') + expect(oversized?.html_bytes).toBeLessThanOrEqual(65_536) + expect(oversized?.html_body).toContain('[truncated for backup-safe storage') + expect(db.prepare(`PRAGMA foreign_key_check`).all()).toEqual([]) +}) diff --git a/packages/worker/src/dr/exporter.node.test.ts b/packages/worker/src/dr/exporter.node.test.ts index 020e448aea..bdf130b689 100644 --- a/packages/worker/src/dr/exporter.node.test.ts +++ b/packages/worker/src/dr/exporter.node.test.ts @@ -11,7 +11,9 @@ import { drExportMaxStorageDumpBufferBytes, listPlatformStorageInventory, runDrExportTick, + runDrExportWatchdogTick, shouldRunDrExportCron, + shouldRunDrExportWatchdogCron, } from '#worker/dr/exporter.ts' import { encodeStorageIdentity } from '#worker/dr/storage-identity.ts' import { @@ -169,10 +171,19 @@ test('exporter progresses phases with mocked bindings and S3, writing summary la ) expect(shouldRunDrExportCron(new Date('2026-07-23T00:30:00.000Z'))).toBe(true) expect(shouldRunDrExportCron(new Date('2026-07-23T01:45:00.000Z'))).toBe(true) - expect(shouldRunDrExportCron(new Date('2026-07-23T02:10:00.000Z'))).toBe(true) - expect(shouldRunDrExportCron(new Date('2026-07-23T02:15:00.000Z'))).toBe( + expect(shouldRunDrExportCron(new Date('2026-07-23T06:10:00.000Z'))).toBe(true) + expect(shouldRunDrExportCron(new Date('2026-07-23T06:15:00.000Z'))).toBe( false, ) + expect( + shouldRunDrExportWatchdogCron(new Date('2026-07-23T06:10:00.000Z')), + ).toBe(false) + expect( + shouldRunDrExportWatchdogCron(new Date('2026-07-23T06:15:00.000Z')), + ).toBe(true) + expect( + shouldRunDrExportWatchdogCron(new Date('2026-07-23T06:20:00.000Z')), + ).toBe(false) expect( await runDrExportTick({ env: { DR_EXPORT_ENABLED: 'false' } as unknown as Env, @@ -589,3 +600,61 @@ test('DR inventory includes registry buckets and package_service_states services ]) expect(inventory.every((entry) => entry.userId === 'user-a')).toBe(true) }) + +test('watchdog passes on a written summary and fails loudly on an incomplete night', async () => { + const env = { + DR_EXPORT_ENABLED: 'true', + DR_BACKUP_ACCOUNT_ID: 'acct', + DR_BACKUP_BUCKET_NAME: 'bucket', + DR_BACKUP_ACCESS_KEY_ID: 'key', + DR_BACKUP_SECRET_ACCESS_KEY: 'secret', + } as unknown as Env + const now = new Date('2026-07-23T06:15:00.000Z') + + expect( + await runDrExportWatchdogTick({ + env: { DR_EXPORT_ENABLED: 'false' } as unknown as Env, + now, + }), + ).toMatchObject({ skipped: true, reason: 'not-configured' }) + + const { client } = createMemoryS3() + await client.put( + stagingSummaryKey('2026-07-23'), + new TextEncoder().encode('{}'), + ) + expect(await runDrExportWatchdogTick({ env, now, s3: client })).toMatchObject( + { day: '2026-07-23', summaryPresent: true }, + ) + + const incomplete = createMemoryS3() + await incomplete.client.put( + 'staging/2026-07-23/exporter/progress.json', + new TextEncoder().encode( + JSON.stringify({ + schemaVersion: 1, + day: '2026-07-23', + startedAt: '2026-07-23T00:30:00.000Z', + phase: 'artifacts', + revision: 42, + storageIndex: 10, + storagePageStartAfter: null, + storagePartialNdjson: '', + storagePartialEntryCount: 0, + storageEntries: [], + r2LabelIndex: 2, + r2ListCursor: null, + r2PartialNdjson: '', + r2Completed: {}, + artifactsIndex: 7, + artifactEntries: [], + blobsWritten: 0, + blobsReused: 0, + warnings: [], + }), + ), + ) + await expect( + runDrExportWatchdogTick({ env, now, s3: incomplete.client }), + ).rejects.toThrow(/summary missing for 2026-07-23.*phase=artifacts/) +}) diff --git a/packages/worker/src/dr/exporter.ts b/packages/worker/src/dr/exporter.ts index 8c637694b7..94bde36d07 100644 --- a/packages/worker/src/dr/exporter.ts +++ b/packages/worker/src/dr/exporter.ts @@ -125,13 +125,29 @@ function utf8ByteLength(value: string) { } /** - * Nightly DR export window: roughly 00:30–02:10 UTC on the worker's - * every-5-minute cron. Ticks outside this window are skipped so daytime - * traffic is not competing with a full-platform export. + * Nightly DR export window: roughly 00:30–06:10 UTC on the worker's + * every-5-minute cron (~68 ticks × 20 s ≈ 22 minutes of staging work). + * Ticks outside this window are skipped so daytime traffic is not competing + * with a full-platform export. The original 00:30–02:10 window never + * finished a night's staging at production scale (the exporter was still in + * the artifacts phase every day), so no `exporter/summary.json` was ever + * written and no day could be sealed. Completed days exit cheaply via the + * `already-complete` check. */ export function shouldRunDrExportCron(now: Date) { const minutes = now.getUTCHours() * 60 + now.getUTCMinutes() - return minutes >= 30 && minutes <= 2 * 60 + 10 + return minutes >= 30 && minutes <= 6 * 60 + 10 +} + +/** + * One cron tick after the export window closes (06:15–06:19 UTC). The + * watchdog fails loudly (lane failure → Sentry) when the night's staging + * summary is missing, because the exporter itself never errors when it + * merely runs out of window. + */ +export function shouldRunDrExportWatchdogCron(now: Date) { + const minutes = now.getUTCHours() * 60 + now.getUTCMinutes() + return minutes >= 6 * 60 + 15 && minutes < 6 * 60 + 20 } export function isDrExportConfigured( @@ -745,6 +761,67 @@ export async function runDrExportTick(input: { } } +export type DrExportWatchdogResult = { + day: string + skipped: boolean + reason?: string + summaryPresent: boolean +} + +/** + * Post-window health check for the nightly staging exporter. Throws when the + * day's `exporter/summary.json` is missing so the scheduled-lane handler + * reports the failure to Sentry — an incomplete night is otherwise silent + * (the exporter just stops getting ticks when the window closes). + */ +export async function runDrExportWatchdogTick(input: { + env: Env + now?: Date + s3?: DrBackupS3Client +}): Promise { + const now = input.now ?? new Date() + const day = formatUtcDay(now) + if (!isDrExportConfigured(input.env)) { + return { + day, + skipped: true, + reason: 'not-configured', + summaryPresent: false, + } + } + const config = readDrBackupS3Config(input.env) + if (!config) { + return { + day, + skipped: true, + reason: 'not-configured', + summaryPresent: false, + } + } + const s3 = input.s3 ?? createDrBackupS3Client(config) + const summary = await s3.getText(stagingSummaryKey(day)) + if (summary) { + console.info( + 'dr_export_watchdog', + JSON.stringify({ day, summaryPresent: true }), + ) + return { day, skipped: false, summaryPresent: true } + } + const progressText = await s3.getText(stagingProgressKey(day)) + let phase = 'missing' + let detail = '' + if (progressText) { + const progress = parseProgress(JSON.parse(progressText.text) as unknown) + if (progress) { + phase = progress.phase + detail = ` storageIndex=${progress.storageIndex} artifactsIndex=${progress.artifactsIndex} revision=${progress.revision} warnings=${progress.warnings.length}` + } + } + throw new Error( + `DR staging summary missing for ${day} after the export window closed (progress phase=${phase}${detail}). The night's non-D1 backup is incomplete and the day cannot be sealed.`, + ) +} + export function __testOnlyCreateInitialProgress(day: string, now: Date) { return createInitialProgress(day, now) } diff --git a/packages/worker/src/email/repo-body-limits.workers.test.ts b/packages/worker/src/email/repo-body-limits.workers.test.ts new file mode 100644 index 0000000000..610d3c3c6a --- /dev/null +++ b/packages/worker/src/email/repo-body-limits.workers.test.ts @@ -0,0 +1,34 @@ +import { env } from 'cloudflare:workers' +import { expect, test } from 'vitest' +import { + maxRestorableTextColumnBytes, + utf8ByteLength, +} from '@kody-internal/shared/backup-restore-safety.ts' +import { emailBodyTruncationNotice, insertEmailMessage } from './repo.ts' +import { ensureEmailTestSchema } from './test-schema.ts' + +test('stored email bodies are bounded so D1 backups stay importable', async () => { + await ensureEmailTestSchema(env.APP_DB) + const oversized = `

${'x'.repeat(maxRestorableTextColumnBytes + 10_000)}

` + + const stored = await insertEmailMessage({ + db: env.APP_DB, + message: { + direction: 'inbound', + userId: `user-${crypto.randomUUID()}`, + fromAddress: 'sender@example.com', + toAddresses: ['inbox@example.com'], + subject: 'Giant newsletter', + textBody: 'short text body', + htmlBody: oversized, + rawMimeKey: 'emails/user/raw.mime', + processingStatus: 'stored', + }, + }) + + expect(stored.textBody).toBe('short text body') + expect(stored.htmlBody?.endsWith(emailBodyTruncationNotice)).toBe(true) + expect(utf8ByteLength(stored.htmlBody ?? '')).toBeLessThanOrEqual( + maxRestorableTextColumnBytes, + ) +}) diff --git a/packages/worker/src/email/repo.ts b/packages/worker/src/email/repo.ts index d4f99d22fa..e79e759853 100644 --- a/packages/worker/src/email/repo.ts +++ b/packages/worker/src/email/repo.ts @@ -1,3 +1,8 @@ +import { + maxRestorableTextColumnBytes, + truncateToUtf8Bytes, + utf8ByteLength, +} from '@kody-internal/shared/backup-restore-safety.ts' import { emailClassificationValues, type EmailAttachmentRecord, @@ -18,6 +23,26 @@ function nowIso() { return new Date().toISOString() } +export const emailBodyTruncationNotice = + '\n[truncated for backup-safe storage; the full message is retained in the raw MIME object]' + +/** + * Bound stored email body columns so a full `email_messages` row stays + * below D1's import statement limit (oversized rows make D1 backups + * un-importable). The canonical full message remains in the R2 raw MIME + * object referenced by `raw_mime_key`. + */ +function boundedEmailBody(body: string | null | undefined): string | null { + if (body == null) return null + if (utf8ByteLength(body) <= maxRestorableTextColumnBytes) return body + return ( + truncateToUtf8Bytes( + body, + maxRestorableTextColumnBytes - utf8ByteLength(emailBodyTruncationNotice), + ) + emailBodyTruncationNotice + ) +} + export type EmailInboundDeliveryFence = { deliveryId: string userId: string @@ -707,8 +732,8 @@ export async function insertEmailMessage(input: { ? JSON.stringify(input.message.headers) : '{}', auth_results: input.message.authResults ?? null, - text_body: input.message.textBody ?? null, - html_body: input.message.htmlBody ?? null, + text_body: boundedEmailBody(input.message.textBody), + html_body: boundedEmailBody(input.message.htmlBody), raw_mime_key: input.message.rawMimeKey ?? null, raw_size: input.message.rawSize ?? 0, processing_status: input.message.processingStatus, diff --git a/packages/worker/src/index.ts b/packages/worker/src/index.ts index 06d526ad3f..ebadbe3fcc 100644 --- a/packages/worker/src/index.ts +++ b/packages/worker/src/index.ts @@ -85,7 +85,9 @@ import { import { isDrExportConfigured, runDrExportTick, + runDrExportWatchdogTick, shouldRunDrExportCron, + shouldRunDrExportWatchdogCron, } from '#worker/dr/exporter.ts' import { handleDrRestoreRequest } from '#worker/dr/dr-restore.ts' import { OAuthPurgeCoordinator } from './oauth-purge.ts' @@ -663,6 +665,15 @@ const workerHandler = { run: () => runDrExportTick({ env, now: scheduledAt }), }) } + if ( + shouldRunDrExportWatchdogCron(scheduledAt) && + isDrExportConfigured(env) + ) { + lanes.push({ + name: 'dr_export_watchdog', + run: () => runDrExportWatchdogTick({ env, now: scheduledAt }), + }) + } // Lane failures are isolated: each rejection is logged and reported to // Sentry explicitly (the withSentry wrapper flushes captured events via // waitUntil), but the handler never throws, so one broken lane cannot diff --git a/packages/worker/src/index.workers.test.ts b/packages/worker/src/index.workers.test.ts index 626095a430..cb58bc4b0d 100644 --- a/packages/worker/src/index.workers.test.ts +++ b/packages/worker/src/index.workers.test.ts @@ -32,7 +32,9 @@ const mocks = vi.hoisted(() => ({ aggregateUsageRollups: vi.fn(async () => ({ skipped: true })), shouldRunUsageAggregationCron: vi.fn(() => false), runDrExportTick: vi.fn(async () => ({ skipped: true })), + runDrExportWatchdogTick: vi.fn(async () => ({ skipped: true })), shouldRunDrExportCron: vi.fn(() => false), + shouldRunDrExportWatchdogCron: vi.fn(() => false), isDrExportConfigured: vi.fn(() => false), refreshStaleStripePlans: vi.fn(async () => ({ refreshed: 0, @@ -83,7 +85,9 @@ vi.mock('#worker/usage/aggregate-rollups.ts', () => ({ vi.mock('#worker/dr/exporter.ts', () => ({ runDrExportTick: mocks.runDrExportTick, + runDrExportWatchdogTick: mocks.runDrExportWatchdogTick, shouldRunDrExportCron: mocks.shouldRunDrExportCron, + shouldRunDrExportWatchdogCron: mocks.shouldRunDrExportWatchdogCron, isDrExportConfigured: mocks.isDrExportConfigured, })) diff --git a/packages/worker/src/mcp/values/service.node.test.ts b/packages/worker/src/mcp/values/service.node.test.ts index 3bdebf3fdf..b3e3821ae3 100644 --- a/packages/worker/src/mcp/values/service.node.test.ts +++ b/packages/worker/src/mcp/values/service.node.test.ts @@ -1,4 +1,5 @@ import { expect, test } from 'vitest' +import { maxRestorableTextColumnBytes } from '@kody-internal/shared/backup-restore-safety.ts' import { McpCallerError } from '#mcp/caller-error.ts' import { deleteAllAppScopedValues, @@ -373,6 +374,37 @@ test('value service rejects unavailable scoped storage', async () => { ) }) +test('value service rejects values too large for restorable D1 backups', async () => { + const testDb = createValueTestDb() + const env = { APP_DB: testDb.db } + + await expect( + saveValue({ + env, + userId: 'user-123', + scope: 'user', + name: 'giantHistoryCache', + value: 'x'.repeat(maxRestorableTextColumnBytes + 1), + storageContext: { sessionId: null, appId: null }, + }), + ).rejects.toSatisfy( + (error: unknown) => + error instanceof McpCallerError && + error.message.includes('too large to store'), + ) + + // A value at the limit is accepted. + const saved = await saveValue({ + env, + userId: 'user-123', + scope: 'user', + name: 'largeButRestorable', + value: 'x'.repeat(maxRestorableTextColumnBytes), + storageContext: { sessionId: null, appId: null }, + }) + expect(saved.name).toBe('largeButRestorable') +}) + test('deleteAllAppScopedValues removes all app-scoped values for one app', async () => { const testDb = createValueTestDb() const env = { APP_DB: testDb.db } diff --git a/packages/worker/src/mcp/values/service.ts b/packages/worker/src/mcp/values/service.ts index 6716a85dd6..847886b83d 100644 --- a/packages/worker/src/mcp/values/service.ts +++ b/packages/worker/src/mcp/values/service.ts @@ -1,3 +1,7 @@ +import { + maxRestorableTextColumnBytes, + utf8ByteLength, +} from '@kody-internal/shared/backup-restore-safety.ts' import { McpCallerError } from '#mcp/caller-error.ts' import { getStorageBindingKey, @@ -62,6 +66,13 @@ export async function saveValue(input: SaveValueInput): Promise { if (!value) { throw new Error('Value is required.') } + if (utf8ByteLength(value) > maxRestorableTextColumnBytes) { + // Oversized D1 rows serialize into export statements that D1's import + // path rejects, which would make production backups un-restorable. + throw new McpCallerError( + `Value is too large to store (${utf8ByteLength(value)} bytes; the limit is ${maxRestorableTextColumnBytes}). Store large payloads in a durable storage bucket instead and keep values small.`, + ) + } const description = input.description?.trim() ?? '' const bucket = await getOrCreateValueBucket({ db: input.env.APP_DB, diff --git a/packages/worker/src/package-invocations/repo.ts b/packages/worker/src/package-invocations/repo.ts index 92e6709c7c..c9c2cc4723 100644 --- a/packages/worker/src/package-invocations/repo.ts +++ b/packages/worker/src/package-invocations/repo.ts @@ -5,8 +5,34 @@ import { string, type InferOutput, } from 'remix/data-schema' +import { + maxRestorableTextColumnBytes, + utf8ByteLength, +} from '@kody-internal/shared/backup-restore-safety.ts' import { toHex } from '@kody-internal/shared/hex.ts' +/** + * Replay-cache ceiling for `response_json`. Rows above this would serialize + * into D1 export statements that D1's import path rejects (SQLITE_TOOBIG), + * making the whole backup un-restorable. Oversized terminal responses are + * stored as NULL; idempotent duplicates of those invocations get the + * existing `idempotency_response_unavailable` outcome instead of a replay. + */ +export const maxStoredInvocationResponseJsonBytes = maxRestorableTextColumnBytes + +function boundedResponseJson( + response: PackageInvocationStoredResponse, +): string | null { + const responseJson = JSON.stringify({ + status: response.status, + body: response.body, + }) + if (utf8ByteLength(responseJson) > maxStoredInvocationResponseJsonBytes) { + return null + } + return responseJson +} + const packageInvocationRowSchema = object({ id: string(), user_id: string(), @@ -392,10 +418,7 @@ export async function insertPackageInvocationRow(input: { }) { const now = new Date().toISOString() const responseJson = input.row.response - ? JSON.stringify({ - status: input.row.response.status, - body: input.row.response.body, - }) + ? boundedResponseJson(input.row.response) : null const result = await input.db .prepare( @@ -524,10 +547,7 @@ export async function updatePackageInvocationResult(input: { response: PackageInvocationStoredResponse claimUpdatedAt: string }) { - const responseJson = JSON.stringify({ - status: input.response.status, - body: input.response.body, - }) + const responseJson = boundedResponseJson(input.response) const result = await input.db .prepare( `UPDATE package_invocations diff --git a/packages/worker/src/package-invocations/service.node.test.ts b/packages/worker/src/package-invocations/service.node.test.ts index 87de185f5c..c7bd555118 100644 --- a/packages/worker/src/package-invocations/service.node.test.ts +++ b/packages/worker/src/package-invocations/service.node.test.ts @@ -9,6 +9,7 @@ import { invokePackageSubscription, } from './service.ts' import { + maxStoredInvocationResponseJsonBytes, tryClaimStalePackageInvocation, updatePackageInvocationResult, } from './repo.ts' @@ -1623,6 +1624,56 @@ test('invokePackageExport enforces idempotency replay, mismatch, corruption, and ) }) +test('oversized terminal responses are not stored so backups stay restorable', async () => { + const db = createDatabase() + seedPackageResolution() + repoMockModule.runBundledModuleWithRegistry.mockResolvedValue({ + // Serialized response_json above maxStoredInvocationResponseJsonBytes. + result: { blob: 'x'.repeat(maxStoredInvocationResponseJsonBytes + 1) }, + logs: [], + }) + + const first = await invokePackageExport({ + env: createEnv(db), + baseUrl: 'https://kody.dev', + token: createToken(), + request: { + packageIdOrKodyId: 'discord-gateway', + exportName: 'dispatch-message-created', + params: { content: 'hi' }, + idempotencyKey: 'evt-oversized', + source: 'discord-gateway', + topic: 'discord.message.created', + }, + }) + const duplicate = await invokePackageExport({ + env: createEnv(db), + baseUrl: 'https://kody.dev', + token: createToken(), + request: { + packageIdOrKodyId: 'discord-gateway', + exportName: 'dispatch-message-created', + params: { content: 'hi' }, + idempotencyKey: 'evt-oversized', + source: 'discord-gateway', + topic: 'discord.message.created', + }, + }) + + // The first call still returns the live response in full. + expect(first.status).toBe(200) + expect(first.body).toMatchObject({ ok: true }) + // The duplicate is deduplicated (no re-execution) but cannot replay the + // dropped oversized response. + expect(duplicate.status).toBe(409) + expect(duplicate.body).toMatchObject({ + ok: false, + error: { code: 'idempotency_response_unavailable' }, + idempotency: { key: 'evt-oversized', replayed: false }, + }) + expect(repoMockModule.runBundledModuleWithRegistry).toHaveBeenCalledTimes(1) +}) + test('invokePackageExport enforces source scopes for wildcard tokens', async () => { const db = createDatabase() seedPackageResolution() diff --git a/tools/migration-ledger.json b/tools/migration-ledger.json index 607433aa2a..d13618dfa7 100644 --- a/tools/migration-ledger.json +++ b/tools/migration-ledger.json @@ -443,6 +443,10 @@ { "filename": "0104-email-sender-rules-and-classification.sql", "sha256": "3e3d120bbf2bdee3dfcbb939bd7b5f9bca9380d5c6e84b0a94818d34eaaee3bd" + }, + { + "filename": "0105-restore-safe-row-sizes.sql", + "sha256": "0c40218da221b778df2869e0533828844fabe3664423b07a3466721ba924f6c5" } ] }