Workbench / The TiffinBox Build
S10 · V1·10
A Language for Discounts
Volume 1, chapter 10. Discount rules get their own small language ("rule "Big order" when total >= ₹1000 then ₹100 off"): a lexer that understands rupees and percentages, a recursive-descent parser with a depth limit and error messages that point at the column, an interpreter that prices an order deterministically, and an analyzer that checks every class of order the rules can distinguish to find rules that can never fire and discounts that collide. Along the way, a profile of TiffinBox's own code finds a regex being recompiled for every dish ever created, and removing it makes decoding the order log 2.3× faster.
Stage 10: a language for discounts
The brief
What you'll build. A new package, in.tiffinbox.rules, in core/:
Lexer: characters to tokens (words, quoted names, whole numbers,₹amounts with up to two decimals, percentages with up to two decimals, comparison operators, brackets), with line and column on every token, ASCII digits only, and comments starting with#;Parser: tokens to a syntax tree (Ast), by recursive descent over a small grammar, withandbinding tighter thanor, a nesting limit of 32, a 500-rule limit, and errors that print the line with a caret under the problem;FactsandInterpreter: the facts a rule may look at, computed once per order (total, day and hour in IST, kitchen, dishes, first order), and a pricing function: the single best money discount, plus free delivery if any rule grants it;Analyzer: an exhaustive check of a rule set before it ships, reporting dead rules and overlapping discounts, each with an example order;- a fix to
Dish: replacing a per-call regex with a hand-written check.
Why a real company needs this. Discounts change every week, are written by marketing and operations, and cost real money when wrong: a "Welcome" offer that stacks with "Big order", or a weekday rule nobody notices never fires. Putting rules in code means a deploy for every campaign; putting them in a generic scripting engine means rules can do anything, including loop forever. A small language sits in between: readable by the people who write the rules, restricted to what rules need, and analysable before it reaches customers.
Why now. Chapter 10 is exactly this pipeline: lexing, grammars and precedence, syntax trees, semantic checks, and evaluation. Stage 5 deferred discounts to here, stage 6 built Money.percent with half-even rounding for it, and stage 7 fixed the business time zone that "hour" and "day" depend on.
What you'll have at the end.
- the rules language with 5 tests (44 in total), a sample rules file, and a checker program;
- real parse errors and a real analysis of the sample file in the README;
- a measured speed-up from removing the regex in
Dish; - ADR-0012: rules as a restricted language, and how a rule set is approved.
Theory to own
- Grammar and precedence. In
when first order or kitchen = k1 and hour < 9, which conditions group together, and how does the grammar's shape decide it? (Chapter: "Parsing and grammars"; Companion, Gaps 3.) - Lexing money. Why is
₹1,000a lexing decision andtotal >= ₹1000a parsing one? What should₹19.999be? (Chapter: "Lexical analysis".) - Errors as a feature. What makes a parse error useful to a non-programmer? (Chapter: "When things go wrong: three kinds of error".)
- Determinism. Two discounts apply to one order. What rule decides which one wins, and why must it depend only on the rules file? (Stage 3's tie-breakers; stage 4's
RANK.) - Checking all orders. There are infinitely many possible orders. How can a checker examine "every order" in finite time? (Chapter 05: equivalence relations; stage 5's exhaustive checks.)
Build it
Step 1: the language, on paper first
Write the grammar and three example rules before any code:
rules := rule*
rule := 'rule' STRING 'when' or 'then' effect
or := and ('or' and)*
and := not ('and' not)*
not := 'not' not | primary
primary := '(' or ')' | 'total' OP MONEY | 'hour' OP NUMBER | 'kitchen' ('='|'!=') WORD
| 'day' 'in' '[' DAY (',' DAY)* ']' | 'day' '=' DAY | 'has' WORD | 'first' 'order'
effect := PERCENT 'off' | MONEY 'off' | 'free' 'delivery'
# TiffinBox discounts, November
rule "Weekday free delivery" when total >= ₹500 and day in [mon, tue, wed, thu, fri] then free delivery
rule "Breakfast at k7" when kitchen = k7 and hour < 11 and has d2 then 10% off
rule "Big order" when total >= ₹1000 then ₹100 off
rule "Welcome" when first order then 15% off
Checkpoint. Someone from operations can read the examples and predict what each rule does.
Step 2: the lexer
Write Lexer.tokens(String): skip spaces and # comments; read words (ASCII letters, digits and _), quoted strings (no newlines), numbers, ₹ amounts and percentages (as hundredths, rejecting a third decimal and more than 9 integer digits), the operators < <= > >= = !=, brackets and commas; reject anything else with a position. Limit the source to 100,000 characters.
Checkpoint. ₹99.5 becomes a money token of 9,950 paise, 12.5% a percentage of 1,250 hundredths of a percent (basis points), and ₹1.999 an error.
Step 3: the parser, with a depth limit and good errors
Write Parser.parse(String) as one method per grammar rule. Build Ast records (And, Or, Not, TotalCmp, HourCmp, KitchenIs, DayIn, Has, FirstOrder; and the effects PercentOff, AmountOff, FreeDelivery). Check meaning while parsing: hours 0–23, kitchen and dish ids in canonical form, percentages from 0.01% to 100%, amounts above ₹0, unique rule names. Count nesting depth on every ( and not, and refuse more than 32. Every error is a RuleError with the source line and a caret.
Checkpoint. first order or kitchen = k1 and hour < 9 parses to Or(FirstOrder, And(KitchenIs k1, HourCmp < 9)), and a rule nested 10,000 parentheses deep is rejected with a message, not a StackOverflowError.
Step 4: facts, evaluation and pricing
Write Facts.of(order, zone, firstOrder): the total, the day and hour in the business time zone, the kitchen, the set of dish ids, and whether it's the customer's first order. Then Interpreter.eval(expr, facts) as one exhaustive switch over the sealed Expr, and Interpreter.price(rules, facts):
- every rule whose condition holds contributes: a money effect is computed (
percentof the subtotal, or a fixed amount capped at the subtotal); free delivery is noted; - the largest money discount wins; ties go to the rule that appears first;
- free delivery combines with a money discount;
- the result names the rules that decided it, and
total()never goes below zero (stage 2'sminusFloorZero).
Checkpoint. A ₹1,200 order on a Monday at 09:00 at k7 containing d2 gets ₹120 off from "Breakfast at k7" (10% beats "Big order"'s ₹100) and free delivery, for a total of ₹1,080; a ₹400 Saturday-evening order gets nothing.
Step 5: the analyzer
Write Analyzer.check(rules):
- collect every constant the rules mention: each money threshold (and its neighbours one paisa either side), each kitchen id, each dish id;
- enumerate one representative of every class of orders: each total, 24 hours, 7 days, each named kitchen plus one that no rule names, every subset of the named dishes, first order or not (with a safety cap on the number of cases);
- evaluate every rule on each representative; a rule that never holds is dead; two money-discount rules that hold together are an overlap, reported with the first example found.
Add a fifth rule to the sample file, "Lunch combo" with total >= ₹500 and total < ₹300, and run the checker.
Checkpoint. The checker reports "Lunch combo" as dead and lists the overlapping discount pairs, but not free delivery (which combines on purpose).
Step 6: tests
Write RulesTest: parsing and pricing the sample, precedence, exact error messages, the nesting limit, and the analyzer's findings (including that free delivery isn't an overlap).
Checkpoint. The build prints tests: 44 passed.
Step 7: a regex in TiffinBox's own hot path
The Companion to this chapter measured String.matches recompiling its pattern on every call. Search core/ for .matches( and find the one in the Dish constructor (since stage 2). Measure creating a million dishes, and stage 6's Bench6 decoding 100,000 records (which creates a Dish per line), then replace the regex with a hand-written check and measure again.
Checkpoint. All 44 tests still pass, and you have before and after numbers.
Senior and architect lens
1. A language is a product with users. The rule writers are its users: the error messages, the restrictions, the sample file and the checker are its user interface. Most small languages fail not because the parser is wrong but because the errors are incomprehensible and nobody can tell what a rule set will do. This one prints the line and a caret, explains what was expected, and tells marketing which rules can't fire.
2. ADR-0012: rules as a restricted language. Write it with these points:
- Decision: discounts are defined in rule files in the TiffinBox rules language (grammar in
Parser's header), evaluated by a pure interpreter overFacts. - Semantics: the single best money discount (ties to the earliest rule) plus free delivery; amounts in paise; percentages rounded half-even; hours and days in Asia/Kolkata.
- Approval: a rule file ships only if it parses and the analyzer reports no dead rules; overlaps are listed in the change request and approved by marketing.
- Limits: 100,000 characters, 500 rules, nesting depth 32, at most 12 dishes named across the file (the analyzer's cap).
- Not supported, on purpose: variables, arithmetic, loops, calls, stacking of money discounts.
- Revisit when: rules need customer history beyond "first order", per-city calendars, or stacking. Each changes the language and the analyzer together.
3. Restriction buys analysability. Because the language has no loops or arithmetic, every condition is a Boolean combination of comparisons against constants, so the analyzer can examine every class of order exactly. Add a single arithmetic expression (total - delivery >= ₹500) and the equivalence classes multiply; add loops and the question becomes undecidable (Rice's theorem, Companion theoretical gap 3). Every feature request for the language should be weighed against what it does to the checker.
4. Profile your own code, not just the libraries'. The Companion's measurement of String.matches was an exercise; the same pattern was in TiffinBox's own constructor for eight stages, costing 2.3× on log decoding. Searching your codebase for the anti-patterns you've just learned about is one of the cheapest performance reviews there is.
5. Pure evaluation makes rules testable and replayable. price(rules, facts) has no clock, no I/O and no hidden state. A support engineer can re-price yesterday's disputed order with yesterday's rules file and get exactly the same answer, and stage 11 can price every order in the log against a proposed rules file to show its effect before it ships.
What breaks first, and when it's addressed:
| Pressure | What breaks | Where it's addressed |
|---|---|---|
| orders priced with rules | the server doesn't call the interpreter yet | stage 11 (pricing in POST /orders) |
| "what would this change cost?" | no way to replay orders against a new rule file | stage 11 (replay the log through two rule sets) |
| many dishes named in rules | the analyzer's 2ⁿ dish subsets | an SMT solver, or grouping dishes into categories |
| rules edited by non-developers | no editor, no versioning, no audit | Volume 3 (rules stored and versioned in the database) |
| stacking discounts | the language has one "best discount" semantics | a deliberate language change, with the analyzer extended |
Evidence
- The grammar and the sample rules file are committed; the build prints
tests: 44 passed. - Three real parse errors (with carets) are in the README.
- The analyzer's output for the sample file, including the dead rule, is in the README, with marketing's decision on each overlap.
- Before-and-after measurements of the
Dishfix are in the README. - The README lists every remaining
.matches(incore/and says whether each is on a hot path. - ADR-0012 is committed.
Carry forward
- The rules language and
Interpreter.priceprice every order from stage 11 onwards; Volume 3 stores rule files in the database with versions and approvals. - The analyzer runs in CI on every rule file change, and before any rules reach production.
Factsis the boundary between orders and rules: new rule features start by adding a fact.- Hand-written checks for identifiers on hot paths, precompiled
Patterns elsewhere, and neverString.matchesin a loop.