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): skip scout runs for a deleted project (#118698)

posthog[bot]e99bc030fa75
diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.py
index 4cc9d75295cd..5032095c5f50 100644
--- a/products/signals/backend/temporal/agentic/scout_coordinator.py
+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py
@@ -21,6 +21,7 @@ from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.dataclasses import frozen
from posthog.models import Team
+from posthog.models.scoping.manager import TeamScopeError
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
@@ -592,51 +593,58 @@ def _collect_planned_runs(
# specific-first from this team's `team_configs` entry, then the fleet `default_team_config`):
# skip seeding the skill, skip seeding/enabling a config, and skip dispatch.
withheld_for_team = _resolve_withheld_skills(team.id, team_configs, default_team_config)
- if needs_seed:
- # Explicitly enrolled (a pinned / force-provisioned id): seed from nothing. The periodic
- # tick is the reconciliation path. `sync_canonical_skills(prune=True)` tombstones rows
- # whose canonical was removed from disk and propagates merged SKILL.md updates to
- # harness-seeded rows the team hasn't edited, so a content change rolls out within one
- # tick. Idempotent; a failure here doesn't abort the tick.
- try:
- sync_canonical_skills(team, prune=True, withheld_skill_names=withheld_for_team)
- except Exception:
- logger.exception(
- "signals_scout coordinator: canonical skill sync failed for team; continuing",
- team_id=team.id,
- )
- # This team's seed posture resolves like the tick cap: its own `team_configs` override
- # layered over the fleet-wide `default_team_config`, most-specific first. Passing the
- # layers (not a shallow merge) lets `_resolve_seed_posture` fall back per key, so a
- # malformed per-team value doesn't clobber a valid fleet default.
- seed_config_layers = [team_configs.get(team.id) or {}, default_team_config]
- # `register_missing_configs` drops withheld skills from its return, so they're already
- # excluded from `live_skills` (and thus from dispatch below) as well as from seeding.
- live_skills = register_missing_configs(team.id, seed_config_layers, withheld_skill_names=withheld_for_team)
- else:
- # Wildcard-discovered (`"*"`): the team already self-seeded its configs through the
- # product-autonomy-gated UI / `sync` materialization, so skip the per-tick seed +
- # reconcile — that's what keeps the hot path cheap as self-enrollment scales to thousands
- # of teams. Read only the live scout skill names (cheap) so a config whose skill was
- # deleted/superseded isn't dispatched, and honor the holdback denylist. Central canonical
- # SKILL.md updates still reach these teams: the runner cold-starts with its own
- # `sync_canonical_skills` before loading the skill (runner.py), so a merged change lands
- # on the scout's NEXT RUN for any harness-seeded row the team hasn't forked. What the
- # per-tick skip drops is only the eager refresh on ticks where nothing dispatches, plus
- # the `prune=True` tombstoning of disk-deleted canonicals and first-appearance of
- # brand-new canonical scouts as rows — both rare, and both catch up on the team's next
- # `sync` (follow-up if needed: a slow fleet-wide prune/seed sweep off the dispatch path).
- live_skills = live_scout_skill_names(team.id, withheld_skill_names=withheld_for_team)
- # The one part of the reconcile the wildcard path still runs: an operational scout
- # that stays off stops the checks and validation that run on it. Only teams with a
- # row that needs it pay for the call, and a withheld scout is never a reason to call.
- if reconcile_by_team.get(team.id, set()) - withheld_for_team:
- _reconcile_wildcard_operational_configs(
- team.id,
- live_skills,
- withheld_for_team,
- [team_configs.get(team.id) or {}, default_team_config],
+ try:
+ if needs_seed:
+ # Explicitly enrolled (a pinned / force-provisioned id): seed from nothing. The periodic
+ # tick is the reconciliation path. `sync_canonical_skills(prune=True)` tombstones rows
+ # whose canonical was removed from disk and propagates merged SKILL.md updates to
+ # harness-seeded rows the team hasn't edited, so a content change rolls out within one
+ # tick. Idempotent; a failure here doesn't abort the tick.
+ try:
+ sync_canonical_skills(team, prune=True, withheld_skill_names=withheld_for_team)
+ except Exception:
+ logger.exception(
+ "signals_scout coordinator: canonical skill sync failed for team; continuing",
+ team_id=team.id,
+ )
+ # This team's seed posture resolves like the tick cap: its own `team_configs` override
+ # layered over the fleet-wide `default_team_config`, most-specific first. Passing the
+ # layers (not a shallow merge) lets `_resolve_seed_posture` fall back per key, so a
+ # malformed per-team value doesn't clobber a valid fleet default.
+ seed_config_layers = [team_configs.get(team.id) or {}, default_team_config]
+ # `register_missing_configs` drops withheld skills from its return, so they're already
+ # excluded from `live_skills` (and thus from dispatch below) as well as from seeding.
+ live_skills = register_missing_configs(
+ team.id, seed_config_layers, withheld_skill_names=withheld_for_team
)
+ else:
+ # Wildcard-discovered (`"*"`): the team already self-seeded its configs through the
+ # product-autonomy-gated UI / `sync` materialization, so skip the per-tick seed +
+ # reconcile — that's what keeps the hot path cheap as self-enrollment scales to thousands
+ # of teams. Read only the live scout skill names (cheap) so a config whose skill was
+ # deleted/superseded isn't dispatched, and honor the holdback denylist. Central canonical
+ # SKILL.md updates still reach these teams: the runner cold-starts with its own
+ # `sync_canonical_skills` before loading the skill (runner.py), so a merged change lands
+ # on the scout's NEXT RUN for any harness-seeded row the team hasn't forked. What the
+ # per-tick skip drops is only the eager refresh on ticks where nothing dispatches, plus
+ # the `prune=True` tombstoning of disk-deleted canonicals and first-appearance of
+ # brand-new canonical scouts as rows — both rare, and both catch up on the team's next
+ # `sync` (follow-up if needed: a slow fleet-wide prune/seed sweep off the dispatch path).
+ live_skills = live_scout_skill_names(team.id, withheld_skill_names=withheld_for_team)
+ # The one part of the reconcile the wildcard path still runs: an operational scout
+ # that stays off stops the checks and validation that run on it. Only teams with a
+ # row that needs it pay for the call, and a withheld scout is never a reason to call.
+ if reconcile_by_team.get(team.id, set()) - withheld_for_team:
+ _reconcile_wildcard_operational_configs(
+ team.id,
+ live_skills,
+ withheld_for_team,
+ [team_configs.get(team.id) or {}, default_team_config],
+ )
+ except TeamScopeError:
+ # The project was deleted during the tick. Skip it rather than fail the whole plan.
+ logger.info("signals_scout coordinator: team is gone, skipping it", team_id=team.id)
+ continue
# The tools drop every output of a run without AI data processing consent, so the run
# only spends model time. The configs keep their status and dispatch again after approval.
if not _ai_data_processing_approved(team):
diff --git a/products/signals/backend/temporal/agentic/scout_scheduler.py b/products/signals/backend/temporal/agentic/scout_scheduler.py
index 2fe2d91533ea..30c16632d403 100644
--- a/products/signals/backend/temporal/agentic/scout_scheduler.py
+++ b/products/signals/backend/temporal/agentic/scout_scheduler.py
@@ -20,6 +20,7 @@ from temporalio.exceptions import ActivityError, ApplicationError, WorkflowAlrea
from posthog.clickhouse.query_tagging import private_capture_context
from posthog.dataclasses import frozen
from posthog.models import Team
+from posthog.models.scoping.manager import TeamScopeError
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.utils import close_db_connections
@@ -144,9 +145,14 @@ class EvaluateScoutPrecheckOutput:
@close_db_connections
async def evaluate_signals_scout_precheck_activity(input: RunSignalsScoutInput) -> EvaluateScoutPrecheckOutput:
"""Evaluate the scout's effective pre-check query. A scout without one always runs."""
- result = await database_sync_to_async(evaluate_scout_precheck, thread_sensitive=False)(
- input.team_id, input.skill_name
- )
+ try:
+ result = await database_sync_to_async(evaluate_scout_precheck, thread_sensitive=False)(
+ input.team_id, input.skill_name
+ )
+ except (TeamScopeError, Team.DoesNotExist):
+ # The project was deleted after the coordinator dispatched this run.
+ logger.info("signals_scout: team is gone, skipping the run", team_id=input.team_id, skill_name=input.skill_name)
+ return EvaluateScoutPrecheckOutput(should_run=False)
if result is None:
return EvaluateScoutPrecheckOutput(should_run=True)
return EvaluateScoutPrecheckOutput(
@@ -156,10 +162,13 @@ async def evaluate_signals_scout_precheck_activity(input: RunSignalsScoutInput)
def _scout_config_runnable(team_id: int, skill_name: str) -> bool:
"""Whether the coordinator would still dispatch this scout: enabled, or paused by the failure
- breaker, which the coordinator probes."""
+ breaker, which the coordinator probes. A deleted project is never runnable."""
+ try:
+ configs = SignalScoutConfig.objects.for_team(team_id)
+ except TeamScopeError:
+ return False
return (
- SignalScoutConfig.objects.for_team(team_id)
- .filter(skill_name=skill_name)
+ configs.filter(skill_name=skill_name)
.filter(
Q(enabled=True)
| Q(
diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.py
index 7384cb806cc4..f62142e2f366 100644
--- a/products/signals/backend/test/test_scout_coordinator.py
+++ b/products/signals/backend/test/test_scout_coordinator.py
@@ -21,6 +21,7 @@ from temporalio.testing import ActivityEnvironment
from posthog.models import Organization, Team, User
from posthog.models.scoping import team_scope
+from posthog.models.scoping.manager import TeamScopeError
from posthog.sync import database_sync_to_async
from products.signals.backend.models import (
@@ -2656,6 +2657,31 @@ async def test_seed_failure_does_not_abort_tick(ateam):
assert any(p.team_id == ateam.id and p.skill_name == "signals-scout-existing" for p in planned)
+async def test_team_deleted_during_the_tick_is_skipped(ateam, aother_team):
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-gone")
+
+ def _seed_other():
+ with team_scope(aother_team.id, canonical=True):
+ _create_skill(aother_team, "signals-scout-kept")
+
+ await database_sync_to_async(_seed_other)()
+ real_register = register_missing_configs
+
+ def _register(team_id, *args, **kwargs):
+ if team_id == ateam.id:
+ raise TeamScopeError(f"Team {team_id} not found on default DB")
+ return real_register(team_id, *args, **kwargs)
+
+ with patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.register_missing_configs", side_effect=_register
+ ):
+ planned = await _run_activity()
+
+ assert {(p.team_id, p.skill_name) for p in planned} == {(aother_team.id, "signals-scout-kept")}
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
@pytest.mark.real_canonical_sync
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index 009a78895c68..44bacbfc2709 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -4168,3 +4168,24 @@ async def test_workflow_sleeps_its_start_delay_and_skips_a_config_disabled_meanw
assert result == output
else:
assert result.skip_reason == "config_disabled"
+
+
+ "activity_function,expected",
+ [
+ (check_signals_scout_config_runnable_activity, False),
+ (evaluate_signals_scout_precheck_activity, EvaluateScoutPrecheckOutput(should_run=False)),
+ ],
+)
+async def test_a_deleted_team_does_not_run(activity_function, expected):
+ missing_team_id = await database_sync_to_async(
+ lambda: (Team.objects.order_by("-id").values_list("id", flat=True).first() or 0) + 1000
+ )()
+
+ result = await ActivityEnvironment().run(
+ activity_function, RunSignalsScoutInput(team_id=missing_team_id, skill_name="s")
+ )
+
+ assert result == expected