Reject stale writes with a compare-and-swap
Two clients can both read version four and compute different replacements. A last-writer-wins UPDATE silently loses one change. Optimistic concurrency makes the version part of the write predicate and checks the affected row count.
The database performs the comparison and update together. Checking the version in Python and then issuing an unconditional UPDATE recreates the race. This exercise uses sequential conflicting writes to demonstrate the same lost-update contract deterministically. A stale writer should re-read and reconsider the operation, not blindly overwrite the newer value.
import sqlite3
with sqlite3.connect(":memory:") as db:
db.execute("create table docs(id int,version int)")
db.execute("insert into docs values(1,2)")
result=db.execute("update docs set version=3 where id=1 and version=1")
print(result.rowcount)Review the design
The version predicate belongs in the database statement. Retrying an operation that encodes business intent may be appropriate; retrying a stale replacement without recomputing its intent is data loss.
Your task
Implement replace_version(db,key,expected,text) for docs(id primary key,version,body). Atomically update body and increment version only if expected matches. Return True for one changed row, otherwise False.
The explanation opens here once every check passes.