Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(devex): flag hot parent row locks (#89930)

Sven Lange4cf7533c432d
diff --git a/.semgrep/rules/devex/hot-parent-row-select-for-update.py b/.semgrep/rules/devex/hot-parent-row-select-for-update.py
new file mode 100644
index 000000000000..9ca879070400
--- /dev/null
+++ b/.semgrep/rules/devex/hot-parent-row-select-for-update.py
@@ -0,0 +1,36 @@
+# Test cases for hot-parent-row-select-for-update.
+# ruff: noqa
+
+
+# ruleid: hot-parent-row-select-for-update
+Team.objects.select_for_update().get(id=team_id)
+
+# ruleid: hot-parent-row-select-for-update
+Organization.objects.select_for_update(skip_locked=True).filter(id__in=organization_ids)
+
+# ruleid: hot-parent-row-select-for-update
+Team.objects.only("id").select_for_update().get(id=team_id)
+
+# ruleid: hot-parent-row-select-for-update
+Organization.objects.filter(is_active=True).order_by("id").select_for_update()
+
+# ruleid: hot-parent-row-select-for-update
+Team.objects.using("default").filter(is_active=True).only("id").order_by("id").select_for_update()
+
+# ok: hot-parent-row-select-for-update
+Team.objects.only("id").select_for_update(no_key=True).get(id=team_id)
+
+# ok: hot-parent-row-select-for-update
+Project.objects.select_for_update().get(id=project_id)
+
+# ok: hot-parent-row-select-for-update
+TeamConversationsSlackConfig.objects.select_for_update().get(team_id=team_id)
+
+# ok: hot-parent-row-select-for-update
+Team.objects.filter(id=team_id).first()
+
+# ok: hot-parent-row-select-for-update
+Organization.objects.only("id").filter(id=organization_id).exists()
+
+# nosemgrep: hot-parent-row-select-for-update -- deleting the parent must block concurrent child inserts
+Team.objects.select_for_update().filter(id__in=team_ids)
diff --git a/.semgrep/rules/devex/hot-parent-row-select-for-update.yaml b/.semgrep/rules/devex/hot-parent-row-select-for-update.yaml
new file mode 100644
index 000000000000..6a8db31da3a1
--- /dev/null
+++ b/.semgrep/rules/devex/hot-parent-row-select-for-update.yaml
@@ -0,0 +1,36 @@
+rules:
+ - id: hot-parent-row-select-for-update
+ message: |
+ Locking Team or Organization makes unrelated child-row writers wait on a hot parent row.
+ If the lock guards one product's per-team settings, lock that product's Team<Product>Config
+ extension row instead, reached through get_or_create_team_extension. Contention then reaches
+ only the writers of that one config. See posthog/models/team/README.md. If the lock enforces
+ a per-team count limit or allocates a per-team number, use a unique constraint, a conditional
+ update, or a dedicated allocation row. Otherwise lock the
+ quiet row that represents the serialized resource. If the parent row is
+ the resource being changed or deleted, suppress this finding with
+ `# nosemgrep: hot-parent-row-select-for-update -- <short justification>`.
+ Pre-existing findings are grandfathered; only newly introduced findings block CI.
+ languages: [python]
+ severity: WARNING
+ patterns:
+ - pattern: $MODEL.objects. ... .select_for_update(...)
+ - pattern-not: $MODEL.objects. ... .select_for_update(..., no_key=True, ...)
+ - metavariable-regex:
+ metavariable: $MODEL
+ regex: ^(Team|Organization)$
+ paths:
+ include:
+ - ee/**/*.py
+ - posthog/**/*.py
+ - products/**/*.py
+ exclude:
+ - '**/test/**'
+ - '**/tests/**'
+ - '**/test_*.py'
+ - '**/*_test.py'
+ - '**/conftest*.py'
+ metadata:
+ category: performance
+ subcategory: audit
+ confidence: HIGH
diff --git a/AGENTS.md b/AGENTS.md
index f578864cadac..bd0299c683f0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -198,6 +198,7 @@ See [.agents/security.md](.agents/security.md) for security guidelines — least
- **Use personhog client for all person/group data access — do not query persons DB tables via the Django ORM or raw SQL.** The `posthog/personhog_client/` gRPC client is the required interface for reading and writing person-related data. This applies to the following tables: `posthog_person`, `posthog_persondistinctid`, `posthog_cohortpeople`, `posthog_group`, `posthog_grouptypemapping`, and related override tables (`posthog_personoverride`, `posthog_pendingpersonoverride`, `posthog_flatpersonoverride`, `posthog_featureflaghashkeyoverride`, `posthog_personlessdistinctid`, `posthog_personoverridemapping`). Use the helpers in `posthog/models/person/util.py` (e.g. `get_person_by_uuid`, `get_persons_by_distinct_ids`, `get_person_by_distinct_id`) and `posthog/models/group_type_mapping.py` (`get_group_types_for_project`) — these already route through personhog with ORM fallback via `_personhog_routed()`. When adding new person/group data access, follow the same `_personhog_routed()` pattern: provide a `personhog_fn` using `get_personhog_client()` and an `orm_fn` fallback. Never add new direct ORM queries like `Person.objects.filter(...)` or `PersonDistinctId.objects.filter(...)` — use the existing routed helpers or create new ones following the established pattern. See `posthog/personhog_client/README.md` for client details and `posthog/personhog_client/client.py` for the full RPC interface.
- **Personhog is for identity questions only; person properties and bulk person reads come from ClickHouse.** Use personhog for resolving distinct IDs to persons, point lookups by person id/UUID, and lifecycle writes. Use ClickHouse (HogQL over the `persons` table, `ActorsQueryRunner`) for loading person properties, hydrating lists of persons, and searching/filtering persons. Avoid reading the `properties` field from personhog where possible — the API will eventually stop surfacing it to users; single-person point lookups that need properties are exempt only while no ClickHouse primitive covers them, and never in bulk. See [docs/internal/person-data-access.md](docs/internal/person-data-access.md).
- **PostHog does not enable `ATOMIC_REQUESTS` — there is no implicit per-request transaction.** Each database operation runs in autocommit mode unless explicitly wrapped. Use `with transaction.atomic():` around the specific writes that must succeed or fail together. Do not wrap an entire view method atomically — keep the block as narrow as possible around the related writes. Avoid performing irreversible side effects (sending emails, calling external APIs, enqueuing Celery tasks) inside an atomic block: if the transaction rolls back, those side effects have already happened. Schedule such side effects after the commit, or use `transaction.on_commit()` for Celery task dispatch.
+- **Do not use `Team` or `Organization` rows as mutexes.** PostgreSQL can take `KEY SHARE` locks on parent rows for foreign-key checks, and `FOR UPDATE` conflicts with them. An unrelated child-row write can therefore wait behind a transaction that locks a hot parent row. Where the lock guards one product's per-team settings, lock that product's `Team<Product>Config` extension row instead, and reach it through `get_or_create_team_extension` so the row exists before you lock it (see [posthog/models/team/README.md](posthog/models/team/README.md)). Contention then reaches only the writers of that one config, not every writer of a table that points at `Team`. Where the lock enforces a per-team count limit or allocates a per-team number, use a unique constraint, a conditional update, or a dedicated allocation row for that resource. Otherwise lock the quiet child or control row for the serialized resource, or take a transaction-scoped advisory lock keyed to it. Lock `Team` or `Organization` only when the transaction updates or deletes that parent row. Keep that transaction short, with no network calls or input-sized Python loops. The `hot-parent-row-select-for-update` Semgrep rule requires each exception to include a short `nosemgrep` justification.
- **Object storage is SeaweedFS — do not add new MinIO dependencies.** Both S3-compatible stores in the dev/CI stack are SeaweedFS: the `objectstorage` service (S3 API on `:19000`) backs general object storage (`OBJECT_STORAGE_*` settings — exports, media uploads, error-tracking source maps, query cache, tasks), and the `seaweedfs` service (S3 API on `:8333`) backs session replay v2 (`SESSION_RECORDING_V2_S3_*` settings). MinIO now survives only as migration tooling: `docker-compose.hobby.yml` keeps it as a source for `bin/migrate-storage-hobby`, and `bin/upgrade-objectstorage` starts a throwaway MinIO to salvage objects off the pre-swap volume. Outside that, don't add docker-compose services, scripts, tests, or docs that stand up a `minio/minio` container. Code that talks to object storage should go through the existing `OBJECT_STORAGE_*` / `SESSION_RECORDING_V2_S3_*` config and a standard S3 client rather than hardcoding an endpoint — that keeps backends swappable. Note the `objectstorage` service registers its credentials at runtime via a bootstrap loop and returns `InvalidAccessKeyId` until that completes, so anything depending on it must wait for its readiness sentinel rather than just for the container to start.
- **Temporal activity payloads have a ~2 MiB hard limit — pass large data by reference, not by value.** Activity inputs and outputs are serialized across a gRPC boundary that Temporal caps at ~2 MiB per payload (the server rejects larger payloads via `blobSizeLimitError`). As a conservative field-level rule, if a field could exceed ~256 KB once serialized (serialized query results, exported file contents, LLM context, rendered HTML, image bytes, unbounded `list[dict[str, Any]]`), write it to Postgres / S3 / object storage from _inside_ the activity and return only the reference (row ID, S3 key). The workflow already has access to any row ID created earlier in the same run; it does not need the content to flow back through. Shuttling large data through the workflow on the way to persistence is a foreseeable failure mode that produces `PayloadSizeError` (`TMPRL1103`) the moment the underlying data crosses the limit.
- **Outbound calls to a third-party API that need rate-limiting or egress telemetry belong in `posthog/egress/` — add a `<domain>/` incarnation (GitHub is the reference) and route callers through its gated, recorded transport, never hand-rolled `requests`. See `posthog/egress/README.md`.**