: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): notify when the quota limit pauses scout runs (#103035)
Arno Hillenca4ff6905012
diff --git a/products/signals/backend/quota.py b/products/signals/backend/quota.pyindex 9fa53c873303..b9affafcd6a1 100644--- a/products/signals/backend/quota.py+++ b/products/signals/backend/quota.py@@ -129,3 +129,42 @@ def capture_signal_report_quota_paused(team: "Team", *, report_id: str | None, slogger.exception("Failed to capture signal_report_quota_paused", report_id=report_id, team_id=team.id, stage=stage)+++def notify_scout_quota_paused(team: "Team") -> None:+ """Tell the org its self-driving credits quota is now blocking scout runs.++ The quota gate skips runs with no run row and no visible state, so without this a team's+ scouts read as silently dead until the next billing period. Idempotent per limiting episode:+ the key carries the org's `quota_limited_until` and limit, so a new episode (period rollover,+ or a raised limit that the org then exceeds again) notifies again. Best-effort: a failed send+ must never fail the gate that called it. Requires `team.organization` to be loaded.+ """+ try:+ usage = (team.organization.usage or {}).get(QuotaResource.SIGNALS_CREDITS.value) or {}+ quota_limited_until = usage.get("quota_limited_until") or 0+ limit = usage.get("limit") or 0+ from products.notifications.backend.facade.api import ( # noqa: PLC0415 (keeps the heavy dep off the import path)+ NotificationData,+ NotificationType,+ TargetType,+ create_notification,+ )++ create_notification(+ NotificationData(+ team_id=team.id,+ notification_type=NotificationType.USAGE_SPIKE,+ title="Scouts paused: self-driving credits limit reached",+ body=(+ "This project is over its self-driving credits limit, so scheduled scout runs are "+ "skipped until the limit lifts. Usage and limits: Settings > Billing."+ ),+ target_type=TargetType.TEAM,+ target_id=str(team.id),+ source_url="/organization/billing",+ idempotency_key=f"signals_scout_quota_paused:{team.organization_id}:{quota_limited_until}:{limit}",+ )+ )+ except Exception:+ logger.warning("signals_scout_quota_notification_failed", team_id=team.id, exc_info=True)diff --git a/products/signals/backend/temporal/agentic/scout_scheduler.py b/products/signals/backend/temporal/agentic/scout_scheduler.pyindex b35f853cbaf9..35364e9c4827 100644--- a/products/signals/backend/temporal/agentic/scout_scheduler.py+++ b/products/signals/backend/temporal/agentic/scout_scheduler.py@@ -24,7 +24,11 @@ from posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.utils import close_db_connectionsfrom products.signals.backend.daily_limit import capture_signal_report_daily_limit_paused, daily_report_limit_gate-from products.signals.backend.quota import capture_signal_report_quota_paused, self_driving_quota_gate+from products.signals.backend.quota import (+ capture_signal_report_quota_paused,+ notify_scout_quota_paused,+ self_driving_quota_gate,+)from products.signals.backend.scout_harness.limits import (TRIGGERED_BY_CHECK,TRIGGERED_BY_MANUAL,@@ -160,6 +164,9 @@ async def _run_signals_scout(input: RunSignalsScoutInput) -> RunSignalsScoutOutpskill_name=input.skill_name,)metrics.increment_scout_run("quota_limited")+ # No run row exists for a skipped run, so this notification is the only user-visible+ # trace that scheduled scouts stopped; idempotent per limiting episode.+ await database_sync_to_async(notify_scout_quota_paused, thread_sensitive=False)(team)return RunSignalsScoutOutput(run_id=None,task_run_id=None,diff --git a/products/signals/backend/test/test_quota.py b/products/signals/backend/test/test_quota.pyindex 88d07601907a..3ac5d929f53a 100644--- a/products/signals/backend/test/test_quota.py+++ b/products/signals/backend/test/test_quota.py@@ -4,7 +4,12 @@ from typing import TYPE_CHECKING, castimport pytestfrom unittest.mock import patch-from products.signals.backend.quota import SelfDrivingQuotaGate, is_team_signals_quota_limited, self_driving_quota_gate+from products.signals.backend.quota import (+ SelfDrivingQuotaGate,+ is_team_signals_quota_limited,+ notify_scout_quota_paused,+ self_driving_quota_gate,+)if TYPE_CHECKING:from posthog.models import Team@@ -74,3 +79,51 @@ def test_self_driving_quota_gate_fails_open_on_flag_error():),):assert self_driving_quota_gate(_team()) == SelfDrivingQuotaGate(limited=True, enforced=False)+++ ("first_usage", "second_usage", "notifies_again"),+ [+ # Same period, same limit: one notification for the whole limiting episode.+ (+ {"quota_limited_until": 1893456000, "limit": 100},+ {"quota_limited_until": 1893456000, "limit": 100},+ False,+ ),+ # Limit raised then exceeded again in the same period: the same `quota_limited_until`+ # alone would reuse the key, so the key also carries the limit.+ (+ {"quota_limited_until": 1893456000, "limit": 100},+ {"quota_limited_until": 1893456000, "limit": 200},+ True,+ ),+ # New period: new `quota_limited_until`, new notification.+ (+ {"quota_limited_until": 1893456000, "limit": 100},+ {"quota_limited_until": 1924992000, "limit": 100},+ True,+ ),+ ],+)+def test_scout_quota_notification_is_idempotent_per_limiting_episode(first_usage, second_usage, notifies_again):+ usage: dict = {}+ team = cast(+ "Team",+ SimpleNamespace(+ id=7,+ api_token="phc_token",+ organization_id="0195a000-0000-0000-0000-000000000000",+ organization=SimpleNamespace(usage=usage),+ ),+ )+ with (+ patch("products.notifications.backend.facade.api.create_notification", return_value=None) as create,+ ):+ usage["signals_credits"] = first_usage+ notify_scout_quota_paused(team)+ usage["signals_credits"] = second_usage+ notify_scout_quota_paused(team)++ keys = [call.args[0].idempotency_key for call in create.call_args_list]+ assert (keys[0] != keys[1]) is notifies_again+ assert all(key.startswith("signals_scout_quota_paused:0195a000-0000-0000-0000-000000000000:") for key in keys)diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex 3d203e2043c2..6a711f5f6d45 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -2853,6 +2853,7 @@ async def test_activity_skips_run_attributed_to_the_limit_that_fired(patch("products.signals.backend.temporal.agentic.scout_scheduler.capture_signal_report_quota_paused") as capture_quota,+ patch("products.signals.backend.temporal.agentic.scout_scheduler.notify_scout_quota_paused") as notify_quota,patch("products.signals.backend.scout_harness.runner.arun_signals_scout", fake_arun),):env = ActivityEnvironment()@@ -2879,6 +2880,12 @@ async def test_activity_skips_run_attributed_to_the_limit_that_fired(assert capture_daily.call_args.kwargs["stage"] == "scout_run"else:capture_daily.assert_not_called()+ # The user-facing pause notification only fires when the quota actually blocks: a+ # dark-launch pause still runs, and the daily limit surfaces in the usage widget.+ if expected_skip_reason == "quota_limited":+ notify_quota.assert_called_once_with(ateam)+ else:+ notify_quota.assert_not_called()@pytest.mark.asynciodiff --git a/tach.toml b/tach.tomlindex 126bc94a8163..bd17803d2311 100644--- a/tach.toml+++ b/tach.toml@@ -860,6 +860,8 @@ depends_on = ["products.mcp_store",# Facade-only: actionability and safety experiments call the shared decision-model client."products.ml_inference",+ # Facade-only: the quota gate tells the org its self-driving credits limit paused scout runs.+ "products.notifications","products.notebooks","products.product_analytics",# Facade-only: Replay Vision authorizes signal emission per scanner rather than through a