Project: a tenant-scoped transactional event importer
Combine tenant isolation, durable deduplication and all-or-nothing batch processing. A batch can contain a retry of an old event, a new event and a conflicting replay. The conflict must abort every new write in this batch while leaving earlier committed batches intact.
Use real SQLite tables with a composite tenant-and-key primary key. The review should explain transaction ownership, the concurrent-writer policy, retention of deduplication records and recovery after an uncertain acknowledgement. The tests exercise local persistence and rollback; they do not turn a single-process fixture into a distributed exactly-once system.
import sqlite3
with sqlite3.connect(":memory:") as db:
db.execute("create table events(tenant text,id text,primary key(tenant,id))")
db.execute("insert into events values(?,?)",("a","same"))
db.execute("insert into events values(?,?)",("b","same"))
print(db.execute("select count(*) from events").fetchone())Review the design
Review the invariant in database state after failure, not only the returned count. A production design must also specify serialization or conflict handling for concurrent writers and a bounded policy for retained event identities.
Your task
Implement import_events(db,tenant,events), events=(key,positive integer amount). Tables events(tenant,id,amount, primary key(tenant,id)) and balances(tenant primary key,value) exist. In one transaction initialize balance if absent, apply each new event once and increment its tenant balance. Identical replay has no effect; changed amount or invalid amount raises ValueError and rolls back the whole batch. Return number of new events. Review concurrency, id retention and recovery policy after passing checks.
The explanation opens here once every check passes.