absurdum reductus

Your Backup Restores Cleanly and Loses Everything

We restored a password vault from an offsite backup. It started. It answered its health check. It had no accounts in it. Nothing was corrupt, nothing errored, and no file was missing from the list we had been told to restore. The vault’s entire contents were in a 12 KB file we had not copied.


It came up#

The drill was ordinary. Take the offsite copy of the vault’s data directory, stand up a provisional instance of the same software on a spare machine, and log in, so that the other recovery steps that need credentials from the vault can proceed. The written procedure, by someone careful who knew the system, said to restore the database file, the attachments directory and the configuration file.

We did that. The instance started. Its health endpoint answered. Then we did the one thing the procedure did not say to do, and counted the rows in the users table. Zero.

The vault woke up, answered, and was empty. Quite an experience, with no second copy to compare it against. That is what it is to be the last copy.

A 12 KB file nobody listed#

The vault runs SQLite in write-ahead-log mode. Any application that does has the same shape, so check yours. In that mode a commit does not modify the database file. SQLite’s own documentation describes it: changes are appended into a separate WAL file, and a commit occurs when a commit record is appended there. Moving those transactions back into the database file is a checkpoint, which happens by default when the WAL reaches a thousand pages, or when the last connection closes.

So while the application is running, the most recent commits live in db.sqlite3-wal, not in db.sqlite3. The same page says what happens if the two are separated: “transactions that were previously committed to the database might be lost, or the database file might become corrupted.”

Here is the whole mechanism in twenty lines, with the application standing in for itself:

import os, shutil, sqlite3

os.makedirs("live", exist_ok=True)
app = sqlite3.connect("live/db.sqlite3")          # the running application
app.execute("pragma journal_mode=wal")
app.execute("create table users (email text)")
app.commit()
app.execute("pragma wal_checkpoint(truncate)")    # an old database: schema long since in the main file
app.execute("insert into users values ('someone@example.com')")
app.commit()                                       # the new account: committed, durable, in the WAL

print("files on disk while the app is running:")
for f in sorted(os.listdir("live")):
    print(f"  {f:16} {os.path.getsize('live/' + f):6} bytes")

def restore(name, files):
    os.makedirs(name, exist_ok=True)
    for f in files:
        shutil.copy("live/" + f, name)
    n = sqlite3.connect(name + "/db.sqlite3").execute(
        "select count(*) from users").fetchone()[0]
    print(f"{name}: copied {len(files)} file(s) -> users = {n}")

restore("restore-a", ["db.sqlite3"])
restore("restore-b", ["db.sqlite3", "db.sqlite3-wal", "db.sqlite3-shm"])
files on disk while the app is running:
  db.sqlite3         8192 bytes
  db.sqlite3-shm    32768 bytes
  db.sqlite3-wal     4152 bytes
restore-a: copied 1 file(s) -> users = 0
restore-b: copied 3 file(s) -> users = 1

The database file is complete and valid. It has the schema. It opens without a complaint. It is simply the database as it stood at the last checkpoint, and everything since is in the file beside it. In the real drill, with an account registered seconds before the backup ran, the whole account was in a 12 KB -wal. Restored without it: zero users. Restored with it and the -shm index: one.

Why this is the worst shape available#

Every other restore failure announces itself. A missing file is a missing file. A schema mismatch is an error. A service that will not start is a service that will not start. This one produces a green result. The software starts, the health check passes, the login page renders, and the data is gone.

In a disaster-recovery context that is especially cruel, because the operator has no independent copy to compare against. That is why they are restoring. “It came up” is the only signal available, and it is a false one. Not very sporting.

It is also a habit that forms honestly. Stop the application and copy its directory, and the copy is fine: the last connection closing does a final checkpoint and deletes the WAL, so the single file really is the whole database. The habit learned on cold copies then meets a hot one, taken by a snapshot of a running volume, and the single file is no longer the whole database. The backup producer did nothing wrong. The snapshot held all three files. The loss happened at the consumer, when a human restored “the database” and meant one file.

The count that separates a good restore from a confident one#

One line, before declaring anything:

python3 -c "import sqlite3;print(sqlite3.connect('/restored/db.sqlite3').execute('select count(*) from users').fetchone())"

Zero, on a database you know had content, means the WAL is missing or the snapshot predates the writes. No amount of “the service started” substitutes for it. The restore script now refuses a tree with no database file and warns loudly on a tree with no -wal, and the drill asserts the hazard as a control that must go red: restore the single file, count zero, or the drill has stopped testing the thing it exists to test.

The neighbour nobody lists#

The same directory held a second file the procedure did not mention: rsa_key.pem, the key the vault uses to sign its session tokens. Omit it and the software generates a new one on start. Logins still work. Every existing session and every issued token silently does not.

Two partial successes in one directory, both quiet. The first loses the data and tells you nothing. The second keeps the data and logs everyone out, and tells you nothing either.

The key was inside the box#

Rehearsing the restore end to end surfaced something the file list could not. The backup was encrypted, as it should be. The question nobody had asked in writing was where the keys lived.

Two of them lived in the wrong place. The portable disk the offsite copy sits on is encrypted, and its passphrase was kept as an item in the vault, which is the thing being restored from that disk. The backup repository on the disk is encrypted too, and its password was kept as a secret inside the cluster the offsite copy exists to survive the loss of. Both had been written into the runbook as prerequisites: have the disk key, have the repository password. A prerequisite is a documentation answer to an operational problem. Written as faults, they read differently: lose the cluster without having copied that password out first, and every snapshot on the disk is ciphertext with no key.

Nothing in the backup path reports this. The backups keep succeeding. Only the restore is impossible, and only on the day it matters.

The test generalises past this vault and this disk. For every encrypted backup, ask where the key lives, and reject any answer that names a system the backup exists to survive the loss of. The remedy is unglamorous: a copy of the key somewhere outside the failure domain, a safe or a vault that is not the one being backed up. Everything else is detail.

A runbook that has never run is a hypothesis#

Three of the four steps in the original procedure were wrong. The file list omitted the WAL and the signing key. The method named for opening the backup repository was refused by the tool. The image it named was not the one that had written the data. Each was a reasonable guess by someone who knew the system, and each was wrong in the specific way that written-but-never-executed instructions are wrong: internally consistent, confidently phrased, untested against the thing itself.

One rehearsal against invented data turned up all three. That is the whole cost of the fix, and the whole argument for it. A restore procedure that has been written and not run is a hypothesis about your backups. The day you most need it to be true is the one day you cannot afford to find out.

We have seen restores you would not believe. Clean ones, with a green health check and nothing inside. Count the rows.