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
8 changes: 6 additions & 2 deletions docs/DEPENDABOT-UPDATE-LIFECYCLE.md
Original file line number Diff line number Diff line change
Expand Up @@ -350,12 +350,16 @@ Observed technical follow-ups from the 2026-11-06 run
- The remaining batch PRs #288, #289, #290 received new heads after the #287
merge; their earlier CI greens and Codex state predate those heads, so each
needs fresh checks before its own merge GO.
- Weekly restore-check cron: the code comment in platform/src/backup.ts says
- Weekly restore-check cron: the code comment in platform/src/backup.ts said
"Mon 04:30 UTC", but the Cloudflare Quartz expression `30 4 * * 1` fires on
SUNDAY (Quartz weekdays run 1 = Sunday to 7 = Saturday)
[RULE: https://developers.cloudflare.com/workers/configuration/cron-triggers/;
https://github.com/commonworld-one/commonworld/blob/main/platform/src/backup.ts].
Code comment and actual behavior disagree.
Fix prepared 2026-11-22 in an unpublished branch: labels say Sunday and the
expression is intentionally unchanged, so live triggers would not move; not
yet merged or deployed. Verified live the same day: the production dashboard
trigger reads "At 04:30 AM on Sunday" and the weekly check ran on Sundays
Nov 1, 8, 15 and 22.
- The repo's backup runbook documents the full end-to-end restore drill (a
production dump restored into a scratch D1) as the second line behind D1 Time
Travel. Recorded to date: a restore drill on STAGING data (2026-10-18, which
Expand Down
14 changes: 14 additions & 0 deletions platform/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@

Newest first. Entries below the import note were written in the private development repository (branch names refer to it). One entry per pushed step on `v1/cloudflare-foundation`.

## 2026-11-22 — Restore-check docs say Sunday, as deployed

Not yet deployed.

- The weekly restore check has always fired on Sunday 04:30 UTC in production: Cloudflare's cron parser counts the
weekday field 1 = Sunday (documented: https://developers.cloudflare.com/workers/configuration/cron-triggers/ —
"Days of the week go from 1 = Sunday to 7 = Saturday"), so `30 4 * * 1` means Sunday, not Monday as comments and
docs said. The expression is intentionally unchanged, so this changes no schedule and no live trigger. Verified
live 2026-11-22: the production trigger reads "At 04:30 AM on Sunday" and the check ran on Sundays Nov 1, 8, 15
and 22.
- Comments (`src/backup.ts`, `wrangler.toml`), `README.md`, the OpenAPI description of `GET /v1/admin/backups`, the
ops runbook and one test title now say Sunday / "weekly check" instead of Monday.
- No behavior, configuration, migration or dependency change.

## 2026-11-21 — Backup: one name per run, key paging for large tables

Not yet deployed.
Expand Down
2 changes: 1 addition & 1 deletion platform/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ object), and prunes `rate_windows` older than 2 h (hourly/daily buckets only: pe
**D1 backups (Cron Triggers, inside Cloudflare)**: daily **03:00 UTC** the Worker dumps every D1 table (schema + all rows)
into one gzipped SQL file + manifest in its environment's private R2 bucket (binding `BACKUPS`: production
`commonworld-backups`, staging `commonworld-backups-staging`, local simulated `commonworld-backups-local`; keys `prod/` /
`staging/` / `local/` + `d1/YYYY-MM-DD.sql.gz`; a job refuses to run when env, bucket and prefix do not match); every **Monday 04:30 UTC** it checks the newest backup (sha256, full
`staging/` / `local/` + `d1/YYYY-MM-DD.sql.gz`; a job refuses to run when env, bucket and prefix do not match); every **Sunday 04:30 UTC** it checks the newest backup (sha256, full
parse, row counts vs manifest, ≤ 36 h old) and writes `<env>/checks/YYYY-MM-DD.json`. One log line per run
(`console.error` on failure, never row data); status at `GET /v1/admin/backups`. Objects expire after 35 days (bucket
lifecycle). Code `src/backup.ts`, runbook `docs/ops/BACKUP-RESTORE.md`, tests `test/backup.test.ts`.
Expand Down
16 changes: 9 additions & 7 deletions platform/docs/ops/BACKUP-RESTORE.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ production bind different buckets and production's is `commonworld-backups`. The
| When (UTC) | Job | Writes |
|---|---|---|
| daily 03:00 (before the 03:17 retention clean-up) | **backup**: every D1 table (schema from `sqlite_master` + every row, read in pages of 5000: a table of up to 5000 rows is read in one D1 batch, i.e. one transaction; a larger table is read by key in several calls, see "What a dump guarantees") → one SQL file → gzip | `<env>/d1/YYYY-MM-DDTHHMMSSZ.sql.gz` + `.manifest.json`, one name per run (a same-second rerun adds `-2`); older `YYYY-MM-DD.*` objects stay valid |
| Monday 04:30 | **restore check** of the newest backup: sha256 of the `.gz` and of the SQL, every statement parsed (each row decoded, column count checked), table list + row count per table + `sqlite_sequence` counters against the manifest, newest backup ≤ 36 h old | `<env>/checks/YYYY-MM-DD.json` |
| Sunday 04:30 | **restore check** of the newest backup: sha256 of the `.gz` and of the SQL, every statement parsed (each row decoded, column count checked), table list + row count per table + `sqlite_sequence` counters against the manifest, newest backup ≤ 36 h old | `<env>/checks/YYYY-MM-DD.json` |

`<env>` = `prod` (production), `staging`, `local` (tests / `wrangler dev`, simulated bucket). Each env has its own bucket (table above).

Expand Down Expand Up @@ -185,7 +185,7 @@ curl -s -H "Authorization: Bearer $ADMIN_KEY" https://commonworld.one/v1/admin/b
```

`healthy` is false when there is no backup, the newest is older than 36 h (the daily job stopped or was killed),
there is no check yet, the newest check failed, or the newest check is older than 8 days (the Monday job stopped), or a backup or check timestamp lies in the future (more than 5 min ahead). Run a job by hand (same code as the cron; a backup overwrites
there is no check yet, the newest check failed, or the newest check is older than 8 days (the weekly job stopped), or a backup or check timestamp lies in the future (more than 5 min ahead). Run a job by hand (same code as the cron; a backup overwrites
today's file):

```
Expand All @@ -200,16 +200,18 @@ curl -s -X POST -H "Authorization: Bearer $ADMIN_KEY" -H 'content-type: applicat
- Tables of at most 5000 rows, and `sqlite_sequence`, are read together in one `db.batch`, which D1 runs as one transaction.
- A larger table is read in several calls at different moments. Pages after the first use the key (`rowid > last`, or the primary key columns of a WITHOUT ROWID table), not an offset. A row that is not inserted, updated, deleted or re-keyed during the dump appears exactly once. This is **not a point-in-time snapshot**: a row changed during the dump may carry an older or newer value, and a row inserted or deleted during it may be present or absent. Different tables can also be read at different moments.
- Today the only such tables are `unnamed_agent_visits` and `ai_bot_visits` (manifest of 2026-11-20: 42,386 and 25,745 rows). The writer upserts today's UTC day, so today's visit counts can mix moments.
- The manifest has a `consistency` block: `paged_tables` lists every table that needed more than one read (mode, key, pages, rows, `count_after`, `changed_during_dump`). `count_after` is a COUNT(*) after the last page. A difference proves the table changed during the dump; equality does not prove it did not, because updates are not counted. The Monday check prints such tables as a note and does not fail on them.
- The manifest has a `consistency` block: `paged_tables` lists every table that needed more than one read (mode, key, pages, rows, `count_after`, `changed_during_dump`). `count_after` is a COUNT(*) after the last page. A difference proves the table changed during the dump; equality does not prove it did not, because updates are not counted. The weekly check prints such tables as a note and does not fail on them.
- A table with no usable key (no primary key, a column named `rowid`, or a key value that is not a string or a safe number) falls back to offset paging and is marked `mode: offset` with a reason.
- The Monday check proves the file is intact and parseable and matches its manifest. It does not load the dump into a database.
- The weekly check proves the file is intact and parseable and matches its manifest. It does not load the dump into a database.
- For a consistent export of a large database, D1's own export is the alternative, but Cloudflare documents that a running export blocks other database requests (https://developers.cloudflare.com/d1/best-practices/import-export-data/). Time Travel restores in place (https://developers.cloudflare.com/d1/reference/time-travel/).
- Names: each run claims its name with a create-only R2 put (`If-None-Match: *`), so parallel runs in the same second get `-2`, `-3`, ... and nothing is overwritten; if 50 names are taken the run fails. "Newest" is chosen by stamp text, then the `-N` number as a number (`-12` after `-9`). The create-only put is tested against the local R2 simulator only; Cloudflare documents conditional put (null on a failed condition) and conditional headers (https://developers.cloudflare.com/r2/api/workers/workers-api-reference/), but I did not test it against real R2.
- Check results are still named `<env>/checks/YYYY-MM-DD.json`: a second check on the same day overwrites the first.

### Verify the Monday check
### Verify the weekly check

The check runs every Monday at 04:30 UTC (cron times are UTC all year, no daylight-saving shift). On Monday after 04:30 UTC:
The check runs every Sunday at 04:30 UTC (cron times are UTC all year, no daylight-saving shift). The expression is
`30 4 * * 1` because Cloudflare's cron parser counts the weekday field 1 = Sunday (Quartz-style); do not "fix" it to
Monday without a deploy decision. On Sunday after 04:30 UTC:

1. `GET /v1/admin/backups` (admin key): `latest_check.ok` is `true`, `latest_check.checked_at` is today ~04:30 UTC,
`latest_check.backup_key` is the newest `<env>/d1/YYYY-MM-DD[THHMMSSZ].sql.gz`, `problems` is empty and `healthy` is `true`.
Expand Down Expand Up @@ -283,7 +285,7 @@ state); the others are not recorded as done.
- [x] R2 bucket `commonworld-backups-staging` + lifecycle `expire-35d` (delete after 35 days; the
bucket's default rule aborts incomplete multipart uploads after 7 days) - created by the owner 2026-10-20.
- [x] Code: crons + `BACKUPS` binding in `wrangler.toml` for staging and production (2026-10-20, not deployed yet).
- [ ] Deploy it to staging first (owner's yes), run both jobs there, and see the next Monday check PASS on staging.
- [ ] Deploy it to staging first (owner's yes), run both jobs there, and see the next Sunday check PASS on staging.
- [ ] Deploy production as usual (`../docs/DEPLOY.md`); the crons and the binding come with it. Nothing else to set.
- [ ] Right after the deploy: `POST /v1/admin/backups/run {"job":"backup"}`, then `{"job":"restore-check"}` → `ok: true`;
`GET /v1/admin/backups` → `healthy: true`.
Expand Down
5 changes: 3 additions & 2 deletions platform/src/backup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
* (row count per table, sqlite_sequence counters, last migration, sha256 of the
* artifact and of the plain SQL). Same manifest format as scripts/d1-backup.sh, so
* scripts/d1-restore.sh restores a Worker backup unchanged.
* RESTORE_CHECK_CRON Mon 04:30 UTC runRestoreCheck(): newest backup -> sha256 (gz + SQL) -> full parse of every
* RESTORE_CHECK_CRON Sun 04:30 UTC runRestoreCheck(): newest backup -> sha256 (gz + SQL) -> full parse of every
* statement (each INSERT decoded to its values, column count checked) -> table
* list, row counts, sqlite_sequence vs manifest -> age <= 36 h. Result to
* `<env>/checks/YYYY-MM-DD.json` + one log line (console.error on FAIL).
Expand All @@ -31,13 +31,14 @@
import type { Env } from './env';

export const BACKUP_CRON = '0 3 * * *';
// Sunday 04:30 UTC: Cloudflare's cron parser counts the weekday field 1 = Sunday (Quartz-style).
export const RESTORE_CHECK_CRON = '30 4 * * 1';
export const BACKUP_FORMAT = 'commonworld-d1-backup/1';
/** Rows per SELECT page. The first page of every table is read in one D1 batch (one transaction = one consistent snapshot). */
export const PAGE_ROWS = 5000;
/** A newest backup older than this fails the restore check (the daily job stopped). */
export const MAX_BACKUP_AGE_HOURS = 36;
/** The Monday check runs weekly; one missed run plus a day of slack before status turns unhealthy. */
/** The weekly check runs on Sunday; one missed run plus a day of slack before status turns unhealthy. */
export const MAX_CHECK_AGE_DAYS = 8;
/** A backup or restore-check timestamp may run ahead of `now` by at most this much (clock skew); later = unhealthy. */
/** Names tried for one run second before the run fails (nothing is overwritten). */
Expand Down
2 changes: 1 addition & 1 deletion platform/src/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ export const OPERATIONS: Operation[] = [
note: 'Guesses from request headers, not identities.' } },
errors: ['invalid_days', 'invalid_limit', 'unknown_bot', 'invalid_verified'] },
{ method: 'GET', path: '/v1/admin/backups', tag: 'Admin', auth: 'admin', ok: 200, summary: 'D1 backups: newest daily backups in R2 and the newest weekly restore check',
description: 'The Worker backs up the whole D1 database every day at 03:00 UTC (schema + every row of every table, one gzipped SQL file + a manifest with row counts and sha256) into the private R2 bucket of its environment (production commonworld-backups, staging commonworld-backups-staging; `bucket` names it) under <env>/d1/, and every Monday 04:30 UTC checks the newest backup (sha256, full parse of every statement, table list, row counts and sqlite_sequence against the manifest, age <= 36 h), result under <env>/checks/. Objects are deleted by the bucket lifecycle after 35 days. `healthy` is false when there is no backup, the newest is older than 36 h, there is no check yet, or the newest check failed; `problems` says which. Lists up to 14 backups, newest first. Counts and hashes only, never row data. 503 backup_target_mismatch = ENVIRONMENT, bucket and key prefix do not match (the job refuses to read or write).',
description: 'The Worker backs up the whole D1 database every day at 03:00 UTC (schema + every row of every table, one gzipped SQL file + a manifest with row counts and sha256) into the private R2 bucket of its environment (production commonworld-backups, staging commonworld-backups-staging; `bucket` names it) under <env>/d1/, and every Sunday 04:30 UTC checks the newest backup (sha256, full parse of every statement, table list, row counts and sqlite_sequence against the manifest, age <= 36 h), result under <env>/checks/. Objects are deleted by the bucket lifecycle after 35 days. `healthy` is false when there is no backup, the newest is older than 36 h, there is no check yet, or the newest check failed; `problems` says which. Lists up to 14 backups, newest first. Counts and hashes only, never row data. 503 backup_target_mismatch = ENVIRONMENT, bucket and key prefix do not match (the job refuses to read or write).',
example: { environment: 'prod', bucket: 'commonworld-backups', healthy: true, problems: ['newest backup older than 36 h'],
backups: [{ key: 'prod/d1/2026-11-02.sql.gz', bytes: 48211, uploaded: '2026-11-02T03:00:02.114Z', created_utc: '2026-11-02T03:00:01Z', total_rows: 701, table_count: 32, sha256: '9f86d081…' }],
latest_check: { ok: true, checked_at: '2026-11-02T04:30:00Z', backup_key: 'prod/d1/2026-11-02.sql.gz', backup_created_utc: '2026-11-02T03:00:01Z', age_hours: 1.5, table_count: 32, total_rows: 701, problems: ['…'] } },
Expand Down
2 changes: 1 addition & 1 deletion platform/test/backup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ describe('cron dispatch', () => {
}
const keys = async () => ((await E.BACKUPS.list()).objects as R2Object[]).map((o) => o.key).sort();

it('03:00 UTC backs up, Monday 04:30 UTC checks, the other crons do neither', async () => {
it('03:00 UTC backs up, Sunday 04:30 UTC checks, the other crons do neither', async () => {
vi.spyOn(console, 'log').mockImplementation(() => undefined);
await fire(CLEANUP_CRON);
expect(await keys()).toEqual([]);
Expand Down
3 changes: 2 additions & 1 deletion platform/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ SETTINGS_CACHE_MS = "5000"

# Nightly (UTC) retention clean-up (deletes daily_usage and idempotency_keys rows older than 30 days, src/retention.ts)
# + full counters reconcile; hourly karma_7d window expiry + stored ranks (src/counters.ts). scheduled() in src/index.ts.
# Daily 03:00 UTC D1 backup to R2 + weekly Monday 04:30 UTC restore check (src/backup.ts, docs/ops/BACKUP-RESTORE.md).
# Daily 03:00 UTC D1 backup to R2 + weekly Sunday 04:30 UTC restore check (src/backup.ts, docs/ops/BACKUP-RESTORE.md).
# `30 4 * * 1` fires on Sunday: Cloudflare's cron parser counts the weekday field 1 = Sunday (Quartz-style).
# Must equal [CLEANUP_CRON, HOURLY_CRON, BACKUP_CRON, RESTORE_CHECK_CRON] (src/retention.ts, src/backup.ts; a test checks).
[triggers]
crons = ["17 3 * * *", "7 * * * *", "0 3 * * *", "30 4 * * 1"]
Expand Down
Loading