The duplicate starts after a successful commit
Imagine a warehouse tool that imports receipts rather than stock snapshots. A CSV row containing DEMO-BOLT-M8,120 means “add 120 bolts.” The importer commits, but its caller loses the response. The caller cannot tell whether the operation failed before the commit or succeeded before the connection disappeared.
Repeating an additive update can turn 120 bolts into 240. Wrapping each attempt in a transaction does not prevent that: both attempts can be individually atomic and still apply the same receipt twice. Transport retries solve delivery uncertainty. Database atomicity determines which related writes become visible together. We need a contract connecting the two.
The accompanying Python 3.12+ standard-library example imports three synthetic SKUs. The first call returns {"rows":3,"units":480,"cached":false}. Repeating the same operation returns the same summary with cached:true; stock remains unchanged. There is no web server or retry scheduler in the sample.
Extract the sample ZIP, enter csv-retry/code, and use a fresh database filename:
python receipt_import.py --db demo.sqlite3 init
python receipt_import.py --db demo.sqlite3 import --key demo-delivery-001 --csv demo_receipts.csv
python receipt_import.py --db demo.sqlite3 import --key demo-delivery-001 --csv demo_receipts.csv
The three commands print these JSON results to standard output; import log events go to standard error:
{"initialized": true}
{"rows": 3, "units": 480, "cached": false}
{"rows": 3, "units": 480, "cached": true}
Identify the operation separately from the file
The caller supplies a stable idempotency key, such as receipt:demo-001, before the first attempt and preserves it for retries. Keys contain 1–128 ASCII letters, digits, dots, underscores, colons, or hyphens, starting with a letter or digit. The importer also calculates SHA-256 over the original CSV bytes. The database stores that digest and the successful summary under the key.
| Next attempt | Outcome | Inventory effect |
|---|---|---|
| Same key, identical bytes | Return stored summary | None |
| Same key, different valid CSV | Raise IdempotencyConflict | None |
| New key, identical bytes | Apply a new receipt | Add quantities again |
This is operation deduplication, not file deduplication. Two legitimate deliveries can contain identical products and quantities. Conversely, changing LF to CRLF, reordering rows, or adding CSV quoting changes the digest even when parsed values match. The client must retain the original upload bytes. A normalized representation would require an explicit, versioned canonicalization contract.
The stored response is a receipt summary, not a fresh inventory query. Later imports may change stock before an earlier request is retried. Returning current totals would make that retry describe a different moment. Here, rows and units remain the original operation’s result; cached describes how this attempt obtained it.
The key is scoped to one database in this demonstration. A service with multiple tenants needs authenticated tenant scope in both operation identity and inventory ownership. A client-supplied key alone does not establish authorization.
Validate the entire bounded input first
parse_payload() accepts at most 1,048,576 bytes and 10,000 data records. It requires UTF-8 without a BOM, the exact header sku,quantity, and at least one receipt. SKUs use 1–64 uppercase ASCII letters, digits, underscores, or hyphens, beginning with a letter or digit. Quantities use decimal digits without leading zeros and range from 1 to 1,000,000. Duplicate SKUs within one import are rejected.
The parser uses csv.reader with strict=True and StringIO(..., newline=""). It checks field count and domain rules explicitly; syntactically valid CSV is not necessarily a valid receipt. Python documents the CSV module’s newline handling and reader behavior.
Parsing completes before the writer transaction begins, including on retries. A malformed changed payload therefore produces a validation error before any key conflict check. The CLI reads only the byte limit plus one to detect oversized files. An HTTP adapter would also need an ingress body limit: checking an already allocated bytes object cannot recover memory spent receiving it.
Whole-file validation keeps malformed later records from partially updating stock and keeps parsing outside the writer lock. It also uses memory proportional to the bounded input. For larger imports, staging and chunking require a different completion contract; committing chunks silently would abandon this sample’s all-or-nothing behavior.
Commit the receipt and its evidence together
Two tables carry the invariant: stock contains quantities; imports contains the key, digest, row count, and total units. A committed operation record means its stock changes committed in the same transaction. Recording the key before the transaction could suppress an import that never happened. Recording it afterward could leave updated stock without retry evidence.
The core sequence in import_receipts() is:
- Acquire the writer transaction with
BEGIN IMMEDIATE. - Look up the key inside that transaction.
- Return its stored summary if the digest matches, or reject a mismatch.
- For a new key, insert the operation record and apply every receipt.
- Commit before returning success; roll back an active transaction on failure.
This excerpt starts after validation, digest calculation, and connection setup. The complete receipt_import.py also rolls back active transactions on exceptions and closes the connection:
connection.execute("BEGIN IMMEDIATE")
previous = connection.execute(
"SELECT payload_sha256, row_count, total_units FROM imports "
"WHERE idempotency_key = ?", (key,),
).fetchone()
if previous is not None:
if previous[0] != digest:
raise IdempotencyConflict("Ключ уже связан с другим CSV.")
result = ImportResult(rows=previous[1], units=previous[2], cached=True)
else:
result = ImportResult(rows=rows, units=sum(r.quantity for r in receipts), cached=False)
connection.execute(
"INSERT INTO imports VALUES (?, ?, ?, ?)",
(key, digest, result.rows, result.units),
)
connection.executemany(
"INSERT INTO stock(sku, quantity) VALUES (?, ?) "
"ON CONFLICT(sku) DO UPDATE SET quantity = stock.quantity + excluded.quantity",
((receipt.sku, receipt.quantity) for receipt in receipts),
)
connection.execute("COMMIT")
The schema also requires stock quantities to remain SQLite integers within the signed 64-bit range. This matters after many imports: a per-row input limit does not cap the lifetime total. If an update violates that constraint, the operation record and earlier stock updates roll back together.
The connection uses autocommit=True so Python does not implicitly manage these transactions. The implementation issues SQL BEGIN, COMMIT, and ROLLBACK explicitly; Connection.commit() would have no effect in this mode. See Python’s transaction-control documentation. Schema initialization runs separately.
Make the lookup safe across connections
A separate “does this key exist?” query followed by a write leaves a race: two connections can both observe absence. Here, BEGIN IMMEDIATE takes the writer slot before the lookup. If the first attempt commits, the next admitted attempt sees the stored result. If it rolls back, the next attempt can apply the receipt. SQLite permits only one writer at a time; its transaction documentation explains when an immediate transaction can encounter contention.
Every attempt opens its own connection. The sample uses a five-second lock timeout by default, configurable above zero through 60 seconds. A contending call can raise sqlite3.OperationalError when it cannot proceed. That is not an empty successful import. A caller may retry a confirmed lock-contention failure with the original key and bytes, using a bounded retry budget and backoff. Other operational errors need their own diagnosis.
The timeout limits lock waiting, not total request duration. Even a cached retry takes the writer slot in this simple implementation. Separate connections observe committed changes under SQLite’s normal isolation settings; see SQLite’s isolation explanation. Enabling WAL can improve reader/writer overlap, but WAL still permits only one writer. It does not turn concurrent imports into parallel writes.
Test the failure boundary, not just the return value
The runnable suite checks database state after success, replay, key conflict, and invalid input. Its rollback test forces a database failure after an earlier stock update, then checks that neither partial stock nor a success record remains. Reusing that key after removing the failure must work.
Concurrency tests use separate connections to a temporary on-disk database. Identical simultaneous attempts must produce one applied result and one cached result, with quantities added once. Distinct keys must both apply to overlapping SKUs. Competing payloads under one key must produce one winner and one conflict, with stock matching the winner. A held writer transaction exercises the timeout path and recovery. These checks target the interleavings that a sequential replay test would miss.
python -m unittest discover -s . -p "test_receipt_import.py" -v
Run that command from the sample’s code directory. Tests of deliberate exceptions and lock contention provide evidence for those paths. They are not a power-loss test, a throughput benchmark, or proof that every deployment has correct storage and durability settings.
Separate a replay from an import failure
The importer emits a JSON log event containing elapsed_ms, rows, cached, and an exception class or null. A successful cached replay means the uncertainty was resolved. A key conflict suggests changed input or key reuse. Repeated lock errors suggest contention worth investigating.
The event intentionally excludes CSV contents, SKUs, keys, digests, database paths, SQL, and exception messages. Row count describes validated input, not committed progress; pair it with the outcome. CLI file-read failures happen before this importer event. A service adapter can add ingress events and a separate request identifier, while avoiding raw keys as metric labels.
Keep the guarantee inside its boundary
The sample never deletes operation records. Deleting one would allow its key to apply the receipt again. A retention policy therefore needs a documented retry horizon and a decision about expired keys; a cleanup task changes observable behavior. Restores must also preserve stock and operation records consistently.
The transaction covers one SQLite database. Sending an email or calling a payment API alongside it would not make those external effects exactly once. An outbox can atomically record an intent here, but its dispatcher still needs a delivery and deduplication design. This example provides a narrower, useful guarantee: while the operation record is retained, successful retries with the same key and bytes recover the stored outcome without adding the inventory again.