Sub topic 12
Privacy, accuracy, and maintenance risks
This chapter assumes you can run pytest, read a Git diff, and have already used an assistant to draft tests and docstrings for a function like apply_discount. It covers what can go wrong after the draft exists. There are three risks: what you send to the assistant, what it gets wrong, and what the output costs you over time.
The three risks
| Risk | Where it happens | Typical failure |
|---|---|---|
| Privacy | When you write the prompt | Secrets or customer data leave your machine |
| Accuracy | When you read the output | Plausible tests or docs that describe behavior the code does not have |
| Maintenance | Weeks after you merge | Generated tests that break on every refactor, and docs that no longer match the code |
The first risk is prevented before you press enter. The second is caught during review and verification. The third is controlled by the process you build around the output.
Privacy: what leaves your machine
Everything in a prompt is data sent to a service. That includes the pasted function, any file the assistant reads on its own, error output, and sample inputs. Whether the provider stores it, logs it, or trains on it depends on your plan and your organization's agreement. Check that policy before assuming anything. The code you paste can also contain things the function does not need.
Common leaks when generating tests and docs:
- Hard-coded credentials in a module you paste whole to get tests for one function.
- Real customer records used as fixtures. A test generator often copies sample values straight into assertions.
- Internal hostnames, ticket numbers, and employee names in comments or docstrings.
- Proprietary algorithms in a repository whose license or contract forbids third-party processing.
- Production log lines pasted to explain a bug, which often contain emails, tokens, or IP addresses.
Reduce what you send
Send the smallest slice that lets the assistant do the job. For apply_discount, that is the function and its docstring. It is not the whole pricing.py with its database settings. When the assistant reads files itself, as in an agentic CLI, also check which directories it can see. Keep .env files and credential folders out of its reach, or out of the project directory.
A cheap guard is a pre-send scan. The script below flags lines that look like secrets or personal data. It is a coarse filter and will miss things, so treat a clean result as "no obvious problems", not as proof.
import re
import sys
from pathlib import Path
PATTERNS = {
"AWS access key ID": re.compile(r"AKIA[0-9A-Z]{16}"),
"private key block": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
"hard-coded credential": re.compile(
r"(?i)(password|secret|token|api_key)\s*=\s*['\"][^'\"]{8,}['\"]"
),
"email address": re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+"),
}
def scan(path):
"""Return a list of (line_number, label) for suspicious lines."""
findings = []
text = Path(path).read_text(encoding="utf-8")
for number, line in enumerate(text.splitlines(), start=1):
for label, pattern in PATTERNS.items():
if pattern.search(line):
findings.append((number, label))
return findings
if __name__ == "__main__":
exit_code = 0
for name in sys.argv[1:]:
for number, label in scan(name):
print(f"{name}:{number}: possible {label}")
exit_code = 1
sys.exit(exit_code)Run it as python scan_prompt_input.py pricing.py before you paste a file. The nonzero exit code means you can also use it as a pre-commit hook or a CI step.
Fixtures and synthetic data
Ask the assistant to invent test data instead of showing it real data. A prompt line such as "Use obviously fake values like [email protected] and ID 12345" works well. Review the generated tests for values that look real. A name, a phone number, or an address that the assistant "remembered" from your pasted data will now be committed to the repository.
Accuracy: plausible is not correct
An assistant predicts likely text. It does not run your code unless you give it a tool that does. Its output can therefore read well and still be wrong. The earlier chapters on reviewing tests and verifying docs gave you the checks. Here is why you need them and where the errors tend to hide.
Wrong in ways that look right
- Invented APIs. Generated tests may call a helper, fixture, or keyword argument that does not exist in your version of the library. These fail loudly, which is the good case.
- Behavior copied from the code, not the contract. If the code has a bug, a test written from the code asserts the bug. This is the tautology problem from the review chapter, and the reason the prompt told the assistant to derive expected values from the docstring.
- Prose that overstates. A docstring can say a function "rounds half up" when the implementation does not.
- Silent omissions. The
Raisessection lists one exception when the code can raise two, or a README documents a flag that was removed.
A worked example: rounding
Suppose the assistant describes apply_discount as rounding half up. Python's built-in round rounds exact halves to the nearest even digit. A price of 0.25 with a 50 percent discount gives exactly 0.125 in binary floating point, so the result is 0.12, not 0.13. A docstring example run as a doctest exposes this:
def apply_discount(price: float, percent: float) -> float:
"""Return price reduced by percent, rounded to two decimals.
Exact halves round to the nearest even cent (Python's round), not up.
Examples:
>>> apply_discount(100, 10)
90.0
>>> apply_discount(0.25, 50)
0.12
"""
if price < 0:
raise ValueError("price must be non-negative")
if not 0 <= percent <= 100:
raise ValueError("percent must be between 0 and 100")
return round(price * (1 - percent / 100), 2)If the docstring had claimed 0.13, python -m doctest pricing.py would print a failure showing expected 0.13 and got 0.12. That is the value of an executable example: the claim and the check are the same text.
Whether banker's rounding is right for money is a separate decision. For real currency code you would likely use decimal.Decimal. The point here is that the doc must state what the code does, and a human must decide whether that is what the code should do.
What a passing run does and does not prove
A green test suite shows that the assertions hold. It does not show that the assertions are the right ones. Two habits close the gap:
- Mutation check by hand. Change the code on purpose, for example
<=to<in the percent check, and confirm a test fails. If nothing fails, the boundary tests are decorative. - Read the expected values first. Before running, check each expected number against the spec. If you cannot explain a value, do not keep the test.
Maintenance: the cost arrives later
Generated output is cheap to produce, so it is easy to produce too much. Each test and each paragraph of documentation is something your team now owns.
Tests that are expensive to keep
- Over-mocked tests assert on call sequences and private helpers. They fail on any refactor even when behavior is unchanged. Prefer mocking at the boundary, like the HTTP client in
get_username, and asserting on results. - Near-duplicate tests appear when you regenerate for a function that already has coverage. Merge them into the existing
parametrizetable instead of adding a second file. - Snapshot-like assertions on long strings or full objects break on harmless changes. Assert on the fields that matter.
Documentation that drifts
Docs are accurate on the day they are written and decay as the code changes. Generated docs make this worse because nobody feels they wrote them. Use these defenses:
- Keep examples executable. Run doctests in CI so a changed return value fails the build.
- Keep prose close to the code. Docstrings drift slower than a separate wiki page.
- Regenerate on purpose. When a function's signature or exceptions change, regenerate its docstring and review the diff, rather than patching one line from memory.
A minimal CI step that enforces the doctest rule:
python -m doctest -v pricing.py
python -m pytest --doctest-modules pricing.py tests/The first command checks the docstring examples. The second runs them together with your unit tests. A doctest covers only the examples. It does not check the Args or Raises prose, so a human still reviews those when the signature changes.
Ownership, licensing, and attribution
Someone must be accountable for each merged line. The reviewer who approves a generated test owns it exactly as if they had typed it. Also check your organization's rules on AI-assisted contributions. Some projects require disclosure, and generated code can resemble licensed code. Open-source maintainers may ask that you note assistant use in the pull request description.
A decision flow before you prompt
A short checklist
Use this before merging generated work:
- The prompt contained no credentials, real customer data, or restricted code.
- Every expected value traces to the docstring or spec, not to the implementation.
- A deliberate code change makes at least one test fail.
- Docstring examples run under doctest in CI.
- Mocks sit at system boundaries, not around internal helpers.
- A named reviewer approved the change and owns it.
Exercise
A teammate pastes an entire billing.py into an assistant to get tests for one function. The file contains STRIPE_TOKEN = "sk_live_example_value_123" and a docstring example using a real customer's email. Name two privacy actions to take now and two changes to the workflow that prevent a repeat.
Show answer
Now: rotate the token, since it has been sent to a third party and should be treated as exposed, and remove the real email from the file and check whether it was committed anywhere. Prevent a repeat: send only the single function and its docstring instead of the whole file, and run a pre-send or pre-commit scan like the one in this chapter (plus replace real data with fake values such as [email protected]). Moving the token to an environment variable and keeping .env files out of the assistant's reach also counts.
Exercise
An assistant writes a docstring for apply_discount saying "rounds half up", and the generated test assert apply_discount(0.25, 50) == 0.13 passes review because "it looks right". What check would have caught this, and what does the real function return?
Show answer
Running the test, or a doctest with that example, would have failed, because apply_discount(0.25, 50) returns 0.12. Python's round rounds exact halves to the nearest even digit. (If the test somehow passed, a hand mutation check would show the assertion was not tied to real behavior.) The doc and the test must then be corrected to match the intended behavior, and the team should decide whether banker's rounding is acceptable for prices.