Plain Reckoner
English

← Blog

Plain Reckoner Team · Release date:

Selected source checked:

AI Debugging with Python pdb: Stop Guessing and Prove the Fix

A coding agent can read a traceback and suggest a plausible fix without seeing the value that caused the failure. Use a debugger to inspect a reproducible case, then check the fix against an independent test. This walkthrough uses Python’s built-in pdb and a deliberately broken local example. It is not a benchmark of an AI agent.

Reproduce the failure

The requirement is specific: an order totaling 100 qualifies for free shipping. The sample function uses total > 100, so a test for 100 fails. Download the example, enter its directory, and run:

python3 -m unittest discover -s . -v

In our local run, test_threshold failed. That result tells us the requirement is not met; it does not by itself tell us why. Check the error and confirm that the test reached the intended assertion rather than failing in setup.

The test checks three independently specified inputs: 99 → no free shipping, 100 → free shipping, and 101 → free shipping. Before the fix only the 100 case failed; after the change all three passed. A passing result still applies only to these cases.

Recorded failing test output, reformatted for readability.

Recorded failing test output, reformatted for readability.

Stop at the comparison

Run python3 -m pdb shipping.py. At the debugger prompt, enter break 2, continue, p total, and list. Our local run stopped inside the function, printed 100, and showed return total > 100. The observed input and comparison explain this particular failure. Exit with quit.

The code and test are small enough to inspect without an agent. In a larger application, a breakpoint can provide a concrete runtime value to an assistant rather than another guessed patch. Treat captured values as potentially sensitive: do not share credentials, customer data, or production request bodies with an external service.

Recorded debugger output shows total 100 at the greater-than comparison.
Recorded local debugger output, reformatted; paths shortened.

Recorded debugger output, reformatted from the local transcript; paths were shortened.

Fix and verify

Change > to >= and rerun the unittest command. In our local run the test passed. Add cases below and above the threshold if those behaviors matter to the application. A single passing test does not establish that the rest of the application works, and the demonstration says nothing about how often any model makes this mistake.

Recorded passing test output after the correction, reformatted for readability.

Recorded passing test output after the correction, reformatted for readability.

Give an agent evidence, not a vague instruction

Provide the requirement, the exact failing test, a sanitized traceback, the breakpoint location, and the observed value. Ask the agent to explain the mismatch before editing. Review the diff and rerun the relevant tests independently. If the result depends on an external service or unavailable environment, record that limitation instead of calling the work complete.

When a debugger is available to the agent

Microsoft’s open-source DebugMCP documents a debugger interface for coding agents, and Microsoft Research’s debug-gym provides an environment for interactive debugging. Check their current setup instructions and permission boundaries before use. We did not run either tool in this example. The research paper Debug2Fix studies interactive debugging in a particular evaluation setup; its findings are not a guarantee for another project or agent.

Python’s pdb documentation explains breakpoints, stepping and inspecting state. Continue with the site’s generated-test and agent-completion guides to check whether a passing test actually covers the requirement and whether the complete task was verified.

Python pdb commands that answer a specific question

Choose a debugger command because it tests a hypothesis. list shows the nearby source; it does not execute it. p total evaluates an expression in the current stack frame. next advances within the current function, while step can enter a called function. where shows the call stack, and up or down changes which frame you inspect. continue resumes until another stop. These commands are documented in the Python debugger reference.

Question Command What to check
Did the expected input reach the function? p total Compare the value with the failing test’s input.
Am I stopped in the code I meant to inspect? list Check the filename, line and comparison.
Who called this function? where Follow the relevant caller rather than assuming the first frame caused the defect.
What happens after this line? next Inspect changed values after the line executes.
What happens inside this function call? step Enter the call when its behavior is the unanswered question.

In the shipping example, the breakpoint is before the return expression runs. That is why the value 100 is useful evidence: it reaches the exact comparison we want to investigate. If you stop in another frame and print a variable with the same name, you may be examining a different value. Confirm the frame before interpreting the result.

For automated reproduction of this trusted sample, the same commands can be supplied on standard input. The interactive form is easier when you are still choosing a hypothesis:

printf 'break 2\ncontinue\np total\nlist\nquit\n' | python3 -m pdb shipping.py

A debugger can evaluate Python expressions, including expressions with side effects. Prefer simple inspection while establishing the cause. Calling an application method from the debugger can itself change state and alter what you are trying to observe.

A second example: a test passes alone but state leaks between calls

An agent working on a task-history helper might produce a function that looks reasonable at first glance:

def record_event(event, history=[]):
    history.append(event)
    return history

Here the requirement is that calls without an explicit history start independently. A caller can also supply an existing list and ask the function to extend it. Those are two distinct behaviors, and the tests in the downloadable example check both.

A single call does not expose the isolation problem. Run the included script from a fresh process:

python3 history.py

It calls the function with first-task, then with second-task, and prints both results plus whether they are the same object. In our local run, both results contained both events and Same list was True. The first returned value changed after the second call because both names refer to the same list. That is stronger evidence than seeing two similar-looking strings in a log: object identity explains the connection.

Recorded Python output shows both results contain both events and refer to the same list.

Actual local output, reformatted for readability. Both returned names refer to one list.

Python evaluates default argument values when the function definition is executed. The list in this definition therefore survives across calls to that function object. The official Python tutorial describes this behavior. Creating a new process creates a fresh function and default list; restarting between every call can hide the bug instead of testing the intended sequence.

Use this correction when omitted history should mean a fresh list:

def record_event(event, history=None):
    if history is None:
        history = []
    history.append(event)
    return history

Check for None explicitly. Replacing the condition with if not history would also replace an intentionally supplied empty list, changing the caller-owned-list behavior. The second test protects that behavior by checking the returned value and its identity with the supplied list.

Run the tests for this example separately so the intentionally broken shipping function does not obscure the result:

python3 -m unittest discover -s . -p test_history.py -v

In our local check the independence assertion failed with the original function and passed after the correction. The explicit-history test passed in both versions. The downloadable verifier performs the change in a temporary copy, so you can repeat the experiment without overwriting the supplied broken examples:

python3 verify_examples.py

A passing verifier means these particular checks behaved as expected before and after their corrections. It does not evaluate a coding model or establish that every possible input is correct. The examples use trusted local files, require no API key and do not call an AI service.

A practical Claude Code debugging prompt

The following prompt also works as a task brief for another coding assistant. The useful part is the evidence it requests and the limits it places around a proposed change. It is a template to adapt, not a prompt with measured success rates.

Requirement: calls without an explicit history must be independent.
Calls with an explicit list must append to and return that same list.

Reproduce the failure with test_history.py before editing history.py.
Show the assertion that fails and explain why it reaches the behavior
in the requirement. Inspect the values and whether the results share
an object. Propose the smallest correction that preserves explicit
list behavior. Keep the test expectations independent of the code.

After editing, run the same tests again. Report the command, working
directory, exit status and uncovered cases. If a check could not run,
say which dependency is missing. Do not claim unrun checks passed.

Give the assistant the small relevant files, the actual failure and the acceptance conditions. If an earlier attempt changed the test to match the implementation, review that diff before using it as the new baseline. Otherwise the assistant can improve agreement between code and tests while moving away from the requirement.

Anthropic’s Claude Code best practices describe providing missing context and a check to run. Our examples apply that workflow to observable local behavior. We have not run a controlled comparison between this prompt and another prompt, so there is no defensible percentage improvement to attach to it.

What to do when AI keeps fixing the same bug

After a failed correction, return to the earliest observation that the proposed explanation does not account for. In the history example, a patch to formatting cannot explain shared object identity. In the shipping example, changing a caller cannot justify excluding a threshold that the requirement explicitly includes. State the contradiction in one sentence, then choose a check that can distinguish the competing explanations.

Keep the reproduction stable while investigating. Changing the input, dependencies, test expectations and implementation at the same time makes a green result harder to interpret. Save the original failing case, then change one relevant thing and repeat the same check. If the failure depends on process lifetime, run the sequence in one process. If it depends on test order, retain the order in the reproduction and investigate the shared state rather than hiding the problem with retries.

Use a compact handoff if the conversation has become crowded with failed attempts. Include the requirement, exact command, observed result, current hypothesis and one unanswered question. Link to the relevant files instead of copying a whole repository into the prompt. A new session may reduce distracting conversation history, but it does not resolve missing evidence by itself.

If the problem cannot be reproduced safely, preserve the uncertainty. You can still inspect the diff and collect sanitized logs, but do not claim that an unobserved incident has been reproduced. Production concurrency, provider behavior and customer-specific data require their own access controls and investigation. These small deterministic examples intentionally avoid those dependencies.

Questions to check before accepting an AI debugging fix

Does a passing test prove the bug is fixed?

It supports the behavior checked by that test under that setup. Verify that the test fails on the defective version for the intended reason and passes on the correction. Also check the neighboring cases and any required integration behavior. An import error on the old version does not establish that the test detected the defect.

Why does unittest say one test ran when there are three inputs?

The shipping example uses one test method with three subTest cases. The runner reports one test method and identifies a failing subtest with its input, such as total=100. Three input checks are not three independent test methods. Read the test source together with the summary so you know what the count means.

Should I install a debugger MCP server first?

Start with the smallest tool that answers the current question. Python’s built-in debugger is enough for these examples. An agent-facing adapter can help an assistant inspect runtime state directly, but it introduces its own setup, permissions and compatibility requirements. Follow the tool’s current documentation and verify an end-to-end session before reporting that it works in your environment.

Will these steps reduce tokens or guarantee a correct fix?

We did not measure token use or model success rates. A focused reproduction gives the assistant concrete evidence and reduces the number of unresolved assumptions, but cost and correctness still depend on the task, tools, model and review. Measure your own workflow if token savings are part of the decision.

Download the code and check the record

The example archive includes both deliberately broken functions, their tests, the temporary-copy verifier and recorded output. Start with README.txt, then run the individual failing example or the verifier. Keep the faulty versions if you want to repeat the demonstration.

For related checks, see reviewing generated tests, verifying that tests actually ran and catching false completion. Each addresses a separate part of the evidence chain: what the assertions mean, what executed and whether the whole requested task was finished.

Source checked November 16, 2026: Python debugger documentation · default argument semantics. Tested November 16, 2026: the two local examples fail before their specified corrections and pass afterward on Python 3.15.2. No coding model was evaluated.

Download code and recorded output ↗