Capstone — Quarry's Record Codec
In short: the record codec is every earlier lesson in one pipeline — pack each record's fields with shifts and width checks (lessons 1–2) in O(1) per record, OR each accepted record's shard into a 64-bit bitset (lessons 3–4) for an O(1) "worth opening" test, and compare epochs with masked subtraction so the ring they count around (lesson
- doesn't break "newer than". Encoding n records is O(n) time and O(n) space for the output words, with O(1) extra space per record beyond that.

Eight lessons ago Quarry was a promise: a storage engine that keeps a hundred million record headers in 400 MB instead of 20 GB. You now have every piece that takes. This capstone joins them into the record codec, the part that turns a batch of incoming records into a segment. That's a list of packed 32-bit header words plus a small index that lets queries skip segments without reading them.
Here's what the codec has to do, and the lesson each part comes from:
| Job | Tool | From |
|---|---|---|
| Pack id, shard, type and epoch into one word | shifts, OR, width checks | lessons 1–2 |
| Refuse a record that doesn't fit | value >> width must be 0 |
lesson 2 |
| Answer "which shards are in this segment?" in one word | a bitset, |=, popcount |
lessons 3–4 |
| Compare epochs that wrap around at 2,048 | masked subtraction | lesson 1 |
| Skip whole segments at query time | masks as sets, & |
lessons 4 and 8 |
The layout, as data
Hard-coding shifts like << 20 in four places is how layouts drift apart. The codec
keeps the layout as a table and derives every shift and mask from it. Changing the
layout (lesson 2's repack) is then a one-line edit:
Packing walks the same table from the top. A field that doesn't fit makes the whole record invalid, and the codec rejects it instead of corrupting it:
LAYOUT = [("id", 12), ("shard", 6), ("type", 3), ("epoch", 11)]
def encode(record):
w = 0
for (name, width), value in zip(LAYOUT, record):
if value < 0 or value >> width:
return None
w = (w << width) | value
return w
print([encode(r) is None for r in ([4095, 63, 7, 2047], [4096, 0, 0, 0], [1, 2, 8, 3])])