Zero2Scale

Null, state and data bugs: if a state is wrong, make it impossible to write

21 min read


An online shop keeps its orders in a struct like this:

type Order struct {
	Paid       bool
	Shipped    bool
	Cancelled  bool
	PaidAt     time.Time
	TrackingNo string
}

The list of orders to ship selects the orders where o.Paid && !o.Shipped. One day someone writes a handler that cancels an order. It sets o.Cancelled = true but does not change Paid. So an order that the customer cancelled appears in the list of orders to ship, and the warehouse packs it and sends it.

The map of software bugs puts this kind of bug in group 2: null, state and data. The calculation is correct, but the data it works on is not what the code expects. The previous article looked at group 1 and found that those bugs sit at the edges of numbers. This article looks at group 2. The question is how "impossible" data gets into a system.

These bugs are states that nobody thought about

Count the states. Three bools combine in 8 ways, but the business has only 4 states: waiting for payment, paid, shipped and cancelled. Of the other 4 combinations, some mean nothing, such as shipped but not paid. Others are the same state written in two ways, such as cancelled with Paid set to true and cancelled with Paid set to false. That count does not include a zero PaidAt while Paid is true, or a TrackingNo on an order that has not shipped.

The short answer of this article is that group 2 bugs live in the gap between two numbers:

  1. The number of states that the type allows.
  2. The number of states that the code really handles.

Every state that the type allows but the code does not expect is a bug. It waits only for one line of code that creates that state. The previous article said that group 1 bugs sit at the edges of numbers. Group 2 bugs also sit at an edge, but it is the edge of all the states the data can be in.

So there are two ways to fix them. The first way is to make the gap smaller, so that the type accepts only correct states. The second way is to give each piece of data one owner, so that no other code can quietly create a new state. The rest of this article goes through what opens the gap and what closes it.

nil is a state that every pointer carries

Every pointer, map, slice and interface in Go carries one extra state: nil. The type does not say which values can be nil and which cannot. Tony Hoare added the null reference to the ALGOL W language in 1965. In a 2009 talk he said that he added it because it was easy to implement, and he called it his billion-dollar mistake.

Go has three common nil traps:

type User struct {
	Name    string
	Profile *Profile // nil for users who signed up before profiles existed
}

func bio(u User) string { return u.Profile.Bio }

type NotFound struct{ ID string }

func (e *NotFound) Error() string { return "not found: " + e.ID }

func find(id string) error {
	var err *NotFound
	if id == "" {
		err = &NotFound{ID: id}
	}
	return err // returns a nil *NotFound inside an error
}

func main() {
	var hits map[string]int
	hits["/posts"]++ // trap 1: writing to a nil map

	fmt.Println(bio(User{Name: "old user"})) // trap 2: a nil pointer

	fmt.Println(find("42") == nil) // trap 3: an interface with nil inside
}

When each trap runs on its own, the output is:

map: panic: assignment to entry in nil map
pointer: panic: runtime error: invalid memory address or nil pointer dereference
find("42") == nil: false
err = <nil>

The third trap is the strangest. find("42") finds no error, but the result is not equal to nil, even though it prints as <nil>. The Go FAQ explains that an interface holds two things: a type and a value. In this example, err has the type *NotFound and the value nil. An interface that holds a type is not equal to nil. So every caller of find thinks that an error happened. The fix is to write return nil when there is no error.

staticcheck, which comes with golangci-lint 2.15.0, catches two of the three traps:

nil/main.go:20:6: SA4023(related information): g2/nil.find never returns a nil interface value (staticcheck)
nil/main.go:40:3: SA5000: assignment to nil map (staticcheck)
nil/main.go:46:38: SA4023: this comparison is never true (staticcheck)

It does not catch u.Profile.Bio. The nil comes from one function and the crash happens in another, so a tool must follow the value across functions to see it. Uber built NilAway for this job and released it as open source in 2023. Uber's blog post says that one service logged more than 3,000 nil panics a day in production. After the team fixed what NilAway found, the number went to zero. The cost is less than 5% extra build time. Its README warns that the project is under active development and can report false positives.

In languages where the type says whether a value can be null, such as String? in Kotlin or Option<T> in Rust, the compiler removes trap 2. Go does not have this, so we depend on linters and on design discipline. The next sections cover that discipline.

nil does not only break small services. On 12 June 2025, Google Cloud had a global outage that lasted several hours. Google's report says that new code in Service Control, the component that checks API policies, was deployed on 29 May. Nothing called that code path until 12 June. On that day, someone inserted a policy with unintended blank fields. The policy was replicated to every region within seconds. The blank fields sent the code into a null pointer, and Service Control went into a crash loop in every region. The report says that this code did not have appropriate error handling and was not protected by a feature flag.

A zero value looks like a value someone chose

Go has no uninitialized variables. Every variable starts at its zero value, such as 0, "", false or time.Time{}. The benefit is that there are no garbage values. The cost is that we cannot tell whether 0 means "the price is zero" or "nobody set the price".

type ProductInput struct {
	Name  string `json:"name"`
	Price int64  `json:"price"` // in satang
}

body := []byte(`{"name": "Go book", "prise": 35000}`) // the client misspelled price

var p ProductInput
err := json.Unmarshal(body, &p)
fmt.Printf("Unmarshal: err=%v price=%d\n", err, p.Price)
Unmarshal: err=<nil> price=0

There is no error. A product with a price of 0 baht is now in the system. encoding/json skips fields that it does not know, and a missing field gets its zero value. Both happen silently.

The blank fields in the Google Cloud policy are the same kind of bug. Blank values got in because nothing said "a blank value is not allowed". They then broke the system far from the place where they came in.

Check once at the entrance, then trust the data inside

A better fix than spreading if p.Price == 0 across the system is to turn raw data into a type that is always valid, once, at the entrance. Alexis King named this idea in a 2019 article: Parse, don't validate. Validation checks the data and returns the same value, so the code that receives the value cannot know whether it was checked. Parsing checks the data and returns a new type, and the type itself says that the check happened.

// Product can only be made by ParseProduct, so every Product is valid.
type Product struct {
	name  string
	price int64
}

func ParseProduct(body []byte) (Product, error) {
	dec := json.NewDecoder(bytes.NewReader(body))
	dec.DisallowUnknownFields() // a misspelled field name must be an error
	var in ProductInput
	if err := dec.Decode(&in); err != nil {
		return Product{}, fmt.Errorf("decoding product: %w", err)
	}
	name := strings.TrimSpace(in.Name)
	if name == "" {
		return Product{}, ErrNoName
	}
	if in.Price <= 0 {
		return Product{}, ErrNoPrice
	}
	return Product{name: name, price: in.Price}, nil
}
ParseProduct: decoding product: json: unknown field "prise"
ParseProduct: price must be greater than zero
ParseProduct: Go book 35000 <nil>

The fields of Product start with a lowercase letter, so other packages cannot build an invalid Product. A function that receives a Product does not need to check the price again.

This website uses the same idea for its contact form. contact.Validate in internal/core/contact takes a Form, which is "the data as the user typed it", and returns a Message, which is "the data after checks and normalization". contact.Email, which builds the email, accepts only a Message. So it can never get an empty name or an email address with a hidden newline. All of this is in the core, which is pure functions as described in the FCIS article, so simple table tests cover it.

If a state is wrong, make it impossible to write

A good entrance stops bad data from outside. But the Order at the start of this article broke because of code inside the system. The handler that forgot to change Paid did not receive bad data from anyone. It created a wrong state itself, because the type allowed it.

Yaron Minsky of Jane Street named this principle in his Effective ML lecture in 2010, and he wrote it down again in a 2011 blog post: make illegal states unrepresentable. You design the type so that a wrong state cannot be written at all. His example is a connection that has a state field and several optional fields. He changes it so that each state carries its own data. The "connected" state has a session ID, and the "disconnected" state has the time of the disconnect.

ML, Rust and Kotlin have sum types for this. Go does not, but an interface with an unexported method comes close:

// State is Pending, Paid, Shipped or Cancelled.
// The method is unexported, so no other package can add a state.
//
//sumtype:decl
type State interface{ isState() }

type Pending struct{}
type Paid struct{ At time.Time }
type Shipped struct {
	PaidAt     time.Time
	TrackingNo string
}
type Cancelled struct{ Reason string }

func (Pending) isState()   {}
func (Paid) isState()      {}
func (Shipped) isState()   {}
func (Cancelled) isState() {}

Count again. State now has exactly 4 forms, the same as the business. "Shipped but not paid" cannot be written. TrackingNo exists only in Shipped, and the payment time exists only in Paid and Shipped.

Go does not check that a type switch covers every state. The gochecksumtype linter in golangci-lint does, when the interface has the line //sumtype:decl. If a switch forgets Cancelled, the output is:

order/order.go:45:2: exhaustiveness check failed for sum type "State" (from order/order.go:13:6): missing cases for Cancelled (gochecksumtype)

This website also has a place where Go cannot enforce everything. contact.Result has Outcome, Message and Errors in one struct. Its comment says that Message is set when the outcome is Accepted and Errors is set when it is Rejected. So the type still allows an Accepted result that has Errors. What keeps it safe is that only one function builds a Result: contact.Validate, and table tests cover it. This is an acceptable trade when there are few states and only one place builds them.

Every state change goes through one gate

A good type says which states can exist. It does not say which state can change into which. A cancelled order must not accept a payment. So the AGENTS.md file of this repository already has a rule for phase 2: status changes go through pure state-machine functions.

var ErrInvalidTransition = errors.New("invalid transition")

// Next is the only place that decides the next state.
func Next(s State, e Event) (State, error) {
	switch s := s.(type) {
	case Pending:
		switch e := e.(type) {
		case Pay:
			return Paid{At: e.At}, nil
		case Cancel:
			return Cancelled{Reason: e.Reason}, nil
		case Ship:
			// not paid yet, so it cannot ship
		}
	case Paid:
		switch e := e.(type) {
		case Ship:
			return Shipped{PaidAt: s.At, TrackingNo: e.TrackingNo}, nil
		case Cancel:
			return Cancelled{Reason: e.Reason}, nil
		case Pay:
			// already paid
		}
	case Shipped, Cancelled:
		// final states
	}
	return s, fmt.Errorf("%w: %T on %T", ErrInvalidTransition, e, s)
}

Event is a sum type in the same way as State: Pay, Ship or Cancel. Look at case Ship: under Pending. It has no code, but it must be there, because gochecksumtype makes every pair of state and event a deliberate decision. When someone adds a Refund event, the linter points to every place that needs a new decision:

order/order.go:47:3: exhaustiveness check failed for sum type "Event" (from order/order.go:31:6): missing cases for Refund (gochecksumtype)
order/order.go:56:3: exhaustiveness check failed for sum type "Event" (from order/order.go:31:6): missing cases for Refund (gochecksumtype)

When every state change is in one pure function, we can test every pair. 4 states times 3 events is 12 pairs. 4 pairs are valid, and the other 8 must return ErrInvalidTransition.

func TestNextEveryPair(t *testing.T) {
	at := time.Date(2026, 12, 3, 10, 0, 0, 0, time.UTC)
	states := []State{Pending{}, Paid{At: at}, Shipped{PaidAt: at, TrackingNo: "TH1"}, Cancelled{Reason: "x"}}
	events := []Event{Pay{At: at}, Ship{TrackingNo: "TH1"}, Cancel{Reason: "x"}}

	want := map[string]State{ // every pair not in this table must fail
		"order.Pending+order.Pay":    Paid{At: at},
		"order.Pending+order.Cancel": Cancelled{Reason: "x"},
		"order.Paid+order.Ship":      Shipped{PaidAt: at, TrackingNo: "TH1"},
		"order.Paid+order.Cancel":    Cancelled{Reason: "x"},
	}

	for _, s := range states {
		for _, e := range events {
			key := fmt.Sprintf("%T+%T", s, e)
			t.Run(key, func(t *testing.T) {
				got, err := Next(s, e)
				w, ok := want[key]
				if !ok {
					if !errors.Is(err, ErrInvalidTransition) {
						t.Fatalf("Next(%T, %T) = %v, %v; want ErrInvalidTransition", s, e, got, err)
					}
					return
				}
				if err != nil || got != w {
					t.Fatalf("Next(%T, %T) = %v, %v; want %v", s, e, got, err, w)
				}
			})
		}
	}
}

This test has 12 subtests, and all of them pass. Compare that with the Order that has three bools. Every handler can change its fields, so there is no single place where you could test "every pair".

Each piece of data needs one owner

The second way to close the gap is ownership. Aliasing means that two names point to the same data, so a change through one name also changes what the other name sees. The map of software bugs already showed the append trap. This section shows two more cases.

The first case was so common that Go changed the language. Before Go 1.22, a for loop had one variable for the whole loop:

var ptrs []*int
for _, v := range []int{1, 2, 3} {
	ptrs = append(ptrs, &v) // before Go 1.22, every iteration got the same address
}
for _, p := range ptrs {
	fmt.Print(*p, " ")
}

The same code, run with Go 1.27.4, but with a different go.mod:

go 1.21:
3 3 3
go 1.22:
1 2 3

David Chase and Russ Cox explained this change on the Go blog in 2023, and they used a Let's Encrypt bug as an example. On 29 February 2020, Let's Encrypt found that when a request had several domain names, the CAA check in Boulder checked one domain name several times instead of checking each one. The Go blog explains that the cause was a pointer to a field of the loop variable, spread across several functions, so it was hard to notice. Let's Encrypt estimated that about 3 million certificates were possibly affected, and it planned to revoke about 1.7 million certificates that had already been replaced.

The second case is a cache that returns its own slice:

type TagCache struct {
	byPost map[string][]string
}

func (c *TagCache) Tags(slug string) []string {
	return c.byPost[slug] // returns the same slice that the cache keeps
}

tags := c.Tags("why-bugs-recur")
tags[0] = "FUNDAMENTALS" // the caller only wanted to display it in upper case
fmt.Println(c.byPost["why-bugs-recur"])
[FUNDAMENTALS bugs]

The caller changed the cache without knowing it, and every request after that gets wrong data. With return slices.Clone(c.byPost[slug]), the cache stays [fundamentals bugs], because the caller gets its own copy.

This repository has a worse aliasing rule in AGENTS.md. Fiber reuses buffers, so a string from c.Params belongs to Fiber, not to us. You must call strings.Clone before you use it after the handler returns. The Opengrep rule fiber-ctx-value-escapes in .opengrep/ checks this.

Stale state is also an ownership problem: a copy in a browser or a cache that nobody updates any more. The article on SSE and Datastar is about making the backend the only owner of state. That is the same answer at the level of architecture.

The same name, a different variable

Shadowing means declaring a new variable with the same name as an existing variable, in an inner scope. In Go this happens easily, because := declares and assigns in one step.

func perPage(raw string) (int, error) {
	n := 10
	if raw != "" {
		n, err := strconv.Atoi(raw) // := creates a new n inside the if
		if err != nil {
			return 0, err
		}
		fmt.Println("inside the if, n =", n)
	}
	return n, nil // the outer n is still 10
}
inside the if, n = 25
perPage("25") = 10 <nil>

Inside the if, everything looks correct, but the parsed value is lost when the block ends. go vet has an analyzer called shadow for this, but it is not on by default. In golangci-lint, turn it on with the govet setting enable: [shadow]:

shadow/main.go:11:3: shadow: declaration of "n" shadows declaration at line 9 (govet)

Write the bug that bit you as a rule

slices.Clone fixes the TagCache bug, but the next person who writes a cache can forget it again. This pattern is a good fit for an Opengrep rule, as the Opengrep article explains: a method that returns a slice or a map field of its receiver directly.

rules:
  - id: internal-slice-escapes
    languages: [go]
    severity: WARNING
    message: >-
      $T.$M returns the slice or map that $T keeps inside. The caller can change
      $T's data through it. Return slices.Clone or maps.Clone instead.
    patterns:
      - pattern-either:
          - pattern-inside: |
              func ($R *$T) $M(...) []$E { ... }
          - pattern-inside: |
              func ($R *$T) $M(...) map[$K]$V { ... }
      - pattern-either:
          - pattern: return $R.$F
          - pattern: return $R.$F[$I]

The fixture file has // ruleid: internal-slice-escapes above Tags, All and Index, which return a field directly. It has // ok: internal-slice-escapes above the versions that use slices.Clone and maps.Clone, and above a method that returns len(c.all). opengrep test reports 1/1: ✓ All tests passed. A scan of internal and cmd in this repository finds nothing. This rule was run with Opengrep 1.26.0.

The rule catches only the direct pattern. If someone writes s := c.all; return s, the rule does not see it. That is the limit of a pattern rule: it does not follow values through variables. But it catches the most common form within seconds, on every commit.

Agents fix a panic with an if

When a test fails because of a nil pointer, the fastest fix is to add if u.Profile == nil { return "" } where it crashed. The panic goes away, the test passes, and the diff is small. This is often the first fix an agent proposes, because it is the smallest change that makes the test pass.

But this fix answers the wrong question. The right question is "why can Profile be nil, and should it be?" If every user must have a profile, fix it at the entrance: give old users an empty profile when they are loaded, or change the type so that it is not a pointer. If some users really have no profile, make every place that uses Profile handle that, not only the place that happened to crash.

The same thing happens with state. An agent that gets a ticket to "add refunds" often adds Refunded bool to Order, because that is the smallest diff. The number of states the type allows grows from 8 to 16. When you read code that an agent wrote, as the article on reading code recommends, ask two questions. Does this diff add states that the type allows? Does this diff give any piece of data a new owner? If the code already uses a sum type and Next, adding Refund makes gochecksumtype point to every decision that must be made, for people and for agents.

A table to keep

Bug Where the gap is Why it recurs What closes the gap
nil dereference Every pointer, map and interface carries nil The type does not say which values can be nil staticcheck SA5000 and SA4023, NilAway, and no pointer when one is not needed
An interface with nil inside The interface's type is not nil It prints as <nil> but does not compare equal Write return nil directly, and staticcheck SA4023
A zero value that looks real 0 and "not set" look the same encoding/json skips what it does not know, silently Parse at the entrance, DisallowUnknownFields, and types that only a parser can build
An impossible state Several bools combine into more states than exist A new field is the smallest diff A sum type with a closed interface, and gochecksumtype
A state change that should not happen Every handler can change fields No single place holds the rules Next as a pure function, and a test for every pair
Aliasing Two names point to the same data The code does not show who holds the data Go 1.22 or later, slices.Clone, and an Opengrep rule
Shadowing := in an inner scope Inside the block, everything looks correct The govet analyzer shadow

What to do differently

Every time you add a field or a type, count two numbers: how many states the type allows, and how many states the code handles. If the numbers are not equal, ask whether a type can make them equal. If it cannot, ask where the extra states can be created, and what guards them. And every time a slice, a map or a pointer leaves a function, ask who owns it now.

The next article in this series looks at group 3: error handling. The Google Cloud report above points there too. The code that caused the outage did not only hit a null pointer. It also had no appropriate error handling.

References