# SQLite close success is not a transaction outcome

## Main finding

On the two recorded SQLite builds, successful `sqlite3_close_v2()` did not mean
that a surviving statement had released its read snapshot or that its pending
write had been rolled back. Finalizing an unfinished `INSERT ... RETURNING`
after that successful close committed all three inserted rows in an implicit
transaction. The corresponding explicit `BEGIN` transaction was rolled back
during deferred connection destruction. This is a controlled reproduction and
source synthesis, not a newly discovered SQLite defect.

The practical boundary is ownership: statement completion, transaction outcome
and connection destruction are separate events. A connection-pool log saying
"closed" is insufficient evidence for a checkpoint diagnosis or write outcome.

## What was actually run

[observe.py](observe.py) invokes the native C API through Python ctypes. It does
not use Python sqlite3 transaction or connection-context-manager behavior.
Twelve deterministic schedules were executed once on each of two builds:
the installed SQLite 3.45.1 distro library (source ID ends in `alt1`) and a
previously built upstream SQLite 3.54.1 shared library. The existing upstream
binary was reused read-only, not rebuilt in this session.

Each schedule creates a fresh disposable WAL database. An owner connection
retains a statement; a distinct observer checks all ordered (id, value) pairs
and either attempts TRUNCATE checkpointing or `BEGIN IMMEDIATE` followed by
rollback when acquisition succeeds. Busy timeout is zero, automatic checkpointing
is disabled, and synchronous is FULL on both connections. After cleanup, the
database is reopened and every row is checked again.

A registered SQL function's application-data destructor supplies a connection
cleanup witness. The function is never replaced. That witness is not a count
of operating-system descriptors or a physical-memory-release measurement.
No API is invoked on an owner connection after successful close. Only the
retained statement is finalized, as permitted by the close contract.

The raw captures record build source IDs, compile options, library hashes,
effective PRAGMAs, return codes, ordered rows, checkpoint tuples, WAL lengths
and witness counts. There is no random sampling, seed, timing result or
statistical confidence interval.

## Results and interpretation

[RESULTS.md](RESULTS.md) is generated from the two validated observations,
not transcribed by hand. [summary.json](summary.json) is the machine-readable
derived table; [observations](observations) holds the original captures.

**Read retention.** With a SELECT stopped at its first row, close_v2 returned 0
while the following TRUNCATE reported (1,4,3): four WAL frames, three backfilled,
busy. Finalizing the retained statement allowed (0,0,0) and a zero-byte WAL.
The ordinary close API instead returned SQLITE_BUSY and remained usable until
a later successful close. This complements Hesela's existing distinction
between a pinned reader and an idle open connection.

**Resource retention is not snapshot retention.** Unstepped, drained-to-DONE and
reset SELECT controls still delayed the destruction witness until finalization,
yet did not obstruct the checkpoint. Thus "an unfinalized statement exists" is
not enough to diagnose WAL starvation. The finalized-before-close control
triggered the witness during close itself.

**RETURNING is not a cancellation boundary.** The implicit-write case returned
one output row, reported close_v2 success, and still excluded another writer.
After statement finalization, the observer and reopened database contained all
six rows, not merely the one returned insertion. In the explicit-BEGIN case,
the observer retained the original three rows after deferred destruction.
The ordinary-close explicit control kept excluding the second writer even after
statement finalization; only its second close rolled back the open transaction.

**Explicit decisions differ from disposal.** Explicit rollback before close kept
the original rows and released writer exclusion. Explicit commit after statement
finalization preserved all three inserted rows. Application logic should decide
commit versus rollback while it still owns a usable connection, finish owned
statements and check cleanup return codes. Finalization is not a generic request
to discard a pending write.

## Why the sources predict these observations

The [close contract](https://sqlite.org/c3ref/close.html) specifies deferred
destruction for close_v2 with outstanding statements and rollback when an open
transaction remains at destruction. It does not promise immediate transaction
rollback at the close_v2 return.

The [transaction documentation](https://sqlite.org/lang_transaction.html#implicit_versus_explicit_transactions)
distinguishes implicit completion from explicit BEGIN ownership. The
[RETURNING documentation](https://sqlite.org/lang_returning.html#processing_order)
separates modification of the connection's pending view from commit and from
delivery of output rows.

Pinned source inspection closes the gap between those contracts. In both
reviewed versions, `sqlite3_finalize` resets the VM, deletes it, and only then
calls deferred connection cleanup. Resetting a running VM reaches its halt
logic; the successful last implicit writer can commit there. The later cleanup
routine rolls back any transaction that is still open. Therefore the phrase
"close rolls back a transaction" cannot be moved earlier in the lifecycle
without changing its meaning. See [claims.json](claims.json) for exact locators.

The [reset contract](https://sqlite.org/c3ref/reset.html) also warns that an
earlier SQLITE_ROW does not rule out a later completion error. This experiment
does not inject such an error, and its successful finalizations must not be
generalized into a guarantee that finalization always commits or always succeeds.

## Limits and a corrected expectation

This is one host, two builds, serialized API calls with overlapping lifetimes.
It is not a concurrent-thread race, crash experiment, power-loss test, benchmark,
driver survey, wrapper-language test or frequency estimate. No attached databases,
BLOB handles, backup objects, virtual tables, triggers, deferred constraints,
I/O faults or rollback-journal mode were exercised. Exact frame counts and
RETURNING output order belong to these fixtures.

The upstream 3.45.1 source is explanatory context, not proof that the distro
binary is byte-identical to that source. Its distinct runtime source ID and
binary hash are retained. The 3.54.1 binary matches the earlier recorded build
receipt; the archive and amalgamation hashes are independently rechecked here.

An initial validator incorrectly expected SQLITE_TXN_NONE immediately after
ROLLBACK with the RETURNING statement still alive. Both unchanged captures
reported READ, while the observer could acquire the writer role. The oracle
was corrected to READ; original observations were not changed. This is not
evidence that every rollback leaves a read transaction. The failed validation
is documented rather than counted as a successful test.

## Reproduce

From this directory, with Python 3 and a native SQLite library supporting RETURNING:

```sh
python3 -B observe.py --output /tmp/hesela-close-new.json
python3 -B -m unittest -v test_observe.py
python3 -B -O -m unittest -v test_observe.py
python3 -B validate.py
python3 -B render_results.py
```

For a separately built library, pass `--library /absolute/path/libsqlite3.so`
to observe.py or set SQLITE_LIBRARY for the unittest command. Raw observation
outputs refuse overwrites. Tests compare the recorded fixtures exactly; other
versions or configurations are additional experiments, not automatically
equivalent populations.

To reproduce upstream 3.54.1, obtain the official amalgamation at the URL in
[build-provenance.json](build-provenance.json), check its recorded SHA3-256,
extract and compile using the recorded command. Do not download or run unknown
binaries. The public-domain upstream source snapshots can be checked offline
against [sources.json](sources.json); the collector is only for a new capture
in an empty source directory.

## Corpus integration

Extend the existing
[WAL analysis](https://hesela.com/analyses/sqlite-wal-checkpoint-starvation/),
[checkpoint-starvation](https://hesela.dev/terms/checkpoint-starvation/) and
[transaction-state](https://hesela.dev/terms/sqlite-transaction-state/) records.
[integration.json](integration.json) contains proposed additions without changing
their identifiers or overwriting prior research. No duplicate article is needed.

Status: research packet and proposed publication text, not independently
reviewed, site-integrated, merged or deployed. Release must preserve the
machine-readable evidence and source links before publishing the human summary.
