diff --git a/docs/litestream.md b/docs/litestream.md index 530292d2..b452bd23 100644 --- a/docs/litestream.md +++ b/docs/litestream.md @@ -275,11 +275,33 @@ inside `shutdown-sync-timeout: 45s` (kept at 45s: the Coolify stop grace is 60s, so it must stay under about 55s) and failed. Request count is unchanged (one L0 PUT per txid either way); only upload timing moves. -Separate, and **not** fixed by this key: every Litestream (re)start writes one -~DB-sized full-snapshot L0 (about 4 GB here) as its first new txid, because the -WAL continuity check cannot prove the WAL is unchanged across a restart. Those -files track deploy/restart count, not the sync interval. Fewer restarts is the -only lever. +Separate, and **not** fixed by this key: restart snapshots. When the last +read-write connection to a WAL database closes, SQLite checkpoints it and then +deletes or resets the `-wal` file. Litestream keeps the WAL on its own +shutdown (`PERSIST_WAL`), but the node startup scripts that run between +Litestream's stop and its next start (pre-migration backup check, billing-link +audit, unique-index check, `migrate-safe`) do not. When one of them closes +last, the next Litestream start finds the WAL shorter than its last LTX +position or with a new salt, logs `reason="wal truncated by another process"` +(debug level), and writes a full-database snapshot L0 (about 4 GB here) as its +first txid on every deploy or restart. The `-wal` can still be on disk when +the container boots; the scripts are what reset it. A plain Litestream +stop/start with nothing read-write touching the DB in between does not +snapshot. + +`scripts/start-with-litestream.sh` therefore starts +`scripts/sqlite-wal-guard.mjs` right after the restore step and before any +script that opens the database: one idle read-only connection, no open +transaction (so Litestream's checkpoints are unaffected), never closed by the +guard itself. A read-only connection cannot checkpoint or delete the WAL, so +even a clean exit of the guard leaves it intact. It stays a child of +Litestream after `exec` and is SIGKILLed with the container, so the startup +scripts are never the last read-write closer and the next start continues +incrementally. If the guard does not become ready the wrapper logs a warning +and behaves as before. The first start after this change still snapshots once +(the previous boot already reset the WAL); the one after it should not. The R2 +sibling path keeps bash as the wrapper, so the guard also lives until the +container ends there. ### Free-tier growth (what to expect) diff --git a/scripts/production-app-watch-paths.json b/scripts/production-app-watch-paths.json index 3563a5e2..72aaa803 100644 --- a/scripts/production-app-watch-paths.json +++ b/scripts/production-app-watch-paths.json @@ -23,5 +23,6 @@ "scripts/ensure-subscription-link-unique-index.mjs", "scripts/audit-subscription-links.mjs", "scripts/replica-status-heartbeat.sh", - "scripts/run-app-with-replica-heartbeat.sh" + "scripts/run-app-with-replica-heartbeat.sh", + "scripts/sqlite-wal-guard.mjs" ] diff --git a/scripts/sqlite-wal-guard.mjs b/scripts/sqlite-wal-guard.mjs new file mode 100644 index 00000000..8538a5bb --- /dev/null +++ b/scripts/sqlite-wal-guard.mjs @@ -0,0 +1,46 @@ +#!/usr/bin/env node +// Holds one idle, READ-ONLY SQLite connection to the production database for +// the life of the container so that no startup script (pre-migration backup, +// billing-link audit, unique-index check, migrate-safe) is ever the last +// READ-WRITE connection to close it. +// +// Why: when the last connection to a WAL database closes, SQLite runs a +// checkpoint and then deletes (or resets) the -wal file; only a read-write +// connection can do that. Litestream keeps the WAL on its own shutdown +// (PERSIST_WAL), but the node startup scripts that run between Litestream's +// stop and its next start do not. When one of them closes last, Litestream's +// next start finds the WAL shorter than its last LTX position (or with a new +// salt), logs reason="wal truncated by another process", and writes a +// full-database snapshot L0 (about 4 GB for Usage-Monitor) on every deploy or +// restart. +// +// The guard holds no transaction after its one probe query, so it never +// blocks Litestream's PASSIVE or TRUNCATE checkpoints. It is read-only, so +// even if it is the last connection to close it cannot checkpoint or remove +// the WAL (verified: process.exit, db.close() and a natural exit all leave the +// -wal intact). It still ignores SIGTERM/SIGINT/SIGHUP and never closes the +// database itself: the container teardown SIGKILLs it after Litestream exits. +// +// usage: sqlite-wal-guard.mjs [ready-file] +import { DatabaseSync } from "node:sqlite"; +import { writeFileSync } from "node:fs"; + +const [path, readyFile] = process.argv.slice(2); +if (!path) { + console.error("[sqlite-wal-guard] usage: sqlite-wal-guard.mjs [ready-file]"); + process.exit(2); +} + +// Read-only: the guard must never write, checkpoint, or change journal mode. +const db = new DatabaseSync(path, { readOnly: true, timeout: 30_000 }); +// sqlite3_open is lazy; one statement maps the -shm and joins the WAL. +db.prepare("SELECT 1 FROM sqlite_master LIMIT 1").get(); + +// No close handlers on purpose: ignore stop signals so the only exit is SIGKILL. +for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) { + process.on(signal, () => {}); +} + +if (readyFile) writeFileSync(readyFile, `${process.pid}\n`); +console.log(`[sqlite-wal-guard] holding idle read-only connection to ${path} (pid ${process.pid}).`); +setInterval(() => {}, 1 << 30); diff --git a/scripts/start-with-litestream.sh b/scripts/start-with-litestream.sh index b7a2937b..38382360 100644 --- a/scripts/start-with-litestream.sh +++ b/scripts/start-with-litestream.sh @@ -233,6 +233,39 @@ stop_replica_heartbeat() { REPLICA_HEARTBEAT_PID="" } +# Keep one idle read-only connection open from here until the container dies +# so the node startup scripts below are never the last READ-WRITE connection to +# close prod.db. The last read-write closer checkpoints and deletes/resets the +# WAL, and Litestream then writes a full-database snapshot L0 (~4 GB) on its +# next start ("wal truncated by another process"). See +# scripts/sqlite-wal-guard.mjs and docs/litestream.md. The guard is never +# stopped: after `exec litestream` it stays a child of Litestream and is +# SIGKILLed with the container. It runs without NODE_OPTIONS (no dd-trace +# preload) and with stdio on /dev/null so it cannot hold a log pipe open. +start_sqlite_wal_guard() { + if [[ "${litestream_enabled}" != "true" || ! -f "${DB_PATH}" ]]; then + return 0 + fi + local ready_file + ready_file="$(mktemp /tmp/um-sqlite-wal-guard-ready.XXXXXX)" + rm -f "${ready_file}" + env -u NODE_OPTIONS node "${REPO_ROOT}/scripts/sqlite-wal-guard.mjs" "${DB_PATH}" "${ready_file}" \ + /dev/null 2>&1 & + SQLITE_WAL_GUARD_PID=$! + local waited=0 + while [[ ! -f "${ready_file}" ]] && kill -0 "${SQLITE_WAL_GUARD_PID}" 2>/dev/null && (( waited < 100 )); do + sleep 0.1 + waited=$((waited + 1)) + done + if [[ -f "${ready_file}" ]]; then + log "sqlite WAL guard started pid=${SQLITE_WAL_GUARD_PID}." + else + log "WARNING: sqlite WAL guard did not become ready; the next Litestream start may write a full snapshot." + fi + rm -f "${ready_file}" +} +start_sqlite_wal_guard + log "Disk space on /data before backup:" df -h /data || true du -sh /data/.* 2>/dev/null || true diff --git a/scripts/test-startup-config.mjs b/scripts/test-startup-config.mjs index 9812c350..975a2e1f 100644 --- a/scripts/test-startup-config.mjs +++ b/scripts/test-startup-config.mjs @@ -201,6 +201,24 @@ try { const linkIndexIndex = startupSource.indexOf( 'node "${REPO_ROOT}/scripts/ensure-subscription-link-unique-index.mjs"' ); + // The WAL guard must be running before ANY startup script opens prod.db + // read-write, or that script is the last closer and Litestream writes a + // full-database snapshot on its next start. + const walGuardIndex = startupSource.indexOf("\nstart_sqlite_wal_guard\n"); + if ( + walGuardIndex < 0 || + walGuardIndex >= backupIndex || + walGuardIndex >= linkAuditIndex || + walGuardIndex >= linkIndexIndex || + walGuardIndex >= migrationIndex + ) { + throw new Error( + "startup wrapper must start the SQLite WAL guard before backup, link audit, link index and migrate-safe" + ); + } + if (!/--require dd-trace\/init/.test(startupSource) || !/env -u NODE_OPTIONS node "\$\{REPO_ROOT\}\/scripts\/sqlite-wal-guard\.mjs"/.test(startupSource)) { + throw new Error("the SQLite WAL guard must run without the dd-trace NODE_OPTIONS preload"); + } if ( backupIndex < 0 || linkAuditIndex < 0 ||