Atomic CSV Import into a Persistent Ledger

Original integration teaching, complete source and tests for the existing synthetic service-company application. Save the extension and tests beside the complete published academy_app.py. All fixtures are fictional and local.

The earlier boundary laboratory proves that a complete input can be parsed before a report is published. The integrated application adds a different responsibility: the destination is a persistent, tenant-scoped SQLite ledger with event identities, a version, and an audit trail. A temporary output file and a database transaction solve different problems. Atomic replacement protects one exported pathname; a database transaction keeps several related tables consistent. Neither mechanism automatically validates the input.

The importer therefore has two phases. In phase one it reads at most 1,000,000 bytes, decodes UTF-8 strictly, parses the selected CSV dialect with `strict=True`, and validates the entire file. The header is exactly `event_id,cents`. Every data record has exactly two fields. An ID is an exact, non-normalized string of 1–80 code points. Cents uses an optional minus sign followed by zero or a nonzero ASCII digit and further ASCII digits, with absolute value no greater than 100,000,000. Plus signs, leading zeroes, surrounding whitespace, fractions, non-ASCII digits, extra columns and malformed quoting are rejected. These are application rules, not properties supplied by the CSV module.

Phase one returns all deliveries only after the last record is valid. A bad last row therefore cannot open a write transaction or publish a valid prefix. Keeping the complete validated list is deliberate here: the byte and record limits bound this teaching interface. A much larger production import would need a staged file or private database plus a measured resource policy. Calling an implementation “streaming” would not remove the need to retain enough identity state to detect a later conflicting reuse.

Identity is not an amount

Event IDs define idempotence. Two distinct IDs with equal amounts are two events. Repeating one ID with the same amount is a retry. Repeating it with a different amount is a conflict. Deduplicating on the amount would erase legitimate business events; adding every delivery would double-count retries.

The parser first reconciles repeated IDs inside the file. Consider deliveries `(A,100)`, `(B,100)`, `(A,100)`. There are three deliveries but two unique events. Both A and B contribute, so the new total is 200. The last A is reported as one within-batch retry. If the last record were `(A,101)`, the full file would be rejected before any database transaction began.

Persistent reconciliation happens separately because the same IDs may already be in the tenant’s ledger. Every lookup includes both tenant and event ID. An event called `shared` for tenant A does not collide with `shared` for tenant B. The query returns an absent row, an identical stored amount, or a changed stored amount. Those cases mean new event, persistent replay, and conflict respectively.

Why validation before `BEGIN IMMEDIATE` is not enough

Full-file validation proves that the representation and internal batch are coherent. It cannot prove that the persistent ledger stayed unchanged while the file was being read. The importer opens one `BEGIN IMMEDIATE` transaction after validation, reads the tenant version, and performs every persistent identity lookup within that transaction. SQLite then serializes competing writers under this local application’s locking rules.

If at least one event is new, the caller’s expected version must equal the tenant’s current version. Otherwise the batch is stale and is rejected. If every unique event is already stored with identical content, the operation is a safe replay even when the caller still has the pre-commit version. This matches the existing single-event behavior and makes a lost success response recoverable without inserting the same event twice.

All new event rows, their non-null audit rows, and the version increment occur inside the same context-managed transaction. The version advances by the number of new events, preserving the meaning it would have after the same accepted events were added individually. The context manager commits only after the body returns. Any exception triggers rollback before it is re-raised.

Worked trace

Begin with tenant A at version 0 and an empty ledger. The file contains A 100, B 100, and A 100 again. Phase one validates three deliveries and records two unique identity/payload pairs. The transaction finds neither A nor B in tenant A. Because the batch has new events, expected version 0 matches current version 0. It inserts A and B, writes two audit rows, and increases the version by two. The committed result reports version 2, total 200, two new events, zero persistent replays and one within-batch retry.

Run the same file again with expected version 0. Inside the transaction, both unique IDs match stored content. There are no new events, so the stale expected version does not make an idempotent retry unsafe. No row or audit entry is added. The result remains version 2 and total 200, with two persistent replays.

Now submit B 100 followed by A 101 at expected version 2. B is an identical replay, but A conflicts with stored content. The importer raises a 409 rejection and the transaction rolls back. No prefix is committed. A batch is not “mostly successful” merely because some earlier records were new or identical.

A failure after inserts must still roll back

Pre-validation tests do not establish database atomicity. The test suite injects an invalid null message while writing the audit row for the second new event. By that point event inserts have been attempted inside the transaction. SQLite raises an integrity error because `audit.message` is non-null. The context manager rolls back both event rows, the first audit row, and the version change. The original ledger remains byte-for-byte represented by the same logical rows: version 1, one 100-cent event, and one audit entry.

This is stronger evidence than testing a bad final CSV value alone. The bad CSV never enters a transaction; the injected audit failure occurs during the transaction after persistent work has started. Both failure paths are needed to establish the two-phase contract.

What the tests establish—and what they do not

Eight groups exercise the published extension against the complete published `academy_app.py` source. They cover strict grammar and logical-versus-physical CSV locations, a bad last row, distinct equal-value events, an identical delivery, a full persistent replay, a conflict inside the file, a stored conflict after an earlier new candidate, tenant isolation, a stale version, and a late audit failure. The expected totals, versions, rows, audit counts and rejection statuses are checked directly.

The tests establish behavior for the local SQLite teaching application under the tested Python interpreter. They do not certify multi-process fairness, distributed transactions, untrusted-file denial-of-service resistance beyond the stated limits, crash durability under every filesystem and SQLite configuration, or production authentication. `BEGIN IMMEDIATE` coordinates this database’s writers; it does not create a network consensus protocol. UTF-8 and exact code-point IDs are selected policies, not universal identity rules.

Independent application

Before reading the solution, reason through four changed cases.

  1. Tenant A is at version 4 with stored `(A,100)`. Import `(B,100)`, `(A,100)`, `(B,100)` using expected version 4. State the new version, total contribution, new-event count, persistent-replay count and within-batch-retry count.
  2. Repeat that file using expected version 4 after the successful import. Explain why it is safe and why the version does not advance.
  3. Reset to the original ledger and change the last B to 101. Identify whether the conflict is detected in phase one or in the transaction, and prove that no persistent row changes.
  4. Let tenant B already have `(A,700)`. Explain why tenant A may still import `(A,100)` and identify the SQL predicate that prevents cross-tenant contamination.

Then add a test in which the audit failure is injected on the first new event and compare it with failure on the second. Both must leave the same pre-transaction state. Finally, state which claim would require a real concurrent-writer experiment rather than the serial failure tests supplied here.

Complete reasoning

In case one, B is new, A is a persistent replay, and the second B is a within-batch retry. One new event advances version 4 to 5. B contributes 100 once; A contributes nothing new because it is already stored. The result reports one new event, one persistent replay and one within-batch retry.

In case two, A and B are both persistent replays and the repeated B remains one within-batch retry. There are no new events, so expected version 4 may be stale without making the replay unsafe. The committed state remains version 5.

In case three, the two B deliveries disagree inside the validated file. Phase one rejects the batch before `BEGIN IMMEDIATE`; the ledger cannot have changed through this importer. A changed amount for an ID that exists only in the database is different: that conflict is discovered inside the transaction, which then rolls back.

In case four, every identity query uses `WHERE tenant=? AND event_id=?`. Tenant B’s A does not answer tenant A’s query, so both tenants can retain exact ID A with different amounts. Removing the tenant predicate would be an authorization and correctness defect. The serial rollback tests establish transactional cleanup for injected failures; an assertion about two simultaneous importers, lock waiting, or winner selection needs an actual concurrency test and a stated timing contract.

Complete importer source

Source SHA256: 84e38085378df8d89e77b7c8e7e59deb9fa96679f3cac8095c23f56ac39d04b2. Tested with Python3.12.14 and the exact published application source.

Complete verification source

Test SHA256: 90efe11c13db97cdcddf9841c6f9d5a4a9f5ff5e23d6489bdd046b12e9e9b5c0. Eight groups passed; exact totals, versions, rows, audit counts and rejection statuses are asserted.

No learner account, course progress, production database or external service is used by this laboratory.