TRENDING
A small white dog with a dark ear curled up asleep on a wooden table beside a brown clay pot, a wicker basket and a bundle of sticks, in a dark seventeenth century Dutch painting
December 2, 2026
How to Alert When Prometheus Stops Seeing Your Service: Tell a Crash From a Removed Target From a Renamed Metric, Use absent() Without False Alarms, and Test Every Silent Failure With promtool
Four round faceted dark red garnet gemstones in a row on a white surface
December 2, 2026
DeepMind’s CellGemma Turns Virtual Drug Screening Into a Residual on Top of the Population Mean, but an MLP Given the Same Baseline Reproduces About Half of Its 16-Point Lead, “All 32 Settings” Holds for One of 12 Metrics, and the Wet-Lab Result Is Three of Five Compounds Against No Comparison Set
Roulette wheel with the white ball resting in the zero pocket
December 2, 2026
CISA Lists the Rejetto HFS Session-Forgery Flaw 140 Days After Its Fix, and GreyNoise’s Report of Its Use Shows One HFS Server Serving as a Relay for 24 Check Point Management Servers the Actor Already Held, With an AI Role It Infers but Does Not Show
Three dark hybrid ducks with white markings foraging in tall green grass on a sunny bank
December 2, 2026
How to Turn On Post-Quantum Key Exchange in nginx and Prove It: Read the Negotiated Group With OpenSSL 3.5, Handle Fallbacks and Oversized Hellos, and Check Every Host in CI
A yellow diamond road sign showing a speed bump beside a SLOW sign on a leafy residential street, with painted chevrons on the road ahead of the raised bump
December 2, 2026
Amodei’s “Pace the Frontier” Essay Turns a Six-Week Delay Into a Legislative Prototype, but Only One of Its Three Delays Has a Date, the 14-Day Wait Has No Stated Start and Adds at Most Two Weeks a Generation in a Simple Model, and the January Restart Has No Test
02 Dec 2026
SXZ.io SXZ.io
  • Home
Search the Site
Popular Searches:
Technology Amazon AI
Recent Posts
A black compact spare tire lying flat on a concrete floor next to a scissor jack and a lug wrench, photographed from above
How to Back Up a Live SQLite Database Without Corrupting It: Count the Broken Copies, Use the Backup API or VACUUM INTO, Publish Only Backups That Verify, and Restore Past a Stale -wal File
December 2, 2026
A blue Link Trainer, the 1930s flight simulator, with yellow wings and tail on a museum stand
Ai2’s DR Tulu 2 Turns Search Bills Into a Local Simulator and Its Table Reproduces, but the Repo Trains Finance Before Science While the Paper Says the Reverse, Never Names DR-Anything, the Framework the Post Tells Readers to Use, and Two Benchmarks Supply 56% of the +9.7 Lead
December 2, 2026
An open split key ring lying on a gray surface, its two ends not meeting
Docker Fixes a Sandboxes Bug That Let a Kit Update Redirect a Stored API Key, but the Same Flaw Scores 5.6, 6.9 or 8.2, the Finder Demonstrated One of 13 Services, and the Upgrade Stops Reading the Environment Variables Some Teams Use to Require Signed Kits
December 2, 2026
SXZ.io SXZ.io
  • Home

Categories

Articles 328 Posts
News 334 Posts
Learning Hub 300 Posts
Home/Learning Hub/How to Back Up a Live SQLite Database Without Corrupting It: Count the Broken Copies, Use the Backup API or VACUUM INTO, Publish Only Backups That Verify, and Restore Past a Stale -wal File
Learning Hub

How to Back Up a Live SQLite Database Without Corrupting It: Count the Broken Copies, Use the Backup API or VACUUM INTO, Publish Only Backups That Verify, and Restore Past a Stale -wal File

Copy a SQLite file while an app is writing and 169 of 250 copies broke, 168 of them passing integrity_check; measure it, then back up safely with the backup API or VACUUM INTO, verify every backup,...

December 2, 2026 46 Min Read
11

A SQLite database is one ordinary file, so backing it up looks easy: copy the file. Many backup scripts and file-sync tools do exactly that. The catch is that copying a file takes time, and while the copy runs your application may commit changes. The copy then holds some pages from before the commit and some from after it. The SQLite documentation says so plainly: “The backup copy then might contain some old and some new content, and thus be corrupt.”

Table Of Content

  • Before you start
  • How SQLite keeps a commit safe, and why a copier can break it
  • Rollback journal mode (the default)
  • WAL mode
  • Step 1: Build a bank that can prove it is intact
  • Step 2: Keep an application writing
  • Step 3: Copy it the way most backup scripts do, and count the broken copies
  • Does it depend on how busy the application is?
  • Step 4: WAL mode changes the failure, it does not remove it
  • Step 5: Use the backup API, and know what it costs
  • What it costs the application
  • Do not back up in small steps while the database is busy
  • Step 6: VACUUM INTO and sqlite3_rsync, the other two official ways
  • sqlite3_rsync
  • Step 7: Turn it into a tool that publishes only backups that verified
  • What each part is for
  • Run it against a live database
  • Step 8: Restore, and the stale -wal trap
  • Step 9: Test the tool, then test the tests
  • The three official ways, side by side
  • Common mistakes, and how to spot them
  • Check that everything works end to end
  • Where to go next
  • Sources

In this tutorial you will find out how often that really happens, measure it, and then fix it. You will build a small bank database that can prove whether a copy of it is intact, keep an application writing to it, and copy it hundreds of times in each of the ways people really back up SQLite. In my runs, a plain copy of a busy database in SQLite’s default mode was broken in 169 of 250 tries, and SQLite’s own integrity check noticed exactly one of them. Then you will learn the safe ways, see what each one costs the application while it runs, build a backup tool that publishes only backups that verified, and learn how to restore without tripping over a leftover -wal file. Finally you will test the tool, and then test the tests by planting bugs in it.

If you have read the PostgreSQL point-in-time recovery tutorial or the incremental backup tutorial, this is the same lesson for a database that is a single file: a backup you have never restored is a hope, not a backup, and a copy that was never checked can fail without any error.

Before you start

You need Python 3.12 or newer and a terminal. I ran everything on Windows 11 with Python 3.13.14, which bundles SQLite 3.50.4, and pytest 9.1.1 for the tests. The code uses only the standard library, so it should behave the same on Linux and macOS, but I did not run it there. You should be comfortable reading short Python scripts and basic SQL; you do not need to know how SQLite stores data, because the next section explains what matters.

Make an empty folder and put every file from this page in it, under the file name in its first comment line. Install the one package you need for the last steps:

python -m pip install pytest==9.1.1

The lab copies a 32 MB file hundreds of times, one copy at a time, and deletes each copy after checking it, so about 200 MB of free disk is plenty. The long runs take a few minutes each on my machine (the main table in step 3 takes about eleven), so start them and read on.

Five words are used throughout, so here they are in plain terms. A transaction is a group of changes that must happen all together or not at all, and a commit is the moment SQLite makes the group permanent. A page is the fixed-size block (4,096 bytes by default) that SQLite reads and writes; a database file is a long row of pages. A snapshot is a consistent picture of the database at a single instant. An invariant is a rule that is true for all good data, such as the rule that the balances always add up to the same total.

How SQLite keeps a commit safe, and why a copier can break it

A commit that changes twenty pages cannot be written in one instant. If the power fails halfway, SQLite must be able to finish or undo the work, and it does that with a side file. There are two designs, and your database uses one of them. The default is the rollback journal; the other is write-ahead logging, called WAL. A backup has to cope with both.

Rollback journal mode (the default)

The SQLite documentation describes it like this: “The traditional rollback journal works by writing a copy of the original unchanged database content into a separate rollback journal file and then writing changes directly into the database file.” The journal lives next to the database as name-journal and is deleted when the commit finishes. While a commit is in progress, the main file is a mixture of old and new pages, and only the journal knows how to undo the new ones. A program that copies just the main file at that moment gets the mixture, with no journal to repair it. The documentation warns about the crash version of the same problem: “If the hot journal files are moved, deleted, or renamed after a crash or power failure, then automatic recovery will not work and the database may go corrupt.”

WAL mode

WAL inverts the design: “The original content is preserved in the database file and the changes are appended into a separate WAL file. A COMMIT occurs when a special record indicating a commit is appended to the WAL.” The main file stays untouched until a checkpoint, which the documentation defines as moving “the WAL file transactions back into the database”. By default SQLite runs one when the WAL file reaches about 1,000 pages, roughly 4 MB. So in WAL mode the real database is the main file plus the -wal file, and a third file, -shm, holds an index for them. Copying only the main file gives you a consistent but older database; copying the main file and then the WAL as two separate steps pairs files from two different moments if a checkpoint runs between the two copies. You will measure both.

The official guidance, quoted from the documentation, is short: there are “multiple safe approaches to making backup copies of SQLite databases”, namely the sqlite3_rsync program, the VACUUM INTO command and the backup API. And a plain file copy is only safe “as long as there are no transactions in progress while the copy is taking place”. The rest of this tutorial puts numbers on that sentence.

Step 1: Build a bank that can prove it is intact

To count broken copies you need a database that can tell a good copy from a bad one. A bank is a convenient example because money only moves between accounts: whatever happens, the balances must add up to the same total. The script below creates 100,000 accounts of 1,000 each, with a 300-byte note on every row so that the file is large enough for a copy to take a measurable amount of time. It also defines transfer_batch, one transaction that moves money between ten random pairs of accounts, records each transfer in a second table, and bumps a counter in a third. A transaction therefore touches pages scattered across the file, which is exactly what a real application does.

# bank.py
"""A tiny bank. Its data can prove that a copy of it is intact."""
import sqlite3

ACCOUNTS = 100_000        # rows in the accounts table
START = 1_000             # every account starts with this balance
TOTAL = ACCOUNTS * START  # the balances must always add up to this
PADDING = "x" * 300       # makes each row about 320 bytes, so the file is about 35 MB

SCHEMA = """
CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER NOT NULL, note TEXT NOT NULL);
CREATE TABLE transfers (id INTEGER PRIMARY KEY AUTOINCREMENT, src INTEGER NOT NULL,
                        dst INTEGER NOT NULL, amount INTEGER NOT NULL);
CREATE TABLE meta (key TEXT PRIMARY KEY, value INTEGER NOT NULL);
"""


def make_db(path, journal_mode="delete"):
    """Create and fill the database. journal_mode is 'delete' (SQLite's default) or 'wal'."""
    con = sqlite3.connect(path, isolation_level=None)
    con.execute(f"PRAGMA journal_mode = {journal_mode}").fetchone()
    con.executescript(SCHEMA)
    con.execute("BEGIN")
    con.executemany("INSERT INTO accounts VALUES (?, ?, ?)",
                    ((i, START, PADDING) for i in range(1, ACCOUNTS + 1)))
    con.execute("INSERT INTO meta VALUES ('transfers', 0)")
    con.execute("COMMIT")
    con.close()


def transfer_batch(con, rng, count=10):
    """One transaction: move money between random accounts and keep the books in step."""
    con.execute("BEGIN IMMEDIATE")
    for _ in range(count):
        src, dst = rng.sample(range(1, ACCOUNTS + 1), 2)
        amount = rng.randint(1, 50)
        con.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?", (amount, src))
        con.execute("UPDATE accounts SET balance = balance + ? WHERE id = ?", (amount, dst))
        con.execute("INSERT INTO transfers (src, dst, amount) VALUES (?, ?, ?)",
                    (src, dst, amount))
    con.execute("UPDATE meta SET value = value + ? WHERE key = 'transfers'", (count,))
    con.execute("COMMIT")

Two details are worth knowing. isolation_level=None turns off Python’s automatic transaction handling, so the code issues BEGIN and COMMIT itself and you can see where a transaction starts and ends. And BEGIN IMMEDIATE takes SQLite’s write lock at the start of the transaction, which is the pattern from the “database is locked” tutorial.

Now the other half: a checker. SQLite has a built-in PRAGMA integrity_check, which verifies the structure of the file, such as page links and index order. It cannot know that your balances should add up to 100,000,000, so the checker below runs it first and then applies the bank’s own rules. It reports one of four verdicts: ok; unreadable (SQLite cannot open the copy); integrity (SQLite’s own check failed); or invariant (the file is structurally fine but the data breaks a rule).

# check.py
"""Decide whether a copy of the bank database is intact, the way a restore would find out."""
import sqlite3

from bank import TOTAL


def bank_problems(con):
    """The bank's own rules, as a list of problems. An empty list means the books balance."""
    total = con.execute("SELECT SUM(balance) FROM accounts").fetchone()[0]
    rows = con.execute("SELECT COUNT(*) FROM transfers").fetchone()[0]
    claimed = con.execute("SELECT value FROM meta WHERE key = 'transfers'").fetchone()[0]
    problems = []
    if total != TOTAL:
        problems.append(f"balances add up to {total:,} instead of {TOTAL:,}")
    if rows != claimed:
        problems.append(f"the transfers table has {rows:,} rows but meta says {claimed:,}")
    return problems


def inspect(path):
    """Return (verdict, detail). The verdict is ok, unreadable, integrity or invariant."""
    try:
        con = sqlite3.connect(path)
        try:
            found = [row[0] for row in con.execute("PRAGMA integrity_check")]
            if found != ["ok"]:
                return "integrity", f"integrity_check says: {found[0]}"
            wrong = bank_problems(con)
            if wrong:
                return "invariant", "; ".join(wrong)
            rows = con.execute("SELECT COUNT(*) FROM transfers").fetchone()[0]
            return "ok", f"{rows:,} transfers, balances add up to {TOTAL:,}"
        finally:
            con.close()
    except sqlite3.DatabaseError as exc:
        return "unreadable", str(exc)


def verdict(path):
    return inspect(path)[0]


if __name__ == "__main__":
    import sys
    print(*inspect(sys.argv[1]))

Create the database and check it. The first command builds the file, the second runs the checker, the third prints its size in bytes:

$ python -c "import bank; bank.make_db('bank.db')"
$ python check.py bank.db
ok 0 transfers, balances add up to 100,000,000
$ python -c "import os; print(os.path.getsize('bank.db'))"
31612928

A fresh database passes both layers and is about 32 MB (it grows slowly as the writer adds transfers). If the second command printed anything other than ok, stop and fix that before you go on.

Step 2: Keep an application writing

A backup test is only meaningful if something is changing the data while you copy it, so the next script plays the part of the live application. It runs as a separate process, the way a real service would, and commits one transfer_batch after another until a file called stop.txt appears. It prints ready after its first commit, and at the end it writes a log of every commit’s start time and duration, which later steps use to measure how long the application waits. The optional last argument is a pace in commits per second; zero means as fast as possible.

# writer.py
"""The live application: commit transfers until a stop file appears, and log how long each commit took."""
import json
import os
import random
import sqlite3
import sys
import time

from bank import transfer_batch


def main(path, stop_file, log_file, pace=0.0, seed=1):
    rng = random.Random(seed)
    con = sqlite3.connect(path, isolation_level=None, timeout=30)
    log = []                      # (wall-clock start, seconds the commit took)
    next_slot = time.time()
    while not os.path.exists(stop_file):
        started, t0 = time.time(), time.perf_counter()
        transfer_batch(con, rng)
        log.append((started, time.perf_counter() - t0))
        if len(log) == 1:
            print("ready", flush=True)
        if pace:                  # pace = commits per second; 0 means as fast as possible
            next_slot += 1.0 / pace
            delay = next_slot - time.time()
            if delay > 0:
                time.sleep(delay)
            else:
                next_slot = time.time()   # fell behind: do not try to catch up
    con.close()
    with open(log_file, "w") as handle:
        json.dump(log, handle)


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2], sys.argv[3], float(sys.argv[4]) if len(sys.argv) > 4 else 0.0)

Open two terminals. In the first, start the writer at 50 commits per second. Three seconds later, in the second, create the stop file and check the database again:

--- terminal A
$ python writer.py bank.db stop.txt log.json 50
ready
--- terminal B, three seconds later
$ python -c "open('stop.txt', 'w').close()"
$ python check.py bank.db
ok 1,530 transfers, balances add up to 100,000,000
$ python -c "import json; log = json.load(open('log.json')); print(len(log), 'commits')"
153 commits; slowest 22.6 ms

The writer made 153 commits of ten transfers each in a little over three seconds, the slowest taking 22.6 milliseconds, and the database is still intact: 1,530 transfers are recorded, the transfer table agrees with the counter, and the balances still add up to 100,000,000.

Step 3: Copy it the way most backup scripts do, and count the broken copies

Here are the ways to copy the database that this tutorial compares. Each function takes a source path and a destination path. The first, copy_file, is what cp, copy, rsync, Explorer and most backup agents do. The others appear in later steps, so skim them now and come back.

# strategies.py
"""Ways to copy a SQLite database. Each takes (source path, destination path)."""
import os
import shutil
import sqlite3
import time


def copy_file(src, dst):
    """What cp, copy, rsync, Explorer and most backup agents do: copy the file."""
    shutil.copyfile(src, dst)


def copy_file_and_wal(src, dst):
    """The same, but remember the write-ahead log too (database first, then the log)."""
    shutil.copyfile(src, dst)
    if os.path.exists(src + "-wal"):
        shutil.copyfile(src + "-wal", dst + "-wal")


def copy_file_then_wal_after(pause):
    """The same two steps with `pause` seconds between them, a stand-in for a database that is slow to copy."""
    def strategy(src, dst):
        shutil.copyfile(src, dst)
        time.sleep(pause)
        if os.path.exists(src + "-wal"):
            shutil.copyfile(src + "-wal", dst + "-wal")
    strategy.__name__ = f"pause_{pause:g}_s"
    return strategy


def lock_then_copy(src, dst):
    """Take SQLite's write lock so nobody can commit, copy the files, release the lock."""
    con = sqlite3.connect(src, isolation_level=None, timeout=30)
    con.execute("BEGIN IMMEDIATE")
    try:
        copy_file_and_wal(src, dst)
    finally:
        con.execute("ROLLBACK")
        con.close()


def backup_api(src, dst):
    """SQLite's online backup API, as Python exposes it: Connection.backup()."""
    source = sqlite3.connect(src, timeout=30)
    target = sqlite3.connect(dst)
    try:
        source.backup(target)
    finally:
        target.close()
        source.close()


def vacuum_into(src, dst):
    """VACUUM INTO writes a compacted, consistent copy of the live database to a new file."""
    con = sqlite3.connect(src, isolation_level=None, timeout=30)
    try:
        con.execute("VACUUM INTO ?", (dst,))
    finally:
        con.close()

The experiment is simple. A writer commits 50 batches a second against the database. For each strategy, the test script waits a random 0 to 50 milliseconds so that every copy lands at a different point in the writer’s cycle, makes the copy, and judges it with the checker from step 1. It also asks the live database how many commits it has made since the copy’s snapshot, which tells you how stale a good copy is. The copy.db file is deleted after each judgement, so the disk never fills.

# tear_test.py
"""Copy a database while it is being written to, over and over, and count the broken copies."""
import argparse
import json
import os
import random
import sqlite3
import statistics
import subprocess
import sys
import time
from collections import Counter

from bank import make_db
from check import inspect
from strategies import (backup_api, copy_file, copy_file_and_wal, copy_file_then_wal_after, lock_then_copy,
                        vacuum_into)

HERE = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(HERE, "data")
VERDICTS = ("ok", "invariant", "integrity", "unreadable", "error")


def start_writer(db, pace=0.0):
    stop = os.path.join(DATA, "stop")
    if os.path.exists(stop):
        os.remove(stop)
    log = os.path.join(DATA, "writer_log.json")
    cmd = [sys.executable, os.path.join(HERE, "writer.py"), db, stop, log, str(pace)]
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True, cwd=HERE)
    assert proc.stdout.readline().strip() == "ready"
    return proc, stop, log


def stop_writer(proc, stop, log):
    open(stop, "w").close()
    proc.wait(timeout=60)
    with open(log) as handle:
        return json.load(handle)


def remove_files(path):
    for suffix in ("", "-wal", "-shm", "-journal"):
        if os.path.exists(path + suffix):
            os.remove(path + suffix)


def fresh_db(mode):
    db = os.path.join(DATA, f"bank_{mode}.db")
    remove_files(db)
    make_db(db, mode)
    return db


def live_transfers(db):
    con = sqlite3.connect(db, timeout=30)
    try:
        return con.execute("SELECT value FROM meta WHERE key = 'transfers'").fetchone()[0]
    finally:
        con.close()


def trials(strategy, db, count, seed=7):
    """Copy `count` times at random moments and judge every copy."""
    rng = random.Random(seed)
    tally, examples, millis, behind = Counter(), {}, [], []
    dst = os.path.join(DATA, "copy.db")
    for _ in range(count):
        time.sleep(rng.uniform(0, 0.05))      # land at a random moment in the writer's cycle
        remove_files(dst)
        try:
            started = time.perf_counter()
            strategy(db, dst)
            millis.append((time.perf_counter() - started) * 1000)
            live = live_transfers(db)         # how far the live database has moved on
            verdict, detail = inspect(dst)
            if verdict == "ok":
                copied = int(detail.split()[0].replace(",", ""))
                behind.append((live - copied) // 10)   # each commit moves 10 transfers
        except (sqlite3.Error, OSError) as exc:
            verdict, detail = "error", f"{type(exc).__name__}: {exc}"
        tally[verdict] += 1
        examples.setdefault(verdict, detail)
    remove_files(dst)
    return {"tally": tally, "examples": examples,
            "ms": statistics.median(millis) if millis else 0,
            "behind": statistics.median(behind) if behind else None}


def header(first):
    return f"{first:<18}" + "".join(f"{v:>11}" for v in VERDICTS) + f"{'median ms':>11}{'commits behind':>16}"


def row(name, result):
    behind = "-" if result["behind"] is None else f"{result['behind']:g}"
    return (f"{name:<18}" + "".join(f"{result['tally'][v]:>11}" for v in VERDICTS)
            + f"{result['ms']:>11.0f}{behind:>16}")


def table(count, pace):
    plans = {
        "delete": [copy_file, lock_then_copy, backup_api, vacuum_into],
        "wal": [copy_file, copy_file_and_wal, lock_then_copy, backup_api, vacuum_into],
    }
    for mode, strategies in plans.items():
        db = fresh_db(mode)
        proc, stop, log = start_writer(db, pace)
        try:
            print(f"journal mode: {mode}, writer at {pace:g} commits per second, {count} copies per strategy")
            print(header("strategy"))
            examples = {}
            for strategy in strategies:
                result = trials(strategy, db, count)
                print(row(strategy.__name__, result))
                for verdict in VERDICTS[1:]:
                    if verdict in result["examples"]:
                        examples[(strategy.__name__, verdict)] = result["examples"][verdict]
        finally:
            commits = stop_writer(proc, stop, log)
        print(f"(the writer committed {len(commits):,} transactions while this ran)")
        for (name, verdict), detail in examples.items():
            print(f"  e.g. {name} -> {verdict}: {detail}")
        print()


def pace_sweep(count):
    db = fresh_db("delete")
    print(f"journal mode: delete, plain file copy, {count} copies per writer speed")
    print(header("commits per second"))
    for pace in (1, 5, 20, 100, 0):
        proc, stop, log = start_writer(db, pace)
        try:
            result = trials(copy_file, db, count)
        finally:
            stop_writer(proc, stop, log)
        print(row(str(pace) if pace else "no limit", result))


def gap_sweep(count, pace):
    db = fresh_db("wal")
    print(f"journal mode: wal, main file then -wal file with a pause between, writer at {pace:g} commits per second,"
          f" {count} copies per pause")
    print(header("pause between"))
    proc, stop, log = start_writer(db, pace)
    try:
        for pause in (0.1, 0.5, 1.5):
            result = trials(copy_file_then_wal_after(pause), db, count)
            print(row(f"{pause:g} s", result))
            for verdict in VERDICTS[1:]:
                if verdict in result["examples"]:
                    print(f"  e.g. {pause:g} s -> {verdict}: {result['examples'][verdict]}")
    finally:
        stop_writer(proc, stop, log)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("what", choices=["table", "pace", "gap"])
    parser.add_argument("--trials", type=int, default=200)
    parser.add_argument("--pace", type=float, default=50)
    args = parser.parse_args()
    os.makedirs(DATA, exist_ok=True)
    if args.what == "table":
        table(args.trials, args.pace)
    elif args.what == "pace":
        pace_sweep(args.trials)
    else:
        gap_sweep(args.trials, args.pace)

Run the experiment with 250 copies per strategy. The command tests a default (rollback journal) database first and a WAL database second, and takes about eleven minutes, so I show the first half here and the second half in step 4:

python tear_test.py table --trials 250 --pace 50
journal mode: delete, writer at 50 commits per second, 250 copies per strategy
strategy                   ok  invariant  integrity unreadable      error  median ms  commits behind
copy_file                  81        168          1          0          0         14               1
lock_then_copy            250          0          0          0          0         15               0
backup_api                250          0          0          0          0        163               2
vacuum_into               250          0          0          0          0        182               2
(the writer committed 8,082 transactions while this ran)
  e.g. copy_file -> invariant: balances add up to 100,000,095 instead of 100,000,000
  e.g. copy_file -> integrity: integrity_check says: *** in database main ***
Page 7733: never used

Read the columns like this. ok: the copy passes every check. invariant: SQLite found nothing wrong with the file, but the data breaks a bank rule. integrity: SQLite’s own integrity_check failed. unreadable: SQLite could not open the copy. error: the copying itself failed. median ms: how long one copy took. commits behind: for the good copies, the median number of commits the live database had made beyond the copy by the time the copy finished.

The plain file copy, the method you most likely use today, produced 169 broken copies out of 250: 168 in the invariant column and 1 in the integrity column. That is the frightening part. SQLite’s own check caught one of the 169 and passed the other 168. Those copies open, they answer queries, and their balances are wrong; the first example line under the table shows one that adds up to 100,000,095 instead of 100,000,000. This happens because every commit rewrites pages scattered across the file, and the copy reads the file from start to end over about 14 milliseconds (the median in the table). A page that a commit changed before the copy reached it is new; a page the copy had already read is old. Money that moved between two accounts on different pages shows up half applied.

The other three rows are all good in this run. lock_then_copy works in rollback-journal mode because, while it holds the write lock, nobody can commit, so the file cannot change under the copy. backup_api and vacuum_into take the same kind of read lock but let SQLite do the reading; they are slower (a median of 163 and 182 milliseconds against 14) and are the subject of steps 5 and 6.

Does it depend on how busy the application is?

It does, and this is the reason a plain copy survives testing. Run the same plain copy against writers of different speeds (150 copies per speed, about three minutes):

python tear_test.py pace --trials 150
journal mode: delete, plain file copy, 150 copies per writer speed
commits per second         ok  invariant  integrity unreadable      error  median ms  commits behind
1                         149          1          0          0          0         14               0
5                         146          4          0          0          0         14               0
20                        118         32          0          0          0         14               0
100                         6        144          0          0          0         14             1.5
no limit                   14        136          0          0          0         15             4.5

At one commit per second only 1 of 150 copies was broken, and at five per second 4 were, so a quiet staging database makes the method look fine. At 20 commits per second 32 of 150 (21 percent) were broken, at 100 per second 144 of 150 (96 percent), and with the writer unlimited 136 of 150 (91 percent). The SQLite documentation agrees with the low end of this table: a plain copy is safe “as long as there are no transactions in progress while the copy is taking place”. The sweep shows how quickly that condition stops being true.

Step 4: WAL mode changes the failure, it does not remove it

Many SQLite applications run in WAL mode, so the same command also repeated the experiment on a WAL database. There is one new row: copy_file_and_wal copies the main file and then the -wal file as a second step, while copy_file now copies only the main file.

journal mode: wal, writer at 50 commits per second, 250 copies per strategy
strategy                   ok  invariant  integrity unreadable      error  median ms  commits behind
copy_file                 249          0          0          1          0         14              21
copy_file_and_wal         250          0          0          0          0         17               0
lock_then_copy            250          0          0          0          0         18               0
backup_api                250          0          0          0          0        211              10
vacuum_into               250          0          0          0          0        245              12
(the writer committed 15,818 transactions while this ran)
  e.g. copy_file -> unreadable: database disk image is malformed

Three things stand out. First, the main file alone (copy_file) is rarely corrupt in WAL mode: 249 of 250 copies passed every check, and the one that failed was unreadable, “database disk image is malformed”. In WAL mode the main file only changes at a checkpoint, so a copy that overlaps a checkpoint is the likely cause; I did not trace that single case further. But look at commits behind: the median “good” copy was 21 commits out of date. The main file is a consistent picture of an older moment, and everything still in the -wal file is missing. Green means consistent, not current.

Second, copying the main file and then the -wal file passed all 250 tries with no commits behind. That does not make it safe. The two copies took 17 milliseconds together, and the method only fails when a checkpoint lands between them. To see what happens with a bigger database, which takes seconds to copy rather than milliseconds, the next experiment pauses between the two copies (60 copies per pause, about three minutes):

python tear_test.py gap --trials 60 --pace 50
journal mode: wal, main file then -wal file with a pause between, writer at 50 commits per second, 60 copies per pause
pause between              ok  invariant  integrity unreadable      error  median ms  commits behind
0.1 s                      57          3          0          0          0        117               0
  e.g. 0.1 s -> invariant: balances add up to 99,999,962 instead of 100,000,000; the transfers table has 3,080 rows but meta says 3,530
0.5 s                      30         17          0         13          0        518               0
  e.g. 0.5 s -> invariant: balances add up to 99,999,901 instead of 100,000,000; the transfers table has 8,360 rows but meta says 8,900
  e.g. 0.5 s -> unreadable: database disk image is malformed
1.5 s                       0         15          0         45          0       1518               -
  e.g. 1.5 s -> invariant: balances add up to 100,000,085 instead of 100,000,000; the transfers table has 33,880 rows but meta says 34,870
  e.g. 1.5 s -> unreadable: database disk image is malformed

With a 0.1-second pause, 3 of 60 copies were wrong. With half a second, 30 of 60 were broken: 17 had bad data and 13 could not be opened at all. With 1.5 seconds, all 60 were broken. The reason is mechanical: a checkpoint during the pause writes pages into the live main file and starts a new log, so the log you copy afterwards belongs to a newer moment than the main file you copied first. The “250 of 250” above is not evidence that the method is safe; it is evidence that a 32 MB file is quick to copy.

Third, lock_then_copy also passed all 250 tries in WAL mode. It holds the write lock, so no commit can run during the copy, and the automatic checkpoints that follow commits cannot run either. It is a valid method, and the SQLite documentation’s rule (“as long as there are no transactions in progress”) is exactly what it enforces. The cost is that the application cannot commit while you hold the lock, which step 5 measures.

Step 5: Use the backup API, and know what it costs

The backup API reads pages through SQLite’s own locking, so a single-step backup returns a snapshot of one moment. In Python it is Connection.backup, which is what backup_api above calls. Both tables show it as a safe and easy choice: backup_api made 250 good copies in each journal mode, and none failed any check. A copy took a median of 163 milliseconds in rollback mode and 211 in WAL mode, against 14 for a plain file copy, probably because SQLite does the page-level work itself and syncs the result when it finishes; I did not profile it. The copies are also slightly behind the live database (2 commits in rollback mode, 10 in WAL mode): the snapshot is taken when the backup starts and the writer keeps committing while the copy is written out. That is what a snapshot means: all of one moment, none of the next.

What it costs the application

A backup is not free for the application, and the cost depends on the journal mode. The next script measures the slowest commit the writer experienced while each backup ran. Each row is the median of five backups at 50 commits per second.

# stall_test.py
"""How long does the writer wait while a backup runs? Measure the slowest commit during each backup."""
import os
import statistics
import time

from strategies import backup_api, lock_then_copy, vacuum_into
from tear_test import DATA, fresh_db, remove_files, start_writer, stop_writer

REPEATS = 5


def measure(mode, strategy, pace=50):
    db = fresh_db(mode)
    proc, stop, log = start_writer(db, pace)
    dst = os.path.join(DATA, "stall_copy.db")
    try:
        time.sleep(2.0)                          # let the writer settle into its rhythm
        remove_files(dst)
        t0 = time.time()
        strategy(db, dst)
        t1 = time.time()
        time.sleep(1.0)
    finally:
        entries = stop_writer(proc, stop, log)
    remove_files(dst)
    calm = [d for s, d in entries if s < t0 - 0.2]
    window = [d for s, d in entries if s <= t1 and s + d >= t0]
    finished = sum(1 for s, d in entries if t0 <= s + d <= t1)
    return t1 - t0, statistics.median(calm) * 1000, max(window, default=0) * 1000, finished, (t1 - t0) * pace


if __name__ == "__main__":
    os.makedirs(DATA, exist_ok=True)
    print(f"writer at 50 commits per second; each row is the median of {REPEATS} backups")
    print(f"{'mode':<8}{'strategy':<16}{'backup s':>9}{'usual ms':>10}{'slowest commit ms':>19}{'commits during':>16}")
    for mode in ("delete", "wal"):
        for strategy in (lock_then_copy, backup_api, vacuum_into):
            runs = [measure(mode, strategy) for _ in range(REPEATS)]
            med = [statistics.median(column) for column in zip(*runs)]
            print(f"{mode:<8}{strategy.__name__:<16}{med[0]:>9.2f}{med[1]:>10.1f}{med[2]:>19.1f}"
                  f"{med[3]:>10.0f} of {med[4]:.0f}")
python stall_test.py
writer at 50 commits per second; each row is the median of 5 backups
mode    strategy         backup s  usual ms  slowest commit ms  commits during
delete  lock_then_copy       0.02       4.6               34.6         0 of 1
delete  backup_api           0.17       4.6              209.2         0 of 9
delete  vacuum_into          0.19       4.7              212.7         0 of 9
wal     lock_then_copy       0.03       1.8               25.4         1 of 1
wal     backup_api           0.16       1.7                2.1         8 of 8
wal     vacuum_into          0.18       1.7               12.8         9 of 9

In rollback-journal mode, the writer’s slowest commit during a backup_api run was 209 milliseconds, about 45 times its usual 4.6, and about as long as the backup itself (0.17 seconds). The backup holds a read lock for the whole copy, and the writer cannot finish a commit until the lock is released. The documentation lists this as a weakness of the old shared-lock-and-copy method: “Any database clients wishing to write to the database file while a backup is being created must wait until the shared lock is relinquished.” A single-step backup in rollback mode holds the same kind of lock for its whole run, so the application feels it. VACUUM INTO behaves the same way (213 milliseconds). In WAL mode the slowest commit during the same backup was 2.1 milliseconds against a usual 1.7, because readers do not block writers; the application did not notice the backup at all. VACUUM INTO in WAL mode showed 12.8 milliseconds, and lock_then_copy stalls writers in both modes for the 20 to 30 milliseconds the copy takes, which is its whole design. The practical rule: with a rollback journal, the cost of a backup is a write stall about as long as the backup, so on a database 100 times bigger you should expect seconds, not milliseconds (simple scaling, not something I measured). WAL mode removes that stall.

Do not back up in small steps while the database is busy

Connection.backup can copy a few pages at a time, which sounds friendlier to the writer. The SQLite documentation warns what happens on a busy database: “If the backup process is restarted frequently enough it may never run to completion”. The script below backs up 500 pages per step and counts how often the number of remaining pages goes up, which means the backup started over.

# steps_test.py
"""Back up in small steps while the database is changing, and watch the backup start over."""
import os
import sqlite3
import time

from tear_test import DATA, fresh_db, remove_files, start_writer, stop_writer


def stepwise(db, dst, pages, limit=15.0):
    source = sqlite3.connect(db, timeout=30)
    target = sqlite3.connect(dst)
    state = {"steps": 0, "restarts": 0, "last": None}
    started = time.time()

    def progress(status, remaining, total):
        state["steps"] += 1
        if state["last"] is not None and remaining > state["last"]:
            state["restarts"] += 1               # pages left went UP: the backup started over
        state["last"] = remaining
        if time.time() - started > limit:
            raise TimeoutError("gave up")

    try:
        source.backup(target, pages=pages, progress=progress, sleep=0.01)
        outcome = "finished"
    except TimeoutError:
        outcome = f"gave up after {limit:.0f} s"
    finally:
        target.close()
        source.close()
    return outcome, state, time.time() - started


if __name__ == "__main__":
    os.makedirs(DATA, exist_ok=True)
    print(f"{'journal':<8}{'writer/s':>9}{'pages per step':>16}{'steps':>7}{'restarts':>10}  outcome")
    dst = os.path.join(DATA, "steps_copy.db")
    for mode in ("delete", "wal"):
        for pace, pages in ((None, 500), (5, 500), (50, 500), (50, -1)):
            db = fresh_db(mode)
            remove_files(dst)
            proc = None
            if pace:
                proc, stop, log = start_writer(db, pace)
            try:
                outcome, state, seconds = stepwise(db, dst, pages)
            finally:
                if proc:
                    stop_writer(proc, stop, log)
            label = "none" if pace is None else f"{pace}"
            print(f"{mode:<8}{label:>9}{pages:>16}{state['steps']:>7}{state['restarts']:>10}  {outcome} ({seconds:.2f} s)")
    remove_files(dst)
python steps_test.py
journal  writer/s  pages per step  steps  restarts  outcome
delete       none             500     16         0  finished (0.42 s)
delete          5             500     16         0  finished (0.14 s)
delete         50             500    300       124  gave up after 15 s (15.09 s)
delete         50              -1      1         0  finished (0.17 s)
wal          none             500     16         0  finished (0.18 s)
wal             5             500     16         0  finished (0.17 s)
wal            50             500    398       175  finished (4.09 s)
wal            50              -1      1         0  finished (0.26 s)

With a quiet database, or at five commits per second, 500-page steps finished in 16 steps with no restart. At 50 commits per second in rollback mode the backup restarted 124 times in 300 steps, and I stopped it after 15 seconds without a result. In WAL mode it did finish, but only after 398 steps, 175 restarts and 4.1 seconds, against 0.26 seconds for the single-step backup. So small steps turned a quarter-second backup into a four-second one in WAL mode and into one that never finished in rollback mode, which is exactly what the documentation’s sentence predicts. If a backup stalls your writer, switch the database to WAL mode; do not switch the backup to small steps.

Step 6: VACUUM INTO and sqlite3_rsync, the other two official ways

VACUUM INTO 'file' writes a compacted copy of the live database to a new file in one read transaction. The documentation says: “The VACUUM INTO command is transactional in the sense that the generated output database is a consistent snapshot of the original database.” It showed the same good results in the tables above. It was a little slower than the backup API in this test, but its output is compact because it repacks the data into fewer pages and leaves out the free ones. The script below checks what each method keeps and changes, on a tiny database whose events table has no INTEGER PRIMARY KEY and has gaps in its row numbers, because the VACUUM documentation warns: “The VACUUM command may change the ROWIDs of entries in any tables that do not have an explicit INTEGER PRIMARY KEY.”

# vacuum_probe.py
"""What do the backup API and VACUUM INTO keep and change? Probe with a tiny database."""
import os
import shutil
import sqlite3
import tempfile


def facts(path):
    con = sqlite3.connect(path)
    out = {
        "rowids": [r[0] for r in con.execute("SELECT rowid FROM events ORDER BY rowid")],
        "journal_mode": con.execute("PRAGMA journal_mode").fetchone()[0],
        "user_version": con.execute("PRAGMA user_version").fetchone()[0],
        "application_id": con.execute("PRAGMA application_id").fetchone()[0],
        "page_size": con.execute("PRAGMA page_size").fetchone()[0],
        "page_count": con.execute("PRAGMA page_count").fetchone()[0],
        "freelist": con.execute("PRAGMA freelist_count").fetchone()[0],
    }
    con.close()
    return out


def build(path, journal_mode, with_index):
    con = sqlite3.connect(path, isolation_level=None)
    con.execute(f"PRAGMA journal_mode = {journal_mode}").fetchone()
    con.execute("PRAGMA user_version = 42")
    con.execute("PRAGMA application_id = 1234")
    con.execute("CREATE TABLE events (kind TEXT, detail TEXT)")        # no INTEGER PRIMARY KEY
    if with_index:
        con.execute("CREATE INDEX events_kind ON events (kind)")
    con.execute("BEGIN")
    con.executemany("INSERT INTO events VALUES (?, ?)", [(f"k{i}", "d" * 200) for i in range(1, 801)])
    con.execute("COMMIT")
    con.execute("DELETE FROM events WHERE rowid % 4 IN (2, 3)")          # leave gaps in the rowids
    con.close()


if __name__ == "__main__":
    work = tempfile.mkdtemp()
    for journal_mode in ("delete", "wal"):
        for with_index in (False, True):
            src = os.path.join(work, f"src_{journal_mode}_{with_index}.db")
            build(src, journal_mode, with_index)
            made = {"source": src}
            dst = src + ".into"
            con = sqlite3.connect(src, isolation_level=None)
            con.execute("VACUUM INTO ?", (dst,))
            con.close()
            made["VACUUM INTO"] = dst
            dst = src + ".api"
            source, target = sqlite3.connect(src), sqlite3.connect(dst)
            source.backup(target)
            target.close()
            source.close()
            made["backup API"] = dst
            dst = src + ".vac"
            sqlite3.connect(src).close()
            shutil.copyfile(src, dst)
            con = sqlite3.connect(dst, isolation_level=None)
            con.execute("VACUUM")
            con.close()
            made["VACUUM (in place)"] = dst
            print(f"=== source journal_mode={journal_mode}, index on events={with_index}")
            for name, path in made.items():
                f = facts(path)
                ids = f["rowids"]
                print(f"{name:<18} rows={len(ids)} first rowids={ids[:6]} last={ids[-1]}  "
                      f"mode={f['journal_mode']} user_version={f['user_version']} app_id={f['application_id']} "
                      f"pages={f['page_count']} free={f['freelist']} bytes={os.path.getsize(path)}")
    shutil.rmtree(work, ignore_errors=True)
python vacuum_probe.py
=== source journal_mode=delete, index on events=False
source             rows=400 first rowids=[1, 4, 5, 8, 9, 12] last=800  mode=delete user_version=42 app_id=1234 pages=45 free=1 bytes=184320
VACUUM INTO        rows=400 first rowids=[1, 4, 5, 8, 9, 12] last=800  mode=delete user_version=42 app_id=1234 pages=24 free=0 bytes=98304
backup API         rows=400 first rowids=[1, 4, 5, 8, 9, 12] last=800  mode=delete user_version=42 app_id=1234 pages=45 free=1 bytes=184320
VACUUM (in place)  rows=400 first rowids=[1, 2, 3, 4, 5, 6] last=400  mode=delete user_version=42 app_id=1234 pages=24 free=0 bytes=98304
=== source journal_mode=delete, index on events=True
source             rows=400 first rowids=[1, 4, 5, 8, 9, 12] last=800  mode=delete user_version=42 app_id=1234 pages=49 free=1 bytes=200704
VACUUM INTO        rows=400 first rowids=[1, 4, 5, 8, 9, 12] last=800  mode=delete user_version=42 app_id=1234 pages=27 free=0 bytes=110592
backup API         rows=400 first rowids=[1, 4, 5, 8, 9, 12] last=800  mode=delete user_version=42 app_id=1234 pages=49 free=1 bytes=200704
VACUUM (in place)  rows=400 first rowids=[1, 4, 5, 8, 9, 12] last=800  mode=delete user_version=42 app_id=1234 pages=27 free=0 bytes=110592
=== source journal_mode=wal, index on events=False
source             rows=400 first rowids=[1, 4, 5, 8, 9, 12] last=800  mode=wal user_version=42 app_id=1234 pages=45 free=1 bytes=184320
VACUUM INTO        rows=400 first rowids=[1, 4, 5, 8, 9, 12] last=800  mode=delete user_version=42 app_id=1234 pages=24 free=0 bytes=98304
backup API         rows=400 first rowids=[1, 4, 5, 8, 9, 12] last=800  mode=wal user_version=42 app_id=1234 pages=45 free=1 bytes=184320
VACUUM (in place)  rows=400 first rowids=[1, 2, 3, 4, 5, 6] last=400  mode=wal user_version=42 app_id=1234 pages=24 free=0 bytes=98304
=== source journal_mode=wal, index on events=True
source             rows=400 first rowids=[1, 4, 5, 8, 9, 12] last=800  mode=wal user_version=42 app_id=1234 pages=49 free=1 bytes=200704
VACUUM INTO        rows=400 first rowids=[1, 4, 5, 8, 9, 12] last=800  mode=delete user_version=42 app_id=1234 pages=27 free=0 bytes=110592
backup API         rows=400 first rowids=[1, 4, 5, 8, 9, 12] last=800  mode=wal user_version=42 app_id=1234 pages=49 free=1 bytes=200704
VACUUM (in place)  rows=400 first rowids=[1, 4, 5, 8, 9, 12] last=800  mode=wal user_version=42 app_id=1234 pages=27 free=0 bytes=110592

Read the probe row by row. Row numbers. The events table has no INTEGER PRIMARY KEY, and a quarter of its rows were deleted, so its hidden row numbers have gaps (1, 4, 5, 8, 9, 12 and so on up to 800). VACUUM INTO and the backup API kept every row number in all four cases. A plain VACUUM run in place renumbered the table that had no index to 1 through 400 and left the indexed table alone. So the documentation’s warning is real for plain VACUUM in SQLite 3.50.4, but I could not make VACUUM INTO renumber anything in this probe. The documentation only says the row numbers may change, so if your application depends on a row number, give the table an INTEGER PRIMARY KEY instead of leaning on the hidden one.

Size. The VACUUM INTO output has 24 pages and 98,304 bytes, where the source and the backup API copy have 45 pages and 184,320 bytes, because it repacks the rows into fewer pages and leaves out the free page. The documentation names that as its advantage, “the resulting backup database is minimal in size and hence the amount of filesystem I/O may be reduced”, along with “all deleted content is purged from the backup, leaving behind no forensic traces”. It also says where the backup API wins: “the backup API uses fewer CPU cycles and can be executed incrementally”. Settings. Both kept user_version (42) and application_id (1234). They differ in journal mode: the backup API copy of a WAL database is still a WAL database (mode=wal), while VACUUM INTO wrote mode=delete, a plain single file. That is why the tool in step 7 converts its backup API copy to DELETE itself.

sqlite3_rsync

The third official method is a separate program, sqlite3_rsync, available since SQLite 3.47.0. Its documentation says it makes REPLICA “a fully-consistent snapshot of ORIGIN at an instant in time” using “a bandwidth-efficient protocol, similar to rsync”, and that either side can be a remote USER@HOST:PATH reached over ssh. It ships in the SQLite tools download, not in Python. I downloaded sqlite-tools-win-x64-3540100.zip from the SQLite download page, checked its SHA3-256 hash against the value printed on that page, unzipped it into its own folder, and ran the tool twice against the live WAL database: once to create the replica, and once more three seconds later after the writer had committed about 150 more batches.

$ sqlite3_rsync bank.db replica.db -v    (exit 0, 0.16 s)
sent 31,651,531 bytes, received 22 bytes, 227,709,014.39 bytes/sec
total size 31,612,928
ok 20 transfers, balances add up to 100,000,000
$ sqlite3_rsync bank.db replica.db -v    (exit 0, 0.49 s)
sent 10,160,622 bytes, received 167,922 bytes, 21,882,508.47 bytes/sec
total size 31,641,600  speedup is 3.06
ok 1,510 transfers, balances add up to 100,000,000
origin 31,645,696 bytes, replica 31,641,600 bytes

The first run sent the whole 31.6 MB and the replica passed the check. The second run, after the writer had committed about 150 more batches, sent 10.2 MB, which is the “speedup is 3.06” the tool printed, and the replica passed the check again with 1,510 transfers. It saved only two thirds because 1,500 random transfers touch thousands of different pages. The documentation describes the protocol this way: the replica “sends cryptographic hashes for pages or groups of pages over to the origin side” and the origin “sends back page content that differs”. It also says that when the two sides are very similar the traffic is “often less than 0.01% of the database size”; a third of my pages had changed, so I was not in that case. The same effect, that changes follow blocks and not rows, appeared in the PostgreSQL incremental backup tutorial. I ran the tool only between two local files; its main use, a push to another machine over ssh, I did not test. The tools build was SQLite 3.54.1, while Python’s own SQLite is 3.50.4, which is fine because the replica is an ordinary database file.

Step 7: Turn it into a tool that publishes only backups that verified

Knowing the safe method is half the job. A backup procedure also has to refuse to publish a bad copy, refuse to delete good backups because of a bad new one, and leave you one self-contained file per backup. The tool below does that in about 150 lines. Read it once from top to bottom, then I will walk through the decisions.

# sqlite_backup.py
"""Back up a live SQLite database safely, publish only backups that verify, restore without leftovers."""
import argparse
import hashlib
import importlib
import json
import os
import pathlib
import shutil
import sqlite3
import time

SUFFIX = ".bak"


class BackupRejected(Exception):
    """A copy was made but it does not verify, so it must not be used."""


class InUse(Exception):
    """The database that a restore would replace is still open somewhere."""


def sha256_of(path):
    digest = hashlib.sha256()
    with open(path, "rb") as handle:
        for block in iter(lambda: handle.read(1 << 20), b""):
            digest.update(block)
    return digest.hexdigest()


def verify(path, check=None):
    """Open a copy the way a restore would and return a list of problems (empty means fine)."""
    try:
        con = sqlite3.connect(path)
        try:
            problems = [row[0] for row in con.execute("PRAGMA integrity_check")]
            if problems == ["ok"]:
                problems = list(check(con)) if check else []
            return problems
        finally:
            con.close()
    except sqlite3.DatabaseError as exc:
        return [str(exc)]


def prune(dest_dir, name, keep):
    """Delete all but the newest `keep` published backups of `name` (the stamp sorts by time)."""
    backups = sorted(pathlib.Path(dest_dir).glob(f"{name}.*{SUFFIX}"))
    for old in backups[:-keep]:
        old.unlink()
        pathlib.Path(str(old) + ".json").unlink(missing_ok=True)


def backup_database(source, dest_dir, keep=7, check=None, stamp=None):
    """Make a consistent copy of a live database and publish it only if it verifies."""
    if keep < 1:
        raise ValueError("keep must be at least 1")
    os.makedirs(dest_dir, exist_ok=True)
    name = os.path.basename(source)
    stamp = stamp or time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())
    final = os.path.join(dest_dir, f"{name}.{stamp}{SUFFIX}")
    partial = final + ".partial"
    for leftover in pathlib.Path(dest_dir).glob(f"{name}.*{SUFFIX}.partial"):
        leftover.unlink()                          # a run that crashed earlier left this behind
    uri = pathlib.Path(source).resolve().as_uri() + "?mode=ro"
    reader = sqlite3.connect(uri, uri=True, timeout=30)   # read-only: a bug here cannot touch the live file
    writer = sqlite3.connect(partial)
    try:
        reader.backup(writer)                      # one step: a consistent snapshot of a live database
        writer.execute("PRAGMA journal_mode = DELETE").fetchone()   # one self-contained file, no -wal
    finally:
        writer.close()
        reader.close()
    problems = verify(partial, check)
    if problems:
        os.replace(partial, final + ".rejected")   # keep it for a post-mortem, never call it a backup
        raise BackupRejected(f"{final}.rejected: " + "; ".join(problems[:3]))
    manifest = {"source": os.path.abspath(source), "created": stamp,
                "bytes": os.path.getsize(partial), "sha256": sha256_of(partial),
                "sqlite_version": sqlite3.sqlite_version}
    os.replace(partial, final)                     # the rename is the moment the backup exists
    with open(final + ".json", "w") as handle:
        json.dump(manifest, handle, indent=2)
    prune(dest_dir, name, keep)                    # only after a good backup, never after a bad one
    return final


def assert_not_in_use(path):
    con = sqlite3.connect(path, timeout=0, isolation_level=None)
    try:
        con.execute("BEGIN EXCLUSIVE")
        con.execute("ROLLBACK")
    except sqlite3.DatabaseError as exc:
        if "locked" in str(exc):
            raise InUse(f"{path} is open in another process; stop the application first") from exc
        # anything else means the old file is damaged, which is a reason to restore, not to refuse
    finally:
        con.close()


def restore_database(backup, target, check=None):
    """Replace `target` with a verified backup, moving the old files aside as a matching set."""
    manifest = backup + ".json"
    if os.path.exists(manifest):
        with open(manifest) as handle:
            if sha256_of(backup) != json.load(handle)["sha256"]:
                raise BackupRejected(f"{backup} does not match its manifest")
    problems = verify(backup, check)
    if problems:
        raise BackupRejected(f"{backup} does not verify: " + "; ".join(problems[:3]))
    if os.path.exists(target):
        assert_not_in_use(target)
    staged = target + ".restoring"
    shutil.copyfile(backup, staged)
    for suffix in ("", "-wal", "-shm", "-journal"):          # the old files travel as a set
        if os.path.exists(target + suffix):
            os.replace(target + suffix, target + ".before-restore" + suffix)
    os.replace(staged, target)


def load_check(spec):
    """Turn 'module:function' into the function, so the command line can run an application's own rules."""
    if not spec:
        return None
    module, _, name = spec.partition(":")
    return getattr(importlib.import_module(module), name)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest="command", required=True)
    one = commands.add_parser("backup")
    one.add_argument("source")
    one.add_argument("dest_dir")
    one.add_argument("--keep", type=int, default=7)
    one.add_argument("--check", help="module:function taking a connection and returning a list of problems")
    two = commands.add_parser("restore")
    two.add_argument("backup")
    two.add_argument("target")
    two.add_argument("--check", help="module:function taking a connection and returning a list of problems")
    args = parser.parse_args()
    if args.command == "backup":
        print(backup_database(args.source, args.dest_dir, keep=args.keep, check=load_check(args.check)))
    else:
        restore_database(args.backup, args.target, check=load_check(args.check))
        print(f"restored {args.backup} to {args.target}")

What each part is for

  1. The source is opened read-only. ?mode=ro in the URI means a bug in this tool cannot modify the live database. Path(...).as_uri() builds a correct file:/// address on Windows as well as on Linux.
  2. One call makes the snapshot. reader.backup(writer) is Python’s wrapper for the backup API. Its documentation says it “works even if the database is being accessed by other clients or concurrently by the same connection”, and with the default pages=-1 it copies the whole database “in a single step”. Step 5 showed why one step matters.
  3. The copy is converted to a plain file. The backup API keeps the source’s WAL setting (the probe in step 6 showed wal in, wal out), so a backup of a WAL database would open as a WAL database and create -wal and -shm files next to itself. PRAGMA journal_mode = DELETE turns it into a single self-contained file. The WAL documentation recommends the same before burning an image onto read-only media: “it is good practice to convert the database to PRAGMA journal_mode=DELETE”.
  4. The copy is verified before anyone can use it. verify opens the copy the way a restore would, runs PRAGMA integrity_check, and then calls the function you pass as check, which receives a connection and returns a list of problems. That is where the bank’s balance rules go.
  5. A failed copy is kept, but never called a backup. It is renamed to .rejected for a post-mortem and the function raises BackupRejected. Note what does not happen: nothing is pruned, so a run of bad backups can never eat your last good ones.
  6. The rename is the moment the backup exists. The copy is written under a .partial name and moved to its final name with a single os.replace call, so anyone looking at the folder sees either no new backup or a complete one. A crash mid-copy leaves a .partial file that the next run deletes; it never leaves a half-written file with a backup’s name. I did not test a power cut in the middle of the rename itself. The manifest records the size, the SHA-256 and the SQLite version, so you can detect a backup that rots on disk later (the same idea as in the download verification tutorial).
  7. Retention runs last. Names carry a UTC timestamp, so sorting the names sorts by time, and prune keeps the newest keep backups. keep must be at least 1 because [:-0] in Python is an empty slice, which would silently keep everything.

On Linux you would also fsync the backup folder after the rename so that the rename itself survives a power cut. I ran this on Windows and did not test that step, so it is not in the code.

Run it against a live database

Start the writer from step 2 against a WAL-mode bank, then run the tool four times with --keep 3 while the writer keeps committing. --check check:bank_problems loads the bank’s rules from check.py. The timestamp has one-second resolution, so wait a second between runs. The harness I used prints the listing and the manifest of the newest backup after the fourth run:

$ python sqlite_backup.py backup bank.db backups --keep 3 --check check:bank_problems
backups\bank.db.20261202T115816Z.bak
$ python sqlite_backup.py backup bank.db backups --keep 3 --check check:bank_problems
backups\bank.db.20261202T115817Z.bak
$ python sqlite_backup.py backup bank.db backups --keep 3 --check check:bank_problems
backups\bank.db.20261202T115819Z.bak
$ python sqlite_backup.py backup bank.db backups --keep 3 --check check:bank_problems
backups\bank.db.20261202T115820Z.bak

  31,625,216  bank.db.20261202T115817Z.bak
         277  bank.db.20261202T115817Z.bak.json
  31,637,504  bank.db.20261202T115819Z.bak
         277  bank.db.20261202T115819Z.bak.json
  31,649,792  bank.db.20261202T115820Z.bak
         277  bank.db.20261202T115820Z.bak.json
{
  "source": "<folder>\\bank.db",
  "created": "20261202T115820Z",
  "bytes": 31649792,
  "sha256": "1c86befe3b570ad4a38e169169ab9f0f6f1cbd4eb393471df01e7f637f013b7c",
  "sqlite_version": "3.50.4"
}

$ python sqlite_backup.py restore backups\bank.db.20261202T115820Z.bak restored.db --check check:bank_problems
restored backups\bank.db.20261202T115820Z.bak to restored.db
ok 2,030 transfers, balances add up to 100,000,000

Three backups remain, each with its manifest, and the oldest was pruned only after the fourth one verified. The backup of a database that was being written to 50 times a second restores to a state the bank accepts.

Step 8: Restore, and the stale -wal trap

A backup you have never restored is a hope. Restoring has its own trap, and it is the same lesson as before from the other side. The documentation lists the mistake in plain words: “Overwriting a database file with another without also deleting any hot journal associated with the original database” is “likely to lead to corruption”. In WAL mode the leftover is the -wal file. After a crash it still holds newer versions of some pages, and if you put an older database file next to it, SQLite replays those newer pages on top of the old file and you get a mixture of two moments, not the backup you thought you restored.

The script below proves it with a real crash. It starts the writer on a WAL database, takes a backup with the tool while the writer runs, lets the writer commit for four more seconds, then kills it with kill(), which is a hard stop with no clean shutdown. It copies the crashed folder twice. In one copy it restores the obvious way, by copying the backup over the database file and leaving the other files alone. In the other it uses restore_database from step 7.

# restore_trap.py
"""Crash a busy WAL-mode database, then restore an older backup two ways: naively and properly."""
import os
import shutil
import time

from bank import make_db
from check import bank_problems, inspect
from sqlite_backup import backup_database, restore_database
from tear_test import DATA, remove_files, start_writer

LIVE = os.path.join(DATA, "live")
BACKUPS = os.path.join(DATA, "backups")


def listing(folder):
    return ", ".join(f"{name} {os.path.getsize(os.path.join(folder, name)):,} bytes"
                     for name in sorted(os.listdir(folder)) if name.startswith("bank.db"))


if __name__ == "__main__":
    for folder in (LIVE, BACKUPS, LIVE + "_naive", LIVE + "_proper"):
        shutil.rmtree(folder, ignore_errors=True)
    os.makedirs(LIVE)
    db = os.path.join(LIVE, "bank.db")
    make_db(db, "wal")
    proc, stop, log = start_writer(db, pace=50)
    time.sleep(1.0)
    backup = backup_database(db, BACKUPS, check=bank_problems)
    print("backup taken while the application was running:", os.path.basename(backup))
    time.sleep(4.0)                                   # the application keeps committing; checkpoints come and go
    proc.kill()                                       # the crash: no clean shutdown, no final checkpoint
    proc.wait()
    print("files left behind by the crash:", listing(LIVE))
    shutil.copytree(LIVE, LIVE + "_naive")
    shutil.copytree(LIVE, LIVE + "_proper")
    print("transfers in the backup:", inspect(backup)[1].split()[0],
          "  in the crashed database:", inspect(db)[1].split()[0])

    naive = os.path.join(LIVE + "_naive", "bank.db")
    shutil.copyfile(backup, naive)                    # the obvious restore: put the backup file in place
    verdict, detail = inspect(naive)
    print(f"naive restore (old -wal left in place): {verdict} - {detail}")

    proper = os.path.join(LIVE + "_proper", "bank.db")
    restore_database(backup, proper, check=bank_problems)
    verdict, detail = inspect(proper)
    print(f"proper restore: {verdict} - {detail}")
    print("files after the proper restore:", listing(LIVE + "_proper"))
    for name in sorted(os.listdir(LIVE + "_proper")):
        print("  ", name)
    for folder in (LIVE + "_naive", LIVE + "_proper"):
        for suffix in ("", "-wal", "-shm", "-journal"):
            remove_files(os.path.join(folder, "bank.db" + suffix))
python restore_trap.py
backup taken while the application was running: bank.db.20261202T115705Z.bak
files left behind by the crash: bank.db 31,649,792 bytes, bank.db-shm 32,768 bytes, bank.db-wal 4,194,192 bytes
transfers in the backup: 500   in the crashed database: 2,550
naive restore (old -wal left in place): unreadable - database disk image is malformed
proper restore: ok - 500 transfers, balances add up to 100,000,000
files after the proper restore: bank.db 31,621,120 bytes, bank.db.before-restore 31,657,984 bytes
   bank.db
   bank.db.before-restore

Read the output from the top. The crash left a 4.2 MB -wal file, which is about the 1,000-page checkpoint threshold, so the log had filled up and been recycled at least once. The backup holds 500 transfers; the crashed database holds 2,550. The naive restore does not even open: SQLite answers “database disk image is malformed”. The old log, left in place, held newer versions of pages from a database with five times as much history. SQLite cannot tell that the main file under it is older, so it uses those pages anyway, and the mixture does not hang together. The proper restore passes the same check and gives back exactly the 500 transfers in the backup.

The folder after the proper restore holds the restored database and bank.db.before-restore, the crashed database, which I checked afterwards and which holds all 2,550 transfers with balances that still add up. No -wal file is left over because restore_database first opens the old database to make sure nobody else is using it, and the WAL documentation says what happens when that last connection closes: “that connection does one last checkpoint and then deletes the WAL and its associated shared-memory file”. Any leftover that SQLite does not clean up, such as a stale -shm or -journal file, is moved aside together with the old database. The function also refuses to run while another process holds the database, which the tests in step 9 check.

Make restores routine, not heroic. Once a week, restore the newest backup into a temporary folder, run your own check on it, and compare its row counts with the manifest. A restore drill that fails on Tuesday is a cheap problem; the same failure during an outage is not.

Step 9: Test the tool, then test the tests

The tool makes promises, so every promise gets a test. Each test uses a small application database with its own rules (a ledger and a meta row that must agree), so the suite runs in seconds. The tests include a writer thread committing while twelve backups are taken in each journal mode, a database whose newest commits exist only in the -wal file, a read-only source file, a stale .partial file, the stale-WAL restore from step 8, a restore over a database that is in use, a restore over a database file that is no longer a database, a stale -shm file, and two kinds of damaged backup (one silently changed byte, which only the manifest catches, and one zeroed page, which only verification catches).

# test_sqlite_backup.py
import json
import os
import shutil
import sqlite3
import stat
import threading
import time

import pytest

import sqlite_backup as sb

ROWS = 2000
PAD = "x" * 300


def make_app(path, mode="delete"):
    """A tiny application database with rules of its own: the ledger and meta must agree."""
    con = sqlite3.connect(path, isolation_level=None)
    con.execute(f"PRAGMA journal_mode = {mode}").fetchone()
    con.executescript("""
        CREATE TABLE ledger (id INTEGER PRIMARY KEY, amount INTEGER NOT NULL, note TEXT NOT NULL);
        CREATE TABLE meta (rows INTEGER NOT NULL, total INTEGER NOT NULL);
    """)
    con.execute("BEGIN")
    con.executemany("INSERT INTO ledger (amount, note) VALUES (?, ?)", ((1, PAD) for _ in range(ROWS)))
    con.execute("INSERT INTO meta VALUES (?, ?)", (ROWS, ROWS))
    con.execute("COMMIT")
    return con


def add_entries(con, count, amount=3):
    con.execute("BEGIN IMMEDIATE")
    for _ in range(count):
        con.execute("INSERT INTO ledger (amount, note) VALUES (?, ?)", (amount, PAD))
    con.execute("UPDATE meta SET rows = rows + ?, total = total + ?", (count, count * amount))
    con.execute("COMMIT")


def books(con):
    """The application's own check, in the form sqlite_backup.verify() wants: a list of problems."""
    rows, total = con.execute("SELECT COUNT(*), SUM(amount) FROM ledger").fetchone()
    want_rows, want_total = con.execute("SELECT rows, total FROM meta").fetchone()
    problems = []
    if rows != want_rows:
        problems.append(f"{rows} ledger rows but meta says {want_rows}")
    if total != want_total:
        problems.append(f"amounts add up to {total} but meta says {want_total}")
    return problems


def ledger_rows(path):
    con = sqlite3.connect(path)
    try:
        return con.execute("SELECT COUNT(*) FROM ledger").fetchone()[0]
    finally:
        con.close()


@pytest.fixture
def app(tmp_path):
    path = str(tmp_path / "app.db")
    make_app(path).close()
    return path


def stamp(i):
    return f"20260101T0000{i:02d}Z"


def test_backup_of_a_quiet_database_verifies_and_matches(app, tmp_path):
    out = sb.backup_database(app, str(tmp_path / "bk"), check=books, stamp=stamp(0))
    assert out.endswith("app.db.20260101T000000Z.bak")
    assert sb.verify(out, books) == []
    assert ledger_rows(out) == ROWS


def test_backup_sees_commits_that_exist_only_in_the_wal(tmp_path):
    path = str(tmp_path / "app.db")
    con = make_app(path, "wal")
    con.execute("PRAGMA wal_checkpoint(TRUNCATE)")
    con.execute("PRAGMA wal_autocheckpoint = 0")        # new commits stay in the -wal file
    add_entries(con, 5)
    assert ledger_rows(path) == ROWS + 5                 # SQLite sees them
    out = sb.backup_database(path, str(tmp_path / "bk"), check=books)
    con.close()
    assert ledger_rows(out) == ROWS + 5                  # a copy of app.db alone would say ROWS


@pytest.mark.parametrize("mode", ["delete", "wal"])
def test_backups_taken_while_writing_are_consistent(tmp_path, mode):
    path = str(tmp_path / "app.db")
    make_app(path, mode).close()
    stop = threading.Event()

    def writer():
        con = sqlite3.connect(path, isolation_level=None, timeout=30)
        while not stop.is_set():
            add_entries(con, 3)
            time.sleep(0.002)
        con.close()

    thread = threading.Thread(target=writer)
    thread.start()
    try:
        for i in range(12):
            out = sb.backup_database(path, str(tmp_path / "bk"), keep=20, check=books, stamp=stamp(i))
            assert sb.verify(out, books) == []
    finally:
        stop.set()
        thread.join()


def test_a_copy_that_fails_the_check_is_not_published_and_prunes_nothing(app, tmp_path):
    dest = str(tmp_path / "bk")
    for i in range(3):
        sb.backup_database(app, dest, keep=3, stamp=stamp(i))
    with pytest.raises(sb.BackupRejected):
        sb.backup_database(app, dest, keep=3, check=lambda con: ["the books do not balance"], stamp=stamp(9))
    names = sorted(os.listdir(dest))
    assert [n for n in names if n.endswith(".bak")] == [f"app.db.{stamp(i)}.bak" for i in range(3)]
    assert any(n.endswith(".rejected") for n in names)
    assert not any(n.endswith(".partial") for n in names)


def test_retention_keeps_the_newest_backups_and_their_manifests(app, tmp_path):
    dest = str(tmp_path / "bk")
    for i in range(6):
        sb.backup_database(app, dest, keep=3, stamp=stamp(i))
    kept = sorted(n for n in os.listdir(dest) if n.endswith(".bak"))
    assert kept == [f"app.db.{stamp(i)}.bak" for i in (3, 4, 5)]
    assert sorted(n for n in os.listdir(dest) if n.endswith(".json")) == [k + ".json" for k in kept]


def test_keep_must_be_at_least_one(app, tmp_path):
    with pytest.raises(ValueError):
        sb.backup_database(app, str(tmp_path / "bk"), keep=0)


def test_a_stale_partial_file_is_removed(app, tmp_path):
    dest = tmp_path / "bk"
    dest.mkdir()
    stale = dest / "app.db.20250101T000000Z.bak.partial"
    stale.write_bytes(b"half a backup from a crashed run")
    sb.backup_database(app, str(dest), stamp=stamp(0))
    assert not stale.exists()


def test_a_read_only_source_is_backed_up_without_being_touched(app, tmp_path):
    before = sb.sha256_of(app)
    os.chmod(app, stat.S_IREAD)
    try:
        sb.backup_database(app, str(tmp_path / "bk"), check=books)
        assert sb.sha256_of(app) == before
    finally:
        os.chmod(app, stat.S_IREAD | stat.S_IWRITE)


def test_a_wal_database_becomes_one_standalone_file(tmp_path):
    path = str(tmp_path / "app.db")
    make_app(path, "wal").close()
    out = sb.backup_database(path, str(tmp_path / "bk"), check=books)
    assert not os.path.exists(out + "-wal") and not os.path.exists(out + "-shm")
    with open(out, "rb") as handle:
        header = handle.read(20)
    assert header[18:20] == b"\x01\x01"                  # 1 = rollback journal; 2 would mean WAL


def test_the_manifest_matches_the_published_file(app, tmp_path):
    out = sb.backup_database(app, str(tmp_path / "bk"))
    with open(out + ".json") as handle:
        manifest = json.load(handle)
    assert manifest["sha256"] == sb.sha256_of(out)
    assert manifest["bytes"] == os.path.getsize(out)


def test_restore_replaces_the_database_and_removes_a_stale_wal(tmp_path):
    live = tmp_path / "live"
    live.mkdir()
    path = str(live / "app.db")
    con = make_app(path, "wal")
    con.execute("PRAGMA wal_checkpoint(TRUNCATE)")
    con.execute("PRAGMA wal_autocheckpoint = 0")
    backup = sb.backup_database(path, str(tmp_path / "bk"), check=books)      # state A
    add_entries(con, 40)                                                      # batch C
    con.execute("PRAGMA wal_checkpoint(TRUNCATE)")                            # the file now holds A + C
    add_entries(con, 1)                                                       # batch D stays in the -wal
    crashed = tmp_path / "crashed"
    crashed.mkdir()
    for suffix in ("", "-wal"):                                               # what a killed app leaves behind
        shutil.copyfile(path + suffix, str(crashed / ("app.db" + suffix)))
    con.close()
    naive = tmp_path / "naive"
    shutil.copytree(crashed, naive)
    shutil.copyfile(backup, str(naive / "app.db"))                            # the trap: old -wal left in place
    assert sb.verify(str(naive / "app.db"), books) != []
    target = str(crashed / "app.db")
    sb.restore_database(backup, target, check=books)
    assert sb.verify(target, books) == []
    assert ledger_rows(target) == ROWS
    assert not os.path.exists(target + "-wal")
    assert ledger_rows(target + ".before-restore") == ROWS + 41               # the old data is kept aside


def test_restore_replaces_a_damaged_database(app, tmp_path):
    out = sb.backup_database(app, str(tmp_path / "bk"), check=books)
    wrecked = tmp_path / "wrecked"
    wrecked.mkdir()
    target = str(wrecked / "app.db")
    open(target, "wb").write(b"this is no longer a database" * 200)
    sb.restore_database(out, target, check=books)
    assert sb.verify(target, books) == []
    assert open(target + ".before-restore", "rb").read().startswith(b"this is no longer")


def test_restore_moves_a_stale_shm_file_aside(app, tmp_path):
    out = sb.backup_database(app, str(tmp_path / "bk"), check=books)
    open(app + "-shm", "wb").write(b"left behind by a process that crashed")
    sb.restore_database(out, app, check=books)
    assert not os.path.exists(app + "-shm")
    assert os.path.exists(app + ".before-restore-shm")


def test_restore_refuses_a_database_that_is_in_use(app, tmp_path):
    out = sb.backup_database(app, str(tmp_path / "bk"))
    holder = sqlite3.connect(app, isolation_level=None)
    holder.execute("BEGIN IMMEDIATE")
    try:
        with pytest.raises(sb.InUse):
            sb.restore_database(out, app)
    finally:
        holder.execute("ROLLBACK")
        holder.close()


def test_restore_rejects_a_silently_changed_backup(app, tmp_path):
    out = sb.backup_database(app, str(tmp_path / "bk"))
    data = bytearray(open(out, "rb").read())
    data[data.index(b"xxxxxxxx")] = ord("y")             # one flipped byte inside a note: still a valid database
    open(out, "wb").write(data)
    assert sb.verify(out) == []
    before = sb.sha256_of(app)
    with pytest.raises(sb.BackupRejected):
        sb.restore_database(out, app)
    assert sb.sha256_of(app) == before


def test_restore_rejects_a_structurally_damaged_backup(app, tmp_path):
    out = sb.backup_database(app, str(tmp_path / "bk"))
    os.remove(out + ".json")                              # no manifest to lean on: verification must catch it
    data = bytearray(open(out, "rb").read())
    data[8192:12288] = bytes(4096)                        # zero out page 3
    open(out, "wb").write(data)
    before = sb.sha256_of(app)
    with pytest.raises(sb.BackupRejected):
        sb.restore_database(out, app)
    assert sb.sha256_of(app) == before

Run the suite:

python -m pytest -v
=========================================================== test session starts ===========================================================
platform win32 -- Python 3.13.14, pytest-9.1.1, pluggy-1.6.0 -- C:\Claude\Cowork\Sxz.io\sxz-automations\venv\Scripts\python.exe
rootdir: C:\Claude\Cowork\Sxz.io\sxz-automations\tmp\sxz-publisher\lab
plugins: anyio-4.14.2
collecting ... collected 17 items

test_sqlite_backup.py::test_backup_of_a_quiet_database_verifies_and_matches PASSED                                                   [  5%]
test_sqlite_backup.py::test_backup_sees_commits_that_exist_only_in_the_wal PASSED                                                    [ 11%]
test_sqlite_backup.py::test_backups_taken_while_writing_are_consistent[delete] PASSED                                                [ 17%]
test_sqlite_backup.py::test_backups_taken_while_writing_are_consistent[wal] PASSED                                                   [ 23%]
test_sqlite_backup.py::test_a_copy_that_fails_the_check_is_not_published_and_prunes_nothing PASSED                                   [ 29%]
test_sqlite_backup.py::test_retention_keeps_the_newest_backups_and_their_manifests PASSED                                            [ 35%]
test_sqlite_backup.py::test_keep_must_be_at_least_one PASSED                                                                         [ 41%]
test_sqlite_backup.py::test_a_stale_partial_file_is_removed PASSED                                                                   [ 47%]
test_sqlite_backup.py::test_a_read_only_source_is_backed_up_without_being_touched PASSED                                             [ 52%]
test_sqlite_backup.py::test_a_wal_database_becomes_one_standalone_file PASSED                                                        [ 58%]
test_sqlite_backup.py::test_the_manifest_matches_the_published_file PASSED                                                           [ 64%]
test_sqlite_backup.py::test_restore_replaces_the_database_and_removes_a_stale_wal PASSED                                             [ 70%]
test_sqlite_backup.py::test_restore_replaces_a_damaged_database PASSED                                                               [ 76%]
test_sqlite_backup.py::test_restore_moves_a_stale_shm_file_aside PASSED                                                              [ 82%]
test_sqlite_backup.py::test_restore_refuses_a_database_that_is_in_use PASSED                                                         [ 88%]
test_sqlite_backup.py::test_restore_rejects_a_silently_changed_backup PASSED                                                         [ 94%]
test_sqlite_backup.py::test_restore_rejects_a_structurally_damaged_backup PASSED                                                     [100%]

=========================================================== 17 passed in 1.54s ============================================================

Passing tests only prove that the tests agree with the code. To find out whether they would notice a real mistake, plant one at a time: the script below changes one line of sqlite_backup.py in a scratch copy, runs the suite, and expects it to fail. A planted bug that the suite does not notice is called a survivor, and it shows you a missing test.

# mutants.py
"""Plant one bug at a time in sqlite_backup.py and see whether the tests notice."""
import os
import shutil
import subprocess
import sys
import tempfile

HERE = os.path.dirname(os.path.abspath(__file__))

MUTANTS = [
    ("copies the file instead of using the backup API", "reader.backup(writer)", "shutil.copyfile(source, partial)"),
    ("skips verification of a new backup", "problems = verify(partial, check)", "problems = []"),
    ("prunes the newest instead of the oldest", "backups[:-keep]", "backups[keep:]"),
    ("keeps one backup too many", "backups[:-keep]", "backups[:-keep - 1]"),
    ("leaves a stale .partial file", "leftover.unlink()", "pass"),
    ("leaves a WAL backup in WAL mode", 'writer.execute("PRAGMA journal_mode = DELETE").fetchone()', "pass"),
    ("writes a wrong hash into the manifest", '"sha256": sha256_of(partial)', '"sha256": "0" * 64'),
    ("accepts keep=0", "if keep < 1:", "if keep < 0:"),
    ("restore ignores the manifest hash", 'if sha256_of(backup) != json.load(handle)["sha256"]:', "if False:"),
    ("restore skips verification", "problems = verify(backup, check)", "problems = []"),
    ("restore leaves the old -wal in place", 'for suffix in ("", "-wal", "-shm", "-journal"):', 'for suffix in ("",):'),
    ("restore skips the in-use check", "        assert_not_in_use(target)", "        pass"),
    ("restore refuses a damaged old database", 'if "locked" in str(exc):', "if True:"),
]


def run_tests(folder):
    env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1")
    result = subprocess.run([sys.executable, "-m", "pytest", "-q", "-x", "-p", "no:cacheprovider",
                             "test_sqlite_backup.py"], cwd=folder, env=env, capture_output=True, text=True)
    return result.returncode, result.stdout.strip().splitlines()[-1] if result.stdout.strip() else ""


if __name__ == "__main__":
    original = open(os.path.join(HERE, "sqlite_backup.py"), encoding="utf-8").read()
    code, last = run_tests(HERE)
    print(f"control   {'passes' if code == 0 else 'FAILS'}   the unmodified tool   [{last}]")
    assert code == 0, "the tests must pass on the real code before mutants mean anything"
    caught = 0
    for number, (name, old, new) in enumerate(MUTANTS, 1):
        assert original.count(old) == 1, f"mutant {number}: pattern must occur exactly once ({original.count(old)})"
        folder = tempfile.mkdtemp(prefix="mutant_")
        shutil.copy(os.path.join(HERE, "test_sqlite_backup.py"), folder)
        with open(os.path.join(folder, "sqlite_backup.py"), "w", encoding="utf-8", newline="\n") as handle:
            handle.write(original.replace(old, new))
        code, last = run_tests(folder)
        caught += code != 0
        print(f"mutant {number:>2} {'CAUGHT  ' if code else 'SURVIVED'} {name}   [{last}]")
        shutil.rmtree(folder, ignore_errors=True)
    print(f"{caught} of {len(MUTANTS)} planted bugs caught")
python mutants.py
control   passes   the unmodified tool   [17 passed in 1.68s]
mutant  1 CAUGHT   copies the file instead of using the backup API   [1 failed, 1 passed in 0.12s]
mutant  2 CAUGHT   skips verification of a new backup   [1 failed, 4 passed in 0.88s]
mutant  3 CAUGHT   prunes the newest instead of the oldest   [1 failed, 5 passed in 2.56s]
mutant  4 CAUGHT   keeps one backup too many   [1 failed, 5 passed in 1.13s]
mutant  5 CAUGHT   leaves a stale .partial file   [1 failed, 7 passed in 1.04s]
mutant  6 CAUGHT   leaves a WAL backup in WAL mode   [1 failed, 9 passed in 2.00s]
mutant  7 CAUGHT   writes a wrong hash into the manifest   [1 failed, 10 passed in 1.12s]
mutant  8 CAUGHT   accepts keep=0   [1 failed, 6 passed in 1.09s]
mutant  9 CAUGHT   restore ignores the manifest hash   [1 failed, 15 passed in 2.28s]
mutant 10 CAUGHT   restore skips verification   [1 failed, 16 passed in 1.35s]
mutant 11 CAUGHT   restore leaves the old -wal in place   [1 failed, 13 passed in 1.49s]
mutant 12 CAUGHT   restore skips the in-use check   [1 failed, 14 passed in 2.53s]
mutant 13 CAUGHT   restore refuses a damaged old database   [1 failed, 12 passed in 1.76s]
13 of 13 planted bugs caught

The control run on the real code passes, and all 13 planted bugs fail the suite. It did not start that way. My first version of the suite caught 11 of 12 and let one survive: “restore leaves the old -wal in place”. The reason is instructive. restore_database opens the old database to check that nobody is using it, and when that last connection closes SQLite folds the old log into the main file and deletes it, so by the time the loop looked for a -wal file there was none to move. The loop still matters for leftovers that SQLite does not clean up, such as a stale -shm file next to a rollback-mode database, so I added a test with one. Writing a second new test, for restoring over a database that is not a database any more, showed that my first draft of assert_not_in_use raised an error on a damaged old file, which is exactly the moment you need a restore to work. The fix was to treat any error other than “locked” as a reason to restore, not to refuse, and the thirteenth planted bug (the if True: line) guards it.

The three official ways, side by side

These are the numbers from this page, gathered in one place. They come from one machine and one 32 MB database, so treat the ratios as the lesson and the exact values as one sample.

Method Broken copies out of 250 (rollback journal, WAL) Median time (rollback, WAL) Slowest commit while it ran (rollback, WAL) What you get
Plain file copy 169, 1 (and in WAL mode a median of 21 commits out of date) 14 ms, 14 ms not measured; it takes no lock The main file; in WAL mode the log is missing
Main file, then -wal file n/a (no log file), 0 (but 3 of 60 with a 0.1 s pause between the two copies, 60 of 60 with 1.5 s) n/a, 17 ms not measured; it takes no lock Two files that must stay together
Take the write lock, then copy 0, 0 15 ms, 18 ms 34.6 ms, 25.4 ms (the length of the copy) Valid copy; writers wait while you copy
Backup API, one step 0, 0 163 ms, 211 ms 209 ms, 2.1 ms (usual 4.6, 1.7) Same journal mode as the source; keeps free pages
VACUUM INTO 0, 0 182 ms, 245 ms 213 ms, 12.8 ms Compact single file, no free pages
sqlite3_rsync not in the 250-copy test; replica passed both live checks 0.16 s first sync, 0.49 s second not measured A replica; second sync sent 10.2 MB after 150 commits

Common mistakes, and how to spot them

Trusting integrity_check alone. It checks structure. In the runs above, broken copies passed it while the books did not balance. Always add a rule from your own application, even a cheap one such as a row count against a counter.

Copying only the main file of a WAL database. It looks fine, every check passes, and it is silently old by whatever sits in the -wal file. Look at the “commits behind” column in step 4 before you believe a green result.

Copying the main file and the -wal file as two steps. A checkpoint between the two copies pairs a new log with an old database. It never failed in my 250 quick tries, but with a pause of only 0.1 seconds between the two copies it failed 3 times in 60, which is exactly why it survives testing and fails in production.

Backing up in small steps on a busy database. A backup that restarts every time the source changes may never finish. Use one step, and take the snapshot from a moment when you can afford the read lock.

Putting the backup on the same disk, or on a network share. One disk failure then takes both. The WAL documentation also warns that “WAL does not work over a network filesystem”, so keep the live database on a local disk and ship finished backup files elsewhere.

Restoring over a live database. Stop the application first, and move the old -wal and -journal files away together with the old database, as restore_database does.

Check that everything works end to end

Run these five checks once on your own database, in your own environment, before you rely on any of this:

  1. Run the tests: python -m pytest -v should report every test passed.
  2. Take a backup while your application is running, with your own check function, and confirm that a .bak file and its .json manifest appear and that no .partial or .rejected file is left behind.
  3. Restore that backup into a different folder and run your check against the result.
  4. Compare the manifest’s SHA-256 with the file’s: python -c "import sqlite_backup as s; print(s.sha256_of('PATH'))".
  5. Break something on purpose, for example zero out a page of a copy of a backup, and confirm that restore_database refuses it and leaves your database untouched.

Where to go next

  • The same ideas at server scale are in PostgreSQL point-in-time recovery and incremental backups, and changed block tracking shows how a backup tool finds which blocks changed.
  • If your SQLite database backs a job queue, read the SQLite job queue tutorial and the WAL and “database is locked” tutorial to keep writers and backups out of each other’s way, and the write-ahead log tutorial for how a log makes a crash survivable.
  • For Git work you cannot afford to lose, the reflog and snapshot tutorial applies the same habit of taking a snapshot before the risky step.
  • Replace bank_problems with your own application’s rules, and run the torn-copy test at your real write rate. The sweep in step 3 shows that the rate decides how often a plain copy breaks.

Sources

  • SQLite documentation, How To Corrupt An SQLite Database File (sections 1.2 to 1.4 on backups, hot journals and mispairing files).
  • SQLite documentation, Using the SQLite Online Backup API, VACUUM, Write-Ahead Logging and sqlite3_rsync.
  • SQLite documentation, PRAGMA statements (integrity_check, quick_check, journal_mode).
  • Python documentation, sqlite3, DB-API 2.0 interface for SQLite databases (Connection.backup).
  • SQLite download page, which lists the SHA3-256 hash of sqlite-tools-win-x64-3540100.zip that was checked before running sqlite3_rsync.

Tags:

Data RecoveryDatabase BackupsDisaster RecoveryPythonSQLiteWrite-Ahead Log

Share

A blue Link Trainer, the 1930s flight simulator, with yellow wings and tail on a museum stand
Previous Post

Ai2’s DR Tulu 2 Turns Search Bills Into a Local Simulator and Its Table Reproduces, but the Repo Trains Finance Before Science While the Paper Says the Reverse, Never Names DR-Anything, the Framework the Post Tells Readers to Use, and Two Benchmarks Supply 56% of the +9.7 Lead

No Comment! Be the first one.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Latest
02 Dec
How to Back Up a Live SQLite Database Without Corrupting It: Count the Broken Copies, Use the Backup API or VACUUM INTO, Publish Only Backups That Verify, and Restore Past a Stale -wal File
02 Dec
Ai2’s DR Tulu 2 Turns Search Bills Into a Local Simulator and Its Table Reproduces, but the Repo Trains Finance Before Science While the Paper Says the Reverse, Never Names DR-Anything, the Framework the Post Tells Readers to Use, and Two Benchmarks Supply 56% of the +9.7 Lead
Trending
December 2, 2026
How to Back Up a Live SQLite Database Without Corrupting It: Count the Broken Copies, Use the Backup API or VACUUM INTO, Publish Only Backups That Verify, and Restore Past a Stale -wal File
December 2, 2026
Ai2’s DR Tulu 2 Turns Search Bills Into a Local Simulator and Its Table Reproduces, but the Repo Trains Finance Before Science While the Paper Says the Reverse, Never Names DR-Anything, the Framework the Post Tells Readers to Use, and Two Benchmarks Supply 56% of the +9.7 Lead
December 2, 2026
Docker Fixes a Sandboxes Bug That Let a Kit Update Redirect a Stored API Key, but the Same Flaw Scores 5.6, 6.9 or 8.2, the Finder Demonstrated One of 13 Services, and the Upgrade Stops Reading the Environment Variables Some Teams Use to Require Signed Kits
December 1, 2026
How to Alert When Prometheus Stops Seeing Your Service: Tell a Crash From a Removed Target From a Renamed Metric, Use absent() Without False Alarms, and Test Every Silent Failure With promtool
December 1, 2026
DeepMind’s CellGemma Turns Virtual Drug Screening Into a Residual on Top of the Population Mean, but an MLP Given the Same Baseline Reproduces About Half of Its 16-Point Lead, “All 32 Settings” Holds for One of 12 Metrics, and the Wet-Lab Result Is Three of Five Compounds Against No Comparison Set
December 1, 2026
CISA Lists the Rejetto HFS Session-Forgery Flaw 140 Days After Its Fix, and GreyNoise’s Report of Its Use Shows One HFS Server Serving as a Relay for 24 Check Point Management Servers the Actor Already Held, With an AI Role It Infers but Does Not Show

Related Posts

A laptop wrapped in a chain and padlock, illustrating least-privilege controls for AI agents.
Learning Hub

How to Secure Tool-Using AI Agents Before They Touch Production

June 8, 2026
Colorful sticky notes arranged on an office wall, symbolizing governance checklists and planning.
Learning Hub

AI Governance for Agentic Apps: A Practical Checklist for Builders

June 8, 2026
A technician connects green fiber optic cables at a data center, representing a private production inference endpoint.
Learning Hub

How to Deploy a Fine-Tuned LLM Behind a Private Production Inference Endpoint

June 8, 2026
Narrow aisle behind black supercomputer racks in a data center
Learning Hub

Kubernetes SELinux Volume Labeling: What Cluster Operators Should Audit Before v1.37

June 8, 2026
SXZ.io SXZ.io
  • [email protected]

Categories

Articles
Learning Hub
News

All Rights Reserved by SXZ.io ©2026