PythiloLesson 3 of 12 · progress kept in this browser

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)
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.