: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
fix(signals): build project profile inventory outside the transaction (#126822)
posthog[bot]ae3ab08ef1c3
diff --git a/products/signals/backend/scout_harness/tools/profile.py b/products/signals/backend/scout_harness/tools/profile.pyindex 5dcbc9364b71..63516b08aec8 100644--- a/products/signals/backend/scout_harness/tools/profile.py+++ b/products/signals/backend/scout_harness/tools/profile.py@@ -162,8 +162,8 @@ def compute_project_profile(*, team: Team, force: bool = False, defer_surfaces:Concurrent cache misses (several scout runs, or a scout run and the`build_signal_project_profile` task, hitting the same team at once) take a Postgresadvisory lock keyed on team_id and re-check the cache after acquiring it. Without- this, a thundering herd would each run `build_inventory` and insert a separate row;- the lock collapses them into a single build with the losers returning the winner's freshly persisted row. After persisting, prune so only the+ this, a thundering herd would each insert a separate row; the lock collapses them+ into a single row with the losers returning the winner's freshly persisted row. After persisting, prune so only thelast `PROFILE_KEEP_N` rows survive — the table would otherwise grow unbounded(one row per cache miss, ~once per `PROFILE_TTL` per team, forever).@@ -173,9 +173,12 @@ def compute_project_profile(*, team: Team, force: bool = False, defer_surfaces:cost is at most one duplicate `build_inventory` per simultaneous force request —bounded and only paid by callers who knowingly opted into it.- The surface queries can take up to `SURFACES_TIME_BUDGET_S`. They run before the- transaction, so the advisory lock and the Postgres connection are not held during them.- `defer_surfaces=True` skips them: the row copies the stored answers from the last+ The surface queries can take up to `SURFACES_TIME_BUDGET_S`, and `build_inventory` runs a+ ClickHouse aggregation. Both run before the transaction, so the advisory lock and the+ Postgres connection are not held during them. Postgres can end a connection that stays idle+ in a transaction for too long. The cost is that concurrent cache misses can each build the+ inventory, but the re-check after the lock still keeps one row. `defer_surfaces=True` skips+ the surface queries: the row copies the stored answers from the last`SURFACES_COPY_MAX_AGE`, and a queued `build_signal_project_profile` adds fresh ones. A forcedbuild queues that task even inside the dedupe window, because its caller expects new data."""@@ -186,7 +189,13 @@ def compute_project_profile(*, team: Team, force: bool = False, defer_surfaces:parent_team = team.parent_teamif parent_team is not None:team = parent_team- surfaces = None if defer_surfaces else build_surfaces(team)+ if defer_surfaces:+ surfaces = deferred_surfaces(+ team, _stored_surfaces(team_id=team.id), answered_since=timezone.now() - SURFACES_COPY_MAX_AGE+ )+ else:+ surfaces = build_surfaces(team)+ payload = _inventory_payload(team, surfaces)with transaction.atomic():with connection.cursor() as cursor:cursor.execute("SELECT pg_advisory_xact_lock(%s, %s)", [_PROFILE_LOCK_NAMESPACE, team.id])@@ -196,11 +205,8 @@ def compute_project_profile(*, team: Team, force: bool = False, defer_surfaces:if existing is not None:return _to_dataclass(existing)if defer_surfaces:- surfaces = deferred_surfaces(- team, _stored_surfaces(team_id=team.id), answered_since=timezone.now() - SURFACES_COPY_MAX_AGE- )transaction.on_commit(partial(enqueue_project_profile_build, team.id, dedupe=not force))- row = _persist_profile(team, surfaces)+ row = _persist_profile(team, payload)return _to_dataclass(row)@@ -211,18 +217,24 @@ def refresh_project_profile_surfaces(*, team_id: int) -> None:the inventory build that the read just did. With no fresh row, this builds a full profile.It does nothing when the fresh row's surfaces were evaluated after the row was written, soa queued duplicate does not repeat the queries.++ The inventory for a new row is built before the transaction, for the same reason as in+ `compute_project_profile`. When the fresh row expires before the lock, the surfaces go on+ that expired row, so the next read copies them into its new row."""team = Team.objects.get(id=resolve_effective_team_id(team_id))latest = _latest_profile(team_id=team.id)if latest is not None and _surfaces_evaluated_since(latest, latest.computed_at):returnsurfaces = build_surfaces(team)+ payload = _inventory_payload(team, surfaces) if latest is None else Nonewith transaction.atomic():with connection.cursor() as cursor:cursor.execute("SELECT pg_advisory_xact_lock(%s, %s)", [_PROFILE_LOCK_NAMESPACE, team.id])- latest = _latest_profile(team_id=team.id)+ latest = _latest_profile(team_id=team.id, include_expired=payload is None)if latest is None:- _persist_profile(team, surfaces)+ if payload is not None:+ _persist_profile(team, payload)returninventory = {**(latest.payload or {}).get("inventory", {}), "surfaces": surfaces}latest.payload = {@@ -232,9 +244,13 @@ def refresh_project_profile_surfaces(*, team_id: int) -> None:latest.save(update_fields=["payload"])-def _persist_profile(team: Team, surfaces: dict[str, dict[str, Any]] | None) -> SignalProjectProfile:- """Build the inventory, write it as a new row, and prune. The caller holds the advisory lock."""- payload: dict[str, Any] = {"inventory": build_inventory(team, surfaces=surfaces).model_dump(mode="json")}+def _inventory_payload(team: Team, surfaces: dict[str, dict[str, Any]]) -> dict[str, Any]:+ """Build the inventory. This runs ClickHouse queries, so call it outside a transaction."""+ return {"inventory": build_inventory(team, surfaces=surfaces).model_dump(mode="json")}+++def _persist_profile(team: Team, payload: dict[str, Any]) -> SignalProjectProfile:+ """Write the payload as a new row, and prune. The caller holds the advisory lock."""now = timezone.now()# `.unscoped()` to match the reads above — off-request builds have no ambient team.row = SignalProjectProfile.objects.unscoped().create(diff --git a/products/signals/backend/test/test_scout_harness_profile.py b/products/signals/backend/test/test_scout_harness_profile.pyindex 37d7ec51b3e9..fae1a3bde97e 100644--- a/products/signals/backend/test/test_scout_harness_profile.py+++ b/products/signals/backend/test/test_scout_harness_profile.py@@ -6,6 +6,7 @@ Layered top-down: builder source-readers → `compute_project_profile` end-to-enfrom __future__ import annotations+from collections.abc import Callablefrom contextlib import nullcontextfrom datetime import UTC, datetime, timedeltafrom types import SimpleNamespace@@ -17,6 +18,7 @@ from unittest.mock import MagicMock, patchfrom django.apps import appsfrom django.core.cache import cache+from django.db import connectionfrom django.utils import timezonefrom parameterized import parameterized@@ -85,6 +87,7 @@ from products.signals.backend.scout_harness.tools.profile import (PROFILE_TTL,compute_project_profile,get_project_profile,+ refresh_project_profile_surfaces,)from products.signals.backend.tasks import build_signal_project_profilefrom products.skills.backend.models.skills import LLMSkill@@ -93,6 +96,7 @@ from products.warehouse_sources.backend.facade.models import ExternalDataJob, Exfrom products.workflows.backend.facade.testing import create_workflow_for_testBUILDERS = "products.signals.backend.scout_harness.profile.builders"+PROFILE_TOOL = "products.signals.backend.scout_harness.tools.profile"class TestProjectContext(BaseTest):@@ -1177,6 +1181,29 @@ class TestComputeProjectProfile(BaseTest):# Allow small slack for the two `timezone.now()` calls in the build path.assert PROFILE_TTL - timedelta(seconds=2) < delta < PROFILE_TTL + timedelta(seconds=2)+ @parameterized.expand(+ [+ ("compute", lambda team: compute_project_profile(team=team)),+ ("compute_deferred_surfaces", lambda team: compute_project_profile(team=team, defer_surfaces=True)),+ ("refresh_without_a_row", lambda team: refresh_project_profile_surfaces(team_id=team.id)),+ ]+ )+ def test_builds_the_inventory_outside_the_transaction(self, _name: str, build: Callable[[Team], Any]) -> None:+ outer_depth = len(connection.atomic_blocks)+ depths: list[int] = []++ def record_depth(team: Team, **kwargs: Any) -> Inventory:+ depths.append(len(connection.atomic_blocks))+ return build_inventory(team, **kwargs)++ with (+ patch(f"{PROFILE_TOOL}.build_inventory", side_effect=record_depth),+ patch("products.signals.backend.tasks.build_signal_project_profile.delay"),+ ):+ build(self.team)+ assert depths == [outer_depth]+ assert SignalProjectProfile.objects.filter(team=self.team).count() == 1+class TestGetProjectProfile(BaseTest):def test_returns_existing_fresh_profile_without_recomputing(self) -> None: