Skip to content

gh-162414: Add optional bounded retry timeout to sqlite3.Connection.backup() - #162594

Open
daneeller wants to merge 3 commits into
python:mainfrom
daneeller:gh-162414-backup-timeout
Open

daneeller wants to merge 3 commits into
python:mainfrom
daneeller:gh-162414-backup-timeout

Conversation

@daneeller

Copy link
Copy Markdown

Summary

sqlite3.Connection.backup() retries indefinitely when the source database is
locked (SQLITE_BUSY / SQLITE_LOCKED). Callers have no way to bound how long
a backup may keep retrying: the timeout argument of connect() applies to
locked table operations, not to the backup retry loop. The existing workaround
— checking a deadline inside a progress callback — cannot interrupt a
backup_step() already in progress and does not surface the underlying SQLite
error code.

This adds a keyword-only timeout parameter to backup() that bounds the
window for retrying a consecutive run of lock conflicts. The default, -1.0,
keeps the historical unbounded behaviour.

Reproduction

With another connection holding BEGIN EXCLUSIVE on the source database,
src.backup(dst) never returns while the lock is held; releasing the lock makes
the same call finish. See gh-162414 for a runnable reproducer.

Design

Connection.backup(target, *, pages=-1, progress=None,
                  name="main", sleep=0.250, timeout=-1.0)
  • timeout bounds retries after a lock conflict is first detected; it bounds
    a consecutive run of conflicts, not the total backup duration. Any
    SQLITE_OK closes the window.
  • The first backup_step() is not charged to the budget. The window starts on
    the first SQLITE_BUSY / SQLITE_LOCKED, before the progress callback, so
    callback time counts.
  • Two checks: one at the top of the loop (never start a step with an expired
    window) and one after a conflict (stop when the remaining budget is spent).
  • The sleep between retries is clipped to the remaining budget.
  • Reuses CPython's internal deadline API (_PyDeadline_Init/Get,
    pycore_time.h). Seconds→nanoseconds uses the exported
    _PyTime_FromSecondsObject with ceiling rounding, so the budget is never
    shortened.
  • On exhaustion, OperationalError is raised carrying sqlite_errorcode /
    sqlite_errorname from the last real SQLITE_BUSY / SQLITE_LOCKED
    result. An exception raised by progress takes precedence.
  • This is a soft, best-effort limit, not a hard real-time deadline (see
    Limitations). The connection's busy handler is left unchanged.

Backward compatibility

  • timeout is keyword-only and optional; the signature is otherwise unchanged.
  • The default -1.0 takes the original code path: no deadline, original sleep,
    original error handling. Existing callers are unaffected.
  • Argument Clinic was regenerated with the tree's official tool; the generated
    header was verified byte-for-byte identical.

Tests

  • Backup-specific suite: 27 tests pass. Covers invalid values (-2,
    -0.5, NaN, ±inf), keyword-only enforcement, healthy backups with tiny
    budgets, bounded-retry error code, callback-exception precedence, connection
    reuse after timeout, and a real SQLite-lock test for BUSY → OK → BUSY
    window restart.
  • Full test_sqlite3: 534 run, 7 skipped, 0 failed.

Platform validation (same CPython commit, SQLite 3.53.4)

Configuration GIL backup tests test_sqlite3
Windows x64 Release enabled 27 OK 534 / 7 skip / 0 fail
Windows x64 Free-threaded (--disable-gil) disabled 27 OK 534 / 7 skip / 0 fail
Windows x64 Debug enabled 27 OK 534 / 7 skip / 0 fail

All three configurations were re-run against the final patch and the final test
file, so no result is carried over from an earlier revision of the tests.

Cross-configuration lock-conflict behaviour was consistent
(OperationalError / sqlite_errorcode=5 / SQLITE_BUSY).

Real-world motivation

The author's independent application uses Connection.backup() for scheduled
backups and already carries a progress-callback deadline workaround that
references this issue. A database-layer integration experiment (real
backup_now() loaded from the project, synthetic isolated data only, no real
user data) showed existing business behaviour unchanged across baseline and
patched interpreters (9/9 scenarios: backup, desensitization, integrity,
connection reuse). Under a persistent lock, the native timeout= path returns
OperationalError with sqlite_errorcode=5 / SQLITE_BUSY, while the callback
workaround raises a TimeoutError with no SQLite error code. The native API
therefore gives callers structured diagnostics without requiring them to
capture and wrap the underlying status themselves.

Scope note: this was a database-layer integration test, not a full
application end-to-end test (third-party dependencies do not yet support
CPython 3.16 dev). The intermittent-lock scenario in that experiment did not
actually produce BUSY → OK → BUSY in the raw callback trace, so it is not
presented as evidence for the window-reset behaviour; that behaviour is covered
by the CPython regression test instead.

Limitations / not verified

  • The time before the first lock conflict is detected is not charged to the
    budget; a backup_step() already in progress cannot be preempted.
  • SQLITE_OK resets the window, so repeated lock/release cycles can accumulate
    more than timeout of waiting. This is a soft limit; callers needing a hard
    wall-clock bound must enforce it at a higher layer.
  • Linux (WSL2 Ubuntu) and Linux free-threaded builds were not verifiable in this
    environment (blocked by local security policy); no cross-platform claim is
    made for Linux. Upstream CI is expected to cover it.
  • No ASan/UBSan, reference-count, or multi-process contention stress testing.
  • SQLITE_LOCKED shares the SQLITE_BUSY code path but has no dedicated
    regression test.
  • The API design and semantics are pending maintainer discussion in
    sqlite3.Connection.backup() blocks indefinitely on a locked source DB; connect(timeout) does not apply #162414 and are not presented as accepted.

Contribution attribution

Per the explicit request in gh-162414, this PR is not solely written by an
LLM. The human author identified the problem from their own application,
drove the design direction and trade-offs (including the -1.0 sentinel,
P-1..P-6, and the F-01/F-02/F-04/F-05/O-3 adopt / O-2 defer decisions),
reviewed the resulting diff line-by-line for those refinements, and will
explain and defend the patch in their own words. An AI Agent assisted with
analysing the backup loop and SQLite semantics, drafting C and Argument
Clinic changes, writing tests and documentation (including applying the
human-approved F-* / O-3 refinements), running builds/tests, and producing
audit notes. AI output was reviewed by the author before inclusion; the
refinements are not claimed as hand-typed line-by-line by the human.

…tion.backup()

backup() retries indefinitely when the source database is locked by another
connection; connect(timeout=...) does not bound this wait. Add a keyword-only
timeout parameter that bounds a consecutive run of SQLITE_BUSY/SQLITE_LOCKED
retries, with the default -1.0 preserving the historical unbounded behaviour.

The deadline starts on the first lock conflict (before progress callback) and
is reset on SQLITE_OK; retries are clipped to the remaining budget. On
exhaustion, OperationalError carries the last real SQLite lock error code.
The limit is best-effort, not a hard real-time deadline.
@python-cla-bot

python-cla-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

@read-the-docs-community

read-the-docs-community Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #36150038 | 📁 Comparing 15c0774 against main (37dcbbd)

  🔍 Preview build  

2 files changed
± library/sqlite3.html
± whatsnew/changelog.html

…ite_errorname

Both attributes are documented on sqlite3.Error, not on
sqlite3.OperationalError, so the py:attr references did not resolve and the
docs build failed the warning check.
Wrapping the method signature did not register the object name, so
:meth:`sqlite3.Connection.backup` stopped resolving in
Doc/whatsnew/3.7.rst and in the new NEWS entry, which failed the docs
warning check.  Keep the signature on one line, as it was before, and move
versionadded out of the parameter field body.
@daneeller
daneeller marked this pull request as ready for review November 25, 2026 04:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant