Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python SQLite lease renewal: reject stale tokens and exact-expiry ownership

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A lease renewal extends a stored expiry only while the supplied token still owns an unexpired claim.

Download Python source kit

Operation contract

The project stores one job with a token and an integer expiry in an owned SQLite database. Renewal validates exact bounded fields, starts BEGIN IMMEDIATE, and conditionally updates the row only when its token matches and expiry is strictly greater than now. The new expiry must move forward and may extend at most ten clock units from the supplied time. A stale token, a nonextending expiry and a request exactly at expiry return false without replacing state. Two real connections use the same file to observe the accepted update.

Failure and ownership boundary

The token is caller-supplied teaching data, not a generated secret or a trusted identity. A deployment must choose a clock domain, prevent clock regression, generate unique claims and authenticate workers. Renewal also cannot revoke an already running external side effect. Python SQLite outbox leases: stale workers must not acknowledge a newer claim, Python SQLite job project: reject conflicting replays by request identity and Python SQLite writer contention: reject a busy transaction before changing state complete the workflow around this one transition.

Working program

python
import sqlite3
import tempfile
from pathlib import Path

def renew(connection, identifier, token, now, new_expiry):
    if type(identifier) is not int or not 1 <= identifier <= 1000 or type(token) is not str or not 1 <= len(token) <= 32:
        raise ValueError("claim fields")
    if any(type(value) is not int or not 0 <= value <= 1000000 for value in (now, new_expiry)) or not now < new_expiry <= now + 10:
        raise ValueError("clock/extension bounds")
    connection.execute("BEGIN IMMEDIATE")
    try:
        changed = connection.execute("UPDATE job SET expiry=? WHERE id=? AND token=? AND expiry>? AND expiry<?",
            (new_expiry, identifier, token, now, new_expiry)).rowcount == 1
        connection.execute("COMMIT")
        return changed
    except BaseException:
        connection.execute("ROLLBACK")
        raise

with tempfile.TemporaryDirectory() as directory:
    database = Path(directory) / "claims.db"
    first = sqlite3.connect(database, isolation_level=None)
    second = sqlite3.connect(database, isolation_level=None)
    try:
        first.execute("CREATE TABLE job(id INTEGER PRIMARY KEY, token TEXT NOT NULL, expiry INTEGER NOT NULL)")
        first.execute("INSERT INTO job VALUES (41, 'claim-a', 10)")
        print("renewed:", renew(first, 41, "claim-a", 5, 15))
        print("stale token:", renew(second, 41, "claim-old", 6, 16))
        print("no extension:", renew(second, 41, "claim-a", 6, 14))
        print("at expiry:", renew(second, 41, "claim-a", 15, 20))
        print("stored expiry:", second.execute("SELECT expiry FROM job").fetchone()[0])
    finally:
        second.close()
        first.close()

Output

Output
renewed: True
stale token: False
no extension: False
at expiry: False
stored expiry: 15

Costs and limits

The primary-key predicate targets one row, with database page and transaction costs rather than an in-memory constant-time guarantee. BEGIN IMMEDIATE may block or fail under writer contention; this project does not implement bounded retry. Two sequential connections establish visibility and token checks, not a multi-worker load result or power-loss guarantee.

Common Mistakes

  • An expiry equal to now is already expired under this contract.
  • Never extend a lease using only its job ID without checking the current token.

Connected lessons

Python SQLite outbox leases: stale workers must not acknowledge a newer claim, Python SQLite job project: reject conflicting replays by request identity, Python SQLite writer contention: reject a busy transaction before changing state.

python
lease-renewal-project
Storage details