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(agents): teach the test and merge-queue skills about clock-granularity flakes (#93157)

Paul D'Ambra9bde71366bdd
diff --git a/.agents/skills/debugging-ci-failures/SKILL.md b/.agents/skills/debugging-ci-failures/SKILL.md
index 4d8b2a595e66..95d18e75b52b 100644
--- a/.agents/skills/debugging-ci-failures/SKILL.md
+++ b/.agents/skills/debugging-ci-failures/SKILL.md
@@ -161,6 +161,11 @@ practice that is most of the queue. So:
- The branch names one PR but carries many. A failure on it is not evidence
against that PR until you find the change that caused it; the branch's other
merge commits are the first suspects.
+- A `…-bisection` branch is the exception to "the other merge commits are the
+ first suspects": Trunk creates it after a batch fails, and it carries only
+ master plus the one PR. The test PR's body names the master SHA it is based
+ on; if master's run at that SHA passed the same test, the failure is an
+ environment-dependent race (`fixing-flaky-tests` step 1), not this PR's.
- In the digest this is the `blocking_merge_queue` state.
### 3. Read the CI report comment (for a PR)
diff --git a/.agents/skills/fixing-flaky-tests/SKILL.md b/.agents/skills/fixing-flaky-tests/SKILL.md
index 66aac9828fb1..215f5a9386c9 100644
--- a/.agents/skills/fixing-flaky-tests/SKILL.md
+++ b/.agents/skills/fixing-flaky-tests/SKILL.md
@@ -52,6 +52,7 @@ Read the timeline before you classify:
- **Interleaved pass/fail on adjacent commits** — the same unchanged test verified passing in some runs, failing in others → genuinely **flaky**; continue here.
- **A long unbroken failure streak** (say 30+ consecutive) is statistically incompatible with a flake — at any per-run rate below ~95%, `p^30 ≈ 0`. That is a **deterministic regression**: go to `debugging-ci-failures` and find the introducing commit (step 4).
+- **Every rerun fails on one runner, yet `master` passes the same code** → an **environment-dependent race**, not a regression: kernel clock granularity, filesystem, runner speed. Retrying on the same runner cannot help, so "failed 3/3 attempts" says nothing about whether the PR caused it. A merge-queue failure hands you the control for free: the `trunk-merge/**` test PR's body names the master SHA it is based on, so read master's run at that SHA (`gh api repos/PostHog/posthog/commits/<sha>/check-runs`) and confirm the same test ran and passed there.
- **Both at once** is common: a latent flake whose rate jumped to ~100%. Find the transition (last green → first red); that boundary, not the digest's one-line verdict, is what tells you what tipped it. `products/engineering_analytics/skills/investigating-ci-failures/` has the boundary query if the failure reached master.
If a failure is reported as (or you suspect it is) **consistent**, don't serialize — measure the rate and attempt a repro **in parallel**.
@@ -143,7 +144,9 @@ Two cost notes for the loop:
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 7 is then analytical, not empirical.
+Before settling for that, ask what the runner has that your machine lacks: Linux mtimes from a coarse clock where macOS gives nanoseconds, a case-sensitive filesystem, a different timezone, `/tmp` on a different filesystem.
+Often you can force the CI condition instead of waiting for it — `os.utime` the files into the ordering the coarse clock produced, run under `TZ=UTC` — and then validate empirically after all.
+Otherwise proceed with a fix grounded in the CI evidence and root-cause analysis, and say so explicitly in the report — the validation in step 7 is then analytical, not empirical.
## 4. Root-cause the flake
@@ -157,6 +160,7 @@ Match the symptom to a cause class; never patch the symptom.
| 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 |
+| Every attempt fails on one runner, passes on another | Clock-granularity race: cutoff read from an earlier write |
### When the cause isn't obvious, bisect
@@ -193,6 +197,7 @@ PostHog-specific patterns:
- **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 `time_machine.travel(..., tick=False)`; never assert on `now()`-derived values.
+- **Timestamp-derived cutoffs**: pinning or filtering "as of" the previous write's recorded time — stamp the times explicitly instead (`/writing-tests`, "Two writes in a row are not ordered in time").
- **ClickHouse eventual consistency**: a query may not see just-inserted data — flush explicitly in the test setup rather than sleeping.
## 5. Decide the outcome — fixing is one of three
diff --git a/.agents/skills/triaging-merge-queue-failures/SKILL.md b/.agents/skills/triaging-merge-queue-failures/SKILL.md
index 8723913ad8c3..b9a11fc8878a 100644
--- a/.agents/skills/triaging-merge-queue-failures/SKILL.md
+++ b/.agents/skills/triaging-merge-queue-failures/SKILL.md
@@ -259,6 +259,8 @@ The same failing check name appears on other PRs' recent attempts or on `master`
- Trunk is selective — it does not retry every failure automatically. Absence of an automatic retry is not evidence the failure was real.
- Trunk closes a shadow PR as soon as it no longer needs that attempt, and GitHub cancels the attempt's in-flight runs with it. Read a wall of `cancelled` runs on a shadow PR as teardown, not as an outage.
- A failed PR is not dropped immediately: Trunk's own wording is that it "failed tests and is waiting for other pull requests to finish testing", and it may then open a bisection attempt. A `failed` state can therefore be followed by more attempts without anyone requeueing.
+- A `-bisection` attempt is based on plain master plus the one PR, and the shadow PR's body names that base SHA. Read master's run at that SHA (`gh api repos/PostHog/posthog/commits/<sha>/check-runs`): if the same test ran and passed there, the PR is the flake's victim, not its cause — verdict 5, even though the same head has now failed twice. pytest `--reruns` cannot rescue an environment-dependent race (clock granularity, runner speed), so "failed every attempt" is not evidence either way; `/fixing-flaky-tests` step 1 covers the comparison.
+- `products/warehouse_sources/junit-product.xml` is excluded from the Trunk quarantine gate (`prepare-product-junit-for-trunk.sh` in `ci-backend.yml`), so a known flake there still reds its shard. Quarantine status never explains a warehouse-sources failure.
## Unattended sweeps
diff --git a/.agents/skills/writing-tests/SKILL.md b/.agents/skills/writing-tests/SKILL.md
index b88fe94dbe2f..7ec9cdd15cc6 100644
--- a/.agents/skills/writing-tests/SKILL.md
+++ b/.agents/skills/writing-tests/SKILL.md
@@ -179,6 +179,12 @@ Escalating to the next rung is the last resort, not the default.
Most ClickHouse tables are already safe: they build their TTL through `ttl_period()` ([`posthog/clickhouse/kafka_engine.py`](../../../posthog/clickhouse/kafka_engine.py)), which returns `""` under `settings.TEST`, so tests get no TTL at all.
A table that hardcodes its `TTL` clause opts out of that guard — `ai_events` is one. Check rather than assume: `grep -rlE '^\s*TTL ' posthog/models/ posthog/clickhouse/ --include=*.py`.
Make the row's lifetime independent of the ambient clock instead — pin the retention column on insert, the way `bulk_create_ai_events` writes `retention_days=10000`. Moving the frozen date forward only resets the timer.
+- **Two writes in a row are not ordered in time.**
+ Don't derive a cutoff from one write's recorded timestamp and expect the next write to land after it.
+ Clocks are coarser than they look: library timestamps are milliseconds, and on Linux file mtimes come from the kernel's coarse clock, which lags the in-process clock by a scheduler tick.
+ The library may also read a different clock than the one you sampled — delta-rs time travel resolves a datetime against the `_delta_log` commit files' mtimes, not the `timestamp` that `DeltaTable.history()` reports.
+ Such a test passes on macOS and fails every rerun on a fast Linux runner, so retries don't save it and it blames whichever PR is in the merge queue.
+ Set the times yourself — `os.utime` on the file, an explicit `created_at` on the row — minutes apart, and pick a cutoff between them. That is also the production shape, where the two events are seconds apart.
- **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.