Skip to content

: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.

chore: add writing-tests skill to gate new test value and cost (#64117)

Raúl Negrón-Otero3533e1b162fe
diff --git a/.agents/skills/writing-tests/SKILL.md b/.agents/skills/writing-tests/SKILL.md
new file mode 100644
index 000000000000..ac0dd77622f1
--- /dev/null
+++ b/.agents/skills/writing-tests/SKILL.md
@@ -0,0 +1,128 @@
+---
+name: writing-tests
+description: >
+ Gates whether a new test should exist and forces it to be efficient, protecting CI from low-value test bloat.
+ Use before adding or substantially changing any pytest, Jest, or Playwright test — whenever an agent or engineer is about to write tests for a new feature, bugfix, or PR.
+ Front-loads the value bar (every test must catch a realistic regression no existing test already catches; test behavior through the public interface, not implementation details; collapse near-duplicates into parameterized cases) and the efficiency bar (deterministic, isolated, fast; pick the cheapest test level; Django TestCase over TransactionTestCase; no sleeps, no real network).
+ Includes a "don't write it" decision tree. For fixing an existing flaky test use `/fixing-flaky-tests`; after this gate says a Playwright test is warranted, use `/playwright-test` for mechanics.
+---
+
+# Writing tests worth keeping
+
+The rationale and the same rules in human-facing form live in the handbook: [Backend coding conventions › Testing](https://posthog.com/handbook/engineering/conventions/backend-coding#testing) (`docs/published/handbook/engineering/conventions/backend-coding.md`).
+This skill is the operational gate — run it before writing tests. It carries the decision procedure plus [a catalog of the bug shapes we actually ship](references/mistakes-we-make.md).
+
+## The gate: one question
+
+Before writing any test, answer in one sentence:
+
+> **What realistic regression does this test catch that no existing test already catches?**
+
+If you can't answer it concretely — name the bug, the code path, the input that would break — **do not write the test.**
+"Increases coverage", "good practice", and "the function exists" are not answers.
+
+A good answer sounds like: _"if someone makes `parse_filters` drop the `team_id` clause, this fails"_ or _"empty-cohort input used to 500; this locks in the 400."_
+That is a test worth keeping.
+
+Aim each test at a failure mode we actually hit, not a hypothetical.
+The bugs PostHog ships and reverts cluster into a handful of shapes — cataloged with the test that catches each, and the failure modes no unit test should, in [references/mistakes-we-make.md](references/mistakes-we-make.md).
+If your test doesn't map to one of them, be skeptical it's worth keeping.
+
+## Don't write it — the four no's
+
+Most low-value tests fall into one of these. Recognize and skip them.
+
+1. **Trivial / framework behavior.**
+ Don't test getters, setters, constants, dataclass field assignment, that Django saved a row, that DRF serialized a field, or that a library does what its docs say.
+ You're testing someone else's code, not yours.
+
+2. **Change-detector tests.**
+ A test that just mirrors the implementation — asserting which private methods were called, in what order, with mocks wired to match the current code — fails on every refactor and catches no real bug.
+ Test _observable behavior through the public interface_ (return value, persisted state, emitted event, HTTP response), not the choreography that produces it.
+ See [Change-Detector Tests Considered Harmful](https://testing.googleblog.com/2015/01/testing-on-toilet-change-detector-tests.html) and [Prefer Testing Public APIs](https://testing.googleblog.com/2015/01/testing-on-toilet-prefer-testing-public.html).
+
+3. **Redundant coverage.**
+ Ten tests that exercise the same path with different data are one parameterized test.
+ If a new test is a variation of an existing one, it's a `@parameterized` case (Python) or a `test.each` row (Jest) — **not** a new test function.
+ AI-generated suites bloat here first: hundreds of near-identical cases turning a 30s suite into 3 minutes.
+
+4. **Coverage-chasing.**
+ Don't add tests to hit a number; an uncovered line is information, not a defect.
+ If the only reason to test a branch is the coverage report, the branch probably doesn't need a test — or the code is dead and should be deleted instead.
+
+When the answer is "don't write it," the right move is often to **extend an existing test** (add a parameterized case) or **delete code** rather than test it.
+Both shrink the suite's surface.
+
+## If you write it — weight it down the pyramid
+
+A test that earns its place still has to be cheap.
+Cost is a ladder; each rung is roughly an order of magnitude slower and flakier than the one below:
+
+```text
+pure function / unit → kea logic test → Django TestCase → ClickHouse-backed test → Playwright e2e
+ cheapest most expensive
+```
+
+The goal is a **ratio**, not a cap: many tests at the bottom, very few at the top.
+A thousand pure unit tests are cheaper and more reliable than ten that boot Django, which are cheaper than one Playwright run.
+Want more coverage? Add it at the bottom.
+
+**When something is hard to test cheaply, that's a design signal — extract, don't escalate.**
+If the only way to exercise your logic is to stand up a database, a request, and a render, the logic is tangled with its dependencies.
+Pull it into a pure function or a kea logic and test _that_ directly: you get a faster test and better-factored code at once.
+Escalating to the next rung is the last resort, not the default.
+
+- If logic is in (or can be moved to) a pure function, test the function — don't stand up a DB, a request, or a render.
+- Frontend: test the **kea logic** (`logic.actions` / `logic.values`), not a full component render, whenever the behavior lives in the logic.
+ A `render()` + DOM-query test is for things only the DOM can show.
+- Reach for ClickHouse or a browser only when the regression genuinely lives there — not because it was the first way the test came to mind.
+
+### Python (pytest / Django)
+
+- **`TestCase`, not `TransactionTestCase`, unless you truly need it.**
+ `TransactionTestCase` flushes the DB between tests instead of rolling back a transaction — dramatically slower, and a common source of cross-test interference.
+ It's a Postgres-isolation choice, orthogonal to which datastore you touch: a ClickHouse-backed test is still a plain `TestCase` (`ClickhouseTestMixin` sets ClickHouse up), so reaching ClickHouse is not a reason to switch.
+ Common cases that people reach for `TransactionTestCase` to solve usually have cheaper alternatives:
+ - testing `transaction.on_commit` side effects → use `TestCase` + `self.captureOnCommitCallbacks(execute=True)`.
+ - needing a connection visible across a real separate thread (`thread_sensitive`) → `async_to_sync(...)`, not `asyncio.run(...)`.
+ Use `TransactionTestCase` only when the regression genuinely requires committed transaction boundaries that `TestCase` hides.
+- **Parameterize** repeated assertions with the `parameterized` library — don't copy-paste test bodies.
+- **No doc comments** in Python tests (house rule).
+- Mock only **true boundaries** — network, external APIs, the clock, queues.
+ Don't mock your own internal helpers (that's how change-detector tests are born).
+
+### Frontend (Jest)
+
+- One top-level `describe` block per file (house rule).
+- Prefer logic tests over component renders (see the ladder above).
+- `test.each` for variations rather than copied test bodies.
+- **No huge snapshots.**
+ A snapshot over a large rendered tree or serialized blob is a change-detector test that bloats the repo and breaks on every unrelated change.
+ Snapshot a small, intentional value, or assert specific fields instead.
+
+### Always — determinism and isolation
+
+- **No `time.sleep` / arbitrary waits.**
+ Use fake timers, `wait_for` / `waitFor` on a real condition, or `freeze_time`.
+ A sleep is a flake waiting to happen, and it slows every run.
+- **No real network / live external services.** Mock the boundary.
+- **No cross-test ordering.**
+ Tests must pass in any order and in isolation; don't rely on state a previous test left behind.
+- **No `@skip` / `xfail` / `.skip`** without a one-line reason and a linked issue.
+ A permanently-skipped test is dead weight — delete it or fix it.
+- **Never commit `.only`** (`it.only` / `describe.only`).
+ It doesn't skip one test, it skips every _other_ test in the file — turning the suite green on a sliver.
+
+## Before you open the PR
+
+The PR template prompts for this under "How did you test this code?" — state the justification where a reviewer will see it.
+One line per group of tests is enough:
+
+> _"Added 3 cases to `test_cohort_query` covering empty / single / oversized cohorts — guards the 500 we just fixed; couldn't extend an existing test because none exercised the empty path."_
+
+If you can't write that line, you've found a test that shouldn't be in the PR.
+
+## Related skills
+
+- **Fixing an existing flaky test** → use `/fixing-flaky-tests` (reproduce, root-cause, validate). Use this skill too only if the fix adds or substantially changes coverage.
+- **Authoring a non-flaky Playwright test** → first use this skill to decide whether a browser test earns its cost; if it does, use `/playwright-test` for the mechanics.
diff --git a/.agents/skills/writing-tests/references/mistakes-we-make.md b/.agents/skills/writing-tests/references/mistakes-we-make.md
new file mode 100644
index 000000000000..7f258d987b0a
--- /dev/null
+++ b/.agents/skills/writing-tests/references/mistakes-we-make.md
@@ -0,0 +1,90 @@
+# Mistakes we actually make
+
+The bugs PostHog ships and reverts cluster into a small number of shapes.
+This catalogs them — derived from merged `fix:` and `revert:` PRs, with each example checked at the diff level (does the PR actually add a regression test, and at what level?) and cross-referenced against recurring production incidents.
+
+Use it to aim a test at a failure mode we really hit, not a hypothetical.
+Find the shape your change touches and write the test at the level noted.
+If your change maps to nothing here and isn't genuinely new behavior, be skeptical the test earns its place.
+
+Two headlines:
+
+- Most bugs that a test can cheaply prevent are **boundary and contract mistakes** — mis-classified errors, null/wrong-shape input, cross-tenant leakage, non-UTC time — caught at the bottom of the pyramid.
+- Some real, costly failure modes are **not cheaply unit-testable** (query perf, migration ordering, async teardown, refactor regressions, resource exhaustion). Writing a unit test for those gives false confidence. Know which kind you have before you write anything.
+
+## Bugs a cheap test catches — write these
+
+### Mis-classified retryable vs non-retryable errors
+
+A data-warehouse import source maps a _permanent_ failure (bad auth, deleted integration, expired password) to a _retryable_ error, so Temporal retries it forever and floods error tracking — or the inverse, a transient blip is made terminal and silently disables a customer's sync.
+The most common `fix:` cluster, and the best-tested.
+
+- **Catch it at:** a pure-unit test asserting the source maps a given exception string to the right (non-)retryable class. No Temporal, no ClickHouse. Assert _both_ directions.
+- [#63677](https://github.com/PostHog/posthog/pull/63677) — Salesforce: treat deleted integration as non-retryable — a deleted OAuth integration raised `Integration not found`, a string the error map didn't match, so it retried forever; the test asserts that string is non-retryable _and_ that `Read timed out` stays retryable.
+- [#63681](https://github.com/PostHog/posthog/pull/63681) — Snowflake: treat expired password as non-retryable — `Specified password has expired` wasn't in the non-retryable set.
+- [#63798](https://github.com/PostHog/posthog/pull/63798) — Postgres: keep transient SSL drops retryable — `SSL connection has been closed unexpectedly` was wrongly non-retryable, so a mid-probe drop permanently disabled the sync (the inverse direction).
+
+### Null / empty / wrong-shape input → crash
+
+Code assumes a value is present or well-formed (a DB field, a JSON body, a group type) and crashes instead of degrading.
+Common — and cheap to guard against relative to the cost of shipping it.
+
+- **Catch it at:** the cheapest level that exercises the boundary — a pure-unit call with the bad value, or a Django `TestCase` hitting the endpoint. No ClickHouse.
+- [#62757](https://github.com/PostHog/posthog/pull/62757) — handle null metrics when serializing experiments — a `NULL` `metrics` column reached `enumerate(None)`, so one bad row 500'd the whole experiments list; the test parameterizes null/empty combinations against the list and detail endpoints.
+- [#11792](https://github.com/PostHog/posthog/pull/11792) — return 400 instead of 500 if event properties isn't JSON — subscripting non-dict `properties` raised `TypeError`; the fix converts it to a `ValueError` (→ 400), and the unit test calls the function directly and asserts that — a rung below even the endpoint.
+- [#61076](https://github.com/PostHog/posthog/pull/61076) — guard `wordPluralize` against null `group_type` — a null group type crashed the flags page render; tested at the helper (Jest) and at the converter that produced the null (Python unit).
+
+### Tenant-isolation / scoping (IDOR)
+
+A query or endpoint isn't scoped to the requesting team/org, leaking reads or allowing writes across tenants.
+
+- **Catch it at:** a Django `TestCase` that creates two orgs and asserts org B can't see or mutate org A's rows — PostHog's standard IDOR-coverage shape.
+- [#61901](https://github.com/PostHog/posthog/pull/61901) — add scoping checks — the value is in the specific two-org tests, e.g. `test_plugin_unused_does_not_leak_other_orgs` (asserts the other org's plugin id is absent) and the dashboard-collaborator cross-project pair (asserts 404 and that the privilege row is unchanged). The PR itself bundles several unrelated fixes, so cite the test, not the bare PR.
+
+### Timezone / non-UTC correctness
+
+Code assumes UTC; date bucketing, pagination cursors, and chart labels shift by a day for teams in other zones — and CI's `TZ=UTC` hides it.
+
+- **Catch it at:** usually the cheapest rung — a pure-unit test parameterized over non-UTC zones (plus a DST boundary). But when the truncation happens _inside ClickHouse_, the cheap test can't see it and you need real execution.
+- [#57593](https://github.com/PostHog/posthog/pull/57593) — timezone-safe date parsing — frontend parsing read the system wall-clock and rolled the calendar day back east of UTC; a pure Jest test over UTC/LA/Tokyo/Berlin and a DST boundary catches it. The clean cheap exemplar.
+- [#61111](https://github.com/PostHog/posthog/pull/61111) — UTC-pin `time_bucket` truncation — `toStartOfDay` truncated on the session-timezone grid while cursors printed UTC, emptying keyset page 2 under a non-UTC `session_timezone`. This one is _not_ cheap: the regression test inserts rows and runs the real SQL with `session_timezone=US/Pacific` (a ClickHouse-backed `TestCase`). Know which kind you have.
+
+### HogQL printer / type coercion
+
+The printer emits SQL that crashes ClickHouse with a cast error or returns wrong results.
+These split into two test levels, and confusing them is a trap.
+
+- **Catch a SQL-_shape_ change at:** a printed-SQL assertion or `.ambr` snapshot (`test_printer.py`), no execution. Fast — but it only proves the SQL changed, not that ClickHouse stopped erroring.
+- **Catch a wrong-_result_ or hard error at:** a ClickHouse-backed `TestCase` that actually runs the query.
+- [#63220](https://github.com/PostHog/posthog/pull/63220) — make `toBool` null-safe — bare `toBool` hard-failed on UUID-shaped strings, fixed to `accurateCastOrNull`. Caught with a printed-SQL string assert plus an `.ambr` snapshot; the snapshot proves the cast wrapper is present, nothing more.
+- [#58713](https://github.com/PostHog/posthog/pull/58713) — coerce funnel aggregation target before the empty check — a numeric-typed property hit ClickHouse error code 72 (`Cannot read floating point value`); the `.ambr` diff alone (a `toString()` wrap) wouldn't prove the error is gone, so the real test executes `.calculate()` against ClickHouse.
+
+## Real bugs where a checked-in unit test is the wrong tool
+
+These failure modes are real and costly, but a cheap unit test either can't catch them or gives false confidence.
+Reach for the right tool instead of writing a test that proves nothing.
+
+- **Non-index-friendly / unbounded queries.**
+ A function wraps an indexed column (`toString(uuid) IN ...`) or leaves `team_id` unbound, degrading to a scan that times out on large teams.
+ The catch is an `assertNumQueries` / query-count bound or reviewing the printed predicate — not a happy-path test.
+ Honest note: in our own history these shipped verified by hand, not by an automated bound — [#61864](https://github.com/PostHog/posthog/pull/61864) (unbound `team_id` → scan) pins only an RPC name through a mock, and [#62417](https://github.com/PostHog/posthog/pull/62417) (indexed column wrapped in `toString`) asserts input validation, not query shape. That gap is exactly what a query-bound test would close.
+
+- **Migration / apply-time ordering.**
+ Code reads a table before its migration creates it — [#59873](https://github.com/PostHog/posthog/pull/59873), a ClickHouse migration read `posthog_instancesetting` before it existed under parallel migration.
+ No checked-in test guards this; the safety net is CI migration replay, which exercises the ordering. Don't write a unit test pretending to.
+
+- **Async / Temporal teardown hangs.**
+ An uncancellable `sync_to_async` gRPC call in fixture teardown hangs the whole job — [#62339](https://github.com/PostHog/posthog/pull/62339), fixed by removing the call and relying on DB CASCADE, not by a test.
+ And beware the adjacent trap: a test that mocks the boundary it is supposed to verify catches nothing. [#60302](https://github.com/PostHog/posthog/pull/60302) fixed a real workflow-logger crash, yet its logger tests mock the logger — so they pass whether or not the crash is present and would miss a re-regression.
+
+- **Refactor regressions that escape correctness tests.**
+ A "behavior-preserving" refactor regresses on an axis the tests don't cover.
+ The lesson isn't "add a characterization test" — it's "cover the behavior that actually changes."
+ [#59920](https://github.com/PostHog/posthog/pull/59920) was reverted even though a data-executing correctness test existed — the regressing behavior was outside what that test asserted; [#56785](https://github.com/PostHog/posthog/pull/56785) had helper and API tests that passed cleanly through both the refactor and its revert.
+
+## Not test-shaped at all
+
+These dominate incident _volume_ but are prevented by monitoring, capacity, and alerting — never a unit test.
+
+- **Resource exhaustion under load** — OOM, connection-pool starvation, event-loop blocking. Load-dependent; prevention is capacity and alerting. (A _known_ accidental O(n) can get a targeted perf test; the load itself cannot.)
+- **Infrastructure / third-party failure** — node crashes, DNS or network changes, disk exhaustion, upstream-provider outages. Root cause sits below the application; remediation is runbooks and monitoring.
diff --git a/.claude/commands/conventions.md b/.claude/commands/conventions.md
index 830254378bd0..c6ddbbc0a612 100644
--- a/.claude/commands/conventions.md
+++ b/.claude/commands/conventions.md
@@ -69,6 +69,7 @@ Hence the explicit separation between the data and view layers.
- We loosely follow BEM conventions. If an element can't be namespaced inside a container class (e.g. modals that break out of the containing DOM element), use BEM style names like `.DashboardMenu__modal` to keep things namespaced.
- Keep an eye out for custom styles in SCSS files that can be easily replaced with Tailwind classes and replace them with Tailwind when you see them
- Testing
+ - Before adding a test, make sure it earns its place and sits as low on the test pyramid as it can — the value/cost rubric in [Testing](#testing) below is language-agnostic.
- Write [logic tests](https://keajs.org/docs/intro/testing) for all logic files.
- [react testing library](https://testing-library.com/docs/react-testing-library/intro/) tests are particularly useful for components with complex interactions or to guide future humans or agents when they're changing components without full context of the uses and edge cases
- Add all new presentational elements and scenes to [our storybook](https://storybook.posthog.net/). Run `pnpm storybook` locally.
@@ -128,6 +129,10 @@ Don't log sensitive information. Make sure you never log:
### Testing
+A test suite is a shared, permanent liability: every test runs on every PR forever, costs CI time, can flake and block unrelated work, and is code someone has to maintain as the system changes.
+So judge a new test on two independent axes — **value** (does it catch a realistic regression we actually make?) and **cost** (how far down the test pyramid does it sit?).
+Maximize value and minimize cost; this never means "write fewer tests", it means drop the ones that catch nothing and push the rest as far down the pyramid as they go.
+
- All new packages and most new significant functionality should come with unit tests
- Significant features should come with integration and/or end-to-end tests
- Analytics-related queries should be covered by snapshot tests for ease of reviewing
@@ -138,6 +143,37 @@ Don't log sensitive information. Make sure you never log:
- that's because you want test output to give you the information you need to fix a failure
- and because you want your assertions to be as concrete as possible it shouldn't be possible to break the code and the test pass
+#### Does this test earn its place?
+
+Before writing a test, answer in one sentence: **what realistic regression does this catch that no existing test already catches?**
+Name the bug, the code path, and the input that would break — "increases coverage", "good practice", and "the function exists" are not answers.
+A good answer sounds like _"if someone makes `parse_filters` drop the `team_id` clause, this fails"_.
+
+Most low-value tests are one of these — recognize them and extend an existing test (or delete the code) instead:
+
+- **Trivial / framework behavior**: getters, setters, constants, that Django saved a row or that DRF serialized a field. You're testing someone else's code, not yours.
+- **Change-detector tests**: asserting which private methods were called, with mocks wired to match the current code. They fail on every refactor and catch no real bug. Assert observable behavior through the public interface (return value, persisted state, emitted event, HTTP response), not the choreography that produces it. See [Change-Detector Tests Considered Harmful](https://testing.googleblog.com/2015/01/testing-on-toilet-change-detector-tests.html).
+- **Redundant coverage**: a new test that's a variation of an existing one is a `@parameterized` case (Python) or a `test.each` row (Jest), not a new test function.
+- **Coverage-chasing**: an uncovered line is information, not a defect — don't add a test just to move the number.
+
+#### Weight tests down the pyramid
+
+Each rung is roughly an order of magnitude slower and flakier than the one below:
+
+```text
+pure function → kea logic test → Django TestCase → ClickHouse-backed test → Playwright e2e
+ cheapest most expensive
+```
+
+Aim for a ratio, not a cap: many tests at the bottom, very few at the top — if you want more coverage, add it at the bottom.
+When logic is hard to test cheaply, that's a design signal: extract it into a pure function (or a kea logic) and test that directly rather than standing up a database, a request, and a render.
+Escalating to the next rung is the last resort, not the default.
+
+- **Use `TestCase`, not `TransactionTestCase`, unless you truly need it.** `TransactionTestCase` flushes the DB between tests instead of rolling back a transaction — dramatically slower, and a common source of cross-test interference. For `transaction.on_commit` side effects use `self.captureOnCommitCallbacks(execute=True)`; reaching ClickHouse is not a reason to switch (`ClickhouseTestMixin` runs on a plain `TestCase`).
+- Mock only true boundaries — network, external APIs, the clock, queues. Don't mock your own internal helpers; that's how change-detector tests are born.
+- Frontend: prefer a kea logic test (`logic.actions` / `logic.values`) over a full component render whenever the behavior lives in the logic, and don't snapshot large rendered trees — assert specific fields instead.
+- Keep tests deterministic and isolated: no `time.sleep` or arbitrary waits (use `freeze_time` or wait on a real condition), no real network or live external services, and they must pass in any order. Don't leave a `@skip`/`xfail`/`.only` without a one-line reason and a linked issue.
+
#### Fast developer ("unit") tests
A good test should:
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index f24fbf721e4b..09746d8a7da9 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -24,6 +24,7 @@
<!-- Describe steps to reproduce and verify the changes, and what the expected behavior is. -->
<!-- Include automated tests if possible, otherwise describe the manual testing routine. -->
<!-- Agents: do NOT claim manual testing you haven't done. State that you're an agent and list only the automated tests you actually ran. -->
+<!-- Added or changed tests? Name the regression each group catches that no existing test did — if you can't name it, it probably shouldn't be in this PR. https://posthog.com/handbook/engineering/conventions/backend-coding#testing -->
👉 _Stay up-to-date with [PostHog coding conventions](https://posthog.com/docs/contribute/coding-conventions) for a smoother review._
diff --git a/AGENTS.md b/AGENTS.md
index 97a8db0a7997..ae884aa8e27d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -137,6 +137,7 @@ See [.agents/security.md](.agents/security.md) for SQL, HogQL, and semgrep secur
- Python: do not create empty `__init__.py` files
- jest tests: when writing jest tests, prefer a single top-level describe block in a file
- Tests: prefer parameterized tests (use the `parameterized` library in Python) — if you're writing multiple assertions for variations of the same logic, it should be parameterized
+- Tests must earn their place: every new test has to catch a realistic regression no existing test already catches (if you can't name it, don't add it), assert observable behavior through the public interface rather than implementation details, and stay cheap — deterministic, isolated, and at the lowest level that catches the bug (see `/writing-tests`)
- Reduce nesting: Use early returns, guard clauses, and helper methods to avoid deeply nested code
- Markdown: prefer semantic line breaks; no hard wrapping
- Use American English spelling
@@ -163,6 +164,7 @@ ALWAYS invoke the matching skill **before** writing or reviewing code in these a
- `/django-migrations` — any Django migration
- `/clickhouse-migrations` — any ClickHouse migration
- `/adopting-generated-api-types` — any frontend file using `lib/api`, `api.get<`, `api.create<`, or handwritten API types
+- `/writing-tests` — adding or substantially changing any test (pytest, Jest, or Playwright)
**Invoke when in the area:**
diff --git a/docs/published/handbook/engineering/conventions/backend-coding.md b/docs/published/handbook/engineering/conventions/backend-coding.md
index 5229ca3b051b..168913ac164d 100644
--- a/docs/published/handbook/engineering/conventions/backend-coding.md
+++ b/docs/published/handbook/engineering/conventions/backend-coding.md
@@ -70,6 +70,10 @@ Don’t log sensitive information. Make sure you never log:
### Testing
+A test suite is a shared, permanent liability: every test runs on every PR forever, costs CI time, can flake and block unrelated work, and is code someone has to maintain as the system changes.
+So judge a new test on two independent axes — **value** (does it catch a realistic regression we actually make?) and **cost** (how far down the test pyramid does it sit?).
+Maximize value and minimize cost; this never means "write fewer tests", it means drop the ones that catch nothing and push the rest as far down the pyramid as they go.
+
- All new packages and most new significant functionality should come with unit tests
- Significant features should come with integration and/or end-to-end tests
- Analytics-related queries should be covered by snapshot tests for ease of reviewing
@@ -80,6 +84,37 @@ Don’t log sensitive information. Make sure you never log:
- that's because you want test output to give you the information you need to fix a failure
- and because you want your assertions to be as concrete as possible it shouldn't be possible to break the code and the test pass
+#### Does this test earn its place?
+
+Before writing a test, answer in one sentence: **what realistic regression does this catch that no existing test already catches?**
+Name the bug, the code path, and the input that would break — "increases coverage", "good practice", and "the function exists" are not answers.
+A good answer sounds like _"if someone makes `parse_filters` drop the `team_id` clause, this fails"_.
+
+Most low-value tests are one of these — recognize them and extend an existing test (or delete the code) instead:
+
+- **Trivial / framework behavior**: getters, setters, constants, that Django saved a row or that DRF serialized a field. You're testing someone else's code, not yours.
+- **Change-detector tests**: asserting which private methods were called, with mocks wired to match the current code. They fail on every refactor and catch no real bug. Assert observable behavior through the public interface (return value, persisted state, emitted event, HTTP response), not the choreography that produces it. See [Change-Detector Tests Considered Harmful](https://testing.googleblog.com/2015/01/testing-on-toilet-change-detector-tests.html).
+- **Redundant coverage**: a new test that's a variation of an existing one is a `@parameterized` case (Python) or a `test.each` row (Jest), not a new test function.
+- **Coverage-chasing**: an uncovered line is information, not a defect — don't add a test just to move the number.
+
+#### Weight tests down the pyramid
+
+Each rung is roughly an order of magnitude slower and flakier than the one below:
+
+```text
+pure function → kea logic test → Django TestCase → ClickHouse-backed test → Playwright e2e
+ cheapest most expensive
+```
+
+Aim for a ratio, not a cap: many tests at the bottom, very few at the top — if you want more coverage, add it at the bottom.
+When logic is hard to test cheaply, that's a design signal: extract it into a pure function (or a kea logic) and test that directly rather than standing up a database, a request, and a render.
+Escalating to the next rung is the last resort, not the default.
+
+- **Use `TestCase`, not `TransactionTestCase`, unless you truly need it.** `TransactionTestCase` flushes the DB between tests instead of rolling back a transaction — dramatically slower, and a common source of cross-test interference. For `transaction.on_commit` side effects use `self.captureOnCommitCallbacks(execute=True)`; reaching ClickHouse is not a reason to switch (`ClickhouseTestMixin` runs on a plain `TestCase`).
+- Mock only true boundaries — network, external APIs, the clock, queues. Don't mock your own internal helpers; that's how change-detector tests are born.
+- Frontend: prefer a kea logic test (`logic.actions` / `logic.values`) over a full component render whenever the behavior lives in the logic, and don't snapshot large rendered trees — assert specific fields instead.
+- Keep tests deterministic and isolated: no `time.sleep` or arbitrary waits (use `freeze_time` or wait on a real condition), no real network or live external services, and they must pass in any order. Don't leave a `@skip`/`xfail`/`.only` without a one-line reason and a linked issue.
+
#### Fast developer ("unit") tests
A good test should:
diff --git a/docs/published/handbook/engineering/conventions/frontend-coding.md b/docs/published/handbook/engineering/conventions/frontend-coding.md
index 79592a714528..3c6392496c9e 100644
--- a/docs/published/handbook/engineering/conventions/frontend-coding.md
+++ b/docs/published/handbook/engineering/conventions/frontend-coding.md
@@ -57,6 +57,7 @@ Hence the explicit separation between the data and view layers.
- We loosely follow BEM conventions. If an element can't be namespaced inside a container class (e.g. modals that break out of the containing DOM element), use BEM style names like `.DashboardMenu__modal` to keep things namespaced.
- Keep an eye out for custom styles in SCSS files that can be easily replaced with Tailwind classes and replace them with Tailwind when you see them
- Testing
+ - Before adding a test, make sure it earns its place and sits as low on the test pyramid as it can — the value/cost rubric in [Backend coding conventions › Testing](backend-coding#testing) is language-agnostic.
- Write [logic tests](https://keajs.org/docs/intro/testing) for all logic files.
- [react testing library](https://testing-library.com/docs/react-testing-library/intro/) tests are particularly useful for components with complex interactions or to guide future humans or agents when they're changing components without full context of the uses and edge cases
- Add all new presentational elements and scenes to [our storybook](https://storybook.dev.posthog.dev/). Run `pnpm storybook` locally.