Research notes / SQLite
SQLite WAL checkpoint starvation: success is not completion
Published 14 October 2026 / Updated 2026-11-30 / Measured synthetic workloads
A successful PASSIVE checkpoint can leave work unfinished. In our controlled run, a read transaction held checkpoint progress at 11 frames while committed writes grew the WAL to 55. Ending that transaction allowed completion without closing its connection.
On this page17 sections
Investigating a large WAL? Compare checkpoint progress, active frames and file footprint.
Investigating an application cache? A correct change signal can still leave stale rows, even after a connection is reopened.
The snapshot, not the connection count
A WAL reader retains a view of committed data for its transaction. Its end mark limits which page versions it can see. A later commit need not become visible until that reader ends its transaction and starts another. [4]
Checkpointing must preserve the versions still needed by readers. Repeatedly retained snapshots can therefore prevent WAL recycling: checkpoint starvation. An open connection without an active read transaction is not the same condition. [1]
A snapshot handle is not retained history or a backup
The optional SQLite snapshot API records a historical WAL view so a later read can reopen it. The sqlite3_snapshot object is not a database copy: keeping the handle allocated does not preserve overwritten history. sqlite3_snapshot_open can return SQLITE_ERROR_SNAPSHOT when that history is no longer available. [Snapshot object] [Historical read contract]
Capture and reopen require SQLITE_ENABLE_SNAPSHOT at build time. Capture also requires autocommit off, WAL mode, no write transaction on the named schema and a transaction already written to the current WAL. A database configured for WAL is therefore not sufficient by itself. [Capture prerequisites]
A failed capture does not return a usable handle. When capture prerequisites are violated, the output pointer has an undefined value; do not dereference it or pass it to the handle destructor as though capture succeeded. Check for SQLITE_OK before consuming the result. Allocation can also fail with SQLITE_NOMEM. [Capture failure contract]
Read lifetime and handle lifetime are separate
The current capture contract makes an important distinction. If sqlite3_snapshot_get itself starts the read transaction, the returned handle is protected from writer or checkpointer invalidation until that read closes. If a read was already open, the documentation does not give that guarantee. An active reader alone is not proof that a returned handle remains reopenable. [Conditional protection]
Freeing the handle releases its allocation; manage the application's read transaction separately. Conversely, ending a read does not promise that an allocated handle will remain usable. The existing reader-lifetime measurements on this page did not exercise the snapshot API. [Handle cleanup]
Reopening and recovering do not create missing versions
The reopening connection must know the database is in WAL mode and have autocommit disabled. To replace an existing read, it must have no active SELECT statements (stepped but not reset or finalized). An SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT leaves that existing read on its prior snapshot; other errors can leave its final state undefined. Check the result before treating a historical view as acquired. [Open result and prior-read state]
Retained WAL bytes and immediately reopenable snapshots are not the same. If a WAL remains after all database connections close, a new connection initially exposes only the last transaction in that WAL to sqlite3_snapshot_open, even when older valid transactions remain in that WAL. sqlite3_snapshot_recover attempts to rescan the retained log and make all valid snapshots available. It cannot reconstruct overwritten or absent history, and requires WAL mode with no open read transaction on the target database. Check its result before relying on the recovered availability. [Retained-WAL discovery]
Handle comparison is also bounded: sqlite3_snapshot_cmp orders valid handles from the same database obtained since its last WAL deletion. It is not a wall-clock timestamp or cross-database ordering. [Comparison scope]
This section is a synthesis of API contracts checked on 28 November 2026, not a new runtime experiment. For an independent recoverable copy, use an appropriate backup mechanism and verify its contents and recovery scope.
Backup cleanup can leave the reader alive
A backup object and a caller-owned source read have different lifetimes. In our separate two-build experiment, both completion and cancellation left a previously established read transaction active. A BEGIN-only control did not retain that read; BEGIN plus SELECT did. The reader-only control produced the same retention without a backup object.
Setting journal_size_limit to zero did not prevent the live WAL from growing. The setting is not a quota on required history. [Official size-limit contract] Read the source-ownership experiment, fourteen schedules and complete evidence before attributing post-backup WAL growth to a leaked backup object.
Releasing a savepoint is not necessarily committing
A SQLite savepoint marks a rollback boundary. Inner RELEASE removes that boundary, but an outer rollback can still undo the writes. Successful outermost release commits; ROLLBACK TO keeps its target available for reuse. [Savepoint contract]
We ran four ordered SQL schedules in each of DELETE and WAL modes on SQLite 3.45.1, using Python sqlite3 with implicit transaction handling disabled. After every SQL statement, fully drained queries read complete rows on the writer and a separate autocommit connection. These diagnostic reads are part of the workload. [Complete observations]
| Mode | Observation point | Writer | Other connection | After reopen |
|---|---|---|---|---|
| DELETE | Inner release, before outer rollback | 1 | Empty | Empty |
| DELETE | Outermost release | 1 | 1 | 1 |
| DELETE | Second rollback to retained mark | Empty | Empty | Empty |
| DELETE | Rollback to older same-name mark | Empty | Empty | Empty |
| WAL | Inner release, before outer rollback | 1 | Empty | Empty |
| WAL | Outermost release | 1 | 1 | 1 |
| WAL | Second rollback to retained mark | Empty | Empty | Empty |
| WAL | Rollback to older same-name mark | Empty | Empty | Empty |
The first schedule released an inner mark, then rolled back the outer transaction. The second released a savepoint-started outer transaction. The third successfully rolled back to the same retained mark twice. The fourth reused a name: releasing its newest mark left the older mark available to undo both inserts.
Savepoint lifetime is part of the API contract, not a consequence of the word WAL. In ARIES section 5.2, a rollback consumes its target savepoint. SQLite deliberately keeps the target of ROLLBACK TO. The repeated-rollback case above exercises that difference. This is a contract comparison; these SQLite schedules do not reproduce ARIES recovery. [ARIES, section 5.2]
Outermost RELEASE does not refresh an existing WAL read transaction. In a separate two-case control, BEGIN followed by a drained SELECT kept the reader on the old empty snapshot after the writer released its outermost savepoint; a fresh connection saw row 1. The retained reader saw row 1 after ending its transaction. BEGIN alone, with its first SELECT delayed until after RELEASE, did not retain that old view. [Reader snapshot contract]
Reproduce with the SQL harness and regression tests. This is normal execution on one recorded runtime, not direct C-API observation, a benchmark or a power-loss test. In WAL, committing and copying committed pages back into the main file remain different operations. [WAL contract]
A successful close can leave a reader or a pending write
Connection disposal, statement completion and transaction outcome are separate events. SQLite documents that sqlite3_close_v2() may return SQLITE_OK while waiting for retained statements to be finalized. The connection handle is then unusable: do not query its transaction state or call diagnostics on it. Observe effects through a separate connection. [Close contract]
Hesela ran twelve ordered native C-API schedules on each of two recorded builds: SQLite 3.45.1 distro alt1 and upstream 3.54.1. These calls used Python ctypes, not Python's sqlite3 transaction wrapper. Each schedule used a fresh WAL database, zero busy timeout and disabled automatic checkpointing. The two builds produced the same case records. [Original observations and derived summary]
Retaining an object is not necessarily retaining a snapshot
With SELECT stopped at its first row, close_v2 returned 0, but the observer's TRUNCATE could not complete. Its tuple was (1, 4, 3): busy, four WAL frames, three frames checkpointed in total. This is unfinished work, not zero checkpoint progress. Finalizing the surviving statement allowed (0, 0, 0). Unstepped, drained and reset controls delayed destruction too, without obstructing TRUNCATE.
| Schedule | Close code | Cleanup witness at close | TRUNCATE after close | After finalization |
|---|---|---|---|---|
| read-active-v2 | 0 | 0 | [1,4,3] | [0,0,0] |
| read-active-v1 | 5 | 0 | [1,4,3] | [0,0,0] |
| read-done-v2 | 0 | 0 | [0,0,0] | [0,0,0] |
| read-unstepped-v2 | 0 | 0 | [0,0,0] | [0,0,0] |
| read-reset-v2 | 0 | 0 | [0,0,0] | [0,0,0] |
| read-finalized-v2 | 0 | 1 | [0,0,0] | [0,0,0] |
The cleanup witness is a registered SQL function's application-data destructor; it is not an operating-system descriptor count. The finalized-before-close control runs that witness during close. Other v2 cases run it when the last pending statement is finalized. Ordinary sqlite3_close() instead returns BUSY with an outstanding statement and leaves the connection usable.
Finalization is not a cancellation request
Each write fixture tried to add three rows but consumed only one RETURNING row. After close_v2 returned OK, finalization completed the implicit transaction and exposed all three additions. In the explicit-BEGIN variant, finalizing the last pending statement allowed deferred connection destruction, which rolled back the still-open explicit transaction. Both finalizations returned 0. [Transaction rules] [RETURNING order]
| Schedule | Close code | Writer probe codes | Visible row counts |
|---|---|---|---|
| write-implicit-v2 | 0 | [5,0,0] | [3,6,6] |
| write-explicit-v2 | 0 | [5,0,0] | [3,3,3] |
| write-implicit-v1 | 5 | [5,0,0] | [3,6,6] |
| write-explicit-v1 | 5 | [5,5,0] | [3,3,3] |
| write-rollback-v2 | 0 | [0,0,0] | [3,3,3] |
| write-commit-v2 | 0 | [0,0,0] | [6,6,6] |
For ordinary-close cases, cleanup includes a second close after finalization. The commit control finalizes and explicitly commits before closing; the rollback control explicitly rolls back before closing. Counts summarize the table, but validation checks every ordered (id, value) pair and the reopened database.
Engineering implication: make the commit-or-rollback decision while the connection is usable, manage owned statements and check completion errors. One returned row or a successful disposal call cannot identify the outcome. An earlier SQLITE_ROW also does not exclude a later reset/finalization error. No such error was injected here. [Completion-error contract]
These are constructed schedules with overlapping lifetimes on one host, not parallel-thread races, crash or power-loss tests, wrapper-language results, benchmarks or failure-rate samples. Exact frame counts are fixture-specific. BLOB handles, backup objects, attached databases and I/O faults were not exercised.
Checking the result through a second implementation
A separate C observer matched all 48 executions: 12 schedules on 2 recorded engine binaries, each with 2 harness compilation modes. It compared complete ordered values, transaction state before close, destructor timing, writer exclusion, WAL counters and reopened rows. These are two compiler modes of the observer, not four SQLite engine configurations. The C observer does not import or call the original Python driver or validator. [Verification results]
The checkpoint witness calls sqlite3_wal_checkpoint_v2() directly: SQLITE_BUSY=5 corresponds to the SQL PRAGMA's busy flag of 1, not its frame counters. Both paths still use SQLite's own checkpoint implementation. This is same-host implementation diversity, not external peer review or a blinded replication: the earlier packet was visible, the engine binaries were reused, and shared assumptions remain possible. [Checkpoint API contract] Download both observers, retained results and sources in one offline bundle.
Read retained SQLite documentation with source-aware navigation, download replay code, raw observations and source snapshots, derived results (JSON) and method and reproduction instructions. The archive contains twelve schedules per build, not 24 independent field samples. The distro build is not asserted byte-identical to the upstream 3.45.1 source.
Observed: three different completion signals
Both cases started with the same 32 rows. One reader kept an explicit transaction open after reading generation 1 from the WAL. The control read and finalized its statement without retaining a transaction. A separate connection committed four updates. We then requested a PASSIVE checkpoint after each update.
| State | Mode | Busy | Log frames | Checkpointed frames | WAL bytes |
|---|---|---|---|---|---|
| Pinned reader / batch 1 | PASSIVE | 0 | 22 | 11 | 90,672 |
| Pinned reader / batch 2 | PASSIVE | 0 | 33 | 11 | 135,992 |
| Pinned reader / batch 3 | PASSIVE | 0 | 44 | 11 | 181,312 |
| Pinned reader / batch 4 | PASSIVE | 0 | 55 | 11 | 226,632 |
| Reader still pinned | TRUNCATE | 1 | 55 | 11 | 226,632 |
| Read transaction ended | RESTART | 0 | 55 | 55 | 226,632 |
| Then truncate | TRUNCATE | 0 | 0 | 0 | 0 |
| Control / idle connection, batch 4 | PASSIVE | 0 | 11 | 11 | 90,672 |
The pinned reader continued returning generation 1 while the writer saw generations 2 through 5. All 32 IDs, generation fields and complete 1,024-byte payloads matched their expected values on every check. After reader release, both connections saw generation 5. Structural integrity checks also returned ok.
The control checkpointed every current frame after each batch. Its WAL file remained 90,672 bytes even when only 11 frames were current. In the pinned case, RESTART finished after release without shrinking the file; the following TRUNCATE reduced it to zero. A retained file is not, by itself, a backlog measurement.
Read all three columns, and keep the mode
PRAGMA main.wal_checkpoint(PASSIVE) returns a busy indicator, log-frame count and checkpointed-frame count. Zero in the first column does not assert equality of the other two. A count of -1 can mean there is no WAL; do not turn that sentinel into a negative backlog. [3]
The checkpointed count includes earlier progress in the current WAL cycle. It is not the number of frames copied by just this call. PASSIVE does not wait for readers via the busy handler. RESTART additionally waits for WAL readers to finish; TRUNCATE also shortens the file on success. These stronger modes can still return busy. Our test explicitly used a zero busy timeout. [2]
Monitoring synthesis: keep mode, result, current frame counts, file length and read-transaction lifetime together. Compare nonnegative counts from the same call; resets make them unsuitable as lifetime counters. A growing difference deserves investigation, not automatic deletion of the WAL. Calling PASSIVE changes database state; it is not a read-only status query.
Which bytes do checkpoint counters describe?
A positive checkpoint count need not mean the main file changed. In a separate controlled SQLite 3.45.1 run, PASSIVE returned (0,100,50), while the main file remained byte-identical to its 8,192-byte baseline. The retained frame map places every page's newest WAL version after frame 50. In upstream 3.45.1, the checkpoint iterator selects the newest frame for each page; the copy loop skips frames beyond its safe frontier, then advances nBackfill on success. [Checkpoint implementation]
This source mechanism explains the observed file state. It is not a trace of the distribution binary's system calls, or proof of zero physical device writes. The API counter also includes previously checkpointed frames, so multiplying it by page size does not measure traffic per call. [Counter contract]
| Stage | Main bytes | WAL bytes | Valid committed frames | Checkpoint result |
|---|---|---|---|---|
| Baseline | 8,192 | 0 | 0 | (0,0,0) |
| PASSIVE, reader pinned | 8,192 | 412,032 | 100 | (0,100,50) |
| FULL, reader released | 204,800 | 412,032 | 100 | (0,100,100) |
| One-page update | 204,800 | 412,032 | 1 | not called |
| TRUNCATE | 204,800 | 0 | 0 | (0,0,0) |
FULL completed but retained a 412,032-byte WAL. The next one-page update reused that same extent: 100 physical frame slots remained, but only one frame belonged to its valid committed prefix. Header salts and rolling checksums distinguish that prefix from old slots. A large retained WAL therefore need not imply an equally large active log. [WAL reset and frame validity] TRUNCATE then removed the WAL extent while 24 freelist pages remained inside the main database: log truncation did not compact database free space.
The reader also changes the space-accounting population
With 512-byte pages and auto_vacuum=NONE, a committed insert left a 1,024-byte main file alongside a 153,600-byte logical database extent; changed pages lived in WAL. After deletion, the old transaction reported 96 rows and 300 dbstat pages; the current transaction reported 24 rows and 77 dbstat pages against the same captured main/WAL bytes. Snapshot selection changes what the traversal counts. [dbstat pager traversal]
dbstat counts B-tree and overflow pages, excluding freelist, pointer-map and lock-byte pages. Its aggregate mode returns one row per tree, with pageno holding a page count. [dbstat contract] For the small 512-byte incremental-auto-vacuum control, 77 dbstat pages + 223 freelist pages + 3 pointer-map pages accounted for all 303 pages. No incremental vacuum was requested. These are different populations from filesystem allocation or NAND writes; see also the B-tree layout measurements.
Count pages, not aggregate rows
On a build with SQLITE_ENABLE_DBSTAT_VTAB, this query separates the number of trees from their page count and page bytes. Aggregate mode requires SQLite 3.31.0 or later. [Aggregate-mode contract]
SELECT count(*) AS trees,
sum(pageno) AS pages,
sum(pgsize) AS page_bytes
FROM dbstat('main', 1);The final 1 enables aggregation: count(*)counts trees, including sqlite_schema, while sum(pageno) counts their pages. Without aggregation, pageno is a page identifier; summing it is not a page count. Neither form includes the excluded free or pointer-map pages.
For several SQL accounting queries that must describe one view, use the same short read transaction and finish it promptly. A monitoring reader can itself retain an old WAL snapshot. This does not make separately sampled file sizes atomic. [Reader and checkpoint lifetimes]
Method: four fresh databases combine 512/4,096-byte pages and NONE/INCREMENTAL auto-vacuum, with eight ordered states each. All 32 semantic/format rows matched on the recorded 3.45.1 and 3.53.1 builds after setting secure_delete=ON explicitly. Initially different defaults changed WAL length; the failed comparison is documented, not averaged away. This setting is a fixture control, not a sanitization recommendation. Calls are serialized; sequential file captures are not an atomic snapshot for live production monitoring. These dependent observations establish neither a performance estimate nor an all-version guarantee. The upstream tag is explanatory, not binary attestation.
Complete reproduction package contains code, tests and all 64 primary main/WAL captures. All 32 accounting rows, second-build comparison and method and limitations preserve the measurement context. Do not delete a live WAL to reclaim space.
Checkpoint completion does not mean history erasure
A separate SQLite 3.45.1 deletion fixture used an ordinary three-row table, core secure_delete=ON, disabled automatic checkpointing and one older read transaction. After deletion the current query omitted the row while the old reader still returned it. A TRUNCATE attempt returned (1,4,3): busy, four log frames, three checkpointed. Calling truncation did not mean it completed.
After the reader ended, FULL and RESTART both returned (0,4,4). The token was absent from the main-file scan but remained in the 16,512-byte WAL; those two captured WAL files were byte-identical. Successful TRUNCATE returned (0,0,0) and reduced the accessible WAL length to zero. A backup made before deletion still returned the original row. These are six stages of one controlled lifecycle, not six independent trials.
The checkpoint API separates these outcomes: RESTART prepares reuse by the next writer; TRUNCATE additionally shortens the log on success. [Checkpoint contract]Historical bytes need not remain indefinitely because a WAL can be reused or truncated.[WAL lifecycle] A zero-length logical file says nothing about physical media, filesystem snapshots or separate copies. Never delete a live WAL manually.
The two 4/4 results are total checkpoint progress, not four new page writes per call: the API includes frames checkpointed earlier. [Counter scope]File-byte presence also differs from replay eligibility. WAL reset changes header salts; frame validity requires matching salts and cumulative checksums, so old bytes may remain without belonging to the new log generation. [WAL format, 4.1 and 4.4]This fixture does not perform a subsequent writer/reset and does not measure residue after reuse.
Meng and Baier's 2019 forensic study examined SQLite deletion under different pragma settings, including retained journal content. Its recovery-tool evaluation is not an erasure-failure rate for deployed systems. We did not reproduce that tool or its benchmark; the present fixture instead isolates checkpoint and old-backup boundaries.[Primary study, sections 4 and 7]
Read the six-stage observations,full method and limits and standalone evidence archive. The complementary FTS5 deletion comparison separates search visibility, current index entries and file bytes. Scope a deletion report to the observer and copy actually tested.
The auto-checkpoint threshold is not a file-size cap
SQLite's auto-checkpoint setting is per connection and triggers a PASSIVE attempt after a commit reaches the configured frame threshold. It does not promise that every attempt completes or that the file is truncated. [5]
Gaffney and colleagues' VLDB 2022 paper connects BLOB size and checkpoint cost: its large-BLOB workload crossed the checkpoint threshold within one update. The evaluation used SQLite 3.38.0 and DuckDB 0.3.2 on cloud and Raspberry Pi hardware, reporting means of three trials. Those historical throughput results do not estimate long-reader prevalence or establish a current speed ranking. We reviewed the method and BLOB results, but did not reproduce that benchmark. [6, sections 4 and 4.3]
Our experiment disables automatic checkpoints to isolate the requested operations. It does not measure the default policy. Frequent checkpoint attempts cannot by themselves end an application's old read transaction.
Method, reproduction and limits
Recorded on Linux, Python 3.12.3, SQLite 3.45.1; source ID, compile options, kernel, script hash and effective settings are in the JSON. Each fresh database used 4,096-byte pages, synchronous=FULL, wal_autocheckpoint=0 and busy_timeout=0. A seed update created a WAL-resident snapshot before the reader opened its transaction.
All SQLite calls ran sequentially on one thread. Transaction lifetimes overlapped, but writer and checkpoint calls never ran simultaneously. This is a deterministic software observation, not a concurrency stress test, power-loss experiment, durability proof, latency benchmark or probability sample. Exact counts belong to this build and workload. No confidence interval is meaningful for this deliberately constructed two-case comparison.
The installed library is not a patch recommendation. SQLite documents a separate WAL-reset race fixed in 3.51.3 and specified backports. Our schedule does not exercise that race or establish its absence in this build. [1, section 11]
Full observations and provenance (JSON) / Reproduction script (Python). Use disposable storage. The script creates and removes its own temporary databases and refuses an existing output filename.
python3 sqlite-wal-readers.py --work-root . --output result.jsonRun recorded 2026-10-14T08:20:23.161354+00:00; no random seed or external Python packages.
A stale snapshot needs a new transaction, not a longer wait
Checkpoint starvation is not the only consequence of retaining a read transaction. When that reader later tries to write, a newer committed database state can cause SQLITE_BUSY_SNAPSHOT. The extended code is 517; its primary code is SQLITE_BUSY (5). Keeping only the primary code loses this distinction. [8]
We added six disposable schedules on SQLite 3.45.1. Connection A read only row 1; B then committed a change to row 1 or row 2. A attempted to increment row 1 twice without ending its transaction. Both attempts returned 517 in all four stale-snapshot cases, including the different-row case and both configured busy timeouts: 0 and 250 ms. B had already committed: there was no still-active writer to wait for.
| Schedule | Observed boundary |
|---|---|
| Read, other commit, then write (four cases) | 517 twice; the read transaction remained active. |
| BEGIN, other commit, then first read | The first read saw the new value; the write committed. |
| BEGIN IMMEDIATE before the other writer | The competing BEGIN returned 5; a WAL reader still succeeded. |
In each stale case, ROLLBACK followed by BEGIN and a fresh read permitted the update. Complete two-row checks verified both connections after commit. The different-row result is a measured counterexample to treating this as a row-level write-conflict detector; it is not a benchmark.
Choose the retry boundary
SQLite documents releasing the obsolete snapshot before starting another transaction. [4] Application consequence: rerun the reads and decisions that depended on them, not just a write calculated from stale values. Bound retries, and keep external side effects separately idempotent. Waiting cannot make the retained snapshot become current.
BEGIN DEFERRED alone does not establish the read snapshot: its first database access matters. BEGIN IMMEDIATE takes the writer position before those reads; its own acquisition can fail when another writer holds it. This moves contention earlier and occupies that position longer, so it is not a universal throughput optimization. [9]
A busy handler is not guaranteed to run for every lock conflict. [10] Our experiment records the configured timeout and returned code, not elapsed wait time or callback counts. It does not establish a latency bound. A failed checkpoint, a stale-snapshot upgrade and an uncertain I/O completion require different handling; do not route every failure through one retry loop.
Six-case observations and build provenance (JSON) / Reproduction script (Python 3.11+). Calls were sequential with overlapping transaction lifetimes, private connection caches and read_uncommitted disabled. No crash, timing benchmark or simultaneous writer race was tested. The recorded library is not a patch recommendation.
python3 sqlite-snapshot-upgrade.py --work-root . --output upgrade.jsonUpgrade experiment recorded 2026-10-16T02:07:30.246278+00:00. The script refuses existing output files and removes only its own temporary databases.
A successful retry can still overwrite the other increment
Restarting the transaction is necessary, but a cached application value can survive that restart. In a separate four-strategy experiment, A read a counter at 0 and calculated 10 in Python. B committed an increment to 1. SQLite rejected A's first write with 517 in every case. We then rolled back A and began a new transaction, changing only the retry strategy.
| Retry after rollback | Observed result |
|---|---|
| Reuse Python's cached 10 | Commit succeeded; final value 10. B's increment was overwritten. |
| Read again, then recompute | Read 1; committed 11. |
| Increment in SQL | value + 10 committed 11. |
| Require the original revision | Zero rows changed; a fresh read and recomputation then committed 11. |
This is an application retry bug, not a SQLite isolation defect. The failed transaction ended. The new transaction was instructed to replace the value with 10; the database was not told that this constant came from an obsolete read. All four final databases passed integrity_check. Structural integrity did not establish that both intended increments survived.
The retry boundary includes the calculation
For this row-local addition, the SQL expression avoids carrying an old computed value across transactions. It is not a general replacement for rereading a decision based on several rows. PostgreSQL's retry guidance independently makes the same application-level distinction: repeat the decision logic as well as its SQL. Its SQLSTATE handling is not SQLite's 517 handling. [11]
Our guarded case used a revision column advanced by every writer:
UPDATE counters
SET value = ?,
revision = revision + 1
WHERE id = ?
AND revision = ?;
SELECT changes();The first guard returned zero, not an SQL error. Check the affected-row count on the same connection immediately after the update. Our plain table has no triggers or foreign-key actions; the counter is not a total of those indirect effects. [12] After rejection, reread and recompute together. Updating only the expected revision while keeping the old value would defeat this safeguard. The protocol requires every writer to advance a non-reused revision; this run does not test wraparound, deletion/recreation or ABA.
What the isolation paper does, and does not, establish
Berenson and colleagues distinguish lost update (P4) from write skew in their 1995 isolation analysis. Section 4.2's snapshot model can prevent the former while allowing the latter. [13, sections 4.1-4.2] Our cached-value case crosses an explicit rollback boundary. It is not a reproduction of P4 within one transaction, or evidence that SQLite implements every behavior of that abstract snapshot model.
Four-strategy observations and provenance (JSON) / Reproduction script (Python 3.11+). Each strategy used a fresh two-row database and two connections. Complete value/revision checks include the untouched second row. Calls were sequential; there were no uncertain commits, crashes, timing measurements or external side effects. These constructed cases give no production error rate.
python3 sqlite-retry-values.py --work-root . --output retry-values.jsonRecorded 2026-10-16T02:38:13.606921+00:00. The script refuses existing output files and removes only its temporary databases. The installed library is not a current-patch recommendation.
A change signal can leave a stale cache
Do not acknowledge a new database-change signal with rows from an older snapshot. In a controlled schedule, a monitor detected a commit while a separate reader retained value 0. A deliberately flawed cache stored that old value and acknowledged the monitor's new token. After the read transaction ended, the monitor had no further change to report, so the cache would skip its next reload. This is an application-design counterexample, not a SQLite defect.
PRAGMA schema.data_version is local to a connection and database. Compare successive values on the same physical connection; its own commits do not change this signal. It is not a transferable database revision. [17]
| Phase | Observed state |
|---|---|
| Before the write | Writer value: 0; reader value: 0; monitor token: 2; cached value: 0. |
| After writer commit | Writer value: 1; reader value: 0; monitor token: 3; cached value: 0. |
| After reader release | Writer value: 1; reader value: 1; monitor token: 3; cached value: 0. |
The positive control paired the reader's token and rows within one read transaction. Another commit occurred while it held that snapshot; after release, the reader detected the changed token and returned value 2. This checks that explicit schedule, not every cache implementation. SQLite's snapshot rules and the paper's WAL end-mark explanation provide the mechanism. [4] [6, section 2.2.2]
Consistent does not necessarily mean newest. TxCache (OSDI 2010) permits bounded staleness while requiring cache and database reads to share one consistent view. That is a broader design principle, not a claim that SQLite implements TxCache; our ordered fixtures are not a replication of its system or benchmarks. [21, section 2.2]
A reconnect starts a new observer
Closing the observer, committing a write and opening a replacement produced the same numeric token on the old and new handles, despite different rows. A cache retaining only the number would miss the change.
| Journal | Replacement observation |
|---|---|
| DELETE | Old / new token: 1 / 1; old / new value: 0 / 1; number-only reload: no. |
| WAL | Old / new token: 2 / 2; old / new value: 0 / 1; number-only reload: no. |
Reset the cached observer state when the physical connection changes. Track the database too: in the attached-database controls, an external write to aux changed only aux.data_version; polling main.data_version missed it. The reverse control updated only main. Both were tested in DELETE and WAL modes. Schema names identify separate database files, not one shared token. [19]
A separate-process WAL writer also committed value 1 while the parent reader retained value 0 and its token. After the child exited, ending the parent's transaction exposed value 1 and a changed token. Moving the writer to a different process did not refresh the retained snapshot automatically. Upstream also tests cross-process notification. [20]
The same connection and filename are still not enough
We kept one physical observer open, detached aux, committed a change through another connection, then reattached the same file as aux. The filename and observer were unchanged; the token was equal before and after, but the complete two-row result had changed. Reusing the alias for a different database produced the same numeric collision.
| Schedule | Before / after |
|---|---|
| DELETE: Write while attached | Token 1 / 2; value 0 / 7. Number-only reload: yes. |
| DELETE: Reattach changed file | Token 1 / 1; value 0 / 7. Number-only reload: no. |
| DELETE: Reattach unchanged file | Token 1 / 1; value 0 / 0. Number-only reload: no. |
| DELETE: Different file, same alias | Token 1 / 1; value 0 / 7. Number-only reload: no. |
| WAL: Write while attached | Token 2 / 3; value 0 / 7. Number-only reload: yes. |
| WAL: Reattach changed file | Token 2 / 2; value 0 / 7. Number-only reload: no. |
| WAL: Reattach unchanged file | Token 2 / 2; value 0 / 0. Number-only reload: no. |
| WAL: Different file, same alias | Token 2 / 2; value 0 / 7. Number-only reload: no. |
The continuously attached write control changed the token. Reattaching an unchanged file returned unchanged rows. These controls distinguish a reset observation history from a claim that every reattachment changes data.Application consequence: invalidate the old baseline after successful reattachment, including when the pathname is unchanged. An application-assigned attachment generation can represent that lifetime; it is not a SQLite commit number. Conservative reload can do extra work in the unchanged control, but it does not confuse equal numbers with continuity.
SQLite documents DETACH as removing an additional database connection. [22] In the reviewed 3.45.1 source, DETACH closes its B-tree handle and ATTACH opens one. This supports the lifetime interpretation; it does not promise a particular reset integer, or establish that our distribution library was built byte-for-byte from that upstream tag. [23]
Row counters answer a different question
In the original controls, ten commits advanced a once-polled observer's token by one and an observer polled after each commit by ten. Both ended with the same rows. Those increments are build-and-schedule observations, not a transaction-count API.
After a one-row UPDATE was rolled back, changes() and total_changes() remained 1 while the stored value returned to 0. With an audit trigger, the direct count stayed 1 and the total was 2 even though rollback removed both effects. These counters describe work on the calling connection, not a durable history of committed rows. [12] [18]
Cache design: keep physical connection identity, database identity, attachment lifetime and read-transaction lifetime with the cached view. Reload through a suitable fresh snapshot, pair its token with its rows, and handle own writes separately. A signal observed on another handle does not establish which generation a reader returned.
The retained evidence contains 33 original fixtures and 21 connection-lifetime fixtures, plus 24 attachment-lifetime fixtures, each applicable schedule repeated three times. All complete row oracles and reopened integrity checks passed. Calls were ordered; the child writer was joined after COMMIT. There was no simultaneous-SQL stress test, pool product, crash or power loss. Exact integers belong to the recorded source ID, not all SQLite releases.
Complete research bundle (ZIP) / reproduction instructions / original observations / lifetime observations / original script / lifetime script. Attachment observations and attachment script cover the additional controls. Download the companion tests named in the instructions to check retained results as well as fresh runs. The scripts refuse existing output paths.
python3 observe.py --output observer-rerun.json
python3 lifetime.py --output lifetime-rerun.json
python3 attachment.py --output attachment-rerun.jsonRead-only is not an immutability promise
A read-only query can succeed, pass integrity checks and still return the wrong generation for the task. In nine controlled schedules, the reader option changed whether committed updates became visible. The two mutable immutable=1 cases deliberately violated its contract; these observations do not establish a SQLite defect.
mode=ro requests a read-only database connection. immutable=1 additionally promises that nobody can modify the underlying file. SQLite then omits locking and change detection. The documented consequence of a false promise includes incorrect results or corruption errors. [14] By contrast, query_only blocks data-changing SQL without making the database handle truly read-only; a checkpoint can still run. [15]
| Schedule | Observed generations |
|---|---|
| DELETE + mode=ro or query_only | Reader 0; writer committed 1; same reader saw 1. |
| DELETE + false immutable promise | Reader stayed at 0 after commit 1; a fresh connection saw 1. |
| WAL + mode=ro or query_only | Reader saw WAL generation 1, then committed generation 2. |
| WAL + false immutable promise | Reader saw main-file generation 0; even a fresh connection saw 0 after commit 2. |
| WAL + explicit mode=ro transaction | Reader retained 1 after commit 2; ending its transaction exposed 2. |
| WAL + query_only checkpoint | UPDATE was rejected; TRUNCATE checkpoint changed the main-file hash and reduced WAL bytes from 8,272 to 0. |
| Unchanged DELETE image + immutable | Reader, writer connection and fresh reader all saw 0. |
Every main-table write attempted through these readers returned SQLITE_READONLY (8). Every recorded integrity check returned ok, including the stale immutable reads. All four ordered records, generation fields and full 512-byte BLOBs matched their scenario's oracle. Write rejection, structural consistency and freshness were different observations, not interchangeable checks.
The ninth schedule also tested the documented query_only checkpoint exception. After rejecting UPDATE, that reader successfully ran PRAGMA wal_checkpoint(TRUNCATE). The three returned counters were 0, 0, 0; the main-file SHA-256 changed and the WAL shrank from 8,272 bytes to zero. Complete reads still matched generation 2. This measures file-state changes visible through the operating system, not stable-media persistence after a power cut.
Separate three reasons for old data
The ordinary WAL transaction retained an intentional snapshot and advanced after ROLLBACK. The immutable DELETE connection retained old results without an explicit transaction; reopening changed that result. In the immutable WAL case, reopening did not recover the committed WAL state. The main-file hash stayed unchanged while the WAL contained the newer commits. This is why "just reconnect" did not solve both constructed misuse cases.
The pinned upstream 3.45.1 pager sends immutable opens through its act_like_temp_file path, setting its reader state and no-lock behavior. [16] This source interpretation is consistent with the experiment. The recorded distribution build has its own source ID; byte-identical compilation from that upstream tag was not established. Outcomes after a broken promise are not an API guarantee.
Use the option to describe reality
Engineering synthesis: use normal read-only access when other actors may write. Reserve immutable access for a finalized image whose bytes and dependencies really will remain fixed. Do not set the flag merely to silence a permission or locking error. A WAL can hold committed data absent from the main file; do not delete it or mistake a main-file-only copy for a current database. [1, sections 4-5]
Read-only is not a filesystem-write sandbox. Ordinary WAL readers may need existing readable -wal and -shm files, or directory permission to create them. For a genuinely fixed image destined for read-only media, SQLite recommends converting to DELETE journal mode before distribution. This is a preparation step on a controlled copy, not permission to remove a live WAL. [1, section 5]
For a reproducible research dataset, record its intended generation and test its contents, not only successful SQL and structural integrity. The companion backup experiments likewise distinguish a completed, structurally valid copy from the recovery point an application actually needs. An intentionally old snapshot is not itself a fault; the requirement determines whether it is suitable.
Reproduction script (Python 3.11+) and all observations and provenance (JSON). Calls were sequential on one thread, using private caches, disabled mmap, 4,096-byte pages and disabled automatic WAL checkpoints. No concurrent calls, process crash, power cut, filesystem write tracing or timing measurement was performed. This is not an error-rate sample or a patch recommendation.
python3 sqlite-immutable-readers.py --output immutable-readers.jsonRecorded 2026-10-17T18:07:27.619556+00:00. Only disposable temporary databases are used; an existing output path is rejected. The release rerun also checks scenario labels, declared method and file-state consistency before publishing JSON. These checks constrain this experiment; they are not a general database verifier.
A frozen crash copy can still need rollback
Structural validity does not establish committed-state validity. In a separate process-exit experiment, no writer remained alive when the database and its hot rollback journal were copied. An immutable reader returned all 12 uncommitted generation-20 records and integrity_check returned ok. Normal recovery on another identical working copy restored committed generation 10. This is a different boundary from the concurrent-write misuse above: the captured files really stayed unchanged during inspection.
| Reader policy | Query result | Integrity check | Main bytes changed |
|---|---|---|---|
| Immutable | Generation 20 | ok | No |
| Read-write + query_only | Generation 10 | ok | Yes, recovered |
| Recover, then immutable | Generation 10 | ok | Yes, recovered |
| Normal read-only | Rollback required (776) | Not completed (776) | No |
| Normal read-write | Generation 10 | ok | Yes, recovered |
The retained matrix contains 400 reader observations from 80 writer fixtures: two SQLite builds, two repetitions, two page sizes (4096/8192 bytes), two journal modes (DELETE/PERSIST), five writer profiles and five reader policies. Every reader received an independently copied, hash-verified sibling input. Full ordered identifiers, generation fields and payloads were checked. COMMIT, ROLLBACK, no-flush and inhibited-flush controls distinguish an unfinished transaction from a completed or unchanged image. Derived results preserve the denominator for every row.
The pinned pager implementations initialize immutable access in PAGER_READER; their normal hot-journal path requires PAGER_OPEN. This source interpretation explains the bypass, but does not guarantee that arbitrary interrupted images remain readable. SQLite 3.45.1 pager and 3.54.1 pager support the mechanism; byte-identical compilation of the tested libraries from those tags was not established. Normal read-only queries instead failed with SQLITE_READONLY_ROLLBACK (776), not SQLITE_READONLY_RECOVERY (264).
SQL write restrictions do not preserve evidence. With query_only enabled on a read-write connection, the read still caused rollback recovery and changed the main-file bytes. Keep originals and sidecars intact, recover a disposable writable copy through SQLite's normal path, and check the intended logical contents before preparing an immutable image. SQLite's copying guidance explicitly retains recovery files after an unfinished transaction.
Check the application state after recovery. The OSDI 2014 ALICE study evaluates crash states with workload-specific checkers and explicitly accounts for recovery procedures (sections 3.1 and 4.1). Our narrower process-exit experiment uses known committed rows as that reference. It does not reproduce ALICE's filesystem crash-state exploration or transfer its historical vulnerability findings to current SQLite. A structurally readable image still needs a check against the application's intended transaction history.
The experiment also retained a failed-fixture control: with spilling disabled, sqlite3_db_cacheflush returned success without changing the main bytes. A successful call alone did not establish the intended hot-journal state. The successful interrupted fixtures verified actual changed bytes and the journal header before testing readers.
Download the offline reproduction bundle, system-build observations, second-build observations and primary-source retrieval receipts. These are constructed software observations after deliberate process exit, not physical power-loss tests, a SQLite defect report or failure-rate estimates. WAL, attached databases, interrupted schema changes and arbitrary corrupt pages were not tested by this supplement.
A practical investigation sequence
- Record actual transaction lifetime, not only connection-pool size.
- Check statement finalization and application paths that retain read transactions.
- Record the checkpoint mode and all three result columns before interpreting success.
- Keep database, WAL and recovery state intact; do not delete a WAL to reclaim space.
- Test any scheduling change against the application's read consistency and latency requirements.
These are engineering checks, not a universal tuning recipe. For persistence and recovery scope, continue with WAL, checkpoints and torn pages. A checkpoint still is not an independent backup.
Primary sources
- SQLite: Write-Ahead Logging, sections 2, 6 and 11
- SQLite: sqlite3_wal_checkpoint_v2, checkpoint modes and return counters
- SQLite: PRAGMA wal_checkpoint, three-column result
- SQLite: Isolation, WAL snapshots and transaction lifetime
- SQLite: sqlite3_wal_autocheckpoint, connection-local PASSIVE threshold
- Gaffney, Prammer, Brasfield, Hipp, Kennedy and Patel. SQLite: Past, Present, and Future. PVLDB 15(12), 3535-3547 (2022). DOI 10.14778/3554821.3554842. Sections 2.2.2, 4 and 4.3.
- SQLite: WAL-mode File Format, WAL-index header and read marks
- SQLite: result and error codes, SQLITE_BUSY_SNAPSHOT (517) and SQLITE_BUSY (5)
- SQLite: DEFERRED, IMMEDIATE and EXCLUSIVE transactions
- SQLite: busy handler invocation is not guaranteed
- PostgreSQL 18: Serialization Failure Handling, retrying decision logic and values
- SQLite: Count The Number Of Rows Modified, direct changes and connection scope
- Berenson, Bernstein, Gray, Melton, E. O'Neil and P. O'Neil. A Critique of ANSI SQL Isolation Levels. MSR-TR-95-51 / SIGMOD 1995. Sections 4.1-4.2.
- SQLite: URI query parameters, mode=ro and immutable
- SQLite: PRAGMA query_only and its filesystem boundary
- SQLite 3.45.1 source: pager.c, immutable and act_like_temp_file
- SQLite: PRAGMA schema.data_version, connection-local comparisons
- SQLite: Total Number Of Rows Modified, connection and trigger scope
- SQLite: ATTACH DATABASE, schema-name scope
- SQLite 3.45.1: data_version tests, connection locality, separate processes and WAL
- Ports, Clements, Zhang, Madden and Liskov. Transactional Consistency and Automatic Management in an Application Data Cache. OSDI 2010. Section 2.2.
- SQLite: DETACH, auxiliary database connection lifetime
- SQLite 3.45.1 attach.c: attachFunc opens and detachFunc closes the database B-tree handle
- SQLite: PRAGMA journal_size_limit, retained journal and WAL size
- Meng and Baier. bring2lite: A Structural Concept and Tool for Forensic Data Analysis and Recovery of Deleted SQLite Records. DFRWS USA 2019, sections 4 and 7. DOI 10.1016/j.diin.2019.04.017.
- Hesela: SQLite deletion scope, generated observations and provenance
- SQLite Database File Format: WAL frame validity and reset (sections 4.1 and 4.4)
- SQLite 3.45.1 wal.c: walIteratorNext and walCheckpoint, newest-page selection and nBackfill
- SQLite: DBSTAT page population, exclusions and aggregate mode
- SQLite 3.45.1 dbstat.c: B-tree page traversal through the pager
- Hesela: SQLite space accounting, 32 generated semantic and format observations
- SQLite C API: closing a connection and deferred destruction
- Hesela: twelve native close-lifecycle schedules on each of two SQLite builds
- Hesela: SQLite close-lifecycle sources, raw observations and replay code
- SQLite: RETURNING processing order and ACID changes
- SQLite C API: reset completion errors after RETURNING
- SQLite: Savepoints, nesting and transaction-stack rules
- Hesela: eight SQLite savepoint schedules, complete observations
- Hesela: WAL savepoint release and retained-reader control, complete observations
- Mohan, Haderle, Lindsay, Pirahesh and Schwarz. ARIES: A Transaction Recovery Method Supporting Fine-Granularity Locking and Partial Rollbacks Using Write-Ahead Logging. ACM TODS 17(1), 94-162 (1992), section 5.2, pp. 117-118. DOI 10.1145/128765.128770.
- SQLite C API: historical database snapshot object
- SQLite C API: snapshot capture prerequisites and conditional read-transaction protection
- SQLite C API: reopening a historical snapshot and error-state boundaries
- SQLite C API: destroying a snapshot object
- SQLite C API: snapshot comparison scope and WAL deletion boundary
- SQLite C API: discovering valid snapshots in a retained WAL
- Hesela: frozen SQLite crash-copy observations, two builds and 400 reader observations
- Hesela: eight primary-source receipts for immutable access and hot-journal recovery
- Pillai et al., OSDI 2014: All File Systems Are Not Created Equal, sections 3.1 and 4.1
Checkpoint sources checked 14 October 2026; transaction sources checked 16 October 2026; paper sections 2.2.2 and 4.3 rechecked 17 October 2026. Reader-option documentation and pinned pager code checked 17 October 2026. Observer contracts, upstream tests and WAL architecture rechecked 20 October 2026. Paper figures are not reproduced.