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
+99
View File
@@ -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')