Pickle serializes Python objects into a Python-specific binary representation. Loading pickle can execute code and requires trusted input.
Evaluate cache boundaries, verify authenticity before deserializing and define freshness rules for reused data.
A parsed batch contains tuples, datetimes and two references to the same list. Pickle can preserve supported Python values and their relationships, making it useful for some internal caches. Its convenience comes with a different loading model from JSON: unpickling can call code. Trust and cache compatibility must be decided before loading.
You'll build cache_batch(raws), the vault's batch cache: park a parsed
batch as bytes, and get back exactly the records you had.

Cache a parsed batch so tomorrow's run skips the parsing
Parsing is the slow part of Quarry's pipeline. If both the source and parser contract are unchanged, a cached parsed batch may avoid repeated work; measure whether it is faster:
back == record is True. The tuple is still a tuple, the int keys are
still ints — every lossy edge from the JSON lesson is gone. Pickle even
tracks which names point at the same object:
import pickle
shared = ["web"]
pair = [shared, shared] # two references to ONE list
back = pickle.loads(pickle.dumps(pair))
back[0].append("disk")
print(back[1])What pickle can't carry is code: a function is pickled by reference — module and name — and reimported at load time. A lambda has no name to look up. A generator is a paused stack frame with nothing to name. Fix this batch so it pickles, keeping the rows intact:
Run it and read which object pickle refused. Then change the batch so it holds only data.
Preparing this topic’s interactive investigation…
Open a batch cache written by someone you don't trust
Here's where the convenience turns dangerous. pickletools.dis shows what's
really in the bytes:
That's not a data layout — it's instructions for a tiny stack machine.
GLOBAL 'datetime date' imports datetime and pushes the date class.
REDUCE pops a callable and a tuple of arguments, calls the callable, and
pushes the result. Rebuilding a date means calling date(...) — and
that's exactly how pickle restores anything: by calling whatever the stream
names, with whatever arguments the stream supplies. A class controls its own
rebuild with __reduce__:
import pickle
class Sneaky:
def __reduce__(self):
return (str.upper, ("owned",))
blob = pickle.dumps(Sneaky())
print(pickle.loads(blob))str.upper is harmless; an attacker picks something that isn't. And the call
happens inside loads, before your code ever sees the result — no check
afterwards can help.
Here's that machine cut down to five instructions you can trace by hand:
Sign a cache so a tampered file is refused
Never unpickle data you did not produce yourself, from a place nobody else can write to.
A cache in a shared directory, an upload, a queue message: each is
"untrusted" the moment someone other than you could have written it. The real
fix is to not use pickle across a trust boundary at all — reach for JSON or a
database instead when data crosses between programs or people. When Quarry
writes its own cache and reads it back, signing proves the bytes are
yours: attach an HMAC, a keyed hash made with a secret only Quarry knows, and
check it before calling loads:
The comparison uses hmac.compare_digest, not ==, so the time it takes
doesn't leak how many bytes matched. A short checksum like CRC-16 is broken
almost at once; HMAC-SHA256's 256 bits put a forged tag out of reach. A valid signature
shows the bytes came from someone holding the key — it does not make hostile bytes safe, which is
why the real rule is still "don't cross a trust boundary with pickle".
A trusted cache also needs an expiry rule
A cache can be authentic and still be wrong for today's program. Imagine that yesterday's parser treated took=2s as the number 2, while today's parser stores milliseconds and expects 2000. Reusing the old parsed result bypasses the corrected parser. Checking only the source filename or modification time does not establish compatibility.
A useful cache key includes the source content digest and a parser/schema version. Store an envelope such as {"schema": 2, "source_digest": "…", "records": [...]}; reject or rebuild entries from another schema. If cache deserialization fails because a class moved modules, a cache miss and reparse may be appropriate. Do not silently apply that policy to the only copy of valuable data.
Pickle reconstructs supported object graphs; it does not preserve everything about a running program. Functions and classes depend on importable names, open resources have lifetimes, and a loaded object is not generally the identical object that existed before serialization. The shared-list exercise checks a subtler promise: alias relationships inside the restored graph survive.
Reason about trust: a cache originally written by your own program is no longer trustworthy if another user can overwrite its directory. HMAC verification must happen before loading, and the key must remain secret. An allow-listing Unpickler exercise shows where class lookup happens; its name SafeUnpickler is not a general sandbox or a guarantee against resource exhaustion. Prefer a constrained data format and schema for externally supplied content.
For transfer, change only the parser version while keeping source bytes identical. Should the cache hit? Explain why the correct answer differs from a purely byte-based cache of an immutable file download.
Reference: pickle's trust and compatibility requirements.
Quick practice
import pickle
print(pickle.loads(pickle.dumps((1, 2, 3))) == (1, 2, 3))TypeErrorRun it, read which object pickle refuses, then pickle a realised list instead of the generator and print "ok".
import pickle
class Payload:
def __reduce__(self):
return (len, ([1, 2, 3],))
print(pickle.loads(pickle.dumps(Payload())))🎯 Your turn
Write cache_batch(raws). The starter's build_record(raw) is the same
stand-in record stage as in the JSON lesson. Your function should:
- build
records = [build_record(r) for r in raws] - pickle the list to bytes with
pickle.HIGHEST_PROTOCOL, then load it back - return
{"count": len(restored), "intact": restored == records, "kinds": sorted type names of every value in every restored record}
Example: one incident record →
{"count": 1, "intact": True, "kinds": ["Decimal", "datetime", "int", "set", "str"]}.
Every one of those types came back as itself, which JSON couldn't do.
Hint: a set comprehension, {type(v).__name__ for r in restored for v in r.values()}, collects the names without duplicates. Then sorted it.
Press ▶ Run and hit ✓ Check. ✅
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 survivor(kind). kind is one of "tuple", "set", "frozenset" or "bytes". The starter builds the value. Return {"pickle": type name after a pickle round trip, "json": type name after a JSON round trip}, and if JSON raises TypeError, use the string "TypeError" instead of a type name.
Write shared_after(items). Make inner = list(items) and pair = [inner, inner]. Round-trip pair through pickle and through JSON separately. In each result, append "new" to element 0, then report the length of element 1. Return {"pickle": ..., "json": ...}.
Write can_pickle(kind). The starter's make(kind) builds a lambda, a generator, a nested function, a dict or a datetime. Try pickle.dumps on it and return True if it works and False if it raises. (Catch Exception: which exception you get varies between Python versions, and the point is whether, not which.)
Subclass pickle.Unpickler as SafeUnpickler and override find_class(self, module, name): if (module, name) is in the starter's ALLOWED, return super().find_class(module, name), otherwise raise pickle.UnpicklingError(f"refused {module}.{name}"). Then write restricted_load(kind): pickle PAYLOADS[kind](), load it with SafeUnpickler(io.BytesIO(blob)).load(), and return the loaded object's type name, or the error message if it was refused.
Write signed_cache(raws, tamper). Seal the list: blob = pickle.dumps(raws) and sealed = hmac.new(KEY, blob, hashlib.sha256).digest() + blob. If tamper is true, flip the lowest bit of the last byte of sealed. Then open it: split off the 32-byte tag, recompute the HMAC of the rest, and compare with hmac.compare_digest before unpickling. Return {"loaded": number of records, "error": None}, or {"loaded": 0, "error": "bad signature"} if the check fails.
A teammate wants Quarry to accept pickled batches uploaded by partner teams, "because it's faster than JSON and keeps our types". Explain, in terms of how unpickling actually works, why this lets an uploader run code on Quarry's machine, and what Quarry should do instead. Say what HMAC signing would and would not fix here.