A settings display still shows base. The connection that loaded the display has just committed own for setting 7. The next check returns the same data_version integer as the previous check, so the cache helper skips its SELECT. A second connection reads own immediately. Both SQLite calls succeeded. The error sits in the line of application code that decided the old tuple could go back to the screen.
That decision depends on three details a cache entry can easily lose. Which opening of the connection supplied the integer? Who can change data through that connection? Did the helper sample the integer before or after reading the rows? An equal pair of numbers has a different explanation in each of the three failing schedules below. Logging only the numbers would leave the maintainer unable to tell which change to make.
The experiment uses a one-row settings table so that someone reviewing the release can check the answer by inspection. One process operates two connections in a fixed sequence. At each scheduled display check, the reviewer can trace the connection, the saved sample, the tuple selected for handoff and a separate read of committed data. The release question is narrow enough to test: when this helper skips a read, what evidence entitles the display to reuse these rows?
State the cache’s freshness contract
The consumer is a settings display. Its input is the complete result of SELECT id, value FROM main.flags ORDER BY id, materialized as a tuple of row tuples. The initial expectation is the literal ((7, "base"),). Row order belongs to the query contract. Immutability matters because a consumer that could edit the returned collection would introduce changes that no database observation could explain. If a fresh SELECT produces the right values but a mapped instance retains older attributes, the separate problem is refreshing a retained SQLAlchemy object.
Check once per scheduled display refresh, immediately before handing rows to that refresh. The display may keep its previous rendering between refreshes. A writer can commit during that interval. In the laboratory, a check begins when A samples its token. Reuse must account for all committed changes through that sample and all completed writes made through A. A reload may also see a commit between the sample and the SELECT. The fixture places its independent read before the next scheduled write, so a difference at a quiet handoff has a definite interpretation.
Choose the checking interval with the display owner. For example, a display scheduled every second can show the previous value until the next successful tick. A suspended event loop or failed refresh can extend the real interval. If the product requires an upper bound on the age of a displayed value, it also needs to notice missed ticks and withdraw or mark the display when the bound expires. This exercise measures scheduled decisions. It makes no wall-clock delivery promise.
There are four permitted outcomes. Reuse hands the existing tuple to the consumer. Reload replaces it after a successful read on the same opening. Rebuild starts a fresh history on an admitted opening, including the very first one. Hold withholds the handoff until the owner can establish a safe boundary or complete a read. Decide which outcome occurred separately from checking the visible value. Two paths that display the same text today can leave very different evidence for tomorrow’s decision.
Build two owned connections to one local file
Run the complete fixture with python3.12 sqlite_cache_review.py on a local filesystem. A later CPython also works with the required sqlite3 interface. The Python listings, taken in order, form one script. To keep the measured ledger, run python3.12 sqlite_cache_review.py > sqlite-cache-evidence.txt and check the process exit status as well as the final line. Use normal execution with assertions enabled. Each branch creates a fresh file under one temporary directory. The cases inside a branch share a file only when they need the preceding history. There are at most two open database connections. A replacement reader opens after the original reader closes.
A owns the display cache. B provides a second database connection for writes and for independently reading the committed settings. The setup opens A with autocommit=True, requests DELETE journaling, and checks the returned mode. It creates both tables and seeds the row before sampling anything used by the cache. B opens the same absolute path with the same autocommit setting. The fixture checks both connections’ journal-mode readbacks and the main filename from PRAGMA database_list. The schema is deliberately small.
CREATE TABLE flags(id INTEGER PRIMARY KEY, value TEXT NOT NULL);
INSERT INTO flags VALUES(7, 'base');
CREATE TABLE unrelated(id INTEGER PRIMARY KEY);Record the Python interpreter and the engine linked to its module. An independently installed SQLite shell can report a different version. Here the executed branches reported CPython 3.12.16, SQLite 3.53.1 and delete on both connections. The emitted branch header includes the temporary path so that a reviewer can associate the two handles with one file during that run. Connection-admission checks are also the subject of SQLite foreign-key connection initialization.
Finish every cursor before advancing the schedule
Every SQL operation uses the same helper, including a PRAGMA returning one integer and an UPDATE returning no rows. It obtains the cursor explicitly, fully fetches a successful result and closes the cursor even when execution or fetching raises. A failed statement has no successfully completed result to hand off. Returning a cursor, generator or iterator from this helper would move the actual read into the caller and make the interleaving in the evidence table ambiguous.
import json
import platform
import sqlite3
import sys
from contextlib import ExitStack
from dataclasses import dataclass
from pathlib import Path
from tempfile import TemporaryDirectory
BASE = ((7, "base"),)
OWN = ((7, "own"),)
EXTERNAL = ((7, "external"),)
AFTER = ((7, "after_close"),)
NEW = ((7, "new"),)
UPDATE = "UPDATE flags SET value = ? WHERE id = 7"
def sql(db, statement, args=()):
cursor = db.cursor()
try:
cursor.execute(statement, args)
return tuple(cursor.fetchall())
finally:
cursor.close()
def token(db):
return sql(db, "PRAGMA main.data_version")[0][0]
def rows(db):
return sql(db, "SELECT id, value FROM main.flags ORDER BY id")SQLite describes the end of an implicit transaction in terms of its last active statement. Closing the cursor gives the schedule an explicit completion point. Python’s in_transaction reports the underlying transaction state. It does not enumerate live cursors or prove that a caller fetched the final row. That is why the fixture uses both a transaction-state check and a structural rule for every SQL call. With Python’s autocommit=True, the rollback control uses SQL BEGIN and ROLLBACK. Calling the connection’s Python rollback() method in this mode would not implement that control. See SQLite transaction and statement lifetime and the Python 3.12 sqlite3 reference, accessed 5 December 2026.
Capture the initial row and its owning baseline
On the freshly seeded file, first ask A for PRAGMA main.data_version. Then read the ordered rows through A. Associate the returned objects in one entry: this reader, this sample and these rows. The measured initial entry contained reader-1, 1 and ((7, "base"),). Only the row tuple is a literal expectation. The script takes whatever integer SQLite supplies and preserves it for a later comparison on that reader.
@dataclass(frozen=True, eq=False)
class Reader:
name: str
db: sqlite3.Connection
@dataclass(frozen=True)
class Entry:
reader: Reader
saved: int
rows: tupleA generation is an application-owned identity for one opening. Here the factory creates a frozen Reader object for every new reader, and the controller tests object identity. The name printed in the log makes that identity legible within a branch. Two branches may both have a reader-1 because they have independent files, controllers and histories. A generation identifier used in a combined service log would also need the enclosing cache or service identity.
Treat the starting row as a fixture input. If A loaded the wrong projection, copied the wrong file or returned half the intended rows, recording its result as the expected value would turn the defect into the oracle. The literal expectation checks the deliberately seeded data. B’s query checks what a separate handle can currently read. A’s stored entry checks what the consumer would receive. Those three quantities answer different questions even when their printed representations happen to match.
SQLite defines the comparison across two samples on the same connection. A change committed by another connection can be detected this way, while a commit by the observer leaves its own value unchanged. SQLite specifically describes refreshing data held in memory as an application of the pragma. The application supplies the ownership and sampling rules needed to use it here. See the SQLite PRAGMA data_version contract, accessed 5 December 2026.
Commit through A and reproduce the stale cache
Keep the initial entry and sample B before touching the setting. Now A executes the parameterized UPDATE with own. The statement finishes with both connections outside an explicit transaction. A samples again and obtains 1, matching its saved 1. The faulty branch performs precisely the conditional operation under review: if equal, take the rows from the saved entry, otherwise issue the SELECT. It takes the first branch and returns ((7, "base"),).
B reads ((7, "own"),), matching the independently declared value. This is a useful place to stop debugging the write. A read on a separate, idle connection has already established that the new value reached the database. The stale result has a narrower cause: the cache helper saw no external change and assumed that every relevant write would have been external. A call to save a setting through the display’s own handle is enough to break that assumption.
Use the same commit for the positive control. The owned write also set the corrected helper’s invalid flag before attempting the UPDATE. That helper sees exactly the same 1 and reloads because it owes the consumer a new read. Its tuple agrees with B. One quiet check later it can legitimately reuse own. Including the quiet check distinguishes a working conditional cache from a repair that permanently issues a SELECT on every display refresh.
Observe the write from the other connection
B’s samples surrounding this one commit were 1 and 2. A’s were 1 and 1. Read each pair from left to right on its own connection. From B’s perspective another connection changed the database. From A’s perspective the write went through its own handle. There is no inconsistency to reconcile between A’s final number and B’s final number. Running the experiment in a single process makes it particularly clear that the boundary is the connection, independent of which process issued the calls.
A review log should preserve which handle took the first sample as carefully as which handle took the second. A label such as “settings database version” omits the property that determines whether comparison is meaningful. Include the role, opening and branch. A useful check when reading application code is to trace the writer backward from the UPDATE to its connection factory. A method on another application object may still execute through the very same SQLite connection as the cache reader.
Detect a committed write from B
Start this check with A’s corrected entry for own. B updates the setting to external and finishes the statement. A now samples 2 against its saved 1. Its controller reads the ordered rows and publishes ((7, "external"),) with the newly sampled token. B independently reads the same tuple. There is no local write to invalidate on A in this step. A’s positive decision to query is therefore evidence that external commit detection actually works.
Check on A | A saved → sampled | Value handed off | Independent value | Review |
Own commit, token-only helper | 1 → 1 | base | own | Reject reuse |
Same commit, invalid flag set | 1 → 1 | own | own | Accept reload |
No intervening write | 1 → 1 | own | own | Accept reuse |
B commits to flags | 1 → 2 | external | external | Accept reload |
In this schedule no SELECT is left running across the writer’s commit. B’s transaction has finished before A’s poll begins. Separate ordinary SQLite connections can observe committed changes at these boundaries. A reader already inside a transaction can have a different visibility boundary, which would change what the independent read establishes. The supplier of the connection must be able to account for that state before handing it to the cache controller. See Isolation in SQLite, accessed 5 December 2026.
Compare rollback with a change to another table
Use B to start a transaction, write rolled_back and read that value on B while its transaction remains active. That inner read proves that the proposed update actually ran. Then execute SQL ROLLBACK and finish its cursor. A’s next token is still 2. A keeps external, and B’s independent read after rollback also returns external. Moving the reference read from after rollback to inside the transaction would silently change what the experiment calls committed.
In the next step B inserts the first ID into unrelated. This time A samples 3 against 2 and reloads the settings. Both the new tuple and the preceding tuple contain external. A decision metric that flags every reload with identical rows as a defect would misclassify this case. The helper had evidence of a committed change to the database; discovering that the settings projection stayed equal was the result of doing the read.
def commits(lab):
a, b, c = lab.reader.db, lab.b, lab.cache
lab.check("initial", "REBUILD", BASE)
old = c.entry
before_b = token(b)
c.write(lab.reader, "own")
after_a, after_b = token(a), token(b)
assert after_a == old.saved and before_b != after_b
faulty = old.rows if after_a == old.saved else rows(a)
assert faulty == BASE and faulty != OWN
lab.record("own-naive", old, after_a, faulty, OWN, "FALSE_REUSE",
detail=dict(b_before=before_b, b_after=after_b))
lab.check("own-fixed", "RELOAD", OWN)
lab.check("quiet", "REUSE", OWN)
before = c.entry.saved
sql(b, UPDATE, ("external",))
lab.check("external", "RELOAD", EXTERNAL)
assert c.sample != before
sql(b, "BEGIN")
sql(b, UPDATE, ("rolled_back",))
assert b.in_transaction and rows(b) == ((7, "rolled_back"),)
sql(b, "ROLLBACK")
lab.check("rollback", "REUSE", EXTERNAL)
before = c.entry.saved
sql(b, "INSERT INTO unrelated VALUES(1)")
lab.check("unrelated", "RELOAD", EXTERNAL)
assert c.sample != beforeRead the token as an invalidation signal
The production predicate has two meaningful outcomes once identity and validity are established: equality permits reuse under the contract, and inequality requests a refresh. Keep the raw integers in the run record so someone can reconstruct the comparison. Counting commits by subtraction would introduce a measurement that this API does not specify. Likewise, a changed token carries no table name, row identifier, previous setting or replacement payload.
That distinction matters for operating the display. A count of reloads can help estimate the cost of the helper’s decisions. A count of settings edits needs its own evidence. In this run there are three different pieces of information about the unrelated insert: the writer’s named SQL statement, A’s changed token and A’s identical projection after reloading. Only the scheduled writer tells the reviewer which table changed. A real cache poll without that schedule cannot recover the writer’s statement from its result.
Replace the connection and discard the old baseline
Begin with a separate file. A reads base under its first generation and then closes. B changes the setting to after_close. A2 opens the same path, checks its admission conditions and samples the pragma. The initial test and this expanded run both obtained 1 on the discarded reader and 1 on the replacement. The broken comparison would keep base indefinitely on an otherwise quiet file. B already reads after_close.
The script deliberately makes the collision diagnostic rather than compulsory. A different run could produce unequal integers on the two openings and accidentally reload. That result would leave the comparison just as unsupported. Review the decision for the replacement by asking whether the first load is unconditional for any integer A2 could return. A test that passes only because two independent numbers happened to differ would approve the wrong implementation.
def reconnect(lab):
lab.check("first-open", "REBUILD", BASE)
old = lab.cache.entry
old.reader.db.close()
sql(lab.b, UPDATE, ("after_close",))
lab.reader = lab.open_reader("reader-2")
db = lab.reader.db
assert sql(db, "PRAGMA main.journal_mode") == (("delete",),)
assert sql(db, "PRAGMA database_list") == ((0, "main", str(lab.path)),)
fresh = token(db)
collision = old.saved == fresh
faulty = old.rows if collision else rows(db)
lab.record("cross-reader", old, fresh, faulty, AFTER,
"FALSE_REUSE" if collision else "ACCIDENTAL_RELOAD")
lab.check("new-generation", "REBUILD", AFTER)The generation belongs to the factory that opens and closes the handle. A connection string, file path or role called “reader” can remain unchanged across replacement. Keeping that label while creating a fresh generation lets operators recognize the same job without confusing its histories. The old entry may remain available for diagnosis until the first successful rebuild. Only a completed check on the admitted generation authorizes a consumer handoff. The resource-lifecycle detail is covered in owning a sqlite3 connection through closure.
Lose an external update by sampling too late
There is a way to miss B’s commit even with the correct connection and no writes through A. Read the rows first. Before sampling the baseline, let B update the row to new and commit. A’s first token sample now reflects an observation made after that commit. The helper saves the sample beside the rows read before it. At its next quiet check the two tokens agree. The retained tuple and the saved token tell stories about different portions of the schedule.
def late(lab):
a = lab.reader.db
retained = rows(a)
assert retained == BASE
sql(lab.b, UPDATE, ("new",))
baseline = Entry(lab.reader, token(a), retained)
now = token(a)
faulty = baseline.rows if now == baseline.saved else rows(a)
assert now == baseline.saved and faulty == BASE
lab.record("late", baseline, now, faulty, NEW, "FALSE_REUSE")The baseline in this case was 2, and the quiet poll returned 2. The independent read returned new. Waiting longer before the quiet poll cannot repair the pair. Another external write might eventually force a reload, making the screen look correct again while leaving the original bug in place. A useful negative control therefore keeps the interval after the late sample quiet. Any subsequent successful discovery of new must come from a deliberate change to the refresh workflow.
Give every scheduled call a place in the evidence
Order | Connection | Statement | Completion | A’s token sample | Retained A value |
1 | A | SELECT settings | Fetched and closed | None | base |
2 | B | UPDATE to new | Committed and closed | None | base |
3 | A | PRAGMA for baseline | Fetched and closed | 2 | base |
4 | A | PRAGMA for next poll | Fetched and closed | 2 | base, reused |
5 | B | Independent SELECT | Fetched and closed | None | base, while B reads new |
“None” means that the event took no sample. In particular, step one did not obtain a token that could later be recovered from the tuple. The Python calls supply the entire ordering. Returning from the SQL helper means all rows have been consumed and the cursor closed. No worker has to win a race, and no duration of sleep forms part of the argument. Preserve this schedule when testing a refactor that moves database work between callbacks. Moving just the baseline call across the write changes the result.
Establish the baseline before loading the rows
Sample the token on A first. Read the replacement rows second. Keep that first sample with those rows even if it is tempting to take a newer measurement at the end. In the early branch the load completes with base, then B commits new. A’s next poll compares 2 with the saved 1 and reloads new. The commit now falls inside the interval covered by the next comparison. It can no longer disappear into a baseline sampled after an old read.
Move B’s commit one step earlier in the between branch. A samples 1, B commits new, and A’s SELECT already sees new. The new entry legitimately carries token 1 beside those rows. At the next check A samples 2 and rereads new. There was one extra SELECT. Retaining the earlier sample gives every intervening external commit a chance to trigger a subsequent check, even when the current SELECT has already incorporated it.
def early(lab):
lab.check("sample-first", "REBUILD", BASE)
sql(lab.b, UPDATE, ("new",))
lab.check("after-read", "RELOAD", NEW)
def between(lab):
def load(db):
sql(lab.b, UPDATE, ("new",))
return rows(db)
lab.check("between", "REBUILD", NEW, load=load)
lab.check("next-poll", "RELOAD", NEW)Think of the sample as the beginning of the interval the following poll must cover. It need not identify the exact state returned by the SELECT. If B commits after the SELECT but before the screen paints, the display may show the earlier value for this tick. The next scheduled poll starts with the earlier sample still saved. If the product instead needs the precise database state at the instant a user acts on it, the interaction needs its own read or transaction boundary. A display timer cannot impose that requirement on another connection’s future writes.
Implement a small controller with explicit ownership
The controller holds one published entry and an invalidation flag. It also records an unresolved writer and the latest attempted sample for diagnostics. Only the connection owner calls check and write. The consumer calls handoff immediately after an approved check in the same sequential schedule. No callback can obtain the previous entry directly while its replacement is being built. Keeping the tuple accessible to the test harness is useful for diagnosis; consumer code uses the guarded method.
class Controller:
def init(self):
self.entry = None
self.invalid = True
self.sample = None
self.error = None
self.pending_writer = None
def write(self, reader, value):
self.invalid = True
if self.pending_writer is not None:
raise RuntimeError("previous write boundary unresolved")
self.pending_writer = reader
if reader.db.in_transaction:
raise RuntimeError("transaction owner must resolve the boundary")
sql(reader.db, UPDATE, (value,))
if not reader.db.in_transaction:
self.pending_writer = None
def acknowledge_boundary(self, reader):
# Only the transaction owner calls this after verifying the outcome.
if self.pending_writer is not reader or reader.db.in_transaction:
raise RuntimeError("write boundary unresolved")
self.pending_writer = None
def check(self, reader, load=rows):
self.sample = None
if reader is None or self.pending_writer is not None:
self.invalid = True
return "HOLD"
previous = self.entry
replace = previous is None or previous.reader is not reader
try:
if reader.db.in_transaction:
self.invalid = True
return "HOLD"
self.sample = token(reader.db)
if not replace and not self.invalid and self.sample == previous.saved:
return "REUSE"
self.invalid = True
candidate = Entry(reader, self.sample, load(reader.db))
except Exception as exc:
# Fail closed at the handoff boundary and retain the cause.
self.invalid = True
self.error = (reader.name, self.sample, type(exc).__name__, str(exc))
return "HOLD"
self.entry = candidate
self.invalid = False
self.error = None
return "REBUILD" if replace else "RELOAD"
def handoff(self):
if self.invalid or self.entry is None:
raise RuntimeError("cache unavailable")
return self.entry.rowsRead the short-circuit conditions in execution order. An unidentified reader, unresolved write or active transaction produces a hold before the token can authorize anything. A first opening or replacement forces construction of an entry even if a previous integer looks familiar. A valid entry for the current opening may take the equality branch. Every path that needs a new tuple first marks the state invalid, runs the complete loader, and installs the assembled entry only after it has all three fields.
The optional loader is how the fixture schedules an intervening B commit and deliberately fails a SELECT. Normal callers use the ordered rows query. In particular, no caller should supply a loader that returns a cursor or mutates flags through A. Either would change the contract of the handoff. The exception handler sits at the boundary where successful materialization becomes permission to publish. It records the cause and returns a distinct hold decision that the caller must handle.
Invalidate writes made by the observing connection
Set invalid before attempting an owned write. The cost of marking a failed or rolled-back write dirty is one possible extra read. Marking it after a successful-looking path leaves room for a commit and a failed acknowledgement to separate the write from invalidation. The fixture’s write method records the responsible reader before executing SQL. A successfully finished autocommit statement clears the pending owner. The invalid flag stays set until the cache has reloaded.
Route every application write on A through this rule, including administrative edits performed by the display owner. The seed statements run before any cache exists. B’s independent writes are intentionally outside A’s invalidation hook. If a caller can acquire A and execute a write behind the controller, the equality branch has lost a premise. The bounded fallback there is to read on each admitted check until that write path is brought under ownership.
An outstanding write outcome can outlive the transaction bit. The recovery branch tries an owned write while the caller already owns an explicit transaction. The helper refuses it, marks its cache invalid and retains the pending writer. Even after the caller executes ROLLBACK, a check still holds. Only the transaction owner, having established what happened, acknowledges the boundary. The next check reloads. That ordering keeps a later request from guessing whether an earlier request successfully completed its work.
Reconcile the complete case ledger
This is the expanded fixture’s executed ledger. Each value cell abbreviates exactly ((7, value),). “None” in a token column means no sample exists for that position. The generation column gives the prior and current opening when they differ. Generation numbers restart on each fresh branch. The transaction column records A followed by B at the independent read, with 0 for false and 1 for true. In the unknown-owner case the harness can identify its file handle while the controller deliberately receives no owner.
Branch / case | Gen. | Prior | Current | Cached | Independent | Tx A/B | Decision |
commits / initial | 1 | None | 1 | base | base | 0/0 | REBUILD |
commits / own-naive | 1 | 1 | 1 | base | own | 0/0 | FALSE_REUSE |
commits / own-fixed | 1 | 1 | 1 | own | own | 0/0 | RELOAD |
commits / quiet | 1 | 1 | 1 | own | own | 0/0 | REUSE |
commits / external | 1 | 1 | 2 | external | external | 0/0 | RELOAD |
commits / rollback | 1 | 2 | 2 | external | external | 0/0 | REUSE |
commits / unrelated | 1 | 2 | 3 | external | external | 0/0 | RELOAD |
reconnect / first-open | 1 | None | 1 | base | base | 0/0 | REBUILD |
reconnect / cross-reader | 1 → 2 | 1 | 1 | base | after_close | 0/0 | FALSE_REUSE |
reconnect / new-generation | 1 → 2 | 1 | 1 | after_close | after_close | 0/0 | REBUILD |
late / late | 1 | 2 | 2 | base | new | 0/0 | FALSE_REUSE |
early / sample-first | 1 | None | 1 | base | base | 0/0 | REBUILD |
early / after-read | 1 | 1 | 2 | new | new | 0/0 | RELOAD |
between / between | 1 | None | 1 | new | new | 0/0 | REBUILD |
between / next-poll | 1 | 1 | 2 | new | new | 0/0 | RELOAD |
recovery / last-good | 1 | None | 1 | base | base | 0/0 | REBUILD |
recovery / read-error | 1 | 1 | 1 | base | own | 0/0 | HOLD |
recovery / retry | 1 | 1 | 1 | own | own | 0/0 | RELOAD |
recovery / in-transaction | 1 | 1 | None | own | own | 1/0 | HOLD |
recovery / unknown-owner | 1 | 1 | None | own | own | 0/0 | HOLD |
recovery / owner-restored | 1 | 1 | 1 | own | own | 0/0 | RELOAD |
recovery / pending-write | 1 | 1 | None | own | own | 0/0 | HOLD |
recovery / boundary-known | 1 | 1 | 1 | own | own | 0/0 | RELOAD |
A second execution on CPython 3.13.5 with SQLite 3.46.1 passed the same case assertions. The table reports the 3.12.16 run. Its integer pairs agree with the earlier test results wherever the schedules overlap. In particular, getting matching numbers across different openings is consistent with the documented restriction on comparisons. The script deliberately has no assertion about which numbers a new opening must return.
The three FALSE_REUSE records are required reproductions of the defective helper. They pass the experiment because each one exposes a wrong tuple at a specific handoff. The corrected paths have a stricter rule: a permitted handoff must equal its literal expectation, and B’s independent read must equal that expectation too. During a hold, the cached column describes retained diagnostic state. The test calls the consumer method and requires it to refuse access.
class Lab:
def init(self, root, branch, stack):
self.branch = branch
self.path = root / (branch + ".sqlite")
self.stack = stack
self.reader = self.open_reader("reader-1")
a = self.reader.db
assert sql(a, "PRAGMA main.journal_mode=DELETE") == (("delete",),)
sql(a, "CREATE TABLE flags(id INTEGER PRIMARY KEY, value TEXT NOT NULL)")
sql(a, "CREATE TABLE unrelated(id INTEGER PRIMARY KEY)")
sql(a, "INSERT INTO flags VALUES(7, 'base')")
self.b = self.open_db()
modes = [sql(db, "PRAGMA main.journal_mode")[0][0] for db in (a, self.b)]
assert modes == ["delete", "delete"]
for db in (a, self.b):
assert sql(db, "PRAGMA database_list") == ((0, "main", str(self.path)),)
print(json.dumps(dict(branch=branch, main=str(self.path), journal=modes,
python=platform.python_version(), sqlite=sqlite3.sqlite_version)))
self.cache = Controller()
self.cases = []
def open_db(self):
db = sqlite3.connect(self.path, autocommit=True)
self.stack.callback(db.close)
return db
def open_reader(self, name):
return Reader(name, self.open_db())
def record(self, case, previous, current, cached, expected_rows, decision,
active=False, detail=None):
independent = rows(self.b)
assert independent == expected_rows
a_tx = self.reader.db.in_transaction
b_tx = self.b.in_transaction
assert (a_tx, b_tx) == (active, False)
self.cases.append(case)
print(json.dumps(dict(case=case, branch=self.branch, generation=self.reader.name,
prior_generation=previous.reader.name if previous else None,
prior=previous.saved if previous else None, current=current,
cached=cached, independent=independent, tx=[a_tx, b_tx],
decision=decision, detail=detail)))
def check(self, case, expected_action, expected_rows, *, load=rows,
unknown=False, active=False):
c = self.cache
previous = c.entry
action = c.check(None if unknown else self.reader, load)
assert action == expected_action
if action == "HOLD":
assert c.invalid and c.entry is previous
try:
c.handoff()
except RuntimeError:
pass
else:
raise AssertionError("held rows reached consumer")
else:
assert c.handoff() == expected_rows
self.record(case, previous, c.sample, c.entry.rows if c.entry else None,
expected_rows, action, active, c.error)Branch and case identifiers are part of the evidence. Two identical token pairs on different files do not describe the same history. Preserve the branch header along with its case lines if you pipe the command output into a release record. Its temporary path identifies what was opened during execution, even after cleanup removes the database. JSON encodes tuples as arrays for transport. The cache and literal oracles in the Python process remain tuples.
Recover from a failed refresh
A failed refresh is easiest to diagnose when the old tuple, the database row and the attempted sample are all visible. In the recovery branch the last successful entry contains base. A commits own. The injected loader requests a missing column, so SQLite raises OperationalError. The attempted token is still 1. The saved entry still describes the last successful load, the independent read returns own, and the consumer is denied a handoff. Assigning the new token or clearing invalidity before the SELECT completed would lose this distinction.
def recovery(lab):
c, a = lab.cache, lab.reader.db
lab.check("last-good", "REBUILD", BASE)
c.write(lab.reader, "own")
def fail(db):
return sql(db, "SELECT missing_column FROM main.flags")
lab.check("read-error", "HOLD", OWN, load=fail)
assert c.entry.rows == BASE and c.error[2] == "OperationalError"
lab.check("retry", "RELOAD", OWN)
sql(a, "BEGIN")
lab.check("in-transaction", "HOLD", OWN, active=True)
sql(a, "ROLLBACK")
lab.check("unknown-owner", "HOLD", OWN, unknown=True)
lab.check("owner-restored", "RELOAD", OWN)
sql(a, "BEGIN")
try:
c.write(lab.reader, "never_applied")
except RuntimeError:
assert c.pending_writer is lab.reader
else:
raise AssertionError("write entered an active transaction")
sql(a, "ROLLBACK")
lab.check("pending-write", "HOLD", OWN)
c.acknowledge_boundary(lab.reader)
lab.check("boundary-known", "RELOAD", OWN)Use the original exception in the review record. This run captured no such column: missing_column, the opening reader-1 and sampled token 1. The ledger retains that evidence when a later successful retry clears the controller’s current error. A missing column has an identifiable cause in this experiment: only the deliberately substituted load requests it. Repeating that same query would accomplish nothing. The retry uses the verified projection on the same idle, owned connection and delivers own.
Restore a known-good path without losing the case record
If a release must proceed while conditional reuse is disabled, restore a small, explicit read path. Establish the reader’s identity and idle transaction boundary, unconditionally select the ordered rows, finish the cursor and hand off only the completed tuple. Keep the broken helper’s generation, attempted sample, exception and last trusted rows in its incident record. Any display of an older tuple during an outage requires a separate decision about labeling and permitted age. This display’s contract withholds it.
Rolling back the helper changes how the application obtains the setting on its next check. Reversing the setting itself would be a data change with a different owner and purpose. Here the accepted database value after recovery is still own. To reinstate conditional reuse, run the entire schedule, including the negative controls. The entry point checks the exact declared case sequence for each branch and closes the opened handles before the temporary directory is removed.
PLAN = [
(commits, "initial own-naive own-fixed quiet external rollback unrelated"),
(reconnect, "first-open cross-reader new-generation"),
(late, "late"),
(early, "sample-first after-read"),
(between, "between next-poll"),
(recovery, "last-good read-error retry in-transaction unknown-owner owner-restored pending-write boundary-known"),
]
def main():
if sys.implementation.name != "cpython" or sys.version_info < (3, 12):
raise SystemExit("Use CPython 3.12 or later")
if not debug:
raise SystemExit("Run with assertions enabled")
with TemporaryDirectory() as location:
for run, required in PLAN:
with ExitStack() as stack:
lab = Lab(Path(location).resolve(), run.__name__, stack)
run(lab)
assert lab.cases == required.split(), (run.__name__, lab.cases)
print("PASS: all declared cases reconciled")
if name == "__main__":
main()Decide whether the helper is ready to ship
Evidence at the scheduled check | Release decision | Accountable owner |
Same opening, valid entry, equal token, completed write boundaries | Reuse the immutable tuple | Refresh owner approves handoff |
Same opening, different token | Read and install complete replacement | Refresh owner |
Owned write attempted, outcome established | Reload even on equality | Writer resolves outcome, refresh owner reads |
Reopened connection with admitted path and mode | Rebuild on first check | Factory supplies new generation |
Unknown owner, active transaction or unresolved write | Hold until ownership and outcome are established | Connection or transaction owner |
Refresh failed or required case missing | Hold conditional release, retain evidence | Release reviewer |
For the executed setup, approve the corrected controller for this scheduled settings display and reject the three token-only or misordered reuse paths. Approval includes conservative reloads on unrelated commits and after a sample made immediately before an intervening write. Those cases cost an extra settings read. They meet the specified boundary and keep the consumer’s data complete. A failed or incomplete run cannot inherit approval from a previous run just because the runtime versions match.
At integration review, ask the factory owner to identify every opening and replacement, the write owner to account for each mutation through A, and the refresh owner to show where the new tuple becomes visible. The consumer owner must demonstrate that a hold actually prevents handoff. A service that catches a hold and silently paints a diagnostic tuple changes the product contract even if its database helper passes every SQL assertion.
Review again if a pool decides which physical reader a request receives, a long-lived read transaction crosses ticks, or the journal mode changes. Each alters an assumption the schedule makes explicit. A WAL reader that tries to promote a stale read into a write raises a separate transaction-recovery question, covered in why a WAL snapshot needs a transaction restart.
Practice database maintenance with an auditable handoff
Give the application owner the exact command, the runtime and journal headers, the case ledger and the four consumer outcomes. Pick one equality case to walk through together. At the own-write check the database already contains own, A’s two samples agree and the invalid flag orders a reload. At the next quiet check the two samples still agree, yet the controller now has a complete, trusted tuple to return. A maintainer who can explain both decisions has enough evidence to review a change to the helper.
Monitor what the owner can act on: how often the display checks, how often it reloads, and whether holds prevent delivery. Preserve the reason for a rebuild so a connection-lifecycle change can be distinguished from a change in the settings workload. Linking those observations back to an actual query and an accountable handoff is part of database monitoring and maintenance practice.
For structured practice with query optimization and database monitoring, explore Refonte Learning’s Database Administrator Essentials.
