: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
perf(api): lazy DRF router, defer heavy imports off django.setup() (#60849)
Julian Bez4bfbfa70dd90
diff --git a/.agents/skills/django-startup-time/SKILL.md b/.agents/skills/django-startup-time/SKILL.mdnew file mode 100644index 000000000000..6b8d14e0b269--- /dev/null+++ b/.agents/skills/django-startup-time/SKILL.md@@ -0,0 +1,38 @@+---+name: django-startup-time+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+ long-lived branch that made the router lazy.+---++# Django startup time++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/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/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++- New app/product: register models from `models/__init__.py`, wire receivers from `AppConfig.ready()`, keep `ready()` light.+- New receiver: wire it at the owning `AppConfig.ready()`, from a dedicated light module (`activity_logging.py`, `signals.py`) — never via the API/viewset module, even if it looks light today; those accumulate heavy imports and `ready()` silently inherits them.+- 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.+- 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.+- 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++One line each — the doc has the full write-up and the fix recipe for every entry.++- **`ready()` re-drags a heavy dep onto startup** — importing a receiver's module runs its module-level imports too; re-measure after wiring.+- **Silent receiver loss** — lost receivers don't error; reproduce in a process that does NOT build the router (`manage.py shell`, celery, `migrate`).+- **Models vanishing from the registry** — a model reachable only via a viewset import breaks `makemigrations`/admin/mypy; import it from `models/__init__.py`, then `dmypy stop`.+- **Lazy-router merge conflicts** — keep the `__init__.py` shim, port master's aggregator deltas into `rest_router.py`.+- **Aggregator package `__init__`s** — shim with PEP 562 `__getattr__`, via `importlib.import_module` and an `__all__` whitelist (catch-alls recurse or deadlock on sibling imports).+- **Serializer field kwargs run at import** — `choices=...` inputs can't be function-locally deferred; move the constant to an import-light module.+- **Vanished re-exports** — regenerating/shimming a module drops names other code imported from it incidentally (e.g. `schema.BaseModel`); grep for consumers of the old namespace.+- **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.+- **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.mdnew file mode 100644index 000000000000..11777a1392fa--- /dev/null+++ b/docs/internal/django-startup-time.md@@ -0,0 +1,202 @@+# Django startup time++`django.setup()` runs on every process: web, but also celery, temporal, `migrate`, `manage.py shell`, and every CI job.+Heavy imports dragged onto that path are paid by all of them.+This doc explains how we keep heavy subsystems off the startup path, the guard that enforces it, how to add code without regressing it, and the traps that have repeatedly caused follow-up fixes.++## The shape of the problem++The cost is almost entirely _module imports_, not runtime work.+A single eager `import` chain reaching the AI core, the batch-export Temporal framework, embedded ClickHouse (`chdb`), `scipy`, or the Stripe SDK adds hundreds of ms each.+The fix is always the same: make the import lazy so it loads only when its code actually runs.++The biggest single lever was the **lazy API router** (below).+Everything else is deferring individual heavy imports off the startup path.++## The four mechanisms++### 1. Lazy API router++The DRF route aggregator (the router build plus ~200 viewset imports) used to run at _package import_ of `posthog.api`.+It now lives in `posthog/api/rest_router.py`, and `posthog/api/__init__.py` is a thin PEP 562 `__getattr__` shim that imports the aggregator only when a router object (`router`, `projects_router`, …) is first accessed — i.e. when the URLconf resolves, on the first web request.+Real submodules (`posthog.api.monitoring`, `.file_system`, …) resolve directly without building the aggregator, so a plain `django.setup()` stays cheap.++This is the laziness Django already intends: the URLconf is the entry point, and non-web processes never resolve it.++Web is the exception and resolves it eagerly: `wsgi.py`/`asgi.py` build the URLconf at import, pre-fork, inside the GC window — because the k8s probes (`/_livez`, `/_readyz`) are served by short-circuiting middleware and never resolve URLs, each worker would otherwise build the router on its **first live request** (measured at multiple seconds per worker, after every deploy).+Pre-building lands the router in the frozen heap, copy-on-write-shared across workers — exactly the pre-lazy-router behavior for web, while every other process keeps the win.+`test_web_entrypoint_prebuilds_the_router` pins this; a prefork smoke (gunicorn `--preload`, 4 workers) verified workers inherit the built router and serve cold requests without it.++### 2. Model registration++Importing a viewset module used to be what registered some models (importing a model class runs `ModelBase.__new__` → `apps.register_model`).+With the router lazy, a model reachable _only_ through a viewset import silently disappears from `apps.get_models()` at setup time.+Every model must be imported from its app's `models/__init__.py` (or `models.py`) so it registers at app-population — independent of the router.++### 3. Signal receivers++Importing a viewset module also runs its `@receiver` decorators, so the eager router connected a pile of receivers as a side effect of `django.setup()`.+With the lazy router, those connect only when the router is first built — so any process that never builds it (celery, temporal, `migrate`, shell) silently loses them.+Wire receivers from the owning app's `AppConfig.ready()` instead, so they connect at setup.++### 4. Garbage collection deferred during boot++Boot allocations are almost all permanent — modules, classes, registries, the generated pydantic schema — so the cyclic GC has nothing useful to reclaim while `django.setup()` runs, yet allocation thresholds trigger ~470 collections during it (~300ms of pauses, single gen2 passes up to ~100ms).+The entrypoints that own a setup (`manage.py`, `posthog/wsgi.py`, `posthog/asgi.py`) wrap it in `gc.disable()` → boot → `gc.freeze()` → `gc.enable()`.+The freeze moves the ~600k surviving boot objects to the permanent generation, so they are excluded from every future full collection — which also makes post-boot work (management-command discovery, the first router build) collect almost for free, and maximizes copy-on-write page sharing when a prototype process forks workers.+There is deliberately no `gc.collect()` before the freeze: a full pass over the boot heap costs ~210ms and reclaims only ~4% of objects (a few MB), so the garbage is frozen along with everything else.+The window must always close — GC left disabled in a long-lived process means unbounded cycle growth — hence the `try`/`finally` and the guard test asserting `gc.isenabled()` and a nonzero freeze count after a `manage.py` boot.+Celery's `django.setup()` happens inside its Django fixup, not in an entrypoint we own, so celery workers do not get the window yet.++## The regression guard++`posthog/test/test_startup_import_budget.py` boots a bare `django.setup()` in a clean subprocess and asserts three things, one per mechanism:++1. No `FORBIDDEN_AT_SETUP` heavy module (the lazy router aggregator, the AI core, `chdb`, `scipy`, …) is in `sys.modules`.+2. Every model registers at app-population — importing the router adds none.+3. No signal receiver connects _only_ when the router is built.++**When a guard fails, fix the import — do not widen the list.**+Defer the offending import, add the missing `models/__init__` import, or wire the receiver at `ready()`.+Removing an entry to make the test pass re-opens the door the guard exists to keep shut.++The list cuts both ways: when you _deliberately_ defer a significant heavy library off the startup path, **add it to `FORBIDDEN_AT_SETUP`** so the win can't silently regress.+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.++**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/setup_import_baseline.txt` costs ≥100ms.+There are deliberately no per-entry time budgets — absolute timings flake in CI — time is only the materiality gate for _new arrivals_: known names are never timed, and a new arrival is deterministic (the PR that adds the import, adds it).+Two captures are taken and the per-name minimum used, because a cold first boot pays page-cache misses that can double a package's apparent cost.+When it fires: defer the import (the failure message carries the playbook); baseline a package only when every process genuinely needs it during setup, with a justifying comment.++## Doing it right, and keeping it right++The startup path is a shared resource with no natural backpressure: nothing about adding a normal import _looks_ expensive, and the cost lands on processes you are not running locally.+Treat these as the defaults whenever you add backend code.++**Adding a new product or app.**+Register every model from `models/__init__.py`.+Wire signal receivers from `AppConfig.ready()`, not as a side effect of importing a viewset.+Keep `ready()` light — it runs in every process, so it must not import a heavy subsystem (see the next rule).++**Adding a signal receiver.**+Put it where it connects at setup: the owning `AppConfig.ready()`.+If the module holding the receiver also imports something heavy at module scope, do not import that module from `ready()` directly — either defer the heavy import inside the function that uses it, or move the receiver into a light module (`signals.py`, `activity_logging.py`) and import _that_ from `ready()`.+The test is simple: importing the module you wire at `ready()` should pull only light dependencies.+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.++**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.++**Adding a viewset or route.**+It will not load at `django.setup()` anymore.+Do not rely on importing it for any side effect (model registration, receiver wiring, monkeypatching) — those must live somewhere that loads at setup.+New routes go in `posthog/api/rest_router.py` (or a product's `register_routes`), never back in the `__init__.py` shim.++**When you are unsure whether something is heavy.**+Measure (next section).+A 30-second `importtime` run settles it; guessing does not.++**How it stays right over time.**+The guard runs in CI on every PR, so a regression is caught at review, not in production.+The standing rule when it goes red is always _defer, don't widen_ — the list is a ratchet, and every entry that moves the wrong way gives back a permanent slice of the win.+Re-profile occasionally even when the guard is green: the guard only catches the specific heavy modules it names, and the floor drifts up as the codebase grows.+When the floor has crept, the lever is the same as it ever was — find the heaviest cumulative import that is not actually needed at setup, and defer it.++## Measuring++- Wall-clock: `time.perf_counter()` around `django.setup()` _inside_ the process.+ Do not time the shell wrapper — env activation is not part of the number.+- Set `TEST=1 DEBUG=1` so `ready()` skips redis/runtime I/O; you want import cost, which is identical in test mode, not environment-dependent network round-trips.+- Import cost breakdown: `python -X importtime` + `tuna` for the tree.+ Rank modules by _self_ time for leaf cost, _cumulative_ for subtree cost.+ **Not** pyinstrument — it smears import cost across `importlib._bootstrap` frames.+- **Importtime self-times can lie: a GC pause lands on whatever module happens to be executing.**+ 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.+- 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.+ Sometimes you cannot just defer a heavy import because it is load-bearing in a circular import — deferring one edge only relocates the cycle.+ `grimp`'s `nominate_cycle_breakers` ranks which edge to cut, so the real work becomes untangling the owning package's cycle before the heavy import can come off the startup path.++## Traps (these have all caused follow-up fixes)++**`ready()` that re-drags a heavy subsystem onto startup.**+The most common regression.+You wire a receiver by importing its owning module in `AppConfig.ready()`, but that module imports a heavy dependency at module scope (a billing/Stripe client, the Temporal framework, the AI core).+The receiver connects — and so does the heavy import, defeating the whole point.+Fix: defer the heavy import _inside_ the method that uses it (`# noqa: PLC0415`), or extract the receiver into a light module that the `ready()` imports instead.+Always re-measure: wiring a receiver and cutting startup time are easy to get backwards.++**Silent receiver loss.**+When receivers stop connecting, nothing errors — the symptom is downstream and quiet (a cache that stops invalidating, cleanup that stops running on background writes).+It will not show up in a smoke test of the web server, because the web server builds the router.+Reproduce in a process that does _not_: `manage.py shell`, a celery worker, `migrate`.++**Models that vanish from the registry.**+A model only reachable via a viewset import disappears at setup.+The failure is indirect: `makemigrations` stops seeing it, admin drops it, and the django-stubs mypy plugin (which builds its model registry via `django.setup()`) reports `"type[X]" has no attribute "objects"`.+Add the model to its app's `models/__init__.py`.++**Stale `dmypy` after a registration change.**+The django-stubs mypy plugin caches its `django.setup()` snapshot in the daemon.+After changing what registers at setup, `dmypy stop` before re-running, or you will chase phantom errors against the old model registry.++**Semantic merge conflicts against the lazy router.**+Long-lived branches that move the aggregator into `rest_router.py` keep colliding with master, which still edits the old eager `posthog/api/__init__.py` (product migrations move viewset modules out of `posthog/api` into `products/`).+Git puts master's aggregator deltas in the `__init__.py` conflict, but on the branch that file is the shim.+Recipe: keep the shim (`--ours` on `__init__.py`), diff the merge base against the incoming version of the old aggregator to get the exact import + route-registration deltas, and port them into `rest_router.py`.+When a module carrying a `ready()`-wired receiver moves, re-point the wiring to its new product's `AppConfig.ready()` and keep any heavy import deferred.+The same shape bites whenever one side moves or renames a module the other side references at module scope — a text-clean merge that breaks on import.++**Removing an eager import chain unmasks latent circular imports.**+The eager router imported a large chain when `posthog/urls.py` loaded, _before_ urls.py reached its own product imports.+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`.+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.++**A package `__init__` that aggregates its submodules taxes every submodule import.**+A worker-facing aggregator (`temporal/__init__.py` importing all destinations to build `WORKFLOWS` / `ACTIVITIES`) makes _any_ `import <pkg>.<submodule>` execute the whole aggregation — Python runs parent package `__init__`s first.+Importing one constants table from one destination loaded thirteen vendor SDKs.+Fix: move the aggregator to a submodule (`workflows.py`) and make the `__init__` a PEP 562 `__getattr__` shim.+Two gotchas in that shim, both found the hard way:+`from <pkg> import workflows` _inside_ the package's own `__getattr__` recurses forever (`_handle_fromlist` re-enters `__getattr__`) — use `importlib.import_module`.+And a catch-all `__getattr__` is wrong: `from <pkg> import <anything>` probes the package attribute first, so a catch-all eagerly loads the aggregator on every such probe — including for submodule names, which deadlocks if any aggregated module imports a sibling through the package root (`record_batch_model` importing `sql` did exactly this, masked for years by the eager init's import order).+Whitelist the public names (`if name in __all__`) and raise `AttributeError` otherwise, so submodule imports fall back to normal resolution.++**DRF serializer field kwargs are evaluated at import.**+`choices=sorted(SUPPORTED_THINGS)` in a serializer field runs at class definition, i.e. when the module imports — you cannot function-locally defer the import it depends on.+If the constant lives in a heavy module (a Temporal destination, an SDK wrapper), move the constant to an import-light module and have both sides import it from there; re-export under the old name to keep existing importers working.++**A deferral relocates cost — check where it lands before calling it a win.**+Deferring an import does not delete the work; it moves it to first use, and first use may be a live request.+The general question to ask of any deferral: _which process pays now, on what path, and is that path latency-sensitive?_+Background workers paying lazily is almost always fine; web workers paying on first requests usually is not.++**Pydantic `defer_build` on the generated schema: attempted and reverted.**+Generating `posthog.schema` against a `defer_build` base took ~400ms of core-schema construction off every setup, and looked safe — validation, `model_dump`, `model_json_schema`, and `TypeAdapter` all build on demand in round-trip tests.+Two failures killed it.+First, cost relocation (above): in a web pod the deferred builds land on each worker's first `/query` after every deploy — previously paid at boot, behind the readiness probe, pre-fork and COW-shared — and the obvious warm-up loop measured ~2.5x more expensive than eager class creation (`model_rebuild()` re-resolves namespaces per model).+Second, and fatal: query runners _construct_ response models directly (no validation, so nothing triggers the lazy build), and `model_dump()` then feeds a deferred child model's mock serializer into pydantic-core through a polymorphic field — `TypeError: 'MockValSer' object cannot be converted to 'SchemaSerializer'`, a hard 500 in any process.+Round-trip tests on a single model cannot catch this: for `defer_build`, the serialization _matrix_ (construct-then-dump, subclass-through-parent, `Any`-typed fields) is the test surface.+The ~1.8s the schema costs at import is real but structural — the tracked path is splitting the generated module, not deferring builds.++**Regenerating a shared snapshot on top of a bad merge.**+Query-count snapshot files (`.ambr`) are generated.+When both branches change one, neither side's version is correct for the merged code — regenerate against the merged branch rather than picking a side.+After regenerating, confirm it is not masking a regression: `makemigrations --check` clean, expected columns still present, and the query _set_ unchanged (a large "updated" count is usually benign renumbering when one query shifts position).++**Measuring the wrapper instead of the work.**+Timing a command that activates an env first folds activation cost into the number.+Measure inside the process.+And when a bare `python /tmp/script.py` cannot find the package, it is `sys.path` (the script's dir, not the repo) — set `PYTHONPATH`, do not conclude the env is broken.diff --git a/ee/api/agentic_provisioning/signature.py b/ee/api/agentic_provisioning/signature.pyindex ac058cb8c04e..42dca455391e 100644--- a/ee/api/agentic_provisioning/signature.py+++ b/ee/api/agentic_provisioning/signature.py@@ -6,7 +6,6 @@ import hashlibfrom django.conf import settingsfrom django.http.request import RawPostDataException-import stripeimport structlogimport posthoganalyticsfrom rest_framework.request import Request@@ -85,6 +84,10 @@ def verify_provisioning_signature(request: Request) -> Response | None:status=400,)+ # Deferred: the stripe SDK is ~0.45s to import and is only needed on this verify path. Keeping it+ # out of module scope keeps it off django.setup() (signature.py is reachable from ready() via billing).+ import stripe # noqa: PLC0415+sig_header = request.headers.get("stripe-signature", "")try:stripe.WebhookSignature.verify_header(decoded_body, sig_header, secret, tolerance=MAX_TIMESTAMP_DRIFT_SECONDS)diff --git a/ee/api/vercel/test/test_vercel_permission.py b/ee/api/vercel/test/test_vercel_permission.pyindex a25af95b2063..65e2ec801cc3 100644--- a/ee/api/vercel/test/test_vercel_permission.py+++ b/ee/api/vercel/test/test_vercel_permission.py@@ -218,7 +218,7 @@ class TestVercelPermissionIntegration(VercelTestBase):cls.client_id_patcher = patch("ee.settings.VERCEL_CLIENT_INTEGRATION_ID", "test_audience")cls.jwks_patcher = patch("ee.api.authentication.get_vercel_jwks")cls.license_patcher = patch("ee.vercel.integration.get_cached_instance_license", return_value=Mock())- cls.billing_patcher = patch("ee.vercel.integration.BillingManager")+ cls.billing_patcher = patch("ee.billing.billing_manager.BillingManager")cls.client_id_patcher.start()cls.mock_get_jwks = cls.jwks_patcher.start()cls.license_patcher.start()diff --git a/ee/apps.py b/ee/apps.pyindex 0cbc6f5104fc..75e278ab7f14 100644--- a/ee/apps.py+++ b/ee/apps.py@@ -4,3 +4,8 @@ from django.apps import AppConfigclass EnterpriseConfig(AppConfig):name = "ee"verbose_name = "Enterprise"++ def ready(self) -> None:+ # Connect the Vercel experimentation-item sync receivers at app-population. They used to+ # wire in via a viewset import; the lazy API router no longer pulls that, so connect here.+ from ee.vercel import integration # noqa: F401, PLC0415diff --git a/ee/hogai/chat_agent/__init__.py b/ee/hogai/chat_agent/__init__.pyindex ab224d365627..ff5627929eb3 100644--- a/ee/hogai/chat_agent/__init__.py+++ b/ee/hogai/chat_agent/__init__.py@@ -1,3 +1,18 @@-from .graph import AssistantGraph+from typing import TYPE_CHECKING, Any__all__ = ["AssistantGraph"]+++def __getattr__(name: str) -> Any:+ # Lazy (PEP 562): importing any chat_agent submodule used to eagerly pull `.graph` and its+ # whole mode_manager -> toolkit -> tools -> runner chain, which imports back here for+ # AssistantGraph — a cycle that only held together via the temporal.ai startup preload.+ if name == "AssistantGraph":+ from .graph import AssistantGraph++ return AssistantGraph+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+++if TYPE_CHECKING:+ from .graph import AssistantGraph as AssistantGraphdiff --git a/ee/hogai/chat_agent/memory/nodes.py b/ee/hogai/chat_agent/memory/nodes.pyindex 161c2fe01984..242771fda332 100644--- a/ee/hogai/chat_agent/memory/nodes.py+++ b/ee/hogai/chat_agent/memory/nodes.py@@ -39,7 +39,7 @@ from posthog.utils import human_listfrom products.posthog_ai.backend.models.assistant import CoreMemoryfrom ee.hogai.artifacts.utils import unwrap_visualization_artifact_content-from ee.hogai.core.agent_modes import SlashCommandName+from ee.hogai.core.agent_modes.const import SlashCommandNamefrom ee.hogai.core.mixins import AssistantContextMixinfrom ee.hogai.core.node import AssistantNodefrom ee.hogai.llm import MaxChatOpenAIdiff --git a/ee/hogai/chat_agent/slash_commands/commands/feedback/command.py b/ee/hogai/chat_agent/slash_commands/commands/feedback/command.pyindex 47eec0315553..97b0faf32ceb 100644--- a/ee/hogai/chat_agent/slash_commands/commands/feedback/command.py+++ b/ee/hogai/chat_agent/slash_commands/commands/feedback/command.py@@ -6,7 +6,7 @@ from langchain_core.runnables import RunnableConfigfrom posthog.schema import AssistantMessage, HumanMessagefrom ee.hogai.chat_agent.slash_commands.commands import SlashCommand-from ee.hogai.core.agent_modes import SlashCommandName+from ee.hogai.core.agent_modes.const import SlashCommandNamefrom ee.hogai.utils.types import AssistantState, PartialAssistantStatediff --git a/ee/hogai/chat_agent/slash_commands/commands/remember/command.py b/ee/hogai/chat_agent/slash_commands/commands/remember/command.pyindex 71a4979323a7..3b1cd807ce8e 100644--- a/ee/hogai/chat_agent/slash_commands/commands/remember/command.py+++ b/ee/hogai/chat_agent/slash_commands/commands/remember/command.py@@ -7,7 +7,7 @@ from posthog.schema import AssistantMessage, HumanMessagefrom products.posthog_ai.backend.models.assistant import CoreMemoryfrom ee.hogai.chat_agent.slash_commands.commands import SlashCommand-from ee.hogai.core.agent_modes import SlashCommandName+from ee.hogai.core.agent_modes.const import SlashCommandNamefrom ee.hogai.utils.types import AssistantState, PartialAssistantStatediff --git a/ee/hogai/eval/data_setup.py b/ee/hogai/eval/data_setup.pyindex 95e992ec988b..64c0f5131d79 100644--- a/ee/hogai/eval/data_setup.py+++ b/ee/hogai/eval/data_setup.py@@ -16,11 +16,11 @@ from django.test import override_settingsfrom posthog.clickhouse.client import sync_executefrom posthog.demo.matrix.manager import MatrixManagerfrom posthog.demo.matrix.taxonomy_inference import infer_taxonomy_for_team+from posthog.demo.products.hedgebox.matrix import HedgeboxMatrixfrom posthog.models import GroupTypeMapping, Organization, OrganizationMembership, Team, Userfrom posthog.models.event.sql import COPY_EVENTS_BETWEEN_TEAMSfrom posthog.models.group.sql import COPY_GROUPS_BETWEEN_TEAMSfrom posthog.models.person.sql import COPY_PERSON_DISTINCT_ID2S_BETWEEN_TEAMS, COPY_PERSONS_BETWEEN_TEAMS-from posthog.tasks.demo_create_data import HedgeboxMatrixfrom products.dashboards.backend.models import Dashboard, DashboardTilefrom products.posthog_ai.backend.models.assistant import CoreMemorydiff --git a/ee/hogai/mcp_tool.py b/ee/hogai/mcp_tool.pyindex c65ccd4bc536..56dc6744b3b3 100644--- a/ee/hogai/mcp_tool.py+++ b/ee/hogai/mcp_tool.py@@ -72,27 +72,31 @@ class MCPToolRegistry:return decorator+ def _ensure_loaded(self) -> dict[str, MCPToolRegistration]:+ # Tools self-register on import, so every read must trigger the import first. Keep the+ # load-then-read invariant in one place — function-local import to avoid the tools <-> mcp_tool cycle.+ from ee.hogai.tools import load_all_tools # noqa: PLC0415 - ensure tools are registered++ load_all_tools()+ return self._tools+def get(self, name: str, team: Team, user: User) -> MCPTool[Any] | None:"""Get an MCP tool instance by name, constructed with team/user."""- import ee.hogai.tools # noqa: F401 - ensure tools are registered-- registration = self._tools.get(name)+ registration = self._ensure_loaded().get(name)if registration:return registration.tool_cls(team=team, user=user)return Nonedef get_scopes(self, name: str) -> list[str]:"""Get the required scopes for a registered MCP tool."""- import ee.hogai.tools # noqa: F401 - ensure tools are registered-- registration = self._tools.get(name)+ registration = self._ensure_loaded().get(name)if registration:return registration.scopesreturn []def get_names(self) -> list[str]:"""Get list of registered MCP tool names."""- return list(self._tools.keys())+ return list(self._ensure_loaded().keys())mcp_tool_registry = MCPToolRegistry()diff --git a/ee/hogai/tools/__init__.py b/ee/hogai/tools/__init__.pyindex d41795286eca..2c6100410004 100644--- a/ee/hogai/tools/__init__.py+++ b/ee/hogai/tools/__init__.py@@ -1,22 +1,30 @@-from .call_mcp_server.tool import CallMCPServerTool-from .create_form import CreateFormTool-from .create_insight import CreateInsightTool-from .create_notebook import CreateNotebookTool--# MCP tool imports trigger @mcp_tool_registry.register decorators-from .execute_sql.mcp_tool import ExecuteSQLMCPTool # noqa: F401-from .execute_sql.tool import ExecuteSQLTool-from .list_data import ListDataTool-from .manage_memories import ManageMemoriesTool-from .read_data import ReadDataTool-from .read_data_warehouse_schema.mcp_tool import ReadDataWarehouseSchemaMCPTool # noqa: F401-from .read_taxonomy.mcp_tool import ReadTaxonomyMCPTool # noqa: F401-from .read_taxonomy.tool import ReadTaxonomyTool-from .search import SearchTool-from .switch_mode import SwitchModeTool-from .task import TaskTool-from .todo_write import TodoWriteTool-from .upsert_dashboard import UpsertDashboardTool+import importlib+from typing import TYPE_CHECKING, Any++# Each tool maps to the submodule that defines it. Resolved lazily via PEP 562 __getattr__+# below, so importing one tool — or this package — does not eagerly pull every tool's+# transitive deps. Notably `create_insight` imports the chat agent, which imports back into+# `ee.hogai.tools`; eager re-exports here formed an import cycle that only survived by+# import-order luck and dragged the whole AI agent core onto the Django startup path.+_TOOL_MODULES: dict[str, str] = {+ "CallMCPServerTool": ".call_mcp_server.tool",+ "CreateFormTool": ".create_form",+ "CreateInsightTool": ".create_insight",+ "CreateNotebookTool": ".create_notebook",+ "ExecuteSQLMCPTool": ".execute_sql.mcp_tool",+ "ExecuteSQLTool": ".execute_sql.tool",+ "ListDataTool": ".list_data",+ "ManageMemoriesTool": ".manage_memories",+ "ReadDataTool": ".read_data",+ "ReadDataWarehouseSchemaMCPTool": ".read_data_warehouse_schema.mcp_tool",+ "ReadTaxonomyMCPTool": ".read_taxonomy.mcp_tool",+ "ReadTaxonomyTool": ".read_taxonomy.tool",+ "SearchTool": ".search",+ "SwitchModeTool": ".switch_mode",+ "TaskTool": ".task",+ "TodoWriteTool": ".todo_write",+ "UpsertDashboardTool": ".upsert_dashboard",+}__all__ = ["CallMCPServerTool",@@ -34,3 +42,41 @@ __all__ = ["UpsertDashboardTool","CreateNotebookTool",]+++def load_all_tools() -> None:+ """Import every tool submodule so the MCP tools self-register via+ @mcp_tool_registry.register. Called by the registry on demand — registration is+ decoupled from package import so that importing the package (or a single tool) stays+ cheap and cycle-free. Idempotent: re-imports are dict lookups in sys.modules.+ """+ for submodule in dict.fromkeys(_TOOL_MODULES.values()):+ importlib.import_module(submodule, __name__)+++def __getattr__(name: str) -> Any:+ submodule = _TOOL_MODULES.get(name)+ if submodule is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ module = importlib.import_module(submodule, __name__)+ return getattr(module, name)+++if TYPE_CHECKING:+ from .call_mcp_server.tool import CallMCPServerTool as CallMCPServerTool+ from .create_form import CreateFormTool as CreateFormTool+ from .create_insight import CreateInsightTool as CreateInsightTool+ from .create_notebook import CreateNotebookTool as CreateNotebookTool+ from .execute_sql.mcp_tool import ExecuteSQLMCPTool as ExecuteSQLMCPTool+ from .execute_sql.tool import ExecuteSQLTool as ExecuteSQLTool+ from .list_data import ListDataTool as ListDataTool+ from .manage_memories import ManageMemoriesTool as ManageMemoriesTool+ from .read_data import ReadDataTool as ReadDataTool+ from .read_data_warehouse_schema.mcp_tool import ReadDataWarehouseSchemaMCPTool as ReadDataWarehouseSchemaMCPTool+ from .read_taxonomy.mcp_tool import ReadTaxonomyMCPTool as ReadTaxonomyMCPTool+ from .read_taxonomy.tool import ReadTaxonomyTool as ReadTaxonomyTool+ from .search import SearchTool as SearchTool+ from .switch_mode import SwitchModeTool as SwitchModeTool+ from .task import TaskTool as TaskTool+ from .todo_write import TodoWriteTool as TodoWriteTool+ from .upsert_dashboard import UpsertDashboardTool as UpsertDashboardTooldiff --git a/ee/hogai/tools/subagent_executor.py b/ee/hogai/tools/subagent_executor.pynew file mode 100644index 000000000000..6ca4e52bb6da--- /dev/null+++ b/ee/hogai/tools/subagent_executor.py@@ -0,0 +1,20 @@+# SubagentExecutor lives in its own module (not in task.py) on purpose: subclassing AgentExecutor+# requires importing ee.hogai.core.executor at module load, which reaches back into ee.hogai.tools+# through posthog.temporal.ai -> chat_agent -> toolkit. Keeping it here lets task.py import it lazily+# inside _arun_impl, so importing the `task` tool never drags the agent core onto the module path —+# while staying a real top-level class that can be imported and patched in tests.+from products.posthog_ai.backend.models.assistant import Conversation++from ee.hogai.core.executor import AgentExecutor+from ee.hogai.stream.redis_stream import get_subagent_stream_key+++class SubagentExecutor(AgentExecutor):+ """Executor for subagent workflows that uses a tool-specific stream key."""++ def __init__(self, conversation: Conversation, tool_call_id: str, execution_id: str):+ # Include execution_id to make workflow IDs unique per execution,+ # preventing conflicts when tool calls are replayed from checkpoints+ stream_key = get_subagent_stream_key(conversation.id, f"{tool_call_id}-{execution_id}")+ super().__init__(conversation, stream_key, reconnectable=False)+ self._workflow_id = f"subagent-{conversation.id}-{tool_call_id}-{execution_id}"diff --git a/ee/hogai/tools/task.py b/ee/hogai/tools/task.pyindex a3bf19774ce8..56c85d61eb72 100644--- a/ee/hogai/tools/task.py+++ b/ee/hogai/tools/task.py@@ -18,11 +18,8 @@ from posthog.schema import (from posthog.models import Team, User-from products.posthog_ai.backend.models.assistant import Conversation-from ee.hogai.artifacts.utils import unwrap_notebook_artifact_content, unwrap_visualization_artifact_contentfrom ee.hogai.context.context import AssistantContextManager-from ee.hogai.core.executor import AgentExecutorfrom ee.hogai.stream.redis_stream import get_subagent_stream_keyfrom ee.hogai.tool import MaxTool, ToolMessagesArtifactfrom ee.hogai.utils.prompt import format_prompt_string@@ -101,17 +98,6 @@ The following artifacts have been generated:"""-class SubagentExecutor(AgentExecutor):- """Executor for subagent workflows that uses a tool-specific stream key."""-- def __init__(self, conversation: Conversation, tool_call_id: str, execution_id: str):- # Include execution_id to make workflow IDs unique per execution,- # preventing conflicts when tool calls are replayed from checkpoints- stream_key = get_subagent_stream_key(conversation.id, f"{tool_call_id}-{execution_id}")- super().__init__(conversation, stream_key, reconnectable=False)- self._workflow_id = f"subagent-{conversation.id}-{tool_call_id}-{execution_id}"--class TaskToolArgs(BaseModel):title: str = Field(description="A short title for the task")task: str = Field(@@ -126,8 +112,14 @@ class TaskTool(MaxTool):args_schema: type[BaseModel] = TaskToolArgsasync def _arun_impl(self, title: str, task: str, agent_mode: AgentMode) -> tuple[str, ToolMessagesArtifact | None]:- # Avoid circular import- from posthog.temporal.ai.chat_agent import ChatAgentWorkflow, ChatAgentWorkflowInputs+ # Deferred: SubagentExecutor (and the chat_agent workflow) pull in ee.hogai.core.executor ->+ # posthog.temporal.ai -> chat_agent -> toolkit, which reaches back into ee.hogai.tools. At module+ # level that cycle only resolved by import-order luck; the lazy API router removed that luck (the+ # agent core is no longer pre-imported at django.setup), so the first MCP-tools request in a fresh+ # worker hit the half-initialized cycle. Importing both lazily here breaks it.+ from posthog.temporal.ai.chat_agent import ChatAgentWorkflow, ChatAgentWorkflowInputs # noqa: PLC0415++ from ee.hogai.tools.subagent_executor import SubagentExecutor # noqa: PLC0415thread_id = self._get_thread_id(self._config)if not thread_id:diff --git a/ee/hogai/tools/test/test_task.py b/ee/hogai/tools/test/test_task.pyindex 63b96b516c01..53161e7ee240 100644--- a/ee/hogai/tools/test/test_task.py+++ b/ee/hogai/tools/test/test_task.py@@ -18,7 +18,8 @@ from products.posthog_ai.backend.models.assistant import Conversationfrom ee.hogai.context.context import AssistantContextManagerfrom ee.hogai.stream.redis_stream import get_subagent_stream_key-from ee.hogai.tools.task import SubagentExecutor, TaskTool+from ee.hogai.tools.subagent_executor import SubagentExecutor+from ee.hogai.tools.task import TaskToolfrom ee.hogai.utils.types import AssistantStatefrom ee.hogai.utils.types.base import NodePathdiff --git a/ee/models/__init__.py b/ee/models/__init__.pyindex 8f967ad4109f..b8555e7b544a 100644--- a/ee/models/__init__.py+++ b/ee/models/__init__.py@@ -1,5 +1,7 @@from .dashboard_privilege import DashboardPrivilegefrom .event_definition import EnterpriseEventDefinition+from .explicit_team_membership import ExplicitTeamMembership+from .feature_flag_role_access import FeatureFlagRoleAccessfrom .license import Licensefrom .property_definition import EnterprisePropertyDefinitionfrom .rbac.access_control import AccessControl@@ -12,6 +14,8 @@ __all__ = ["DashboardPrivilege","EnterpriseEventDefinition","EnterprisePropertyDefinition",+ "ExplicitTeamMembership",+ "FeatureFlagRoleAccess","License","Role","RoleMembership",diff --git a/ee/vercel/integration.py b/ee/vercel/integration.pyindex 79ee37f78e00..d96ebe8c2951 100644--- a/ee/vercel/integration.py+++ b/ee/vercel/integration.py@@ -36,7 +36,6 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.api.authentication import VercelAuthenticationfrom ee.api.vercel.types import VercelClaims, VercelUserClaims-from ee.billing.billing_manager import BillingManagerfrom ee.billing.billing_types import BillingProviderfrom ee.vercel.client import SSOTokenResponse, VercelAPIClient@@ -349,6 +348,10 @@ class VercelIntegration:license = get_cached_instance_license()if license:try:+ # Deferred: BillingManager pulls the billing stack (stripe SDK, requests). This module+ # is imported at AppConfig.ready() to wire the Vercel receivers, so keep that path light.+ from ee.billing.billing_manager import BillingManager # noqa: PLC0415+billing_manager = BillingManager(license)billing_manager.authorize(organization, billing_provider=BillingProvider.VERCEL)logger.info(@@ -423,6 +426,8 @@ class VercelIntegration:f"No admin or owner found for organization {organization.id} — cannot deauthorize billing")+ from ee.billing.billing_manager import BillingManager # noqa: PLC0415+billing_manager = BillingManager(license, user=org_membership.user)billing_manager.deauthorize(organization, billing_provider=BillingProvider.VERCEL)logger.info(diff --git a/ee/vercel/test/test_integration.py b/ee/vercel/test/test_integration.pyindex 8187e7b595a2..6a99b2ffda02 100644--- a/ee/vercel/test/test_integration.py+++ b/ee/vercel/test/test_integration.py@@ -162,7 +162,7 @@ class TestVercelIntegration(TestCase):def test_update_installation_not_found(self):VercelIntegration.update_installation(self.NONEXISTENT_INSTALLATION_ID, "pro200")- @patch("ee.vercel.integration.BillingManager")+ @patch("ee.billing.billing_manager.BillingManager")@patch("ee.vercel.integration.get_cached_instance_license")def test_delete_installation(self, mock_license, mock_billing_manager):mock_license.return_value = Mock()@@ -182,7 +182,7 @@ class TestVercelIntegration(TestCase):assert OrganizationIntegration.objects.filter(integration_id=self.installation_id).exists()- @patch("ee.vercel.integration.BillingManager")+ @patch("ee.billing.billing_manager.BillingManager")@patch("ee.vercel.integration.get_cached_instance_license")def test_delete_installation_calls_billing_deauthorize(self, mock_license, mock_billing_manager):"""Deleting installation should notify billing service to cancel subscription."""@@ -200,7 +200,7 @@ class TestVercelIntegration(TestCase):self.organization, billing_provider=BillingProvider.VERCEL)- @patch("ee.vercel.integration.BillingManager")+ @patch("ee.billing.billing_manager.BillingManager")@patch("ee.vercel.integration.get_cached_instance_license")def test_delete_installation_aborts_on_billing_failure(self, mock_license, mock_billing_manager):"""Deletion should not proceed if billing deauthorization fails, so Vercel retries the webhook."""@@ -215,7 +215,7 @@ class TestVercelIntegration(TestCase):assert OrganizationIntegration.objects.filter(integration_id=self.installation_id).exists()- @patch("ee.vercel.integration.BillingManager")+ @patch("ee.billing.billing_manager.BillingManager")@patch("ee.vercel.integration.get_cached_instance_license")def test_delete_installation_blocked_by_open_invoices(self, mock_license, mock_billing_manager):from ee.billing.billing_manager import BillingServiceOpenInvoicesError@@ -413,7 +413,7 @@ class TestVercelIntegration(TestCase):self.fail("SSO should NOT require login for trusted Vercel user")@patch("ee.vercel.integration.report_user_signed_up")- @patch("ee.vercel.integration.BillingManager")+ @patch("ee.billing.billing_manager.BillingManager")@patch("ee.vercel.integration.get_cached_instance_license")def test_billing_failure_does_not_delete_existing_user(self, mock_license, mock_billing, mock_report):"""Billing failure should NOT delete existing users (only newly created ones)."""diff --git a/manage.py b/manage.pyindex 9c571cdcfc77..fd25c6aaa645 100755--- a/manage.py+++ b/manage.py@@ -1,6 +1,7 @@#!/usr/bin/env python"""Django's command-line utility for administrative tasks."""+import gcimport osimport sysfrom pathlib import Path@@ -22,6 +23,21 @@ def main():"forget to activate a virtual environment?") from exc+ # Boot allocations are almost all permanent (modules, classes, registries), so cyclic GC+ # during django.setup() only adds pauses (~300ms across ~470 collections). Disable it for+ # the boot, then freeze the survivors so later full collections skip them too. Skipped when+ # --settings/--pythonpath override the settings module, since those only take effect inside+ # execute_from_command_line. See docs/internal/django-startup-time.md.+ if not any(arg.startswith(("--settings", "--pythonpath")) for arg in sys.argv):+ gc.disable()+ try:+ import django++ django.setup()+ finally:+ gc.freeze()+ gc.enable()+# Default query tags so management commands don't trip the DEBUG-only UntaggedQueryError# in sync_execute. HTTP requests (runserver's CHQueries middleware) and Celery tasks reset# tags at their own boundaries, so this only effectively applies to direct CLI commands.diff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex 5f0dc9bf6373..72932efc5a72 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -1,673 +1,38 @@import importlibimport importlib.util--from django.apps import apps--from rest_framework import decorators, exceptions, viewsets-from rest_framework_extensions.routers import NestedRegistryItem--# Preload to work around circular imports in `ee.hogai.{core.agent_modes,chat_agent,tools}`.-import posthog.temporal.ai # noqa: F401-from posthog.api import data_color_theme, metalytics, my_notifications, project, user_integration, user_push_token-from posthog.api.csp_reporting import CSPReportingViewSet-from posthog.api.js_snippet import JsSnippetViewSet-from posthog.api.query_performance_proxy import QueryPerformanceProxyViewSet-from posthog.api.routing import DefaultRouterPlusPlus, RouterRegistry-from posthog.api.sdk_health import SdkHealthViewSet-from posthog.api.wizard import http as wizard-from posthog.approvals import api as approval_api-from posthog.settings import EE_AVAILABLE--from ee.api.quota_limits import QuotaLimitsViewSet-from ee.api.session_summaries import SessionGroupSummaryViewSet, SingleSessionSummaryViewSet-from ee.api.vercel import vercel_installation, vercel_product, vercel_proxy, vercel_resource--from ..session_recordings.session_recording_api import SessionRecordingViewSet-from ..session_recordings.session_recording_external_reference_api import SessionRecordingExternalReferenceViewSet-from ..session_recordings.session_recording_playlist_api import SessionRecordingPlaylistViewSet-from ..taxonomy import property_definition_api-from . import (- advanced_activity_logs,- async_migration,- authentication,- cimd_verification_token,- cli_auth,- comments,- dead_letter_queue,- debug_ch_queries,- event_definition,- event_schema,- health_issue,- hog,- ingestion_warnings,- instance_settings,- instance_status,- integration,- materialized_column_slot,- object_media_preview,- organization,- organization_domain,- organization_integration,- organization_invite,- organization_member,- organization_personal_api_key,- personal_api_key,- project_secret_api_key,- proxy_record,- query,- quick_filters,- resource_transfer,- role_external_reference,- schema_property_group,- search,- sharing,- tagged_item,- team,- uploaded_media,- user,- user_home_settings,- web_vitals,- webauthn,- welcome,-)-from .column_configuration import ColumnConfigurationViewSet-from .core_event import CoreEventViewSet-from .data_management import DataManagementViewSet-from .event_filter_config import EventFilterConfigViewSet-from .file_system import file_system, file_system_shortcut, persisted_folder, user_product_list-from .llm_prompt import LLMPromptViewSet-from .oauth import OrganizationOAuthApplicationViewSet-from .session import SessionViewSet--[email protected]_view(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"])[email protected]_classes([])[email protected]_classes([])-def api_not_found(request):- raise exceptions.NotFound(detail="Endpoint not found.")---router = DefaultRouterPlusPlus()-# Shared router handles, addressable by name, that products nest onto from their own-# `register_routes(routers)`. See posthog/api/routing.py:RouterRegistry.-routers = RouterRegistry()-routers.set_root(router)--# Nested endpoints shared-projects_router = routers.add("projects", router.register(r"projects", project.RootProjectViewSet, "projects"))-projects_router.register(r"environments", team.ProjectEnvironmentsViewSet, "project_environments", ["project_id"])-environments_router = routers.add(- "environments", router.register(r"environments", team.RootTeamViewSet, "environments")-)---def register_legacy_dual_route_team_nested_viewset(- prefix: str, viewset: type[viewsets.GenericViewSet], basename: str, parents_query_lookups: list[str]-) -> tuple[NestedRegistryItem, NestedRegistryItem]:- """- Register a team-nested viewset under BOTH /api/projects/:team_id/ and- /api/environments/:team_id/, for endpoints whose dual-route surface needs- to be preserved for existing clients.-- Background: PostHog briefly split projects and environments as separate- concepts then rolled the split back. /api/projects/ is the canonical path;- /api/environments/ is preserved only for clients that integrated against it- during the split (SDKs, customer integrations), and gets auto-marked- `deprecated: true` in the generated OpenAPI schema by the postprocess hook- in posthog.api.documentation whenever a matching /api/projects/ route- exists. That deprecation flag is what makes Orval pick the project route- as canonical for the generated TypeScript client.-- The `basename` argument encodes which side was the original canonical one,- which matters for stable URL-reverse names:- • `project_<X>` — project is canonical; env is a back-compat alias.- Pass this for endpoints that were (re-)introduced- env-only after the rollback by mistake.- • `environment_<X>` — env was the canonical surface from the split era;- project alias is back-filled. Pass this for legacy- env-canonical endpoints.- Either way, the project URL ends up with basename `project_<X>` and the env- URL with `environment_<X>`.-- DO NOT USE FOR NEW ENDPOINTS. New team-nested endpoints should register- directly under projects_router with no env alias — `# nosemgrep` markers- around env registrations are the smell to look for in code review; this- helper is the smell to look for in PRs that *add* registrations.-- Returns (project_nested, environment_nested).- """- return routers.register_legacy_dual_route(prefix, viewset, basename, parents_query_lookups)---projects_router.register(r"sdk_health", SdkHealthViewSet, "project_sdk_health", ["project_id"])-projects_router.register(- r"activity_log",- advanced_activity_logs.ActivityLogViewSet,- "project_activity_log",- ["project_id"],-)-projects_router.register(- r"advanced_activity_logs",- advanced_activity_logs.AdvancedActivityLogsViewSet,- "project_advanced_activity_logs",- ["project_id"],-)-projects_router.register(- r"my_notifications",- my_notifications.MyNotificationsViewSet,- "project_my_notifications",- ["project_id"],-)--# Tasks endpoints--# PostHog Code invites (not project-scoped)--# Seats (proxied to billing service)--# Quota limits (project-scoped — backs the LLM gateway's QuotaResolver)-projects_router.register(- r"quota_limits",- QuotaLimitsViewSet,- "project_quota_limits",- ["team_id"],-)--register_legacy_dual_route_team_nested_viewset(- r"column_configurations",- ColumnConfigurationViewSet,- "project_column_configurations",- ["team_id"],-)--register_legacy_dual_route_team_nested_viewset(- r"event_filter",- EventFilterConfigViewSet,- "project_event_filter",- ["team_id"],-)--register_legacy_dual_route_team_nested_viewset(- r"health_issues",- health_issue.HealthIssueViewSet,- "project_health_issues",- ["team_id"],-)--register_legacy_dual_route_team_nested_viewset(- r"llm_prompts",- LLMPromptViewSet,- "project_llm_prompts",- ["team_id"],-)---register_legacy_dual_route_team_nested_viewset(- r"integrations", integration.IntegrationViewSet, "environment_integrations", ["team_id"]-)-register_legacy_dual_route_team_nested_viewset(- r"ingestion_warnings",- ingestion_warnings.IngestionWarningsViewSet,- "environment_ingestion_warnings",- ["team_id"],-)---projects_router.register(- r"data_management",- DataManagementViewSet,- "project_data_management",- ["project_id"],-)--register_legacy_dual_route_team_nested_viewset(- r"materialized_column_slots",- materialized_column_slot.MaterializedColumnSlotViewSet,- "project_materialized_column_slots",- ["team_id"],-)---register_legacy_dual_route_team_nested_viewset(- r"file_system", file_system.FileSystemViewSet, "environment_file_system", ["team_id"]-)--projects_router.register(- r"desktop_file_system",- file_system.DesktopFileSystemViewSet,- "project_desktop_file_system",- ["team_id"],-)--register_legacy_dual_route_team_nested_viewset(- r"file_system_shortcut",- file_system_shortcut.FileSystemShortcutViewSet,- "environment_file_system_shortcut",- ["team_id"],-)--projects_router.register(- r"desktop_file_system_shortcut",- file_system_shortcut.DesktopFileSystemShortcutViewSet,- "project_desktop_file_system_shortcut",- ["team_id"],-)--register_legacy_dual_route_team_nested_viewset(- r"persisted_folder",- persisted_folder.PersistedFolderViewSet,- "environment_persisted_folder",- ["team_id"],-)--projects_router.register(- r"desktop_persisted_folder",- persisted_folder.DesktopPersistedFolderViewSet,- "project_desktop_persisted_folder",- ["team_id"],-)--register_legacy_dual_route_team_nested_viewset(- r"user_product_list",- user_product_list.UserProductListViewSet,- "environment_user_product_list",- ["team_id"],-)--projects_router.register(- r"event_definitions",- event_definition.EventDefinitionViewSet,- "project_event_definitions",- ["project_id"],-)-projects_router.register(- r"property_definitions",- property_definition_api.PropertyDefinitionViewSet,- "project_property_definitions",- ["project_id"],-)-projects_router.register(- r"schema_property_groups",- schema_property_group.SchemaPropertyGroupViewSet,- "project_schema_property_groups",- ["project_id"],-)-projects_router.register(- r"event_schemas",- event_schema.EventSchemaViewSet,- "project_event_schemas",- ["project_id"],-)--projects_router.register(r"uploaded_media", uploaded_media.MediaViewSet, "project_media", ["project_id"])--projects_router.register(- r"object_media_previews",- object_media_preview.ObjectMediaPreviewViewSet,- "project_object_media_previews",- ["project_id"],-)--projects_router.register(r"tags", tagged_item.TaggedItemViewSet, "project_tags", ["project_id"])-register_legacy_dual_route_team_nested_viewset(r"query", query.QueryViewSet, "environment_query", ["team_id"])---# Organizations nested endpoints-organizations_router = routers.add(- "organizations", router.register(r"organizations", organization.OrganizationViewSet, "organizations")-)-organizations_router.register(r"projects", project.ProjectViewSet, "organization_projects", ["organization_id"])-organizations_router.register(- r"integrations",- organization_integration.OrganizationIntegrationViewSet,- "organization_integrations",- ["organization_id"],-)-organizations_router.register(- r"oauth_applications",- OrganizationOAuthApplicationViewSet,- "organization_oauth_applications",- ["organization_id"],-)-organizations_router.register(- r"members",- organization_member.OrganizationMemberViewSet,- "organization_members",- ["organization_id"],-)-organizations_router.register(- r"invites",- organization_invite.OrganizationInviteViewSet,- "organization_invites",- ["organization_id"],-)-organizations_router.register(- r"domains",- organization_domain.OrganizationDomainViewset,- "organization_domains",- ["organization_id"],-)-organizations_router.register(- r"personal_api_keys",- organization_personal_api_key.OrganizationPersonalAPIKeyViewSet,- "organization_personal_api_keys",- ["organization_id"],-)-organizations_router.register(- r"cimd_verification_tokens",- cimd_verification_token.CIMDVerificationTokenViewSet,- "organization_cimd_verification_tokens",- ["organization_id"],-)-organizations_router.register(- r"proxy_records",- proxy_record.ProxyRecordViewset,- "proxy_records",- ["organization_id"],-)-organizations_router.register(- r"resource_transfers",- resource_transfer.ResourceTransferViewSet,- "organization_resource_transfers",- ["organization_id"],-)-organizations_router.register(- r"role_external_references",- role_external_reference.RoleExternalReferenceViewSet,- "organization_role_external_references",- ["organization_id"],-)-organizations_router.register(- r"welcome",- welcome.WelcomeViewSet,- "organization_welcome",- ["organization_id"],-)-organizations_router.register(- r"advanced_activity_logs",- advanced_activity_logs.OrganizationAdvancedActivityLogsViewSet,- "organization_advanced_activity_logs",- ["organization_id"],-)--# General endpoints (shared across CH & PG)-router.register(r"login", authentication.LoginViewSet, "login")-router.register(r"login/dev", authentication.DevLoginViewSet, "login_dev")-router.register(r"login/token", authentication.TwoFactorViewSet, "login_token")-router.register(r"login/precheck", authentication.LoginPrecheckViewSet, "login_precheck")-router.register(r"login/email-mfa", authentication.EmailMFAViewSet, "login_email_mfa")-router.register(r"login/2fa/passkey", authentication.TwoFactorPasskeyViewSet, "login_2fa_passkey")-router.register(r"webauthn/register", webauthn.WebAuthnRegistrationViewSet, "webauthn_register")-router.register(r"webauthn/signup-register", webauthn.WebAuthnSignupRegistrationViewSet, "webauthn_signup_register")-router.register(r"webauthn/login", webauthn.WebAuthnLoginViewSet, "webauthn_login")-router.register(r"webauthn/credentials", webauthn.WebAuthnCredentialViewSet, "webauthn_credentials")-router.register(r"reset", authentication.PasswordResetViewSet, "password_reset")-users_router = router.register(r"users", user.UserViewSet, "users")-users_router.register(- r"integrations",- user_integration.UserIntegrationViewSet,- "user_integration",- ["uuid"],-)-users_router.register(- r"push_tokens",- user_push_token.UserPushTokenViewSet,- "user_push_token",- ["uuid"],-)-router.register(- r"user_home_settings",- user_home_settings.UserHomeSettingsViewSet,- "user_home_settings",-)-router.register(r"personal_api_keys", personal_api_key.PersonalAPIKeyViewSet, "personal_api_keys")-router.register(r"cli-auth", cli_auth.CLIAuthViewSet, "cli_auth")-router.register(r"instance_status", instance_status.InstanceStatusViewSet, "instance_status")-router.register(r"dead_letter_queue", dead_letter_queue.DeadLetterQueueViewSet, "dead_letter_queue")-router.register(r"async_migrations", async_migration.AsyncMigrationsViewset, "async_migrations")-router.register(r"instance_settings", instance_settings.InstanceSettingsViewset, "instance_settings")-router.register(r"debug_ch_queries", debug_ch_queries.DebugCHQueries, "debug_ch_queries")-router.register(r"query_performance_proxy", QueryPerformanceProxyViewSet, "query_performance_proxy")--from posthog.api.cohort import CohortViewSet, LegacyCohortViewSet # noqa: E402-from posthog.api.element import ElementViewSet, LegacyElementViewSet # noqa: E402-from posthog.api.event import EventViewSet, LegacyEventViewSet # noqa: E402-from posthog.api.person import LegacyPersonViewSet, PersonViewSet # noqa: E402-from posthog.api.web_experiment import WebExperimentViewSet # noqa: E402--# Legacy endpoints CH (to be removed eventually)-router.register(r"cohort", LegacyCohortViewSet, basename="cohort")-router.register(r"element", LegacyElementViewSet, basename="element")-router.register(r"event", LegacyEventViewSet, basename="event")--# Nested endpoints CH-register_legacy_dual_route_team_nested_viewset(r"events", EventViewSet, "environment_events", ["team_id"])-projects_router.register(r"web_experiments", WebExperimentViewSet, "web_experiments", ["project_id"])-projects_router.register(r"cohorts", CohortViewSet, "project_cohorts", ["project_id"])--register_legacy_dual_route_team_nested_viewset(- r"elements",- ElementViewSet,- "environment_elements",- ["team_id"], # TODO: Can be removed?-)--legacy_project_session_recordings_router, environment_sessions_recordings_router = (- register_legacy_dual_route_team_nested_viewset(- r"session_recordings",- SessionRecordingViewSet,- "environment_session_recordings",- ["team_id"],- )-)--register_legacy_dual_route_team_nested_viewset(- r"session_recording_external_references",- SessionRecordingExternalReferenceViewSet,- "project_session_recording_external_references",- ["team_id"],-)--register_legacy_dual_route_team_nested_viewset(- r"session_recording_playlists",- SessionRecordingPlaylistViewSet,- "environment_session_recording_playlist",- ["team_id"],-)--register_legacy_dual_route_team_nested_viewset(r"sessions", SessionViewSet, "environment_sessions", ["team_id"])--if EE_AVAILABLE:- from ee.clickhouse.views.groups import GroupsTypesViewSet, GroupsViewSet, GroupUsageMetricViewSet- from ee.clickhouse.views.person import EnterprisePersonViewSet, LegacyEnterprisePersonViewSet-- register_legacy_dual_route_team_nested_viewset(r"groups", GroupsViewSet, "environment_groups", ["team_id"])- group_types_router = projects_router.register(- r"groups_types", GroupsTypesViewSet, "project_groups_types", ["project_id"]- )- group_types_router.register(- r"metrics", GroupUsageMetricViewSet, "project_groups_metrics", ["project_id", "group_type_index"]- )- register_legacy_dual_route_team_nested_viewset(- r"persons", EnterprisePersonViewSet, "environment_persons", ["team_id"]- )- router.register(r"person", LegacyEnterprisePersonViewSet, "persons")- vercel_installations_router = router.register(- r"vercel/v1/installations",- vercel_installation.VercelInstallationViewSet,- "vercel_installations",- )- vercel_installations_router.register(- r"resources",- vercel_resource.VercelResourceViewSet,- "vercel_installation_resources",- ["installation_id"],+from typing import TYPE_CHECKING, Any++# The API route aggregator (the DRF router build + ~200 viewset imports) lives in+# `posthog.api.rest_router`, imported lazily — only when a name it defines or re-exports+# (the router objects, view modules like `dashboard`) is first accessed, which in practice+# is when the URLconf resolves (first web request). Real submodules (`posthog.api.monitoring`,+# `.file_system`, ...) resolve directly without building the aggregator, so a plain+# `django.setup()` (shell, migrate, celery, CI) stays cheap. See posthog/api/rest_router.py.+++def __getattr__(name: str) -> Any:+ # A real submodule — import it directly, cheaply, without building the aggregator. This is+ # what keeps django.setup() off the route-building path (the setup-time importers all hit+ # real submodules).+ if importlib.util.find_spec(f"{__name__}.{name}") is not None:+ return importlib.import_module(f"{__name__}.{name}")+ # Otherwise it's a name the aggregator defines or re-exports (router objects, plus view+ # modules like `dashboard` that come from other packages). Build it lazily and delegate.+ from posthog.api import rest_router # noqa: PLC0415++ try:+ return getattr(rest_router, name)+ except AttributeError:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None+++if TYPE_CHECKING:+ from posthog.api.rest_router import (+ api_not_found as api_not_found,+ environments_router as environments_router,+ organizations_router as organizations_router,+ projects_router as projects_router,+ register_legacy_dual_route_team_nested_viewset as register_legacy_dual_route_team_nested_viewset,+ router as router,+ routers as routers,)- router.register(- r"vercel/v1/products",- vercel_product.VercelProductViewSet,- "vercel_products",- )- router.register(- r"vercel/proxy",- vercel_proxy.VercelProxyViewSet,- "vercel_proxy",- )--else:- register_legacy_dual_route_team_nested_viewset(r"persons", PersonViewSet, "environment_persons", ["team_id"])- router.register(r"person", LegacyPersonViewSet, "persons")--# session_recordings sharing nest stays central — the session_recordings viewsets-# still live under posthog/session_recordings/ rather than in a product folder.-environment_sessions_recordings_router.register(- r"sharing",- sharing.SharingConfigurationViewSet,- "environment_recording_sharing",- ["team_id", "recording_id"],-)-legacy_project_session_recordings_router.register(- r"sharing",- sharing.SharingConfigurationViewSet,- "project_recording_sharing",- ["team_id", "recording_id"],-)--projects_router.register(- r"session_group_summaries",- SessionGroupSummaryViewSet,- "project_session_group_summaries",- ["project_id"],-)--projects_router.register(- r"single_session_summaries",- SingleSessionSummaryViewSet,- "project_single_session_summaries",- ["project_id"],-)--register_legacy_dual_route_team_nested_viewset(- r"quick_filters",- quick_filters.QuickFilterViewSet,- "project_quick_filters",- ["team_id"],-)---projects_router.register(- r"comments",- comments.CommentViewSet,- "project_comments",- ["project_id"],-)---projects_router.register(- r"hog",- hog.HogViewSet,- "hog",- ["team_id"],-)--register_legacy_dual_route_team_nested_viewset(- r"metalytics",- metalytics.MetalyticsViewSet,- "environment_metalytics",- ["team_id"],-)--projects_router.register(r"search", search.SearchViewSet, "project_search", ["project_id"])--register_legacy_dual_route_team_nested_viewset(- r"project_secret_api_keys",- project_secret_api_key.ProjectSecretAPIKeyViewSet,- "environment_project_secret_api_keys",- ["team_id"],-)--register_legacy_dual_route_team_nested_viewset(- r"data_color_themes", data_color_theme.DataColorThemeViewSet, "environment_data_color_themes", ["team_id"]-)--register_legacy_dual_route_team_nested_viewset(- r"web_vitals",- web_vitals.WebVitalsViewSet,- "project_web_vitals",- ["team_id"],-)--router.register(r"wizard", wizard.SetupWizardViewSet, "wizard")---register_legacy_dual_route_team_nested_viewset(- r"csp-reporting",- CSPReportingViewSet,- "project_csp_reporting",- ["team_id"],-)---projects_router.register(r"js-snippet", JsSnippetViewSet, "project_js_snippet", ["team_id"])---register_legacy_dual_route_team_nested_viewset(- r"change_requests",- approval_api.ChangeRequestViewSet,- "project_change_requests",- ["team_id"],-)--register_legacy_dual_route_team_nested_viewset(- r"approval_policies",- approval_api.ApprovalPolicyViewSet,- "project_approval_policies",- ["team_id"],-)--register_legacy_dual_route_team_nested_viewset(- r"core_events",- CoreEventViewSet,- "project_core_events",- ["team_id"],-)---# --- Product route auto-discovery ------------------------------------------------------# Every parent above (root + projects + environments + organizations) and all of core's-# own routes are registered before this loop. Migrated products then register themselves-# by exposing `register_routes(routers)` in `products/<name>/backend/routes.py`; the loop-# finds them via INSTALLED_APPS, so adding a product needs no edit here.-#-# Why a loop here, and why eager (not AppConfig.ready()):-# - ROOT_URLCONF is imported lazily on first URL resolution, not during django.setup().-# `posthog/urls.py` imports this module, so the whole API surface loads at first-# request and never at boot — Celery workers and management commands that never-# resolve a URL never import it. We keep that.-# - ready()-based self-registration would run inside django.setup() in every process,-# and registering a route imports its viewset class — so it would drag the entire-# product API into setup() everywhere, regressing that laziness. Running the loop at-# import of `posthog.api` (i.e. first request) keeps the API out of setup().-# - Net: core still triggers registration (via the existing `posthog.api` import) rather-# than products self-pushing — you can have "core imports nothing statically" OR "API-# stays out of setup()", not both; we keep the API lazy.-#-# Order-independence: products only nest onto the four core-owned parents and never onto-# each other, and all parents exist before this loop, so iteration order does not affect-# the resolved route set. `RouterRegistry.add()` rejects product callers, making-# "parents stay core-owned" an enforced invariant rather than a convention.-#-# Accepted cost: routes are imported dynamically here, so the core->product import edges-# are not statically visible to import tooling (tach/grimp). Accepted on purpose — it-# removes the hand-maintained product list that duplicated PRODUCTS_APPS.-for _app_config in apps.get_app_configs():- if not _app_config.name.startswith("products."):- continue- _routes_module = f"{_app_config.name}.routes"- # find_spec (not try/except ImportError) so a real ImportError inside a routes.py- # surfaces instead of being silently swallowed as "no routes module".- if importlib.util.find_spec(_routes_module) is None:- continue- _register_routes = getattr(importlib.import_module(_routes_module), "register_routes", None)- if callable(_register_routes):- _register_routes(routers)diff --git a/posthog/api/authentication.py b/posthog/api/authentication.pyindex 2ceff5a0db6f..53744d4d55ce 100644--- a/posthog/api/authentication.py+++ b/posthog/api/authentication.py@@ -12,13 +12,11 @@ from django.contrib.auth import (logout as auth_logout,)from django.contrib.auth.password_validation import validate_password-from django.contrib.auth.signals import user_logged_infrom django.contrib.auth.tokens import PasswordResetTokenGenerator as DefaultPasswordResetTokenGeneratorfrom django.contrib.auth.views import redirect_to_loginfrom django.core.exceptions import ValidationErrorfrom django.core.signing import BadSignaturefrom django.db import transaction-from django.dispatch import receiverfrom django.http import Http404, HttpRequest, HttpResponse, JsonResponsefrom django.shortcuts import redirectfrom django.utils import timezone@@ -31,7 +29,6 @@ from axes.handlers.proxy import AxesProxyHandlerfrom django_otp import login as otp_loginfrom django_otp.plugins.otp_static.models import StaticDevicefrom loginas.utils import is_impersonated_session, restore_original_login-from prometheus_client import Counterfrom rest_framework import mixins, permissions, serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import APIException@@ -78,12 +75,6 @@ from posthog.workos_radar import RadarAction, RadarAuthMethod, evaluate_auth_attlogger = structlog.get_logger("posthog.auth")mfa_logger = structlog.get_logger("posthog.auth.mfa")-USER_AUTH_METHOD_MISMATCH = Counter(- "user_auth_method_mismatches_sso_enforcement",- "A user successfully authenticated with a different method than the one they're required to use",- labelnames=["login_method", "sso_enforced_method", "user_uuid"],-)-class WebauthnCredentialPrecheck(TypedDict):id: str@@ -91,30 +82,6 @@ class WebauthnCredentialPrecheck(TypedDict):transports: list[str]-@receiver(user_logged_in)-def post_login(sender, user, request: HttpRequest, **kwargs):- """- Runs after every user login (including tests)- Sets SESSION_COOKIE_CREATED_AT_KEY in the session to the current time- """-- if hasattr(request, "backend"):- sso_enforcement = OrganizationDomain.objects.get_sso_enforcement_for_email_address(user.email)- if sso_enforcement is not None and sso_enforcement != request.backend.name:- USER_AUTH_METHOD_MISMATCH.labels(- login_method=request.backend.name, sso_enforced_method=sso_enforcement, user_uuid=user.uuid- ).inc()-- request.session[settings.SESSION_COOKIE_CREATED_AT_KEY] = time.time()-- # Cache device info on signup to skip login notification for this device- if user.last_login is None:- short_user_agent = get_short_user_agent(request)- ip_address = get_ip_address(request)- country = get_geoip_properties(ip_address).get("$geoip_country_name", "Unknown")- check_and_cache_login_device(user.id, country, short_user_agent)--@require_http_methods(["POST"])def logout(request):clear_two_factor_session_flags(request)diff --git a/posthog/api/file_system/registrations.py b/posthog/api/file_system/registrations.pyindex fe91027b750f..9155c04bed20 100644--- a/posthog/api/file_system/registrations.py+++ b/posthog/api/file_system/registrations.py@@ -17,11 +17,10 @@ from posthog.api.file_system.deletion import (from posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.activity_logging.model_activity import is_impersonated_sessionfrom posthog.models.user import User-from posthog.session_recordings.session_recording_playlist_api import log_playlist_activityfrom products.cdp.backend.models.hog_functions.utils import humanize_hog_function_type-from products.tasks.backend.api import task_visibility_qfrom products.tasks.backend.models import Task as _Task+from products.tasks.backend.visibility import task_visibility_qdef _first_non_blank(*values: str | None) -> str | None:@@ -168,6 +167,11 @@ def _link_post_delete(context: DeletionContext, link: Any) -> None:def _playlist_post_restore(context: RestoreContext, playlist: Any) -> None:+ # Deferred: session_recording_playlist_api pulls session_recording_api -> the session_summary+ # temporal workflow (-> google-genai). This module is imported from AppConfig.ready(), so a+ # module-level import would drag all of that onto every process's startup path.+ from posthog.session_recordings.session_recording_playlist_api import log_playlist_activity # noqa: PLC0415+organization = context.organizationif not organization:return@@ -203,6 +207,8 @@ def _playlist_post_restore(context: RestoreContext, playlist: Any) -> None:def _playlist_post_delete(context: DeletionContext, playlist: Any) -> None:+ from posthog.session_recordings.session_recording_playlist_api import log_playlist_activity # noqa: PLC0415+organization = context.organizationif not organization:returndiff --git a/posthog/api/organization.py b/posthog/api/organization.pyindex c3bc400310e3..9f0949871743 100644--- a/posthog/api/organization.py+++ b/posthog/api/organization.py@@ -1,12 +1,8 @@-import dataclassesfrom collections.abc import Callablefrom functools import cached_propertyfrom typing import Any, Literal, Union, cast-from django.core.cache import cache-from django.db import transactionfrom django.db.models import Model, QuerySet-from django.db.models.signals import post_delete, post_savefrom django.shortcuts import get_object_or_404import posthoganalytics@@ -22,6 +18,10 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import OrgScopedPrimaryKeyRelatedFieldfrom posthog.api.shared import ProjectBasicSerializer, TeamBasicSerializerfrom posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication+from posthog.caching.organization_serializer_cache import (+ ORG_SERIALIZER_CACHE_TTL_SECONDS,+ _org_serializer_cache_version,+)from posthog.cloud_utils import get_cached_instance_license, is_cloudfrom posthog.constants import INTERNAL_BOT_EMAIL_SUFFIX, AvailableFeaturefrom posthog.event_usage import (@@ -32,13 +32,9 @@ from posthog.event_usage import ()from posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.email_utils import validate_display_name-from posthog.models import Organization, Team, User-from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activity+from posthog.models import Organization, Userfrom posthog.models.activity_logging.model_activity import ImpersonatedContextfrom posthog.models.organization import OrganizationMembership-from posthog.models.organization_invite import OrganizationInvite-from posthog.models.project import Project-from posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.models.uploaded_media import UploadedMediafrom posthog.permissions import (CREATE_ACTIONS,@@ -54,10 +50,6 @@ from posthog.tasks.tasks import delete_organization_data_and_notify_taskfrom posthog.user_permissions import UserPermissions, UserPermissionsSerializerMixinfrom posthog.utils import get_safe_cache, safe_cache_set-from ee.models.explicit_team_membership import ExplicitTeamMembership-from ee.models.rbac.access_control import AccessControl-from ee.models.rbac.role import RoleMembership-class PremiumMultiorganizationPermission(permissions.BasePermission):"""Require user to have all necessary premium features on their plan for create access to the endpoint."""@@ -96,43 +88,6 @@ class OrganizationPermissionsWithDelete(OrganizationAdminWritePermissions):tracer = trace.get_tracer(__name__)-ORG_SERIALIZER_CACHE_TTL_SECONDS = 60 * 60-ORG_SERIALIZER_VERSION_TTL_SECONDS = 7 * 24 * 60 * 60-_ORG_SERIALIZER_VERSION_KEY_PREFIX = "org_serializer_version:"---def _org_serializer_version_key(organization_id: str) -> str:- return f"{_ORG_SERIALIZER_VERSION_KEY_PREFIX}{organization_id}"---def _org_serializer_cache_version(organization_id: str) -> int:- key = _org_serializer_version_key(organization_id)- raw = get_safe_cache(key)- if raw is None:- try:- cache.add(key, 0, timeout=ORG_SERIALIZER_VERSION_TTL_SECONDS)- except Exception:- pass- return 0- try:- return int(raw)- except (TypeError, ValueError):- return 0---def _bump_org_serializer_cache_version(organization_id: str) -> None:- key = _org_serializer_version_key(organization_id)- try:- cache.incr(key)- except ValueError:- try:- cache.add(key, 1, timeout=ORG_SERIALIZER_VERSION_TTL_SECONDS)- except Exception:- pass- except Exception:- pass--CacheField = Literal["teams", "projects"]OrgCacheField = Literal["member_count"]@@ -180,62 +135,6 @@ def _resolve_cached_user_id(serializer_context: dict[str, Any]) -> int | None:return user.id-def _instance_org_id(instance: Any) -> str | None:- organization_id = getattr(instance, "organization_id", None)- return str(organization_id) if organization_id is not None else None---def _team_id_to_org_id(instance: Any) -> str | None:- team_id = getattr(instance, "team_id", None)- if team_id is None:- return None- organization_id = Team.objects.filter(id=team_id).values_list("organization_id", flat=True).first()- return str(organization_id) if organization_id is not None else None---def _role_id_to_org_id(instance: Any) -> str | None:- role = getattr(instance, "role", None)- if role is None:- return None- organization_id = getattr(role, "organization_id", None)- return str(organization_id) if organization_id is not None else None---_VISIBILITY_RESOURCES = {"project", "organization"}---def _access_control_to_org_id(instance: Any) -> str | None:- if getattr(instance, "resource", None) not in _VISIBILITY_RESOURCES:- return None- return _team_id_to_org_id(instance)---_INVALIDATION_SOURCES: list[tuple[type[Model], Callable[[Any], str | None]]] = [- (Team, _instance_org_id),- (Project, _instance_org_id),- (OrganizationMembership, _instance_org_id),- (AccessControl, _access_control_to_org_id),- (ExplicitTeamMembership, _team_id_to_org_id),- (RoleMembership, _role_id_to_org_id),-]---def _connect_invalidation(model: type[Model], get_org_id: Callable[[Any], str | None]) -> None:- def receiver_fn(sender: type[Model], instance: Any, **kwargs: Any) -> None:- organization_id = get_org_id(instance)- if organization_id is None:- return- _bump_org_serializer_cache_version(organization_id)- transaction.on_commit(lambda: _bump_org_serializer_cache_version(organization_id))-- post_save.connect(receiver_fn, sender=model, weak=False)- post_delete.connect(receiver_fn, sender=model, weak=False)---for _model, _resolver in _INVALIDATION_SOURCES:- _connect_invalidation(_model, _resolver)--class OrganizationSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin, UserAccessControlSerializerMixin):@@ -652,137 +551,3 @@ class OrganizationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return Response({"status": False, "error": "An internal error has occurred."}, status=500)return Response({"status": True})---@mutable_receiver(model_activity_signal, sender=Organization)-def handle_organization_change(- sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs-):- log_activity(- organization_id=after_update.id,- team_id=None,- user=user,- was_impersonated=was_impersonated,- item_id=after_update.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(scope, previous=before_update, current=after_update),- name=after_update.name,- ),- )--[email protected](frozen=True)-class OrganizationMembershipContext(ActivityContextBase):- organization_id: str- organization_name: str- user_id: str- user_email: str- user_name: str- level: str--[email protected](frozen=True)-class OrganizationInviteContext(ActivityContextBase):- organization_id: str- organization_name: str- target_email: str- inviter_user_id: str | None- inviter_user_email: str | None- inviter_user_name: str | None- level: str---@mutable_receiver(model_activity_signal, sender=OrganizationMembership)-def handle_organization_membership_change(- sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs-):- # Use after_update for create/update, before_update for delete- membership = after_update or before_update-- if not membership:- return-- member_user = membership.user- member_name = f"{member_user.first_name} {member_user.last_name}".strip()-- context = OrganizationMembershipContext(- organization_id=str(membership.organization_id),- organization_name=membership.organization.name,- user_id=str(member_user.id),- user_email=member_user.email,- user_name=member_name,- level=str(OrganizationMembership.Level(membership.level).label),- )-- if activity == "created":- detail_name = f"{member_name} ({member_user.email}) joined {membership.organization.name}"- elif activity == "deleted":- detail_name = f"{member_name} ({member_user.email}) left {membership.organization.name}"- else:- detail_name = f"{member_name} ({member_user.email}) membership updated in {membership.organization.name}"-- log_activity(- organization_id=membership.organization_id,- team_id=None,- user=user,- was_impersonated=was_impersonated,- item_id=membership.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(scope, previous=before_update, current=after_update),- name=detail_name,- context=context,- ),- )---@mutable_receiver(model_activity_signal, sender=OrganizationInvite)-def handle_organization_invite_change(- sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs-):- # Use after_update for create/update, before_update for delete- invite = after_update or before_update-- if not invite:- return-- inviter_user = invite.created_by- inviter_name = f"{inviter_user.first_name} {inviter_user.last_name}".strip() if inviter_user else None-- context = OrganizationInviteContext(- organization_id=str(invite.organization_id),- organization_name=invite.organization.name,- target_email=invite.target_email,- inviter_user_id=str(inviter_user.id) if inviter_user else None,- inviter_user_email=inviter_user.email if inviter_user else None,- inviter_user_name=inviter_name,- level=str(OrganizationMembership.Level(invite.level).label),- )-- if activity == "created":- if inviter_user:- detail_name = f"User {inviter_name} ({inviter_user.email}) invited user {invite.target_email} into organization {invite.organization.name}"- else:- detail_name = f"User {invite.target_email} was invited to organization {invite.organization.name}"- elif activity == "deleted":- detail_name = f"Invite for {invite.target_email} to organization {invite.organization.name} was cancelled"- else:- detail_name = f"Invite for {invite.target_email} to organization {invite.organization.name} was updated"-- log_activity(- organization_id=invite.organization_id,- team_id=None,- user=user,- was_impersonated=was_impersonated,- item_id=invite.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(scope, previous=before_update, current=after_update),- name=detail_name,- context=context,- ),- )diff --git a/posthog/api/personal_api_key.py b/posthog/api/personal_api_key.pyindex 69a537d227fa..ee2dfbdeeec0 100644--- a/posthog/api/personal_api_key.py+++ b/posthog/api/personal_api_key.py@@ -1,8 +1,6 @@import uuidfrom typing import cast-from django.db.models.signals import pre_delete-from django.dispatch import receiverfrom django.utils import timezoneimport posthoganalytics@@ -13,13 +11,7 @@ from rest_framework.permissions import BasePermission, IsAuthenticatedfrom posthog.api.utils import actionfrom posthog.auth import PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.models import PersonalAPIKey, User-from posthog.models.activity_logging.activity_log import changes_between-from posthog.models.activity_logging.personal_api_key_utils import (- log_personal_api_key_activity,- log_personal_api_key_scope_change,-)from posthog.models.personal_api_key import LEGACY_HASH_PREFIX-from posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.models.team.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_value, mask_key_valuefrom posthog.permissions import TimeSensitiveActionPermission@@ -262,30 +254,3 @@ class PersonalAPIKeyViewSet(viewsets.ModelViewSet):serializer = cast(PersonalAPIKeySerializer, self.get_serializer(instance))serializer.roll(instance)return response.Response(serializer.data, status=status.HTTP_200_OK)---@mutable_receiver(model_activity_signal, sender=PersonalAPIKey)-def handle_personal_api_key_change(- sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs-):- changes = changes_between(scope, previous=before_update, current=after_update)-- # Check if scope changed (scoped_teams or scoped_organizations)- scope_fields = ["scoped_teams", "scoped_organizations"]- scope_changed = any(change.field in scope_fields for change in changes if change.field)-- if scope_changed and activity == "updated":- # Filter out scope fields from changes as we dont want to present them to the user- filtered_changes = [- change for change in changes if change.field not in ["scoped_teams", "scoped_organizations"]- ]- log_personal_api_key_scope_change(before_update, after_update, user, was_impersonated, filtered_changes)- else:- log_personal_api_key_activity(after_update, activity, user, was_impersonated, changes)---@receiver(pre_delete, sender=PersonalAPIKey)-def handle_personal_api_key_delete(sender, instance, **kwargs):- from posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonated-- log_personal_api_key_activity(instance, "deleted", get_current_user(), get_was_impersonated())diff --git a/posthog/api/project_secret_api_key.py b/posthog/api/project_secret_api_key.pyindex b16f636a01d7..ec123cccd8a9 100644--- a/posthog/api/project_secret_api_key.py+++ b/posthog/api/project_secret_api_key.py@@ -2,8 +2,6 @@ from typing import castfrom django.db import IntegrityErrorfrom django.db.models import QuerySet-from django.db.models.signals import pre_delete-from django.dispatch import receiverfrom django.utils import timezonefrom rest_framework import response, serializers, status, viewsets@@ -15,11 +13,7 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import actionfrom posthog.auth import PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.models import User-from posthog.models.activity_logging.activity_log import changes_between-from posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonated, model_activity_signal-from posthog.models.activity_logging.project_secret_api_key_utils import log_project_secret_api_key_activityfrom posthog.models.project_secret_api_key import ProjectSecretAPIKey-from posthog.models.signals import mutable_receiverfrom posthog.models.utils import generate_random_token_secret, hash_key_value, mask_key_valuefrom posthog.permissions import TeamMemberStrictManagementPermission, TimeSensitiveActionPermissionfrom posthog.scopes import (@@ -167,16 +161,3 @@ class ProjectSecretAPIKeyViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):serializer = cast(ProjectSecretAPIKeySerializer, self.get_serializer(instance))serializer.roll(instance)return response.Response(serializer.data, status=status.HTTP_200_OK)---@mutable_receiver(model_activity_signal, sender=ProjectSecretAPIKey)-def handle_project_secret_api_key_change(- sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs-):- changes = changes_between(scope, previous=before_update, current=after_update)- log_project_secret_api_key_activity(after_update, activity, user, was_impersonated, changes)---@receiver(pre_delete, sender=ProjectSecretAPIKey)-def handle_project_secret_api_key_delete(sender, instance, **kwargs):- log_project_secret_api_key_activity(instance, "deleted", get_current_user(), get_was_impersonated())diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.pynew file mode 100644index 000000000000..5f0dc9bf6373--- /dev/null+++ b/posthog/api/rest_router.py@@ -0,0 +1,673 @@+import importlib+import importlib.util++from django.apps import apps++from rest_framework import decorators, exceptions, viewsets+from rest_framework_extensions.routers import NestedRegistryItem++# Preload to work around circular imports in `ee.hogai.{core.agent_modes,chat_agent,tools}`.+import posthog.temporal.ai # noqa: F401+from posthog.api import data_color_theme, metalytics, my_notifications, project, user_integration, user_push_token+from posthog.api.csp_reporting import CSPReportingViewSet+from posthog.api.js_snippet import JsSnippetViewSet+from posthog.api.query_performance_proxy import QueryPerformanceProxyViewSet+from posthog.api.routing import DefaultRouterPlusPlus, RouterRegistry+from posthog.api.sdk_health import SdkHealthViewSet+from posthog.api.wizard import http as wizard+from posthog.approvals import api as approval_api+from posthog.settings import EE_AVAILABLE++from ee.api.quota_limits import QuotaLimitsViewSet+from ee.api.session_summaries import SessionGroupSummaryViewSet, SingleSessionSummaryViewSet+from ee.api.vercel import vercel_installation, vercel_product, vercel_proxy, vercel_resource++from ..session_recordings.session_recording_api import SessionRecordingViewSet+from ..session_recordings.session_recording_external_reference_api import SessionRecordingExternalReferenceViewSet+from ..session_recordings.session_recording_playlist_api import SessionRecordingPlaylistViewSet+from ..taxonomy import property_definition_api+from . import (+ advanced_activity_logs,+ async_migration,+ authentication,+ cimd_verification_token,+ cli_auth,+ comments,+ dead_letter_queue,+ debug_ch_queries,+ event_definition,+ event_schema,+ health_issue,+ hog,+ ingestion_warnings,+ instance_settings,+ instance_status,+ integration,+ materialized_column_slot,+ object_media_preview,+ organization,+ organization_domain,+ organization_integration,+ organization_invite,+ organization_member,+ organization_personal_api_key,+ personal_api_key,+ project_secret_api_key,+ proxy_record,+ query,+ quick_filters,+ resource_transfer,+ role_external_reference,+ schema_property_group,+ search,+ sharing,+ tagged_item,+ team,+ uploaded_media,+ user,+ user_home_settings,+ web_vitals,+ webauthn,+ welcome,+)+from .column_configuration import ColumnConfigurationViewSet+from .core_event import CoreEventViewSet+from .data_management import DataManagementViewSet+from .event_filter_config import EventFilterConfigViewSet+from .file_system import file_system, file_system_shortcut, persisted_folder, user_product_list+from .llm_prompt import LLMPromptViewSet+from .oauth import OrganizationOAuthApplicationViewSet+from .session import SessionViewSet++[email protected]_view(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"])[email protected]_classes([])[email protected]_classes([])+def api_not_found(request):+ raise exceptions.NotFound(detail="Endpoint not found.")+++router = DefaultRouterPlusPlus()+# Shared router handles, addressable by name, that products nest onto from their own+# `register_routes(routers)`. See posthog/api/routing.py:RouterRegistry.+routers = RouterRegistry()+routers.set_root(router)++# Nested endpoints shared+projects_router = routers.add("projects", router.register(r"projects", project.RootProjectViewSet, "projects"))+projects_router.register(r"environments", team.ProjectEnvironmentsViewSet, "project_environments", ["project_id"])+environments_router = routers.add(+ "environments", router.register(r"environments", team.RootTeamViewSet, "environments")+)+++def register_legacy_dual_route_team_nested_viewset(+ prefix: str, viewset: type[viewsets.GenericViewSet], basename: str, parents_query_lookups: list[str]+) -> tuple[NestedRegistryItem, NestedRegistryItem]:+ """+ Register a team-nested viewset under BOTH /api/projects/:team_id/ and+ /api/environments/:team_id/, for endpoints whose dual-route surface needs+ to be preserved for existing clients.++ Background: PostHog briefly split projects and environments as separate+ concepts then rolled the split back. /api/projects/ is the canonical path;+ /api/environments/ is preserved only for clients that integrated against it+ during the split (SDKs, customer integrations), and gets auto-marked+ `deprecated: true` in the generated OpenAPI schema by the postprocess hook+ in posthog.api.documentation whenever a matching /api/projects/ route+ exists. That deprecation flag is what makes Orval pick the project route+ as canonical for the generated TypeScript client.++ The `basename` argument encodes which side was the original canonical one,+ which matters for stable URL-reverse names:+ • `project_<X>` — project is canonical; env is a back-compat alias.+ Pass this for endpoints that were (re-)introduced+ env-only after the rollback by mistake.+ • `environment_<X>` — env was the canonical surface from the split era;+ project alias is back-filled. Pass this for legacy+ env-canonical endpoints.+ Either way, the project URL ends up with basename `project_<X>` and the env+ URL with `environment_<X>`.++ DO NOT USE FOR NEW ENDPOINTS. New team-nested endpoints should register+ directly under projects_router with no env alias — `# nosemgrep` markers+ around env registrations are the smell to look for in code review; this+ helper is the smell to look for in PRs that *add* registrations.++ Returns (project_nested, environment_nested).+ """+ return routers.register_legacy_dual_route(prefix, viewset, basename, parents_query_lookups)+++projects_router.register(r"sdk_health", SdkHealthViewSet, "project_sdk_health", ["project_id"])+projects_router.register(+ r"activity_log",+ advanced_activity_logs.ActivityLogViewSet,+ "project_activity_log",+ ["project_id"],+)+projects_router.register(+ r"advanced_activity_logs",+ advanced_activity_logs.AdvancedActivityLogsViewSet,+ "project_advanced_activity_logs",+ ["project_id"],+)+projects_router.register(+ r"my_notifications",+ my_notifications.MyNotificationsViewSet,+ "project_my_notifications",+ ["project_id"],+)++# Tasks endpoints++# PostHog Code invites (not project-scoped)++# Seats (proxied to billing service)++# Quota limits (project-scoped — backs the LLM gateway's QuotaResolver)+projects_router.register(+ r"quota_limits",+ QuotaLimitsViewSet,+ "project_quota_limits",+ ["team_id"],+)++register_legacy_dual_route_team_nested_viewset(+ r"column_configurations",+ ColumnConfigurationViewSet,+ "project_column_configurations",+ ["team_id"],+)++register_legacy_dual_route_team_nested_viewset(+ r"event_filter",+ EventFilterConfigViewSet,+ "project_event_filter",+ ["team_id"],+)++register_legacy_dual_route_team_nested_viewset(+ r"health_issues",+ health_issue.HealthIssueViewSet,+ "project_health_issues",+ ["team_id"],+)++register_legacy_dual_route_team_nested_viewset(+ r"llm_prompts",+ LLMPromptViewSet,+ "project_llm_prompts",+ ["team_id"],+)+++register_legacy_dual_route_team_nested_viewset(+ r"integrations", integration.IntegrationViewSet, "environment_integrations", ["team_id"]+)+register_legacy_dual_route_team_nested_viewset(+ r"ingestion_warnings",+ ingestion_warnings.IngestionWarningsViewSet,+ "environment_ingestion_warnings",+ ["team_id"],+)+++projects_router.register(+ r"data_management",+ DataManagementViewSet,+ "project_data_management",+ ["project_id"],+)++register_legacy_dual_route_team_nested_viewset(+ r"materialized_column_slots",+ materialized_column_slot.MaterializedColumnSlotViewSet,+ "project_materialized_column_slots",+ ["team_id"],+)+++register_legacy_dual_route_team_nested_viewset(+ r"file_system", file_system.FileSystemViewSet, "environment_file_system", ["team_id"]+)++projects_router.register(+ r"desktop_file_system",+ file_system.DesktopFileSystemViewSet,+ "project_desktop_file_system",+ ["team_id"],+)++register_legacy_dual_route_team_nested_viewset(+ r"file_system_shortcut",+ file_system_shortcut.FileSystemShortcutViewSet,+ "environment_file_system_shortcut",+ ["team_id"],+)++projects_router.register(+ r"desktop_file_system_shortcut",+ file_system_shortcut.DesktopFileSystemShortcutViewSet,+ "project_desktop_file_system_shortcut",+ ["team_id"],+)++register_legacy_dual_route_team_nested_viewset(+ r"persisted_folder",+ persisted_folder.PersistedFolderViewSet,+ "environment_persisted_folder",+ ["team_id"],+)++projects_router.register(+ r"desktop_persisted_folder",+ persisted_folder.DesktopPersistedFolderViewSet,+ "project_desktop_persisted_folder",+ ["team_id"],+)++register_legacy_dual_route_team_nested_viewset(+ r"user_product_list",+ user_product_list.UserProductListViewSet,+ "environment_user_product_list",+ ["team_id"],+)++projects_router.register(+ r"event_definitions",+ event_definition.EventDefinitionViewSet,+ "project_event_definitions",+ ["project_id"],+)+projects_router.register(+ r"property_definitions",+ property_definition_api.PropertyDefinitionViewSet,+ "project_property_definitions",+ ["project_id"],+)+projects_router.register(+ r"schema_property_groups",+ schema_property_group.SchemaPropertyGroupViewSet,+ "project_schema_property_groups",+ ["project_id"],+)+projects_router.register(+ r"event_schemas",+ event_schema.EventSchemaViewSet,+ "project_event_schemas",+ ["project_id"],+)++projects_router.register(r"uploaded_media", uploaded_media.MediaViewSet, "project_media", ["project_id"])++projects_router.register(+ r"object_media_previews",+ object_media_preview.ObjectMediaPreviewViewSet,+ "project_object_media_previews",+ ["project_id"],+)++projects_router.register(r"tags", tagged_item.TaggedItemViewSet, "project_tags", ["project_id"])+register_legacy_dual_route_team_nested_viewset(r"query", query.QueryViewSet, "environment_query", ["team_id"])+++# Organizations nested endpoints+organizations_router = routers.add(+ "organizations", router.register(r"organizations", organization.OrganizationViewSet, "organizations")+)+organizations_router.register(r"projects", project.ProjectViewSet, "organization_projects", ["organization_id"])+organizations_router.register(+ r"integrations",+ organization_integration.OrganizationIntegrationViewSet,+ "organization_integrations",+ ["organization_id"],+)+organizations_router.register(+ r"oauth_applications",+ OrganizationOAuthApplicationViewSet,+ "organization_oauth_applications",+ ["organization_id"],+)+organizations_router.register(+ r"members",+ organization_member.OrganizationMemberViewSet,+ "organization_members",+ ["organization_id"],+)+organizations_router.register(+ r"invites",+ organization_invite.OrganizationInviteViewSet,+ "organization_invites",+ ["organization_id"],+)+organizations_router.register(+ r"domains",+ organization_domain.OrganizationDomainViewset,+ "organization_domains",+ ["organization_id"],+)+organizations_router.register(+ r"personal_api_keys",+ organization_personal_api_key.OrganizationPersonalAPIKeyViewSet,+ "organization_personal_api_keys",+ ["organization_id"],+)+organizations_router.register(+ r"cimd_verification_tokens",+ cimd_verification_token.CIMDVerificationTokenViewSet,+ "organization_cimd_verification_tokens",+ ["organization_id"],+)+organizations_router.register(+ r"proxy_records",+ proxy_record.ProxyRecordViewset,+ "proxy_records",+ ["organization_id"],+)+organizations_router.register(+ r"resource_transfers",+ resource_transfer.ResourceTransferViewSet,+ "organization_resource_transfers",+ ["organization_id"],+)+organizations_router.register(+ r"role_external_references",+ role_external_reference.RoleExternalReferenceViewSet,+ "organization_role_external_references",+ ["organization_id"],+)+organizations_router.register(+ r"welcome",+ welcome.WelcomeViewSet,+ "organization_welcome",+ ["organization_id"],+)+organizations_router.register(+ r"advanced_activity_logs",+ advanced_activity_logs.OrganizationAdvancedActivityLogsViewSet,+ "organization_advanced_activity_logs",+ ["organization_id"],+)++# General endpoints (shared across CH & PG)+router.register(r"login", authentication.LoginViewSet, "login")+router.register(r"login/dev", authentication.DevLoginViewSet, "login_dev")+router.register(r"login/token", authentication.TwoFactorViewSet, "login_token")+router.register(r"login/precheck", authentication.LoginPrecheckViewSet, "login_precheck")+router.register(r"login/email-mfa", authentication.EmailMFAViewSet, "login_email_mfa")+router.register(r"login/2fa/passkey", authentication.TwoFactorPasskeyViewSet, "login_2fa_passkey")+router.register(r"webauthn/register", webauthn.WebAuthnRegistrationViewSet, "webauthn_register")+router.register(r"webauthn/signup-register", webauthn.WebAuthnSignupRegistrationViewSet, "webauthn_signup_register")+router.register(r"webauthn/login", webauthn.WebAuthnLoginViewSet, "webauthn_login")+router.register(r"webauthn/credentials", webauthn.WebAuthnCredentialViewSet, "webauthn_credentials")+router.register(r"reset", authentication.PasswordResetViewSet, "password_reset")+users_router = router.register(r"users", user.UserViewSet, "users")+users_router.register(+ r"integrations",+ user_integration.UserIntegrationViewSet,+ "user_integration",+ ["uuid"],+)+users_router.register(+ r"push_tokens",+ user_push_token.UserPushTokenViewSet,+ "user_push_token",+ ["uuid"],+)+router.register(+ r"user_home_settings",+ user_home_settings.UserHomeSettingsViewSet,+ "user_home_settings",+)+router.register(r"personal_api_keys", personal_api_key.PersonalAPIKeyViewSet, "personal_api_keys")+router.register(r"cli-auth", cli_auth.CLIAuthViewSet, "cli_auth")+router.register(r"instance_status", instance_status.InstanceStatusViewSet, "instance_status")+router.register(r"dead_letter_queue", dead_letter_queue.DeadLetterQueueViewSet, "dead_letter_queue")+router.register(r"async_migrations", async_migration.AsyncMigrationsViewset, "async_migrations")+router.register(r"instance_settings", instance_settings.InstanceSettingsViewset, "instance_settings")+router.register(r"debug_ch_queries", debug_ch_queries.DebugCHQueries, "debug_ch_queries")+router.register(r"query_performance_proxy", QueryPerformanceProxyViewSet, "query_performance_proxy")++from posthog.api.cohort import CohortViewSet, LegacyCohortViewSet # noqa: E402+from posthog.api.element import ElementViewSet, LegacyElementViewSet # noqa: E402+from posthog.api.event import EventViewSet, LegacyEventViewSet # noqa: E402+from posthog.api.person import LegacyPersonViewSet, PersonViewSet # noqa: E402+from posthog.api.web_experiment import WebExperimentViewSet # noqa: E402++# Legacy endpoints CH (to be removed eventually)+router.register(r"cohort", LegacyCohortViewSet, basename="cohort")+router.register(r"element", LegacyElementViewSet, basename="element")+router.register(r"event", LegacyEventViewSet, basename="event")++# Nested endpoints CH+register_legacy_dual_route_team_nested_viewset(r"events", EventViewSet, "environment_events", ["team_id"])+projects_router.register(r"web_experiments", WebExperimentViewSet, "web_experiments", ["project_id"])+projects_router.register(r"cohorts", CohortViewSet, "project_cohorts", ["project_id"])++register_legacy_dual_route_team_nested_viewset(+ r"elements",+ ElementViewSet,+ "environment_elements",+ ["team_id"], # TODO: Can be removed?+)++legacy_project_session_recordings_router, environment_sessions_recordings_router = (+ register_legacy_dual_route_team_nested_viewset(+ r"session_recordings",+ SessionRecordingViewSet,+ "environment_session_recordings",+ ["team_id"],+ )+)++register_legacy_dual_route_team_nested_viewset(+ r"session_recording_external_references",+ SessionRecordingExternalReferenceViewSet,+ "project_session_recording_external_references",+ ["team_id"],+)++register_legacy_dual_route_team_nested_viewset(+ r"session_recording_playlists",+ SessionRecordingPlaylistViewSet,+ "environment_session_recording_playlist",+ ["team_id"],+)++register_legacy_dual_route_team_nested_viewset(r"sessions", SessionViewSet, "environment_sessions", ["team_id"])++if EE_AVAILABLE:+ from ee.clickhouse.views.groups import GroupsTypesViewSet, GroupsViewSet, GroupUsageMetricViewSet+ from ee.clickhouse.views.person import EnterprisePersonViewSet, LegacyEnterprisePersonViewSet++ register_legacy_dual_route_team_nested_viewset(r"groups", GroupsViewSet, "environment_groups", ["team_id"])+ group_types_router = projects_router.register(+ r"groups_types", GroupsTypesViewSet, "project_groups_types", ["project_id"]+ )+ group_types_router.register(+ r"metrics", GroupUsageMetricViewSet, "project_groups_metrics", ["project_id", "group_type_index"]+ )+ register_legacy_dual_route_team_nested_viewset(+ r"persons", EnterprisePersonViewSet, "environment_persons", ["team_id"]+ )+ router.register(r"person", LegacyEnterprisePersonViewSet, "persons")+ vercel_installations_router = router.register(+ r"vercel/v1/installations",+ vercel_installation.VercelInstallationViewSet,+ "vercel_installations",+ )+ vercel_installations_router.register(+ r"resources",+ vercel_resource.VercelResourceViewSet,+ "vercel_installation_resources",+ ["installation_id"],+ )+ router.register(+ r"vercel/v1/products",+ vercel_product.VercelProductViewSet,+ "vercel_products",+ )+ router.register(+ r"vercel/proxy",+ vercel_proxy.VercelProxyViewSet,+ "vercel_proxy",+ )++else:+ register_legacy_dual_route_team_nested_viewset(r"persons", PersonViewSet, "environment_persons", ["team_id"])+ router.register(r"person", LegacyPersonViewSet, "persons")++# session_recordings sharing nest stays central — the session_recordings viewsets+# still live under posthog/session_recordings/ rather than in a product folder.+environment_sessions_recordings_router.register(+ r"sharing",+ sharing.SharingConfigurationViewSet,+ "environment_recording_sharing",+ ["team_id", "recording_id"],+)+legacy_project_session_recordings_router.register(+ r"sharing",+ sharing.SharingConfigurationViewSet,+ "project_recording_sharing",+ ["team_id", "recording_id"],+)++projects_router.register(+ r"session_group_summaries",+ SessionGroupSummaryViewSet,+ "project_session_group_summaries",+ ["project_id"],+)++projects_router.register(+ r"single_session_summaries",+ SingleSessionSummaryViewSet,+ "project_single_session_summaries",+ ["project_id"],+)++register_legacy_dual_route_team_nested_viewset(+ r"quick_filters",+ quick_filters.QuickFilterViewSet,+ "project_quick_filters",+ ["team_id"],+)+++projects_router.register(+ r"comments",+ comments.CommentViewSet,+ "project_comments",+ ["project_id"],+)+++projects_router.register(+ r"hog",+ hog.HogViewSet,+ "hog",+ ["team_id"],+)++register_legacy_dual_route_team_nested_viewset(+ r"metalytics",+ metalytics.MetalyticsViewSet,+ "environment_metalytics",+ ["team_id"],+)++projects_router.register(r"search", search.SearchViewSet, "project_search", ["project_id"])++register_legacy_dual_route_team_nested_viewset(+ r"project_secret_api_keys",+ project_secret_api_key.ProjectSecretAPIKeyViewSet,+ "environment_project_secret_api_keys",+ ["team_id"],+)++register_legacy_dual_route_team_nested_viewset(+ r"data_color_themes", data_color_theme.DataColorThemeViewSet, "environment_data_color_themes", ["team_id"]+)++register_legacy_dual_route_team_nested_viewset(+ r"web_vitals",+ web_vitals.WebVitalsViewSet,+ "project_web_vitals",+ ["team_id"],+)++router.register(r"wizard", wizard.SetupWizardViewSet, "wizard")+++register_legacy_dual_route_team_nested_viewset(+ r"csp-reporting",+ CSPReportingViewSet,+ "project_csp_reporting",+ ["team_id"],+)+++projects_router.register(r"js-snippet", JsSnippetViewSet, "project_js_snippet", ["team_id"])+++register_legacy_dual_route_team_nested_viewset(+ r"change_requests",+ approval_api.ChangeRequestViewSet,+ "project_change_requests",+ ["team_id"],+)++register_legacy_dual_route_team_nested_viewset(+ r"approval_policies",+ approval_api.ApprovalPolicyViewSet,+ "project_approval_policies",+ ["team_id"],+)++register_legacy_dual_route_team_nested_viewset(+ r"core_events",+ CoreEventViewSet,+ "project_core_events",+ ["team_id"],+)+++# --- Product route auto-discovery -----------------------------------------------------+# Every parent above (root + projects + environments + organizations) and all of core's+# own routes are registered before this loop. Migrated products then register themselves+# by exposing `register_routes(routers)` in `products/<name>/backend/routes.py`; the loop+# finds them via INSTALLED_APPS, so adding a product needs no edit here.+#+# Why a loop here, and why eager (not AppConfig.ready()):+# - ROOT_URLCONF is imported lazily on first URL resolution, not during django.setup().+# `posthog/urls.py` imports this module, so the whole API surface loads at first+# request and never at boot — Celery workers and management commands that never+# resolve a URL never import it. We keep that.+# - ready()-based self-registration would run inside django.setup() in every process,+# and registering a route imports its viewset class — so it would drag the entire+# product API into setup() everywhere, regressing that laziness. Running the loop at+# import of `posthog.api` (i.e. first request) keeps the API out of setup().+# - Net: core still triggers registration (via the existing `posthog.api` import) rather+# than products self-pushing — you can have "core imports nothing statically" OR "API+# stays out of setup()", not both; we keep the API lazy.+#+# Order-independence: products only nest onto the four core-owned parents and never onto+# each other, and all parents exist before this loop, so iteration order does not affect+# the resolved route set. `RouterRegistry.add()` rejects product callers, making+# "parents stay core-owned" an enforced invariant rather than a convention.+#+# Accepted cost: routes are imported dynamically here, so the core->product import edges+# are not statically visible to import tooling (tach/grimp). Accepted on purpose — it+# removes the hand-maintained product list that duplicated PRODUCTS_APPS.+for _app_config in apps.get_app_configs():+ if not _app_config.name.startswith("products."):+ continue+ _routes_module = f"{_app_config.name}.routes"+ # find_spec (not try/except ImportError) so a real ImportError inside a routes.py+ # surfaces instead of being silently swallowed as "no routes module".+ if importlib.util.find_spec(_routes_module) is None:+ continue+ _register_routes = getattr(importlib.import_module(_routes_module), "register_routes", None)+ if callable(_register_routes):+ _register_routes(routers)diff --git a/posthog/api/tagged_item.py b/posthog/api/tagged_item.pyindex 5fb5b5cd0b29..25e7779199ac 100644--- a/posthog/api/tagged_item.py+++ b/posthog/api/tagged_item.py@@ -1,6 +1,5 @@-import dataclasses-from collections.abc import Callable, Sequence-from typing import Any, Literal, Optional, cast+from collections.abc import Sequence+from typing import Any, castfrom django.db import modelsfrom django.db.models import Prefetch, Q, QuerySet, prefetch_related_objects@@ -12,15 +11,6 @@ from rest_framework.viewsets import GenericViewSetfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import actionfrom posthog.models import Tag, TaggedItem-from posthog.models.activity_logging.activity_log import (- ActivityContextBase,- Change,- Detail,- changes_between,- log_activity,-)-from posthog.models.activity_logging.tag_utils import get_tagged_item_related_object_info-from posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.models.tag import tagifyfrom posthog.rbac.user_access_control import access_level_satisfied_for_resource@@ -291,135 +281,3 @@ class TaggedItemViewSet(TeamAndOrgViewSetMixin, GenericViewSet):return response.Response(Tag.objects.filter(team=self.team).values_list("name", flat=True).distinct().order_by("name"))--[email protected](frozen=True)-class TagContext(ActivityContextBase):- team_id: int- name: str--[email protected](frozen=True)-class TaggedItemContext(ActivityContextBase):- tag_name: str- tag_id: str- team_id: int- related_object_type: Optional[str] = None- related_object_id: Optional[str] = None- related_object_name: Optional[str] = None---@mutable_receiver(model_activity_signal, sender=Tag)-def handle_tag_change(sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs):- context = TagContext(- team_id=after_update.team_id,- name=after_update.name,- )-- log_activity(- organization_id=after_update.team.organization_id if after_update.team else None,- team_id=after_update.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=after_update.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(scope, previous=before_update, current=after_update),- name=after_update.name,- context=context,- ),- )--[email protected](frozen=True)-class RelatedObjectActivityLogger:- """How to mirror a TaggedItem activity onto a related object's activity stream.-- `scope` is used as both the `log_activity(scope=...)` and `Change.type` value.- `resolve_name` derives the display name for the activity row; the default- just returns the precomputed `related_object_name`.- """-- scope: str- resolve_name: Callable[[TaggedItem, Optional[str]], Optional[str]] = lambda tagged_item, default_name: default_name---RELATED_OBJECT_ACTIVITY_LOGGERS: dict[str, RelatedObjectActivityLogger] = {- "ticket": RelatedObjectActivityLogger(- scope="Ticket",- resolve_name=lambda tagged_item, default_name: (- f"Ticket #{tagged_item.ticket.ticket_number}" if tagged_item.ticket else default_name- ),- ),- "account": RelatedObjectActivityLogger(scope="Account"),- "endpoint": RelatedObjectActivityLogger(scope="Endpoint"),-}---@mutable_receiver(model_activity_signal, sender=TaggedItem)-def handle_tagged_item_change(- sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs-):- # Use after_update for create/update, before_update for delete- tagged_item = after_update or before_update-- if not tagged_item or not tagged_item.tag:- return-- related_object_type, related_object_id, related_object_name = get_tagged_item_related_object_info(tagged_item)-- context = TaggedItemContext(- tag_name=tagged_item.tag.name,- tag_id=str(tagged_item.tag.id),- team_id=tagged_item.tag.team_id,- related_object_type=related_object_type,- related_object_id=related_object_id,- related_object_name=related_object_name,- )-- team = tagged_item.tag.team- organization_id = team.organization_id if team else None- team_id = tagged_item.tag.team_id-- log_activity(- organization_id=organization_id,- team_id=team_id,- user=user,- was_impersonated=was_impersonated,- item_id=tagged_item.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(scope, previous=before_update, current=after_update),- name=tagged_item.tag.name,- context=context,- ),- )-- # Mirror the tag change onto the related object's own activity stream- # (e.g. so a tag added to a Ticket shows up on that ticket's timeline).- related_logger = RELATED_OBJECT_ACTIVITY_LOGGERS.get(related_object_type or "")- if related_logger and related_object_id:- tag_action: Literal["created", "deleted"] = "created" if activity == "created" else "deleted"- log_activity(- organization_id=organization_id,- team_id=team_id,- user=user,- was_impersonated=was_impersonated,- item_id=related_object_id,- scope=related_logger.scope,- activity="updated",- detail=Detail(- name=related_logger.resolve_name(tagged_item, related_object_name),- changes=[- Change(- type=related_logger.scope,- field="tag",- action=tag_action,- after=tagged_item.tag.name if activity == "created" else None,- before=tagged_item.tag.name if activity == "deleted" else None,- )- ],- ),- )diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.pyindex 4eb371956d30..8d7b8f3c0490 100644--- a/posthog/api/test/test_authentication.py+++ b/posthog/api/test/test_authentication.py@@ -33,7 +33,7 @@ from rest_framework.test import APIRequestFactoryfrom social_django.models import UserSocialAuthfrom two_factor.utils import totp_digits-from posthog.api.authentication import password_reset_token_generator, post_login, social_login_notification+from posthog.api.authentication import password_reset_token_generator, social_login_notificationfrom posthog.auth import (InternalAPIUser,OAuthAccessTokenAuthentication,@@ -51,6 +51,7 @@ from posthog.helpers.user_devices import ()from posthog.middleware import KnownLoginDeviceCookieMiddlewarefrom posthog.models import User+from posthog.models.activity_logging.signal_handlers import post_loginfrom posthog.models.instance_setting import set_instance_settingfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization import Organization, OrganizationMembershipdiff --git a/posthog/apps.py b/posthog/apps.pyindex 4e72296d61ef..35079e3783eb 100644--- a/posthog/apps.py+++ b/posthog/apps.py@@ -31,6 +31,14 @@ class PostHogConfig(AppConfig):connect_signal_handlers()+ # Connect core signal receivers at app-population. They used to wire in as an import+ # side effect of viewset modules; with the lazy API router those no longer load at+ # django.setup(), so a process that never builds the router (celery, temporal, migrate,+ # shell) would lose them. They live in dedicated import-light modules — never wire+ # ready() through an API module, even one that looks light today.+ import posthog.caching.organization_serializer_cache # noqa: F401, PLC0415+ import posthog.models.activity_logging.signal_handlers # noqa: F401, PLC0415+self._setup_lazy_admin()self._prewarm_timezone_offsets_cache()posthoganalytics.api_key = "sTMFPsFhdP1Ssg" # ty: ignore[invalid-assignment]diff --git a/posthog/asgi.py b/posthog/asgi.pyindex a56291b00749..c75b13ca75d9 100644--- a/posthog/asgi.py+++ b/posthog/asgi.py@@ -1,3 +1,4 @@+import gcimport os# Django Imports@@ -100,4 +101,20 @@ def task_run_event_ingest_wrapper(func):return inner-application = lifetime_wrapper(self_capture_wrapper(task_run_event_ingest_wrapper(get_asgi_application())))+# Boot allocations are almost all permanent, so cyclic GC during django.setup() only adds+# pauses (~300ms). Disable it for the boot, then freeze the survivors so later full+# collections skip them — which also maximizes copy-on-write sharing when a prototype+# process forks workers. See docs/internal/django-startup-time.md.+gc.disable()+try:+ application = lifetime_wrapper(self_capture_wrapper(task_run_event_ingest_wrapper(get_asgi_application())))++ # Resolve the URLconf now, at module load — the lazy API router otherwise builds on+ # each worker's first live request (probes short-circuit in middleware and never warm+ # it). See the matching block in wsgi.py for the full reasoning.+ from django.urls import get_resolver++ _ = get_resolver().url_patterns # property access triggers the build+finally:+ gc.freeze()+ gc.enable()diff --git a/posthog/caching/organization_serializer_cache.py b/posthog/caching/organization_serializer_cache.pynew file mode 100644index 000000000000..ec528e1c9413--- /dev/null+++ b/posthog/caching/organization_serializer_cache.py@@ -0,0 +1,118 @@+"""Org-serializer cache versioning and its invalidation receivers.++The OrganizationSerializer caches expensive per-org fields (teams, projects, member count)+under a per-organization version number; writes to any membership-shaped model bump the+version. The receivers must connect at django.setup() — background writes (celery, temporal,+migrate) invalidate too, not just API mutations — so this lives in its own import-light+module wired from PostHogConfig.ready(), not in the API module whose import the lazy router+no longer triggers at setup.+"""++from collections.abc import Callable+from typing import Any++from django.core.cache import cache+from django.db import transaction+from django.db.models import Model+from django.db.models.signals import post_delete, post_save++from posthog.models.organization import OrganizationMembership+from posthog.models.project import Project+from posthog.models.team import Team+from posthog.utils import get_safe_cache++from ee.models.explicit_team_membership import ExplicitTeamMembership+from ee.models.rbac.access_control import AccessControl+from ee.models.rbac.role import RoleMembership++ORG_SERIALIZER_CACHE_TTL_SECONDS = 60 * 60+ORG_SERIALIZER_VERSION_TTL_SECONDS = 7 * 24 * 60 * 60+_ORG_SERIALIZER_VERSION_KEY_PREFIX = "org_serializer_version:"+++def _org_serializer_version_key(organization_id: str) -> str:+ return f"{_ORG_SERIALIZER_VERSION_KEY_PREFIX}{organization_id}"+++def _org_serializer_cache_version(organization_id: str) -> int:+ key = _org_serializer_version_key(organization_id)+ raw = get_safe_cache(key)+ if raw is None:+ try:+ cache.add(key, 0, timeout=ORG_SERIALIZER_VERSION_TTL_SECONDS)+ except Exception:+ pass+ return 0+ try:+ return int(raw)+ except (TypeError, ValueError):+ return 0+++def _bump_org_serializer_cache_version(organization_id: str) -> None:+ key = _org_serializer_version_key(organization_id)+ try:+ cache.incr(key)+ except ValueError:+ try:+ cache.add(key, 1, timeout=ORG_SERIALIZER_VERSION_TTL_SECONDS)+ except Exception:+ pass+ except Exception:+ pass+++def _instance_org_id(instance: Any) -> str | None:+ organization_id = getattr(instance, "organization_id", None)+ return str(organization_id) if organization_id is not None else None+++def _team_id_to_org_id(instance: Any) -> str | None:+ team_id = getattr(instance, "team_id", None)+ if team_id is None:+ return None+ organization_id = Team.objects.filter(id=team_id).values_list("organization_id", flat=True).first()+ return str(organization_id) if organization_id is not None else None+++def _role_id_to_org_id(instance: Any) -> str | None:+ role = getattr(instance, "role", None)+ if role is None:+ return None+ organization_id = getattr(role, "organization_id", None)+ return str(organization_id) if organization_id is not None else None+++_VISIBILITY_RESOURCES = {"project", "organization"}+++def _access_control_to_org_id(instance: Any) -> str | None:+ if getattr(instance, "resource", None) not in _VISIBILITY_RESOURCES:+ return None+ return _team_id_to_org_id(instance)+++_INVALIDATION_SOURCES: list[tuple[type[Model], Callable[[Any], str | None]]] = [+ (Team, _instance_org_id),+ (Project, _instance_org_id),+ (OrganizationMembership, _instance_org_id),+ (AccessControl, _access_control_to_org_id),+ (ExplicitTeamMembership, _team_id_to_org_id),+ (RoleMembership, _role_id_to_org_id),+]+++def _connect_invalidation(model: type[Model], get_org_id: Callable[[Any], str | None]) -> None:+ def receiver_fn(sender: type[Model], instance: Any, **kwargs: Any) -> None:+ organization_id = get_org_id(instance)+ if organization_id is None:+ return+ _bump_org_serializer_cache_version(organization_id)+ transaction.on_commit(lambda: _bump_org_serializer_cache_version(organization_id))++ post_save.connect(receiver_fn, sender=model, weak=False)+ post_delete.connect(receiver_fn, sender=model, weak=False)+++for _model, _resolver in _INVALIDATION_SOURCES:+ _connect_invalidation(_model, _resolver)diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.pyindex 5933b7273e0a..f5563dee1184 100644--- a/posthog/clickhouse/client/connection.py+++ b/posthog/clickhouse/client/connection.py@@ -4,17 +4,16 @@ from collections.abc import Mappingfrom contextlib import contextmanagerfrom enum import StrEnumfrom functools import cache+from typing import TYPE_CHECKINGfrom django.conf import settings-from clickhouse_connect import get_client-from clickhouse_connect.driver import (- Client as HttpClient,- httputil,-)from clickhouse_driver import Client as SyncClientfrom clickhouse_pool import ChPool+if TYPE_CHECKING:+ from clickhouse_connect.driver import Client as HttpClient+from posthog.clickhouse.workload import Workloadfrom posthog.settings import data_storesfrom posthog.utils import patchable@@ -129,7 +128,7 @@ def get_clickhouse_creds(user: ClickHouseUser) -> tuple[str, str]:class ProxyClient:- def __init__(self, client: HttpClient):+ def __init__(self, client: "HttpClient"):self._client = clientdef execute(@@ -166,17 +165,26 @@ class ProxyClient:pass-_clickhouse_http_pool_mgr = httputil.get_pool_manager(- maxsize=settings.CLICKHOUSE_CONN_POOL_MAX, # max number of open connection per pool- block=True, # makes the maxsize limit per pool, keeps connections- num_pools=12, # number of pools- ca_cert=settings.CLICKHOUSE_CA,- verify=settings.QUERYSERVICE_VERIFY,-)+@cache+def _clickhouse_http_pool_mgr():+ # clickhouse_connect probes pandas/numpy availability when imported, dragging pandas and+ # pyarrow (~400ms) onto the path of whoever imports it — and this module loads at+ # django.setup(). Only the HTTP client paths need it, so build the pool manager on demand.+ from clickhouse_connect.driver import httputil # noqa: PLC0415++ return httputil.get_pool_manager(+ maxsize=settings.CLICKHOUSE_CONN_POOL_MAX, # max number of open connection per pool+ block=True, # makes the maxsize limit per pool, keeps connections+ num_pools=12, # number of pools+ ca_cert=settings.CLICKHOUSE_CA,+ verify=settings.QUERYSERVICE_VERIFY,+ )@contextmanagerdef get_http_client(**overrides):+ from clickhouse_connect import get_client # noqa: PLC0415+kwargs = {"host": settings.CLICKHOUSE_HOST,"database": settings.CLICKHOUSE_DATABASE,@@ -188,7 +196,7 @@ def get_http_client(**overrides):"send_receive_timeout": 30 if settings.TEST else 999_999_999,"autogenerate_session_id": True,# beware, this makes each query to run in a separate session - no temporary tables will work- "pool_mgr": _clickhouse_http_pool_mgr,+ "pool_mgr": _clickhouse_http_pool_mgr(),**overrides,}yield ProxyClient(get_client(**kwargs))diff --git a/posthog/clickhouse/client/execute.py b/posthog/clickhouse/client/execute.pyindex 8965ecf7493b..9f2479b25b00 100644--- a/posthog/clickhouse/client/execute.py+++ b/posthog/clickhouse/client/execute.py@@ -1,3 +1,4 @@+import sysimport timeimport typesimport logging@@ -38,7 +39,6 @@ from posthog.clickhouse.query_tagging import ()from posthog.errors import clickhouse_error_type, wrap_clickhouse_query_errorfrom posthog.settings import CLICKHOUSE_PER_TEAM_QUERY_SETTINGS, DEBUG, TEST-from posthog.temporal.common.clickhouse import update_query_tags_with_temporal_infofrom posthog.utils import generate_short_id, patchableQUERY_STARTED_COUNTER = Counter(@@ -363,8 +363,13 @@ def sync_execute(elif tags.feature == Feature.CACHE_WARMUP:ch_user = ClickHouseUser.CACHE_WARMUP- # update tags if inside temporal (should not)- update_query_tags_with_temporal_info()+ # update tags if inside temporal (should not). Only meaningful inside a Temporal activity,+ # and being in one implies temporalio is imported — so the gate keeps the helper's module+ # (aiohttp + pyarrow at module scope) off every other process's startup path.+ if "temporalio" in sys.modules:+ from posthog.temporal.common.clickhouse import update_query_tags_with_temporal_info # noqa: PLC0415++ update_query_tags_with_temporal_info()add_fallback_query_tags(tags)diff --git a/posthog/clickhouse/cluster.py b/posthog/clickhouse/cluster.pyindex 7de41a80fcba..4b91ad5fab4a 100644--- a/posthog/clickhouse/cluster.py+++ b/posthog/clickhouse/cluster.py@@ -9,9 +9,8 @@ from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence, Setfrom concurrent.futures import ALL_COMPLETED, FIRST_EXCEPTION, Future, ThreadPoolExecutor, as_completedfrom copy import copyfrom dataclasses import dataclass, field-from typing import Any, Generic, Literal, NamedTuple, Optional, TypeVar+from typing import Any, ClassVar, Generic, Literal, NamedTuple, Optional, TypeVar-import dagsterfrom clickhouse_driver import Clientfrom clickhouse_pool import ChPool@@ -20,7 +19,27 @@ from posthog.clickhouse.client.connection import NodeRole, Workload, _make_ch_pofrom posthog.settings import CLICKHOUSE_PER_TEAM_SETTINGSfrom posthog.settings.data_stores import CLICKHOUSE_CLUSTER-logger = dagster.get_dagster_logger("clickhouse")++class _LazyDagsterLogger:+ """Defer `import dagster` (~320ms) off this module's import. cluster.py loads very early at+ django.setup() (via posthog.errors -> the clickhouse client), but the dagster logger is only+ needed when a log call actually fires. get_dagster_logger() resolves the dagster run context at+ emit time, so caching one instance here matches the previous module-level behavior — no change to+ log routing inside dagster ops, just no dagster import for the web/migrate/shell/celery processes+ that never log from here.+ """++ _logger: ClassVar[logging.Logger | None] = None++ def __getattr__(self, name: str) -> Any:+ if _LazyDagsterLogger._logger is None:+ import dagster # noqa: PLC0415++ _LazyDagsterLogger._logger = dagster.get_dagster_logger("clickhouse")+ return getattr(_LazyDagsterLogger._logger, name)+++logger = _LazyDagsterLogger()def ON_CLUSTER_CLAUSE(on_cluster=True):diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex fdc4a17a5b4a..cd1341bf13c6 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -160,7 +160,6 @@ from posthog.synthetic_user import SyntheticUserfrom products.data_tools.backend.models.join import DataWarehouseJoinfrom products.data_warehouse.backend.sync_status import get_warehouse_sync_warningsfrom products.revenue_analytics.backend.views import RevenueAnalyticsBaseView-from products.revenue_analytics.backend.views.orchestrator import build_all_revenue_analytics_viewsfrom products.warehouse_sources.backend.models.credential import DataWarehouseCredentialfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema@@ -1071,6 +1070,10 @@ class Database(BaseModel):if not is_direct_query:try:if not is_managed_viewset_enabled:+ from products.revenue_analytics.backend.views.orchestrator import ( # noqa: PLC0415+ build_all_revenue_analytics_views,+ )+revenue_views = list(build_all_revenue_analytics_views(team, timings))except Exception as e:capture_exception(e)diff --git a/posthog/hogql/resolver_utils.py b/posthog/hogql/resolver_utils.pyindex b9e5be3a2381..db673b45a36a 100644--- a/posthog/hogql/resolver_utils.py+++ b/posthog/hogql/resolver_utils.py@@ -4,6 +4,8 @@ import difflibfrom collections.abc import Generatorfrom typing import Optional+from pydantic import BaseModel+from posthog.hogql import astfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.models import (@@ -220,7 +222,7 @@ def ast_to_query_node(expr: ast.Expr | ast.HogQLXTag):return tuple(ast_to_query_node(e) for e in expr.exprs)elif isinstance(expr, ast.HogQLXTag):for klass in schema.__dict__.values():- if isinstance(klass, type) and issubclass(klass, schema.BaseModel) and klass.__name__ == expr.kind:+ if isinstance(klass, type) and issubclass(klass, BaseModel) and klass.__name__ == expr.kind:attributes = expr.to_dict()attributes.pop("kind")# Query runners use "source" instead of "children" for their source querydiff --git a/posthog/models/__init__.py b/posthog/models/__init__.pyindex 11bbaa4e8c53..1fc1be2ea2d6 100644--- a/posthog/models/__init__.py+++ b/posthog/models/__init__.py@@ -2,6 +2,7 @@# You should try and make them alphabetically sorted manually if possible# isort: skip_filefrom ..session_recordings.models.session_recording import SessionRecording+from ..session_recordings.models.session_recording_external_reference import SessionRecordingExternalReferencefrom ..session_recordings.models.session_recording_playlist import SessionRecordingPlaylistfrom ..session_recordings.models.session_recording_playlist_item import SessionRecordingPlaylistItemfrom ._deprecated_prompts import Prompt, PromptSequence, UserPromptState@@ -29,6 +30,7 @@ from .role_external_reference import RoleExternalReferencefrom .file_system.file_system import FileSystemfrom .file_system.folder_instructions import FileSystemFolderInstructionsfrom .file_system.file_system_view_log import FileSystemViewLog+from .file_system.persisted_folder import PersistedFolderfrom .filters import Filter, RetentionFilterfrom .group import Groupfrom .group_usage_metric import GroupUsageMetric@@ -114,6 +116,7 @@ __all__ = ["FileSystem","FileSystemFolderInstructions","FileSystemViewLog",+ "PersistedFolder","Filter","Group","GroupUsageMetric",@@ -161,6 +164,7 @@ __all__ = ["SchemaPropertyGroupProperty","SessionRecording","SessionRecordingPlaylist",+ "SessionRecordingExternalReference","SessionRecordingPlaylistItem","SharePassword","SharingConfiguration",diff --git a/posthog/models/activity_logging/signal_handlers.py b/posthog/models/activity_logging/signal_handlers.pyindex da25dd0b2f5b..ee47d4455944 100644--- a/posthog/models/activity_logging/signal_handlers.py+++ b/posthog/models/activity_logging/signal_handlers.py@@ -1,7 +1,11 @@+import timeimport inspectimport dataclasses+from collections.abc import Callablefrom datetime import timedelta+from typing import Literal, Optional+from django.conf import settingsfrom django.contrib.auth import get_user_modelfrom django.contrib.auth.signals import user_logged_in, user_logged_outfrom django.core.signing import TimestampSigner@@ -12,21 +16,36 @@ from django.http import HttpRequestimport structlogfrom loginas import settings as la_settingsfrom loginas.utils import is_impersonated_session+from prometheus_client import Counter+from posthog.caching.login_device_cache import check_and_cache_login_devicefrom posthog.constants import AUTH_BACKEND_DISPLAY_NAMESfrom posthog.exceptions_capture import capture_exception+from posthog.geoip import get_geoip_propertiesfrom posthog.helpers.impersonation import get_original_user_from_session+from posthog.models import Organization, PersonalAPIKey, Tag, TaggedItemfrom posthog.models.activity_logging.activity_log import (ActivityContextBase,ActivityScope,+ Change,Detail,LogActivityEntry,bulk_log_activity,changes_between,log_activity,)+from posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonated+from posthog.models.activity_logging.personal_api_key_utils import (+ log_personal_api_key_activity,+ log_personal_api_key_scope_change,+)+from posthog.models.activity_logging.project_secret_api_key_utils import log_project_secret_api_key_activity+from posthog.models.activity_logging.tag_utils import get_tagged_item_related_object_infofrom posthog.models.activity_logging.utils import activity_storage+from posthog.models.organization import OrganizationMembershipfrom posthog.models.organization_domain import OrganizationDomain+from posthog.models.organization_invite import OrganizationInvite+from posthog.models.project_secret_api_key import ProjectSecretAPIKeyfrom posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.models.user import Userfrom posthog.utils import get_ip_address, get_short_user_agent@@ -400,3 +419,352 @@ def handle_experiment_to_saved_metric_change(type="saved_metric_config",),)+++# --- Receivers relocated from posthog.api viewset modules ---------------------------------+# These used to live next to their viewsets and wired in as an import side effect of the+# eager API router. With the lazy router, AppConfig.ready() imports this module instead, so+# they connect in every process — importing a 400+ line DRF module at setup just for its+# receivers proved rot-prone (the module gains heavy imports, setup silently inherits them).++[email protected](frozen=True)+class TagContext(ActivityContextBase):+ team_id: int+ name: str++[email protected](frozen=True)+class TaggedItemContext(ActivityContextBase):+ tag_name: str+ tag_id: str+ team_id: int+ related_object_type: Optional[str] = None+ related_object_id: Optional[str] = None+ related_object_name: Optional[str] = None+++@mutable_receiver(model_activity_signal, sender=Tag)+def handle_tag_change(sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs):+ context = TagContext(+ team_id=after_update.team_id,+ name=after_update.name,+ )++ log_activity(+ organization_id=after_update.team.organization_id if after_update.team else None,+ team_id=after_update.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=after_update.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=after_update.name,+ context=context,+ ),+ )++[email protected](frozen=True)+class RelatedObjectActivityLogger:+ """How to mirror a TaggedItem activity onto a related object's activity stream.++ `scope` is used as both the `log_activity(scope=...)` and `Change.type` value.+ `resolve_name` derives the display name for the activity row; the default+ just returns the precomputed `related_object_name`.+ """++ scope: str+ resolve_name: Callable[[TaggedItem, Optional[str]], Optional[str]] = lambda tagged_item, default_name: default_name+++RELATED_OBJECT_ACTIVITY_LOGGERS: dict[str, RelatedObjectActivityLogger] = {+ "ticket": RelatedObjectActivityLogger(+ scope="Ticket",+ resolve_name=lambda tagged_item, default_name: (+ f"Ticket #{tagged_item.ticket.ticket_number}" if tagged_item.ticket else default_name+ ),+ ),+ "account": RelatedObjectActivityLogger(scope="Account"),+ "endpoint": RelatedObjectActivityLogger(scope="Endpoint"),+}+++@mutable_receiver(model_activity_signal, sender=TaggedItem)+def handle_tagged_item_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ # Use after_update for create/update, before_update for delete+ tagged_item = after_update or before_update++ if not tagged_item or not tagged_item.tag:+ return++ related_object_type, related_object_id, related_object_name = get_tagged_item_related_object_info(tagged_item)++ context = TaggedItemContext(+ tag_name=tagged_item.tag.name,+ tag_id=str(tagged_item.tag.id),+ team_id=tagged_item.tag.team_id,+ related_object_type=related_object_type,+ related_object_id=related_object_id,+ related_object_name=related_object_name,+ )++ team = tagged_item.tag.team+ organization_id = team.organization_id if team else None+ team_id = tagged_item.tag.team_id++ log_activity(+ organization_id=organization_id,+ team_id=team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=tagged_item.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=tagged_item.tag.name,+ context=context,+ ),+ )++ # Mirror the tag change onto the related object's own activity stream+ # (e.g. so a tag added to a Ticket shows up on that ticket's timeline).+ related_logger = RELATED_OBJECT_ACTIVITY_LOGGERS.get(related_object_type or "")+ if related_logger and related_object_id:+ tag_action: Literal["created", "deleted"] = "created" if activity == "created" else "deleted"+ log_activity(+ organization_id=organization_id,+ team_id=team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=related_object_id,+ scope=related_logger.scope,+ activity="updated",+ detail=Detail(+ name=related_logger.resolve_name(tagged_item, related_object_name),+ changes=[+ Change(+ type=related_logger.scope,+ field="tag",+ action=tag_action,+ after=tagged_item.tag.name if activity == "created" else None,+ before=tagged_item.tag.name if activity == "deleted" else None,+ )+ ],+ ),+ )+++@mutable_receiver(model_activity_signal, sender=Organization)+def handle_organization_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ log_activity(+ organization_id=after_update.id,+ team_id=None,+ user=user,+ was_impersonated=was_impersonated,+ item_id=after_update.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=after_update.name,+ ),+ )++[email protected](frozen=True)+class OrganizationMembershipContext(ActivityContextBase):+ organization_id: str+ organization_name: str+ user_id: str+ user_email: str+ user_name: str+ level: str++[email protected](frozen=True)+class OrganizationInviteContext(ActivityContextBase):+ organization_id: str+ organization_name: str+ target_email: str+ inviter_user_id: str | None+ inviter_user_email: str | None+ inviter_user_name: str | None+ level: str+++@mutable_receiver(model_activity_signal, sender=OrganizationMembership)+def handle_organization_membership_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ # Use after_update for create/update, before_update for delete+ membership = after_update or before_update++ if not membership:+ return++ member_user = membership.user+ member_name = f"{member_user.first_name} {member_user.last_name}".strip()++ context = OrganizationMembershipContext(+ organization_id=str(membership.organization_id),+ organization_name=membership.organization.name,+ user_id=str(member_user.id),+ user_email=member_user.email,+ user_name=member_name,+ level=str(OrganizationMembership.Level(membership.level).label),+ )++ if activity == "created":+ detail_name = f"{member_name} ({member_user.email}) joined {membership.organization.name}"+ elif activity == "deleted":+ detail_name = f"{member_name} ({member_user.email}) left {membership.organization.name}"+ else:+ detail_name = f"{member_name} ({member_user.email}) membership updated in {membership.organization.name}"++ log_activity(+ organization_id=membership.organization_id,+ team_id=None,+ user=user,+ was_impersonated=was_impersonated,+ item_id=membership.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=detail_name,+ context=context,+ ),+ )+++@mutable_receiver(model_activity_signal, sender=OrganizationInvite)+def handle_organization_invite_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ # Use after_update for create/update, before_update for delete+ invite = after_update or before_update++ if not invite:+ return++ inviter_user = invite.created_by+ inviter_name = f"{inviter_user.first_name} {inviter_user.last_name}".strip() if inviter_user else None++ context = OrganizationInviteContext(+ organization_id=str(invite.organization_id),+ organization_name=invite.organization.name,+ target_email=invite.target_email,+ inviter_user_id=str(inviter_user.id) if inviter_user else None,+ inviter_user_email=inviter_user.email if inviter_user else None,+ inviter_user_name=inviter_name,+ level=str(OrganizationMembership.Level(invite.level).label),+ )++ if activity == "created":+ if inviter_user:+ detail_name = f"User {inviter_name} ({inviter_user.email}) invited user {invite.target_email} into organization {invite.organization.name}"+ else:+ detail_name = f"User {invite.target_email} was invited to organization {invite.organization.name}"+ elif activity == "deleted":+ detail_name = f"Invite for {invite.target_email} to organization {invite.organization.name} was cancelled"+ else:+ detail_name = f"Invite for {invite.target_email} to organization {invite.organization.name} was updated"++ log_activity(+ organization_id=invite.organization_id,+ team_id=None,+ user=user,+ was_impersonated=was_impersonated,+ item_id=invite.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=detail_name,+ context=context,+ ),+ )+++@mutable_receiver(model_activity_signal, sender=PersonalAPIKey)+def handle_personal_api_key_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ changes = changes_between(scope, previous=before_update, current=after_update)++ # Check if scope changed (scoped_teams or scoped_organizations)+ scope_fields = ["scoped_teams", "scoped_organizations"]+ scope_changed = any(change.field in scope_fields for change in changes if change.field)++ if scope_changed and activity == "updated":+ # Filter out scope fields from changes as we dont want to present them to the user+ filtered_changes = [+ change for change in changes if change.field not in ["scoped_teams", "scoped_organizations"]+ ]+ log_personal_api_key_scope_change(before_update, after_update, user, was_impersonated, filtered_changes)+ else:+ log_personal_api_key_activity(after_update, activity, user, was_impersonated, changes)+++@receiver(pre_delete, sender=PersonalAPIKey)+def handle_personal_api_key_delete(sender, instance, **kwargs):+ from posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonated++ log_personal_api_key_activity(instance, "deleted", get_current_user(), get_was_impersonated())+++@mutable_receiver(model_activity_signal, sender=ProjectSecretAPIKey)+def handle_project_secret_api_key_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ changes = changes_between(scope, previous=before_update, current=after_update)+ log_project_secret_api_key_activity(after_update, activity, user, was_impersonated, changes)+++@receiver(pre_delete, sender=ProjectSecretAPIKey)+def handle_project_secret_api_key_delete(sender, instance, **kwargs):+ log_project_secret_api_key_activity(instance, "deleted", get_current_user(), get_was_impersonated())+++# --- Login session/device bookkeeping, relocated from posthog.api.authentication ---------+# user_logged_in fires wherever login happens; wiring this via the API module meant it only+# connected once the URLconf had been imported — an ordering that web happens to satisfy but+# nothing guarantees.++USER_AUTH_METHOD_MISMATCH = Counter(+ "user_auth_method_mismatches_sso_enforcement",+ "A user successfully authenticated with a different method than the one they're required to use",+ labelnames=["login_method", "sso_enforced_method", "user_uuid"],+)+++@receiver(user_logged_in)+def post_login(sender, user, request: HttpRequest, **kwargs):+ """+ Runs after every user login (including tests)+ Sets SESSION_COOKIE_CREATED_AT_KEY in the session to the current time+ """++ if hasattr(request, "backend"):+ sso_enforcement = OrganizationDomain.objects.get_sso_enforcement_for_email_address(user.email)+ if sso_enforcement is not None and sso_enforcement != request.backend.name:+ USER_AUTH_METHOD_MISMATCH.labels(+ login_method=request.backend.name, sso_enforced_method=sso_enforcement, user_uuid=user.uuid+ ).inc()++ request.session[settings.SESSION_COOKIE_CREATED_AT_KEY] = time.time()++ # Cache device info on signup to skip login notification for this device+ if user.last_login is None:+ short_user_agent = get_short_user_agent(request)+ ip_address = get_ip_address(request)+ country = get_geoip_properties(ip_address).get("$geoip_country_name", "Unknown")+ check_and_cache_login_device(user.id, country, short_user_agent)diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 6d09b657ff4e..d8ff07ee3b82 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -15,6 +15,7 @@ from products.workflows.backend.providers import MAILDEV_MOCK_DNS_RECORDSif TYPE_CHECKING:import aiohttpfrom anthropic import Anthropic+ from slack_sdk.web.async_client import AsyncWebClientfrom stripe import StripeClientfrom django.conf import settings@@ -35,7 +36,6 @@ from rest_framework.exceptions import ValidationErrorfrom rest_framework.request import Requestfrom slack_sdk import WebClientfrom slack_sdk.errors import SlackApiError-from slack_sdk.web.async_client import AsyncWebClientfrom posthog.cache_utils import cache_forfrom posthog.exceptions_capture import capture_exception@@ -1146,7 +1146,11 @@ class SlackIntegration:def client(self) -> WebClient:return WebClient(self.integration.sensitive_config["access_token"])- def async_client(self, session: Optional["aiohttp.ClientSession"] = None) -> AsyncWebClient:+ def async_client(self, session: Optional["aiohttp.ClientSession"] = None) -> "AsyncWebClient":+ # slack_sdk's async client imports aiohttp at module scope; this is a models module,+ # so a top-level import would put aiohttp on the django.setup() path+ from slack_sdk.web.async_client import AsyncWebClient # noqa: PLC0415+return AsyncWebClient(self.integration.sensitive_config["access_token"], session=session)def granted_scopes(self) -> frozenset[str]:diff --git a/posthog/models/integration_repository_cache.py b/posthog/models/integration_repository_cache.pyindex f4b2c4b5d83d..a2454aaa6dd0 100644--- a/posthog/models/integration_repository_cache.py+++ b/posthog/models/integration_repository_cache.py@@ -10,6 +10,7 @@ the IDE repo dropdown.from __future__ import annotations+import sysimport timeimport uuidimport base64@@ -25,7 +26,6 @@ from django.db.models import Qfrom django.utils import timezoneimport structlog-import temporalio.activityfrom posthog import redis as posthog_redisfrom posthog.helpers.async_concurrency import run_parallel_with_backoff@@ -416,8 +416,14 @@ async def _acquire_sync_lock(integration_id: int) -> AsyncIterator[None]:raise SyncFullCacheTimeoutError(f"Waited {SYNC_LOCK_MAX_WAIT_SECONDS}s for sync lock on integration {integration_id}")- if temporalio.activity.in_activity():- temporalio.activity.heartbeat()+ # Only meaningful inside a Temporal activity, and being in one implies temporalio is+ # imported — this is a models module, so a top-level import would put temporalio on+ # the django.setup() path+ if "temporalio" in sys.modules:+ import temporalio.activity # noqa: PLC0415++ if temporalio.activity.in_activity():+ temporalio.activity.heartbeat()await asyncio.sleep(SYNC_LOCK_POLL_INTERVAL_SECONDS)stop_heartbeat = asyncio.Event()diff --git a/posthog/tasks/demo_create_data.py b/posthog/tasks/demo_create_data.pyindex 6f0dbb7ef48e..99a57a688be4 100644--- a/posthog/tasks/demo_create_data.py+++ b/posthog/tasks/demo_create_data.py@@ -2,8 +2,6 @@ from django.core.cache import cachefrom celery import shared_task-from posthog.demo.matrix import manager-from posthog.demo.products.hedgebox.matrix import HedgeboxMatrixfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.scoping_audit import skip_team_scope_audit@@ -12,6 +10,12 @@ from posthog.scoping_audit import skip_team_scope_audit@shared_task(ignore_result=True)@skip_team_scope_auditdef create_data_for_demo_team(team_id: int, user_id: int, cache_key: str) -> None:+ # Deferred: the demo matrix pulls mimesis (a fake-data generator). This task module is+ # eager-imported by posthog/tasks/__init__, so a module-level import drags mimesis onto+ # every process's startup path. Only needed when actually generating demo data.+ from posthog.demo.matrix import manager # noqa: PLC0415+ from posthog.demo.products.hedgebox.matrix import HedgeboxMatrix # noqa: PLC0415+team = Team.objects.get(pk=team_id)user = User.objects.get(pk=user_id)if team and user:diff --git a/posthog/tasks/demo_reset_master_team.py b/posthog/tasks/demo_reset_master_team.pyindex 30fdd78b0eea..ca62908e7733 100644--- a/posthog/tasks/demo_reset_master_team.py+++ b/posthog/tasks/demo_reset_master_team.py@@ -1,10 +1,12 @@from django.db import transaction-from posthog.demo.matrix import MatrixManager-from posthog.demo.products import HedgeboxMatrix-def demo_reset_master_team() -> None:+ # Deferred: the demo matrix pulls mimesis (fake-data generator); this module is+ # eager-imported by posthog/tasks/__init__, so a module-level import drags it onto startup.+ from posthog.demo.matrix import MatrixManager # noqa: PLC0415+ from posthog.demo.products import HedgeboxMatrix # noqa: PLC0415+matrix = HedgeboxMatrix()manager = MatrixManager(matrix)with transaction.atomic():diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 6205ab9fb9f0..fa12d23b0167 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -13,7 +13,6 @@ import posthoganalyticsfrom celery import shared_taskfrom posthoganalytics import new_context, tag-from posthog.api.two_factor_reset import TWO_FACTOR_RESET_TOKEN_TIMEOUT_HOURSfrom posthog.caching.login_device_cache import check_and_cache_login_devicefrom posthog.cloud_utils import is_cloudfrom posthog.constants import AUTH_BACKEND_DISPLAY_NAMES, INVITE_DAYS_VALIDITY@@ -938,6 +937,10 @@ def send_two_factor_auth_backup_code_used_email(user_id: int) -> None:@skip_team_scope_auditdef send_two_factor_reset_email(user_id: int, token: str) -> None:"""Send 2FA reset email to user when an admin initiates a reset."""+ # Deferred: this constant lives in a DRF viewset module; email.py is eager-imported by+ # posthog/tasks/__init__, so a module-level import drags that machinery onto startup.+ from posthog.api.two_factor_reset import TWO_FACTOR_RESET_TOKEN_TIMEOUT_HOURS # noqa: PLC0415+user: User = User.objects.get(pk=user_id)reset_link = f"{settings.SITE_URL}/reset_2fa/{user.uuid}/{token}"diff --git a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambrindex d336ead88217..9431d4718309 100644--- a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr+++ b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr@@ -271,6 +271,45 @@'''# ---# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.18+ '''+ SELECT "ee_featureflagroleaccess"."id",+ "ee_featureflagroleaccess"."feature_flag_id",+ "ee_featureflagroleaccess"."role_id",+ "ee_featureflagroleaccess"."added_at",+ "ee_featureflagroleaccess"."updated_at"+ FROM "ee_featureflagroleaccess"+ WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999+ '''+# ---+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.19+ '''+ SELECT "ee_featureflagroleaccess"."id",+ "ee_featureflagroleaccess"."feature_flag_id",+ "ee_featureflagroleaccess"."role_id",+ "ee_featureflagroleaccess"."added_at",+ "ee_featureflagroleaccess"."updated_at"+ FROM "ee_featureflagroleaccess"+ WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999+ '''+# ---+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.2+ '''+ SELECT "posthog_organizationintegration"."id",+ "posthog_organizationintegration"."organization_id",+ "posthog_organizationintegration"."kind",+ "posthog_organizationintegration"."integration_id",+ "posthog_organizationintegration"."config",+ "posthog_organizationintegration"."sensitive_config",+ "posthog_organizationintegration"."created_by_id",+ "posthog_organizationintegration"."created_at",+ "posthog_organizationintegration"."updated_at"+ FROM "posthog_organizationintegration"+ WHERE ("posthog_organizationintegration"."kind" = 'vercel'+ AND "posthog_organizationintegration"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid)+ LIMIT 21+ '''+# ---+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.20'''SELECT "posthog_experiment"."id","posthog_experiment"."name",@@ -306,7 +345,7 @@WHERE "posthog_experiment"."feature_flag_id" = 99999'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.19+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.21'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -348,24 +387,7 @@LIMIT 21'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.2- '''- SELECT "posthog_organizationintegration"."id",- "posthog_organizationintegration"."organization_id",- "posthog_organizationintegration"."kind",- "posthog_organizationintegration"."integration_id",- "posthog_organizationintegration"."config",- "posthog_organizationintegration"."sensitive_config",- "posthog_organizationintegration"."created_by_id",- "posthog_organizationintegration"."created_at",- "posthog_organizationintegration"."updated_at"- FROM "posthog_organizationintegration"- WHERE ("posthog_organizationintegration"."kind" = 'vercel'- AND "posthog_organizationintegration"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid)- LIMIT 21- '''-# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.20+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.22'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -473,7 +495,7 @@LIMIT 21'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.21+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.23'''SELECT "posthog_featureflag"."id","posthog_featureflag"."key",@@ -511,7 +533,7 @@LIMIT 21'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.22+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.24'''SELECT "posthog_user"."id","posthog_user"."password",@@ -557,7 +579,7 @@LIMIT 21'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.23+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.25'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -665,7 +687,7 @@LIMIT 21'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.24+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.26'''SELECT "posthog_featureflag"."id","posthog_featureflag"."key",@@ -696,7 +718,7 @@UPDATE'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.25+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.27'''SELECT "posthog_featureflag"."id","posthog_featureflag"."key",@@ -727,7 +749,7 @@LIMIT 1'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.26+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.28'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -752,7 +774,7 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.27+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.29'''SELECT "posthog_filesystemshortcut"."id","posthog_filesystemshortcut"."team_id",@@ -775,7 +797,36 @@AND "posthog_filesystemshortcut"."href" IS NOT NULL))'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.28+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.3+ '''+ SELECT "posthog_scheduledchange"."id",+ "posthog_scheduledchange"."record_id",+ "posthog_scheduledchange"."model_name",+ "posthog_scheduledchange"."payload",+ "posthog_scheduledchange"."scheduled_at",+ "posthog_scheduledchange"."executed_at",+ "posthog_scheduledchange"."failure_reason",+ "posthog_scheduledchange"."failure_count",+ "posthog_scheduledchange"."is_recurring",+ "posthog_scheduledchange"."recurrence_interval",+ "posthog_scheduledchange"."last_executed_at",+ "posthog_scheduledchange"."cron_expression",+ "posthog_scheduledchange"."end_date",+ "posthog_scheduledchange"."timezone",+ "posthog_scheduledchange"."team_id",+ "posthog_scheduledchange"."created_at",+ "posthog_scheduledchange"."created_by_id",+ "posthog_scheduledchange"."updated_at"+ FROM "posthog_scheduledchange"+ WHERE ("posthog_scheduledchange"."executed_at" IS NULL+ AND "posthog_scheduledchange"."scheduled_at" <= '2023-12-21 09:00:00+00:00'::timestamptz)+ ORDER BY "posthog_scheduledchange"."scheduled_at" ASC+ LIMIT 10000+ FOR+ UPDATE NOWAIT+ '''+# ---+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.30'''SELECT "posthog_integration"."id","posthog_integration"."team_id",@@ -794,7 +845,7 @@LIMIT 21'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.29+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.31'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -836,36 +887,7 @@LIMIT 21'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.3- '''- SELECT "posthog_scheduledchange"."id",- "posthog_scheduledchange"."record_id",- "posthog_scheduledchange"."model_name",- "posthog_scheduledchange"."payload",- "posthog_scheduledchange"."scheduled_at",- "posthog_scheduledchange"."executed_at",- "posthog_scheduledchange"."failure_reason",- "posthog_scheduledchange"."failure_count",- "posthog_scheduledchange"."is_recurring",- "posthog_scheduledchange"."recurrence_interval",- "posthog_scheduledchange"."last_executed_at",- "posthog_scheduledchange"."cron_expression",- "posthog_scheduledchange"."end_date",- "posthog_scheduledchange"."timezone",- "posthog_scheduledchange"."team_id",- "posthog_scheduledchange"."created_at",- "posthog_scheduledchange"."created_by_id",- "posthog_scheduledchange"."updated_at"- FROM "posthog_scheduledchange"- WHERE ("posthog_scheduledchange"."executed_at" IS NULL- AND "posthog_scheduledchange"."scheduled_at" <= '2023-12-21 09:00:00+00:00'::timestamptz)- ORDER BY "posthog_scheduledchange"."scheduled_at" ASC- LIMIT 10000- FOR- UPDATE NOWAIT- '''-# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.30+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.32'''SELECT "posthog_organizationintegration"."id","posthog_organizationintegration"."organization_id",@@ -882,7 +904,7 @@LIMIT 21'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.31+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.33'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",@@ -900,7 +922,7 @@WHERE "posthog_taggeditem"."feature_flag_id" = 99999'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.32+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.34'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",@@ -918,7 +940,7 @@WHERE "posthog_taggeditem"."feature_flag_id" = 99999'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.33+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.35'''SELECT "posthog_survey"."id","posthog_survey"."team_id",@@ -963,7 +985,7 @@WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.34+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.36'''SELECT "posthog_survey"."id","posthog_survey"."team_id",@@ -1008,7 +1030,29 @@WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.35+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.37+ '''+ SELECT "ee_featureflagroleaccess"."id",+ "ee_featureflagroleaccess"."feature_flag_id",+ "ee_featureflagroleaccess"."role_id",+ "ee_featureflagroleaccess"."added_at",+ "ee_featureflagroleaccess"."updated_at"+ FROM "ee_featureflagroleaccess"+ WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999+ '''+# ---+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.38+ '''+ SELECT "ee_featureflagroleaccess"."id",+ "ee_featureflagroleaccess"."feature_flag_id",+ "ee_featureflagroleaccess"."role_id",+ "ee_featureflagroleaccess"."added_at",+ "ee_featureflagroleaccess"."updated_at"+ FROM "ee_featureflagroleaccess"+ WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999+ '''+# ---+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.39'''SELECT "posthog_experiment"."id","posthog_experiment"."name",@@ -1044,7 +1088,45 @@WHERE "posthog_experiment"."feature_flag_id" = 99999'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.36+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.4+ '''+ SELECT "posthog_featureflag"."id",+ "posthog_featureflag"."key",+ "posthog_featureflag"."name",+ "posthog_featureflag"."filters",+ "posthog_featureflag"."team_id",+ "posthog_featureflag"."created_by_id",+ "posthog_featureflag"."created_at",+ "posthog_featureflag"."updated_at",+ "posthog_featureflag"."deleted",+ "posthog_featureflag"."active",+ "posthog_featureflag"."version",+ "posthog_featureflag"."last_modified_by_id",+ "posthog_featureflag"."rollback_conditions",+ "posthog_featureflag"."performed_rollback",+ "posthog_featureflag"."ensure_experience_continuity",+ "posthog_featureflag"."usage_dashboard_id",+ "posthog_featureflag"."has_enriched_analytics",+ "posthog_featureflag"."is_remote_configuration",+ "posthog_featureflag"."has_encrypted_payloads",+ "posthog_featureflag"."evaluation_runtime",+ "posthog_featureflag"."bucketing_identifier",+ "posthog_featureflag"."last_called_at"+ FROM "posthog_featureflag"+ INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")+ WHERE (NOT ("posthog_featureflag"."deleted")+ AND ("posthog_featureflag"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_featureflag"."team_id" = 99999))+ AND "posthog_featureflag"."id" = 99999)+ LIMIT 21+ '''+# ---+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.40'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -1086,7 +1168,7 @@LIMIT 21'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.37+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.41'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -1194,7 +1276,7 @@LIMIT 21'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.38+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.42'''SELECT "posthog_scheduledchange"."id","posthog_scheduledchange"."record_id",@@ -1219,7 +1301,7 @@LIMIT 21'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.39+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.43'''SELECT "posthog_scheduledchange"."id","posthog_scheduledchange"."record_id",@@ -1244,45 +1326,7 @@LIMIT 21'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.4- '''- SELECT "posthog_featureflag"."id",- "posthog_featureflag"."key",- "posthog_featureflag"."name",- "posthog_featureflag"."filters",- "posthog_featureflag"."team_id",- "posthog_featureflag"."created_by_id",- "posthog_featureflag"."created_at",- "posthog_featureflag"."updated_at",- "posthog_featureflag"."deleted",- "posthog_featureflag"."active",- "posthog_featureflag"."version",- "posthog_featureflag"."last_modified_by_id",- "posthog_featureflag"."rollback_conditions",- "posthog_featureflag"."performed_rollback",- "posthog_featureflag"."ensure_experience_continuity",- "posthog_featureflag"."usage_dashboard_id",- "posthog_featureflag"."has_enriched_analytics",- "posthog_featureflag"."is_remote_configuration",- "posthog_featureflag"."has_encrypted_payloads",- "posthog_featureflag"."evaluation_runtime",- "posthog_featureflag"."bucketing_identifier",- "posthog_featureflag"."last_called_at"- FROM "posthog_featureflag"- INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")- WHERE (NOT ("posthog_featureflag"."deleted")- AND ("posthog_featureflag"."team_id" =- (SELECT U0."parent_team_id" AS "parent_team_id"- FROM "posthog_team" U0- WHERE U0."id" = 99999- LIMIT 1)- OR ("posthog_team"."parent_team_id" IS NULL- AND "posthog_featureflag"."team_id" = 99999))- AND "posthog_featureflag"."id" = 99999)- LIMIT 21- '''-# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.40+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.44'''SELECT "posthog_scheduledchange"."id","posthog_scheduledchange"."record_id",@@ -1307,7 +1351,7 @@LIMIT 21'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.41+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.45'''SELECT "posthog_scheduledchange"."id","posthog_scheduledchange"."record_id",@@ -1332,7 +1376,7 @@LIMIT 21'''# ----# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.42+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.46'''SELECT "posthog_featureflag"."id","posthog_featureflag"."key",diff --git a/posthog/temporal/ai/posthog_code_slack_mention.py b/posthog/temporal/ai/posthog_code_slack_mention.pyindex e77e0b045a23..c0c6dc0c63c9 100644--- a/posthog/temporal/ai/posthog_code_slack_mention.py+++ b/posthog/temporal/ai/posthog_code_slack_mention.py@@ -445,11 +445,6 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):)-# `api.py` imports the workflow classes above, so keep this module-level import-# after their definitions to avoid a circular import during module initialization.-from products.slack_app.backend.api import resolve_slack_user # noqa: E402--async def _gate_on_personal_github(inputs: "PostHogCodeSlackMentionWorkflowInputs",channel: str,@@ -499,6 +494,10 @@ def resolve_posthog_code_slack_user_activity(thread_ts: str,slack_user_id: str,) -> int | None:+ # Imported lazily to break a circular import: products.slack_app.backend.api+ # imports the workflow classes defined in this module at its top level.+ from products.slack_app.backend.api import resolve_slack_user+integration = Integration.objects.select_related("team", "team__organization").get(id=inputs.integration_id,kind="slack",@@ -1154,7 +1153,7 @@ def forward_posthog_code_followup_activity(Returns True if the message was handled (forwarded or rejected), False ifno mapping exists and the caller should continue with the normal new-task flow."""- from products.slack_app.backend.api import _parse_rules_command+ from products.slack_app.backend.api import _parse_rules_command, resolve_slack_userif _parse_rules_command(event_text):return Falsediff --git a/posthog/temporal/ai_observability/metrics.py b/posthog/temporal/ai_observability/metrics.pyindex c088a6e46767..2e4bee48435b 100644--- a/posthog/temporal/ai_observability/metrics.py+++ b/posthog/temporal/ai_observability/metrics.py@@ -1,11 +1,9 @@-import timeimport typingimport datetime as dtfrom django.conf import settingsfrom temporalio import activity, workflow-from temporalio.common import MetricMeterfrom temporalio.worker import (ActivityInboundInterceptor,ExecuteActivityInput,@@ -17,6 +15,12 @@ from temporalio.worker import (from posthog.temporal.common.logger import get_write_only_logger+# Generic temporal metric helpers live in common so other subsystems (e.g. session-replay+# delete-recordings) can import them without pulling this package's eager worker registration.+from posthog.temporal.common.metrics import Attributes, ExecutionTimeRecorder, get_metric_meter++__all__ = ["Attributes", "ExecutionTimeRecorder", "get_metric_meter"]+LOGGER = get_write_only_logger(__name__)EVAL_ACTIVITY_TYPES = {@@ -35,23 +39,6 @@ EVAL_WORKFLOW_TYPES = {"run-evaluation",}-Attributes = dict[str, str | int | float | bool]---def get_metric_meter(additional_attributes: Attributes | None = None) -> MetricMeter:- """Return a meter depending on in which context we are."""- if activity.in_activity():- meter = activity.metric_meter()- elif workflow.in_workflow():- meter = workflow.metric_meter()- else:- raise RuntimeError("Not within workflow or activity context")-- if additional_attributes:- meter = meter.with_additional_attributes(additional_attributes)-- return meter-def increment_workflow_started() -> None:"""Track workflow starts."""@@ -145,70 +132,6 @@ def record_schedule_to_start_latency(activity_type: str, latency_ms: int) -> Nonhist.record(dt.timedelta(milliseconds=latency_ms))-class ExecutionTimeRecorder:- """Context manager to record execution time to a histogram metric."""-- def __init__(- self,- histogram_name: str,- /,- description: str | None = None,- histogram_attributes: Attributes | None = None,- log: bool = False,- ) -> None:- self.histogram_name = histogram_name- self.description = description- self.histogram_attributes = histogram_attributes or {}- self.log = log- self._start_counter: float | None = None- self._status_override: str | None = None-- def set_status(self, status: str) -> None:- """Override the status that will be recorded. Use for non-exception outcomes like SKIPPED."""- self._status_override = status-- def __enter__(self) -> typing.Self:- self._start_counter = time.perf_counter()- return self-- def __exit__(self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback) -> None:- if not self._start_counter:- raise RuntimeError("Start counter not initialized, did you call `__enter__`?")-- end_counter = time.perf_counter()- delta_milli_seconds = int((end_counter - self._start_counter) * 1000)- delta = dt.timedelta(milliseconds=delta_milli_seconds)-- attributes = dict(self.histogram_attributes)-- if exc_value is not None:- attributes["status"] = "FAILED"- attributes["exception"] = str(exc_value)- elif self._status_override is not None:- attributes["status"] = self._status_override- attributes["exception"] = ""- else:- attributes["status"] = "COMPLETED"- attributes["exception"] = ""-- meter = get_metric_meter(attributes)- hist = meter.create_histogram_timedelta(name=self.histogram_name, description=self.description, unit="ms")- try:- hist.record(value=delta)- except Exception:- LOGGER.exception("Failed to record execution time to histogram '%s'", self.histogram_name)-- if self.log:- LOGGER.info(- "Finished %s with status '%s' in %dms",- self.histogram_name,- attributes["status"],- delta_milli_seconds,- )-- self._start_counter = None--class EvalsMetricsInterceptor(Interceptor):"""Interceptor to emit Prometheus metrics for evals workflows."""diff --git a/posthog/temporal/ai_observability/test_metrics.py b/posthog/temporal/ai_observability/test_metrics.pyindex 1eaf310000ff..955aaa83cf0f 100644--- a/posthog/temporal/ai_observability/test_metrics.py+++ b/posthog/temporal/ai_observability/test_metrics.py@@ -16,7 +16,7 @@ class TestExecutionTimeRecorder:mock_hist = MagicMock()mock_meter.create_histogram_timedelta.return_value = mock_hist- with patch("posthog.temporal.ai_observability.metrics.get_metric_meter", return_value=mock_meter) as mock_get:+ with patch("posthog.temporal.common.metrics.get_metric_meter", return_value=mock_meter) as mock_get:with ExecutionTimeRecorder("test_histogram"):pass@@ -30,7 +30,7 @@ class TestExecutionTimeRecorder:mock_hist = MagicMock()mock_meter.create_histogram_timedelta.return_value = mock_hist- with patch("posthog.temporal.ai_observability.metrics.get_metric_meter", return_value=mock_meter) as mock_get:+ with patch("posthog.temporal.common.metrics.get_metric_meter", return_value=mock_meter) as mock_get:with pytest.raises(ValueError):with ExecutionTimeRecorder("test_histogram"):raise ValueError("test error")@@ -51,7 +51,7 @@ class TestExecutionTimeRecorder:mock_hist = MagicMock()mock_meter.create_histogram_timedelta.return_value = mock_hist- with patch("posthog.temporal.ai_observability.metrics.get_metric_meter", return_value=mock_meter) as mock_get:+ with patch("posthog.temporal.common.metrics.get_metric_meter", return_value=mock_meter) as mock_get:with ExecutionTimeRecorder("test_histogram", histogram_attributes={"activity_type": "test_activity"}):pass@@ -66,7 +66,7 @@ class TestExecutionTimeRecorder:mock_hist = MagicMock()mock_meter.create_histogram_timedelta.return_value = mock_hist- with patch("posthog.temporal.ai_observability.metrics.get_metric_meter", return_value=mock_meter) as mock_get:+ with patch("posthog.temporal.common.metrics.get_metric_meter", return_value=mock_meter) as mock_get:with ExecutionTimeRecorder("test_histogram") as recorder:recorder.set_status("SKIPPED")diff --git a/posthog/temporal/common/metrics.py b/posthog/temporal/common/metrics.pynew file mode 100644index 000000000000..257d0c197716--- /dev/null+++ b/posthog/temporal/common/metrics.py@@ -0,0 +1,80 @@+import time+import typing+import datetime as dt++from temporalio import activity, workflow+from temporalio.common import MetricMeter++from posthog.temporal.common.logger import get_write_only_logger++LOGGER = get_write_only_logger(__name__)++Attributes = dict[str, str | int | float | bool]+++def get_metric_meter(additional_attributes: Attributes | None = None) -> MetricMeter:+ """Return a meter depending on in which context we are."""+ if activity.in_activity():+ meter = activity.metric_meter()+ elif workflow.in_workflow():+ meter = workflow.metric_meter()+ else:+ raise RuntimeError("Not within workflow or activity context")+ if additional_attributes:+ meter = meter.with_additional_attributes(additional_attributes)+ return meter+++class ExecutionTimeRecorder:+ """Context manager to record execution time to a histogram metric."""++ def __init__(+ self,+ histogram_name: str,+ /,+ description: str | None = None,+ histogram_attributes: Attributes | None = None,+ log: bool = False,+ ) -> None:+ self.histogram_name = histogram_name+ self.description = description+ self.histogram_attributes = histogram_attributes or {}+ self.log = log+ self._start_counter: float | None = None+ self._status_override: str | None = None++ def set_status(self, status: str) -> None:+ """Override the status that will be recorded. Use for non-exception outcomes like SKIPPED."""+ self._status_override = status++ def __enter__(self) -> typing.Self:+ self._start_counter = time.perf_counter()+ return self++ def __exit__(self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback) -> None:+ if self._start_counter is None:+ raise RuntimeError("Start counter not initialized, did you call `__enter__`?")+ end_counter = time.perf_counter()+ delta_milli_seconds = int((end_counter - self._start_counter) * 1000)+ delta = dt.timedelta(milliseconds=delta_milli_seconds)+ attributes = dict(self.histogram_attributes)+ if exc_value is not None:+ attributes["status"] = "FAILED"+ attributes["exception"] = str(exc_value)+ elif self._status_override is not None:+ attributes["status"] = self._status_override+ attributes["exception"] = ""+ else:+ attributes["status"] = "COMPLETED"+ attributes["exception"] = ""+ meter = get_metric_meter(attributes)+ hist = meter.create_histogram_timedelta(name=self.histogram_name, description=self.description, unit="ms")+ try:+ hist.record(value=delta)+ except Exception:+ LOGGER.exception("Failed to record execution time to histogram '%s'", self.histogram_name)+ if self.log:+ LOGGER.info(+ "Finished %s with status '%s' in %dms", self.histogram_name, attributes["status"], delta_milli_seconds+ )+ self._start_counter = Nonediff --git a/posthog/temporal/data_imports/pipelines/pipeline/typings.py b/posthog/temporal/data_imports/pipelines/pipeline/typings.pyindex 013b0bf98a16..72711770818e 100644--- a/posthog/temporal/data_imports/pipelines/pipeline/typings.py+++ b/posthog/temporal/data_imports/pipelines/pipeline/typings.py@@ -1,12 +1,27 @@+# Annotations are lazy (PEP 563) so the dlt import below can stay type-only — dlt is heavy and this+# module is reachable from warehouse_sources models at django.setup().+from __future__ import annotations+import dataclassesfrom collections.abc import AsyncIterable, Callable, Iterable-from typing import Any, ClassVar, Literal, NotRequired, Optional, Protocol, TypedDict, TypeVar+from typing import TYPE_CHECKING, Any, ClassVar, Literal, NotRequired, Optional, Protocol, TypedDict, TypeVar-from dlt.common.data_types.typing import TDataTypefrom structlog.types import FilteringBoundLoggerfrom products.data_warehouse.backend.types import IncrementalFieldType+if TYPE_CHECKING:+ from dlt.common.data_types.typing import TDataType+else:+ # Runtime stub so get_type_hints() on the dataclasses below resolves without importing dlt (kept+ # type-only above). Deliberately not `str` — nothing should rely on the runtime value, and a named+ # stub makes accidental use obvious rather than silently passing as a plausible type. The real,+ # mypy-visible type comes from the TYPE_CHECKING branch.+ class TDataType:+ def __repr__(self) -> str:+ return "<TDataType: type-checking-only stub for dlt.common.data_types.typing.TDataType>"++SortMode = Literal["asc", "desc"]PartitionMode = Literal["md5", "numerical", "datetime"]PartitionFormat = Literal["month", "week", "day", "hour"]diff --git a/posthog/temporal/session_replay/delete_recordings/metrics.py b/posthog/temporal/session_replay/delete_recordings/metrics.pyindex dfef9b960ede..4fc4db90eeff 100644--- a/posthog/temporal/session_replay/delete_recordings/metrics.py+++ b/posthog/temporal/session_replay/delete_recordings/metrics.py@@ -13,7 +13,7 @@ from temporalio.worker import (WorkflowInterceptorClassInput,)-from posthog.temporal.ai_observability.metrics import ExecutionTimeRecorder, get_metric_meter+from posthog.temporal.common.metrics import ExecutionTimeRecorder, get_metric_meter# ---------------------------------------------------------------------------# Histogram bucket config (imported by common/worker.py for PrometheusConfig)diff --git a/posthog/temporal/tests/external_data/test_external_data_job.py b/posthog/temporal/tests/external_data/test_external_data_job.pyindex 9da115591de5..9d99ddabdcf4 100644--- a/posthog/temporal/tests/external_data/test_external_data_job.py+++ b/posthog/temporal/tests/external_data/test_external_data_job.py@@ -450,7 +450,8 @@ async def test_update_external_job_activity_with_non_retryable_error(activity_enteam_id=team.id,)with mock.patch(- "products.warehouse_sources.backend.models.external_data_schema.external_data_workflow_exists",+ # patched at its defining module: update_should_sync imports it function-locally now+ "products.data_warehouse.backend.data_load.service.external_data_workflow_exists",return_value=False,):await activity_environment.run(update_external_data_job_model, inputs)@@ -502,7 +503,8 @@ async def test_update_external_job_activity_with_not_source_sepecific_non_retryateam_id=team.id,)with mock.patch(- "products.warehouse_sources.backend.models.external_data_schema.external_data_workflow_exists",+ # patched at its defining module: update_should_sync imports it function-locally now+ "products.data_warehouse.backend.data_load.service.external_data_workflow_exists",return_value=False,):await activity_environment.run(update_external_data_job_model, inputs)diff --git a/posthog/test/setup_import_baseline.txt b/posthog/test/setup_import_baseline.txtnew file mode 100644index 000000000000..3ea73aa334f9--- /dev/null+++ b/posthog/test/setup_import_baseline.txt@@ -0,0 +1,35 @@+# Imports known to be on the django.setup() path — see docs/internal/django-startup-time.md.+#+# This is NOT an approval list for heavy imports; it is the set of packages that are+# genuinely needed at setup (settings, models, the celery app) plus everything that was+# already there when the new-heavy-import guard was introduced. The companion test+# (test_no_new_heavy_imports_at_setup) fails when a package NOT listed here costs more+# than the threshold at a bare django.setup() — deliberately with no per-entry time+# budgets, since absolute timings flake in CI; time is only the materiality gate for+# NEW arrivals.+#+# Before adding an entry: defer the import instead (function-local, TYPE_CHECKING, lazy+# facade, or a light activity_logging/visibility module for ready() wiring). Add here only+# when every process truly needs the package during django.setup(), with a comment saying+# why. Entries are top-level package names for third-party, full module names for+# first-party.+#+# Third-party packages on the setup path today (cheap entries listed too, so a slow CI+# runner cannot push a known package over the threshold):+botocore+celery+clickhouse_driver+cryptography+django+dns+grpc+kombu+oauth2_provider+pkg_resources+psycopg+redis+rich+trio+# First-party modules with a known, structural import cost:+posthog.schema # the generated data model — splitting it is tracked as its own projectdiff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtnew file mode 100644index 000000000000..181f12647188--- /dev/null+++ b/posthog/test/setup_receivers_baseline.txt@@ -0,0 +1,192 @@+# First-party signal receivers connected after a bare django.setup(), as signal:module.qualname.+# Maintained by test_setup_receivers_match_baseline — regenerate with:+# UPDATE_SETUP_RECEIVERS_BASELINE=1 pytest posthog/test/test_startup_import_budget.py -k receivers_match+# A receiver disappearing from this set means it connects in NO process (silent audit/cache loss):+# restore its AppConfig.ready() wiring instead of deleting the line.+model_activity:posthog.models.activity_logging.signal_handlers.handle_experiment_holdout_change+model_activity:posthog.models.activity_logging.signal_handlers.handle_experiment_saved_metric_change+model_activity:posthog.models.activity_logging.signal_handlers.handle_experiment_to_saved_metric_change+model_activity:posthog.models.activity_logging.signal_handlers.handle_organization_change+model_activity:posthog.models.activity_logging.signal_handlers.handle_organization_domain_change+model_activity:posthog.models.activity_logging.signal_handlers.handle_organization_invite_change+model_activity:posthog.models.activity_logging.signal_handlers.handle_organization_membership_change+model_activity:posthog.models.activity_logging.signal_handlers.handle_personal_api_key_change+model_activity:posthog.models.activity_logging.signal_handlers.handle_project_secret_api_key_change+model_activity:posthog.models.activity_logging.signal_handlers.handle_tag_change+model_activity:posthog.models.activity_logging.signal_handlers.handle_tagged_item_change+model_activity:posthog.models.activity_logging.signal_handlers.log_user_change_activity+model_activity:products.actions.backend.activity_logging.handle_action_change+model_activity:products.ai_observability.backend.activity_logging.handle_evaluation_change+model_activity:products.alerts.backend.activity_logging.handle_alert_configuration_change+model_activity:products.alerts.backend.activity_logging.handle_alert_subscription_change+model_activity:products.alerts.backend.activity_logging.handle_threshold_change+model_activity:products.annotations.backend.activity_logging.handle_annotation_change+model_activity:products.batch_exports.backend.activity_logging.handle_batch_export_change+model_activity:products.business_knowledge.backend.signals.handle_knowledge_source_change+model_activity:products.dashboards.backend.activity_logging.handle_dashboard_change+model_activity:products.dashboards.backend.activity_logging.handle_dashboard_widget_change+model_activity:products.data_warehouse.backend.activity_logging.handle_external_data_schema_change+model_activity:products.data_warehouse.backend.activity_logging.handle_external_data_source_change+model_activity:products.experiments.backend.activity_logging.handle_experiment_change+model_activity:products.exports.backend.models.subscription.log_subscription_activity+model_activity:products.feature_flags.backend.activity_logging.handle_feature_flag_change+model_activity:products.legal_documents.backend.signals.handle_legal_document_change+model_activity:products.logs.backend.activity_logging.handle_logs_alert_activity+model_activity:products.logs.backend.activity_logging.handle_logs_sampling_rule_activity+model_activity:products.managed_migrations.backend.api.batch_imports.handle_batch_import_change+model_activity:products.signals.backend.activity_logging.handle_signal_scout_config_change+post_delete:ee.vercel.integration.delete_experiment_experimentation_item+post_delete:ee.vercel.integration.delete_resource_experimentation_item+post_delete:posthog.caching.organization_serializer_cache._connect_invalidation.<locals>.receiver_fn+post_delete:posthog.models.event_ingestion_restriction_config.delete_redis_cache_with_config+post_delete:posthog.models.file_system.file_system_mixin.FileSystemSyncMixin.__init_subclass__.<locals>._file_system_post_delete+post_delete:posthog.models.file_system.file_system_view_log._drop_view_logs_when_file_deleted+post_delete:posthog.models.oauth._block_cimd_url_on_application_delete+post_delete:posthog.models.organization.clean_up_alert_subscriptions_on_membership_removal+post_delete:posthog.models.organization.sync_billing_on_membership_removal+post_delete:posthog.models.person.util.person_deleted+post_delete:posthog.models.person.util.person_distinct_id_deleted+post_delete:posthog.models.product_intent.product_intent._invalidate_product_intents_on_delete+post_delete:posthog.models.remote_config.product_tour_deleted+post_delete:posthog.models.remote_config.site_function_changed+post_delete:posthog.models.team.team.delete_team_in_cache_on_delete+post_delete:posthog.storage.team_access_cache_signal_handlers.organization_membership_deleted+post_delete:posthog.storage.team_access_cache_signal_handlers.personal_api_key_deleted+post_delete:posthog.storage.team_access_cache_signal_handlers.project_secret_api_key_deleted+post_delete:posthog.storage.team_access_cache_signal_handlers.team_deleted_auth_cache+post_delete:products.access_control.backend.property_access_control._invalidate_restriction_cache_on_change+post_delete:products.actions.backend.models.action.action_deleted+post_delete:products.ai_observability.backend.models.llm_prompt.invalidate_llm_prompt_cache+post_delete:products.ai_observability.backend.models.provider_keys.provider_key_deleted+post_delete:products.cdp.backend.models.hog_functions.hog_function.team_inject_web_apps_changd+post_delete:products.cdp.backend.models.hook.hook_deleted+post_delete:products.cdp.backend.models.plugin.plugin_attachement_reload_needed+post_delete:products.cdp.backend.models.plugin.plugin_config_reload_needed+post_delete:products.cdp.backend.models.plugin.plugin_reload_needed+post_delete:products.cohorts.backend.models.cohort.cohort_people_changed+post_delete:products.cohorts.backend.models.dependencies.clear_team_cohort_dependency_cache+post_delete:products.cohorts.backend.models.dependencies.cohort_deleted+post_delete:products.event_definitions.backend.models.event_definition._invalidate_default_event_info_on_delete+post_delete:products.feature_flags.backend.flags_cache.cohort_changed_flags_cache+post_delete:products.feature_flags.backend.flags_cache.evaluation_context_changed_flags_cache+post_delete:products.feature_flags.backend.flags_cache.feature_flag_changed_flags_cache+post_delete:products.feature_flags.backend.flags_cache.team_deleted_flags_cache+post_delete:products.feature_flags.backend.local_evaluation.cohort_changed+post_delete:products.feature_flags.backend.local_evaluation.evaluation_context_changed+post_delete:products.feature_flags.backend.local_evaluation.feature_flag_changed+post_delete:products.feature_flags.backend.models.feature_flag.refresh_flag_cache_on_updates+post_delete:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_change+post_delete:products.surveys.backend.models.survey_changed+post_delete:products.tasks.backend.models._unfile_task_on_hard_delete+post_init:posthog.storage.team_llm_gateway_policy_signal_handlers._snapshot_loaded_state+post_save:ee.models.license.license_saved+post_save:ee.vercel.integration.sync_experiment_experimentation_item+post_save:ee.vercel.integration.sync_feature_flag_experimentation_item+post_save:posthog.caching.organization_serializer_cache._connect_invalidation.<locals>.receiver_fn+post_save:posthog.models.activity_logging.activity_log.activity_log_created+post_save:posthog.models.comment.comment.log_comment_activity+post_save:posthog.models.event_ingestion_restriction_config.update_redis_cache_with_config+post_save:posthog.models.file_system.file_system_mixin.FileSystemSyncMixin.__init_subclass__.<locals>._file_system_post_save+post_save:posthog.models.file_system.user_product_list.access_control_created+post_save:posthog.models.organization.cache_organization_session_age+post_save:posthog.models.organization.sync_billing_on_membership_save+post_save:posthog.models.person.util.person_created+post_save:posthog.models.person.util.person_distinct_id_created+post_save:posthog.models.product_intent.product_intent._invalidate_product_intents_on_save+post_save:posthog.models.remote_config.error_tracking_suppression_rule_saved+post_save:posthog.models.remote_config.feature_flag_saved+post_save:posthog.models.remote_config.js_snippet_config_saved+post_save:posthog.models.remote_config.product_tour_saved+post_save:posthog.models.remote_config.site_app_saved+post_save:posthog.models.remote_config.site_function_changed+post_save:posthog.models.remote_config.survey_saved+post_save:posthog.models.remote_config.team_saved+post_save:posthog.models.team.extensions.register_team_extension_signal.<locals>.receiver_func+post_save:posthog.models.team.team.put_team_in_cache_on_save+post_save:posthog.models.team.team.reevaluate_authorized_urls_health+post_save:posthog.storage.team_access_cache_signal_handlers.organization_membership_saved+post_save:posthog.storage.team_access_cache_signal_handlers.personal_api_key_saved+post_save:posthog.storage.team_access_cache_signal_handlers.project_secret_api_key_saved+post_save:posthog.storage.team_access_cache_signal_handlers.team_saved_auth_cache+post_save:posthog.storage.team_access_cache_signal_handlers.user_saved+post_save:posthog.storage.team_llm_gateway_policy_signal_handlers._update_cache_on_save+post_save:products.access_control.backend.property_access_control._invalidate_restriction_cache_on_change+post_save:products.actions.backend.models.action.action_saved+post_save:products.ai_observability.backend.models.clustering_job.create_default_clustering_jobs_for_new_team+post_save:products.ai_observability.backend.models.evaluations.evaluation_saved+post_save:products.ai_observability.backend.models.llm_prompt.invalidate_llm_prompt_cache+post_save:products.ai_observability.backend.models.provider_keys.provider_key_saved+post_save:products.ai_observability.backend.models.taggers.tagger_saved+post_save:products.annotations.backend.activity_logging.annotation_created+post_save:products.cdp.backend.models.hog_functions.hog_function.action_saved+post_save:products.cdp.backend.models.hog_functions.hog_function.cohort_saved+post_save:products.cdp.backend.models.hog_functions.hog_function.enabled_default_hog_functions_for_new_team+post_save:products.cdp.backend.models.hog_functions.hog_function.hog_function_saved+post_save:products.cdp.backend.models.hog_functions.hog_function.team_inject_web_apps_changd+post_save:products.cdp.backend.models.hog_functions.hog_function.team_saved+post_save:products.cdp.backend.models.hook.hook_saved+post_save:products.cdp.backend.models.plugin.plugin_attachement_reload_needed+post_save:products.cdp.backend.models.plugin.plugin_config_reload_needed+post_save:products.cdp.backend.models.plugin.plugin_reload_needed+post_save:products.cdp.backend.models.plugin.preinstall_plugins_for_new_organization+post_save:products.cohorts.backend.models.dependencies.cohort_changed+post_save:products.cohorts.backend.models.dependencies.cohort_conditions_changed_backfill+post_save:products.conversations.backend.signals.emit_ticket_created_event+post_save:products.conversations.backend.signals.post_github_reply_on_team_message+post_save:products.conversations.backend.signals.post_slack_reply_on_team_message+post_save:products.conversations.backend.signals.post_teams_reply_on_team_message+post_save:products.conversations.backend.signals.send_email_reply_on_team_message+post_save:products.conversations.backend.signals.update_ticket_on_message+post_save:products.data_modeling.backend.signals.sync_saved_query_name_to_node+post_save:products.data_warehouse.backend.models.revenue_analytics_config.create_external_data_source_revenue_analytics_config+post_save:products.event_definitions.backend.models.event_definition._invalidate_default_event_info_on_save+post_save:products.exports.backend.models.subscription.subscription_saved+post_save:products.feature_flags.backend.flags_cache.cohort_changed_flags_cache+post_save:products.feature_flags.backend.flags_cache.evaluation_context_changed_flags_cache+post_save:products.feature_flags.backend.flags_cache.feature_flag_changed_flags_cache+post_save:products.feature_flags.backend.flags_cache.team_created_flags_cache+post_save:products.feature_flags.backend.local_evaluation.cohort_changed+post_save:products.feature_flags.backend.local_evaluation.evaluation_context_changed+post_save:products.feature_flags.backend.local_evaluation.evaluation_context_name_changed+post_save:products.feature_flags.backend.local_evaluation.feature_flag_changed+post_save:products.feature_flags.backend.models.feature_flag.refresh_flag_cache_on_updates+post_save:products.product_analytics.backend.models.insight_caching_state.sync_dashboard_tile+post_save:products.product_analytics.backend.models.insight_caching_state.sync_dashboard_updated+post_save:products.product_analytics.backend.models.insight_caching_state.sync_insight+post_save:products.product_analytics.backend.models.insight_caching_state.sync_sharing_configuration+post_save:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_change+post_save:products.surveys.backend.models.survey_changed+post_save:products.tasks.backend.models._unfile_task_on_soft_delete+post_save:products.tasks.backend.models.track_task_run_completion+post_save:products.workflows.backend.models.hog_flow.hog_flow.action_saved_for_hog_flows+post_save:products.workflows.backend.models.hog_flow.hog_flow.hog_flow_saved+post_save:products.workflows.backend.models.hog_flow.hog_flow.team_saved_for_hog_flows+post_save:products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.handle_hog_flow_batch_job_created+pre_delete:posthog.models.activity_logging.signal_handlers.handle_experiment_holdout_delete+pre_delete:posthog.models.activity_logging.signal_handlers.handle_experiment_saved_metric_delete+pre_delete:posthog.models.activity_logging.signal_handlers.handle_personal_api_key_delete+pre_delete:posthog.models.activity_logging.signal_handlers.handle_project_secret_api_key_delete+pre_delete:posthog.models.organization.ensure_organization_membership_consistency+pre_delete:posthog.models.organization_invite._unsuppress_delegator_onboarding_on_invite_delete+pre_delete:posthog.storage.team_access_cache_signal_handlers.clear_project_secret_api_key_cache_on_delete+pre_delete:posthog.storage.team_llm_gateway_policy_signal_handlers._clear_cache_on_delete+pre_delete:products.alerts.backend.activity_logging.cleanup_alert_hog_functions+pre_delete:products.alerts.backend.activity_logging.handle_alert_subscription_delete+pre_delete:products.managed_migrations.backend.api.batch_imports.handle_batch_import_delete+pre_save:posthog.models.event_ingestion_restriction_config.capture_old_restriction_type+pre_save:posthog.models.organization.organization_about_to_be_created+pre_save:posthog.models.organization.organization_membership_saved+pre_save:posthog.models.product_intent.product_intent._capture_original_team_id+pre_save:posthog.storage.team_access_cache_signal_handlers.personal_api_key_pre_save+pre_save:posthog.storage.team_access_cache_signal_handlers.project_secret_api_key_pre_save+pre_save:posthog.storage.team_access_cache_signal_handlers.team_pre_save_auth_cache+pre_save:posthog.storage.team_llm_gateway_policy_signal_handlers._capture_old_state_if_deferred+pre_save:products.cohorts.backend.models.dependencies.cohort_pre_save+pre_save:products.conversations.backend.signals.handle_comment_soft_delete+pre_save:products.customer_analytics.backend.models.account._enforce_account_group_type_index_drift_policy+pre_save:products.event_definitions.backend.models.event_definition._capture_event_definition_old_name+pre_save:products.surveys.backend.models.pre_save_survey+user_logged_in:posthog.models.activity_logging.signal_handlers.log_user_login_activity+user_logged_in:posthog.models.activity_logging.signal_handlers.post_login+user_logged_out:posthog.models.activity_logging.signal_handlers.log_user_logout_activity+user_logged_out:posthog.models.oauth._revoke_impersonation_oauth_tokensdiff --git a/posthog/test/test_decorators.py b/posthog/test/test_decorators.pyindex 51f8aec62de9..761f62b7934b 100644--- a/posthog/test/test_decorators.py+++ b/posthog/test/test_decorators.py@@ -6,12 +6,14 @@ from posthog.test.base import APIBaseTest, BaseTestfrom unittest.mock import patchfrom django.core.cache import cache+from django.test import override_settings+from django.urls import include, pathfrom rest_framework.decorators import actionfrom rest_framework.response import Responsefrom rest_framework.viewsets import GenericViewSet-from posthog.api import router+from posthog.api.routing import DefaultRouterPlusPlusfrom posthog.decorators import cached_by_filters, disallow_if_impersonated, is_stale_filterfrom posthog.models.filters.filter import Filterfrom posthog.models.filters.path_filter import PathFilter@@ -37,9 +39,7 @@ class DummyViewSet(*((TeamAndOrgViewSetMixin, GenericViewSet) if TYPE_CHECKING ereturn {"result": "bla"}-router.register(r"dummy", DummyViewSet, "dummy")--+@override_settings(ROOT_URLCONF="posthog.test.test_decorators")class TestCachedByFiltersDecorator(APIBaseTest):def setUp(self) -> None:DummyViewSet.team = self.team # Simulating TeamAndOrgViewSetMixin@@ -274,9 +274,20 @@ class ImpersonationTestViewSet(GenericViewSet):return Response({"status": "success", "method": request.method})-router.register(r"impersonation-test", ImpersonationTestViewSet, "impersonation-test")+# A dedicated test URLconf instead of registering on the live application router: the live+# router's URL set is frozen the first time anything imports posthog.urls, so module-scope+# registrations only worked when this file happened to be collected before that — shard+# composition changes kept flipping the order. override_settings(ROOT_URLCONF=...) makes the+# routes exist exactly for these tests, in any order, and stops them leaking into the real+# URL space of every other test in the process.+_test_router = DefaultRouterPlusPlus()+_test_router.register(r"dummy", DummyViewSet, "dummy")+_test_router.register(r"impersonation-test", ImpersonationTestViewSet, "impersonation-test")++urlpatterns = [path("api/", include(_test_router.urls))]+@override_settings(ROOT_URLCONF="posthog.test.test_decorators")class TestDisallowIfImpersonatedDecorator(APIBaseTest):@patch("posthog.decorators.is_impersonated_session")def test_allows_non_impersonated_session(self, mock_is_impersonated):diff --git a/posthog/test/test_startup_import_budget.py b/posthog/test/test_startup_import_budget.pynew file mode 100644index 000000000000..270b23a9842a--- /dev/null+++ b/posthog/test/test_startup_import_budget.py@@ -0,0 +1,453 @@+import os+import re+import sys+import subprocess+from pathlib import Path++# Heavy subsystems that must NOT be imported by a bare ``django.setup()``. Each one was+# deliberately pulled off the startup path (lazy API router, deferred AI-core imports,+# deferred embedded-ClickHouse). Importing any of them at setup means a new module-level+# import re-opened a door — defer it (function-local / TYPE_CHECKING / lazy facade) instead+# of widening this budget. See logs/startup-profile and the PRs that introduced these cuts.+FORBIDDEN_AT_SETUP = [+ "posthog.api.rest_router", # the 160-route DRF aggregator — builds lazily on first request+ "posthog.temporal.ai", # AI temporal workflows -> ee.hogai chat-agent core+ "ee.hogai.chat_agent.graph", # the assistant graph+ "ee.hogai.tools", # the agent tool registry+ "chdb", # embedded ClickHouse+ "posthog.temporal.ai_observability", # eval/clustering workers (pulls scipy, etc.)+ "scipy", # only reached via ai_observability clustering — must not be at startup+ "posthog.session_recordings.session_recording_api", # pulls the session_summary workflow+ "google.genai", # Gemini SDK — only reached via the session-summary video workflow+ "mimesis", # fake-data generator — only used by demo-data tasks+ "stripe", # Stripe SDK — only on the billing/agentic-provisioning request path (deferred there)+ "dagster", # orchestration framework — only the dagster worker needs it (cluster.py logger is lazy)+ "dlt", # data-load-tool — only the warehouse import pipelines need it (deferred in pipeline typings)+ "products.revenue_analytics.backend.views.sources.stripe", # revenue view builders (pandas-heavy)+ "user_agents", # UA parser — only the request-time UA-summary path needs it (deferred in posthog.utils)+ "products.batch_exports.backend.temporal", # batch export workflows + every destination's vendor SDK+ "databricks", # Databricks SDK — only the databricks batch export destination needs it+ "snowflake", # Snowflake SDK — only the snowflake batch export destination needs it+ "temporalio", # Temporal SDK — only workers and call-time service paths need it (gated on sys.modules)+ "modal", # Modal SDK — only the tasks/notebooks sandbox runtime needs it+ "aiohttp", # async HTTP — pulled by slack async client / temporal clickhouse, both deferred+ "s3fs", # S3 filesystem — only warehouse delete/import paths need it+ "pandas", # only query/export paths need it — reached via clickhouse_connect's import-time probe+ "pyarrow", # arrow tables — reached via pandas.compat and batch-export internals, both deferred+ "numpy", # alert detectors / weighted sampling / warehouse coercion — all call-time now+]++# Runs in a clean interpreter: pytest has already imported half the world, so we cannot+# inspect this process's sys.modules. A subprocess gives a faithful cold-start snapshot.+_SNAPSHOT = """+import os+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")+import django+django.setup()+import sys+print("\\n".join(sorted(m for m in sys.modules)))+"""+++def test_django_setup_does_not_import_heavy_subsystems() -> None:+ result = subprocess.run(+ [sys.executable, "-c", _SNAPSHOT],+ capture_output=True,+ text=True,+ timeout=120,+ )+ assert result.returncode == 0, f"django.setup() failed:\n{result.stderr[-2000:]}"+ loaded = set(result.stdout.splitlines())++ offenders = [mod for mod in FORBIDDEN_AT_SETUP if mod in loaded or any(m.startswith(mod + ".") for m in loaded)]+ assert not offenders, (+ f"These heavy modules were imported by a bare django.setup(): {offenders}. "+ "Something added a module-level import that drags them onto the startup path "+ "(shell, migrate, celery, CI all pay for it). Defer the offending import instead."+ )+++# Counterpart guard to the lazy API router: with the route aggregator off the startup path,+# a model class only registers if its app's ``models/__init__`` imports it (importing the+# class is what runs ``ModelBase.__new__`` -> ``apps.register_model``). A model reachable+# *only* through a viewset import would silently vanish from ``apps.get_models()`` at+# setup-time, breaking makemigrations, admin, and the django-stubs mypy plugin. This asserts+# every model registers at app-population, so importing the router adds none.+_ROUTER_MODEL_DIFF = """+import os+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")+import django+django.setup()+from django.apps import apps++def labels():+ return {f"{m._meta.app_label}.{m.__name__}" for m in apps.get_models()}++before = labels()+# The full URLconf, not just rest_router: it builds the router AND imports the product url+# modules urls.py pulls directly — the path where latent import cycles have twice detonated.+import importlib+importlib.import_module("posthog.urls")+after = labels()+print("\\n".join(sorted(after - before)))+"""+++def test_all_models_register_at_app_population_not_via_router() -> None:+ result = subprocess.run(+ [sys.executable, "-c", _ROUTER_MODEL_DIFF],+ capture_output=True,+ text=True,+ timeout=120,+ )+ assert result.returncode == 0, (+ "django.setup() or the cold URLconf import failed — if the traceback shows a partially "+ f"initialized module, an import cycle only ever resolved by import-order luck:\n{result.stderr[-2000:]}"+ )+ late = [m for m in result.stdout.splitlines() if m]+ assert not late, (+ f"These models only registered once the API router imported their viewsets: {late}. "+ "A model must be imported from its app's models/__init__ (or models.py) so it registers "+ "at app-population — Django requires this for makemigrations, admin, and mypy. Add the "+ "missing import to the app's models package instead of relying on a viewset import."+ )+++# Same trap as the model guard, but for Django signal receivers. Importing a viewset module also runs+# its ``@receiver`` decorators — so the eager router connected a pile of receivers as a side effect of+# ``django.setup()``. With the lazy router those connect only when the router is first built, so any+# process that never builds it (celery, temporal, migrate, shell) silently loses them. The fallout is+# not cosmetic: feature-flag cache invalidation (``flags_cache``/``local_evaluation``) and alert+# cleanup (``alerts.backend.api.alert``) stop firing on background writes. Every receiver must be wired+# at setup — canonically from the owning app's ``AppConfig.ready()`` — so building the router connects+# none. The offending receivers are now wired from their owning ``AppConfig.ready()`` (feature_flags,+# alerts, ee, and posthog core); this guards against new viewset-only receivers sneaking back in.+_ROUTER_RECEIVER_DIFF = """+import os+import weakref++os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")+import django++django.setup()+from django.contrib.auth import signals as auth_signals+from django.db.models import signals+from posthog.models.signals import model_activity_signal++_SIGNALS = ["pre_save", "post_save", "pre_delete", "post_delete", "m2m_changed", "pre_init", "post_init"]+# model_activity_signal is PostHog's custom audit-log signal, not a django.db.models one. Its+# `handle_*_change` receivers live in viewset modules, so they are exactly the kind that the eager+# router used to wire as a side effect — include it or this whole class of regression is invisible.+# Auth signals are included for parity with the setup-receivers baseline: an auth receiver wired+# only via a viewset import would otherwise slip past both guards.+_CUSTOM_SIGNALS = {+ "model_activity": model_activity_signal,+ "user_logged_in": auth_signals.user_logged_in,+ "user_logged_out": auth_signals.user_logged_out,+ "user_login_failed": auth_signals.user_login_failed,+}+++def _resolve(entry):+ ref = entry[1]+ fn = ref() if isinstance(ref, weakref.ReferenceType) else ref+ if fn is None:+ return None+ return f"{getattr(fn, '__module__', '?')}.{getattr(fn, '__qualname__', repr(fn))}"+++def _connected():+ out = set()+ for name in _SIGNALS:+ for entry in getattr(signals, name).receivers:+ resolved = _resolve(entry)+ if resolved:+ out.add(f"{name}:{resolved}")+ for name, sig in _CUSTOM_SIGNALS.items():+ for entry in sig.receivers:+ resolved = _resolve(entry)+ if resolved:+ out.add(f"{name}:{resolved}")+ return out+++before = _connected()+# The full URLconf, not just rest_router — see the model-diff capture above.+import importlib+importlib.import_module("posthog.urls")+after = _connected()+print("\\n".join(sorted(after - before)))+"""+++def test_signal_receivers_connect_at_setup_not_via_router() -> None:+ result = subprocess.run(+ [sys.executable, "-c", _ROUTER_RECEIVER_DIFF],+ capture_output=True,+ text=True,+ timeout=120,+ )+ assert result.returncode == 0, f"snapshot failed:\n{result.stderr[-2000:]}"+ late = [r for r in result.stdout.splitlines() if r]+ assert not late, (+ f"These {len(late)} signal receivers connect ONLY when the API router is imported: {late}. "+ "They are wired as an import side effect of a viewset module, so with the lazy router they never "+ "connect in a process that doesn't build it (celery, temporal, migrate, shell). Connect them from "+ "the owning app's AppConfig.ready() so they wire at django.setup()."+ )+++# The diff guard above has a blind spot: it only catches a receiver that connects *late* (via the+# router). It cannot catch a receiver that connects in NO process — e.g. someone deletes an+# F401-suppressed side-effect import from an AppConfig.ready(), so the handler is never imported, never+# wired, and `before`/`after` both lack it (empty diff, green test) while the audit log silently stops.+# This pins the COMPLETE set of first-party receivers connected at setup against a committed baseline —+# a hand-curated "one representative per relocation" list proved both fiddly and incomplete (several+# ready()-wired receivers were never pinned). A receiver missing from the live set is silent audit/cache+# loss; an unexpected one is a new wiring to record deliberately. Regenerate the file with:+# UPDATE_SETUP_RECEIVERS_BASELINE=1 pytest posthog/test/test_startup_import_budget.py -k receivers_match+# Known granularity limit: receivers created in a loop share one qualname (e.g. the org-cache+# _connect_invalidation closures), so the set can't see one of their senders being dropped —+# Django stores sender identity as id(), which is not stable enough to snapshot.+_RECEIVERS_BASELINE = Path(__file__).parent / "setup_receivers_baseline.txt"++_SETUP_RECEIVERS_CAPTURE = """+import os+import weakref++os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")+import django++django.setup()+from django.contrib.auth import signals as auth_signals+from django.db.models import signals as model_signals+from posthog.models.signals import model_activity_signal++_FIRST_PARTY = ("posthog.", "products.", "ee.", "common.")+_SIGNALS = {+ name: getattr(model_signals, name)+ for name in ("pre_save", "post_save", "pre_delete", "post_delete", "m2m_changed", "pre_init", "post_init")+}+_SIGNALS |= {name: getattr(auth_signals, name) for name in ("user_logged_in", "user_logged_out", "user_login_failed")}+_SIGNALS["model_activity"] = model_activity_signal++out = set()+for signal_name, signal in _SIGNALS.items():+ for entry in signal.receivers:+ ref = entry[1]+ fn = ref() if isinstance(ref, weakref.ReferenceType) else ref+ if fn is None:+ continue+ module = getattr(fn, "__module__", "")+ qualname = getattr(fn, "__qualname__", "")+ if not module or not qualname:+ continue # partials/lambdas have no stable name; their repr would embed addresses+ path = f"{module}.{qualname}"+ if path.startswith(_FIRST_PARTY):+ out.add(f"{signal_name}:{path}")+print("\\n".join(sorted(out)))+"""+++def test_setup_receivers_match_baseline() -> None:+ result = subprocess.run(+ [sys.executable, "-c", _SETUP_RECEIVERS_CAPTURE],+ capture_output=True,+ text=True,+ timeout=120,+ )+ assert result.returncode == 0, f"receiver snapshot failed:\n{result.stderr[-2000:]}"+ connected = {line for line in result.stdout.splitlines() if ":" in line}+ assert len(connected) > 20, f"implausibly few receivers captured ({len(connected)}) — capture broken?"++ if os.environ.get("UPDATE_SETUP_RECEIVERS_BASELINE"):+ header = (+ "# First-party signal receivers connected after a bare django.setup(), as signal:module.qualname.\n"+ "# Maintained by test_setup_receivers_match_baseline — regenerate with:\n"+ "# UPDATE_SETUP_RECEIVERS_BASELINE=1 pytest posthog/test/test_startup_import_budget.py -k receivers_match\n"+ "# A receiver disappearing from this set means it connects in NO process (silent audit/cache loss):\n"+ "# restore its AppConfig.ready() wiring instead of deleting the line.\n"+ )+ _RECEIVERS_BASELINE.write_text(header + "\n".join(sorted(connected)) + "\n")+ return++ baseline = {line for line in _RECEIVERS_BASELINE.read_text().splitlines() if line and not line.startswith("#")}+ missing = sorted(baseline - connected)+ unexpected = sorted(connected - baseline)+ assert not missing, (+ f"These receivers are in setup_receivers_baseline.txt but NOT connected at django.setup(): {missing}. "+ "Their wiring was likely dropped (e.g. a 'remove unused import' cleanup deleted a # noqa: F401 "+ "side-effect import from an AppConfig.ready()), so they connect in no process and their audit/cache "+ "writes silently stop. Restore the ready() wiring in the owning app; only remove a baseline line when "+ "the receiver itself was deliberately deleted."+ )+ assert not unexpected, (+ f"These receivers connect at django.setup() but are not in setup_receivers_baseline.txt: {unexpected}. "+ "If the new wiring is deliberate (receiver in an import-light module, imported from the owning "+ "AppConfig.ready() — see docs/internal/django-startup-time.md), record it: "+ "UPDATE_SETUP_RECEIVERS_BASELINE=1 pytest posthog/test/test_startup_import_budget.py -k receivers_match"+ )+++# Cold-start trap the lazy router introduced and the whole pytest suite is blind to. With the AI agent+# core off the startup path, a fresh process no longer pre-imports it — so the FIRST reader of the MCP+# tool registry (the first MCP-tools API request in a new worker) becomes the first importer of the+# ee.hogai.tools -> chat_agent chain. A latent cycle in that chain (.task -> core.executor ->+# posthog.temporal.ai -> chat_agent.toolkit -> back into ee.hogai.tools) used to resolve only by+# import-order luck: the eager router imported the chain at setup, so by the time anything read the+# registry the modules were already complete. Remove that luck and the first request 500s on a+# half-initialized import. Every in-process test misses it because hundreds of test modules import the+# agent core long before the registry is read, so the cycle is always pre-resolved. A clean interpreter+# is the only place this reproduces — same reason the snapshot guards above run in a subprocess.+_MCP_REGISTRY_COLD_LOAD = """+import os+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")+import django+django.setup()+from ee.hogai.mcp_tool import mcp_tool_registry+names = mcp_tool_registry.get_names()+assert names, "registry returned no tools"+print(len(names))+"""+++def test_mcp_tool_registry_loads_cold_without_import_cycle() -> None:+ result = subprocess.run(+ [sys.executable, "-c", _MCP_REGISTRY_COLD_LOAD],+ capture_output=True,+ text=True,+ timeout=120,+ )+ assert result.returncode == 0, (+ "Reading the MCP tool registry in a cold process (mirrors the first MCP-tools request in a fresh "+ "worker) crashed. A module-level import in a tool submodule reaches back into ee.hogai.tools through "+ "the chat_agent chain, forming a cycle that only resolves when something imported the agent core "+ f"first — which no longer happens at django.setup(). Defer the offending import. Subprocess stderr:\n"+ f"{result.stderr[-2000:]}"+ )+++# The boot entrypoints (manage.py, wsgi.py, asgi.py) disable cyclic GC around django.setup()+# and freeze the survivors — boot allocations are ~all permanent, so collecting them only adds+# pauses (~300ms). The dangerous failure mode is the window not closing: GC left disabled means+# unbounded cycle growth in a long-lived process. This boots through manage.py and asserts both+# ends of the window.+def test_boot_gc_window_reenables_and_freezes() -> None:+ manage_py = Path(__file__).parents[2] / "manage.py"+ probe = (+ "import gc; "+ "assert gc.isenabled(), 'GC left disabled after boot'; "+ "count = gc.get_freeze_count(); "+ "assert count > 100_000, f'boot objects not frozen (freeze count {count})'; "+ "print('GC_BOOT_OK')"+ )+ result = subprocess.run(+ [sys.executable, str(manage_py), "shell", "-c", probe],+ capture_output=True,+ text=True,+ timeout=120,+ )+ assert result.returncode == 0, f"manage.py shell failed:\n{result.stderr[-2000:]}"+ assert "GC_BOOT_OK" in result.stdout, result.stdout[-500:]+++# Forward-looking counterpart to FORBIDDEN_AT_SETUP: that list catches *known* evicted modules+# returning; this catches a *new* heavy import nobody has named yet. There are deliberately no+# per-entry time budgets — absolute timings flake in CI — time is only the materiality gate+# for packages absent from the baseline. Captured with GC disabled, because a migrating gen2+# pause (~100ms) otherwise gets booked as self-time of whatever innocent module was executing.+_NEW_IMPORT_THRESHOLD_MS = 100+_FIRST_PARTY_ROOTS = ("posthog", "products", "ee", "common")+_IMPORT_BASELINE = Path(__file__).parent / "setup_import_baseline.txt"++_IMPORTTIME_CAPTURE = """+import gc+import os+gc.disable()+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")+import django+django.setup()+"""+++def _capture_setup_import_costs() -> dict[str, int]:+ result = subprocess.run(+ [sys.executable, "-X", "importtime", "-c", _IMPORTTIME_CAPTURE],+ capture_output=True,+ text=True,+ timeout=120,+ )+ assert result.returncode == 0, f"django.setup() failed:\n{result.stderr[-2000:]}"++ costs: dict[str, int] = {}+ for line in result.stderr.splitlines():+ match = re.match(r"import time:\s+(\d+) \|\s+\d+ \| +(\S+)$", line)+ if not match:+ continue+ self_us, module = int(match.group(1)), match.group(2)+ root = module.split(".")[0]+ if root in _FIRST_PARTY_ROOTS:+ # judged per module: aggregating posthog.* would be one permanent offender+ costs[module] = self_us+ else:+ costs[root] = costs.get(root, 0) + self_us+ return costs+++def test_no_new_heavy_imports_at_setup() -> None:+ baseline = {+ line.split("#")[0].strip() for line in _IMPORT_BASELINE.read_text().splitlines() if line.split("#")[0].strip()+ }+ contradictions = baseline & set(FORBIDDEN_AT_SETUP)+ assert not contradictions, (+ f"These names are in BOTH setup_import_baseline.txt and FORBIDDEN_AT_SETUP: {sorted(contradictions)}. "+ "The baseline permits what the forbidden list bans — someone likely baselined a module to dodge the "+ "new-import check while it remains deliberately evicted. Remove it from the baseline and defer the "+ "import that pulled it back in."+ )+ # Two captures, per-name minimum: the first boot on a cold machine pays page-cache misses+ # that can double a package's apparent cost (django measured 116ms cold vs ~67ms warm);+ # the minimum converges on the stable warm number, so the threshold compares like with like.+ first, second = _capture_setup_import_costs(), _capture_setup_import_costs()+ costs = {name: min(us, second.get(name, us)) for name, us in first.items()}++ threshold_us = _NEW_IMPORT_THRESHOLD_MS * 1000+ offenders = {name: us for name, us in costs.items() if us >= threshold_us and name not in baseline}+ assert not offenders, (+ f"New heavy import(s) appeared on the django.setup() path: "+ f"{ {name: f'{us / 1000:.0f}ms' for name, us in sorted(offenders.items(), key=lambda kv: -kv[1])} }. "+ "Every process (web, celery, temporal, migrate, shell, every CI job) now pays this on every boot. "+ "DO NOT add the package to setup_import_baseline.txt to make this pass — defer the import instead: "+ "function-local with `# noqa: PLC0415`, TYPE_CHECKING for type-only uses, a PEP 562 lazy facade for "+ "package aggregators, or a light activity_logging/visibility module for AppConfig.ready() wiring. "+ "Read docs/internal/django-startup-time.md for the patterns and the traps. To find the door, run: "+ "python -X importtime -c 'import gc; gc.disable(); import django; django.setup()' and trace the first "+ "importer of the offending package. Only if the package is genuinely required by every process during "+ "django.setup() may it be baselined, with a comment justifying why."+ )+++# Counterpart to the lazy-router guard for WEB specifically: the router must NOT build at a+# bare django.setup() (every process pays), but it MUST build at web-entrypoint import —+# pre-fork, so workers share it copy-on-write. Without this, each worker builds the router+# on its first live request (k8s probes short-circuit in middleware and never warm it),+# which measured at multiple seconds per worker after every deploy.+def test_web_entrypoint_prebuilds_the_router() -> None:+ probe = """+import os+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")+import posthog.wsgi # noqa: F401 — the real web entry; builds the app and resolves the URLconf+import sys+assert "posthog.api.rest_router" in sys.modules, "wsgi import did not build the API router"+from django.urls import get_resolver+assert get_resolver()._populated or get_resolver().url_patterns, "URLconf not resolved"+print("WSGI_PREBUILD_OK")+"""+ result = subprocess.run(+ [sys.executable, "-c", probe],+ capture_output=True,+ text=True,+ timeout=180,+ )+ assert result.returncode == 0, f"posthog.wsgi import failed:\n{result.stderr[-2000:]}"+ assert "WSGI_PREBUILD_OK" in result.stdout, result.stdout[-500:]diff --git a/posthog/utils.py b/posthog/utils.pyindex 51dc36b5de76..f2873add9fa2 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -50,7 +50,6 @@ from prometheus_client import Histogramfrom rest_framework import serializersfrom rest_framework.request import Requestfrom rest_framework.utils.encoders import JSONEncoder-from user_agents import parsefrom posthog.cloud_utils import get_cached_instance_license, is_cloudfrom posthog.constants import AvailableFeature@@ -915,6 +914,10 @@ def get_short_user_agent(request: HttpRequest) -> str:if not user_agent_str:return ""+ # Deferred: posthog.utils is imported all over at django.setup(); user_agents is only needed on+ # this request-time UA-parsing path, so keep it off the startup path.+ from user_agents import parse # noqa: PLC0415+user_agent = parse(user_agent_str)# strip the last (patch/build) number from the version, it can change frequentlydiff --git a/posthog/wsgi.py b/posthog/wsgi.pyindex df3254cb1c34..06b08faf00a3 100644--- a/posthog/wsgi.py+++ b/posthog/wsgi.py@@ -7,6 +7,7 @@ For more information on this file, seehttps://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/"""+import gcimport osfrom django.core.wsgi import get_wsgi_application@@ -20,7 +21,29 @@ os.environ.setdefault("SERVER_GATEWAY_INTERFACE", "WSGI")start_continuous_profiling()initialize_otel()-_django_application = get_wsgi_application()++# Boot allocations are almost all permanent, so cyclic GC during django.setup() only adds+# pauses (~300ms). Disable it for the boot, then freeze the survivors so later full+# collections skip them — which also maximizes copy-on-write sharing when a prototype+# process forks workers. See docs/internal/django-startup-time.md.+gc.disable()+try:+ _django_application = get_wsgi_application()++ # Resolve the URLconf now, at module load. The lazy API router otherwise builds on+ # each worker's FIRST LIVE REQUEST — k8s probes (/_livez, /_readyz) short-circuit in+ # middleware and never warm it — costing seconds per worker after every deploy.+ # Building it here keeps the cost at worker boot, behind readiness. (Verified against+ # the production image: Unit 1.35 loads this module once per application process — no+ # prototype fork/COW — so each worker pays its own boot, exactly like before the lazy+ # router.) Non-web processes (celery, temporal, migrate, shell) never load this module+ # and keep the lazy win.+ from django.urls import get_resolver++ _ = get_resolver().url_patterns # property access triggers the build+finally:+ gc.freeze()+ gc.enable()# Nginx Unit forks workers from a prototype process that imported this module, so# the query_cache RedisCluster must be discovered post-fork: a client built here atdiff --git a/products/actions/backend/activity_logging.py b/products/actions/backend/activity_logging.pynew file mode 100644index 000000000000..2568b2c583d8--- /dev/null+++ b/products/actions/backend/activity_logging.py@@ -0,0 +1,36 @@+# Activity-log receivers, kept in a module with no API/query-runner imports so+# AppConfig.ready() can wire them cheaply in every process type (celery, temporal,+# migrate) without pulling the viewset import graph into django.setup().++from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity+from posthog.models.signals import model_activity_signal, mutable_receiver++from products.actions.backend.models.action import Action+++@mutable_receiver(model_activity_signal, sender=Action)+def handle_action_change(+ sender, scope, before_update, after_update, activity, was_impersonated=False, **kwargs+) -> None:+ # Detect soft delete/restore by checking the deleted field+ if before_update and after_update:+ if not before_update.deleted and after_update.deleted:+ # Soft deleted+ activity = "deleted"+ elif before_update.deleted and not after_update.deleted:+ # Restored from soft delete+ activity = "updated"++ log_activity(+ organization_id=after_update.team.organization_id,+ team_id=after_update.team_id,+ user=after_update.created_by,+ was_impersonated=was_impersonated,+ item_id=after_update.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=after_update.name,+ ),+ )diff --git a/products/actions/backend/api/action.py b/products/actions/backend/api/action.pyindex 3bee02d175f5..7fa7e05aefc3 100644--- a/products/actions/backend/api/action.py+++ b/products/actions/backend/api/action.py@@ -29,10 +29,8 @@ from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetfrom posthog.constants import TREND_FILTER_TYPE_EVENTSfrom posthog.event_usage import report_user_actionfrom posthog.models import Team-from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activityfrom posthog.models.event.event import Selectorfrom posthog.models.property.util import build_selector_regex-from posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.rbac.user_access_control import UserAccessControlSerializerMixinfrom posthog.resource_limits import LimitKey, check_count_limit@@ -617,31 +615,3 @@ class ActionViewSet(a["reference_count"] = ref_counts.get(a["id"], 0)return Response({"results": actions_list})---@mutable_receiver(model_activity_signal, sender=Action)-def handle_action_change(- sender, scope, before_update, after_update, activity, was_impersonated=False, **kwargs-) -> None:- # Detect soft delete/restore by checking the deleted field- if before_update and after_update:- if not before_update.deleted and after_update.deleted:- # Soft deleted- activity = "deleted"- elif before_update.deleted and not after_update.deleted:- # Restored from soft delete- activity = "updated"-- log_activity(- organization_id=after_update.team.organization_id,- team_id=after_update.team_id,- user=after_update.created_by,- was_impersonated=was_impersonated,- item_id=after_update.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(scope, previous=before_update, current=after_update),- name=after_update.name,- ),- )diff --git a/products/actions/backend/apps.py b/products/actions/backend/apps.pyindex c3ff9bb5d6f0..f800027844b8 100644--- a/products/actions/backend/apps.py+++ b/products/actions/backend/apps.py@@ -5,3 +5,9 @@ class ActionsConfig(AppConfig):default_auto_field = "django.db.models.BigAutoField"name = "products.actions.backend"label = "actions"++ def ready(self) -> None:+ # Connect the action activity-log receiver at app-population, from a dedicated light+ # module. It must not live in the viewset module: that pulls posthog.api routing/utils+ # (and posthog.schema with them) into django.setup() for every process type.+ from products.actions.backend import activity_logging # noqa: F401, PLC0415diff --git a/products/ai_observability/backend/activity_logging.py b/products/ai_observability/backend/activity_logging.pynew file mode 100644index 000000000000..8b333bdec14d--- /dev/null+++ b/products/ai_observability/backend/activity_logging.py@@ -0,0 +1,61 @@+import copy+from typing import Any++from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity+from posthog.models.signals import model_activity_signal, mutable_receiver++from products.ai_observability.backend.models.evaluations import Evaluation++# Lives here, not in api/evaluations.py, so it can wire at AppConfig.ready() without dragging the+# evaluations viewset (which pulls scipy / google.genai / the ai_observability Temporal worker) onto+# the django.setup() path. Evaluations are mutated outside web requests, so the audit log must+# connect in every process.++_COMPILED_KEYS = ("bytecode", "bytecode_error")+++def _strip_compiled_from_conditions(conditions: list[dict[str, Any]] | None) -> list[dict[str, Any]]:+ if not conditions:+ return []+ return [{k: v for k, v in cond.items() if k not in _COMPILED_KEYS} for cond in conditions]+++def _strip_compiled_from_eval_config(config: dict[str, Any] | None) -> dict[str, Any]:+ if not config:+ return {}+ return {k: v for k, v in config.items() if k not in _COMPILED_KEYS}+++@mutable_receiver(model_activity_signal, sender=Evaluation)+def handle_evaluation_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ # `save()` re-derives `conditions[*].bytecode` and `evaluation_config.bytecode` on every write.+ # Strip them on shallow copies so the diff reflects user intent, not the compiler — mutating+ # `after_update` directly would also mutate the live instance DRF serialises for the response.+ before_log = copy.copy(before_update) if before_update is not None else None+ after_log = copy.copy(after_update) if after_update is not None else None+ for snapshot in (before_log, after_log):+ if snapshot is not None:+ snapshot.conditions = _strip_compiled_from_conditions(snapshot.conditions)+ snapshot.evaluation_config = _strip_compiled_from_eval_config(snapshot.evaluation_config)++ if before_update and after_update:+ before_deleted = getattr(before_update, "deleted", None)+ after_deleted = getattr(after_update, "deleted", None)+ if before_deleted is not None and after_deleted is not None and before_deleted != after_deleted:+ activity = "restored" if after_deleted is False else "deleted"++ log_activity(+ organization_id=after_update.team.organization_id,+ team_id=after_update.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=after_update.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_log, current=after_log),+ name=after_update.name,+ ),+ )diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.pyindex 1fa65f911b6d..300eafdb9b7a 100644--- a/products/ai_observability/backend/api/evaluations.py+++ b/products/ai_observability/backend/api/evaluations.py@@ -1,4 +1,3 @@-import copyimport jsonfrom typing import Any@@ -20,8 +19,6 @@ from posthog.api.monitoring import monitorfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.event_usage import report_user_action-from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity-from posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.permissions import AccessControlPermissionfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.temporal.ai_observability.message_utils import extract_text_from_messages@@ -763,53 +760,3 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi)return Response({"results": results})---_COMPILED_KEYS = ("bytecode", "bytecode_error")---def _strip_compiled_from_conditions(conditions: list[dict[str, Any]] | None) -> list[dict[str, Any]]:- if not conditions:- return []- return [{k: v for k, v in cond.items() if k not in _COMPILED_KEYS} for cond in conditions]---def _strip_compiled_from_eval_config(config: dict[str, Any] | None) -> dict[str, Any]:- if not config:- return {}- return {k: v for k, v in config.items() if k not in _COMPILED_KEYS}---@mutable_receiver(model_activity_signal, sender=Evaluation)-def handle_evaluation_change(- sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs-):- # `save()` re-derives `conditions[*].bytecode` and `evaluation_config.bytecode` on every write.- # Strip them on shallow copies so the diff reflects user intent, not the compiler — mutating- # `after_update` directly would also mutate the live instance DRF serialises for the response.- before_log = copy.copy(before_update) if before_update is not None else None- after_log = copy.copy(after_update) if after_update is not None else None- for snapshot in (before_log, after_log):- if snapshot is not None:- snapshot.conditions = _strip_compiled_from_conditions(snapshot.conditions)- snapshot.evaluation_config = _strip_compiled_from_eval_config(snapshot.evaluation_config)-- if before_update and after_update:- before_deleted = getattr(before_update, "deleted", None)- after_deleted = getattr(after_update, "deleted", None)- if before_deleted is not None and after_deleted is not None and before_deleted != after_deleted:- activity = "restored" if after_deleted is False else "deleted"-- log_activity(- organization_id=after_update.team.organization_id,- team_id=after_update.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=after_update.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(scope, previous=before_log, current=after_log),- name=after_update.name,- ),- )diff --git a/products/ai_observability/backend/apps.py b/products/ai_observability/backend/apps.pyindex 8b5504694f52..b91509371ece 100644--- a/products/ai_observability/backend/apps.py+++ b/products/ai_observability/backend/apps.py@@ -5,3 +5,9 @@ class AIObservabilityConfig(AppConfig):default_auto_field = "django.db.models.BigAutoField"name = "products.ai_observability.backend"label = "ai_observability"++ def ready(self) -> None:+ # Connect the Evaluation activity-log receiver at app-population. It lives in a light+ # activity_logging module (not the evaluations viewset, which pulls scipy / google.genai /+ # the ai_observability Temporal worker) so wiring it here stays off the django.setup() path.+ from products.ai_observability.backend import activity_logging # noqa: F401, PLC0415diff --git a/products/alerts/backend/activity_logging.py b/products/alerts/backend/activity_logging.pynew file mode 100644index 000000000000..73d7815960c8--- /dev/null+++ b/products/alerts/backend/activity_logging.py@@ -0,0 +1,162 @@+"""Activity-log and cleanup receivers for alert configuration changes.++Kept in their own import-light module so the alerts AppConfig can wire them at ready()+without importing the API module — whose module-scope imports reach the alert detector+stack (posthog.tasks.alerts -> numpy). The Temporal/celery alert-check paths mutate these+models directly, so the receivers must connect in every process, not just where the API+loads.+"""++import dataclasses+from typing import Optional++from django.db.models.signals import pre_delete+from django.dispatch import receiver++from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activity+from posthog.models.signals import model_activity_signal, mutable_receiver++from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold++[email protected](frozen=True)+class AlertConfigurationContext(ActivityContextBase):+ insight_id: Optional[int] = None+ insight_short_id: Optional[str] = None+ insight_name: Optional[str] = "Insight"+ alert_id: Optional[int] = None+ alert_name: Optional[str] = "Alert"++[email protected](frozen=True)+class AlertSubscriptionContext(AlertConfigurationContext):+ subscriber_name: Optional[str] = None+ subscriber_email: Optional[str] = None+++@mutable_receiver(model_activity_signal, sender=AlertConfiguration)+def handle_alert_configuration_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+) -> None:+ log_activity(+ organization_id=after_update.team.organization_id,+ team_id=after_update.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=after_update.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=after_update.name or f"Alert for {after_update.insight.name}",+ context=AlertConfigurationContext(+ insight_id=after_update.insight_id,+ insight_short_id=after_update.insight.short_id,+ insight_name=after_update.insight.name,+ ),+ ),+ )+++@mutable_receiver(model_activity_signal, sender=Threshold)+def handle_threshold_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+) -> None:+ alert_config = None+ if hasattr(after_update, "alertconfiguration_set"):+ alert_config = after_update.alertconfiguration_set.first()++ if alert_config:+ log_activity(+ organization_id=alert_config.team.organization_id,+ team_id=alert_config.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=alert_config.id,+ scope="AlertConfiguration",+ activity=activity,+ detail=Detail(+ changes=changes_between("Threshold", previous=before_update, current=after_update),+ type="threshold_change",+ context=AlertConfigurationContext(+ insight_id=alert_config.insight_id,+ insight_short_id=alert_config.insight.short_id,+ insight_name=alert_config.insight.name,+ alert_name=alert_config.name,+ ),+ ),+ )+++@mutable_receiver(model_activity_signal, sender=AlertSubscription)+def handle_alert_subscription_change(+ before_update, after_update, activity, user, was_impersonated=False, **kwargs+) -> None:+ alert_config = after_update.alert_configuration++ if alert_config:+ log_activity(+ organization_id=alert_config.team.organization_id,+ team_id=alert_config.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=alert_config.id,+ scope="AlertConfiguration",+ activity=activity,+ detail=Detail(+ changes=changes_between("AlertSubscription", previous=before_update, current=after_update),+ type="alert_subscription_change",+ context=AlertSubscriptionContext(+ insight_id=alert_config.insight_id,+ insight_short_id=alert_config.insight.short_id,+ insight_name=alert_config.insight.name,+ subscriber_name=after_update.user.get_full_name(),+ subscriber_email=after_update.user.email,+ alert_name=alert_config.name,+ ),+ ),+ )+++@receiver(pre_delete, sender=AlertConfiguration)+def cleanup_alert_hog_functions(sender, instance: AlertConfiguration, **kwargs) -> None:+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType++ for hog_function in HogFunction.objects.filter(+ team_id=instance.team_id,+ type=HogFunctionType.INTERNAL_DESTINATION,+ deleted=False,+ filters__contains={"properties": [{"key": "alert_id", "value": str(instance.id)}]},+ ):+ hog_function.enabled = False+ hog_function.deleted = True+ hog_function.save()+++@receiver(pre_delete, sender=AlertSubscription)+def handle_alert_subscription_delete(sender, instance, **kwargs) -> None:+ from posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonated++ alert_config = instance.alert_configuration++ if alert_config:+ log_activity(+ organization_id=alert_config.team.organization_id,+ team_id=alert_config.team_id,+ user=get_current_user(),+ was_impersonated=get_was_impersonated(),+ item_id=alert_config.id,+ scope="AlertConfiguration",+ activity="deleted",+ detail=Detail(+ type="alert_subscription_change",+ context=AlertSubscriptionContext(+ insight_id=alert_config.insight_id,+ insight_short_id=alert_config.insight.short_id,+ insight_name=alert_config.insight.name,+ subscriber_name=instance.user.get_full_name(),+ subscriber_email=instance.user.email,+ alert_name=alert_config.name,+ ),+ ),+ )diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.pyindex a924db51e907..38ff338dec0e 100644--- a/products/alerts/backend/api/alert.py+++ b/products/alerts/backend/api/alert.py@@ -1,13 +1,9 @@import uuid-import dataclasses-from typing import Optionalfrom zoneinfo import ZoneInfofrom django.contrib.postgres.search import TrigramSimilarity, TrigramWordSimilarityfrom django.db.models import F, OuterRef, Q, QuerySet, Subquery, Valuefrom django.db.models.functions import Coalesce-from django.db.models.signals import pre_delete-from django.dispatch import receiverfrom drf_spectacular.utils import OpenApiParameter, OpenApiTypes, extend_schema, extend_schema_viewfrom rest_framework import serializers, viewsets@@ -31,8 +27,6 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.event_usage import get_request_analytics_propertiesfrom posthog.helpers.trigram_search import MAX_SEARCH_LENGTH, MIN_NAME_TRIGRAM_SIMILARITY, normalize_search_termfrom posthog.models import User-from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activity-from posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.resource_limits import LimitKey, check_count_limitfrom posthog.schema_migrations.upgrade_manager import upgrade_queryfrom posthog.tasks.alerts.detector import MAX_DETECTOR_BREAKDOWN_VALUES@@ -46,7 +40,6 @@ from posthog.utils import relative_date_parsefrom products.alerts.backend.api.alert_schedule_restriction import AlertScheduleRestrictionfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold-from products.product_analytics.backend.api.insight import InsightBasicSerializerfrom products.product_analytics.backend.models.insight import Insight@@ -318,6 +311,11 @@ class AlertSerializer(serializers.ModelSerializer):]def to_representation(self, instance):+ # Deferred: the insight API serializer drags the product-analytics query-runner chain;+ # keeping it out of module scope lets this module connect its delete receivers at+ # AppConfig.ready() without pulling that chain onto startup.+ from products.product_analytics.backend.api.insight import InsightBasicSerializer # noqa: PLC0415+data = super().to_representation(instance)data["subscribed_users"] = UserBasicSerializer(instance.subscribed_users.all(), many=True, read_only=True).datadata["insight"] = InsightBasicSerializer(instance.insight).data@@ -956,146 +954,3 @@ class ThresholdViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelViewSet):scope_object = "alert"queryset = Threshold.objects.all()serializer_class = ThresholdWithAlertSerializer--[email protected](frozen=True)-class AlertConfigurationContext(ActivityContextBase):- insight_id: Optional[int] = None- insight_short_id: Optional[str] = None- insight_name: Optional[str] = "Insight"- alert_id: Optional[int] = None- alert_name: Optional[str] = "Alert"--[email protected](frozen=True)-class AlertSubscriptionContext(AlertConfigurationContext):- subscriber_name: Optional[str] = None- subscriber_email: Optional[str] = None---@mutable_receiver(model_activity_signal, sender=AlertConfiguration)-def handle_alert_configuration_change(- sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs-) -> None:- log_activity(- organization_id=after_update.team.organization_id,- team_id=after_update.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=after_update.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(scope, previous=before_update, current=after_update),- name=after_update.name or f"Alert for {after_update.insight.name}",- context=AlertConfigurationContext(- insight_id=after_update.insight_id,- insight_short_id=after_update.insight.short_id,- insight_name=after_update.insight.name,- ),- ),- )---@mutable_receiver(model_activity_signal, sender=Threshold)-def handle_threshold_change(- sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs-) -> None:- alert_config = None- if hasattr(after_update, "alertconfiguration_set"):- alert_config = after_update.alertconfiguration_set.first()-- if alert_config:- log_activity(- organization_id=alert_config.team.organization_id,- team_id=alert_config.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=alert_config.id,- scope="AlertConfiguration",- activity=activity,- detail=Detail(- changes=changes_between("Threshold", previous=before_update, current=after_update),- type="threshold_change",- context=AlertConfigurationContext(- insight_id=alert_config.insight_id,- insight_short_id=alert_config.insight.short_id,- insight_name=alert_config.insight.name,- alert_name=alert_config.name,- ),- ),- )---@mutable_receiver(model_activity_signal, sender=AlertSubscription)-def handle_alert_subscription_change(- before_update, after_update, activity, user, was_impersonated=False, **kwargs-) -> None:- alert_config = after_update.alert_configuration-- if alert_config:- log_activity(- organization_id=alert_config.team.organization_id,- team_id=alert_config.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=alert_config.id,- scope="AlertConfiguration",- activity=activity,- detail=Detail(- changes=changes_between("AlertSubscription", previous=before_update, current=after_update),- type="alert_subscription_change",- context=AlertSubscriptionContext(- insight_id=alert_config.insight_id,- insight_short_id=alert_config.insight.short_id,- insight_name=alert_config.insight.name,- subscriber_name=after_update.user.get_full_name(),- subscriber_email=after_update.user.email,- alert_name=alert_config.name,- ),- ),- )---@receiver(pre_delete, sender=AlertConfiguration)-def cleanup_alert_hog_functions(sender, instance: AlertConfiguration, **kwargs) -> None:- from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType-- for hog_function in HogFunction.objects.filter(- team_id=instance.team_id,- type=HogFunctionType.INTERNAL_DESTINATION,- deleted=False,- filters__contains={"properties": [{"key": "alert_id", "value": str(instance.id)}]},- ):- hog_function.enabled = False- hog_function.deleted = True- hog_function.save()---@receiver(pre_delete, sender=AlertSubscription)-def handle_alert_subscription_delete(sender, instance, **kwargs) -> None:- from posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonated-- alert_config = instance.alert_configuration-- if alert_config:- log_activity(- organization_id=alert_config.team.organization_id,- team_id=alert_config.team_id,- user=get_current_user(),- was_impersonated=get_was_impersonated(),- item_id=alert_config.id,- scope="AlertConfiguration",- activity="deleted",- detail=Detail(- type="alert_subscription_change",- context=AlertSubscriptionContext(- insight_id=alert_config.insight_id,- insight_short_id=alert_config.insight.short_id,- insight_name=alert_config.insight.name,- subscriber_name=instance.user.get_full_name(),- subscriber_email=instance.user.email,- alert_name=alert_config.name,- ),- ),- )diff --git a/products/alerts/backend/apps.py b/products/alerts/backend/apps.pyindex 8b3464b3b11d..0aaa887a84b4 100644--- a/products/alerts/backend/apps.py+++ b/products/alerts/backend/apps.py@@ -5,3 +5,11 @@ class AlertsConfig(AppConfig):default_auto_field = "django.db.models.BigAutoField"name = "products.alerts.backend"label = "alerts"++ def ready(self) -> None:+ # Connect the alert activity-log and cleanup receivers (hog-function teardown,+ # subscription delete logging) at app-population. They used to wire in via the viewset+ # import; the lazy API router no longer pulls that, so connect here. They live in their+ # own module because the API module imports the alert detector stack (numpy) at module+ # scope — see activity_logging's docstring.+ from products.alerts.backend import activity_logging # noqa: F401, PLC0415diff --git a/products/annotations/backend/activity_logging.py b/products/annotations/backend/activity_logging.pynew file mode 100644index 000000000000..716fbca05fda--- /dev/null+++ b/products/annotations/backend/activity_logging.py@@ -0,0 +1,63 @@+# Activity-log receivers, kept in a module with no API/query-runner imports so+# AppConfig.ready() can wire them cheaply in every process type (celery, temporal,+# migrate) without pulling the viewset import graph into django.setup().++import dataclasses+from typing import Optional++from django.db.models.signals import post_save+from django.dispatch import receiver++from posthog.event_usage import report_user_action+from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activity+from posthog.models.signals import model_activity_signal, mutable_receiver++from products.annotations.backend.models.annotation import Annotation++[email protected](frozen=True)+class AnnotationContext(ActivityContextBase):+ scope: str+ dashboard_id: Optional[int] = None+ dashboard_name: Optional[str] = None+ dashboard_item_id: Optional[int] = None+ dashboard_item_short_id: Optional[str] = None+ dashboard_item_name: Optional[str] = None+ recording_id: Optional[str] = None+++@receiver(post_save, sender=Annotation, dispatch_uid="hook-annotation-created")+def annotation_created(sender, instance, created, raw, using, **kwargs):+ if instance.created_by:+ event_name: str = "annotation created" if created else "annotation updated"+ report_user_action(instance.created_by, event_name, instance.get_analytics_metadata())+++@mutable_receiver(model_activity_signal, sender=Annotation)+def handle_annotation_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ context = AnnotationContext(+ scope=after_update.scope,+ dashboard_id=after_update.dashboard_id,+ dashboard_name=after_update.dashboard_name,+ dashboard_item_id=after_update.dashboard_item_id,+ dashboard_item_short_id=after_update.insight_short_id,+ dashboard_item_name=after_update.insight_name,+ recording_id=after_update.recording_id,+ )++ log_activity(+ organization_id=after_update.organization_id or after_update.team.organization_id,+ team_id=after_update.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=after_update.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=after_update.content,+ context=context,+ ),+ )diff --git a/products/annotations/backend/api/annotation.py b/products/annotations/backend/api/annotation.pyindex 13cab46cea87..42c242eaffdc 100644--- a/products/annotations/backend/api/annotation.py+++ b/products/annotations/backend/api/annotation.py@@ -1,10 +1,7 @@-import dataclassesfrom datetime import datetime-from typing import Any, Optional+from typing import Anyfrom django.db.models import Q, QuerySet-from django.db.models.signals import post_save-from django.dispatch import receiverfrom rest_framework import filters, pagination, serializers, viewsets@@ -12,26 +9,12 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.shared import UserBasicSerializer-from posthog.event_usage import report_user_action-from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activity-from posthog.models.signals import model_activity_signal, mutable_receiverfrom products.annotations.backend.models.annotation import Annotationfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.product_analytics.backend.models.insight import Insight[email protected](frozen=True)-class AnnotationContext(ActivityContextBase):- scope: str- dashboard_id: Optional[int] = None- dashboard_name: Optional[str] = None- dashboard_item_id: Optional[int] = None- dashboard_item_short_id: Optional[str] = None- dashboard_item_name: Optional[str] = None- recording_id: Optional[str] = None--class AnnotationSerializer(serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True)dashboard_id = serializers.IntegerField(required=False, allow_null=True)@@ -215,40 +198,3 @@ class AnnotationsViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Moreturn queryset.filter(Q(scope=Annotation.Scope.ORGANIZATION, organization_id=team.organization_id) | Q(team=team))---@receiver(post_save, sender=Annotation, dispatch_uid="hook-annotation-created")-def annotation_created(sender, instance, created, raw, using, **kwargs):- if instance.created_by:- event_name: str = "annotation created" if created else "annotation updated"- report_user_action(instance.created_by, event_name, instance.get_analytics_metadata())---@mutable_receiver(model_activity_signal, sender=Annotation)-def handle_annotation_change(- sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs-):- context = AnnotationContext(- scope=after_update.scope,- dashboard_id=after_update.dashboard_id,- dashboard_name=after_update.dashboard_name,- dashboard_item_id=after_update.dashboard_item_id,- dashboard_item_short_id=after_update.insight_short_id,- dashboard_item_name=after_update.insight_name,- recording_id=after_update.recording_id,- )-- log_activity(- organization_id=after_update.organization_id or after_update.team.organization_id,- team_id=after_update.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=after_update.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(scope, previous=before_update, current=after_update),- name=after_update.content,- context=context,- ),- )diff --git a/products/annotations/backend/api/test/test_annotation.py b/products/annotations/backend/api/test/test_annotation.pyindex 12cfeff79bff..3c95a548ba78 100644--- a/products/annotations/backend/api/test/test_annotation.py+++ b/products/annotations/backend/api/test/test_annotation.py@@ -19,7 +19,7 @@ from products.product_analytics.backend.models.insight import Insightclass TestAnnotation(APIBaseTest, QueryMatchingTest):- @patch("products.annotations.backend.api.annotation.report_user_action")+ @patch("products.annotations.backend.activity_logging.report_user_action")def test_retrieving_annotation(self, mock_capture: MagicMock) -> None:Annotation.objects.create(organization=self.organization,@@ -35,7 +35,7 @@ class TestAnnotation(APIBaseTest, QueryMatchingTest):assert len(response["results"]) == 1assert response["results"][0]["content"] == "hello world!"- @patch("products.annotations.backend.api.annotation.report_user_action")+ @patch("products.annotations.backend.activity_logging.report_user_action")def test_retrieving_annotation_is_not_n_plus_1(self, _mock_capture: MagicMock) -> None:with self.assertNumQueries(FuzzyInt(9, 10)), snapshot_postgres_queries_context(self):response = self.client.get(f"/api/projects/{self.team.id}/annotations/").json()@@ -105,7 +105,7 @@ class TestAnnotation(APIBaseTest, QueryMatchingTest):assert response_2.status_code == 200assert response_2.json()["results"] == []- @patch("products.annotations.backend.api.annotation.report_user_action")+ @patch("products.annotations.backend.activity_logging.report_user_action")def test_creating_annotation(self, mock_capture: MagicMock) -> None:team2 = Organization.objects.bootstrap(None)[2]@@ -136,7 +136,7 @@ class TestAnnotation(APIBaseTest, QueryMatchingTest):{"scope": "organization", "date_marker": date_marker},)- @patch("products.annotations.backend.api.annotation.report_user_action")+ @patch("products.annotations.backend.activity_logging.report_user_action")def test_can_create_annotations_as_a_bot(self, mock_capture: MagicMock) -> None:response = self.client.post(f"/api/projects/{self.team.id}/annotations/",@@ -156,7 +156,7 @@ class TestAnnotation(APIBaseTest, QueryMatchingTest):get_created_response = self.client.get(f"/api/projects/{self.team.id}/annotations/{instance.id}/")assert get_created_response.json()["creation_type"] == "GIT"- @patch("products.annotations.backend.api.annotation.report_user_action")+ @patch("products.annotations.backend.activity_logging.report_user_action")def test_downgrading_scope_from_org_to_project_uses_team_id_from_api(self, mock_capture: MagicMock) -> None:second_team = Team.objects.create(organization=self.organization, name="Second team")test_annotation = Annotation.objects.create(diff --git a/products/annotations/backend/apps.py b/products/annotations/backend/apps.pyindex a86b4e5a2ea3..781cee34f36d 100644--- a/products/annotations/backend/apps.py+++ b/products/annotations/backend/apps.py@@ -6,3 +6,9 @@ from django.apps import AppConfigclass AnnotationsConfig(AppConfig):name = "products.annotations.backend"label = "annotations"++ def ready(self) -> None:+ # Connect the annotation activity-logging / analytics receivers at app-population, from a+ # dedicated light module — importing the viewset module here would pull posthog.api+ # routing/utils (and posthog.schema with them) into django.setup() for every process type.+ from products.annotations.backend import activity_logging # noqa: F401, PLC0415diff --git a/products/batch_exports/backend/activity_logging.py b/products/batch_exports/backend/activity_logging.pynew file mode 100644index 000000000000..f97c28efa63f--- /dev/null+++ b/products/batch_exports/backend/activity_logging.py@@ -0,0 +1,70 @@+"""Activity-log receiver for BatchExport changes.++Kept in its own import-light module so the batch_exports AppConfig can wire it at+ready() without importing the API module (which pulls DRF, the batch export service+layer, and the Temporal client). The Temporal batch-export service mutates BatchExport+directly (pause/unpause), so the receiver must be connected in every process — workers+included — not just where the API loads.+"""++import dataclasses++from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activity+from posthog.models.signals import model_activity_signal, mutable_receiver++from products.batch_exports.backend.models.batch_export import BatchExport++[email protected](frozen=True)+class BatchExportContext(ActivityContextBase):+ name: str+ destination_type: str+ interval: str+ created_by_user_id: str | None+ created_by_user_email: str | None+ created_by_user_name: str | None+++@mutable_receiver(model_activity_signal, sender=BatchExport)+def handle_batch_export_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ from posthog.models.activity_logging.batch_export_utils import ( # noqa: PLC0415+ get_batch_export_created_by_info,+ get_batch_export_destination_type,+ get_batch_export_detail_name,+ )++ # Use after_update for create/update, before_update for delete+ batch_export = after_update or before_update++ if not batch_export:+ return++ destination_type = get_batch_export_destination_type(batch_export)+ created_by_user_id, created_by_user_email, created_by_user_name = get_batch_export_created_by_info(batch_export)+ detail_name = get_batch_export_detail_name(batch_export, destination_type)++ context = BatchExportContext(+ name=batch_export.name or "Unnamed Export",+ destination_type=destination_type,+ interval=batch_export.interval or "",+ created_by_user_id=created_by_user_id,+ created_by_user_email=created_by_user_email,+ created_by_user_name=created_by_user_name,+ )++ log_activity(+ organization_id=batch_export.team.organization_id,+ team_id=batch_export.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=batch_export.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=detail_name,+ context=context,+ ),+ )diff --git a/products/batch_exports/backend/api/batch_export.py b/products/batch_exports/backend/api/batch_export.pyindex 0c421f495368..ef98e8833145 100644--- a/products/batch_exports/backend/api/batch_export.py+++ b/products/batch_exports/backend/api/batch_export.py@@ -37,7 +37,6 @@ from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.utils import actionfrom posthog.event_usage import groupsfrom posthog.models import Team, User-from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activityfrom posthog.models.integration import (AzureBlobIntegration,AzureBlobIntegrationError,@@ -45,7 +44,6 @@ from posthog.models.integration import (DatabricksIntegrationError,Integration,)-from posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.temporal.common.client import sync_connectfrom posthog.utils import relative_date_parse, str_to_bool@@ -76,11 +74,9 @@ from products.batch_exports.backend.service import (sync_cancel_running_batch_export_backfill,unpause_batch_export,)-from products.batch_exports.backend.temporal.destinations.azure_blob_batch_export import (- SUPPORTED_COMPRESSIONS as AZURE_BLOB_SUPPORTED_COMPRESSIONS,-)-from products.batch_exports.backend.temporal.destinations.s3_batch_export import (- SUPPORTED_COMPRESSIONS as S3_SUPPORTED_COMPRESSIONS,+from products.batch_exports.backend.temporal.destinations.constants import (+ AZURE_BLOB_SUPPORTED_COMPRESSIONS,+ S3_SUPPORTED_COMPRESSIONS,)logger = structlog.get_logger(__name__)@@ -1714,58 +1710,3 @@ class BatchExportBackfillViewSet(raise ValidationError(f"Cannot cancel a backfill that is in '{batch_export_backfill.status}' status")return response.Response({"cancelled": True})--[email protected](frozen=True)-class BatchExportContext(ActivityContextBase):- name: str- destination_type: str- interval: str- created_by_user_id: str | None- created_by_user_email: str | None- created_by_user_name: str | None---@mutable_receiver(model_activity_signal, sender=BatchExport)-def handle_batch_export_change(- sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs-):- from posthog.models.activity_logging.batch_export_utils import (- get_batch_export_created_by_info,- get_batch_export_destination_type,- get_batch_export_detail_name,- )-- # Use after_update for create/update, before_update for delete- batch_export = after_update or before_update-- if not batch_export:- return-- destination_type = get_batch_export_destination_type(batch_export)- created_by_user_id, created_by_user_email, created_by_user_name = get_batch_export_created_by_info(batch_export)- detail_name = get_batch_export_detail_name(batch_export, destination_type)-- context = BatchExportContext(- name=batch_export.name or "Unnamed Export",- destination_type=destination_type,- interval=batch_export.interval or "",- created_by_user_id=created_by_user_id,- created_by_user_email=created_by_user_email,- created_by_user_name=created_by_user_name,- )-- log_activity(- organization_id=batch_export.team.organization_id,- team_id=batch_export.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=batch_export.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(scope, previous=before_update, current=after_update),- name=detail_name,- context=context,- ),- )diff --git a/products/batch_exports/backend/apps.py b/products/batch_exports/backend/apps.pyindex da202cca7ded..06f8d3df318d 100644--- a/products/batch_exports/backend/apps.py+++ b/products/batch_exports/backend/apps.py@@ -6,3 +6,11 @@ from django.apps import AppConfigclass BatchExportsConfig(AppConfig):name = "products.batch_exports.backend"label = "batch_exports"++ def ready(self) -> None:+ # The BatchExport activity-log receiver (handle_batch_export_change) used to wire in via the+ # viewset import. The lazy API router no longer pulls that, and the Temporal batch-export+ # service mutates BatchExport directly (pause/unpause), so without wiring here its audit-log+ # entries are silently dropped in the worker. It lives in its own module because the API+ # module is heavy (DRF, service layer, Temporal client) — see activity_logging's docstring.+ from products.batch_exports.backend import activity_logging # noqa: F401, PLC0415diff --git a/products/batch_exports/backend/temporal/__init__.py b/products/batch_exports/backend/temporal/__init__.pyindex 4dae968c56e6..713b817c7624 100644--- a/products/batch_exports/backend/temporal/__init__.py+++ b/products/batch_exports/backend/temporal/__init__.py@@ -1,104 +1,34 @@-from products.batch_exports.backend.temporal.backfill_batch_export import (- BackfillBatchExportWorkflow,- backfill_schedule,- create_batch_export_backfill_model,- get_backfill_info,- update_batch_export_backfill_model,-)-from products.batch_exports.backend.temporal.batch_exports import finish_batch_export_run, start_batch_export_run-from products.batch_exports.backend.temporal.destinations.azure_blob_batch_export import (- AzureBlobBatchExportWorkflow,- insert_into_azure_blob_activity_from_stage,-)-from products.batch_exports.backend.temporal.destinations.bigquery_batch_export import (- BigQueryBatchExportWorkflow,- insert_into_bigquery_activity_from_stage,-)-from products.batch_exports.backend.temporal.destinations.databricks_batch_export import (- DatabricksBatchExportWorkflow,- insert_into_databricks_activity_from_stage,-)-from products.batch_exports.backend.temporal.destinations.file_download_batch_export import (- FileDownloadBatchExportWorkflow,- export_to_file_download_bucket_with_temporary_credentials,- generate_file_downloads,-)-from products.batch_exports.backend.temporal.destinations.http_batch_export import (- HttpBatchExportWorkflow,- insert_into_http_activity,-)-from products.batch_exports.backend.temporal.destinations.postgres_batch_export import (- PostgresBatchExportWorkflow,- insert_into_postgres_activity_from_stage,-)-from products.batch_exports.backend.temporal.destinations.redshift_batch_export import (- RedshiftBatchExportWorkflow,- copy_into_redshift_activity_from_stage,- insert_into_redshift_activity_from_stage,-)-from products.batch_exports.backend.temporal.destinations.s3_batch_export import (- S3BatchExportWorkflow,- insert_into_s3_activity_from_stage,-)-from products.batch_exports.backend.temporal.destinations.snowflake_batch_export import (- SnowflakeBatchExportWorkflow,- insert_into_snowflake_activity_from_stage,-)-from products.batch_exports.backend.temporal.destinations.workflows_batch_export import (- WorkflowsBatchExportWorkflow,- insert_into_workflows_activity_from_stage,-)-from products.batch_exports.backend.temporal.monitoring import (- BatchExportMonitoringWorkflow,- fetch_exported_event_counts,- get_batch_export,- get_clickhouse_event_counts,- reconcile_event_counts,- update_batch_export_runs,-)-from products.batch_exports.backend.temporal.noop import NoOpWorkflow, noop_activity-from products.batch_exports.backend.temporal.pipeline.internal_stage import insert_into_internal_stage_activity+"""Batch export Temporal workflows and activities.-WORKFLOWS = [- BackfillBatchExportWorkflow,- BigQueryBatchExportWorkflow,- NoOpWorkflow,- PostgresBatchExportWorkflow,- RedshiftBatchExportWorkflow,- S3BatchExportWorkflow,- SnowflakeBatchExportWorkflow,- DatabricksBatchExportWorkflow,- AzureBlobBatchExportWorkflow,- HttpBatchExportWorkflow,- BatchExportMonitoringWorkflow,- WorkflowsBatchExportWorkflow,- FileDownloadBatchExportWorkflow,-]+The worker-facing aggregator (``WORKFLOWS`` / ``ACTIVITIES`` and every workflow class)+lives in ``workflows.py`` and is resolved lazily via PEP 562 ``__getattr__``. Eager+imports here would make *any* ``...temporal.<submodule>`` import pay for every+destination's vendor SDK (databricks, snowflake, bigquery, …) — which put ~1.6s on the+Django startup path when the API module imported a single constants table from one+destination. Only the Temporal worker needs the full set, and it still gets it through+``from products.batch_exports.backend.temporal import WORKFLOWS, ACTIVITIES``.+"""-ACTIVITIES = [- backfill_schedule,- create_batch_export_backfill_model,- get_backfill_info,- generate_file_downloads,- export_to_file_download_bucket_with_temporary_credentials,- start_batch_export_run,- finish_batch_export_run,- update_batch_export_backfill_model,- insert_into_bigquery_activity_from_stage,- insert_into_http_activity,- insert_into_postgres_activity_from_stage,- insert_into_redshift_activity_from_stage,- insert_into_workflows_activity_from_stage,- copy_into_redshift_activity_from_stage,- insert_into_snowflake_activity_from_stage,- noop_activity,- get_batch_export,- get_clickhouse_event_counts,- update_batch_export_runs,- insert_into_internal_stage_activity,- fetch_exported_event_counts,- reconcile_event_counts,- insert_into_s3_activity_from_stage,- insert_into_databricks_activity_from_stage,- insert_into_azure_blob_activity_from_stage,-]+import importlib+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from products.batch_exports.backend.temporal.workflows import ACTIVITIES, WORKFLOWS++__all__ = ["ACTIVITIES", "WORKFLOWS"]+++def __getattr__(name: str) -> Any:+ # Only the worker-facing aggregator names resolve through here; everything else raises+ # AttributeError so ``from <this package> import <submodule>`` falls back to a regular+ # submodule import. A catch-all would eagerly load the aggregator on that probe — and+ # deadlock on a circular import, since aggregated modules import siblings through the+ # package root (e.g. record_batch_model imports ``sql``).+ if name in __all__:+ workflows = importlib.import_module("products.batch_exports.backend.temporal.workflows")+ return getattr(workflows, name)+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(__all__))diff --git a/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py b/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.pyindex fbeb5c053823..c7d5d669e004 100644--- a/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py@@ -29,6 +29,9 @@ from products.batch_exports.backend.temporal.batch_exports import (get_data_interval,start_batch_export_run,)+from products.batch_exports.backend.temporal.destinations.constants import (+ AZURE_BLOB_SUPPORTED_COMPRESSIONS as SUPPORTED_COMPRESSIONS,+)from products.batch_exports.backend.temporal.destinations.utils import EXTERNAL_LOGGER, get_manifest_key, get_object_keyfrom products.batch_exports.backend.temporal.pipeline.consumer import Consumer, run_consumer_from_stagefrom products.batch_exports.backend.temporal.pipeline.entrypoint import execute_batch_export_using_internal_stage@@ -64,11 +67,6 @@ COMPRESSION_EXTENSIONS = {"snappy": "sz",}-SUPPORTED_COMPRESSIONS = {- "Parquet": ["zstd", "lz4", "snappy", "gzip", "brotli"],- "JSONLines": ["gzip", "brotli"],-}-LOGGER = get_write_only_logger(__name__)diff --git a/products/batch_exports/backend/temporal/destinations/constants.py b/products/batch_exports/backend/temporal/destinations/constants.pynew file mode 100644index 000000000000..687949bab3a0--- /dev/null+++ b/products/batch_exports/backend/temporal/destinations/constants.py@@ -0,0 +1,16 @@+"""Destination capability tables that must stay import-light.++The destination modules import their vendor SDKs at module scope, so anything that only+needs these tables — like the batch exports API serializers validating file format and+compression combinations — should import them from here instead of the destination module.+"""++S3_SUPPORTED_COMPRESSIONS: dict[str, list[str]] = {+ "Parquet": ["zstd", "lz4", "snappy", "gzip", "brotli"],+ "JSONLines": ["gzip", "brotli"],+}++AZURE_BLOB_SUPPORTED_COMPRESSIONS: dict[str, list[str]] = {+ "Parquet": ["zstd", "lz4", "snappy", "gzip", "brotli"],+ "JSONLines": ["gzip", "brotli"],+}diff --git a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py b/products/batch_exports/backend/temporal/destinations/s3_batch_export.pyindex 92992b4150a9..e7837c45a9ba 100644--- a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py@@ -37,6 +37,9 @@ from products.batch_exports.backend.temporal.batch_exports import (get_data_interval,start_batch_export_run,)+from products.batch_exports.backend.temporal.destinations.constants import (+ S3_SUPPORTED_COMPRESSIONS as SUPPORTED_COMPRESSIONS,+)from products.batch_exports.backend.temporal.destinations.utils import get_manifest_key, get_object_keyfrom products.batch_exports.backend.temporal.metrics import ExecutionTimeRecorderfrom products.batch_exports.backend.temporal.pipeline.consumer import Consumer, run_consumer_from_stage@@ -84,11 +87,6 @@ COMPRESSION_EXTENSIONS = {"lz4": "lz4",}-SUPPORTED_COMPRESSIONS = {- "Parquet": ["zstd", "lz4", "snappy", "gzip", "brotli"],- "JSONLines": ["gzip", "brotli"],-}-LOGGER = get_write_only_logger(__name__)EXTERNAL_LOGGER = get_logger("EXTERNAL")diff --git a/products/batch_exports/backend/temporal/workflows.py b/products/batch_exports/backend/temporal/workflows.pynew file mode 100644index 000000000000..4dae968c56e6--- /dev/null+++ b/products/batch_exports/backend/temporal/workflows.py@@ -0,0 +1,104 @@+from products.batch_exports.backend.temporal.backfill_batch_export import (+ BackfillBatchExportWorkflow,+ backfill_schedule,+ create_batch_export_backfill_model,+ get_backfill_info,+ update_batch_export_backfill_model,+)+from products.batch_exports.backend.temporal.batch_exports import finish_batch_export_run, start_batch_export_run+from products.batch_exports.backend.temporal.destinations.azure_blob_batch_export import (+ AzureBlobBatchExportWorkflow,+ insert_into_azure_blob_activity_from_stage,+)+from products.batch_exports.backend.temporal.destinations.bigquery_batch_export import (+ BigQueryBatchExportWorkflow,+ insert_into_bigquery_activity_from_stage,+)+from products.batch_exports.backend.temporal.destinations.databricks_batch_export import (+ DatabricksBatchExportWorkflow,+ insert_into_databricks_activity_from_stage,+)+from products.batch_exports.backend.temporal.destinations.file_download_batch_export import (+ FileDownloadBatchExportWorkflow,+ export_to_file_download_bucket_with_temporary_credentials,+ generate_file_downloads,+)+from products.batch_exports.backend.temporal.destinations.http_batch_export import (+ HttpBatchExportWorkflow,+ insert_into_http_activity,+)+from products.batch_exports.backend.temporal.destinations.postgres_batch_export import (+ PostgresBatchExportWorkflow,+ insert_into_postgres_activity_from_stage,+)+from products.batch_exports.backend.temporal.destinations.redshift_batch_export import (+ RedshiftBatchExportWorkflow,+ copy_into_redshift_activity_from_stage,+ insert_into_redshift_activity_from_stage,+)+from products.batch_exports.backend.temporal.destinations.s3_batch_export import (+ S3BatchExportWorkflow,+ insert_into_s3_activity_from_stage,+)+from products.batch_exports.backend.temporal.destinations.snowflake_batch_export import (+ SnowflakeBatchExportWorkflow,+ insert_into_snowflake_activity_from_stage,+)+from products.batch_exports.backend.temporal.destinations.workflows_batch_export import (+ WorkflowsBatchExportWorkflow,+ insert_into_workflows_activity_from_stage,+)+from products.batch_exports.backend.temporal.monitoring import (+ BatchExportMonitoringWorkflow,+ fetch_exported_event_counts,+ get_batch_export,+ get_clickhouse_event_counts,+ reconcile_event_counts,+ update_batch_export_runs,+)+from products.batch_exports.backend.temporal.noop import NoOpWorkflow, noop_activity+from products.batch_exports.backend.temporal.pipeline.internal_stage import insert_into_internal_stage_activity++WORKFLOWS = [+ BackfillBatchExportWorkflow,+ BigQueryBatchExportWorkflow,+ NoOpWorkflow,+ PostgresBatchExportWorkflow,+ RedshiftBatchExportWorkflow,+ S3BatchExportWorkflow,+ SnowflakeBatchExportWorkflow,+ DatabricksBatchExportWorkflow,+ AzureBlobBatchExportWorkflow,+ HttpBatchExportWorkflow,+ BatchExportMonitoringWorkflow,+ WorkflowsBatchExportWorkflow,+ FileDownloadBatchExportWorkflow,+]++ACTIVITIES = [+ backfill_schedule,+ create_batch_export_backfill_model,+ get_backfill_info,+ generate_file_downloads,+ export_to_file_download_bucket_with_temporary_credentials,+ start_batch_export_run,+ finish_batch_export_run,+ update_batch_export_backfill_model,+ insert_into_bigquery_activity_from_stage,+ insert_into_http_activity,+ insert_into_postgres_activity_from_stage,+ insert_into_redshift_activity_from_stage,+ insert_into_workflows_activity_from_stage,+ copy_into_redshift_activity_from_stage,+ insert_into_snowflake_activity_from_stage,+ noop_activity,+ get_batch_export,+ get_clickhouse_event_counts,+ update_batch_export_runs,+ insert_into_internal_stage_activity,+ fetch_exported_event_counts,+ reconcile_event_counts,+ insert_into_s3_activity_from_stage,+ insert_into_databricks_activity_from_stage,+ insert_into_azure_blob_activity_from_stage,+]diff --git a/products/dashboards/backend/activity_logging.py b/products/dashboards/backend/activity_logging.pynew file mode 100644index 000000000000..052a16e64606--- /dev/null+++ b/products/dashboards/backend/activity_logging.py@@ -0,0 +1,70 @@+from typing import Any, cast++from posthog.models.activity_logging.activity_log import ActivityScope, Detail, changes_between, log_activity+from posthog.models.signals import model_activity_signal, mutable_receiver+from posthog.models.team import Team+from posthog.models.user import User++from products.dashboards.backend.models.dashboard import Dashboard+from products.dashboards.backend.models.dashboard_widget import DashboardWidget++# Lives here, not in api/dashboard.py, so these can wire at AppConfig.ready() without dragging the+# dashboard viewset (which pulls scipy via the error-tracking widget query runners) onto the+# django.setup() path. Dashboards are mutated outside web requests, so the audit log must connect+# in every process.+++@mutable_receiver(model_activity_signal, sender=DashboardWidget)+def handle_dashboard_widget_change(+ sender: Any,+ scope: str,+ before_update: DashboardWidget | None,+ after_update: DashboardWidget | None,+ activity: str,+ user: User | None,+ was_impersonated: bool = False,+ **kwargs: Any,+) -> None:+ instance = after_update or before_update+ if instance is None:+ return+ organization_id = Team.objects.values_list("organization_id", flat=True).filter(pk=instance.team_id).first()+ log_activity(+ organization_id=organization_id,+ team_id=instance.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=instance.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(cast(ActivityScope, scope), previous=before_update, current=after_update),+ name=instance.name or instance.widget_type,+ ),+ )+++@mutable_receiver(model_activity_signal, sender=Dashboard)+def handle_dashboard_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ if before_update and after_update:+ before_deleted = getattr(before_update, "deleted", None)+ after_deleted = getattr(after_update, "deleted", None)+ if before_deleted is not None and after_deleted is not None and before_deleted != after_deleted:+ activity = "restored" if after_deleted is False else "deleted"++ log_activity(+ organization_id=after_update.team.organization_id,+ team_id=after_update.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=after_update.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=after_update.name,+ type="dashboard",+ ),+ )diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex ae315029b6c4..201666547bbc 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -50,10 +50,8 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.helpers import create_dashboard_from_templatefrom posthog.helpers.dashboard_templates import create_from_template, dashboard_template_from_creation_payloadfrom posthog.helpers.trigram_search import DESCRIPTION_FIELD, MAX_SEARCH_LENGTH, NAME_FIELD, apply_trigram_search-from posthog.models.activity_logging.activity_log import ActivityScope, Detail, changes_between, log_activityfrom posthog.models.file_system.file_system import create_or_update_file, delete_filefrom posthog.models.quick_filter import QuickFilter-from posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.models.tagged_item import TaggedItemfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -2835,59 +2833,3 @@ class LegacyDashboardsViewSet(DashboardsViewSet):class LegacyInsightViewSet(InsightViewSet):param_derived_from_user_current_team = "project_id"---@mutable_receiver(model_activity_signal, sender=DashboardWidget)-def handle_dashboard_widget_change(- sender: Any,- scope: str,- before_update: DashboardWidget | None,- after_update: DashboardWidget | None,- activity: str,- user: User | None,- was_impersonated: bool = False,- **kwargs: Any,-) -> None:- instance = after_update or before_update- if instance is None:- return- organization_id = Team.objects.values_list("organization_id", flat=True).filter(pk=instance.team_id).first()- log_activity(- organization_id=organization_id,- team_id=instance.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=instance.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(cast(ActivityScope, scope), previous=before_update, current=after_update),- name=instance.name or instance.widget_type,- ),- )---@mutable_receiver(model_activity_signal, sender=Dashboard)-def handle_dashboard_change(- sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs-):- if before_update and after_update:- before_deleted = getattr(before_update, "deleted", None)- after_deleted = getattr(after_update, "deleted", None)- if before_deleted is not None and after_deleted is not None and before_deleted != after_deleted:- activity = "restored" if after_deleted is False else "deleted"-- log_activity(- organization_id=after_update.team.organization_id,- team_id=after_update.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=after_update.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(scope, previous=before_update, current=after_update),- name=after_update.name,- type="dashboard",- ),- )diff --git a/products/dashboards/backend/apps.py b/products/dashboards/backend/apps.pyindex 95c5cd86939b..ad7a4280958a 100644--- a/products/dashboards/backend/apps.py+++ b/products/dashboards/backend/apps.py@@ -7,3 +7,11 @@ class DashboardsConfig(AppConfig):default_auto_field = "django.db.models.BigAutoField"name = "products.dashboards.backend"label = "dashboards"++ def ready(self) -> None:+ # Connect the dashboard/dashboard-widget activity-log receivers at app-population. They used+ # to wire in as an import side effect of the viewset module; the lazy API router no longer+ # pulls that, so a process that never builds the router (celery, temporal, migrate) would+ # drop audit logs on dashboard writes. They live in a light activity_logging module because+ # the dashboard viewset pulls scipy via the error-tracking widget query runners.+ from products.dashboards.backend import activity_logging # noqa: F401, PLC0415diff --git a/products/data_warehouse/backend/activity_logging.py b/products/data_warehouse/backend/activity_logging.pynew file mode 100644index 000000000000..4e3bd18e6aa2--- /dev/null+++ b/products/data_warehouse/backend/activity_logging.py@@ -0,0 +1,122 @@+import dataclasses++from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activity+from posthog.models.activity_logging.external_data_utils import (+ get_external_data_source_created_by_info,+ get_external_data_source_detail_name,+)+from posthog.models.signals import model_activity_signal, mutable_receiver++from products.warehouse_sources.backend.models.external_data_schema import (+ ExternalDataSchema,+ sync_frequency_interval_to_sync_frequency,+)+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource++# Lives here, not in the api/external_data_{schema,source}.py viewsets, so these can wire at+# AppConfig.ready() without dragging those viewsets (which pull dlt via the data-import pipeline+# imports) onto the django.setup() path. The Temporal data-import workflows mutate these models, so+# the audit log must connect there too.++[email protected](frozen=True)+class ExternalDataSchemaContext(ActivityContextBase):+ name: str+ sync_type: str | None+ sync_frequency: str | None+ source_id: str+ source_type: str+++@mutable_receiver(model_activity_signal, sender=ExternalDataSchema)+def handle_external_data_schema_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ if activity == "created":+ # We don't want to log the creation of schemas as they get bulk created on source creation+ return++ external_data_schema = after_update or before_update++ if not external_data_schema:+ return++ source = external_data_schema.source+ source_type = source.source_type if source else ""++ sync_frequency = None+ if external_data_schema.sync_frequency_interval:+ sync_frequency = sync_frequency_interval_to_sync_frequency(external_data_schema.sync_frequency_interval)++ context = ExternalDataSchemaContext(+ name=external_data_schema.name or "",+ sync_type=external_data_schema.sync_type,+ sync_frequency=sync_frequency,+ source_id=str(source.id) if source else "",+ source_type=source_type,+ )++ log_activity(+ organization_id=external_data_schema.team.organization_id,+ team_id=external_data_schema.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=external_data_schema.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=external_data_schema.name,+ context=context,+ ),+ )++[email protected](frozen=True)+class ExternalDataSourceContext(ActivityContextBase):+ source_type: str+ prefix: str | None+ description: str | None+ created_by_user_id: str | None+ created_by_user_email: str | None+ created_by_user_name: str | None+++@mutable_receiver(model_activity_signal, sender=ExternalDataSource)+def handle_external_data_source_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ # Use after_update for create/update, before_update for delete+ external_data_source = after_update or before_update++ if not external_data_source:+ return++ created_by_user_id, created_by_user_email, created_by_user_name = get_external_data_source_created_by_info(+ external_data_source+ )+ detail_name = get_external_data_source_detail_name(external_data_source)++ context = ExternalDataSourceContext(+ source_type=external_data_source.source_type or "",+ prefix=external_data_source.prefix,+ description=external_data_source.description,+ created_by_user_id=created_by_user_id,+ created_by_user_email=created_by_user_email,+ created_by_user_name=created_by_user_name,+ )++ log_activity(+ organization_id=external_data_source.team.organization_id,+ team_id=external_data_source.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=external_data_source.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=detail_name,+ context=context,+ ),+ )diff --git a/products/data_warehouse/backend/api/external_data_schema.py b/products/data_warehouse/backend/api/external_data_schema.pyindex d8d803a6fc7a..895513b5bf0e 100644--- a/products/data_warehouse/backend/api/external_data_schema.py+++ b/products/data_warehouse/backend/api/external_data_schema.py@@ -1,5 +1,4 @@import datetime as dt-import dataclassesfrom collections.abc import Callablefrom typing import Any, Optional@@ -16,8 +15,6 @@ from posthog.hogql.database.database import Databasefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import actionfrom posthog.exceptions_capture import capture_exception-from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activity-from posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.temporal.data_imports.cdc.adapters import get_cdc_adapterfrom posthog.temporal.data_imports.sources import SourceRegistryfrom posthog.temporal.data_imports.sources.common.base import WebhookSource@@ -1037,60 +1034,3 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):}return Response(status=status.HTTP_200_OK, data=data)--[email protected](frozen=True)-class ExternalDataSchemaContext(ActivityContextBase):- name: str- sync_type: str | None- sync_frequency: str | None- source_id: str- source_type: str---@mutable_receiver(model_activity_signal, sender=ExternalDataSchema)-def handle_external_data_schema_change(- sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs-):- if activity == "created":- # We don't want to log the creation of schemas as they get bulk created on source creation- return-- external_data_schema = after_update or before_update-- if not external_data_schema:- return-- source = external_data_schema.source- source_type = source.source_type if source else ""-- sync_frequency = None- if external_data_schema.sync_frequency_interval:- from products.warehouse_sources.backend.models.external_data_schema import (- sync_frequency_interval_to_sync_frequency,- )-- sync_frequency = sync_frequency_interval_to_sync_frequency(external_data_schema.sync_frequency_interval)-- context = ExternalDataSchemaContext(- name=external_data_schema.name or "",- sync_type=external_data_schema.sync_type,- sync_frequency=sync_frequency,- source_id=str(source.id) if source else "",- source_type=source_type,- )-- log_activity(- organization_id=external_data_schema.team.organization_id,- team_id=external_data_schema.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=external_data_schema.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(scope, previous=before_update, current=after_update),- name=external_data_schema.name,- context=context,- ),- )diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex 6200c54209b7..84ae2c7641fb 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -33,12 +33,6 @@ from posthog.hogql.database.database import Databasefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import actionfrom posthog.exceptions_capture import capture_exception-from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activity-from posthog.models.activity_logging.external_data_utils import (- get_external_data_source_created_by_info,- get_external_data_source_detail_name,-)-from posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.models.user import Userfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.rbac.user_access_control import UserAccessControlSerializerMixin@@ -2905,53 +2899,3 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi"error": result.error,},)--[email protected](frozen=True)-class ExternalDataSourceContext(ActivityContextBase):- source_type: str- prefix: str | None- description: str | None- created_by_user_id: str | None- created_by_user_email: str | None- created_by_user_name: str | None---@mutable_receiver(model_activity_signal, sender=ExternalDataSource)-def handle_external_data_source_change(- sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs-):- # Use after_update for create/update, before_update for delete- external_data_source = after_update or before_update-- if not external_data_source:- return-- created_by_user_id, created_by_user_email, created_by_user_name = get_external_data_source_created_by_info(- external_data_source- )- detail_name = get_external_data_source_detail_name(external_data_source)-- context = ExternalDataSourceContext(- source_type=external_data_source.source_type or "",- prefix=external_data_source.prefix,- description=external_data_source.description,- created_by_user_id=created_by_user_id,- created_by_user_email=created_by_user_email,- created_by_user_name=created_by_user_name,- )-- log_activity(- organization_id=external_data_source.team.organization_id,- team_id=external_data_source.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=external_data_source.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(scope, previous=before_update, current=after_update),- name=detail_name,- context=context,- ),- )diff --git a/products/data_warehouse/backend/apps.py b/products/data_warehouse/backend/apps.pyindex 3e0d61df306d..91f091182197 100644--- a/products/data_warehouse/backend/apps.py+++ b/products/data_warehouse/backend/apps.py@@ -5,3 +5,11 @@ class DataWarehouseConfig(AppConfig):default_auto_field = "django.db.models.BigAutoField"name = "products.data_warehouse.backend"label = "data_warehouse"++ def ready(self) -> None:+ # Connect the external-data-source / -schema activity-log receivers at app-population. They+ # used to wire in as an import side effect of the viewset modules; the lazy API router no+ # longer pulls that, so a process that never builds the router (notably the Temporal data+ # import workflows, which mutate these models heavily) would drop audit logs. They live in a+ # light activity_logging module because both viewsets pull in dlt via the data-import chain.+ from products.data_warehouse.backend import activity_logging # noqa: F401, PLC0415diff --git a/products/data_warehouse/backend/models/test/test_table.py b/products/data_warehouse/backend/models/test/test_table.pyindex 7444f4028ba8..4ab086272c84 100644--- a/products/data_warehouse/backend/models/test/test_table.py+++ b/products/data_warehouse/backend/models/test/test_table.py@@ -354,7 +354,7 @@ class TestTable(BaseTest):chdb_result = type("R", (), {"__str__": lambda self: chdb_csv})()with (patch("products.warehouse_sources.backend.models.table.TEST", False),- patch("products.warehouse_sources.backend.models.table.chdb.query", return_value=chdb_result) as chdb_query,+ patch("chdb.query", return_value=chdb_result) as chdb_query,):getattr(table, method_name)()diff --git a/products/data_warehouse/backend/test/test_repair_qualified_schema_duplicates.py b/products/data_warehouse/backend/test/test_repair_qualified_schema_duplicates.pyindex dbfc0b556c09..e36115537b99 100644--- a/products/data_warehouse/backend/test/test_repair_qualified_schema_duplicates.py+++ b/products/data_warehouse/backend/test/test_repair_qualified_schema_duplicates.py@@ -11,7 +11,8 @@ from products.warehouse_sources.backend.models.external_data_schema import Exterfrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTable-_TEMPORAL = "products.warehouse_sources.backend.models.external_data_schema"+# Patched at the defining module: update_should_sync imports these function-locally now.+_TEMPORAL = "products.data_warehouse.backend.data_load.service"class TestRepairQualifiedSchemaDuplicates(BaseTest):diff --git a/products/early_access_features/backend/apps.py b/products/early_access_features/backend/apps.pyindex c945a83b8bda..ac707264c606 100644--- a/products/early_access_features/backend/apps.py+++ b/products/early_access_features/backend/apps.py@@ -15,8 +15,6 @@ class EarlyAccessFeaturesConfig(AppConfig):from posthog.models.activity_logging.activity_log import Detail, log_activityfrom posthog.models.activity_logging.model_activity import is_impersonated_session- from products.early_access_features.backend.api import _set_enrollment_filters-def _with_feature_flag(queryset):return queryset.select_related("feature_flag")@@ -33,6 +31,11 @@ class EarlyAccessFeaturesConfig(AppConfig):def _pre_delete(context, feature):feature_flag = getattr(feature, "feature_flag", None)if feature_flag:+ # Deferred: the api module imports the feature_flag -> dashboard -> error_tracking+ # query-runner chain (-> scipy) at module scope. This hook only runs on actual+ # deletion, so importing it here keeps that chain off AppConfig.ready() / startup.+ from products.early_access_features.backend.api import _set_enrollment_filters # noqa: PLC0415+feature_flag.filters = _set_enrollment_filters(dict(feature_flag.filters or {}), enrolled=None)feature_flag.save(update_fields=["filters"])diff --git a/products/experiments/backend/models/__init__.py b/products/experiments/backend/models/__init__.pyindex fbca08f7c37b..2ce54cd55b53 100644--- a/products/experiments/backend/models/__init__.py+++ b/products/experiments/backend/models/__init__.py@@ -1,3 +1,4 @@from .team_experiments_config import TeamExperimentsConfig+from .web_experiment import WebExperiment-__all__ = ["TeamExperimentsConfig"]+__all__ = ["TeamExperimentsConfig", "WebExperiment"]diff --git a/products/feature_flags/backend/activity_logging.py b/products/feature_flags/backend/activity_logging.pynew file mode 100644index 000000000000..2b9bba27056b--- /dev/null+++ b/products/feature_flags/backend/activity_logging.py@@ -0,0 +1,58 @@+from posthog.models.activity_logging.activity_log import Detail, Trigger, changes_between, log_activity+from posthog.models.signals import model_activity_signal, mutable_receiver++from products.feature_flags.backend.models.feature_flag import FeatureFlag++# Lives here, not in api/feature_flag.py, so it can wire at AppConfig.ready() without dragging that+# viewset (which pulls scipy via the dashboard -> error-tracking query runners cross-import) onto the+# django.setup() path. Flags are mutated outside web requests (cohort recalculation, scheduled+# changes), so the audit log must connect in every process.+++@mutable_receiver(model_activity_signal, sender=FeatureFlag)+def handle_feature_flag_change(+ sender,+ scope,+ before_update,+ after_update,+ activity,+ was_impersonated=False,+ **kwargs,+):+ # Extract scheduled change context if present+ scheduled_change_context = getattr(after_update, "_scheduled_change_context", {})+ scheduled_change_id = scheduled_change_context.get("scheduled_change_id")+ is_scheduled_change = scheduled_change_id is not None++ # Create trigger info for scheduled changes+ trigger = None+ if is_scheduled_change:+ trigger = Trigger(+ job_type="scheduled_change",+ job_id=str(scheduled_change_id),+ payload={"scheduled_change_id": scheduled_change_id},+ )++ changes = changes_between(scope, previous=before_update, current=after_update)+ resolved_activity = activity+ deleted_change = next((change for change in changes if change.field == "deleted"), None)+ if deleted_change:+ if bool(deleted_change.after):+ resolved_activity = "deleted"+ elif bool(deleted_change.before):+ resolved_activity = "restored"++ log_activity(+ organization_id=after_update.team.organization_id,+ team_id=after_update.team_id,+ user=after_update.last_modified_by,+ was_impersonated=was_impersonated,+ item_id=after_update.id,+ scope=scope,+ activity=resolved_activity,+ detail=Detail(+ changes=changes,+ name=after_update.key,+ trigger=trigger,+ ),+ )diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 5f4b2e906443..a16bb720754c 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -46,7 +46,7 @@ from posthog.exceptions import Conflictfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.dashboard_templates import add_enriched_insights_to_feature_flag_dashboardfrom posthog.models import Team-from posthog.models.activity_logging.activity_log import Detail, changes_between, load_activity, log_activity+from posthog.models.activity_logging.activity_log import Detail, load_activity, log_activityfrom posthog.models.activity_logging.activity_page import ActivityLogPaginatedResponseSerializer, activity_page_responsefrom posthog.models.activity_logging.model_activity import ImpersonatedContext, is_impersonated_sessionfrom posthog.models.person.point_in_time_properties import (@@ -54,7 +54,6 @@ from posthog.models.person.point_in_time_properties import (get_person_and_distinct_ids_for_identifier,)from posthog.models.property import Property-from posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.permissions import TeamSecretTokenPermissionfrom posthog.queries.base import determine_parsed_date_for_property_matchingfrom posthog.rate_limit import BurstRateThrottle, ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle@@ -572,7 +571,7 @@ class EvaluationContextSerializerMixin(serializers.Serializer):def _log_evaluation_context_change(self, obj: FeatureFlag, before: list[str], after: list[str]) -> None:from loginas.utils import is_impersonated_session- from posthog.models.activity_logging.activity_log import Change, Detail, log_activity+ from posthog.models.activity_logging.activity_log import Change, Detailrequest = self.context.get("request")was_impersonated = is_impersonated_session(request) if request else False@@ -3873,57 +3872,6 @@ class FeatureFlagViewSet(return activity_page_response(activity_page, limit, page, request)-@mutable_receiver(model_activity_signal, sender=FeatureFlag)-def handle_feature_flag_change(- sender,- scope,- before_update,- after_update,- activity,- was_impersonated=False,- **kwargs,-):- # Extract scheduled change context if present- scheduled_change_context = getattr(after_update, "_scheduled_change_context", {})- scheduled_change_id = scheduled_change_context.get("scheduled_change_id")- is_scheduled_change = scheduled_change_id is not None-- # Create trigger info for scheduled changes- trigger = None- if is_scheduled_change:- from posthog.models.activity_logging.activity_log import Trigger-- trigger = Trigger(- job_type="scheduled_change",- job_id=str(scheduled_change_id),- payload={"scheduled_change_id": scheduled_change_id},- )-- changes = changes_between(scope, previous=before_update, current=after_update)- resolved_activity = activity- deleted_change = next((change for change in changes if change.field == "deleted"), None)- if deleted_change:- if bool(deleted_change.after):- resolved_activity = "deleted"- elif bool(deleted_change.before):- resolved_activity = "restored"-- log_activity(- organization_id=after_update.team.organization_id,- team_id=after_update.team_id,- user=after_update.last_modified_by,- was_impersonated=was_impersonated,- item_id=after_update.id,- scope=scope,- activity=resolved_activity,- detail=Detail(- changes=changes,- name=after_update.key,- trigger=trigger,- ),- )--class LegacyFeatureFlagViewSet(FeatureFlagViewSet):param_derived_from_user_current_team = "project_id"diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambrindex c94809214292..90c02e34b16e 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr@@ -3853,6 +3853,28 @@'''# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.82+ '''+ SELECT "ee_featureflagroleaccess"."id",+ "ee_featureflagroleaccess"."feature_flag_id",+ "ee_featureflagroleaccess"."role_id",+ "ee_featureflagroleaccess"."added_at",+ "ee_featureflagroleaccess"."updated_at"+ FROM "ee_featureflagroleaccess"+ WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.83+ '''+ SELECT "ee_featureflagroleaccess"."id",+ "ee_featureflagroleaccess"."feature_flag_id",+ "ee_featureflagroleaccess"."role_id",+ "ee_featureflagroleaccess"."added_at",+ "ee_featureflagroleaccess"."updated_at"+ FROM "ee_featureflagroleaccess"+ WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.84'''SELECT "posthog_experiment"."id","posthog_experiment"."name",@@ -3889,7 +3911,7 @@AND NOT "posthog_experiment"."deleted")'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.83+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.85'''SELECT "posthog_experiment"."id","posthog_experiment"."name",@@ -3926,7 +3948,7 @@AND NOT "posthog_experiment"."deleted")'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.84+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.86'''SELECT "posthog_survey"."id","posthog_survey"."team_id",@@ -3971,7 +3993,7 @@WHERE "posthog_survey"."linked_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.85+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.87'''SELECT "posthog_earlyaccessfeature"."id","posthog_earlyaccessfeature"."team_id",@@ -3986,7 +4008,7 @@WHERE "posthog_earlyaccessfeature"."feature_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.86+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.88'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -4037,7 +4059,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.87+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.89'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -4066,7 +4088,15 @@AND "posthog_featureflagdashboards"."feature_flag_id" = 99999)'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.88+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.9+ '''+ SELECT "posthog_team"."id",+ "posthog_team"."organization_id"+ FROM "posthog_team"+ WHERE "posthog_team"."organization_id" IN ('00000000-0000-0000-0000-000000000000'::uuid)+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.90'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -4117,7 +4147,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.89+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.91'''SELECT 1 AS "a"FROM "posthog_team"@@ -4126,15 +4156,7 @@LIMIT 1'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.9- '''- SELECT "posthog_team"."id",- "posthog_team"."organization_id"- FROM "posthog_team"- WHERE "posthog_team"."organization_id" IN ('00000000-0000-0000-0000-000000000000'::uuid)- '''-# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.90+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.92'''SELECT "posthog_featureflagevaluationcontext"."id","posthog_featureflagevaluationcontext"."feature_flag_id",@@ -4149,7 +4171,7 @@WHERE "posthog_featureflagevaluationcontext"."feature_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.91+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.93'''SELECT "posthog_tag"."name" AS "tag__name"FROM "posthog_taggeditem"diff --git a/products/feature_flags/backend/apps.py b/products/feature_flags/backend/apps.pyindex d13bbcbc667c..077ddc443a6c 100644--- a/products/feature_flags/backend/apps.py+++ b/products/feature_flags/backend/apps.py@@ -8,3 +8,18 @@ class FeatureFlagsConfig(AppConfig):default_auto_field = "django.db.models.AutoField"name = "products.feature_flags.backend"label = "feature_flags"++ def ready(self) -> None:+ # Connect the flag-cache invalidation receivers at app-population. They used to ride in+ # as an import side effect of a viewset module; with the lazy API router that no longer+ # happens, so a process that never builds the router (celery, temporal, migrate, shell)+ # would stop invalidating the flags cache on flag/cohort/team writes. Wire them here.+ # Same story for the flag activity-log receiver (handle_feature_flag_change), which used to+ # ride in on the viewset import. Flags are mutated in non-web processes (cohort recalculation+ # etc.), so its audit logs must wire here too. It lives in a light activity_logging module+ # because the flag viewset pulls scipy via the dashboard -> error-tracking query runners.+ from products.feature_flags.backend import ( # noqa: F401, PLC0415+ activity_logging, # noqa: F401, PLC0415+ flags_cache,+ local_evaluation,+ )diff --git a/products/growth/backend/cross_sell_candidate_selector.py b/products/growth/backend/cross_sell_candidate_selector.pyindex f79865815dbf..fc2fe827ceb5 100644--- a/products/growth/backend/cross_sell_candidate_selector.py+++ b/products/growth/backend/cross_sell_candidate_selector.py@@ -1,8 +1,6 @@from collections import defaultdictfrom dataclasses import dataclass, field-import numpy as np-from posthog.schema import ProductItemCategory, ProductKeyfrom posthog.products import Products@@ -209,6 +207,10 @@ class CrossSellCandidateSelector:sampling from the candidate set. Returns an empty list when thereare no eligible candidates."""+ # this module loads at django.setup() via the file-system product list — numpy at+ # module scope would put it on every process's startup path+ import numpy as np # noqa: PLC0415+weighted = self._get_weighted_candidates()if not weighted:return []diff --git a/products/logs/backend/activity_logging.py b/products/logs/backend/activity_logging.pynew file mode 100644index 000000000000..55e7ad11a7ef--- /dev/null+++ b/products/logs/backend/activity_logging.py@@ -0,0 +1,67 @@+# Activity-log receivers, kept in a module with no API/query-runner imports so+# AppConfig.ready() can wire them cheaply in every process type (celery, temporal,+# migrate) without pulling the viewset import graph into django.setup().++from typing import Any, cast++from posthog.models.activity_logging.activity_log import ActivityScope, Detail, changes_between, log_activity+from posthog.models.signals import model_activity_signal, mutable_receiver+from posthog.models.user import User++from products.logs.backend.models import LogsAlertConfiguration, LogsExclusionRule+++@mutable_receiver(model_activity_signal, sender=LogsAlertConfiguration)+def handle_logs_alert_activity(+ sender,+ scope,+ before_update,+ after_update,+ activity,+ user,+ was_impersonated=False,+ **kwargs,+):+ instance = after_update or before_update+ log_activity(+ organization_id=instance.team.organization_id,+ team_id=instance.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=instance.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=instance.name,+ ),+ )+++@mutable_receiver(model_activity_signal, sender=LogsExclusionRule)+def handle_logs_sampling_rule_activity(+ sender: Any,+ scope: str,+ before_update: LogsExclusionRule | None,+ after_update: LogsExclusionRule | None,+ activity: str,+ user: User | None,+ was_impersonated: bool = False,+ **kwargs: Any,+) -> None:+ instance = after_update or before_update+ if instance is None:+ return+ log_activity(+ organization_id=instance.team.organization_id,+ team_id=instance.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=instance.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(cast(ActivityScope, scope), previous=before_update, current=after_update),+ name=instance.name,+ ),+ )diff --git a/products/logs/backend/alerts_api.py b/products/logs/backend/alerts_api.pyindex 5b2d97ff1a77..e9be222dc1ef 100644--- a/products/logs/backend/alerts_api.py+++ b/products/logs/backend/alerts_api.py@@ -22,8 +22,7 @@ from posthog.schema import LogsAlertFiltersfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.event_usage import report_user_action-from posthog.models.activity_logging.activity_log import Change, Detail, changes_between, log_activity-from posthog.models.signals import model_activity_signal, mutable_receiver+from posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.permissions import PostHogFeatureFlagPermission@@ -1183,30 +1182,3 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):def perform_destroy(self, instance: LogsAlertConfiguration) -> None:self._track("logs alert deleted", instance)super().perform_destroy(instance)---@mutable_receiver(model_activity_signal, sender=LogsAlertConfiguration)-def handle_logs_alert_activity(- sender,- scope,- before_update,- after_update,- activity,- user,- was_impersonated=False,- **kwargs,-):- instance = after_update or before_update- log_activity(- organization_id=instance.team.organization_id,- team_id=instance.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=instance.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(scope, previous=before_update, current=after_update),- name=instance.name,- ),- )diff --git a/products/logs/backend/apps.py b/products/logs/backend/apps.pyindex e89d23de84d1..583694ad3f65 100644--- a/products/logs/backend/apps.py+++ b/products/logs/backend/apps.py@@ -5,3 +5,10 @@ class LogsConfig(AppConfig):default_auto_field = "django.db.models.BigAutoField"name = "products.logs.backend"label = "logs"++ def ready(self) -> None:+ # Connect the logs alert / sampling-rule activity-log receivers at app-population, from a+ # dedicated light module. They must not live in the viewset modules: the lazy API router no+ # longer pulls those, and alerts_api transitively imports the whole query-runner layer,+ # which would drag posthog.schema and HogQL into django.setup() for every process type.+ from products.logs.backend import activity_logging # noqa: F401, PLC0415diff --git a/products/logs/backend/sampling_api.py b/products/logs/backend/sampling_api.pyindex 98db0539a76e..889c30c66667 100644--- a/products/logs/backend/sampling_api.py+++ b/products/logs/backend/sampling_api.py@@ -17,8 +17,6 @@ from posthog.schema import PropertyGroupFilterfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.event_usage import report_user_action-from posthog.models.activity_logging.activity_log import ActivityScope, Detail, changes_between, log_activity-from posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.models.user import Userfrom posthog.permissions import PostHogFeatureFlagPermission@@ -381,32 +379,3 @@ class LogsSamplingRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):},status=status.HTTP_200_OK,)---@mutable_receiver(model_activity_signal, sender=LogsExclusionRule)-def handle_logs_sampling_rule_activity(- sender: Any,- scope: str,- before_update: LogsExclusionRule | None,- after_update: LogsExclusionRule | None,- activity: str,- user: User | None,- was_impersonated: bool = False,- **kwargs: Any,-) -> None:- instance = after_update or before_update- if instance is None:- return- log_activity(- organization_id=instance.team.organization_id,- team_id=instance.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=instance.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(cast(ActivityScope, scope), previous=before_update, current=after_update),- name=instance.name,- ),- )diff --git a/products/managed_migrations/backend/api/batch_imports.py b/products/managed_migrations/backend/api/batch_imports.pyindex bea8cedda316..a6c97e4e7a7d 100644--- a/products/managed_migrations/backend/api/batch_imports.py+++ b/products/managed_migrations/backend/api/batch_imports.py@@ -21,7 +21,6 @@ from posthog.models.activity_logging.model_activity import get_current_user, getfrom posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.models.user import User-from products.batch_exports.backend.api.batch_export import resolve_and_validate_urlfrom products.managed_migrations.backend.models.batch_import_utils import (extract_batch_import_info,get_batch_import_created_by_info,@@ -62,6 +61,10 @@ class BatchImportSerializer(serializers.ModelSerializer):def validate_endpoint_url(self, value: str | None) -> str | None:if not value or not value.strip():return None+ # Deferred: batch_export pulls the batch-export Temporal framework; keeping it out of+ # module scope lets this module connect its delete receiver at AppConfig.ready() cheaply.+ from products.batch_exports.backend.api.batch_export import resolve_and_validate_url # noqa: PLC0415+try:resolve_and_validate_url(value)except ValueError:diff --git a/products/managed_migrations/backend/apps.py b/products/managed_migrations/backend/apps.pyindex ca44dd29e99c..d26063d55a8b 100644--- a/products/managed_migrations/backend/apps.py+++ b/products/managed_migrations/backend/apps.py@@ -5,3 +5,11 @@ class ManagedMigrationsConfig(AppConfig):default_auto_field = "django.db.models.BigAutoField"name = "products.managed_migrations.backend"label = "managed_migrations"++ def ready(self) -> None:+ # batch_imports.py holds the BatchImport activity-log receiver (handle_batch_import_change)+ # plus a pre_delete cleanup receiver. They used to wire in via the viewset import; the lazy+ # API router no longer pulls that, so a process that never builds the router (celery, temporal,+ # migrate, shell) would stop logging batch-import activity and skip the delete cleanup. The+ # module is light, so import it directly here.+ from products.managed_migrations.backend.api import batch_imports # noqa: F401, PLC0415diff --git a/products/notebooks/backend/activity_logging.py b/products/notebooks/backend/activity_logging.pynew file mode 100644index 000000000000..cdf44641d60a--- /dev/null+++ b/products/notebooks/backend/activity_logging.py@@ -0,0 +1,36 @@+"""Activity-log helper for Notebook changes.++Kept out of the API module so the notebooks AppConfig can use it in the file-system+delete/restore hooks it registers at ready() without importing the API module — whose+module-scope imports reach the kernel runtime and the tasks sandbox (modal SDK).+"""++from typing import Optional++from posthog.models.activity_logging.activity_log import Change, Detail, log_activity+from posthog.models.user import User+from posthog.models.utils import UUIDT++from products.notebooks.backend.models import Notebook+++def log_notebook_activity(+ activity: str,+ notebook: Notebook,+ organization_id: UUIDT,+ team_id: int,+ user: User,+ was_impersonated: bool,+ changes: Optional[list[Change]] = None,+) -> None:+ short_id = str(notebook.short_id)+ log_activity(+ organization_id=organization_id,+ team_id=team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=notebook.short_id,+ scope="Notebook",+ activity=activity,+ detail=Detail(changes=changes, short_id=short_id, name=notebook.title),+ )diff --git a/products/notebooks/backend/api/notebook.py b/products/notebooks/backend/api/notebook.pyindex c69981264c91..6249ad073478 100644--- a/products/notebooks/backend/api/notebook.py+++ b/products/notebooks/backend/api/notebook.py@@ -1,7 +1,7 @@import mathimport hashlibfrom datetime import timedelta-from typing import Any, Optional, cast+from typing import Any, castfrom django.db import transactionfrom django.db.models import Q, QuerySet@@ -32,7 +32,7 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import actionfrom posthog.exceptions import Conflictfrom posthog.models import User-from posthog.models.activity_logging.activity_log import Change, Detail, changes_between, load_activity, log_activity+from posthog.models.activity_logging.activity_log import Change, changes_between, load_activityfrom posthog.models.activity_logging.activity_page import activity_page_responsefrom posthog.models.utils import UUIDTfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin@@ -42,13 +42,14 @@ from posthog.settings import SERVER_GATEWAY_INTERFACEfrom posthog.utils import relative_date_parsefrom products.notebooks.backend import collab+from products.notebooks.backend.activity_logging import log_notebook_activityfrom products.notebooks.backend.collab import submit_stepsfrom products.notebooks.backend.kernel_runtime import build_notebook_sandbox_config, get_kernel_runtimefrom products.notebooks.backend.models import KernelRuntime, Notebookfrom products.notebooks.backend.python_analysis import analyze_python_globals, annotate_python_nodesfrom products.notebooks.backend.query_validation import InvalidNotebookQueryError, normalize_notebook_query_nodes+from products.tasks.backend.exceptions import SandboxProvisionErrorfrom products.tasks.backend.services.sandbox import SandboxStatus-from products.tasks.backend.temporal.exceptions import SandboxProvisionErrorfrom ee.hogai.utils.aio import async_to_syncfrom ee.hogai.utils.asgi import SyncIterableToAsync@@ -68,28 +69,6 @@ def depluralize(string: str | None) -> str | None:return string-def log_notebook_activity(- activity: str,- notebook: Notebook,- organization_id: UUIDT,- team_id: int,- user: User,- was_impersonated: bool,- changes: Optional[list[Change]] = None,-) -> None:- short_id = str(notebook.short_id)- log_activity(- organization_id=organization_id,- team_id=team_id,- user=user,- was_impersonated=was_impersonated,- item_id=notebook.short_id,- scope="Notebook",- activity=activity,- detail=Detail(changes=changes, short_id=short_id, name=notebook.title),- )--_NOTEBOOK_FIELD_HELP_TEXTS = {"id": {"help_text": "UUID of the notebook."},"short_id": {"help_text": "Short alphanumeric identifier used in URLs and API lookups."},diff --git a/products/notebooks/backend/apps.py b/products/notebooks/backend/apps.pyindex 41ec4c80e276..4d628b7c8155 100644--- a/products/notebooks/backend/apps.py+++ b/products/notebooks/backend/apps.py@@ -16,7 +16,9 @@ class NotebooksConfig(AppConfig):from posthog.models.activity_logging.model_activity import is_impersonated_sessionfrom posthog.models.user import User- from products.notebooks.backend.api.notebook import log_notebook_activity+ # Lives in its own module: the API module's imports reach the kernel runtime and the+ # tasks sandbox (modal SDK), which must stay off the django.setup() path.+ from products.notebooks.backend.activity_logging import log_notebook_activityregister_file_system_type("notebook",diff --git a/products/signals/backend/report_generation/research.py b/products/signals/backend/report_generation/research.pyindex 4bfb3f7e5e25..9572b8eef4e5 100644--- a/products/signals/backend/report_generation/research.py+++ b/products/signals/backend/report_generation/research.py@@ -8,7 +8,12 @@ from typing import TYPE_CHECKINGfrom pydantic import BaseModel, Field, field_validator-from products.signals.backend.temporal.types import SignalData, _render_extra_to_text+# Deferred: importing temporal.types here runs the signals temporal package __init__, which+# eager-imports agentic -> report -> back into this module, forming a circular import.+# SignalData is annotation-only (this module uses `from __future__ import annotations`); the one+# runtime helper is imported locally in _render_signal_for_research.+if TYPE_CHECKING:+ from products.signals.backend.temporal.types import SignalDataclass ActionabilityChoice(str, Enum):@@ -254,6 +259,8 @@ def _render_previous_presentation_context(previous_title: str | None, previous_sdef _render_signal_for_research(signal: SignalData, index: int, total: int) -> str:"""Render a single signal for the research prompt, with numbering."""+ from products.signals.backend.temporal.types import _render_extra_to_text # noqa: PLC0415+lines = [f"### Signal {index}/{total} (id: `{signal.signal_id}`)"]lines.append(f"- **Source:** {signal.source_product} / {signal.source_type}")lines.append(f"- **Source ID:** {signal.source_id}")diff --git a/products/signals/backend/report_generation/select_repo.py b/products/signals/backend/report_generation/select_repo.pyindex 977b4a29588d..dfef6478075e 100644--- a/products/signals/backend/report_generation/select_repo.py+++ b/products/signals/backend/report_generation/select_repo.py@@ -14,7 +14,6 @@ from __future__ import annotationsimport loggingfrom typing import TYPE_CHECKING-from products.signals.backend.temporal.types import SignalData, render_signals_to_textfrom products.tasks.backend.models import Taskfrom products.tasks.backend.repo_selection import (REPO_SELECTION_DUMMY_REPOSITORY,@@ -26,6 +25,10 @@ from products.tasks.backend.repo_selection import ()if TYPE_CHECKING:+ # Deferred (see _select below): importing temporal.types runs the signals temporal package+ # __init__ (agentic -> back into report_generation), a circular import. SignalData is+ # annotation-only here (module uses `from __future__ import annotations`).+ from products.signals.backend.temporal.types import SignalDatafrom products.tasks.backend.services.custom_prompt_internals import OutputFnlogger = logging.getLogger(__name__)@@ -99,6 +102,8 @@ async def select_repository_for_report(output_fn: OutputFn = None,) -> RepoSelectionResult:"""Select the most relevant repository for a set of signals."""+ from products.signals.backend.temporal.types import render_signals_to_text # noqa: PLC0415+request_section = render_signals_to_text(signals)return await select_repository_for_team(team_id,diff --git a/products/slack_app/backend/signals.py b/products/slack_app/backend/signals.pyindex c83bb81d72a0..a584fbaf96b4 100644--- a/products/slack_app/backend/signals.py+++ b/products/slack_app/backend/signals.py@@ -5,11 +5,16 @@ from django.dispatch import receiverfrom posthog.models.user_integration import UserIntegration-from products.slack_app.backend.api import _invalidate_user_repo_list_cache-@receiver(post_save, sender=UserIntegration)@receiver(post_delete, sender=UserIntegration)def invalidate_repo_list_on_user_github_change(sender: Any, instance: UserIntegration, **kwargs) -> None:- if instance.kind == UserIntegration.IntegrationKind.GITHUB:- _invalidate_user_repo_list_cache(instance.user_id)+ if instance.kind != UserIntegration.IntegrationKind.GITHUB:+ return+ # Deferred: products.slack_app.backend.api imports posthog.temporal.ai workflows at module+ # scope, which pulls the whole ee.hogai chat-agent core. This receiver is wired from+ # AppConfig.ready(), so a module-level import would drag the AI core into every process's+ # startup. The cache helper is only needed when a GitHub integration actually changes.+ from products.slack_app.backend.api import _invalidate_user_repo_list_cache # noqa: PLC0415++ _invalidate_user_repo_list_cache(instance.user_id)diff --git a/products/slack_app/backend/tests/test_followup_forwarding.py b/products/slack_app/backend/tests/test_followup_forwarding.pyindex f79d01de482d..a3453d5d7dd9 100644--- a/products/slack_app/backend/tests/test_followup_forwarding.py+++ b/products/slack_app/backend/tests/test_followup_forwarding.py@@ -678,7 +678,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):assert "gh pr checkout https://github.com/org/repo/pull/1" in new_run.state.get("initial_prompt_override", "")assert "gh pr checkout https://github.com/org/repo/pull/1" in new_run.state.get("pending_user_message", "")- @patch("posthog.temporal.ai.posthog_code_slack_mention.resolve_slack_user", return_value=None)+ @patch("products.slack_app.backend.api.resolve_slack_user", return_value=None)@patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")def test_terminal_run_unauthorized_user_returns_true_with_resolver_feedback(self, mock_slack_cls, mock_resolve):self.task_run.status = self.TaskRun.Status.COMPLETED@@ -740,7 +740,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):)assert mapping.task_run_id == self.task_run.id- @patch("posthog.temporal.ai.posthog_code_slack_mention.resolve_slack_user", return_value=None)+ @patch("products.slack_app.backend.api.resolve_slack_user", return_value=None)@patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")def test_unauthorized_actor_returns_true_with_resolver_feedback(self, mock_slack_cls, mock_resolve):self._create_mapping(mentioning_user="U_ALICE")@@ -757,7 +757,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):@patch("posthog.temporal.ai.posthog_code_slack_mention.create_sandbox_connection_token", return_value="jwt-token")@patch("posthog.temporal.ai.posthog_code_slack_mention.send_user_message")- @patch("posthog.temporal.ai.posthog_code_slack_mention.resolve_slack_user")+ @patch("products.slack_app.backend.api.resolve_slack_user")@patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")def test_cross_user_followup_authorized_prefixes_actor_name(self, mock_slack_cls, mock_resolve, mock_send, mock_token@@ -791,7 +791,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):@patch("posthog.temporal.ai.posthog_code_slack_mention.create_sandbox_connection_token", return_value="jwt-token")@patch("posthog.temporal.ai.posthog_code_slack_mention.send_user_message")- @patch("posthog.temporal.ai.posthog_code_slack_mention.resolve_slack_user")+ @patch("products.slack_app.backend.api.resolve_slack_user")@patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")def test_cross_user_followup_falls_back_to_email_when_no_full_name(self, mock_slack_cls, mock_resolve, mock_send, mock_token@@ -807,7 +807,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):mock_send.assert_called_once_with(self.task_run, "[email protected]: ping", auth_token="jwt-token", timeout=90)- @patch("posthog.temporal.ai.posthog_code_slack_mention.resolve_slack_user", return_value=None)+ @patch("products.slack_app.backend.api.resolve_slack_user", return_value=None)@patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")def test_cross_user_followup_unmapped_user_delegates_feedback_to_resolver(self, mock_slack_cls, mock_resolve):# A second Slack user who can't be resolved to a PostHog member of this team@@ -827,7 +827,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):mock_slack_instance.client.chat_postMessage.assert_not_called()@patch("posthog.temporal.ai.posthog_code_slack_mention.execute_task_processing_workflow")- @patch("posthog.temporal.ai.posthog_code_slack_mention.resolve_slack_user")+ @patch("products.slack_app.backend.api.resolve_slack_user")@patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")def test_cross_user_terminal_run_resume_prefixes_actor_name(self, mock_slack_cls, mock_resolve, mock_execute_workflowdiff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.pyindex 72ac7528e525..4b3b1f0aedaa 100644--- a/products/tasks/backend/api.py+++ b/products/tasks/backend/api.py@@ -164,6 +164,7 @@ from .temporal.process_task.utils import (resolve_user_github_integration_for_task,user_github_integration_is_usable,)+from .visibility import task_run_visibility_q, task_visibility_qlogger = logging.getLogger(__name__)TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS = 20.0@@ -283,36 +284,6 @@ class TasksPagination(_SchemaAwareLimitOffsetPagination):max_limit = 100-def task_visibility_q(user_id: int | None) -> Q:- """Filter for tasks visible to the given user.-- A task is visible if:- - its creator matches `user_id`, or- - it has no creator at all (legacy unowned tasks remain visible to any- team member — they cannot be executed in any case because oauth.py- requires `task.created_by` to mint OAuth tokens), or- - it was generated by the signals pipeline or Signals scout- (`origin_product=SIGNAL_REPORT` or `origin_product=SIGNALS_SCOUT`).- Signals tasks are team-scoped artifacts that the pipeline must attach to- a system-picked `created_by` so the agent can mint an OAuth token, but- they are not personal — any team member should be able to view them.- """- return (- Q(created_by_id=user_id)- | Q(created_by__isnull=True)- | Q(origin_product__in=[Task.OriginProduct.SIGNAL_REPORT, Task.OriginProduct.SIGNALS_SCOUT])- )---def task_run_visibility_q(user_id: int | None) -> Q:- """`task_visibility_q` traversed via the `task` FK on TaskRun / TaskAutomation."""- return (- Q(task__created_by_id=user_id)- | Q(task__created_by__isnull=True)- | Q(task__origin_product__in=[Task.OriginProduct.SIGNAL_REPORT, Task.OriginProduct.SIGNALS_SCOUT])- )--def _parse_slack_thread_url(url: str) -> tuple[str, str] | None:"""Parse a Slack permalink into `(channel, thread_ts)`"""try:diff --git a/products/tasks/backend/temporal/exceptions.py b/products/tasks/backend/exceptions.pysimilarity index 100%rename from products/tasks/backend/temporal/exceptions.pyrename to products/tasks/backend/exceptions.pydiff --git a/products/tasks/backend/services/docker_sandbox.py b/products/tasks/backend/services/docker_sandbox.pyindex 31a4cdba6868..bdebe85f42c9 100644--- a/products/tasks/backend/services/docker_sandbox.py+++ b/products/tasks/backend/services/docker_sandbox.py@@ -18,8 +18,7 @@ from django.conf import settingsif TYPE_CHECKING:from products.tasks.backend.temporal.process_task.utils import McpServerConfig-from products.tasks.backend.models import SandboxSnapshot-from products.tasks.backend.temporal.exceptions import (+from products.tasks.backend.exceptions import (SandboxCleanupError,SandboxExecutionError,SandboxNotFoundError,@@ -27,6 +26,7 @@ from products.tasks.backend.temporal.exceptions import (SandboxTimeoutError,SnapshotCreationError,)+from products.tasks.backend.models import SandboxSnapshotfrom .agentsh import (BASH_ENV_SCRIPT,diff --git a/products/tasks/backend/services/modal_sandbox.py b/products/tasks/backend/services/modal_sandbox.pyindex 22e966ef034d..289016d8aa8d 100644--- a/products/tasks/backend/services/modal_sandbox.py+++ b/products/tasks/backend/services/modal_sandbox.py@@ -27,6 +27,15 @@ import requestsfrom posthog.exceptions_capture import capture_exceptionfrom posthog.settings import CLOUD_DEPLOYMENT+from products.tasks.backend.exceptions import (+ SandboxCleanupError,+ SandboxExecutionError,+ SandboxNotFoundError,+ SandboxNotRunningError,+ SandboxProvisionError,+ SandboxTimeoutError,+ SnapshotCreationError,+)from products.tasks.backend.models import SandboxSnapshotfrom products.tasks.backend.services.agentsh import (BASH_ENV_SCRIPT,@@ -58,15 +67,6 @@ from products.tasks.backend.services.sandbox import (redact_sandbox_command,wait_for_health_check,)-from products.tasks.backend.temporal.exceptions import (- SandboxCleanupError,- SandboxExecutionError,- SandboxNotFoundError,- SandboxNotRunningError,- SandboxProvisionError,- SandboxTimeoutError,- SnapshotCreationError,-)from .sandbox import AgentServerResult, ExecutionResult, ExecutionStream, SandboxConfig, SandboxStatus, SandboxTemplatediff --git a/products/tasks/backend/services/test_docker_sandbox.py b/products/tasks/backend/services/test_docker_sandbox.pyindex 25f46828580a..280d2025ee5f 100644--- a/products/tasks/backend/services/test_docker_sandbox.py+++ b/products/tasks/backend/services/test_docker_sandbox.py@@ -5,6 +5,7 @@ from typing import Anyimport pytestfrom unittest.mock import MagicMock, patch+from products.tasks.backend.exceptions import SandboxExecutionErrorfrom products.tasks.backend.services.docker_sandbox import DockerSandboxfrom products.tasks.backend.services.sandbox import (ExecutionResult,@@ -15,7 +16,6 @@ from products.tasks.backend.services.sandbox import (parse_sandbox_repo_mount_map,redact_sandbox_command,)-from products.tasks.backend.temporal.exceptions import SandboxExecutionErrordef _agent_server_launch_command(mock_execute: Any) -> str:diff --git a/products/tasks/backend/services/test_title_generator.py b/products/tasks/backend/services/test_title_generator.pyindex 36f03d5d743b..8a3ee949b0e9 100644--- a/products/tasks/backend/services/test_title_generator.py+++ b/products/tasks/backend/services/test_title_generator.py@@ -6,7 +6,7 @@ from products.tasks.backend.services.title_generator import _fallback_title, genclass TestTitleGenerator:- @patch("products.tasks.backend.services.title_generator.Client")+ @patch("products.ai_observability.backend.llm.client.Client")def test_generate_task_title_success(self, mock_client_cls):mock_client = MagicMock()mock_client_cls.return_value = mock_client@@ -20,7 +20,7 @@ class TestTitleGenerator:assert result == "Fix login bug"mock_client_cls.assert_called_once_with(distinct_id="task-title-generator")- @patch("products.tasks.backend.services.title_generator.Client")+ @patch("products.ai_observability.backend.llm.client.Client")def test_generate_task_title_multipart_response(self, mock_client_cls):mock_client = MagicMock()mock_client_cls.return_value = mock_client@@ -35,7 +35,7 @@ class TestTitleGenerator:assert result == "Add dashboard metrics"- @patch("products.tasks.backend.services.title_generator.Client")+ @patch("products.ai_observability.backend.llm.client.Client")def test_generate_task_title_falls_back_on_error(self, mock_client_cls):mock_client_cls.side_effect = Exception("API error")@@ -43,21 +43,21 @@ class TestTitleGenerator:assert result == "This is a test description that should be used as fallback"- @patch("products.tasks.backend.services.title_generator.Client")+ @patch("products.ai_observability.backend.llm.client.Client")def test_generate_task_title_empty_description(self, mock_client_cls):result = generate_task_title("")assert result == "Untitled Task"mock_client_cls.assert_not_called()- @patch("products.tasks.backend.services.title_generator.Client")+ @patch("products.ai_observability.backend.llm.client.Client")def test_generate_task_title_whitespace_only(self, mock_client_cls):result = generate_task_title(" \n\t ")assert result == "Untitled Task"mock_client_cls.assert_not_called()- @patch("products.tasks.backend.services.title_generator.Client")+ @patch("products.ai_observability.backend.llm.client.Client")def test_generate_task_title_truncates_long_response(self, mock_client_cls):mock_client = MagicMock()mock_client_cls.return_value = mock_client@@ -72,7 +72,7 @@ class TestTitleGenerator:assert len(result) == 60assert result == "A" * 60- @patch("products.tasks.backend.services.title_generator.Client")+ @patch("products.ai_observability.backend.llm.client.Client")def test_generate_task_title_ignores_non_text_chunks(self, mock_client_cls):mock_client = MagicMock()mock_client_cls.return_value = mock_client@@ -86,7 +86,7 @@ class TestTitleGenerator:assert result == "Valid title"- @patch("products.tasks.backend.services.title_generator.Client")+ @patch("products.ai_observability.backend.llm.client.Client")def test_generate_task_title_empty_response(self, mock_client_cls):mock_client = MagicMock()mock_client_cls.return_value = mock_clientdiff --git a/products/tasks/backend/services/tests/test_modal_sandbox.py b/products/tasks/backend/services/tests/test_modal_sandbox.pyindex 0a472ad6940f..704d27d85ab6 100644--- a/products/tasks/backend/services/tests/test_modal_sandbox.py+++ b/products/tasks/backend/services/tests/test_modal_sandbox.py@@ -5,6 +5,7 @@ from unittest.mock import MagicMock, patchfrom requests.exceptions import ConnectionError, Timeout+from products.tasks.backend.exceptions import SandboxExecutionError, SandboxProvisionErrorfrom products.tasks.backend.services.modal_provision_diagnostics import (MAX_PROVISION_LOG_EXCERPT_LINES,summarize_modal_output,@@ -20,7 +21,6 @@ from products.tasks.backend.services.modal_sandbox import (_image_ref_cache,)from products.tasks.backend.services.sandbox import AgentServerResult, ExecutionResult, SandboxConfig-from products.tasks.backend.temporal.exceptions import SandboxExecutionError, SandboxProvisionErrordef _agent_server_launch_command(mock_execute: Any) -> str:diff --git a/products/tasks/backend/services/title_generator.py b/products/tasks/backend/services/title_generator.pyindex 89cf8ecd825b..b8150f265375 100644--- a/products/tasks/backend/services/title_generator.py+++ b/products/tasks/backend/services/title_generator.py@@ -1,9 +1,6 @@import loggingfrom typing import Any-from products.ai_observability.backend.llm.client import Client-from products.ai_observability.backend.llm.types import CompletionRequest-logger = logging.getLogger(__name__)@@ -13,6 +10,12 @@ def generate_task_title(description: str) -> str:Returns a generated title or falls back to truncated description if generation fails."""+ # Deferred: the llm client pulls google.genai (Gemini SDK), and this module is reachable from a+ # tasks serializer that the file-system registrations import at AppConfig.ready() — a module-level+ # import here would drag the SDK onto the django.setup() path that every process pays for.+ from products.ai_observability.backend.llm.client import Client # noqa: PLC0415+ from products.ai_observability.backend.llm.types import CompletionRequest # noqa: PLC0415+if not description or not description.strip():return "Untitled Task"diff --git a/products/tasks/backend/temporal/create_snapshot/activities/clone_repository.py b/products/tasks/backend/temporal/create_snapshot/activities/clone_repository.pyindex 219876886421..2e12191107f7 100644--- a/products/tasks/backend/temporal/create_snapshot/activities/clone_repository.py+++ b/products/tasks/backend/temporal/create_snapshot/activities/clone_repository.py@@ -4,8 +4,8 @@ from temporalio import activityfrom posthog.temporal.common.utils import asyncify+from products.tasks.backend.exceptions import GitHubAuthenticationError, RepositoryCloneErrorfrom products.tasks.backend.services.sandbox import Sandbox-from products.tasks.backend.temporal.exceptions import GitHubAuthenticationError, RepositoryCloneErrorfrom products.tasks.backend.temporal.observability import log_activity_executionfrom ..utils import get_github_tokendiff --git a/products/tasks/backend/temporal/create_snapshot/activities/get_snapshot_context.py b/products/tasks/backend/temporal/create_snapshot/activities/get_snapshot_context.pyindex 482738fe2e3c..bc17a5075d01 100644--- a/products/tasks/backend/temporal/create_snapshot/activities/get_snapshot_context.py+++ b/products/tasks/backend/temporal/create_snapshot/activities/get_snapshot_context.py@@ -5,7 +5,7 @@ from temporalio import activityfrom posthog.models.integration import Integrationfrom posthog.temporal.common.utils import asyncify-from products.tasks.backend.temporal.exceptions import TaskInvalidStateError+from products.tasks.backend.exceptions import TaskInvalidStateErrorfrom products.tasks.backend.temporal.observability import log_with_activity_contextdiff --git a/products/tasks/backend/temporal/create_snapshot/activities/setup_repository.py b/products/tasks/backend/temporal/create_snapshot/activities/setup_repository.pyindex dd1224764fb0..1f693c45bf39 100644--- a/products/tasks/backend/temporal/create_snapshot/activities/setup_repository.py+++ b/products/tasks/backend/temporal/create_snapshot/activities/setup_repository.py@@ -4,8 +4,8 @@ from temporalio import activityfrom posthog.temporal.common.utils import asyncify+from products.tasks.backend.exceptions import RetryableRepositorySetupErrorfrom products.tasks.backend.services.sandbox import Sandbox-from products.tasks.backend.temporal.exceptions import RetryableRepositorySetupErrorfrom products.tasks.backend.temporal.observability import log_activity_executionfrom .get_snapshot_context import SnapshotContextdiff --git a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_clone_repository.py b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_clone_repository.pyindex 8f0c76515490..64c0f719f272 100644--- a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_clone_repository.py+++ b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_clone_repository.py@@ -5,13 +5,13 @@ from unittest.mock import patchfrom asgiref.sync import async_to_sync+from products.tasks.backend.exceptions import RepositoryCloneError, SandboxNotFoundErrorfrom products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplatefrom products.tasks.backend.temporal.create_snapshot.activities.clone_repository import (CloneRepositoryInput,clone_repository,)from products.tasks.backend.temporal.create_snapshot.activities.get_snapshot_context import SnapshotContext-from products.tasks.backend.temporal.exceptions import RepositoryCloneError, SandboxNotFoundError@pytest.mark.skipif(diff --git a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_create_snapshot.py b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_create_snapshot.pyindex 1818f0fbe185..225e460d58c4 100644--- a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_create_snapshot.py+++ b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_create_snapshot.py@@ -5,6 +5,7 @@ import pytestfrom asgiref.sync import async_to_sync+from products.tasks.backend.exceptions import SandboxNotFoundError, SnapshotCreationErrorfrom products.tasks.backend.models import SandboxSnapshotfrom products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplatefrom products.tasks.backend.temporal.create_snapshot.activities.create_snapshot import (@@ -12,7 +13,6 @@ from products.tasks.backend.temporal.create_snapshot.activities.create_snapshotcreate_snapshot,)from products.tasks.backend.temporal.create_snapshot.activities.get_snapshot_context import SnapshotContext-from products.tasks.backend.temporal.exceptions import SandboxNotFoundError, SnapshotCreationErrordef _run_or_skip_on_modal_outage(activity_environment, fn, input_data):diff --git a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_setup_repository.py b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_setup_repository.pyindex f7426cc0daea..dcc57c0c3fcb 100644--- a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_setup_repository.py+++ b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_setup_repository.py@@ -4,13 +4,13 @@ import pytestfrom asgiref.sync import async_to_sync+from products.tasks.backend.exceptions import SandboxNotFoundErrorfrom products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplatefrom products.tasks.backend.temporal.create_snapshot.activities.get_snapshot_context import SnapshotContextfrom products.tasks.backend.temporal.create_snapshot.activities.setup_repository import (SetupRepositoryInput,setup_repository,)-from products.tasks.backend.temporal.exceptions import SandboxNotFoundError@pytest.mark.skipif(diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.pyindex c0df04f3ccdb..75cc2a71a945 100644--- a/products/tasks/backend/temporal/oauth.py+++ b/products/tasks/backend/temporal/oauth.py@@ -6,8 +6,8 @@ from posthog.temporal.oauth import (create_oauth_access_token_for_user as _create_oauth_access_token_for_user,)+from products.tasks.backend.exceptions import OAuthTokenError, TaskInvalidStateErrorfrom products.tasks.backend.models import Task-from products.tasks.backend.temporal.exceptions import OAuthTokenError, TaskInvalidStateError__all__ = ["ARRAY_APP_CLIENT_ID_DEV",diff --git a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.pyindex eb5af724a9aa..ad77b225162b 100644--- a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py@@ -5,11 +5,11 @@ from temporalio import activityfrom posthog.temporal.common.utils import asyncify+from products.tasks.backend.exceptions import SandboxNotFoundErrorfrom products.tasks.backend.models import TaskRunfrom products.tasks.backend.redis import run_uses_dedicated_streamfrom products.tasks.backend.services.sandbox import Sandboxfrom products.tasks.backend.stream.redis_stream import publish_task_run_stream_complete-from products.tasks.backend.temporal.exceptions import SandboxNotFoundErrorfrom products.tasks.backend.temporal.observability import log_activity_executionlogger = logging.getLogger(__name__)diff --git a/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.py b/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.pyindex 2be30a830f30..2e498a4ec6c3 100644--- a/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.py+++ b/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.py@@ -4,15 +4,15 @@ from temporalio import activityfrom posthog.temporal.common.utils import asyncify-from products.tasks.backend.models import SandboxSnapshot, Task-from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate-from products.tasks.backend.temporal.exceptions import (+from products.tasks.backend.exceptions import (GitHubAuthenticationError,OAuthTokenError,SnapshotNotFoundError,SnapshotNotReadyError,TaskNotFoundError,)+from products.tasks.backend.models import SandboxSnapshot, Task+from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplatefrom products.tasks.backend.temporal.oauth import create_oauth_access_tokenfrom products.tasks.backend.temporal.observability import emit_agent_log, log_activity_executionfrom products.tasks.backend.temporal.process_task.utils import (diff --git a/products/tasks/backend/temporal/process_task/activities/execute_task_in_sandbox.py b/products/tasks/backend/temporal/process_task/activities/execute_task_in_sandbox.pyindex c9d2dd199e1d..9d32ca562f3d 100644--- a/products/tasks/backend/temporal/process_task/activities/execute_task_in_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/execute_task_in_sandbox.py@@ -5,9 +5,9 @@ from temporalio import activityfrom posthog.temporal.common.logger import get_loggerfrom posthog.temporal.common.utils import asyncify+from products.tasks.backend.exceptions import SandboxExecutionError, TaskExecutionFailedErrorfrom products.tasks.backend.models import TaskRunfrom products.tasks.backend.services.sandbox import Sandbox-from products.tasks.backend.temporal.exceptions import SandboxExecutionError, TaskExecutionFailedErrorfrom products.tasks.backend.temporal.observability import emit_agent_log, log_activity_executionfrom .get_task_processing_context import TaskProcessingContextdiff --git a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py b/products/tasks/backend/temporal/process_task/activities/get_pr_context.pyindex f56bca7a83f5..f37886371206 100644--- a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_pr_context.py@@ -10,8 +10,8 @@ from posthog.models.integration import GitHubIntegrationfrom posthog.models.user_integration import UserGitHubIntegration, UserIntegrationfrom posthog.temporal.common.utils import close_db_connections+from products.tasks.backend.exceptions import TaskInvalidStateErrorfrom products.tasks.backend.models import TaskRun-from products.tasks.backend.temporal.exceptions import TaskInvalidStateErrorfrom products.tasks.backend.temporal.observability import log_activity_executionfrom products.tasks.backend.temporal.process_task.activities import TaskProcessingContextdiff --git a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.pyindex 6b3392b26061..8f5cbfb79685 100644--- a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py+++ b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py@@ -8,6 +8,7 @@ from temporalio import activityfrom posthog.temporal.common.utils import asyncify+from products.tasks.backend.exceptions import GitHubAuthenticationError, OAuthTokenError, TaskNotFoundErrorfrom products.tasks.backend.models import SandboxSnapshot, Task, TaskRunfrom products.tasks.backend.services.connection_token import (SANDBOX_JWT_STATE_KID_KEY,@@ -20,7 +21,6 @@ from products.tasks.backend.services.sandbox import (SandboxTemplate,parse_sandbox_repo_mount_map,)-from products.tasks.backend.temporal.exceptions import GitHubAuthenticationError, OAuthTokenError, TaskNotFoundErrorfrom products.tasks.backend.temporal.metrics import StepTimer, increment_snapshot_usagefrom products.tasks.backend.temporal.oauth import create_oauth_access_tokenfrom products.tasks.backend.temporal.observability import emit_agent_log, log_activity_executiondiff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.pyindex 04d15bbff523..9d054d0d32c9 100644--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py@@ -10,8 +10,8 @@ from posthog.models import Teamfrom posthog.temporal.common.utils import asyncify, close_db_connectionsfrom products.tasks.backend.constants import MODAL_VM_SANDBOX_FEATURE_FLAG, SANDBOX_EVENT_INGEST_FEATURE_FLAG+from products.tasks.backend.exceptions import TaskInvalidStateError, TaskNotFoundErrorfrom products.tasks.backend.models import SandboxEnvironment, Task, TaskRun-from products.tasks.backend.temporal.exceptions import TaskInvalidStateError, TaskNotFoundErrorfrom products.tasks.backend.temporal.observability import emit_agent_log, log_with_activity_contextfrom products.tasks.backend.temporal.process_task.utils import (format_allowed_domains_for_log,diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex b470a0dd77a6..2af19858e1de 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -8,6 +8,7 @@ from temporalio import activityfrom posthog.temporal.common.utils import asyncify+from products.tasks.backend.exceptions import GitHubAuthenticationError, OAuthTokenError, TaskNotFoundErrorfrom products.tasks.backend.models import SandboxSnapshot, Task, TaskRunfrom products.tasks.backend.services.agentsh import ENV_FILEfrom products.tasks.backend.services.connection_token import (@@ -16,7 +17,6 @@ from products.tasks.backend.services.connection_token import (get_sandbox_jwt_public_key,)from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate-from products.tasks.backend.temporal.exceptions import GitHubAuthenticationError, OAuthTokenError, TaskNotFoundErrorfrom products.tasks.backend.temporal.metrics import StepTimer, increment_snapshot_usagefrom products.tasks.backend.temporal.oauth import create_oauth_access_tokenfrom products.tasks.backend.temporal.observability import emit_agent_log, log_activity_executiondiff --git a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.pyindex 6e451ece3a98..78edcc66b933 100644--- a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py+++ b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py@@ -5,11 +5,11 @@ from temporalio import activityfrom posthog.temporal.common.logger import get_loggerfrom posthog.temporal.common.utils import asyncify+from products.tasks.backend.exceptions import SandboxNotFoundError, SandboxNotRunningError, TaskNotFoundErrorfrom products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.services.agent_command import send_refresh_sessionfrom products.tasks.backend.services.connection_token import create_sandbox_connection_tokenfrom products.tasks.backend.services.sandbox import Sandbox-from products.tasks.backend.temporal.exceptions import SandboxNotFoundError, SandboxNotRunningError, TaskNotFoundErrorfrom products.tasks.backend.temporal.metrics import increment_credential_refreshfrom products.tasks.backend.temporal.observability import log_activity_execution, track_eventfrom products.tasks.backend.temporal.process_task.sandbox_credentials import (diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.pyindex 525098e159bb..44bc0fecbe89 100644--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py@@ -7,11 +7,11 @@ from posthog.temporal.common.logger import get_loggerfrom posthog.temporal.common.utils import asyncifyfrom posthog.temporal.oauth import PosthogMcpScopes+from products.tasks.backend.exceptions import OAuthTokenError, SandboxExecutionErrorfrom products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.services.agentsh import ENV_FILE, ENV_WRAPPER_SCRIPT, build_exec_prefixfrom products.tasks.backend.services.connection_token import create_sandbox_event_ingest_tokenfrom products.tasks.backend.services.sandbox import Sandbox, SandboxBase-from products.tasks.backend.temporal.exceptions import OAuthTokenError, SandboxExecutionErrorfrom products.tasks.backend.temporal.oauth import create_oauth_access_tokenfrom products.tasks.backend.temporal.observability import emit_agent_log, log_activity_executionfrom products.tasks.backend.temporal.process_task.utils import (diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.pyindex f744c0b81443..8cad11bed5fa 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py@@ -7,9 +7,9 @@ import pytestimport modalfrom asgiref.sync import async_to_sync+from products.tasks.backend.exceptions import SandboxNotFoundErrorfrom products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplatefrom products.tasks.backend.stream.redis_stream import TaskRunRedisStream, get_task_run_stream_key-from products.tasks.backend.temporal.exceptions import SandboxNotFoundErrorfrom products.tasks.backend.temporal.process_task.activities.cleanup_sandbox import CleanupSandboxInput, cleanup_sandboxdiff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_execute_task_in_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_execute_task_in_sandbox.pyindex f553b5f445cd..1f95a84a3ed2 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_execute_task_in_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_execute_task_in_sandbox.py@@ -4,8 +4,8 @@ import pytestfrom asgiref.sync import async_to_sync+from products.tasks.backend.exceptions import SandboxNotFoundErrorfrom products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate-from products.tasks.backend.temporal.exceptions import SandboxNotFoundErrorfrom products.tasks.backend.temporal.process_task.activities.execute_task_in_sandbox import (ExecuteTaskInput,execute_task_in_sandbox,diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.pyindex 0a8a527c707f..902a708e0e4e 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py@@ -5,7 +5,7 @@ from unittest.mock import MagicMock, patchfrom django.core.exceptions import ObjectDoesNotExist-from products.tasks.backend.temporal.exceptions import TaskInvalidStateError+from products.tasks.backend.exceptions import TaskInvalidStateErrorfrom products.tasks.backend.temporal.process_task.activities.get_pr_context import (GetPrContextInput,GetPrContextOutput,diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.pyindex e6419fc193f5..a6919994a2de 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py@@ -9,8 +9,8 @@ from posthog.models import OrganizationMembership, Userfrom posthog.models.user_integration import UserIntegrationfrom products.tasks.backend.constants import MODAL_VM_SANDBOX_FEATURE_FLAG, SANDBOX_EVENT_INGEST_FEATURE_FLAG+from products.tasks.backend.exceptions import TaskInvalidStateError, TaskNotFoundErrorfrom products.tasks.backend.models import SandboxEnvironment, Task-from products.tasks.backend.temporal.exceptions import TaskInvalidStateError, TaskNotFoundErrorfrom products.tasks.backend.temporal.process_task.activities.get_task_processing_context import (GetTaskProcessingContextInput,TaskProcessingContext,diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.pyindex 1dab6625912b..9fcfc3006fa9 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py@@ -3,12 +3,8 @@ from unittest.mock import MagicMock, patchfrom asgiref.sync import async_to_sync+from products.tasks.backend.exceptions import SandboxExecutionError, SandboxNotFoundError, SandboxNotRunningErrorfrom products.tasks.backend.services.sandbox import ExecutionResult-from products.tasks.backend.temporal.exceptions import (- SandboxExecutionError,- SandboxNotFoundError,- SandboxNotRunningError,-)from products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials import (RefreshSandboxCredentialsInput,refresh_sandbox_credentials,diff --git a/products/tasks/backend/visibility.py b/products/tasks/backend/visibility.pynew file mode 100644index 000000000000..d3c80749e481--- /dev/null+++ b/products/tasks/backend/visibility.py@@ -0,0 +1,40 @@+"""Task visibility filters.++Kept out of the API module so import-light consumers (the file-system registration in+posthog.api.file_system.registrations, which loads at django.setup()) don't pull the whole+tasks API surface — its module-scope imports reach jsonschema and the modal SDK.+"""++from django.db.models import Q++from products.tasks.backend.models import Task+++def task_visibility_q(user_id: int | None) -> Q:+ """Filter for tasks visible to the given user.++ A task is visible if:+ - its creator matches `user_id`, or+ - it has no creator at all (legacy unowned tasks remain visible to any+ team member — they cannot be executed in any case because oauth.py+ requires `task.created_by` to mint OAuth tokens), or+ - it was generated by the signals pipeline or Signals scout+ (`origin_product=SIGNAL_REPORT` or `origin_product=SIGNALS_SCOUT`).+ Signals tasks are team-scoped artifacts that the pipeline must attach to+ a system-picked `created_by` so the agent can mint an OAuth token, but+ they are not personal — any team member should be able to view them.+ """+ return (+ Q(created_by_id=user_id)+ | Q(created_by__isnull=True)+ | Q(origin_product__in=[Task.OriginProduct.SIGNAL_REPORT, Task.OriginProduct.SIGNALS_SCOUT])+ )+++def task_run_visibility_q(user_id: int | None) -> Q:+ """`task_visibility_q` traversed via the `task` FK on TaskRun / TaskAutomation."""+ return (+ Q(task__created_by_id=user_id)+ | Q(task__created_by__isnull=True)+ | Q(task__origin_product__in=[Task.OriginProduct.SIGNAL_REPORT, Task.OriginProduct.SIGNALS_SCOUT])+ )diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex 22322d8ddd3a..7d18a4f33f1c 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -1,3 +1,4 @@+import sysimport uuidfrom datetime import date, datetime, timedeltafrom typing import Any, Literal, Optional@@ -5,7 +6,6 @@ from typing import Any, Literal, Optionalfrom django.conf import settingsfrom django.db import models-import numpyfrom dateutil import parserfrom django_deprecate_fields import deprecate_field@@ -16,13 +16,6 @@ from posthog.sync import database_sync_to_asyncfrom posthog.temporal.data_imports.naming_convention import NamingConventionfrom posthog.temporal.data_imports.pipelines.pipeline.typings import PartitionFormat, PartitionMode-from products.data_warehouse.backend.data_load.service import (- external_data_workflow_exists,- pause_external_data_schedule,- sync_external_data_job_workflow,- unpause_external_data_schedule,-)-from products.data_warehouse.backend.s3 import get_s3_clientfrom products.data_warehouse.backend.types import IncrementalFieldTypetype IncrementalFieldValue = str | int | float | None@@ -291,7 +284,14 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField) -> None:incremental_field_type = self.sync_type_config.get("incremental_field_type")- last_value_py = last_value.item() if isinstance(last_value, numpy.generic) else last_value+ # a numpy scalar can only arrive here if numpy is already imported (the import-pipeline+ # paths that produce one import it); gating keeps numpy off the django.setup() path+ if "numpy" in sys.modules:+ import numpy # noqa: PLC0415++ last_value_py = last_value.item() if isinstance(last_value, numpy.generic) else last_value+ else:+ last_value_py = last_valuelast_value_json: Anyif last_value_py is None:@@ -334,6 +334,9 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldself.save()def delete_table(self):+ # s3fs/boto3 at module scope would load at app population — only this method needs them+ from products.data_warehouse.backend.s3 import get_s3_client # noqa: PLC0415+if self.table is not None:try:client = get_s3_client()@@ -400,6 +403,15 @@ def aget_schema_by_id(schema_id: str, team_id: int) -> ExternalDataSchema | Nonedef update_should_sync(schema_id: str, team_id: int, should_sync: bool) -> ExternalDataSchema | None:+ # data_load.service imports temporalio at module scope; this is a models module, so a+ # top-level import would put the Temporal client on the django.setup() path+ from products.data_warehouse.backend.data_load.service import ( # noqa: PLC0415+ external_data_workflow_exists,+ pause_external_data_schedule,+ sync_external_data_job_workflow,+ unpause_external_data_schedule,+ )+schema = ExternalDataSchema.objects.select_related("source").get(id=schema_id, team_id=team_id)schema.should_sync = should_syncschema.save()diff --git a/products/warehouse_sources/backend/models/external_data_source.py b/products/warehouse_sources/backend/models/external_data_source.pyindex 3d57a4b40ae2..d04e945735b5 100644--- a/products/warehouse_sources/backend/models/external_data_source.py+++ b/products/warehouse_sources/backend/models/external_data_source.py@@ -4,7 +4,6 @@ from uuid import UUIDfrom django.db import modelsimport structlog-import temporaliofrom posthog.helpers.encrypted_fields import EncryptedJSONFieldfrom posthog.models.activity_logging.model_activity import ModelActivityMixin@@ -120,6 +119,10 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldSourceRegistry.get_source(ExternalDataSourceType(self.source_type)).cleanup_cdc_resources_on_deletion(self)def reload_schemas(self):+ # temporalio at module scope would put the Temporal client on the django.setup() path —+ # this is a models module; the service import below pulls it anyway, but only at call time+ import temporalio.service # noqa: PLC0415+from products.data_warehouse.backend.data_load.service import (sync_external_data_job_workflow,trigger_external_data_workflow,diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex e37eccf87e8b..2d3cb40c6cd8 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -8,7 +8,6 @@ from uuid import UUIDfrom django.db import modelsfrom django.db.models import Q-import chdbimport structlogfrom clickhouse_driver.errors import ServerException as ClickHouseServerException@@ -220,6 +219,8 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletself,safe_expose_ch_error: bool = True,) -> DataWarehouseTableIntrospectedColumns:+ import chdb # noqa: PLC0415 - embedded ClickHouse; deferred so this model module stays off the startup path+result: list[tuple[str, ...]] | None = Noneplaceholder_context = HogQLContext(team_id=self.team.pk)s3_table_func = build_function_call(@@ -347,6 +348,8 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletreturn Nonedef get_count(self, safe_expose_ch_error=True) -> int:+ import chdb # noqa: PLC0415 - embedded ClickHouse; deferred so this model module stays off the startup path+placeholder_context = HogQLContext(team_id=self.team.pk)s3_table_func = build_function_call(url=self.url_pattern,diff --git a/products/workflows/backend/models/__init__.py b/products/workflows/backend/models/__init__.pyindex 6cd2675c3b85..09dbd5f9b503 100644--- a/products/workflows/backend/models/__init__.py+++ b/products/workflows/backend/models/__init__.py@@ -1,6 +1,7 @@from .hog_flow.hog_flow import HogFlowfrom .hog_flow.hog_flow_template import HogFlowTemplatefrom .hog_flow_batch_job import HogFlowBatchJob+from .hog_flow_schedule.hog_flow_schedule import HogFlowSchedulefrom .team_workflows_config import TeamWorkflowsConfig-__all__ = ["HogFlow", "HogFlowBatchJob", "HogFlowTemplate", "TeamWorkflowsConfig"]+__all__ = ["HogFlow", "HogFlowBatchJob", "HogFlowSchedule", "HogFlowTemplate", "TeamWorkflowsConfig"]