: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): cut fixed overhead in backend test runs (#104782)
Raúl Negrón-Otero4b3cc36b2b7a
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 77d322e1d134..ed1f53cbbca3 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -170,6 +170,9 @@ env:CLICKHOUSE_TEST_CLUSTER_SECURE: 'False'CLICKHOUSE_TEST_CLUSTER_VERIFY: 'False'TEST: 1+ # The root conftest ends a green pytest session with os._exit once every report is written.+ # That also hides a crash during interpreter teardown, so the hourly schedule exits normally.+ POSTHOG_PYTEST_HARD_EXIT: ${{ github.event_name == 'schedule' && '0' || '1' }}# Depot CI runners expose OTEL_SERVICE_NAME=ci-worker ambient; GitHub Actions test steps do not.# Left set, it leaks into settings.OTEL_SERVICE_NAME (personhog metric client_name label) and# diverges from test assertions. Blank it to match the GHA environment. Depot also injects@@ -679,10 +682,16 @@ jobs:# The posthog-ci-test-selection event properties, as one JSON object.telemetry: ${{ steps.discover.outputs.telemetry }}steps:+ # A deep checkout is slow with or without blob:none: the blobless one fetches every file of+ # the tree in a second request. Check out at depth 1, then add the history the merge-base+ # steps read, without file contents.- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2- with:- fetch-depth: 1000- filter: blob:none+ - name: Fetch history without file contents+ # --depth, not --deepen: --deepen adds no history once GitHub has replaced the PR's+ # merge ref, because no ref then points at GITHUB_SHA.+ run: |+ git fetch --no-tags --filter=blob:none --depth=1000 origin "$GITHUB_SHA"+ echo "History depth: $(git rev-list --count HEAD)"- name: Verify PR merge for test selectionid: verify-mergeif: github.event_name == 'pull_request'@@ -690,7 +699,7 @@ jobs:PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}run: |set -euo pipefail- trap 'echo "::error::Cannot verify the PR merge checkout. Check the checkout ref and fetch depth before retrying." >&2' ERR+ trap 'echo "::error::Cannot verify the PR merge checkout. Check the checkout ref and the history fetch before retrying." >&2' ERRtest "$(git rev-parse HEAD)" = "$GITHUB_SHA"test "$(git rev-list --parents -n 1 HEAD | wc -w)" -eq 3test "$(git rev-parse HEAD^2)" = "$PR_HEAD_SHA"diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 74b0ad05ee36..71366a313780 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -75,6 +75,9 @@ env:CLICKHOUSE_TEST_CLUSTER_SECURE: 'False'CLICKHOUSE_TEST_CLUSTER_VERIFY: 'False'TEST: 1+ # The root conftest ends a green pytest session with os._exit once every report is written.+ # That also hides a crash during interpreter teardown, so the hourly schedule exits normally.+ POSTHOG_PYTEST_HARD_EXIT: ${{ github.event_name == 'schedule' && '0' || '1' }}CLICKHOUSE_SERVER_IMAGE_VERSION: ${{ github.event.inputs.clickhouseServerVersion || '' }}CLICKHOUSE_COMPAT_PYTEST_TARGETS: 'posthog/clickhouse ee/clickhouse'OBJECT_STORAGE_ENABLED: 'True'@@ -570,10 +573,17 @@ jobs:telemetry: ${{ steps.discover.outputs.telemetry }}steps:+ # A deep checkout is slow with or without blob:none: the blobless one fetches every file of+ # the tree in a second request. Check out at depth 1, then add the history the merge-base+ # steps read, without file contents.- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2- with:- fetch-depth: 1000- filter: blob:none++ - name: Fetch history without file contents+ # --depth, not --deepen: --deepen adds no history once GitHub has replaced the PR's+ # merge ref, because no ref then points at GITHUB_SHA.+ run: |+ git fetch --no-tags --filter=blob:none --depth=1000 origin "$GITHUB_SHA"+ echo "History depth: $(git rev-list --count HEAD)"- name: Verify PR merge for test selectionid: verify-merge@@ -582,7 +592,7 @@ jobs:PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}run: |set -euo pipefail- trap 'echo "::error::Cannot verify the PR merge checkout. Check the checkout ref and fetch depth before retrying." >&2' ERR+ trap 'echo "::error::Cannot verify the PR merge checkout. Check the checkout ref and the history fetch before retrying." >&2' ERRtest "$(git rev-parse HEAD)" = "$GITHUB_SHA"test "$(git rev-list --parents -n 1 HEAD | wc -w)" -eq 3test "$(git rev-parse HEAD^2)" = "$PR_HEAD_SHA"@@ -601,7 +611,7 @@ jobs:BASE_REF: ${{ github.event.pull_request.base.ref }}run: |# HEAD is the synthetic merge commit; HEAD^2 is the PR branch tip.- # The fetch-depth:1000 checkout + base-ref fetch above ensure the+ # The history fetch and the base-ref fetch above ensure the# full ancestry needed to find the divergence point is available.MERGE_BASE=$(git merge-base HEAD^2 "origin/${BASE_REF}" 2>/dev/null || echo "")if [ -z "$MERGE_BASE" ]; thendiff --git a/conftest.py b/conftest.pyindex 33f6971ac4ef..98b0f6020200 100644--- a/conftest.py+++ b/conftest.py@@ -1,5 +1,9 @@import gc+import os+import sys+import atexitimport warnings+import contextlibfrom collections.abc import Generatorimport pytest@@ -244,6 +248,29 @@ def pytest_unconfigure() -> None:gc.unfreeze()[email protected](wrapper=True, tryfirst=True)+def pytest_cmdline_main(config: pytest.Config) -> Generator[None, int | pytest.ExitCode, int | pytest.ExitCode]:+ exit_code = yield+ # pytest's wrap_session has already run pytest_sessionfinish (JUnit XML, split durations) and+ # pytest_unconfigure (including the gc.unfreeze above), and pytest-cov has saved its data.+ # A green session then skips the interpreter teardown, which frees each object of a large+ # collection one by one. A failing session exits normally, so no red shard's reports depend on+ # that ordering. An xdist worker sends its results after this hook, so it exits normally too.+ if (+ os.environ.get("POSTHOG_PYTEST_HARD_EXIT") == "1"+ and exit_code == pytest.ExitCode.OK+ and "PYTEST_XDIST_WORKER" not in os.environ+ ):+ # A private CPython API. It runs the atexit flushes of the analytics client and the report+ # buffer, but not threading's exit callbacks, so thread pools are not joined.+ atexit._run_exitfuncs()+ with contextlib.suppress(BrokenPipeError):+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)+ return exit_code++@pytest.fixture(autouse=True)def _activate_personhog_fake(request):"""Force all person/group reads through the personhog fake for every test.diff --git a/docs/internal/ci-things-already-tried.md b/docs/internal/ci-things-already-tried.mdindex 4d66f64e5138..fac287534b7c 100644--- a/docs/internal/ci-things-already-tried.md+++ b/docs/internal/ci-things-already-tried.md@@ -23,13 +23,14 @@ If the reason is no longer correct, write this in the PR and try the idea again.## Verdicts-| Verdict | Meaning |-| ------------ | --------------------------------------------------------------- |-| `rejected` | Someone built the idea and measured it. The result was too bad. |-| `reverted` | The change went to master. Then someone removed it. |-| `superseded` | The problem was real. A different solution replaced this one. |-| `abandoned` | Someone started the work and stopped. There is no verdict. |-| `open` | The idea is good. The work is incomplete. You can continue it. |+| Verdict | Meaning |+| ------------ | --------------------------------------------------------------------------- |+| `rejected` | Someone built the idea and measured it. The result was too bad. |+| `reverted` | The change went to master. Then someone removed it. |+| `superseded` | The problem was real. A different solution replaced this one. |+| `abandoned` | Someone started the work and stopped. There is no verdict. |+| `open` | The idea is good. The work is incomplete. You can continue it. |+| `landed` | The change is on master. An earlier attempt or alternative is still a trap. |## Add an entry@@ -100,6 +101,27 @@ Measure the setup cost first. Then you know what a scope change can win._Also asked as:_ session-scoped database fixture, build the test database once, why is the first test so slow+### Collapse the warehouse-sources parametrized tests++**Verdict: rejected** · Sep 2026 · measured, not built ([PR run](https://github.com/PostHog/posthog/actions/runs/35767882260), [master run](https://github.com/PostHog/posthog/actions/runs/35768184399))++warehouse-sources collects about 58,000 tests. About 56,000 of them take less than 20 ms, and pytest-split puts almost all of them in one shard.+Their cost was not the count. They took 89 s on master and 202 s on PR runs, because turbo dropped `COVERAGE_CORE` from the product jobs and coverage used its slow tracer.+Four functions that run once per source give 5,392 tests and 15 s. Collapsing them saves little.+The larger fixed cost is collection: each shard of the product collects all 58,000 tests, which takes about 90 s, before pytest-split selects its group.++_Also asked as:_ too many parametrized tests, trim the warehouse-sources suite, delete per-source tests, why is the last warehouse-sources shard slow++### Lower the backend shard wall target from 12 to 10 minutes++**Verdict: rejected** · Sep 2026 · one run each: [12 minutes](https://github.com/PostHog/posthog/actions/runs/35784807053), [10 minutes](https://github.com/PostHog/posthog/actions/runs/35784814651)++`TARGET_WALL_SECONDS` in `turbo-discover.js` sizes every backend test shard.+At 10 minutes a full PR run used 23% more shard minutes, in 85 test jobs instead of 58.+It did not finish sooner (13.4 minutes against 12.9, inside run-to-run noise). Each extra shard pays the full setup and collection cost again.++_Also asked as:_ more shards, smaller shards, lower the shard target, split the slowest shard+### Shard the Playwright E2E suite**Verdict: reverted** · Feb 2026 · [#46774](https://github.com/PostHog/posthog/pull/46774), reverted by [#46853](https://github.com/PostHog/posthog/pull/46853)@@ -217,7 +239,7 @@ _Also asked as:_ skip product tests on a full run, narrow the product matrix, wh### Disable the pytest `unraisableexception` and `threadexception` plugins-**Verdict: open, and approved** · Jul 2026 · [#70886](https://github.com/PostHog/posthog/pull/70886)+**Verdict: landed** · Jul 2026 to Sep 2026 · [#70886](https://github.com/PostHog/posthog/pull/70886), landed by [#89057](https://github.com/PostHog/posthog/pull/89057); the hard exit below landed by [#104782](https://github.com/PostHog/posthog/pull/104782)Each pytest session runs several full-heap `gc.collect()` passes at cleanup.These plugins run the passes only to report `__del__` exceptions and thread exceptions as warnings.@@ -226,14 +248,18 @@ These plugins run the passes only to report `__del__` exceptions and thread exceA fixed benchmark of 320 tests decreased from 24.7 seconds to 21.8 seconds.A reviewer approved the PR. The branch then became inactive, and the stale bot closed it.-You can open this PR again without changes.+[#89057](https://github.com/PostHog/posthog/pull/89057) landed the same change, and `pytest.ini` now disables both plugins.Read this entry before you try a different solution for the pytest cleanup cost.[#88759](https://github.com/PostHog/posthog/pull/88759) tried a different solution. It deleted the `gc.unfreeze()` in `pytest_unconfigure`.That call is necessary. [#62707](https://github.com/PostHog/posthog/pull/62707) added it after the Temporal shards stopped with a segmentation fault and exit code 139. CI made the same crash again on #88759.Frozen objects do not get the final cyclic collections of `Py_FinalizeEx`. Thus their finalizers run late in the teardown, after Python removes the extension modules.-_Also asked as:_ pytest teardown is slow, reduce gc.collect at session end, speed up pytest cleanup, why does the shard hang after the tests pass+Backend CI skips `Py_FinalizeEx` on green shards. With `POSTHOG_PYTEST_HARD_EXIT=1`, the root conftest runs the `atexit` handlers and calls `os._exit` after `pytest_unconfigure`, so the `gc.unfreeze()` still runs first.+One run each: each shard saved 8 to 29 seconds ([before](https://github.com/PostHog/posthog/actions/runs/35777473197), [after](https://github.com/PostHog/posthog/actions/runs/35777464934)).+A failing shard, the hourly scheduled run and local runs keep the normal exit, so a teardown crash still shows there. Do not delete the `gc.unfreeze()`.++_Also asked as:_ pytest teardown is slow, reduce gc.collect at session end, speed up pytest cleanup, why does the shard hang after the tests pass, os.\_exit after pytest## Python and pytest runtime@@ -430,6 +456,29 @@ If you propose this again, name the jobs and prove that each one reads only the_Also asked as:_ sparse-checkout, partial clone, do not check out the whole repo, speed up the checkout step+### Drop `filter: blob:none` from a deep checkout++**Verdict: rejected** · Sep 2026 · [run](https://github.com/PostHog/posthog/actions/runs/35789980165)++Backend test discovery needs 1000 commits of history.+With `fetch-depth: 1000` and `filter: blob:none`, the checkout took 42 to 46 s, because it fetches every file of the tree in a second request.+Without the filter it took 39 s, because the server then packs the file contents of all 1000 commits.+A depth-1 checkout followed by `git fetch --filter=blob:none --depth=1000` takes about 7 s, and the job uses that now.+`--deepen=999` in its place fetched nothing when GitHub had already replaced the PR's merge ref, which failed the run.+The `test-selection-verdict` and `backend-coverage-report` jobs still use deep blobless checkouts. They run after the required gate, so no PR waits on them.++_Also asked as:_ blobless clone is slow, partial clone checkout, speed up the discovery checkout, fetch-depth 1000++### Check out the PR head by SHA in the Django test shards++**Verdict: rejected** · Sep 2026 · [before](https://github.com/PostHog/posthog/actions/runs/35777473197), [after](https://github.com/PostHog/posthog/actions/runs/35781233592)++The Django test shards check out `pull_request.head.ref` and spend about 22 s. The product shards check out the merge commit and spend about 6 s.+The difference is in the `git fetch --depth=1`, and on master pushes the same Django checkout takes about 7 s.+A checkout of `pull_request.head.sha` also took 21 to 22 s, so the refspec is not the cause. The cause is not known.++_Also asked as:_ slow checkout in the Django shards, head.ref or head.sha, why is the Django checkout slower than the product checkout+### Jest reports the Rust snapshots as obsolete**Verdict: superseded** · Jan 2026 · [#46008](https://github.com/PostHog/posthog/pull/46008)diff --git a/docs/internal/django-startup-time.md b/docs/internal/django-startup-time.mdindex fb9c6700780c..963d5cc15629 100644--- a/docs/internal/django-startup-time.md+++ b/docs/internal/django-startup-time.md@@ -176,7 +176,8 @@ The eager router imported a large chain when `posthog/urls.py` loaded, _before_That chain often imported some module fully and early, accidentally papering over a circular import elsewhere that only ever worked because of that import order.Make the router lazy and the accidental pre-import disappears, so the next process to import the URLconf hits the cycle head-on.The real example: `slack_app.backend.api` imports workflow classes from `posthog_code_slack_mention`, which imported a helper straight back from `slack_app.backend.api` at module scope (placed late with `# noqa: E402` — a tell that someone already fought the ordering).-With the pre-import gone, Django's system checks (`check_custom_error_handlers` imports the URLconf, e.g. during `ensure_migration_defaults`) raised `cannot import name ... from partially initialized module`.+With the pre-import gone, Django's system checks (`check_custom_error_handlers` imports the URLconf) raised `cannot import name ... from partially initialized module`.+They raised it during `ensure_migration_defaults`, which skips the system checks now, so the same cycle would surface first in a test that loads the URLconf.Two things make this nasty: it surfaces far from the change (a migration-defaults step in one CI job, not the lazy-router files), and the buggy code is not yours — so it is tempting to blame master.Do not assume: the decisive test is `django.setup()` then `import_module("posthog.urls")` in a clean subprocess, run on a detached `origin/master` worktree _and_ the branch.If only the branch fails, you unmasked it and you own the fix — break the cycle by deferring the back-reference to its call sites.diff --git a/posthog/management/commands/ensure_migration_defaults.py b/posthog/management/commands/ensure_migration_defaults.pyindex 6f170e714bf7..0e2c9055ff91 100644--- a/posthog/management/commands/ensure_migration_defaults.py+++ b/posthog/management/commands/ensure_migration_defaults.py@@ -317,6 +317,10 @@ _FEATURE_FLAG_TEMPLATE: dict[str, Any] = {class Command(BaseCommand):help = "Ensure default data from migrations exists for schema-only restores."+ # A setup step of every schema restore. The system checks import the URLconf, which costs more than+ # the seeding (docs/internal/django-startup-time.md). Tests that load the URLconf still catch its+ # import errors.+ requires_system_checks: list[str] = []def _seed_streamlit_oauth_app(self, created_items: list[str], skipped_items: list[str]) -> None:# OAuthApplication.clean() rejects RS256 where no OIDC RSA private key isdiff --git a/posthog/management/commands/register_temporal_search_attributes.py b/posthog/management/commands/register_temporal_search_attributes.pyindex d7043c62a0f5..370d277c529f 100644--- a/posthog/management/commands/register_temporal_search_attributes.py+++ b/posthog/management/commands/register_temporal_search_attributes.py@@ -32,6 +32,9 @@ def _resolve_type(key: SearchAttributeKey) -> enums.IndexedValueType.ValueType:class Command(BaseCommand):help = "Register PostHog custom search attributes in Temporal"+ # A setup step in CI, dev runs and preview environments. The command never touches the ORM or the+ # URLconf, so the system checks only add startup time.+ requires_system_checks: list[str] = []def add_arguments(self, parser):parser.add_argument(diff --git a/turbo.json b/turbo.jsonindex 38c352fc6b31..d727070c1703 100644--- a/turbo.json+++ b/turbo.json@@ -27,11 +27,14 @@// changes the SQL a query runner builds, so a result cached under one mode// must not satisfy a run in the other."env": ["DATABASE_URL", "REDIS_URL", "CLICKHOUSE_HOST", "TEST", "PERSON_ON_EVENTS_V2_ENABLED"],- // Credentials and the fork-PR flag the product-run temporal suites need- // (tasks sandbox JWT, batch-exports Modal/S3, RUNS_ON_INTERNAL_PR that- // skips internal-only tests for external contributors). Turbo strips- // undeclared env vars, so a var set on the CI job never reaches pytest- // unless listed here. Pass-through, not env: they must not become cache keys.+ // Job env that pytest reads. Turbo strips undeclared env vars, so a var set on+ // the CI job never reaches pytest unless listed here, and nothing fails when one+ // is missing. Pass-through, not env: they must not become cache keys.+ // - Credentials and the fork-PR flag the product-run temporal suites need (tasks+ // sandbox JWT, batch-exports Modal/S3, RUNS_ON_INTERNAL_PR that skips+ // internal-only tests for external contributors).+ // - COVERAGE_CORE: without it, coverage uses its slower C tracer.+ // - POSTHOG_PYTEST_HARD_EXIT: without it, green shards pay the interpreter teardown."passThroughEnv": ["PYTEST_ADDOPTS","RUNNER_NAME",@@ -39,7 +42,9 @@"SANDBOX_JWT_PRIVATE_KEY","MODAL_TOKEN_ID","MODAL_TOKEN_SECRET",- "AWS_S3_ALLOW_UNSAFE_RENAME"+ "AWS_S3_ALLOW_UNSAFE_RENAME",+ "COVERAGE_CORE",+ "POSTHOG_PYTEST_HARD_EXIT"]},"backend:lint": {