Repository navigation
Description
Environment
- CPython 3.13.14 (Windows 11),
sqlite3module. The behavior also appears in earlier CPython versions; I only runtime-tested 3.13.
What happens
sqlite3.Connection.backup() can block indefinitely when the source database is locked by another connection. The timeout argument of sqlite3.connect() does not bound this wait — it applies to locked table operations, not to the backup retry loop.
In the repro below, a parent process holds BEGIN EXCLUSIVE on the source database. The child calls src.backup(dst) and never returns while the lock is held (killed after 4 seconds). Once the lock is released, the identical child code finishes in 0.06 s.
Repro
# parent.py: hold an exclusive write lock for 4 seconds, then release
import sqlite3, subprocess, sys, time
CHILD = """
import sqlite3, sys
src = sqlite3.connect(sys.argv[1], timeout=1)
dst = sqlite3.connect(sys.argv[2], timeout=1)
print('child: calling backup()', flush=True)
src.backup(dst)
print('child: backup() returned', flush=True)
"""
conn = sqlite3.connect("locked.db")
conn.execute("CREATE TABLE t(x)")
conn.commit()
conn.execute("BEGIN EXCLUSIVE")
conn.execute("INSERT INTO t VALUES (1)")
p = subprocess.Popen([sys.executable, "-c", CHILD, "locked.db", "backup.db"],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
try:
p.communicate(timeout=4)
except subprocess.TimeoutExpired:
p.kill()
p.communicate()
print("child was still blocked after 4 s")
conn.rollback()
conn.close()Observed:
child: calling backup()
child was still blocked after 4 s
child: calling backup() # control run, lock released
child: backup() returned
Documentation gap
The current backup() docs say:
Works even if the database is being accessed by other clients or concurrently by the same connection.
and define sleep as:
The number of seconds to sleep between successive attempts to back up remaining pages.
They do not say that backup() retries on SQLITE_BUSY/SQLITE_LOCKED until it succeeds or a real error occurs, nor that connect(timeout=...) has no effect on this wait. A reader can reasonably assume the connection timeout applies, which is not the case.
Suggested documentation change
Add a note to the sqlite3.Connection.backup() section, e.g.:
backup()retries internally when the source database is locked; thetimeoutpassed toconnect()does not limit this wait. To bound the total time, pass aprogresscallback that checks your own deadline and raises, or callbackup()with a bounded number ofpagesper step.
If a code change is considered instead, an optional deadline/timeout parameter on backup() would be useful, but I understand that is an API change and may need broader discussion.
Impact
A background backup thread that relies on connect(timeout=...) can hang forever if another process holds a write lock, with no exception and no timeout to trigger cleanup or retry logic.
No project-specific or private data is included in this report; the repro uses only the standard library.
Linked PRs
Metadata
Metadata
Assignees
Labels
Projects
- StatusShow more project fieldsNo status
Activity
daneeller commentedon Nov 22, 2026
A verified workaround that could be worth adding to the
backup()docs, including one non-obvious detail.A bounded wait can be implemented with the
progressparameter ofbackup()itself, using a monotonic clock:Verified on 3.13 with another connection holding
BEGIN EXCLUSIVE: the above aborted in ~1.8 s with a 1 s deadline and completed in 0.01 s once the lock was released, instead of blocking indefinitely.The non-obvious part:
Connection.set_progress_handler()does not fire duringbackup()'s busy-wait. I first tried that API and it hung for over 2 minutes — the backup step loop retries on SQLITE_BUSY without executing VM instructions, so the connection-level progress handler never gets a chance to run. Only theprogress=argument tobackup()is invoked on those retries.Suggested addition to the
Connection.backup()docs:picnixz commentedon Nov 22, 2026
I think this is the expected behavior and that the docs are sufficiently clear. At least, this is wgat I would expect if something is locked.
daneeller commentedon Nov 22, 2026
Thanks for the clarification — that makes sense, I'll keep the progress-callback workaround on my side rather than pushing for a doc change. Appreciated you taking the time.
picnixz commentedon Nov 22, 2026
That being said, we may consider making the timeout handled by the backup retry loop. Or add another timeout parameter to backup().
daneeller commentedon Nov 23, 2026
That's an interesting direction — a
timeoutparameter onbackup()would be much cleaner than the progress-callback workaround. If you'd like, I can prepare a PR with the retry-loop change, tests for a locked source DB, and a docs update. Happy to follow your call on whether this is worth doing.picnixz commentedon Nov 23, 2026
Well I would like such PR but not a PR solely written by an LLM. You can do it yourself to try learning about sqlite internals but I'd prefer that an agent is not the only one doing the work.
pythongh-162414: Fix cross-reference targets for sqlite_errorcode/sql…
pythongh-162414: Restore the one-line backup() signature
daneeller commentedon Nov 25, 2026
Thanks for the guidance — I appreciate the point about not relying entirely on an LLM, and I agree with it. I've opened PR #162594 with a patch for this.
I've been working on this over the past couple of days. I started by reading through the existing backup code and sketching a few possible designs; then I used AI assistance to help implement the patch and run the test matrix, while I reviewed each change and decided what the expected behaviour should be.
My initial idea was to coordinate SQLite's inner lock wait and CPython's outer retry loop under a single time budget. I considered a proportional split first, then a scheme that reallocates the remaining budget according to actual execution state. After weighing what that would require — touching the busy handler, connection configuration, behaviour under concurrency, and backward compatibility — I concluded it added too much complexity and risk for this issue, so I dropped it.
What the patch actually does is a smaller, deadline-based change inside the existing retry loop:
SQLITE_BUSYorSQLITE_LOCKEDis seen, before theprogresscallback runs, so callback time counts against the budget.SQLITE_OKcloses the window — deliberately simpler than diffing remaining pages, and it does not depend on observing page progress while the source database is being modified.Concretely, this ships as a new keyword-only
timeout=-1.0parameter onConnection.backup(): the default keeps today's unlimited-retry behaviour, and any non-negative value bounds the consecutive-conflict retry window in seconds.It is intentionally a soft, best-effort limit, not a hard deadline: a
backup_step()that is already inside SQLite's lock wait cannot be preempted, and becauseSQLITE_OKresets the window, repeated lock/release cycles can accumulate more thantimeoutof waiting in total. Theprogresscallback still runs first on every step, and its exception still wins.Current state: the 27 backup tests and the full
test_sqlite3suite (534 run, 7 skipped, 0 failed) pass on Windows Release, Debug, and free-threaded builds, all re-run against the final revision of the patch rather than carried over from an earlier one. I have not validated on Linux locally, but the upstream CI matrix has since finished fully green, including the sanitizer and free-threading builds.I also ran it against the database layer of an application I maintain, which currently carries a
progress-callback workaround for this same problem. With a persistently locked target, the patched CPython raisesOperationalErrorwithsqlite_errorcode=5(SQLITE_BUSY), whereas the workaround surfaces its ownTimeoutErrorwithout the underlying code. To be clear, that was a database-layer integration check, not a full end-to-end application test.AI was a significant part of the implementation and validation, but the design decisions, the trade-offs, and the choice of what to test were mine. Happy to discuss or revise the API and the timeout semantics based on your feedback.