feat(diagnose): add Python feedback-loop and instrumentation references

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Łukasz Boryń 2026-06-11 12:06:40 +02:00
parent 1fee9ca488
commit f0983ea2ef
3 changed files with 202 additions and 6 deletions

View File

@ -21,8 +21,9 @@ you don't, you are guessing.
### 1. Build the feedback loop
Before hypothesising, construct a reproducible pass/fail signal. Iterate on
the loop itself until it runs in seconds and the failure is unambiguous.
See [feedback-loops-r.md](feedback-loops-r.md) for R recipes (testthat,
`targets`, bookdown, shiny) and two canonical worked examples.
Recipes + two worked examples per language:
[feedback-loops-py.md](feedback-loops-py.md) (pytest) /
[feedback-loops-r.md](feedback-loops-r.md) (testthat, `targets`, bookdown).
### 2. Reproduce
Run the loop. Confirm it triggers the **exact** symptom the user reported,
@ -43,10 +44,11 @@ instrumentation.
### 4. Instrument
Map each test to **one** Phase-3 prediction. Change one variable at a time.
Prefer interactive inspection over logging — see
[instrumentation-r.md](instrumentation-r.md) for `browser`, `debugonce`,
`rlang::entrace` / `last_trace`, `lobstr::cst`, `profvis`, and the
`### DIAGNOSE-<date>` tag convention so cleanup is `grep`-able.
Prefer interactive inspection over logging —
[instrumentation-py.md](instrumentation-py.md) (`breakpoint`, `--pdb`,
`cProfile`) / [instrumentation-r.md](instrumentation-r.md) (`browser`,
`debugonce`, `profvis`) — plus the `### DIAGNOSE-<date>` tag convention so
cleanup is `grep`-able.
### 5. Fix + regression test
Hand off to [tdd-bdd](../tdd-bdd/SKILL.md):

View File

@ -0,0 +1,111 @@
# Feedback loops in Python
A bug you can reproduce in 2 seconds with one keystroke is half-fixed. The
loop **is** the product of phase 1. Spend time on it.
## Loop recipes, fastest first
### A single pytest test
The gold standard. Run one test, quiet, stop on first failure.
```bash
just test ARGS="tests/test_assemble.py::test_idempotent -x -q"
# or directly in the dev container:
pytest tests/test_assemble.py::test_idempotent -x -q
```
`-k` selects by name substring; `--lf` reruns last-failed; `-p no:cov`
drops coverage overhead while hunting.
### A single function, no test yet
`python -c` or a 5-line script that prints `PASS` / `FAIL` and exits
non-zero. That is a valid loop.
```bash
python -c "from mypkg.norm import normalize_chrom; assert normalize_chrom('chr1')=='1'; print('PASS')"
```
### A notebook bug
Don't re-run 40 cells. Extract the failing logic into a `.py` module and
drive it from one pytest test — also where the fix will live.
## Make the loop deterministic
- **Seed every RNG**: `np.random.default_rng(42)`, `random.seed(42)`.
Never rely on global `np.random` state.
- **Pin env**: `monkeypatch.setenv("TZ", "UTC")`, `("PYTHONHASHSEED", "0")`.
- **Freeze versions**: you already build in Docker off `uv.lock` — rules
out "broke because pandas 2.2 changed a default".
- **Isolate the filesystem**: `tmp_path`, never the repo tree.
- **Kill ambient network** so a hung NCBI call can't masquerade as a bug
(see [../tdd-bdd/mocking-py.md](../tdd-bdd/mocking-py.md) autouse fixture).
If the same loop gives two different answers in a row, **fix the loop
before phase 2**.
---
## Worked example 1 — in-place mutation, intermittently wrong output
**Symptom (user):** `assemble_expr()` sometimes returns a frame with the
wrong totals; running the same step twice gives different results.
**Phase 1 — build the loop.** Compress to an idempotence test:
```python
def test_assemble_expr_is_idempotent():
"""Given one raw frame, when assembled twice, then both results match."""
raw = make_raw_fixture()
pd.testing.assert_frame_equal(assemble_expr(raw), assemble_expr(raw))
```
`pytest tests/test_assemble.py -x -q` fails on the second call. Loop is
deterministic and 0.3 s.
**Phase 3 — hypotheses.** H1: `assemble_expr` mutates `raw` in place
(pandas view aliasing). Prediction: a defensive `raw = raw.copy()` makes
call two match call one.
**Phase 4 — instrument.** One tagged line:
```python
def assemble_expr(raw: pd.DataFrame) -> pd.DataFrame:
raw = raw.copy() ### DIAGNOSE-2026-06-11
...
```
Test passes. H1 confirmed.
**Phase 5 — regression test** = the idempotence test. Move the copy from
the diagnostic patch into the real fix at the contract boundary (return a
fresh frame, don't mutate the argument — see
[../tdd-bdd/interface-design-py.md](../tdd-bdd/interface-design-py.md)).
**Phase 6 — cleanup.** `grep -rn "### DIAGNOSE-" .` → zero hits. Commit:
*"fix(assemble_expr): return a fresh frame — H1: pandas view aliasing
caused non-idempotent totals"*.
---
## Worked example 2 — flaky test that depends on RNG
**Symptom (user):** `test_top_terms_stable` passes locally, fails ~1/10 on CI.
**Phase 1 — build the loop.** Run it many times via the plugin
`pytest-repeat`, or a shell loop:
```bash
for i in $(seq 50); do
pytest tests/test_textmining.py::test_top_terms_stable -q \
|| { echo "FAIL on iter $i"; break; }
done
```
Fails on iteration 7. Reproduces in < 30 s.
**Phase 3 — hypotheses.** H1: the fixture samples with an unseeded
generator; ties in the z-score ranking sort differently per run. H2:
dict/set iteration order via unset `PYTHONHASHSEED`. H1 more likely (the
mock matrix is tiny → ties common).
**Phase 4 — instrument.** Pass a seeded generator into the fixture; rerun
the 50× loop. All green. H1 confirmed; H2 not pursued (one variable at a
time).
**Phase 5 — regression test:** the seeded test *is* the regression test.
**Phase 6 — cleanup.** Nothing to revert. Commit: *"test(textmining): seed
RNG to stabilise tie-break — H1 confirmed"*. File a follow-up: production
`score_terms()` should break ties on a stable key (`term_id`), not input
order → [../tdd-bdd/refactoring-r.md](../tdd-bdd/refactoring-r.md) candidate.

View File

@ -0,0 +1,83 @@
# Instrumentation in Python
Phase 4 of `diagnose`. The rule: **prefer interactive inspection over
logging, change one variable at a time, tag every line you add so cleanup
is `grep`-able**.
## Interactive inspection (prefer these)
### `breakpoint()`
Drop a breakpoint at the suspected frame and poke around (honours
`PYTHONBREAKPOINT`; defaults to pdb).
```python
def assemble_expr(raw: pd.DataFrame) -> pd.DataFrame:
breakpoint() ### DIAGNOSE-2026-06-11
df = raw.pipe(reshape).pipe(rename)
return df
```
At the prompt: `pp df.head()`, `df.dtypes`, `raw.shape`, `n` step, `c`
continue, `q` abort, `w` show the stack.
### pytest `--pdb` / `--trace`
Drop into the debugger without editing code.
```bash
pytest tests/test_assemble.py::test_idempotent --pdb # break at the failure
pytest tests/test_assemble.py::test_idempotent --trace # break at test start
```
`--pdb` opens the frame *at the moment of the exception* — best
post-mortem when you don't yet know which line throws. No cleanup needed.
### Post-mortem on a script
```python
import pdb, traceback, sys
try:
main()
except Exception: ### DIAGNOSE-2026-06-11
traceback.print_exc(); pdb.post_mortem(sys.exc_info()[2])
```
Reset by deleting the tagged block in cleanup.
## Logging (only when interactive isn't possible)
When the bug only repros non-interactively (CI, a `multiprocessing`
worker, a long batch run), print *with the diagnose tag*:
```python
print(f"### DIAGNOSE-2026-06-11 assemble_expr: shape={df.shape} "
f"sha={pd.util.hash_pandas_object(df).sum()}", file=sys.stderr)
```
No tag, no cleanup. `pytest -s` lets prints through; `caplog` captures
`logging` records if the code already logs.
## Performance bugs
### `cProfile` → find the dominant call
```bash
python -m cProfile -s cumtime -m mypkg.pipeline | head -20
```
One function dominating cumulative time → target it. Thousands of tiny
calls → a Python-level loop that should be vectorised (pandas/numpy/polars).
### `timeit` / `pytest-benchmark` for A/B
Once you have a hypothesis about the slow path:
```python
def test_assemble_faster(benchmark):
benchmark(new_assemble, raw) # pytest-benchmark plugin
```
Line-level attribution: `line_profiler`'s `@profile` on the suspect
function.
## The `### DIAGNOSE-<date>` tag convention
- **Every** line you add for diagnosis carries `### DIAGNOSE-YYYY-MM-DD`.
- One date format, one tag, one regex finds them all.
- Phase 6 ends only when `grep -rn "### DIAGNOSE-" .` returns zero hits.
## Anti-patterns
- **`print()` without a tag** — survives into commits. (ruff's `T201` flags
bare prints; lean on it.)
- **Multiple hypotheses instrumented at once** — loses the signal.
- **Editing the function under test to "make it work"** while still
collecting evidence — that's a fix smuggled into instrumentation.
- **Leaving `breakpoint()` in** — hangs CI waiting on stdin. ruff `T100`
catches it; let the linter gate the commit.