: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
feat(self-driving): gate pipeline stages on the self-driving credits quota (#74651)
Alex Lebedeva8e40a3bb9d7
diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.pyindex 5cc78cbcc7fa..e0441530ca87 100644--- a/ee/billing/quota_limiting.py+++ b/ee/billing/quota_limiting.py@@ -7,7 +7,7 @@ from time import timefrom typing import Any, Optional, TypedDict, castfrom django.conf import settings-from django.db import close_old_connections+from django.db import close_old_connections, transactionfrom django.db.models import Qfrom django.db.models.expressions import RawSQLfrom django.utils import timezone@@ -26,6 +26,7 @@ from posthog.models.team.team import Teamfrom posthog.redis import get_clientfrom posthog.tasks.usage_report import (convert_team_usage_rows_to_dict,+ get_self_driving_credits_used_in_period_for_org,get_signals_credited_refund_credits_for_org,get_teams_with_ai_credits_used_in_period,get_teams_with_ai_event_count_in_period,@@ -732,6 +733,57 @@ def update_org_billing_quotas(organization: Organization):invalidate_llm_gateway_quota_cache(teams_by_token.values())+def refresh_org_self_driving_quota(organization_id: str) -> None:+ """Recompute one org's live `signals_credits` usage for today and re-evaluate its quota limits.++ Dispatched when a self-driving implementation run records its first PR URL (the billable moment), so+ the Redis limited flag can flip within seconds of the PR that crosses the limit. Without this,+ `update_org_billing_quotas` reads the `todays_usage` value patched by the last quota cron tick,+ which by definition predates the PR that just landed — the cron (every 15 minutes) remains the+ backstop for orgs that cross the limit without a PR event.++ Concurrent refreshes for one org (two PRs landing close together) are serialized on the org+ row, and this path only ever raises `todays_usage`: it fires exclusively because a PR landed,+ so a slower refresh that counted usage before a newer PR must not overwrite the fresher value+ and momentarily unpause the org. Decreases (refunds, cron corrections) stay the cron's job.++ Scope caveat: the recount covers today's UTC window keyed on the implementation run's+ `created_at`, so a PR recorded after midnight by a run created before midnight falls in+ yesterday's window and is invisible to this refresh and to the cron. It reaches enforcement+ hours later, when the previous day's usage report lands in `organization.usage`; billing+ itself stays correct because that report queries yesterday's window with the PR present.+ """+ organization = Organization.objects.filter(id=organization_id).first()+ if organization is None or not organization.usage:+ return+ if not organization.usage.get(QuotaResource.SIGNALS_CREDITS.value):+ return++ # The billing count runs outside the lock so the hot organization row is locked only for+ # the compare-and-patch; the monotonic guard below makes a stale count harmless.+ period_start, period_end = get_current_day()+ todays_credits = get_self_driving_credits_used_in_period_for_org(organization.id, period_start, period_end)++ with transaction.atomic():+ # filter().first() like the precheck above: the org can be deleted between the two+ # reads, and a deleted org needs no refresh rather than a DoesNotExist from the task.+ organization = Organization.objects.select_for_update().filter(id=organization_id).first()+ if organization is None:+ return+ resource_usage = (organization.usage or {}).get(QuotaResource.SIGNALS_CREDITS.value)+ if not resource_usage:+ return+ if todays_credits > (resource_usage.get("todays_usage") or 0):+ resource_usage["todays_usage"] = todays_credits+ _patch_organization_usage_jsonb(+ organization, [([QuotaResource.SIGNALS_CREDITS.value, "todays_usage"], todays_credits)]+ )+ # Evaluate from the freshest committed usage, not this task's snapshot: a newer concurrent+ # refresh may have written a higher value while we held or waited on the lock.+ organization.refresh_from_db(fields=["usage"])+ update_org_billing_quotas(organization)++def set_org_usage_summary(organization: Organization,new_usage: Optional[OrganizationUsageInfo] = None,@@ -1186,6 +1238,16 @@ def update_all_orgs_billing_quotas(org.refresh_from_db(fields=["usage", "customer_trust_scores", "never_drop_data"])refresh_total_seconds += time() - refresh_call_startrefresh_count += 1+ if (org.usage or {}).get(QuotaResource.SIGNALS_CREDITS.value):+ # The queries-phase snapshot predates any push-refresh that fired during+ # this run (`refresh_org_self_driving_quota` raises `todays_usage` the+ # moment a PR lands); writing the older snapshot back would unpause an+ # over-limit org until the next tick. Recount live instead — as a count+ # of the current window it also keeps legitimate decreases (day+ # rollover, refunds) intact.+ todays_report["signals_credits"] = get_self_driving_credits_used_in_period_for_org(+ org_id, period_start, period_end+ )_patch_todays_usage(org, todays_report)diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.pyindex a2b315c2e3f7..b70d4ff01b7a 100644--- a/ee/billing/test/test_quota_limiting.py+++ b/ee/billing/test/test_quota_limiting.py@@ -31,6 +31,7 @@ from ee.billing.quota_limiting import (get_team_attribute_by_quota_resource,list_limited_team_attributes,org_quota_limited_until,+ refresh_org_self_driving_quota,replace_limited_team_tokens,set_org_usage_summary,update_all_orgs_billing_quotas,@@ -2869,3 +2870,99 @@ class TestSignalsRefundQuotaOffset(BaseTest):with patch("ee.billing.quota_limiting.get_signals_credited_refund_credits_for_org") as mock_offset:org_quota_limited_until(self.organization, QuotaResource.EVENTS, [], [])mock_offset.assert_not_called()+++class TestRefreshOrgSelfDrivingQuota(BaseTest):+ def _set_self_driving_usage(self, usage: int, *, todays_usage: int = 0, limit: int = 4500) -> None:+ self.organization.usage = {+ "signals_credits": {"usage": usage, "todays_usage": todays_usage, "limit": limit},+ "period": ["2026-06-01T00:00:00Z", "2026-07-01T00:00:00Z"],+ }+ self.organization.customer_trust_scores = {}+ self.organization.save()++ @patch("posthoganalytics.capture")+ @patch("posthoganalytics.feature_enabled", return_value=False)+ @freeze_time("2026-06-15T12:00:00Z")+ def test_refresh_patches_todays_usage_and_flips_the_limiter(self, _feature_enabled, _capture) -> None:+ # The event-driven path exists because the cron-patched todays_usage predates the PR that+ # just landed: a stale value here means the flag doesn't flip until the next cron tick.+ self._set_self_driving_usage(3000, todays_usage=0)+ with patch(+ "ee.billing.quota_limiting.get_self_driving_credits_used_in_period_for_org", return_value=1500+ ) as live_mock:+ refresh_org_self_driving_quota(str(self.organization.id))++ assert live_mock.call_args.args[0] == self.organization.id+ self.organization.refresh_from_db()+ assert self.organization.usage is not None+ assert self.organization.usage["signals_credits"]["todays_usage"] == 1500+ # 3000 recorded + 1500 live == the 4500 limit: the team must now be in the limited zset.+ assert self.team.api_token in list_limited_team_attributes(+ QuotaResource.SIGNALS_CREDITS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY+ )++ @patch("posthoganalytics.capture")+ @patch("posthoganalytics.feature_enabled", return_value=False)+ @freeze_time("2026-06-15T12:00:00Z")+ def test_stale_concurrent_refresh_cannot_lower_usage_or_unpause(self, _feature_enabled, _capture) -> None:+ # Two refreshes can overlap when two PRs land close together; the one that counted usage+ # before the newer PR can finish last. Its stale, lower count must not overwrite the+ # fresher value and momentarily reopen the gates for an over-limit org.+ self._set_self_driving_usage(3000, todays_usage=1500)+ replace_limited_team_tokens(+ QuotaResource.SIGNALS_CREDITS,+ {self.team.api_token: 1750323600},+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,+ )+ with patch("ee.billing.quota_limiting.get_self_driving_credits_used_in_period_for_org", return_value=100):+ refresh_org_self_driving_quota(str(self.organization.id))++ self.organization.refresh_from_db()+ assert self.organization.usage is not None+ assert self.organization.usage["signals_credits"]["todays_usage"] == 1500+ assert self.team.api_token in list_limited_team_attributes(+ QuotaResource.SIGNALS_CREDITS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY+ )++ @patch("posthoganalytics.capture")+ @patch("posthoganalytics.feature_enabled", return_value=False)+ @freeze_time("2026-06-15T12:00:00Z")+ def test_quota_cron_recounts_live_instead_of_writing_its_stale_snapshot(self, _feature_enabled, _capture) -> None:+ # The cron snapshots fleet usage before its org loop, so a push-refresh that fires while+ # the loop runs (a PR landing) writes a fresher, higher todays_usage than the snapshot.+ # Writing the snapshot back would unpause the over-limit org until the next tick; the+ # cron must recount candidates live at decision time instead.+ self._set_self_driving_usage(3000, todays_usage=1500)+ # Score must be in the frozen clock's future: candidate selection reads the zset+ # through `list_limited_team_attributes`, which drops expired entries.+ replace_limited_team_tokens(+ QuotaResource.SIGNALS_CREDITS,+ {self.team.api_token: 1798761600},+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,+ )+ with (+ patch(+ "ee.billing.quota_limiting.get_teams_with_signals_credits_used_in_period",+ return_value=[(self.team.id, 100)],+ ),+ patch(+ "ee.billing.quota_limiting.get_self_driving_credits_used_in_period_for_org", return_value=1500+ ) as live_mock,+ ):+ update_all_orgs_billing_quotas()++ assert live_mock.call_args.args[0] == str(self.organization.id)+ self.organization.refresh_from_db()+ assert self.organization.usage is not None+ assert self.organization.usage["signals_credits"]["todays_usage"] == 1500+ assert self.team.api_token in list_limited_team_attributes(+ QuotaResource.SIGNALS_CREDITS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY+ )++ def test_refresh_is_a_noop_without_self_driving_usage(self) -> None:+ self.organization.usage = {"events": {"usage": 1, "todays_usage": 0, "limit": None}}+ self.organization.save()+ with patch("ee.billing.quota_limiting.get_self_driving_credits_used_in_period_for_org") as live_mock:+ refresh_org_self_driving_quota(str(self.organization.id))+ live_mock.assert_not_called()diff --git a/ee/tasks/quota_limiting.py b/ee/tasks/quota_limiting.pynew file mode 100644index 000000000000..35754530da40--- /dev/null+++ b/ee/tasks/quota_limiting.py@@ -0,0 +1,13 @@+from celery import shared_task++from ee.billing.quota_limiting import refresh_org_self_driving_quota+++@shared_task(ignore_result=True, max_retries=0)+def refresh_org_self_driving_quota_task(organization_id: str) -> None:+ """Event-driven self-driving quota re-evaluation for one org (see `refresh_org_self_driving_quota`).++ No retries: the 15-minute quota cron is the backstop for a failed refresh, and re-running a+ stale refresh later could briefly overwrite a fresher `todays_usage`.+ """+ refresh_org_self_driving_quota(organization_id)diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 8becaf5d7d2b..6767bd78afec 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -228,6 +228,7 @@ export const FEATURE_FLAGS = {SETTINGS_SESSIONS_V2_JOIN: 'settings-sessions-v2-join', // owner: @robbie-c #team-web-analyticsSETTINGS_WEB_ANALYTICS_PRE_AGGREGATED_TABLES: 'web-analytics-pre-aggregated-tables', // owner: @lricoy #team-web-analyticsSIGNALS_PR_REFUNDS: 'signals-pr-refunds', // owner: #team-self-driving, gates the inbox PR refund flow (also checked server-side)+ SELF_DRIVING_QUOTA_ENFORCEMENT: 'self-driving-quota-enforcement', // owner: #team-self-driving, gates self-driving PR-limit enforcement (also checked server-side)SLACK_APP_ASSISTANT: 'slack-app-assistant', // owner: @VojtechBartos #team-platform-featuresSLACK_APP_OAUTH: 'slack-app-oauth', // owner: @VojtechBartos #team-platform-featuresSLOPE_GRAPH_INSIGHT: 'slope-graph-insight', // owner: @pauldambra #team-product-analyticsdiff --git a/frontend/src/scenes/inbox/components/shell/InboxUsageWidget.tsx b/frontend/src/scenes/inbox/components/shell/InboxUsageWidget.tsxindex d58536e0b411..3ff86e0b2c21 100644--- a/frontend/src/scenes/inbox/components/shell/InboxUsageWidget.tsx+++ b/frontend/src/scenes/inbox/components/shell/InboxUsageWidget.tsx@@ -147,12 +147,17 @@ export function InboxUsageWidget(): JSX.Element | null {limitPrs,freePrs,status,+ quotaLimited,resetDate,spentUsd,percentage,} = useValues(inboxUsageLogic)const { openModal } = useActions(inboxUsageLogic)+ // The server-truth pause (quotaLimited) can lead the widget's own usage math (billing data+ // lags), so the raise-the-limit affordances escalate on either signal.+ const atLimit = status === 'limit' || quotaLimited+if (isLoading) {return <UsageCardSkeleton />}@@ -170,7 +175,7 @@ export function InboxUsageWidget(): JSX.Element | null {<LemonTag type="muted" size="small">Free plan</LemonTag>- ) : canAccessBilling && status !== 'limit' ? (+ ) : canAccessBilling && !atLimit ? (<buttontype="button"onClick={openModal}@@ -204,18 +209,23 @@ export function InboxUsageWidget(): JSX.Element | null {<span className="text-tertiary tabular-nums">Resets {resetDate.format('MMM D')}</span>)}</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.+ </span>+ )}{canAccessBilling ? (!isSubscribed ? (<UpgradeButton product={product} />) : (- status === 'limit' && (+ atLimit && (<LemonButton type="primary" size="small" fullWidth center onClick={openModal}>Increase limit</LemonButton>))) : (- (!isSubscribed || status === 'limit') && (+ (!isSubscribed || atLimit) && (<span className="text-xs text-muted">{isSubscribed? 'Contact an organization admin to raise the limit.'diff --git a/frontend/src/scenes/inbox/logics/inboxUsageLogic.test.ts b/frontend/src/scenes/inbox/logics/inboxUsageLogic.test.tsindex 1ce8bd4e1f38..e853619a30fd 100644--- a/frontend/src/scenes/inbox/logics/inboxUsageLogic.test.ts+++ b/frontend/src/scenes/inbox/logics/inboxUsageLogic.test.ts@@ -15,7 +15,8 @@ const CREDITS_PER_PR = 1500const mockUsageEndpoints = (currentUsage: number,- summary: Omit<SignalReportRefundSummaryResponseApi, 'credited_refund_count'>+ summary: Omit<SignalReportRefundSummaryResponseApi, 'credited_refund_count' | 'quota_limited'> &+ Partial<Pick<SignalReportRefundSummaryResponseApi, 'quota_limited'>>): void => {useMocks({get: {@@ -25,7 +26,7 @@ const mockUsageEndpoints = (],'/api/projects/:team_id/signals/reports/refund-summary/': () => [200,- { credited_refund_count: summary.credited_credits / CREDITS_PER_PR, ...summary },+ { credited_refund_count: summary.credited_credits / CREDITS_PER_PR, quota_limited: false, ...summary },],},})@@ -39,7 +40,8 @@ const setRefundsFlag = (): void => {const mountWithUsage = async (currentUsage: number,- summary: Omit<SignalReportRefundSummaryResponseApi, 'credited_refund_count'>+ summary: Omit<SignalReportRefundSummaryResponseApi, 'credited_refund_count' | 'quota_limited'> &+ Partial<Pick<SignalReportRefundSummaryResponseApi, 'quota_limited'>>): Promise<ReturnType<typeof inboxUsageLogic.build>> => {mockUsageEndpoints(currentUsage, summary)featureFlagLogic.mount()@@ -106,6 +108,20 @@ describe('inboxUsageLogic', () => {expect(logic.values.usedPrs).toBe(4)})+ // The enforcement flag and the refunds flag roll out independently; an enforcement-only org+ // still needs the summary loaded, or quota_limited never reaches the paused banner.+ it('loads the summary and surfaces quotaLimited with only the enforcement flag on', async () => {+ mockUsageEndpoints(1500, { period_billable_credits: 1500, credited_credits: 0, quota_limited: true })+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SELF_DRIVING_QUOTA_ENFORCEMENT], {+ [FEATURE_FLAGS.SELF_DRIVING_QUOTA_ENFORCEMENT]: true,+ })+ logic = inboxUsageLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadRefundSummarySuccess'])+ expect(logic.values.quotaLimited).toBe(true)+ })+// The org-keyed refunds flag resolves late on the client, so the client can fire the summary// request while the server (re-checking the same flag) still returns 404. That mismatch must// degrade to a null summary — falling back to billing's own usage — not bubble up as andiff --git a/frontend/src/scenes/inbox/logics/inboxUsageLogic.ts b/frontend/src/scenes/inbox/logics/inboxUsageLogic.tsindex 622e7169ac3d..5cef0c710cdc 100644--- a/frontend/src/scenes/inbox/logics/inboxUsageLogic.ts+++ b/frontend/src/scenes/inbox/logics/inboxUsageLogic.ts@@ -72,6 +72,8 @@ export interface inboxUsageLogicValues {percentage: numberpricePerPrUsd: number | nullproduct: BillingProductV2Type | null+ quotaEnforcementFlagEnabled: boolean+ quotaLimited: booleanrefundSummary: SignalReportRefundSummaryResponseApi | nullrefundSummaryLoading: booleanrefundsFlagEnabled: boolean@@ -79,6 +81,7 @@ export interface inboxUsageLogicValues {showLimitFormErrors: booleanspentUsd: number | nullstatus: InboxUsageStatus+ summaryFlagEnabled: booleanusedPrs: numberusedPrsDisplay: number}@@ -163,6 +166,8 @@ export interface inboxUsageLogicActions {export interface inboxUsageLogicMeta {__keaTypeGenInternalSelectorTypes: {refundsFlagEnabled: (featureFlags: FeatureFlagsSet) => boolean+ quotaEnforcementFlagEnabled: (featureFlags: FeatureFlagsSet) => boolean+ summaryFlagEnabled: (refundsFlagEnabled: boolean, quotaEnforcementFlagEnabled: boolean) => booleanproduct: (billing: BillingType | null) => BillingProductV2Type | nullisLoading: (billing: BillingType | null,@@ -170,7 +175,7 @@ export interface inboxUsageLogicMeta {product: BillingProductV2Type | null,refundSummary: SignalReportRefundSummaryResponseApi | null,refundSummaryLoading: boolean,- refundsFlagEnabled: boolean+ summaryFlagEnabled: boolean) => booleanisSubscribed: (product: BillingProductV2Type | null) => booleancreditsPerPr: (product: BillingProductV2Type | null) => number | null@@ -190,6 +195,7 @@ export interface inboxUsageLogicMeta {freePrs: number) => number | nullstatus: (usedPrs: number, limitPrs: number | null) => InboxUsageStatus+ quotaLimited: (refundSummary: SignalReportRefundSummaryResponseApi | null) => booleanusedPrsDisplay: (usedPrs: number, limitPrs: number | null) => numberspentUsd: (usedPrs: number, freePrs: number, pricePerPrUsd: number | null) => number | nullpercentage: (usedPrs: number, limitPrs: number | null, freePrs: number) => number@@ -245,7 +251,7 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([null as SignalReportRefundSummaryResponseApi | null,{loadRefundSummary: async (): Promise<SignalReportRefundSummaryResponseApi | null> => {- if (!values.featureFlags[FEATURE_FLAGS.SIGNALS_PR_REFUNDS] || values.currentTeamId == null) {+ if (!values.summaryFlagEnabled || values.currentTeamId == null) {return null}try {@@ -310,6 +316,19 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([(featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): boolean =>!!featureFlags[FEATURE_FLAGS.SIGNALS_PR_REFUNDS],],+ quotaEnforcementFlagEnabled: [+ (s) => [s.featureFlags],+ (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): boolean =>+ !!featureFlags[FEATURE_FLAGS.SELF_DRIVING_QUOTA_ENFORCEMENT],+ ],+ // The refund summary matters under either flag: refunds needs the netting numbers, quota+ // enforcement needs quota_limited for the paused banner. The flags roll out independently,+ // so gating the load on refunds alone would hide the paused state for enforcement-only orgs.+ summaryFlagEnabled: [+ (s) => [s.refundsFlagEnabled, s.quotaEnforcementFlagEnabled],+ (refundsFlagEnabled: boolean, quotaEnforcementFlagEnabled: boolean): boolean =>+ refundsFlagEnabled || quotaEnforcementFlagEnabled,+ ],product: [(s) => [s.billing],(billing: null | import('~/types').BillingType): BillingProductV2Type | null =>@@ -322,7 +341,7 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([s.product,s.refundSummary,s.refundSummaryLoading,- s.refundsFlagEnabled,+ s.summaryFlagEnabled,],(billing: null | import('~/types').BillingType,@@ -330,7 +349,7 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([product: BillingProductV2Type | null,refundSummary: SignalReportRefundSummaryResponseApi | null,refundSummaryLoading: boolean,- refundsFlagEnabled: boolean+ summaryFlagEnabled: boolean): boolean => {if (billing === null && billingLoading) {return true@@ -340,7 +359,7 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([// show yet. Once billing has rendered a count, a summary load kicked off by the// late-resolving org-keyed flag updates the number in place instead of tearing// the card down into a skeleton and back.- return !product && refundsFlagEnabled && refundSummary === null && refundSummaryLoading+ return !product && summaryFlagEnabled && refundSummary === null && refundSummaryLoading},],// Free plan can't raise the limit past the free allocation — the widget points to@@ -425,6 +444,13 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([return 'normal'},],+ // Server truth from the quota limiter: enforcement is actually pausing the pipeline,+ // as opposed to the widget's own usage math in `status`.+ quotaLimited: [+ (s) => [s.refundSummary],+ (refundSummary: SignalReportRefundSummaryResponseApi | null): boolean =>+ refundSummary?.quota_limited === true,+ ],// Displayed usage caps at the limit — we never show "53 / 50" when usage runs over.usedPrsDisplay: [(s) => [s.usedPrs, s.limitPrs],@@ -486,7 +512,7 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([// load alone silently skips the summary on pageloads where flags resolve late, leaving the// widget on billing's lagging recorded usage until something else re-triggers the loader.subscriptions(({ actions }) => ({- refundsFlagEnabled: (enabled: boolean) => {+ summaryFlagEnabled: (enabled: boolean) => {if (enabled) {actions.loadRefundSummary()}diff --git a/posthog/settings/celery.py b/posthog/settings/celery.pyindex fe1a67cbc1c7..5ca75c7cb678 100644--- a/posthog/settings/celery.py+++ b/posthog/settings/celery.py@@ -16,6 +16,7 @@ CELERY_DEFAULT_QUEUE = "celery"# List them here so Celery's import_default_modules() registers them deterministically# (worker + tests), independent of what else got imported.CELERY_IMPORTS: list[str] = [+ "ee.tasks.quota_limiting","posthog.api.oauth.cimd","posthog.caching.warming","posthog.email",diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex 95cdf69fe286..b04a806d209e 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -1699,6 +1699,20 @@ def get_signals_credited_refund_credits_for_org(return credited_refund_credits_for_org(organization_id, begin, end)+def get_self_driving_credits_used_in_period_for_org(+ organization_id: str | uuid.UUID, begin: datetime, end: datetime+) -> int:+ """Live self-driving credits used in `[begin, end)` across one org's teams.++ Input to the event-driven quota re-evaluation (`refresh_org_self_driving_quota`), which needs a+ fresher number than the cron-patched `todays_usage`. Re-exported from this posthog-layer+ module for the same boundary reason as the helper above.+ """+ return sum(+ credits for _, credits in get_signals_billing_credits_by_team(begin, end, organization_id=organization_id)+ )++@timed_log()@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)def get_teams_with_posthog_code_credits_used_in_period(diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex f2ee82d05e6b..454e33b34fd5 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -262,10 +262,12 @@ class TestSignalsProductModuleIntegrity:"match_signal_to_report_activity","mark_report_failed_activity","read_signals_from_s3_activity",+ "check_report_quota_gate_activity","mark_report_in_progress_activity","mark_report_pending_input_activity","mark_report_ready_activity","publish_report_completed_activity",+ "revert_report_to_candidate_activity","delete_team_reports_activity","get_grouping_paused_state_activity","pause_grouping_until_activity",diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex c62670ed3f5f..b79c2b858c68 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -150,6 +150,10 @@ Defined in `backend/temporal/summary.py`.**Flow:**+0. **Quota gate** → `check_report_quota_gate_activity` (`stage=summary_entry`; see Billing limit enforcement below).+ When it blocks, the workflow exits and the report stays `candidate`.+ The gate re-runs before repository selection (`pre_repo_selection`) and before agentic research (`pre_research`) — a block there reverts the report `in_progress → candidate` via `revert_report_to_candidate_activity` before exiting, so a promotion rule can pick it up again.+ All three sites are gated with `workflow.patched("self-driving-quota-gates")`.1. **Fetch signals** for the report from ClickHouse → `fetch_signals_for_report_activity`2. **Mark in-progress** in Postgres and advance `signals_at_run` by 3 → `mark_report_in_progress_activity`3. **Safety judge** → `report_safety_judge_activity`@@ -350,6 +354,7 @@ potential → candidate → in_progress → ready→ pending_input→ failed→ potential (reset by actionability judge)+ → candidate (mid-run quota pause; re-promotes on the next matching signal)# Re-promotion: READY reports are re-promoted to candidate on each new matching signal,# triggering a new summary run that reuses the previous repo selection and findings for@@ -963,6 +968,7 @@ All events use `distinct_id = team.uuid` and `groups(organization, team)`. Per-s- `signal_emitted` — `emit_signal()` after Temporal dispatch succeeds- `signal_assigned_to_report` — grouping assigned the signal (+ `report_id`, `is_new_report`, `promoted`)- `signal_report_reresearch_skipped` — signal hit an already-researched report past the re-research cap, so no new run spawned (+ `report_id`, `signal_count`, `status`, `threshold`). Fires per suppressed signal+- `signal_report_quota_paused` — a quota gate observed the team's org over its self-driving credits limit (+ `stage`: `promotion` | `summary_entry` | `pre_repo_selection` | `pre_research` | `autostart` | `manual_create` | `task_create` | `implementation_run`, `enforced`, `report_id`). See Billing limit enforcement- `signal_report_started` — report run began (+ `report_id`, `signal_count`, `run_count`, `source_products`)- `signals_repo_research_started` / `signals_repo_research_completed` — repo selection stage (+ `report_id`, `result`: `reused` | `selected` | `no_repo` | `failed`, optional `failure_reason`: `no_github_integration` | `agentic_activity_error`)- `signal_report_completed` — terminal per run (+ `result`: `ready` | `failed` | `pending_input` | `not_actionable`, optional `failure_reason`)@@ -1157,6 +1163,62 @@ Preserved: canonical scouts and the `authoring-scouts` companion, identified by---+## Billing limit enforcement++Self-driving bills a flat credit charge per report that ships an implementation PR (see `backend/billing.py`),+so a team whose org is over its `signals_credits` quota must stop generating new research and PRs — including flows already mid-pipeline.+The authority for "over quota" is the Redis quota-limiter flag (`ee.billing.quota_limiting`, resource `signals_credits`),+read through `quota.is_team_signals_quota_limited()` and bundled with the rollout flag by `quota.self_driving_quota_gate()`.+The quota is org-level (the org's billing cap): usage from every team in the org counts against one shared limit.+When the org crosses it, the quota cron fans the limited flag out to every team token in the org, so the per-team check reads an org-wide verdict and all of an org's teams pause together.++**Enforcement is feature-flag-gated for rollout** (`self-driving-quota-enforcement`, org-keyed).+Gates always run and emit telemetry when the team is limited;+they only block when the flag is on, so the would-block volume is measurable before enablement (`enforced=false` events are dark-launch rows).+Every check **fails open** — a Redis or flag-read error lets work through rather than stalling the fleet — and the bypass is alertable via `signals_quota_check_failed_open_total`.++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) |+| `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 |+| `autostart` | `maybe_autostart_implementation_task` (all callers) | No implementation task is created — the step that would lead to the billable PR |+| `manual_create` / `task_create` | tasks facade `create_task` / `create_and_run_task` | Creating a self-driving implementation task (e.g. "start work" from a report) returns 402 with a raise-the-limit message; `create_pr=False` sessions (research, repo selection) are exempt. `task_create` is the facade backstop behind auto-start, kept as its own stage so the manual path stays attributable |+| `implementation_run` | `enforce_self_driving_run_quota` (process-task workflow) | A PR-opening (`create_pr`) run that hasn't recorded its PR yet re-checks every 5 minutes and cancels itself through the standard cancellation path |++**The billable event re-evaluates the quota immediately.**+When a self-driving-origin run records its first PR URL (agent report, PATCH, or GitHub webhook backstop), the tasks facade queues `refresh_org_self_driving_quota` (Celery), which recomputes the org's live `signals_credits` usage and re-runs the Redis limiter — so the PR that crosses the limit flips the flag within seconds instead of at the next 15-minute quota cron tick.+The cron remains the backstop.+One timing edge: the live count is keyed to the implementation run's creation day (UTC), so a PR recorded just after midnight by a run created before midnight falls in the previous day's window and does not move the live counters.+It reaches enforcement hours later, via that day's usage report; the charge itself still lands in the correct day.++**A quota-cancelled run leaves only the report.**+`release_quota_cancelled_implementation` removes the run's `SignalReportTask` gate row and implementation `task_run` artefact (which would otherwise permanently block re-implementation) and appends a system `note` artefact explaining the stop.+Reports that already shipped a billable PR (through a sibling run of the same task) are skipped entirely: that gate row is billing's evidence for the charge, and deleting it would re-bill the report on its next implementation and break refund eligibility.+Runs that already recorded a PR URL are never cancelled: the report is already billed, so finishing the run and its CI follow-ups costs nothing more.+The release path is deliberately not hardened against a PR landing concurrently with the cancel (or an earlier run's PR on the same task): a PR that slips through ships un-billed.+Enforcement exists to stop runaway generation, not to guarantee billing capture, so under-billing errs in the customer's favor.+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.++**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.++**Resume is organic, never automatic.**+Nothing re-spawns paused work when the limit is raised or the billing period resets:+a `candidate` report re-promotes on its next matching signal (ingestion unmutes once the team is no longer limited),+and a `ready` report's implementation starts only when a later research cycle re-evaluates auto-start (or a user starts it manually).++**Telemetry:** every gate observation emits `signal_report_quota_paused` with `stage`, `enforced`, `report_id` (null at stages without one), `team_id`, and `organization_id`.+Promotion-stage events are emitted only when the signal would actually have promoted the report, so the volume measures withheld summary runs.++---+## Data Types (`backend/temporal/types.py`)| Type | Description |diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.pyindex ae287ee31e59..ee122663f8d8 100644--- a/products/signals/backend/auto_start.py+++ b/products/signals/backend/auto_start.py@@ -30,6 +30,7 @@ from products.signals.backend.models import (SignalTeamConfig,SignalUserAutonomyConfig,)+from products.signals.backend.quota import capture_signal_report_quota_paused, self_driving_quota_gatefrom products.signals.backend.report_generation.research import (ActionabilityAssessment,ActionabilityChoice,@@ -621,7 +622,7 @@ async def maybe_autostart_implementation_task(elif priority is None:skip_reason = "no priority assessment"if skip_reason is not None:- logger.info("signals auto-start skipped", report_id=report_id, team_id=team_id, reason=skip_reason)+ logger.info("self-driving auto-start skipped", report_id=report_id, team_id=team_id, reason=skip_reason)returnassert priority is not None # narrowed by the `priority is None` skip_reason guard above@@ -632,11 +633,31 @@ async def maybe_autostart_implementation_task(# fallback) may auto-start. Null (never set) leaves autostart on, so only False disables here.# Reports still generate and notify.logger.info(- "signals auto-start skipped", report_id=report_id, team_id=team_id, reason="autostart disabled for team"+ "self-driving auto-start skipped",+ report_id=report_id,+ team_id=team_id,+ reason="autostart disabled for team",)returnteam_default_priority = Priority(team_config.default_autostart_priority) if team_config else Priority.P4+ # Quota gate: the implementation task is the step that leads to the billable PR, so a team+ # whose org is over its self-driving credits quota starts none, on any path (pipeline, custom agent, scout, or+ # a user's reviewer edit). The report stays ready; the next new-signal research cycle after+ # the quota lifts re-evaluates auto-start.+ team = await Team.objects.select_related("organization").aget(pk=team_id)+ quota_gate = await database_sync_to_async(self_driving_quota_gate, thread_sensitive=False)(team)+ if quota_gate.limited:+ capture_signal_report_quota_paused(team, report_id=report_id, stage="autostart", enforced=quota_gate.enforced)+ if quota_gate.enforced:+ logger.info(+ "self-driving auto-start skipped",+ report_id=report_id,+ team_id=team_id,+ reason="org over self-driving credits quota",+ )+ return+# A user-triggered auto-start runs as the triggering user; otherwise resolve a trusted# (commit-authorship) reviewer. Either way the task's user is never an attacker-named colleague.if triggering_user_id is not None:@@ -654,7 +675,7 @@ async def maybe_autostart_implementation_task(task_user = await database_sync_to_async(_resolve_autostart_fallback_user, thread_sensitive=False)(team_id)if task_user is None:logger.info(- "signals auto-start skipped",+ "self-driving auto-start skipped",report_id=report_id,team_id=team_id,reason="no autostart runner: no reviewer met threshold, and no enabling member for a report at/above the team autostart priority",@@ -688,7 +709,7 @@ async def maybe_autostart_implementation_task()if not created:# Another evaluation won the race and already created the implementation task.- logger.info("signals auto-start skipped", report_id=report_id, team_id=team_id, reason="lost create race")+ logger.info("self-driving auto-start skipped", report_id=report_id, team_id=team_id, reason="lost create race")returndiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex fb2e933fef3a..f1918276daa3 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -304,6 +304,14 @@ class SignalReport(UUIDModel):self.run_count += 1updated_fields.update(["last_run_at", "signals_at_run", "run_count"])+ # A summary run paused mid-workflow by the self-driving credits quota gate returns to+ # CANDIDATE, so the report re-promotes on the next matching signal instead of sticking+ # in IN_PROGRESS (which no promotion rule ever picks up). No side effects: promoted_at+ # is still accurate, and run_count / signals_at_run keep the values the aborted run+ # advanced them to (run_count feeds Temporal workflow IDs and must never roll back).+ case (S.IN_PROGRESS, S.CANDIDATE):+ pass+case (S.IN_PROGRESS, S.READY):if title is None or summary is None:raise ValueError("title and summary are required for in_progress -> ready")diff --git a/products/signals/backend/quota.py b/products/signals/backend/quota.pyindex 8c7670c9624b..9fa53c873303 100644--- a/products/signals/backend/quota.py+++ b/products/signals/backend/quota.py@@ -4,17 +4,32 @@ Lives in its own module (not `billing.py`) to avoid a circular import: `billing.`posthog.tasks.usage_report`, which `ee.billing.quota_limiting` imports in turn."""+from dataclasses import dataclass+from typing import TYPE_CHECKING+import structlog+import posthoganalyticsfrom temporalio import activity+from posthog.event_usage import groupsfrom posthog.temporal.common.metrics import get_metric_meterfrom ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limited+if TYPE_CHECKING:+ from posthog.models import Team+logger = structlog.get_logger(__name__)+# Enforcement kill switch for the pipeline quota gates (promotion, summary stages, auto-start).+# While the flag is off the gates still run and emit `signal_report_quota_paused` telemetry with+# `enforced=false`, but never block, so the would-block volume is measurable before rollout.+SELF_DRIVING_QUOTA_ENFORCEMENT_FLAG = "self-driving-quota-enforcement"-def _record_failed_open() -> None:++def record_quota_check_failed_open() -> None:+ """Count a self-driving quota check that errored and failed open (no-op outside a Temporal+ activity). Shared by every gate whose fail-open must stay alertable."""# Emit the meter directly rather than via products.signals.backend.temporal.metrics: importing# that package runs its __init__, which imports buffer.py, which imports this module (cycle).if not activity.in_activity():@@ -38,5 +53,79 @@ def is_team_signals_quota_limited(team_api_token: str) -> bool:)except Exception:logger.warning("signals_quota_check_failed_open", exc_info=True)- _record_failed_open()+ record_quota_check_failed_open()+ return False+++@dataclass(frozen=True)+class SelfDrivingQuotaGate:+ """One pipeline gate decision: `limited` is the raw quota state (for telemetry), `enforced`+ is whether the gate should actually block (limited AND the enforcement flag is on)."""++ limited: bool+ enforced: bool+++def self_driving_quota_enforcement_enabled(team: "Team") -> bool:+ """Whether quota-gate enforcement is rolled out to this team's org.++ Org-keyed like the `signals-pr-refunds` gate (the limit is the org's billing cap). Fails open+ (no enforcement) on a flag-read error, matching the quota check's own fail-open policy: a flag+ outage must not stall the fleet's pipelines. Also gates visibility of the refund-summary+ endpoint (the widget's source for the paused state), which must work with refunds off.+ """+ try:+ org_id = str(team.organization_id)+ return (+ posthoganalytics.feature_enabled(+ SELF_DRIVING_QUOTA_ENFORCEMENT_FLAG,+ org_id,+ groups={"organization": org_id},+ group_properties={"organization": {"id": org_id}},+ )+ is True+ )+ except Exception:+ logger.warning("self_driving_quota_enforcement_flag_check_failed", exc_info=True)return False+++def self_driving_quota_gate(team: "Team") -> SelfDrivingQuotaGate:+ """Resolve the quota gate for one team: is it quota-limited, and is enforcement on.++ The limit itself is org-level (the org's billing cap): the quota cron sums usage across all+ of the org's teams and, when the org crosses its limit, writes every one of the org's team+ tokens into the Redis limited set. This per-team check therefore reads an org-wide verdict,+ and all teams in an org pause together.++ The enforcement flag is only read when the team is actually limited, so the fleet-wide hot+ paths pay a single cached Redis read. Blocking network I/O; wrap in `sync_to_async` from+ async code.+ """+ if not is_team_signals_quota_limited(team.api_token):+ return SelfDrivingQuotaGate(limited=False, enforced=False)+ return SelfDrivingQuotaGate(limited=True, enforced=self_driving_quota_enforcement_enabled(team))+++def capture_signal_report_quota_paused(team: "Team", *, report_id: str | None, stage: str, enforced: bool) -> None:+ """`signal_report_quota_paused`: a pipeline gate observed the team's org over its self-driving+ credits quota at `stage`. `enforced=false` rows are dark-launch would-blocks. Best-effort: telemetry+ must never fail the pipeline step that emitted it. Requires `team.organization` to be loaded.+ """+ try:+ posthoganalytics.capture(+ event="signal_report_quota_paused",+ distinct_id=str(team.uuid),+ properties={+ "team_id": team.id,+ "organization_id": str(team.organization_id),+ "report_id": report_id,+ "stage": stage,+ "enforced": enforced,+ },+ groups=groups(team.organization, team),+ )+ except Exception:+ logger.exception(+ "Failed to capture signal_report_quota_paused", report_id=report_id, team_id=team.id, stage=stage+ )diff --git a/products/signals/backend/task_run_artefacts.py b/products/signals/backend/task_run_artefacts.pyindex 5930553a0cef..c9b734ba2463 100644--- a/products/signals/backend/task_run_artefacts.py+++ b/products/signals/backend/task_run_artefacts.py@@ -13,15 +13,20 @@ purpose is *derived* — there is no relationship label on the task↔report assfrom __future__ import annotations+import json++from django.db import transaction+from products.signals.backend.artefact_schemas import (SIGNALS_PRODUCT,TASK_RUN_TYPE_DISCUSSION,TASK_RUN_TYPE_IMPLEMENTATION,TASK_RUN_TYPE_REPO_SELECTION,TASK_RUN_TYPE_RESEARCH,+ NoteArtefact,TaskRunArtefact,)-from products.signals.backend.billing import mark_report_billing_exempt+from products.signals.backend.billing import first_billable_pr_run_at, mark_report_billing_exemptfrom products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact, SignalReportTask# The task-run vocabulary lives in `artefact_schemas` (a leaf module the model layer can import@@ -37,6 +42,7 @@ __all__ = ["append_task_run_artefact","record_implementation_task","record_report_task",+ "release_quota_cancelled_implementation","signals_task_ids",]@@ -155,3 +161,70 @@ def record_report_task(task_id=task_id,run_id=run_id,)+++def release_quota_cancelled_implementation(*, team_id: int, task_id: str) -> list[str]:+ """Remove a quota-cancelled implementation's auto-start records so its report can be+ implemented again by a later cycle.++ A run the quota gate cancels mid-flight never shipped its PR, but its `SignalReportTask` gate+ row and implementation `task_run` artefact would keep `associated_task_runs` reporting a+ started implementation and permanently block re-implementation. Deleting both restores the+ report to "never implemented"; a system `note` artefact records for the report timeline why+ the run stopped. Locks each report row (the same lock auto-start creation takes) so the+ removal serializes with a concurrent auto-start evaluation. Returns the affected report ids+ (empty when the task has no implementation link).++ Reports that already shipped a billable PR are skipped entirely: the cancel decision is+ run-scoped but this delete is task-scoped, and a sibling run of the same task may have+ shipped the PR that billed the report. Its `SignalReportTask` row is billing's evidence —+ the `billed_earlier` dedup and refund eligibility both resolve through it — so deleting it+ would re-bill the report on its next implementation and strand the paid charge unrefundable.+ """+ report_ids = list(+ SignalReportTask.objects.filter(+ team_id=team_id, task_id=task_id, relationship=TASK_RUN_TYPE_IMPLEMENTATION+ ).values_list("report_id", flat=True)+ )+ released: list[str] = []+ for report_id in report_ids:+ with transaction.atomic():+ report = SignalReport.objects.select_for_update().filter(id=report_id, team_id=team_id).first()+ if report is None:+ continue+ if first_billable_pr_run_at(report_id) is not None:+ # A sibling run already shipped this report's billable PR. These records are+ # billing's evidence for that charge — deleting them would double-bill the next+ # implementation — and the report needs no release: it *is* implemented.+ continue+ SignalReportTask.objects.filter(+ team_id=team_id,+ report_id=report_id,+ task_id=task_id,+ relationship=TASK_RUN_TYPE_IMPLEMENTATION,+ ).delete()+ for artefact in SignalReportArtefact.objects.filter(+ team_id=team_id,+ report_id=report_id,+ task_id=task_id,+ type=SignalReportArtefact.ArtefactType.TASK_RUN,+ ):+ try:+ content = json.loads(artefact.content)+ except (TypeError, ValueError):+ continue+ if content.get("product") == SIGNALS_PRODUCT and content.get("type") == TASK_RUN_TYPE_IMPLEMENTATION:+ artefact.delete()+ SignalReportArtefact.add_log(+ team_id=team_id,+ report_id=str(report_id),+ content=NoteArtefact(+ note=(+ "Implementation run stopped: the organization reached its self-driving pull request "+ "limit. A new run can start after the limit is raised or the billing period resets."+ )+ ),+ attribution=ArtefactAttribution.system(),+ )+ released.append(str(report_id))+ return releaseddiff --git a/products/signals/backend/temporal/__init__.py b/products/signals/backend/temporal/__init__.pyindex aea8b8aa13a6..5d297ee92e59 100644--- a/products/signals/backend/temporal/__init__.py+++ b/products/signals/backend/temporal/__init__.py@@ -63,6 +63,7 @@ from products.signals.backend.temporal.signal_queries import ()from products.signals.backend.temporal.summary import (SignalReportSummaryWorkflow,+ check_report_quota_gate_activity,dispatch_inbox_slack_notifications_activity,mark_report_failed_activity,mark_report_in_progress_activity,@@ -70,6 +71,7 @@ from products.signals.backend.temporal.summary import (mark_report_ready_activity,publish_report_completed_activity,reset_report_to_potential_activity,+ revert_report_to_candidate_activity,)WORKFLOWS = [@@ -113,10 +115,12 @@ ACTIVITIES = [match_signal_to_report_activity,mark_report_failed_activity,read_signals_from_s3_activity,+ check_report_quota_gate_activity,mark_report_in_progress_activity,mark_report_pending_input_activity,mark_report_ready_activity,publish_report_completed_activity,+ revert_report_to_candidate_activity,delete_team_reports_activity,get_grouping_paused_state_activity,pause_grouping_until_activity,diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.pyindex ee629a606f3b..8dede15c5f76 100644--- a/products/signals/backend/temporal/grouping.py+++ b/products/signals/backend/temporal/grouping.py@@ -33,6 +33,7 @@ from products.signals.backend.artefact_attribution import ArtefactAttributionfrom products.signals.backend.artefact_schemas import RelatedTofrom products.signals.backend.billing import BILLING_EXEMPT_SOURCE_PRODUCTSfrom products.signals.backend.models import SignalReport, SignalReportArtefact+from products.signals.backend.quota import capture_signal_report_quota_paused, self_driving_quota_gatefrom products.signals.backend.signal_metadata import EMBEDDING_MODELfrom products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.drop_telemetry import capture_signal_dropped@@ -690,6 +691,7 @@ class AssignAndEmitDbResult:reresearch_capped: boolreport_status: strreport_signal_count: int+ promotion_suppressed: bool@temporalio.activity.defn@@ -698,9 +700,10 @@ class AssignAndEmitDbResult:async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> AssignAndEmitSignalOutput:match_result = input.match_result- def do_assign_and_emit() -> AssignAndEmitDbResult:+ def do_assign_and_emit(suppress_promotion: bool) -> AssignAndEmitDbResult:with transaction.atomic():promoted = False+ promotion_suppressed = Falseif isinstance(match_result, ExistingReportMatch):report = SignalReport.objects.select_for_update().get(id=match_result.report_id, team_id=input.team_id)@@ -748,6 +751,7 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Asreresearch_capped=False,report_status=report.status,report_signal_count=report.signal_count,+ promotion_suppressed=False,)# Resolved reports are terminal — never reopen them. When a signal would have grouped# into an already-resolved report, the issue it fixed has recurred (or a related one@@ -813,12 +817,20 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Asand report.signal_count >= report.signals_at_run)):+ if suppress_promotion:+ # The team's org is over its self-driving credits quota with enforcement on: the signal is still+ # assigned, weighted, and emitted, but no summary run spawns. The status is left+ # untouched, so the first matching signal after the quota lifts re-evaluates+ # promotion under the same rules.+ promotion_suppressed = True# If candidate got here - it usually means CH issue down the way# (e.g. CH wait raised before start_child_workflow)- if report.status != SignalReport.Status.CANDIDATE:+ elif report.status != SignalReport.Status.CANDIDATE:updated_fields = report.transition_to(SignalReport.Status.CANDIDATE)report.save(update_fields=updated_fields)- promoted = True+ promoted = True+ else:+ promoted = Truereport_id = str(report.id)@@ -856,12 +868,16 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Asreresearch_capped=reresearch_capped,report_status=report.status,report_signal_count=report.signal_count,+ promotion_suppressed=promotion_suppressed,)try:- db_result = await database_sync_to_async(do_assign_and_emit, thread_sensitive=False)()-team = await Team.objects.select_related("organization").aget(pk=input.team_id)+ # Resolved before the assign transaction: the quota gate is Redis + flag network I/O that+ # must not run while holding the report row lock.+ quota_gate = await database_sync_to_async(self_driving_quota_gate, thread_sensitive=False)(team)++ db_result = await database_sync_to_async(do_assign_and_emit, thread_sensitive=False)(quota_gate.enforced)# If we matched a deleted report, soft-delete all its stale signals in ClickHouse.# This prevents data corruption where non-deleted signals for a deleted report@@ -949,6 +965,12 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Asteam_id=input.team_id,source_id=input.source_id,)+ # Emitted only when the signal would have promoted the report, so the event volume+ # measures withheld summary runs rather than every assignment on a limited team.+ if quota_gate.limited and (db_result.promoted or db_result.promotion_suppressed):+ capture_signal_report_quota_paused(+ team, report_id=db_result.report_id, stage="promotion", enforced=quota_gate.enforced+ )if not db_result.matched_deleted_report:metrics.increment_funnel(metrics.FUNNEL_STAGE_GROUPED, input.source_product)diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.pyindex ab41145fac29..81c6c0329460 100644--- a/products/signals/backend/temporal/summary.py+++ b/products/signals/backend/temporal/summary.py@@ -26,6 +26,11 @@ from posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connectionsfrom products.signals.backend.models import SignalReport+from products.signals.backend.quota import (+ capture_signal_report_quota_paused,+ record_quota_check_failed_open,+ self_driving_quota_gate,+)from products.signals.backend.report_generation.research import ActionabilityChoicefrom products.signals.backend.report_generation.select_repo import RepoSelectionResultfrom products.signals.backend.temporal import metrics@@ -167,8 +172,33 @@ class SignalReportSummaryWorkflow:max_iterations=max_iterations,)+ async def _quota_gate_pauses(self, inputs: SignalReportSummaryWorkflowInputs, stage: str) -> bool:+ return await workflow.execute_activity(+ check_report_quota_gate_activity,+ CheckReportQuotaGateInput(team_id=inputs.team_id, report_id=inputs.report_id, stage=stage),+ start_to_close_timeout=timedelta(minutes=1),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )++ async def _revert_report_to_candidate(self, inputs: SignalReportSummaryWorkflowInputs) -> None:+ await workflow.execute_activity(+ revert_report_to_candidate_activity,+ RevertReportToCandidateInput(team_id=inputs.team_id, report_id=inputs.report_id),+ start_to_close_timeout=timedelta(minutes=1),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+async def _run_once(self, inputs: SignalReportSummaryWorkflowInputs, log: FilteringBoundLogger) -> bool:"""Run a single report generation cycle. Returns True if new signals arrived and another cycle is needed."""+ # 0. Quota gate: a team whose org is over its self-driving credits quota gets no new research or PRs. The+ # report stays candidate and re-promotes on the first matching signal after the quota+ # lifts. patched(): executions recorded before the gate existed replay the old command+ # sequence (see also the two mid-run gates below, same patch id).+ if workflow.patched("self-driving-quota-gates") and await self._quota_gate_pauses(+ inputs, stage="summary_entry"+ ):+ log.info("Report run paused: org over self-driving credits quota", stage="summary_entry")+ return False# 1. Fetch signals for the reportfetch_result: FetchSignalsForReportOutput = await workflow.execute_activity(fetch_signals_for_report_activity,@@ -237,6 +267,16 @@ class SignalReportSummaryWorkflow:)# No loop, as report is unsafereturn False+ # Quota re-check before each sandbox-heavy step: the team can cross its limit while+ # this workflow is between activities (e.g. a parallel report's PR landed). The report+ # is in_progress here, so a pause must revert it to candidate rather than just exit,+ # or no promotion rule would ever pick it up again.+ if workflow.patched("self-driving-quota-gates") and await self._quota_gate_pauses(+ inputs, stage="pre_repo_selection"+ ):+ log.info("Report run paused: org over self-driving credits quota", stage="pre_repo_selection")+ await self._revert_report_to_candidate(inputs)+ return False# 4. Select repository for the agentic researchrepo_result: RepoSelectionResult = await workflow.execute_activity(select_repository_activity,@@ -265,6 +305,12 @@ class SignalReportSummaryWorkflow:pending_reason="repo_selection_required",)else:+ if workflow.patched("self-driving-quota-gates") and await self._quota_gate_pauses(+ inputs, stage="pre_research"+ ):+ log.info("Report run paused: org over self-driving credits quota", stage="pre_research")+ await self._revert_report_to_candidate(inputs)+ return False# 5. Run the agentic report research flow with the selected repository to use code/MCP data to assess signalsagentic_result: RunAgenticReportOutput = await workflow.execute_activity(run_agentic_report_activity,@@ -415,6 +461,71 @@ class SignalReportSummaryWorkflow:raise+@dataclass+class CheckReportQuotaGateInput:+ team_id: int+ report_id: str+ stage: str+++@scoped_temporal()+@close_db_connections+async def check_report_quota_gate_activity(input: CheckReportQuotaGateInput) -> bool:+ """Whether the summary workflow must pause at `stage`: the team's org is over its self-driving+ credits quota and enforcement is on. Emits `signal_report_quota_paused` whenever the team is limited,+ enforced or not, so the dark-launch would-block volume is measurable. Never raises: any+ failure resolves to False (run proceeds), matching the quota module's fail-open policy.+ """+ try:+ team = await Team.objects.select_related("organization").aget(pk=input.team_id)+ gate = await database_sync_to_async(self_driving_quota_gate, thread_sensitive=False)(team)+ if gate.limited:+ capture_signal_report_quota_paused(+ team, report_id=input.report_id, stage=input.stage, enforced=gate.enforced+ )+ return gate.enforced+ except Exception:+ record_quota_check_failed_open()+ logger.exception(+ "Self-driving quota gate check failed open",+ report_id=input.report_id,+ team_id=input.team_id,+ stage=input.stage,+ )+ return False+++@dataclass+class RevertReportToCandidateInput:+ team_id: int+ report_id: str+++@scoped_temporal()+@close_db_connections+async def revert_report_to_candidate_activity(input: RevertReportToCandidateInput) -> None:+ """Return a report paused mid-run by the quota gate from in_progress to candidate, so the next+ matching signal re-promotes it (no promotion rule ever picks up an in_progress report).+ """++ @transaction.atomic+ def do_update() -> None:+ report = SignalReport.objects.select_for_update().get(id=input.report_id, team_id=input.team_id)+ if report.status != SignalReport.Status.IN_PROGRESS:+ return+ updated_fields = report.transition_to(SignalReport.Status.CANDIDATE)+ report.save(update_fields=updated_fields)++ await database_sync_to_async(do_update, thread_sensitive=False)()+ logger.info(+ "Reverted quota-paused report to candidate",+ report_id=input.report_id,+ team_id=input.team_id,+ )++@dataclassclass MarkReportInProgressInput:team_id: intdiff --git a/products/signals/backend/test/test_assign_and_emit_signal.py b/products/signals/backend/test/test_assign_and_emit_signal.pyindex a19804b948cb..3ef5d0d811ed 100644--- a/products/signals/backend/test/test_assign_and_emit_signal.py+++ b/products/signals/backend/test/test_assign_and_emit_signal.py@@ -15,6 +15,7 @@ from posthog.sync import database_sync_to_asyncfrom products.signals.backend.artefact_schemas import RelatedTofrom products.signals.backend.models import SignalReport, SignalReportArtefact+from products.signals.backend.quota import SelfDrivingQuotaGatefrom products.signals.backend.temporal.grouping import (WEIGHT_THRESHOLD,AssignAndEmitSignalInput,@@ -642,3 +643,60 @@ async def test_deleted_report_emits_matched_deleted_telemetry(ateam, patch_side_assert properties["report_id"] == str(report.id)assert properties["source_id"] == input_.source_idassert properties["source_product"] == "conversations"+++# ---------------------------------------------------------------------------+# Quota gate: promotion withheld for enforced over-quota teams+# ---------------------------------------------------------------------------+++ ("enforced", "expected_status", "expected_promoted"),+ [+ # Enforced over-quota team: the signal is assigned and weighted, but no summary run spawns+ # and the status is untouched so the first post-quota signal re-evaluates promotion.+ (True, SignalReport.Status.POTENTIAL, False),+ # Dark launch (limited, enforcement flag off): behavior unchanged, telemetry only.+ (False, SignalReport.Status.CANDIDATE, True),+ ],+)+async def test_quota_gate_withholds_promotion_only_when_enforced(+ ateam, patch_side_effects, enforced, expected_status, expected_promoted+):+ with patch(+ f"{GROUPING_MODULE_PATH}.self_driving_quota_gate",+ return_value=SelfDrivingQuotaGate(limited=True, enforced=enforced),+ ):+ result = await assign_and_emit_signal_activity(_build_input(ateam.id, _new_match(), weight=WEIGHT_THRESHOLD))++ assert result.promoted is expected_promoted+ report = await database_sync_to_async(SignalReport.objects.get)(id=result.report_id)+ assert report.status == expected_status+ assert report.signal_count == 1+ assert report.total_weight == pytest.approx(WEIGHT_THRESHOLD)++ quota_events = [+ call+ for call in patch_side_effects["capture"].call_args_list+ if call.kwargs.get("event") == "signal_report_quota_paused"+ ]+ assert len(quota_events) == 1+ assert quota_events[0].kwargs["properties"]["stage"] == "promotion"+ assert quota_events[0].kwargs["properties"]["enforced"] is enforced+++async def test_quota_gate_emits_no_event_when_signal_would_not_promote(ateam, patch_side_effects):+ """A limited team's below-threshold signal must not emit quota telemetry: the event volume+ measures withheld summary runs, not every assignment on a limited team."""+ with patch(+ f"{GROUPING_MODULE_PATH}.self_driving_quota_gate",+ return_value=SelfDrivingQuotaGate(limited=True, enforced=True),+ ):+ await assign_and_emit_signal_activity(_build_input(ateam.id, _new_match(), weight=WEIGHT_THRESHOLD * 0.5))++ events = [call.kwargs.get("event") for call in patch_side_effects["capture"].call_args_list]+ assert "signal_report_quota_paused" not in eventsdiff --git a/products/signals/backend/test/test_auto_start.py b/products/signals/backend/test/test_auto_start.pyindex 89ae2dba6f79..14187162d7a3 100644--- a/products/signals/backend/test/test_auto_start.py+++ b/products/signals/backend/test/test_auto_start.py@@ -34,6 +34,7 @@ from products.signals.backend.models import (SignalTeamConfig,SignalUserAutonomyConfig,)+from products.signals.backend.quota import SelfDrivingQuotaGatefrom products.signals.backend.report_generation.research import (ActionabilityAssessment,ActionabilityChoice,@@ -637,3 +638,64 @@ def test_autostart_description_appends_fix_loop_instructions_only_for_metric_rep# Evidence-hygiene guardrail: fix-loop PRs may target public repos, so the prompt must forbid# real telemetry (raw rows, error messages, identifiers) in before/after evidence.assert ("never raw telemetry rows" in description) is expect_fix_loop++[email protected]_db(transaction=True)[email protected]("enforced", [True, False])+async def test_quota_gate_blocks_autostart_only_when_enforced(enforced):+ # The implementation task is the step that leads to the billable PR: an enforced over-quota+ # team must start none, while dark launch (limited, flag off) must leave auto-start untouched.+ # Committed rows for the same reason as the autostart-switch test above.+ Task = apps.get_model("tasks", "Task")+ TaskRun = apps.get_model("tasks", "TaskRun")++ def _setup() -> tuple[Team, SignalReport]:+ organization = Organization.objects.create(name="quota-org")+ team = Team.objects.create(organization=organization, name="quota-team")+ enabler = User.objects.create(email="[email protected]")+ OrganizationMembership.objects.create(user=enabler, organization=organization)+ SignalSourceConfig.objects.create(+ team=team, source_product="error_tracking", source_type="issue_created", created_by=enabler+ )+ report = SignalReport.objects.create(+ team=team, status=SignalReport.Status.READY, title="t", summary="s", signal_count=0, total_weight=0.0+ )+ return team, report++ team, report = await sync_to_async(_setup)()++ def _fake_create_and_run_task(**kwargs):+ task = Task.objects.create(+ team_id=team.id,+ title=kwargs["title"],+ description=kwargs["description"],+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ )+ run = TaskRun.objects.create(task=task, team_id=team.id)+ return SimpleNamespace(task_id=task.id, team_id=team.id, latest_run=SimpleNamespace(id=run.id))++ with (+ patch.object(tasks_facade, "create_and_run_task", side_effect=_fake_create_and_run_task) as mock_create,+ patch("products.signals.backend.auto_start.resolve_agent_runtime", return_value=AgentRuntime()),+ patch(+ "products.signals.backend.auto_start.self_driving_quota_gate",+ return_value=SelfDrivingQuotaGate(limited=True, enforced=enforced),+ ),+ ):+ await maybe_autostart_implementation_task(+ team_id=team.id,+ report_id=str(report.id),+ repository="owner/repo",+ title="t",+ summary="s",+ actionability=ActionabilityAssessment(+ explanation="Clear fix in the affected module.",+ actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE,+ already_addressed=False,+ ),+ reviewers_content=[],+ priority=PriorityAssessment(explanation="Affects many sessions.", priority=Priority.P2),+ )++ assert (mock_create.call_count == 0) is enforceddiff --git a/products/signals/backend/test/test_quota.py b/products/signals/backend/test/test_quota.pyindex 7fa88484cfb8..88d07601907a 100644--- a/products/signals/backend/test/test_quota.py+++ b/products/signals/backend/test/test_quota.py@@ -1,7 +1,18 @@+from types import SimpleNamespace+from typing import TYPE_CHECKING, cast+import pytestfrom unittest.mock import patch-from products.signals.backend.quota import is_team_signals_quota_limited+from products.signals.backend.quota import SelfDrivingQuotaGate, is_team_signals_quota_limited, self_driving_quota_gate++if TYPE_CHECKING:+ from posthog.models import Team+++def _team() -> "Team":+ # The gate only reads api_token / organization_id, so a stub keeps these tests DB-free.+ return cast("Team", SimpleNamespace(api_token="phc_token", organization_id="0195a000-0000-0000-0000-000000000000"))@pytest.mark.parametrize(@@ -31,3 +42,35 @@ def test_fail_open_metric_noops_outside_activity():with patch("products.signals.backend.quota.get_metric_meter") as mock_meter:assert is_team_signals_quota_limited("phc_token") is Falsemock_meter.assert_not_called()+++ ("limited", "flag_on", "expected_enforced"),+ [+ (False, True, False),+ (True, True, True),+ # Dark launch: a limited team with the enforcement flag off must never be blocked.+ (True, False, False),+ ],+)+def test_self_driving_quota_gate_enforces_only_when_limited_and_flag_on(limited, flag_on, expected_enforced):+ with (+ patch("products.signals.backend.quota.is_team_limited", return_value=limited),+ patch("products.signals.backend.quota.posthoganalytics.feature_enabled", return_value=flag_on) as flag_mock,+ ):+ assert self_driving_quota_gate(_team()) == SelfDrivingQuotaGate(limited=limited, enforced=expected_enforced)+ if not limited:+ # The flag is network I/O and must stay off the fleet-wide not-limited hot path.+ flag_mock.assert_not_called()+++def test_self_driving_quota_gate_fails_open_on_flag_error():+ # A flag-service outage must not start blocking pipelines: limited stays visible, enforcement off.+ with (+ patch("products.signals.backend.quota.is_team_limited", return_value=True),+ patch(+ "products.signals.backend.quota.posthoganalytics.feature_enabled",+ side_effect=RuntimeError("flags down"),+ ),+ ):+ assert self_driving_quota_gate(_team()) == SelfDrivingQuotaGate(limited=True, enforced=False)diff --git a/products/signals/backend/test/test_refunds.py b/products/signals/backend/test/test_refunds.pyindex 2e5b56ddae2b..d746dfa636e0 100644--- a/products/signals/backend/test/test_refunds.py+++ b/products/signals/backend/test/test_refunds.py@@ -20,6 +20,7 @@ from posthog.models import Organization, Teamfrom products.signals.backend.billing import SIGNALS_CREDITS_PER_REPORT_WITH_PRfrom products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportRefund+from products.signals.backend.quota import SELF_DRIVING_QUOTA_ENFORCEMENT_FLAGfrom products.signals.backend.tasks import (_OUT_OF_PERIOD_SYNC_ERROR,_REFUND_SYNC_MAX_RETRIES,@@ -484,6 +485,7 @@ class TestSignalReportRefundAPI(APIBaseTest):"credited_refund_count": 2,"credited_credits": 3000,"period_billable_credits": 1500,+ "quota_limited": False,}@freeze_time(_NOW)@@ -497,8 +499,36 @@ class TestSignalReportRefundAPI(APIBaseTest):assert self._refund(report).json()["billing_path"] == "excluded"assert self.client.get(url).json()["period_billable_credits"] == 0+ @freeze_time(_NOW)+ def test_refund_summary_reports_quota_limited_from_the_gate(self, _flag):+ # The widget's "agents are paused" banner keys off this field, so it must reflect the+ # same gate the pipeline enforces, not the widget's own usage math.+ from products.signals.backend.quota import SelfDrivingQuotaGate++ url = f"/api/projects/{self.team.id}/signals/reports/refund-summary/"+ with patch(+ "products.signals.backend.views.self_driving_quota_gate",+ return_value=SelfDrivingQuotaGate(limited=True, enforced=True),+ ):+ assert self.client.get(url).json()["quota_limited"] is True+class TestSignalReportRefundFlagGate(APIBaseTest):+ @patch("posthoganalytics.feature_enabled")+ def test_refund_summary_available_with_only_enforcement_flag(self, flag_mock):+ # The two flags roll out independently; an enforcement-only org still needs quota_limited+ # from this endpoint, or the widget's paused banner can never render.+ flag_mock.side_effect = lambda key, *args, **kwargs: key == SELF_DRIVING_QUOTA_ENFORCEMENT_FLAG+ summary = self.client.get(f"/api/projects/{self.team.id}/signals/reports/refund-summary/")+ assert summary.status_code == status.HTTP_200_OK+ assert summary.json()["quota_limited"] is False+ # The refund action itself stays refunds-gated.+ report = _make_report(self.team)+ refund = self.client.post(+ f"/api/projects/{self.team.id}/signals/reports/{report.id}/refund/", {"reason": "other"}, format="json"+ )+ assert refund.status_code == status.HTTP_404_NOT_FOUND+@parameterized.expand([("refund",), ("refund_summary",)])@patch("posthoganalytics.feature_enabled", return_value=False)def test_endpoints_unavailable_with_flag_off(self, action_path, _flag):diff --git a/products/signals/backend/test/test_summary_quota_gate.py b/products/signals/backend/test/test_summary_quota_gate.pynew file mode 100644index 000000000000..903f81a7f13e--- /dev/null+++ b/products/signals/backend/test/test_summary_quota_gate.py@@ -0,0 +1,286 @@+import uuid+import random+import asyncio+from datetime import UTC, datetime++import pytest+from unittest.mock import patch++import pytest_asyncio+from asgiref.sync import sync_to_async+from temporalio import activity+from temporalio.contrib.pydantic import pydantic_data_converter+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from posthog.models import Organization, Team+from posthog.sync import database_sync_to_async++from products.signals.backend.models import SignalReport+from products.signals.backend.quota import SelfDrivingQuotaGate+from products.signals.backend.report_generation.research import ActionabilityChoice+from products.signals.backend.report_generation.select_repo import RepoSelectionResult+from products.signals.backend.temporal.agentic.report import RunAgenticReportInput, RunAgenticReportOutput+from products.signals.backend.temporal.agentic.select_repository import SelectRepositoryInput+from products.signals.backend.temporal.report_safety_judge import SafetyJudgeInput, SafetyJudgeOutput+from products.signals.backend.temporal.signal_queries import FetchSignalsForReportInput, FetchSignalsForReportOutput+from products.signals.backend.temporal.summary import (+ CheckReportQuotaGateInput,+ MarkReportFailedInput,+ MarkReportInProgressInput,+ ResetReportToPotentialInput,+ RevertReportToCandidateInput,+ SignalReportSummaryWorkflow,+ check_report_quota_gate_activity,+ revert_report_to_candidate_activity,+)+from products.signals.backend.temporal.types import SignalData, SignalReportSummaryWorkflowInputs++SUMMARY_MODULE_PATH = "products.signals.backend.temporal.summary"+TASK_QUEUE = "test-summary-quota-queue"+++@pytest_asyncio.fixture+async def aorganization():+ organization = await sync_to_async(Organization.objects.create)(+ name=f"SelfDrivingSummaryQuotaOrg-{random.randint(1, 99999)}",+ )+ yield organization+ await sync_to_async(organization.delete)()+++@pytest_asyncio.fixture+async def ateam(aorganization):+ team = await sync_to_async(Team.objects.create)(+ organization=aorganization,+ name=f"SelfDrivingSummaryQuotaTeam-{random.randint(1, 99999)}",+ )+ yield team+ await sync_to_async(team.delete)()+++# ---------------------------------------------------------------------------+# check_report_quota_gate_activity+# ---------------------------------------------------------------------------++[email protected]("enforced", [True, False])+async def test_check_activity_returns_enforced(ateam, enforced):+ with (+ patch(+ f"{SUMMARY_MODULE_PATH}.self_driving_quota_gate",+ return_value=SelfDrivingQuotaGate(limited=True, enforced=enforced),+ ),+ patch("products.signals.backend.quota.posthoganalytics.capture"),+ ):+ result = await check_report_quota_gate_activity(+ CheckReportQuotaGateInput(team_id=ateam.id, report_id=str(uuid.uuid4()), stage="summary_entry")+ )+ assert result is enforced+++async def test_check_activity_fails_open_when_team_lookup_errors():+ # The never-raises contract: a failure inside the gate check must resolve to "proceed", not+ # bubble into the workflow's except handler and mark the report failed.+ result = await check_report_quota_gate_activity(+ CheckReportQuotaGateInput(team_id=99_999_999, report_id=str(uuid.uuid4()), stage="summary_entry")+ )+ assert result is False+++# ---------------------------------------------------------------------------+# revert_report_to_candidate_activity+# ---------------------------------------------------------------------------+++async def test_revert_returns_in_progress_report_to_candidate(ateam):+ report = await database_sync_to_async(SignalReport.objects.create)(+ team=ateam,+ status=SignalReport.Status.IN_PROGRESS,+ total_weight=2.0,+ signal_count=2,+ signals_at_run=5,+ run_count=2,+ )++ await revert_report_to_candidate_activity(RevertReportToCandidateInput(team_id=ateam.id, report_id=str(report.id)))++ refreshed = await database_sync_to_async(SignalReport.objects.get)(id=report.id)+ assert refreshed.status == SignalReport.Status.CANDIDATE+ # run_count feeds Temporal workflow IDs and must never roll back on a quota pause.+ assert refreshed.run_count == 2++[email protected]("status", [SignalReport.Status.CANDIDATE, SignalReport.Status.READY])+async def test_revert_noops_when_report_is_not_in_progress(ateam, status):+ # An activity retry landing after another run already moved the report on must not clobber it.+ report = await database_sync_to_async(SignalReport.objects.create)(+ team=ateam,+ status=status,+ title="t",+ summary="s",+ total_weight=2.0,+ signal_count=2,+ )++ await revert_report_to_candidate_activity(RevertReportToCandidateInput(team_id=ateam.id, report_id=str(report.id)))++ refreshed = await database_sync_to_async(SignalReport.objects.get)(id=report.id)+ assert refreshed.status == status+++# ---------------------------------------------------------------------------+# Workflow wiring: the gates must short-circuit the run at the right points+# ---------------------------------------------------------------------------+++class _Recorder:+ def __init__(self, gate_answers: dict[str, bool]) -> None:+ self.gate_answers = gate_answers+ self.gate_checks: list[str] = []+ self.fetches = 0+ self.marks_in_progress = 0+ self.safety_checks = 0+ self.repo_selections = 0+ self.researches = 0+ self.reverts = 0+ self.resets = 0+ self.failures = 0+++def _signal_data() -> SignalData:+ return SignalData(+ signal_id=str(uuid.uuid4()),+ content="something happened",+ source_product="error_tracking",+ source_type="issue",+ source_id=str(uuid.uuid4()),+ weight=1.0,+ timestamp=datetime(2026, 1, 1, tzinfo=UTC),+ )+++async def _run_summary_workflow(recorder: _Recorder) -> None:+ @activity.defn(name="check_report_quota_gate_activity")+ async def fake_quota(input: CheckReportQuotaGateInput) -> bool:+ recorder.gate_checks.append(input.stage)+ return recorder.gate_answers.get(input.stage, False)++ @activity.defn(name="fetch_signals_for_report_activity")+ async def fake_fetch(input: FetchSignalsForReportInput) -> FetchSignalsForReportOutput:+ recorder.fetches += 1+ return FetchSignalsForReportOutput(signals=[_signal_data()])++ @activity.defn(name="mark_report_in_progress_activity")+ async def fake_mark_in_progress(input: MarkReportInProgressInput) -> None:+ recorder.marks_in_progress += 1++ @activity.defn(name="report_safety_judge_activity")+ async def fake_safety(input: SafetyJudgeInput) -> SafetyJudgeOutput:+ recorder.safety_checks += 1+ return SafetyJudgeOutput(safe=True, explanation="ok")++ @activity.defn(name="select_repository_activity")+ async def fake_select_repo(input: SelectRepositoryInput) -> RepoSelectionResult:+ recorder.repo_selections += 1+ return RepoSelectionResult(repository="owner/repo", reason="selected")++ @activity.defn(name="run_agentic_report_activity")+ async def fake_research(input: RunAgenticReportInput) -> RunAgenticReportOutput:+ recorder.researches += 1+ # NOT_ACTIONABLE terminates the workflow via the reset path, keeping the fake surface small.+ return RunAgenticReportOutput(+ title="t",+ summary="s",+ choice=ActionabilityChoice.NOT_ACTIONABLE,+ priority=None,+ explanation="e",+ already_addressed=False,+ repository="owner/repo",+ )++ @activity.defn(name="revert_report_to_candidate_activity")+ async def fake_revert(input: RevertReportToCandidateInput) -> None:+ recorder.reverts += 1++ @activity.defn(name="reset_report_to_potential_activity")+ async def fake_reset(input: ResetReportToPotentialInput) -> None:+ recorder.resets += 1++ @activity.defn(name="mark_report_failed_activity")+ async def fake_failed(input: MarkReportFailedInput) -> None:+ recorder.failures += 1++ # The production self-driving worker runs with the pydantic data converter; the default converter+ # mangles the enum/pydantic payloads these activities exchange (RepoSelectionResult,+ # ActionabilityChoice), sending the workflow down the wrong decision branch.+ async with await WorkflowEnvironment.start_time_skipping(data_converter=pydantic_data_converter) as env:+ async with Worker(+ env.client,+ task_queue=TASK_QUEUE,+ workflows=[SignalReportSummaryWorkflow],+ activities=[+ fake_quota,+ fake_fetch,+ fake_mark_in_progress,+ fake_safety,+ fake_select_repo,+ fake_research,+ fake_revert,+ fake_reset,+ fake_failed,+ ],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ await asyncio.wait_for(+ env.client.execute_workflow(+ SignalReportSummaryWorkflow.run,+ SignalReportSummaryWorkflowInputs(team_id=1, report_id=str(uuid.uuid4())),+ id=f"summary-quota-{uuid.uuid4()}",+ task_queue=TASK_QUEUE,+ ),+ timeout=30,+ )+++async def test_entry_gate_stops_run_before_any_work():+ recorder = _Recorder(gate_answers={"summary_entry": True})+ await _run_summary_workflow(recorder)+ assert recorder.gate_checks == ["summary_entry"]+ # Nothing downstream runs, and the report row is untouched (no in_progress transition to revert).+ assert recorder.fetches == 0+ assert recorder.marks_in_progress == 0+ assert recorder.reverts == 0+ assert recorder.failures == 0+++async def test_pre_research_gate_reverts_report_and_skips_research():+ recorder = _Recorder(gate_answers={"pre_research": True})+ await _run_summary_workflow(recorder)+ assert recorder.gate_checks == ["summary_entry", "pre_repo_selection", "pre_research"]+ assert recorder.marks_in_progress == 1+ assert recorder.repo_selections == 1+ # The expensive research never starts, and the in_progress report is handed back to candidate.+ assert recorder.researches == 0+ assert recorder.reverts == 1+ assert recorder.failures == 0+++async def test_open_gates_let_the_run_flow_through():+ recorder = _Recorder(gate_answers={})+ await _run_summary_workflow(recorder)+ assert recorder.gate_checks == ["summary_entry", "pre_repo_selection", "pre_research"]+ assert recorder.researches == 1+ assert recorder.reverts == 0+ assert recorder.failures == 0diff --git a/products/signals/backend/test/test_task_run_artefacts.py b/products/signals/backend/test/test_task_run_artefacts.pyindex 4c3d20685664..2fdc01942595 100644--- a/products/signals/backend/test/test_task_run_artefacts.py+++ b/products/signals/backend/test/test_task_run_artefacts.py@@ -1,9 +1,11 @@import json+from datetime import UTC, datetimefrom posthog.test.base import BaseTestfrom parameterized import parameterized+from products.signals.backend.billing import first_billable_pr_run_atfrom products.signals.backend.custom_agent.persistence import create_custom_agent_ready_reportfrom products.signals.backend.custom_agent.schemas import CustomAgentFinalReportfrom products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportTask@@ -21,6 +23,7 @@ from products.signals.backend.task_run_artefacts import (aappend_task_run_artefact,append_task_run_artefact,record_implementation_task,+ release_quota_cancelled_implementation,signals_task_ids,)from products.tasks.backend.facade.repo_selection_types import RepoSelectionResult@@ -360,3 +363,81 @@ class TestReportsForTaskFilter(BaseTest):)assert self._matched_report_ids(other_task) == set()assert self._matched_report_ids(task) == {str(report.id)}+++class TestReleaseQuotaCancelledImplementation(BaseTest):+ def _report(self) -> SignalReport:+ return SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="t",+ summary="s",+ signal_count=1,+ total_weight=1.0,+ )++ def _task(self) -> Task:+ return Task.objects.create(+ team=self.team,+ title="task",+ description="desc",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ )++ def test_release_removes_gate_records_and_leaves_only_the_report(self):+ # The auto-start gate reads both the SignalReportTask row and the implementation artefact;+ # leaving either behind after a quota cancel would permanently block re-implementation.+ report = self._report()+ task = self._task()+ record_implementation_task(team_id=self.team.id, report_id=str(report.id), task_id=str(task.id))+ # A research artefact from another task must survive the release untouched.+ research_task = self._task()+ append_task_run_artefact(+ team_id=self.team.id,+ report_id=str(report.id),+ product=SIGNALS_PRODUCT,+ type=TASK_RUN_TYPE_RESEARCH,+ task_id=str(research_task.id),+ )++ released = release_quota_cancelled_implementation(team_id=self.team.id, task_id=str(task.id))++ assert released == [str(report.id)]+ assert not SignalReportTask.objects.filter(task_id=task.id).exists()+ assert not SignalReport.associated_task_runs(+ report_id=str(report.id), team_id=self.team.id, product=SIGNALS_PRODUCT, type=TASK_RUN_TYPE_IMPLEMENTATION+ )+ assert SignalReport.associated_task_runs(+ report_id=str(report.id), team_id=self.team.id, product=SIGNALS_PRODUCT, type=TASK_RUN_TYPE_RESEARCH+ )+ note = SignalReportArtefact.objects.get(report=report, type=SignalReportArtefact.ArtefactType.NOTE)+ assert "pull request limit" in json.loads(note.content)["note"]++ def test_release_without_implementation_link_is_a_noop(self):+ task = self._task()+ assert release_quota_cancelled_implementation(team_id=self.team.id, task_id=str(task.id)) == []++ def test_release_skips_report_whose_billable_pr_shipped_from_a_sibling_run(self):+ # The cancel decision is run-scoped but this delete is task-scoped: a sibling run of the+ # same task can have shipped the report's billable PR in an earlier period. The bridge row+ # is billing's evidence for that charge (billed-earlier dedup, refund eligibility), so the+ # release must leave the report untouched instead of re-opening it for a second billing.+ report = self._report()+ task = self._task()+ record_implementation_task(team_id=self.team.id, report_id=str(report.id), task_id=str(task.id))+ TaskRun.objects.create(+ team=self.team,+ task=task,+ output={"pr_url": "https://github.com/x/y/pull/1"},+ created_at=datetime(2026, 6, 10, tzinfo=UTC),+ )++ released = release_quota_cancelled_implementation(team_id=self.team.id, task_id=str(task.id))++ assert released == []+ assert SignalReportTask.objects.filter(task_id=task.id, relationship=TASK_RUN_TYPE_IMPLEMENTATION).exists()+ assert first_billable_pr_run_at(report.id) is not None+ # Auto-start must still see a started implementation — the report is implemented, not stuck.+ assert SignalReport.associated_task_runs(+ report_id=str(report.id), team_id=self.team.id, product=SIGNALS_PRODUCT, type=TASK_RUN_TYPE_IMPLEMENTATION+ )diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 6018dbe22e9d..455ff1343e3b 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -104,6 +104,7 @@ from products.signals.backend.models import (SignalTeamConfig,SignalUserAutonomyConfig,)+from products.signals.backend.quota import self_driving_quota_enforcement_enabled, self_driving_quota_gatefrom products.signals.backend.report_generation.research import ActionabilityChoicefrom products.signals.backend.report_generation.resolve_reviewers import (get_org_member_github_login_to_user_map,@@ -687,6 +688,13 @@ class SignalReportRefundSummaryResponseSerializer(serializers.Serializer):"PR count that reacts to new PRs and same-day refunds immediately."),)+ quota_limited = serializers.BooleanField(+ help_text=(+ "Whether autonomous PR generation is currently paused for this project because the "+ "organization is over its self-driving credits quota. Read from the quota limiter, so it "+ "reflects the same state the pipeline gates enforce."+ ),+ )class SignalReportContentUpdateSerializer(serializers.Serializer):@@ -2225,7 +2233,11 @@ class SignalReportViewSet()@action(detail=False, methods=["get"], url_path="refund-summary", required_scopes=["task:read"])def refund_summary(self, request: Request, **kwargs):- if not self._signals_pr_refunds_enabled():+ # Two independent flags can each make this endpoint matter: refunds (the netting numbers)+ # and quota enforcement (`quota_limited` drives the widget's paused banner, and enforcement+ # can roll out before refunds). Gating on refunds alone would hide the paused state for+ # enforcement-only orgs.+ if not (self._signals_pr_refunds_enabled() or self_driving_quota_enforcement_enabled(self.team)):raise NotFound("PR refunds are not enabled for this organization.")period = current_billing_period_bounds(self.organization)@@ -2245,6 +2257,7 @@ class SignalReportViewSet("credited_refund_count": aggregates["credited_refund_count"] or 0,"credited_credits": aggregates["credited_credits"] or 0,"period_billable_credits": period_billable_credits_for_org(self.organization.id, period=period),+ "quota_limited": self_driving_quota_gate(self.team).enforced,})diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex c351d05d3e57..ba0863673c64 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -1803,6 +1803,8 @@ export interface SignalReportRefundSummaryResponseApi {credited_credits: number/** The organization's live billable signals credits for the current billing period, computed by the same rules as the nightly usage report — including PRs created today that billing hasn't recorded yet, and already excluding refund-excluded and billing-exempt reports. Take the max of this and billing's recorded usage for a live PR count that reacts to new PRs and same-day refunds immediately. */period_billable_credits: number+ /** Whether autonomous PR generation is currently paused for this project because the organization is over its self-driving credits quota. Read from the quota limiter, so it reflects the same state the pipeline gates enforce. */+ quota_limited: boolean}export interface LLMSkillFileInputApi {diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 77a7555ca3ee..f85089cd471a 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -959,6 +959,13 @@ def create_and_run_task(An id the creator can't file into (see ``_visible_channel``) is ignored rather thanraising — feed placement must never break task creation."""+ # create_pr=False sessions (research, repo selection, custom agents) can never open the+ # billable PR, so the quota gate must not block them.+ if origin_product == Task.OriginProduct.SIGNAL_REPORT and create_pr:+ # Distinct stage from create_task's `manual_create`: the main caller here is the+ # auto-start pipeline, whose over-quota hits must not pollute the manual-path+ # dark-launch bucket.+ enforce_self_driving_pr_quota(team, report_id=signal_report_id, stage="task_create")channel = _visible_channel(channel_id, team.id, user_id) if channel_id is not None else Nonetask = Task.create_and_run(team=team,@@ -2163,6 +2170,73 @@ def _send_wizard_pr_ready_email_for_pr(run: TaskRun) -> None:transaction.on_commit(lambda: send_wizard_pr_ready_email.delay(str(run.id)))+def _refresh_self_driving_quota_for_pr(run: TaskRun, old_pr_url: str | None) -> None:+ """Queue an org-level self-driving quota re-evaluation when a self-driving-origin run records its first+ PR URL. That write is the report's billable moment (products/signals/backend/billing.py), so+ re-evaluating now lets the quota limiter flag the org within seconds of the PR that crosses+ its limit (for runs created the same UTC day; `refresh_org_self_driving_quota` documents the+ cross-midnight gap); the 15-minute quota cron only re-reads usage on its next tick. Dispatched+ on commit so the task reads the committed pr_url; best-effort because the cron is the backstop.+ Never raises: the callers signal workflow completion and run other PR side effects right after,+ and a refresh hiccup must not abort those or turn an already-committed run write into a 500.+ """+ try:+ if old_pr_url:+ return+ new_pr_url = (run.output or {}).get("pr_url") if isinstance(run.output, dict) else None+ if not new_pr_url or run.task.origin_product != Task.OriginProduct.SIGNAL_REPORT:+ return+ # Billing only ever counts GitHub PR URLs (billing.py validates the same prefix), so a+ # recompute for any other output.pr_url string is a guaranteed no-op; don't let arbitrary+ # client-written values enqueue org-wide refreshes. Literal kept local because tasks code+ # must not import signals internals.+ if not new_pr_url.startswith("https://github.com/"):+ return+ organization_id = Team.objects.filter(id=run.task.team_id).values_list("organization_id", flat=True).first()+ if organization_id is None:+ return+ from ee.tasks.quota_limiting import (+ refresh_org_self_driving_quota_task, # noqa: PLC0415 — keep billing deps off the api import path+ )++ def _dispatch() -> None:+ try:+ refresh_org_self_driving_quota_task.delay(str(organization_id))+ except Exception:+ logger.warning(+ "self_driving_quota_refresh_dispatch_failed", extra={"run_id": str(run.id)}, exc_info=True+ )++ transaction.on_commit(_dispatch)+ except Exception:+ logger.warning("self_driving_quota_refresh_failed", extra={"run_id": str(run.id)}, exc_info=True)+++def enforce_self_driving_pr_quota(team: Team, *, report_id: str | None = None, stage: str = "manual_create") -> None:+ """Refuse to create a PR-opening self-driving task while the team's org is over its self-driving+ credits quota with enforcement on. The implementation task is the step that leads to the+ billable PR, so the manual create-from-report path must respect the same limit as the pipeline+ auto-start gate (products/signals/backend/auto_start.py). Emits `signal_report_quota_paused`+ at ``stage`` whenever the org is limited, so each caller's gate stays measurable during the+ dark launch like every other gate. Raises ``QuotaLimitExceeded`` (402).+ """+ from posthog.exceptions import QuotaLimitExceeded # noqa: PLC0415 — keep billing deps off the api import path++ from products.signals.backend.quota import ( # noqa: PLC0415 — cross-product read kept off the api import path+ capture_signal_report_quota_paused,+ self_driving_quota_gate,+ )++ gate = self_driving_quota_gate(team)+ if gate.limited:+ capture_signal_report_quota_paused(team, report_id=report_id, stage=stage, enforced=gate.enforced)+ if gate.enforced:+ raise QuotaLimitExceeded(+ "Your organization reached its self-driving pull request limit. "+ "Increase the limit from the Inbox usage widget, or ask an org admin to do so."+ )++def update_task_run(run_id: str | UUID,task_id: str | UUID,@@ -2292,6 +2366,7 @@ def update_task_run(new_pr_url = (run.output or {}).get("pr_url") if isinstance(run.output, dict) else Noneif new_pr_url and new_pr_url != old_pr_url:+ _refresh_self_driving_quota_for_pr(run, old_pr_url)_post_slack_update_for_pr(run)_send_wizard_pr_ready_email_for_pr(run)post_pr_created_thread_update(run, new_pr_url)@@ -2338,6 +2413,7 @@ def set_task_run_output(merged = merge_pr_output(existing, output)run.output = _apply_caller_output(existing, output, merged)run.save(update_fields=["output", "updated_at"])+ _refresh_self_driving_quota_for_pr(run, existing.get("pr_url"))if task.json_schema:signal_workflow_completion(run.id, TaskRun.Status.COMPLETED, None)run.publish_stream_state_event()@@ -4293,6 +4369,14 @@ def create_task(elif title:validated_data.setdefault("title_manually_set", True)+ # The write serializer binds the report as `signal_report` (a PK field); direct callers may+ # pass `signal_report_id`. Either way this is the manual "start work from a report" path.+ # Gated regardless of the relationship label: the label is client-selected and manually+ # created tasks run PR-capable by default, so a "discussion" label must not dodge the limit.+ report_ref = validated_data.get("signal_report") or validated_data.get("signal_report_id")+ if report_ref and validated_data.get("origin_product") == Task.OriginProduct.SIGNAL_REPORT:+ enforce_self_driving_pr_quota(team, report_id=str(getattr(report_ref, "id", report_ref)))+logger.info("Creating task with data: %s", validated_data)with transaction.atomic():task = Task.objects.create(**validated_data)diff --git a/products/tasks/backend/temporal/__init__.py b/products/tasks/backend/temporal/__init__.pyindex b88ae1ccbce1..4c0f6a10f15e 100644--- a/products/tasks/backend/temporal/__init__.py+++ b/products/tasks/backend/temporal/__init__.py@@ -22,6 +22,7 @@ from .process_task.activities import (create_resume_snapshot,create_sandbox_for_repository,emit_progress_activity,+ enforce_self_driving_run_quota,execute_task_in_sandbox,forward_pending_user_message,get_sandbox_for_repository,@@ -98,6 +99,7 @@ ACTIVITIES = [cleanup_sandbox,complete_run_stream,emit_progress_activity,+ enforce_self_driving_run_quota,track_workflow_event,post_slack_update,update_task_run_status,diff --git a/products/tasks/backend/temporal/process_task/activities/__init__.py b/products/tasks/backend/temporal/process_task/activities/__init__.pyindex f750b9a04257..5cd9af71ee89 100644--- a/products/tasks/backend/temporal/process_task/activities/__init__.py+++ b/products/tasks/backend/temporal/process_task/activities/__init__.py@@ -1,6 +1,7 @@from .cleanup_sandbox import CleanupSandboxInput, CompleteRunStreamInput, cleanup_sandbox, complete_run_streamfrom .create_resume_snapshot import CreateResumeSnapshotInput, CreateResumeSnapshotOutput, create_resume_snapshotfrom .emit_progress_activity import EmitProgressInput, emit_progress_activity+from .enforce_self_driving_quota import EnforceSelfDrivingRunQuotaInput, enforce_self_driving_run_quotafrom .execute_task_in_sandbox import ExecuteTaskInput, ExecuteTaskOutput, execute_task_in_sandboxfrom .forward_pending_message import forward_pending_user_messagefrom .get_sandbox_for_repository import (@@ -105,6 +106,8 @@ __all__ = ["create_resume_snapshot","create_sandbox_for_repository","emit_progress_activity",+ "EnforceSelfDrivingRunQuotaInput",+ "enforce_self_driving_run_quota","execute_task_in_sandbox","forward_pending_user_message","relay_agent_design_signals",diff --git a/products/tasks/backend/temporal/process_task/activities/enforce_self_driving_quota.py b/products/tasks/backend/temporal/process_task/activities/enforce_self_driving_quota.pynew file mode 100644index 000000000000..6829b9c8846d--- /dev/null+++ b/products/tasks/backend/temporal/process_task/activities/enforce_self_driving_quota.py@@ -0,0 +1,173 @@+from dataclasses import dataclass++import structlog+from temporalio import activity++from posthog.models import Team+from posthog.temporal.common.utils import asyncify++from products.signals.backend.quota import (+ capture_signal_report_quota_paused,+ record_quota_check_failed_open,+ self_driving_quota_gate,+)+from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.temporal.observability import log_with_activity_context++logger = structlog.get_logger(__name__)++# Outcomes for the workflow's quota-recheck loop.+SELF_DRIVING_QUOTA_PROCEED = "proceed"+SELF_DRIVING_QUOTA_STOP_CHECKING = "stop_checking"+SELF_DRIVING_QUOTA_CANCELLED = "cancelled"++# Persisted as the run's error_message, so it is what the tasks UI shows for the stopped run.+SELF_DRIVING_QUOTA_CANCEL_REASON = (+ "Stopped automatically: the organization reached its self-driving pull request limit."+)++# Only GitHub-hosted PR URLs are billable (products/signals/backend/billing.py applies the same+# prefix rule), so only they attest already-billed work. Run output is caller-writable, which+# means any other pr_url value must not stop enforcement. Literal kept local because tasks code+# must not import signals internals.+_BILLABLE_PR_URL_PREFIX = "https://github.com/"+++def _has_billable_pr_url(output: object) -> bool:+ if not isinstance(output, dict):+ return False+ pr_url = output.get("pr_url")+ return isinstance(pr_url, str) and pr_url.startswith(_BILLABLE_PR_URL_PREFIX)+++@dataclass+class EnforceSelfDrivingRunQuotaInput:+ run_id: str+ task_id: str+ team_id: int+++@asyncify+def enforce_self_driving_run_quota(input: EnforceSelfDrivingRunQuotaInput) -> str:+ """Mid-run quota gate for self-driving-origin implementation runs.++ Returns one of:++ - ``stop_checking``: the run is not self-driving-billable (wrong origin, already terminal) or has+ already recorded a billable (GitHub) PR URL. A shipped billable PR means the report is already+ billed, so letting the run finish (and its CI follow-ups run) costs the customer nothing more.+ - ``proceed``: the team's org is under its quota, or enforcement is off. Check again later.+ - ``cancelled``: the team's org is over quota with enforcement on. The run was cancelled through the+ standard cancellation path (agent interrupted, workflow signalled its own completion) and+ the report's auto-start records were released so a later cycle can re-implement it with+ "only the report" left behind.++ Fails open (``proceed``) on unexpected errors in the quota check itself: the periodic recheck+ and the quota cron are the backstop, and a quota-infra blip must never kill a healthy run. An+ error inside the cancel round-trip is a different class — the completion signal may already+ have been delivered — so it is logged loudly instead of being counted as a fail-open, and also+ returns ``proceed``: a still-alive run gets the cancel retried on the next recheck, while a+ run the signal did reach is already tearing down and will not be rechecked.+ """+ try:+ run = TaskRun.objects.select_related("task").filter(id=input.run_id, team_id=input.team_id).first()+ if run is None or run.is_terminal:+ return SELF_DRIVING_QUOTA_STOP_CHECKING+ task = run.task+ if task.origin_product != Task.OriginProduct.SIGNAL_REPORT:+ return SELF_DRIVING_QUOTA_STOP_CHECKING+ if _has_billable_pr_url(run.output):+ return SELF_DRIVING_QUOTA_STOP_CHECKING++ team = Team.objects.select_related("organization").get(id=input.team_id)+ gate = self_driving_quota_gate(team)+ if gate.limited:+ # Dark-launch would-blocks are emitted once per run (marker in run state), not once+ # per 5-minute recheck, so the flag-off measurement counts runs that would have been+ # cancelled rather than ticks survived. An enforced hit always emits: it cancels the+ # run, so it fires once by construction.+ already_reported = bool((run.state or {}).get("self_driving_quota_paused_reported"))+ if gate.enforced or not already_reported:+ capture_signal_report_quota_paused(+ team,+ report_id=str(task.signal_report_id) if task.signal_report_id else None,+ stage="implementation_run",+ enforced=gate.enforced,+ )+ if not gate.enforced:+ TaskRun.update_state_atomic(run.id, updates={"self_driving_quota_paused_reported": True})+ if not gate.enforced:+ return SELF_DRIVING_QUOTA_PROCEED+ except Exception:+ record_quota_check_failed_open()+ logger.warning("self_driving_run_quota_check_failed_open", run_id=input.run_id, exc_info=True)+ return SELF_DRIVING_QUOTA_PROCEED++ from products.tasks.backend.facade.cancellation import ( # noqa: PLC0415 — cancellation imports the workflow module, which imports this package (cycle)+ cancel_task_run,+ )++ try:+ outcome, _ = cancel_task_run(+ input.run_id,+ input.task_id,+ input.team_id,+ reason=SELF_DRIVING_QUOTA_CANCEL_REASON,+ source="self_driving_quota",+ )+ except Exception:+ # Not a fail-open: the cancel round-trip died part-way, so the completion signal may or+ # may not have been delivered. No release either — if the run is still alive, releasing+ # would let a duplicate implementation start alongside it; the next recheck retries the+ # cancel (and the release with it). If the signal landed, no recheck will come and the+ # report keeps its implementation records until someone releases them manually — loud so+ # it gets followed up, like a release failure.+ logger.exception("self_driving_quota_cancel_failed", run_id=input.run_id, task_id=input.task_id)+ return SELF_DRIVING_QUOTA_PROCEED++ if outcome == "already_terminal":+ # The run reached a terminal state between our snapshot and the cancel — possibly by+ # shipping its PR (the billable moment). Releasing the report's records here could delete+ # the very SignalReportTask row the billing usage query counts that PR through, un-billing+ # shipped work. Nothing is in flight anymore, so just stop checking.+ return SELF_DRIVING_QUOTA_STOP_CHECKING+ if outcome != "accepted":+ log_with_activity_context(+ "Self-driving quota cancel not accepted, will re-check later",+ run_id=input.run_id,+ outcome=outcome,+ )+ return SELF_DRIVING_QUOTA_PROCEED++ # The cancel is irreversible from here on: failures below must not report "proceed", or the+ # workflow would believe the run is healthy while it is being torn down.+ try:+ # Re-read after the cancel round-trip: the agent can ship its PR (agent report or webhook+ # backstop) while the interrupt is in flight. A billable PR means the report is billed — keep+ # its records; the run still ends cancelled.+ refreshed_output = TaskRun.objects.filter(id=input.run_id).values_list("output", flat=True).first()+ if _has_billable_pr_url(refreshed_output):+ log_with_activity_context(+ "PR landed during self-driving quota cancel, keeping the report's billing records",+ run_id=input.run_id,+ task_id=input.task_id,+ )+ return SELF_DRIVING_QUOTA_CANCELLED++ from products.signals.backend.task_run_artefacts import ( # noqa: PLC0415 — cross-product write kept off the activity import path+ release_quota_cancelled_implementation,+ )++ released = release_quota_cancelled_implementation(team_id=input.team_id, task_id=str(input.task_id))+ log_with_activity_context(+ "Cancelled self-driving implementation run over the PR limit",+ run_id=input.run_id,+ task_id=input.task_id,+ released_report_ids=released,+ )+ except Exception:+ # The report keeps its implementation records, which blocks re-implementation until+ # someone releases it manually — loud so it gets followed up.+ logger.exception("self_driving_quota_release_failed", run_id=input.run_id, task_id=input.task_id)+ return SELF_DRIVING_QUOTA_CANCELLEDdiff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_enforce_self_driving_quota.py b/products/tasks/backend/temporal/process_task/activities/tests/test_enforce_self_driving_quota.pynew file mode 100644index 000000000000..e5036123fc8f--- /dev/null+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_enforce_self_driving_quota.py@@ -0,0 +1,245 @@+import json++import pytest+from unittest.mock import patch++from django.apps import apps++from asgiref.sync import async_to_sync++from products.signals.backend.quota import SelfDrivingQuotaGate+from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.temporal.process_task.activities.enforce_self_driving_quota import (+ SELF_DRIVING_QUOTA_CANCELLED,+ SELF_DRIVING_QUOTA_PROCEED,+ SELF_DRIVING_QUOTA_STOP_CHECKING,+ EnforceSelfDrivingRunQuotaInput,+ enforce_self_driving_run_quota,+)++MODULE = "products.tasks.backend.temporal.process_task.activities.enforce_self_driving_quota"+++def _run_activity(activity_environment, run: TaskRun) -> str:+ return async_to_sync(activity_environment.run)(+ enforce_self_driving_run_quota,+ EnforceSelfDrivingRunQuotaInput(run_id=str(run.id), task_id=str(run.task_id), team_id=run.team_id),+ )+++def _make_self_driving_run(test_task, test_task_run):+ SignalReport = apps.get_model("signals", "SignalReport")+ report = SignalReport.objects.create(team=test_task.team, status=SignalReport.Status.READY, title="t", summary="s")+ test_task.origin_product = Task.OriginProduct.SIGNAL_REPORT+ test_task.signal_report_id = report.id+ test_task.save(update_fields=["origin_product", "signal_report_id"])+ test_task_run.status = TaskRun.Status.IN_PROGRESS+ test_task_run.save(update_fields=["status"])+ return report++[email protected]_secrets+class TestEnforceSelfDrivingRunQuotaActivity:+ @pytest.mark.django_db(transaction=True)+ def test_non_self_driving_origin_stops_checking_without_gating(self, activity_environment, test_task_run):+ # The gate must never touch user or AI tasks: a wrong-origin run exits before any quota read.+ with patch(f"{MODULE}.self_driving_quota_gate") as gate_mock:+ assert _run_activity(activity_environment, test_task_run) == SELF_DRIVING_QUOTA_STOP_CHECKING+ gate_mock.assert_not_called()++ @pytest.mark.django_db(transaction=True)+ def test_run_with_pr_url_stops_checking_even_when_over_quota(self, activity_environment, test_task, test_task_run):+ # A shipped PR means the report is already billed; cancelling would kill paid work.+ _make_self_driving_run(test_task, test_task_run)+ test_task_run.output = {"pr_url": "https://github.com/x/y/pull/1"}+ test_task_run.save(update_fields=["output"])+ with patch(f"{MODULE}.self_driving_quota_gate", return_value=SelfDrivingQuotaGate(limited=True, enforced=True)):+ assert _run_activity(activity_environment, test_task_run) == SELF_DRIVING_QUOTA_STOP_CHECKING+ test_task_run.refresh_from_db()+ assert test_task_run.status == TaskRun.Status.IN_PROGRESS++ @pytest.mark.django_db(transaction=True)+ @pytest.mark.parametrize(+ ("gate", "expected"),+ [+ (SelfDrivingQuotaGate(limited=False, enforced=False), SELF_DRIVING_QUOTA_PROCEED),+ # Dark launch: limited but not enforced must never cancel.+ (SelfDrivingQuotaGate(limited=True, enforced=False), SELF_DRIVING_QUOTA_PROCEED),+ ],+ )+ def test_under_quota_or_dark_launch_proceeds(self, activity_environment, test_task, test_task_run, gate, expected):+ _make_self_driving_run(test_task, test_task_run)+ with (+ patch(f"{MODULE}.self_driving_quota_gate", return_value=gate),+ patch(f"{MODULE}.capture_signal_report_quota_paused"),+ ):+ assert _run_activity(activity_environment, test_task_run) == expected+ test_task_run.refresh_from_db()+ assert test_task_run.status == TaskRun.Status.IN_PROGRESS++ @pytest.mark.django_db(transaction=True)+ def test_dark_launch_telemetry_emits_once_per_run_not_per_recheck(+ self, activity_environment, test_task, test_task_run+ ):+ # The 5-minute recheck would otherwise emit a would-block event per tick for the run's whole+ # lifetime, corrupting the measurement the dark launch exists to produce.+ _make_self_driving_run(test_task, test_task_run)+ with (+ patch(f"{MODULE}.self_driving_quota_gate", return_value=SelfDrivingQuotaGate(limited=True, enforced=False)),+ patch(f"{MODULE}.capture_signal_report_quota_paused") as capture_mock,+ ):+ assert _run_activity(activity_environment, test_task_run) == SELF_DRIVING_QUOTA_PROCEED+ assert _run_activity(activity_environment, test_task_run) == SELF_DRIVING_QUOTA_PROCEED+ assert capture_mock.call_count == 1++ @pytest.mark.django_db(transaction=True)+ def test_already_terminal_cancel_outcome_never_releases_the_report(+ self, activity_environment, test_task, test_task_run+ ):+ # The un-billing race: the run finished (possibly shipping its PR) between the activity's+ # snapshot and the cancel. Releasing would delete the SignalReportTask row the billing+ # usage query counts that PR through.+ report = _make_self_driving_run(test_task, test_task_run)+ from products.signals.backend.task_run_artefacts import record_implementation_task++ record_implementation_task(team_id=test_task.team_id, report_id=str(report.id), task_id=str(test_task.id))+ SignalReportTask = apps.get_model("signals", "SignalReportTask")+ with (+ patch(f"{MODULE}.self_driving_quota_gate", return_value=SelfDrivingQuotaGate(limited=True, enforced=True)),+ patch(f"{MODULE}.capture_signal_report_quota_paused"),+ patch(+ "products.tasks.backend.facade.cancellation.cancel_task_run",+ return_value=("already_terminal", None),+ ),+ ):+ assert _run_activity(activity_environment, test_task_run) == SELF_DRIVING_QUOTA_STOP_CHECKING+ assert SignalReportTask.objects.filter(task_id=test_task.id).exists()++ @pytest.mark.django_db(transaction=True)+ def test_pr_landing_during_cancel_keeps_billing_records(self, activity_environment, test_task, test_task_run):+ # The agent can report its PR while the cancel interrupt is in flight: the report is then+ # billed, so its records must survive even though the run ends cancelled.+ report = _make_self_driving_run(test_task, test_task_run)+ from products.signals.backend.task_run_artefacts import record_implementation_task++ record_implementation_task(team_id=test_task.team_id, report_id=str(report.id), task_id=str(test_task.id))+ SignalReportTask = apps.get_model("signals", "SignalReportTask")++ def _cancel_and_land_pr(*args, **kwargs):+ TaskRun.objects.filter(id=test_task_run.id).update(output={"pr_url": "https://github.com/x/y/pull/2"})+ return ("accepted", None)++ with (+ patch(f"{MODULE}.self_driving_quota_gate", return_value=SelfDrivingQuotaGate(limited=True, enforced=True)),+ patch(f"{MODULE}.capture_signal_report_quota_paused"),+ patch("products.tasks.backend.facade.cancellation.cancel_task_run", side_effect=_cancel_and_land_pr),+ ):+ assert _run_activity(activity_environment, test_task_run) == SELF_DRIVING_QUOTA_CANCELLED+ assert SignalReportTask.objects.filter(task_id=test_task.id).exists()++ @pytest.mark.django_db(transaction=True)+ def test_non_github_pr_url_does_not_grant_enforcement_immunity(+ self, activity_environment, test_task, test_task_run+ ):+ # Run output is caller-writable and only GitHub PR URLs are billable, so a forged+ # non-GitHub value must neither stop the rechecks nor keep the report's records+ # after the cancel.+ report = _make_self_driving_run(test_task, test_task_run)+ from products.signals.backend.task_run_artefacts import record_implementation_task++ record_implementation_task(team_id=test_task.team_id, report_id=str(report.id), task_id=str(test_task.id))+ test_task_run.output = {"pr_url": "https://example.com/not-github/pull/1"}+ test_task_run.save(update_fields=["output"])+ SignalReportTask = apps.get_model("signals", "SignalReportTask")+ with (+ patch(f"{MODULE}.self_driving_quota_gate", return_value=SelfDrivingQuotaGate(limited=True, enforced=True)),+ patch(f"{MODULE}.capture_signal_report_quota_paused"),+ patch("products.tasks.backend.facade.cancellation.cancel_task_run", return_value=("accepted", None)),+ ):+ assert _run_activity(activity_environment, test_task_run) == SELF_DRIVING_QUOTA_CANCELLED+ assert not SignalReportTask.objects.filter(task_id=test_task.id).exists()++ @pytest.mark.django_db(transaction=True)+ def test_release_failure_still_reports_cancelled(self, activity_environment, test_task, test_task_run):+ # The cancel is irreversible: a release failure must not tell the workflow to proceed as if+ # the run were healthy.+ _make_self_driving_run(test_task, test_task_run)+ with (+ patch(f"{MODULE}.self_driving_quota_gate", return_value=SelfDrivingQuotaGate(limited=True, enforced=True)),+ patch(f"{MODULE}.capture_signal_report_quota_paused"),+ patch("products.tasks.backend.facade.cancellation.cancel_task_run", return_value=("accepted", None)),+ patch(+ "products.signals.backend.task_run_artefacts.release_quota_cancelled_implementation",+ side_effect=RuntimeError("db down"),+ ),+ ):+ assert _run_activity(activity_environment, test_task_run) == SELF_DRIVING_QUOTA_CANCELLED++ @pytest.mark.django_db(transaction=True)+ def test_enforced_over_quota_cancels_run_and_releases_report(self, activity_environment, test_task, test_task_run):+ # The core money path: a PR-less self-driving run on an enforced over-quota team is cancelled+ # and its report is released so a later cycle can re-implement it.+ report = _make_self_driving_run(test_task, test_task_run)+ from products.signals.backend.task_run_artefacts import record_implementation_task++ record_implementation_task(+ team_id=test_task.team_id,+ report_id=str(report.id),+ task_id=str(test_task.id),+ run_id=str(test_task_run.id),+ )+ SignalReportTask = apps.get_model("signals", "SignalReportTask")+ SignalReportArtefact = apps.get_model("signals", "SignalReportArtefact")++ with (+ patch(f"{MODULE}.self_driving_quota_gate", return_value=SelfDrivingQuotaGate(limited=True, enforced=True)),+ patch(f"{MODULE}.capture_signal_report_quota_paused") as capture_mock,+ patch(+ "products.tasks.backend.facade.cancellation.cancel_task_run", return_value=("accepted", None)+ ) as cancel_mock,+ ):+ assert _run_activity(activity_environment, test_task_run) == SELF_DRIVING_QUOTA_CANCELLED++ assert cancel_mock.call_count == 1+ assert cancel_mock.call_args.kwargs["source"] == "self_driving_quota"+ assert not SignalReportTask.objects.filter(task_id=test_task.id).exists()+ notes = [+ a+ for a in SignalReportArtefact.objects.filter(report_id=report.id, type="note")+ if "pull request limit" in json.loads(a.content)["note"]+ ]+ assert len(notes) == 1+ assert capture_mock.call_args.kwargs["stage"] == "implementation_run"+ assert capture_mock.call_args.kwargs["enforced"] is True++ @pytest.mark.django_db(transaction=True)+ def test_fails_open_when_gate_errors(self, activity_environment, test_task, test_task_run):+ # A quota-infra blip must never kill a healthy run.+ _make_self_driving_run(test_task, test_task_run)+ with patch(f"{MODULE}.self_driving_quota_gate", side_effect=RuntimeError("redis down")):+ assert _run_activity(activity_environment, test_task_run) == SELF_DRIVING_QUOTA_PROCEED+ test_task_run.refresh_from_db()+ assert test_task_run.status == TaskRun.Status.IN_PROGRESS++ @pytest.mark.django_db(transaction=True)+ def test_cancel_failure_is_not_misclassified_as_fail_open(self, activity_environment, test_task, test_task_run):+ # A cancel that dies part-way may have already delivered the completion signal, so it is+ # not a benign quota-check blip: it must not feed the fail-open counter, and nothing may+ # be released while the run could still be alive — the next recheck retries the cancel.+ report = _make_self_driving_run(test_task, test_task_run)+ from products.signals.backend.task_run_artefacts import record_implementation_task++ record_implementation_task(team_id=test_task.team_id, report_id=str(report.id), task_id=str(test_task.id))+ SignalReportTask = apps.get_model("signals", "SignalReportTask")+ with (+ patch(f"{MODULE}.self_driving_quota_gate", return_value=SelfDrivingQuotaGate(limited=True, enforced=True)),+ patch(f"{MODULE}.capture_signal_report_quota_paused"),+ patch(+ "products.tasks.backend.facade.cancellation.cancel_task_run",+ side_effect=RuntimeError("signal round-trip died"),+ ),+ patch(f"{MODULE}.record_quota_check_failed_open") as failed_open_mock,+ ):+ assert _run_activity(activity_environment, test_task_run) == SELF_DRIVING_QUOTA_PROCEED+ failed_open_mock.assert_not_called()+ assert SignalReportTask.objects.filter(task_id=test_task.id).exists()diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex 8311562dc6b1..faf7266bc687 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -3,6 +3,7 @@ import jsonimport uuidimport randomimport asyncio+import dataclassesfrom concurrent.futures import ThreadPoolExecutorfrom datetime import UTC, datetime, timedelta@@ -566,6 +567,16 @@ class TestProcessTaskFollowupDispatch:@pytest.mark.django_dbclass TestProcessTaskWorkflowUnit:+ def test_quota_recheck_not_scheduled_for_non_pr_runs(self):+ # Research / repo-selection sessions run as SIGNAL_REPORT-origin tasks with+ # create_pr=False; scheduling the recheck for them would let the quota gate cancel+ # in-flight research.+ wf = ProcessTaskWorkflow()+ wf._context = dataclasses.replace(+ _build_context(github_integration_id=None), origin_product="signal_report", create_pr=False+ )+ assert wf._self_driving_quota_recheck_scheduled() is False+async def test_final_sandbox_cleanup_completes_the_run_stream(self, monkeypatch):cleanup_inputs: list[CleanupSandboxInput] = []diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 5568554ecb72..4d34c2d290c4 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -35,6 +35,12 @@ from .activities.cleanup_sandbox import ()from .activities.create_resume_snapshot import CreateResumeSnapshotInput, create_resume_snapshotfrom .activities.emit_progress_activity import EmitProgressInput, emit_progress_activity+from .activities.enforce_self_driving_quota import (+ SELF_DRIVING_QUOTA_CANCELLED,+ SELF_DRIVING_QUOTA_STOP_CHECKING,+ EnforceSelfDrivingRunQuotaInput,+ enforce_self_driving_run_quota,+)from .activities.execute_task_in_sandbox import ExecuteTaskOutputfrom .activities.feature_flags import (IsSlackAppAgentDesignEnabledForTaskActivityInput,@@ -185,6 +191,7 @@ class TaskEvent(StrEnum):TIMEOUT_REACHED = "timeout_reached"CI_FOLLOW_UP = "ci_follow_up"SANDBOX_GONE = "sandbox_gone"+ QUOTA_RECHECK = "quota_recheck"class CIFollowUpDecision(StrEnum):@@ -247,6 +254,17 @@ _PATCH_ID_CONCURRENT_FOLLOWUP_STEERING = "tasks-concurrent-followup-steering"# schedule it. Same two-step cleanup lifecycle as the patches above._PATCH_ID_DROP_SLACK_POST_AFTER_PROVISIONING = "tasks-drop-slack-post-after-provisioning"+# Self-driving-origin implementation runs periodically re-check the org's self-driving credits quota and+# cancel themselves before opening the billable PR when the org crossed its limit mid-run. Gates+# the recheck timer + activity commands so pre-rollout histories replay without them.+_PATCH_ID_SELF_DRIVING_QUOTA_KILL = "tasks-self-driving-quota-kill"++# How often a PR-less self-driving run re-checks the quota while waiting on agent activity. Frequent+# enough to catch a limit crossed by a parallel run's PR; each check is one Redis read.+SELF_DRIVING_QUOTA_RECHECK_INTERVAL = timedelta(minutes=5)++_ORIGIN_PRODUCT_SIGNAL_REPORT = "signal_report"+# Gates the new agent-design flag-eval execute_activity site.# Two-step deprecate-then-delete cleanup lifecycle as above._PATCH_ID_SLACK_AGENT_DESIGN_STATUS = "tasks-slack-agent-design-status"@@ -318,6 +336,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._pr_progress_emitted: bool = False# Decided once at workflow start; gates the placeholder skip + relay spawn.self._is_agent_design_enabled: bool = False+ # Deadline-based so heartbeats waking the event loop don't keep resetting the timer.+ self._self_driving_quota_next_check_at: Optional[datetime] = None+ self._self_driving_quota_checks_active: bool = Trueself._current_slack_relay_workflow_id: Optional[str] = None@property@@ -484,6 +505,26 @@ class ProcessTaskWorkflow(PostHogWorkflow):await workflow.sleep(CI_FOLLOW_UP_DELAY.total_seconds())return TaskEvent.CI_FOLLOW_UP+ def _self_driving_quota_recheck_scheduled(self) -> bool:+ return (+ self._self_driving_quota_checks_active+ and self._context is not None+ and self.context.origin_product == _ORIGIN_PRODUCT_SIGNAL_REPORT+ # Research / repo-selection / custom-agent sessions run with create_pr=False and can+ # never open the billable PR; rechecking them would let the quota gate cancel+ # in-flight research.+ and self.context.create_pr+ and workflow.patched(_PATCH_ID_SELF_DRIVING_QUOTA_KILL)+ )++ async def _wait_for_quota_recheck(self):+ if self._self_driving_quota_next_check_at is None:+ self._self_driving_quota_next_check_at = workflow.now() + SELF_DRIVING_QUOTA_RECHECK_INTERVAL+ remaining = self._self_driving_quota_next_check_at - workflow.now()+ if remaining.total_seconds() > 0:+ await workflow.sleep(remaining.total_seconds())+ return TaskEvent.QUOTA_RECHECK+def _describe_wait(self, *, warm_idle: bool, ci_follow_up_scheduled: bool, inactivity_timeout: timedelta) -> str:"""Human-readable summary of what the loop is blocked on, for the Temporal UI.@@ -548,6 +589,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):]if ci_follow_up_scheduled:possible_events.append(asyncio.create_task(self._wait_for_ci_follow_up()))+ if not warm_idle and self._self_driving_quota_recheck_scheduled():+ possible_events.append(asyncio.create_task(self._wait_for_quota_recheck()))done, pending = await workflow.wait(possible_events, return_when=asyncio.FIRST_COMPLETED)for task in pending:task.cancel()@@ -796,6 +839,40 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._last_active_time = workflow.now()case _:raise ValueError(f"Unknown CIFollowUpDecision: {follow_up_result}")+ case TaskEvent.QUOTA_RECHECK:+ self._self_driving_quota_next_check_at = workflow.now() + SELF_DRIVING_QUOTA_RECHECK_INTERVAL+ try:+ quota_outcome = await workflow.execute_activity(+ enforce_self_driving_run_quota,+ EnforceSelfDrivingRunQuotaInput(+ run_id=self.context.run_id,+ task_id=self.context.task_id,+ team_id=self.context.team_id,+ ),+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )+ except Exception:+ # A failed quota check must never kill a healthy run; the next+ # recheck (or the quota cron) is the backstop.+ workflow.logger.warning(+ "Self-driving quota recheck activity failed, continuing",+ extra={"run_id": self.context.run_id},+ )+ continue+ if quota_outcome == SELF_DRIVING_QUOTA_STOP_CHECKING:+ self._self_driving_quota_checks_active = False+ elif quota_outcome == SELF_DRIVING_QUOTA_CANCELLED:+ self._self_driving_quota_checks_active = False+ # The cancel path already signalled complete_task; set the fields+ # here as well so loop exit doesn't depend on signal delivery order.+ if not self._task_completed:+ self._completion_status = "cancelled"+ self._completion_error = (+ "Stopped automatically: the organization reached its "+ "self-driving pull request limit."+ )+ self._task_completed = Truecase TaskEvent.SANDBOX_GONE:self._mark_sandbox_gone()case TaskEvent.SIGNAL_RECEIVED:diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex 952c92e85a7a..8318bd5d7cee 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -825,3 +825,211 @@ class TestRecentWizardCloudRunTimes(TestCase):times = facade.recent_wizard_cloud_run_times(self.user.id, since)self.assertEqual(len(times), 2)self.assertEqual(times, sorted(times))+++class TestSelfDrivingQuotaFacadeGates(TestCase):+ organization: ClassVar[Organization]+ team: ClassVar[Team]+ user: ClassVar[User]++ @classmethod+ def setUpTestData(cls):+ cls.organization = Organization.objects.create(name="Quota Org")+ cls.team = Team.objects.create(organization=cls.organization, name="Quota Team")+ cls.user = User.objects.create(email="[email protected]", distinct_id="quota-facade-distinct")++ def _enforced_gate(self):+ from products.signals.backend.quota import SelfDrivingQuotaGate++ return patch(+ "products.signals.backend.quota.self_driving_quota_gate",+ return_value=SelfDrivingQuotaGate(limited=True, enforced=True),+ )++ def test_create_and_run_task_blocked_for_self_driving_origin_when_enforced(self):+ # The implementation task is the step that leads to the billable PR; over-quota teams+ # must not get one through the facade regardless of caller.+ from posthog.exceptions import QuotaLimitExceeded++ with (+ self._enforced_gate(),+ patch("products.signals.backend.quota.capture_signal_report_quota_paused") as capture_mock,+ self.assertRaises(QuotaLimitExceeded),+ ):+ facade.create_and_run_task(+ team=self.team,+ title="Implementation: t",+ description="d",+ origin_product=facade.TaskOriginProduct.SIGNAL_REPORT,+ user_id=self.user.id,+ repository="posthog/posthog",+ )+ self.assertFalse(Task.objects.filter(team=self.team).exists())+ # The facade gate keeps its own stage: its main caller is the auto-start pipeline, whose+ # over-quota hits must not pollute the manual-path (`manual_create`) telemetry bucket.+ self.assertEqual(capture_mock.call_args.kwargs["stage"], "task_create")+ self.assertTrue(capture_mock.call_args.kwargs["enforced"])++ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_create_and_run_task_allows_non_pr_sessions_when_enforced(self, _mock_workflow):+ # Research / repo-selection sessions create SIGNAL_REPORT tasks with create_pr=False;+ # they can never open the billable PR, and blocking them would hard-fail the pipeline+ # mid-run instead of letting the summary gates pause it.+ Integration.objects.create(team=self.team, kind="github", config={})+ with self._enforced_gate():+ created = facade.create_and_run_task(+ team=self.team,+ title="Research: t",+ description="d",+ origin_product=facade.TaskOriginProduct.SIGNAL_REPORT,+ user_id=self.user.id,+ repository="posthog/posthog",+ create_pr=False,+ )+ self.assertTrue(Task.objects.filter(id=created.task_id).exists())++ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_create_and_run_task_dark_launch_emits_without_blocking(self, _mock_workflow):+ # Limited without enforcement must create the task and still emit the would-block+ # event, or the manual gate is invisible during the dark launch.+ from products.signals.backend.quota import SelfDrivingQuotaGate++ Integration.objects.create(team=self.team, kind="github", config={})+ with (+ patch(+ "products.signals.backend.quota.self_driving_quota_gate",+ return_value=SelfDrivingQuotaGate(limited=True, enforced=False),+ ),+ patch("products.signals.backend.quota.capture_signal_report_quota_paused") as capture_mock,+ ):+ created = facade.create_and_run_task(+ team=self.team,+ title="Implementation: t",+ description="d",+ origin_product=facade.TaskOriginProduct.SIGNAL_REPORT,+ user_id=self.user.id,+ repository="posthog/posthog",+ )+ self.assertTrue(Task.objects.filter(id=created.task_id).exists())+ self.assertEqual(capture_mock.call_args.kwargs["stage"], "task_create")+ self.assertFalse(capture_mock.call_args.kwargs["enforced"])++ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_create_and_run_task_unaffected_for_other_origins_when_enforced(self, _mock_workflow):+ # The self-driving PR limit must never block user-created tasks.+ Integration.objects.create(team=self.team, kind="github", config={})+ with self._enforced_gate():+ created = facade.create_and_run_task(+ team=self.team,+ title="User task",+ description="d",+ origin_product=facade.TaskOriginProduct.USER_CREATED,+ user_id=self.user.id,+ repository="posthog/posthog",+ )+ self.assertTrue(Task.objects.filter(id=created.task_id).exists())++ @parameterized.expand([(None,), ("implementation",), ("discussion",)])+ def test_create_task_blocked_for_manual_report_creation_when_enforced(self, relationship):+ # The inbox "start work from report" path (write serializer binds `signal_report`).+ # Every relationship label is gated: the label is client-selected and manual tasks run+ # PR-capable by default, so a "discussion" label must not dodge the limit.+ from django.apps import apps++ from posthog.exceptions import QuotaLimitExceeded++ SignalReport = apps.get_model("signals", "SignalReport")+ report = SignalReport.objects.create(team=self.team, status="ready", title="t", summary="s")+ with (+ self._enforced_gate(),+ patch("products.signals.backend.quota.capture_signal_report_quota_paused") as capture_mock,+ self.assertRaises(QuotaLimitExceeded),+ ):+ facade.create_task(+ self.team.id,+ self.user.id,+ validated_data={+ "title": "Implementation: t",+ "description": "d",+ "origin_product": Task.OriginProduct.SIGNAL_REPORT,+ "signal_report": report,+ "signal_report_task_relationship": relationship,+ },+ )+ self.assertFalse(Task.objects.filter(team=self.team).exists())+ # Genuinely manual creations keep the `manual_create` stage, distinct from the facade+ # backstop's `task_create`.+ self.assertEqual(capture_mock.call_args.kwargs["stage"], "manual_create")+++class TestSelfDrivingQuotaRefreshDispatch(TestCase):+ organization: ClassVar[Organization]+ team: ClassVar[Team]+ user: ClassVar[User]++ @classmethod+ def setUpTestData(cls):+ cls.organization = Organization.objects.create(name="Refresh Org")+ cls.team = Team.objects.create(organization=cls.organization, name="Refresh Team")+ cls.user = User.objects.create(email="[email protected]", distinct_id="refresh-distinct")++ def _self_driving_run(self) -> TaskRun:+ task = Task.objects.create(+ team=self.team,+ title="Implementation: t",+ description="d",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ created_by=self.user,+ )+ return TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)++ @parameterized.expand(+ [+ # First PR URL on a self-driving-origin run is the billable moment: re-evaluate now.+ ("first_pr_dispatches", None, {"pr_url": "https://github.com/x/y/pull/1"}, True),+ # A repeat write for the same PR must not spam the quota task.+ (+ "repeat_write_skipped",+ "https://github.com/x/y/pull/1",+ {"pr_url": "https://github.com/x/y/pull/1"},+ False,+ ),+ # No PR in the output: nothing billable happened.+ ("no_pr_skipped", None, {"summary": "wip"}, False),+ # Billing only counts GitHub PR URLs; anything else must not enqueue a refresh.+ ("non_github_pr_url_skipped", None, {"pr_url": "https://evil.example/pr/1"}, False),+ ]+ )+ @patch("ee.tasks.quota_limiting.refresh_org_self_driving_quota_task")+ def test_refresh_dispatch_on_first_pr(self, _name, old_pr_url, output, expect_dispatch, task_mock):+ run = self._self_driving_run()+ run.output = output+ run.save(update_fields=["output"])+ with self.captureOnCommitCallbacks(execute=True):+ facade._refresh_self_driving_quota_for_pr(run, old_pr_url)+ self.assertEqual(task_mock.delay.call_count, 1 if expect_dispatch else 0)+ if expect_dispatch:+ self.assertEqual(task_mock.delay.call_args.args, (str(self.organization.id),))++ @patch("ee.tasks.quota_limiting.refresh_org_self_driving_quota_task")+ def test_refresh_swallows_lookup_failure(self, task_mock):+ # The refresh is best-effort (the quota cron is the backstop): a transient DB fault must+ # not propagate, or it would 500 an already-committed run write and abort the completion+ # signaling that follows at both call sites.+ run = self._self_driving_run()+ run.output = {"pr_url": "https://github.com/x/y/pull/1"}+ run.save(update_fields=["output"])+ with patch("products.tasks.backend.facade.api.Team.objects.filter", side_effect=RuntimeError("db down")):+ facade._refresh_self_driving_quota_for_pr(run, None)+ task_mock.delay.assert_not_called()++ @patch("ee.tasks.quota_limiting.refresh_org_self_driving_quota_task")+ def test_refresh_dispatch_skipped_for_other_origins(self, task_mock):+ run = self._self_driving_run()+ run.task.origin_product = Task.OriginProduct.USER_CREATED+ run.task.save(update_fields=["origin_product"])+ run.output = {"pr_url": "https://github.com/x/y/pull/1"}+ run.save(update_fields=["output"])+ with self.captureOnCommitCallbacks(execute=True):+ facade._refresh_self_driving_quota_for_pr(run, None)+ task_mock.delay.assert_not_called()diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.pyindex 079000a45dfc..c143b6a88b08 100644--- a/products/tasks/backend/webhooks.py+++ b/products/tasks/backend/webhooks.py@@ -242,6 +242,11 @@ def _record_run_pr_url(task_run: TaskRun, pr_url: str) -> None:post_pr_created_thread_update(task_run, pr_url)if not recorded:return+ from products.tasks.backend.facade.api import ( # noqa: PLC0415 — keep the heavy facade module off the webhook import path+ _refresh_self_driving_quota_for_pr,+ )++ _refresh_self_driving_quota_for_pr(task_run, None)# Publish-only (no append_log): the S3 run log has a live writer — the agent is streaming# log batches at exactly this moment — and append_log's read-modify-write would race it.# Tolerant: a stream hiccup must not fail the webhook; clients recover on refetch.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6065457531cb..14f0e92b040d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -65980,6 +65980,8 @@ export namespace Schemas {credited_credits: number;/** The organization's live billable signals credits for the current billing period, computed by the same rules as the nightly usage report — including PRs created today that billing hasn't recorded yet, and already excluding refund-excluded and billing-exempt reports. Take the max of this and billing's recorded usage for a live PR count that reacts to new PRs and same-day refunds immediately. */period_billable_credits: number;+ /** Whether autonomous PR generation is currently paused for this project because the organization is over its self-driving credits quota. Read from the quota limiter, so it reflects the same state the pipeline gates enforce. */+ quota_limited: boolean;}export interface SignalReportStateRequest {