SkilVaultSign inStart free

Catalogue / root-cause-debugging-method

root-cause-debugging-method

Older skill: source not recordedSignedDebugs software defects through a reproduce, isolate, hypothesize, test, fix, prevent cycle: reading stack traces properly, bisecting regressions, driving language debuggers, recognizing common bug patterns, and landing fixes with regression tests. Use when the user says "this crashes with a TypeErr…
---
name: root-cause-debugging-method
description: >-
  Debugs software defects through a reproduce, isolate, hypothesize, test, fix,
  prevent cycle: reading stack traces properly, bisecting regressions, driving
  language debuggers, recognizing common bug patterns, and landing fixes with
  regression tests. Use when the user says "this crashes with a TypeError",
  "find the root cause", "it fails intermittently", "trace this stack trace",
  "hunt down this memory leak", or "the tests broke after yesterday's merge".
  Not for writing features, setting up monitoring or alerting, or triaging
  incident response.
---

Root-Cause Debugging Method

A disciplined loop for getting from "it's broken" to "fixed, with proof": Reproduce → Isolate → Hypothesize → Test → Fix → Prevent. No fix is written before the cause is understood — patching symptoms is how one bug becomes three.

Phase 1 — Reproduce and observe

  1. Collect the complete error, not just its first line. File, line number,

operation that failed, and the frames between.

  1. Write down reproduction steps that work every time, plus the environment:

runtime version, OS, role, data state. For intermittent bugs, record the observed frequency instead of pretending it is deterministic.

  1. Check what recently changed near the failure site:
   git log --oneline -10
   git log -p --follow -- src/modules/cart/PriceSummary.tsx
  1. Trace the failing value backwards from the crash site to where it was born.

Instrument boundaries when values are opaque — temporarily:

console.log('[PriceSummary] props:', JSON.stringify(props));
console.log('[PriceSummary] totals type:', typeof props.totals);

Phase 2 — Isolate

Pick the isolation strategy that fits the evidence:

| Situation | Strategy | |---|---| | Unknown location in a long pipeline | Disable or stub half the stages, test, repeat on the failing half | | Heavy setup around a small failure | Build a minimal reproduction: new file, smallest failing input, strip dependencies one at a time | | Regression from a known-good release | git bisect (below) | | Exact crash location known | Time-travel: trace the bad value back to where it diverged | | Logic you can't hold in your head | Walk the code line by line stating intended vs actual behavior (rubber-duck) |

Git bisect, executed in the project's working tree after confirming the known-good and known-bad revisions with the user:

git bisect start
git bisect bad                 # current state is broken
git bisect good v2.3.0         # last release known to work
# git checks out the midpoint — test, then mark it:
git bisect good                # or: git bisect bad
# ...until git reports "abc123 is the first bad commit"
git bisect reset

# Automated variant with a deterministic test script:
git bisect start HEAD v2.3.0
git bisect run npm test

A flaky test can convict the wrong commit; use a deterministic one.

Phase 3 — Hypothesize and test

Write the hypothesis as a falsifiable claim with a prediction:

> Claim: OrderList crashes because the query returns > { orders: null } while loading completes. > Prediction: an early return on falsy orders removes the crash. > Test: add exactly that guard and rerun the reproduction.

Then change one variable and record the outcome:

| Hypothesis | Change | Result | Verdict | |---|---|---|---| | Null orders | Add if (!orders) return <EmptyState/> | Crash gone | Confirmed |

Never test two hypotheses in one edit — a pass then proves nothing.

Phase 4 — Fix and prevent

  1. Write the failing test first, watch it fail.
  2. Apply the smallest change that addresses the root cause.
  3. Run the full suite; check the normal, empty, loading and error states.
  4. Remove every temporary console.log, debugger and breakpoint() before

delivering.

Debugger toolbox

| Language | Debugger | Entry point | |---|---|---| | JavaScript/TS | Node inspector | node --inspect dist/server.js (or --inspect-brk to pause before app code) | | Python | pdb | python -m pdb manage.py runserver | | Go | Delve | dlv debug ./cmd/queue | | Rust | rust-gdb / rust-lldb | rust-gdb ./target/debug/ingest | | Java | JDB / IDE debugger | IDE launch configuration |

With ts-node: node --inspect -r ts-node/register src/server.ts. Python 3.7+ prefers breakpoint(); print(f"{orders=}") prints name and value together.

pdb commands:

| Command | Action | |---|---| | n / s | Next line / step into | | c | Continue | | l | List source | | p expr / pp expr | Print / pretty-print | | w | Show stack | | q | Quit |

Delve commands:

| Command | Action | |---|---| | break handler.go:88 | Set breakpoint | | continue / next / step | Resume / next line / step in | | print job | Inspect a variable | | goroutines | List goroutines |

VS Code launch.json must reference the extensions and tasks that actually exist in the workspace — a copied config pointing at a missing preLaunchTask or an obsolete debugger type just fails confusingly. Use conditional or exception breakpoints to cut noise.

Common bug patterns

| Pattern | Symptom | Usual cause | |---|---|---| | Race condition | Works sometimes | Missing await, unsequenced async | | Off-by-one | First/last item missing | Loop bounds, index arithmetic | | Null reference | "undefined is not..." | Missing guard at a real boundary | | Memory leak | Memory only grows | Undisposed listeners, timers, subscriptions | | N+1 queries | Slows as data grows | Querying inside a loop | | Type coercion | Odd comparisons | Loose equality, implicit conversion | | Loop closure | Callbacks share one value | var capture instead of let | | Stale state | Old value in callback | Closure over state, missing deps |

Before/after examples (fresh scenarios):

// BUG: total read before the fetch lands
let total;
fetchTotal().then(v => { total = v; });
render(total);                       // renders undefined

// FIX: await the value before using it
const total = await fetchTotal();
render(total);
// BUG: interval and listener leak on every mount
useEffect(() => {
  const id = setInterval(pollShipment, 5000);
  window.addEventListener('online', syncQueue);
}, []);

// FIX: clean up with the same references
useEffect(() => {
  const id = setInterval(pollShipment, 5000);
  window.addEventListener('online', syncQueue);
  return () => { clearInterval(id); window.removeEventListener('online', syncQueue); };
}, []);
// BUG: every handler logs 3 — the loop variable is function-scoped
for (var slot = 0; slot < 3; slot++) {
  buttons[slot].onclick = () => book(slot);
}

// FIX: block-scoped binding gives each handler its own slot
for (let slot = 0; slot < 3; slot++) {
  buttons[slot].onclick = () => book(slot);
}
// BUG: functional updates ignored — counter sticks at 1
useEffect(() => {
  setInterval(() => setSteps(steps + 1), 1000);   // always initial steps
}, []);

// FIX: update from previous state, and own the interval
useEffect(() => {
  const id = setInterval(() => setSteps(s => s + 1), 1000);
  return () => clearInterval(id);
}, []);

Quick fixes for frequent errors

| Error | Fix | |---|---| | Cannot read property 'x' of undefined | invoice?.customer?.name ?? 'Unknown' when absence is valid; repair the producer when it is not | | Unhandled promise rejection | Attach .catch or wrap the await in try/catch — never swallow into silent success | | React "Too many re-renders" | Remove state updates from render; move side effects into useEffect | | CORS error | Server sends correct origin/credentials headers; or a dev proxy keeps requests same-origin. Do not disable browser security | | Maximum call stack size exceeded | Add the recursion base case (if (n <= 1) return 1;); circular objects need a serializer that breaks cycles | | Module not found | Install the package, check ./ relative vs package path and ESM extensions; reinstalling node_modules is a last resort, done with the user's OK | | await outside async | Mark the function async (or use top-level await where the runtime supports it) | | forEach with async callback | Use for...of when order matters, or Promise.all(items.map(...)) when parallel |

// BUG: nested optional data crashes the invoice view
const city = order.delivery.address.city;

// FIX: guard each level, or validate at the boundary
const city = order?.delivery?.address?.city ?? '—';
// BUG: new object identity every render re-fires the effect
useEffect(() => { loadFilters({ sort: 'name' }); }, [{ sort: 'name' }]);

// FIX: stabilize the dependency
const filters = useMemo(() => ({ sort: 'name' }), []);
useEffect(() => { loadFilters(filters); }, [filters]);

Escalation: the three-fix threshold

After three failed fix attempts, stop. Failures landing in different places each time usually mean an architectural assumption is wrong, not three separate bugs. At the threshold:

  1. Stop patching symptoms and write down the pattern of failures.
  2. Name the violated assumption (data ownership, lifecycle, concurrency).
  3. Propose a structural change instead of the next patch, and discuss it with

the user before more edits.

Reset to Phase 1 early if edits are piling up, hypotheses got vague, the reproduction stopped reproducing, or fixes keep moving the error elsewhere.

Report format

Finish every investigation with these four items:

  1. Root cause — the specific mechanism, not "a race condition somewhere".
  2. Evidence — the stack trace, log lines, or failing test that proves it.
  3. Fix — the minimal change, with the regression test that now passes.
  4. Prevention — the guard, test or convention that stops a recurrence.

Never

  • Ship a fix without a reproduction and a failing-then-passing regression test.
  • Stack multiple experimental changes into one edit — a pass then proves nothing.
  • Leave console.log, debugger or breakpoint() statements in delivered code.
  • Expose a debugger port beyond loopback, attach to processes you don't own, or debug against production without explicit user approval.
  • Delete node_modules/lockfiles or reinstall dependencies as a reflex fix without the user's go-ahead.