feat(diagnose): adopt loop-recipes taxonomy, completion gate, and minimisation

- Extract 10-recipe loop taxonomy + tighten/non-determinism principles
  into new sibling loop-recipes.md (language-agnostic)
- Shrink feedback-loops-{py,r}.md to worked-examples-only; both now
  under the 100-line cap (R: 146 -> 95, py: 111 -> 79)
- Phase 1: add four-bullet completion gate (red / tight / deterministic
  / agent-runnable) + "no red-capable command, no Phase 2" guardrail
- Phase 2: rename to "Reproduce + minimise"; add shrink-to-smallest
  sub-step
- Phase 5: add "no correct seam is itself the finding" escape valve
  pointing to refactoring-r.md instead of writing a lying test
- Phase 6: lead with "what would have prevented this bug?" framing

Adapted from mattpocock/skills diagnosing-bugs.
This commit is contained in:
Łukasz Boryń 2026-06-18 23:29:55 +02:00
parent 8b0455fabc
commit 22951e5b79
4 changed files with 108 additions and 110 deletions

View File

@ -19,18 +19,30 @@ you don't, you are guessing.
## Phases
### 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.
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).
Before hypothesising, construct a reproducible pass/fail signal — iterate
on the loop itself until it satisfies the gate below.
### 2. Reproduce
Recipe taxonomy: [loop-recipes.md](loop-recipes.md). Worked examples:
[feedback-loops-py.md](feedback-loops-py.md) / [feedback-loops-r.md](feedback-loops-r.md).
**Completion gate** (Phase 1 is done only when *all four* hold):
- [ ] **Red** on the bug — the assert names the user's exact symptom.
- [ ] **Tight** — seconds, not minutes.
- [ ] **Deterministic** — same verdict every run.
- [ ] **Agent-runnable** — unattended; no human prompt mid-loop.
**No red-capable command, no Phase 2.**
### 2. Reproduce + minimise
Run the loop. Confirm it triggers the **exact** symptom the user reported,
not a neighbour. *"Got an error"* is not the same as *"got `subscript out
of bounds` at `R/plot/build_plot.R:42`"*. If you can't reproduce, you
don't have the bug — go back to phase 1.
Once red, **shrink** the repro to the smallest scenario that still goes
red — cut inputs, callers, config, data one at a time, re-running after
each cut. Every remaining element must be load-bearing.
### 3. Hypothesise (before touching code)
Generate **3–5 falsifiable hypotheses**, ranked by plausibility. Each must
include a prediction the loop can decide.
@ -53,23 +65,27 @@ cleanup is `grep`-able.
### 5. Fix + regression test
Hand off to [bdd](../bdd/SKILL.md):
- State the bug as one Given/When/Then scenario.
- Translate into a failing testthat test at the **public** interface
- Translate into a failing test at the **public** interface
(see `../bdd/mocking-r.md` — do not reach past it).
- Watch it fail with the original error.
- Apply the fix. Watch it pass. Re-run the original user-facing scenario.
If no correct seam exists, **that is itself the finding** — the codebase
architecture is preventing the bug from being locked down. File a
[refactoring-r.md](../bdd/refactoring-r.md) candidate; don't write a test
that lies about the bug pattern.
### 6. Cleanup + post-mortem
Then ask: **what would have prevented this bug?**
- `grep -r "### DIAGNOSE-" .` and remove every tagged line.
- Confirm the bug no longer reproduces in the user-facing context
(re-render the book, re-run the pipeline end-to-end).
- Commit message names the confirmed hypothesis ("H1: `data.table`
reference semantics in `assemble_expr`") so future readers see the *why*.
- Note architectural follow-ups as
[refactoring-r.md](../bdd/refactoring-r.md) candidates; file them,
don't auto-fix in the same commit.
- File architectural follow-ups to [refactoring-r.md](../bdd/refactoring-r.md); don't auto-fix in the same commit.
## Guardrails
- **Never** skip phase 1. Hypothesising without a loop is guessing.
- **Never** test more than one hypothesis at a time — you lose the signal.
- **Never** apply the fix before the regression test fails for the right
reason.

View File

@ -1,44 +1,12 @@
# Feedback loops in Python
# Feedback loops in Python — worked examples
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 [../bdd/mocking-py.md](../bdd/mocking-py.md) autouse fixture).
If the same loop gives two different answers in a row, **fix the loop
before phase 2**.
Two worked instantiations of [loop-recipes.md](loop-recipes.md). Python
idioms: `pytest path::test -x -q` for a single test; `-k` for substring,
`--lf` for last-failed, `-p no:cov` to drop coverage overhead.
Determinism: `np.random.default_rng(42)` (never global `np.random`),
`monkeypatch.setenv("PYTHONHASHSEED", "0")`, `tmp_path` for filesystem
isolation; autouse network-kill fixture in
[../bdd/mocking-py.md](../bdd/mocking-py.md).
---

View File

@ -1,63 +1,12 @@
# Feedback loops in R
# Feedback loops in R — worked examples
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 testthat test
The gold standard. Run only the file you care about, with the minimal
reporter.
```r
testthat::test_file(
"tests/testthat/plot/test_build_plot.R",
reporter = "minimal"
)
```
Or from the shell:
```bash
Rscript -e 'testthat::test_file("tests/testthat/plot/test_build_plot.R", reporter="minimal")'
```
### A single `targets` target
Don't rebuild the whole pipeline. Name the broken target.
```r
targets::tar_make(names = "assemble_expr")
# Inspect upstream inputs without re-running:
targets::tar_load(c(modb_raw, gene_meta))
```
### A single bookdown chapter
Avoid re-rendering 40 chapters to debug one.
```r
bookdown::preview_chapter("Rmd/chapters/genetics.Rmd")
# or a one-liner that just knits one Rmd:
rmarkdown::render("Rmd/chapters/genetics.Rmd", quiet = TRUE)
```
### Shiny
```r
shinytest2::test_app("inst/app", filter = "broken-scenario")
```
### Worst case: an `Rscript` one-liner
When nothing native exists, write a 5-line script that prints `"PASS"` /
`"FAIL"` and exits non-zero on failure. That is your loop.
## Make the loop deterministic
- **Seed the RNG** at the top of the test or script:
`withr::local_seed(42)`.
- **Pin the environment.** `withr::local_envvar(c(TZ = "UTC", LC_ALL = "C"))`
kills locale and timezone flakiness.
- **Pin package versions** with `renv::snapshot()` before you start
hunting; rules out "it broke because dplyr 1.1 changed semantics".
- **Quarantine global options** with `withr::local_options(list(...))`.
- For `box::use` modules, `box::reload(R/modb/client)` between runs to
drop cached state.
If the same loop produces a different answer twice in a row, **fix the
loop before going to phase 2**.
Two worked instantiations of [loop-recipes.md](loop-recipes.md). R
idioms: `testthat::test_file(..., reporter="minimal")` for a single test;
`targets::tar_make(names = ...)` for one pipeline target;
`bookdown::preview_chapter()` for one Rmd; `shinytest2::test_app()` for
Shiny. Determinism: `withr::local_seed/local_envvar/local_options`,
`box::reload(R/<module>)` to drop cached `box::use` state,
`renv::snapshot()` to pin versions before hunting.
---

View File

@ -0,0 +1,65 @@
# Loop recipes — the taxonomy
A bug you can reproduce in 2 seconds with one keystroke is half-fixed.
Phase 1's product *is* the loop. Spend time on it.
## Recipes, fastest-acceptable first
1. **Failing test** — one test file, minimal reporter, stop on first
failure. The gold standard.
2. **Curl / HTTP script** — for an endpoint bug, the request is the loop.
3. **CLI invocation with fixture input** — when the CLI itself reproduces
on a small fixture file.
4. **Headless browser script** — for UI bugs that survive a unit test
(Playwright, `shinytest2`).
5. **Replay a captured trace** — record one production trace, replay
it deterministically.
6. **Throwaway harness** — a 5-line script printing `PASS`/`FAIL` with a
non-zero exit on failure. Valid when nothing native exists.
7. **Property / fuzz loop** — when the bug only surfaces under randomised
inputs, pin the seed and run the family.
8. **Bisection harness** — when "what changed?" is the question, the
loop wraps `git bisect run`.
9. **Differential loop** — two implementations, same input, assert equal.
10. **HITL bash script** — last resort. A human-in-the-loop step is the
escape valve when nothing automated can decide.
Language-flavored worked examples:
[feedback-loops-r.md](feedback-loops-r.md) /
[feedback-loops-py.md](feedback-loops-py.md).
## Tighten the loop
- **Red on the bug**, not a neighbour. The assert names the user's exact
symptom.
- **Tight — seconds, not minutes.** Strip coverage, strip orchestration,
strip rebuild. If the loop won't shrink, run a smaller slice.
- **One keystroke.** A typed-out command bus rewires per-bug context loss;
put it in a `justfile` recipe or shell history.
## Kill non-determinism
If the same loop produces two answers in a row, **fix the loop before
Phase 2**. Universal moves:
- **Seed every RNG**; never rely on global state.
- **Pin the environment** — timezone (`UTC`), locale, hash seed.
- **Freeze package versions** — `renv.lock`, `uv.lock`, or container.
- **Isolate the filesystem** — temp dirs, never the repo tree.
- **Quarantine ambient network** so a hung outbound call can't masquerade
as a logic bug.
## When you genuinely cannot build a loop
The bug is real, the loop won't form. Two paths:
1. **Build a worse loop, knowingly.** A 30-second smoke test that passes
*most* of the time you fix the bug is better than no loop. Document
the false-positive/negative rate next to the assert.
2. **Escalate to the human.** State out loud: *"I can reproduce this
symptom but cannot pin it to a deterministic test. The architectural
cost of doing so is X. Want me to spend that, or accept a smoke
test?"* Then wait.
Never silently abandon Phase 1 and start guessing. That is the failure
mode this skill exists to prevent.