A storage boundary converts validated application records into stored representations and reconstructs them when read.
Connect typed CSV records, JSON fields and database storage, then verify the complete round trip.
The export says a request took zero milliseconds. After storage, the report says the duration is unknown. Nothing crashed, but a fact was lost. Follow a row through CSV strings, typed Python values, SQLite and JSON fields, then check the read-back against an independently specified record.

Type a raw CSV row before it reaches the vault
The CSV has columns id, source, level, ms, tags, where tags is a
|-separated list like web|disk. Typing a row is where two decisions get
made that matter later:
An empty ms becomes None, not 0: "we don't know" and "it took zero
milliseconds" are different facts, and SQLite stores None as NULL and
gives it back as None. Tags become a sorted, de-duplicated list, so the
same tags always produce the same value — without that, the final comparison
could fail on ordering alone:
row = {"id": "7", "source": "web-01", "level": "WARN", "ms": "", "tags": ""}
tags = sorted({t for t in row["tags"].split("|") if t})
print(tags, "".split("|"))Preparing this topic’s interactive investigation…
Store a record whose tags are a list
SQLite binds only None, int, float, str and bytes, so the list of
tags has to cross as JSON text — json.dumps(["disk", "web"]) is the string
'["disk", "web"]'. Everything else goes in as itself, inside one
transaction with :name placeholders. Here's what happens if you forget the
JSON step:
Run it and read which type the driver refused to bind. Then pack the list as JSON before inserting.
Reading back means the reverse: select every row in id order, turn each into
a dict, and json.loads the tags column back into a list. Watch a single
row's tags column change type on the way out:
Prove the round trip lost nothing — and catch it when it does
Python's == on two lists of dicts compares every field of every record,
including the difference between None and 0, "7" and 7, and
["web"] and '["web"]'. That comparison is only worth something if it
would fail when something goes wrong — and each of these bugs is easy to
write and invisible at a glance: forgetting json.loads on the way out,
storing ms as text, turning an empty ms into 0, leaving tags unsorted,
a half-stored batch after a rollback.
back = [{"id": 1, "ms": None, "tags": ["web"]}]
sent = [{"id": 1, "ms": 0, "tags": ["web"]}]
print(back == sent)When a batch breaks a constraint — a duplicate id — the transaction rolls
back and nothing is stored. The capstone reports that honestly: stored is
0 and unchanged is False, because the vault doesn't hold what it was
given.
Check the representation at every crossing
Follow one CSV row all the way through: id="7", ms="0", tags="web|disk|web". Conversion should produce integer id 7, integer duration 0, and ['disk', 'web']. SQLite receives the first two as integers and the tags as JSON text. Reading back must decode that text before comparing records.
Now change only ms to an empty cell. The typed record should contain None, the SQL value should be NULL, and read-back should return None. Replacing either case with value or None after converting to an integer loses a real zero. This is why the missing-data decision belongs at the CSV boundary, where the original cell is still visible.
Equality is useful evidence, but not a universal type check: Python considers 1 == True and 1 == 1.0 true. When exact types matter, assert the schema as well as equality. And encode/decode functions with the same mistake can agree with each other, so add at least one independently specified expected record.
Design the batch policy: the main round-trip task rejects a constraint-breaking batch atomically. The later vault_report exercise accepts rows with valid numeric cells and reports rejected row numbers. These are different contracts. For accepted rows [id=1, id=2, id=1], the primary-key constraint still fails; numeric validation alone cannot make duplicates safe. State which layer owns that decision before catching another exception.
For independent transfer, prepare a four-row export containing a valid zero, an empty duration, repeated tags and a duplicate id. Predict the result separately under the all-or-nothing and row-rejection policies. Then check database state after failure. A summary of attempted inserts is not a count of committed rows.
References: CSV row representation, JSON conversions, and SQLite transactions.
Measure what each format actually costs
Which format is smallest, fastest? Measure it — here's a harness that builds
synthetic records and writes and reads them through all four, timing each
with time.perf_counter:
CSV is compact because the header is written once, but gives you back
strings. JSON pays for repeating every key on every record, and has broad cross-language support. CSV and SQLite also have readers
in many languages; compare their data models and access patterns.
Pickle restores supported Python objects; its speed depends on the data, but only
Python can read it, and never from a stranger. This small benchmark does not establish a general speed or size ranking.
SQLite supports a WHERE clause, updates to individual records and
transactions. The in-memory benchmark does not measure persistent-disk
durability. Choose the format for its access and consistency requirements,
then benchmark a representative workload.
Quick practice
sent = {"id": 2, "ms": 120, "tags": ["disk", "web"]}
back = {"id": "2", "ms": 120, "tags": ["disk", "web"]}
print(sent == back)Run it, see the mismatch, then add the missing json.loads so tags_back is a list again.
rows = [{"id": 3, "tags": ["web"]}, {"id": 1, "tags": ["disk"]}]
sent = sorted(rows, key=lambda r: r["id"])
print([r["id"] for r in sent])🎯 Your turn
Write vault_roundtrip(csv_text). The starter includes read_csv from the
first lesson and the SCHEMA. You write to_record and the round trip:
records = [to_record(row) for row in read_csv(csv_text)]- store them in one transaction, with
tagsasjson.dumps(...)text - if the batch raises
sqlite3.IntegrityError, return{"stored": 0, "unchanged": False, "levels": {}, "slowest": None} - read everything back
ORDER BY id, decodingtags - return:
"stored": how many records came back"unchanged": whether they equal the records sorted by id"levels":{level: count}, fromSELECT level, COUNT(*) ... GROUP BY level"slowest": the id with the largestms(the lowest id on a tie), orNoneif no record has anms
Example: three incidents where id 2 took 950 ms →
{"stored": 3, "unchanged": True, "levels": {"INFO": 1, "WARN": 2}, "slowest": 2}.
Hint: max(timed, key=lambda r: r["ms"]), where timed is the records
read back in id order that have an ms, returns the first of any tie, which
is the lowest id.
Press ▶ Run and hit ✓ Check. When it's green, the vault is done: data goes out of memory and comes back unchanged. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write pack_tags(tags) returning the JSON text Quarry stores in the tags column: the tags de-duplicated and sorted, encoded with json.dumps.
Write to_record(row). row is a dict of strings from read_csv. Return id as an int, source and level unchanged, ms as an int or None if the cell is empty, and tags (a |-separated string) as a sorted list without duplicates or blanks.
Write format_sizes(records). records is a list of flat dicts sharing the same keys. Return {"csv": bytes, "json": bytes}: the UTF-8 byte length of the CSV text (header from the first record's keys, lineterminator="\n") and of json.dumps(records, separators=(",", ":"), ensure_ascii=False). For an empty list the CSV is 0 bytes and the JSON is [].
Write slow_ids(csv_text, level). Read the CSV with the starter's read_csv, store id, level and ms (as ints, empty ms as NULL) in a :memory: table, then return the ids of records at level that have an ms, slowest first, with ties broken by lower id first. Use a ? parameter for the level.
Write vault_report(csv_text). The CSV has id, level and ms. A data row is rejected if its id or ms isn't an integer (an empty ms is also a reject here). Store the accepted rows in a :memory: SQLite table in one transaction. Return {"stored": count, "rejected": [data-row numbers, first data row = 1], "levels": {level: {"count": n, "max_ms": m}}}, with the level figures computed by SQL (GROUP BY level).
Across this section Quarry used four formats. Explain why the vault stores records in SQLite rather than as one JSON file or one pickle file per batch, and name one situation where each of CSV, JSON and pickle is still the right choice. Use at least one concrete property (queryability, transactions, trust, types, who reads it) in each answer.