# SQLite backup completion does not release a caller-owned snapshot

Research type: controlled reproduction and engineering synthesis. Recorded 21 October 2026.
This extends Hesela's backup-completion and WAL-reader work. It is a controlled
reproduction and synthesis of documented behavior, not a newly discovered SQLite bug.

## Main finding

Finishing or cancelling a backup object did not end the source read transaction
that our application had opened first. Writes continued, PASSIVE checkpoints
returned success, and WAL history kept growing after the backup object was gone.
Ending that read transaction, without closing its connection, allowed TRUNCATE.

Setting `journal_size_limit=0` did not prevent this growth. Nor did it make the
idle control's active WAL a zero-byte file. The setting is not a live-WAL quota.

A second boundary matters: `BEGIN` alone left autocommit disabled but did not pin
a source read transaction across backup steps. `BEGIN` followed by a real read
did. A connection-level "in transaction" boolean is not enough to diagnose the
specific read lifetime retaining history.

## What we measured

Two builds, fourteen schedules each, three repetitions: 84 retained native runs.
The distro library is SQLite 3.45.1 with a distribution source ID ending in
`alt1`. The second is upstream 3.54.1, built from the official amalgamation.
Both its archive and C-file SHA3-256 matched SQLite's published values before
the retained measurements. Their compile options differ. Agreement is replication on two builds,
not an isolated causal estimate of a version change.

All fourteen schedule outcomes agreed across repeats and builds. We compared
source transaction states, backup counters, checkpoint results, logical-row
hashes and WAL lengths. We deliberately did not equate complete destination-file
bytes across SQLite versions; those hashes remain in the raw receipts.

The table collapses the two journal-limit values (-1 and 0), which gave the same
listed outcomes. "Final" means after three more commits following backup cleanup,
not immediately when the backup completed.

| Source view | Backup action | Destination generation | Source read after cleanup | Final WAL frames / checkpointed | Final WAL bytes |
| --- | --- | ---: | --- | ---: | ---: |
| No explicit transaction | Complete | 16 | None | 36 / 36 | 148,352 |
| No explicit transaction | Cancel | 0 | None | 36 / 36 | 148,352 |
| BEGIN only | Complete | 16 | None | 36 / 36 | 148,352 |
| BEGIN only | Cancel | 0 | None | 36 / 36 | 148,352 |
| BEGIN + SELECT | Complete | 10 | Retained | 360 / 36 | 1,483,232 |
| BEGIN + SELECT | Cancel | 0 | Retained | 360 / 36 | 1,483,232 |
| BEGIN + SELECT | No backup object | 0, untouched | Retained | 360 / 36 | 1,483,232 |

These rows come from [summary.json](summary.json), generated by
[summarize.py](summarize.py), not manually entered result data.
Each collapsed table row covers twelve retained observations: two limits, three
repeats and two builds.

### Three independent signals

1. Completed copies returned SQLITE_DONE (101), then finish returned SQLITE_OK (0).
   They passed a reopened, read-only full-row oracle and integrity_check.
2. Cancelled copies never returned DONE, but finish still returned 0. Reopening
   verified every row of the pre-existing generation-0 destination, not a partial
   generation-10/16 mixture. This confirms the cancellation contract, not success.
3. Both cleanup paths left the caller-owned read intact. The reader-only control
   produced the same WAL trace without creating any backup object at all. This
   isolates the retained transaction rather than blaming an orphaned backup.

Immediately after backup cleanup, pinned cases had 252 WAL frames, 36 checkpointed,
and 1,038,272 WAL bytes. TRUNCATE returned SQLITE_BUSY (5) with busy_timeout=0.
Three subsequent commits grew that to 360 frames and 1,483,232 bytes, while the
checkpointed count stayed at 36. Each PASSIVE call returned 0. A full read still
returned generation 10 just before releasing the source transaction.

After the owned read transaction ended, TRUNCATE returned 0 with both counts and
WAL length equal to zero. The same still-open source connection then returned all
generation-19 rows. In unpinned controls, checkpointed frames equalled current log
frames, even though a 148,352-byte WAL existed. File length alone was not backlog.

## Exact schedule and oracle

Each case creates private temporary files. There is no existing-database input.
The source has 32 rows with deterministic 4,096-byte ASCII payloads, 4,096-byte
pages, and WAL mode. Both measured builds used 38 source pages. The destination
starts in DELETE mode with complete generation-0 sentinel rows.

First, initialize source generation 9 and truncate its WAL. Commit generation 10,
leaving a WAL-resident view. Open a separate source connection. Depending on the
case, do nothing, execute BEGIN, or execute BEGIN and SELECT all rows. Statements
are finalized; only the explicit transaction can retain the read.

For backup cases, copy two pages. Then perform six ordered rounds: the independent
writer commits generation 11 through 16, copying two more pages after each commit.
Request PASSIVE after each round. Unpinned/deferred copies repeatedly reported
36 pages remaining; pinned copies advanced from 36 to 24. No BUSY was needed for
those backup restarts. Complete cases drain with no further writes until DONE.
Cancel cases finish immediately without draining. The reader-only control omits
all backup calls but keeps the same writer/checkpoint schedule.

After cleanup, request TRUNCATE, then commit generations 17 through 19, each
followed by PASSIVE. Check the pinned view, release only this fixture's owned
transaction, and request TRUNCATE again. Compare every source row through both
connections. Close and reopen the destination read-only and compare every ID,
generation and complete payload against its expected generation. Also run
integrity_check. No destination API is called while its backup object is active.

Effective settings: synchronous=FULL, wal_autocheckpoint=0, busy_timeout=0, mmap_size=0;
journal_size_limit is set and read back on both source connections. Automatic
checkpoints are deliberately disabled; this is not a test of the default policy.

## Mechanism: source contracts, not just matching outputs

The [backup API](https://sqlite.org/c3ref/backup_finish.html) distinguishes DONE
from cleanup. Its return from finish does not certify completion.
The [backup guide](https://sqlite.org/backup.html) describes incremental copying;
the more detailed API and our writer schedule determine the copied generation.

The reviewed 3.54.1 amalgamation's backup_step opens a source read only when no
source transaction is active and records whether it must close that read before
returning. backup_finish detaches the backup and rolls back an outstanding
destination transaction. It does not issue ROLLBACK on the caller's source
transaction. See source locators in [sources.json](sources.json). This explains
both the pinned case and the BEGIN-only control.

The [isolation contract](https://sqlite.org/isolation.html) explains why our pinned
reader and completed copy retained generation 10 while other commits advanced.
The [WAL design](https://sqlite.org/wal.html#concurrency) explains why the
checkpoint cannot retire page history needed by that read. The
[checkpoint API](https://sqlite.org/c3ref/wal_checkpoint_v2.html) permits PASSIVE
to leave work unfinished; its checkpointed count includes previous progress in
the current WAL cycle, not only work done by that invocation.

The [journal-size pragma](https://sqlite.org/pragma.html#pragma_journal_size_limit)
concerns retained file size around reset/reuse. In the reviewed wal.c commit path,
truncation is bounded below by the end of required frames. Our measurements
demonstrate the practical consequence under a retained reader. They do not show
that the pragma is ineffective for reclaiming unused file tail space.

Finally, [get_autocommit](https://sqlite.org/c3ref/get_autocommit.html) and
[txn_state](https://sqlite.org/c3ref/txn_state.html) report different state.
In BEGIN-only cases, these were 0 and SQLITE_TXN_NONE (0) between steps.
After BEGIN plus a read they were 0 and SQLITE_TXN_READ (1).
Use the actual schema's transaction state together with ownership and lifetime.

## Engineering synthesis

A backup's completion, its selected generation, release of source history and
reclamation of WAL file space are separate acceptance conditions.
Applications that intentionally pin a source view should define who ends that
view on success, cancellation and errors. Clean up only a transaction owned by
that operation; do not blindly roll back unrelated work on a pooled connection.

Monitor the backup result and progress, required data generation, source read
lifetime, checkpoint mode and counters, and actual file length together. Bound
snapshot duration according to the application's freshness and storage budget.
This experiment does not provide a universal duration, byte cap, retry budget or
throughput recommendation. Do not delete a live WAL to recover space.

## Limits and evidence strength

- Synthetic fixed-size workload on one Linux host, not sampled operational failures.
- Calls are single-threaded and sequential, with overlapping lifetimes but no
  simultaneously executing SQLite calls. No race or multi-process stress test.
- Three repetitions establish repeatability here, not probabilities or confidence
  intervals. Exact frame/page counts are fixture-specific.
- WAL bytes are stat file length, not allocated blocks, write amplification,
  physical I/O, SSD wear, free capacity or power-loss durability.
- Generations label payload versions, not timestamps. We measured no elapsed-time
  freshness, backup duration, RPO, RTO or production workload.
- A controlled newer build reproduces this behavior but is not a comprehensive
  security/update recommendation. The old distro build is not recommended for use.
- Ordinary structural validity is not application-level restore verification.
  The row oracle adds exact fixture semantics, not every real recovery dependency.
- Pre-review pilots and native unit-test reruns are not pooled into the 84-run receipt.
  No statistically new general law or new SQLite defect is claimed.

## Reproduce and review

Linux, Python 3.9+, stat and an SQLite library exposing sqlite3_txn_state are
required. The published run used Python 3.12.3 and kernel 6.8.0-146-generic.
Use an empty output filename and disposable workspace. The script refuses existing
outputs and cleans up only its own temporary databases. Failed runs can leave an
empty output reservation; an empty file is not a receipt.

From this directory:

```sh
python3 -B observe.py --work-root /tmp --output system-replay.json
python3 -B observe.py --work-root /tmp --output upstream-replay.json --library /absolute/path/libsqlite3-3.54.1.so
python3 -B summarize.py --output summary-replay.json
python3 -B -m unittest -v test_observe.py
python3 -B -O -m unittest -v test_observe.py
env SQLITE_LIBRARY=/absolute/path/libsqlite3-3.54.1.so python3 -B -m unittest -v test_observe.py
env SQLITE_LIBRARY=/absolute/path/libsqlite3-3.54.1.so python3 -B -O -m unittest -v test_observe.py
```

The summary command validates and summarizes the two retained observations beside
the script; it does not silently replace them with replay files.
Tests validate retained receipts and execute fourteen additional schedules on the
selected library. To validate a replay independently:

```sh
python3 -B -c 'import json, observe; observe.validate_receipt(json.load(open("system-replay.json")))'
```

For the upstream build, fetch the exact archive URL in sources.json into a new
build directory. Before extraction, verify SHA3-256 with
`openssl dgst -sha3-256 sqlite-amalgamation-3540100.zip`. After extraction,
verify sqlite3.c as well. Reject a mismatch. The recorded compile command was:

```sh
gcc -O2 -fPIC -shared -DSQLITE_THREADSAFE=1 -o libsqlite3-3.54.1.so sqlite-amalgamation-3540100/sqlite3.c -lpthread -ldl -lm
```

Compiler: GCC (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0. No system installation or
global library replacement was performed. Source IDs, binary hashes, compile
options and driver hash are in each receipt. Compiler flags and reviewed source
hashes are in sources.json. Rebuilt binary identity can depend on toolchain details;
check the upstream source ID and behavioral assertions rather than assuming a
different compiler must emit the same ELF hash.

## Publication map

The companion [backup analysis](https://hesela.com/analyses/backup-verification-is-not-a-restore-test/#sqlite-backup-retention)
connects this evidence to completion, source freshness and application recovery.
The [WAL-reader analysis](https://hesela.com/analyses/sqlite-wal-checkpoint-starvation/#backup-owned-read)
explains checkpoint counters and reader lifetime without duplicating the result table.
The stable corpus records are [SQLite Online Backup API](https://hesela.dev/terms/sqlite-online-backup/)
and [checkpoint starvation](https://hesela.dev/terms/checkpoint-starvation/).

These publication changes are prepared for review, not a claim of deployment.
The retained observations predate the manuscript integration; test reruns do not
increase the 84 observations in the original receipt.

Research scripts and observations are Hesela-authored. SQLite code/documentation
is upstream public-domain material; see the recorded official rights source.
The upstream archive and compiled binaries are retained outside the repo and are
not bundled. Public reuse of Hesela-authored material should follow the project's
existing cite-and-reuse policy, not a new license invented by this experiment.
