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): point the startup-time skill at hothog and the facade rule (#105256)

Julian Bez69ec74622e59
diff --git a/.agents/skills/django-startup-time/SKILL.md b/.agents/skills/django-startup-time/SKILL.md
index ed8a0f6a216b..40c3286b70bf 100644
--- a/.agents/skills/django-startup-time/SKILL.md
+++ b/.agents/skills/django-startup-time/SKILL.md
@@ -4,7 +4,7 @@ description: >
Keep heavy imports off the django.setup() path that every process (web, celery, temporal,
migrate, shell, CI) pays for. Use when touching AppConfig.ready(), wiring signal receivers,
editing the lazy API router (posthog/api/rest_router.py or its __init__.py shim), deferring a
- heavy import, when the startup-import-budget guard fails, or when merging master into a
+ heavy import or profiling import time (importtime, hothog), when the startup-import-budget guard fails, or when merging master into a
long-lived branch that made the router lazy.
---
@@ -12,7 +12,7 @@ description: >
Full background — the four mechanisms (lazy router, model registration, receiver wiring, boot GC window), the regression guards, how to add code without regressing them, how to measure, and the detailed trap write-ups: **[docs/internal/django-startup-time.md](../../../docs/internal/django-startup-time.md)**. That doc is the single source of detail; this skill is the trigger and the checklist.
-The guards live in `posthog/test/repo_invariants/test_startup_import_budget.py`. **When one fails, defer the import — don't remove an entry to dodge it.** Conversely, when you deliberately defer a significant heavy lib off setup, **add it to `FORBIDDEN_AT_SETUP`** (after confirming it's absent from a bare `django.setup()`). New imports nobody has named yet are caught by `test_no_new_heavy_imports_at_setup`: any package not in `posthog/test/repo_invariants/setup_import_baseline.txt` costing ≥100ms at setup fails the build — defer it; baseline only what every process genuinely needs at setup.
+The guards live in `posthog/test/repo_invariants/test_startup_import_budget.py`. **When one fails, defer the import — don't remove an entry to dodge it.** Conversely, when you deliberately defer a significant heavy lib off setup, **add it to `FORBIDDEN_AT_SETUP`** (after confirming it's absent from a bare `django.setup()`). Never pin a product facade or its contracts module there: facades must stay importable from anywhere, so pin the heavy module you deferred instead. New imports nobody has named yet are caught by `test_no_new_heavy_imports_at_setup`: any package not in `posthog/test/repo_invariants/setup_import_baseline.txt` costing ≥100ms at setup fails the build — defer it; baseline only what every process genuinely needs at setup.
## Defaults when adding backend code
@@ -21,6 +21,7 @@ The guards live in `posthog/test/repo_invariants/test_startup_import_budget.py`.
- New heavy dependency (vendor SDK, Temporal/AI/ClickHouse, pandas/pyarrow/scipy): import it function-locally on the path that uses it with `# noqa: PLC0415`, never at module scope.
- Schema types on a setup-path module: enums from `posthog.schema_enums` (cheap); pydantic models from `posthog.schema` only inside the method that uses them. No module-level `from posthog.tasks...` on setup paths — `CeleryQueue` lives in `posthog.celery_queues`.
- New viewset/route: it no longer loads at setup — don't rely on import side effects; routes go in `rest_router.py`, not the `__init__.py` shim.
+- Where to cut: at the setup-path entry (the module `ready()` wires, a model file, `apps.py`), never inside a module that consumes a product facade. When a facade reaches setup, the entry defers the implementation module that leads to it; facade imports stay at module scope. If the setup path needs one symbol from a heavy module, move it to a light module and re-export it.
- Any deferral relocates cost — ask which process pays now, on what path, and whether that path is latency-sensitive (background workers paying lazily: fine; web workers paying on first requests: usually not).
## Traps to check before you commit
@@ -37,4 +38,5 @@ One line each — the doc has the full write-up and the fix recipe for every ent
- **Patch targets break on call-time imports** — `@patch("mod.helper")` stops intercepting once `mod` imports `helper` at call time; patch the defining module instead.
- **Snapshot regen on a bad merge** — regenerate `.ambr` against the merged branch, then confirm it isn't masking a regression.
- **Measuring the wrapper, not the work** — time inside the process; `importtime` + `tuna`, not pyinstrument; `grimp` for cycles and door enumeration.
+- **Guessing where to defer** — run [hothog](https://github.com/PostHog/hothog) on the `importtime` log; its `1-cut@` column names the dominator to defer at, and `--compare` gives the before/after. Name this skill and hothog in the PR's agent context, so a reviewer knows how the cuts were chosen.
- **Phantom importtime costs from GC** — re-capture with `gc.disable()`; if the cost vanishes, the finding is GC, not the module. Keep the entrypoints' GC window closing in a `finally`.
diff --git a/docs/internal/django-startup-time.md b/docs/internal/django-startup-time.md
index 963d5cc15629..1fee94146e80 100644
--- a/docs/internal/django-startup-time.md
+++ b/docs/internal/django-startup-time.md
@@ -80,6 +80,11 @@ The list cuts both ways: when you _deliberately_ defer a significant heavy libra
Removing an entry to dodge a failure weakens the guard; adding one to lock in a deferral strengthens it.
Confirm the module is absent from a bare `django.setup()` first, then add it.
+**Never add a product facade or its contracts module to `FORBIDDEN_AT_SETUP`.**
+A facade is the sanctioned door of a product, and code imports it at module scope from anywhere, setup-path modules included.
+Pinning it makes the guard fail the next legitimate consumer.
+Pin the module you actually deferred instead: the heavy module that a receiver or model file used to import.
+
**The forward-looking guard: new heavy imports.**
`FORBIDDEN_AT_SETUP` only catches modules someone already named; `test_no_new_heavy_imports_at_setup` catches the heavy import nobody has named yet.
It captures `python -X importtime` over a bare setup (GC disabled, so a migrating gen2 pause can't masquerade as a module's cost), aggregates self-time by top-level package for third-party (SDKs split across submodules; the package total is the meaningful number) and per-module for first-party, and fails when a name **not** in `posthog/test/repo_invariants/setup_import_baseline.txt` costs ≥100ms.
@@ -104,6 +109,16 @@ The test is simple: importing the module you wire at `ready()` should pull only
Prefer the dedicated light module even when the owning module looks light _today_ — API/viewset modules accumulate module-scope imports, and `ready()` silently inherits whatever they gain.
The batch-exports `ready()` wired its receiver through the API module on a "the module is light" justification; the module later picked up imports reaching every destination's vendor SDK, and `django.setup()` quietly grew ~1.6s.
+**Choosing where to cut.**
+Cut at the setup-path entry: the module that `ready()` wires, a model file, or `apps.py`.
+Do not defer a product facade import inside the modules that consume it.
+That hides the product boundary and treats the facade like an optional SDK.
+When a heavy facade reaches setup, find the receiver or model module on the setup path that leads to it.
+In that module, defer the import of the implementation module that sits between it and the facade.
+Leave every facade import itself at module scope.
+When the setup path needs only one symbol from a heavy module, move that symbol to a light module and re-export it from the old place.
+hothog's `1-cut@` column (see [Measuring](#measuring)) names the dominator: the one module where a deferral removes the whole subtree.
+
**Adding a heavy dependency** (a vendor SDK, a Temporal/AI/ClickHouse path, anything pulling pandas/pyarrow/scipy).
If it is used on one code path, import it function-locally at that path with `# noqa: PLC0415`, not at module scope.
A module-level import is "free" to write but is paid by every process that transitively imports the module, forever.
@@ -135,6 +150,13 @@ When the floor has crept, the lever is the same as it ever was — find the heav
A ~100ms gen2 collection fires wherever the allocation counter crosses its threshold, and `importtime` books it as that module's self-time — a 400-line module of dict literals showed 117ms, and the phantom _migrates between modules when import order changes_ (two runs of the same code attributed it to two different modules).
Before deferring a suspiciously expensive module, sanity-check it: a pure-Python module with no heavy imports should cost microseconds.
The decisive test is re-capturing with `gc.disable()` in front — if the cost vanishes, the module is innocent and the finding is GC, not imports.
+- Deciding what to defer, and where: [hothog](https://github.com/PostHog/hothog).
+ It reads an `importtime` log, re-runs the entry under an import hook, and ranks each heavy import by the cost that would actually come off the path.
+ Each row gets a verdict (`easy`, `many`, `BLOCKED:baseclass`, `BLOCKED:modscope`) and the `1-cut@` dominator to defer at.
+ `--compare` diffs two logs, which gives the before/after for a PR.
+ Install it into the project venv, not as an isolated tool, because it imports the code it analyzes:
+ `uv pip install hothog`, then `hothog <importtime.log> --django-settings posthog.settings --env DEBUG=1 --env TEST=1 --first-party posthog,products,ee,common`.
+ Capture the log with GC disabled, or hothog ranks the GC phantoms described above.
- Finding the _trigger_ of a heavy load: monkeypatch `builtins.__import__` to print the stack the first time the target module is imported.
A profile shows cost but never whether it is _removable_ — confirm with an A/B, because a module is often reachable by more than one path and cutting one changes nothing.
- Import _structure_, when a deferral is blocked: `grimp` builds the module import graph.