Zero2Scale

A map of software bugs: every kind, sorted into groups

20 min read


In the article on reading code, the example function had this line:

if user.role == "admin" or "editor":

The condition is always true, because a non-empty string is true in Python. Any user can delete any post. It is a small bug, but it is not a new one. It has a name, people have written it thousands of times before, and there are tools that catch it before anyone runs the code.

That is the point of this article. Bugs feel random when you meet them one at a time, but there aren't infinitely many kinds. Most bugs belong to a few dozen kinds that have been named, studied, and, for many of them, automated away. If you know the map, you can ask a better question than "why did this break?". You can ask "which group is this, and why didn't the tool for that group catch it?"

This article is the map. The next articles in the series take one group at a time: why it keeps happening, and how to stop it with the type system, the compiler, linters, Opengrep rules, and tests.

How to group bugs

There is no single correct taxonomy. Researchers and standards bodies have tried several:

  • CWE (Common Weakness Enumeration) from MITRE lists close to a thousand kinds of weakness, mostly security related, each with an ID such as CWE-79 (XSS) or CWE-476 (NULL pointer dereference). It is the vocabulary security tools use in their reports.
  • Orthogonal Defect Classification (ODC), from IBM in the early 1990s, sorts defects by what the fix changed: assignment, checking, algorithm, interface, timing, and so on.
  • Textbooks on testing, such as Boris Beizer's, have their own lists.

I don't follow any one of them exactly. I sort by one question that is useful to a working programmer: where was the wrong idea? Was it in a calculation, in the data, in how two parts talk to each other, in time, or in the requirements themselves? Each answer points to a different tool.

The twelve groups:

  1. Logic and arithmetic
  2. Null, state, and data
  3. Error handling
  4. Resources and memory
  5. Concurrency
  6. Security
  7. Interfaces and contracts
  8. Text, encoding, and locale
  9. Time and dates
  10. Performance
  11. Configuration, build, and deployment
  12. Requirements and design

1. Logic and arithmetic

The code runs and does exactly what it says. What it says is wrong.

  • Off-by-one (fencepost) errors: <= where < was meant, a loop that skips the last item, a page count that is one short.
  • Wrong boolean logic: and vs or, a negation applied to the wrong half after De Morgan, the "admin" or "editor" above.
  • Operator precedence: a & mask == 0 in C means a & (mask == 0).
  • Integer overflow, underflow, and truncation: adding two large int32s, converting a 64-bit value to 16 bits, unsigned values that wrap below zero.
  • Floating-point mistakes: 0.1 + 0.2 != 0.3, money stored as float64, comparing floats with ==, dividing by zero and getting NaN or Inf instead of an error.
  • Unit mismatches: milliseconds vs seconds, cents vs baht, kilometres vs miles.
  • Copy-paste errors: a duplicated line, a block copied and only half edited, x used where y was meant.
  • Missing cases: a switch that doesn't handle a newly added enum value.
  • Dead or unreachable code: a condition that can never be true, or a statement that never runs.

Real examples: Ariane 5 flight 501 (1996) blew up 37 seconds after launch because a 64-bit float was converted to a 16-bit signed integer that overflowed. NASA lost the Mars Climate Orbiter (1999) because one team's software produced pound-force seconds and another's expected newton-seconds. Apple's "goto fail" bug (2014) was one duplicated line that made the rest of a TLS certificate check unreachable.

if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
    goto fail;
    goto fail;   /* always runs: the check below never happens */
if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
    goto fail;

Where it gets caught: many of these are exactly what linters are good at: always-true conditions, unreachable code, self-assignment, non-exhaustive switches. Overflow and float problems are better prevented by types (int64 minor units for money, a Duration type instead of a bare number). Off-by-one errors are mostly found by tests that check the boundaries.

2. Null, state, and data

The calculation is right, but the data it works on is not what the code assumes.

  • Null/nil dereference: using a pointer, map, or object that is nil. Tony Hoare, who added null references to ALGOL W in 1965, later called it his "billion-dollar mistake".
  • Uninitialized values, and in Go, zero values that quietly mean something (0 for a price that was never set, writing to a nil map panics).
  • Aliasing and shared mutable state: two variables point at the same data, and changing one changes the other by surprise.
  • Stale state: a cached copy that no longer matches the source. The SSE and Datastar article is about this whole group.
  • Invalid state transitions: an order that goes from "cancelled" back to "paid".
  • Shadowing: a new variable with the same name hides the one you meant to set.

Go has a classic aliasing trap with append:

base := make([]int, 3, 10)
a := append(base, 1)
b := append(base, 2) // same backing array as a
fmt.Println(a[3])    // prints 2, not 1

This project has a real one in its AGENTS.md. Fiber reuses its buffers, so a string returned by c.Params("id") can change after the handler returns. Save it in a cache or use it in a goroutine without copying it, and some time later it holds a different request's value. Nothing crashes. The data is just wrong.

Where it gets caught: type systems that make null explicit (Rust's Option, Kotlin's String?) remove null bugs entirely. Go doesn't have that, but tools such as Uber's NilAway and staticcheck catch many of them. Invalid transitions are prevented by modelling the states as types and putting the transitions in one pure function, which is the "state machine" rule in this project.

3. Error handling

The failure was expected. The code just handled it badly.

  • Ignored errors: f.Close() or json.Unmarshal(...) with the error thrown away.
  • Swallowed exceptions: catch (Exception e) {} or except: pass.
  • Comparing errors the wrong way: err == ErrNotFound when the error has been wrapped, so the comparison is always false. Use errors.Is.
  • Losing context: returning the error without saying what you were doing, so the log says only EOF.
  • Partial failure: step 2 of 3 fails and step 1 is not undone. Money leaves one account and doesn't arrive in the other.
  • Wrong layer: a cache miss that becomes a 500, or a panic in library code that should have been an error.
  • Unsafe retries: retrying something that isn't idempotent, so a customer is charged twice.

Error-handling bugs are dangerous because the error path is the path tests rarely run. A 2014 study of failures in distributed systems (Yuan et al., "Simple Testing Can Prevent Most Critical Failures") found that most catastrophic failures came from incorrect handling of errors that the code had already detected, and that many could have been caught by simple checks such as looking for empty catch blocks.

Where it gets caught: errcheck finds ignored errors in Go. errorlint, which this project enables, finds == comparisons on errors that may be wrapped. Empty catch blocks and "TODO: handle error" are easy to write as Opengrep rules. Partial failure needs design: transactions, idempotency keys, and tests that inject failures.

4. Resources and memory

Something was acquired and not released, or released and then used.

  • Leaks: memory, file handles, database connections, HTTP response bodies, goroutines that block forever.
  • Unbounded growth: a cache with no TTL, a queue with no limit, a map that only grows.
  • Memory-safety bugs in C, C++, and unsafe code: buffer overflow, out-of-bounds read, use-after-free, double free, dangling pointers.
  • Stack overflow from recursion without a reliable base case.

Heartbleed (2014) was an out-of-bounds read in OpenSSL: the server trusted a length field sent by the client and returned up to 64 KB of its own memory, which could contain private keys. The CrowdStrike outage in July 2024, which crashed about 8.5 million Windows machines, also ended in an out-of-bounds read: a new content update expected 21 input fields, the sensor supplied only 20, and reading the 21st went past the end of the array.

In Go, the everyday version is smaller:

resp, err := http.Get(url)
if err != nil {
    return err
}
// missing: defer resp.Body.Close()
// each call leaks a connection until the process runs out

Where it gets caught: memory-safe languages remove the whole memory-safety subgroup, which is why both Google and Microsoft have reported that around 70% of their serious security bugs were memory-safety issues. For Go, linters such as bodyclose and sqlclosecheck catch common leaks. In C and C++, compiler sanitizers (AddressSanitizer, LeakSanitizer) and fuzzing catch the rest at run time.

5. Concurrency

Each piece is correct on its own. Running them at the same time is not.

  • Data race: two goroutines or threads access the same memory at once, and at least one writes.
  • Race condition (check-then-act): "if the seat is free, book it" with another request booking in between. TOCTOU (time of check to time of use) is the security version.
  • Lost update: two requests read a balance of 100, each adds 10, both write 110.
  • Deadlock: A waits for B while B waits for A. Livelock and starvation are its cousins.
  • Order violation: code assumes initialization finished before it is used.
  • Loop variable capture: before Go 1.22, every goroutine started in a for loop could see the same, last value of the loop variable.

The Therac-25 radiation machine (1985–87) gave several patients massive overdoses, and some of them died. One of the causes was a race: if the operator edited the treatment settings quickly enough, the machine used a mix of old and new settings.

Concurrency bugs are the hardest group to reproduce. They depend on timing, so they may appear once in ten thousand runs, or only under production load.

Where it gets caught: Rust's ownership rules prevent data races at compile time. Go has a race detector (go test -race), but it only finds races in code that actually runs during the test. Static tools catch patterns such as copying a sync.Mutex by value (go vet does this). Lost updates are prevented in the database with transactions, SELECT ... FOR UPDATE, or a version column.

6. Security

Code that works for honest users and fails for a dishonest one. Most security bugs are another group's bug that an attacker can trigger on purpose.

  • Injection: SQL, OS command, LDAP, template, and log injection. The cause is always the same: data that ends up being treated as code.
  • Cross-site scripting (XSS): user input rendered as HTML or JavaScript. This project's rule "never put user input inside a data-* expression" exists because of this.
  • Path traversal: ../../etc/passwd in a file name.
  • Broken access control: a missing permission check, or IDOR, where changing /orders/123 to /orders/124 shows someone else's order.
  • Secrets in code, weak or home-made cryptography, and predictable random numbers used for tokens.
  • SSRF, unsafe deserialization, open redirects.
  • Regular expression denial of service (ReDoS): a regex that takes exponential time on a crafted input.

Log4Shell (2021) let attackers run code on servers just by getting a string such as ${jndi:ldap://...} into a log message. In July 2019 Cloudflare had a global outage after deploying a single regular expression that backtracked catastrophically and used all the CPU on its servers.

Where it gets caught: this is where static analysis is most mature. gosec, Opengrep, and CodeQL all have rules for injection, weak crypto, and hard-coded secrets. The stronger tools do taint analysis: they follow user input from where it enters (a request parameter) to where it becomes dangerous (a SQL query) and report the path. Access-control bugs are harder, because the tool can't know who is supposed to see what. Those need tests and review.

7. Interfaces and contracts

Each side is correct according to its own idea of the agreement. The two ideas differ.

  • API misuse: arguments in the wrong order, a function that returns a new value but is called as if it changed its argument (strings.ToUpper(s) with the result ignored), a library used in a way it doesn't support.
  • Schema drift: a service renames a JSON field and its clients still read the old one.
  • Serialization surprises: a 64-bit ID that loses precision in JavaScript, omitempty dropping a legitimate zero, a time zone lost in transit.
  • Version mismatches between a library, its dependencies, and the code that calls them.
  • Hidden assumptions: a caller that assumes a list is sorted, or that a function never returns an empty slice.

The CrowdStrike incident fits here too. The bug was an out-of-bounds read, but the cause was a disagreement about the format of a file: how many fields it would contain.

Where it gets caught: types that make the contract explicit (a generated client from an OpenAPI or protobuf schema), contract tests between services, and linters that flag ignored return values. An Opengrep rule is a good way to ban a misuse your team has already been bitten by once.

8. Text, encoding, and locale

Code written by people who mostly tested with English.

  • Bytes vs characters: in UTF-8, each Thai character is 3 bytes. len("สวัสดี") in Go is 18, not 6.
  • Cutting in the middle of a character: s[:10] on Thai text can split a character and produce invalid UTF-8, shown as �.
  • Characters vs what people see: ที่ is three code points (ท, a vowel mark, a tone mark) but one visible unit. Cutting between them leaves a floating tone mark.
  • Locale-dependent behaviour: sorting, upper and lower case (the Turkish dotless i), number and date formats.
  • No spaces between words: Thai search and line breaking can't split on spaces.
  • Normalization: two strings that look the same but are encoded differently, so they don't compare equal.
s := "สวัสดีครับ"
fmt.Println(s[:10])                // "สวั\xe0" — broken text
fmt.Println(string([]rune(s)[:3])) // "สวั" — whole code points

Where it gets caught: mostly by tests with real data in the languages you serve, including emoji and Thai. A few patterns, such as slicing a string by byte index right after reading user input, can be flagged by a custom Opengrep rule.

9. Time and dates

Time looks simple and is full of exceptions.

  • Time zones: storing local time without a zone, comparing times from two zones, a "daily" job that runs at midnight UTC, which is 7 a.m. in Bangkok.
  • Daylight saving: a day with 23 or 25 hours, a local time that happens twice or never.
  • Leap years and leap seconds.
  • Calendar systems: the Thai Buddhist year 2569 is 2026. Parse it as a Gregorian year and you are 543 years in the future.
  • Wall clock vs monotonic clock: measuring a duration with a clock that NTP can move backwards.
  • Range limits: the year 2038 problem for 32-bit Unix timestamps.
  • Hidden now(): code that calls the current time inside a rule, so tests depend on the day they run.

On 31 December 2008, Microsoft's Zune 30 music players froze worldwide. The code that converted days into years went into an infinite loop on day 366 of a leap year.

Where it gets caught: types and conventions (always store UTC, use a time type with a zone, never a bare string) and tests that pass the time in as a parameter. This project's rule that core code must not call time.Now() is enforced by depguard and an architecture test, and it exists because of this group.

10. Performance

The answer is correct. It just arrives too late, or costs too much.

  • N+1 queries: one query for a list, then one more for every row.
  • Accidental quadratic algorithms: a lookup in a list inside a loop over another list.
  • Unnecessary work: building strings with + in a loop, allocating in a hot path, parsing the same template on every request.
  • Missing database indexes.
  • Missing timeouts: one slow dependency ties up every worker.
  • Cache stampede: a popular key expires and a thousand requests rebuild it at the same moment.

Where it gets caught: some patterns are visible statically (a query inside a loop, regexp.MustCompile inside a function that is called per request), and linters such as prealloc or Opengrep rules can flag them. The rest needs measurement: benchmarks, profiles, and query logs.

11. Configuration, build, and deployment

The code is right. What runs in production isn't that code, or isn't configured the way you think.

  • Wrong configuration: a missing environment variable that defaults to something dangerous, a staging URL in production.
  • Feature flag mistakes: an old flag reused for a new meaning.
  • Partial deployment: some servers run the new version and some the old.
  • Dependency problems: an unpinned version that changes under you, a compromised package.
  • Database migrations that lock a big table, or that the old code can't work with during a rolling deploy.
  • "Works on my machine": a case-insensitive filesystem locally and a case-sensitive one in production.

Knight Capital lost about 440 million dollars in 45 minutes in August 2012. A new release went out to seven of its eight servers. The eighth still had old code, and the release reused a flag that, on that server, switched on a long-dead trading function.

Where it gets caught: configuration validated at startup (fail fast instead of running with a bad default), lock files and dependency scanners, and policy checks on infrastructure files. Opengrep and similar tools can scan Dockerfiles, Kubernetes YAML, and Terraform as well as code.

12. Requirements and design

The code does exactly what the specification says, and the specification is wrong.

  • Misunderstood requirements: we built what was written, not what was meant.
  • Missing cases in the requirements: nobody asked what happens on a refund after a partial shipment.
  • Usability bugs: the feature works, but people can't find it or use it wrongly.
  • Design flaws: a model of the domain that can't express a real situation, so every new rule needs a special case.

This group is last because no tool can find it. A linter can't know your customer wanted something else. It is caught only by talking to people, writing examples before code, and reviewing the design. It is also the most expensive group, because the fix is often to rebuild something that works perfectly.

Another way to group: how bugs behave

Programmers have also named bugs by how they behave when you try to fix them:

  • Bohrbug: solid and repeatable. Same input, same failure. The easy kind.
  • Heisenbug: disappears or changes when you try to observe it, for example when you add a log line or attach a debugger. Usually concurrency or uninitialized memory.
  • Mandelbug: the causes are so many and so tangled that the behaviour looks chaotic.
  • Schrödinbug: code that someone reads and realizes could never have worked, after which it stops working.

These names are half a joke, but they're useful. If a bug is a Heisenbug, stop adding print statements and start suspecting groups 2 and 5.

Where each group gets caught

Every group can be found at more than one point. The earlier, the cheaper:

Group Types / compiler Static analysis Tests / fuzzing Run time / production Review / talking
1. Logic and arithmetic Partly Strong Strong Partly
2. Null, state, and data Strong (if the language allows) Good Good
3. Error handling Partly Strong Failure injection Logs
4. Resources and memory Strong (memory-safe languages) Good Fuzzing, sanitizers Monitoring
5. Concurrency Rust only Patterns only Race detector Often found here Design
6. Security Partly Strong (taint analysis) Fuzzing WAF, monitoring Access control
7. Interfaces and contracts Strong (shared schemas) Good Contract tests
8. Text and locale A little Strong (real data)
9. Time and dates Good (time types) A little Strong (time as a parameter)
10. Performance Patterns only Benchmarks Profiling
11. Configuration and deployment Good (infrastructure files) Startup checks Canary deploys
12. Requirements and design Examples User feedback Only here

Two things stand out. First, static analysis covers more of the table than most teams use it for: it is strong in groups 1, 3, and 6, and useful in most of the others. Second, it does almost nothing for group 12. Tools make it cheaper to get the code right. They don't tell you whether you built the right thing.

This project's rules are a list of bug groups

If you read this repository's AGENTS.md again with this map in mind, almost every rule is a decision to prevent one group of bugs once, instead of finding it again and again:

  • "Money is int64 minor units, never float64" prevents part of group 1.
  • "Status changes go through pure state-machine functions" prevents invalid transitions in group 2.
  • "Ctx values are only valid inside the handler, copy them" prevents aliasing in group 2.
  • "A Redis error must never produce a 5xx" prevents the wrong-layer error in group 3.
  • "Every key gets a TTL" prevents unbounded growth in group 4.
  • "Never put user input inside a data-* expression" prevents XSS in group 6.
  • "Core must not call time.Now()" prevents the hidden clock in group 9.

The rules that matter most are the ones a tool enforces: depguard and the architecture test fail the build. A rule that lives only in a document gets forgotten. A rule in the linter is applied to every commit, including commits written by AI.

The series

The next articles take the groups in turn. For each one:

  • why it keeps happening, even to experienced programmers,
  • what the language and type system can prevent by design,
  • which existing tools catch it (go vet, staticcheck, golangci-lint, gosec, errcheck, and their equivalents in other languages),
  • how to write your own Opengrep rule when a bug has bitten your team once, so it can't bite twice,
  • and what still needs tests and review.

Opengrep will appear often. It is an open-source fork of Semgrep, started in 2025, and its rules look like the code they match, so writing a new one takes minutes instead of days. That makes it the natural tool for turning "we were bitten by this once" into "the build fails if anyone writes this again".

Sources