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(tests): add Python test maintenance skill (#87030)

Paul D'Ambra5cb858590bee
diff --git a/.agents/skills/maintaining-python-tests/SKILL.md b/.agents/skills/maintaining-python-tests/SKILL.md
new file mode 100644
index 000000000000..38647c440a0b
--- /dev/null
+++ b/.agents/skills/maintaining-python-tests/SKILL.md
@@ -0,0 +1,211 @@
+---
+name: maintaining-python-tests
+description: >
+ Maintains existing pytest and Django test suites without weakening correctness. Use when asked to reduce Python test runtime or CI work, investigate slow pytest families, remove stale migration tests, consolidate repeated setup, improve Python test ownership, or measure whether a test optimization worked after merge. Ranks work by measured cost, applies the writing-tests value gate to existing coverage, preserves distinct behavior cases, validates isolation after shared-fixture changes, and separates testcase work from pytest-suite wall time. For an intermittent failure, use fixing-flaky-tests instead.
+---
+
+# Maintaining Python tests
+
+Use this skill for an existing Python test suite. Use `/writing-tests` before adding or substantially changing coverage. Use `/fixing-flaky-tests` when intermittent failure is the main problem.
+
+The goal is not a smaller test count. The goal is a suite that catches the same realistic regressions with less compute, less waiting, and less maintenance.
+
+## Principles
+
+1. **Measure before changing code.** Rank tests by total observed work, not by one slow local run.
+2. **Preserve behavior coverage.** Keep cases that exercise different validation, persistence, integration, or output paths.
+3. **Remove only expired or redundant coverage.** Get explicit approval before deleting a test.
+4. **Share expensive infrastructure, not mutable test state.** Preserve isolation with unique IDs, schemas, tables, topics, or tenants.
+5. **Measure after merge.** Local results prove the mechanism. Fresh master data proves the result in CI.
+6. **Separate testcase work from suite wall time.** A change can reduce summed testcase time and not change the slowest pytest suite.
+
+Read [measurement.md](references/measurement.md) before you query timing data or report an improvement.
+Read [optimization-patterns.md](references/optimization-patterns.md) when you select a fix.
+
+## Workflow
+
+### 1. Define the result
+
+Write down the user problem before choosing a test:
+
+- Reduce total test compute.
+- Reduce the slowest pytest suite.
+- Remove expired maintenance burden.
+- Restore test ownership.
+- Reduce repeated external-service setup.
+
+These results need different measurements. Do not claim faster CI when only summed test call time decreased.
+
+### 2. Rank current work
+
+Use recent PostHog test spans from `master` when available. Start with a complete window after the latest relevant merge.
+
+Rank at least three views:
+
+- **Individual tests:** execution count multiplied by duration.
+- **Parameterized families:** all cases under one test function or fixture family.
+- **Pytest suites or shards:** root-span wall time and the slowest suite per run attempt.
+
+Use p50 to find steady cost. Use p95 to find contention or tail behavior. Use sampled observed hours to find repeated medium-cost tests. Use root-span testcase totals for complete pytest work.
+
+Do not select a target from an old ranking after several fixes merge. Rebuild the ranking first.
+
+Do not rank from `.test_durations`. It holds flat default values (0.01, 18.0, and 60.0) for tests that pytest-split could not time. These values are not measurements.
+
+### 3. State why the test exists
+
+Apply the `/writing-tests` gate to every target:
+
+> What realistic regression does this test catch that no existing test already catches?
+
+Then classify each case:
+
+- **Distinct behavior:** keep it.
+- **Same behavior with representative inputs:** parameterize it.
+- **Framework or implementation detail:** replace it with an observable assertion, or propose to delete it.
+- **Temporary migration coverage:** check whether every supported environment completed the migration.
+- **Runnable backfill or reusable migration system:** keep active behavior coverage.
+
+Do not infer redundancy from similar names. Read the setup, execution path, assertions, and production entry point.
+
+### 4. Establish a baseline
+
+Run the exact target with the same command that you will use after the change. Record:
+
+- Test call time.
+- Full command wall time.
+- Setup and teardown time when available.
+- Number of collected and executed cases.
+- Whether the run was cold or warm.
+
+Run the surrounding class or file when fixtures can change the result. A single test can hide repeated setup that only appears across the family.
+
+Do not compare full pytest wall time with summed call time. They measure different work.
+
+### 5. Find the cost center
+
+Profile before rewriting. Attribute time to one of these groups:
+
+- Test collection or environment boot.
+- Fixture setup or teardown.
+- Database creation, flush, or migration.
+- Worker, consumer, broker, or container startup.
+- Product code executed by the test.
+- Snapshot serialization or formatting.
+- Polling, retries, or real time.
+
+Use a wall-clock profile for subprocesses and I/O. Use a CPU profile for Python or JavaScript work. A CPU profile can miss time spent in services or child processes.
+
+### 6. Select the smallest safe fix
+
+Prefer these options in order:
+
+1. Remove expired coverage with explicit approval.
+2. Replace incidental implementation assertions with stronger observable assertions.
+3. Move the test to a cheaper level.
+4. Reuse expensive immutable infrastructure across cases.
+5. Reuse production objects only when the production path repeats unnecessary work.
+6. Remove a distinct case only when another test proves the same regression through the same boundary.
+
+Do not add timing assertions. CI timing is too noisy for a correctness test.
+
+### 7. Preserve isolation
+
+A shared fixture must not create an ordering dependency.
+
+Before sharing setup, identify all state it owns:
+
+- Tenant or team IDs.
+- Database rows and transactions.
+- ClickHouse tables.
+- Kafka topics and consumer offsets.
+- Temporal task queues and workflow IDs.
+- Object-storage prefixes.
+- Environment variables and global settings.
+- Mocks and patched functions.
+
+Give each case unique mutable state. Reset shared clients when their local cache or offset can affect the next case.
+
+Run cases alone, together, and in a different order when the framework permits it. Run the family more than once when shared setup has process-level state.
+
+### 8. Validate correctness and cost
+
+Use this validation ladder:
+
+1. Run the exact target.
+2. Run the parameter family, class, or file.
+3. Run related integration modes and pipeline versions.
+4. Repeat the family when setup is shared.
+5. Run lint, type checks, and repository preflight.
+
+Keep exact result, response, persisted-state, or emitted-message assertions. Do not replace them with weaker row counts or truthiness checks to gain speed.
+
+Use TDD when the change affects a helper or the contract of a test framework. Make the intended behavior fail first. For a pure runtime change, use a measured baseline instead of an unreliable timing test.
+
+### 9. Report the local result accurately
+
+Use this format:
+
+```text
+Target: <test, family, or shard>
+Regression: <what behavior remains protected>
+Cost center: <measured source of time>
+Change: <smallest fix>
+Before: <metric, command, cases, cold/warm state>
+After: <same metric and conditions>
+Correctness: <focused and surrounding tests>
+Isolation: <how shared state stays separate>
+Follow-up: <post-merge query or none>
+```
+
+Do not report a percentage from two different measurement types.
+
+### 10. Verify after merge
+
+Wait for fresh `master` runs that contain the merge commit. Compare equivalent windows and cohorts.
+
+Check all relevant outcomes:
+
+- Exact test p50 and p95.
+- Family sampled time per workflow attempt.
+- Slowest affected suite per workflow attempt.
+- Complete JUnit testcase time per workflow attempt.
+- Slowest pytest-suite wall time.
+- Failure rate and test count.
+- Unowned test-span share when ownership changed.
+
+If summed testcase time falls but suite wall time does not change, report both facts. Select the next target from the current slowest shard.
+
+If the expected metric does not change, do not declare success from local data. Check whether the cost moved into fixture setup, teardown, or another test.
+
+## Deletion rules
+
+Get explicit user approval before you delete tests. Then confirm all of these conditions:
+
+- You can name the behavior that the test covered.
+- Another named test covers it, or the production behavior no longer exists.
+- No supported upgrade, rollback, or runnable command needs the old state.
+- You keep migration source files and active backfill coverage.
+- The surrounding suite passes without hidden ordering dependencies.
+
+Delete expired tests. Do not leave them skipped. A skip keeps unused code and can still add collection or service cost.
+
+## Boundaries
+
+- Do not remove cases to improve a count.
+- Do not use sleeps, retries, or larger timeouts as performance fixes.
+- Do not mock the behavior that the test exists to prove.
+- Do not convert integration coverage to a unit test unless an integration wiring guard remains.
+- Do not optimize production code only for a test. Confirm that the repeated work exists in production.
+- Do not edit CI workflows as part of a test-runtime fix.
+- Do not use PR runs as the post-merge result. Use fresh `master` runs.
+- Do not claim causality from a broad before-and-after window when unrelated changes also merged.
+
+## Related skills
+
+- `/writing-tests`: decide whether new or changed coverage earns its cost.
+- `/fixing-flaky-tests`: reproduce and fix intermittent failures.
+- `/debugging-ci-failures`: classify a failing CI run before changing a test.
+- `/django-migrations`: change or remove migration-related code safely.
+- `/establishing-code-ownership`: add or correct ownership rules.
+- `/querying-posthog-data`: verify the trace schema and HogQL before reading CI timing data.
diff --git a/.agents/skills/maintaining-python-tests/references/measurement.md b/.agents/skills/maintaining-python-tests/references/measurement.md
new file mode 100644
index 000000000000..4a07d2612c4f
--- /dev/null
+++ b/.agents/skills/maintaining-python-tests/references/measurement.md
@@ -0,0 +1,263 @@
+# Measuring test cost
+
+Use the same measurement before and after a change. State the command, scope, and time type.
+
+## Local measurements
+
+Start with the repository test runner:
+
+```bash
+hogli test path/to/test.py::TestClass::test_name
+```
+
+Use pytest directly when you need pytest timing output:
+
+```bash
+uv run pytest -q path/to/test.py::TestClass::test_name --durations=20
+```
+
+Measure full wall time separately:
+
+```bash
+/usr/bin/time -f 'wall=%e user=%U system=%S max_rss_kb=%M' \
+ uv run pytest -q path/to/test.py -k 'target_family' --durations=20
+```
+
+For a parameterized family, record all cases. Do not compare one case before the change with the full family after it.
+
+Run a cold baseline when the optimization targets startup. Run a warm baseline when the optimization targets repeated work within one process. Label the result.
+
+## Interpreting pytest time
+
+Pytest can report separate phases:
+
+- **setup:** fixture setup before the test call.
+- **call:** the test function body.
+- **teardown:** fixture cleanup after the test call.
+- **wall:** the complete command, including collection and process startup.
+
+A module-scoped fixture can move cost from repeated call phases into one setup phase. The call sum can decrease while wall time does not change. Report both.
+
+Do not assume that expensive setup always shows in the setup phase. A Django migration test runs the migration executor in the call phase, so its call time is almost equal to its total time.
+
+## Profiling
+
+Use cProfile for in-process Python CPU work:
+
+```bash
+uv run python -m cProfile -o /tmp/test.prof -m pytest -q <nodeid>
+uv run python - <<'PY'
+import pstats
+pstats.Stats('/tmp/test.prof').strip_dirs().sort_stats('cumulative').print_stats(40)
+PY
+```
+
+Use py-spy or a system profiler when subprocesses, native code, or I/O dominate. Use service logs when the test starts a worker or container.
+
+Do not profile a broad file first. Profile the smallest target that still reproduces the cost.
+
+## CI timing data
+
+The Backend CI timing reporter writes pytest spans to `posthog.trace_spans`.
+
+Useful fields include:
+
+```text
+service_name = 'ci-backend'
+resource_attributes['ci.branch']
+resource_attributes['ci.run_id']
+resource_attributes['ci.run_attempt']
+attributes['test.runner']
+attributes['test.outcome']
+attributes['test.owner_team']
+attributes['test.file']
+attributes['test.file_source']
+attributes['shard.segment']
+attributes['shard.testcase_seconds']
+is_root_span
+duration_nano
+```
+
+Invoke `/querying-posthog-data` before you use `posthog:execute-sql`. Verify the available trace fields before you query them. Use `master` for post-merge impact. Use explicit UTC windows.
+
+### Rank emitted slow pytest tests
+
+The reporter emits individual test spans only above its configured duration threshold. Use this query to rank the sampled slow-test work, not all pytest work.
+
+```sql
+SELECT
+ name,
+ coalesce(nullIf(attributes['test.owner_team'], ''), 'unowned') AS owner_team,
+ count() AS executions,
+ round(quantile(0.5)(duration_nano / 1000000000), 3) AS p50_seconds,
+ round(quantile(0.95)(duration_nano / 1000000000), 3) AS p95_seconds,
+ round(sum(duration_nano) / 1000000000 / 3600, 2) AS observed_hours
+FROM posthog.trace_spans
+WHERE timestamp >= now() - INTERVAL 2 DAY
+ AND service_name = 'ci-backend'
+ AND resource_attributes['ci.branch'] = 'master'
+ AND attributes['test.runner'] = 'pytest'
+ AND attributes['test.outcome'] = 'passed'
+ AND duration_nano > 0
+GROUP BY name, owner_team
+HAVING executions >= 10
+ORDER BY observed_hours DESC
+LIMIT 50
+```
+
+Adjust the two-day window only when the sample is too small or includes a known incident. A missing after row can mean the test fell below the reporting threshold, not that it stopped running.
+
+### Compare a test before and after a merge
+
+Use two windows with the same length. Leave a gap around the merge so old jobs cannot enter the after group.
+
+```sql
+WITH samples AS (
+ SELECT
+ multiIf(
+ timestamp >= toDateTime('2026-01-01 00:00:00', 'UTC')
+ AND timestamp < toDateTime('2026-01-02 00:00:00', 'UTC'), 'before',
+ timestamp >= toDateTime('2026-01-03 00:00:00', 'UTC')
+ AND timestamp < toDateTime('2026-01-04 00:00:00', 'UTC'), 'after',
+ 'excluded'
+ ) AS period,
+ duration_nano / 1000000000 AS seconds
+ FROM posthog.trace_spans
+ WHERE service_name = 'ci-backend'
+ AND resource_attributes['ci.branch'] = 'master'
+ AND attributes['test.outcome'] = 'passed'
+ AND name = '<exact test span name>'
+)
+SELECT
+ period,
+ count() AS executions,
+ round(quantile(0.5)(seconds), 3) AS p50_seconds,
+ round(quantile(0.95)(seconds), 3) AS p95_seconds,
+ round(avg(seconds), 3) AS mean_seconds
+FROM samples
+WHERE period != 'excluded'
+GROUP BY period
+ORDER BY period
+```
+
+Use the exact merge timestamp from GitHub to choose the windows. Confirm that the after window contains runs with the merged code. This comparison applies only while the test emits a span in both periods.
+
+### Measure a parameter family per workflow run
+
+```sql
+WITH per_run AS (
+ SELECT
+ resource_attributes['ci.run_id'] AS run_id,
+ resource_attributes['ci.run_attempt'] AS run_attempt,
+ sum(duration_nano) / 1000000000 AS sampled_seconds,
+ uniq(name) AS sampled_cases
+ FROM posthog.trace_spans
+ WHERE timestamp >= now() - INTERVAL 2 DAY
+ AND service_name = 'ci-backend'
+ AND resource_attributes['ci.branch'] = 'master'
+ AND attributes['test.outcome'] = 'passed'
+ AND name LIKE '%::test_target_family[%]'
+ GROUP BY run_id, run_attempt
+)
+SELECT
+ count() AS attempts,
+ round(quantile(0.5)(sampled_seconds), 2) AS p50_sampled_seconds_per_attempt,
+ round(quantile(0.95)(sampled_seconds), 2) AS p95_sampled_seconds_per_attempt,
+ round(avg(sampled_cases), 1) AS mean_sampled_cases_per_attempt
+FROM per_run
+```
+
+Check the expected case count against the sampled case count. Use this query only when every target case exceeds the reporting threshold. A lower duration is not valid if fewer cases emitted spans.
+
+### Measure the affected shard
+
+```sql
+WITH per_run AS (
+ SELECT
+ resource_attributes['ci.run_id'] AS run_id,
+ resource_attributes['ci.run_attempt'] AS run_attempt,
+ max(duration_nano) / 1000000000 AS slowest_suite_seconds,
+ sum(duration_nano) / 1000000000 AS total_suite_seconds,
+ count() AS suites
+ FROM posthog.trace_spans
+ WHERE timestamp >= now() - INTERVAL 2 DAY
+ AND service_name = 'ci-backend'
+ AND resource_attributes['ci.branch'] = 'master'
+ AND is_root_span
+ AND attributes['shard.segment'] = '<segment>'
+ GROUP BY run_id, run_attempt
+)
+SELECT
+ count() AS attempts,
+ round(quantile(0.5)(slowest_suite_seconds), 2) AS p50_slowest_suite_seconds,
+ round(quantile(0.95)(slowest_suite_seconds), 2) AS p95_slowest_suite_seconds,
+ round(quantile(0.5)(total_suite_seconds), 2) AS p50_total_suite_seconds,
+ round(avg(suites), 1) AS suites_per_attempt
+FROM per_run
+```
+
+The slowest root span approximates the segment's pytest-suite critical path. It excludes checkout, cache restoration, artifact handling, and other GitHub Actions steps.
+
+### Measure total pytest work and suite wall time
+
+```sql
+WITH per_run AS (
+ SELECT
+ resource_attributes['ci.run_id'] AS run_id,
+ resource_attributes['ci.run_attempt'] AS run_attempt,
+ sumIf(toFloatOrZero(attributes['shard.testcase_seconds']), is_root_span) AS testcase_seconds,
+ maxIf(duration_nano, is_root_span) / 1000000000 AS slowest_suite_seconds,
+ uniqIf(trace_id, is_root_span) AS suites
+ FROM posthog.trace_spans
+ WHERE timestamp >= now() - INTERVAL 2 DAY
+ AND service_name = 'ci-backend'
+ AND resource_attributes['ci.branch'] = 'master'
+ GROUP BY run_id, run_attempt
+ HAVING suites > 0
+)
+SELECT
+ count() AS attempts,
+ round(quantile(0.5)(testcase_seconds), 1) AS p50_testcase_seconds,
+ round(quantile(0.95)(testcase_seconds), 1) AS p95_testcase_seconds,
+ round(quantile(0.5)(slowest_suite_seconds), 1) AS p50_slowest_suite_seconds,
+ round(quantile(0.95)(slowest_suite_seconds), 1) AS p95_slowest_suite_seconds
+FROM per_run
+```
+
+`shard.testcase_seconds` includes every JUnit testcase, including tests below the individual-span threshold. The slowest suite span measures pytest execution, not the complete GitHub Actions job.
+
+Summed testcase time under-reports the job step. The difference scales with the number of collected tests, not with their duration, because collection and module imports cost time per test. Do not size a suite from summed durations alone.
+
+### Measure ownership
+
+```sql
+SELECT
+ toDate(timestamp) AS day,
+ count() AS test_spans,
+ countIf(nullIf(attributes['test.owner_team'], '') IS NULL) AS unowned_spans,
+ round(100 * unowned_spans / test_spans, 2) AS unowned_percent
+FROM posthog.trace_spans
+WHERE timestamp >= now() - INTERVAL 2 DAY
+ AND service_name = 'ci-backend'
+ AND attributes['test.runner'] = 'pytest'
+GROUP BY day
+ORDER BY day
+```
+
+Treat ownership as a routing result. It does not prove that test cost decreased.
+
+## Reporting limits
+
+Before you state an improvement, confirm these conditions:
+
+- Both samples use the same branch.
+- Both samples use the same test name or family rule.
+- Both samples contain the same cases.
+- Both samples use the same time type.
+- The after sample contains the merged code.
+- The sample sizes are large enough to resist one unusual run.
+- The evidence is not a file that the changed step wrote.
+
+State when unrelated changes landed in the same window. Use the exact-test result for causal claims. Use the whole-run result as directional evidence.
+
+A file that a step writes cannot prove that the step is correct. To test a correction or a filter, run it again on the raw inputs.
diff --git a/.agents/skills/maintaining-python-tests/references/optimization-patterns.md b/.agents/skills/maintaining-python-tests/references/optimization-patterns.md
new file mode 100644
index 000000000000..896c12553303
--- /dev/null
+++ b/.agents/skills/maintaining-python-tests/references/optimization-patterns.md
@@ -0,0 +1,182 @@
+# Test optimization patterns
+
+Select a pattern only after measurement identifies the cost center.
+
+## Reuse expensive infrastructure
+
+Use this pattern when each case starts the same worker, consumer, client, container, or database helper.
+
+Good shared state is expensive and immutable during a case:
+
+- A Temporal worker on one task queue.
+- A Kafka client or consumer factory.
+- A database parser or schema registry.
+- A container that hosts an external service.
+
+Bad shared state contains case output:
+
+- A tenant row reused by every case.
+- One workflow ID or object-storage prefix.
+- A consumer offset that the next test inherits.
+- A mutable global patch.
+
+A safe change has this shape:
+
+1. Create the infrastructure once at module or class scope.
+2. Give every case unique mutable identifiers.
+3. Pass the shared object through an explicit fixture or helper parameter.
+4. Keep teardown at the same scope as setup.
+5. Run all modes and all cases together.
+6. Run selected cases alone to prove that no previous case prepares them.
+
+Measure setup, call, and full wall time. Fixture reuse often moves cost between phases.
+
+## Preserve parameter cases
+
+Do not remove values because they appear similar. Check which boundary each value exercises:
+
+- Serializer validation.
+- Normalization.
+- Persistence.
+- Database constraints.
+- Post-save hooks.
+- External client behavior.
+- Query output.
+
+Keep the full matrix when different values can fail at different boundaries. Optimize the shared work around the matrix.
+
+Use parameterization to remove duplicated test code. Parameterization alone does not reduce execution cost.
+
+## Replace incidental snapshots
+
+A snapshot can be the main cost when it formats a large query, object graph, or rendered tree.
+
+Remove a snapshot only when it describes implementation rather than behavior. Replace it with assertions that cover all meaningful output fields.
+
+A safe replacement proves:
+
+- The query or request still executes.
+- Every mode still runs.
+- The complete result shape remains correct.
+- Important values remain exact.
+- The test still fails for the regression it protects.
+
+Do not replace a snapshot with a path-only or non-empty assertion. That weakens coverage.
+
+## Reuse production work
+
+A slow test can reveal repeated work in production. Optimize product code only after profiling proves the repeated work exists outside the test harness.
+
+Examples include:
+
+- Rebuilding the same database or schema object inside one operation.
+- Parsing the same query several times.
+- Fetching the same immutable configuration for each item in one request.
+
+Keep API and integration cases after the production optimization. Strengthen persisted-state assertions when shared production work can cause cross-item contamination.
+
+## Move a test to a cheaper level
+
+Move a test to a cheaper level when its regression does not require its current boundary:
+
+```text
+pure function -> Django SimpleTestCase -> Django TestCase -> integration service
+```
+
+Keep one wiring guard at the higher level when the lower-level test cannot prove that the production entry point uses the tested component.
+
+Examples:
+
+- Put a DRF validation matrix in `SimpleTestCase`. Keep one endpoint 400 case.
+- Test transformation logic as a pure function. Keep one pipeline round trip.
+
+Do not mock the boundary that the test exists to prove.
+
+## Use cheaper Django isolation
+
+Prefer `SimpleTestCase` when no database access is needed.
+
+Prefer `TestCase` when transaction rollback can isolate the case.
+
+Use `TransactionTestCase` only when the regression requires committed transaction behavior. Database flushes make it expensive.
+
+A change of the base class needs an isolation proof. Run the complete class more than once and in a different order when possible.
+
+## Retire temporary migration tests
+
+A dedicated data-migration test is temporary when all of these conditions hold:
+
+- Every supported environment applied the migration.
+- The rollback window closed.
+- No supported upgrade begins from the old state.
+- The behavior does not remain as a runnable command or reusable backfill.
+
+Delete the expired test after explicit approval. Keep the migration file.
+
+Keep tests for:
+
+- Migration tooling and safety checks.
+- Reusable backfill frameworks.
+- Backfills that operators can still run.
+- Production commands with active behavior.
+
+Do not mark an expired test as skipped.
+
+## Reduce database setup
+
+Look for repeated creation of organizations, teams, users, schemas, and permissions.
+
+Safe options include:
+
+- Use a lighter base class.
+- Create immutable parent rows once.
+- Use factories that create only required fields.
+- Move pure validation out of a database-backed endpoint matrix.
+
+Do not share tenant rows when the code under test mutates tenant state. Unique tenant IDs are often the cheapest isolation boundary.
+
+## Remove real waiting
+
+A maintenance change must not add sleeps or retries.
+
+Replace polling with one of these options:
+
+- Await the workflow or task result.
+- Flush the queue or consumer through a test helper.
+- Freeze or advance the clock.
+- Wait on an explicit condition with a bounded diagnostic error.
+
+If the wait represents real external nondeterminism, use `/fixing-flaky-tests` before you change it.
+
+## Improve ownership
+
+An unowned slow test has two maintenance problems. Fix the path or ownership rule after you confirm the correct team.
+
+Prefer the narrowest stable ownership path. Do not assign a broad directory to a team only to capture one file.
+
+Verify the emitted `test.owner_team` value after the reporter change reaches CI. A local resolver result proves the rule. It does not prove the timing reporter emitted it.
+
+## Common incorrect results
+
+Reject these results:
+
+- The test count fell because a filter stopped collecting cases.
+- Call time fell because work moved to setup.
+- One warm run is compared with one cold run.
+- Local wall time is compared with CI call time.
+- The average fell while p95 and the slowest-suite time increased.
+- A snapshot was removed without equivalent result assertions.
+- A worker was shared while cases reused mutable IDs.
+- A broad before-and-after window is described as causal.
+
+## When to stop
+
+Stop work on a target when one of these conditions is true:
+
+- The target no longer appears in the current high-cost ranking.
+- The next change would weaken a meaningful boundary.
+- The remaining time is required product behavior.
+- Another shard now controls the critical path.
+- The evidence does not identify a cost center.
+
+Rebuild the ranking. Select the next measured target. Do not continue work on a test that no longer matters.