Skip to content

sqlite3 docs: a series of SELECTs is not a consistent read snapshot under default transaction control #162418

Closed as not planned

Description

@daneeller

Documentation gap: a series of SELECTs on one connection is not a consistent read snapshot under the default transaction control

Summary

The docs state which statements implicitly open a transaction in legacy transaction-control mode, but they never state the consequence that matters in practice: plain SELECTs do not start a read transaction, so several reads on one connection (for example, exporting several tables) can observe different committed states of the database. Users commonly assume that queries issued inside one with conn: block form a consistent snapshot — they do not, in the default configuration.

Environment

  • Python 3.13.14, SQLite 3.53.1 (same behaviour on Python 3.14.5).
  • Default sqlite3.connect() settings (isolation_level="", autocommit=LEGACY_TRANSACTION_CONTROL).

Pure-stdlib reproducer

import sqlite3
import tempfile
from pathlib import Path

p = Path(tempfile.mkdtemp()) / "snap.db"
c = sqlite3.connect(p)
c.execute("CREATE TABLE a (v TEXT)")
c.execute("CREATE TABLE b (v TEXT)")
c.execute("INSERT INTO a VALUES ('old')")
c.execute("INSERT INTO b VALUES ('old')")
c.commit()
c.close()

def run(isolation_level, explicit_begin):
    reader = sqlite3.connect(p, isolation_level=isolation_level)
    writer = sqlite3.connect(p, timeout=0.3)
    try:
        if explicit_begin:
            reader.execute("BEGIN")

        va = reader.execute("SELECT v FROM a").fetchone()[0]
        # another connection atomically updates BOTH tables between the two reads
        try:
            writer.execute("UPDATE a SET v='new'")
            writer.execute("UPDATE b SET v='new'")
            writer.commit()
            vb = reader.execute("SELECT v FROM b").fetchone()[0]
            result = f"a={va}, b={vb} -> {'TORN' if va != vb else 'consistent'}"
        except sqlite3.OperationalError as e:
            # reader holds a shared lock => a snapshot was actually established
            result = f"a={va}; writer blocked ({e}) -> snapshot held"
        print(f"isolation_level={isolation_level!r:8s} explicit_begin={explicit_begin!s:5s} -> {result}")
    finally:
        reader.close()
        writer.close()

run("", False)
run("", True)
run(None, False)
run(None, True)

Observed output

default isolation_level is '' (LEGACY_TRANSACTION_CONTROL):
isolation_level=''       explicit_begin=False -> read a=old, b=new  TORN
isolation_level=''       explicit_begin=True  -> writer blocked (database is locked); reader a=old -> snapshot held consistent

autocommit-style (isolation_level=None):
isolation_level=None     explicit_begin=False -> read a=old, b=new  TORN
isolation_level=None     explicit_begin=True  -> writer blocked (database is locked); reader a=old -> snapshot held consistent

Both the default legacy mode and isolation_level=None (autocommit mode) tear. Only an explicit BEGIN establishes a read snapshot (shown here by the writer being blocked until the reader closes).

Relevant documentation

Explanation -> Transaction control -> Transaction control via the isolation_level attribute says:

If the connection attribute isolation_level is not None, new transactions are implicitly opened before execute() and executemany() executes INSERT, UPDATE, DELETE, or REPLACE statements; for other statements, no implicit transaction handling is performed.

Reference -> Cursor objects -> execute(sql, parameters=(), /) repeats the same list and adds:

If autocommit is LEGACY_TRANSACTION_CONTROL, isolation_level is not None, sql is an INSERT, UPDATE, DELETE, or REPLACE statement, and there is no open transaction, a transaction is implicitly opened before executing sql.

Reference -> Module functions -> sqlite3.connect() says:

autocommit currently defaults to LEGACY_TRANSACTION_CONTROL. The default will change to False in a future Python release.

So the mechanism is technically documented. What is missing is the consequence: because SELECT is not in that list, a sequence of reads is not a consistent snapshot, even though conn.in_transaction may be False and the connection looks like it is "in a transaction" from the user's point of view. The fix is also documented, but only in the other transaction-control subsection:

It is suggested to set autocommit to False, which implies PEP 249-compliant transaction control. This means: sqlite3 ensures that a transaction is always open [...]; sqlite3 uses BEGIN DEFERRED statements when opening transactions.

Suggested documentation addition

After the sentence "for other statements, no implicit transaction handling is performed", add something like:

Consequently, in legacy transaction control mode a series of SELECT statements does not form a consistent read snapshot: another connection can commit changes between them. If you need a stable view across multiple queries (for example when exporting several tables), issue an explicit BEGIN or use autocommit=False, which keeps a transaction open at all times.

This is a documentation-only report. The behaviour itself matches SQLite's transaction semantics; the gap is that the docs describe the mechanism without spelling out the data-consistency consequence, and the recommended fix lives in a different subsection that readers looking at execute() will not necessarily see.

Activity

  1. picnixz commented on Nov 22, 2026

    @picnixz
    Member

    I think this is something readers should infer from sqlite semantics themselves though. The suggested paragraph is too much.

  2. daneeller commented on Nov 22, 2026

    @daneeller
    Author

    Agreed — that's a fair call, it's a semantic inference rather than something the docs need to spell out. Thanks for the review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions