I killed a SQLite writer mid-commit to see what would survive

2026-11-28来源 dev.toEnglish

I expected killing a SQLite process with kill -9 to either lose nothing, because WAL mode is supposed to be crash-safe, or lose everything, because I was imagining some worse failure in the back of my mind. It did neither. What it actually lost, and when, turned out to depend on exactly which byte the process died on, and that was worth measuring properly rather than trusting from memory.

I ran all of this locally with Python's sqlite3 module and the sqlite3 CLI, both linked against SQLite 3.45.1, no containers, no network calls. Everything below is from this machine, this afternoon. I repeated the trickier tests three times each and say so where I did; the rest are single runs.

Killing the writer before it commits

First test: a writer opens a transaction, inserts 1,000 rows, and sits there without committing while I kill it. It had already committed four earlier transactions of 1,000 rows each.

trial 1: rows=4000 integrity=ok recovery_time=0.0212s trial 2: rows=4000 integrity=ok recovery_time=0.0207s trial 3: rows=4000 integrity=ok recovery_time=0.0230s 

4,000 rows, not 5,000. The uncommitted transaction disappeared cleanly, every time, and PRAGMA integrity_check came back ok in all three trials. That part matched what I expected.

The "recovery_time" column needed a second look, though. Reopening the database and running SELECT count(*) plus an integrity check took about 21ms, which I was about to credit to WAL recovery. Then I ran the same two queries against a database of the same shape that had been closed normally, no crash involved:

clean close after kill -9
trial 1 0.0150s 0.0212s
trial 2 0.0129s 0.0207s
trial 3 0.0142s 0.0230s

Most of that 21ms is just the sqlite3 CLI starting up, which happens either way. The part actually attributable to recovering from the crash is the gap between the two columns, roughly 6–9ms across the three trials. Still fast, but it's a different number than the one I almost wrote down, and with only three trials of each I wouldn't trust it to a tighter range than that.

Killing the writer right after it commits

Second test: same setup, but the writer commits its fifth transaction and I kill it before anything checkpoints the WAL back into the main database file.

Right after the kill, before I'd opened any new connection:

file size
main .db 4,096 bytes
.db-wal 1,512,072 bytes

The main file hadn't grown at all. Everything from all five transactions was sitting in the WAL file. The first query I ran against it afterwards:

sqlite3 test.db "SELECT count(*) FROM t;" 5000 sqlite3 test.db "PRAGMA integrity_check;" ok 

All 5,000 rows were there, and the main file had grown to 1,462,272 bytes by the time that query returned. I hadn't run any checkpoint command. The plain SELECT triggered it as a side effect of opening the connection, and the -wal file was gone afterwards. In this run, nobody had to remember to checkpoint after the crash; the next reader did it as a side effect, because that's the default wal_autocheckpoint behaviour this database was running with, not something I asked for explicitly.

One reader can stall a checkpoint indefinitely

Third test: a reader opens a transaction and just holds it, no commit, no rollback, for 8 seconds. While it's open, a separate writer commits 20 transactions of 100 rows (2,000 rows). Then I tried to checkpoint:

checkpoint PASSIVE while reader open: 0|128|0 checkpoint TRUNCATE while reader open: 1|128|0 

That leading 1 is SQLite telling me the checkpoint was blocked. Zero of the 128 pending frames got moved into the main file either time, and the WAL file sat at exactly 527,392 bytes before and after both attempts. The writer never raised an error or saw its commits rejected; its 20 commits all went through, and only printed "writer done" once finished (I didn't instrument it for per-commit timing, so I can't say how fast, only that none of them failed). Only the checkpoint stalled.

Once the reader's transaction ended, running the exact same TRUNCATE checkpoint again gave 0|0|0, and the -wal file was gone. No manual intervention, no rebuild, just the next checkpoint succeeding because nothing was holding a snapshot open any more. If something in your stack opens a long read transaction and forgets to close it, this is what it costs you: not a slow query, a WAL file that quietly keeps growing until that transaction ends.

200 corrupted bytes cost a whole 50-row commit

This is the one I didn't expect going in. I killed a writer right after its tenth commit (500 rows total, 50 per commit), before any checkpoint, giving me a 255,472-byte WAL file. Then, instead of killing anything, I just chopped the last 200 bytes off that file with truncate(), simulating a disk write that didn't fully land, and reopened the database.

expected actual
rows 500 450
integrity_check — ok

Three trials, same result every time: exactly 50 rows gone, one whole commit, not a partial one. That matches what SQLite's own documentation says its WAL recovery does: read frames in order and stop at the first one that doesn't check out, then treat everything from there on as if it had never been written. I didn't instrument the recovery internals to watch that frame-by-frame, so I'm reporting the row-count result I measured and the documented mechanism that explains it, not something I directly observed happening. Either way, 200 bytes of damage took an entire 50-row commit with it, and integrity_check doesn't flag any of this as a problem, because as far as the database is concerned, that transaction simply never happened.

The old journal mode doesn't let this situation arise the same way

I wanted the opposite reading, so I set up a smaller version of the same idea, a reader holding an open transaction, and a writer trying to get in, but with journal_mode=DELETE, SQLite's older rollback-journal mode, instead of WAL. This time the reader held its transaction for 5 seconds, and the writer only had to do a single insert and commit, not 20.

commit FAILED after 2.005s: OperationalError('database is locked') retry after reader released: commit succeeded after 0.0018s 

With a busy_timeout of 2,000ms, the one commit the writer tried blocked for the full timeout and then failed outright with "database is locked." That's a smaller test than the WAL one above, but it already shows the shape of the difference: WAL let a much busier writer (20 commits) through without complaint while a reader was open, and paid for it later in a stalled checkpoint; the old mode didn't let the WAL grow in the first place, it just blocked, then refused, the writer. Neither behaviour is free.

Writers still only run one at a time

Last test: does WAL actually let writes happen in parallel? I ran 250 commits from a single process, then 250 commits split across five concurrent processes (50 each), three times each, and had every writer process catch and count its own OperationalErrors so I'd have a real count instead of an impression:

single process 5 concurrent processes
trial 1 0.0551s 0.1228s
trial 2 0.0483s 0.0899s
trial 3 0.0498s 0.1177s

Same total work, roughly 1.9 to 2.4 times slower with five processes than with one. Across all fifteen individual writer runs (5 processes × 3 trials), each one logged its own error count, and every single one came back errors=0. WAL still only allows one writer at a time; what it buys you is that readers don't get blocked by that writer, not that writers stop queuing. I should flag one thing I didn't isolate here: this machine has 4 cores running 5 writer processes at once, so some of that slowdown could be ordinary scheduling contention rather than SQLite's write lock specifically. I can say the five processes didn't write faster than one; I can't cleanly separate how much of the gap is the database lock versus the OS juggling five Python processes on four cores.

What I got wrong on the way

My first attempt at the truncation test used a normal con.close() instead of kill -9 to end the writer. SQLite checkpoints and removes the WAL file as part of a clean shutdown when it's the last connection, so by the time I went to truncate the WAL file, it had already vanished and the data was safely in the main file. I'd built a test for corruption and accidentally built a test for how tidy a normal shutdown is instead. Switching back to killing the process with -9 is what actually left a WAL file to damage.

Run it yourself

import sqlite3, time, os con = sqlite3.connect("demo.db", timeout=30) con.execute("PRAGMA journal_mode=WAL") con.execute("CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, val TEXT)") for c in range(10): con.execute("BEGIN") for r in range(50): con.execute("INSERT INTO t (val) VALUES (?)", (f"c{c}_r{r}",)) con.commit() print("PID", os.getpid()) # now: kill -9 <PID> from another shell # then, before reopening: truncate the last 200 bytes of demo.db-wal # with open("demo.db-wal", "r+b") as f: # f.truncate(os.path.getsize("demo.db-wal") - 200) 

Reopen with sqlite3 demo.db "SELECT count(*) FROM t; PRAGMA integrity_check;" and compare the row count against what you expect.

Where I landed

I'm keeping WAL mode for anything where a reader and a writer need to coexist. The checkpoint-blocked-by-a-reader thing bothered me less once I saw wal_checkpoint just tells you the 1 straight up; I'll add that PRAGMA to a health check rather than wait for the WAL file to show up fat on disk.

The 450-rows result is the one that actually changed how I'd debug a "missing data" ticket. Before this, "the commit returned, so the row is in there" was close enough to a fact in my head. Now, if I ever see a database that's missing exactly one batch of writes and nothing else looks wrong, a torn write at the end of a WAL file is on my list of suspects, above "the application code dropped it," not below.

原文:https://www.a8q9.cn/en/article/i-killed-a-sqlite-writer-mid-commit-to-see-what-would-survive-d220da.html

相关文章