How can observing a program’s execution lead us from a failure back to its defect?
Authors
Dylan DeLong-Headley
Gregory M. Kapfhammer
Published
December 2, 2026
Overview
This blog post is our first look at The Debugging Book. We briefly visit the “Introduction to Debugging” chapter. Then we focus on Part II, “Observing Executions”, which contains four chapters:
Each chapter treats a failure as the visible end of a chain of events that starts at a defect in the code. To find the defect, we follow that chain backward by observing the execution.
Why Observe Executions?
The Running Example: remove_html_markup()
The “Introduction to Debugging” chapter studies a function that should strip HTML tags from a string and keep the text between them. The function tracks whether it is inside a tag and whether it is inside a quote, so that a > inside a quoted attribute value does not end the tag early. It has a bug:
def remove_html_markup(s): tag =False quote =False out =""for c in s:if c =='<'andnot quote: tag =Trueelif c =='>'andnot quote: tag =Falseelif c =='"'or c =="'"and tag: quote =not quoteelifnot tag: out = out + creturn outinputs = ['<b>foo</b>', '<b id="bar">foo</b>', '<b>"foo"</b>', '"<b>foo</b>"']for inp in inputs:print(f"{inp!r:24} -> {remove_html_markup(inp)!r}")
The first two inputs work. The last two should produce "foo", but the quotation marks disappear. The last input also keeps its tags: the opening quotation mark switches the function into “quote mode” even though it is outside a tag, and in that mode it ignores < and > until the next quotation mark.
From Mistake to Failure
The chapter names each link in the chain that ends in a bug report:
A mistake is a human act or decision that leads to an error. Here, the programmer forgot that and binds more tightly than or.
A defect is an error in the program code, also called a bug. Here, it is the line elif c == '"' or c == "'" and tag:. Python reads it as c == '"' or (c == "'" and tag), so a double quotation mark toggles quote even outside a tag.
A fault is an error in the program state, also called an infection. After the defect runs, quote is True while tag is False, which should never happen.
A failure is an error in the program’s visible behavior. Here, the output is missing its quotation marks.
The book summarizes this as mistake → defect → fault → … → fault → failure. We only see the failure at the end. The defect is hidden in the code, and the fault spreads through the state in between, so we have to watch the state step by step to find the first point where it goes wrong. Once we find it, the fix is to add parentheses so that the tag check applies to both kinds of quotation mark:
elif (c =='"'or c =="'") and tag:
This also connects to our FB9 summary on reducing failure-inducing inputs. A reduced input such as '"foo"' produces a much shorter execution to observe than a long fuzzer-generated one, so it is worth reducing an input before we start observing.
Why Not Just Add print() Calls?
The quickest way to observe a program is to add print() calls. The chapter explains why this “printf debugging” does not scale:
It is inefficient. A 1,000-character input means reading 1,000 lines of logs.
It is a maintenance problem. Every statement must be added by hand and removed later, and a forgotten one can even leak sensitive data.
It shows only the variables we guessed in advance, so a wrong guess means editing and rerunning the program.
We would rather observe any variable at any point without editing the program. Python makes this possible with debugging hooks, which the “Tracing Executions” chapter explores.
Tracing Executions
Debugging Hooks and a Tracer Class
Python lets us register a trace function with sys.settrace(). The interpreter calls it before each new line runs ('line') and when a function is called ('call'), returns ('return') or raises an exception ('exception'). Each call receives the current frame, which holds the line number (frame.f_lineno) and the local variables (frame.f_locals), so a trace function can observe any variable at any point without editing the program.
The chapter wraps this hook in a Tracer class. As a context manager, with Tracer(): ... turns tracing on for exactly one block of code. Instead of printing every variable on every line, it prints only the variables that changed, followed by the source line about to run. The following version is simplified from the book’s code, and it counts line numbers from the def line of remove_html_markup(), so line 11 is the defect:
s = '"a"'
1 tag = False
tag = False
2 quote = False
quote = False
3 out = ""
out = ''
5 for c in s:
c = '"'
6 if c == '<' and not quote:
8 elif c == '>' and not quote:
10 elif c == '"' or c == "'" and tag:
11 quote = not quote
quote = True
5 for c in s:
c = 'a'
6 if c == '<' and not quote:
8 elif c == '>' and not quote:
10 elif c == '"' or c == "'" and tag:
12 elif not tag:
13 out = out + c
out = 'a'
5 for c in s:
c = '"'
6 if c == '<' and not quote:
8 elif c == '>' and not quote:
10 elif c == '"' or c == "'" and tag:
11 quote = not quote
quote = False
5 for c in s:
15 return out
remove_html_markup() returns 'a'
Each numbered line is the line about to run, and each indented line lists the variables that the previous line changed. The output shows quote = True right after quote = not quote runs while tag is still False, which is where the fault enters the state. The other chapters in Part II reuse this class: a debugger is a tracer that pauses for commands, an assertion checker is a tracer that evaluates a condition, and a profiler is a tracer that records time.
Conditional Tracing
A full trace is readable for a three-character input, but real executions run millions of lines, so the chapter adds ways to report only the events we care about.
Breakpoints: A Condition at a Location
A ConditionalTracer evaluates a condition string with eval(), using the frame’s local variables plus a line variable. It reports only while the condition is true and prints ... where it skipped lines. A condition on the location is a breakpoint. Ours also checks the state, so it reports line 11 only when we are not inside a tag:
class ConditionalTracer(Tracer):def__init__(self, condition="False", **kwargs):super().__init__(**kwargs)self.condition = conditionself.reporting =Falsedef eval_in_context(self, expr, frame): line = frame.f_lineno - frame.f_code.co_firstlinenotry:returneval(expr, None, dict(frame.f_locals, line=line))exceptNameError: # a variable is not defined yetreturnNonedef do_report(self, frame):returnself.eval_in_context(self.condition, frame)def traceit(self, frame, event, arg): report =bool(self.do_report(frame))if report andnotself.reporting:print("...")self.reporting = reportif report:self.print_status(frame, event, arg)with ConditionalTracer(condition="line == 11 and not tag"): result = remove_html_markup('"<b>foo</b>"')
...
s = '"<b>foo</b>"', tag = False, quote = False, out = '', c = '"'
11 quote = not quote
...
quote = True, out = '<b>foo</b>'
11 quote = not quote
The breakpoint is reached once for each quotation mark outside the tag. Both times c is '"' and tag is False, yet line 11 is about to toggle quote. Since quote should never change outside a tag, these reports lead us to the defect.
Watchpoints: An Event on a State Change
When we know which variable goes wrong but not where, a watchpoint reports whenever an expression changes value, regardless of which line changed it. The book’s EventTracer adds a list of events to watch. Because a 'line' event fires before its line runs, each report shows the line that follows the change:
class EventTracer(ConditionalTracer):def__init__(self, events=(), **kwargs):super().__init__(**kwargs)self.events = eventsself.last_values = {e: Nonefor e in events}def do_report(self, frame): values = {e: self.eval_in_context(e, frame) for e inself.events} changed = values !=self.last_valuesself.last_values = valuesreturn changed orsuper().do_report(frame)with EventTracer(events=["quote"]): result = remove_html_markup('"<b>foo</b>"')
...
s = '"<b>foo</b>"', tag = False, quote = False
3 out = ""
...
quote = True, out = '', c = '"'
5 for c in s:
...
quote = False, out = '<b>foo</b>'
5 for c in s:
After quote is created, it becomes True after the first character, so the function keeps <b> and </b> as text. It becomes False again only after the last character.
Efficient Tracing
Running a Python trace function on every line costs far more than the traced line itself. The chapter’s solution is to instrument only the locations we care about: insert a check into the function’s source code at the breakpoint and compile the new version, so no trace function is needed. The following segment builds such a version with insert_check(), a simplified form of the book’s insert_tracer(), and times 1,000 calls with no tracing, with our EventTracer and with the inserted check:
quote toggled outside a tag
quote toggled outside a tag
No tracing: 0.67 ms
EventTracer: 643.07 ms
Instrumented: 0.66 ms
The instrumented function reports the same two problems as our breakpoint. The numbers vary by machine, but the traced version is hundreds of times slower, while the instrumented version runs at nearly its original speed because its check is ordinary code on line 11. The cost is flexibility, since moving the breakpoint means generating and compiling the function again.
Tracing Binary Executables
Compiled languages such as C have no sys.settrace(), so their debuggers rely on the hardware and the operating system. A software breakpoint temporarily replaces an instruction with a special break instruction, while hardware breakpoints and watchpoints let the processor itself watch an address or a memory location. On Linux and UNIX, the ptrace() system call lets the debugger control and inspect the program. Compilers can also instrument code while building it, much like insert_check().
Question: What is the difference between a breakpoint and a watchpoint?Click to Expand for the Answer
A breakpoint is a condition at a location: it triggers when execution reaches a given line, optionally only when a condition holds there. A watchpoint is an event on a state change: it triggers whenever a variable or expression changes, no matter which line caused the change. A breakpoint is useful when you know where to look, and a watchpoint is useful when you only know which value goes wrong.
How Debuggers Work
The “How Debuggers Work” chapter shows that an interactive debugger is a tracer that can stop. Its Debugger class extends Tracer. On each line it checks stop_here(), which is true when the debugger is stepping or when the current line has a breakpoint. When it stops, it reads commands from the user until a command such as step or continue lets the program run again.
The commands are handled by a command dispatcher. A method named NAME_command implements the command NAME, and execute() uses getattr() to find the method for whatever the user typed. Adding a command therefore means adding one method, and each method’s docstring doubles as its help text. The following version is simplified from the book’s code. Because the site’s build cannot type commands, it reads them from a list instead of calling input():
class Debugger(Tracer):def__init__(self, commands, **kwargs):super().__init__(**kwargs)self.commands =list(commands)self.stepping =Trueself.breakpoints =set()def traceit(self, frame, event, arg): line = frame.f_lineno - frame.f_code.co_firstlinenoif event !="line"ornot (self.stepping or line inself.breakpoints):returnself.frame = frame source = linecache.getline(frame.f_code.co_filename, frame.f_lineno)print(f"{line:2}{source.rstrip()}")self.interact =Truewhileself.interact andself.commands: command =self.commands.pop(0)print(f"(debugger) {command}") name, _, arg = command.partition(" ")getattr(self, f"{name}_command")(arg)def step_command(self, arg):"""Execute up to the next line"""self.stepping, self.interact =True, Falsedef continue_command(self, arg):"""Resume execution until the next breakpoint"""self.stepping, self.interact =False, Falsedef break_command(self, arg):"""Set a breakpoint in the given line"""self.breakpoints.add(int(arg))def print_command(self, arg):"""Print the value of an expression"""print(eval(arg, None, dict(self.frame.f_locals)))def quit_command(self, arg):"""Clear all breakpoints and finish execution"""self.breakpoints.clear()self.continue_command(arg)with Debugger(["break 11", "continue", "print c, tag, quote","step", "print quote", "quit"]): result = remove_html_markup('"<b>foo</b>"')
1 tag = False
(debugger) break 11
(debugger) continue
11 quote = not quote
(debugger) print c, tag, quote
('"', False, False)
(debugger) step
5 for c in s:
(debugger) print quote
True
(debugger) quit
The debugger stops at the first line because it starts out stepping. We set a breakpoint on the defect and continue. At the breakpoint, print shows that c is a quotation mark while tag is False, and after one step, quote is True. Unlike a trace, the debugger lets us decide what to inspect next based on what we just saw. The book’s version adds list to show the source, delete to remove breakpoints and help to list the commands from their docstrings.
Asserting Expectations
Tracing and debugging both rely on a human to notice when the state is wrong. The “Asserting Expectations” chapter has the computer do this instead. An assert statement checks a condition at runtime and stops the program with an AssertionError as soon as the condition is false. A test checks one run, but an assertion in the code checks every run that reaches it.
The chapter uses assertions in three ways:
A precondition at the start of a function checks what the caller must provide. If it fails, the caller is at fault.
A postcondition at the end of a function checks its result. If it fails, the function itself is at fault.
A data invariant checks that an object’s state stays valid. The chapter’s Time class has a repOK() method that checks, for example, that hours stay between 0 and 23, and calls it after every change.
The following square_root() from the chapter has a precondition and a postcondition. The postcondition uses math.isclose() because floating-point results are rarely exact. We also add a partial check to remove_html_markup(). It cannot say what the right output is, but it can say that the output should contain no < or >:
import mathdef square_root(x):assert x >=0, "x must not be negative"# precondition approx, guess =None, x /2while approx != guess: approx, guess = guess, (guess + x / guess) /2assert math.isclose(approx * approx, x) # postconditionreturn approxdef checked_remove(s): out = remove_html_markup(s)assert'<'notin out and'>'notin out, f"markup left in {out!r}"return outfor call in [lambda: square_root(2), lambda: square_root(-1),lambda: checked_remove('"<b>foo</b>"'),lambda: checked_remove('<b>"foo"</b>')]:try:print(repr(call()))exceptAssertionErroras error:print("AssertionError:", error)
1.414213562373095
AssertionError: x must not be negative
AssertionError: markup left in '<b>foo</b>'
'foo'
The precondition rejects -1, and the partial check catches the input whose tags survive. It misses '<b>"foo"</b>', though, because that output is wrong without containing any markup. Partial checks are cheap to write, but they only catch some failures. Our comparison section later goes further by checking an invariant before every line, which finds the defect itself.
Python skips all assertions when it runs with the -O (optimize) flag, so an assertion must never do work the program depends on:
For the same reason, assertions should not have side effects and should not replace real error handling, such as checking user input. The chapter also covers system invariants, such as tools like Valgrind and memory sanitizers that check every memory access in C programs. Since assertions cost time, it suggests keeping cheap checks on in production and turning off expensive ones first.
Debugging Performance Issues
A program can also fail by being too slow. The “Debugging Performance Issues” chapter’s main rule is to measure before optimizing, because the slow part is often not where we expect it. It describes two ways to measure:
An instrumenting profiler, such as Python’s cProfile, records the time at the entry and exit of every function or line. It is precise but slow, since it is a tracer.
A sampling profiler, such as scalene, interrupts the program at regular intervals and records where it is. It is much cheaper but only gives estimates, so it needs a long-running program to collect enough samples.
The chapter’s PerformanceDebugger is an instrumenting profiler built on the tracer, and it reports the share of time each line takes. The following LineTimer is a small version of it. On every event, it adds the time since the previous line event to that previous line, and then it prints the three lines with the largest share of 100 calls:
import timefrom collections import Counterclass LineTimer(Tracer):def__init__(self, **kwargs):super().__init__(**kwargs)self.time, self.last = Counter(), Nonedef traceit(self, frame, event, arg): now = time.perf_counter()ifself.last:self.time[self.last[0]] += now -self.last[1] line = frame.f_lineno - frame.f_code.co_firstlinenoself.last = (line, now) if event =="line"elseNonewith LineTimer() as timer:for _ inrange(100): remove_html_markup('<b>foo</b>')total =sum(timer.time.values())for line, seconds in timer.time.most_common(3):print(f"line {line:2}: {seconds / total:.0%} of the time")
line 5: 21% of the time
line 6: 20% of the time
line 8: 15% of the time
The loop header (line 5) and the comparisons on lines 6 and 8 take the largest shares, because every character passes through them, although the exact shares vary from run to run. Since the profiler is itself a tracer, the times it reports include its own overhead, which is the cost of instrumenting that a sampling profiler avoids. Once the measurements show where the time goes, the chapter recommends improving the algorithm or the data structures there, rather than tuning code that barely runs. It also shows that delta debugging can reduce an input that makes a function slow, by treating “takes longer than a time limit” as the failure.
Comparing Observation Techniques
All four techniques in Part II are built on the same debugging hooks. They differ in what they observe, when they act and how much they slow the program down.
Side-by-Side Comparison
What each technique observes and when it acts
Technique
What it observes
When it acts
Tracing
Every event and state change
Continuously
Debugger
State at chosen points
When it stops for the user
Assertions
Expected properties of the state
At check locations, or on every line for invariants
Profiling
Time and hit counts per line or function
Continuously (instrumenting) or on a timer (sampling)
Strengths and limitations of each technique
Technique
Strengths
Limitations
Tracing
Shows the whole execution without guessing; conditions and watchpoints narrow the output
Slow, and the output gets long for real programs
Debugger
Interactive, so you can explore and change your hypothesis as you go
Manual, hard to repeat, and cannot run in automated builds
Assertions
Automatic and repeatable; catches a fault as soon as it enters the state
You must know what to expect, and checks must not have side effects
Profiling
Shows where time is actually spent before you optimize
Cannot detect wrong results, and instrumentation distorts timing
Choosing a Technique
The fault’s location is unknown: start with a trace or a watchpoint on a suspicious variable, then narrow it down.
A location is suspected: set a breakpoint there and step through it in a debugger, or instrument just that line when speed matters.
The expected behavior is known: write it as an assertion or invariant so that the tests catch the fault as soon as it appears.
The program is slow rather than wrong: profile first and optimize only the lines that the measurements point to.
Applying the Techniques to remove_html_markup()
The previous sections already used tracing, a breakpoint and a watchpoint. The segment below applies an assertion and a profiler, again built on our tracer classes. The book’s version of remove_html_markup() uses the invariant tag or not quote, meaning that a quote can only occur inside a tag. InvariantChecker evaluates the invariant before every line and records the line that ran just before it first failed. LineCounter counts how often each line runs, which is the simplest form of an instrumenting profiler:
from collections import Counterclass InvariantChecker(ConditionalTracer): previous = broken =Nonedef traceit(self, frame, event, arg):if event !="line"orself.broken:returnifself.eval_in_context(self.condition, frame) isFalse:self.broken =self.previous line = frame.f_lineno - frame.f_code.co_firstlineno source = linecache.getline(frame.f_code.co_filename, frame.f_lineno)self.previous =f"line {line}: {source.strip()}"class LineCounter(Tracer):def__init__(self, **kwargs):super().__init__(**kwargs)self.hits = Counter()def traceit(self, frame, event, arg):if event =="line":self.hits[frame.f_lineno - frame.f_code.co_firstlineno] +=1with InvariantChecker(condition="tag or not quote") as checker: remove_html_markup('"<b>foo</b>"')print("Invariant broken after", checker.broken)with LineCounter() as counter: remove_html_markup("<b>"+"x"*100+"</b>")print("Most executed lines:", counter.hits.most_common(3))
Invariant broken after line 11: quote = not quote
Most executed lines: [(5, 108), (6, 107), (8, 105)]
The invariant checker finds the defect line without any human input, so it could run as part of a test suite. The line counter shows that the loop header (line 5) and the first two comparisons (lines 6 and 8) run most often, so an optimization would have to start there. The interactive debugger waits for typed commands, so we demonstrate it live in class with faultline debug.
Action Items
These action items apply what we learned from Part II to our own development and to the course’s long-term software projects:
Stop relying on print() statements as our main way to find bugs. They are slow to add and remove, show only what we guessed in advance, and sometimes end up in commits by accident.
Start writing preconditions, postconditions and data invariants into the project code, so that a fault is caught where it enters the state instead of where it becomes visible. We should also use a debugger with breakpoints and watchpoints, such as the one in VS Code, when a test fails for a reason we cannot see.
Start measuring with a profiler before optimizing any slow part of a project, and include the profile in the pull request so that reviewers can see the reason for the change.
Keep reducing failure-inducing inputs, as in our FB9 summary, before observing an execution, because a smaller input produces a shorter trace to read.
Keep checking that assertions have no side effects and do not replace error handling, since running Python with -O removes them.
Lessons Learned
Debugging means following a chain from a defect in the code, through faults in the program state, to a visible failure, and observing the execution is how we follow that chain backward.
Python’s sys.settrace() hook lets us observe any variable at any line without editing the program, and tracers, debuggers, assertion checkers and profilers can all be built on it.
Breakpoints and watchpoints keep a trace small enough to read, while instrumenting the code keeps it fast enough to use.
A debugger is a tracer that stops for commands, and a command dispatcher makes it easy to extend.
Assertions let the computer check our expectations in every run, but they must not have side effects, because they can be turned off.
Performance problems need measurement first, with instrumenting profilers giving precise results and sampling profilers giving cheaper estimates.
NoteOpen-Source Tool for Software Engineers
Our tool is faultline, a Python command-line tool, managed with uv, that follows a fault from the defect to the failure by observing the execution. It has one subcommand for each idea in this post: chain compares a passing and a failing run, trace supports breakpoints and watchpoints, debug is a small interactive debugger, check tests preconditions, postconditions and invariants, and profile compares instrumenting and sampling profilers. All of them share a single sys.settrace() tracer core and run on the same buggy remove_html_markup(). Run uv run faultline demo to see them all in order, and check out faultline on GitHub.