Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 33 additions & 5 deletions docs/contributing/disaster-recovery.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 `<objectKey>.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:
Expand Down Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -336,52 +336,6 @@ export class CachedUploadStep implements BackupRuntimeStep {
async sleep(): Promise<void> {}
}

export class RetryFinalizationStep implements BackupRuntimeStep {
readonly finalizationAttempts: number[] = []
private readonly cache = new Map<string, unknown>()

async do<T>(
name: string,
config: unknown,
callback: () => Promise<T>,
): Promise<T>
async do<T>(name: string, callback: () => Promise<T>): Promise<T>
async do<T>(
name: string,
configOrCallback: unknown,
callback?: () => Promise<T>,
): Promise<T> {
if (this.cache.has(name)) return this.cache.get(name) as T
const execute =
typeof configOrCallback === 'function'
? (configOrCallback as () => Promise<T>)
: 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<void> {}
}

export class RetryUploadStep implements BackupRuntimeStep {
readonly uploadAttempts: number[] = []
private readonly cache = new Map<string, unknown>()
Expand Down
134 changes: 71 additions & 63 deletions packages/backup-control-plane/backup-runtime.node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import {
DATABASE_ID,
MemoryBucket,
RetryAfterCommitStep,
RetryFinalizationStep,
RetryUploadStep,
environment,
exportEnvelope,
Expand Down Expand Up @@ -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[] = []
Expand Down Expand Up @@ -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'),
Expand All @@ -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 () => {
Expand Down Expand Up @@ -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,
)
})

Expand Down Expand Up @@ -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(
Expand All @@ -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()
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading