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.

fix(signals): keep surface queries off synchronous profile reads (#118109)

posthog[bot]1e118d14e21d
diff --git a/products/signals/backend/scout_harness/profile/__init__.py b/products/signals/backend/scout_harness/profile/__init__.py
index 3267a1c1bf8f..6750bac83aef 100644
--- a/products/signals/backend/scout_harness/profile/__init__.py
+++ b/products/signals/backend/scout_harness/profile/__init__.py
@@ -5,7 +5,12 @@ grows with each new inventory section. Keeping it module-scoped lets the source-
stay small and testable.
"""
-from products.signals.backend.scout_harness.profile.builders import INVENTORY_SOURCE_VERSION, build_inventory
+from products.signals.backend.scout_harness.profile.builders import (
+ INVENTORY_SOURCE_VERSION,
+ build_inventory,
+ build_surfaces,
+ deferred_surfaces,
+)
from products.signals.backend.scout_harness.profile.schema import Inventory
-__all__ = ["INVENTORY_SOURCE_VERSION", "Inventory", "build_inventory"]
+__all__ = ["INVENTORY_SOURCE_VERSION", "Inventory", "build_inventory", "build_surfaces", "deferred_surfaces"]
diff --git a/products/signals/backend/scout_harness/profile/builders.py b/products/signals/backend/scout_harness/profile/builders.py
index fc7bc9ca7585..6beeaa1cbd58 100644
--- a/products/signals/backend/scout_harness/profile/builders.py
+++ b/products/signals/backend/scout_harness/profile/builders.py
@@ -84,7 +84,7 @@ logger = logging.getLogger(__name__)
# (or restructuring an existing one) without bumping the version would silently mix old
# and new shapes in the cache. A redaction change bumps it too, so rows built before the
# redaction stop being served.
-INVENTORY_SOURCE_VERSION = "v16"
+INVENTORY_SOURCE_VERSION = "v17"
# Top-events ClickHouse query bounds. 7d is short enough to spot recent bursts and long
# enough to stabilize counts on low-traffic teams; 50 covers the long tail without
@@ -127,15 +127,16 @@ REVIEWER_CORRECTIONS_LIMIT = 20
# most), so it needs no result cap of its own.
SCOUT_FLEET_EMITTED_LOOKBACK_DAYS = 30
-# `_surfaces` binds a pre-check's `{since}` to this many days before now, and `{interval_minutes}`
+# `build_surfaces` binds a pre-check's `{since}` to this many days before now, and `{interval_minutes}`
# to the same span. Most default queries carry their own window off `{now}` and ignore both.
SURFACES_LOOKBACK_DAYS = 30
# The total time the surface queries can take in one build. A surface that the budget leaves out
# reads as `in_use: null`.
SURFACES_TIME_BUDGET_S = 30
+_UNANSWERED_SURFACE: dict[str, Any] = {"in_use": None, "evaluated_at": None, "row_count": None}
-def build_inventory(team: Team) -> Inventory:
+def build_inventory(team: Team, *, surfaces: dict[str, dict[str, Any]] | None = None) -> Inventory:
"""Aggregate the deterministic inventory layer for a team.
Each source is read independently — a failure in one (e.g. warehouse temporarily
@@ -172,7 +173,7 @@ def build_inventory(team: Team) -> Inventory:
"recent_actions": _recent_actions(team),
"business_knowledge": _business_knowledge(team),
"top_events": _top_events(team),
- "surfaces": _surfaces(team),
+ "surfaces": build_surfaces(team) if surfaces is None else surfaces,
}
)
@@ -922,7 +923,7 @@ def _top_events(team: Team) -> list[dict[str, Any]] | None:
]
-def _surfaces(team: Team) -> dict[str, dict[str, Any]]:
+def build_surfaces(team: Team) -> dict[str, dict[str, Any]]:
"""Whether each canonical scout's surface is in use, keyed by scout name.
`top_events` keeps only the top events by volume, and `products_in_use` reads onboarding, so
@@ -946,22 +947,46 @@ def _surfaces(team: Team) -> dict[str, dict[str, Any]]:
deadline = time.monotonic() + SURFACES_TIME_BUDGET_S
return {
skill_name: _surface_entry(team, skill_name, queries[skill_name], configs.get(skill_name), now, deadline)
- for skill_name in sorted(queries.keys() - withheld_skills_for_team(team.id))
+ for skill_name in _surface_skill_names(team, queries)
}
+def deferred_surfaces(
+ team: Team, stored: dict[str, dict[str, Any]], *, answered_since: datetime
+) -> dict[str, dict[str, Any]]:
+ """The `surfaces` section without the queries: the stored answers, and `deferred` for the rest.
+
+ A stored entry is kept only when its query answered at or after `answered_since`. A reader
+ cannot tell a copied entry from a new one, so an old answer or a failure is not copied.
+ """
+ deferred = {**_UNANSWERED_SURFACE, "source": "deferred"}
+ return {
+ skill_name: stored[skill_name] if _answered_since(stored.get(skill_name), answered_since) else deferred
+ for skill_name in _surface_skill_names(team, canonical_precheck_queries())
+ }
+
+
+def _answered_since(entry: dict[str, Any] | None, since: datetime) -> bool:
+ if not entry or entry.get("source") != "skill_default" or not entry.get("evaluated_at"):
+ return False
+ return datetime.fromisoformat(entry["evaluated_at"]) >= since
+
+
+def _surface_skill_names(team: Team, queries: dict[str, str]) -> list[str]:
+ return sorted(queries.keys() - withheld_skills_for_team(team.id))
+
+
def _surface_entry(
team: Team, skill_name: str, query: str, config: SignalScoutConfig | None, now: datetime, deadline: float
) -> dict[str, Any]:
- unanswered: dict[str, Any] = {"in_use": None, "evaluated_at": None, "row_count": None}
# Each query gets at most the time left in the build, so one slow query cannot pass the budget.
remaining_s = math.floor(deadline - time.monotonic())
if remaining_s < 1:
- return {**unanswered, "source": "time_budget"}
+ return {**_UNANSWERED_SURFACE, "source": "time_budget"}
acting_user = resolve_scout_run_acting_user(team, skill_name, config)
user = User.objects.filter(pk=acting_user.user_id).first() if acting_user is not None else None
if user is None:
- return {**unanswered, "source": "no_acting_user"}
+ return {**_UNANSWERED_SURFACE, "source": "no_acting_user"}
try:
result = run_precheck_query(
team,
@@ -979,7 +1004,7 @@ def _surface_entry(
skill_name,
exc_info=True,
)
- return {**unanswered, "source": "query_error"}
+ return {**_UNANSWERED_SURFACE, "source": "query_error"}
return {
"in_use": result.should_run,
"evaluated_at": now.isoformat(),
diff --git a/products/signals/backend/scout_harness/profile/schema.py b/products/signals/backend/scout_harness/profile/schema.py
index cce9eab4f97e..12509d3ac38c 100644
--- a/products/signals/backend/scout_harness/profile/schema.py
+++ b/products/signals/backend/scout_harness/profile/schema.py
@@ -339,8 +339,9 @@ class SurfaceEntry(_Section):
in_use: bool | None
evaluated_at: str | None
# `skill_default` when the shipped default query answered. Otherwise the reason `in_use` is
- # null: `query_error`, `no_acting_user`, or `time_budget`.
- source: Literal["skill_default", "query_error", "no_acting_user", "time_budget"]
+ # null: `query_error`, `no_acting_user`, `time_budget`, or `deferred` when a background build
+ # has not run the query yet.
+ source: Literal["skill_default", "query_error", "no_acting_user", "time_budget", "deferred"]
# The rows the query returned, capped at the pre-check row cap. Null when `in_use` is null.
row_count: int | None
diff --git a/products/signals/backend/scout_harness/tools/profile.py b/products/signals/backend/scout_harness/tools/profile.py
index c23a0bc5afb0..5dcbc9364b71 100644
--- a/products/signals/backend/scout_harness/tools/profile.py
+++ b/products/signals/backend/scout_harness/tools/profile.py
@@ -8,6 +8,8 @@ so a fresh scout doesn't burn 4-5 orientation tool calls on `inbox-source-config
team, or builds a fresh one on cache miss. A read-only caller gets the newest row of any age
instead, marked `stale` when it is past `expires_at`. `compute_project_profile` is the explicit
build path. The cache-miss branch and the `build_signal_project_profile` Celery task call it.
+A read does not run the slow surface queries: it copies the recent stored `surfaces` answers
+and queues the Celery task, which runs them through `refresh_project_profile_surfaces`.
Profile is *deterministic ground truth* (computed from authoritative tables). Distinct
from `SignalScratchpad`, which is the *scout's inferred learnings* (TTL'd, possibly wrong).
@@ -17,7 +19,8 @@ Profile feeds the scratchpad; the scratchpad does not update profile.
from __future__ import annotations
from dataclasses import asdict, dataclass, field
-from datetime import timedelta
+from datetime import datetime, timedelta
+from functools import partial
from typing import Any
from django.db import connection, transaction
@@ -27,7 +30,14 @@ from posthog.models.scoping.manager import resolve_effective_team_id
from posthog.models.team.team import Team
from products.signals.backend.models import SignalProjectProfile
-from products.signals.backend.scout_harness.profile import INVENTORY_SOURCE_VERSION, build_inventory
+from products.signals.backend.scout_harness.profile import (
+ INVENTORY_SOURCE_VERSION,
+ Inventory,
+ build_inventory,
+ build_surfaces,
+ deferred_surfaces,
+)
+from products.signals.backend.tasks import enqueue_project_profile_build
# Soft cache TTL — `get_project_profile` recomputes when the newest row is older than this.
# A scout run reads the profile at start, so a team whose scouts run more often than this
@@ -38,6 +48,9 @@ from products.signals.backend.scout_harness.profile import INVENTORY_SOURCE_VERS
# Callers that *know* the underlying data just changed can bypass the cache via
# `get_project_profile(..., force_refresh=True)`.
PROFILE_TTL = timedelta(hours=1)
+# How old a stored surface answer can be and still go into a new row. Twice the TTL keeps
+# answers across back-to-back hourly rows, and drops the answers a daily scout would read.
+SURFACES_COPY_MAX_AGE = 2 * PROFILE_TTL
# Keep the last N profiles per team. The table is append-only on cache miss; without
# pruning a single active team accumulates indefinitely. N=10 keeps some history for
@@ -129,14 +142,17 @@ def get_project_profile(*, team_id: int, force_refresh: bool = False, lazy_build
# build a fresh one, and an old snapshot still orients better than a 404.
cached = _latest_profile(team_id=team_id, include_expired=not lazy_build)
if cached is not None:
+ # Queue the surface queries again when an earlier background build did not land.
+ if lazy_build and not _surfaces_evaluated_since(cached, timezone.now() - PROFILE_TTL):
+ enqueue_project_profile_build(team_id)
return _to_dataclass(cached)
if not lazy_build:
return None
team = Team.objects.get(id=team_id)
- return compute_project_profile(team=team, force=force_refresh)
+ return compute_project_profile(team=team, force=force_refresh, defer_surfaces=True)
-def compute_project_profile(*, team: Team, force: bool = False) -> ProjectProfile:
+def compute_project_profile(*, team: Team, force: bool = False, defer_surfaces: bool = False) -> ProjectProfile:
"""Build a new profile from authoritative sources and persist it.
Currently writes the inventory layer only. The row is the cache for the next
@@ -156,6 +172,12 @@ def compute_project_profile(*, team: Team, force: bool = False) -> ProjectProfil
a fresh row exists. The lock still serializes concurrent forced rebuilds, so the
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
+ `SURFACES_COPY_MAX_AGE`, and a queued `build_signal_project_profile` adds fresh ones. A forced
+ build queues that task even inside the dedupe window, because its caller expects new data.
"""
# Canonicalize: `RootTeamMixin.save()` stores the row under the root team, so the
# advisory lock, post-lock cache re-check, and prune must all key on the canonical
@@ -164,6 +186,7 @@ def compute_project_profile(*, team: Team, force: bool = False) -> ProjectProfil
parent_team = team.parent_team
if parent_team is not None:
team = parent_team
+ surfaces = None if defer_surfaces else build_surfaces(team)
with transaction.atomic():
with connection.cursor() as cursor:
cursor.execute("SELECT pg_advisory_xact_lock(%s, %s)", [_PROFILE_LOCK_NAMESPACE, team.id])
@@ -172,19 +195,73 @@ def compute_project_profile(*, team: Team, force: bool = False) -> ProjectProfil
existing = _latest_profile(team_id=team.id)
if existing is not None:
return _to_dataclass(existing)
- payload: dict[str, Any] = {"inventory": build_inventory(team).model_dump(mode="json")}
- now = timezone.now()
- # `.unscoped()` to match the reads above — off-request builds have no ambient team.
- row = SignalProjectProfile.objects.unscoped().create(
- team=team,
- expires_at=now + PROFILE_TTL,
- source_version=INVENTORY_SOURCE_VERSION,
- payload=payload,
- )
- _prune_stale_profiles(team_id=team.id)
+ 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)
return _to_dataclass(row)
+def refresh_project_profile_surfaces(*, team_id: int) -> None:
+ """Run the surface queries and store them on the team's fresh profile.
+
+ The fresh row keeps its other sections and its `expires_at`, so a refresh does not repeat
+ 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, so
+ a queued duplicate does not repeat the queries.
+ """
+ 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):
+ return
+ surfaces = build_surfaces(team)
+ with 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)
+ if latest is None:
+ _persist_profile(team, surfaces)
+ return
+ inventory = {**(latest.payload or {}).get("inventory", {}), "surfaces": surfaces}
+ latest.payload = {
+ **(latest.payload or {}),
+ "inventory": Inventory.model_validate(inventory).model_dump(mode="json"),
+ }
+ 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")}
+ now = timezone.now()
+ # `.unscoped()` to match the reads above — off-request builds have no ambient team.
+ row = SignalProjectProfile.objects.unscoped().create(
+ team=team,
+ expires_at=now + PROFILE_TTL,
+ source_version=INVENTORY_SOURCE_VERSION,
+ payload=payload,
+ )
+ _prune_stale_profiles(team_id=team.id)
+ return row
+
+
+def _surfaces_evaluated_since(row: SignalProjectProfile, since: datetime) -> bool:
+ """True when no surface entry is `deferred` and the newest evaluation is at or after `since`.
+
+ A row whose queries all failed has no evaluation time. It counts as current until it
+ expires, because `deferred_surfaces` does not copy failures, so the next row retries them.
+ """
+ surfaces = ((row.payload or {}).get("inventory") or {}).get("surfaces") or {}
+ if any(entry.get("source") == "deferred" for entry in surfaces.values()):
+ return False
+ evaluated = [
+ datetime.fromisoformat(entry["evaluated_at"]) for entry in surfaces.values() if entry.get("evaluated_at")
+ ]
+ return not evaluated or max(evaluated) >= since
+
+
def _prune_stale_profiles(*, team_id: int) -> int:
"""Delete all but the `PROFILE_KEEP_N` most recent profiles for a team.
@@ -207,6 +284,14 @@ def _prune_stale_profiles(*, team_id: int) -> int:
return deleted
+def _stored_surfaces(*, team_id: int) -> dict[str, dict[str, Any]]:
+ """The `surfaces` section of the newest row on the current schema, whatever its age."""
+ row = _latest_profile(team_id=team_id, include_expired=True)
+ if row is None:
+ return {}
+ return (row.payload or {}).get("inventory", {}).get("surfaces") or {}
+
+
def _latest_profile(*, team_id: int, include_expired: bool = False) -> SignalProjectProfile | None:
"""Newest profile for the team on the current schema, within its TTL unless `include_expired`.
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 04f3dd64f62c..823a1dd9465c 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -1,3 +1,4 @@
+from contextlib import suppress
from datetime import timedelta
from decimal import Decimal
@@ -1024,10 +1025,24 @@ def rebuild_signal_repository_activity(team_id: int, repository: str, force: boo
_PROFILE_BUILD_DEDUPE_SECONDS = 5 * 60
-def enqueue_project_profile_build(team_id: int) -> None:
- """Queue one `build_signal_project_profile` per team per dedupe window."""
- if cache.add(f"signals_project_profile_build/{team_id}", "1", timeout=_PROFILE_BUILD_DEDUPE_SECONDS):
- build_signal_project_profile.delay(team_id)
+def enqueue_project_profile_build(team_id: int, *, dedupe: bool = True) -> None:
+ """Queue one `build_signal_project_profile` per team per dedupe window.
+
+ `dedupe=False` queues the build even inside the window. A read calls this after it has its
+ profile, so a cache or broker failure is reported and does not fail the read. A failed
+ enqueue releases the window, so the next read can queue the build again.
+ """
+ key = f"signals_project_profile_build/{team_id}"
+ claimed = False
+ try:
+ claimed = cache.add(key, "1", timeout=_PROFILE_BUILD_DEDUPE_SECONDS)
+ if claimed or not dedupe:
+ build_signal_project_profile.delay(team_id)
+ except Exception as exc:
+ capture_exception(exc, {"team_id": team_id})
+ if claimed:
+ with suppress(Exception):
+ cache.delete(key)
@shared_task(
@@ -1037,15 +1052,15 @@ def enqueue_project_profile_build(team_id: int) -> None:
)
@with_team_scope()
def build_signal_project_profile(team_id: int) -> None:
- """Build the team's project profile off the request path, for a read caller that found none.
+ """Run the surface queries off the request path, and build the profile if the team has none.
- `get_project_profile` returns a fresh row if one landed since the enqueue, and its advisory
- lock collapses this build with a concurrent scout build.
+ A read caller that found no profile queues this, and so does a read whose profile has no
+ current surface entries.
"""
# The `tools` package imports this module through `slack_delivery_queue`.
- from products.signals.backend.scout_harness.tools.profile import get_project_profile # noqa: PLC0415
+ from products.signals.backend.scout_harness.tools.profile import refresh_project_profile_surfaces # noqa: PLC0415
- get_project_profile(team_id=team_id)
+ refresh_project_profile_surfaces(team_id=team_id)
@shared_task(
diff --git a/products/signals/backend/test/test_scout_harness_profile.py b/products/signals/backend/test/test_scout_harness_profile.py
index e5315405d298..4a76bb5a560a 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-en
from __future__ import annotations
+from contextlib import nullcontext
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from uuid import uuid4
@@ -14,6 +15,7 @@ from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flus
from unittest.mock import MagicMock, patch
from django.apps import apps
+from django.core.cache import cache
from django.utils import timezone
from parameterized import parameterized
@@ -72,8 +74,8 @@ from products.signals.backend.scout_harness.profile.builders import (
_recent_surveys,
_scout_fleet,
_signal_source_configs,
- _surfaces,
_top_events,
+ build_surfaces,
)
from products.signals.backend.scout_harness.profile.schema import ScoutFleetEntry
from products.signals.backend.scout_harness.tools.emit import emit_eligibility, emit_eligibility_for_run
@@ -1024,7 +1026,7 @@ class TestTopEvents(BaseTest):
class TestSurfaces(ClickhouseTestMixin, BaseTest):
def test_every_shipped_default_runs_and_reads_a_quiet_surface_as_not_in_use(self) -> None:
# An empty project: a backstop row (surveys) or a bad placeholder binding would read as in use.
- surfaces = _surfaces(self.team)
+ surfaces = build_surfaces(self.team)
assert set(surfaces) == set(canonical_precheck_queries())
assert {name: (entry["source"], entry["in_use"]) for name, entry in surfaces.items()} == dict.fromkeys(
@@ -1037,7 +1039,7 @@ class TestSurfaces(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events()
- entry = _surfaces(self.team)["signals-scout-csp-violations"]
+ entry = build_surfaces(self.team)["signals-scout-csp-violations"]
assert (entry["in_use"], entry["source"], entry["row_count"]) == (True, "skill_default", 1)
assert entry["evaluated_at"] is not None
@@ -1059,7 +1061,7 @@ class TestSurfaces(ClickhouseTestMixin, BaseTest):
"products.signals.backend.scout_harness.precheck.execute_hogql_query", side_effect=[response]
) as query,
):
- surfaces = _surfaces(self.team)
+ surfaces = build_surfaces(self.team)
assert surfaces["signals-scout-x"]["in_use"] is in_use
assert (surfaces["signals-scout-x"]["source"], surfaces["signals-scout-x"]["row_count"]) == (source, row_count)
@@ -1076,7 +1078,7 @@ class TestSurfaces(ClickhouseTestMixin, BaseTest):
return_value=SimpleNamespace(columns=["n"], results=[[1]]),
),
):
- surfaces = _surfaces(self.team)
+ surfaces = build_surfaces(self.team)
assert list(surfaces) == ["signals-scout-x"]
@@ -1202,6 +1204,90 @@ class TestGetProjectProfile(BaseTest):
build_signal_project_profile(self.team.id)
result = get_project_profile(team_id=self.team.id, lazy_build=False)
assert result is not None and result.stale is False
+ sources = {entry["source"] for entry in result.payload["inventory"]["surfaces"].values()}
+ assert sources and "deferred" not in sources
+
+ @parameterized.expand(
+ [
+ ("recent_answers", "recent", True),
+ ("answers_older_than_the_copy_window", "old", False),
+ ("failed_queries", "failed", False),
+ ("no_row", None, False),
+ ]
+ )
+ def test_cache_miss_read_defers_surface_queries_to_a_background_build(
+ self, _name: str, seed: str | None, copies_stored: bool
+ ) -> None:
+ cache.clear()
+ stored = {}
+ if seed is not None:
+ with (
+ patch(f"{BUILDERS}.run_precheck_query", side_effect=RuntimeError("query failed"))
+ if seed == "failed"
+ else nullcontext()
+ ):
+ old = compute_project_profile(team=self.team)
+ payload = old.payload
+ if seed == "old":
+ answered_at = (timezone.now() - 3 * PROFILE_TTL).isoformat()
+ for entry in payload["inventory"]["surfaces"].values():
+ entry["evaluated_at"] = answered_at
+ SignalProjectProfile.objects.filter(id=old.profile_id).update(
+ expires_at=timezone.now() - timedelta(minutes=1), payload=payload
+ )
+ stored = payload["inventory"]["surfaces"]
+ with (
+ patch(f"{BUILDERS}.run_precheck_query", side_effect=AssertionError("surface query on a read")),
+ patch("products.signals.backend.tasks.build_signal_project_profile.delay") as mock_delay,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ result = get_project_profile(team_id=self.team.id)
+ assert result is not None
+ surfaces = result.payload["inventory"]["surfaces"]
+ assert set(surfaces) == set(canonical_precheck_queries())
+ if copies_stored:
+ assert surfaces == stored
+ else:
+ assert {entry["source"] for entry in surfaces.values()} == {"deferred"}
+ mock_delay.assert_called_once_with(self.team.id)
+
+ def test_background_build_fills_surfaces_on_the_read_row_and_skips_a_duplicate(self) -> None:
+ cache.clear()
+ with patch("products.signals.backend.tasks.build_signal_project_profile.delay"):
+ with self.captureOnCommitCallbacks(execute=True):
+ read = get_project_profile(team_id=self.team.id)
+ assert read is not None
+ build_signal_project_profile(self.team.id)
+ row = SignalProjectProfile.objects.get(team=self.team)
+ assert str(row.id) == read.profile_id
+ assert "deferred" not in {entry["source"] for entry in row.payload["inventory"]["surfaces"].values()}
+ with patch(f"{BUILDERS}.run_precheck_query", side_effect=AssertionError("duplicate surface query")):
+ build_signal_project_profile(self.team.id)
+
+ @parameterized.expand([("queued", None, 1), ("broker_down", ConnectionError("broker down"), 2)])
+ def test_cache_hit_with_deferred_surfaces_queues_a_build_without_failing_the_read(
+ self, _name: str, delay_error: Exception | None, expected_enqueues: int
+ ) -> None:
+ cache.clear()
+ cached = compute_project_profile(team=self.team, defer_surfaces=True)
+ cache.clear()
+ with patch(
+ "products.signals.backend.tasks.build_signal_project_profile.delay", side_effect=delay_error
+ ) as mock_delay:
+ first = get_project_profile(team_id=self.team.id)
+ get_project_profile(team_id=self.team.id)
+ assert first is not None and first.profile_id == cached.profile_id
+ assert mock_delay.call_count == expected_enqueues
+
+ def test_force_refresh_queues_a_surface_build_inside_the_dedupe_window(self) -> None:
+ cache.clear()
+ with (
+ patch("products.signals.backend.tasks.build_signal_project_profile.delay") as mock_delay,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ get_project_profile(team_id=self.team.id)
+ get_project_profile(team_id=self.team.id, force_refresh=True)
+ assert mock_delay.call_count == 2
@parameterized.expand([("fresh", timedelta(minutes=30), False), ("expired", -timedelta(days=1), True)])
def test_lazy_build_false_returns_newest_row_whatever_its_age(