From f08223c3b26b602a511cf78bbdbd9264f8f29698 Mon Sep 17 00:00:00 2001 From: lukabor Date: Thu, 28 May 2026 23:02:19 +0200 Subject: [PATCH] add skill: diagnose (six-phase bug hunt) + R refs; cross-link tdd-bdd --- README.md | 2 + skills/engineering/diagnose/SKILL.md | 79 ++++++++++ .../engineering/diagnose/feedback-loops-r.md | 146 ++++++++++++++++++ .../engineering/diagnose/instrumentation-r.md | 108 +++++++++++++ skills/engineering/tdd-bdd/SKILL.md | 4 + 5 files changed, 339 insertions(+) create mode 100644 skills/engineering/diagnose/SKILL.md create mode 100644 skills/engineering/diagnose/feedback-loops-r.md create mode 100644 skills/engineering/diagnose/instrumentation-r.md diff --git a/README.md b/README.md index 1e284f8..78c2f1a 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,8 @@ skill list. ### engineering - **tdd-bdd** — strict red-green-refactor loop with BDD Given/When/Then scenarios as the unit of work. +- **diagnose** — six-phase bug hunt: feedback loop → reproduce → + hypothesise → instrument → fix with regression test → cleanup. ## Adding a skill diff --git a/skills/engineering/diagnose/SKILL.md b/skills/engineering/diagnose/SKILL.md new file mode 100644 index 0000000..46d9bdd --- /dev/null +++ b/skills/engineering/diagnose/SKILL.md @@ -0,0 +1,79 @@ +--- +name: diagnose +description: Systematic six-phase bug hunt — build a fast deterministic feedback loop first, reproduce, hypothesize, instrument one variable at a time, fix with a regression test, then clean up and post-mortem. Use when the user says "diagnose", "/diagnose", "debug this", "find the bug", "root cause", "this is flaky", "this is intermittent", "regression", "performance issue", or reports an unexpected failure / hang / wrong output that is not a one-line typo. +--- + +# diagnose + +## When to use +- User says "diagnose", "/diagnose", "find the bug", "root cause", + "intermittent / flaky", "regression", "perf issue". +- A reported failure is *not* a one-line typo — the cause is non-obvious. +- A test that used to pass is now red and the diff alone doesn't explain it. + +## Core principle +**The feedback loop is the product.** If you have a fast, deterministic, +agent-runnable pass/fail signal for the bug, you will find the cause. If +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. +See [feedback-loops-r.md](feedback-loops-r.md) for R recipes (testthat, +`targets`, bookdown, shiny) and two canonical worked examples. + +### 2. Reproduce +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. + +### 3. Hypothesise (before touching code) +Generate **3–5 falsifiable hypotheses**, ranked by plausibility. Each must +include a prediction the loop can decide. +``` +H1 (most likely): . + Prediction: makes the failure disappear / move. +H2: ... +``` +Share the ranking with the user. Cheap course-correction before +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-` tag convention so cleanup is `grep`-able. + +### 5. Fix + regression test +Hand off to [tdd-bdd](../tdd-bdd/SKILL.md): +- State the bug as one Given/When/Then scenario. +- Translate into a failing testthat test at the **public** interface + (see `../tdd-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. + +### 6. Cleanup + post-mortem +- `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](../tdd-bdd/refactoring-r.md) candidates; file them, + 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. +- **Never** ship instrumentation. Cleanup is a phase, not an afterthought. + +## See also +- [../tdd-bdd/SKILL.md](../tdd-bdd/SKILL.md) — phase 5 is a tdd-bdd cycle. +- [../tdd-bdd/refactoring-r.md](../tdd-bdd/refactoring-r.md) — file + architectural follow-ups here. diff --git a/skills/engineering/diagnose/feedback-loops-r.md b/skills/engineering/diagnose/feedback-loops-r.md new file mode 100644 index 0000000..db0d29d --- /dev/null +++ b/skills/engineering/diagnose/feedback-loops-r.md @@ -0,0 +1,146 @@ +# Feedback loops in R + +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**. + +--- + +## Worked example 1 — in-place mutation, intermittently wrong output + +**Symptom (user):** `build_plot()` sometimes returns a plot with the wrong +y-axis; running the same chapter twice in a row gives different results. + +**Phase 1 — build the loop.** +The bookdown render is too slow and the bug is intermittent. Compress to a +testthat test that runs the broken target twice and compares: +```r +test_that("assemble_expr is idempotent", { + withr::local_seed(1) + raw <- make_modb_mock() + a <- assemble_expr(raw) + b <- assemble_expr(raw) # same input, expect same output + expect_equal(a, b) +}) +``` +Run: `testthat::test_file("tests/testthat/test_assemble.R", reporter="minimal")`. +It fails on second invocation only. Loop is now deterministic and 0.4 s. + +**Phase 3 — hypotheses.** +H1: `assemble_expr` mutates `raw` in place (data.table reference +semantics). Prediction: wrapping the input with `data.table::copy(raw)` +makes the second call match the first. + +**Phase 4 — instrument.** +One line: +```r +assemble_expr <- function(raw) { + raw <- data.table::copy(raw) ### DIAGNOSE-2026-05-28 + ... +} +``` +Test passes. H1 confirmed. + +**Phase 5 — regression test** = the idempotence test above (already +written). Now move the `copy()` from the diagnostic patch into the real +fix at the boundary the contract requires (likely the constructor of the +`modb_result` object — see `../tdd-bdd/interface-design-r.md`). + +**Phase 6 — cleanup.** +`grep -r "### DIAGNOSE-" .` shows zero hits. Commit message: +*"fix(assemble_expr): defensive copy of modb_result — H1 confirmed: +data.table ref-semantics caused intermittent y-axis swap"*. + +--- + +## Worked example 2 — flaky test that depends on RNG + +**Symptom (user):** `test_textmining.R::"top terms are stable"` passes +locally, fails 1/10 times on CI. + +**Phase 1 — build the loop.** +Run the single test 50 times in a row in a one-liner: +```bash +for i in $(seq 50); do + Rscript -e 'testthat::test_file("tests/testthat/plot/test_textmining.R", reporter="minimal")' \ + || { echo "FAIL on iter $i"; break; } +done +``` +Fails on iteration 7. Loop reproduces in < 30 s. + +**Phase 3 — hypotheses.** +H1: the mock data uses `runif()` without a seed; ties in the z-score +ranking sort differently across runs. +H2: a locale-dependent sort on term names. + +H1 is more likely (untied scores are improbable when sampling 100 uniforms; +ties happen when the test mock samples a tiny matrix). + +**Phase 4 — instrument.** +Add `withr::local_seed(42)` at the top of the test. Run the 50× loop again. +All green. H1 confirmed; H2 not pursued (one variable at a time). + +**Phase 5 — regression test:** the seeded test *is* the regression test. +Add a comment: `# seed pins the tie-breaking order; see DIAGNOSE post-mortem`. + +**Phase 6 — cleanup.** +Nothing to revert. Commit: *"test(textmining): seed RNG to stabilise +top-term tie-break — H1 confirmed"*. File an architectural follow-up: +"production `score_terms()` should break ties on a stable key +(`term_id`) rather than relying on input order" → goes to +`../tdd-bdd/refactoring-r.md` candidate list. diff --git a/skills/engineering/diagnose/instrumentation-r.md b/skills/engineering/diagnose/instrumentation-r.md new file mode 100644 index 0000000..93a605c --- /dev/null +++ b/skills/engineering/diagnose/instrumentation-r.md @@ -0,0 +1,108 @@ +# Instrumentation in R + +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) + +### `browser()` +Drop a breakpoint at the suspected frame and poke around. +```r +build_plot <- function(modb_raw) { + browser() ### DIAGNOSE-2026-05-28 + df <- modb_raw |> reshape() |> rename() + ggplot(df, aes(...)) +} +``` +At the prompt: `ls()`, `str(df)`, `head(modb_raw)`, `n` to step, `c` to +continue, `Q` to abort. + +### `debugonce(fn)` / `debug(fn)` +Same effect as `browser()` but without editing the function. Best when the +target function lives in a package or `box` module. +```r +debugonce(build_plot) +build_plot(modb_raw) # browser fires once, then disables itself +``` +Cleanup is automatic. `debug()` persists until `undebug()`. + +### `options(error = ...)` for post-mortem +Drop into the failing frame *at the moment of the error*. +```r +options(error = rlang::entrace) ### DIAGNOSE-2026-05-28 +# reproduce the bug, then: +rlang::last_trace() # clean stack with frame numbers +rlang::last_trace(drop = FALSE) # everything +``` +Or the classic: +```r +options(error = recover) # pick a frame after the crash +``` +Reset with `options(error = NULL)` in cleanup. + +### `lobstr::cst()` — mid-execution stack +```r +build_plot <- function(modb_raw) { + lobstr::cst() ### DIAGNOSE-2026-05-28 — see who called me + ... +} +``` +Useful when the same helper is called from multiple sites and you can't +tell which path hit it. + +## Logging (only when interactive isn't possible) + +When the bug only repros in a non-interactive run (CI, `targets` +workers, a long bookdown render), `cat()` *with the diagnose tag*: +```r +cat(sprintf("### DIAGNOSE-2026-05-28 assemble_expr: nrow=%d md5=%s\n", + nrow(df), digest::digest(df))) +``` +The tag matters. Cleanup is `grep -r "### DIAGNOSE-" .` followed by +manual review — no tag, no cleanup. + +## Performance bugs + +### `profvis::profvis()` +Wrap the slow call. Open the resulting flamegraph in the IDE. +```r +profvis::profvis(build_book()) +``` +Look for: one box that dominates (target it), or thousands of tiny boxes +(loop / vectorisation problem). + +### `bench::mark()` +For A/B microbenchmarks once you have a hypothesis about the slow path: +```r +bench::mark( + baseline = old_assemble(raw), + patched = new_assemble(raw), + iterations = 50 +) +``` + +## `targets` pipelines + +After a target fails, inspect upstream inputs without re-running them: +```r +targets::tar_load_everything() +browser() ### DIAGNOSE-2026-05-28 +``` +For long-running pipelines, set `tar_option_set(error = "continue")` so +one bad target doesn't hide later ones from view. + +## The `### DIAGNOSE-` tag convention + +- **Every** line you add for diagnosis carries `### DIAGNOSE-YYYY-MM-DD`. +- Single date format. Single tag. One regex finds them all. +- Phase 6 ends only when `grep -r "### DIAGNOSE-" .` returns zero hits. + +## Anti-patterns +- **Adding `print()`s without a tag.** They survive into commits. +- **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 — + separate the two phases. +- **Leaving `options(error = recover)` in `.Rprofile`.** Devastating in + scripts and CI. diff --git a/skills/engineering/tdd-bdd/SKILL.md b/skills/engineering/tdd-bdd/SKILL.md index d4b991c..6019591 100644 --- a/skills/engineering/tdd-bdd/SKILL.md +++ b/skills/engineering/tdd-bdd/SKILL.md @@ -98,3 +98,7 @@ from step 0 is a *plan*; it is not a queue of tests to enqueue at once. — don't silently drop it. Move it up (integration) or down (unit) one level and reconfirm with the user. - Refactor only with a green bar. No "tidy while red". + +## See also +- [../diagnose/SKILL.md](../diagnose/SKILL.md) — chasing an existing bug? + Run `/diagnose` first; phase 5 hands back here for the regression test.