fix(release): snapshot SQLite before archiving active WAL databases

This commit is contained in:
cesnimda
2026-11-20 19:26:51 +01:00
parent a30e40bd9c
commit 908295c634
6 changed files with 256 additions and 4 deletions
@@ -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.
@@ -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-<stamp>.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.
@@ -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,)])