Skip to content

Run the Ledger Contract Checks

The Course
•
20 min study

The ledger makes promises: orders are all or nothing, retries are recognized, no item passes its capacity, limits are exact, cancellation and write failures are reported. A promise without a check is a hope. The project keeps its checks in checks.go, in one function, checkLedger, that both entry points call. In the browser, check.go calls it and prints a success line. In the download, ledger_test.go calls it from go test.

This playground replaces main.go with check.go and runs the checks against the same types.go, parse.go, ledger.go, pool.go and app.go as before.

What the checks cover

checkLedger runs seven groups, each one the kind of check you wrote this week:

  • checkOrders: a shortage on a later line reserves nothing, the exact remaining stock can be taken, a retry is replayed, a reused ID conflicts, and errors.As reads the shortage's fields.
  • checkCancel: cancelling returns stock, a second cancel and a reused cancelled ID are rejected, the snapshot is exact JSON, and a cancel that would pass capacity changes nothing.
  • checkParse: order lines are normalized, joined problems include every sentinel, and eight lines are accepted while nine are not.
  • checkConservation: 400 seeded random commands, with the conservation invariant checked after every one.
  • checkRun: a full transcript through run, a failing writer, and an already cancelled context.
  • checkLimits: 200-byte lines and 1000 commands pass, one more of either fails with no output.
  • checkPool: results keep their order for 0, 1, 3 and 50 workers, and an empty input works.
Run the order ledger checks Go
package main import "fmt" func main() { if err := checkLedger(); err != nil { panic(err) } fmt.Println("Order ledger checks passed") } package main import ( "context" "encoding/json" "errors" "fmt" "io" "math/rand/v2" "slices" "strings" ) var errClosed = errors.New("destination closed") type brokenWriter struct{} func (brokenWriter) Write([]byte) (int, error) { return 0, errClosed } // checkLedger is called by the browser check entry and by go test. func checkLedger() error { for _, check := range []func() error{checkOrders, checkCancel, checkParse, checkConservation, checkRun, checkLimits, checkPool} { if err := check(); err != nil { return err } } return nil } func checkOrders() error { l := NewLedger() if _, err := l.Stock("tent", 5); err != nil { return err } if _, err := l.Stock("drill", 1); err != nil { return err } // A shortage on the second line leaves the first line unreserved. _, err := l.Order("A1", []Line{{"drill", 1}, {"tent", 6}}) var shortage *ShortageError if !errors.As(err, &shortage) || *shortage != (ShortageError{Item: "tent", Have: 5, Need: 6}) { return fmt.Errorf("shortage: got %v", err) } if l.stock["drill"] != 1 { return fmt.Errorf("partial order: drill stock is %d after a rejected order", l.stock["drill"]) } // The rejected ID was not recorded, and the exact remaining stock can be taken. if outcome, err := l.Order("A1", []Line{{"drill", 1}, {"tent", 5}}); err != nil || outcome != Reserved { return fmt.Errorf("exact stock: got %v, %v", outcome, err) } if outcome, err := l.Order("A1", []Line{{"drill", 1}, {"tent", 5}}); err != nil || outcome != Replayed { return fmt.Errorf("retry: got %v, %v", outcome, err) } if _, err := l.Order("A1", []Line{{"tent", 5}}); !errors.Is(err, errConflict) { return fmt.Errorf("reused ID: got %v", err) } if _, err := l.Order("B1", []Line{{"lamp", 1}}); !errors.As(err, &shortage) || shortage.Have != 0 { return fmt.Errorf("unknown item: got %v", err) } return nil } func checkCancel() error { l := NewLedger() if _, err := l.Stock("tent", 3); err != nil { return err } if _, err := l.Order("B2", []Line{{"tent", 2}}); err != nil { return err } if err := l.Cancel("B2"); err != nil || l.stock["tent"] != 3 { return fmt.Errorf("cancel: got %v, tent stock %d", err, l.stock["tent"]) } if err := l.Cancel("B2"); !errors.Is(err, errCancelled) { return fmt.Errorf("repeated cancel: got %v", err) } if _, err := l.Order("B2", []Line{{"tent", 2}}); !errors.Is(err, errCancelled) { return fmt.Errorf("order after cancel: got %v", err) } if err := l.Cancel("Z9"); !errors.Is(err, errUnknownOrder) { return fmt.Errorf("unknown order: got %v", err) } data, err := json.Marshal(l.Snapshot()) if want := `{"stock":{"tent":3},"orders":{"B2":"cancelled"}}`; err != nil || string(data) != want { return fmt.Errorf("snapshot: got %s, %v", data, err) } // Returning stock may not pass the capacity, and a failed cancel changes nothing. full := NewLedger() for _, item := range []string{"drill", "tent"} { if _, err := full.Stock(item, 1); err != nil { return err } } if _, err := full.Order("C3", []Line{{"drill", 1}, {"tent", 1}}); err != nil { return err } if _, err := full.Stock("tent", maxStock); err != nil { return err } if err := full.Cancel("C3"); !errors.Is(err, errCapacity) { return fmt.Errorf("cancel past capacity: got %v", err) } if full.stock["drill"] != 0 || full.orders["C3"].cancelled { return errors.New("a failed cancel changed the ledger") } if _, err := full.Stock("tent", 1); !errors.Is(err, errCapacity) { return fmt.Errorf("stock past capacity: got %v", err) } return nil } func checkParse() error { cmd, err := parseCommand("order A7 tent:2 drill:1") if err != nil || !slices.Equal(cmd.Lines, []Line{{"drill", 1}, {"tent", 2}}) { return fmt.Errorf("order lines are not normalized: %+v, %v", cmd.Lines, err) } _, err = parseCommand("order A7 tent:0 Drill:2 tent:1") for _, want := range []error{errQuantity, errItem, errDuplicateItem} { if !errors.Is(err, want) { return fmt.Errorf("joined problems: %v does not include %v", err, want) } } entries := make([]string, maxOrderLines+1) for i := range entries { entries[i] = fmt.Sprintf("item%d:1", i) } if _, err := parseCommand("order A7 " + strings.Join(entries[:maxOrderLines], " ")); err != nil { return fmt.Errorf("eight lines: got %v", err) } if _, err := parseCommand("order A7 " + strings.Join(entries, " ")); !errors.Is(err, errOrderLines) { return fmt.Errorf("nine lines: got %v", err) } for text, want := range map[string]error{ "stock tent 1000": nil, "stock tent 1001": errQuantity, "stock tent 0": errQuantity, "stock Tent 1": errItem, "order a-1 tent:1": errOrderID, } { if _, err := parseCommand(text); !errors.Is(err, want) { return fmt.Errorf("%q: got %v, want %v", text, err, want) } } return nil } // checkConservation applies random commands and checks that, for every item, // stock plus open reservations equals everything ever stocked. func checkConservation() error { random := rand.New(rand.NewPCG(7, 11)) items := []string{"drill", "lamp", "tent"} l := NewLedger() stocked := make(map[string]int) for step := range 400 { id := fmt.Sprintf("R%d", random.IntN(30)) switch random.IntN(3) { case 0: item, n := items[random.IntN(3)], 1+random.IntN(20) if _, err := l.Stock(item, n); err == nil { stocked[item] += n } case 1: var lines []Line for _, item := range items { if random.IntN(2) == 0 { lines = append(lines, Line{item, 1 + random.IntN(15)}) } } if len(lines) > 0 { _, _ = l.Order(id, lines) } case 2: _ = l.Cancel(id) } for _, item := range items { total := l.stock[item] for _, o := range l.orders { for _, line := range o.lines { if !o.cancelled && line.Item == item { total += line.Quantity } } } if total != stocked[item] { return fmt.Errorf("step %d: %s stock and reservations add up to %d, not %d", step, item, total, stocked[item]) } } } return nil } func checkRun() error { input := "stock tent 5\nstock drill 2\n\norder A1 tent:2 drill:1\norder A1 drill:1 tent:2\n" + "order A2 tent:4\ncancel A1\nreport" want := "Stocked tent: 5\nStocked drill: 2\nReserved A1\nReplayed A1\n" + "Line 6: order A2: not enough tent: have 3, need 4\nCancelled A1\n" + `{"stock":{"drill":2,"tent":5},"orders":{"A1":"cancelled"}}` + "\n" var out strings.Builder if err := run(context.Background(), strings.NewReader(input), &out); err != nil { return err } if out.String() != want { return fmt.Errorf("unexpected transcript: %q", out.String()) } if err := run(context.Background(), strings.NewReader("report"), brokenWriter{}); !errors.Is(err, errClosed) { return fmt.Errorf("write failure: got %v", err) } ctx, cancel := context.WithCancel(context.Background()) cancel() out.Reset() if err := run(ctx, strings.NewReader("report"), &out); !errors.Is(err, context.Canceled) || out.Len() != 0 { return fmt.Errorf("cancelled run: got %v and %q", err, out.String()) } return nil } func checkLimits() error { exact := "report" + strings.Repeat(" ", maxLineBytes-len("report")) for _, input := range []string{exact, exact + "\n", strings.Repeat("report\n", maxCommands)} { if err := run(context.Background(), strings.NewReader(input), io.Discard); err != nil { return fmt.Errorf("input at the limit was rejected: %v", err) } } for input, want := range map[string]error{ "report\n" + exact + " ": errLineTooLong, "report\n" + exact + " \nreport": errLineTooLong, strings.Repeat("report\n", maxCommands+1): errTooManyCommands, } { var out strings.Builder err := run(context.Background(), strings.NewReader(input), &out) if !errors.Is(err, want) || out.Len() != 0 { return fmt.Errorf("input past a limit: got %v and %d bytes of output", err, out.Len()) } } return nil } func checkPool() error { numbers := make([]int, 20) for i := range numbers { numbers[i] = i } for _, workers := range []int{0, 1, 3, 50} { squares, err := mapConcurrent(context.Background(), numbers, workers, func(n int) int { return n * n }) if err != nil || len(squares) != len(numbers) { return fmt.Errorf("%d workers: got %v, %v", workers, squares, err) } for i, square := range squares { if square != i*i { return fmt.Errorf("%d workers: result %d is %d", workers, i, square) } } } if results, err := mapConcurrent(context.Background(), []int{}, 4, func(n int) int { return n }); err != nil || len(results) != 0 { return fmt.Errorf("empty input: got %v, %v", results, err) } return nil } package main import ( "errors" "fmt" ) // Limits that bound every input before it can change the ledger. const ( maxQuantity = 1000 // per stock command or order line maxStock = 10000 // per item, at any time maxOrderLines = 8 maxLineBytes = 200 maxCommands = 1000 ) var ( errItem = errors.New("item names use 1-20 lowercase letters, digits or hyphens") errOrderID = errors.New("order IDs use 1-12 letters or digits") errQuantity = errors.New("quantity must be 1-1000") errDuplicateItem = errors.New("item is listed twice") errOrderLines = errors.New("orders take 1-8 lines") errCapacity = errors.New("stock would exceed 10000") errConflict = errors.New("order ID reused with different lines") errUnknownOrder = errors.New("order not found") errCancelled = errors.New("order is cancelled") errLineTooLong = errors.New("line is longer than 200 bytes") errTooManyCommands = errors.New("input has more than 1000 commands") ) // Line is one item and quantity in a stock command or an order. type Line struct { Item string Quantity int } // ShortageError reports the first item an order could not reserve. type ShortageError struct { Item string Have int Need int } func (e *ShortageError) Error() string { return fmt.Sprintf("not enough %s: have %d, need %d", e.Item, e.Have, e.Need) } package main import ( "cmp" "errors" "fmt" "slices" "strconv" "strings" ) // Command is one parsed input line. type Command struct { Verb string ID string // the order ID, for order and cancel Lines []Line // one line for stock, sorted by item for order } func validItem(name string) bool { if len(name) < 1 || len(name) > 20 { return false } for _, r := range name { if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') { return false } } return true } func validOrderID(id string) bool { if len(id) < 1 || len(id) > 12 { return false } for _, r := range id { if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9') { return false } } return true } func parseQuantity(text string) (int, error) { n, err := strconv.Atoi(text) if err != nil || n < 1 || n > maxQuantity { return 0, errQuantity } return n, nil } // parseOrder reports every bad entry at once, joined into one error. func parseOrder(id string, entries []string) (Command, error) { if !validOrderID(id) { return Command{}, fmt.Errorf("%q: %w", id, errOrderID) } if len(entries) < 1 || len(entries) > maxOrderLines { return Command{}, fmt.Errorf("order %s: %w", id, errOrderLines) } var problems []error seen := make(map[string]bool) lines := make([]Line, 0, len(entries)) for _, entry := range entries { item, quantity, ok := strings.Cut(entry, ":") if !ok { problems = append(problems, fmt.Errorf("%q: use ITEM:QUANTITY", entry)) continue } if !validItem(item) { problems = append(problems, fmt.Errorf("%q: %w", item, errItem)) continue } if seen[item] { problems = append(problems, fmt.Errorf("%q: %w", item, errDuplicateItem)) continue } seen[item] = true n, err := parseQuantity(quantity) if err != nil { problems = append(problems, fmt.Errorf("%q: %w", item, err)) continue } lines = append(lines, Line{Item: item, Quantity: n}) } if err := errors.Join(problems...); err != nil { return Command{}, fmt.Errorf("order %s: %w", id, err) } // Sorting makes the line order irrelevant, so a reordered retry still matches. slices.SortFunc(lines, func(a, b Line) int { return cmp.Compare(a.Item, b.Item) }) return Command{Verb: "order", ID: id, Lines: lines}, nil } func parseCommand(text string) (Command, error) { fields := strings.Fields(text) verb, args := fields[0], fields[1:] switch verb { case "stock": if len(args) != 2 { return Command{}, errors.New("use stock ITEM QUANTITY") } if !validItem(args[0]) { return Command{}, fmt.Errorf("%q: %w", args[0], errItem) } n, err := parseQuantity(args[1]) if err != nil { return Command{}, err } return Command{Verb: verb, Lines: []Line{{Item: args[0], Quantity: n}}}, nil case "order": if len(args) == 0 { return Command{}, errors.New("use order ID ITEM:QUANTITY ...") } return parseOrder(args[0], args[1:]) case "cancel": if len(args) != 1 || !validOrderID(args[0]) { return Command{}, errors.New("use cancel ID") } return Command{Verb: verb, ID: args[0]}, nil case "report": if len(args) != 0 { return Command{}, errors.New("report takes no arguments") } return Command{Verb: verb}, nil default: return Command{}, fmt.Errorf("unknown command %q", verb) } } package main import ( "fmt" "iter" "maps" "slices" ) type order struct { lines []Line cancelled bool } // Ledger tracks stock and the orders that reserved it. Every method either // applies its whole change or returns an error and changes nothing. type Ledger struct { stock map[string]int orders map[string]order } func NewLedger() *Ledger { return &Ledger{stock: make(map[string]int), orders: make(map[string]order)} } // addStock returns have+n, or errCapacity if the sum would pass maxStock. // Comparing with maxStock-have cannot overflow, unlike computing have+n first. func addStock(have, n int) (int, error) { if n > maxStock-have { return 0, errCapacity } return have + n, nil } // Stock adds quantity to an item and returns its new total. func (l *Ledger) Stock(item string, quantity int) (int, error) { total, err := addStock(l.stock[item], quantity) if err != nil { return 0, fmt.Errorf("stock %s: %w", item, err) } l.stock[item] = total return total, nil } type Outcome int const ( Reserved Outcome = iota Replayed ) // Order reserves every line or none. Sending the same order ID with the same // lines again is a retry: it is recognized and reserves nothing more. func (l *Ledger) Order(id string, lines []Line) (Outcome, error) { if previous, exists := l.orders[id]; exists { if previous.cancelled { return 0, fmt.Errorf("order %s: %w", id, errCancelled) } if !slices.Equal(previous.lines, lines) { return 0, fmt.Errorf("order %s: %w", id, errConflict) } return Replayed, nil } staged := maps.Clone(l.stock) for _, line := range lines { have := staged[line.Item] if line.Quantity > have { return 0, fmt.Errorf("order %s: %w", id, &ShortageError{Item: line.Item, Have: have, Need: line.Quantity}) } staged[line.Item] = have - line.Quantity } l.stock = staged l.orders[id] = order{lines: slices.Clone(lines)} return Reserved, nil } // Cancel returns an open order's stock. It fails without changes if that // would take any item past maxStock. func (l *Ledger) Cancel(id string) error { previous, exists := l.orders[id] if !exists { return fmt.Errorf("order %s: %w", id, errUnknownOrder) } if previous.cancelled { return fmt.Errorf("order %s: %w", id, errCancelled) } staged := maps.Clone(l.stock) for _, line := range previous.lines { total, err := addStock(staged[line.Item], line.Quantity) if err != nil { return fmt.Errorf("cancel %s: %s: %w", id, line.Item, err) } staged[line.Item] = total } l.stock = staged previous.cancelled = true l.orders[id] = previous return nil } // Items yields each item and its quantity in name order. func (l *Ledger) Items() iter.Seq2[string, int] { return func(yield func(string, int) bool) { for _, item := range slices.Sorted(maps.Keys(l.stock)) { if !yield(item, l.stock[item]) { return } } } } // Snapshot is the ledger's state in a form encoding/json writes canonically: // map keys come out sorted, so equal ledgers produce identical bytes. type Snapshot struct { Stock map[string]int `json:"stock"` Orders map[string]string `json:"orders"` } func (l *Ledger) Snapshot() Snapshot { orders := make(map[string]string, len(l.orders)) for id, o := range l.orders { orders[id] = "open" if o.cancelled { orders[id] = "cancelled" } } return Snapshot{Stock: maps.Clone(l.stock), Orders: orders} } package main import ( "context" "sync" ) // mapConcurrent applies f to every item on up to workers goroutines and // returns the results in input order. If ctx is cancelled first, it returns // ctx.Err() and no results. func mapConcurrent[T, R any](ctx context.Context, items []T, workers int, f func(T) R) ([]R, error) { workers = max(1, min(workers, len(items))) results := make([]R, len(items)) jobs := make(chan int) var wg sync.WaitGroup for range workers { wg.Add(1) go func() { defer wg.Done() for i := range jobs { results[i] = f(items[i]) // each index has exactly one writer } }() } send: for i := range items { select { case jobs <- i: case <-ctx.Done(): break send } } close(jobs) wg.Wait() if err := ctx.Err(); err != nil { return nil, err } return results, nil } package main import ( "bufio" "context" "encoding/json" "errors" "fmt" "io" "iter" "strings" ) const workers = 4 type numbered struct { line int text string } type parsed struct { line int cmd Command err error } // numberedLines yields every line with its 1-based number. Check // scanner.Err after the loop. func numberedLines(scanner *bufio.Scanner) iter.Seq2[int, string] { return func(yield func(int, string) bool) { for number := 1; scanner.Scan(); number++ { if !yield(number, scanner.Text()) { return } } } } // readCommands reads all input before anything runs, so input that breaks a // limit is rejected as a whole. func readCommands(r io.Reader) ([]numbered, error) { scanner := bufio.NewScanner(r) // A scanner returns lines shorter than its buffer, with or without a final // newline. Both the initial capacity and the maximum count, so setting // both to one byte over the limit enforces the limit exactly. scanner.Buffer(make([]byte, 0, maxLineBytes+1), maxLineBytes+1) var input []numbered last := 0 for number, text := range numberedLines(scanner) { last = number text = strings.TrimSpace(text) if text == "" { continue } if len(input) == maxCommands { return nil, fmt.Errorf("line %d: %w", number, errTooManyCommands) } input = append(input, numbered{line: number, text: text}) } if err := scanner.Err(); err != nil { if errors.Is(err, bufio.ErrTooLong) { return nil, fmt.Errorf("line %d: %w", last+1, errLineTooLong) } return nil, err } return input, nil } func execute(l *Ledger, cmd Command) (string, error) { switch cmd.Verb { case "stock": line := cmd.Lines[0] total, err := l.Stock(line.Item, line.Quantity) if err != nil { return "", err } return fmt.Sprintf("Stocked %s: %d", line.Item, total), nil case "order": outcome, err := l.Order(cmd.ID, cmd.Lines) if err != nil { return "", err } if outcome == Replayed { return "Replayed " + cmd.ID, nil } return "Reserved " + cmd.ID, nil case "cancel": if err := l.Cancel(cmd.ID); err != nil { return "", err } return "Cancelled " + cmd.ID, nil case "report": data, err := json.Marshal(l.Snapshot()) if err != nil { return "", err } return string(data), nil default: return "", fmt.Errorf("unknown command %q", cmd.Verb) } } // run parses every command concurrently, then applies them one at a time in // input order. Rejected commands are reported and skipped. Read, write and // cancellation failures end the run. func run(ctx context.Context, r io.Reader, w io.Writer) (err error) { input, err := readCommands(r) if err != nil { return fmt.Errorf("read input: %w", err) } commands, err := mapConcurrent(ctx, input, workers, func(n numbered) parsed { cmd, err := parseCommand(n.text) return parsed{line: n.line, cmd: cmd, err: err} }) if err != nil { return err } out := bufio.NewWriter(w) defer func() { if flushErr := out.Flush(); flushErr != nil && err == nil { err = fmt.Errorf("write output: %w", flushErr) } }() ledger := NewLedger() for _, p := range commands { text, cmdErr := "", p.err if cmdErr == nil { text, cmdErr = execute(ledger, p.cmd) } if cmdErr != nil { // errors.Join separates problems with newlines; keep one line per command. text = fmt.Sprintf("Line %d: %s", p.line, strings.ReplaceAll(cmdErr.Error(), "\n", "; ")) } if _, err := fmt.Fprintln(out, text); err != nil { return fmt.Errorf("write output: %w", err) } } return nil }
Text
Order ledger checks passed
Exercise

Break the atomic commit

In ledger.go, in Order, change staged := maps.Clone(l.stock) to staged := l.stock. Run the checks. Read the failure, explain which promise broke and why the check noticed, then restore the line.

Hint 1: the idea

Without the copy, every staged change goes straight into the real stock, so a line reserved before a later line fails stays reserved.

Hint 2: a first step

Find the first order in checkOrders: it asks for a drill and then for more tents than there are.

Worked solution

The checks fail with partial order: drill stock is 0 after a rejected order. The order for one drill and six tents reserved the drill directly in l.stock, then failed on the tents and returned the error. The real map was already changed, and nothing undid it. checkOrders checks the drill stock right after the rejection, so it sees the missing unit. The conservation check would also catch it, a few random steps later.

Every guarantee has a mutation

The course's tooling breaks the project in nine ways, listed in mutations.json next to the project, and requires both go test and the browser check to fail for each. Try a few yourself, one at a time, predicting the failing check before you run:

  • In parse.go, replace the slices.SortFunc line with one that keeps the original order. A reordered retry now conflicts.
  • In ledger.go, change line.Quantity > have to >=. Taking the exact remaining stock fails.
  • In pool.go, change the final ctx.Err() check so it never returns the error. A cancelled run now prints output.
  • In app.go, replace the deferred err = fmt.Errorf(...) with _ = flushErr. A failed write is reported as success.
Local checks add the race detector

The browser runs Go on one thread, so it cannot observe two goroutines touching the same memory at once. The downloaded project's README runs go test -race ., which instruments every memory access and fails if the worker pool, or any later change to it, ever races.

Was this article helpful?

Your response is saved on this device.