Sub topic 10
Common failure modes and how to spot them
This chapter assumes you can write and run Python code and tests, and that you have used a chat or editor-integrated AI assistant. It also assumes you have read the earlier chapters on goals, context, constraints, examples, and verification. Here you will learn the ways generated code usually goes wrong, the signs that give each one away, and what to change in the prompt or the review process.
Why failures look convincing
An assistant produces text that is likely to follow from your prompt. It does not run your code, read your repository, or know your deadline. Because its output is fluent and confidently formatted, wrong code reads the same as right code.
Most failures fall into a few families. Each has a cause you can name, a symptom you can check, and a fix.
| Failure mode | Typical cause | Quick check |
|---|---|---|
| Invented API | Missing version or library context | Import it and call it |
| Wrong version or style | Language or framework version not stated | Compare against your runtime |
| Quietly changed scope | Vague goal or missing "do not change" rule | Read the diff, not the summary |
| Missed edge case | No examples for odd inputs | Run boundary inputs |
| Wrong output shape | No output format requested | Parse it with your own tooling |
| Drift in long chats | Early constraints forgotten | Restate constraints, start fresh |
| Confident but wrong explanation | The assistant describes what it intended, not what the code does | Run the code and compare |
Invented or misremembered APIs
The assistant may call a function that does not exist, or use a real function with the wrong arguments. This is often called a hallucination. It happens most with less common libraries, recent releases, and project-specific code the assistant has never seen.
Signs to look for:
- An import you do not recognize, or a method name that sounds right but is not in the documentation.
- A keyword argument that your installed version rejects.
- A helper that "should" exist in your codebase, such as
utils.sanitize_input, but does not.
Here is a small example. Suppose you asked for code that finds the most common word in a string, and the response included this line:
words = text.split_words()Python strings have no split_words method. Running the code fails immediately:
text = "the cat and the hat"
try:
words = text.split_words()
except AttributeError as error:
print(error)The output is 'str' object has no attribute 'split_words'. This is the good case, because the failure is loud. The dangerous case is an invented function that exists but behaves differently from what its name suggests.
How to prevent and catch it:
- State the library and exact version in the prompt, for example "pandas 2.1".
- Paste the relevant signature or a short documentation excerpt when the library is niche.
- Run the code before reading it closely. An
ImportErrororAttributeErrorcosts seconds. - Check unfamiliar calls against the official documentation, not against a second prompt to the same assistant.
Wrong version, wrong style
A response can be valid code for a different version of the language or framework than yours. Common examples are typing.List[int] where your project uses list[int], os.path where your codebase uses pathlib, or a deprecated framework call that your version has removed.
The code often runs, so the problem shows up later as warnings, failing linters, or a review comment that it does not match the rest of the project. The fix is context. Name the version, and state the style rule as a constraint:
Context: Python 3.10, pathlib is used everywhere, type hints use built-in generics (list[int]).
Constraints: no new dependencies; follow the existing snake_case naming.Quietly changed scope
When you ask for a fix, an assistant may also rename variables, reformat the file, remove a "redundant" check, or add a feature you did not request. Each change is small, but together they make the diff hard to review and can break behavior elsewhere.
Signs to look for:
- A diff much larger than the problem you described.
- Deleted lines you did not mention.
- New parameters, new files, or new dependencies.
- A summary that says "I also improved..."
Prevent it with explicit scope rules, such as "change only the parse_row function" or "do not modify any other function, import, or formatting". Catch it by reading the actual diff:
git diff --stat
git diff--stat shows how many lines changed in each file. If it lists files you did not expect, stop and investigate before reading anything else.
Missed edge cases
The assistant tends to write the most common path well. It misses empty input, None, very large values, Unicode, negative numbers, and duplicate entries unless you point to them.
Consider the slugify function from earlier chapters. The prompt said titles are plain ASCII, and the response was correct under that assumption. Now see what happens when the assumption is broken:
import re
def slugify(text: str) -> str:
text = text.strip().lower()
text = re.sub(r"[^a-z0-9]+", "-", text)
return text.strip("-")
print(repr(slugify("Café Münster")))
print(repr(slugify("")))
print(repr(slugify("!!!")))The output is:
'caf-m-nster'
''
''The accented letters are treated as separators, so the result loses characters and may collide with other titles. Empty and symbol-only input both return an empty string. The function follows its stated rules, but the rules did not cover these cases.
This is a requirements gap, not an assistant bug. The assistant did what the prompt said. To close the gap, decide what you want and add it as an example:
slugify("Café Münster") -> "cafe-munster"
slugify("!!!") -> raises ValueErrorThen ask for a revised function. Writing the edge case as an input and output pair gives you a test case at the same time.
Tests that pass for the wrong reason
If you ask the assistant to write both the code and the tests, the two can share the same misunderstanding. The tests then pass, and you learn nothing.
Warning signs:
- Tests that only repeat the implementation, such as computing the expected value with the same expression the function uses.
- No tests for errors, empty input, or boundaries.
- Assertions that are always true, such as
assert result is not None. - Mocks that replace the very thing being tested.
Here is a weak test next to a useful one:
import pytest
from slugify_module import slugify
def test_weak():
assert slugify("Hello, World!") is not None
@pytest.mark.parametrize(
"text, expected",
[
("Hello, World!", "hello-world"),
(" Multiple spaces ", "multiple-spaces"),
("", ""),
],
)
def test_strong(text, expected):
assert slugify(text) == expectedtest_weak passes for almost any function that returns a value. test_strong fails if the output changes. Write the expected values yourself, from your own requirements, before you look at the generated code.
A useful check is to break the code on purpose. Change one character in the implementation, such as replacing "-" with "_", and run the tests. If they still pass, they are not testing what you think.
Wrong output shape
When you do not say how the answer should be delivered, you get whatever the assistant prefers: explanation first, code in several fragments, a full file when you wanted a diff, or comments saying # rest of the code unchanged.
That last pattern is a trap. If you paste the response over your file, the placeholder comment replaces real code. Prevent it with the output format line from the template, for example "Return the complete function, with no placeholder comments." Catch it by searching the response for phrases such as rest of, ..., and unchanged before you copy anything.
Drift in long conversations
In a long chat, early instructions lose influence. After many turns the assistant may stop following a constraint you set at the start, such as "standard library only", and import a third-party package.
Signs to look for:
- A constraint that was respected in the first answer and broken in the tenth.
- Variable names or style that change between responses.
- The assistant "fixing" a bug by undoing an earlier fix.
Two habits help. First, restate the constraints that matter in each new request, in one line. Second, when a conversation has gone through many revisions, start a new one. Paste the current code, the goal, and the constraints, and leave out the history. A fresh, complete prompt is often more reliable than a long thread.
Confident but wrong explanations
An assistant can describe its code accurately in one sentence and inaccurately in the next. Explanations such as "this runs in O(n) time" or "this is thread-safe" are generated the same way as code, and they are not checked.
Treat claims about performance, security, and concurrency as statements to test. Time the function on realistic input. Run it under concurrent load. Ask a human reviewer or a dedicated tool, such as a linter or a security scanner, for a second opinion. A claim in a response is a hypothesis, not evidence.
A triage workflow
When a response looks wrong, or looks right but you are not sure, work through the same order each time. Cheap checks come first.
Each loop back to "Run the code" follows a prompt change, which connects this chapter to the iteration chapter. The goal is to turn each failure into a better prompt, not only a patched answer.
Diagnosing the cause
Before you rewrite a prompt, decide which part was missing. This table maps symptoms to the prompt section that probably needs work.
| Symptom | Likely missing section |
|---|---|
| Uses a library you do not have | Constraints (allowed libraries) |
| Code runs on a newer Python only | Context (language version) |
| Handles normal input but fails odd input | Examples |
| Solves a different problem | Goal |
| Response cannot be pasted directly | Output format |
| Result is too large to review | Decomposition (split the task) |
A callout to keep in mind:
Putting it together
Suppose you asked for a function that reads a CSV file and returns the total of a price column. The response imports pandas, which you did not install, ignores rows with empty prices, and ends with # rest of the module unchanged. Three failures appear at once: a constraint was missing (standard library only), an edge case was undefined (what to do with empty values), and the output format was unspecified.
A revised prompt fixes all three:
Task: Write read_total(path: str) -> float that sums the "price" column of a CSV file.
Context: Python 3.10, standard library only.
Constraints: treat an empty price as 0; raise ValueError if the column is missing.
Examples: a file with prices 1.50, "", 2.25 -> 3.75
Output format: return only the complete function, no placeholder comments.Notice that each added line answers one specific failure. That is the practical value of knowing the failure modes: you can read a bad response as a list of prompt gaps.
Exercise
An assistant's fix for a failing function also renames three variables and reformats the file. The tests pass. Name the failure mode, one way to detect it, and one line to add to the next prompt.
Show answer
This is quietly changed scope. Detect it by running git diff --stat and git diff and noticing changes unrelated to the bug. Add a scope rule such as "Change only the function parse_row. Do not rename variables, reformat code, or modify anything else."
Exercise
You asked an assistant to write a function and its tests. All tests pass, but you suspect they are weak. Describe a quick experiment that shows whether they are.
Show answer
Break the implementation on purpose, for example change one operator or constant, and rerun the tests. If they still pass, they do not check that behavior. Also write your own expected values from the requirements and compare them with the generated tests.