One-Sentence Definition
Debugging turns a discrepancy between expected and actual behavior into a reproducible test case, isolates the root cause through observation, hypotheses, and controlled experiments, and locks in the fix with verification.
Why It Matters
- Developers spend a large share of their engineering hours debugging. The gap in systematic debugging skill often matters more than raw typing or code-generation speed.
- Debugging is a learnable method, not guesswork: experienced engineers rely on a repeatable loop—reproduce, shrink the scope, bisect, and compare—rather than intuition alone.
- AI-generated code makes disciplined debugging even more important: LLM outputs almost always look plausible on the surface, while subtle bugs hide in edge cases and data-type boundaries.
Practical Boundaries
Fixing random seeds helps narrow non-determinism, but cannot guarantee bit-identical outputs across different hardware accelerators, library versions, or non-deterministic GPU kernels. Similarly, logging model inputs for debugging should capture only the minimal metadata and redacted snippets required to reproduce an issue rather than storing raw user PII.
How It Works / Diagram
Core debugging techniques:
| Technique | How It Works |
|---|---|
| Minimal Reproduction | Strip away unrelated code and data until you have the smallest self-contained script that still triggers the bug |
| Bisection (Binary Search) | Cut the search space in half at each step—across input rows, commits (git bisect), or config flags |
| Print Probes | print(repr(x), type(x))—simple and effective; in Python 3.8+, use self-documenting expressions like f"{x=}" |
| Interactive Breakpoints | Pause execution in place to inspect live stack frames and variables (see k1.prog.breakpoint) |
| Reading Stack Traces | Start at the bottom line to read the exception type and message, then trace upward to the frame in your own code (see k1.prog.stack-trace) |
| Rubber Duck Debugging | Explain what each line actually does out loud to a colleague (or a rubber duck); the mismatch between intent and code often jumps out mid-sentence |
| Differential Comparison | Diff a known working run against a failing run to see what changed |
Using git bisect to binary-search commit history for the exact commit that introduced a regression: https://git-scm.com/docs/git-bisect
Runnable Example
A complete end-to-end debugging loop on a broken average-score function: reproduce → inspect runtime types to test a hypothesis → binary-search for the bad record → fix at the boundary → add a regression assertion (verified on Python 3.15.0):
# File: examples/13_debugging.py
# The scientific debugging loop: Reproduce -> Hypothesize -> Verify -> Fix -> Regression Test
def average_scores(records):
total = 0
for r in records:
total += r["score"]
return total / len(records)
data = [{"name": "a", "score": 90}, {"name": "b", "score": "85"}, {"name": "c", "score": 70}]
# 1) Reproduce
try:
average_scores(data)
except TypeError as e:
print("Reproduced error:", e)
# 2) Hypothesis: one record's score is not numeric. 3) Verify: print runtime types
for r in data:
print(f" {r['name']}: {r['score']!r} -> {type(r['score']).__name__}")
# Binary search: locate the first malformed record in a large dataset
def first_bad(rows):
lo, hi = 0, len(rows)
while lo < hi:
mid = (lo + hi) // 2
if all(isinstance(r["score"], (int, float)) for r in rows[: mid + 1]):
lo = mid + 1
else:
hi = mid
return lo
print("Bisected index of first bad record:", first_bad(data))
# 4) Fix: normalize types at the boundary + guard empty inputs 5) Regression tests
def average_scores_fixed(records):
if not records:
return 0.0
return sum(float(r["score"]) for r in records) / len(records)
assert average_scores_fixed(data) == (90 + 85 + 70) / 3
assert average_scores_fixed([]) == 0.0
print("Fixed and passed regression tests:", round(average_scores_fixed(data), 2))
Captured output:
Reproduced error: unsupported operand type(s) for +=: 'int' and 'str'
a: 90 -> int
b: '85' -> str
c: 70 -> int
Bisected index of first bad record: 1
Fixed and passed regression tests: 81.67
The root cause was not a flaw in the arithmetic formula—it was upstream data storing one score as the string '85'. The fix normalizes inputs at the function boundary (converting to float) and also guards against division by zero on an empty list.
Common Pitfalls
- Editing code before reproducing the bug: Making speculative edits as soon as you see an error message often masks the trigger without fixing the bug.
- Patching symptoms instead of the root cause: Swallowing exceptions with a bare
try/except: passpushes the failure further downstream where it is much harder to diagnose. - Changing three variables at once: If you tweak three things simultaneously and the error disappears, you still do not know which change actually fixed it.
- Skipping regression tests: Without an automated assertion covering the failure case, the exact same bug tends to resurface months later.
- Pasting a raw traceback into an AI chat with zero context: Without a minimal reproduction script, expected vs. actual output, and environment versions, an LLM can only guess.
Connection to AI Development
- Failure modes specific to ML/DL code: Tensor shape mismatches, mixed
dtypeprecision, CPU vs. GPU device placement errors, train/test data leakage, and unseeded stochasticity. Always pin random seeds and printshape / dtype / devicefirst when debugging tensor pipelines. - Many "bugs" in LLM applications live outside Python code: Regressions often come from prompt template edits, noisy RAG retrieval chunks, or upstream model checkpoint updates. Log redacted input summaries, prompt template versions, model IDs, tool payloads, and request IDs (see k1.prog.logging) so failures can be replayed deterministically.
- How to use AI assistants effectively during debugging: Provide the minimal reproduction script, the full stack trace, and the hypotheses you have already ruled out, then ask the model to propose candidate causes and how to test each one rather than asking for a blind code patch.
- Python 3.15 adds the Tachyon sampling profiler (
profiling.sampling), which can attach to live running processes with low overhead to diagnose performance bottlenecks: https://docs.python.org/3.15/whatsnew/3.15.html
Further Reading
- Andreas Zeller, The Debugging Book (free online textbook with executable Python examples): https://www.debuggingbook.org/
- Python
pdbDocumentation: https://docs.python.org/3/library/pdb.html git bisectDocumentation: https://git-scm.com/docs/git-bisect- David J. Agans, Debugging: The 9 Indispensable Rules for Finding Even the Most Elusive Software and Hardware Problems (2002)
Concept Check
Once your fix stops the original input from raising an exception, is verification complete?
Reference answer: Not yet—you should still verify that the returned value matches expectations, check adjacent boundary inputs (such as empty collections), and commit a regression test covering the root cause.
Verification & Reproduction
Verified on: 2026-10-14. Example status: Passed. Run log: 13_debugging.py.
Companion Code & Verification Materials