:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(ci): add fixing-flaky-tests agent skill (#62704)
Raúl Negrón-Otero04b389894ac8
diff --git a/.agents/skills/debugging-ci-failures/SKILL.md b/.agents/skills/debugging-ci-failures/SKILL.mdindex ae7615ef8160..4d33b83e28e0 100644--- a/.agents/skills/debugging-ci-failures/SKILL.md+++ b/.agents/skills/debugging-ci-failures/SKILL.md@@ -23,6 +23,10 @@ Always start with the `hogli ci:insights` digest. It is the institutional,cross-run source of truth, and it is fresher and more reliable than scraping`gh run list` / the GitHub Actions API, which can lag or rate-limit.+This skill triages and classifies. Once a failure is confirmed flaky, hand off+to the `fixing-flaky-tests` skill, which owns local reproduction, root-cause+fixing, and N-run validation.+## Safety rulesDo not do any of these without explicit approval in the current conversation:@@ -107,19 +111,19 @@ explains the run's conclusion. Keep excerpts under 40 lines.## Classification-| Signal in the log | Class | First action |-| ------------------------------------------------------------------------ | ------------------- | -------------------------------------------------------------------- |-| `AssertionError`, test diff, `FAILED test_...` in a committed test file | code regression | reproduce with `hogli test <path>::<test>` |-| Test failed here, passed on `master` or on rerun in the same PR | flaky test | confirm against `master` history; do not "fix" without user approval |-| `ruff`, `oxlint`, `stylelint`, `markdownlint`, `prettier` errors | lint | `hogli lint:python:fix` or `hogli format` on touched files |-| `mypy`, `pyright`, `tsc`, `typescript:check` errors | typecheck | run the same checker locally, not the full suite |-| Chromatic / Storybook / Playwright visual diff, snapshot mismatch | snapshot / visual | surface the diff URL; do NOT auto-accept snapshots |-| `manage.py migrate` error, `migrations:check` failure, missing migration | migration / schema | `hogli migrations:check` locally |-| OpenAPI schema diff, generated API types out of sync | codegen drift | `hogli build:openapi` |-| `Cannot connect`, `ECONNREFUSED`, OOM, runner killed, setup step timeout | infra / runner | treat as transient; report, do not fix |-| `apt-get`, `uv sync`, `pnpm install`, docker pull, setup action failures | environment / setup | diff `.nvmrc`, `pyproject.toml`, `package.json`, Dockerfiles |-| `hogli lint:skills`, `hogli build:skills` failure | skills build | run the same `hogli` command locally |-| SDK compat check, `ci-survey-sdk-check`, cross-version failure | SDK compatibility | check SDK version matrix for the affected package |+| Signal in the log | Class | First action |+| ------------------------------------------------------------------------ | ------------------- | ------------------------------------------------------------------ |+| `AssertionError`, test diff, `FAILED test_...` in a committed test file | code regression | reproduce with `hogli test <path>::<test>` |+| Test failed here, passed on `master` or on rerun in the same PR | flaky test | confirm against `master` history; to fix, use `fixing-flaky-tests` |+| `ruff`, `oxlint`, `stylelint`, `markdownlint`, `prettier` errors | lint | `hogli lint:python:fix` or `hogli format` on touched files |+| `mypy`, `pyright`, `tsc`, `typescript:check` errors | typecheck | run the same checker locally, not the full suite |+| Chromatic / Storybook / Playwright visual diff, snapshot mismatch | snapshot / visual | surface the diff URL; do NOT auto-accept snapshots |+| `manage.py migrate` error, `migrations:check` failure, missing migration | migration / schema | `hogli migrations:check` locally |+| OpenAPI schema diff, generated API types out of sync | codegen drift | `hogli build:openapi` |+| `Cannot connect`, `ECONNREFUSED`, OOM, runner killed, setup step timeout | infra / runner | treat as transient; report, do not fix |+| `apt-get`, `uv sync`, `pnpm install`, docker pull, setup action failures | environment / setup | diff `.nvmrc`, `pyproject.toml`, `package.json`, Dockerfiles |+| `hogli lint:skills`, `hogli build:skills` failure | skills build | run the same `hogli` command locally |+| SDK compat check, `ci-survey-sdk-check`, cross-version failure | SDK compatibility | check SDK version matrix for the affected package |If multiple signals match, choose the most specific class. For example, prefercodegen drift over lint, migration over typecheck, and snapshot / visual over a@@ -133,7 +137,7 @@ is unclear, read `.agents/skills/hogli/SKILL.md` and `hogli <command> --help`.| Class | Repro guidance || ------------------- | ------------------------------------------------------------------------------------ || code regression | `hogli test path/to/test.py::TestClass::test_method` or `hogli test <file.test.ts>` |-| flaky test | Run the exact test repeatedly only if the runner supports it. Do not invent flags. |+| flaky test | Hand off to the `fixing-flaky-tests` skill. || lint | Use the failing formatter/linter on touched files, e.g. `hogli format:python`. || typecheck | Run the failing checker, e.g. `pnpm --filter=@posthog/frontend typescript:check`. || snapshot / visual | Run the specific Playwright or Storybook workflow; read `playwright-test` if needed. |diff --git a/.agents/skills/fixing-flaky-tests/SKILL.md b/.agents/skills/fixing-flaky-tests/SKILL.mdnew file mode 100644index 000000000000..cb01cea14a4e--- /dev/null+++ b/.agents/skills/fixing-flaky-tests/SKILL.md@@ -0,0 +1,175 @@+---+name: fixing-flaky-tests+description: >+ Guides an agent through reproducing, root-causing, fixing, and validating flaky tests in the PostHog monorepo.+ Use when a test fails intermittently in CI but passes on rerun or locally, when `hogli ci:insights` or the debugging-ci-failures skill classifies a failure as a flaky test, when given a GitHub Actions URL for a flaky job, or when asked to deflake, stabilize, or fix a flaky Jest, pytest, or Playwright test.+ Core discipline: reproduce locally before changing anything, fix the root cause (never mask it with sleeps, retries, or bigger timeouts), and prove the fix with an N-run validation loop sized to the observed failure rate.+---++# Fixing flaky tests++Three non-negotiables, in order:++1. **Reproduce before you fix.** A fix for a failure you never observed is a guess.+ Only fall back to analytical fixes when the escalation ladder below is exhausted.+2. **Fix the root cause.** Sleeps, raised timeouts, retries, and weakened assertions hide flakes; they do not fix them.+3. **Validate with an N-run loop.** One green run proves nothing about an intermittent failure.+ Size N to the observed failure rate.++For triaging a red CI run (finding and classifying the failure), use the `debugging-ci-failures` skill first — this skill takes over once the failure is classified as a flaky test.+For writing new Playwright tests that aren't flaky, use the `playwright-test` skill.++## 1. Confirm it is actually flaky++Before investing in reproduction:++```bash+hogli ci:insights search "<test name or error>" # occurrence history, confidence, existing fix+git log --oneline -10 -- <test_file_path> # recently fixed already?+```++- An insight with a **merged fix** means the flake may already be resolved — read the fix, confirm it covers this failure, and report instead of re-fixing.+- A test failing **consistently** (every run, including on `master`) is a regression, not a flake — go back to `debugging-ci-failures`.+- Record the observed failure rate (occurrences / total runs from `ci:insights`, or from rerun attempts on the PR).+ You need it to size the validation loop later.++## 2. Extract the failure from CI++```bash+gh run view <run-id> --log-failed+# If the job was re-run and the latest attempt passed, the flaky failure+# lives in a previous attempt:+gh api "repos/PostHog/posthog/actions/runs/{run_id}/attempts/1/jobs"+gh api "repos/PostHog/posthog/actions/jobs/{job_id}/logs"+```++Capture before moving on:++- Exact test ID (file path + test name) and the failing assertion or error.+- Surrounding warnings — `[MSW] Unhandled`, async leak warnings, teardown errors — these are often the actual cause, printed before the symptom.+- Which other tests ran in the same worker/shard before it (ordering suspects).++## 3. Reproduce locally — before touching anything++Escalate through these conditions until the failure appears.+Stop at the first level that reproduces it; that level is your validation environment for step 6.++1. **Single run**: `hogli test <path>::<test>` — confirms the test runs at all.+2. **Repetition loop** (default N=20): catches probabilistic flakes.+3. **CI-like conditions**: CI runs Jest sharded with low worker counts on contended runners — read the current flags from `frontend/package.json`'s `test` script and `.github/workflows/ci-frontend.yml` before running.+ Example (with the flags as of this writing), running the test alongside its shard neighbors:++ ```bash+ pnpm --filter=@posthog/frontend jest <test_file> <neighbor_file> --maxWorkers=2 --forceExit+ ```++ For pytest, run the whole file or class rather than the single test, so module-level fixtures and ordering match CI.++4. **Ordering**: run suspected polluter tests before the victim; reverse the order within the file.+ Flakes that vanish in isolation are ordering bugs.+5. **Contention**: re-run the loop while something CPU-heavy runs in another shell (e.g. a parallel full-file jest run).+ Timeout-class flakes often only show here.++The loop harness — judge by exit code, not by grepping output:++```bash+N=20; PASS=0; FAIL=0+for i in $(seq 1 $N); do+ if <test command> >/tmp/flake-run.log 2>&1; then+ PASS=$((PASS+1))+ else+ FAIL=$((FAIL+1)); cp /tmp/flake-run.log /tmp/flake-fail-$i.log; echo "run $i: FAIL"+ fi+done+echo "$PASS passed, $FAIL failed out of $N"+```++Two cost notes for the loop:++- While reproducing, `break` after the first failure — one captured failure log is enough.+ Complete all N runs only when measuring the failure rate or validating in step 6.+- The `pnpm --filter=@posthog/frontend jest` script runs `pnpm build:products` before every invocation.+ Inside a loop, build once, then iterate with `pnpm --filter=@posthog/frontend exec jest ...`, which skips the rebuild.++**If nothing reproduces after the full ladder**, the flake is CI-environment-specific.+Proceed with a fix grounded in the CI evidence and root-cause analysis, and say so explicitly in the report — the validation in step 6 is then analytical, not empirical.++## 4. Root-cause the flake++Match the symptom to a cause class; never patch the symptom.++| Symptom | Likely cause class |+| ------------------------------------------------------ | ------------------------------------------------------------ |+| Timeout waiting for promise/listener/element | Unawaited async work, missing mock, hidden pending request |+| Passes alone, fails with neighbors (or vice versa) | Shared state: module cache, DB rows, global config, ordering |+| Fails near midnight/UTC boundaries, or on slow runners | Real clock usage — missing `freeze_time` / fake timers |+| Assertion on list order or generated IDs | Nondeterministic ordering/IDs asserted as deterministic |+| Query can't see just-written data | Eventual consistency (ClickHouse), missing flush/commit |+| Only fails under `--maxWorkers=2` / contention | Race condition surfaced by scheduling, too-tight timeout |++PostHog-specific patterns:++### Frontend (Jest + kea)++- **Missing MSW mocks**: kea logics with `afterMount` loaders fire API calls through the `connect()` chain — a logic three levels deep can trigger an unmocked fetch.+ Unhandled requests currently resolve with a benign empty paginated 200, so the symptom is a loader succeeding with empty or wrong data, not a network error.+ The `[MSW] Unhandled GET ...` warning in the log names the missing mock — add the `useMocks` entry.+ The unhandled-request behavior has changed before (it used to hang); if symptoms don't match, read `frontend/src/mocks/jest.ts` for what unmocked requests do today.+- **`toFinishAllListeners()` timeouts**: waits for ALL kea listener promises across ALL mounted logics (3s default — `LISTENER_FINISH_WAIT_TIMEOUT` in `kea-test-utils`).+ Any connected logic with a pending loader blocks it.+ Fix the pending work; do not raise the timeout.+- **Mock URL mismatch**: `mocksToHandlers` strips trailing slashes, but query params, `@current`-style segments, and `:param` patterns must match the real request URL.+ Compare against the `[MSW] Unhandled` line.+- **Per-test handler reset**: `frontend/src/mocks/jest.ts` registers a global `afterEach(() => mswServer.resetHandlers())`.+ Each `it.each` case is a separate test, so runtime mocks must be (re-)registered in `beforeEach`.+- **Leaked mounts**: logics mounted in `beforeEach` and never unmounted leak async work into later tests.++### Backend (pytest)++- **DB state leakage**: shared rows across tests without isolation — check fixture scope and whether the test needs `@pytest.mark.django_db(transaction=True)`.+- **Real time**: use `freeze_time`; never assert on `now()`-derived values.+- **ClickHouse eventual consistency**: a query may not see just-inserted data — flush explicitly in the test setup rather than sleeping.++## 5. Fix the root cause — never mask it++| Tempting masking move | Do instead |+| ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |+| `sleep(2)` / `setTimeout` before asserting | Await the specific condition (`waitFor`, `expectLogic`, explicit flush) |+| Raise the test/listener timeout | Find what is hanging; the timeout is the messenger |+| Add retries (`pytest-rerunfailures` `--reruns`, `jest.retryTimes`) | Reserve for genuinely nondeterministic external infra, with a comment and a linked issue — never for product code under test |+| Skip / quarantine the test | Only with explicit user approval, with a linked issue |+| Loosen the assertion | Make the data deterministic (sort, freeze, seed), keep the assertion strict |++Keep the fix minimal and inside the test or its fixtures when possible.+If the race is in product code, the flake found a real bug — fix the product code and say so in the report.++## 6. Validate with an N-run loop++Run the step-3 harness on the fixed code **under the same conditions that reproduced the failure** (same neighbors, worker count, contention).++Size N from the observed pre-fix failure rate: if it failed about 1 in k runs, you need roughly **N ≥ 3k** consecutive passes for ~95% confidence the flake is gone — `(1 - 1/k)^(3k) ≈ 5%`.+So use **N = max(3k, 20)**.+Without a usable rate estimate, run 50 and note the reduced confidence in the report.+If the flake was never reproducible locally, run N = 20 as a regression check and label the validation as analytical.++Any failure in the loop → back to step 4; the root cause was wrong or incomplete.+Finish with one normal run of the surrounding file/suite to confirm the fix didn't break sibling tests.++## 7. Report++```text+Test: <file path>::<test name>+Observed in CI: <rate, e.g. ~1 in 8 runs over 2 weeks (ci:insights)>+Local repro: <command + conditions, e.g. 3/20 failures with neighbor X, maxWorkers=2 | not reproducible locally>+Root cause: <one or two sentences>+Fix: <what changed and why it removes the cause>+Validation: <N>/<N> passes under repro conditions | analytical only (CI-specific)+Follow-ups: <product bug found, related tests with the same pattern, or none>+```++## Boundaries++- Do not rerun CI jobs, push, or post to GitHub to "test" the fix — validate locally.+- Do not edit `.github/workflows/` as part of a flake fix.+- Do not accept/update snapshots to make a flake pass.+- If the same root-cause pattern clearly affects sibling tests, fix them in the same change only when mechanical; otherwise list them as follow-ups.