From 908295c634075e99c15964f482a4147d69fd9dc4 Mon Sep 17 00:00:00 2001 From: cesnimda Date: Fri, 20 Nov 2026 19:26:51 +0100 Subject: [PATCH] fix(release): snapshot SQLite before archiving active WAL databases --- deploy/deploy.sh | 9 +- .../11_BACKUP_RESTORE_ROLLBACK.md | 6 ++ .../evidence/sqlite-archive-format/README.md | 17 ++++ .../reproduce-legacy-wal.py | 54 ++++++++++ scripts/archive-sqlite-volume.py | 75 ++++++++++++++ scripts/test-deploy-backup.py | 99 +++++++++++++++++++ 6 files changed, 256 insertions(+), 4 deletions(-) create mode 100644 docs/release-readiness/evidence/sqlite-archive-format/reproduce-legacy-wal.py create mode 100644 scripts/archive-sqlite-volume.py diff --git a/deploy/deploy.sh b/deploy/deploy.sh index 34640659..4c14f3b8 100644 --- a/deploy/deploy.sh +++ b/deploy/deploy.sh @@ -289,8 +289,8 @@ backup_database() { fi if [ "$provider" = "sqlite" ]; then - # SQLite lives in the jobtracker_data volume. Tar it from a throwaway container - # so the host needs no sqlite tooling and no knowledge of the volume layout. + # Snapshot SQLite through its backup API before archiving the read-only data + # volume. A raw tar can span a WAL checkpoint and omit committed transactions. # # docker compose prefixes volume names with the project name, which defaults to # the directory name. Naming the bare volume here would silently CREATE an empty @@ -307,11 +307,12 @@ backup_database() { echo "Backing up SQLite data volume '${volume}' to ${target}" # The archive path is built inside the container: passing /backup/... as an argument # gets rewritten by MSYS path translation when the script is run from Git Bash. - if ! docker run --rm \ + if ! docker run --rm -i --network none \ -v "$volume":/data:ro \ -v "$BACKUP_DIR":/backup \ -e ARCHIVE_NAME="$(basename "$target")" \ - alpine:3 sh -c 'tar czf "/backup/$ARCHIVE_NAME" -C /data .'; then + python:3.12.10-slim-bookworm sh -c 'umask 077; exec python3 - /data "/backup/$ARCHIVE_NAME"' \ + < scripts/archive-sqlite-volume.py; then echo "SQLite volume backup FAILED. Aborting deploy." rm -f "$target" return 1 diff --git a/docs/release-readiness/11_BACKUP_RESTORE_ROLLBACK.md b/docs/release-readiness/11_BACKUP_RESTORE_ROLLBACK.md index 215dcf1b..9cdcc2ee 100644 --- a/docs/release-readiness/11_BACKUP_RESTORE_ROLLBACK.md +++ b/docs/release-readiness/11_BACKUP_RESTORE_ROLLBACK.md @@ -1,5 +1,11 @@ # Recovery implementation review and rehearsal plan +## RR-17 SQLite WAL snapshot + +At source `a30e40bd9c4d420a2915b65a4483d6734c029a93`, a real GNU tar archive lost a previously committed SQLite row when a WAL checkpoint occurred between reading the main file and its journal. Tar, the header verifier and the restored database integrity check all succeeded. A control archive recovered both rows. The isolated release fix uses SQLite's online backup API for each regular `jobtracker.db` and preserves the existing gzip/tar layout for restore. + +The offline suite passed 35 backup methods and six rollback methods. Linux container execution, closed WAL databases on a read-only mount without sidecars, whole-set consistency and release acceptance remain open. The required image, space and qualification details are in the [WAL evidence](evidence/sqlite-archive-format/README.md#committed-wal-data-20-november-2026). + ## RR-13 monthly recovery period across retention and upload 19 November 2026, isolated release branch from `67b9b675194d3c26432a4da156f680d3368f767e`. A backup that crossed the local month boundary between retention and upload could omit the retained monthly set while reporting success. A failed calendar command could select the monthly root as the destination. A monthly set that disappeared before transfer could also produce a success message. All three cases were reproduced with synthetic files and a recording transfer stub. diff --git a/docs/release-readiness/evidence/sqlite-archive-format/README.md b/docs/release-readiness/evidence/sqlite-archive-format/README.md index 544e3b51..1751ed62 100644 --- a/docs/release-readiness/evidence/sqlite-archive-format/README.md +++ b/docs/release-readiness/evidence/sqlite-archive-format/README.md @@ -25,3 +25,20 @@ The test at `BackupDatabaseMemberTests.test_host_tar_producer_with_database_and_ The focused run overlaps the full suite. To repeat, put the desired tar directory first on PATH and run `python scripts/test-deploy-backup.py BackupDatabaseMemberTests.test_host_tar_producer_with_database_and_sidecar -v`. The test resolves the absolute producer path before invocation. Source baseline `5718d9521be0935e1c0364a775ed8ce7d0702f43`. The validator and deployment script are unchanged. Linux/Alpine producer qualification remains blocked on a pre-existing isolated Linux environment. WSL listed only a stopped Docker Desktop distribution. This fixture's sidecar exercises filename classification only. Live WAL consistency, restore, deployment, permissions, encryption and recovery-set completeness remain open. + +## Committed WAL data, 20 November 2026 + +An open SQLite writer committed row 1, checkpointed, and committed row 2 with automatic checkpoints disabled. The source contained both rows before the backup started. A synthetic padding file and pipe backpressure let the test force a normal checkpoint after GNU tar read the main file and before it read the WAL. The [reproducer](reproduce-legacy-wal.py) uses a temporary volume, a real `tar czf` producer and the deployment's existing archive verifier. + +| Legacy archive | Tar | Format verifier | Restored integrity check | Restored row IDs | +| --- | --- | --- | --- | --- | +| Open writer, stable WAL | 0 | 0 | ok | 1, 2 | +| Open writer, checkpoint between member reads | 0 | 0 | ok | 1 | + +The new producer opens each matching regular SQLite database read-only, holds a read transaction while copying with SQLite's backup API, and writes a self-contained database with rollback journaling enabled. GNU tar archives these snapshots at their original relative paths and omits their obsolete WAL, SHM and rollback journals. Other files retain the original tar path and type handling. The isolated tests recovered both committed rows from the database member alone while a third row remained uncommitted. They checked nested database paths containing brackets/spaces, ordinary adjacent files, unrelated sidecars, and rejection of empty or corrupt input before the next deployment gate. + +The SQLite branch now requires the project's existing `python:3.12.10-slim-bookworm` base image on the Docker host, including Python's sqlite3 module, GNU tar and gzip. The default Docker pull policy can require image acquisition if it is absent. The helper runs with container networking disabled and the source volume mounted read-only. The disposable container filesystem needs room for the separate uncompressed snapshots. Snapshotting holds a database read transaction during copying, which can delay WAL truncation or a rollback-journal writer. Restore consumers continue to receive `jobtracker-sqlite-.tar.gz` and the original database member names. + +**Local evidence.** Windows x64, Python 3.12.10, SQLite 3.49.1, Git for Windows GNU tar 1.35. `python -Werror scripts/test-deploy-backup.py -v` passed 35 methods in 33.602 seconds. `python -Werror scripts/test-deploy-rollback.py -v` passed six methods in 0.867 seconds. Git Bash syntax validation passed. The two focused snapshot methods overlap the 35. The fixture runs the actual deployment backup and verification functions with the Docker invocation mapped to the same shell/Python helper on the host. No image was pulled or executed. An early harness run selected Windows bsdtar, which rejected GNU's anchored exclusions. The producer now resolves the executable from PATH and the Windows harness selects Git's GNU tar. + +**Remaining qualification.** Exercise the image, GNU tar metadata and Linux read-only WAL locking on a disposable target host. Include an idle WAL database with no sidecars, since SQLite can need directory writes to establish them. A read-only open or backup error aborts the gate. Custom connection strings pointing outside the volume, independently changing databases/files, Data Protection keys, tombstones, remote encryption and retrieval, full restore, RPO/RTO and production approval still require their own evidence. Reverting the isolated producer change restores the previous raw-volume behavior and its demonstrated race. diff --git a/docs/release-readiness/evidence/sqlite-archive-format/reproduce-legacy-wal.py b/docs/release-readiness/evidence/sqlite-archive-format/reproduce-legacy-wal.py new file mode 100644 index 00000000..f5605f56 --- /dev/null +++ b/docs/release-readiness/evidence/sqlite-archive-format/reproduce-legacy-wal.py @@ -0,0 +1,54 @@ +"""Synthetic control showing a checkpoint between tar reads of a database and its WAL.""" +from contextlib import closing +import os +from pathlib import Path +import sqlite3 +import subprocess +import sys +import tarfile +import tempfile + +producer, validator = sys.argv[1:] +with tempfile.TemporaryDirectory(prefix='legacy-sqlite-wal-') as temp: + root = Path(temp) + volume = root / 'data' + volume.mkdir() + with closing(sqlite3.connect(volume / 'jobtracker.db')) as writer: + assert writer.execute('PRAGMA journal_mode=WAL').fetchone() == ('wal',) + writer.execute('PRAGMA wal_autocheckpoint=0') + writer.execute('CREATE TABLE receipt (id INTEGER PRIMARY KEY)') + writer.execute('INSERT INTO receipt VALUES (1)') + writer.commit() + assert writer.execute('PRAGMA wal_checkpoint(TRUNCATE)').fetchone()[0] == 0 + writer.execute('INSERT INTO receipt VALUES (2)') + writer.commit() + # Sorted after the main file and before the WAL. Backpressure on the archive's + # output stream holds tar here while SQLite performs its ordinary checkpoint. + (volume / 'jobtracker.db-padding').write_bytes(os.urandom(4 * 1024 * 1024)) + for mode in ('stable', 'checkpoint'): + archive = root / (mode + '.tar.gz') + with subprocess.Popen([producer, 'czf', '-', '--sort=name', '-C', 'data', '.'], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, cwd=root) as tar: + first = tar.stdout.read(65536) + if mode == 'checkpoint': + assert writer.execute('PRAGMA wal_checkpoint(TRUNCATE)').fetchone()[0] == 0 + rest, stderr = tar.communicate(timeout=20) + assert tar.returncode == 0, stderr + archive.write_bytes(first + rest) + validation = subprocess.run([sys.executable, validator, archive], capture_output=True, timeout=10) + assert validation.returncode == 0, validation.stderr + restored = root / ('restored-' + mode) + restored.mkdir() + with tarfile.open(archive) as bundle: + for name in ('jobtracker.db', 'jobtracker.db-wal', 'jobtracker.db-shm'): + member = bundle.getmember('./' + name) + with bundle.extractfile(member) as stream: + (restored / name).write_bytes(stream.read()) + with closing(sqlite3.connect(restored / 'jobtracker.db')) as copy: + rows = copy.execute('SELECT id FROM receipt ORDER BY id').fetchall() + assert copy.execute('PRAGMA integrity_check').fetchone() == ('ok',) + expected = [(1,), (2,)] + assert writer.execute('SELECT id FROM receipt ORDER BY id').fetchall() == expected + print(f'{mode}: tar exit 0, verifier exit 0, source {expected}, restored {rows}, integrity ok') + assert rows == (expected if mode == 'stable' else [(1,)]) diff --git a/scripts/archive-sqlite-volume.py b/scripts/archive-sqlite-volume.py new file mode 100644 index 00000000..3082ba09 --- /dev/null +++ b/scripts/archive-sqlite-volume.py @@ -0,0 +1,75 @@ +"""Archive a volume with standalone SQLite snapshots and the remaining original files.""" +from contextlib import closing +import os +from pathlib import Path +import shutil +import sqlite3 +import stat +import subprocess +import sys +import tempfile + + +def snapshot(source, destination): + info = source.lstat() + if not stat.S_ISREG(info.st_mode): + raise ValueError('Expected a regular database file.') + with source.open('rb') as original: + if original.read(16) != b'SQLite format 3\x00': + raise ValueError('Expected a SQLite database header.') + with closing(sqlite3.connect(source.as_uri() + '?mode=ro', uri=True)) as reader: + # Establish one read transaction before copying. WAL writers may keep + # committing without moving the snapshot or restarting a large backup. + reader.execute('BEGIN') + reader.execute('PRAGMA schema_version').fetchone() + with closing(sqlite3.connect(destination)) as copied: + reader.backup(copied) + if copied.execute('PRAGMA journal_mode=DELETE').fetchone() != ('delete',): + raise ValueError('Snapshot still requires a journal.') + if hasattr(os, 'chown'): + os.chown(destination, info.st_uid, info.st_gid) + shutil.copystat(source, destination) + + +def archive_volume(volume, target): + def raise_walk_error(error): + raise error + + # Keep uncompressed snapshots on the throwaway container filesystem. + with tempfile.TemporaryDirectory(prefix='sqlite-snapshot-') as temporary: + stage = Path(temporary) + excludes = [] + snapshots = [] + for folder, dirs, files in os.walk(volume, onerror=raise_walk_error): + if 'jobtracker.db' in dirs: + raise ValueError('Expected a database file.') + if 'jobtracker.db' not in files: + continue + source = Path(folder) / 'jobtracker.db' + name = source.relative_to(volume).as_posix() + staged = stage / 'snapshot' / name + staged.parent.mkdir(parents=True, exist_ok=True) + snapshot(source, staged) + snapshots.append('snapshot/' + name) + for suffix in ('', '-shm', '-wal', '-journal'): + excludes.append('--exclude=./' + name + suffix) + if not snapshots: + raise ValueError('No database found.') + # The original volume's names start with "./". Only staged members match + # this transform. Literal, anchored excludes preserve unrelated sidecars. + tar = shutil.which('tar') + if not tar: + raise FileNotFoundError('GNU tar is required.') + subprocess.run([tar, 'czf', target.name, '--anchored', '--no-wildcards', *excludes, + '--transform=flags=r;s|^snapshot/|./|', '-C', volume.as_posix(), '.', + '-C', stage.as_posix(), *snapshots], + cwd=target.parent, check=True, stderr=subprocess.DEVNULL) + + +if __name__ == '__main__': + try: + volume, target = map(Path, sys.argv[1:]) + archive_volume(volume.resolve(strict=True), target.absolute()) + except (OSError, ValueError, sqlite3.Error, subprocess.CalledProcessError): + # Member names and database contents may contain private information. + sys.exit('SQLite volume snapshot or archive creation failed.') diff --git a/scripts/test-deploy-backup.py b/scripts/test-deploy-backup.py index 7868bdb2..129ed6f0 100644 --- a/scripts/test-deploy-backup.py +++ b/scripts/test-deploy-backup.py @@ -2,6 +2,7 @@ import os import io import gzip +from contextlib import closing from pathlib import Path import shlex import shutil @@ -451,6 +452,104 @@ class BackupSqlTrailerTests(unittest.TestCase): self.assertNotIn('NEXT DEPLOY GATE WOULD START', result.stdout) +class BackupSqliteSnapshotTests(unittest.TestCase): + def backup(self, root): + source = (ROOT / 'deploy/deploy.sh').read_text(encoding='utf-8') + functions = [] + for name in ['backup_database', 'verify_backup_file_shape', 'verify_volume_backup']: + start = source.index(name + '() {') + functions.append(source[start:source.index('\n}\n', start) + 3]) + launch = next(line for line in functions[0].splitlines() if 'python:3.12.10-slim-bookworm sh -c' in line) + command = launch.split("sh -c '", 1)[1].split("'", 1)[0] + local_command = command.replace('exec python3', 'exec "$PYTHON"').replace(' /data ', ' "$VOLUME" ') + local_command = local_command.replace('"/backup/', '"$BACKUP_DIR/') + # Map only container paths and the Python executable to this host. The + # shell body, helper from stdin, SQLite, tar and validator all run. + script = '\n'.join([ + 'set -euo pipefail', + 'BACKUP_DIR=' + shlex.quote((root / 'backups').as_posix()), + 'VOLUME=' + shlex.quote((root / 'data').as_posix()), + 'PYTHON=' + shlex.quote(Path(sys.executable).as_posix()), + 'DATABASE_PROVIDER=sqlite; BACKUP_STAMP=fixture; DEPLOY_SKIP_DB_BACKUP=false; COMPOSE_PROJECT_NAME=fixture', + 'python3() { "$PYTHON" "$@"; }', + 'report_backup() { echo "FORMAT VERIFIED"; }', + 'docker() {', + ' if [[ "$1 $2" == "volume inspect" ]]; then return 0; fi', + ' [[ "$*" == *"fixture_jobtracker_data:/data:ro "* && "$*" == *" --network none "* ]] || return 99', + ' local arg', + ' [[ "${!#}" == ' + shlex.quote(command) + ' ]] || return 99', + ' for arg in "$@"; do case "$arg" in ARCHIVE_NAME=*) export "$arg";; esac; done', + ' export PYTHON VOLUME BACKUP_DIR', + ' bash -c ' + shlex.quote(local_command), + '}', + *functions, + 'if ! backup_database; then exit 1; fi', + 'echo "NEXT DEPLOY GATE WOULD START"', + ]) + env = os.environ.copy() + if os.name == 'nt': + env['PATH'] = str(Path(BASH).parents[1] / 'usr/bin') + os.pathsep + env['PATH'] + return subprocess.run([BASH, '--noprofile', '--norc'], input=script, cwd=ROOT, env=env, + capture_output=True, text=True, encoding='utf-8', timeout=30) + + def test_standalone_snapshot_contains_committed_wal_rows_with_writer_open(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + volume = root / 'data' + nested = volume / 'nested [copy]' + nested.mkdir(parents=True) + (volume / 'jobtracker.db-notes').write_bytes(b'attachment data') + (nested / 'unrelated.db-wal').write_bytes(b'unrelated file') + # An identically named database in a nested directory retains its path. + with closing(sqlite3.connect(nested / 'jobtracker.db')) as other: + other.execute('CREATE TABLE nested_fixture (id INTEGER)') + with closing(sqlite3.connect(volume / 'jobtracker.db')) as writer: + self.assertEqual(('wal',), writer.execute('PRAGMA journal_mode=WAL').fetchone()) + writer.execute('PRAGMA wal_autocheckpoint=0') + writer.execute('CREATE TABLE receipt (id INTEGER PRIMARY KEY)') + writer.execute('INSERT INTO receipt VALUES (1)') + writer.commit() + self.assertEqual(0, writer.execute('PRAGMA wal_checkpoint(TRUNCATE)').fetchone()[0]) + writer.execute('INSERT INTO receipt VALUES (2)') + writer.commit() + writer.execute('INSERT INTO receipt VALUES (3)') + self.assertGreater((volume / 'jobtracker.db-wal').stat().st_size, 0) + result = self.backup(root) + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + self.assertIn('NEXT DEPLOY GATE WOULD START', result.stdout) + writer.rollback() + self.assertEqual(0, writer.execute('PRAGMA wal_checkpoint(TRUNCATE)').fetchone()[0]) + + with tarfile.open(root / 'backups/jobtracker-sqlite-fixture.tar.gz') as bundle: + for sidecar in ['-wal', '-shm', '-journal']: + self.assertNotIn('./jobtracker.db' + sidecar, bundle.getnames()) + for path, expected in [('./jobtracker.db-notes', b'attachment data'), + ('./nested [copy]/unrelated.db-wal', b'unrelated file')]: + with bundle.extractfile(path) as stream: + self.assertEqual(expected, stream.read()) + for name, query, expected in [('./jobtracker.db', 'SELECT id FROM receipt ORDER BY id', [(1,), (2,)]), + ('./nested [copy]/jobtracker.db', 'SELECT * FROM nested_fixture', [])]: + with self.subTest(name=name), bundle.extractfile(name) as stream: + restored = root / 'restored.db' + restored.write_bytes(stream.read()) + with closing(sqlite3.connect(restored.as_uri() + '?mode=ro', uri=True)) as copy: + self.assertEqual(expected, copy.execute(query).fetchall()) + self.assertEqual(('ok',), copy.execute('PRAGMA integrity_check').fetchone()) + self.assertEqual(('delete',), copy.execute('PRAGMA journal_mode').fetchone()) + + def test_invalid_database_prevents_archive_promotion(self): + for contents in [b'', b'SQLite format 3\x00' + bytes(200)]: + with self.subTest(size=len(contents)), tempfile.TemporaryDirectory() as temp: + root = Path(temp) + (root / 'data').mkdir() + (root / 'data/jobtracker.db').write_bytes(contents) + result = self.backup(root) + self.assertNotEqual(0, result.returncode, result.stdout + result.stderr) + self.assertNotIn('FORMAT VERIFIED', result.stdout) + self.assertNotIn('NEXT DEPLOY GATE WOULD START', result.stdout) + self.assertEqual([], list((root / 'backups').iterdir())) + + class BackupDatabaseMemberTests(unittest.TestCase): def test_host_tar_producer_with_database_and_sidecar(self): producer = shutil.which('tar')