Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): report and limit spend through usage reports (#123866)

Oliver Brownefa58a7550c3b
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.py
index f47fd0952179..80f416c81b7f 100644
--- a/ee/billing/billing_manager.py
+++ b/ee/billing/billing_manager.py
@@ -783,6 +783,7 @@ class BillingManager:
mcp_events=usage_summary.get("mcp_events", {}),
ai_credits=usage_summary.get("ai_credits", {}),
signals_credits=usage_summary.get("signals_credits", {}),
+ signals_spend_credits=usage_summary.get("signals_spend_credits", {}),
posthog_code_credits=usage_summary.get("posthog_code_credits", {}),
posthog_code_token_credits=usage_summary.get("posthog_code_token_credits", {}),
sandbox_compute_credits=usage_summary.get("sandbox_compute_credits", {}),
diff --git a/ee/billing/billing_types.py b/ee/billing/billing_types.py
index 8450f21ea93d..8b6bb52a4132 100644
--- a/ee/billing/billing_types.py
+++ b/ee/billing/billing_types.py
@@ -26,6 +26,7 @@ UsageType = Literal[
"rows_exported_in_period",
"ai_credits_used_in_period",
"signals_credits_used_in_period",
+ "signals_spend_credits_used_in_period",
"posthog_code_credits_used_in_period",
"posthog_code_token_credits_used_in_period",
"sandbox_compute_credits_used_in_period",
@@ -67,6 +68,7 @@ USAGE_TYPE_OPTIONS: tuple[UsageTypeOption, ...] = (
{"label": "Rows exported", "value": "rows_exported_in_period"},
{"label": "PostHog AI", "value": "ai_credits_used_in_period"},
{"label": "Self-driving inbox credits", "value": "signals_credits_used_in_period"},
+ {"label": "Self-driving spend credits", "value": "signals_spend_credits_used_in_period"},
{"label": "PostHog Desktop credits", "value": "posthog_code_credits_used_in_period"},
{"label": "PostHog Desktop token credits", "value": "posthog_code_token_credits_used_in_period"},
{"label": "Sandbox compute credits", "value": "sandbox_compute_credits_used_in_period"},
@@ -170,6 +172,7 @@ class BillingPeriod(TypedDict):
class UsageSummary(TypedDict):
limit: Optional[int]
usage: Optional[int]
+ billing_start_date: NotRequired[str]
class ProductFeature(TypedDict):
@@ -192,7 +195,7 @@ class CustomerInfo(TypedDict):
projected_total_amount_usd_with_limit_after_discount: Optional[str]
products: Optional[list[CustomerProduct]]
custom_limits_usd: Optional[dict[str, int]]
- usage_summary: Optional[dict[str, dict[str, Optional[int]]]]
+ usage_summary: Optional[dict[str, UsageSummary]]
free_trial_until: Optional[str]
discount_percent: Optional[int]
discount_amount_usd: Optional[str]
diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.py
index 2fbff3126764..f481313098c7 100644
--- a/ee/billing/quota_limiting.py
+++ b/ee/billing/quota_limiting.py
@@ -1,7 +1,7 @@
import copy
import json
from collections.abc import Callable, Collection, Iterable, Iterator, Mapping, Sequence
-from datetime import datetime, timedelta
+from datetime import date, datetime, timedelta
from enum import Enum
from functools import lru_cache, partial
from itertools import batched, groupby
@@ -90,6 +90,7 @@ class QuotaResource(Enum):
ROWS_EXPORTED = "rows_exported"
AI_CREDITS = "ai_credits"
SIGNALS_CREDITS = "signals_credits"
+ SIGNALS_SPEND_CREDITS = "signals_spend_credits"
POSTHOG_CODE_CREDITS = "posthog_code_credits"
WORKFLOW_EMAILS = "workflow_emails"
WORKFLOW_PUSH = "workflow_push"
@@ -104,6 +105,14 @@ class QuotaLimitingCaches(Enum):
QUOTA_LIMITING_SUSPENDED_KEY = "@posthog/quota-limiting-suspended/"
+def self_driving_quota_resource(organization: Organization) -> QuotaResource:
+ summary = (organization.usage or {}).get("signals_spend_credits") or {}
+ cutoff = summary.get("billing_start_date")
+ if cutoff is not None and date.fromisoformat(cutoff) <= timezone.now().date():
+ return QuotaResource.SIGNALS_SPEND_CREDITS
+ return QuotaResource.SIGNALS_CREDITS
+
+
OVERAGE_BUFFER = {
QuotaResource.EVENTS: 0,
QuotaResource.EXCEPTIONS: 0,
@@ -118,6 +127,7 @@ OVERAGE_BUFFER = {
QuotaResource.ROWS_EXPORTED: 0,
QuotaResource.AI_CREDITS: 0,
QuotaResource.SIGNALS_CREDITS: 0,
+ QuotaResource.SIGNALS_SPEND_CREDITS: 0,
QuotaResource.POSTHOG_CODE_CREDITS: 0,
QuotaResource.WORKFLOW_EMAILS: 0,
QuotaResource.WORKFLOW_PUSH: 0,
@@ -130,6 +140,7 @@ OVERAGE_BUFFER = {
GRACE_PERIOD_EXEMPT_RESOURCES: set[QuotaResource] = {
QuotaResource.AI_CREDITS,
QuotaResource.SIGNALS_CREDITS,
+ QuotaResource.SIGNALS_SPEND_CREDITS,
QuotaResource.REPLAY_VISION_CREDITS,
QuotaResource.POSTHOG_CODE_CREDITS,
}
@@ -150,6 +161,7 @@ class UsageCounters(TypedDict):
rows_exported: int
ai_credits: int
signals_credits: int
+ signals_spend_credits: int
posthog_code_credits: int
posthog_code_token_credits: int
sandbox_compute_credits: int
@@ -464,6 +476,9 @@ def org_quota_limited_until(
todays_usage = summary.get("todays_usage") or 0
current_usage = usage + todays_usage
limit = summary.get("limit")
+ if resource in {QuotaResource.SIGNALS_CREDITS, QuotaResource.SIGNALS_SPEND_CREDITS}:
+ if resource != self_driving_quota_resource(organization):
+ limit = None
quota_limited_until = summary.get("quota_limited_until", None)
quota_limiting_suspended_until = summary.get("quota_limiting_suspended_until", None)
@@ -497,7 +512,10 @@ def org_quota_limited_until(
resource,
limit is not None and current_usage >= limit + OVERAGE_BUFFER[resource],
)
- if resource == QuotaResource.SIGNALS_CREDITS and current_usage - refund_offset < limit:
+ if (
+ resource in {QuotaResource.SIGNALS_CREDITS, QuotaResource.SIGNALS_SPEND_CREDITS}
+ and current_usage - refund_offset < limit
+ ):
active_persisted_limit = quota_limited_until is not None and quota_limited_until > timezone.now().timestamp()
if team_tokens is None and previously_quota_limited_team_tokens and not active_persisted_limit:
team_tokens = get_team_attribute_by_quota_resource(organization)
@@ -511,7 +529,10 @@ def org_quota_limited_until(
period_end = dateutil.parser.isoparse(organization.usage["period"][1])
try:
period_usage = get_self_driving_credits_used_in_period_for_org(
- organization.id, period_start, period_end
+ organization.id,
+ period_start,
+ period_end,
+ spend_billing=resource == QuotaResource.SIGNALS_SPEND_CREDITS,
)
except Exception as error:
capture_exception(error, {"organization_id": str(organization.id)})
@@ -1287,6 +1308,7 @@ def _aggregate_quota_usage(
mcp_events=all_data["teams_with_mcp_event_count_in_period"].get(team.id, 0),
ai_credits=all_data["teams_with_ai_credits_used_in_period"].get(team.id, 0),
signals_credits=all_data["teams_with_signals_credits_used_in_period"].get(team.id, 0),
+ signals_spend_credits=all_data["teams_with_signals_spend_credits_used_in_period"].get(team.id, 0),
posthog_code_credits=all_data["teams_with_posthog_code_credits_used_in_period"].get(team.id, 0),
posthog_code_token_credits=all_data["teams_with_posthog_code_token_credits_used_in_period"].get(team.id, 0),
sandbox_compute_credits=all_data["teams_with_sandbox_compute_credits_used_in_period"].get(team.id, 0),
@@ -1354,13 +1376,7 @@ def update_all_orgs_billing_quotas(
dry_run: bool = False,
progress_callback: Callable[[str, str, str], None] | None = None,
) -> QuotaLimitingRunResult:
- """
- This is called on a cron job every 30 minutes to update all orgs with their quotas.
- Specifically it's update quota_limited_until and quota_limiting_suspended_until in their usage
- field on the Organization model.
-
- # Start and end of the current day
- """
+ """Refresh organization quotas every 15 minutes, including today's usage."""
total_start = time()
period = get_current_day()
service = UsageCounterService()
@@ -1386,6 +1402,7 @@ def update_all_orgs_billing_quotas(
UsageCounter.LOGS_BYTES,
UsageCounter.AI_CREDITS,
UsageCounter.SIGNALS_CREDITS,
+ UsageCounter.SIGNALS_SPEND_CREDITS,
UsageCounter.POSTHOG_CODE_CREDITS,
UsageCounter.SANDBOX_COMPUTE_CREDITS,
UsageCounter.REPLAY_VISION_CREDITS,
@@ -1436,6 +1453,9 @@ def update_all_orgs_billing_quotas(
"teams_with_mcp_event_count_in_period": convert_team_usage_rows_to_dict(mcp_event_counts),
"teams_with_ai_credits_used_in_period": dict(counter_report.counts[UsageCounter.AI_CREDITS]),
"teams_with_signals_credits_used_in_period": dict(counter_report.counts[UsageCounter.SIGNALS_CREDITS]),
+ "teams_with_signals_spend_credits_used_in_period": dict(
+ counter_report.counts[UsageCounter.SIGNALS_SPEND_CREDITS]
+ ),
"teams_with_posthog_code_credits_used_in_period": {
team_id: combine_posthog_code_credits(token_credits.get(team_id, 0), compute_credits.get(team_id, 0))
for team_id in token_credits.keys() | compute_credits.keys()
diff --git a/ee/billing/test/test_billing_manager.py b/ee/billing/test/test_billing_manager.py
index 63e16e41e63a..3cdeca9cf6f4 100644
--- a/ee/billing/test/test_billing_manager.py
+++ b/ee/billing/test/test_billing_manager.py
@@ -446,6 +446,7 @@ class TestBillingManager(BaseTest):
"mcp_events": {"usage": 30, "limit": 500, "todays_usage": 0},
"ai_credits": {"usage": 1200, "limit": 20000, "todays_usage": 150},
"signals_credits": {},
+ "signals_spend_credits": {},
"replay_vision_credits": {},
"posthog_code_credits": {},
"workflow_emails": {"usage": 100, "limit": 10000, "todays_usage": 10},
diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.py
index 2485eecb9cb9..f5dc985689f6 100644
--- a/ee/billing/test/test_quota_limiting.py
+++ b/ee/billing/test/test_quota_limiting.py
@@ -273,7 +273,7 @@ class TestQuotaLimiting(BaseTest):
self.organization.save()
flush_persons_and_events()
- with self.assertNumQueries(FuzzyInt(4, 11)):
+ with self.assertNumQueries(FuzzyInt(4, 13)):
result = self._run_quota_limiting()
assert patch_capture.call_count == 0 # No events should be captured since org won't be limited
assert result.quota_limited_orgs["events"] == {}
@@ -2515,6 +2515,7 @@ def _full_usage_counters(**overrides: int) -> UsageCounters:
mcp_events=0,
ai_credits=0,
signals_credits=0,
+ signals_spend_credits=0,
posthog_code_credits=0,
posthog_code_token_credits=0,
sandbox_compute_credits=0,
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 4d65ff9e5897..2d3e035ee98b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -12710,6 +12710,10 @@ snapshots:
hash: v1.k794b7964.5d3b14a70ad66dedc5721197efa5c943c48fc310a9478e0c6503d83512a54e4e.ngvR1B3bnYaXytKq3W2S1ZkF6WGbJG_ckRXFK-UDhTo
scenes-app-inbox-scene--settings--light:
hash: v1.k794b7964.72906ad9972deb6b3c3492dfd2f655779c81c807116713eefa82b5ff46adc1ae.mnAqR8rp5r7-h801X12KN_IpMZSXFLHI4eqOjyW0xVI
+ scenes-app-inbox-scene--settings-with-spend-billing--dark:
+ hash: v1.k794b7964.0050df5c3012833eead1b81a2123a56b477fe74fb6b46b5783214710ee5fb544.p3o_gkqaXVdjA1w3Tui2NnurpXCqich7ZgmEBB9l_o4
+ scenes-app-inbox-scene--settings-with-spend-billing--light:
+ hash: v1.k794b7964.56f690456ad3301907844cfe39b2849b7325345f5297bf3c7b0d471f10e8f567.AAKoUpX188aeXsLH6DR7djCvzFjgFy3YKlSD-IMnrqo
scenes-app-inbox-scene--triage--dark:
hash: v1.k794b7964.77e43b36fdcd81befecf4de80e489050f525840924ec6ddef37c23a9179dbe8a.B3qkZFYBncFaPn2EBg4cBoYu_LIwW29imNwBdLXF5eo
scenes-app-inbox-scene--triage--light:
diff --git a/frontend/src/scenes/billing/constants.ts b/frontend/src/scenes/billing/constants.ts
index 2915c8dcb13e..e9219918c453 100644
--- a/frontend/src/scenes/billing/constants.ts
+++ b/frontend/src/scenes/billing/constants.ts
@@ -51,6 +51,7 @@ export const SPEND_TYPES = [
{ label: 'Rows exported', value: 'rows_exported_in_period' },
{ label: 'PostHog AI', value: 'ai_credits_used_in_period' },
{ label: 'Self-driving inbox credits', value: 'signals_credits_used_in_period' },
+ { label: 'Self-driving spend credits', value: 'signals_spend_credits_used_in_period' },
{ label: 'PostHog Desktop credits', value: 'posthog_code_credits_used_in_period' },
{ label: 'Replay vision credits', value: 'replay_vision_credits_used_in_period' },
{ label: 'Workflow emails', value: 'workflow_emails_sent_in_period' },
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index cd0e2269fa12..63e5384b91cf 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2453,7 +2453,15 @@ export interface BillingType {
projected_total_amount_usd_with_limit?: string
projected_total_amount_usd_with_limit_after_discount?: string
products: BillingProductV2Type[]
- usage_summary?: Record<string, { usage?: number | null; limit?: number | null; todays_usage?: number | null }>
+ usage_summary?: Record<
+ string,
+ {
+ usage?: number | null
+ limit?: number | null
+ todays_usage?: number | null
+ billing_start_date?: string
+ }
+ >
custom_limits_usd?: {
[key: string]: number | null
diff --git a/posthog/models/organization.py b/posthog/models/organization.py
index 029199085eb6..234628e3f0e0 100644
--- a/posthog/models/organization.py
+++ b/posthog/models/organization.py
@@ -2,7 +2,7 @@ import sys
from collections.abc import Collection
from datetime import datetime, timedelta
from functools import cache as functools_cache
-from typing import TYPE_CHECKING, Any, Literal, Optional, Self, TypedDict, Union
+from typing import TYPE_CHECKING, Any, Literal, NotRequired, Optional, Self, TypedDict, Union
from django.conf import settings
from django.contrib.postgres.fields import ArrayField
@@ -59,6 +59,7 @@ class OrganizationUsageInfo(TypedDict):
mcp_events: OrganizationUsageResource | None
ai_credits: OrganizationUsageResource | None
signals_credits: OrganizationUsageResource | None
+ signals_spend_credits: NotRequired[OrganizationUsageResource | None]
posthog_code_credits: OrganizationUsageResource | None
posthog_code_token_credits: OrganizationUsageResource | None
sandbox_compute_credits: OrganizationUsageResource | None
diff --git a/posthog/tasks/test/test_usage_counters.py b/posthog/tasks/test/test_usage_counters.py
index 003d65c65e58..2e0100343494 100644
--- a/posthog/tasks/test/test_usage_counters.py
+++ b/posthog/tasks/test/test_usage_counters.py
@@ -150,6 +150,7 @@ class TestUsageCounterReport(SimpleTestCase):
"get_teams_with_logs_bytes_in_period": self.legacy[UsageCounter.LOGS_BYTES],
"get_teams_with_ai_credits_used_in_period": self.legacy[UsageCounter.AI_CREDITS],
"get_teams_with_signals_credits_used_in_period": self.legacy[UsageCounter.SIGNALS_CREDITS],
+ "get_teams_with_signals_spend_credits_used_in_period": self.legacy[UsageCounter.SIGNALS_SPEND_CREDITS],
"get_teams_with_posthog_code_credits_used_in_period": self.legacy[UsageCounter.POSTHOG_CODE_CREDITS],
"get_teams_with_replay_vision_credits_used_in_period": self.legacy[UsageCounter.REPLAY_VISION_CREDITS],
"get_teams_with_billable_event_count_in_period": self.events,
@@ -631,6 +632,7 @@ class TestUsageCounterReport(SimpleTestCase):
UsageCounter.LOGS_RETENTION_BYTE_DAYS,
UsageCounter.AI_CREDITS,
UsageCounter.SIGNALS_CREDITS,
+ UsageCounter.SIGNALS_SPEND_CREDITS,
UsageCounter.POSTHOG_CODE_CREDITS,
UsageCounter.SANDBOX_COMPUTE_CREDITS,
UsageCounter.REPLAY_VISION_CREDITS,
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index 210fc6e14ee2..c85b0d2bd5a3 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -5210,10 +5210,13 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
"""Signals credits are a flat charge per report whose implementation shipped a PR (Postgres path)."""
from django.apps import apps
- from posthog.tasks.usage_report import get_teams_with_signals_credits_used_in_period
+ from posthog.tasks.usage_report import (
+ get_teams_with_signals_credits_used_in_period,
+ get_teams_with_signals_spend_credits_used_in_period,
+ )
from products.signals.backend.artefact_schemas import TASK_RUN_TYPE_IMPLEMENTATION
- from products.signals.backend.models import SignalReport, SignalReportTask
+ from products.signals.backend.models import SignalReport, SignalReportTask, SignalSpend
# `products.tasks` is isolated; reach its models via the app registry, not a cross-boundary import.
Task = apps.get_model("tasks", "Task")
@@ -5247,6 +5250,22 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
self.assertEqual(result, [(team.id, 1500)])
+ SignalSpend.objects.for_team(team.id).create(
+ team=team,
+ kind=SignalSpend.Kind.AD_HOC,
+ signal_id=uuid4(),
+ finalized_at=period.start,
+ spend=15,
+ usage_billing=True,
+ )
+ SignalReport.objects.filter(id=report.id).update(created_at=period.start - relativedelta(days=1))
+ # Changing the plan does not reclassify existing work.
+ organization = team.organization
+ organization.usage = {"signals_spend_credits": {"billing_start_date": period.start.date().isoformat()}}
+ organization.save(update_fields=["usage"])
+ self.assertEqual(get_teams_with_signals_credits_used_in_period(period.start, period.end), [(team.id, 1500)])
+ self.assertEqual(get_teams_with_signals_spend_credits_used_in_period(period.start, period.end), [(team.id, 15)])
+
def test_self_driving_credits_for_orgs_sum_each_orgs_teams(self) -> None:
org_a = Organization.objects.create(name="Org A")
org_b = Organization.objects.create(name="Org B")
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index f7c9d01aec2c..2ffb73e4198f 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -80,7 +80,13 @@ from products.replay_vision.backend.billing import (
)
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.quota import unreported_spend_by_org
-from products.signals.backend.facade.billing import credited_refund_credits_for_org, signals_billing_credits_by_team
+from products.signals.backend.facade.billing import (
+ TeamSignalsCredits,
+ credited_refund_credits_for_org,
+ signals_billing_credits_by_team,
+ signals_spend_billing_credits_by_team,
+ signals_spend_quota_credits_by_team,
+)
from products.surveys.backend.models import Survey
from products.surveys.backend.util import (
SurveyEventProperties,
@@ -330,6 +336,7 @@ class UsageReportCounters:
# Signals Billing Credits (flat credits per report whose implementation shipped a PR)
signals_credits_used_in_period: int
+ signals_spend_credits_used_in_period: int
# PostHog Desktop Billing Credits
posthog_code_credits_used_in_period: int
@@ -2197,6 +2204,20 @@ def get_teams_with_signals_credits_used_in_period(
return [(row.team_id, row.credits) for row in signals_billing_credits_by_team(begin, end)]
+@timed_log()
+def get_teams_with_signals_spend_credits_used_in_period(
+ begin: datetime, end: datetime
+) -> list[tuple[int, int]]: # nosemgrep: tuple-return-prefer-dataclass -- counter API rows
+ return [(row.team_id, row.credits) for row in signals_spend_billing_credits_by_team(begin, end)]
+
+
+@timed_log()
+def get_teams_with_signals_spend_quota_credits_used_in_period(
+ begin: datetime, end: datetime
+) -> list[TeamSignalsCredits]:
+ return signals_spend_quota_credits_by_team(begin, end)
+
+
def get_signals_credited_refund_credits_for_org(
organization_id: str | uuid.UUID, begin: datetime, end: datetime
) -> int:
@@ -2227,7 +2248,7 @@ def get_self_driving_credits_used_in_period_for_orgs(
def get_self_driving_credits_used_in_period_for_org(
- organization_id: str | uuid.UUID, begin: datetime, end: datetime
+ organization_id: str | uuid.UUID, begin: datetime, end: datetime, *, spend_billing: bool = False
) -> int:
"""Live self-driving credits used in `[begin, end)` across one org's teams.
@@ -2235,7 +2256,8 @@ def get_self_driving_credits_used_in_period_for_org(
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(row.credits for row in signals_billing_credits_by_team(begin, end, organization_id=organization_id))
+ counter = signals_spend_quota_credits_by_team if spend_billing else signals_billing_credits_by_team
+ return sum(row.credits for row in counter(begin, end, organization_id=organization_id))
@timed_log()
@@ -2787,7 +2809,7 @@ def get_teams_with_logs_retention_byte_days_in_period(
def get_teams_with_logs_records_in_period(
begin: datetime,
end: datetime,
-) -> list[tuple[int, int]]:
+) -> TeamUsageRows:
with tags_context(product=Product.LOGS, feature=Feature.USAGE_REPORT):
return sync_execute(
"""
@@ -3117,6 +3139,7 @@ def has_non_zero_usage(report: UsageReportCounters) -> bool:
or report.business_knowledge_queries_in_period > 0
or report.ai_credits_used_in_period > 0
or report.signals_credits_used_in_period > 0
+ or report.signals_spend_credits_used_in_period > 0
or report.posthog_code_credits_used_in_period > 0
or report.task_sandbox_seconds_in_period > 0
or report.logs_bytes_in_period > 0
@@ -3704,6 +3727,9 @@ def _get_team_report(all_data: dict[str, Any], team: Team) -> UsageReportCounter
),
ai_credits_used_in_period=all_data["teams_with_ai_credits_used_in_period"].get(team.id, 0),
signals_credits_used_in_period=all_data["teams_with_signals_credits_used_in_period"].get(team.id, 0),
+ signals_spend_credits_used_in_period=all_data["teams_with_signals_spend_credits_used_in_period"].get(
+ team.id, 0
+ ),
posthog_code_credits_used_in_period=combine_posthog_code_credits(
all_data["teams_with_posthog_code_credits_used_in_period"].get(team.id, 0),
all_data["teams_with_sandbox_compute_credits_used_in_period"].get(team.id, 0),
diff --git a/posthog/temporal/tests/usage_report/test_aggregate_activity.py b/posthog/temporal/tests/usage_report/test_aggregate_activity.py
index a508c29e803d..44f235408ff4 100644
--- a/posthog/temporal/tests/usage_report/test_aggregate_activity.py
+++ b/posthog/temporal/tests/usage_report/test_aggregate_activity.py
@@ -12,6 +12,7 @@ import gzip
import json
import uuid
import asyncio
+from datetime import timedelta
from threading import Event
from typing import Any
@@ -19,6 +20,7 @@ import pytest
from unittest.mock import patch
from asgiref.sync import sync_to_async
+from pydantic import TypeAdapter
from posthog.models import Organization, Team
from posthog.storage import object_storage
@@ -28,6 +30,8 @@ from posthog.temporal.usage_report.activities import aggregate_and_chunk_org_rep
from posthog.temporal.usage_report.queries import QUERIES, QUERY_INDEX
from posthog.temporal.usage_report.storage import queries_key, write_json
from posthog.temporal.usage_report.types import AggregateInputs, RunQueryToS3Result, WorkflowContext
+from posthog.usage_counters import UsageCounter, UsageCounterMode, UsageCounterPlan, UsageCounterReport
+from posthog.utils import DayRange
from products.ai_observability.backend.models.offline_evaluations import OfflineEvaluationUsageLedger
@@ -486,3 +490,53 @@ async def test_aggregate_filters_by_organization_ids(minio_workflow_ctx: Workflo
assert result.total_orgs == 1
rows = _read_jsonl_gz(result.chunk_keys[0])
assert {row["organization_id"] for row in rows} == {str(org_a.id)}
+
+
[email protected]_db(transaction=True)
[email protected]("version", ["old_queries", "old_counter_plan", "new_counter_plan"])
+async def test_aggregate_accepts_saved_inputs_before_signals_spend(
+ minio_workflow_ctx: WorkflowContext, activity_environment, version: str
+) -> None:
+ org = await _make_org("Historical usage")
+ team = await _make_team(org, "Team")
+ ctx = minio_workflow_ctx.model_copy(update={"organization_ids": [str(org.id)]})
+ query_results = _seed_query_results(ctx, team.id, -1)
+ query_results = [
+ result for result in query_results if result.query_name != UsageCounter.SIGNALS_SPEND_CREDITS.value
+ ]
+ counter_result = None
+ expected_spend = 0
+ if version != "old_queries":
+ modes = {UsageCounter.EVENTS: UsageCounterMode.LEGACY}
+ counts = {UsageCounter.EVENTS.value: [(team.id, 100)]}
+ if version == "new_counter_plan":
+ modes[UsageCounter.SIGNALS_SPEND_CREDITS] = UsageCounterMode.LEGACY
+ counts[UsageCounter.SIGNALS_SPEND_CREDITS.value] = [(team.id, 17)]
+ expected_spend = 17
+ ctx.usage_counter_plan = UsageCounterPlan(
+ period=DayRange(start=ctx.period_start, end=ctx.period_end + timedelta(microseconds=1)),
+ caller="usage_reports_v2",
+ modes=modes,
+ complete=True,
+ )
+ query_results = [
+ result for result in query_results if result.query_name not in ctx.usage_counter_plan.query_names
+ ]
+ key = queries_key(ctx, "usage_counters")
+ write_json(key, TypeAdapter(UsageCounterReport).dump_python(UsageCounterReport(counts=counts), mode="json"))
+ counter_result = RunQueryToS3Result(query_name="usage_counters", s3_key=key, duration_ms=1)
+
+ with patch("posthog.temporal.usage_report.activities.get_instance_metadata", return_value=_instance_metadata()):
+ result = await activity_environment.run(
+ aggregate_and_chunk_org_reports,
+ AggregateInputs(ctx=ctx, query_results=query_results, counter_result=counter_result),
+ )
+
+ assert _read_json(result.manifest_key)["total_orgs"] == 1
+ rows = _read_jsonl_gz(result.chunk_keys[0])
+ assert len(rows) == 1
+ report = rows[0]["usage_report"]
+ assert report["event_count_in_period"] == 100
+ assert report["signals_spend_credits_used_in_period"] == expected_spend
+ assert report["teams"][str(team.id)]["signals_spend_credits_used_in_period"] == expected_spend
diff --git a/posthog/temporal/tests/usage_report/test_aggregator.py b/posthog/temporal/tests/usage_report/test_aggregator.py
index 90b01a7749ad..49c268ffaaa4 100644
--- a/posthog/temporal/tests/usage_report/test_aggregator.py
+++ b/posthog/temporal/tests/usage_report/test_aggregator.py
@@ -31,6 +31,7 @@ from posthog.temporal.usage_report.aggregator import (
add_pre_mcp_event_count_patch_defaults,
add_pre_replay_vision_spend_projection_patch_defaults,
add_pre_sandbox_compute_patch_defaults,
+ add_pre_signals_spend_patch_defaults,
add_pre_transactional_emails_patch_defaults,
build_manifest,
iter_chunk_lines,
@@ -46,9 +47,11 @@ from posthog.temporal.usage_report.types import (
WorkflowContext,
)
from posthog.usage_counters import (
+ UsageCounter,
UsageCounterComparison,
UsageCounterComparisonRows,
UsageCounterMode,
+ UsageCounterPlan,
UsageCounterReport,
UsageCounterService,
)
@@ -543,3 +546,15 @@ def test_failed_chunk_run_does_not_publish_manifest(failure: str, report_count:
check_cancelled=check_cancelled,
)
assert not any(key.endswith("manifest.json") for key in written)
+
+
+def test_signals_spend_default_does_not_hide_a_missing_planned_counter() -> None:
+ ctx = _ctx()
+ ctx.usage_counter_plan = UsageCounterPlan(
+ period=DayRange(start=ctx.period_start, end=ctx.period_end),
+ caller="usage_reports_v2",
+ modes={UsageCounter.SIGNALS_SPEND_CREDITS: UsageCounterMode.LEGACY},
+ )
+ all_data: dict[str, dict[int, int]] = {}
+ add_pre_signals_spend_patch_defaults(all_data, AggregateInputs(ctx=ctx, query_results=[]))
+ assert UsageCounter.SIGNALS_SPEND_CREDITS.value not in all_data
diff --git a/posthog/temporal/tests/usage_report/test_parity.py b/posthog/temporal/tests/usage_report/test_parity.py
index aed181f6894a..6c95ad1e1618 100644
--- a/posthog/temporal/tests/usage_report/test_parity.py
+++ b/posthog/temporal/tests/usage_report/test_parity.py
@@ -297,6 +297,7 @@ def test_end_to_end_parity_celery_task_vs_temporal_activity(
(UsageCounter.LOGS_RETENTION_BYTE_DAYS, "get_teams_with_logs_retention_byte_days_in_period"),
(UsageCounter.AI_CREDITS, "get_teams_with_ai_credits_used_in_period"),
(UsageCounter.SIGNALS_CREDITS, "get_teams_with_signals_credits_used_in_period"),
+ (UsageCounter.SIGNALS_SPEND_CREDITS, "get_teams_with_signals_spend_credits_used_in_period"),
(UsageCounter.POSTHOG_CODE_CREDITS, "get_teams_with_posthog_code_credits_used_in_period"),
(UsageCounter.REPLAY_VISION_CREDITS, "get_teams_with_replay_vision_credits_used_in_period"),
(UsageCounter.EVENTS, "get_teams_with_billable_event_count_in_period"),
diff --git a/posthog/temporal/tests/usage_report/test_workflow.py b/posthog/temporal/tests/usage_report/test_workflow.py
index 3bb690b7f0ac..2dbcd98b5af3 100644
--- a/posthog/temporal/tests/usage_report/test_workflow.py
+++ b/posthog/temporal/tests/usage_report/test_workflow.py
@@ -10,6 +10,7 @@ import asyncio
import logging
from collections.abc import Callable
from contextlib import nullcontext
+from dataclasses import replace
from datetime import UTC, datetime, timedelta
import pytest
@@ -55,6 +56,8 @@ from posthog.temporal.usage_report.workflow import (
QUERY_CONCURRENCY,
REPLAY_VISION_SPEND_PROJECTION_QUERY_NAME,
SANDBOX_COMPUTE_QUERY_NAME,
+ SIGNALS_SPEND_QUERY_NAME,
+ SIGNALS_SPEND_QUERY_PATCH_ID,
TRANSACTIONAL_EMAILS_QUERY_NAME,
USAGE_COUNTER_SERVICE_PATCH_ID,
RunUsageReportsWorkflow,
@@ -64,6 +67,7 @@ from posthog.temporal.usage_report.workflow import (
_queries_for_mcp_event_count_patch,
_queries_for_replay_vision_spend_projection_patch,
_queries_for_sandbox_compute_patch,
+ _queries_for_signals_spend_patch,
_queries_for_transactional_emails_patch,
build_context,
)
@@ -87,6 +91,7 @@ def test_sandbox_compute_query_is_versioned_for_existing_histories() -> None:
("logs_distinct_patterns", _queries_for_logs_distinct_patterns_patch, LOGS_DISTINCT_PATTERNS_QUERY_NAME),
("transactional_emails", _queries_for_transactional_emails_patch, TRANSACTIONAL_EMAILS_QUERY_NAME),
("mcp_event_count", _queries_for_mcp_event_count_patch, MCP_EVENT_COUNT_QUERY_NAME),
+ ("signals_spend", _queries_for_signals_spend_patch, SIGNALS_SPEND_QUERY_NAME),
(
"replay_vision_spend_projection",
_queries_for_replay_vision_spend_projection_patch,
@@ -188,6 +193,7 @@ async def test_workflow_rejects_invalid_inputs_before_running_queries(
"concurrency",
"serial_counters",
"counter_query_failure",
+ "pre_signals_spend",
"pre_aggregation_queue",
"aggregation_queue",
],
@@ -216,6 +222,8 @@ async def test_workflow_runs_query_then_aggregate(report_behavior: str, caplog:
max_active = 0
max_active_counters = 0
fails = report_behavior in {"activity_failure", "query_failure", "pre_patch_query_failure", "counter_query_failure"}
+ pre_signals_spend = report_behavior == "pre_signals_spend"
+ recording_queries = [spec for spec in QUERIES if not pre_signals_spend or spec.name != SIGNALS_SPEND_QUERY_NAME]
pre_patch = report_behavior.startswith("pre_patch")
legacy_aggregation_queue = pre_patch or report_behavior == "pre_aggregation_queue"
parallel_counters = not pre_patch and report_behavior != "serial_counters"
@@ -237,6 +245,15 @@ async def test_workflow_runs_query_then_aggregate(report_behavior: str, caplog:
if report_behavior == "flag_failure":
flag.side_effect = RuntimeError("flag service unavailable")
plan = await plan_usage_counters(ctx)
+ if pre_signals_spend:
+ plan = replace(
+ plan,
+ modes={
+ counter: mode
+ for counter, mode in plan.modes.items()
+ if counter != UsageCounter.SIGNALS_SPEND_CREDITS
+ },
+ )
plans.append(plan)
return plan
@@ -351,11 +368,13 @@ async def test_workflow_runs_query_then_aggregate(report_behavior: str, caplog:
if (pre_patch and name == USAGE_COUNTER_SERVICE_PATCH_ID)
or (report_behavior == "serial_counters" and name == PARALLEL_COUNTER_QUERIES_PATCH_ID)
or (legacy_aggregation_queue and name == AGGREGATION_QUEUE_PATCH_ID)
+ or (pre_signals_spend and name == SIGNALS_SPEND_QUERY_PATCH_ID)
else patched(name)
),
)
- if legacy_aggregation_queue or report_behavior == "serial_counters"
- else nullcontext()
+ if legacy_aggregation_queue or report_behavior == "serial_counters" or pre_signals_spend
+ else nullcontext(),
+ patch("posthog.temporal.usage_report.workflow.QUERIES", recording_queries),
):
try:
with pytest.raises(WorkflowFailureError) if fails else nullcontext():
@@ -433,7 +452,7 @@ async def test_workflow_runs_query_then_aggregate(report_behavior: str, caplog:
scheduled_summaries[attrs.activity_id] = decoded_summary
counter_names = plans[0].query_names if plans else set()
- expected_names = [spec.name for spec in QUERIES if spec.name not in counter_names]
+ expected_names = [spec.name for spec in recording_queries if spec.name not in counter_names]
with override_settings(USAGE_REPORT_AGGREGATION_TASK_QUEUE=aggregation_queue):
await Replayer(
workflows=[RunUsageReportsWorkflow],
@@ -457,6 +476,10 @@ async def test_workflow_runs_query_then_aggregate(report_behavior: str, caplog:
expected_counters = plans[0].legacy_counters if parallel_counters else []
assert set(seen_counters) == set(expected_counters)
assert len(seen_counters) == len(expected_counters)
+ if pre_signals_spend:
+ assert SIGNALS_SPEND_QUERY_NAME not in seen_query_names
+ assert UsageCounter.SIGNALS_SPEND_CREDITS not in seen_counters
+ assert UsageCounter.SIGNALS_SPEND_CREDITS not in plans[0].modes
if report_behavior == "concurrency":
assert max_active == QUERY_CONCURRENCY
assert max_active_counters == QUERY_CONCURRENCY
@@ -480,6 +503,7 @@ async def test_workflow_runs_query_then_aggregate(report_behavior: str, caplog:
counter: expected_mode if counter in COUNTER_FLAG_NAMES else UsageCounterMode.LEGACY
for counter in UsageCounter
if counter not in PLAN_DEFERRED_COUNTERS
+ and (not pre_signals_spend or counter != UsageCounter.SIGNALS_SPEND_CREDITS)
}
assert aggregate_payloads[0].ctx.usage_counter_plan == (plans[0] if plans else None)
diff --git a/posthog/temporal/usage_report/activities.py b/posthog/temporal/usage_report/activities.py
index 5fc158f11489..d2e0b38aa680 100644
--- a/posthog/temporal/usage_report/activities.py
+++ b/posthog/temporal/usage_report/activities.py
@@ -32,6 +32,7 @@ from posthog.temporal.usage_report.aggregator import (
add_pre_mcp_event_count_patch_defaults,
add_pre_replay_vision_spend_projection_patch_defaults,
add_pre_sandbox_compute_patch_defaults,
+ add_pre_signals_spend_patch_defaults,
add_pre_transactional_emails_patch_defaults,
get_org_user_counts,
iter_org_reports,
@@ -261,6 +262,7 @@ async def aggregate_and_chunk_org_reports(inputs: AggregateInputs) -> AggregateR
check_cancelled()
counter_report = load_usage_counter_report(inputs)
all_data.update({field: dict(rows) for field, rows in counter_report.counts.items()})
+ add_pre_signals_spend_patch_defaults(all_data, inputs)
check_cancelled()
org_user_counts = get_org_user_counts()
instance_metadata = get_instance_metadata(
diff --git a/posthog/temporal/usage_report/aggregator.py b/posthog/temporal/usage_report/aggregator.py
index b195c8973082..04d362f279e9 100644
--- a/posthog/temporal/usage_report/aggregator.py
+++ b/posthog/temporal/usage_report/aggregator.py
@@ -48,7 +48,7 @@ from posthog.temporal.usage_report.types import (
RunQueryToS3Result,
WorkflowContext,
)
-from posthog.usage_counters import UsageCounterReport
+from posthog.usage_counters import UsageCounter, UsageCounterReport
from products.ai_observability.backend.offline_evaluation_billing import get_offline_evaluation_usage
@@ -140,6 +140,17 @@ def add_pre_replay_vision_spend_projection_patch_defaults(
all_data[key] = {}
+def add_pre_signals_spend_patch_defaults(all_data: dict[str, dict[int, int]], inputs: AggregateInputs) -> None:
+ counter = UsageCounter.SIGNALS_SPEND_CREDITS
+ plan = inputs.ctx.usage_counter_plan
+ if plan is not None and counter in plan.modes:
+ return
+ if any(result.query_name == counter.value for result in inputs.query_results):
+ return
+ # Inputs saved before the counter existed remain valid after a deployment.
+ all_data.setdefault(counter.value, {})
+
+
def add_pre_business_knowledge_usage_patch_defaults(
all_data: dict[str, dict[int, int]], query_results: list[RunQueryToS3Result]
) -> None:
diff --git a/posthog/temporal/usage_report/queries.py b/posthog/temporal/usage_report/queries.py
index 407b8b4ff109..ce9c8cbc84ad 100644
--- a/posthog/temporal/usage_report/queries.py
+++ b/posthog/temporal/usage_report/queries.py
@@ -89,6 +89,7 @@ from posthog.tasks.usage_report import (
get_teams_with_rows_synced_in_period,
get_teams_with_sdk_logs_records_in_period,
get_teams_with_signals_credits_used_in_period,
+ get_teams_with_signals_spend_credits_used_in_period,
get_teams_with_survey_responses_count_in_period,
get_teams_with_task_sandbox_usage_in_period,
get_teams_with_workflow_transactional_emails_sent_in_period,
@@ -546,6 +547,10 @@ QUERIES: list[QuerySpec] = [
name="teams_with_signals_credits_used_in_period",
fn=get_teams_with_signals_credits_used_in_period,
),
+ QuerySpec(
+ name="teams_with_signals_spend_credits_used_in_period",
+ fn=get_teams_with_signals_spend_credits_used_in_period,
+ ),
QuerySpec(
name="teams_with_posthog_code_credits_used_in_period",
fn=get_teams_with_posthog_code_credits_used_in_period,
diff --git a/posthog/temporal/usage_report/workflow.py b/posthog/temporal/usage_report/workflow.py
index 37c88234f41c..6aef855486ac 100644
--- a/posthog/temporal/usage_report/workflow.py
+++ b/posthog/temporal/usage_report/workflow.py
@@ -60,6 +60,8 @@ LOGS_DISTINCT_PATTERNS_QUERY_PATCH_ID = "usage-report-logs-distinct-patterns-que
LOGS_DISTINCT_PATTERNS_QUERY_NAME = "teams_with_logs_distinct_patterns_in_period"
TRANSACTIONAL_EMAILS_QUERY_PATCH_ID = "usage-report-transactional-emails-query-2026-10"
TRANSACTIONAL_EMAILS_QUERY_NAME = "teams_with_workflow_transactional_emails_sent_in_period"
+SIGNALS_SPEND_QUERY_PATCH_ID = "usage-report-signals-spend-query-2026-11"
+SIGNALS_SPEND_QUERY_NAME = "teams_with_signals_spend_credits_used_in_period"
MCP_EVENT_COUNT_QUERY_PATCH_ID = "usage-report-mcp-event-count-query-2026-10"
MCP_EVENT_COUNT_QUERY_NAME = "teams_with_mcp_event_count_in_period"
REPLAY_VISION_SPEND_PROJECTION_QUERY_PATCH_ID = "usage-report-replay-vision-spend-projection-query-2026-10"
@@ -88,6 +90,12 @@ def _queries_for_transactional_emails_patch(queries: list[QuerySpec], patch_appl
return [spec for spec in queries if spec.name != TRANSACTIONAL_EMAILS_QUERY_NAME]
+def _queries_for_signals_spend_patch(queries: list[QuerySpec], patch_applied: bool) -> list[QuerySpec]:
+ if patch_applied:
+ return queries
+ return [spec for spec in queries if spec.name != SIGNALS_SPEND_QUERY_NAME]
+
+
def _queries_for_mcp_event_count_patch(queries: list[QuerySpec], patch_applied: bool) -> list[QuerySpec]:
if patch_applied:
return queries
@@ -182,6 +190,7 @@ class RunUsageReportsWorkflow(PostHogWorkflow):
queries = _queries_for_replay_vision_spend_projection_patch(
queries, workflow.patched(REPLAY_VISION_SPEND_PROJECTION_QUERY_PATCH_ID)
)
+ queries = _queries_for_signals_spend_patch(queries, workflow.patched(SIGNALS_SPEND_QUERY_PATCH_ID))
queries = _queries_for_business_knowledge_usage_patch(
queries, workflow.patched(BUSINESS_KNOWLEDGE_USAGE_QUERY_PATCH_ID)
)
diff --git a/posthog/usage_counters.py b/posthog/usage_counters.py
index 276a68b3980e..221e4246efcc 100644
--- a/posthog/usage_counters.py
+++ b/posthog/usage_counters.py
@@ -54,6 +54,7 @@ class UsageCounter(StrEnum):
LOGS_RETENTION_BYTE_DAYS = "teams_with_logs_retention_byte_days_in_period"
AI_CREDITS = "teams_with_ai_credits_used_in_period"
SIGNALS_CREDITS = "teams_with_signals_credits_used_in_period"
+ SIGNALS_SPEND_CREDITS = "teams_with_signals_spend_credits_used_in_period"
POSTHOG_CODE_CREDITS = "teams_with_posthog_code_credits_used_in_period"
SANDBOX_COMPUTE_CREDITS = "teams_with_sandbox_compute_credits_used_in_period"
REPLAY_VISION_CREDITS = "teams_with_replay_vision_credits_used_in_period"
@@ -309,11 +310,13 @@ class UsageCounterService:
UsageCounter.LOGS_RETENTION_BYTE_DAYS: usage_report.get_teams_with_logs_retention_byte_days_in_period,
UsageCounter.AI_CREDITS: usage_report.get_teams_with_ai_credits_used_in_period,
UsageCounter.SIGNALS_CREDITS: usage_report.get_teams_with_signals_credits_used_in_period,
+ UsageCounter.SIGNALS_SPEND_CREDITS: usage_report.get_teams_with_signals_spend_credits_used_in_period,
UsageCounter.POSTHOG_CODE_CREDITS: usage_report.get_teams_with_posthog_code_credits_used_in_period,
UsageCounter.SANDBOX_COMPUTE_CREDITS: lambda begin, end: self._sandbox_compute_query(begin, end).credits,
UsageCounter.REPLAY_VISION_CREDITS: usage_report.get_teams_with_replay_vision_credits_used_in_period,
}
self._quota_events_query = usage_report.get_teams_with_billable_event_count_in_period
+ self._quota_signals_spend_query = usage_report.get_teams_with_signals_spend_quota_credits_used_in_period
self._exceptions_query = usage_report.get_teams_with_exceptions_captured_in_period
self._logs_retention_query = usage_report.get_teams_with_logs_retention_bytes_in_period
self._sandbox_compute_query = usage_report.get_teams_with_billable_sandbox_compute_usage_in_period
@@ -345,6 +348,8 @@ class UsageCounterService:
) -> list[tuple[int, int]]: # nosemgrep: tuple-return-prefer-dataclass -- Legacy query contract: (team_id, count).
if caller == "quota_limiting" and counter == UsageCounter.EVENTS:
rows = self._quota_events_query(begin, end, count_distinct=False)
+ elif caller == "quota_limiting" and counter == UsageCounter.SIGNALS_SPEND_CREDITS:
+ return [(row.team_id, row.credits) for row in self._quota_signals_spend_query(begin, end)]
else:
rows = self._queries[counter](begin, end)
# Flag readers return string team IDs, and the rows synced and exported readers return dictionaries.
diff --git a/products/billing/frontend/generated/api.schemas.ts b/products/billing/frontend/generated/api.schemas.ts
index e794dd1b5749..64dcc75b4780 100644
--- a/products/billing/frontend/generated/api.schemas.ts
+++ b/products/billing/frontend/generated/api.schemas.ts
@@ -1346,7 +1346,7 @@ export type BillingSpendRetrieveParams = {
*/
top_projects?: number | null
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null
@@ -1398,7 +1398,7 @@ export type BillingSpendExportRetrieveParams = {
*/
top_projects?: number | null
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null
@@ -1450,7 +1450,7 @@ export type BillingUsageRetrieveParams = {
*/
top_projects?: number | null
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null
@@ -1502,7 +1502,7 @@ export type BillingUsageExportRetrieveParams = {
*/
top_projects?: number | null
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null
@@ -1610,7 +1610,7 @@ export type BillingSpendExportDownloadParams = {
*/
top_projects?: number | null
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null
@@ -1662,7 +1662,7 @@ export type BillingSpendTimeseriesRetrieveParams = {
*/
top_projects?: number | null
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null
@@ -1701,7 +1701,7 @@ export type BillingUsageExportDownloadParams = {
*/
top_projects?: number | null
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null
@@ -1753,7 +1753,7 @@ export type BillingUsageTimeseriesRetrieveParams = {
*/
top_projects?: number | null
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null
@@ -1780,7 +1780,7 @@ export type BillingProjectSpendExportDownloadParams = {
*/
start_date?: string | null
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null
@@ -1807,7 +1807,7 @@ export type BillingProjectSpendTimeseriesRetrieveParams = {
*/
start_date?: string | null
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null
@@ -1834,7 +1834,7 @@ export type BillingProjectUsageExportDownloadParams = {
*/
start_date?: string | null
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null
@@ -1861,7 +1861,7 @@ export type BillingProjectUsageTimeseriesRetrieveParams = {
*/
start_date?: string | null
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null
diff --git a/products/signals/backend/apps.py b/products/signals/backend/apps.py
index 57fc582ca7ad..aaa12bcc371c 100644
--- a/products/signals/backend/apps.py
+++ b/products/signals/backend/apps.py
@@ -99,7 +99,13 @@ class SignalsConfig(AppConfig):
def _record_task_spend_delta(
- *, team_id: int, run_id: UUID, cost_delta_microusd: int, origin_product: str, **kwargs: object
+ *,
+ team_id: int,
+ run_id: UUID,
+ cost_delta_microusd: int,
+ origin_product: str,
+ accounting_failed: bool = False,
+ **kwargs: object,
) -> None:
if origin_product not in {"signal_report", "signals_scout"}:
return
@@ -108,4 +114,6 @@ def _record_task_spend_delta(
record_task_cost_delta, # noqa: PLC0415 — keeps accounting off Django startup
)
- record_task_cost_delta(team_id=team_id, run_id=run_id, cost_delta_microusd=cost_delta_microusd)
+ record_task_cost_delta(
+ team_id=team_id, run_id=run_id, cost_delta_microusd=cost_delta_microusd, accounting_failed=accounting_failed
+ )
diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.py
index acb1398e24ce..0b91825c26b9 100644
--- a/products/signals/backend/auto_start.py
+++ b/products/signals/backend/auto_start.py
@@ -51,7 +51,11 @@ from products.signals.backend.models import (
SignalUserAutonomyConfig,
)
from products.signals.backend.pipeline_identity import AI_STAGE_IMPLEMENTATION
-from products.signals.backend.quota import capture_signal_report_quota_paused, self_driving_quota_gate
+from products.signals.backend.quota import (
+ capture_signal_report_quota_paused,
+ self_driving_limit_name,
+ self_driving_quota_gate,
+)
from products.signals.backend.report_assignments import release_claim
from products.signals.backend.report_claims import get_active_claim
from products.signals.backend.report_generation.research import (
@@ -563,7 +567,6 @@ SKIP_REQUIRES_HUMAN_INPUT = "requires_human_input"
SKIP_ALREADY_ADDRESSED = "already_addressed"
SKIP_NO_PRIORITY = "no_priority"
SKIP_AUTOSTART_DISABLED = "autostart_disabled"
-SKIP_QUOTA_EXHAUSTED = "quota_exhausted"
SKIP_NO_RUNNER = "no_runner"
SKIP_FREE_TRIAL = "free_trial"
@@ -935,6 +938,8 @@ def _create_implementation_task_if_absent(
branch=base_branch,
signal_report_id=report_id,
implementation_spend_kind=implementation_spend_kind,
+ # Research increments run_count after admission; scouts create READY reports directly.
+ continue_admitted_pipeline=report.run_count > 0 or report.status == SignalReport.Status.READY,
# Resolved by the caller outside this lock, like `agent_runtime` above, so the
# create-time free-trial gate makes no flag request while the report row is locked.
free_trial_enabled=free_trial_enabled,
@@ -1015,7 +1020,6 @@ def start_requested_implementation(
return "already_started"
if task_run_usage_limited(user, request.team_id):
raise RequestedImplementationUnavailable("The requested user cannot start another task run")
- tasks_facade.enforce_self_driving_pr_quota(team, report_id=request.report_id, stage="manual_rerun")
if pending_replacement(request.team_id, request.report_id) is not None:
raise RequestedImplementationUnavailable("A replacement is already in progress")
actionability_row = (
@@ -1526,9 +1530,6 @@ async def maybe_autostart_implementation_task(
unresolved_issues = await database_sync_to_async(resolve_issue_dependencies, thread_sensitive=False)(
team_id=team_id, report_id=report_id, ch_user=ch_user
)
- # Between the team's master switch and the quota gate. A team that opted out of auto-start
- # entirely gets no artefact and no gate reason, and a duplicate or a plan parent never counts
- # as quota-held work, because the work was never this report's to do.
link_skip = await database_sync_to_async(_evaluate_link_gates, thread_sensitive=False)(team_id, report_id)
if link_skip is None and unresolved_issues:
link_skip = unresolved_dependency_skip(unresolved_issues)
@@ -1543,25 +1544,7 @@ async def maybe_autostart_implementation_task(
await database_sync_to_async(_record_link_gate_skip, thread_sensitive=False)(team_id, report_id, link_skip)
return AutostartOutcome(status="blocked", reason=link_skip.detail)
- # 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",
- )
- await database_sync_to_async(_capture_autostart_skipped, thread_sensitive=False)(
- team_id=team_id, report_id=report_id, skip_reason=SKIP_QUOTA_EXHAUSTED
- )
- return AutostartOutcome(status="blocked", reason="Self-driving quota is exhausted")
# 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.
@@ -1754,6 +1737,7 @@ async def maybe_autostart_from_report_artefacts(
*,
team_id: int,
report_id: str,
+ triggering_user_id: int | None = None,
implementation_spend_kind: str = "reviewer_triggered_implementation",
remaining_retries: int = 2,
dispatch: ImplementationDispatch | None = None,
@@ -1778,6 +1762,17 @@ async def maybe_autostart_from_report_artefacts(
`inbox:write`, while every other write that automatic start reads needs `task:write`. A person
who wants a run presses Implement, which carries its own authorization.
"""
+ # A fresh user edit admits new work. Persisted reviewer attribution is only the execution
+ # identity: reusing it as this gate would also block an already-admitted pipeline.
+ if triggering_user_id is not None:
+ team = await Team.objects.select_related("organization").aget(id=team_id)
+ gate = await database_sync_to_async(self_driving_quota_gate)(team)
+ if gate.limited:
+ await database_sync_to_async(capture_signal_report_quota_paused)(
+ team, report_id=report_id, stage="reviewer_edit", enforced=gate.enforced
+ )
+ if gate.enforced:
+ return AutostartOutcome(status="blocked", reason=f"Self-driving {self_driving_limit_name(team)} reached")
if await SignalReport.objects.filter(id=report_id, team_id=team_id, user_authored=True).aexists():
logger.info(
"signals auto-start re-eval skipped",
diff --git a/products/signals/backend/billing.py b/products/signals/backend/billing.py
index 8ea1f3d9fdcb..20a18865dac1 100644
--- a/products/signals/backend/billing.py
+++ b/products/signals/backend/billing.py
@@ -1,38 +1,5 @@
-"""Signals billing — a flat credit charge per report that ships an implementation PR.
-
-Signals is billed on outcomes, not LLM spend: each signal report whose implementation task
-opens a pull request is charged a flat number of credits, once. The chargeable moment is
-deterministic — the first implementation `TaskRun` with a `pr_url` set — so a report is
-billed exactly once, in the period that PR first appeared, regardless of any later status
-changes, re-judgements, or additional runs.
-
-Billing eligibility uses the `SignalReportTask` implementation bridge and the first task-run
-PR URL. PR-link artefacts also include external work, so their presence cannot authorize a charge.
-
-Because this is a billing source it fails closed: a run only bills when its PR URL is a GitHub
-URL and the run, task, bridge, and report teams all agree, so malformed bridge rows never
-produce a charge.
-
-Credits use the same unit as ai_credits: 1 credit = $0.01, so the flat $15 charge is 1500
-credits.
-
-Two mechanisms remove a report from billing:
-
-- **Refunds** (retrospective, `SignalReportRefund`): an `excluded`-path refund makes the usage
- query skip the report entirely — committed strictly on the same UTC day as the first billable
- PR run, so no usage send (all of which happen ≥3h45m into the next UTC day) can ever observe
- the exclusion flipping. A `credited`-path refund is deliberately NOT consulted here: usage
- stays truthful and the money comes back as a billing-service credit.
-- **Exemptions** (prospective, `SignalReport.billing_exempt_reason`): PostHog-system-origin
- reports are marked never-billable before their billable moment exists, so they never enter
- usage (nor, via the same query driving quota `todays_usage`, consume a free-tier slot).
-
-Emergent semantic to be aware of: because of the `billed_earlier` idempotency check below, a
-report whose first billable PR run has been refunded can NEVER be billed again — a later, second
-PR run on the same report finds the first run before the period and is skipped, and the first
-run itself is refund-excluded (excluded path) or already handled by a credit (credited path).
-This is why restoring a refunded report is blocked at the API layer: refund → restore → new PR
-would otherwise be repeatable free work.
+"""A report's first implementation PR determines its legacy charge, even after a refund.
+Usage billing counts finalized spend; both meters feed reporting and quota refresh.
"""
import uuid
@@ -41,7 +8,7 @@ from collections.abc import Collection, Sequence
from datetime import datetime
from typing import TYPE_CHECKING, NamedTuple
-from django.db.models import F, Min, OuterRef, QuerySet, Subquery, Sum
+from django.db.models import Exists, F, Min, OuterRef, Q, QuerySet, Subquery, Sum
from django.utils import timezone
from dateutil.relativedelta import relativedelta
@@ -50,7 +17,13 @@ from posthog.models.organization import BillingPeriod
from products.signals.backend.artefact_schemas import TASK_RUN_TYPE_IMPLEMENTATION
from products.signals.backend.enums import SignalSourceProduct
-from products.signals.backend.models import SignalReport, SignalReportRefund, SignalReportTask, SignalScoutRun
+from products.signals.backend.models import (
+ SignalReport,
+ SignalReportRefund,
+ SignalReportTask,
+ SignalScoutRun,
+ SignalSpend,
+)
from products.signals.backend.scout_harness.lazy_seed import scout_skill_row_is_proven_canonical
from products.skills.backend.models.skills import LLMSkill
from products.tasks.backend.facade.api import GITHUB_PR_URL_PREFIX
@@ -85,7 +58,9 @@ def _bridges_with_pr_run(*, include_manual: bool = False, **run_created_at: date
happened to be on it. The run-level conditions sit in one `filter()` so they all resolve
against the same `TaskRun` row.
"""
+ usage_billed = SignalSpend.objects.unscoped().filter(task_run_id=OuterRef("task__runs__id"), usage_billing=True)
return SignalReportTask.objects.filter(
+ Q() if include_manual else ~Exists(usage_billed),
**({} if include_manual else {"task__runs__state__billing_product__isnull": True}),
relationship=_IMPLEMENTATION,
task__runs__output__pr_url__startswith=GITHUB_PR_URL_PREFIX,
diff --git a/products/signals/backend/emission/conversations_coordinator.py b/products/signals/backend/emission/conversations_coordinator.py
index 92cae1bad4f2..eca538805375 100644
--- a/products/signals/backend/emission/conversations_coordinator.py
+++ b/products/signals/backend/emission/conversations_coordinator.py
@@ -23,6 +23,9 @@ from products.signals.backend.emission import InternalSourceType, get_signal_con
from products.signals.backend.emission.pipeline import run_signal_pipeline
from products.signals.backend.emission.steering import afetch_source_config
from products.signals.backend.models import SignalSourceConfig
+from products.signals.backend.quota import is_team_signals_quota_limited
+
+from ee.billing.quota_limiting import self_driving_quota_resource
logger = structlog.get_logger(__name__)
@@ -72,10 +75,14 @@ async def emit_conversations_signals_activity(inputs: EmitConversationsSignalsIn
return {"status": "skipped", "reason": "no_config_registered", "signals_emitted": 0}
async with Heartbeater():
try:
- team = await Team.objects.aget(id=inputs.team_id)
+ team = await Team.objects.select_related("organization").aget(id=inputs.team_id)
except Team.DoesNotExist:
log.warning("Team no longer exists, skipping")
return {"status": "skipped", "reason": "team_deleted", "signals_emitted": 0}
+ if await database_sync_to_async(is_team_signals_quota_limited, thread_sensitive=False)(
+ team.api_token, self_driving_quota_resource(team.organization)
+ ):
+ return {"status": "skipped", "reason": "quota_limited", "signals_emitted": 0}
# Before the record fetch: the conversations fetcher records emission optimistically, so a
# failure after it returns would permanently skip this batch on the Temporal retry.
source_config = await afetch_source_config(team.id, config.source_product, config.source_type)
diff --git a/products/signals/backend/emission/emit_signals.py b/products/signals/backend/emission/emit_signals.py
index 69dd8012b929..86d2b7959f60 100644
--- a/products/signals/backend/emission/emit_signals.py
+++ b/products/signals/backend/emission/emit_signals.py
@@ -17,9 +17,12 @@ from posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeater
from products.signals.backend.emission import get_signal_config
from products.signals.backend.emission.pipeline import run_signal_pipeline
from products.signals.backend.emission.steering import afetch_source_config
+from products.signals.backend.quota import is_team_signals_quota_limited
from products.warehouse_sources.backend.facade.hooks import EmitSignalsActivityInputs
from products.warehouse_sources.backend.facade.models import ExternalDataSchema
+from ee.billing.quota_limiting import self_driving_quota_resource
+
logger = structlog.get_logger(__name__)
@@ -39,6 +42,10 @@ async def emit_data_import_signals_activity(inputs: EmitSignalsActivityInputs) -
if schema.table is None:
log.warning(f"Schema {inputs.schema_id} has no table for emitting signals")
return {"status": "skipped", "reason": "no_table", "signals_emitted": 0}
+ if await database_sync_to_async(is_team_signals_quota_limited, thread_sensitive=False)(
+ team.api_token, self_driving_quota_resource(team.organization)
+ ):
+ return {"status": "skipped", "reason": "quota_limited", "signals_emitted": 0}
# `DataWarehouseTable.name` is the storage form (e.g. `<prefix><source_type>_<schema>`),
# but HogQL exposes warehouse tables under the keys produced by `get_data_warehouse_table_name`
# (e.g. `github.issues` or `github.<prefix>.<schema>`). Querying the storage name fails to resolve.
@@ -65,7 +72,7 @@ async def emit_data_import_signals_activity(inputs: EmitSignalsActivityInputs) -
async def _fetch_schema_and_team(schema_id: uuid.UUID, team_id: int) -> tuple[ExternalDataSchema, Team]:
schema = await ExternalDataSchema.objects.prefetch_related("table", "source").aget(id=schema_id, team_id=team_id)
- team = await Team.objects.aget(id=team_id)
+ team = await Team.objects.select_related("organization").aget(id=team_id)
return schema, team
diff --git a/products/signals/backend/emission/tests/test_emission_quota.py b/products/signals/backend/emission/tests/test_emission_quota.py
new file mode 100644
index 000000000000..6edd9bc3dfd4
--- /dev/null
+++ b/products/signals/backend/emission/tests/test_emission_quota.py
@@ -0,0 +1,94 @@
+from uuid import uuid4
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from posthog.models import Organization, Team
+
+from products.signals.backend.emission.conversations_coordinator import (
+ EmitConversationsSignalsInputs,
+ emit_conversations_signals_activity,
+)
+from products.signals.backend.emission.emit_signals import EmitSignalsActivityInputs, emit_data_import_signals_activity
+
+from ee.billing.quota_limiting import QuotaResource
+
+
[email protected](params=["legacy_limited", "spend_limited", "spend_allowed"])
+def quota_case(request):
+ spend_billing = request.param.startswith("spend")
+ team = Team(
+ id=7,
+ api_token="test-token",
+ organization=Organization(
+ usage={"signals_spend_credits": {"billing_start_date": "2000-01-01"}} if spend_billing else {}
+ ),
+ )
+ resource = QuotaResource.SIGNALS_SPEND_CREDITS if spend_billing else QuotaResource.SIGNALS_CREDITS
+ return team, resource, request.param.endswith("limited")
+
+
+async def test_warehouse_checks_quota_before_consuming_records(quota_case):
+ team, resource, limited = quota_case
+ config = MagicMock()
+ config.record_fetcher.return_value = []
+ module = "products.signals.backend.emission.emit_signals"
+ with (
+ patch(f"{module}.Heartbeater"),
+ patch(f"{module}.get_signal_config", return_value=config),
+ patch(f"{module}._fetch_schema_and_team", AsyncMock(return_value=(MagicMock(), team))),
+ patch(f"{module}.is_team_signals_quota_limited", return_value=limited) as gate,
+ patch(f"{module}.afetch_source_config", AsyncMock(return_value={})),
+ patch(f"{module}.get_data_warehouse_table_name", return_value="github.issues"),
+ patch(f"{module}.run_signal_pipeline", AsyncMock(return_value={"status": "success"})) as pipeline,
+ ):
+ result = await emit_data_import_signals_activity(
+ EmitSignalsActivityInputs(
+ team_id=team.id,
+ schema_id=uuid4(),
+ source_id=uuid4(),
+ job_id="job-x",
+ source_type="GitHub",
+ schema_name="issues",
+ last_synced_at=None,
+ )
+ )
+
+ gate.assert_called_once_with(team.api_token, resource)
+ if limited:
+ assert result == {"status": "skipped", "reason": "quota_limited", "signals_emitted": 0}
+ config.record_fetcher.assert_not_called()
+ pipeline.assert_not_awaited()
+ else:
+ assert result == {"status": "success"}
+ config.record_fetcher.assert_called_once()
+ pipeline.assert_awaited_once()
+
+
+async def test_conversations_checks_quota_before_consuming_records(quota_case):
+ team, resource, limited = quota_case
+ config = MagicMock()
+ config.record_fetcher.return_value = []
+ module = "products.signals.backend.emission.conversations_coordinator"
+ with (
+ patch(f"{module}.Heartbeater"),
+ patch(f"{module}.get_signal_config", return_value=config),
+ patch(f"{module}.Team.objects.select_related") as teams,
+ patch(f"{module}.is_team_signals_quota_limited", return_value=limited) as gate,
+ patch(f"{module}.afetch_source_config", AsyncMock(return_value={})),
+ patch(f"{module}.run_signal_pipeline", AsyncMock(return_value={"status": "success"})) as pipeline,
+ ):
+ teams.return_value.aget = AsyncMock(return_value=team)
+ result = await emit_conversations_signals_activity(EmitConversationsSignalsInputs(team_id=team.id))
+
+ gate.assert_called_once_with(team.api_token, resource)
+ if limited:
+ assert result == {"status": "skipped", "reason": "quota_limited", "signals_emitted": 0}
+ config.record_fetcher.assert_not_called()
+ pipeline.assert_not_awaited()
+ else:
+ assert result == {"status": "success"}
+ config.record_fetcher.assert_called_once()
+ pipeline.assert_awaited_once()
diff --git a/products/signals/backend/emission/tests/test_emit_signals.py b/products/signals/backend/emission/tests/test_emit_signals.py
index 217395443234..9bed5af079d5 100644
--- a/products/signals/backend/emission/tests/test_emit_signals.py
+++ b/products/signals/backend/emission/tests/test_emit_signals.py
@@ -1283,12 +1283,13 @@ class TestEmitActivityTableNameResolution:
schema.table = table
schema.source = source
- fetch_mock = AsyncMock(return_value=(schema, MagicMock()))
+ fetch_mock = AsyncMock(return_value=(schema, MagicMock(organization=MagicMock(usage={}))))
with (
patch(f"{ACTIVITY_MODULE_PATH}.Heartbeater"),
patch(f"{ACTIVITY_MODULE_PATH}.get_signal_config", return_value=config),
patch(f"{ACTIVITY_MODULE_PATH}._fetch_schema_and_team", fetch_mock),
+ patch(f"{ACTIVITY_MODULE_PATH}.is_team_signals_quota_limited", return_value=False),
patch(f"{ACTIVITY_MODULE_PATH}.afetch_source_config", AsyncMock(return_value={})),
patch(f"{ACTIVITY_MODULE_PATH}.run_signal_pipeline", new_callable=AsyncMock) as run_mock,
):
@@ -1318,7 +1319,7 @@ class TestEmitActivitySourceConfigThreading:
return []
config = _make_config(record_fetcher=capture_fetcher)
- team = MagicMock(id=7)
+ team = MagicMock(id=7, organization=MagicMock(usage={}))
schema = MagicMock()
schema.table.name = "test_table"
@@ -1326,6 +1327,7 @@ class TestEmitActivitySourceConfigThreading:
patch(f"{ACTIVITY_MODULE_PATH}.Heartbeater"),
patch(f"{ACTIVITY_MODULE_PATH}.get_signal_config", return_value=config),
patch(f"{ACTIVITY_MODULE_PATH}._fetch_schema_and_team", AsyncMock(return_value=(schema, team))),
+ patch(f"{ACTIVITY_MODULE_PATH}.is_team_signals_quota_limited", return_value=False),
patch(f"{ACTIVITY_MODULE_PATH}.get_data_warehouse_table_name", return_value="test.table"),
patch(
f"{ACTIVITY_MODULE_PATH}.afetch_source_config",
diff --git a/products/signals/backend/facade/billing.py b/products/signals/backend/facade/billing.py
index fb94a9057f5e..44de836fd387 100644
--- a/products/signals/backend/facade/billing.py
+++ b/products/signals/backend/facade/billing.py
@@ -6,7 +6,7 @@ from datetime import datetime
from posthog.dataclasses import frozen
-from products.signals.backend import billing
+from products.signals.backend import billing, spend_billing
@frozen
@@ -35,3 +35,23 @@ def signals_billing_credits_by_team(
def credited_refund_credits_for_org(organization_id: str | uuid.UUID, begin: datetime, end: datetime) -> int:
"""Credits that credited-path refunds returned for the org's pull request runs created in ``[begin, end)``."""
return billing.credited_refund_credits_for_org(organization_id, begin, end)
+
+
+def signals_spend_billing_credits_by_team(
+ begin: datetime,
+ end: datetime,
+ *,
+ organization_id: str | uuid.UUID | None = None,
+ organization_ids: Collection[str | uuid.UUID] | None = None,
+) -> list[TeamSignalsCredits]:
+ rows = spend_billing.get_signals_spend_billing_credits_by_team(
+ begin, end, organization_id=organization_id, organization_ids=organization_ids
+ )
+ return [TeamSignalsCredits(team_id=team_id, credits=credits) for team_id, credits in rows]
+
+
+def signals_spend_quota_credits_by_team(
+ begin: datetime, end: datetime, *, organization_id: str | uuid.UUID | None = None
+) -> list[TeamSignalsCredits]:
+ rows = spend_billing.get_signals_spend_quota_credits_by_team(begin, end, organization_id=organization_id)
+ return [TeamSignalsCredits(team_id=team_id, credits=credits) for team_id, credits in rows]
diff --git a/products/signals/backend/facade/self_driving.py b/products/signals/backend/facade/self_driving.py
index 224c77129ec4..a03f03b04a5c 100644
--- a/products/signals/backend/facade/self_driving.py
+++ b/products/signals/backend/facade/self_driving.py
@@ -21,6 +21,7 @@ __all__ = [
"record_quota_check_failed_open",
"self_driving_free_trial_enabled",
"self_driving_quota_gate",
+ "self_driving_limit_name",
]
@@ -28,6 +29,10 @@ def self_driving_quota_gate(team: "Team") -> SelfDrivingQuotaGate:
return quota.self_driving_quota_gate(team)
+def self_driving_limit_name(team: "Team") -> str:
+ return quota.self_driving_limit_name(team)
+
+
def capture_signal_report_quota_paused(team: "Team", *, report_id: str | None, stage: str, enforced: bool) -> None:
quota.capture_signal_report_quota_paused(team, report_id=report_id, stage=stage, enforced=enforced)
diff --git a/products/signals/backend/llm_spend.py b/products/signals/backend/llm_spend.py
index 2279cbd48b3d..fd0341e25f33 100644
--- a/products/signals/backend/llm_spend.py
+++ b/products/signals/backend/llm_spend.py
@@ -14,7 +14,7 @@ from posthog.llm.gateway_usage import GatewayRequestCost, fetch_gateway_cost
from posthog.sync import database_sync_to_async
from products.signals.backend.pricing import cost_to_spend
-from products.signals.backend.spend import record_llm_spend
+from products.signals.backend.spend import begin_signal_spend, record_llm_spend
logger = structlog.get_logger(__name__)
USAGE_WAIT_SECONDS = 10.0
@@ -97,6 +97,8 @@ async def generate_with_spend(
and marks the stage unaccounted.
"""
try:
+ if team_id is not None and signal_id is not None:
+ await database_sync_to_async(begin_signal_spend)(team_id=team_id, signal_id=signal_id)
response = await generation
except (Exception, asyncio.CancelledError) as error:
request_id = (
diff --git a/products/signals/backend/migrations/0235_signalspend_usage_billing.py b/products/signals/backend/migrations/0235_signalspend_usage_billing.py
new file mode 100644
index 000000000000..1361377327ef
--- /dev/null
+++ b/products/signals/backend/migrations/0235_signalspend_usage_billing.py
@@ -0,0 +1,15 @@
+# Generated by Django 6.1.3 on 2026-11-04 16:25
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("signals", "0234_signalscoutnote_report_note_origin")]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalspend",
+ name="usage_billing",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index f80586e780c0..1e795c304404 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0234_signalscoutnote_report_note_origin
+0235_signalspend_usage_billing
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index c05dbb3ba25c..024f4d591343 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1847,7 +1847,9 @@ class SignalReportArtefact(UUIDModel):
claim_id=claim_id,
)
if reevaluate_autostart and (not update.protected or rules.effects_enabled):
- cls._schedule_autostart_reevaluation(team_id=team_id, report_id=str(report_id))
+ cls._schedule_autostart_reevaluation(
+ team_id=team_id, report_id=str(report_id), triggering_user_id=attribution.user_id
+ )
return artefact
return cls._create(
team_id=team_id, report_id=report_id, content=content, attribution=attribution, claim_id=claim_id
@@ -1962,7 +1964,9 @@ class SignalReportArtefact(UUIDModel):
)
@staticmethod
- def _schedule_autostart_reevaluation(*, team_id: int, report_id: str) -> None:
+ def _schedule_autostart_reevaluation(
+ *, team_id: int, report_id: str, triggering_user_id: int | None = None
+ ) -> None:
"""After the current transaction commits, re-evaluate auto-start for the report.
Changing a report's suggested reviewers can newly satisfy auto-start (e.g. adding a
@@ -1976,7 +1980,9 @@ class SignalReportArtefact(UUIDModel):
from products.signals.backend import auto_start
try:
- async_to_sync(auto_start.maybe_autostart_from_report_artefacts)(team_id=team_id, report_id=report_id)
+ async_to_sync(auto_start.maybe_autostart_from_report_artefacts)(
+ team_id=team_id, report_id=report_id, triggering_user_id=triggering_user_id
+ )
except Exception:
logger.exception(
"signals reviewer-change auto-start re-evaluation failed", extra={"report_id": report_id}
@@ -4137,6 +4143,9 @@ class SignalSpend(TeamScopedRootMixin, UUIDModel):
accounting_failed = models.BooleanField(default=False)
finalized_at = models.DateTimeField(null=True, blank=True, db_index=True)
billing_exempt = models.BooleanField(default=False, db_default=False)
+ # Freeze the meter at admission: a later plan change must not bill the same work twice.
+ # Existing receipts and old workers retain the legacy PR meter.
+ usage_billing = models.BooleanField(default=False, db_default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
diff --git a/products/signals/backend/quota.py b/products/signals/backend/quota.py
index b9affafcd6a1..8e9e5a29dbc5 100644
--- a/products/signals/backend/quota.py
+++ b/products/signals/backend/quota.py
@@ -14,14 +14,14 @@ from temporalio import activity
from posthog.event_usage import groups
from posthog.temporal.common.metrics import get_metric_meter
-from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limited
+from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limited, self_driving_quota_resource
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).
+# Enforcement kill switch for new report/scout pipelines and manual work.
# 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"
@@ -40,7 +40,7 @@ def record_quota_check_failed_open() -> None:
).add(1)
-def is_team_signals_quota_limited(team_api_token: str) -> bool:
+def is_team_signals_quota_limited(team_api_token: str, resource: QuotaResource) -> bool:
"""Whether a team is currently over its Signals credits quota.
Fails open on a quota-limiter read error so an infra blip lets work through rather than stalling.
@@ -48,9 +48,7 @@ def is_team_signals_quota_limited(team_api_token: str) -> bool:
Synchronous (Redis read); wrap in `sync_to_async` when calling from async code.
"""
try:
- return is_team_limited(
- team_api_token, QuotaResource.SIGNALS_CREDITS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY
- )
+ return is_team_limited(team_api_token, resource, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)
except Exception:
logger.warning("signals_quota_check_failed_open", exc_info=True)
record_quota_check_failed_open()
@@ -102,11 +100,18 @@ def self_driving_quota_gate(team: "Team") -> SelfDrivingQuotaGate:
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):
+ if not is_team_signals_quota_limited(team.api_token, self_driving_quota_resource(team.organization)):
return SelfDrivingQuotaGate(limited=False, enforced=False)
return SelfDrivingQuotaGate(limited=True, enforced=self_driving_quota_enforcement_enabled(team))
+def self_driving_limit_name(team: "Team") -> str:
+ """Use the same cutover for customer-facing limit units and enforcement."""
+ if self_driving_quota_resource(team.organization) == QuotaResource.SIGNALS_SPEND_CREDITS:
+ return "spending limit"
+ return "pull request limit"
+
+
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
@@ -141,7 +146,9 @@ def notify_scout_quota_paused(team: "Team") -> None:
must never fail the gate that called it. Requires `team.organization` to be loaded.
"""
try:
- usage = (team.organization.usage or {}).get(QuotaResource.SIGNALS_CREDITS.value) or {}
+ resource = self_driving_quota_resource(team.organization)
+ usage = (team.organization.usage or {}).get(resource.value) or {}
+ limit_name = self_driving_limit_name(team)
quota_limited_until = usage.get("quota_limited_until") or 0
limit = usage.get("limit") or 0
from products.notifications.backend.facade.api import ( # noqa: PLC0415 (keeps the heavy dep off the import path)
@@ -155,15 +162,15 @@ def notify_scout_quota_paused(team: "Team") -> None:
NotificationData(
team_id=team.id,
notification_type=NotificationType.USAGE_SPIKE,
- title="Scouts paused: self-driving credits limit reached",
+ title=f"New scout runs paused: self-driving {limit_name} reached",
body=(
- "This project is over its self-driving credits limit, so scheduled scout runs are "
- "skipped until the limit lifts. Usage and limits: Settings > Billing."
+ f"This project reached its self-driving {limit_name}. New scout runs are paused "
+ "until the limit lifts. Work already underway will finish. Usage and limits: Settings > Billing."
),
target_type=TargetType.TEAM,
target_id=str(team.id),
source_url="/organization/billing",
- idempotency_key=f"signals_scout_quota_paused:{team.organization_id}:{quota_limited_until}:{limit}",
+ idempotency_key=f"signals_scout_quota_paused:{team.organization_id}:{resource.value}:{quota_limited_until}:{limit}",
)
)
except Exception:
diff --git a/products/signals/backend/scout_harness/run_gates.py b/products/signals/backend/scout_harness/run_gates.py
index e4c9932d5c85..0cd20c68038e 100644
--- a/products/signals/backend/scout_harness/run_gates.py
+++ b/products/signals/backend/scout_harness/run_gates.py
@@ -24,7 +24,11 @@ from posthog.models import Team
from products.signals.backend.daily_limit import daily_report_limit_gate
from products.signals.backend.models import SignalScoutRun
-from products.signals.backend.quota import capture_signal_report_quota_paused, self_driving_quota_gate
+from products.signals.backend.quota import (
+ capture_signal_report_quota_paused,
+ self_driving_limit_name,
+ self_driving_quota_gate,
+)
from products.signals.backend.scout_harness.limits import (
STALE_RUN_CUTOFF_S,
TRIGGERED_BY_WORKFLOW,
@@ -124,8 +128,8 @@ def check_spend_gates(team: Team, *, capture_analytics: bool = True) -> ScoutRun
kind=ScoutRunRejectionKind.THROTTLED,
reason="quota_limited",
detail=(
- "Self-driving is paused because this project reached its pull request limit. "
- "Raise the limit or wait for usage to reset."
+ f"New scout runs are paused because this project reached its self-driving {self_driving_limit_name(team)}. "
+ "Work already underway will finish. Raise the limit in Settings > Billing or wait for usage to reset."
),
)
if daily_report_limit_gate(team).limited:
diff --git a/products/signals/backend/spend.py b/products/signals/backend/spend.py
index 4d19e7e6fa50..3805cb588d3a 100644
--- a/products/signals/backend/spend.py
+++ b/products/signals/backend/spend.py
@@ -20,7 +20,12 @@ from posthog.dataclasses import frozen
from products.signals.backend.models import SignalReport, SignalScoutRun, SignalSpend
from products.signals.backend.pricing import cost_to_spend
-from products.signals.backend.spend_billing import apply_report_billing, scout_spend_exempt, trial_spend_exempt
+from products.signals.backend.spend_billing import (
+ apply_report_billing,
+ scout_spend_exempt,
+ trial_spend_exempt,
+ uses_spend_billing,
+)
@frozen
@@ -131,11 +136,19 @@ def _locked_ad_hoc_spend(*, team_id: int, signal_id: str) -> SignalSpend:
kind=SignalSpend.Kind.AD_HOC,
# get_or_create calls callable defaults only when it creates the row, so the trial lookup is
# skipped for existing rows. django-stubs types defaults as plain field values.
- defaults={"billing_exempt": lambda: trial_spend_exempt(team_id)}, # type: ignore[misc]
+ defaults={
+ "billing_exempt": lambda: trial_spend_exempt(team_id), # type: ignore[misc]
+ "usage_billing": lambda: uses_spend_billing(team_id),
+ },
)
return SignalSpend.objects.for_team(team_id).select_for_update().get(id=spend.id)
+def begin_signal_spend(*, team_id: int, signal_id: str) -> None:
+ with transaction.atomic():
+ _locked_ad_hoc_spend(team_id=team_id, signal_id=signal_id)
+
+
def _save_ad_hoc_spend(spend: SignalSpend, *, finalize: bool = False) -> None:
if spend.finalized_at is not None:
return
@@ -262,22 +275,26 @@ def record_task_spend(
scout = SignalScoutRun.objects.for_team(team_id).get(id=scout_run_id)
spend.created_at = min(spend.created_at, scout.created_at)
spend.billing_exempt = spend.billing_exempt or scout_spend_exempt(scout)
+ spend.usage_billing = uses_spend_billing(team_id, started_at=spend.created_at)
if report:
apply_report_billing(spend, report)
spend.spend = cost_to_spend(run.cost_microusd or 0, task_count=1)
- spend.accounting_failed = not run.complete
+ spend.accounting_failed = spend.accounting_failed or run.accounting_failed
spend.save()
_save_scout_total(spend)
-def record_task_cost_delta(*, team_id: int, run_id: UUID, cost_delta_microusd: int) -> None:
+def record_task_cost_delta(
+ *, team_id: int, run_id: UUID, cost_delta_microusd: int, accounting_failed: bool = False
+) -> None:
# The sender holds the run lock and commits this delta together with gateway request deduplication.
with transaction.atomic():
spend = SignalSpend.objects.for_team(team_id).select_for_update().filter(task_run_id=run_id).first()
if spend is None or spend.finalized_at is not None:
return
spend.spend += cost_to_spend(cost_delta_microusd)
- spend.save(update_fields=["spend", "updated_at"])
+ spend.accounting_failed = spend.accounting_failed or accounting_failed
+ spend.save(update_fields=["spend", "accounting_failed", "updated_at"])
_save_scout_total(spend)
@@ -361,7 +378,9 @@ def finish_report_spend(*, team_id: int, report_id: str, signal_id: str) -> None
report.save(update_fields=["triggering_signal_id"])
-def complete_task_spend(*, team_id: int, run_id: str, report_id: str | None = None) -> None:
+def complete_task_spend(
+ *, team_id: int, run_id: str, report_id: str | None = None, final_attempt: bool = False
+) -> None:
from products.tasks.backend.facade.billing import ( # noqa: PLC0415
TaskTokenUsageUnavailable,
locked_task_run_spend,
@@ -371,14 +390,19 @@ def complete_task_spend(*, team_id: int, run_id: str, report_id: str | None = No
spend = SignalSpend.objects.for_team(team_id).filter(task_run_id=UUID(str(run_id))).first()
if spend is None:
return
- if spend.finalized_at is None:
+ if spend.finalized_at is None and not spend.accounting_failed:
with locked_task_run_spend(team_id=team_id, run_id=UUID(run_id)) as run:
if not run.is_terminal:
return
- process_pending_gateway_usage(run_id=UUID(run_id), team_id=team_id, limit=1000)
+ try:
+ if not run.accounting_failed:
+ process_pending_gateway_usage(run_id=UUID(run_id), team_id=team_id, limit=1000)
+ except Exception:
+ if not final_attempt:
+ raise
with locked_task_run_spend(team_id=team_id, run_id=UUID(run_id)) as run:
spend = SignalSpend.objects.for_team(team_id).select_for_update().get(id=spend.id)
- if spend.finalized_at is None:
+ if spend.finalized_at is None and not spend.accounting_failed:
billing_report_id = spend.report_id or report_id
if billing_report_id is not None:
report = (
@@ -389,12 +413,12 @@ def complete_task_spend(*, team_id: int, run_id: str, report_id: str | None = No
if report:
apply_report_billing(spend, report)
spend.spend = cost_to_spend(run.cost_microusd or 0, task_count=1)
- spend.accounting_failed = not run.complete
+ spend.accounting_failed = run.accounting_failed or (final_attempt and not run.complete)
if run.is_terminal and run.complete:
spend.finalized_at = timezone.now()
spend.save()
_save_scout_total(spend)
- if spend.accounting_failed:
+ if spend.finalized_at is None and not spend.accounting_failed:
raise TaskTokenUsageUnavailable("Task usage is not settled yet")
if spend.signal_id:
async_to_sync(submit_signal_metadata_updates)(team_id=team_id, signal_ids=[str(spend.signal_id)])
diff --git a/products/signals/backend/spend_billing.py b/products/signals/backend/spend_billing.py
index 6cc91f0a92e2..09c074a96e83 100644
--- a/products/signals/backend/spend_billing.py
+++ b/products/signals/backend/spend_billing.py
@@ -1,3 +1,14 @@
+from collections.abc import Collection
+from datetime import UTC, date, datetime
+from uuid import UUID
+
+from django.db.models import DateTimeField, F, Q, Sum, Value
+from django.db.models.fields.json import KeyTextTransform
+from django.db.models.functions import Cast, Coalesce, TruncDate
+from django.db.models.lookups import GreaterThan, LessThanOrEqual
+from django.utils import timezone
+
+import structlog
import posthoganalytics
from posthog.models import Team
@@ -6,6 +17,8 @@ from products.signals.backend.enums import SignalSourceProduct
from products.signals.backend.free_trial import SELF_DRIVING_FREE_TRIAL_FLAG
from products.signals.backend.models import SignalReport, SignalScoutRun, SignalSpend
+logger = structlog.get_logger(__name__)
+
def system_source_exempt(source_product: str | None) -> bool:
return source_product in {SignalSourceProduct.HEALTH_CHECKS, SignalSourceProduct.ENGINEERING_ANALYTICS}
@@ -38,6 +51,79 @@ def trial_spend_exempt(team_id: int) -> bool:
)
+def uses_spend_billing(team_id: int, *, started_at: datetime | None = None) -> bool:
+ cutoff = Team.objects.values_list("organization__usage__signals_spend_credits__billing_start_date", flat=True).get(
+ id=team_id
+ )
+ return bool(cutoff and (started_at or timezone.now()).astimezone(UTC).date() >= date.fromisoformat(cutoff))
+
+
+def _spend_credits_by_team(
+ begin: datetime,
+ end: datetime,
+ *,
+ organization_id: str | UUID | None = None,
+ organization_ids: Collection[str | UUID] | None = None,
+ include_running: bool,
+) -> dict[int, int]:
+ if end <= begin:
+ return {}
+ eligible = Q(usage_billing=True, billing_exempt=False)
+ if organization_id is not None:
+ eligible &= Q(team__organization_id=organization_id)
+ if organization_ids is not None:
+ eligible &= Q(team__organization_id__in=organization_ids)
+ # Running costs belong in quota checks before their final receipt becomes billable.
+ now = datetime.now(UTC)
+ period = Q(finalized_at__gte=begin, finalized_at__lt=end)
+ if include_running and begin <= now < end:
+ period_start = Cast(KeyTextTransform("0", "team__organization__usage__period"), DateTimeField())
+ period_end = Cast(KeyTextTransform("1", "team__organization__usage__period"), DateTimeField())
+ period |= Q(
+ LessThanOrEqual(period_start, Value(now)),
+ GreaterThan(period_end, Value(now)),
+ finalized_at__isnull=True,
+ accounting_failed=False,
+ created_at__gte=period_start,
+ )
+ usage_at = Coalesce("finalized_at", Value(now)) if include_running else F("finalized_at")
+ # Deliberately cross-team: both usage reporting and organization quota use this aggregation.
+ totals = (
+ SignalSpend.objects.unscoped()
+ .alias(usage_at=usage_at)
+ .filter(eligible, period)
+ .values("team_id", day=TruncDate("usage_at", tzinfo=UTC))
+ .annotate(total_spend=Sum("spend"))
+ )
+ credits: dict[int, int] = {}
+ # Round once per team/day, so a period recount equals the daily reports billing sums.
+ for total in totals.iterator(chunk_size=1000):
+ team_id = total["team_id"]
+ credits[team_id] = credits.get(team_id, 0) + round(total["total_spend"])
+ return {team_id: amount for team_id, amount in credits.items() if amount}
+
+
+def get_signals_spend_billing_credits_by_team(
+ begin: datetime,
+ end: datetime,
+ organization_id: str | UUID | None = None,
+ organization_ids: Collection[str | UUID] | None = None,
+) -> list[tuple[int, int]]: # nosemgrep: tuple-return-prefer-dataclass -- usage-counter contract
+ return list(
+ _spend_credits_by_team(
+ begin, end, organization_id=organization_id, organization_ids=organization_ids, include_running=False
+ ).items()
+ )
+
+
+def get_signals_spend_quota_credits_by_team(
+ begin: datetime,
+ end: datetime,
+ organization_id: str | UUID | None = None,
+) -> list[tuple[int, int]]: # nosemgrep: tuple-return-prefer-dataclass -- usage-counter contract
+ return list(_spend_credits_by_team(begin, end, organization_id=organization_id, include_running=True).items())
+
+
def apply_report_billing(spend: SignalSpend, report: SignalReport) -> None:
if report.billing_exempt_reason:
spend.billing_exempt = True
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 8a27670df844..30a4a5c09e8c 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -157,6 +157,7 @@ def launch_inbox_onboarding_job(self: Task, team_id: int, job: str) -> None:
@shared_task(
+ bind=True,
ignore_result=True,
queue=CeleryQueue.LONG_RUNNING.value,
autoretry_for=(Exception,),
@@ -166,12 +167,12 @@ def launch_inbox_onboarding_job(self: Task, team_id: int, job: str) -> None:
reject_on_worker_lost=True,
)
@with_team_scope(canonical=True)
-def settle_scout_spend(team_id: int, run_id: str) -> None:
+def settle_scout_spend(self: Task, team_id: int, run_id: str) -> None:
from products.signals.backend.spend import (
complete_task_spend, # noqa: PLC0415 - keeps spend accounting off the task registration import path
)
- complete_task_spend(team_id=team_id, run_id=run_id)
+ complete_task_spend(team_id=team_id, run_id=run_id, final_attempt=self.request.retries >= self.max_retries)
@shared_task(
diff --git a/products/signals/backend/temporal/buffer.py b/products/signals/backend/temporal/buffer.py
index f8b94107d5e6..e734a872600c 100644
--- a/products/signals/backend/temporal/buffer.py
+++ b/products/signals/backend/temporal/buffer.py
@@ -33,6 +33,8 @@ from products.signals.backend.temporal.grouping_v2 import TeamSignalGroupingV2Wo
from products.signals.backend.temporal.safety_filter import SafetyFilterInput, safety_filter_activity
from products.signals.backend.temporal.types import BufferSignalsInput, EmitSignalInputs, TeamSignalGroupingV2Input
+from ee.billing.quota_limiting import self_driving_quota_resource
+
logger = structlog.get_logger(__name__)
# TODO: Check if the size of the buffer doesn't overload memory for the Temporal workflow handling the batch
@@ -95,7 +97,9 @@ async def check_signals_quota_limited_activity(input: CheckSignalsQuotaInput) ->
names the exact limit that fired; the workflow only acts on the boolean.
"""
team = await Team.objects.select_related("organization").aget(pk=input.team_id)
- quota_limited = await sync_to_async(is_team_signals_quota_limited, thread_sensitive=False)(team.api_token)
+ quota_limited = await sync_to_async(is_team_signals_quota_limited, thread_sensitive=False)(
+ team.api_token, self_driving_quota_resource(team.organization)
+ )
daily_gate = await database_sync_to_async(daily_report_limit_gate, thread_sensitive=False)(team)
# Captured whenever the daily gate binds — even when the quota drop below wins the
# single-reason drop metric — so the daily-limit event stream stays complete on co-bound days.
diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.py
index fdcddcbad11c..ce44ae2aa898 100644
--- a/products/signals/backend/temporal/summary.py
+++ b/products/signals/backend/temporal/summary.py
@@ -306,6 +306,9 @@ def _is_research_sandbox_unavailable(error: BaseException) -> bool:
@temporalio.workflow.defn(name="signal-report-summary")
class SignalReportSummaryWorkflow:
+ def __init__(self) -> None:
+ self._quota_admitted = False
+
@staticmethod
def parse_inputs(inputs: list[str]) -> SignalReportSummaryWorkflowInputs:
loaded = json.loads(inputs[0])
@@ -401,7 +404,9 @@ class SignalReportSummaryWorkflow:
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),
+ CheckReportQuotaGateInput(
+ team_id=inputs.team_id, report_id=inputs.report_id, stage=stage, admitted=self._quota_admitted
+ ),
start_to_close_timeout=timedelta(minutes=1),
retry_policy=RetryPolicy(maximum_attempts=3),
)
@@ -525,6 +530,9 @@ class SignalReportSummaryWorkflow:
):
log.info("Report run paused: org over self-driving credits quota", stage="summary_entry")
return False
+ # Pending signals and the implementation buffer may cause more research passes in
+ # this same pipeline. Admission covers all of them through the final implementation.
+ self._quota_admitted = True
claim_before_fetch = workflow.patched("signals-spend-explicit-owner")
signal_count = 0
source_products: list[str] = []
@@ -937,25 +945,23 @@ class SignalReportSummaryWorkflow:
raise
-@dataclass
+@frozen
class CheckReportQuotaGateInput:
team_id: int
report_id: str
stage: str
+ admitted: bool = False
@temporalio.activity.defn
@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 with enforcement on, or the team hit its daily report limit. Emits
- `signal_report_quota_paused` whenever the team is quota-limited, enforced or not, so the
- dark-launch would-block volume is measurable, and `signal_report_daily_limit_paused` when the
- daily limit binds; both fire when both limits are hit, keeping each event stream complete for
- its own gate. Never raises: any failure resolves to False (run proceeds), matching both
- modules' fail-open policy.
- """
+ """Check limits before accepting a report pipeline, never between its stages."""
+ # Existing histories still schedule these activities. Returning False preserves replay
+ # compatibility while letting the admitted pass finish repository selection and research.
+ if input.admitted or input.stage in {"pre_repo_selection", "pre_research"}:
+ return False
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)
diff --git a/products/signals/backend/test/test_auto_start.py b/products/signals/backend/test/test_auto_start.py
index bac48775bcdb..8c181e92b50a 100644
--- a/products/signals/backend/test/test_auto_start.py
+++ b/products/signals/backend/test/test_auto_start.py
@@ -1,5 +1,6 @@
import re
import json
+from contextlib import nullcontext
from datetime import timedelta
from types import SimpleNamespace
@@ -13,6 +14,7 @@ from asgiref.sync import async_to_sync, sync_to_async
from social_django.models import UserSocialAuth
from posthog.constants import AvailableFeature
+from posthog.exceptions import QuotaLimitExceeded
from posthog.models import Integration, Organization, Team, User
from posthog.models.organization import OrganizationMembership
from posthog.models.scoping import team_scope
@@ -31,6 +33,7 @@ from products.signals.backend.artefact_schemas import (
)
from products.signals.backend.auto_start import (
NO_SUPERSEDE,
+ AutostartOutcome,
ImplementationReportContent,
ReportChangedDuringAutostart,
ReportSteering,
@@ -1456,11 +1459,18 @@ async def test_a_non_link_skip_is_counted_under_its_own_reason_without_a_log_ent
@pytest.mark.asyncio
@pytest.mark.django_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.
+ ("status", "run_count", "enforced", "should_block"),
+ [
+ (SignalReport.Status.READY, 0, True, False),
+ (SignalReport.Status.IN_PROGRESS, 1, True, False),
+ (SignalReport.Status.CANDIDATE, 0, True, True),
+ (SignalReport.Status.CANDIDATE, 0, False, False),
+ ],
+)
+async def test_autostart_requires_admission_or_available_quota(
+ status: str, run_count: int, enforced: bool, should_block: bool
+) -> None:
Task = apps.get_model("tasks", "Task")
TaskRun = apps.get_model("tasks", "TaskRun")
@@ -1473,7 +1483,7 @@ async def test_quota_gate_blocks_autostart_only_when_enforced(enforced):
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
+ team=team, status=status, run_count=run_count, title="t", summary="s", signal_count=0, total_weight=0.0
)
return team, report
@@ -1486,16 +1496,17 @@ async def test_quota_gate_blocks_autostart_only_when_enforced(enforced):
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))
+ TaskRun.objects.create(task=task, team_id=team.id)
+ return task
with (
- patch.object(tasks_facade, "create_and_run_task", side_effect=_fake_create_and_run_task) as mock_create,
+ patch.object(Task, "create_and_run", side_effect=_fake_create_and_run_task),
patch("products.signals.backend.auto_start.resolve_agent_runtime", return_value=AgentRuntime()),
patch(
- "products.signals.backend.auto_start.self_driving_quota_gate",
+ "products.signals.backend.quota.self_driving_quota_gate",
return_value=SelfDrivingQuotaGate(limited=True, enforced=enforced),
),
+ pytest.raises(QuotaLimitExceeded) if should_block else nullcontext(),
):
await maybe_autostart_implementation_task(
team_id=team.id,
@@ -1512,7 +1523,7 @@ async def test_quota_gate_blocks_autostart_only_when_enforced(enforced):
priority=PriorityAssessment(explanation="Affects many sessions.", priority=Priority.P2),
)
- assert (mock_create.call_count == 0) is enforced
+ assert await Task.objects.filter(team_id=team.id).aexists() is not should_block
@pytest.mark.asyncio
@@ -1594,8 +1605,11 @@ async def test_free_trial_gate_blocks_autostart(
@pytest.mark.asyncio
@pytest.mark.django_db(transaction=True)
[email protected]("autostart_eligible", [True, False])
-async def test_repo_selection_eligibility_reaches_autostart(autostart_eligible):
+ ("autostart_eligible", "user_edit", "enforced"),
+ [(True, False, True), (False, False, True), (True, True, True), (True, True, False)],
+)
+async def test_reviewer_reevaluation_checks_quota_only_for_a_fresh_user_edit(autostart_eligible, user_edit, enforced):
# The re-eval reads the flag off the persisted artefact and hands it to autostart rather than
# deciding for itself, so a reviewer edit arriving later still gets the whole gate applied.
def _setup() -> tuple[Team, SignalReport]:
@@ -1633,9 +1647,25 @@ async def test_repo_selection_eligibility_reaches_autostart(autostart_eligible):
team, report = await sync_to_async(_setup)()
- with patch("products.signals.backend.auto_start.maybe_autostart_implementation_task") as mock_autostart:
- await maybe_autostart_from_report_artefacts(team_id=team.id, report_id=str(report.id))
+ with (
+ patch(
+ "products.signals.backend.auto_start.maybe_autostart_implementation_task",
+ return_value=AutostartOutcome(status="started"),
+ ) as mock_autostart,
+ patch(
+ "products.signals.backend.auto_start.self_driving_quota_gate",
+ return_value=SelfDrivingQuotaGate(limited=True, enforced=enforced),
+ ),
+ patch("products.signals.backend.auto_start._latest_reviewers_content", return_value=([], 123)),
+ ):
+ outcome = await maybe_autostart_from_report_artefacts(
+ team_id=team.id, report_id=str(report.id), triggering_user_id=123 if user_edit else None
+ )
+ assert outcome.status == ("blocked" if user_edit and enforced else "started")
+ if user_edit and enforced:
+ mock_autostart.assert_not_called()
+ return
assert mock_autostart.call_args.kwargs["repository_autostart_eligible"] is autostart_eligible
diff --git a/products/signals/backend/test/test_billing.py b/products/signals/backend/test/test_billing.py
index 5bbf9922613c..6dc8c4ef5fa0 100644
--- a/products/signals/backend/test/test_billing.py
+++ b/products/signals/backend/test/test_billing.py
@@ -1,5 +1,5 @@
-from datetime import UTC, datetime
-from typing import TYPE_CHECKING
+from datetime import UTC, datetime, timedelta
+from typing import TYPE_CHECKING, cast
from uuid import uuid4
import time_machine
@@ -7,10 +7,13 @@ from posthog.test.base import BaseTest
from unittest.mock import patch
from django.apps import apps
+from django.utils import timezone
from parameterized import parameterized
from posthog.models import Organization, Team
+from posthog.models.organization import OrganizationUsageInfo
+from posthog.tasks.usage_report import get_teams_with_signals_spend_credits_used_in_period
from products.signals.backend.artefact_schemas import TASK_RUN_TYPE_IMPLEMENTATION, TASK_RUN_TYPE_RESEARCH
from products.signals.backend.billing import (
@@ -18,7 +21,9 @@ from products.signals.backend.billing import (
BillingExemptionError,
FirstBillablePrRun,
_bridges_with_pr_run,
+ annotate_first_billable_pr_run_at,
first_billable_pr_run,
+ first_billable_pr_run_at_by_report,
get_signals_billing_credits_by_team,
mark_report_billing_exempt,
system_billing_exempt_reason,
@@ -31,8 +36,28 @@ from products.signals.backend.models import (
SignalSpend,
)
from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, _compute_row_hash
+from products.signals.backend.spend import (
+ complete_signal_pipeline,
+ finish_report_spend,
+ record_llm_spend,
+ record_task_spend,
+)
+from products.signals.backend.spend_billing import (
+ get_signals_spend_billing_credits_by_team,
+ get_signals_spend_quota_credits_by_team,
+)
from products.skills.backend.models.skills import LLMSkill
+from ee.billing.quota_limiting import (
+ QuotaLimitingCaches,
+ QuotaResource,
+ list_limited_team_attributes,
+ org_quota_limited_until,
+ self_driving_quota_resource,
+ set_org_usage_summary,
+ update_all_orgs_billing_quotas,
+)
+
if TYPE_CHECKING:
from products.tasks.backend.models import (
Task as TaskModel,
@@ -98,7 +123,10 @@ def _make_pr_run(
)
SignalReportTask.objects.create(team=team, report=report, task=task, relationship=relationship)
run_output = output if output is not _UNSET else ({"pr_url": pr_url} if pr_url is not None else {})
- return TaskRun.objects.create(team=team, task=task, output=run_output, created_at=created_at)
+ run = TaskRun.objects.create(team=team, task=task, output=run_output, created_at=created_at)
+ if relationship == TASK_RUN_TYPE_IMPLEMENTATION:
+ record_task_spend(team_id=team.id, run_id=str(run.id), report_id=str(report.id), stage="implementation")
+ return run
def _make_refund(report: SignalReport, *, billing_path: str, pr_run_created_at: datetime | None = None) -> None:
@@ -138,8 +166,8 @@ class TestSignalsBilling(BaseTest):
# 1 credit = $0.01, so $15 == 1500 credits.
self.assertEqual(SIGNALS_CREDITS_PER_REPORT_WITH_PR, 1500)
- @parameterized.expand([(False,), (True,)])
- def test_organization_filter_excludes_other_organizations(self, as_list: bool) -> None:
+ @parameterized.expand([(as_list, usage_billing) for as_list in (False, True) for usage_billing in (False, True)])
+ def test_organization_filter_excludes_other_organizations(self, as_list: bool, usage_billing: bool) -> None:
other_team = Team.objects.create(organization=Organization.objects.create(name="Other org"))
with time_machine.travel(_at(10), tick=False):
for team in (self.team, other_team):
@@ -149,17 +177,20 @@ class TestSignalsBilling(BaseTest):
kind=SignalSpend.Kind.AD_HOC,
signal_id=uuid4(),
spend=20,
+ usage_billing=usage_billing,
finalized_at=_at(10),
)
org_filter = (
{"organization_ids": [self.organization.id]} if as_list else {"organization_id": self.organization.id}
)
- with patch("posthoganalytics.get_feature_flag", return_value="2026-06-01") as flag:
- self.assertEqual(
- dict(get_signals_billing_credits_by_team(PERIOD_START, PERIOD_END, **org_filter)),
- {self.team.id: 1500},
- )
- flag.assert_not_called()
+ if usage_billing:
+ self.organization.usage = {"signals_spend_credits": {"billing_start_date": "2026-06-01"}}
+ self.organization.save(update_fields=["usage"])
+ counter = get_signals_spend_billing_credits_by_team if usage_billing else get_signals_billing_credits_by_team
+ self.assertEqual(
+ dict(counter(PERIOD_START, PERIOD_END, **org_filter)), {self.team.id: 20 if usage_billing else 1500}
+ )
+ self.assertEqual(counter(PERIOD_START, PERIOD_END, organization_ids=[]), [])
@parameterized.expand([(None, 1500), ("posthog_ai", 0)])
def test_report_with_pr_billed_only_when_not_billed_as_phai(self, product: str | None, credits: int) -> None:
@@ -532,3 +563,399 @@ class TestBillingExemptions(BaseTest):
unproven_report = _make_report(self.team)
self._scout_run("signals-scout-health-checks", [str(unproven_report.id)])
self.assertIsNone(system_billing_exempt_reason(self.team.id, unproven_report.id))
+
+
+class TestSpendBasedBilling(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.cutoff = "2026-06-10"
+ trial = patch("products.signals.backend.spend_billing.posthoganalytics.feature_enabled", return_value=False)
+ self.trial_mock = trial.start()
+ self.addCleanup(trial.stop)
+
+ @property
+ def cutoff(self) -> str | None:
+ return (self.organization.usage or {}).get("signals_spend_credits", {}).get("billing_start_date")
+
+ @cutoff.setter
+ def cutoff(self, value: str | None) -> None:
+ self.organization.usage = {"signals_spend_credits": {"billing_start_date": value}} if value else {}
+ self.organization.usage["period"] = [PERIOD_START.isoformat(), PERIOD_END.isoformat()]
+ self.organization.save(update_fields=["usage"])
+
+ def _generation(
+ self, signal_id: str, cost: int | None, *, request_id: str = "request", team: Team | None = None
+ ) -> None:
+ record_llm_spend(
+ token_cost_microusd=cost, team_id=(team or self.team).id, signal_id=signal_id, stage="grouping"
+ )
+
+ def _day(self, day: int, *, organization_id: str | None = None) -> dict[int, int]:
+ begin = _at(day, 0)
+ return dict(get_signals_spend_billing_credits_by_team(begin, begin + timedelta(days=1), organization_id))
+
+ def test_unknown_generation_cost_never_becomes_billable(self) -> None:
+ signal_id = str(uuid4())
+ with time_machine.travel(_at(10), tick=False):
+ self._generation(signal_id, None)
+ complete_signal_pipeline(team_id=self.team.id, signal_id=signal_id)
+ assert self._day(10) == {}
+ with time_machine.travel(_at(11), tick=False):
+ self._generation(signal_id, 120_000)
+ complete_signal_pipeline(team_id=self.team.id, signal_id=signal_id)
+ assert self._day(10) == {}
+ assert self._day(11) == {}
+ assert SignalSpend.objects.for_team(self.team.id).get(signal_id=signal_id).accounting_failed
+
+ def test_new_signal_preserves_prior_days_and_bills_only_its_own_spend(self) -> None:
+ signal_id, next_signal_id = str(uuid4()), str(uuid4())
+ with time_machine.travel(_at(10), tick=False):
+ self._generation(signal_id, 100_000)
+ assert self._day(10) == {}
+ complete_signal_pipeline(team_id=self.team.id, signal_id=signal_id)
+ with time_machine.travel(_at(11), tick=False):
+ self._generation(next_signal_id, 50_000, request_id="resumed-work")
+ assert self._day(10) == {self.team.id: 10}
+ assert self._day(11) == {}
+ complete_signal_pipeline(team_id=self.team.id, signal_id=next_signal_id)
+ complete_signal_pipeline(team_id=self.team.id, signal_id=next_signal_id)
+ assert self._day(10) == {self.team.id: 10}
+ assert self._day(11) == {self.team.id: 5}
+ assert dict(get_signals_spend_billing_credits_by_team(PERIOD_START, PERIOD_END)) == {self.team.id: 15}
+ assert SignalSpend.objects.for_team(self.team.id).count() == 2
+ assert dict(get_signals_spend_billing_credits_by_team(_at(10, 0), _at(10))) == {}
+ assert dict(get_signals_spend_billing_credits_by_team(_at(10), _at(10) + timedelta(microseconds=1))) == {
+ self.team.id: 10
+ }
+ assert dict(get_signals_spend_billing_credits_by_team(_at(10) + timedelta(microseconds=1), _at(11))) == {}
+ assert dict(get_signals_spend_billing_credits_by_team(_at(10), _at(10))) == {}
+
+ @parameterized.expand([(kind,) for kind in SignalSpend.Kind.values])
+ def test_quota_refresh_counts_running_and_settled_spend_once_before_daily_reporting(self, kind: str) -> None:
+ self.organization.usage = {
+ "signals_spend_credits": {"usage": 90, "todays_usage": 0, "limit": 100, "billing_start_date": "2026-06-10"},
+ "period": ["2026-06-01T00:00:00Z", "2026-07-01T00:00:00Z"],
+ }
+ self.organization.customer_trust_scores = {}
+ self.organization.save()
+ signal_id = str(uuid4())
+ with time_machine.travel(_at(9), tick=False):
+ report = _make_report(self.team)
+ with time_machine.travel(_at(10), tick=False):
+ scout = None
+ if kind == SignalSpend.Kind.SCOUT_RUN:
+ task = _task_model().objects.create(team=self.team, title="Synthetic scout", description="")
+ run = _task_run_model().objects.create(team=self.team, task=task)
+ scout = SignalScoutRun.objects.for_team(self.team.id).create(
+ team=self.team, task_run=run, skill_name="example-scout", skill_version=1
+ )
+ signal_owned = kind in {SignalSpend.Kind.AD_HOC, SignalSpend.Kind.RESEARCH, SignalSpend.Kind.REPO_SELECTION}
+ spend = SignalSpend.objects.for_team(self.team.id).create(
+ team=self.team,
+ kind=kind,
+ signal_id=signal_id if signal_owned else None,
+ scout_run=scout,
+ report=None if signal_owned or scout else report,
+ task_run_id=(scout.task_run_id if scout else uuid4()) if kind != SignalSpend.Kind.AD_HOC else None,
+ spend=20,
+ usage_billing=True,
+ )
+ assert self._day(10) == {}
+ with time_machine.travel(_at(10) + timedelta(minutes=10), tick=False):
+ for finalized in (False, True):
+ if finalized:
+ spend.finalized_at = _at(10)
+ spend.save(update_fields=["finalized_at"])
+ update_all_orgs_billing_quotas()
+ self.organization.refresh_from_db()
+ assert self.organization.usage is not None
+ assert self.organization.usage["signals_spend_credits"]["usage"] == 90
+ assert self.organization.usage["signals_spend_credits"]["todays_usage"] == 20
+ assert self.team.api_token in list_limited_team_attributes(
+ QuotaResource.SIGNALS_SPEND_CREDITS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY
+ )
+ assert self._day(10) == ({self.team.id: 20} if finalized else {})
+ mark_report_billing_exempt(report, SignalReport.BillingExemptReason.POSTHOG_SYSTEM)
+ assert self._day(10) == {self.team.id: 20}
+ with time_machine.travel(_at(11), tick=False):
+ assert dict(get_teams_with_signals_spend_credits_used_in_period(_at(10, 0), _at(11, 0))) == {
+ self.team.id: 20
+ }
+
+ def test_plan_changes_only_change_the_meter_for_new_work(self) -> None:
+ legacy, usage = str(uuid4()), str(uuid4())
+ self.cutoff = "2026-06-20"
+ with time_machine.travel(_at(10), tick=False):
+ legacy_report = _make_report(self.team)
+ _make_pr_run(self.team, legacy_report, created_at=_at(10))
+ self._generation(legacy, 100_000, request_id="legacy")
+ assert dict(get_signals_billing_credits_by_team(PERIOD_START, PERIOD_END)) == {self.team.id: 1500}
+ self.cutoff = "2026-06-01"
+ with time_machine.travel(_at(11), tick=False):
+ usage_report = _make_report(self.team)
+ _make_pr_run(self.team, usage_report, created_at=_at(11))
+ self._generation(usage, 200_000, request_id="usage")
+ complete_signal_pipeline(team_id=self.team.id, signal_id=legacy)
+ complete_signal_pipeline(team_id=self.team.id, signal_id=usage)
+ assert dict(get_signals_billing_credits_by_team(PERIOD_START, PERIOD_END)) == {self.team.id: 1500}
+ assert first_billable_pr_run(legacy_report.id, team_id=self.team.id) is not None
+ assert first_billable_pr_run(usage_report.id, team_id=self.team.id) is None
+ assert self._day(10) == {}
+ assert self._day(11, organization_id=str(self.organization.id)) == {self.team.id: 20}
+ self.cutoff = "2026-06-30"
+ assert dict(get_signals_billing_credits_by_team(PERIOD_START, PERIOD_END)) == {self.team.id: 1500}
+ assert self._day(11) == {self.team.id: 20}
+
+ @parameterized.expand([("settling", False, 20), ("failed", True, 0)])
+ def test_only_settling_spend_in_current_billing_period_counts_towards_quota(
+ self, _name: str, failed: bool, expected_credits: int
+ ) -> None:
+ with time_machine.travel(_at(10), tick=False):
+ self._generation(str(uuid4()), 200_000)
+ if failed:
+ SignalSpend.objects.for_team(self.team.id).update(accounting_failed=True)
+ with time_machine.travel(_at(11), tick=False):
+ assert dict(get_signals_spend_quota_credits_by_team(_at(11, 0), _at(12, 0))) == (
+ {self.team.id: expected_credits} if expected_credits else {}
+ )
+ assert self.organization.usage is not None
+ self.organization.usage["period"] = ["2026-07-01T00:00:00Z", "2026-08-01T00:00:00Z"]
+ self.organization.save(update_fields=["usage"])
+ with time_machine.travel("2026-07-02T12:00:00Z", tick=False):
+ assert dict(get_signals_spend_quota_credits_by_team(PERIOD_END, datetime(2026, 8, 1, tzinfo=UTC))) == {}
+ assert self._day(10) == {}
+
+ @parameterized.expand([("report",), ("signal",)])
+ def test_legacy_report_charge_and_new_signal_spend_are_independent(self, existing_work: str) -> None:
+ legacy_signal = str(uuid4())
+ with time_machine.travel(_at(9), tick=False):
+ legacy_report = _make_report(self.team) if existing_work == "report" else None
+ if existing_work == "signal":
+ self._generation(legacy_signal, 50_000, request_id="existing-signal")
+ with time_machine.travel(_at(10), tick=False):
+ if legacy_report is None:
+ legacy_report = SignalReport.objects.create(team=self.team, triggering_signal_id=legacy_signal)
+ _make_pr_run(self.team, legacy_report, created_at=_at(10))
+ self._generation(legacy_signal, 100_000, request_id="existing-report")
+ complete_signal_pipeline(team_id=self.team.id, signal_id=legacy_signal, report_id=str(legacy_report.id))
+ signal_id = str(uuid4())
+ self._generation(signal_id, 250_000, request_id="new-report")
+ report = SignalReport.objects.create(
+ team=self.team,
+ status=SignalReport.Status.READY,
+ triggering_signal_id=signal_id,
+ )
+ _make_pr_run(self.team, report, created_at=_at(10))
+ complete_signal_pipeline(team_id=self.team.id, signal_id=signal_id, report_id=str(report.id))
+ finish_report_spend(team_id=self.team.id, signal_id=signal_id, report_id=str(report.id))
+ expected = 35 if existing_work == "report" else 25
+ assert self._day(10) == {self.team.id: expected}
+ assert first_billable_pr_run(report.id, team_id=report.team_id) is None
+ assert first_billable_pr_run(legacy_report.id, team_id=legacy_report.team_id) is None
+ reports = SignalReport.objects.filter(id__in=[report.id, legacy_report.id])
+ expected_refundable: set[str] = set()
+ assert (
+ set(first_billable_pr_run_at_by_report([report.id, legacy_report.id], team_id=self.team.id))
+ == expected_refundable
+ )
+ with self.assertNumQueries(1):
+ annotated = list(annotate_first_billable_pr_run_at(reports))
+ assert {
+ str(row.id) for row in annotated if row.__dict__["first_billable_pr_run_at"] is not None
+ } == expected_refundable
+ SignalReport.objects.filter(id=report.id).update(triggering_signal_id=legacy_signal)
+ assert self._day(10) == {self.team.id: expected}
+ assert first_billable_pr_run(report.id, team_id=report.team_id) is None
+
+ def test_rounding_is_per_team_day_and_period_recounts_match_daily_reports(self) -> None:
+ other_org = Organization.objects.create(
+ name="Synthetic billing organization", usage={"signals_spend_credits": {"billing_start_date": "2026-06-10"}}
+ )
+ other_team = Team.objects.create(organization=other_org)
+ with time_machine.travel(_at(10, 0), tick=False):
+ for team in (self.team, other_team):
+ for _ in range(2):
+ signal_id = str(uuid4())
+ self._generation(signal_id, 6_000, request_id=signal_id, team=team)
+ complete_signal_pipeline(team_id=team.id, signal_id=signal_id)
+ with time_machine.travel(_at(10, 23), tick=False):
+ signal_id = str(uuid4())
+ self._generation(signal_id, 6_000, request_id=signal_id)
+ complete_signal_pipeline(team_id=self.team.id, signal_id=signal_id)
+ with time_machine.travel(_at(11, 0), tick=False):
+ signal_id = str(uuid4())
+ self._generation(signal_id, 6_000, request_id=signal_id)
+ complete_signal_pipeline(team_id=self.team.id, signal_id=signal_id)
+ self._generation(str(uuid4()), 6_000, request_id="still-running")
+ assert dict(get_signals_spend_quota_credits_by_team(PERIOD_START, PERIOD_END)) == {
+ self.team.id: 3,
+ other_team.id: 1,
+ }
+ with timezone.override("Pacific/Kiritimati"):
+ assert self._day(10) == {self.team.id: 2, other_team.id: 1}
+ assert self._day(10, organization_id=str(self.organization.id)) == {self.team.id: 2}
+ assert dict(get_signals_spend_billing_credits_by_team(PERIOD_START, PERIOD_END, self.organization.id)) == {
+ self.team.id: 3
+ }
+ other_org.usage = {"signals_spend_credits": {"billing_start_date": "2026-06-11"}}
+ other_org.save(update_fields=["usage"])
+ assert self._day(10) == {self.team.id: 2, other_team.id: 1}
+ assert self._day(10, organization_id=str(other_org.id)) == {other_team.id: 1}
+
+ @parameterized.expand([("source",), ("report",)])
+ def test_system_funded_work_keeps_spend_but_does_not_bill(self, exemption: str) -> None:
+ signal_id = str(uuid4())
+ with time_machine.travel(_at(10), tick=False):
+ self._generation(signal_id, 100_000)
+ report = None
+ if exemption == "report":
+ report = SignalReport.objects.create(
+ team=self.team,
+ status=SignalReport.Status.READY,
+ billing_exempt_reason=SignalReport.BillingExemptReason.POSTHOG_SYSTEM,
+ )
+ complete_signal_pipeline(
+ team_id=self.team.id,
+ signal_id=signal_id,
+ report_id=str(report.id) if report else None,
+ billing_exempt=exemption == "source",
+ )
+ assert self._day(10) == {}
+ spend = SignalSpend.objects.for_team(self.team.id).get(signal_id=signal_id)
+ assert spend.spend == 10
+ self.assertIsNotNone(spend.finalized_at)
+
+ @parameterized.expand([("trial", True), ("unknown", None)])
+ def test_trial_flag_does_not_change_billing_meter(self, _name: str, trial: bool | None) -> None:
+ self.trial_mock.return_value = trial
+ signal_id = str(uuid4())
+ with time_machine.travel(_at(10), tick=False):
+ report = _make_report(self.team)
+ _make_pr_run(self.team, report, created_at=_at(10))
+ self._generation(signal_id, 100_000)
+ complete_signal_pipeline(team_id=self.team.id, signal_id=signal_id, report_id=str(report.id))
+ assert self._day(10) == ({} if trial is True else {self.team.id: 10})
+
+ def test_ending_trial_does_not_bill_its_settled_spend(self) -> None:
+ signal_id = str(uuid4())
+ with time_machine.travel(_at(10), tick=False):
+ self.trial_mock.return_value = True
+ self._generation(signal_id, 100_000)
+ complete_signal_pipeline(team_id=self.team.id, signal_id=signal_id)
+ self.trial_mock.return_value = False
+ assert self._day(10) == {}
+ assert SignalSpend.objects.for_team(self.team.id).get(signal_id=signal_id).billing_exempt
+
+ def test_scout_deletion_preserves_recognized_billing(self) -> None:
+ task = _task_model().objects.create(team=self.team, title="Synthetic scout", description="")
+ run = _task_run_model().objects.create(team=self.team, task=task)
+ scout = SignalScoutRun.objects.for_team(self.team.id).create(
+ team=self.team, task_run=run, skill_name="synthetic-scout", skill_version=1
+ )
+ SignalSpend.objects.for_team(self.team.id).create(
+ team=self.team,
+ scout_run=scout,
+ task_run_id=run.id,
+ kind=SignalSpend.Kind.SCOUT_RUN,
+ usage_billing=True,
+ finalized_at=_at(10),
+ spend=4,
+ )
+ scout.delete()
+ assert self._day(10) == {self.team.id: 4}
+
+ def test_finalized_spend_ignores_subsequent_source_changes(self) -> None:
+ signal_id = str(uuid4())
+ with time_machine.travel(_at(10), tick=False):
+ self._generation(signal_id, 100_000)
+ complete_signal_pipeline(team_id=self.team.id, signal_id=signal_id)
+ with time_machine.travel(_at(11), tick=False):
+ with self.assertRaises(ValueError):
+ self._generation(signal_id, 90_000)
+ complete_signal_pipeline(team_id=self.team.id, signal_id=signal_id)
+ spend = SignalSpend.objects.for_team(self.team.id).get(signal_id=signal_id)
+ assert not spend.accounting_failed
+ self.assertIsNotNone(spend.finalized_at)
+ assert spend.spend == 10
+ assert self._day(10) == {self.team.id: 10}
+ assert self._day(11) == {}
+
+ @parameterized.expand(
+ [
+ (None, QuotaResource.SIGNALS_CREDITS),
+ ("2026-06-20", QuotaResource.SIGNALS_CREDITS),
+ ("2026-06-10", QuotaResource.SIGNALS_SPEND_CREDITS),
+ ]
+ )
+ @time_machine.travel(_at(11), tick=False)
+ def test_billing_response_selects_active_meter(self, cutoff: str | None, expected: QuotaResource) -> None:
+ self.organization.usage = {"signals_spend_credits": {"billing_start_date": "2026-06-10", "limit": 20}}
+ spend_usage: dict[str, int | str] = {"usage": 25, "limit": 20}
+ if cutoff:
+ spend_usage["billing_start_date"] = cutoff
+ set_org_usage_summary(
+ self.organization,
+ cast(
+ OrganizationUsageInfo,
+ {
+ "signals_spend_credits": spend_usage,
+ "signals_credits": {"usage": 4500, "limit": 3000},
+ "period": [_at(1, 0).isoformat(), _at(30, 0).isoformat()],
+ },
+ ),
+ )
+ assert self_driving_quota_resource(self.organization) == expected
+ for resource in (QuotaResource.SIGNALS_CREDITS, QuotaResource.SIGNALS_SPEND_CREDITS):
+ assert bool(org_quota_limited_until(self.organization, resource, [])) == (resource == expected)
+
+ def test_distinct_meters_use_billing_cutoff_and_run_age(self) -> None:
+ self.organization.usage = {"signals_spend_credits": {"billing_start_date": "2026-06-10", "limit": 1000}}
+ self.organization.save(update_fields=["usage"])
+ with time_machine.travel(_at(9), tick=False):
+ old_report = _make_report(self.team)
+ legacy_report = _make_report(self.team)
+ SignalSpend.objects.for_team(self.team.id).create(
+ team=self.team,
+ signal_id=uuid4(),
+ kind=SignalSpend.Kind.AD_HOC,
+ spend=500,
+ finalized_at=_at(10),
+ )
+ _make_pr_run(self.team, legacy_report, created_at=_at(9))
+ _make_pr_run(self.team, old_report, created_at=_at(10))
+ with time_machine.travel(_at(10), tick=False):
+ SignalSpend.objects.for_team(self.team.id).create(
+ team=self.team,
+ signal_id=uuid4(),
+ kind=SignalSpend.Kind.AD_HOC,
+ spend=25,
+ usage_billing=True,
+ finalized_at=_at(10),
+ )
+ with patch("posthoganalytics.get_feature_flag", side_effect=RuntimeError("unavailable")):
+ assert dict(get_signals_billing_credits_by_team(_at(9, 0), _at(11, 0))) == {self.team.id: 1500}
+ assert dict(get_signals_spend_billing_credits_by_team(_at(9, 0), _at(11, 0))) == {self.team.id: 25}
+ assert dict(get_signals_billing_credits_by_team(_at(10, 0), _at(11, 0))) == {}
+
+ @parameterized.expand([("missing", {}), ("default_plan", {"usage": 0, "limit": 0})])
+ def test_unenrolled_org_reports_only_legacy_usage(self, _name: str, spend_usage: dict) -> None:
+ set_org_usage_summary(
+ self.organization,
+ cast(OrganizationUsageInfo, {"signals_spend_credits": spend_usage, "events": {"usage": 12, "limit": 100}}),
+ )
+ self.organization.save(update_fields=["usage"])
+ assert self_driving_quota_resource(self.organization) == QuotaResource.SIGNALS_CREDITS
+ assert self.organization.usage is not None
+ assert self.organization.usage["events"]["usage"] == 12
+ with time_machine.travel(_at(10), tick=False):
+ report = _make_report(self.team)
+ _make_pr_run(self.team, report, created_at=_at(10))
+ SignalSpend.objects.for_team(self.team.id).create(
+ team=self.team,
+ signal_id=uuid4(),
+ kind=SignalSpend.Kind.AD_HOC,
+ spend=25,
+ finalized_at=_at(10),
+ )
+ assert dict(get_signals_spend_billing_credits_by_team(_at(10, 0), _at(10, 0) + timedelta(days=1))) == {}
+ assert dict(get_signals_billing_credits_by_team(_at(10, 0), _at(11, 0))) == {self.team.id: 1500}
diff --git a/products/signals/backend/test/test_buffer_workflow.py b/products/signals/backend/test/test_buffer_workflow.py
index a7d5d34cd14e..44de24696db1 100644
--- a/products/signals/backend/test/test_buffer_workflow.py
+++ b/products/signals/backend/test/test_buffer_workflow.py
@@ -3,6 +3,7 @@ import asyncio
from contextlib import suppress
import pytest
+import time_machine
from unittest.mock import patch
from temporalio import activity
@@ -11,6 +12,8 @@ from temporalio.service import RPCError
from temporalio.testing import ActivityEnvironment, WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+from posthog.models import Organization
+
from products.signals.backend.daily_limit import DailyReportLimitGate
from products.signals.backend.temporal.buffer import (
BufferSignalsWorkflow,
@@ -23,6 +26,8 @@ from products.signals.backend.temporal.buffer import (
from products.signals.backend.temporal.safety_filter import SafetyFilterInput, SafetyFilterOutput
from products.signals.backend.temporal.types import BufferSignalsInput, EmitSignalInputs
+from ee.billing.quota_limiting import QuotaResource
+
TASK_QUEUE = "test-buffer-queue"
BUFFER_MODULE = "products.signals.backend.temporal.buffer"
@@ -144,6 +149,8 @@ async def test_safety_failure_requeues_only_failed_signals(mixed_batch: bool):
@pytest.mark.asyncio
@pytest.mark.django_db
+@time_machine.travel("2026-06-10", tick=False)
[email protected]("spend_billing", [False, True])
@pytest.mark.parametrize(
("billing_limited", "daily_limited", "expected", "expected_reason"),
[
@@ -154,10 +161,14 @@ async def test_safety_failure_requeues_only_failed_signals(mixed_batch: bool):
],
)
async def test_check_activity_attributes_drop_to_the_limit_that_fired(
- ateam, billing_limited, daily_limited, expected, expected_reason
+ ateam, billing_limited, daily_limited, expected, expected_reason, spend_billing
):
+ if spend_billing:
+ await Organization.objects.filter(id=ateam.organization_id).aupdate(
+ usage={"signals_spend_credits": {"billing_start_date": "2026-06-10"}}
+ )
with (
- patch(f"{BUFFER_MODULE}.is_team_signals_quota_limited", return_value=billing_limited),
+ patch(f"{BUFFER_MODULE}.is_team_signals_quota_limited", return_value=billing_limited) as quota_check,
patch(
f"{BUFFER_MODULE}.daily_report_limit_gate",
return_value=DailyReportLimitGate(limited=daily_limited, limit=2, reports_today=2),
@@ -173,6 +184,9 @@ async def test_check_activity_attributes_drop_to_the_limit_that_fired(
)
assert result is expected
+ quota_check.assert_called_once_with(
+ ateam.api_token, QuotaResource.SIGNALS_SPEND_CREDITS if spend_billing else QuotaResource.SIGNALS_CREDITS
+ )
dropped_events = [c.kwargs for c in analytics_capture.call_args_list if c.kwargs["event"] == "signal_dropped"]
if expected_reason is None:
dropped.assert_not_called()
diff --git a/products/signals/backend/test/test_quota.py b/products/signals/backend/test/test_quota.py
index 3ac5d929f53a..2c45d1e3cff1 100644
--- a/products/signals/backend/test/test_quota.py
+++ b/products/signals/backend/test/test_quota.py
@@ -2,6 +2,7 @@ from types import SimpleNamespace
from typing import TYPE_CHECKING, cast
import pytest
+import time_machine
from unittest.mock import patch
from products.signals.backend.quota import (
@@ -11,13 +12,22 @@ from products.signals.backend.quota import (
self_driving_quota_gate,
)
+from ee.billing.quota_limiting import QuotaResource
+
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"))
+ # Keep quota-gate tests independent of the database.
+ return cast(
+ "Team",
+ SimpleNamespace(
+ api_token="phc_token",
+ organization_id="0195a000-0000-0000-0000-000000000000",
+ organization=SimpleNamespace(usage={}),
+ ),
+ )
@pytest.mark.parametrize(
@@ -29,7 +39,7 @@ def _team() -> "Team":
)
def test_reflects_quota_limiter(limited, expected):
with patch("products.signals.backend.quota.is_team_limited", return_value=limited) as mock_limited:
- assert is_team_signals_quota_limited("phc_token") is expected
+ assert is_team_signals_quota_limited("phc_token", QuotaResource.SIGNALS_CREDITS) is expected
# Always queries the signals_credits resource for the given token.
args = mock_limited.call_args.args
assert args[0] == "phc_token"
@@ -38,14 +48,14 @@ def test_reflects_quota_limiter(limited, expected):
def test_fails_open_on_error():
with patch("products.signals.backend.quota.is_team_limited", side_effect=RuntimeError("redis down")):
- assert is_team_signals_quota_limited("phc_token") is False
+ assert is_team_signals_quota_limited("phc_token", QuotaResource.SIGNALS_CREDITS) is False
def test_fail_open_metric_noops_outside_activity():
# The fail-open counter only records inside a Temporal activity; outside one it must not raise.
with patch("products.signals.backend.quota.is_team_limited", side_effect=RuntimeError("redis down")):
with patch("products.signals.backend.quota.get_metric_meter") as mock_meter:
- assert is_team_signals_quota_limited("phc_token") is False
+ assert is_team_signals_quota_limited("phc_token", QuotaResource.SIGNALS_CREDITS) is False
mock_meter.assert_not_called()
@@ -127,3 +137,37 @@ def test_scout_quota_notification_is_idempotent_per_limiting_episode(first_usage
keys = [call.args[0].idempotency_key for call in create.call_args_list]
assert (keys[0] != keys[1]) is notifies_again
assert all(key.startswith("signals_scout_quota_paused:0195a000-0000-0000-0000-000000000000:") for key in keys)
+
+
+@time_machine.travel("2026-06-15T12:00:00Z", tick=False)
+ "cutover,limit_name",
+ [(None, "pull request limit"), ("2026-06-16", "pull request limit"), ("2026-06-15", "spending limit")],
+)
+def test_limit_messages_follow_the_billing_cutover(cutover, limit_name):
+ from posthog.exceptions import QuotaLimitExceeded
+
+ from products.signals.backend.scout_harness.run_gates import check_spend_gates
+ from products.tasks.backend.facade.api import enforce_self_driving_pr_quota
+
+ team = _team()
+ team.id = 7
+ team.organization.usage = {"signals_spend_credits": {"billing_start_date": cutover}} if cutover else {}
+ with (
+ patch("products.signals.backend.quota.self_driving_quota_gate", return_value=SelfDrivingQuotaGate(True, True)),
+ patch(
+ "products.signals.backend.scout_harness.run_gates.self_driving_quota_gate",
+ return_value=SelfDrivingQuotaGate(True, True),
+ ),
+ patch("products.signals.backend.quota.capture_signal_report_quota_paused"),
+ patch("products.notifications.backend.facade.api.create_notification") as notification,
+ ):
+ with pytest.raises(QuotaLimitExceeded, match=limit_name):
+ enforce_self_driving_pr_quota(team)
+ rejection = check_spend_gates(team, capture_analytics=False)
+ assert rejection is not None and limit_name in rejection.detail
+ notify_scout_quota_paused(team)
+ message = notification.call_args.args[0]
+ assert limit_name in message.title
+ assert limit_name in message.body
+ assert "Work already underway will finish" in message.body
diff --git a/products/signals/backend/test/test_requested_implementation.py b/products/signals/backend/test/test_requested_implementation.py
index 482423761a75..d1cf89a3b42c 100644
--- a/products/signals/backend/test/test_requested_implementation.py
+++ b/products/signals/backend/test/test_requested_implementation.py
@@ -19,6 +19,7 @@ from products.signals.backend.auto_start import (
start_requested_implementation,
)
from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportTask, SignalSpend
+from products.signals.backend.quota import SelfDrivingQuotaGate
from products.signals.backend.report_generation.research import ActionabilityAssessment, ActionabilityChoice
from products.signals.backend.report_generation.select_repo import RepoSelectionResult
from products.signals.backend.spend import record_task_spend
@@ -116,7 +117,9 @@ class TestRequestedImplementation(BaseTest):
with (
patch("products.signals.backend.auto_start.task_run_usage_limited", return_value=False),
- patch.object(tasks_facade, "enforce_self_driving_pr_quota"),
+ patch(
+ "products.signals.backend.quota.self_driving_quota_gate", return_value=SelfDrivingQuotaGate(True, True)
+ ),
patch(
"products.signals.backend.auto_start.self_driving_free_trial_enabled", return_value=False
) as free_trial_flag,
@@ -167,7 +170,6 @@ class TestRequestedImplementation(BaseTest):
)
with (
patch("products.signals.backend.auto_start.task_run_usage_limited", return_value=False),
- patch.object(tasks_facade, "enforce_self_driving_pr_quota"),
patch.object(tasks_facade, "run_task") as run_task,
):
try:
@@ -219,7 +221,6 @@ class TestRequestedImplementation(BaseTest):
with (
patch("products.signals.backend.auto_start.task_run_usage_limited", return_value=False),
- patch.object(tasks_facade, "enforce_self_driving_pr_quota"),
patch.object(tasks_facade, "create_and_run_task", side_effect=fake_create_and_run_task),
patch("products.signals.backend.auto_start.resolve_agent_runtime", return_value=AgentRuntime()),
patch("products.signals.backend.auto_start.load_report_steering", return_value=NO_STEERING),
@@ -279,7 +280,6 @@ class TestRequestedImplementation(BaseTest):
with (
patch("products.signals.backend.auto_start.task_run_usage_limited", return_value=False),
- patch.object(tasks_facade, "enforce_self_driving_pr_quota"),
patch.object(tasks_facade, "create_and_run_task", side_effect=fake_create_and_run_task),
patch("products.signals.backend.auto_start.resolve_agent_runtime", return_value=AgentRuntime()),
patch("products.signals.backend.auto_start.load_report_steering", return_value=NO_STEERING),
diff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.py
index 805b18bd0876..be573b94b2b6 100644
--- a/products/signals/backend/test/test_signal_report_artefact_api.py
+++ b/products/signals/backend/test/test_signal_report_artefact_api.py
@@ -465,6 +465,7 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
if allowed:
assert mock_autostart.call_args.kwargs["report_id"] == str(report.id)
assert mock_autostart.call_args.kwargs["team_id"] == self.team.id
+ assert mock_autostart.call_args.kwargs["triggering_user_id"] == self.user.id
def test_put_adding_reviewer_notifies_added_reviewer_on_commit(self):
# Manually adding a reviewer enqueues a Slack ping (after commit) for only the newly-added
diff --git a/products/signals/backend/test/test_spend.py b/products/signals/backend/test/test_spend.py
index a962ee1bc7c3..b3ca5176a75b 100644
--- a/products/signals/backend/test/test_spend.py
+++ b/products/signals/backend/test/test_spend.py
@@ -265,11 +265,21 @@ class TestSignalSpend(BaseTest):
None if finalized else driver
)
- @parameterized.expand([("priced", 12_345), ("free", 0), ("cancelled", None), ("missing_id", None)])
+ @parameterized.expand(
+ [("priced", 12_345), ("cutover", 12_345), ("free", 0), ("cancelled", None), ("missing_id", None)]
+ )
async def test_generation_waits_for_spend_without_regenerating(self, outcome: str, cost: int | None) -> None:
driver = str(uuid4())
response = Mock(_request_id=None if outcome == "missing_id" else "generation-1")
- generate = AsyncMock(return_value=response)
+
+ async def generate_response():
+ if outcome == "cutover":
+ await Organization.objects.filter(id=self.organization.id).aupdate(
+ usage={"signals_spend_credits": {"billing_start_date": timezone.now().date().isoformat()}}
+ )
+ return response
+
+ generate = AsyncMock(side_effect=generate_response)
with (
patch(
"products.signals.backend.llm_spend.fetch_gateway_cost",
@@ -310,6 +320,8 @@ class TestSignalSpend(BaseTest):
assert spend.spend == cost_to_spend(cost or 0)
assert spend.accounting_failed is (cost is None)
assert spend.llm_failed_stages == (["summarization"] if cost is None else [])
+ if outcome == "cutover":
+ assert not spend.usage_billing
@parameterized.expand([("unavailable",), ("hung",), ("activity_deadline",)])
async def test_usage_timeout_preserves_completed_generation(self, outcome: str) -> None:
@@ -879,6 +891,8 @@ class TestSignalSpend(BaseTest):
original_table = cursor.fetchone()[0]
with connection.schema_editor() as editor:
state = migration.Migration("0208_reset_signal_spend", "signals").apply(state, editor)
+ meter_migration = import_module("products.signals.backend.migrations.0235_signalspend_usage_billing")
+ state = meter_migration.Migration("0235_signalspend_usage_billing", "signals").apply(state, editor)
spend = state.apps.get_model("signals", "SignalSpend")
assert not spend.objects.exists()
row = spend.objects.create(
@@ -890,6 +904,7 @@ class TestSignalSpend(BaseTest):
finalized_at=timezone.now(),
)
assert spend.objects.get(id=row.id).spend == Decimal("4.0123")
+ assert not spend.objects.get(id=row.id).usage_billing
legacy_signal = old_spend.objects.create(
team_id=self.team.id,
signal_id=row.signal_id,
@@ -1076,7 +1091,7 @@ class TestSignalSpend(BaseTest):
owner = SignalSpend.objects.for_team(self.team.id).get(
**({"scout_run_id": scout.id} if scout else {"signal_id": driver})
)
- assert owner.accounting_failed
+ assert not owner.accounting_failed
assert owner.finalized_at is None
self.temporal.start_workflow.assert_not_called()
fetch.reset_mock()
@@ -1131,7 +1146,7 @@ class TestSignalSpend(BaseTest):
scout.refresh_from_db()
assert scout.total_spend == (Decimal("16.3456") if settled_before_owner else Decimal("4"))
assert scout.metadata is not None
- assert scout.metadata["spend_accounting_failed_stages"] == (["scout"] if settled_before_owner else [])
+ assert scout.metadata["spend_accounting_failed_stages"] == []
task_run.status = TaskRun.Status.FAILED
task_run.save(update_fields=["status"])
self._set_task_cost(task_run, 123_456)
@@ -1141,13 +1156,40 @@ class TestSignalSpend(BaseTest):
scout.refresh_from_db()
assert scout.total_spend == Decimal("16.3456")
assert scout.metadata is not None
- assert scout.metadata["spend_accounting_failed_stages"] == ["scout"]
+ assert scout.metadata["spend_accounting_failed_stages"] == []
self._set_task_cost(task_run, 123_457)
scout.refresh_from_db()
assert scout.total_spend == Decimal("16.3457")
assert scout.metadata is not None
assert scout.metadata["spend_accounting_failed_stages"] == []
+ @parameterized.expand([("subscription",), ("missing_cost",), ("gateway_error",)])
+ def test_unrecoverable_task_cost_does_not_remain_pending(self, failure: str) -> None:
+ driver = str(uuid4())
+ report = SignalReport.objects.create(team=self.team, triggering_signal_id=driver)
+ run = self._run(report=report)
+ self._set_task_cost(run, 100_000)
+ run.refresh_from_db()
+ run.status = TaskRun.Status.IN_PROGRESS if failure == "subscription" else TaskRun.Status.COMPLETED
+ run.state["unprocessed_request_ids"] = ["missing-request"]
+ if failure == "subscription":
+ run.state["token_cost_incomplete"] = True
+ run.save(update_fields=["state", "status"])
+ with patch(
+ "products.tasks.backend.logic.services.gateway_usage._fetch_gateway_cost",
+ new=AsyncMock(side_effect=RuntimeError("gateway unavailable"))
+ if failure == "gateway_error"
+ else AsyncMock(return_value=None),
+ ):
+ if failure == "subscription":
+ process_pending_gateway_usage(team_id=self.team.id, run_id=run.id)
+ else:
+ complete_task_spend(team_id=self.team.id, run_id=str(run.id), final_attempt=True)
+ spend = SignalSpend.objects.for_team(self.team.id).get(task_run_id=run.id)
+ assert spend.accounting_failed
+ assert spend.finalized_at is None
+ assert spend.spend == Decimal("14")
+
@parameterized.expand([(TaskRun.Status.IN_PROGRESS,), (TaskRun.Status.COMPLETED,)])
def test_reaped_scout_retries_accounting_until_gateway_cost_settles(self, status: str) -> None:
run = self._run()
diff --git a/products/signals/backend/test/test_summary_settle_autostart.py b/products/signals/backend/test/test_summary_settle_autostart.py
index 9cfd21379d06..8baf6872fa79 100644
--- a/products/signals/backend/test/test_summary_settle_autostart.py
+++ b/products/signals/backend/test/test_summary_settle_autostart.py
@@ -32,6 +32,7 @@ from products.signals.backend.temporal.inbox_notification import (
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,
ImplementationBufferInput,
MarkReportInProgressInput,
MarkReportReadyInput,
@@ -183,7 +184,11 @@ async def _run_summary_workflow(
recorder: _Recorder, *, requested_user_id: int | None = None, requested_after_run_count: int | None = None
) -> None:
@activity.defn(name="check_report_quota_gate_activity")
- async def fake_quota(input) -> bool:
+ async def fake_quota(input: CheckReportQuotaGateInput) -> bool:
+ # Simulate the limit being crossed during the first pass. Any further stage or
+ # buffered research must carry the original admission through implementation.
+ if recorder.researches > 0:
+ assert input.admitted
return False
@activity.defn(name="fetch_signals_for_report_activity")
diff --git a/products/signals/backend/test/test_summary_workflow.py b/products/signals/backend/test/test_summary_workflow.py
index 16b921024790..d04d2d8f7626 100644
--- a/products/signals/backend/test/test_summary_workflow.py
+++ b/products/signals/backend/test/test_summary_workflow.py
@@ -81,6 +81,14 @@ async def ateam(aorganization):
# ---------------------------------------------------------------------------
+def test_legacy_quota_gate_payload_requires_admission() -> None:
+ payloads = pydantic_data_converter.payload_converter.to_payloads(
+ [{"team_id": 1, "report_id": str(uuid.uuid4()), "stage": "summary_entry"}]
+ )
+ (decoded,) = pydantic_data_converter.payload_converter.from_payloads(payloads, [CheckReportQuotaGateInput])
+ assert decoded.admitted is False
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
@pytest.mark.parametrize("enforced", [True, False])
@@ -111,16 +119,46 @@ async def test_check_activity_pauses_on_daily_limit_with_billing_clear(ateam):
patch("products.signals.backend.daily_limit.posthoganalytics.capture") as capture,
):
result = await check_report_quota_gate_activity(
- CheckReportQuotaGateInput(team_id=ateam.id, report_id=str(uuid.uuid4()), stage="pre_research")
+ CheckReportQuotaGateInput(team_id=ateam.id, report_id=str(uuid.uuid4()), stage="summary_entry")
)
assert result is True
assert capture.call_args.kwargs["event"] == "signal_report_daily_limit_paused"
properties = capture.call_args.kwargs["properties"]
- assert properties["stage"] == "pre_research"
+ assert properties["stage"] == "summary_entry"
assert properties["limit"] == 3
assert properties["reports_today"] == 3
+ "stage,admitted,paused",
+ [
+ ("summary_entry", False, True),
+ ("pre_repo_selection", False, False),
+ ("pre_research", False, False),
+ ("summary_entry", True, False),
+ ],
+)
+async def test_limits_only_block_admission_not_later_stages(ateam, stage, admitted, paused):
+ with (
+ patch(
+ f"{SUMMARY_MODULE_PATH}.self_driving_quota_gate",
+ return_value=SelfDrivingQuotaGate(limited=True, enforced=True),
+ ),
+ patch(
+ f"{SUMMARY_MODULE_PATH}.daily_report_limit_gate",
+ return_value=DailyReportLimitGate(limited=True, limit=3, reports_today=3),
+ ),
+ ):
+ assert (
+ await check_report_quota_gate_activity(
+ CheckReportQuotaGateInput(team_id=ateam.id, report_id=str(uuid.uuid4()), stage=stage, admitted=admitted)
+ )
+ is paused
+ )
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_check_activity_fails_open_when_team_lookup_errors():
@@ -437,7 +475,8 @@ async def test_entry_gate_stops_run_before_any_work():
@pytest.mark.asyncio
-async def test_pre_research_gate_reverts_report_and_skips_research():
+async def test_historical_pre_research_pause_still_reverts_report():
+ # Old activity results can still return True during replay; retain their command sequence.
recorder = _Recorder(gate_answers={"pre_research": True})
await _run_summary_workflow(recorder)
assert recorder.gate_checks == ["summary_entry", "pre_repo_selection", "pre_research"]
diff --git a/products/signals/frontend/inbox/InboxScene.stories.tsx b/products/signals/frontend/inbox/InboxScene.stories.tsx
index 5828fea6e8e7..d432f2a6b12d 100644
--- a/products/signals/frontend/inbox/InboxScene.stories.tsx
+++ b/products/signals/frontend/inbox/InboxScene.stories.tsx
@@ -7,6 +7,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { urls } from 'scenes/urls'
import { mswDecorator } from '~/mocks/browser'
+import { billingJson } from '~/mocks/fixtures/_billing'
import { expect, userEvent } from 'storybook/test'
@@ -350,6 +351,46 @@ export const Settings: Story = {
decorators: [routeTo(urls.inbox('settings'))],
}
+export const SettingsWithSpendBilling: Story = {
+ parameters: { featureFlags: { [FEATURE_FLAGS.SELF_DRIVING_QUOTA_ENFORCEMENT]: true } },
+ decorators: [
+ routeTo(urls.inbox('settings')),
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/signals/reports/refund-summary/': {
+ credited_refund_count: 0,
+ credited_credits: 0,
+ period_billable_credits: 0,
+ quota_limited: true,
+ },
+ '/api/billing': () => [
+ 200,
+ {
+ ...billingJson,
+ products: [
+ {
+ ...billingJson.products[0],
+ type: 'inbox_usage',
+ name: 'Inbox usage',
+ usage_key: 'signals_spend_credits',
+ current_amount_usd: '12.34',
+ current_usage: 1234,
+ },
+ ],
+ usage_summary: { signals_spend_credits: { billing_start_date: '2020-01-01' } },
+ },
+ ],
+ },
+ }),
+ ],
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await expect(await canvas.findByText('$12.34')).toBeVisible()
+ await expect(await canvas.findByText('Spending limit reached')).toBeVisible()
+ await expect(canvas.getByText(/Work already underway will finish/)).toBeVisible()
+ },
+}
+
export const Sources: Story = {
decorators: [routeTo(urls.inbox('sources'))],
parameters: { testOptions: { snapshotBrowsers: [] } },
diff --git a/products/signals/frontend/inbox/components/shell/InboxUsageWidget.tsx b/products/signals/frontend/inbox/components/shell/InboxUsageWidget.tsx
index ad7072655941..a11cea99bc32 100644
--- a/products/signals/frontend/inbox/components/shell/InboxUsageWidget.tsx
+++ b/products/signals/frontend/inbox/components/shell/InboxUsageWidget.tsx
@@ -8,6 +8,7 @@ import { LemonField } from 'lib/lemon-ui/LemonField'
import { currencyFormatter } from 'scenes/billing/billing-utils'
import { billingProductLogic } from 'scenes/billing/billingProductLogic'
import { paymentEntryLogic } from 'scenes/billing/paymentEntryLogic'
+import { urls } from 'scenes/urls'
import { BillingProductV2Type } from '~/types'
@@ -141,6 +142,8 @@ function EditLimitModal(): JSX.Element {
export function InboxUsageWidget(): JSX.Element | null {
const {
product,
+ spendProduct,
+ spendAmountUsd,
isLoading,
isSubscribed,
canAccessBilling,
@@ -164,6 +167,30 @@ export function InboxUsageWidget(): JSX.Element | null {
if (isLoading) {
return <UsageCardSkeleton />
}
+ if (spendProduct) {
+ return (
+ <div className="flex flex-col gap-2">
+ <span className="text-[13px] font-semibold">Inbox spend</span>
+ {spendAmountUsd != null && (
+ <span className="text-xs tabular-nums">{currencyFormatter(spendAmountUsd)}</span>
+ )}
+ {quotaLimited && (
+ <>
+ <LemonTag type="warning">Spending limit reached</LemonTag>
+ <span className="text-xs text-secondary">
+ New work is paused. Work already underway will finish.
+ {!canAccessBilling && ' Ask an organization admin to change the limit.'}
+ </span>
+ </>
+ )}
+ {canAccessBilling && (
+ <LemonButton size="small" type="secondary" to={urls.organizationBilling()}>
+ View usage and limits
+ </LemonButton>
+ )}
+ </div>
+ )
+ }
if (!product) {
return null
}
@@ -221,8 +248,7 @@ export function InboxUsageWidget(): JSX.Element | null {
)}
{quotaLimited && (
<span className="text-xs font-medium text-danger">
- Agents are paused. They won't write new reports or open pull requests until the limit is raised
- or usage resets.
+ New work is paused until the limit is raised or usage resets. Work already underway will finish.
</span>
)}
{canAccessBilling ? (
diff --git a/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx b/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx
index 2f95ce52f16a..19ee6f15cdc9 100644
--- a/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx
+++ b/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx
@@ -19,7 +19,7 @@ export function SettingsTab(): JSX.Element {
useMountedLogic(integrationsLogic)
// The usage widget renders nothing without the billing product, so the section title
// must hide with it rather than sit over an empty area.
- const { product: inboxUsageProduct, isLoading: inboxUsageLoading } = useValues(inboxUsageLogic)
+ const { product: inboxUsageProduct, spendProduct, isLoading: inboxUsageLoading } = useValues(inboxUsageLogic)
return (
<div className="mx-auto flex w-full max-w-4xl flex-col gap-8 px-6 py-6">
@@ -52,10 +52,14 @@ export function SettingsTab(): JSX.Element {
>
<SlackNotificationsSection />
</SettingsSection>
- {(inboxUsageProduct != null || inboxUsageLoading) && (
+ {(inboxUsageProduct != null || spendProduct != null || inboxUsageLoading) && (
<SettingsSection
- title={usageEnabled ? 'Pull request usage' : 'Usage'}
- description="Pull requests agents opened this billing period."
+ title={spendProduct ? 'Billing usage' : usageEnabled ? 'Pull request usage' : 'Usage'}
+ description={
+ spendProduct
+ ? 'Recorded billable usage this billing period.'
+ : 'Pull requests agents opened this billing period.'
+ }
>
<InboxUsageWidget />
</SettingsSection>
diff --git a/products/signals/frontend/inbox/logics/inboxUsageLogic.test.ts b/products/signals/frontend/inbox/logics/inboxUsageLogic.test.ts
index 02739f47c84a..3e101200c488 100644
--- a/products/signals/frontend/inbox/logics/inboxUsageLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/inboxUsageLogic.test.ts
@@ -99,6 +99,27 @@ const mountWithUsage = async (
return logic
}
+const mockSpendBilling = (
+ cutoff: string | undefined,
+ discountPercent = 0,
+ amountUsd: string | null = '12.34'
+): void => {
+ useMocks({
+ get: {
+ '/api/billing': () => [
+ 200,
+ {
+ products: [PRICED_INBOX_PRODUCT, { type: 'inbox_usage', current_amount_usd: amountUsd }],
+ discount_percent: discountPercent,
+ usage_summary: {
+ signals_spend_credits: { billing_start_date: cutoff },
+ },
+ },
+ ],
+ },
+ })
+}
+
describe('inboxUsageLogic', () => {
let logic: ReturnType<typeof inboxUsageLogic.build> | undefined
@@ -109,8 +130,107 @@ describe('inboxUsageLogic', () => {
initKeaTests()
})
+ it.each([undefined, '2099-01-01', '2020-01-01'])(
+ 'selects the spend product only after its Billing cutoff (%s)',
+ async (cutoff) => {
+ mockSpendBilling(cutoff)
+ logic = inboxUsageLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.spendProduct?.type ?? null).toBe(cutoff === '2020-01-01' ? 'inbox_usage' : null)
+ expect(logic.values.product?.type).toBe('inbox')
+ }
+ )
+
afterEach(() => {
logic?.unmount()
+ jest.useRealTimers()
+ jest.restoreAllMocks()
+ })
+
+ it.each<[number, string | null, number | null]>([
+ [0, '100', 100],
+ [30, '100', 70],
+ [100, '100', 0],
+ [30, null, null],
+ ])('applies the account discount to spend (%s%%, $%s)', async (discountPercent, amountUsd, expected) => {
+ jest.useFakeTimers({ advanceTimers: true, now: new Date('2026-06-11T12:00:00Z') })
+ mockSpendBilling('2026-06-10', discountPercent, amountUsd)
+ logic = inboxUsageLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.spendAmountUsd).toBe(expected)
+ })
+
+ it('switches meters and refreshes quota at UTC midnight, ignoring a pending legacy response', async () => {
+ jest.useFakeTimers({ advanceTimers: true, now: new Date('2026-06-09T23:59:00Z') })
+ mockSpendBilling('2026-06-10')
+ let finishLegacyRequest!: () => void
+ let legacyRequestStarted!: () => void
+ const legacyRequest = new Promise<void>((resolve) => (finishLegacyRequest = resolve))
+ const legacyRequested = new Promise<void>((resolve) => (legacyRequestStarted = resolve))
+ let requestCount = 0
+ useMocks({
+ get: {
+ '/api/projects/:team_id/signals/reports/refund-summary/': async () => {
+ const quotaLimited = Date.now() < Date.parse('2026-06-10T00:00:00Z')
+ if (++requestCount === 2) {
+ legacyRequestStarted()
+ await legacyRequest
+ }
+ return [
+ 200,
+ {
+ period_billable_credits: 4500,
+ credited_credits: 0,
+ credited_refund_count: 0,
+ quota_limited: quotaLimited,
+ },
+ ]
+ },
+ },
+ })
+ featureFlagLogic.mount()
+ setRefundsFlag()
+ logic = inboxUsageLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ const billing = logic.values.billing
+ expect(logic.values.spendProduct).toBeNull()
+ expect(logic.values.quotaLimited).toBe(true)
+
+ logic.actions.loadRefundSummary()
+ await legacyRequested
+
+ jest.advanceTimersByTime(Date.parse('2026-06-10T00:00:00Z') - Date.now())
+
+ expect(logic.values.billing).toBe(billing)
+ expect(logic.values.spendProduct?.type).toBe('inbox_usage')
+ expect(logic.values.refundSummaryLoading).toBe(true)
+ expect(logic.values.quotaLimited).toBe(false)
+ await expectLogic(logic).toDispatchActions(['loadRefundSummarySuccess'])
+ expect(logic.values.quotaLimited).toBe(false)
+
+ finishLegacyRequest()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.quotaLimited).toBe(false)
+ })
+
+ it('refreshes the meter when a background tab becomes visible after cutoff', async () => {
+ jest.useFakeTimers({ advanceTimers: true, now: new Date('2026-06-09T23:59:00Z') })
+ mockSpendBilling('2026-06-10')
+ logic = inboxUsageLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ const billing = logic.values.billing
+ expect(logic.values.spendProduct).toBeNull()
+
+ jest.setSystemTime(new Date('2026-06-10T12:00:00Z'))
+ jest.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible')
+ document.dispatchEvent(new Event('visibilitychange'))
+
+ expect(logic.values.billing).toBe(billing)
+ expect(logic.values.spendProduct?.type).toBe('inbox_usage')
})
// createdPrs must read `max(billing's recorded usage, live billable credits)`, the gross total
diff --git a/products/signals/frontend/inbox/logics/inboxUsageLogic.ts b/products/signals/frontend/inbox/logics/inboxUsageLogic.ts
index 2fcfc6dde8a7..78db2068991d 100644
--- a/products/signals/frontend/inbox/logics/inboxUsageLogic.ts
+++ b/products/signals/frontend/inbox/logics/inboxUsageLogic.ts
@@ -1,4 +1,16 @@
-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import {
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ kea,
+ listeners,
+ path,
+ reducers,
+ selectors,
+ sharedListeners,
+} from 'kea'
+import type { BreakPointFunction } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
@@ -6,7 +18,7 @@ import { subscriptions } from 'kea-subscriptions'
import { ApiError } from 'lib/api-error'
import { FEATURE_FLAGS } from 'lib/constants'
-import { Dayjs } from 'lib/dayjs'
+import { dayjs, Dayjs } from 'lib/dayjs'
import { billingLogic } from 'lib/logic/billing/billingLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
@@ -41,6 +53,7 @@ export interface inboxUsageLogicValues {
canAccessBilling: boolean // billingLogic
featureFlags: FeatureFlagsSet // featureFlagLogic
currentTeamId: number | null // teamLogic
+ billingDate: string
createdPrs: number
creditsPerPr: number | null
customLimitUsd: number | null
@@ -85,6 +98,8 @@ export interface inboxUsageLogicValues {
refundsFlagEnabled: boolean
resetDate: Dayjs | null
showLimitFormErrors: boolean
+ spendAmountUsd: number | null
+ spendProduct: BillingProductV2Type | null
spentUsd: number | null
status: InboxUsageStatus
summaryFlagEnabled: boolean
@@ -110,10 +125,16 @@ export interface inboxUsageLogicActions {
[key: string]: number | null
}
} // billingLogic
+ checkBillingDate: (now?: number) => {
+ now: number
+ }
+ clearRefundSummary: () => {
+ value: true
+ }
closeModal: () => {
value: true
}
- loadRefundSummary: () => any
+ loadRefundSummary: (_?: any) => any
loadRefundSummaryFailure: (
error: string,
errorObject?: any
@@ -182,10 +203,23 @@ export interface inboxUsageLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxUsageLogicMeta {
+ sharedListeners: {
+ refreshQuotaForMeterChange: (
+ payload: any,
+ breakpoint: BreakPointFunction,
+ action: {
+ type: string
+ payload: any
+ },
+ previousState: any
+ ) => void | Promise<void>
+ }
__keaTypeGenInternalSelectorTypes: {
refundsFlagEnabled: (featureFlags: FeatureFlagsSet) => boolean
quotaEnforcementFlagEnabled: (featureFlags: FeatureFlagsSet) => boolean
summaryFlagEnabled: (refundsFlagEnabled: boolean, quotaEnforcementFlagEnabled: boolean) => boolean
+ spendProduct: (billing: BillingType | null, billingDate: string) => BillingProductV2Type | null
+ spendAmountUsd: (spendProduct: BillingProductV2Type | null, billing: BillingType | null) => number | null
product: (billing: BillingType | null) => BillingProductV2Type | null
isLoading: (
billing: BillingType | null,
@@ -264,6 +298,8 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([
actions: [billingLogic, ['loadBilling', 'updateBillingLimits', 'updateBillingLimitsSuccess']],
})),
actions({
+ checkBillingDate: (now: number = Date.now()) => ({ now }),
+ clearRefundSummary: true,
openModal: true,
closeModal: true,
}),
@@ -277,13 +313,19 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([
refundSummary: [
null as SignalReportRefundSummaryResponseApi | null,
{
- loadRefundSummary: async (): Promise<SignalReportRefundSummaryResponseApi | null> => {
+ loadRefundSummary: async (
+ _ = undefined,
+ breakpoint
+ ): Promise<SignalReportRefundSummaryResponseApi | null> => {
if (!values.summaryFlagEnabled || values.currentTeamId == null) {
return null
}
try {
- return await signalsReportsRefundSummaryRetrieve(String(values.currentTeamId))
+ const summary = await signalsReportsRefundSummaryRetrieve(String(values.currentTeamId))
+ breakpoint()
+ return summary
} catch (error) {
+ breakpoint()
// The refunds flag is org-keyed and resolves late on the client, so the client can
// believe refunds are on while the server (re-checking the same flag) disagrees and
// returns 404. Degrade to the same null the client-flag guard returns when refunds
@@ -297,7 +339,12 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([
},
],
})),
- reducers({
+ reducers(() => ({
+ refundSummary: [null as SignalReportRefundSummaryResponseApi | null, { clearRefundSummary: () => null }],
+ billingDate: [
+ dayjs.utc().format('YYYY-MM-DD'),
+ { checkBillingDate: (_, { now }) => dayjs.utc(now).format('YYYY-MM-DD') },
+ ],
isModalOpen: [
false,
{
@@ -307,7 +354,7 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([
updateBillingLimitsSuccess: () => false,
},
],
- }),
+ })),
// Defined before `selectors` so the `limitForm` values selector exists when
// `estimatedBudgetUsd` lists it as an input (kea builds in array order).
forms(({ values }) => ({
@@ -357,6 +404,23 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([
(refundsFlagEnabled: boolean, quotaEnforcementFlagEnabled: boolean): boolean =>
refundsFlagEnabled || quotaEnforcementFlagEnabled,
],
+ spendProduct: [
+ (s) => [s.billing, s.billingDate],
+ (billing: BillingType | null, billingDate: string): BillingProductV2Type | null => {
+ const summary = billing?.usage_summary?.signals_spend_credits
+ const cutoff = summary?.billing_start_date
+ return cutoff && cutoff <= billingDate
+ ? (billing?.products?.find((product) => product.type === 'inbox_usage') ?? null)
+ : null
+ },
+ ],
+ spendAmountUsd: [
+ (s) => [s.spendProduct, s.billing],
+ (spendProduct: BillingProductV2Type | null, billing: BillingType | null): number | null =>
+ spendProduct?.current_amount_usd != null
+ ? Number(spendProduct.current_amount_usd) * (1 - (billing?.discount_percent || 0) / 100)
+ : null,
+ ],
product: [
(s) => [s.billing],
(billing: null | import('~/types').BillingType): BillingProductV2Type | null =>
@@ -554,7 +618,17 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([
},
],
}),
- listeners(({ actions, values }) => ({
+ sharedListeners(({ actions, values, selectors }) => ({
+ refreshQuotaForMeterChange: (_, __, ___, previousState) => {
+ if (values.spendProduct?.type !== selectors.spendProduct(previousState)?.type) {
+ actions.clearRefundSummary()
+ actions.loadRefundSummary()
+ }
+ },
+ })),
+ listeners(({ actions, values, selectors, sharedListeners }) => ({
+ checkBillingDate: sharedListeners.refreshQuotaForMeterChange,
+ [billingLogic.actionTypes.loadBillingSuccess]: sharedListeners.refreshQuotaForMeterChange,
openModal: () => {
// Seed the field with the current limit (or the free allowance when uncapped).
actions.setLimitFormValue('prs', values.limitPrs ?? values.freePrs)
@@ -564,7 +638,12 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([
// listener — a plain dismiss or resolve just makes this a cheap no-op reload).
[inboxBulkActionsLogic.actionTypes.reportStateChanged]: () => actions.loadRefundSummary(),
// A raised limit can lift the quota pause, and `quotaLimited` only comes from the summary.
- updateBillingLimitsSuccess: () => actions.loadRefundSummary(),
+ updateBillingLimitsSuccess: (_, __, ___, previousState) => {
+ if (values.spendProduct?.type !== selectors.spendProduct(previousState)?.type) {
+ actions.clearRefundSummary()
+ }
+ actions.loadRefundSummary()
+ },
})),
// Fires on mount and again when the org-group-keyed flag arrives after mount — a mount-time
// load alone silently skips the summary on pageloads where flags resolve late, leaving the
@@ -576,7 +655,26 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([
}
},
})),
- afterMount(({ actions, values }) => {
+ afterMount(({ actions, values, cache }) => {
+ cache.disposables.add(() => {
+ let timeout: ReturnType<typeof setTimeout>
+ const updateDate = (): void => {
+ const now = dayjs.utc()
+ actions.checkBillingDate(now.valueOf())
+ timeout = setTimeout(updateDate, now.add(1, 'day').startOf('day').diff(now))
+ }
+ const onVisibilityChange = (): void => {
+ if (document.visibilityState === 'visible') {
+ actions.checkBillingDate()
+ }
+ }
+ updateDate()
+ document.addEventListener('visibilitychange', onVisibilityChange)
+ return () => {
+ clearTimeout(timeout)
+ document.removeEventListener('visibilitychange', onVisibilityChange)
+ }
+ }, 'billingDate')
if (!values.billing) {
actions.loadBilling()
}
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 3b783ab66b80..7557ce07b502 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -2063,6 +2063,7 @@ def create_and_run_task(
branch: str | None = None,
signal_report_id: str | None = None,
free_trial_enabled: bool | None = None,
+ continue_admitted_pipeline: bool = False,
internal: bool | None = None,
sandbox_environment_id: str | None = None,
channel_id: str | UUID | None = None,
@@ -2083,6 +2084,10 @@ def create_and_run_task(
that flag before it takes the report row lock, so handing the result over keeps the flag
request out of the lock. Left NULL, the gate reads the flag itself.
+ ``continue_admitted_pipeline`` is for server-side report orchestration after admission.
+ It lets implementation finish an accepted report/scout pipeline when the spend cap changes.
+ New manual work leaves it false and checks the quota before creating a run.
+
``scheduled_at`` creates the run in NOT_STARTED and defers its workflow until the dispatcher
materializes it at or after that time. The run still stores its complete execution settings.
@@ -2094,13 +2099,11 @@ def create_and_run_task(
signal_report_id = columns.signal_report_id
if columns.hog_flow_id is not None:
extra["hog_flow_id"] = columns.hog_flow_id
- # create_pr=False sessions (research, repo selection, custom agents) can never open the
- # billable PR, so the quota gate must not block them.
+ # Research and repository selection continue an admitted pipeline; their caller owns
+ # admission. Direct implementation creation still needs its own quota check.
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")
+ if not continue_admitted_pipeline:
+ enforce_self_driving_pr_quota(team, report_id=signal_report_id, stage="task_create")
enforce_self_driving_free_trial(
team, report_id=signal_report_id, stage="task_create", enabled=free_trial_enabled
)
@@ -3683,6 +3686,7 @@ def enforce_self_driving_pr_quota(team: Team, *, report_id: str | None = None, s
from products.signals.backend.facade.self_driving import ( # noqa: PLC0415 — cross-product read kept off the api import path
capture_signal_report_quota_paused,
+ self_driving_limit_name,
self_driving_quota_gate,
)
@@ -3691,8 +3695,9 @@ def enforce_self_driving_pr_quota(team: Team, *, report_id: str | None = None, s
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."
+ f"Your organization reached its self-driving {self_driving_limit_name(team)}. "
+ "New work is paused; work already underway will finish. "
+ "Increase the limit in Settings > Billing, or ask an organization admin to do so."
)
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index 158dfd3f65a9..163f46708896 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -181,6 +181,7 @@ class TaskRunSpend:
complete: bool
is_terminal: bool
stage: str
+ accounting_failed: bool
@dataclass(frozen=True)
diff --git a/products/tasks/backend/logic/services/gateway_usage.py b/products/tasks/backend/logic/services/gateway_usage.py
index c1bb7500b898..44b6dc77e178 100644
--- a/products/tasks/backend/logic/services/gateway_usage.py
+++ b/products/tasks/backend/logic/services/gateway_usage.py
@@ -79,6 +79,7 @@ def _save_accounting_state(run: TaskRun) -> None:
run_id=run.id,
team_id=run.team_id,
cost_delta_microusd=delta,
+ accounting_failed=_run_spend(run).accounting_failed,
origin_product=previous.task.origin_product,
)
@@ -297,6 +298,8 @@ def _run_spend(run: TaskRun, *, queued: bool | None = None) -> TaskRunSpend:
complete=usage.complete,
is_terminal=run.is_terminal,
stage=(run.state or {}).get("ai_stage") or "task",
+ accounting_failed=bool((run.state or {}).get("token_cost_incomplete"))
+ or (run.is_terminal and not gateway_usage_enabled(run)),
)
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.py
index 1f4888d94b87..34170c308e4d 100644
--- 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.py
@@ -1,41 +1,13 @@
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.facade.self_driving import (
- capture_signal_report_quota_paused,
- record_quota_check_failed_open,
- self_driving_quota_gate,
-)
-from products.tasks.backend.constants import GITHUB_PR_URL_PREFIX
-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, so only they attest already-billed work. Run output is
-# caller-writable, which means any other pr_url value must not stop enforcement.
-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(GITHUB_PR_URL_PREFIX)
-
@dataclass
class EnforceSelfDrivingRunQuotaInput:
@@ -47,127 +19,6 @@ class EnforceSelfDrivingRunQuotaInput:
@activity.defn
@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
- or (run.state or {}).get("billing_product") == "posthog_ai"
- ):
- 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_source_id) if task.signal_report_source_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.facade.report_tasks 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_CANCELLED
+ # Keep the activity and its wire contract for existing workflow histories. Limits now
+ # apply at pipeline admission; an accepted pipeline can finish even after the cap is hit.
+ return SELF_DRIVING_QUOTA_STOP_CHECKING
diff --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.py
index f8674c5901cb..a3e7be326416 100644
--- 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.py
@@ -1,23 +1,30 @@
-import json
-
import pytest
+import time_machine
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 posthog.exceptions import QuotaLimitExceeded
+from posthog.usage_counters import UsageCounter, UsageCounterService
+from posthog.utils import get_current_day
+
+from products.signals.backend.spend import record_task_cost_delta
+from products.tasks.backend.facade.api import enforce_self_driving_pr_quota
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"
+from ee.billing.quota_limiting import (
+ QuotaLimitingCaches,
+ QuotaResource,
+ remove_limited_team_tokens,
+ update_org_billing_quotas,
+)
def _run_activity(activity_environment, run: TaskRun) -> str:
@@ -41,211 +48,70 @@ def _make_self_driving_run(test_task, test_task_run):
@pytest.mark.requires_secrets
class TestEnforceSelfDrivingRunQuotaActivity:
@pytest.mark.django_db(transaction=True)
- @pytest.mark.parametrize("manual_report", [False, True])
- def test_non_self_driving_origin_stops_checking_without_gating(
- self, activity_environment, test_task, test_task_run, manual_report
- ):
- if manual_report:
- _make_self_driving_run(test_task, test_task_run)
- test_task_run.state = {"billing_product": "posthog_ai"}
- test_task_run.save(update_fields=["state"])
- 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(
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
+ def test_running_spend_blocks_new_work_but_allows_accepted_work_to_finish(
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.
+ ) -> None:
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),
+ organization = test_task.team.organization
+ organization.usage = {
+ "signals_spend_credits": {"usage": 90, "limit": 100, "billing_start_date": "2026-06-10"},
+ "period": ["2026-06-01T00:00:00Z", "2026-07-01T00:00:00Z"],
+ }
+ organization.customer_trust_scores = {}
+ organization.save()
+ spend = (
+ apps.get_model("signals", "SignalSpend")
+ .objects.for_team(test_task.team_id)
+ .create(
+ team_id=test_task.team_id,
+ report=report,
+ task_run_id=test_task_run.id,
+ kind="reviewer_triggered_implementation",
+ usage_billing=True,
+ )
)
- 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
+ record_task_cost_delta(team_id=test_task.team_id, run_id=test_task_run.id, cost_delta_microusd=200_000)
+ period = get_current_day()
+ counters = UsageCounterService()
+ assert counters.get_legacy(UsageCounter.SIGNALS_SPEND_CREDITS, period.start, period.end) == []
+ quota_counts = dict(
+ counters.get_legacy(UsageCounter.SIGNALS_SPEND_CREDITS, period.start, period.end, caller="quota_limiting")
+ )
+ organization.usage["signals_spend_credits"]["todays_usage"] = quota_counts[test_task.team_id]
+ organization.save(update_fields=["usage"])
+ try:
+ update_org_billing_quotas(organization)
+ organization.refresh_from_db()
+ organization.usage["signals_spend_credits"].update(usage=0, todays_usage=0, limit=20)
+ organization.save(update_fields=["usage"])
+ update_org_billing_quotas(organization)
+ with (
+ patch("products.signals.backend.quota.self_driving_quota_enforcement_enabled", return_value=True),
+ patch(
+ "products.tasks.backend.facade.cancellation.cancel_task_run", return_value=("accepted", None)
+ ) as cancel,
+ ):
+ assert _run_activity(activity_environment, test_task_run) == SELF_DRIVING_QUOTA_STOP_CHECKING
+ with pytest.raises(QuotaLimitExceeded, match="spending limit"):
+ enforce_self_driving_pr_quota(test_task.team)
+ cancel.assert_not_called()
+ test_task_run.refresh_from_db()
+ assert test_task_run.status == TaskRun.Status.IN_PROGRESS
+ spend.refresh_from_db()
+ assert spend.finalized_at is None
+ finally:
+ remove_limited_team_tokens(
+ QuotaResource.SIGNALS_SPEND_CREDITS,
+ [test_task.team.api_token],
+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,
+ )
@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.
+ def test_legacy_running_work_also_finishes(self, activity_environment, test_task, test_task_run) -> None:
_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
+ with patch("products.tasks.backend.facade.cancellation.cancel_task_run") as cancel:
+ assert _run_activity(activity_environment, test_task_run) == SELF_DRIVING_QUOTA_STOP_CHECKING
+ cancel.assert_not_called()
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/activities/update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
index 652c7a1fa9bd..a5180e752051 100644
--- a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
+++ b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
@@ -204,6 +204,7 @@ def complete_signal_spend(run_id: str) -> None:
team_id=run.team_id,
run_id=run_id,
report_id=str(run.task.signal_report_source_id) if run.task.signal_report_source_id else None,
+ final_attempt=activity.in_activity() and activity.info().attempt >= 10,
)
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index e533466feb3c..b3e7d55eb3a0 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -2748,6 +2748,21 @@ class TestSelfDrivingQuotaFacadeGates(TestCase):
)
self.assertTrue(Task.objects.filter(id=created.task_id).exists())
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_admitted_implementation_continues_after_limit_is_reached(self, _mock_workflow):
+ Integration.objects.create(team=self.team, kind="github", config={})
+ with self._enforced_gate():
+ created = facade.create_and_run_task(
+ team=self.team,
+ title="Implementation: accepted report",
+ description="Finish the accepted pipeline",
+ origin_product=facade.TaskOriginProduct.SIGNAL_REPORT,
+ user_id=self.user.id,
+ repository="posthog/posthog",
+ continue_admitted_pipeline=True,
+ )
+ 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
diff --git a/products/tasks/backend/tests/test_gateway_usage_workflow.py b/products/tasks/backend/tests/test_gateway_usage_workflow.py
index 93b7eb211ee9..7dc114989fa8 100644
--- a/products/tasks/backend/tests/test_gateway_usage_workflow.py
+++ b/products/tasks/backend/tests/test_gateway_usage_workflow.py
@@ -264,7 +264,7 @@ class TestScoutSpendSettlement(BaseTest):
complete_task_spend(team_id=self.team.id, run_id=str(run.id))
spend = SignalSpend.objects.for_team(self.team.id).get(scout_run=scout)
self.assertIsNone(spend.finalized_at)
- self.assertTrue(spend.accounting_failed)
+ self.assertFalse(spend.accounting_failed)
with patch(
"products.tasks.backend.logic.services.gateway_usage._fetch_gateway_cost",
new=AsyncMock(return_value=GatewayRequestCost(model="example", provider="example", cost_microusd=50)),
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index ad91f6c57960..51c28a4558c4 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -62,7 +62,7 @@
]
},
"BillingUsageTypesSchema": {
- "description": "Array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types.",
+ "description": "Array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types.",
"anyOf": [
{
"type": "array",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 02c530c6c8b6..70f46e8db3f9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -120053,7 +120053,7 @@ export namespace Schemas {
*/
top_projects?: number | null;
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null;
@@ -120105,7 +120105,7 @@ export namespace Schemas {
*/
top_projects?: number | null;
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null;
@@ -120157,7 +120157,7 @@ export namespace Schemas {
*/
top_projects?: number | null;
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null;
@@ -120209,7 +120209,7 @@ export namespace Schemas {
*/
top_projects?: number | null;
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null;
@@ -120641,7 +120641,7 @@ export namespace Schemas {
*/
top_projects?: number | null;
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null;
@@ -120693,7 +120693,7 @@ export namespace Schemas {
*/
top_projects?: number | null;
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null;
@@ -120732,7 +120732,7 @@ export namespace Schemas {
*/
top_projects?: number | null;
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null;
@@ -120784,7 +120784,7 @@ export namespace Schemas {
*/
top_projects?: number | null;
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null;
@@ -123080,7 +123080,7 @@ export namespace Schemas {
*/
start_date?: string | null;
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null;
@@ -123107,7 +123107,7 @@ export namespace Schemas {
*/
start_date?: string | null;
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null;
@@ -123134,7 +123134,7 @@ export namespace Schemas {
*/
start_date?: string | null;
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null;
@@ -123161,7 +123161,7 @@ export namespace Schemas {
*/
start_date?: string | null;
/**
- * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.
* @nullable
*/
usage_types?: string | null;
diff --git a/services/mcp/src/generated/billing/api.ts b/services/mcp/src/generated/billing/api.ts
index e449752dbdf1..5291d679b59b 100644
--- a/services/mcp/src/generated/billing/api.ts
+++ b/services/mcp/src/generated/billing/api.ts
@@ -73,7 +73,7 @@ export const BillingSpendRetrieveQueryParams = () => zod.object({
.string()
.nullish()
.describe(
- 'JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types.'
+ 'JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types.'
),
})
@@ -134,7 +134,7 @@ export const BillingUsageRetrieveQueryParams = () => zod.object({
.string()
.nullish()
.describe(
- 'JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types.'
+ 'JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types.'
),
})
@@ -301,7 +301,7 @@ export const BillingSpendTimeseriesRetrieveQueryParams = () => zod.object({
.string()
.nullish()
.describe(
- 'JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types.'
+ 'JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types.'
),
})
@@ -410,6 +410,6 @@ export const BillingUsageTimeseriesRetrieveQueryParams = () => zod.object({
.string()
.nullish()
.describe(
- 'JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types.'
+ 'JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types.'
),
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-spend-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-spend-get.json
index b8ba065e7221..418e98073d5f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-spend-get.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-spend-get.json
@@ -116,7 +116,7 @@
"type": "null"
}
],
- "description": "Array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types."
+ "description": "Array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types."
}
},
"type": "object"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-usage-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-usage-get.json
index 21866d8b390b..e56378cc517e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-usage-get.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-usage-get.json
@@ -116,7 +116,7 @@
"type": "null"
}
],
- "description": "Array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types."
+ "description": "Array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, signals_spend_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_and_traces_mb_in_period, logs_mb_in_period, apm_tracing_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. [\"event_count_in_period\",\"recording_count_in_period\"]. Omit for all types."
}
},
"type": "object"