Workbench / The TiffinBox Build
S6 · V1·06
A Versioned Binary Record
Volume 1, chapter 06. Orders get a compact binary form: a magic number, a version byte, varint lengths, strict UTF-8, a CRC-32, and an extension section so the format can grow without breaking old readers. A fuzzer runs 200,000 mutated records through the first decoder and finds out-of-memory errors and negative array sizes; the hardened decoder turns every bad input into one exception type. The binary form is 3.7× smaller than JSON, and then, gzipped, it's bigger. Money gains exact splitting and named rounding, and kitchen ids finally sort k7, k9, k12.
Stage 6: a versioned binary record
The brief
What you'll build.
OrderCodec:encode(order, extensions)anddecode(bytes)for a compact, versioned binary form of anOrder, with an extension section that old readers skip and a committed "golden" version-1 record that every future version must still read.- A fuzzer that mutates valid records and feeds them to the decoder, plus a hardened decoder that accepts only valid records and rejects everything else with one exception type,
MalformedRecordException. Money.split(n)andMoney.percent(basisPoints): splitting that never loses a paisa, and percentages rounded by a named rule.Ids.NATURAL: kitchen and dish ids sorted the way people read them, now used bytbx --by-kitchen.
Why a real company needs this. Stage 8 writes every order event to disk, and stage 9 sends them over the network. Whatever bytes are written today must be readable in five years by code that doesn't exist yet, and whatever bytes arrive from outside must not be able to crash or exhaust the server. Both are representation problems, and they're far cheaper to get right before the first byte is stored.
Why now. Chapter 06 covers exactly what a format needs: varints, byte order, UTF-8 and its invalid forms, checksums at the edge, serialisation compatibility, and money as fixed point. Stage 3 also left a promise: k12 sorting before k7.
What you'll have at the end.
OrderCodecwith a documented layout and 5 new tests (30 in total), including a golden record and a fuzz test in the build;- real measurements of size against JSON, raw and gzipped, and of decoding speed;
tbxlinked tocoreas one self-contained jar, with natural kitchen order;- ADR-0008: the record format, how it evolves, and what it promises.
Theory to own
- Varints. How does an unsigned LEB128 varint encode 300? How many bytes does a 64-bit value take at most, and what must a decoder do with an 11th continuation byte? (Chapter: "Variable-length integers".)
- Compatibility. What's the difference between backward and forward compatibility? Which does a version byte give you, and which does an "unknown tags are skipped" section give you? (Chapter: "Serialisation compatibility".)
- Untrusted lengths. A record says "the next string is 2,000,000,000 bytes long". What happens if the decoder believes it? (Chapter Exercises leaves out "Parsing untrusted binary data"; Companion, Gaps 2.)
- Checksums. What does a CRC-32 protect against, and what doesn't it protect against? (Chapter Exercises "What the chapter leaves out": checksums and hashes.)
- Splitting money. ₹10 split three ways is 333 + 333 + 333 paise = ₹9.99. Where does the missing paisa go, and why is "round each share" never enough? (Chapter: "Money, decimals and fixed point"; Companion, drill D3.)
Build it
Step 1: the layout, written down first
Before writing code, write the layout as a comment at the top of OrderCodec:
- a header: the magic bytes
'T' 'B', a version byte (1), and the body length as a varint; - a body: order id, kitchen id, line count, each line (dish id, name, price in paise, quantity), the status (a kind byte, epoch milliseconds, then prep minutes or a reason where the state has one), and an extension count followed by
{tag, length, bytes}entries; - a trailer: CRC-32 of the body, 4 bytes big-endian.
Strings are a varint byte length followed by UTF-8.
Checkpoint. Someone could write a decoder in another language from the comment alone.
Step 2: encoder and a first, trusting decoder
Implement encode and a straightforward decode that reads fields in order with a ByteBuffer, trusting every length it reads. Keep extensions in a TreeMap so encoding is deterministic.
Checkpoint. A sample order (two lines, one with a Telugu dish name, status Cancelled) round-trips, and the record is 86 bytes.
Step 3: fuzz the trusting decoder
Write Fuzz6.java (outside the test suite) that takes the sample record and, 200,000 times, overwrites 1–3 random bytes, sometimes truncates, and calls decode, counting outcomes by exception type. Run it twice: once on the raw mutations, and once resealing each mutation with a correct CRC so the mutations reach the parser instead of stopping at the checksum. Run with -Xmx256m.
Checkpoint. You have a table of outcomes for both runs.
Step 4: harden the decoder
Rewrite decode so that:
- every length and count is checked by a
bounded(value, max, what)helper against what the remaining input could hold and a business limit (64 KiB per record, 100 lines, 1,000 bytes per string, 16 extensions); - varints longer than 9 bytes are rejected (TiffinBox values never need 64 bits);
- strings are decoded strictly, so invalid UTF-8 is an error;
- bytes left over after the checksum, or after the last field, are an error;
- domain validation (stage 2's constructors) runs on decoded values, and its exceptions are wrapped;
- every failure surfaces as
MalformedRecordException.
Then rerun the fuzzer.
Checkpoint. Both fuzz runs show only MalformedRecordException and decoded.
Step 5: tests that pin the format
Add RepresentationTest with:
- a round trip of every status, with an idempotency-key extension (tag 1) and an unknown tag 99 that must survive;
- a golden record: the sample's version-1 bytes as a hex string committed in the test, which must decode to the sample, and which the encoder must reproduce exactly;
- a fuzz test: 20,000 mutations, each either decoding or throwing
MalformedRecordException(anything else fails the build), plus a hand-made record whose length varint is huge; - money splitting and percentages;
- natural id order.
Checkpoint. The build prints tests: 30 passed.
Step 6: measure size against JSON
Write Bench6.java that generates 100,000 realistic orders (1–3 lines from a 10-dish menu, 40 kitchens), encodes each as a binary record and as compact one-line JSON, and reports total sizes, gzipped sizes, and decode time.
Checkpoint. You can say how much the binary format saves, and whether it still saves after compression.
Step 7: money that never loses a paisa, and ids in human order
Add to Money:
split(n): n parts differing by at most one paisa, summing exactly to the whole, with the extra paise going to the first parts;percent(basisPoints): a percentage in basis points (1% = 100), rounded half-even to the paisa, withBigDecimaldoing the division.
Add Ids with isCanonical(id) (letters then a number without leading zeros) and NATURAL, a comparator that orders by prefix and then numerically. Use it in tbx --by-kitchen, linking tbx to core and packaging core's classes into tbx.jar.
Checkpoint. ₹10.00.split(3) is 334, 333, 333 paise; every split of several amounts sums to the original; tbx prints k7, k9, k12.
Senior and architect lens
1. A stored format is a promise to the future. The golden record turns that promise into a test: no change can ship that stops reading version 1. Real systems keep a folder of golden files, one per version ever written. Stage 8 will store millions of these records; after that, the format can grow but never break.
2. ADR-0008: the order record format. Write it with these points:
- Decision: the layout in
OrderCodec's header comment; version 1; a tagged extension section for additions; explicit numbering of status kinds; CRC-32 per record. - Evolution rules: new optional data goes in a new extension tag (never reuse a tag number); a change existing readers can't skip safely bumps the version, and new readers must keep reading every older version; golden records for each version live in the tests.
- Limits: 64 KiB per record, 100 lines, 1,000 bytes per string, 16 extensions. They're part of the format, because readers enforce them.
- Not promised: tamper-evidence (CRC isn't a MAC); compatibility for anything outside the documented layout.
- Revisit when: a second language must read the records (then a schema language such as Protocol Buffers pays for itself), or records need field-level evolution beyond extensions.
3. Parsers of untrusted input are a security boundary. The fuzzer found denial-of-service bugs (out of memory from 86 bytes) in an ordinary-looking decoder. Every parser that reads bytes from a file, a network or a user deserves the same treatment: bounded lengths, strict decoding, one error type, and a fuzz test in the build. Java's own ObjectInputStream deserialisation is the cautionary tale: decades of vulnerabilities from trusting the input to describe its own objects.
4. Measure the format for its actual use. Binary was 3.7× smaller raw and a third bigger gzipped. Either claim alone would be misleading. The right question is what the bytes are for: a hot append-only log, a network payload, an archive. Volume 4 adds a third option (columnar storage) for the analytics use, where neither of these wins.
5. Representation choices leak into people's experience. "k12 before k7" and "₹9.99 for three shares of ₹10" are representation bugs that users see. Fixing them in core (Ids.NATURAL, Money.split) means every screen and report gets them right without each one remembering to.
What breaks first, and when it's addressed:
| Pressure | What breaks | Where it's addressed |
|---|---|---|
| storing millions of records | nothing yet writes them durably | stage 8 (append-only log of these records) |
| a torn write at the end of a log | a partial record | stage 8 uses the length prefix and CRC to detect and truncate it |
| another service, in another language, reading records | a hand-written layout must be re-implemented | ADR-0008's revisit trigger; Volume 3 (schemas) |
| tampering by someone with disk access | CRC can be recomputed | Volume 7 (MACs and signatures) |
| analytics over a day's records | row-by-row decoding of every field | stage 7 (a layout built for scans) |
Evidence
- The layout comment in
OrderCodec, and ADR-0008, are committed. - Both fuzz runs against the trusting decoder, and against the hardened one, are in the README with a sentence each.
- The build prints
tests: 30 passed, including the golden record and the fuzz test. - You can read the golden hex field by field (annotate it in the README).
- Your size and decode-time measurements, raw and gzipped, are in the README with the conclusion for the stage 8 log.
tbx --by-kitchenprints k7, k9, k12, its 21 checks pass, and the new reproducible jar hash is recorded.
Carry forward
OrderCodecis the on-disk and on-wire form of an order. Stage 8's log appends these records; stage 9 can serve them; the golden record guards them from here on.MalformedRecordExceptionand bounded decoding are the pattern for every parser of outside input in TiffinBox, including stage 9's HTTP parser and stage 10's rules language.Money.splitandMoney.percentare how stage 10's discounts and Volume 3's refunds compute amounts: allocation, not rounding, and named rounding rules.Ids.NATURALsorts ids wherever people read them; machine output that must stay byte-stable can still choose text order on purpose.