The TiffinBox BuildOne system, every chapter
0 / 0

Workbench / The TiffinBox Build

S5 · V1·05

Proving the Lifecycle

Volume 1, chapter 05. The order lifecycle stops being checked by a few examples and is checked exhaustively: every state against every event against an executable specification table, every history of up to six events (19,530 of them) against invariants, and the state graph for dead ends. The very first exhaustive check finds a real bug that every existing test missed. Then the lifecycle gains refunds, the change is verified the same way, and order creation becomes idempotent with keys whose collision odds you can compute.

6 parts · ~8 min to read
Updated Suggest a correction

Stage 5: proving the lifecycle

The brief

What you'll build.

  • LifecycleTest: four checks that cover the lifecycle completely within a finite model:
  • every (state, event) pair against a specification table that lives in the test;
  • every event one minute too early, against every state;
  • every history of up to six events, against invariants ("delivered only after accepted then ready", "time never goes backwards", "terminal states never move");
  • the state graph: every state reachable, and no state that can't reach an ending.
  • Refunds: a new RefundDue state and RefundPaid event, replacing stage 2's "cancel after ready needs a refund flow" rejection.
  • IdempotencyKey and Idempotency: a retried "place order" request returns the order it already created, instead of creating a second one.

A change of plan. Stage 1's plan put discount rules in this stage. They move to stage 10, where rules get their own small language and the logic in this chapter (conditions as formulas, conflicts as satisfiability) can be applied to rules as data. The lifecycle is the thing every later stage depends on, so it gets this stage's full attention.

Why a real company needs this. An order lifecycle bug doesn't crash anything. It produces an order that was "delivered" without being ready, a refund on food never cooked, or a second charge when a phone on a weak network retries "Place order". Each is rare, invisible in testing with a handful of examples, and expensive in support tickets and trust.

Why now. Chapter 05 gives you the tools: sets and relations (states and transitions), logic and quantifiers ("for every history…"), induction (invariants that hold after every step), counting (how many histories exist), graphs (reachability) and the birthday bound (key sizes).

What you'll have at the end.

  • 6 new tests (25 in total), four of them exhaustive;
  • a lifecycle of 6 states and 5 events whose specification is an executable table;
  • idempotent order creation, safe under concurrent retries;
  • ADR-0007: the lifecycle specification is the test, and changing it means changing the table.

Theory to own

  1. Counting the space. With 6 states and 5 events, how many (state, event) pairs are there? How many event sequences of length exactly k? Of length 1 to 6? (Chapter: "Counting principles".)
  2. Invariants as induction. "Time never goes backwards" must hold after every event in every history. What are the base case and the inductive step, and why is checking every single transition enough? (Chapter: "Mathematical induction"; "Loop invariants".)
  3. Quantifiers. Write "every reachable state can reach a terminal state" with ∀ and ∃. What graph algorithm checks it? (Chapter: "Predicates and quantifiers"; "Graph theory".)
  4. Functions and injectivity. An idempotency key hashes customerId + clientRequestId. Why does plain concatenation make two different requests share a key, and what fixes it? (Chapter: "Injective, surjective and bijective".)
  5. The birthday bound. If keys are truncated to b bits, roughly how many keys until a collision becomes likely? What's the probability at a billion keys for b = 64 and b = 128? (Chapter: "The birthday paradox and hash collisions".)

Build it

Step 1: check every transition for one invariant, and find a bug

Before changing anything, write a test that explores every state reachable from Placed (at 06:31) under an "alphabet" of events: each of the four event kinds, at 06:30, 06:31 and 06:32, plus an invalid prep time. For every transition that moves the order, assert that the new state's time isn't before the old one's.

Checkpoint. Run it against stage 2's Transition, and read the failure.

Step 2: fix it once, in the transition function

Give OrderStatus an Instant at() method (every state already has the component, so each record implements it automatically), and make Transition.apply reject any event earlier than the current state.

Checkpoint. The test from step 1 passes, and the compiler points out the test's own switch helper is now redundant (use s.at()).

Step 3: refunds, and the expression problem in action

Replace stage 2's rejection of "cancel after ready" with a real flow:

  • RefundDue(at, reason): a new state, reached from Ready by CancelRequested;
  • RefundPaid(at): a new event, moving RefundDue to Cancelled with the original reason;
  • everything else in RefundDue is rejected ("order is being refunded"), and RefundPaid anywhere else is rejected ("no refund is due").

Checkpoint. Before you finish, compile after adding only the new records, and read what the compiler says.

Step 4: the specification as an executable table

Rewrite LifecycleTest so the specification is a text table in the test, one row per state and one column per event, with the target state or - for rejected. The test parses it and checks all 30 cells. Finally, assert the number of cells checked equals (number of states) × (number of events), using getPermittedSubclasses(), so a state or event added without updating the table fails the test.

Checkpoint. All 30 cells pass. Then break one transition on purpose (make Accepted + HandedOver move to Delivered) and check that the failure names the cell.

Step 5: every history, and the state graph

Add three more checks:

  • early events: every event one minute before every state's time is rejected;
  • every history of 1 to 6 events (one of each event kind at each step, a minute apart) from Placed, checking after each step: terminal states never move; reaching Delivered requires the path Placed, Accepted, Ready; reaching RefundDue requires having been Ready; time never goes backwards. Count the histories and assert 19,530;
  • the state graph: build edges from the transitions, check that every state is reachable from Placed, and that from every state Delivered or Cancelled is reachable.

Checkpoint. The build prints tests: 23 passed.

Step 6: idempotent order creation

A phone on a weak network sends "Place order", times out, and retries. Make creation idempotent:

  • IdempotencyKey.of(customerId, clientRequestId): SHA-256 of the two parts joined by a NUL separator (rejecting NUL inside either part), keeping the first 128 bits as 32 hex characters;
  • Idempotency.orderFor(key, create): runs create at most once per key and returns the same order id to every caller.

Test that the key separates ("ab", "c") from ("a", "bc"), and that 100 concurrent retries on 8 threads create exactly one order.

Checkpoint. The build prints tests: 25 passed.

Senior and architect lens

1. Exhaustive checking is cheap when the model is small, and the lifecycle is small. 30 pairs and 19,530 histories run in milliseconds. The skill is choosing the model: which values matter to the logic (event kinds, relative times, prep times at the boundary) and which don't (the reason text). Stating what's outside the model is as important as the checks themselves.

2. The bug was found by varying something examples held constant. Every example test used one instant, so none could see time go backwards. Exhaustive and property-based checks find bugs in the dimensions you didn't think were dimensions. When a test suite uses one magic constant everywhere (one time, one user, one currency), ask what happens when it varies.

3. ADR-0007: the specification is the table in the test. Write it with these points:

  • Decision: the lifecycle's specification is LifecycleTest.SPEC plus the invariants in the same file. Changing the lifecycle means changing the table in the same commit, reviewed by product and engineering together.
  • Why: the table is readable by non-engineers, and the test makes it impossible for documentation and code to disagree.
  • Consequences: every new state or event fails the build until the table and invariants cover it (the cell count check).
  • Revisit when: the lifecycle depends on data the table can't express (kitchen-specific rules, time windows). Then move to a model checker or a property-based testing library, and keep the table for the core.

4. Idempotency is a contract with the client, not just a server feature. It only works if the client generates the request id once and reuses it on every retry, and the server keeps the key at least as long as clients retry. Both halves need writing down: the API contract (Volume 3 uses an Idempotency-Key header, as Stripe and others do) and the retention period. And the key must be scoped (here, by customer), so one customer's id can never return another customer's order.

5. Late and out-of-order events are normal, so decide what to do with them on purpose. This stage rejects events earlier than the current state. That's simple, and wrong for some businesses: a delivery confirmation that arrives late is still true. Stage 8's event log records both the event's time and the time it was received, which lets later stages accept late facts without corrupting durations. Distributed systems (Volume 5) generalise this to event-time against processing-time.

What breaks first, and when it's addressed:

Pressure What breaks Where it's addressed
restarts and multiple servers the idempotency store and orders live in one process's memory stage 8 (durable log), Volume 3 (database)
late but true events strict rejection loses real facts stage 8 (event time against received time)
rules that differ per kitchen or city one global table stage 10 (rules as data), Volume 3
concurrent events on one order Transition is pure, but two updates can race Volume 3 (optimistic locking), Volume 4
refunds actually paid RefundPaid is an event nobody sends yet Volume 3 (payments integration), Volume 5 (sagas)

Evidence

  • The failing output from step 1 (against stage 2's code) is in the README, with a sentence on what it means in production.
  • LifecycleTest has the specification table, and the build prints tests: 25 passed.
  • A deliberately broken transition fails at least two of the exhaustive checks (paste the output, then restore).
  • A new state added without updating the table fails the cell-count check (try it with a dummy record, then remove it).
  • The README states what the exhaustive checks don't cover.
  • The concurrent retry test passes repeatedly (run the build five times).
  • ADR-0007 is committed, and stage 1's plan table is updated: discounts move to stage 10.

Carry forward

  • LifecycleTest.SPEC is the lifecycle's specification from now on. Stage 8's event log, the Spring service in Volume 3 and the apps in Volumes 2 and 22 all follow it.
  • OrderStatus.at() and the "no earlier events" rule are relied on by every duration TiffinBox computes.
  • IdempotencyKey becomes the Idempotency-Key contract of the HTTP API in stage 9 and Volume 3.
  • Exhaustive checks for small, critical models are the standard: permissions (Volume 3) and discount rules (stage 10) get the same treatment.