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(devex): refuse pushes to branches sitting in the trunk merge queue (#84196)

Georges-Antoine Assi96d1f4437797
diff --git a/.agents/skills/debugging-ci-failures/SKILL.md b/.agents/skills/debugging-ci-failures/SKILL.md
index 4d33b83e28e0..225b603a7766 100644
--- a/.agents/skills/debugging-ci-failures/SKILL.md
+++ b/.agents/skills/debugging-ci-failures/SKILL.md
@@ -109,6 +109,19 @@ When scanning logs, search for `FAIL`, `Error`, `error:`, `assert`,
`Traceback`, `exit code`, and `##[error]`. Stop at the first failing step that
explains the run's conclusion. Keep excerpts under 40 lines.
+For test-job failures, the `trunk` MCP server's `investigate-ci-failure` tool
+is a shortcut past log scanning: give it the run URL
+(`https://github.com/PostHog/posthog/actions/runs/<run-id>`) and it returns
+structured failing-test details — names, error messages, stdout/stderr — from
+the results CI uploaded to Trunk Flaky Tests, with quarantined known-flaky
+tests already filtered out. It only covers what ran and uploaded: for jobs
+that died before tests (build, setup, lint), stay with `gh run view --log`.
+Authenticate once via `/mcp` → `trunk` (browser OAuth); headless environments
+instead add an `Authorization: Bearer` header with a `TRUNK_API_TOKEN` org
+token to the server entry in `.mcp.json`. To dig into one test's flakiness
+history, hand off to `fixing-flaky-tests`, which covers the `search-test` and
+`fix-flaky-test` tools.
+
## Classification
| Signal in the log | Class | First action |
diff --git a/.agents/skills/fixing-flaky-tests/SKILL.md b/.agents/skills/fixing-flaky-tests/SKILL.md
index c222c874f56b..18ac7402b537 100644
--- a/.agents/skills/fixing-flaky-tests/SKILL.md
+++ b/.agents/skills/fixing-flaky-tests/SKILL.md
@@ -2,7 +2,7 @@
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.
+ 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, when asked to check Trunk Flaky Tests for a test, PR, or master, 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.
Stabilizing is not the only valid outcome — the skill also gates whether the test should exist, so deleting a test that catches nothing real, or re-leveling one that flakes because of the level it runs at, are first-class endings.
---
@@ -64,6 +64,20 @@ hogli ci:insights search "<test name or error>" # historical context / existi
An insight with a **merged fix** means the flake may already be resolved — read the fix, confirm _against the run data_ that it covers this failure, and report instead of re-fixing.
+### Corroborate with Trunk Flaky Tests
+
+CI uploads test results to [Trunk Flaky Tests](https://app.trunk.io/posthog-inc/flaky-tests?repo=PostHog/posthog), which tracks per-test failure history across `master` and PR runs.
+On a PR, the `trunk-io` bot's "Trunk Test Analytics" comment links that PR's slice (`https://app.trunk.io/posthog-inc/flaky-tests/pr/<number>?repo=PostHog/posthog`).
+
+The `trunk` MCP server in `.mcp.json` queries it (tools are marked experimental by Trunk):
+
+- `search-test` (`repoName: "PostHog/posthog"`, `testNameSearch: "<test name, no filepath>"`) → the test case ID.
+- `fix-flaky-test` (`repoName`, `testCaseId`) → failure history, first-seen commit, git blame, and Trunk's root-cause investigation; `createNewInvestigation: true` triggers a fresh analysis (takes up to a minute).
+
+Authenticate once via `/mcp` → `trunk` (browser OAuth); headless environments instead add an `Authorization: Bearer` header with a `TRUNK_API_TOKEN` org token to the server entry.
+
+Like `ci:insights`, this is corroboration and history, not the classification authority — flaky-vs-deterministic and the rate still come from the run data above.
+
## 2. Extract the failure from CI
```bash
diff --git a/.flox/env/manifest.toml b/.flox/env/manifest.toml
index 8e233c75cd03..4c6fe8dad5e1 100644
--- a/.flox/env/manifest.toml
+++ b/.flox/env/manifest.toml
@@ -50,6 +50,7 @@ ninja.pkg-path = "ninja"
emscripten = { pkg-path = "emscripten", pkg-group = "emscripten", version = "4.0.23" }
libpthread-stubs = { pkg-path = "libpthread-stubs", pkg-group = "emscripten" }
watchman = { pkg-path = "watchman" } # Fast file watching for Django/Celery autoreload (uses pywatchman)
+trunk-io = { pkg-path = "trunk-io", version = "^1.3.4" } # Launcher for the Trunk merge queue CLI; the CLI version itself is pinned in .trunk/trunk.yaml
# Set environment variables in the `[vars]` section. These variables may not
# reference one another, and are added to the environment without first
diff --git a/.husky/pre-push b/.husky/pre-push
index f22400d3b354..acee0733ac45 100755
--- a/.husky/pre-push
+++ b/.husky/pre-push
@@ -10,6 +10,81 @@ then
exit 1 # push will not execute
fi
+# Refuse to push a branch whose PR sits in the Trunk merge queue, because the push knocks
+# it out of the queue. Queue membership comes from `trunk merge status`, which needs a
+# one-time `trunk login`; anything short of a recognized in-queue answer (missing gh or
+# trunk, not logged in, offline, unrecognized output) allows the push, with transient
+# gh and trunk failures retried three times before failing open. A PR in
+# "Pending Failure" also allows: after a failed batch, pushing a fix is the intended
+# action and Trunk drops the queue entry itself. TRUNK_QUEUE_PUSH_CHECK_DISABLED=1 skips.
+if [ -z "$TRUNK_QUEUE_PUSH_CHECK_DISABLED" ] \
+ && command -v gh >/dev/null 2>&1 \
+ && command -v trunk >/dev/null 2>&1
+then
+ repo=$(printf '%s' "$2" | sed -E 's#^.*github\.com[:/]##; s#\.git$##')
+ if [ -n "$repo" ] && [ "$repo" != "$2" ]
+ then
+ while read -r local_ref local_sha remote_ref remote_sha
+ do
+ case "$remote_ref" in
+ refs/heads/*) branch="${remote_ref#refs/heads/}" ;;
+ *) continue ;;
+ esac
+ case "$local_sha" in
+ *[!0]*) ;;
+ *) continue ;; # deleting the branch closes the PR; nothing for the guard to protect
+ esac
+ branch_prs=''
+ for attempt in 1 2 3
+ do
+ if branch_prs=$(gh pr list -R "$repo" --head "$branch" --state open \
+ --json number --jq '.[].number' </dev/null 2>/dev/null)
+ then
+ break
+ fi
+ branch_prs=''
+ sleep 1
+ done
+ for pr in $branch_prs
+ do
+ case "$pr" in
+ *[!0-9]*) continue ;;
+ esac
+ trunk_ok=''
+ for attempt in 1 2 3
+ do
+ if trunk_out=$(trunk merge status "$pr" --ci --no-progress </dev/null 2>&1)
+ then
+ trunk_ok=1
+ break
+ fi
+ case "$trunk_out" in
+ # Deterministic auth/config errors: retrying cannot help, and most
+ # devs without a login would otherwise pay the retries on every push.
+ *"not logged in"*|*"trunk login"*|*"trunk init"*) break ;;
+ esac
+ sleep 1
+ done
+ [ -z "$trunk_ok" ] && continue
+ # Clear states first: "Pending Failure" would otherwise hit the queued
+ # pattern's "pending", and "not in the queue" its "queue".
+ if printf '%s' "$trunk_out" | grep -qiE '(not|no longer)[^.]*queue|pending failure|merged|failed|cancelled'
+ then
+ continue
+ fi
+ if printf '%s' "$trunk_out" | grep -qiE 'queued|pending|testing|tests passed|waiting'
+ then
+ echo "pre-push: PR #$pr ('$branch') is in the Trunk merge queue — this push would remove it from the queue."
+ echo "Do NOT push to this branch. Let the queued PR merge, then make further changes on a NEW branch and open a NEW pull request."
+ echo "If you really need to update this PR instead, run 'trunk merge cancel $pr' (or comment '/trunk cancel'), wait for it to leave the queue, then push again."
+ exit 1
+ fi
+ echo "pre-push: unrecognized 'trunk merge status' output for PR #$pr — queue guard skipped for it."
+ done
+ done
+ fi
+fi
+
# Catch deterministic CI failures before this push burns a CI matrix.
# Advisories never block; HOGLI_PREFLIGHT_DISABLED=1 makes it a no-op; no hogli → skip.
if command -v hogli >/dev/null 2>&1
diff --git a/.mcp.json b/.mcp.json
index 563c1b8e7d2b..72b7d2dc74b5 100644
--- a/.mcp.json
+++ b/.mcp.json
@@ -7,6 +7,10 @@
"posthog-local": {
"type": "http",
"url": "http://localhost:8787/mcp"
+ },
+ "trunk": {
+ "type": "http",
+ "url": "https://mcp.trunk.io/mcp"
}
}
}
diff --git a/.trunk/.gitignore b/.trunk/.gitignore
new file mode 100644
index 000000000000..15966d087ebc
--- /dev/null
+++ b/.trunk/.gitignore
@@ -0,0 +1,9 @@
+*out
+*logs
+*actions
+*notifications
+*tools
+plugins
+user_trunk.yaml
+user.yaml
+tmp
diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml
new file mode 100644
index 000000000000..52c035ab3518
--- /dev/null
+++ b/.trunk/trunk.yaml
@@ -0,0 +1,14 @@
+# Config for the Trunk CLI (https://docs.trunk.io/reference/trunk-yaml).
+# PostHog uses Trunk for the merge queue only (trunk merge / status / cancel),
+# not for linting: repo linters run through their own tooling and CI, so
+# keep this file free of lint, runtimes, and plugin config.
+version: 0.1
+cli:
+ version: 1.25.0
+actions:
+ disabled:
+ - git-lfs
+ - trunk-announce
+ - trunk-check-pre-push
+ - trunk-fmt-pre-commit
+ - trunk-upgrade-available
diff --git a/AGENTS.md b/AGENTS.md
index b6c0c4d4ea01..7ff32502f2c6 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -118,6 +118,13 @@ Draft status doesn't help, since runs are dispatched before draft/skip logic app
- Restack only when you need to, rather than rebasing the whole stack on master repeatedly.
- When a restack must push many branches, stagger them instead of force-pushing all at once.
+#### Pre-push checks — merge queue guard
+
+The pre-push hook refuses to push a branch whose PR is sitting in the Trunk merge queue — a push there would knock the PR out of the queue.
+A PR whose batch failed and is waiting for a retest does not block, so you can push a fix then — Trunk drops the PR from the queue on push, which is what you want after a failure.
+When it blocks you, leave the branch alone and put further changes on a new branch with a new PR; to intentionally update the queued PR instead, run `trunk merge cancel <number>` (or comment `/trunk cancel`), wait for it to leave the queue, then push.
+The check fails open (missing `gh` or `trunk`, not logged in, offline, API errors), and `TRUNK_QUEUE_PUSH_CHECK_DISABLED=1` skips it.
+
#### Pre-push checks — ci:preflight
A pre-push hook runs `hogli ci:preflight --strict`, failing the push on deterministic CI breakage reachable from your diff (lint, lockfiles, migration conflicts). Never bypass it (`--no-verify`).
@@ -130,6 +137,7 @@ All merges into `master` go through the Trunk merge queue.
Never run `gh pr merge` or click the GitHub merge button — both are blocked by branch ruleset.
- Enqueue: `gh pr comment <number> --body "/trunk merge"`. Cancel: `gh pr comment <number> --body "/trunk cancel"`.
+- The Trunk CLI is an alternative to the comments: `trunk merge <number>` enqueues, `trunk merge status <number>` inspects, `trunk merge cancel <number>` dequeues. It ships in the flox environment but needs a one-time interactive `trunk login`, so agents and headless environments should keep using the comments.
- After enqueueing, babysit the PR until it merges or fails — follow [`.agents/skills/merging-prs/SKILL.md`](./.agents/skills/merging-prs/SKILL.md) for the preflight, watch, and failure-handling loop.
- Queue progress is the `Trunk Merge Queue (master)` check run on the PR's head commit. The PR's own checks don't reflect the queue's testing — it runs CI on a `trunk-merge/**` branch.
- On failure the Trunk bot comments with links to the failing workflows; fix, push, and re-enqueue.
@@ -161,6 +169,7 @@ Examples:
## CI / GitHub Actions
- `.nvmrc` controls the Node.js version for all CI workflows (via `actions/setup-node`) — changing it affects every CI job that runs Node
+- CI uploads test results to Trunk Flaky Tests; the `trunk` MCP server in `.mcp.json` queries per-test flakiness on a PR or `master` (authenticate via `/mcp`, or a `TRUNK_API_TOKEN` bearer header when headless) — see `/debugging-ci-failures` and `/fixing-flaky-tests`
- Every job in `.github/workflows/` must declare `timeout-minutes` — prevents stuck runners from burning credits indefinitely
- **CI workflow changes must stay backwards compatible with open PRs that haven't rebased.** A workflow edit hits every in-flight PR immediately (it runs against the PR merged with master), but companion changes — a new dependency, file, or config — only reach a branch once it rebases. If the workflow starts requiring something an unrebased branch lacks, every such PR fails before its tests run. Make the new behavior degrade gracefully when the prerequisite is absent, or gate it so unrebased branches are unaffected. This has broken CI repeatedly.