: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): report the PR quota pause and unblock suggestion scans (#94327)
posthog[bot]bbc636005a44
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex 94a32c87ed11..5df2949d54a4 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -1280,7 +1280,7 @@ Gates, in pipeline order:| Stage | Where | Behavior when limited (enforced) || ------------------------------------- | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || ingestion | `check_signals_quota_limited_activity` (buffer flush) | Batch dropped before safety filter / flush (pre-existing gate) |-| scout runs | `run_signals_scout_activity` + manual-trigger API | Run skipped / trigger 429s (pre-existing gate) |+| `scout_run` | `run_signals_scout_activity` + manual-trigger API | Run skipped / trigger 429s. The manual path captures the pause itself, since a rejected trigger never reaches the activity || `promotion` | `assign_and_emit_signal_activity` | Signal still assigned, weighted, and emitted, but the report is not promoted — no summary run spawns; status left untouched || `summary_entry` | `SignalReportSummaryWorkflow`, before any work | Workflow exits; report stays `candidate` || `pre_repo_selection` / `pre_research` | `SignalReportSummaryWorkflow`, between the heavy steps | Workflow reverts the report `in_progress → candidate` and exits; an in-flight research **activity** is never interrupted |@@ -1303,6 +1303,10 @@ Enforcement exists to stop runaway generation, not to guarantee billing capture,A cancel that errors part-way is logged loudly (`self_driving_quota_cancel_failed`) rather than counted as a quota-check fail-open, and nothing is released:a still-alive run gets the cancel retried on the next recheck, while a run the completion signal did reach keeps its implementation records until they are released manually.+**Scout suggestion scans are deliberately not gated.**+A suggestion scan (`arun_scout_suggestions`, and the `suggestions/refresh/` endpoint) opens no pull request, so it can never move the meter, and its output is a stored batch the scouts tab reads rather than signals the pipeline would drop.+Skipping one also costs more than it saves: the coordinator stamps `last_requested_at` at dispatch, so a skipped project waits the full `refresh_days` window even after its billing period resets.+**The pause is blanket: billing-exempt reports pause too.**Every gate reads only the org-level quota verdict; none consults a report's `billing_exempt_reason`, so PostHog-system reports (health checks, engineering analytics, exempt scout skills) — which never consume the quota — pause alongside billable work while the org is over its cap.This is deliberate: a single org-level contract ("over the cap → self-driving pauses") stays simple to reason about and support, the paused work is PostHog-generated and resumes organically once the limit lifts, and an org at its spend ceiling also stops consuming agent compute for non-billable reports.diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex d454b7879eca..5b6c7ea136fd 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -27,7 +27,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e- `config_registry.py``register_missing_configs(team_id)` — auto-creates an enabled, default-schedule `SignalScoutConfig` for any `signals-scout-*` skill lacking one ("author a skill, get a scout"). Called by the coordinator tick; the HTTP surface registers explicitly via the write-scoped config `create` endpoint instead (reads stay side-effect free). A canonical scout's `scout-tags` frontmatter (read through `lazy_seed.canonical_config_tags_for`) is stamped on the row it creates, which is how a product surface claims its scouts by tag instead of by hardcoded skill name — AI observability's self-driving tab lists the `ai-observability`-tagged configs. Forward-only like the rest of the seed posture: adding the key to an already-seeded scout leaves that team's existing config untagged until someone tags it through the config API.- `suggestions.py` / `suggestions_runner.py`- Pre-computed scout suggestions: the push-side twin of the "Suggest a scout" chat button. `suggestions.py` (temporalio-free, cheap to import) holds the structured-output contract the headless run returns (`ScoutSuggestionBatch`: 3-5 items, each a `canonical` "turn this on" pick or a `custom` draft with a ready-to-create `draft_body`), the `signals-scout-suggestions` flag-payload settings (`enabled`, `eligibility_tier` 0-4 (0 = allowlist only), `refresh_days`, `max_children_per_tick`, allow/blocklist, failure breaker), the planner (`plan_suggestion_runs`: recomputes the priority queue from Postgres every tick; tier, then never-generated, then most overdue, then most recently engaged; engagement is a report view or rating, a scout a person turned on or off (`status_changed_by`), or a scout a person created (`created_by`), never a plain edit or a system touch; nothing is stored as a queue; engagement is read only for the teams already in the tier map, since `SignalReportAction.last_at` is deliberately unindexed and an unbounded filter on it scans the whole action history; a team past the failure breaker doubles its refresh interval per further failure, because the cooldown is shorter than the refresh window and so could never hold a scheduled retry back), draft validation (`validate_suggestion_items` drops anything the one-click Create could not apply as-is), and persistence on `SignalScoutSuggestionSet` (one row per team, items as JSON, every write under a row lock since each is a read-modify-write of the column; dismissals carry forward by `skill_name` and survive as hidden tombstones when a batch omits the name, compacted to the dismissal fields so a dropped draft body does not sit in the row forever; a batch persisted after the fleet moved is stored `stale`, and a batch that merely aged past `refresh_days`, whether it held items or concluded there was nothing to suggest, reads as `stale` through `effective_status`, since nothing writes that status on expiry; a failed generation anywhere after the gates keeps the prior items and counts toward the breaker; `mark_stale_if_fleet_changed` is wired to `SignalScoutConfig` saves in `../receivers.py`). Reads hide dismissed, created, and already-enabled items, plus custom drafts whose name a stored skill or config has since taken; the manual refresh endpoint honors the same kill switch and blocklist as the planner, runs the scan as its authenticated caller rather than the resolved team member, and a manual dispatch stamps `last_requested_at` so the coordinator does not double up. `suggestions_runner.py` is the one piece that needs the tasks agent facade: `arun_scout_suggestions` gates (AI-processing consent, signals quota, an acting user), mints a `read_only` headless task with the reserved `SIGNALS_SCOUT_SUGGESTIONS` origin, no GitHub token and no MCP Store servers, because the scan reads project text any member can write, parses the batch with no prose salvage (an unparseable close-out is a failed generation), validates, persists, and emits `$scout_suggestions_generated`. Driven by `temporal/agentic/scout_suggestions.py` (coordinator + child, same shape as the scout coordinator, own schedule) and exposed read/dismiss/refresh at `signals/scout/suggestions/` (`../scout_suggestions_api.py`), where membership, token scope, and resource-level RBAC all anchor to the canonical parent team. The prompt shares `SCOUT_PROJECT_SCAN_GUIDANCE` (in `prompt.py`) with the chat template so the two voices never drift.+ Pre-computed scout suggestions: the push-side twin of the "Suggest a scout" chat button. `suggestions.py` (temporalio-free, cheap to import) holds the structured-output contract the headless run returns (`ScoutSuggestionBatch`: 3-5 items, each a `canonical` "turn this on" pick or a `custom` draft with a ready-to-create `draft_body`), the `signals-scout-suggestions` flag-payload settings (`enabled`, `eligibility_tier` 0-4 (0 = allowlist only), `refresh_days`, `max_children_per_tick`, allow/blocklist, failure breaker), the planner (`plan_suggestion_runs`: recomputes the priority queue from Postgres every tick; tier, then never-generated, then most overdue, then most recently engaged; engagement is a report view or rating, a scout a person turned on or off (`status_changed_by`), or a scout a person created (`created_by`), never a plain edit or a system touch; nothing is stored as a queue; engagement is read only for the teams already in the tier map, since `SignalReportAction.last_at` is deliberately unindexed and an unbounded filter on it scans the whole action history; a team past the failure breaker doubles its refresh interval per further failure, because the cooldown is shorter than the refresh window and so could never hold a scheduled retry back), draft validation (`validate_suggestion_items` drops anything the one-click Create could not apply as-is), and persistence on `SignalScoutSuggestionSet` (one row per team, items as JSON, every write under a row lock since each is a read-modify-write of the column; dismissals carry forward by `skill_name` and survive as hidden tombstones when a batch omits the name, compacted to the dismissal fields so a dropped draft body does not sit in the row forever; a batch persisted after the fleet moved is stored `stale`, and a batch that merely aged past `refresh_days`, whether it held items or concluded there was nothing to suggest, reads as `stale` through `effective_status`, since nothing writes that status on expiry; a failed generation anywhere after the gates keeps the prior items and counts toward the breaker; `mark_stale_if_fleet_changed` is wired to `SignalScoutConfig` saves in `../receivers.py`). Reads hide dismissed, created, and already-enabled items, plus custom drafts whose name a stored skill or config has since taken; the manual refresh endpoint honors the same kill switch and blocklist as the planner, runs the scan as its authenticated caller rather than the resolved team member, and a manual dispatch stamps `last_requested_at` so the coordinator does not double up. `suggestions_runner.py` is the one piece that needs the tasks agent facade: `arun_scout_suggestions` gates (AI-processing consent, an acting user; deliberately no self-driving credits gate, since a scan opens no pull request and so bills nothing, while a skip would still burn the team's whole refresh window), mints a `read_only` headless task with the reserved `SIGNALS_SCOUT_SUGGESTIONS` origin, no GitHub token and no MCP Store servers, because the scan reads project text any member can write, parses the batch with no prose salvage (an unparseable close-out is a failed generation), validates, persists, and emits `$scout_suggestions_generated`. Driven by `temporal/agentic/scout_suggestions.py` (coordinator + child, same shape as the scout coordinator, own schedule) and exposed read/dismiss/refresh at `signals/scout/suggestions/` (`../scout_suggestions_api.py`), where membership, token scope, and resource-level RBAC all anchor to the canonical parent team. The prompt shares `SCOUT_PROJECT_SCAN_GUIDANCE` (in `prompt.py`) with the chat template so the two voices never drift.- `slack_delivery.py` / `slack_delivery_queue.py` / `slack_charts.py`Best-effort direct Slack delivery for configured scout outputs. Finding emissions and surfaced report emits/edits snapshot the run config's destination after their database write commits, then enqueue the shared retrying Celery worker. The destination targets a single channel or up to `MAX_SCOUT_SLACK_DM_TARGETS` members who each get an individual DM (one Celery task per recipient, so retries and permanent failures stay independent; a group DM would need the `mpim:write` scope the Slack app doesn't request). Integrations are project-scoped, so a workspace connected from any environment in the project can receive the canonical parent team's scout output.A report message renders its `charts` through the exports facade (`render_png_export`, attributed to the run's acting user, so the insight access check applies; a system render that expires with its delivery url, so it stays out of the user's export quota and does not outlive its only reference) and appends them as `image` blocks pointing at a signed delivery url; chart links in the prose still reduce to their label. A threaded report carries its charts on the lead message, since the replies only hold the summary's tail. Only `InsightVizNode` / `SavedInsightNode` charts render, capped per report and by a render-time budget (a render only starts if it can finish inside the budget), with rendered assets remembered per delivery so a Slack retry does not re-render, and every failure is skipped rather than failing the delivery — the whole chart build is best effort, not only the render. The Slack integration row is resolved again after the build, since a workspace reconnected during the render window replaces the token on the same row.diff --git a/products/signals/backend/scout_harness/run_gates.py b/products/signals/backend/scout_harness/run_gates.pyindex ea4ac2406fa2..bf8bcf2b64a7 100644--- a/products/signals/backend/scout_harness/run_gates.py+++ b/products/signals/backend/scout_harness/run_gates.py@@ -23,7 +23,7 @@ from posthog.models import Teamfrom products.signals.backend.daily_limit import daily_report_limit_gatefrom products.signals.backend.models import SignalScoutRun-from products.signals.backend.quota import is_team_signals_quota_limited+from products.signals.backend.quota import capture_signal_report_quota_paused, self_driving_quota_gatefrom products.signals.backend.scout_harness.limits import (STALE_RUN_CUTOFF_S,TRIGGERED_BY_WORKFLOW,@@ -99,12 +99,23 @@ def check_fleet_gates(team_id: int) -> ScoutRunRejection | None:def check_spend_gates(team: Team) -> ScoutRunRejection | None:"""Fail fast on the two spend gates `run_signals_scout_activity` re-checks authoritatively, so- a caller gets a clean throttle instead of a 202 whose run only skips."""- if is_team_signals_quota_limited(team.api_token):+ a caller gets a clean throttle instead of a 202 whose run only skips.++ The quota side captures `signal_report_quota_paused` here rather than leaving it to the+ activity: a rejection dispatches nothing, so this is the only place an off-schedule run's+ pause is recorded. `team.organization` must be loaded for that capture.+ """+ quota_gate = self_driving_quota_gate(team)+ if quota_gate.limited:+ capture_signal_report_quota_paused(team, report_id=None, stage="scout_run", enforced=quota_gate.enforced)+ if quota_gate.enforced:return ScoutRunRejection(kind=ScoutRunRejectionKind.THROTTLED,reason="quota_limited",- detail="This project is over its Signals credits quota. Try again later.",+ detail=(+ "Self-driving is paused because this project reached its pull request limit. "+ "Raise the limit or wait for usage to reset."+ ),)if daily_report_limit_gate(team).limited:return ScoutRunRejection(diff --git a/products/signals/backend/scout_harness/suggestions_runner.py b/products/signals/backend/scout_harness/suggestions_runner.pyindex 2ae758d3cc88..8c1a75cfc586 100644--- a/products/signals/backend/scout_harness/suggestions_runner.py+++ b/products/signals/backend/scout_harness/suggestions_runner.py@@ -22,7 +22,6 @@ from posthog.models.team.team import Teamfrom posthog.sync import database_sync_to_asyncfrom products.signals.backend.agent_runtime import STEP_SCOUT_SUGGESTIONS, resolve_agent_runtime-from products.signals.backend.quota import is_team_signals_quota_limitedfrom products.signals.backend.scout_harness.config_registry import (MAX_RUN_INTERVAL_MINUTES,MIN_RUN_INTERVAL_MINUTES,@@ -135,10 +134,12 @@ class SuggestionRunResult:def _gate_skip_reason(team: Team) -> str | None:+ """No self-driving credits gate here: a scan opens no pull request, so it bills nothing, and+ the coordinator stamps `last_requested_at` at dispatch — a skip would cost the team its whole+ refresh window for a limit the scan never charges against.+ """if team.organization.is_ai_data_processing_approved is not True:return "ai_data_processing_not_approved"- if is_team_signals_quota_limited(team.api_token):- return "quota_limited"return Nonediff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 5f9b16fc7ae0..16a1a89d3d3e 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -2447,7 +2447,7 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):404: OpenApiResponse(description="Config not found for this project (or the scout is withheld)."),409: OpenApiResponse(description="A run for this scout is already in progress."),429: OpenApiResponse(- description="The project is over its Signals credits quota, its daily report limit, or its daily scout run budget; try again later."+ description="Self-driving is paused at the project's pull request limit, or the project is over its daily report limit or its daily scout run budget; try again later."),},summary="Run a scout now",@@ -2456,8 +2456,9 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"Useful to test a scout right after authoring it, or to refresh its findings on demand. ""The run executes asynchronously on the worker and inherits every guard the scheduled ""path has: it is forbidden if scouts are not enabled for the project (403), and skipped "- "if the project is over its Signals credits quota, daily report limit, or daily run "- "budget (429) or a run for this scout is already in progress (409). A manual run counts "+ "if self-driving is paused at the project's pull request limit, or the project is over "+ "its daily report limit or daily run budget (429), or a run for this scout is already "+ "in progress (409). A manual run counts ""against the same daily run ""budget as scheduled runs, so repeated manual runs of the same scout can exhaust the ""project's daily allowance. A manual run does not change the scout's schedule or "@@ -2506,7 +2507,8 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# single-flight in the runner and at the Temporal server), but rejecting here avoids# dispatching a workflow that would only be skipped, and turns the common cases into clean# 429/409 responses. Shared with the workflow-triggered path (see `run_gates`).- team = Team.objects.get(pk=team_id)+ # `organization` is select_related for the spend gate's quota-pause capture.+ team = Team.objects.select_related("organization").get(pk=team_id)for rejection in (check_spend_gates(team), check_run_in_flight(team_id, skill_name)):if rejection is not None:_raise_rejection(rejection)diff --git a/products/signals/backend/scout_harness/workflow_runs.py b/products/signals/backend/scout_harness/workflow_runs.pyindex aa5f3c6e58e3..6e80483f48d1 100644--- a/products/signals/backend/scout_harness/workflow_runs.py+++ b/products/signals/backend/scout_harness/workflow_runs.py@@ -64,7 +64,8 @@ def start_workflow_scout_run(*, team_id: int, skill_name: str) -> WorkflowScoutRscout that cannot run (a typo, a deleted skill) and surfaces as a step failure the authornotices; `CONFLICT` / `THROTTLED` are ordinary backpressure the step skips on."""- team = Team.objects.get(pk=team_id)+ # `organization` is select_related for the spend gate's quota-pause capture.+ team = Team.objects.select_related("organization").get(pk=team_id)if team.parent_team_id:raise _rejected(ScoutRunRejectionKind.FORBIDDEN,diff --git a/products/signals/backend/scout_suggestions_api.py b/products/signals/backend/scout_suggestions_api.pyindex 93515d1944e8..b7d262926811 100644--- a/products/signals/backend/scout_suggestions_api.py+++ b/products/signals/backend/scout_suggestions_api.py@@ -28,7 +28,6 @@ from posthog.temporal.common.client import sync_connectfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.signals.backend.models import SignalScoutSuggestionSet-from products.signals.backend.quota import is_team_signals_quota_limitedfrom products.signals.backend.scout_chat import consume_daily_attempt, refund_daily_attemptfrom products.signals.backend.scout_harness.suggestions import (dismiss_suggestion,@@ -212,7 +211,7 @@ class SignalScoutSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSdescription="Organization has not approved AI data processing, or suggestions are off for this project."),409: OpenApiResponse(description="A refresh is already running for this project."),- 429: OpenApiResponse(description="Daily refresh cap reached, or the project is over its Signals quota."),+ 429: OpenApiResponse(description="Daily refresh cap reached."),},summary="Refresh suggested scouts",description=(@@ -229,8 +228,6 @@ class SignalScoutSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSraise exceptions.PermissionDenied("Enable AI data processing for this organization to get scout suggestions.")- if is_team_signals_quota_limited(team.api_token):- raise exceptions.Throttled(detail="This project is over its Signals credits quota. Try again later.")# The same kill switch and blocklist the scheduled planner honors, so a caller with# `signal_scout:write` cannot pull a paid scan on a project an operator has turned off.if not suggestions_allowed_for_team(read_suggestion_settings(), team.id):diff --git a/products/signals/backend/temporal/agentic/scout_scheduler.py b/products/signals/backend/temporal/agentic/scout_scheduler.pyindex aa656ba4da5c..d5c0a3e76f2b 100644--- a/products/signals/backend/temporal/agentic/scout_scheduler.py+++ b/products/signals/backend/temporal/agentic/scout_scheduler.py@@ -21,7 +21,7 @@ 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 is_team_signals_quota_limited+from products.signals.backend.quota import capture_signal_report_quota_paused, self_driving_quota_gatefrom products.signals.backend.scout_harness.limits import (TRIGGERED_BY_MANUAL,TRIGGERED_BY_SCHEDULE,@@ -91,17 +91,21 @@ async def run_signals_scout_activity(input: RunSignalsScoutInput) -> RunSignalsSwhich run outside the run-row try/except — so a transient drop is reported as a failedrun rather than escaping the activity and breaching the "never raises" contract."""- # Skip the run when the team is over its Signals credits quota or its daily report limit,+ # Skip the run when the team is over its self-driving credits quota or its daily report limit,# before any LLM work: a scout run exists to feed signals into the pipeline, and ingestion- # drops them while either limit binds.+ # drops them while either limit binds. The quota side reads `self_driving_quota_gate` rather+ # than the raw limiter so this stage honors the enforcement kill switch and appears in the+ # `signal_report_quota_paused` stream alongside every other paused stage.team = await Team.objects.select_related("organization").aget(pk=input.team_id)- quota_limited = await database_sync_to_async(is_team_signals_quota_limited, thread_sensitive=False)(team.api_token)+ quota_gate = await database_sync_to_async(self_driving_quota_gate, thread_sensitive=False)(team)daily_gate = await database_sync_to_async(daily_report_limit_gate, thread_sensitive=False)(team)- # Captured whenever the daily gate binds — even when the quota skip below wins the- # single-status run counter — so the daily-limit event stream stays complete on co-bound days.+ # Each gate captures whenever it binds — even when the other wins the single-status run+ # counter — so neither event stream has holes on a co-bound day.+ if quota_gate.limited:+ capture_signal_report_quota_paused(team, report_id=None, stage="scout_run", enforced=quota_gate.enforced)if daily_gate.limited:capture_signal_report_daily_limit_paused(team, report_id=None, stage="scout_run", gate=daily_gate)- if quota_limited:+ if quota_gate.enforced:logger.info("signals_scout: skipping run, team over signals_credits quota",team_id=input.team_id,diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex 22cdfdbd6c01..d3a158a8ca6f 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -33,6 +33,7 @@ from posthog.sync import database_sync_to_asyncfrom products.signals.backend.agent_runtime import AgentRuntimefrom products.signals.backend.daily_limit import DailyReportLimitGatefrom products.signals.backend.models import SignalScoutConfig, SignalScoutRun+from products.signals.backend.quota import SelfDrivingQuotaGatefrom products.signals.backend.report_charts import ReportChartfrom products.signals.backend.scout_harness import run_costsfrom products.signals.backend.scout_harness.derived_metadata import DERIVED_METADATA_KEY@@ -2365,21 +2366,33 @@ async def test_activity_returns_skip_outcome_when_already_running(ateam):@pytest.mark.asyncio@pytest.mark.django_db@pytest.mark.parametrize(- ("billing_limited", "daily_limited", "expected_skip_reason"),+ ("quota_gate", "daily_limited", "expected_skip_reason"),[- (True, False, "quota_limited"),- (False, True, "daily_report_limit"),- (True, True, "quota_limited"),+ (SelfDrivingQuotaGate(limited=True, enforced=True), False, "quota_limited"),+ (SelfDrivingQuotaGate(limited=False, enforced=False), True, "daily_report_limit"),+ (SelfDrivingQuotaGate(limited=True, enforced=True), True, "quota_limited"),+ # Dark launch: a limited team with enforcement off still runs, and still reports the pause.+ (SelfDrivingQuotaGate(limited=True, enforced=False), False, None),],)async def test_activity_skips_run_attributed_to_the_limit_that_fired(- ateam, billing_limited, daily_limited, expected_skip_reason+ ateam, quota_gate, daily_limited, expected_skip_reason):- fake_arun = AsyncMock()+ fake_arun = AsyncMock(+ return_value=RunResult(+ run_id="abc",+ task_run_id="def",+ status="completed",+ last_message="ok",+ runtime_s=1.5,+ skill_name="signals-scout-errors",+ skill_version=2,+ )+ )with (patch(- "products.signals.backend.temporal.agentic.scout_scheduler.is_team_signals_quota_limited",- return_value=billing_limited,+ "products.signals.backend.temporal.agentic.scout_scheduler.self_driving_quota_gate",+ return_value=quota_gate,),patch("products.signals.backend.temporal.agentic.scout_scheduler.daily_report_limit_gate",@@ -2387,7 +2400,10 @@ async def test_activity_skips_run_attributed_to_the_limit_that_fired(),patch("products.signals.backend.temporal.agentic.scout_scheduler.capture_signal_report_daily_limit_paused"- ) as capture,+ ) as capture_daily,+ patch(+ "products.signals.backend.temporal.agentic.scout_scheduler.capture_signal_report_quota_paused"+ ) as capture_quota,patch("products.signals.backend.scout_harness.runner.arun_signals_scout", fake_arun),):env = ActivityEnvironment()@@ -2396,16 +2412,24 @@ async def test_activity_skips_run_attributed_to_the_limit_that_fired(RunSignalsScoutInput(team_id=ateam.id, skill_name="signals-scout-errors"),)- fake_arun.assert_not_called()- assert output.run_id is None- assert output.status is Noneassert output.skip_reason == expected_skip_reason- # The capture event tracks its own gate: it fires whenever the daily limit binds, even when- # the quota skip wins the single-status run counter.+ if expected_skip_reason is None:+ fake_arun.assert_called_once()+ else:+ fake_arun.assert_not_called()+ assert output.run_id is None+ assert output.status is None+ # Each capture tracks its own gate: it fires whenever that limit binds, even when the other+ # one wins the single-status run counter, and a dark-launch pause is reported without blocking.+ if quota_gate.limited:+ assert capture_quota.call_args.kwargs["stage"] == "scout_run"+ assert capture_quota.call_args.kwargs["enforced"] is quota_gate.enforced+ else:+ capture_quota.assert_not_called()if daily_limited:- assert capture.call_args.kwargs["stage"] == "scout_run"+ assert capture_daily.call_args.kwargs["stage"] == "scout_run"else:- capture.assert_not_called()+ capture_daily.assert_not_called()@pytest.mark.asyncio@@ -2426,8 +2450,8 @@ async def test_activity_runs_when_team_under_signals_quota(ateam):with (patch(- "products.signals.backend.temporal.agentic.scout_scheduler.is_team_signals_quota_limited",- return_value=False,+ "products.signals.backend.temporal.agentic.scout_scheduler.self_driving_quota_gate",+ return_value=SelfDrivingQuotaGate(limited=False, enforced=False),),patch("products.signals.backend.scout_harness.runner.arun_signals_scout", side_effect=fake_arun),):diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 7f7f18700651..27c230bf13ca 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -42,6 +42,7 @@ from products.signals.backend.models import (SignalScratchpad,)from products.signals.backend.pipeline_identity import AI_STAGE_RESEARCH+from products.signals.backend.quota import SelfDrivingQuotaGatefrom products.signals.backend.scout_harness.derived_metadata import DERIVED_METADATA_KEY, stamp_derived_metadatafrom products.signals.backend.scout_harness.lazy_seed import (HARNESS_SEEDED_BY,@@ -3592,7 +3593,9 @@ class TestScoutHarnessMetadataAPI(APIBaseTest):# The gates themselves live in `run_gates`, shared with the workflow-triggered run path, so# that's where they're patched; the view only maps their outcome onto DRF exceptions.-_QUOTA = "products.signals.backend.scout_harness.run_gates.is_team_signals_quota_limited"+_QUOTA = "products.signals.backend.scout_harness.run_gates.self_driving_quota_gate"+_QUOTA_CAPTURE = "products.signals.backend.scout_harness.run_gates.capture_signal_report_quota_paused"+_UNDER_QUOTA = SelfDrivingQuotaGate(limited=False, enforced=False)_DAILY_GATE = "products.signals.backend.scout_harness.run_gates.daily_report_limit_gate"_FLAG = "products.signals.backend.scout_harness.run_gates._read_flag_payload"_START = "products.signals.backend.temporal.agentic.scout_scheduler.start_manual_signals_scout_run"@@ -3621,7 +3624,7 @@ class TestScoutHarnessConfigRunAPI(APIBaseTest):# guard for the "allow disabled" decision; a stray `enabled` gate would fail the disabled case.config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo", enabled=enabled)with (- patch(_QUOTA, return_value=False),+ patch(_QUOTA, return_value=_UNDER_QUOTA),patch(_CONNECT) as connect,patch(_START, return_value="wf-123") as start,):@@ -3631,18 +3634,37 @@ class TestScoutHarnessConfigRunAPI(APIBaseTest):assert response.json() == {"skill_name": "signals-scout-foo", "workflow_id": "wf-123", "started": True}start.assert_called_once_with(connect.return_value, team_id=self.team.id, skill_name="signals-scout-foo")- def test_run_over_quota_returns_429_without_dispatching(self) -> None:+ @parameterized.expand(+ [+ ("enforced", True, status.HTTP_429_TOO_MANY_REQUESTS, False),+ # Dark launch: the pause is reported, but the run still dispatches.+ ("dark_launch", False, status.HTTP_202_ACCEPTED, True),+ ]+ )+ def test_run_over_quota_reports_the_pause_and_blocks_only_when_enforced(+ self, _name: str, enforced: bool, expected_status: int, dispatches: bool+ ) -> None:config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")- with patch(_QUOTA, return_value=True), patch(_START) as start:+ gate = SelfDrivingQuotaGate(limited=True, enforced=enforced)+ with (+ patch(_QUOTA, return_value=gate),+ patch(_QUOTA_CAPTURE) as capture,+ patch(_CONNECT),+ patch(_START, return_value="wf-123") as start,+ ):response = self.client.post(self._run_url(str(config.id)))- assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS- start.assert_not_called()+ assert response.status_code == expected_status+ assert start.called is dispatches+ # Without this the pause leaves no event trail: a rejected trigger never reaches the+ # activity that would otherwise report it.+ assert capture.call_args.kwargs["stage"] == "scout_run"+ assert capture.call_args.kwargs["enforced"] is enforceddef test_run_over_daily_report_limit_returns_429_without_dispatching(self) -> None:config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")with (- patch(_QUOTA, return_value=False),+ patch(_QUOTA, return_value=_UNDER_QUOTA),patch(_DAILY_GATE, return_value=DailyReportLimitGate(limited=True, limit=2, reports_today=2)),patch(_START) as start,):@@ -3654,7 +3676,7 @@ class TestScoutHarnessConfigRunAPI(APIBaseTest):def test_run_with_in_flight_run_returns_409_without_dispatching(self) -> None:config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")_make_run(self.team, skill_name="signals-scout-foo") # TaskRun IN_PROGRESS by default- with patch(_QUOTA, return_value=False), patch(_START) as start:+ with patch(_QUOTA, return_value=_UNDER_QUOTA), patch(_START) as start:response = self.client.post(self._run_url(str(config.id)))assert response.status_code == status.HTTP_409_CONFLICT@@ -3663,13 +3685,13 @@ class TestScoutHarnessConfigRunAPI(APIBaseTest):def test_run_maps_workflow_already_started_race_to_409(self) -> None:config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")race = WorkflowAlreadyStartedError("wf", "RunSignalsScoutWorkflow")- with patch(_QUOTA, return_value=False), patch(_CONNECT), patch(_START, side_effect=race):+ with patch(_QUOTA, return_value=_UNDER_QUOTA), patch(_CONNECT), patch(_START, side_effect=race):response = self.client.post(self._run_url(str(config.id)))assert response.status_code == status.HTTP_409_CONFLICTdef test_run_unknown_config_returns_404_without_dispatching(self) -> None:- with patch(_QUOTA, return_value=False), patch(_START) as start:+ with patch(_QUOTA, return_value=_UNDER_QUOTA), patch(_START) as start:response = self.client.post(self._run_url("00000000-0000-0000-0000-000000000000"))assert response.status_code == status.HTTP_404_NOT_FOUND@@ -3679,7 +3701,7 @@ class TestScoutHarnessConfigRunAPI(APIBaseTest):config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")with (patch(_WITHHELD, return_value={"signals-scout-foo"}),- patch(_QUOTA, return_value=False),+ patch(_QUOTA, return_value=_UNDER_QUOTA),patch(_START) as start,):response = self.client.post(self._run_url(str(config.id)))@@ -3691,7 +3713,7 @@ class TestScoutHarnessConfigRunAPI(APIBaseTest):# A config can outlive its skill; dispatching would 202 then fail in the runner with no run# row to poll. Reject up front — guards the latest-non-deleted-skill check in `run`.config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-orphan")- with patch(_QUOTA, return_value=False), patch(_START) as start:+ with patch(_QUOTA, return_value=_UNDER_QUOTA), patch(_START) as start:response = self.client.post(self._run_url(str(config.id)))assert response.status_code == status.HTTP_404_NOT_FOUND@@ -3707,7 +3729,7 @@ class TestScoutHarnessConfigRunAPI(APIBaseTest):TaskRun = apps.get_model("tasks", "TaskRun")TaskRun.objects.filter(id=stale.task_run_id).update(created_at=old)with (- patch(_QUOTA, return_value=False),+ patch(_QUOTA, return_value=_UNDER_QUOTA),patch(_CONNECT),patch(_START, return_value="wf-123") as start,):@@ -3723,7 +3745,7 @@ class TestScoutHarnessConfigRunAPI(APIBaseTest):config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")with (patch(_FLAG, return_value={"guaranteed_team_ids": [self.team.id], "skip_team_ids": [self.team.id]}),- patch(_QUOTA, return_value=False),+ patch(_QUOTA, return_value=_UNDER_QUOTA),patch(_START) as start,):response = self.client.post(self._run_url(str(config.id)))@@ -3743,7 +3765,7 @@ class TestScoutHarnessConfigRunAPI(APIBaseTest):_FLAG,return_value={"guaranteed_team_ids": [self.team.id], "default_team_config": {"max_runs_per_day": 1}},),- patch(_QUOTA, return_value=False),+ patch(_QUOTA, return_value=_UNDER_QUOTA),patch(_START) as start,):response = self.client.post(self._run_url(str(config.id)))diff --git a/products/signals/backend/test/test_scout_suggestions.py b/products/signals/backend/test/test_scout_suggestions.pyindex ba1781a8b3c5..ad0b8244f539 100644--- a/products/signals/backend/test/test_scout_suggestions.py+++ b/products/signals/backend/test/test_scout_suggestions.py@@ -586,6 +586,28 @@ async def test_runner_records_a_cancelled_scan_as_a_failure(asuggestion_team):assert (row.status, row.consecutive_failures) == (SignalScoutSuggestionSet.Status.FAILED, 1)+async def test_runner_scans_a_project_that_is_over_its_pr_quota(asuggestion_team):+ # A scan opens no pull request, so it charges nothing against the self-driving credits meter,+ # and a skip would still cost the team the whole refresh window stamped at dispatch. Patched+ # at the limiter read every quota gate bottoms out on, so re-adding one in any form fails here.+ batch = ScoutSuggestionBatch(suggestions=[_custom()])+ with (+ patch("products.signals.backend.quota.is_team_limited", return_value=True),+ patch(+ f"{_RUNNER}.MultiTurnSession.start", new_callable=AsyncMock, return_value=(_fake_session(), batch)+ ) as start,+ patch(f"{_RUNNER}.get_or_create_signals_sandbox_env", return_value="env"),+ patch(f"{_RUNNER}.resolve_acting_user_id_for_team", return_value=42),+ patch("products.signals.backend.scout_harness.suggestions.discover_canonical_skills", return_value=()),+ ):+ result = await arun_scout_suggestions(asuggestion_team.id)++ assert (result.status, result.skip_reason) == ("completed", None)+ start.assert_awaited_once()++@pytest.mark.asyncio@pytest.mark.django_dbasync def test_runner_skips_unapproved_org_before_any_spend(asuggestion_team):@@ -782,6 +804,24 @@ class TestScoutSuggestionsAPI(APIBaseTest):# The scan must act as the caller, not a resolved (possibly more privileged) member.self.assertEqual(mock_start.call_args.kwargs["acting_user_id"], self.user.pk)+ @patch("products.signals.backend.scout_suggestions_api.sync_connect", return_value=MagicMock())+ @patch(+ "products.signals.backend.temporal.agentic.scout_suggestions.start_manual_scout_suggestions_run",+ return_value="wf-1",+ )+ @patch(+ "products.signals.backend.scout_suggestions_api.read_suggestion_settings",+ return_value=SuggestionSettings(enabled=True),+ )+ def test_refresh_dispatches_for_a_project_over_its_pr_quota(self, _settings, mock_start, _connect):+ # The refresh cannot mint a pull request, so the credits limit must not throttle it.+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ with patch("products.signals.backend.quota.is_team_limited", return_value=True):+ response = self.client.post(f"/api/projects/{self.team.id}/signals/scout/suggestions/refresh/")+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)+ mock_start.assert_called_once()+@patch("products.signals.backend.scout_suggestions_api.sync_connect", return_value=MagicMock())@patch("products.signals.backend.temporal.agentic.scout_suggestions.start_manual_scout_suggestions_run")@patch(diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 3f0352ed4ee8..29c7ec63526d 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -904,7 +904,7 @@ export const getSignalsScoutConfigRunUrl = (projectId: string, id: string) => {}/**- * Dispatch one on-demand run of this scout immediately, regardless of its schedule. Useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously on the worker and inherits every guard the scheduled path has: it is forbidden if scouts are not enabled for the project (403), and skipped if the project is over its Signals credits quota, daily report limit, or daily run budget (429) or a run for this scout is already in progress (409). A manual run counts against the same daily run budget as scheduled runs, so repeated manual runs of the same scout can exhaust the project's daily allowance. A manual run does not change the scout's schedule or `last_run_at`. A disabled scout can still be run this way (to test before enabling). Returns immediately with the workflow id — poll the scout's runs for the result.+ * Dispatch one on-demand run of this scout immediately, regardless of its schedule. Useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously on the worker and inherits every guard the scheduled path has: it is forbidden if scouts are not enabled for the project (403), and skipped if self-driving is paused at the project's pull request limit, or the project is over its daily report limit or daily run budget (429), or a run for this scout is already in progress (409). A manual run counts against the same daily run budget as scheduled runs, so repeated manual runs of the same scout can exhaust the project's daily allowance. A manual run does not change the scout's schedule or `last_run_at`. A disabled scout can still be run this way (to test before enabling). Returns immediately with the workflow id — poll the scout's runs for the result.* @summary Run a scout now*/export const signalsScoutConfigRun = async (diff --git a/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx b/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsxindex 5de69fec1542..a3fa00eb1037 100644--- a/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx+++ b/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx@@ -22,7 +22,6 @@ import { GitHubBranchCombobox } from 'lib/integrations/GitHubBranchCombobox'import { GitHubRepositoryCombobox } from 'lib/integrations/GitHubRepositoryCombobox'import { integrationsLogic } from 'lib/integrations/integrationsLogic'-import { inboxUsageLogic } from '../../logics/inboxUsageLogic'import { signalTeamConfigLogic } from '../../logics/signalTeamConfigLogic'import { userAutonomyLogic } from '../../logics/userAutonomyLogic'import { PRIORITY_THRESHOLD_OPTIONS, SignalReportPriority } from '../../types'@@ -231,9 +230,10 @@ function BaseBranchOverrides(): JSX.Element {* than the billing usage card: it is "how much should the agents do", not "what does the plan* allow", and placing it next to plan usage read as if the two limits were one system. Renders* regardless of the auto-start toggle, since the cap pauses report generation, not just PRs.- * While the billing quota has the pipeline paused, the live count is withheld so remaining daily- * headroom is not advertised on a day when nothing will arrive. Same collapsed-by-default shape- * as Base branch overrides: the trigger's count keeps the state readable without opening.+ * The billing quota deliberately does not overwrite this row: it caps pull requests, not reports,+ * so stamping its pause here reported the wrong limit as the reason nothing arrived. Same+ * collapsed-by-default shape as Base branch overrides: the trigger's count keeps the state+ * readable without opening.*/function DailyReportLimit(): JSX.Element {const {@@ -245,13 +245,11 @@ function DailyReportLimit(): JSX.Element {teamConfigUpdating,} = useValues(signalTeamConfigLogic)const { setDraftMaxReportsPerDay, saveDraftMaxReportsPerDay } = useActions(signalTeamConfigLogic)- const { quotaLimited } = useValues(inboxUsageLogic)- const summary = quotaLimited- ? 'Paused by plan limit'- : maxReportsPerDay != null- ? `${Math.min(reportsGeneratedToday, maxReportsPerDay)} / ${maxReportsPerDay} today`- : null+ const summary =+ maxReportsPerDay != null+ ? `${Math.min(reportsGeneratedToday, maxReportsPerDay)} / ${maxReportsPerDay} today`+ : nullreturn (<>@@ -289,7 +287,7 @@ function DailyReportLimit(): JSX.Element {</div></CollapsibleContent></Collapsible>- {dailyReportLimitReached && !quotaLimited && (+ {dailyReportLimitReached && (<p className="text-xs font-medium text-danger mb-0 px-2.5 pb-1.5">Daily report limit reached. New reports resume at midnight in your project's timezone.</p>diff --git a/products/signals/frontend/inbox/components/shell/InboxUsageWidget.tsx b/products/signals/frontend/inbox/components/shell/InboxUsageWidget.tsxindex 798e0bec2cfc..8853bd5d35e0 100644--- a/products/signals/frontend/inbox/components/shell/InboxUsageWidget.tsx+++ b/products/signals/frontend/inbox/components/shell/InboxUsageWidget.tsx@@ -220,7 +220,8 @@ export function InboxUsageWidget(): JSX.Element | null {</div>{quotaLimited && (<span className="text-xs font-medium text-danger">- Agents are paused and won't open new pull requests until the limit is raised or usage resets.+ Agents are paused. They won't write new reports or open pull requests until the limit is raised+ or usage resets.</span>)}{canAccessBilling ? (diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex 895607f4551f..d782fa3bd639 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -1129,7 +1129,7 @@ export const SignalsScoutConfigDestroyParams = () => zod.object({})/**- * Dispatch one on-demand run of this scout immediately, regardless of its schedule. Useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously on the worker and inherits every guard the scheduled path has: it is forbidden if scouts are not enabled for the project (403), and skipped if the project is over its Signals credits quota, daily report limit, or daily run budget (429) or a run for this scout is already in progress (409). A manual run counts against the same daily run budget as scheduled runs, so repeated manual runs of the same scout can exhaust the project's daily allowance. A manual run does not change the scout's schedule or `last_run_at`. A disabled scout can still be run this way (to test before enabling). Returns immediately with the workflow id — poll the scout's runs for the result.+ * Dispatch one on-demand run of this scout immediately, regardless of its schedule. Useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously on the worker and inherits every guard the scheduled path has: it is forbidden if scouts are not enabled for the project (403), and skipped if self-driving is paused at the project's pull request limit, or the project is over its daily report limit or daily run budget (429), or a run for this scout is already in progress (409). A manual run counts against the same daily run budget as scheduled runs, so repeated manual runs of the same scout can exhaust the project's daily allowance. A manual run does not change the scout's schedule or `last_run_at`. A disabled scout can still be run this way (to test before enabling). Returns immediately with the workflow id — poll the scout's runs for the result.* @summary Run a scout now*/export const SignalsScoutConfigRunParams = () => zod.object({