Debugging Failures and Localizing Faults
A bug report is a claim that a system is not behaving as expected. It describes what somebody saw, but it almost never says where in the source code the problem comes from. Getting from the report to the source of the problem is a skill called fault localization.
Debugging differs from writing code in where you start. When you write a function, you know where you are, and the compiler and the tests tell you when you have made a mistake. When you debug, you start from the end of a chain of consequences and work backwards towards a cause that may not immediately be clear. You rarely have a failing test for a reported bug. If a test had caught the problem, it should already have been fixed.
Debugging is a process with four steps, each of which you can learn:
- reproduce the failure,
- localize the fault,
- fix it, and
- validate that the fix worked without introducing new defects.
A Parcel That Was Never Delivered
Our running example continues.
A customer reports that the tracker showed one of their parcels as delivered, but it never arrived.
The report describes something a user saw on their screen. Between that screen and the source of the problem are the display, the tracker, an adapter, and a carrier's web service, and the fault could be in any of them. It could also be in none of them. The parcel may have been delivered to a neighbour, and the software may be reporting exactly what the carrier said.
Failures and Faults
Failure and fault are often used interchangeably, but it is useful to distinguish them, because debugging moves from one to the other.
A failure is the incorrect behaviour that can be observed from outside the program, such as a wrong answer or a crash. The failure is what a user reports.
A fault is the defect in the code that caused the failure, such as a wrong comparison or a missing case. The fault is what you eventually fix.
The two can be both temporally and spatially distant. A fault can sit in a codebase for years without executing. When it does execute, it leaves the program in an incorrect state. That state is usually invisible. Other code might correct it automatically, or it might pass through several layers of abstraction before becoming visible. Debugging follows this chain backwards, from the failure you can see to the fault you can fix, and the longer the chain, the harder the process.
There might also be no fault at all. A "bug" report may describe intended behaviour that the user did not expect, or come from a misunderstanding of what the software promises. The problem may also be in configuration or data rather than in code. The first step includes establishing that the failure is real, and deciding who on the technical team should handle it.
Reproduction
The first task when fixing a bug is to reproduce it. Some bugs can be localized from a user's (often vague) description, but most cannot. To reproduce a bug is to trigger it reliably in your own environment. Once you've reproduced a bug, you can examine the code execution in a debugger, and write a test that encodes the reproduction and expects() the non-faulty behaviour. Reproduction is a precondition to all the rest of this chapter: without reproduction, you cannot tell whether a change fixed the bug or whether the symptom just did not appear that time.
A useful reproduction has two properties: determinism and minimality.
Deterministic. A failure that appears on one run in five is much harder to fix than one that appears every time, because every later experiment gives an unreliable answer. If the failure does not appear, you learn nothing. Nondeterminism usually has one of a few causes:
- Randomness can be passed in as parameters (the controllability argument from Chapter 12).
- Remote calls can be replaced with the test doubles from Chapter 18.
- Stale test state can be removed with the lifecycle hooks from Chapter 9.
- Concurrency is a common and difficult source of nondeterministic failures, but it is mostly beyond the scope of this course.
Minimal. Start from whatever reproduces the failure and remove things: fewer inputs, fewer steps. Stop when removing anything else makes the failure disappear.
Minimizing a reproduction is useful even when the original reproduction is already reliable, because minimizing is a form of localization. Every element you remove without losing the failure is an element you don't have to analyze while debugging. If you shrink a reproduction from a full interaction with an application to a single call to one adapter, you've narrowed the search from the whole program to a few dozen lines, before you have read any code.
For our report, we reproduce the failure by asking the customer a few questions: which parcel, which carrier, and what the screen showed. The answers give us a tracking number, and our minimal reproduction is one call:
const carrier: CarrierCClient = new CarrierCClient("https://api.carrier-c.example");
const found: Result<Shipment, TrackingError> = await carrier.track("Z2200417");
// found.value.status is "delivered"; the parcel is sitting in a depotTrackingError is the failure type the library has published since Chapter 19.
This reproduction has no user interface, no tracker, and no other carriers. The failure still occurs with all of those removed, which is already useful: the problem is either (1) in this adapter or (2) in the carrier it communicated with.
Debugging Tools
Before we search for the parcel's fault, we first discuss the tools we will use. Most debugging tools help to answer one of two questions: what is the state at this point, and how did the program get here?
The debugger, introduced in Chapter 6, is useful for both. A breakpoint pauses the program at a line and lets you inspect every variable in scope, which is the most direct way to test a hypothesis about state. Stepping moves through the program one line at a time, either over a call or into it, so you can follow a value as it changes. A conditional breakpoint pauses only when an expression is true, which makes it practical to catch the one parcel out of four hundred that goes wrong.
The Stepper Was a Debugger
The stepper in CPSC 110 let you watch an expression evaluate one step at a time, showing each intermediate form on the way to a value. It was a teaching tool, but it was also the first debugger you used. When a function produced the wrong answer, stepping showed you the point where the value stopped being what you expected.
The debugger in this chapter does the same job in more complex conditions. The stepper could show every step, because ISL programs were small and had no mutable state. A debugger works on a running system with mutable state, many nested calls, and libraries you did not write. It cannot show everything, so you have to choose where to look. The skill the stepper taught is still the same: when a value is wrong, find the earliest point at which it is wrong, and look at what happened immediately before.
Print statements provide a rough answer to the first question (what is the state at this point). They remain widely used because they are quick and work everywhere, including places a debugger cannot easily reach. Their output is noisy though, and they are frequently left behind after a change which makes the important messages harder to notice. Remove them as part of the fix, and prefer the debugger where it is available.
Logging is the form of printing that stays in production code. A deployed system cannot be paused and stepped through, so the only information available afterwards is whatever the program recorded while it ran. Deciding what to log is therefore a design decision, made long before any bug report arrives. Had our tracker logged each carrier's response, we could read what carrier C sent for this parcel without asking the customer to try again.
Two tools from earlier in the textbook also help with debugging. The type checker eliminates categories of faults before the program runs, so a fault that survives compilation is already in a narrower category. The test suite localizes faults: a failing unit test names the unit, which does most of the search for you. This is another argument for the design advice from Part 2, and it is why a system of small, independently tested units is quicker to debug than one that can only be tested end-to-end.
Assertions, from Chapter 3, are especially useful, because they reduce the distance between a fault and a failure. An assertion turns incorrect state into a failure the moment it occurs, before it can spread to an unrelated part of the program. A Shipment with an invalid status can be caught where it is created, with a stack trace immediately pointing at the offending code.
Reading a Stack Trace
A stack trace is the chain of calls that were in progress when an exception was thrown, listed with the innermost call first. The top line is where the exception was thrown. Each line below it is the call that led to the line above, ending at the program's entry point.
Two habits make stack traces useful. The first is to find the topmost line that refers to code you wrote. Traces often begin with several lines inside a library, and those lines are usually reporting your mistake rather than the library's. The library was given something it could not work with, and the important question is which of your lines passed it in.
The second is to read the trace as a description of how the program got there, not only where it stopped. When a function is called from several places, the trace tells you which caller was responsible this time, which the line where it stopped cannot tell you.
Localizing the Fault
Once you have a reproduction, the next question is where the fault is. It is tempting to start changing things at this point, but this is usually unproductive. Changing code without a hypothesis produces a different program, but it does not help you understand the program any better. If the failure happens to disappear, you do not know why, so you cannot tell whether the fault is fixed or just hidden.
A more deliberate approach follows the same pattern as a scientific experiment:
- Form a hypothesis about what is wrong, stated precisely enough that an observation could show it to be false.
- Predict what you would observe if it were true, and what you would observe if it were not.
- Make the observation.
- Keep or discard the hypothesis, and repeat.
Stating the prediction before observing stops you from accepting a result that does not distinguish between explanations. "The adapter is returning the wrong status" is not a useful hypothesis, because almost any observation is consistent with it. "The adapter maps the carrier's NOT_DELIVERED to delivered" is useful, because it predicts one specific value from one specific call.
Narrowing the Search
Several techniques can narrow the search:
Follow the dependencies. The dependency graphs from Chapter 17, tell us which code depends on which, and following the arrows back tells usevery place the wrong value could have come from.In our example, the failing value was a status: it was displayed by the user interface, which got it from the tracker, which got it from an adapter, which derived it from a carrier's response. The dependency graph is particularly useful in a system with low coupling. With low coupling, the dependency chain is short and, thus, there aren't many files you need to search through. In a tightly coupled system, the arrows lead everywhere and your search may need to cover the whole program.
Start from what changed. Most faults are recent. If the tracker worked last month and does not work now, the difference is a small set of commits, and reading them is often faster than reasoning about the code.
Bisect. When the search space is still large, halve it. The most familiar form is bisecting the input, which is what minimizing a reproduction does. The same idea applies to a path through the code, where checking the state at the midpoint tells you which half the value went wrong in. It also applies to a project's history.
Bisecting History
When a failure is known to be new, the commit that introduced it can be found without reading any code, by using binary search on the project's history.
Pick a commit where the failure does not occur and one where it does. Check out the commit halfway between them and test it. If the failure occurs, the commit you want is in the earlier half, and if it does not, the commit is in the later half. Repeat with the remaining half. Each round halves the number of candidates, so a thousand commits take about ten tests.
git bisect automates the bookkeeping. You mark one commit good and one bad, and it checks out the midpoints for you until one commit is left. If the failure can be checked by a script, git bisect can also run that script at each step.
Bisecting finds the commit where the behaviour changed, which is usually, but not always, where the fault is. A commit can expose a fault that was already present.
Two Rounds of Hypothesize-Predict-Observe on the Parcel
For the parcel, we've already narrowed our search to one adapter through our minimal reproduction. Recall from Chapter 20 that each adapter now converts its carrier's status words itself, in a toStatus of its own. Carrier C's is a function in the same file as the class instead of a private method, so that a test can call it directly:
// in CarrierCClient.ts, alongside the class
export function toStatus(raw: string): ShipmentStatus {
if (raw.includes("DELIVERED")) {
return "delivered";
}
if (raw.includes("EXCEPTION")) {
return "exception";
}
return "in-transit";
}The function is not exported from the library's index.ts, so it is not part of the published contract. Reading it suggests some guesses about the fault, and two rounds of the process above turn these guesses into a diagnosis.
Round one. Our first hypothesis is the cheapest one to check: the carrier is reporting the parcel as delivered, and we are correctly passing that on. If this is true, the raw response contains a status that clearly means delivered. If it is false, the response says something else. The observation needs a breakpoint on the conversion, or one temporary line placed before it:
const body: unknown = await response.json();
console.log(body); // { trackingNumber: "Z2200417", status: "NOT_DELIVERED", ... }The prediction fails, so we discard the hypothesis. This is still a useful result. The carrier is not claiming that the parcel arrived, so our own code is producing the wrong answer.
Round two. Our next hypothesis is about the conversion itself: toStatus maps "NOT_DELIVERED" to "delivered", because it tests for a substring rather than for the whole value. This prediction is precise enough to be wrong, and checking it needs no carrier, no network, and no parcel:
expect(toStatus("NOT_DELIVERED")).not.to.equal("delivered");
// fails: toStatus returned "delivered"The hypothesis is correct! "NOT_DELIVERED".includes("DELIVERED") is true, so the first branch matches. We can now write a test that runs in a millisecond and reaches the fault.
Notice how each step of the debugging process narrowed our search:
- Reproduction removed the user interface, the tracker, and four carriers.
- Round one ruled out the carrier.
- Round two ruled out everything except a single function. We could then turn the bug into a failing test that can strengthen our test suite.
As a final note: the fault was not introduced by a recent edit. The substring test had been in the code since it was written, and it gave the right answer for every status the carrier sent until the carrier started sending one it had never sent before. Nothing in our repository changed: the new input from the carrier exposed the fault. "We did not change anything" is not evidence that the fault is somewhere else.
Fixing the Fault
Once the fault is found, the fix can seem obvious, and this is where a second kind of mistake is easy to make. We could fix the parcel bug like this:
if (raw === "NOT_DELIVERED") {
return "exception";
}
if (raw.includes("DELIVERED")) {
return "delivered";
}The reported failure goes away and the customer is satisfied, but the fault is still there. NOT-DELIVERED would cause the same failure, and so would any future status from the carrier that contains the same substring. This is a symptomatic fix: it addresses the reported instance rather than the defect that caused it.
Three questions help distinguish a symptomatic fix from a real one.
What other failures could this fault cause? One fault usually causes several failures, and only one of them has been reported. If we which other inputs follow the same faulty path, we can find those failures before a customer. In the example above, we could get other failures in reporting delivery status for any raw status that includes DELIVERED.
Where is the fault? The failure appeared in the display, but the display is not wrong---it showed what is was given. The fault is in the conversion, and that's where we should apply a fix. Fixing a symptom where it was observed (e.g., by patching the display), rather than where it was caused, leaves the fault in place and adds technical debt to the project.
Why was this fault possible? The substring test matched an open-ended set of strings to a fixed set of meanings, which cannot be correct in general, because the carrier can always introduce a status we have never seen. The real fix (which has to be applied to each toStatus we moved to an adapter in Chapter 20) is to match exactly against the statuses the carrier documents, and to reject anything unrecognized rather than guessing.
Writing the Test First
Before changing any code, we turn the check from round two into a permanent test. Narrowing down the reproduction to a single function helps us greatly here. The test includes the correct answer in an expect:
test("a NOT_DELIVERED status is not reported as delivered", () => {
expect(toStatus("NOT_DELIVERED")).to.equal("exception");
});Run the test and watch it fail before applying the fix. A test that was written after the fix and never seen to fail may not be checking anything. It passes, but so would an empty test. Seeing the test fail first shows that it detects the fault.
The fix itself must still handle EXCEPTION, which the old code recognized, or it would introduce a regression of its own:
export function toStatus(raw: string): Result<ShipmentStatus, string> {
if (raw === "DELIVERED") {
return { ok: true, value: "delivered" };
}
if (raw === "NOT_DELIVERED") {
return { ok: true, value: "exception" };
}
if (raw === "EXCEPTION") {
return { ok: true, value: "exception" };
}
if (raw === "IN_TRANSIT") {
return { ok: true, value: "in-transit" };
}
return { ok: false, error: "unrecognized status: " + raw };
}The fix changes the return type of toStatus, so the test's assertion becomes expect(toStatus("NOT_DELIVERED")).to.deep.equal({ ok: true, value: "exception" }).
This is the same kind of converter as in Chapter 18. The original bug was possible because an unvalidated value from outside the program was interpreted by guesswork, exactly what we tried to prevent in Chapter 18.. Debugging often ends in a design change, because usually it's often a design problemt hat leads to a fault.
Validating the Fix
The fix is finished when the reported failure is gone and nothing that worked before has changed. Run the new test and watch it pass; it stays in the suite to guard against this fault returning. Then we repeat the reproduction from the start of the chapter: carrier.track("Z2200417") now reports the parcel as exception, which is consistent with a parcel that never arrived.
A change can also affect parts of the system it was not meant to touch, so run the whole suite, not only the new test. Chapter 20 made the same argument about restructuring, and it is why both chapters depend on the regression suite from Chapter 9.
Fixing a Public API
Our tracker is a published library, so this fix changes a contract that other teams have written code against. Clients now receive exception where they used to receive delivered (the fault fix), and they receive ok: false where an unrecognized status used to appear as in-transit (a design change). Neither change alters a type, so the compiler cannot warn clients, and a client may have adapted to the wrong answer, for example by checking a second field to work out the real status.
What do we do? As per Chapter 19, either: (1) release the fix as a breaking change, (2) add a corrected version of the operation and deprecate the old one, or (3) document the behaviour and leave the code alone. We decide that we can't leave a tracker that reports undelivered parcels as delivered as-is, so we'll take path (1): ship this fix as a breaking change, with release notes that describe both changes.
The severity of a bug can override all of this. A bug that loses data, exposes information, or lets someone do what they should not be able to do is fixed immediately, even if clients depend on it and get no notice, because the alternative is worse. The deep-dive example below shows this decision being made in real time. Significant functionality was disabled within hours, and the more careful design came later.
When Are Breaking Bug Fixes Allowed?
The Falador Massacre was the dramatic name given to the result of a bug in the MMORPG RuneScape. In RuneScape, player-versus-player (PvP) combat was disabled in most of the game. It was only allowed in special areas, such as "The Wilderness" and some parts of player-owned houses. Cities such as Falador were meant to be safe from PvP combat.
In this game, a player killed by another player (in PvP) loses the items they were carrying. In many MMORPGs, obtaining items can take many hours of repetitive gameplay, possibly mapping to days and weeks of real-world time investment. Thus, losing items unexpectedly, as was possible with this bug, can be devastating.
The fault was that when players were removed from a player-owned house while PvP was enabled for them, PvP stayed enabled. The failure is that some players were able to attack other players in areas that were supposed to be safe, which caused a great deal of chaos.
This issue was reported in the middle of the night for the game's developers. The developer on call identified the fault and deployed a simple, but breaking fix: houses could no longer turn on PvP, and the PvP state no longer had any effect. This disabled significant PvP features in the game, but disabling them cost less than letting the "massacre" continue.
The game code was later updated to add a notion of "areas" to the game. Areas could be checked to ensure that states such as PvP were not enabled where they should not be.
(We talk about video game examples not because we expect you have played them, but because they are large, complex, and often, poorly designed, pieces of software whose high-level meaning can be explained easily. An example of another bug that required a breaking fix is the Corrupted Blood incident.)
Debugging Is a Process
Each step in this chapter either shortens the chain from fault to failure or searches it systematically: (1) Reproduce the failure, so that it can be triggered on demand and is small enough to reason about. (2) Localize the fault by forming hypotheses and halving the search space. (3) Fix the fault where it is, and ask why it was possible, because the answer often points to a design improvement as well as a correction. And finally, (4) validate the fix with a test that you saw fail first, and with a suite that checks everything else.
Little of this process is new. "Good design" properties turn out to make a system quick to debug too:
- small units that a failing test can name (Chapter 11),
- low coupling so that the chain of dependencies is short (Chapter 17),
- validation at the edge so that bad data is rejected where it enters rather than misinterpreted three layers later (Chapter 19),
- assertions that make incorrect state visible (Chapter 3), and
- a regression suite that can check any fix (Chapter 9).
None of these were introduced as debugging techniques, but all of them help when something goes wrong.
Exercise: The Overnight Shift Report
As a warehouse supervisor, I want the overnight shift report to show the hours my staff worked, so that payroll is correct.
A supervisor reports that one employee's overnight shift was recorded as -17 hours. Payroll rejected the run, and the problem does not happen for day shifts.
/**
* Computes the length of a shift in hours.
*
* @param {number} startHour the hour the shift began, 0 to 23.
* @param {number} endHour the hour the shift ended, 0 to 23.
* @returns {number} the shift length in hours.
*/
function shiftLength(startHour: number, endHour: number): number {
return endHour - startHour;
}Work through the following:
- Separate the two. Identify the fault and the failure in this report, and say which of them the supervisor observed.
- Reproduce it. Write the smallest call that triggers the failure, and state the property of overnight shifts that makes them different from day shifts. Explain what your minimal reproduction has already ruled out.
- Form a hypothesis. State a hypothesis precise enough to be false, and give the observation that would distinguish it from a competing explanation, such as bad data from the time-clock system.
- Fix the fault. Correct the defect rather than the reported instance. Then describe other failures that the same fault could cause, which nobody has reported yet.
- Ask why it was possible. The documentation says that both parameters are hours from 0 to 23, but nothing enforces this. Describe a design change, using an idea from an earlier chapter, that would have made this fault impossible or caught it at the edge.
- Guard it. Write the regression test, and say what you would check about that test before trusting the fix. Then decide whether this function belongs in a published API, and if it did, what the compatibility consequences of your fix would be.