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(billing): add billing alerts backend (#66355)

willwearinge57812805d2d
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.yml
index 5c76c29ac978..5ec8b6581e9b 100644
--- a/.github/workflows/container-images-cd.yml
+++ b/.github/workflows/container-images-cd.yml
@@ -496,7 +496,7 @@ jobs:
- name: Check for changes that affect billing temporal worker
id: check_changes_billing_temporal_worker
run: |
- if git diff --name-only HEAD^ HEAD | grep -qE '^ee/billing/|^posthog/temporal/quota_limiting|^posthog/temporal/salesforce_enrichment|^posthog/temporal/usage_report|^posthog/temporal/common|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then
+ if git diff --name-only HEAD^ HEAD | grep -qE '^ee/billing/|^products/billing_alerts/|^posthog/temporal/quota_limiting|^posthog/temporal/salesforce_enrichment|^posthog/temporal/usage_report|^posthog/temporal/common|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then
echo "changed=true" >> $GITHUB_OUTPUT
else
echo "changed=false" >> $GITHUB_OUTPUT
diff --git a/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml b/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
index 77d75962b40b..10a668b0dbd1 100644
--- a/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
+++ b/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
@@ -29,6 +29,33 @@ rules:
- '/products/logs/backend/test/**'
- '/products/logs/backend/**/test_*.py'
+ - id: billing-alert-state-direct-mutation
+ patterns:
+ - pattern-either:
+ - pattern: $ALERT.state = $VALUE
+ - pattern: $ALERT.consecutive_failures = $VALUE
+ - pattern: $ALERT.enabled = $VALUE
+ - pattern: $QUERY.update(..., state=$VALUE, ...)
+ - pattern: $QUERY.update(..., consecutive_failures=$VALUE, ...)
+ - pattern: $QUERY.update(..., enabled=$VALUE, ...)
+ message: |
+ Direct mutation of a billing alert's lifecycle fields bypasses its state
+ machine adapter. Route the change through
+ products.billing_alerts.backend.logic.state_machine.
+ languages: [python]
+ severity: ERROR
+ metadata:
+ category: correctness
+ subcategory: audit
+ confidence: HIGH
+ paths:
+ include:
+ - '/products/billing_alerts/backend/**/*.py'
+ exclude:
+ - '/products/billing_alerts/backend/logic/state_machine.py'
+ - '/products/billing_alerts/backend/test/**'
+ - '/products/billing_alerts/backend/**/test_*.py'
+
- id: insight-alert-state-direct-mutation
patterns:
- pattern-either:
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.py
index cc380695feef..dbcf508c490f 100644
--- a/ee/billing/billing_manager.py
+++ b/ee/billing/billing_manager.py
@@ -40,6 +40,11 @@ logger = structlog.get_logger(__name__)
BILLING_PROVIDER_WEBHOOK_SIGNATURE_HEADER = "X-PostHog-Billing-Provider-Signature"
BILLING_PROVIDER_WEBHOOK_TIMESTAMP_HEADER = "X-PostHog-Billing-Provider-Timestamp"
BILLING_PROVIDER_WEBHOOK_SIGNATURE_VERSION = "sha256"
+BILLING_TIMESERIES_REQUEST_TIMEOUT = (5, 30)
+
+# Marks tokens minted by the billing alerts evaluation job; billing recognizes this claim
+# on its read-only billing status path for tokens without a user role.
+BILLING_ALERTS_EVALUATION_SERVICE_ACTION = "billing_alerts_evaluation"
class BillingAPIErrorCodes(Enum):
@@ -826,6 +831,20 @@ class BillingManager:
handle_billing_service_error(res)
return res.json()
+ def get_billing_status_for_alerts(self, organization: Organization) -> dict[str, Any]:
+ """Read billing status for billing alert evaluation.
+
+ Evaluation runs as a backend job without an acting user, so the token carries the
+ billing alerts service_action claim instead of a user role claim.
+ """
+ res = requests.get(
+ f"{BILLING_SERVICE_URL}/api/billing",
+ headers=self.get_auth_headers(organization, service_action=BILLING_ALERTS_EVALUATION_SERVICE_ACTION),
+ timeout=BILLING_TIMESERIES_REQUEST_TIMEOUT,
+ )
+ handle_billing_service_error(res)
+ return res.json()
+
def get_usage_data(self, organization: Organization, params: dict[str, Any]) -> dict[str, Any]:
return self._request_with_post_fallback(organization, "/api/v2/usage/", params)
@@ -846,7 +865,12 @@ class BillingManager:
url = f"{BILLING_SERVICE_URL}{path}"
headers = self.get_auth_headers(organization)
- res = requests.get(url, headers=headers, params=self._to_query_params(params))
+ res = requests.get(
+ url,
+ headers=headers,
+ params=self._to_query_params(params),
+ timeout=BILLING_TIMESERIES_REQUEST_TIMEOUT,
+ )
if res.status_code in (414, 431):
logger.info(
@@ -855,7 +879,12 @@ class BillingManager:
status_code=res.status_code,
organization_id=str(organization.id),
)
- res = requests.post(url, headers=headers, json=self._to_post_body(params))
+ res = requests.post(
+ url,
+ headers=headers,
+ json=self._to_post_body(params),
+ timeout=BILLING_TIMESERIES_REQUEST_TIMEOUT,
+ )
handle_billing_service_error(res)
return res.json()
diff --git a/ee/billing/billing_types.py b/ee/billing/billing_types.py
index 5f10b2a475f7..70a180a5f7b4 100644
--- a/ee/billing/billing_types.py
+++ b/ee/billing/billing_types.py
@@ -102,6 +102,7 @@ class CustomerInfo(TypedDict):
available_product_features: list[ProductFeature]
current_total_amount_usd: Optional[str]
current_total_amount_usd_after_discount: Optional[str]
+ 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]]]]
diff --git a/ee/billing/test/test_billing_manager.py b/ee/billing/test/test_billing_manager.py
index 1a9c343757f1..3beb381fbad0 100644
--- a/ee/billing/test/test_billing_manager.py
+++ b/ee/billing/test/test_billing_manager.py
@@ -1531,11 +1531,13 @@ class TestRequestWithPostFallback(BaseTest):
assert result == {"results": []}
mock_get.assert_called_once()
+ assert mock_get.call_args.kwargs["timeout"] == (5, 30)
get_params = mock_get.call_args[1]["params"]
assert get_params["teams_map"] == '{"1": "Team A"}'
assert get_params["start_date"] == "2025-01-01"
mock_post.assert_called_once()
+ assert mock_post.call_args.kwargs["timeout"] == (5, 30)
post_json = mock_post.call_args[1]["json"]
assert post_json["teams_map"] == {"1": "Team A"}
assert post_json["start_date"] == "2025-01-01"
diff --git a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts
index 3dacfcba00ba..514ef730ea1f 100644
--- a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts
@@ -56,6 +56,23 @@ export class CdpInternalEventsConsumer extends CdpConsumerBase {
const invocationsToBeQueued = await this.hogFunctionPipeline.buildInvocations(invocationGlobals, {
hogTypes: this.hogTypes,
filterFn: () => true,
+ invocationFilterFn: (fn, globals) => {
+ if (!/^\$[a-z0-9_]+_alert_(firing|resolved|errored|auto_disabled)$/.test(globals.event.event)) {
+ return true
+ }
+ const alertId = globals.event.properties?.alert_id
+ return Boolean(
+ typeof alertId === 'string' &&
+ fn.filters?.events?.some((event) => event.id === globals.event.event) &&
+ fn.filters?.properties?.some(
+ (property) =>
+ property.type === 'event' &&
+ property.key === 'alert_id' &&
+ property.operator === 'exact' &&
+ property.value === alertId
+ )
+ )
+ },
})
return {
diff --git a/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.ts b/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.ts
index 664b3d5e6b3e..963e727c0609 100644
--- a/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.ts
@@ -221,5 +221,38 @@ describe('CDP Internal Events Consumer', () => {
expect(invocations).toHaveLength(1)
expect(invocations[0].functionId).toBe(internalFn.id)
})
+
+ it('routes managed alert events only to the destination matching the event and alert id', async () => {
+ const filters = (alertId: string) => ({
+ filters: {
+ ...HOG_FILTERS_EXAMPLES.no_filters.filters,
+ events: [{ id: '$billing_alert_firing', type: 'events' as const }],
+ properties: [{ key: 'alert_id', value: alertId, operator: 'exact', type: 'event' }],
+ },
+ })
+ const matching = await insertHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...filters('alert-1'),
+ })
+ await insertHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...filters('alert-2'),
+ })
+ await insertHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_INPUTS_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ })
+ const event = createInternalEvent(team.id, {})
+ event.event.event = '$billing_alert_firing'
+ event.event.properties = { alert_id: 'alert-1', current_value: '100' }
+
+ const globals = await processor._parseKafkaBatch([createKafkaMessage(event)])
+ const { invocations } = await processor.processBatch(globals)
+
+ expect(invocations.map((invocation) => invocation.functionId)).toEqual([matching.id])
+ })
})
})
diff --git a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts
index 73ba8e097c1e..30240c372fef 100644
--- a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts
+++ b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts
@@ -45,6 +45,7 @@ export interface HogFunctionInvocationPipelineDeps {
export interface BuildHogFunctionInvocationsOptions {
hogTypes: HogFunctionTypeType[]
filterFn: (fn: HogFunctionType) => boolean
+ invocationFilterFn?: (fn: HogFunctionType, globals: HogFunctionInvocationGlobals) => boolean
}
/**
@@ -86,7 +87,9 @@ export class HogFunctionInvocationPipeline {
const possibleInvocations = (
await Promise.all(
invocationGlobals.map(async (globals) => {
- const teamHogFunctions = hogFunctionsByTeam[globals.project.id]
+ const teamHogFunctions = opts.invocationFilterFn
+ ? hogFunctionsByTeam[globals.project.id].filter((fn) => opts.invocationFilterFn!(fn, globals))
+ : hogFunctionsByTeam[globals.project.id]
const { invocations, metrics, logs } = await buildHogFunctionInvocations(
this.deps.hogInputsService,
diff --git a/posthog/cdp/internal_events.py b/posthog/cdp/internal_events.py
index 6072aaa4a99d..f4e698c364df 100644
--- a/posthog/cdp/internal_events.py
+++ b/posthog/cdp/internal_events.py
@@ -1,3 +1,4 @@
+import re
import uuid
from dataclasses import dataclass
from datetime import UTC, datetime
@@ -12,6 +13,17 @@ from posthog.kafka_client.topics import KAFKA_CDP_INTERNAL_EVENTS
logger = structlog.get_logger(__name__)
+# Single source of truth for the managed-alert event boundary. Also used as a Postgres regex
+# filter (products/cdp hog_function queryset) and mirrored in the Node CDP consumer, so keep it
+# POSIX-compatible (no (?:...) groups).
+MANAGED_ALERT_EVENT_PATTERN = r"^\$[a-z0-9_]+_alert_(firing|resolved|errored|auto_disabled)$"
+_MANAGED_ALERT_EVENT = re.compile(MANAGED_ALERT_EVENT_PATTERN)
+
+
+def is_managed_alert_internal_event(event_name: object) -> bool:
+ """Return whether an internal event is reserved for an alert-owned destination."""
+ return isinstance(event_name, str) and _MANAGED_ALERT_EVENT.fullmatch(event_name) is not None
+
@dataclass
class InternalEventEvent:
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 9a75d1360c13..648e4f190401 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -155,6 +155,10 @@ from products.batch_exports.backend.temporal import (
ACTIVITIES as BATCH_EXPORTS_ACTIVITIES,
WORKFLOWS as BATCH_EXPORTS_WORKFLOWS,
)
+from products.billing_alerts.backend.temporal import (
+ ACTIVITIES as BILLING_ALERTS_ACTIVITIES,
+ WORKFLOWS as BILLING_ALERTS_WORKFLOWS,
+)
from products.business_knowledge.backend.temporal import (
ACTIVITIES as BUSINESS_KNOWLEDGE_ACTIVITIES,
WORKFLOWS as BUSINESS_KNOWLEDGE_WORKFLOWS,
@@ -397,8 +401,11 @@ _task_queue_specs = [
),
(
settings.BILLING_TASK_QUEUE,
- QUOTA_LIMITING_WORKFLOWS + SALESFORCE_ENRICHMENT_WORKFLOWS + USAGE_REPORTS_WORKFLOWS,
- QUOTA_LIMITING_ACTIVITIES + SALESFORCE_ENRICHMENT_ACTIVITIES + USAGE_REPORTS_ACTIVITIES,
+ QUOTA_LIMITING_WORKFLOWS + SALESFORCE_ENRICHMENT_WORKFLOWS + USAGE_REPORTS_WORKFLOWS + BILLING_ALERTS_WORKFLOWS,
+ QUOTA_LIMITING_ACTIVITIES
+ + SALESFORCE_ENRICHMENT_ACTIVITIES
+ + USAGE_REPORTS_ACTIVITIES
+ + BILLING_ALERTS_ACTIVITIES,
),
(
settings.VIDEO_EXPORT_TASK_QUEUE,
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 58ab5d948d9f..e003b8ed6f6b 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -612,6 +612,8 @@ SPECTACULAR_SETTINGS = {
"HealthIssueStatusEnum": "posthog.models.health_issue.HealthIssue.Status",
"HealthIssueSeverityEnum": "posthog.models.health_issue.HealthIssue.Severity",
"IngestionWarningSeverityEnum": "posthog.api.ingestion_warnings_v2.INGESTION_WARNING_SEVERITIES",
+ "BillingAlertMetricEnum": "products.billing_alerts.backend.models.BillingAlertConfiguration.Metric",
+ "BillingAlertStateEnum": "products.billing_alerts.backend.models.BillingAlertConfiguration.State",
# Disambiguates from the same-valued inline enum on the signals LogsAlertStateChangeSignalExtra contract.
"LogsAlertThresholdOperatorEnum": "products.logs.backend.models.LogsAlertConfiguration.ThresholdOperator",
# Shared by _LogsGroupByBody.groupBySource and _LogsGroupByDimension.source (labels == values).
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index ba1739c36283..b1677cbdf812 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -76,6 +76,7 @@ from posthog.temporal.warehouse_sources_queue_partition_management.schedule impo
)
from posthog.temporal.weekly_digest.types import WeeklyDigestInput
+from products.billing_alerts.backend.temporal.schedule import create_schedule_due_billing_alert_checks_schedule
from products.business_knowledge.backend.temporal.schedule import create_business_knowledge_refresh_coordinator_schedule
from products.conversations.backend.temporal.channel_summary.schedule import create_channel_summary_coordinator_schedule
from products.conversations.backend.temporal.schedule import create_support_reply_coordinator_schedule
@@ -846,6 +847,7 @@ async def create_error_tracking_recommendations_refresh_schedule(client: Client)
schedules = [
cleanup_sync_vectors_schedule,
create_run_quota_limiting_schedule,
+ create_schedule_due_billing_alert_checks_schedule,
create_upgrade_queries_schedule,
create_count_all_playlists_schedule,
create_error_tracking_recommendations_refresh_schedule,
diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txt
index 421b269b84b4..7bd8ff9116f6 100644
--- a/posthog/test/setup_receivers_baseline.txt
+++ b/posthog/test/setup_receivers_baseline.txt
@@ -225,7 +225,7 @@ pre_delete:posthog.storage.team_access_cache_signal_handlers.clear_project_secre
pre_delete:posthog.storage.team_llm_gateway_policy_signal_handlers._clear_cache_on_delete
pre_delete:products.alerts.backend.activity_logging.cleanup_alert_hog_functions
pre_delete:products.alerts.backend.activity_logging.handle_alert_subscription_delete
-pre_delete:products.billing_alerts.backend.team_lifecycle.disable_billing_alerts_before_team_delete
+pre_delete:products.billing_alerts.backend.team_lifecycle.rehome_billing_alerts_before_team_delete
pre_delete:products.managed_migrations.backend.activity_logging.handle_batch_import_delete
pre_delete:products.tasks.backend.models.clear_channel_repositories_on_github_integration_delete
pre_delete:products.tasks.backend.team_deletion.cancel_task_workflows_on_team_delete
diff --git a/products/alerts/backend/destinations.py b/products/alerts/backend/destinations.py
index e30f663d5d84..1c2cc2a34b57 100644
--- a/products/alerts/backend/destinations.py
+++ b/products/alerts/backend/destinations.py
@@ -87,7 +87,12 @@ def create_alert_destination_hog_functions(configs: list[AlertDestinationConfig]
team = config.team
serializer = HogFunctionSerializer(
data=config.payload,
- context={"request": request, "get_team": lambda team=team: team, "is_create": True},
+ context={
+ "request": request,
+ "get_team": lambda team=team: team,
+ "is_create": True,
+ "allow_managed_alert_destination": True,
+ },
)
serializer.is_valid(raise_exception=True)
hog_function = serializer.save(team=team)
@@ -108,17 +113,18 @@ def soft_delete_alert_destinations(
unique_ids = set(hog_function_ids)
with transaction.atomic():
event_filter = _allowed_event_filter(allowed_event_ids)
- owned_ids = set(
+ owned_rows = list(
HogFunction.objects.select_for_update()
.filter(
event_filter,
team_id=team_id,
- id__in=unique_ids,
+ deleted=False,
template_id__in=DESTINATION_TEMPLATE_IDS.values(),
filters__properties__contains=[{"key": "alert_id", "value": alert_id}],
)
- .values_list("id", flat=True)
+ .values_list("id", "template_id", "filters")
)
+ owned_ids = {hog_function_id for hog_function_id, _, _ in owned_rows}
invalid_ids = unique_ids - owned_ids
if invalid_ids:
formatted_ids = ", ".join(str(hog_function_id) for hog_function_id in sorted(invalid_ids, key=str))
@@ -129,8 +135,31 @@ def soft_delete_alert_destinations(
]
}
)
- HogFunction.objects.filter(team_id=team_id, id__in=owned_ids).update(deleted=True, enabled=False)
- _reload_hog_functions_after_commit(team_id=team_id, hog_function_ids=owned_ids)
+
+ allowed_events = set(allowed_event_ids)
+ rows_by_template: dict[str | None, list[tuple[UUID, str | None]]] = {}
+ for hog_function_id, template_id, filters in owned_rows:
+ event_id = next(
+ (
+ event_filter.get("id")
+ for event_filter in (filters or {}).get("events", [])
+ if isinstance(event_filter, dict) and event_filter.get("type") == "events"
+ ),
+ None,
+ )
+ rows_by_template.setdefault(template_id, []).append((hog_function_id, event_id))
+
+ for group in rows_by_template.values():
+ group_ids = {hog_function_id for hog_function_id, _ in group}
+ if not unique_ids.intersection(group_ids):
+ continue
+ if group_ids != unique_ids.intersection(group_ids) or {event_id for _, event_id in group} != allowed_events:
+ raise ValidationError(
+ {"hog_function_ids": ["Delete every HogFunction in the destination group together."]}
+ )
+
+ HogFunction.objects.filter(team_id=team_id, id__in=unique_ids).update(deleted=True, enabled=False)
+ _reload_hog_functions_after_commit(team_id=team_id, hog_function_ids=unique_ids)
def soft_delete_all_alert_destinations(*, team_id: int, alert_id: str, allowed_event_ids: Collection[str]) -> int:
@@ -153,6 +182,36 @@ def soft_delete_all_alert_destinations(*, team_id: int, alert_id: str, allowed_e
return deleted_count
+def soft_delete_alert_destinations_for_alerts(
+ *, team_id: int, alert_ids: Collection[str], allowed_event_ids: Collection[str]
+) -> int:
+ """Soft-delete alert-owned destinations in bulk when their execution team is removed."""
+ event_filter = _allowed_event_filter(allowed_event_ids)
+ if not alert_ids:
+ return 0
+ destination_ids: set[UUID] = set()
+ with transaction.atomic():
+ alert_id_filter = Q(pk__in=[])
+ for alert_id in alert_ids:
+ alert_id_filter |= Q(filters__properties__contains=[{"key": "alert_id", "value": alert_id}])
+ destination_ids = set(
+ HogFunction.objects.select_for_update()
+ .filter(
+ alert_id_filter,
+ event_filter,
+ team_id=team_id,
+ deleted=False,
+ template_id__in=DESTINATION_TEMPLATE_IDS.values(),
+ )
+ .values_list("id", flat=True)
+ )
+ deleted_count = HogFunction.objects.filter(team_id=team_id, id__in=destination_ids).update(
+ deleted=True, enabled=False
+ )
+ _reload_hog_functions_after_commit(team_id=team_id, hog_function_ids=destination_ids)
+ return deleted_count
+
+
def count_active_alert_destinations(*, team_id: int, alert_id: str, allowed_event_ids: Collection[str]) -> int:
return _active_alert_destinations_qs(
team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids
diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.py
index bab4d76a0722..f7af573d4b88 100644
--- a/products/alerts/backend/facade/api.py
+++ b/products/alerts/backend/facade/api.py
@@ -27,6 +27,7 @@ from products.alerts.backend.destination_configs import (
from products.alerts.backend.destinations import (
create_alert_destination_hog_functions,
soft_delete_alert_destinations,
+ soft_delete_alert_destinations_for_alerts,
soft_delete_all_alert_destinations,
)
from products.alerts.backend.email_notifications import send_alert_email
@@ -170,6 +171,7 @@ __all__ = [
"insight_ids_with_alerts",
"snooze_alert_from_slack",
"soft_delete_alert_destinations",
+ "soft_delete_alert_destinations_for_alerts",
"soft_delete_all_alert_destinations",
"send_alert_email",
"validate_destination_data",
diff --git a/products/alerts/backend/state_machine.py b/products/alerts/backend/state_machine.py
index 6e199f52c57e..bb5776bd330e 100644
--- a/products/alerts/backend/state_machine.py
+++ b/products/alerts/backend/state_machine.py
@@ -88,6 +88,17 @@ class AlertPolicy:
LOGS_ALERT_POLICY = AlertPolicy()
+BILLING_ALERT_POLICY = AlertPolicy(
+ broken_is_terminal=False,
+ transient_errors_count_toward_broken=True,
+ notify_error_on_every_failure=True,
+ cooldown_gates_initial_fire=False,
+ cooldown_gates_resolve=False,
+ renotify_while_firing=True,
+ clear_check_ends_snooze=True,
+ disable_when_broken=True,
+)
+
@dataclass(frozen=True)
class CheckInput:
diff --git a/products/alerts/backend/test/test_destinations.py b/products/alerts/backend/test/test_destinations.py
index 3fee20d31c02..250418aff548 100644
--- a/products/alerts/backend/test/test_destinations.py
+++ b/products/alerts/backend/test/test_destinations.py
@@ -36,22 +36,42 @@ class TestSoftDeleteAlertDestinations(APIBaseTest):
},
)
+ def _make_group(self, *, template_id: str, alert_id: str) -> list[HogFunction]:
+ return [
+ self._make_hog_function(template_id=template_id, alert_id=alert_id, event_id=event_id)
+ for event_id in ALLOWED_EVENT_IDS
+ ]
+
def test_deletes_alert_destination_with_matching_alert_id(self) -> None:
- destination = self._make_hog_function(template_id="template-slack", alert_id="alert-1")
+ destinations = self._make_group(template_id="template-slack", alert_id="alert-1")
soft_delete_alert_destinations(
team_id=self.team.id,
alert_id="alert-1",
allowed_event_ids=ALLOWED_EVENT_IDS,
- hog_function_ids=[destination.id],
+ hog_function_ids=[destination.id for destination in destinations],
)
- destination.refresh_from_db()
- assert destination.deleted is True
- assert destination.enabled is False
+ for destination in destinations:
+ destination.refresh_from_db()
+ assert destination.deleted is True
+ assert destination.enabled is False
+
+ def test_rejects_partial_destination_group(self) -> None:
+ destinations = self._make_group(template_id="template-slack", alert_id="alert-1")
+
+ with self.assertRaisesRegex(ValidationError, "Delete every HogFunction"):
+ soft_delete_alert_destinations(
+ team_id=self.team.id,
+ alert_id="alert-1",
+ allowed_event_ids=ALLOWED_EVENT_IDS,
+ hog_function_ids=[destinations[0].id],
+ )
+
+ assert not HogFunction.objects.filter(id__in=[destination.id for destination in destinations], deleted=True)
def test_reports_invalid_ids_and_does_not_delete_any_destinations(self) -> None:
- destination = self._make_hog_function(template_id="template-slack", alert_id="alert-1")
+ destinations = self._make_group(template_id="template-slack", alert_id="alert-1")
other = self._make_hog_function(template_id="template-webhook", alert_id="alert-1", event_id="$unrelated_event")
with self.assertRaises(ValidationError) as error:
@@ -59,7 +79,7 @@ class TestSoftDeleteAlertDestinations(APIBaseTest):
team_id=self.team.id,
alert_id="alert-1",
allowed_event_ids=ALLOWED_EVENT_IDS,
- hog_function_ids=[destination.id, other.id],
+ hog_function_ids=[destinations[0].id, other.id],
)
assert isinstance(error.exception.detail, dict)
@@ -68,7 +88,7 @@ class TestSoftDeleteAlertDestinations(APIBaseTest):
assert str(hog_function_id_errors[0]) == (
f"These HogFunctions do not belong to this alert: {other.id}. Refresh the alert and try again."
)
- for hog_function in (destination, other):
+ for hog_function in (*destinations, other):
hog_function.refresh_from_db()
assert hog_function.deleted is False
assert hog_function.enabled is True
@@ -98,47 +118,49 @@ class TestSoftDeleteAlertDestinations(APIBaseTest):
assert destination.enabled is True
def test_rejects_empty_allowed_event_ids_without_deleting_destinations(self) -> None:
- destination = self._make_hog_function(template_id="template-slack", alert_id="alert-1")
+ destinations = self._make_group(template_id="template-slack", alert_id="alert-1")
with self.assertRaisesRegex(ValueError, "allowed_event_ids must not be empty"):
soft_delete_all_alert_destinations(team_id=self.team.id, alert_id="alert-1", allowed_event_ids=())
- destination.refresh_from_db()
- assert destination.deleted is False
- assert destination.enabled is True
+ for destination in destinations:
+ destination.refresh_from_db()
+ assert destination.deleted is False
+ assert destination.enabled is True
@patch("products.alerts.backend.destinations.reload_hog_functions_on_workers")
def test_reload_happens_after_destination_delete_commits(self, reload_hog_functions_on_workers) -> None:
- destination = self._make_hog_function(template_id="template-slack", alert_id="alert-1")
+ destinations = self._make_group(template_id="template-slack", alert_id="alert-1")
with self.captureOnCommitCallbacks(execute=True):
soft_delete_alert_destinations(
team_id=self.team.id,
alert_id="alert-1",
allowed_event_ids=ALLOWED_EVENT_IDS,
- hog_function_ids=[destination.id],
+ hog_function_ids=[destination.id for destination in destinations],
)
reload_hog_functions_on_workers.assert_not_called()
reload_hog_functions_on_workers.assert_called_once_with(
- team_id=self.team.id, hog_function_ids=[str(destination.id)]
+ team_id=self.team.id, hog_function_ids=sorted(str(destination.id) for destination in destinations)
)
@patch("products.alerts.backend.destinations.reload_hog_functions_on_workers", side_effect=RuntimeError("boom"))
def test_reload_failure_does_not_fail_committed_delete(self, _reload_hog_functions_on_workers) -> None:
- destination = self._make_hog_function(template_id="template-slack", alert_id="alert-1")
+ destinations = self._make_group(template_id="template-slack", alert_id="alert-1")
with self.captureOnCommitCallbacks(execute=True):
soft_delete_alert_destinations(
team_id=self.team.id,
alert_id="alert-1",
allowed_event_ids=ALLOWED_EVENT_IDS,
- hog_function_ids=[destination.id],
+ hog_function_ids=[destination.id for destination in destinations],
)
- destination.refresh_from_db()
- assert destination.deleted is True
- assert destination.enabled is False
+ for destination in destinations:
+ destination.refresh_from_db()
+ assert destination.deleted is True
+ assert destination.enabled is False
class TestAlertInternalEventDelivery(APIBaseTest):
diff --git a/products/billing_alerts/README.md b/products/billing_alerts/README.md
new file mode 100644
index 000000000000..aa1d6cd5968b
--- /dev/null
+++ b/products/billing_alerts/README.md
@@ -0,0 +1,11 @@
+# Billing alerts
+
+Billing alerts are organization-scoped and use `execution_team_id` only as the Team that owns HogFunction execution.
+
+`backend:contract-check` is intentionally off for now. Core still imports the product's Temporal registration surface for worker and schedule setup, so product lint treats this as a legacy interface leak. Keep the narrow `tach.toml` interface in place, and enable the contract check once Temporal registration moves behind a fully isolated product boundary.
+
+Scheduled evaluation follows the shared alert delivery barrier: evaluate and produce every alert in the activity batch, flush once, acknowledge each producer result, then persist each lifecycle outcome in a short transaction.
+
+Billing follows the Logs alerting pattern: billing owns its evaluation rules, persistence adapter, and lifecycle message definitions. The shared alerting infrastructure handles lifecycle decisions, scheduling, grouped destination persistence, and event delivery.
+
+The MCP server exposes atomic create and partial-update tools for billing alert configuration. They use the existing organization write scope and retain the API's organization Admin or Owner permission check.
diff --git a/products/billing_alerts/backend/alert_destinations.py b/products/billing_alerts/backend/alert_destinations.py
new file mode 100644
index 000000000000..b038ae9d2e3d
--- /dev/null
+++ b/products/billing_alerts/backend/alert_destinations.py
@@ -0,0 +1,171 @@
+from __future__ import annotations
+
+from typing import Final, Literal
+
+from django.db.models import Q
+
+from products.alerts.backend.destination_configs import DestinationType, EventKindSpec
+from products.alerts.backend.facade.api import DESTINATION_TEMPLATE_IDS
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+
+EventKind = Literal["firing", "resolved", "errored", "broken"]
+
+BILLING_DESTINATION_TYPES = (DestinationType.SLACK, DestinationType.WEBHOOK, DestinationType.TEAMS)
+
+DESTINATION_TYPE_BY_TEMPLATE_ID = {
+ DESTINATION_TEMPLATE_IDS[destination_type]: destination_type for destination_type in BILLING_DESTINATION_TYPES
+}
+
+_PRODUCT_LABEL = "billing alert"
+_BASE_DATA = {
+ "alert_id": "{event.properties.alert_id}",
+ "alert_name": "{event.properties.alert_name}",
+ "metric": "{event.properties.metric}",
+ "current_value": "{event.properties.current_value}",
+ "baseline_value": "{event.properties.baseline_value}",
+ "absolute_delta": "{event.properties.absolute_delta}",
+ "relative_delta_percentage": "{event.properties.relative_delta_percentage}",
+ "evaluation_date": "{event.properties.evaluation_date}",
+ "reason": "{event.properties.reason}",
+ "alert_url": "{project.url}/organization/billing",
+}
+
+
+_ERROR_DATA = {
+ "error_message": "{event.properties.error_message}",
+ "consecutive_failures": "{event.properties.consecutive_failures}",
+}
+
+
+def _spec(
+ *,
+ event: str,
+ display_kind: str,
+ header: str,
+ details: tuple[tuple[str, str], ...],
+ extra_data: dict[str, str] | None = None,
+) -> EventKindSpec:
+ return EventKindSpec(
+ event_id=f"$billing_alert_{event}",
+ display_kind=display_kind,
+ header=header,
+ details=details,
+ primary_action_url="{project.url}/organization/billing",
+ primary_action_label="View billing alert",
+ webhook_body={
+ "id": "{event.uuid}",
+ "type": f"billing_alert.{event}",
+ "timestamp": "{event.properties.triggered_at}",
+ "data": {**_BASE_DATA, **(extra_data or {})},
+ },
+ product_label=_PRODUCT_LABEL,
+ )
+
+
+EVENT_KIND_CONFIG: dict[EventKind, EventKindSpec] = {
+ "firing": _spec(
+ event="firing",
+ display_kind="firing",
+ header="Billing alert '{event.properties.alert_name}' is firing",
+ details=(
+ ("Metric", "{event.properties.metric}"),
+ ("Current", "{event.properties.current_value}"),
+ ("Baseline", "{event.properties.baseline_value}"),
+ ("Reason", "{event.properties.reason}"),
+ ),
+ ),
+ "resolved": _spec(
+ event="resolved",
+ display_kind="resolved",
+ header="Billing alert '{event.properties.alert_name}' has resolved",
+ details=(
+ ("Metric", "{event.properties.metric}"),
+ ("Current", "{event.properties.current_value}"),
+ ("Baseline", "{event.properties.baseline_value}"),
+ ("Reason", "{event.properties.reason}"),
+ ),
+ ),
+ "errored": _spec(
+ event="errored",
+ display_kind="errored",
+ header="Billing alert '{event.properties.alert_name}' could not evaluate",
+ details=(
+ ("Error", "{event.properties.error_message}"),
+ ("Failure count", "{event.properties.consecutive_failures}"),
+ ),
+ extra_data=_ERROR_DATA,
+ ),
+ "broken": _spec(
+ event="auto_disabled",
+ display_kind="auto-disabled",
+ header="Billing alert '{event.properties.alert_name}' was auto-disabled",
+ details=(
+ ("Reason", "{event.properties.consecutive_failures} consecutive check failures."),
+ ("Last error", "{event.properties.error_message}"),
+ ),
+ extra_data=_ERROR_DATA,
+ ),
+}
+
+EVENT_KINDS: tuple[EventKind, ...] = tuple(EVENT_KIND_CONFIG)
+BILLING_ALERT_EVENT_IDS: Final = tuple(spec.event_id for spec in EVENT_KIND_CONFIG.values())
+
+BILLING_ALERT_SLACK_CONTEXT_ELEMENTS = (
+ "Organization-wide billing alert",
+ "Execution project: <{project.url}|{project.name}>",
+)
+
+
+def destination_groups_for_alerts(
+ *,
+ team_ids: set[int],
+ alert_ids: set[str],
+) -> dict[str, dict[str, dict[str, str]]]:
+ """Map alert id -> destination type value -> event id -> HogFunction id for enabled,
+ billing-owned destinations.
+
+ This is the single implementation of destination-group resolution; callers enforce the
+ complete-group invariant (a group must cover every event kind) on the returned mapping.
+ """
+ if not team_ids or not alert_ids:
+ return {}
+
+ ownership_filter = Q(pk__in=[])
+ for alert_id in alert_ids:
+ ownership_filter |= Q(filters__properties__contains=[{"key": "alert_id", "value": alert_id}])
+
+ rows = HogFunction.objects.filter(
+ ownership_filter,
+ team_id__in=team_ids,
+ enabled=True,
+ deleted=False,
+ template_id__in=list(DESTINATION_TYPE_BY_TEMPLATE_ID),
+ ).values_list("id", "template_id", "filters")
+
+ groups: dict[str, dict[str, dict[str, str]]] = {}
+ for hog_function_id, template_id, filters in rows:
+ destination_type = DESTINATION_TYPE_BY_TEMPLATE_ID.get(template_id) if template_id else None
+ if destination_type is None or not isinstance(filters, dict):
+ continue
+ properties = filters.get("properties") or []
+ events = filters.get("events") or []
+ if not isinstance(properties, list) or not isinstance(events, list):
+ continue
+ event_id = next(
+ (
+ event_filter.get("id")
+ for event_filter in events
+ if isinstance(event_filter, dict) and event_filter.get("type") == "events"
+ ),
+ None,
+ )
+ if event_id not in BILLING_ALERT_EVENT_IDS:
+ continue
+ for property_filter in properties:
+ if not isinstance(property_filter, dict) or property_filter.get("key") != "alert_id":
+ continue
+ alert_id = str(property_filter.get("value"))
+ if alert_id in alert_ids:
+ groups.setdefault(alert_id, {}).setdefault(destination_type.value, {})[event_id] = str(hog_function_id)
+ break
+ return groups
diff --git a/products/billing_alerts/backend/facade/__init__.py b/products/billing_alerts/backend/facade/__init__.py
new file mode 100644
index 000000000000..6eb68a1bf8ef
--- /dev/null
+++ b/products/billing_alerts/backend/facade/__init__.py
@@ -0,0 +1 @@
+"""Facade boundary for the billing alerts product."""
diff --git a/products/billing_alerts/backend/facade/api.py b/products/billing_alerts/backend/facade/api.py
new file mode 100644
index 000000000000..15ac08b7f320
--- /dev/null
+++ b/products/billing_alerts/backend/facade/api.py
@@ -0,0 +1,278 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime
+from typing import Any, cast
+from uuid import UUID
+
+from django.db import transaction
+from django.db.models import QuerySet
+from django.utils import timezone
+
+from rest_framework.exceptions import ValidationError as DRFValidationError
+
+from posthog.models.integration import Integration
+from posthog.models.team.team import Team
+
+from products.alerts.backend.facade.api import (
+ AlertDestinationData,
+ DestinationType,
+ build_alert_destination_config,
+ create_alert_destination_hog_functions,
+ soft_delete_alert_destinations,
+ soft_delete_all_alert_destinations,
+ validate_destination_data,
+)
+
+from ..alert_destinations import (
+ BILLING_ALERT_EVENT_IDS,
+ BILLING_ALERT_SLACK_CONTEXT_ELEMENTS,
+ BILLING_DESTINATION_TYPES,
+ EVENT_KIND_CONFIG,
+ EVENT_KINDS,
+ EventKind,
+ destination_groups_for_alerts,
+)
+from ..logic.evaluator import BillingAlertEvaluationError
+from ..logic.notifications import BillingAlertPreview, evaluate_and_dispatch_billing_alert, preview_billing_alert
+from ..logic.state_machine import (
+ apply_disable,
+ apply_enable,
+ apply_outcome,
+ apply_snooze,
+ apply_threshold_change,
+ apply_unsnooze,
+ billing_alert_snapshot,
+ next_billing_alert_check_at,
+)
+from ..models import BillingAlertConfiguration, BillingAlertEvent, validate_threshold_configuration
+
+
+@dataclass(frozen=True)
+class BillingAlertDispatchResult:
+ event: BillingAlertEvent
+ dispatched_destinations: int
+
+
+class BillingAlertExecutionTeamUnavailable(Exception):
+ """Raised when an organization has no team to use for destination execution."""
+
+
+def initialize_billing_alert_lifecycle(alert: BillingAlertConfiguration) -> None:
+ """Apply lifecycle state implied by a newly created alert configuration."""
+ snapshot = billing_alert_snapshot(alert)
+
+ if not alert.enabled:
+ update_fields = apply_outcome(alert, apply_disable(snapshot))
+ elif alert.snoozed_until is not None:
+ update_fields = apply_outcome(alert, apply_snooze(snapshot))
+ else:
+ return
+
+ alert.save(update_fields=[*update_fields, "updated_at"])
+
+
+def apply_billing_alert_configuration_lifecycle(
+ alert: BillingAlertConfiguration,
+ *,
+ enabled_change: bool | None,
+ snoozed_until_provided: bool,
+ snoozed_until: datetime | None,
+ threshold_changed: bool,
+) -> None:
+ """Apply one control-plane change through the shared lifecycle adapter."""
+ snapshot = billing_alert_snapshot(alert)
+
+ if threshold_changed:
+ apply_outcome(alert, apply_threshold_change(snapshot))
+ snapshot = billing_alert_snapshot(alert)
+
+ if enabled_change is True:
+ apply_outcome(alert, apply_enable(snapshot))
+ snapshot = billing_alert_snapshot(alert)
+ elif enabled_change is False:
+ apply_outcome(alert, apply_disable(snapshot))
+ snapshot = billing_alert_snapshot(alert)
+
+ if snoozed_until_provided:
+ if snoozed_until is None:
+ apply_outcome(alert, apply_unsnooze(snapshot))
+ else:
+ apply_outcome(alert, apply_snooze(snapshot))
+
+
+def reschedule_billing_alert_configuration(
+ alert: BillingAlertConfiguration,
+ *,
+ configuration_changed: bool,
+) -> None:
+ if not configuration_changed:
+ return
+ alert.configuration_revision += 1
+ alert.pending_evaluation_date = None
+ alert.retry_attempt_count = 0
+ alert.next_check_at = next_billing_alert_check_at(alert, timezone.now())
+ alert.save(
+ update_fields=[
+ "configuration_revision",
+ "pending_evaluation_date",
+ "retry_attempt_count",
+ "next_check_at",
+ "updated_at",
+ ]
+ )
+
+
+def execution_team_for_organization(organization_id: UUID, preferred_team: Team | None) -> Team:
+ if preferred_team and preferred_team.organization_id == organization_id:
+ return preferred_team
+
+ team = Team.objects.filter(organization_id=organization_id).order_by("id").first()
+ if team is None:
+ raise BillingAlertExecutionTeamUnavailable("This organization does not have an execution team.")
+ return team
+
+
+def visible_events_for_alert(alert: BillingAlertConfiguration) -> QuerySet[BillingAlertEvent]:
+ return BillingAlertEvent.objects.filter(claim__alert=alert).select_related("claim").order_by("-created_at")
+
+
+def evaluate_and_dispatch_alert(alert: BillingAlertConfiguration) -> BillingAlertDispatchResult:
+ event, dispatched = evaluate_and_dispatch_billing_alert(alert)
+ return BillingAlertDispatchResult(event=event, dispatched_destinations=dispatched)
+
+
+def preview_alert(alert: BillingAlertConfiguration) -> BillingAlertPreview:
+ return preview_billing_alert(alert)
+
+
+def delete_alert_and_destinations(alert: BillingAlertConfiguration) -> None:
+ with transaction.atomic():
+ if alert.team_id is not None:
+ soft_delete_all_alert_destinations(
+ team_id=alert.execution_team_id,
+ alert_id=str(alert.id),
+ allowed_event_ids=BILLING_ALERT_EVENT_IDS,
+ )
+ alert.delete()
+
+
+def destinations_for_alerts(alerts: list[BillingAlertConfiguration]) -> dict[str, list[dict[str, Any]]]:
+ alert_ids = {str(alert.id) for alert in alerts}
+ team_ids = {alert.execution_team_id for alert in alerts if alert.team_id is not None}
+ if not alert_ids or not team_ids:
+ return {}
+
+ groups = destination_groups_for_alerts(team_ids=team_ids, alert_ids=alert_ids)
+ required_event_ids = set(BILLING_ALERT_EVENT_IDS)
+ return {
+ alert_id: [
+ {"type": destination_type, "hog_function_ids": sorted(hog_function_ids.values())}
+ for destination_type, hog_function_ids in sorted(groups.get(alert_id, {}).items())
+ if set(hog_function_ids) == required_event_ids
+ ]
+ for alert_id in alert_ids
+ }
+
+
+def slack_integration_belongs_to_team(*, integration_id: int, team_id: int) -> bool:
+ return Integration.objects.filter(
+ id=integration_id,
+ team_id=team_id,
+ kind=Integration.IntegrationKind.SLACK,
+ ).exists()
+
+
+def create_destination(alert: BillingAlertConfiguration, *, request: Any, data: dict[str, Any]) -> list[UUID]:
+ destination_data = cast(AlertDestinationData, data)
+ validate_destination_data(destination_data, allowed_destination_types=BILLING_DESTINATION_TYPES)
+ destination_data["type"] = DestinationType(data["type"])
+ with transaction.atomic():
+ locked_alert = BillingAlertConfiguration.objects.select_for_update().get(
+ pk=alert.pk,
+ organization_id=alert.organization_id,
+ )
+ if locked_alert.team is None:
+ raise DRFValidationError({"type": "This billing alert does not have an execution team."})
+ # Check Slack ownership against the locked row. The configs below are built for
+ # locked_alert.team, so validating the unlocked copy could authorize one team's
+ # integration while creating the destination under another.
+ if destination_data["type"] == DestinationType.SLACK and not slack_integration_belongs_to_team(
+ integration_id=destination_data["slack_workspace_id"],
+ team_id=locked_alert.execution_team_id,
+ ):
+ raise DRFValidationError(
+ {"slack_workspace_id": "Slack integration does not belong to this billing alert execution team."}
+ )
+ existing_types = {
+ destination["type"] for destination in destinations_for_alerts([locked_alert]).get(str(locked_alert.id), [])
+ }
+ if destination_data["type"].value in existing_types:
+ raise DRFValidationError({"type": f"A {destination_data['type'].label} destination already exists."})
+ configs = [
+ build_alert_destination_config(
+ team=locked_alert.team,
+ spec=EVENT_KIND_CONFIG[kind],
+ alert_id=str(locked_alert.id),
+ alert_name=locked_alert.name,
+ data=destination_data,
+ slack_context_elements=BILLING_ALERT_SLACK_CONTEXT_ELEMENTS,
+ )
+ for kind in EVENT_KINDS
+ ]
+ hog_functions = create_alert_destination_hog_functions(configs, request=request)
+ return [hog_function.id for hog_function in hog_functions]
+
+
+def delete_destination(alert: BillingAlertConfiguration, hog_function_ids: list[UUID]) -> None:
+ with transaction.atomic():
+ locked_alert = BillingAlertConfiguration.objects.select_for_update().get(
+ pk=alert.pk,
+ organization_id=alert.organization_id,
+ )
+ if locked_alert.team_id is None:
+ # An alert with no execution team has no destinations to remove. Skip rather than let
+ # execution_team_id raise, matching delete_alert_and_destinations.
+ return
+ soft_delete_alert_destinations(
+ team_id=locked_alert.execution_team_id,
+ alert_id=str(locked_alert.id),
+ allowed_event_ids=BILLING_ALERT_EVENT_IDS,
+ hog_function_ids=hog_function_ids,
+ )
+
+
+def apply_destination_changes(alert: BillingAlertConfiguration, *, request: Any, changes: dict[str, Any]) -> None:
+ """Apply complete destination-group changes inside the caller's configuration transaction."""
+ for hog_function_ids in changes.get("delete", []):
+ delete_destination(alert, hog_function_ids)
+ for destination_data in changes.get("create", []):
+ create_destination(alert, request=request, data=destination_data)
+
+
+__all__ = [
+ "BILLING_ALERT_EVENT_IDS",
+ "BILLING_DESTINATION_TYPES",
+ "EVENT_KINDS",
+ "BillingAlertDispatchResult",
+ "BillingAlertConfiguration",
+ "BillingAlertEvaluationError",
+ "BillingAlertEvent",
+ "BillingAlertExecutionTeamUnavailable",
+ "BillingAlertPreview",
+ "EventKind",
+ "apply_billing_alert_configuration_lifecycle",
+ "apply_destination_changes",
+ "create_destination",
+ "delete_alert_and_destinations",
+ "delete_destination",
+ "destinations_for_alerts",
+ "evaluate_and_dispatch_alert",
+ "preview_alert",
+ "execution_team_for_organization",
+ "initialize_billing_alert_lifecycle",
+ "reschedule_billing_alert_configuration",
+ "slack_integration_belongs_to_team",
+ "validate_threshold_configuration",
+ "visible_events_for_alert",
+]
diff --git a/products/billing_alerts/backend/logic/__init__.py b/products/billing_alerts/backend/logic/__init__.py
new file mode 100644
index 000000000000..8b137891791f
--- /dev/null
+++ b/products/billing_alerts/backend/logic/__init__.py
@@ -0,0 +1 @@
+
diff --git a/products/billing_alerts/backend/logic/evaluator.py b/products/billing_alerts/backend/logic/evaluator.py
new file mode 100644
index 000000000000..c67c0e70d4ec
--- /dev/null
+++ b/products/billing_alerts/backend/logic/evaluator.py
@@ -0,0 +1,177 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import UTC, date, datetime, timedelta
+from decimal import Decimal, InvalidOperation
+from time import perf_counter
+from typing import Any
+
+from django.utils import timezone
+
+from posthog.cloud_utils import get_cached_instance_license
+from posthog.models import Organization
+
+from products.billing_alerts.backend.models import BillingAlertConfiguration
+
+from ee.billing.billing_manager import BillingManager
+
+# Billing period totals the evaluator reads for each supported metric. Both are
+# after-discount amounts so alerts fire on what the customer actually owes.
+_METRIC_AMOUNT_FIELD: dict[str, str] = {
+ BillingAlertConfiguration.Metric.SPEND: "current_total_amount_usd_after_discount",
+ BillingAlertConfiguration.Metric.PROJECTED_SPEND: "projected_total_amount_usd_with_limit_after_discount",
+}
+
+
+@dataclass(frozen=True)
+class BillingAlertEvaluation:
+ evaluation_date: date
+ period_start: datetime
+ period_end: datetime
+ current_value: Decimal | None
+ baseline_value: Decimal | None
+ absolute_delta: Decimal | None
+ relative_delta_percentage: Decimal | None
+ threshold_breached: bool
+ reason: str
+ payload: dict[str, Any]
+ is_inconclusive: bool = False
+ query_duration_ms: int | None = None
+
+
+class BillingAlertEvaluationError(Exception):
+ pass
+
+
+def _validate_supported_metric(alert: BillingAlertConfiguration) -> None:
+ if alert.metric not in _METRIC_AMOUNT_FIELD or alert.currency != "USD":
+ raise BillingAlertEvaluationError("Billing alerts currently support USD spend only.")
+ if alert.threshold_type != BillingAlertConfiguration.ThresholdType.ABSOLUTE_VALUE:
+ raise BillingAlertEvaluationError(
+ "Billing alerts currently support absolute value thresholds only. "
+ "Increase-over-baseline thresholds are not available for billing-period totals."
+ )
+
+
+def _decimal(value: Any, *, field: str) -> Decimal:
+ try:
+ parsed = Decimal(str(value))
+ except (InvalidOperation, TypeError, ValueError):
+ raise BillingAlertEvaluationError(f"Billing status returned an invalid amount for {field}: {value!r}.")
+ if not parsed.is_finite():
+ raise BillingAlertEvaluationError(f"Billing status returned an invalid amount for {field}: {value!r}.")
+ return parsed
+
+
+def _parse_period_boundary(value: Any) -> datetime | None:
+ if value is None:
+ return None
+ try:
+ parsed = datetime.fromisoformat(str(value))
+ except (TypeError, ValueError):
+ return None
+ return parsed.astimezone(UTC) if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+
+
+def expected_evaluation_date(alert: BillingAlertConfiguration, now: datetime | None = None) -> date:
+ if alert.pending_evaluation_date is not None:
+ return alert.pending_evaluation_date
+ now = now or timezone.now()
+ delayed_now = now.astimezone(UTC) - timedelta(hours=alert.evaluation_delay_hours)
+ return delayed_now.date() - timedelta(days=1)
+
+
+def fetch_billing_data(
+ alert: BillingAlertConfiguration,
+ organization: Organization,
+ *,
+ manager: BillingManager | None = None,
+ now: datetime | None = None,
+) -> tuple[dict[str, Any], int]:
+ manager = manager or BillingManager(get_cached_instance_license())
+ start = perf_counter()
+ response = manager.get_billing_status_for_alerts(organization)
+ return response, int((perf_counter() - start) * 1000)
+
+
+def _customer(billing_response: dict[str, Any]) -> dict[str, Any]:
+ customer = billing_response.get("customer")
+ if not isinstance(customer, dict):
+ raise BillingAlertEvaluationError("Billing status did not include customer data.")
+ return customer
+
+
+def evaluate_billing_alert(
+ alert: BillingAlertConfiguration,
+ *,
+ manager: BillingManager | None = None,
+ now: datetime | None = None,
+ billing_response: dict[str, Any] | None = None,
+ query_duration_ms: int | None = None,
+) -> BillingAlertEvaluation:
+ _validate_supported_metric(alert)
+ now = now or timezone.now()
+ expected_date = expected_evaluation_date(alert, now)
+
+ if billing_response is None:
+ organization = Organization.objects.get(id=alert.organization_id)
+ billing_response, query_duration_ms = fetch_billing_data(alert, organization, manager=manager, now=now)
+
+ customer = _customer(billing_response)
+ billing_period = customer.get("billing_period") or {}
+ # Fall back to the evaluation date's UTC day when the billing period is absent (e.g. a
+ # customer with no active subscription), so the recorded event still has a period window.
+ default_start = datetime.combine(expected_date, datetime.min.time(), tzinfo=UTC)
+ period_start = _parse_period_boundary(billing_period.get("current_period_start")) or default_start
+ period_end = _parse_period_boundary(billing_period.get("current_period_end")) or (default_start + timedelta(days=1))
+
+ amount_field = _METRIC_AMOUNT_FIELD[alert.metric]
+ raw_amount = customer.get(amount_field)
+
+ payload: dict[str, Any] = {
+ "expected_evaluation_date": expected_date.isoformat(),
+ "metric": alert.metric,
+ "threshold_type": alert.threshold_type,
+ "amount_field": amount_field,
+ "period_start": billing_period.get("current_period_start"),
+ "period_end": billing_period.get("current_period_end"),
+ "has_active_subscription": customer.get("has_active_subscription"),
+ }
+
+ def result(*, reason: str, **overrides: Any) -> BillingAlertEvaluation:
+ values: dict[str, Any] = {
+ "evaluation_date": expected_date,
+ "period_start": period_start,
+ "period_end": period_end,
+ "current_value": None,
+ "baseline_value": None,
+ "absolute_delta": None,
+ "relative_delta_percentage": None,
+ "threshold_breached": False,
+ "payload": payload,
+ "query_duration_ms": query_duration_ms,
+ **overrides,
+ }
+ return BillingAlertEvaluation(reason=reason, **values)
+
+ if raw_amount is None:
+ return result(
+ reason="Billing status did not include a spend total for this billing period yet.",
+ is_inconclusive=True,
+ )
+
+ current_value = _decimal(raw_amount, field=amount_field)
+
+ if current_value < alert.minimum_value:
+ return result(
+ reason=f"Current value {current_value} is below the minimum value {alert.minimum_value}.",
+ current_value=current_value,
+ )
+
+ threshold_value = alert.threshold_value or Decimal("0")
+ breached = current_value >= threshold_value
+ return result(
+ reason=f"Current value {current_value} {'met' if breached else 'did not meet'} threshold {threshold_value}.",
+ current_value=current_value,
+ threshold_breached=breached,
+ )
diff --git a/products/billing_alerts/backend/logic/notifications.py b/products/billing_alerts/backend/logic/notifications.py
new file mode 100644
index 000000000000..978b8b139ca8
--- /dev/null
+++ b/products/billing_alerts/backend/logic/notifications.py
@@ -0,0 +1,283 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime
+
+from django.db import transaction
+from django.utils import timezone
+
+import structlog
+
+from posthog.kafka_client.client import ProduceResult
+
+from products.alerts.backend.destinations import (
+ alert_internal_event_delivered,
+ flush_alert_internal_events,
+ produce_alert_internal_event,
+)
+from products.billing_alerts.backend.alert_destinations import (
+ BILLING_ALERT_EVENT_IDS,
+ EVENT_KIND_CONFIG,
+ EventKind,
+ destination_groups_for_alerts,
+)
+from products.billing_alerts.backend.logic.evaluator import BillingAlertEvaluation, evaluate_billing_alert
+from products.billing_alerts.backend.logic.state_machine import (
+ AlertCheckOutcome,
+ BillingAlertAlreadyEvaluated,
+ BillingAlertCheck,
+ NotificationAction,
+ billing_alert_snapshot,
+ commit_billing_alert_check,
+ evaluate_alert_check,
+ lock_and_validate_billing_alert_claim,
+ prepare_billing_alert_check,
+ prepare_billing_alert_failure,
+)
+from products.billing_alerts.backend.models import BillingAlertConfiguration, BillingAlertEvent
+
+logger = structlog.get_logger(__name__)
+
+NOTIFICATION_FLUSH_TIMEOUT_SECONDS = 10
+
+_EVENT_KIND_BY_MODEL_KIND: dict[str, EventKind] = {
+ BillingAlertEvent.Kind.BROKEN_CONFIG: "broken",
+ BillingAlertEvent.Kind.FIRING: "firing",
+ BillingAlertEvent.Kind.RESOLVED: "resolved",
+ BillingAlertEvent.Kind.ERRORED: "errored",
+}
+
+
+@dataclass(frozen=True)
+class BillingAlertPreview:
+ """Read-only evaluation of a paused alert: what a check would find, nothing persisted."""
+
+ evaluation: BillingAlertEvaluation
+ outcome: AlertCheckOutcome
+
+ @property
+ def would_notify(self) -> bool:
+ return self.outcome.notification != NotificationAction.NONE
+
+
+def preview_billing_alert(
+ alert: BillingAlertConfiguration,
+ *,
+ now: datetime | None = None,
+ billing_response: dict | None = None,
+ query_duration_ms: int | None = None,
+) -> BillingAlertPreview:
+ """Evaluate an alert without claiming, persisting, or dispatching.
+
+ Paused alerts use this so a manual check reports the current spend and would-be
+ outcome without sending notifications or completing the day's evaluation claim.
+ """
+ now = now or timezone.now()
+ evaluation = evaluate_billing_alert(
+ alert, now=now, billing_response=billing_response, query_duration_ms=query_duration_ms
+ )
+ outcome = evaluate_alert_check(billing_alert_snapshot(alert), evaluation, now)
+ return BillingAlertPreview(evaluation=evaluation, outcome=outcome)
+
+
+@dataclass(frozen=True)
+class PendingBillingAlertDispatch:
+ check: BillingAlertCheck
+ # None means the check produced no delivery-worthy event; delivery itself happens at commit
+ # time, inside the batch barrier.
+ event_name: str | None
+
+
+def _kind_for_event(event: BillingAlertEvent) -> EventKind | None:
+ return _EVENT_KIND_BY_MODEL_KIND.get(event.kind)
+
+
+def _properties(event: BillingAlertEvent, now: datetime, *, consecutive_failures: int) -> dict:
+ alert = event.alert
+ return {
+ "alert_id": str(alert.id),
+ "alert_name": alert.name,
+ "metric": event.metric,
+ "threshold_type": alert.threshold_type,
+ "threshold_percentage": str(event.threshold_percentage_snapshot)
+ if event.threshold_percentage_snapshot is not None
+ else None,
+ "threshold_value": str(event.threshold_value_snapshot) if event.threshold_value_snapshot is not None else None,
+ "minimum_value": str(event.minimum_value_snapshot) if event.minimum_value_snapshot is not None else None,
+ "current_value": str(event.current_value) if event.current_value is not None else None,
+ "baseline_value": str(event.baseline_value) if event.baseline_value is not None else None,
+ "absolute_delta": str(event.absolute_delta) if event.absolute_delta is not None else None,
+ "relative_delta_percentage": str(event.relative_delta_percentage)
+ if event.relative_delta_percentage is not None
+ else None,
+ "evaluation_date": event.evaluation_date.isoformat() if event.evaluation_date else None,
+ "reason": event.reason,
+ "error_message": event.error_message,
+ "consecutive_failures": consecutive_failures,
+ "triggered_at": now.isoformat(),
+ }
+
+
+def _destination_ids(event: BillingAlertEvent) -> tuple[list[str], bool]:
+ kind = _kind_for_event(event)
+ if kind is None:
+ return [], False
+ event_id = EVENT_KIND_CONFIG[kind].event_id
+ alert_id = str(event.alert_id)
+ groups = destination_groups_for_alerts(
+ team_ids={event.alert.execution_team_id},
+ alert_ids={alert_id},
+ ).get(alert_id, {})
+ required_events = set(BILLING_ALERT_EVENT_IDS)
+ return (
+ sorted(event_ids[event_id] for event_ids in groups.values() if set(event_ids) == required_events),
+ bool(groups),
+ )
+
+
+def prepare_billing_alert_dispatch(
+ alert: BillingAlertConfiguration,
+ *,
+ now: datetime | None = None,
+ billing_response: dict | None = None,
+ query_duration_ms: int | None = None,
+ error: Exception | None = None,
+ is_transient_error: bool = False,
+ failure_reason: str = "Billing alert evaluation failed.",
+ source: str = BillingAlertEvent.Source.SCHEDULED,
+) -> PendingBillingAlertDispatch:
+ """Evaluate an alert and enqueue any internal event without persisting the outcome."""
+ now = now or timezone.now()
+ if error is None:
+ check = prepare_billing_alert_check(
+ alert,
+ source=source,
+ now=now,
+ billing_response=billing_response,
+ query_duration_ms=query_duration_ms,
+ )
+ else:
+ check = prepare_billing_alert_failure(
+ alert,
+ error,
+ source=source,
+ now=now,
+ query_duration_ms=query_duration_ms,
+ is_transient_error=is_transient_error,
+ reason=failure_reason,
+ )
+ kind = _kind_for_event(check.event)
+ event_name = EVENT_KIND_CONFIG[kind].event_id if kind is not None else None
+ if (
+ event_name is not None
+ and check.outcome.notification == NotificationAction.ERROR
+ and check.claim.attempts.filter(notification_sent_at__isnull=False).exists()
+ ):
+ # One delivered error notification per evaluation date is enough. Same-day retries of an
+ # already-notified failure would resend an identical message on every attempt, up to
+ # MAX_EVALUATION_ATTEMPTS per day for a sustained outage. notification_sent_at is only set
+ # when destination targets actually received the event, so a failed delivery still retries
+ # delivery, and BROKEN escalation notifications are unaffected.
+ event_name = None
+ return PendingBillingAlertDispatch(check=check, event_name=event_name)
+
+
+def commit_pending_billing_alert_dispatches(
+ dispatches: list[PendingBillingAlertDispatch],
+) -> list[tuple[BillingAlertEvent, int]]:
+ """Fence a batch, flush its internal events once, then persist every corresponding outcome."""
+ if not dispatches:
+ return []
+
+ with transaction.atomic():
+ # Acquire every alert and claim lock in a stable order. The outer transaction retains
+ # these locks through Kafka acknowledgement and lifecycle persistence.
+ for dispatch in sorted(dispatches, key=lambda item: str(item.check.alert.id)):
+ lock_and_validate_billing_alert_claim(dispatch.check)
+
+ prepared: list[tuple[PendingBillingAlertDispatch, list[str], ProduceResult | None]] = []
+ for dispatch in dispatches:
+ destination_ids: list[str] = []
+ produce_result = None
+ if dispatch.event_name is not None:
+ destination_ids, has_configured_destinations = _destination_ids(dispatch.check.event)
+ if has_configured_destinations and not destination_ids:
+ # The alert has destinations, but no group carries the full set of required
+ # events (e.g. one per-kind HogFunction was deleted or disabled out of band).
+ # We deliberately do not dispatch a partial group; surface it so a silently
+ # non-delivering alert is observable instead of looking like "no destinations".
+ logger.warning(
+ "Billing alert has configured destinations but no complete delivery group; skipping dispatch",
+ alert_id=str(dispatch.check.event.alert_id),
+ event_name=dispatch.event_name,
+ )
+ if destination_ids or not has_configured_destinations:
+ produce_result = produce_alert_internal_event(
+ team_id=dispatch.check.event.alert.execution_team_id,
+ event_name=dispatch.event_name,
+ properties=_properties(
+ dispatch.check.event,
+ dispatch.check.now,
+ consecutive_failures=dispatch.check.outcome.consecutive_failures,
+ ),
+ timestamp=dispatch.check.now,
+ uuid=str(dispatch.check.claim.delivery_uuid),
+ )
+ prepared.append((dispatch, destination_ids, produce_result))
+
+ if any(produce_result is not None for _, _, produce_result in prepared):
+ flush_alert_internal_events(NOTIFICATION_FLUSH_TIMEOUT_SECONDS)
+
+ results: list[tuple[BillingAlertEvent, int]] = []
+ for dispatch, destination_ids, produce_result in prepared:
+ delivered = dispatch.event_name is None
+ if dispatch.event_name is not None and produce_result is not None:
+ delivered = alert_internal_event_delivered(
+ produce_result,
+ team_id=dispatch.check.event.alert.execution_team_id,
+ alert_id=str(dispatch.check.event.alert_id),
+ event_name=dispatch.event_name,
+ )
+ event = commit_billing_alert_check(
+ dispatch.check,
+ notification_delivered=delivered,
+ destination_ids=destination_ids,
+ )
+ results.append((event, len(destination_ids) if delivered else 0))
+ return results
+
+
+def commit_pending_billing_alert_dispatch(
+ dispatch: PendingBillingAlertDispatch,
+) -> tuple[BillingAlertEvent, int]:
+ return commit_pending_billing_alert_dispatches([dispatch])[0]
+
+
+def evaluate_and_dispatch_billing_alert(
+ alert: BillingAlertConfiguration,
+ *,
+ now: datetime | None = None,
+ billing_response: dict | None = None,
+ query_duration_ms: int | None = None,
+ error: Exception | None = None,
+ is_transient_error: bool = False,
+ failure_reason: str = "Billing alert evaluation failed.",
+ source: str = BillingAlertEvent.Source.MANUAL,
+) -> tuple[BillingAlertEvent, int]:
+ """Evaluate, cross the shared delivery barrier, then persist the safe outcome."""
+ try:
+ dispatch = prepare_billing_alert_dispatch(
+ alert,
+ now=now,
+ billing_response=billing_response,
+ query_duration_ms=query_duration_ms,
+ error=error,
+ is_transient_error=is_transient_error,
+ failure_reason=failure_reason,
+ source=source,
+ )
+ except BillingAlertAlreadyEvaluated as already_evaluated:
+ if already_evaluated.event is None:
+ raise
+ return already_evaluated.event, 0
+ return commit_pending_billing_alert_dispatch(dispatch)
diff --git a/products/billing_alerts/backend/logic/state_machine.py b/products/billing_alerts/backend/logic/state_machine.py
new file mode 100644
index 000000000000..65253449698a
--- /dev/null
+++ b/products/billing_alerts/backend/logic/state_machine.py
@@ -0,0 +1,548 @@
+"""Billing adapter for the shared alert lifecycle state machine."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, replace
+from datetime import UTC, datetime, timedelta
+
+from django.db import transaction
+from django.utils import timezone
+
+import structlog
+
+from posthog.exceptions_capture import capture_exception
+
+from products.alerts.backend.scheduling import compute_shard_offset_seconds
+from products.alerts.backend.state_machine import (
+ BILLING_ALERT_POLICY,
+ MAX_CONSECUTIVE_FAILURES,
+ AlertCheckOutcome,
+ AlertSnapshot,
+ AlertState,
+ CheckInput,
+ NotificationAction,
+ Outcome,
+ apply_disable,
+ apply_enable,
+ apply_snooze,
+ apply_threshold_change,
+ apply_unsnooze,
+ evaluate_alert_check as shared_evaluate_alert_check,
+ evaluate_alert_failure as shared_evaluate_alert_failure,
+)
+from products.billing_alerts.backend.logic.evaluator import (
+ BillingAlertEvaluation,
+ evaluate_billing_alert,
+ expected_evaluation_date,
+)
+from products.billing_alerts.backend.models import (
+ DAILY_CHECK_INTERVAL_HOURS,
+ BillingAlertConfiguration,
+ BillingAlertEvaluationClaim,
+ BillingAlertEvent,
+)
+
+BILLING_ALERT_SCHEDULE_INTERVAL_SECONDS = 60 * 60
+EVALUATION_LEASE = timedelta(minutes=15)
+EVALUATION_RETRY_BASE = timedelta(minutes=15)
+EVALUATION_RETRY_MAX = timedelta(hours=6)
+MAX_EVALUATION_ATTEMPTS = 8
+
+logger = structlog.get_logger(__name__)
+
+__all__ = [
+ "BILLING_ALERT_POLICY",
+ "BillingAlertAlreadyEvaluated",
+ "BillingAlertCheck",
+ "BillingAlertEvaluationInProgress",
+ "BillingAlertConfigurationChanged",
+ "MAX_CONSECUTIVE_FAILURES",
+ "AlertCheckOutcome",
+ "AlertState",
+ "NotificationAction",
+ "Outcome",
+ "apply_disable",
+ "apply_enable",
+ "apply_outcome",
+ "apply_snooze",
+ "apply_threshold_change",
+ "apply_unsnooze",
+ "billing_alert_snapshot",
+ "claim_billing_alert_evaluation",
+ "lock_and_validate_billing_alert_claim",
+ "commit_billing_alert_check",
+ "evaluate_alert_check",
+ "evaluate_alert_failure",
+ "next_billing_alert_check_at",
+ "prepare_billing_alert_check",
+ "prepare_billing_alert_failure",
+]
+
+
+class BillingAlertEvaluationInProgress(Exception):
+ pass
+
+
+class BillingAlertConfigurationChanged(Exception):
+ pass
+
+
+class BillingAlertAlreadyEvaluated(Exception):
+ def __init__(self, event: BillingAlertEvent | None) -> None:
+ self.event = event
+ super().__init__("This billing date has already been evaluated for the current configuration.")
+
+
+@dataclass(frozen=True)
+class BillingAlertCheck:
+ alert: BillingAlertConfiguration
+ claim: BillingAlertEvaluationClaim
+ event: BillingAlertEvent
+ outcome: AlertCheckOutcome
+ snapshot: AlertSnapshot
+ source: str
+ is_inconclusive: bool
+ now: datetime
+
+
+def billing_alert_snapshot(alert: BillingAlertConfiguration) -> AlertSnapshot:
+ return AlertSnapshot(
+ state=AlertState(alert.state),
+ cooldown=timedelta(hours=alert.cooldown_hours),
+ last_notified_at=alert.last_notified_at,
+ snooze_until=alert.snoozed_until,
+ consecutive_failures=alert.consecutive_failures,
+ )
+
+
+def evaluate_alert_check(
+ snapshot: AlertSnapshot,
+ evaluation: BillingAlertEvaluation,
+ now: datetime,
+) -> AlertCheckOutcome:
+ return shared_evaluate_alert_check(
+ snapshot,
+ CheckInput(
+ threshold_breached=evaluation.threshold_breached,
+ is_inconclusive=evaluation.is_inconclusive,
+ ),
+ now,
+ policy=BILLING_ALERT_POLICY,
+ )
+
+
+def evaluate_alert_failure(
+ snapshot: AlertSnapshot,
+ *,
+ error_message: str,
+ is_transient_error: bool,
+ attempts_remaining: bool = False,
+) -> AlertCheckOutcome:
+ outcome = shared_evaluate_alert_failure(
+ snapshot,
+ error_message=error_message,
+ is_transient_error=is_transient_error,
+ policy=BILLING_ALERT_POLICY,
+ )
+ if not (is_transient_error and attempts_remaining):
+ return outcome
+ # consecutive_failures escalates to BROKEN, which disables the alert, and it counts consecutive
+ # evaluation *dates*. The retry backoff reaches the fifth attempt about four hours in and
+ # MAX_CONSECUTIVE_FAILURES is five, so advancing it per attempt would let one upstream outage
+ # disable an alert within a single day. Hold the counter and the escalation while this date can
+ # still be retried; the error event and its notification are kept so the attempt stays visible.
+ return replace(
+ outcome,
+ new_state=snapshot.state,
+ consecutive_failures=snapshot.consecutive_failures,
+ disable=False,
+ notification=NotificationAction.ERROR,
+ )
+
+
+def apply_outcome(alert: BillingAlertConfiguration, outcome: Outcome) -> list[str]:
+ state_before = AlertState(alert.state)
+ alert.state = outcome.new_state.value
+ alert.consecutive_failures = outcome.consecutive_failures
+ update_fields = ["state", "consecutive_failures"]
+
+ if state_before == AlertState.SNOOZED and outcome.new_state != AlertState.SNOOZED:
+ alert.snoozed_until = None
+ update_fields.append("snoozed_until")
+
+ if isinstance(outcome, AlertCheckOutcome) and outcome.disable:
+ alert.enabled = False
+ update_fields.append("enabled")
+
+ return update_fields
+
+
+def next_billing_alert_check_at(alert: BillingAlertConfiguration, now: datetime) -> datetime:
+ utc_now = now.astimezone(UTC)
+ boundary_hour = alert.evaluation_delay_hours % 24
+ shard_offset_seconds = compute_shard_offset_seconds(
+ alert.id,
+ DAILY_CHECK_INTERVAL_HOURS * 60,
+ schedule_interval_seconds=BILLING_ALERT_SCHEDULE_INTERVAL_SECONDS,
+ )
+ next_at = utc_now.replace(hour=boundary_hour, minute=0, second=0, microsecond=0) + timedelta(
+ seconds=shard_offset_seconds
+ )
+ return next_at + timedelta(days=1) if next_at <= utc_now else next_at
+
+
+def _event_kind(outcome: AlertCheckOutcome) -> str:
+ return {
+ NotificationAction.NONE: BillingAlertEvent.Kind.CHECK,
+ NotificationAction.FIRE: BillingAlertEvent.Kind.FIRING,
+ NotificationAction.RESOLVE: BillingAlertEvent.Kind.RESOLVED,
+ NotificationAction.ERROR: BillingAlertEvent.Kind.ERRORED,
+ NotificationAction.BROKEN: BillingAlertEvent.Kind.BROKEN_CONFIG,
+ }[outcome.notification]
+
+
+def _sync_alert(target: BillingAlertConfiguration, source: BillingAlertConfiguration) -> None:
+ """Copy every concrete field so callers never keep stale in-memory state after a locked read."""
+ for field in BillingAlertConfiguration._meta.concrete_fields:
+ setattr(target, field.attname, getattr(source, field.attname))
+
+
+def claim_billing_alert_evaluation(
+ alert: BillingAlertConfiguration,
+ *,
+ now: datetime,
+) -> BillingAlertEvaluationClaim:
+ lease_expires_at = now + EVALUATION_LEASE
+ with transaction.atomic():
+ locked_alert = BillingAlertConfiguration.objects.select_for_update().get(
+ pk=alert.pk,
+ organization_id=alert.organization_id,
+ )
+ if locked_alert.team_id is None:
+ raise ValueError("Billing alert does not have an execution team.")
+ if locked_alert.configuration_revision != alert.configuration_revision:
+ _sync_alert(alert, locked_alert)
+ raise BillingAlertConfigurationChanged("Billing alert configuration changed before evaluation began.")
+
+ evaluation_date = locked_alert.pending_evaluation_date or expected_evaluation_date(locked_alert, now)
+ try:
+ claim = BillingAlertEvaluationClaim.objects.select_for_update().get(
+ alert=locked_alert,
+ evaluation_date=evaluation_date,
+ configuration_revision=locked_alert.configuration_revision,
+ )
+ except BillingAlertEvaluationClaim.DoesNotExist:
+ claim = BillingAlertEvaluationClaim.objects.create(
+ alert=locked_alert,
+ evaluation_date=evaluation_date,
+ configuration_revision=locked_alert.configuration_revision,
+ )
+
+ if claim.status == BillingAlertEvaluationClaim.Status.COMPLETED:
+ existing_event = claim.attempts.order_by("-attempt_number").first()
+ raise BillingAlertAlreadyEvaluated(existing_event)
+ if (
+ claim.status == BillingAlertEvaluationClaim.Status.EVALUATING
+ and claim.lease_expires_at is not None
+ and claim.lease_expires_at > now
+ ):
+ raise BillingAlertEvaluationInProgress("A billing alert evaluation is already running.")
+ if (
+ claim.status == BillingAlertEvaluationClaim.Status.RETRYABLE
+ and claim.next_retry_at is not None
+ and claim.next_retry_at > now
+ ):
+ raise BillingAlertEvaluationInProgress("This billing alert evaluation is waiting to retry.")
+
+ claim.status = BillingAlertEvaluationClaim.Status.EVALUATING
+ claim.lease_expires_at = lease_expires_at
+ claim.next_retry_at = None
+ claim.attempt_count += 1
+ claim.save(update_fields=["status", "lease_expires_at", "next_retry_at", "attempt_count", "updated_at"])
+
+ locked_alert.pending_evaluation_date = evaluation_date
+ locked_alert.retry_attempt_count = claim.attempt_count
+ locked_alert.next_check_at = lease_expires_at
+ locked_alert.save(
+ update_fields=["pending_evaluation_date", "retry_attempt_count", "next_check_at", "updated_at"]
+ )
+ _sync_alert(alert, locked_alert)
+ return claim
+
+
+def _new_event(
+ alert: BillingAlertConfiguration,
+ claim: BillingAlertEvaluationClaim,
+ *,
+ source: str,
+ kind: str,
+ state_after: str,
+) -> BillingAlertEvent:
+ if alert.team_id is None:
+ raise ValueError("Billing alert does not have an execution team.")
+ return BillingAlertEvent(
+ claim=claim,
+ team_id=alert.team_id,
+ kind=kind,
+ source=source,
+ attempt_number=claim.attempt_count,
+ metric=alert.metric,
+ state_before=alert.state,
+ state_after=state_after,
+ )
+
+
+def _prepare_billing_alert_failure(
+ alert: BillingAlertConfiguration,
+ claim: BillingAlertEvaluationClaim,
+ error: Exception,
+ *,
+ source: str,
+ now: datetime,
+ query_duration_ms: int | None,
+ is_transient_error: bool,
+ reason: str,
+) -> BillingAlertCheck:
+ snapshot = billing_alert_snapshot(alert)
+ outcome = evaluate_alert_failure(
+ snapshot,
+ error_message=reason,
+ is_transient_error=is_transient_error,
+ # Mirrors the retry gate in commit_billing_alert_check: while this evaluation date can
+ # still be retried, the day's failure has not settled and must not escalate.
+ attempts_remaining=claim.attempt_count < MAX_EVALUATION_ATTEMPTS and alert.enabled,
+ )
+ event = _new_event(
+ alert,
+ claim,
+ source=source,
+ kind=_event_kind(outcome),
+ state_after=outcome.new_state.value,
+ )
+ event.threshold_breached = False
+ event.query_duration_ms = query_duration_ms
+ event.error_code = error.__class__.__name__
+ event.error_message = reason
+ event.is_transient_error = is_transient_error
+ event.reason = reason
+ event.payload = {}
+ return BillingAlertCheck(
+ alert=alert,
+ claim=claim,
+ event=event,
+ outcome=outcome,
+ snapshot=snapshot,
+ source=source,
+ is_inconclusive=False,
+ now=now,
+ )
+
+
+def prepare_billing_alert_failure(
+ alert: BillingAlertConfiguration,
+ error: Exception,
+ *,
+ source: str,
+ now: datetime | None = None,
+ query_duration_ms: int | None = None,
+ is_transient_error: bool = False,
+ reason: str = "Billing alert evaluation failed.",
+) -> BillingAlertCheck:
+ now = now or timezone.now()
+ claim = claim_billing_alert_evaluation(alert, now=now)
+ return _prepare_billing_alert_failure(
+ alert,
+ claim,
+ error,
+ source=source,
+ now=now,
+ query_duration_ms=query_duration_ms,
+ is_transient_error=is_transient_error,
+ reason=reason,
+ )
+
+
+def _prepare_billing_alert_evaluation(
+ alert: BillingAlertConfiguration,
+ claim: BillingAlertEvaluationClaim,
+ evaluation: BillingAlertEvaluation,
+ *,
+ source: str,
+ now: datetime,
+) -> BillingAlertCheck:
+ snapshot = billing_alert_snapshot(alert)
+ outcome = evaluate_alert_check(snapshot, evaluation, now)
+ event = _new_event(
+ alert,
+ claim,
+ source=source,
+ kind=_event_kind(outcome),
+ state_after=outcome.new_state.value,
+ )
+ event.period_start = evaluation.period_start
+ event.period_end = evaluation.period_end
+ event.current_value = evaluation.current_value
+ event.baseline_value = evaluation.baseline_value
+ event.absolute_delta = evaluation.absolute_delta
+ event.relative_delta_percentage = evaluation.relative_delta_percentage
+ event.threshold_value_snapshot = alert.threshold_value
+ event.threshold_percentage_snapshot = alert.threshold_percentage
+ event.minimum_value_snapshot = alert.minimum_value
+ event.threshold_breached = evaluation.threshold_breached
+ event.query_duration_ms = evaluation.query_duration_ms
+ event.reason = evaluation.reason
+ event.payload = evaluation.payload
+ return BillingAlertCheck(
+ alert=alert,
+ claim=claim,
+ event=event,
+ outcome=outcome,
+ snapshot=snapshot,
+ source=source,
+ is_inconclusive=evaluation.is_inconclusive,
+ now=now,
+ )
+
+
+def prepare_billing_alert_check(
+ alert: BillingAlertConfiguration,
+ *,
+ source: str,
+ now: datetime | None = None,
+ billing_response: dict | None = None,
+ query_duration_ms: int | None = None,
+) -> BillingAlertCheck:
+ now = now or timezone.now()
+ claim = claim_billing_alert_evaluation(alert, now=now)
+ try:
+ evaluation = evaluate_billing_alert(
+ alert,
+ now=now,
+ billing_response=billing_response,
+ query_duration_ms=query_duration_ms,
+ )
+ except Exception as error:
+ capture_exception(error, {"alert_id": str(alert.id), "feature": "billing_alerts"})
+ logger.exception("Billing alert evaluation failed", alert_id=str(alert.id))
+ return _prepare_billing_alert_failure(
+ alert,
+ claim,
+ error,
+ source=source,
+ now=now,
+ query_duration_ms=query_duration_ms,
+ is_transient_error=False,
+ reason="Billing alert evaluation failed.",
+ )
+
+ return _prepare_billing_alert_evaluation(alert, claim, evaluation, source=source, now=now)
+
+
+def _retry_at(claim: BillingAlertEvaluationClaim, now: datetime) -> datetime:
+ multiplier = 2 ** max(claim.attempt_count - 1, 0)
+ delay = min(EVALUATION_RETRY_BASE * multiplier, EVALUATION_RETRY_MAX)
+ return now + delay
+
+
+def _validate_claim(
+ check: BillingAlertCheck, alert: BillingAlertConfiguration, claim: BillingAlertEvaluationClaim
+) -> None:
+ if alert.configuration_revision != claim.configuration_revision:
+ raise BillingAlertConfigurationChanged("Billing alert configuration changed during evaluation.")
+ if (
+ claim.status != BillingAlertEvaluationClaim.Status.EVALUATING
+ or claim.attempt_count != check.event.attempt_number
+ ):
+ raise BillingAlertEvaluationInProgress("A newer billing alert evaluation owns this claim.")
+
+
+def lock_and_validate_billing_alert_claim(check: BillingAlertCheck) -> None:
+ """Take the alert and claim locks used by configuration updates; they persist for the rest of
+ the caller's transaction, fencing notification delivery against concurrent config changes."""
+ locked_alert = BillingAlertConfiguration.objects.select_for_update().get(
+ pk=check.alert.pk,
+ organization_id=check.alert.organization_id,
+ )
+ claim = BillingAlertEvaluationClaim.objects.select_for_update().get(
+ pk=check.claim.pk,
+ alert_id=check.alert.pk,
+ )
+ _validate_claim(check, locked_alert, claim)
+
+
+def commit_billing_alert_check(
+ check: BillingAlertCheck,
+ *,
+ notification_delivered: bool,
+ destination_ids: list[str] | None = None,
+) -> BillingAlertEvent:
+ notification_requested = check.outcome.notification != NotificationAction.NONE
+ # A user notification only counts when a real destination target received it. The internal
+ # event can be "delivered" to Kafka with no destinations configured, which advances the
+ # lifecycle and claim but must not start the notification cooldown.
+ targets_delivered = notification_delivered and bool(destination_ids)
+ committed_outcome = check.outcome
+ if notification_requested and not notification_delivered:
+ committed_outcome = replace(
+ check.outcome,
+ new_state=check.snapshot.state,
+ consecutive_failures=min(check.snapshot.consecutive_failures, check.outcome.consecutive_failures),
+ update_last_notified_at=False,
+ disable=False,
+ )
+
+ retry_requested = (
+ check.is_inconclusive
+ or check.event.is_transient_error
+ or (notification_requested and not notification_delivered)
+ )
+
+ with transaction.atomic():
+ locked_alert = BillingAlertConfiguration.objects.select_for_update().get(
+ pk=check.alert.pk,
+ organization_id=check.alert.organization_id,
+ )
+ claim = BillingAlertEvaluationClaim.objects.select_for_update().get(
+ pk=check.claim.pk,
+ alert_id=check.alert.pk,
+ )
+ _validate_claim(check, locked_alert, claim)
+ event = check.event
+ event.claim = claim
+ event.team_id = locked_alert.team_id or event.team_id
+
+ event.state_after = committed_outcome.new_state.value
+ if notification_requested and targets_delivered:
+ event.notification_sent_at = check.now
+ event.targets_notified = {"hog_functions": destination_ids or []}
+
+ update_fields = apply_outcome(locked_alert, committed_outcome)
+ locked_alert.last_checked_at = check.now
+ update_fields.append("last_checked_at")
+
+ should_retry = retry_requested and claim.attempt_count < MAX_EVALUATION_ATTEMPTS and locked_alert.enabled
+ if should_retry:
+ retry_at = _retry_at(claim, check.now)
+ locked_alert.next_check_at = retry_at
+ locked_alert.pending_evaluation_date = claim.evaluation_date
+ locked_alert.retry_attempt_count = claim.attempt_count
+ claim.status = BillingAlertEvaluationClaim.Status.RETRYABLE
+ claim.next_retry_at = retry_at
+ else:
+ locked_alert.next_check_at = next_billing_alert_check_at(locked_alert, check.now)
+ locked_alert.pending_evaluation_date = None
+ locked_alert.retry_attempt_count = 0
+ claim.status = BillingAlertEvaluationClaim.Status.COMPLETED
+ claim.next_retry_at = None
+ update_fields.extend(["next_check_at", "pending_evaluation_date", "retry_attempt_count"])
+
+ if notification_requested and targets_delivered and check.outcome.update_last_notified_at:
+ locked_alert.last_notified_at = check.now
+ update_fields.append("last_notified_at")
+
+ locked_alert.save(update_fields=[*set(update_fields), "updated_at"])
+ event.save(force_insert=True)
+ claim.lease_expires_at = None
+ claim.save(update_fields=["status", "lease_expires_at", "next_retry_at", "updated_at"])
+ _sync_alert(check.alert, locked_alert)
+ return event
diff --git a/products/billing_alerts/backend/models.py b/products/billing_alerts/backend/models.py
index 298508e20040..f8cf7ff37748 100644
--- a/products/billing_alerts/backend/models.py
+++ b/products/billing_alerts/backend/models.py
@@ -145,8 +145,6 @@ class BillingAlertConfiguration(UUIDModel):
if self.baseline_window_days < 1:
raise ValidationError({"baseline_window_days": "Must be at least 1."})
- if self.minimum_value < 0:
- raise ValidationError({"minimum_value": "Must be greater than or equal to 0."})
if self.team_id:
team_organization_id = (
Team.objects.filter(id=self.team_id).values_list("organization_id", flat=True).first()
@@ -154,16 +152,41 @@ class BillingAlertConfiguration(UUIDModel):
if team_organization_id is not None and team_organization_id != self.organization_id:
raise ValidationError({"team": "Execution team must belong to the billing alert organization."})
- if self.threshold_type == self.ThresholdType.RELATIVE_INCREASE:
- if self.threshold_percentage is None:
- raise ValidationError({"threshold_percentage": "Required for relative increase alerts."})
- if self.threshold_percentage <= 0:
- raise ValidationError({"threshold_percentage": "Must be greater than 0."})
- elif self.threshold_type in (self.ThresholdType.ABSOLUTE_VALUE, self.ThresholdType.ABSOLUTE_INCREASE):
- if self.threshold_value is None:
- raise ValidationError({"threshold_value": "Required for absolute threshold alerts."})
- if self.threshold_value < 0:
- raise ValidationError({"threshold_value": "Must be greater than or equal to 0."})
+ errors = validate_threshold_configuration(
+ threshold_type=self.threshold_type,
+ threshold_percentage=self.threshold_percentage,
+ threshold_value=self.threshold_value,
+ minimum_value=self.minimum_value,
+ )
+ if errors:
+ raise ValidationError(errors)
+
+
+def validate_threshold_configuration(
+ *,
+ threshold_type: str,
+ threshold_percentage: Decimal | None,
+ threshold_value: Decimal | None,
+ minimum_value: Decimal,
+) -> dict[str, str]:
+ """Threshold policy shared by model validation and the DRF serializer."""
+ errors: dict[str, str] = {}
+ if minimum_value < 0:
+ errors["minimum_value"] = "Must be greater than or equal to 0."
+ if threshold_type == BillingAlertConfiguration.ThresholdType.RELATIVE_INCREASE:
+ if threshold_percentage is None:
+ errors["threshold_percentage"] = "Required for relative increase alerts."
+ elif threshold_percentage <= 0:
+ errors["threshold_percentage"] = "Must be greater than 0."
+ elif threshold_type in (
+ BillingAlertConfiguration.ThresholdType.ABSOLUTE_VALUE,
+ BillingAlertConfiguration.ThresholdType.ABSOLUTE_INCREASE,
+ ):
+ if threshold_value is None:
+ errors["threshold_value"] = "Required for absolute threshold alerts."
+ elif threshold_value < 0:
+ errors["threshold_value"] = "Must be greater than or equal to 0."
+ return errors
class BillingAlertEvaluationClaim(UUIDModel):
diff --git a/products/billing_alerts/backend/presentation/__init__.py b/products/billing_alerts/backend/presentation/__init__.py
new file mode 100644
index 000000000000..8b137891791f
--- /dev/null
+++ b/products/billing_alerts/backend/presentation/__init__.py
@@ -0,0 +1 @@
+
diff --git a/products/billing_alerts/backend/presentation/serializers.py b/products/billing_alerts/backend/presentation/serializers.py
new file mode 100644
index 000000000000..30c5244ef559
--- /dev/null
+++ b/products/billing_alerts/backend/presentation/serializers.py
@@ -0,0 +1,468 @@
+from __future__ import annotations
+
+from decimal import Decimal
+from typing import Any, cast
+from urllib.parse import urlparse
+
+from django.db import transaction
+from django.db.models import QuerySet
+
+from drf_spectacular.utils import extend_schema_field
+from rest_framework import serializers
+from rest_framework.exceptions import ValidationError
+
+from products.alerts.backend.facade.api import (
+ AlertDestinationData,
+ AlertDestinationValidationError,
+ DestinationType,
+ validate_destination_data,
+)
+from products.billing_alerts.backend.facade import api as billing_alerts_api
+from products.billing_alerts.backend.facade.api import (
+ BillingAlertConfiguration,
+ BillingAlertEvent,
+ validate_threshold_configuration,
+)
+
+_DESTINATIONS_CACHE_KEY = "_billing_alert_destinations_by_alert_id"
+_NOT_PROVIDED = object()
+
+
+def _any_field_changed(
+ instance: BillingAlertConfiguration,
+ validated_data: dict[str, Any],
+ fields: set[str],
+) -> bool:
+ return any(field in validated_data and validated_data[field] != getattr(instance, field) for field in fields)
+
+
+def _is_microsoft_teams_webhook(webhook_url: str) -> bool:
+ parsed = urlparse(webhook_url)
+ hostname = parsed.hostname or ""
+ path = parsed.path
+ if hostname.endswith(".logic.azure.com"):
+ return parsed.port in (None, 443) and path.startswith("/workflows/") and "/triggers/manual/paths/invoke" in path
+ if hostname.endswith(".webhook.office.com"):
+ return path.startswith("/webhookb2/") and "/IncomingWebhook/" in path
+ if hostname.endswith((".powerautomate.com", ".flow.microsoft.com")):
+ return bool(path.strip("/"))
+ if hostname.endswith(".environment.api.powerplatform.com"):
+ return path.startswith("/powerautomate/automations/direct/") and "/workflows/" in path
+ return False
+
+
+class BillingAlertEventSerializer(serializers.ModelSerializer):
+ # Model properties derived from the claim, so DRF cannot generate them.
+ evaluation_date = serializers.DateField(
+ read_only=True,
+ allow_null=True,
+ help_text="Billing data date evaluated by this event.",
+ )
+ configuration_revision = serializers.IntegerField(
+ source="claim.configuration_revision",
+ read_only=True,
+ help_text="Configuration revision used for this evaluation.",
+ )
+
+ class Meta:
+ model = BillingAlertEvent
+ fields = [
+ "id",
+ "kind",
+ "source",
+ "attempt_number",
+ "created_at",
+ "evaluation_date",
+ "configuration_revision",
+ "period_start",
+ "period_end",
+ "metric",
+ "current_value",
+ "baseline_value",
+ "absolute_delta",
+ "relative_delta_percentage",
+ "threshold_breached",
+ "state_before",
+ "state_after",
+ "notification_sent_at",
+ "targets_notified",
+ "query_duration_ms",
+ "error_code",
+ "error_message",
+ "reason",
+ ]
+ read_only_fields = [field for field in fields if field not in ("evaluation_date", "configuration_revision")]
+ extra_kwargs = {
+ "id": {"help_text": "Unique identifier for this billing alert event."},
+ "kind": {"help_text": "Event kind for a check, state transition, or delivery-worthy alert event."},
+ "source": {"help_text": "Whether this evaluation was scheduled or manually requested."},
+ "attempt_number": {"help_text": "Attempt number for this billing date and configuration revision."},
+ "created_at": {"help_text": "When this event was recorded."},
+ "period_start": {"help_text": "Start of the evaluated billing period."},
+ "period_end": {"help_text": "End of the evaluated billing period."},
+ "metric": {"help_text": "Billing metric evaluated by this event."},
+ "current_value": {"help_text": "Metric value for the evaluated billing date."},
+ "baseline_value": {"help_text": "Average metric value across the baseline window."},
+ "absolute_delta": {"help_text": "Current value minus the baseline value."},
+ "relative_delta_percentage": {"help_text": "Percentage change against the baseline value."},
+ "threshold_breached": {"help_text": "Whether the evaluated value breached the configured threshold."},
+ "state_before": {"help_text": "Alert state before this event was applied."},
+ "state_after": {"help_text": "Alert state after this event was applied."},
+ "notification_sent_at": {"help_text": "When notifications for this event were delivered."},
+ "targets_notified": {"help_text": "Notification targets recorded for this event."},
+ "query_duration_ms": {"help_text": "Milliseconds spent fetching billing data for this evaluation."},
+ "error_code": {"help_text": "Exception class name recorded when the evaluation failed."},
+ "error_message": {"help_text": "Failure description recorded when the evaluation failed."},
+ "reason": {"help_text": "Human-readable explanation of the evaluation outcome."},
+ }
+
+
+class BillingAlertDestinationSummarySerializer(serializers.Serializer):
+ type = serializers.ChoiceField(choices=["slack", "webhook", "teams"])
+ hog_function_ids = serializers.ListField(child=serializers.UUIDField())
+
+
+class BillingAlertDestinationCreateDataSerializer(serializers.Serializer):
+ type = serializers.ChoiceField(choices=["slack", "webhook", "teams"], help_text="Destination type.")
+ slack_workspace_id = serializers.IntegerField(
+ required=False, help_text="Slack integration ID in the alert execution project."
+ )
+ slack_channel_id = serializers.CharField(required=False, help_text="Slack channel ID for alert delivery.")
+ slack_channel_name = serializers.CharField(
+ required=False, allow_blank=True, help_text="Optional Slack channel name shown in the UI."
+ )
+ webhook_url = serializers.URLField(
+ required=False, help_text="HTTPS webhook URL for webhook or Microsoft Teams delivery."
+ )
+
+ def validate(self, attrs: dict) -> dict:
+ data = cast(AlertDestinationData, attrs)
+ data["type"] = DestinationType(attrs["type"])
+ try:
+ validate_destination_data(data, allowed_destination_types=billing_alerts_api.BILLING_DESTINATION_TYPES)
+ except AlertDestinationValidationError as error:
+ if error.field:
+ raise ValidationError({error.field: error.message})
+ raise ValidationError(error.message)
+
+ # URL-shape checks beyond the shared required-field validation.
+ webhook_url = attrs.get("webhook_url")
+ if data["type"] in (DestinationType.WEBHOOK, DestinationType.TEAMS) and webhook_url:
+ parsed_url = urlparse(webhook_url)
+ if parsed_url.scheme != "https" or not parsed_url.netloc:
+ raise ValidationError({"webhook_url": "Webhook URLs must be valid HTTPS URLs."})
+ if data["type"] == DestinationType.TEAMS and not _is_microsoft_teams_webhook(webhook_url):
+ raise ValidationError({"webhook_url": "Enter a supported Microsoft Teams webhook URL."})
+ return attrs
+
+
+class BillingAlertDestinationChangesSerializer(serializers.Serializer):
+ delete = serializers.ListField(
+ child=serializers.ListField(
+ child=serializers.UUIDField(),
+ min_length=len(billing_alerts_api.BILLING_ALERT_EVENT_IDS),
+ max_length=len(billing_alerts_api.BILLING_ALERT_EVENT_IDS),
+ ),
+ required=False,
+ default=list,
+ )
+
+ def get_fields(self) -> dict[str, serializers.Field]:
+ fields = super().get_fields()
+ fields["create"] = BillingAlertDestinationCreateDataSerializer(many=True, required=False, default=list)
+ return fields
+
+
+class BillingAlertConfigurationSerializer(serializers.ModelSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique identifier for this billing alert.")
+ organization_id = serializers.UUIDField(read_only=True, help_text="Organization this billing alert belongs to.")
+ execution_team_id = serializers.IntegerField(
+ source="team_id",
+ read_only=True,
+ allow_null=True,
+ help_text="Team used as the execution context for internal notification destinations.",
+ )
+ created_by_id = serializers.IntegerField(
+ read_only=True, allow_null=True, help_text="User ID that created this alert."
+ )
+ updated_by_id = serializers.IntegerField(
+ read_only=True,
+ allow_null=True,
+ help_text="User ID that last updated this alert.",
+ )
+ name = serializers.CharField(max_length=160, help_text="Display name for this billing alert.")
+ description = serializers.CharField(required=False, allow_blank=True, help_text="Optional internal description.")
+ enabled = serializers.BooleanField(required=False, help_text="Whether scheduled checks should evaluate this alert.")
+ metric = serializers.ChoiceField(
+ choices=BillingAlertConfiguration.Metric.choices,
+ required=False,
+ help_text="Billing-period total to evaluate: current spend so far, or projected period-end spend.",
+ )
+ threshold_type = serializers.ChoiceField(
+ choices=BillingAlertConfiguration.ThresholdType.choices,
+ required=False,
+ help_text="Threshold rule type. The first version supports absolute value only.",
+ )
+ threshold_percentage = serializers.DecimalField(
+ max_digits=8,
+ decimal_places=2,
+ required=False,
+ allow_null=True,
+ help_text="Reserved for future increase-over-baseline rules. Not used by absolute value alerts.",
+ )
+ threshold_value = serializers.DecimalField(
+ max_digits=20,
+ decimal_places=6,
+ required=False,
+ allow_null=True,
+ help_text="Absolute value or absolute increase that triggers absolute threshold alerts.",
+ )
+ minimum_value = serializers.DecimalField(
+ max_digits=20,
+ decimal_places=6,
+ required=False,
+ help_text="Minimum current value before the alert can fire.",
+ )
+ baseline_window_days = serializers.IntegerField(
+ required=False,
+ min_value=1,
+ max_value=90,
+ help_text="Reserved for future increase-over-baseline rules. Not used by absolute value alerts.",
+ )
+ evaluation_delay_hours = serializers.IntegerField(
+ required=False,
+ min_value=0,
+ max_value=72,
+ help_text="Hours after a UTC billing date ends before it becomes eligible for evaluation.",
+ )
+ cooldown_hours = serializers.IntegerField(
+ required=False,
+ min_value=0,
+ max_value=24 * 30,
+ help_text="Minimum hours between repeated firing notifications.",
+ )
+ snoozed_until = serializers.DateTimeField(
+ required=False,
+ allow_null=True,
+ help_text="ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume.",
+ )
+ destinations = serializers.SerializerMethodField(
+ help_text="Notification destination groups configured for this alert, including their shared HogFunctions.",
+ )
+ destination_changes = BillingAlertDestinationChangesSerializer(
+ required=False,
+ write_only=True,
+ help_text="Destination groups to create or delete in the same transaction as this configuration write.",
+ )
+
+ class Meta:
+ model = BillingAlertConfiguration
+ fields = [
+ "id",
+ "organization_id",
+ "execution_team_id",
+ "created_by_id",
+ "updated_by_id",
+ "name",
+ "description",
+ "enabled",
+ "metric",
+ "currency",
+ "configuration_revision",
+ "threshold_type",
+ "threshold_percentage",
+ "threshold_value",
+ "minimum_value",
+ "baseline_window_days",
+ "evaluation_delay_hours",
+ "state",
+ "cooldown_hours",
+ "snoozed_until",
+ "next_check_at",
+ "last_checked_at",
+ "last_notified_at",
+ "consecutive_failures",
+ "destinations",
+ "destination_changes",
+ "created_at",
+ "updated_at",
+ ]
+ read_only_fields = [
+ "currency",
+ "configuration_revision",
+ "state",
+ "next_check_at",
+ "last_checked_at",
+ "last_notified_at",
+ "consecutive_failures",
+ "created_at",
+ "updated_at",
+ ]
+ extra_kwargs = {
+ "currency": {"help_text": "Server-controlled currency for spend values."},
+ "configuration_revision": {"help_text": "Revision incremented whenever evaluation behavior changes."},
+ "state": {"help_text": "Current lifecycle state of this alert."},
+ "next_check_at": {"help_text": "When the next scheduled evaluation is due."},
+ "last_checked_at": {"help_text": "When this alert was last evaluated."},
+ "last_notified_at": {"help_text": "When notifications were last delivered for this alert."},
+ "consecutive_failures": {"help_text": "Number of consecutive failed evaluations."},
+ "created_at": {"help_text": "When this alert was created."},
+ "updated_at": {"help_text": "When this alert was last updated."},
+ }
+
+ @extend_schema_field(BillingAlertDestinationSummarySerializer(many=True))
+ def get_destinations(self, obj: BillingAlertConfiguration) -> list[dict[str, Any]]:
+ cache = self.context.get(_DESTINATIONS_CACHE_KEY)
+ if cache is None:
+ alerts = self._destination_cache_alerts(obj)
+ cache = billing_alerts_api.destinations_for_alerts(alerts)
+ self.context[_DESTINATIONS_CACHE_KEY] = cache
+ destinations_by_alert_id = cast(dict[str, list[dict[str, Any]]], cache)
+ return destinations_by_alert_id.get(str(obj.id), [])
+
+ def _destination_cache_alerts(self, obj: BillingAlertConfiguration) -> list[BillingAlertConfiguration]:
+ parent_instance = getattr(getattr(self, "parent", None), "instance", None)
+ instance = parent_instance if parent_instance is not None else self.instance
+
+ if isinstance(instance, BillingAlertConfiguration):
+ return [instance]
+ if isinstance(instance, QuerySet | list):
+ alerts = [item for item in instance if isinstance(item, BillingAlertConfiguration)]
+ if alerts:
+ return alerts
+ return [obj]
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ current = self.instance
+ # On create there is no instance, so fall back to the model default rather than
+ # RELATIVE_INCREASE: an omitted threshold_type should validate as what actually
+ # gets persisted (ABSOLUTE_VALUE), not trip the "absolute value only" rejection below.
+ threshold_type = attrs.get(
+ "threshold_type",
+ current.threshold_type if current else BillingAlertConfiguration.ThresholdType.ABSOLUTE_VALUE,
+ )
+ threshold_percentage = attrs.get(
+ "threshold_percentage",
+ current.threshold_percentage if current else None,
+ )
+ threshold_value = attrs.get("threshold_value", current.threshold_value if current else None)
+ minimum_value = attrs.get("minimum_value", current.minimum_value if current else Decimal("0"))
+
+ errors = validate_threshold_configuration(
+ threshold_type=threshold_type,
+ threshold_percentage=threshold_percentage,
+ threshold_value=threshold_value,
+ minimum_value=minimum_value,
+ )
+ if errors:
+ raise ValidationError(errors)
+
+ # The first version evaluates a single billing-period total, so only absolute value
+ # thresholds are meaningful. Increase-over-baseline rules need daily buckets.
+ if threshold_type != BillingAlertConfiguration.ThresholdType.ABSOLUTE_VALUE:
+ raise ValidationError(
+ {"threshold_type": "Billing alerts currently support the absolute value threshold only."}
+ )
+
+ enabled = attrs.get("enabled", current.enabled if current else True)
+ if attrs.get("snoozed_until") is not None and not enabled:
+ raise ValidationError({"snoozed_until": "A disabled alert cannot also be snoozed."})
+ return attrs
+
+ def create(self, validated_data: dict[str, Any]) -> BillingAlertConfiguration:
+ destination_changes = validated_data.pop("destination_changes", None)
+ with transaction.atomic():
+ alert = super().create(validated_data)
+ billing_alerts_api.initialize_billing_alert_lifecycle(alert)
+ if destination_changes:
+ billing_alerts_api.apply_destination_changes(
+ alert, request=self.context["request"], changes=destination_changes
+ )
+ return alert
+
+ def update(
+ self,
+ instance: BillingAlertConfiguration,
+ validated_data: dict[str, Any],
+ ) -> BillingAlertConfiguration:
+ destination_changes = validated_data.pop("destination_changes", None)
+ snoozed_until = validated_data.get("snoozed_until", _NOT_PROVIDED)
+ evaluation_fields = {
+ "threshold_type",
+ "threshold_percentage",
+ "threshold_value",
+ "minimum_value",
+ "baseline_window_days",
+ "evaluation_delay_hours",
+ }
+ revision_fields = evaluation_fields | {
+ "enabled",
+ "snoozed_until",
+ "cooldown_hours",
+ }
+ with transaction.atomic():
+ locked = BillingAlertConfiguration.objects.select_for_update().get(
+ pk=instance.pk,
+ organization_id=instance.organization_id,
+ )
+ evaluation_changed = _any_field_changed(locked, validated_data, evaluation_fields)
+ configuration_changed = _any_field_changed(
+ locked,
+ validated_data,
+ revision_fields,
+ )
+ enabled_change: bool | None = None
+ if "enabled" in validated_data and validated_data["enabled"] != locked.enabled:
+ enabled_change = validated_data["enabled"]
+
+ billing_alerts_api.apply_billing_alert_configuration_lifecycle(
+ locked,
+ enabled_change=enabled_change,
+ snoozed_until_provided=snoozed_until is not _NOT_PROVIDED,
+ snoozed_until=snoozed_until if snoozed_until is not _NOT_PROVIDED else None,
+ threshold_changed=evaluation_changed,
+ )
+
+ updated = super().update(locked, validated_data)
+ billing_alerts_api.reschedule_billing_alert_configuration(
+ updated,
+ configuration_changed=configuration_changed,
+ )
+ if destination_changes:
+ billing_alerts_api.apply_destination_changes(
+ updated, request=self.context["request"], changes=destination_changes
+ )
+ return updated
+
+
+class BillingAlertDeleteDestinationSerializer(serializers.Serializer):
+ hog_function_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ min_length=len(billing_alerts_api.BILLING_ALERT_EVENT_IDS),
+ max_length=len(billing_alerts_api.BILLING_ALERT_EVENT_IDS),
+ help_text="HogFunction IDs to delete as one atomic destination group.",
+ )
+
+
+class BillingAlertDestinationResponseSerializer(serializers.Serializer):
+ hog_function_ids = serializers.ListField(child=serializers.UUIDField())
+
+
+class BillingAlertCheckNowResponseSerializer(serializers.Serializer):
+ event = BillingAlertEventSerializer(
+ required=False,
+ allow_null=True,
+ help_text="Evaluation event recorded by the manual check, or null for a paused preview.",
+ )
+ dispatched_destinations = serializers.IntegerField(help_text="Number of destination HogFunctions queued.")
+ preview = serializers.BooleanField(
+ help_text="True when the alert is paused: it was evaluated but no notifications were sent.",
+ )
+ threshold_breached = serializers.BooleanField(
+ help_text="Whether the evaluated billing-period total breached the configured threshold.",
+ )
+ current_value = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="Evaluated billing-period total, or null when billing data was not available.",
+ )
diff --git a/products/billing_alerts/backend/presentation/throttles.py b/products/billing_alerts/backend/presentation/throttles.py
new file mode 100644
index 000000000000..d41c901496b3
--- /dev/null
+++ b/products/billing_alerts/backend/presentation/throttles.py
@@ -0,0 +1,18 @@
+from typing import Any
+
+from rest_framework.request import Request
+
+from posthog.rate_limit import PersonalApiKeyOrUserRateThrottle
+
+
+class BillingAlertCheckNowThrottle(PersonalApiKeyOrUserRateThrottle):
+ """Limit manual billing evaluations across every caller in an organization."""
+
+ scope = "billing_alert_check_now"
+ rate = "10/minute"
+
+ def get_cache_key(self, request: Request, view: Any) -> str | None:
+ organization_id = self.safely_get_organization_id_from_view(view)
+ if organization_id:
+ return self.cache_format % {"scope": self.scope, "ident": f"organization_{organization_id}"}
+ return super().get_cache_key(request, view)
diff --git a/products/billing_alerts/backend/presentation/views.py b/products/billing_alerts/backend/presentation/views.py
new file mode 100644
index 000000000000..6e79f41fbf5d
--- /dev/null
+++ b/products/billing_alerts/backend/presentation/views.py
@@ -0,0 +1,190 @@
+from __future__ import annotations
+
+from typing import cast
+
+from django.db.models import QuerySet
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import ValidationError
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.event_usage import report_user_action
+from posthog.models.team.team import Team
+from posthog.models.user import User
+from posthog.permissions import OrganizationAdminReadPermissions
+
+from products.billing_alerts.backend.facade import api as billing_alerts_api
+from products.billing_alerts.backend.facade.api import BillingAlertConfiguration
+from products.billing_alerts.backend.presentation.serializers import (
+ BillingAlertCheckNowResponseSerializer,
+ BillingAlertConfigurationSerializer,
+ BillingAlertDeleteDestinationSerializer,
+ BillingAlertDestinationCreateDataSerializer,
+ BillingAlertDestinationResponseSerializer,
+ BillingAlertEventSerializer,
+)
+from products.billing_alerts.backend.presentation.throttles import BillingAlertCheckNowThrottle
+
+
+@extend_schema(tags=["billing"])
+class BillingAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+ scope_object = "organization"
+ queryset = BillingAlertConfiguration.objects.all()
+ serializer_class = BillingAlertConfigurationSerializer
+ lookup_field = "id"
+ permission_classes = [OrganizationAdminReadPermissions]
+
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ return queryset.filter(organization_id=self.organization.id).order_by("-created_at")
+
+ def _execution_team(self) -> Team:
+ user = cast(User, self.request.user)
+ try:
+ return billing_alerts_api.execution_team_for_organization(self.organization.id, user.team)
+ except billing_alerts_api.BillingAlertExecutionTeamUnavailable as e:
+ raise ValidationError(str(e)) from e
+
+ def perform_create(self, serializer: serializers.BaseSerializer) -> None:
+ user = cast(User, self.request.user)
+ execution_team = self._execution_team()
+ serializer.save(
+ organization_id=self.organization.id,
+ team=execution_team,
+ created_by_id=user.id,
+ updated_by_id=user.id,
+ )
+ report_user_action(user, "billing alert created", request=self.request)
+
+ def perform_update(self, serializer: serializers.BaseSerializer) -> None:
+ user = cast(User, self.request.user)
+ alert = cast(BillingAlertConfiguration, serializer.instance)
+ execution_team = self._execution_team() if alert.team_id is None else alert.team
+ serializer.save(team=execution_team, updated_by_id=user.id)
+ report_user_action(user, "billing alert updated", request=self.request)
+
+ def perform_destroy(self, instance: BillingAlertConfiguration) -> None:
+ billing_alerts_api.delete_alert_and_destinations(instance)
+
+ @extend_schema(
+ request=None,
+ responses={200: BillingAlertEventSerializer(many=True)},
+ description="List evaluation and notification events for this billing alert, newest first.",
+ )
+ @action(detail=True, methods=["GET"], url_path="events", required_scopes=["organization:read"])
+ def events(self, request: Request, *args: object, **kwargs: object) -> Response:
+ alert = self.get_object()
+ queryset = billing_alerts_api.visible_events_for_alert(alert)
+ page = self.paginate_queryset(queryset)
+ if page is not None:
+ serializer = BillingAlertEventSerializer(page, many=True)
+ return self.get_paginated_response(serializer.data)
+
+ serializer = BillingAlertEventSerializer(queryset, many=True)
+ return Response(serializer.data)
+
+ @extend_schema(
+ request=None,
+ responses={200: BillingAlertCheckNowResponseSerializer},
+ description=(
+ "Evaluate this billing alert immediately against real billing spend data. "
+ "An enabled alert can send notifications when the evaluation records a dispatchable event. "
+ "A paused alert is evaluated as a preview only: it reports the current spend and would-be "
+ "outcome without sending notifications or recording an evaluation."
+ ),
+ )
+ @action(
+ detail=True,
+ methods=["POST"],
+ url_path="check_now",
+ required_scopes=["organization:write"],
+ throttle_classes=[BillingAlertCheckNowThrottle],
+ )
+ def check_now(self, request: Request, *args: object, **kwargs: object) -> Response:
+ alert = self.get_object()
+
+ def _amount(value: object) -> str | None:
+ return str(value) if value is not None else None
+
+ if not alert.enabled:
+ try:
+ preview = billing_alerts_api.preview_alert(alert)
+ except billing_alerts_api.BillingAlertEvaluationError as e:
+ raise ValidationError(str(e)) from e
+ response = BillingAlertCheckNowResponseSerializer(
+ {
+ "event": None,
+ "dispatched_destinations": 0,
+ "preview": True,
+ "threshold_breached": preview.evaluation.threshold_breached,
+ "current_value": _amount(preview.evaluation.current_value),
+ }
+ )
+ report_user_action(
+ request.user,
+ "billing alert checked now",
+ {"alert_id": str(alert.id), "preview": True},
+ request=request,
+ )
+ return Response(response.data)
+
+ result = billing_alerts_api.evaluate_and_dispatch_alert(alert)
+ response = BillingAlertCheckNowResponseSerializer(
+ {
+ "event": result.event,
+ "dispatched_destinations": result.dispatched_destinations,
+ "preview": False,
+ "threshold_breached": result.event.threshold_breached,
+ "current_value": _amount(result.event.current_value),
+ }
+ )
+ report_user_action(request.user, "billing alert checked now", {"alert_id": str(alert.id)}, request=request)
+ return Response(response.data)
+
+ @extend_schema(
+ request=BillingAlertDestinationCreateDataSerializer,
+ responses={201: BillingAlertDestinationResponseSerializer},
+ description="Create a notification destination for this alert. One HogFunction is created per alert event kind.",
+ )
+ @action(detail=True, methods=["POST"], url_path="destinations", required_scopes=["organization:write"])
+ def create_destination(self, request: Request, *args: object, **kwargs: object) -> Response:
+ alert = self.get_object()
+ serializer = BillingAlertDestinationCreateDataSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+
+ hog_function_ids = billing_alerts_api.create_destination(alert, request=self.request, data=data)
+
+ report_user_action(
+ request.user,
+ "billing alert destination created",
+ {"alert_id": str(alert.id), "type": data["type"], "event_kinds": list(billing_alerts_api.EVENT_KINDS)},
+ request=request,
+ )
+ response = BillingAlertDestinationResponseSerializer({"hog_function_ids": hog_function_ids})
+ return Response(response.data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(
+ request=BillingAlertDeleteDestinationSerializer,
+ responses={204: None},
+ description="Delete a notification destination by deleting its HogFunction group atomically.",
+ )
+ @action(detail=True, methods=["POST"], url_path="destinations/delete", required_scopes=["organization:write"])
+ def delete_destination(self, request: Request, *args: object, **kwargs: object) -> Response:
+ alert = self.get_object()
+ serializer = BillingAlertDeleteDestinationSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ hog_function_ids = serializer.validated_data["hog_function_ids"]
+
+ billing_alerts_api.delete_destination(alert, hog_function_ids)
+
+ report_user_action(
+ request.user,
+ "billing alert destination deleted",
+ {"alert_id": str(alert.id), "count": len(hog_function_ids)},
+ request=request,
+ )
+ return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/products/billing_alerts/backend/routes.py b/products/billing_alerts/backend/routes.py
new file mode 100644
index 000000000000..2323d1836fd6
--- /dev/null
+++ b/products/billing_alerts/backend/routes.py
@@ -0,0 +1,12 @@
+from posthog.api.routing import RouterRegistry
+
+from products.billing_alerts.backend.presentation.views import BillingAlertViewSet
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ routers.organizations.register(
+ r"billing/alerts",
+ BillingAlertViewSet,
+ "organization_billing_alerts",
+ ["organization_id"],
+ )
diff --git a/products/billing_alerts/backend/team_lifecycle.py b/products/billing_alerts/backend/team_lifecycle.py
index bd7d7b895c6c..826ba69a6e15 100644
--- a/products/billing_alerts/backend/team_lifecycle.py
+++ b/products/billing_alerts/backend/team_lifecycle.py
@@ -1,21 +1,35 @@
from __future__ import annotations
-from django.db import connections
-from django.db.models import F
+from django.db import connections, transaction
+from django.db.models import F, QuerySet
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django.utils import timezone
+from posthog.models.organization import Organization
from posthog.models.team.team import Team
from products.billing_alerts.backend.models import BillingAlertConfiguration
+def _deleting_team_ids(*, origin: object, instance: Team, using: str) -> set[int]:
+ if isinstance(origin, Organization):
+ return set(
+ Team.objects.using(using).filter(organization_id=instance.organization_id).values_list("id", flat=True)
+ )
+
+ if isinstance(origin, QuerySet) and origin.model is Team:
+ return set(origin.using(using).values_list("id", flat=True))
+
+ return {instance.id}
+
+
@receiver(pre_delete, sender=Team, dispatch_uid="billing_alerts_rehome_before_team_delete")
-def disable_billing_alerts_before_team_delete(
+def rehome_billing_alerts_before_team_delete(
sender: type[Team],
instance: Team,
using: str,
+ origin: object,
**kwargs: object,
) -> None:
"""Skip quietly when this receiver's code is deployed before its migration has run."""
@@ -23,14 +37,40 @@ def disable_billing_alerts_before_team_delete(
if table_name not in connections[using].introspection.table_names():
return
- BillingAlertConfiguration.objects.using(using).filter(team_id=instance.id).update(
- team_id=None,
- enabled=False,
- state=BillingAlertConfiguration.State.NOT_FIRING,
- configuration_revision=F("configuration_revision") + 1,
- snoozed_until=None,
- pending_evaluation_date=None,
- retry_attempt_count=0,
- next_check_at=None,
- updated_at=timezone.now(),
+ from products.alerts.backend.destinations import soft_delete_alert_destinations_for_alerts # noqa: PLC0415
+ from products.billing_alerts.backend.alert_destinations import BILLING_ALERT_EVENT_IDS # noqa: PLC0415
+
+ deleting_team_ids = _deleting_team_ids(origin=origin, instance=instance, using=using)
+ replacement_team_id = (
+ Team.objects.using(using)
+ .filter(organization_id=instance.organization_id)
+ .exclude(id__in=deleting_team_ids)
+ .order_by("id")
+ .values_list("id", flat=True)
+ .first()
)
+
+ with transaction.atomic(using=using):
+ alerts = BillingAlertConfiguration.objects.using(using).select_for_update().filter(team_id=instance.id)
+ alert_ids = [str(alert_id) for alert_id in alerts.values_list("id", flat=True)]
+ soft_delete_alert_destinations_for_alerts(
+ team_id=instance.id,
+ alert_ids=alert_ids,
+ allowed_event_ids=BILLING_ALERT_EVENT_IDS,
+ )
+
+ # Billing alerts evaluate organization-wide data, but HogFunction destinations are team-scoped.
+ # Re-home and disable them because team-specific integrations cannot be moved safely.
+ # This bulk re-home on team deletion is an administrative lifecycle reset, not a per-alert
+ # evaluation transition, so it intentionally does not route through the state machine adapter.
+ alerts.update( # nosemgrep: billing-alert-state-direct-mutation
+ team_id=replacement_team_id,
+ enabled=False,
+ state=BillingAlertConfiguration.State.NOT_FIRING,
+ snoozed_until=None,
+ configuration_revision=F("configuration_revision") + 1,
+ pending_evaluation_date=None,
+ retry_attempt_count=0,
+ next_check_at=None,
+ updated_at=timezone.now(),
+ )
diff --git a/products/billing_alerts/backend/temporal/__init__.py b/products/billing_alerts/backend/temporal/__init__.py
new file mode 100644
index 000000000000..0166dbf5747a
--- /dev/null
+++ b/products/billing_alerts/backend/temporal/__init__.py
@@ -0,0 +1,18 @@
+from products.billing_alerts.backend.temporal.activities import (
+ discover_due_billing_alerts_activity,
+ evaluate_billing_alert_batch_activity,
+)
+from products.billing_alerts.backend.temporal.workflows import (
+ CheckBillingAlertBatchWorkflow,
+ ScheduleDueBillingAlertChecksWorkflow,
+)
+
+WORKFLOWS = [
+ ScheduleDueBillingAlertChecksWorkflow,
+ CheckBillingAlertBatchWorkflow,
+]
+
+ACTIVITIES = [
+ discover_due_billing_alerts_activity,
+ evaluate_billing_alert_batch_activity,
+]
diff --git a/products/billing_alerts/backend/temporal/activities.py b/products/billing_alerts/backend/temporal/activities.py
new file mode 100644
index 000000000000..db7daf2f3c3e
--- /dev/null
+++ b/products/billing_alerts/backend/temporal/activities.py
@@ -0,0 +1,265 @@
+from __future__ import annotations
+
+from collections import defaultdict
+from datetime import UTC, datetime
+from typing import Any
+
+from django.db.models import F, Q, QuerySet, Window
+from django.db.models.functions import RowNumber
+
+import structlog
+import temporalio.activity
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models import Organization
+from posthog.sync import database_sync_to_async
+from posthog.temporal.common.heartbeat import Heartbeater
+
+from products.billing_alerts.backend.logic.evaluator import expected_evaluation_date, fetch_billing_data
+from products.billing_alerts.backend.logic.notifications import (
+ PendingBillingAlertDispatch,
+ commit_pending_billing_alert_dispatches,
+ prepare_billing_alert_dispatch,
+)
+from products.billing_alerts.backend.logic.state_machine import (
+ BillingAlertAlreadyEvaluated,
+ BillingAlertEvaluationInProgress,
+ next_billing_alert_check_at,
+)
+from products.billing_alerts.backend.models import BillingAlertConfiguration
+from products.billing_alerts.backend.temporal.retry_policy import BILLING_ALERT_EVALUATE_RETRY_POLICY
+from products.billing_alerts.backend.temporal.types import BillingAlertInfo, EvaluateBillingAlertBatchActivityInputs
+
+MAX_DUE_BILLING_ALERTS_PER_TICK = 500
+# Failure events are only recorded on the final attempt, so this must match the Temporal policy.
+MAX_ACTIVITY_ATTEMPTS = BILLING_ALERT_EVALUATE_RETRY_POLICY.maximum_attempts
+logger = structlog.get_logger(__name__)
+
+
+def due_billing_alerts_q(now: datetime) -> QuerySet[BillingAlertConfiguration]:
+ """Return the product-owned eligibility query for the hourly sweep."""
+ return (
+ BillingAlertConfiguration.objects.filter(enabled=True)
+ .filter(Q(next_check_at__lte=now) | Q(next_check_at__isnull=True))
+ .filter(Q(snoozed_until__isnull=True) | Q(snoozed_until__lte=now))
+ .exclude(state=BillingAlertConfiguration.State.BROKEN)
+ )
+
+
+def _due_billing_alerts_for_sweep(now: datetime) -> QuerySet[BillingAlertConfiguration]:
+ """Interleave due alerts by organization inside the global sweep budget."""
+ return (
+ due_billing_alerts_q(now)
+ .annotate(
+ _organization_rank=Window(
+ expression=RowNumber(),
+ partition_by=[F("organization_id")],
+ order_by=[F("next_check_at").asc(nulls_first=True), F("id").asc()],
+ )
+ )
+ .order_by(
+ "_organization_rank",
+ F("next_check_at").asc(nulls_first=True),
+ "organization_id",
+ "id",
+ )
+ .only("id", "organization_id", "baseline_window_days", "evaluation_delay_hours", "pending_evaluation_date")[
+ :MAX_DUE_BILLING_ALERTS_PER_TICK
+ ]
+ )
+
+
+def _group_key(alert: BillingAlertConfiguration, now: datetime) -> tuple[Any, ...]:
+ return (
+ str(alert.organization_id),
+ alert.baseline_window_days,
+ alert.evaluation_delay_hours,
+ expected_evaluation_date(alert, now),
+ )
+
+
+def _reschedule_completed_alert(alert: BillingAlertConfiguration, now: datetime) -> None:
+ next_check_at = next_billing_alert_check_at(alert, now)
+ updated = (
+ BillingAlertConfiguration.objects.filter(
+ id=alert.id,
+ organization_id=alert.organization_id,
+ configuration_revision=alert.configuration_revision,
+ )
+ .filter(Q(next_check_at__lte=now) | Q(next_check_at__isnull=True))
+ .update(next_check_at=next_check_at, pending_evaluation_date=None, retry_attempt_count=0, updated_at=now)
+ )
+ if updated:
+ alert.next_check_at = next_check_at
+ alert.pending_evaluation_date = None
+ alert.retry_attempt_count = 0
+
+
+def _record_group_failure(
+ alert_group: list[BillingAlertConfiguration],
+ error: Exception,
+ *,
+ now: datetime,
+ is_transient_error: bool,
+ reason: str,
+) -> list[PendingBillingAlertDispatch]:
+ first_alert = alert_group[0]
+ alert_ids = [str(alert.id) for alert in alert_group]
+ capture_exception(error, {"alert_ids": alert_ids, "feature": "billing_alerts"})
+ logger.exception(
+ "Billing alert group failure",
+ alert_ids=alert_ids,
+ organization_id=str(first_alert.organization_id),
+ reason=reason,
+ )
+
+ pending_dispatches: list[PendingBillingAlertDispatch] = []
+ for alert in alert_group:
+ try:
+ pending_dispatches.append(
+ prepare_billing_alert_dispatch(
+ alert,
+ now=now,
+ error=error,
+ is_transient_error=is_transient_error,
+ failure_reason=reason,
+ )
+ )
+ except BillingAlertAlreadyEvaluated:
+ _reschedule_completed_alert(alert, now)
+ continue
+ except BillingAlertEvaluationInProgress:
+ continue
+ except Exception as dispatch_error:
+ capture_exception(dispatch_error, {"alert_id": str(alert.id), "feature": "billing_alerts"})
+ logger.exception("Billing alert failure event preparation failed", alert_id=str(alert.id))
+ raise
+ return pending_dispatches
+
+
+def _commit_before_activity_retry(pending_dispatches: list[PendingBillingAlertDispatch]) -> None:
+ """Persist work already prepared in this run before the activity re-raises.
+
+ Preparing a dispatch commits its claim as EVALUATING with a lease. If we let the activity fail
+ without committing, those claims stay leased, so the Temporal retry skips them as
+ already-running until the lease expires. A failure here must not mask the original error: the
+ caller is about to raise the one that actually matters.
+ """
+ if not pending_dispatches:
+ return
+ try:
+ commit_pending_billing_alert_dispatches(pending_dispatches)
+ except Exception as commit_error:
+ capture_exception(commit_error, {"feature": "billing_alerts"})
+ logger.exception(
+ "Billing alert partial commit before activity retry failed",
+ alert_ids=[str(dispatch.check.alert.id) for dispatch in pending_dispatches],
+ )
+
+
+def _evaluate_billing_alerts(
+ inputs: EvaluateBillingAlertBatchActivityInputs,
+ *,
+ activity_attempt: int = MAX_ACTIVITY_ATTEMPTS,
+) -> None:
+ now = datetime.now(UTC)
+ alerts = list(due_billing_alerts_q(now).filter(id__in=inputs.alert_ids).order_by("organization_id", "metric", "id"))
+ grouped: dict[tuple[Any, ...], list[BillingAlertConfiguration]] = defaultdict(list)
+ for alert in alerts:
+ grouped[_group_key(alert, now)].append(alert)
+
+ pending_dispatches: list[PendingBillingAlertDispatch] = []
+ for alert_group in grouped.values():
+ first_alert = alert_group[0]
+ try:
+ organization = Organization.objects.get(id=first_alert.organization_id)
+ except Organization.DoesNotExist as e:
+ pending_dispatches.extend(
+ _record_group_failure(
+ alert_group,
+ e,
+ now=now,
+ is_transient_error=False,
+ reason="Billing alert organization was not found.",
+ )
+ )
+ continue
+
+ try:
+ billing_response, query_duration_ms = fetch_billing_data(first_alert, organization, now=now)
+ except Exception as e:
+ if activity_attempt < MAX_ACTIVITY_ATTEMPTS:
+ _commit_before_activity_retry(pending_dispatches)
+ raise
+ pending_dispatches.extend(
+ _record_group_failure(
+ alert_group,
+ e,
+ now=now,
+ is_transient_error=True,
+ reason="Billing alert data fetch failed.",
+ )
+ )
+ continue
+
+ for alert in alert_group:
+ try:
+ pending_dispatches.append(
+ prepare_billing_alert_dispatch(
+ alert,
+ now=now,
+ billing_response=billing_response,
+ query_duration_ms=query_duration_ms,
+ )
+ )
+ except BillingAlertAlreadyEvaluated:
+ _reschedule_completed_alert(alert, now)
+ continue
+ except BillingAlertEvaluationInProgress:
+ continue
+ except Exception as dispatch_error:
+ capture_exception(dispatch_error, {"alert_id": str(alert.id), "feature": "billing_alerts"})
+ logger.exception("Billing alert evaluation preparation failed", alert_id=str(alert.id))
+ _commit_before_activity_retry(pending_dispatches)
+ raise
+
+ commit_pending_billing_alert_dispatches(pending_dispatches)
+
+
+async def discover_due_billing_alerts_activity() -> list[BillingAlertInfo]:
+ @database_sync_to_async(thread_sensitive=False)
+ def get_due_alerts() -> list[BillingAlertInfo]:
+ now = datetime.now(UTC)
+ alerts = list(_due_billing_alerts_for_sweep(now))
+ if len(alerts) >= MAX_DUE_BILLING_ALERTS_PER_TICK:
+ # The sweep is capped, so any remainder waits for the next tick. Billing alerts are
+ # time-sensitive, so make the truncation visible instead of silently deferring them.
+ total_due = due_billing_alerts_q(now).count()
+ logger.warning(
+ "Billing alert sweep hit its per-tick cap; deferring the remainder to the next tick",
+ cap=MAX_DUE_BILLING_ALERTS_PER_TICK,
+ total_due=total_due,
+ deferred=max(total_due - MAX_DUE_BILLING_ALERTS_PER_TICK, 0),
+ )
+ # The key must match _group_key so the batch activity's per-group billing fetch lines up
+ # with the workflow's batching.
+ return [
+ BillingAlertInfo(
+ alert_id=str(alert.id),
+ query_key=":".join(str(part) for part in _group_key(alert, now)),
+ )
+ for alert in alerts
+ ]
+
+ async with Heartbeater():
+ return await get_due_alerts()
+
+
+async def evaluate_billing_alert_batch_activity(inputs: EvaluateBillingAlertBatchActivityInputs) -> None:
+ async with Heartbeater():
+ await database_sync_to_async(_evaluate_billing_alerts, thread_sensitive=False)(
+ inputs,
+ activity_attempt=temporalio.activity.info().attempt,
+ )
diff --git a/products/billing_alerts/backend/temporal/retry_policy.py b/products/billing_alerts/backend/temporal/retry_policy.py
new file mode 100644
index 000000000000..2e997ee91aa3
--- /dev/null
+++ b/products/billing_alerts/backend/temporal/retry_policy.py
@@ -0,0 +1,9 @@
+import datetime as dt
+
+import temporalio.common
+
+BILLING_ALERT_EVALUATE_RETRY_POLICY = temporalio.common.RetryPolicy(
+ initial_interval=dt.timedelta(seconds=10),
+ maximum_interval=dt.timedelta(minutes=2),
+ maximum_attempts=3,
+)
diff --git a/products/billing_alerts/backend/temporal/schedule.py b/products/billing_alerts/backend/temporal/schedule.py
new file mode 100644
index 000000000000..a65b5cc74c62
--- /dev/null
+++ b/products/billing_alerts/backend/temporal/schedule.py
@@ -0,0 +1,34 @@
+import datetime as dt
+
+from django.conf import settings
+
+from temporalio.client import (
+ Client,
+ Schedule,
+ ScheduleActionStartWorkflow,
+ ScheduleOverlapPolicy,
+ SchedulePolicy,
+ ScheduleSpec,
+)
+
+from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
+
+SCHEDULE_ID = "schedule-due-billing-alert-checks-schedule"
+
+
+async def create_schedule_due_billing_alert_checks_schedule(client: Client) -> None:
+ schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ "schedule-due-billing-alert-checks",
+ id=SCHEDULE_ID,
+ task_queue=settings.BILLING_TASK_QUEUE,
+ execution_timeout=dt.timedelta(minutes=10),
+ ),
+ spec=ScheduleSpec(cron_expressions=["5 * * * *"]),
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
+ )
+
+ if await a_schedule_exists(client, SCHEDULE_ID):
+ await a_update_schedule(client, SCHEDULE_ID, schedule)
+ else:
+ await a_create_schedule(client, SCHEDULE_ID, schedule, trigger_immediately=False)
diff --git a/products/billing_alerts/backend/temporal/types.py b/products/billing_alerts/backend/temporal/types.py
new file mode 100644
index 000000000000..8c98b591e47a
--- /dev/null
+++ b/products/billing_alerts/backend/temporal/types.py
@@ -0,0 +1,17 @@
+import dataclasses
+
+
[email protected](frozen=True)
+class BillingAlertInfo:
+ alert_id: str
+ query_key: str
+
+
[email protected](frozen=True)
+class BillingAlertBatchWorkflowInputs:
+ alert_ids: list[str]
+
+
[email protected](frozen=True)
+class EvaluateBillingAlertBatchActivityInputs:
+ alert_ids: list[str]
diff --git a/products/billing_alerts/backend/temporal/workflows.py b/products/billing_alerts/backend/temporal/workflows.py
new file mode 100644
index 000000000000..40b9712ee0bc
--- /dev/null
+++ b/products/billing_alerts/backend/temporal/workflows.py
@@ -0,0 +1,99 @@
+from __future__ import annotations
+
+import json
+import asyncio
+import hashlib
+import datetime as dt
+from collections import defaultdict
+
+import temporalio.common
+import temporalio.workflow
+from temporalio.exceptions import WorkflowAlreadyStartedError
+
+from posthog.temporal.common.base import PostHogWorkflow
+
+from products.billing_alerts.backend.temporal.activities import (
+ discover_due_billing_alerts_activity,
+ evaluate_billing_alert_batch_activity,
+)
+from products.billing_alerts.backend.temporal.retry_policy import BILLING_ALERT_EVALUATE_RETRY_POLICY
+from products.billing_alerts.backend.temporal.types import (
+ BillingAlertBatchWorkflowInputs,
+ EvaluateBillingAlertBatchActivityInputs,
+)
+
+BILLING_ALERT_BATCH_SIZE = 50
+BILLING_ALERT_BATCH_EXECUTION_TIMEOUT = dt.timedelta(minutes=70)
+
+
+def _chunks(items: list[str], size: int) -> list[list[str]]:
+ return [items[index : index + size] for index in range(0, len(items), size)]
+
+
+def _batch_workflow_id(alert_ids: list[str]) -> str:
+ digest = hashlib.sha256(",".join(sorted(alert_ids)).encode("utf-8")).hexdigest()[:16]
+ return f"check-billing-alert-batch-{digest}"
+
+
[email protected](name="schedule-due-billing-alert-checks")
+class ScheduleDueBillingAlertChecksWorkflow(PostHogWorkflow):
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> None:
+ return None
+
+ @temporalio.workflow.run
+ async def run(self) -> None:
+ alerts = await temporalio.workflow.execute_activity(
+ discover_due_billing_alerts_activity,
+ start_to_close_timeout=dt.timedelta(minutes=2),
+ retry_policy=temporalio.common.RetryPolicy(
+ initial_interval=dt.timedelta(seconds=5),
+ maximum_interval=dt.timedelta(minutes=1),
+ maximum_attempts=3,
+ ),
+ )
+ alert_ids_by_query_key: dict[str, list[str]] = defaultdict(list)
+ for alert in alerts:
+ alert_ids_by_query_key[alert.query_key].append(alert.alert_id)
+ tasks = []
+ for alert_ids in alert_ids_by_query_key.values():
+ for batch in _chunks(alert_ids, BILLING_ALERT_BATCH_SIZE):
+ tasks.append(
+ temporalio.workflow.execute_child_workflow(
+ CheckBillingAlertBatchWorkflow.run,
+ BillingAlertBatchWorkflowInputs(alert_ids=batch),
+ id=_batch_workflow_id(batch),
+ parent_close_policy=temporalio.workflow.ParentClosePolicy.ABANDON,
+ execution_timeout=BILLING_ALERT_BATCH_EXECUTION_TIMEOUT,
+ )
+ )
+
+ if tasks:
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+ for result in results:
+ if isinstance(result, WorkflowAlreadyStartedError):
+ temporalio.workflow.logger.info("billing_alert_batch.already_running")
+ elif isinstance(result, BaseException):
+ temporalio.workflow.logger.warning(
+ "billing_alert_batch.child_workflow_error",
+ extra={"error": str(result)},
+ )
+
+
[email protected](name="check-billing-alert-batch")
+class CheckBillingAlertBatchWorkflow(PostHogWorkflow):
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> BillingAlertBatchWorkflowInputs:
+ loaded = BillingAlertBatchWorkflowInputs(**json.loads(inputs[0]))
+ if not loaded.alert_ids:
+ raise ValueError("alert_ids must not be empty")
+ return loaded
+
+ @temporalio.workflow.run
+ async def run(self, inputs: BillingAlertBatchWorkflowInputs) -> None:
+ await temporalio.workflow.execute_activity(
+ evaluate_billing_alert_batch_activity,
+ EvaluateBillingAlertBatchActivityInputs(alert_ids=inputs.alert_ids),
+ start_to_close_timeout=dt.timedelta(minutes=15),
+ retry_policy=BILLING_ALERT_EVALUATE_RETRY_POLICY,
+ )
diff --git a/products/billing_alerts/backend/test/__init__.py b/products/billing_alerts/backend/test/__init__.py
new file mode 100644
index 000000000000..8b137891791f
--- /dev/null
+++ b/products/billing_alerts/backend/test/__init__.py
@@ -0,0 +1 @@
+
diff --git a/products/billing_alerts/backend/test/test_activities.py b/products/billing_alerts/backend/test/test_activities.py
new file mode 100644
index 000000000000..7e2e34704018
--- /dev/null
+++ b/products/billing_alerts/backend/test/test_activities.py
@@ -0,0 +1,251 @@
+from datetime import UTC, datetime, timedelta
+from decimal import Decimal
+
+from freezegun import freeze_time
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from posthog.models import Organization, Team
+
+from products.billing_alerts.backend.models import (
+ BillingAlertConfiguration,
+ BillingAlertEvaluationClaim,
+ BillingAlertEvent,
+)
+from products.billing_alerts.backend.temporal.activities import (
+ _due_billing_alerts_for_sweep,
+ _evaluate_billing_alerts,
+ _group_key,
+ due_billing_alerts_q,
+)
+from products.billing_alerts.backend.temporal.types import EvaluateBillingAlertBatchActivityInputs
+
+
+def _billing_response(current: int) -> dict:
+ return {
+ "customer": {
+ "has_active_subscription": True,
+ "billing_period": {
+ "current_period_start": "2026-06-01T00:00:00Z",
+ "current_period_end": "2026-07-01T00:00:00Z",
+ "interval": "month",
+ },
+ "current_total_amount_usd_after_discount": str(current),
+ "projected_total_amount_usd_with_limit_after_discount": str(current),
+ }
+ }
+
+
+class TestBillingAlertActivities(BaseTest):
+ def _alert(self, **overrides) -> BillingAlertConfiguration:
+ defaults = {
+ "organization_id": self.organization.id,
+ "team_id": self.team.id,
+ "created_by_id": self.user.id,
+ "name": "Period spend cap",
+ "metric": BillingAlertConfiguration.Metric.SPEND,
+ "threshold_type": BillingAlertConfiguration.ThresholdType.ABSOLUTE_VALUE,
+ "threshold_value": Decimal("100"),
+ "minimum_value": Decimal("0"),
+ "evaluation_delay_hours": 6,
+ }
+ defaults.update(overrides)
+ return BillingAlertConfiguration.objects.create(**defaults)
+
+ @freeze_time("2026-06-23T12:00:00Z")
+ @patch("products.billing_alerts.backend.temporal.activities.fetch_billing_data")
+ def test_fetch_failure_records_alert_failures_and_continues_batch(self, mock_fetch_billing_data) -> None:
+ failed_alert = self._alert(name="Spend alert")
+ successful_alert = self._alert(
+ name="Second spend alert",
+ evaluation_delay_hours=7,
+ )
+
+ def fetch_for_alert(alert, _organization, *, now):
+ if alert.id == failed_alert.id:
+ raise RuntimeError("billing unavailable")
+ return _billing_response(100), 12
+
+ mock_fetch_billing_data.side_effect = fetch_for_alert
+
+ with (
+ patch(
+ "products.billing_alerts.backend.logic.notifications.produce_alert_internal_event",
+ return_value=MagicMock(),
+ ),
+ patch(
+ "products.billing_alerts.backend.logic.notifications.flush_alert_internal_events"
+ ) as flush_alert_internal_events,
+ patch(
+ "products.billing_alerts.backend.logic.notifications.alert_internal_event_delivered",
+ return_value=True,
+ ) as alert_internal_event_delivered,
+ ):
+ _evaluate_billing_alerts(
+ EvaluateBillingAlertBatchActivityInputs(alert_ids=[str(failed_alert.id), str(successful_alert.id)])
+ )
+
+ failed_alert.refresh_from_db()
+ successful_alert.refresh_from_db()
+ failed_event = BillingAlertEvent.objects.get(claim__alert=failed_alert)
+ successful_event = BillingAlertEvent.objects.get(claim__alert=successful_alert)
+
+ assert mock_fetch_billing_data.call_count == 2
+ assert failed_event.kind == BillingAlertEvent.Kind.ERRORED
+ assert failed_event.is_transient_error is True
+ assert failed_event.error_message == "Billing alert data fetch failed."
+ assert failed_alert.state == BillingAlertConfiguration.State.NOT_FIRING
+ assert successful_event.kind == BillingAlertEvent.Kind.FIRING
+ assert successful_alert.state == BillingAlertConfiguration.State.FIRING
+ flush_alert_internal_events.assert_called_once()
+ assert alert_internal_event_delivered.call_count == 2
+
+ def test_due_query_applies_billing_eligibility_boundaries(self) -> None:
+ now = datetime(2026, 6, 23, 12, tzinfo=UTC)
+ due = self._alert(name="Due", next_check_at=now)
+ never_checked = self._alert(name="Never checked", next_check_at=None)
+ self._alert(name="Future", next_check_at=now + timedelta(hours=1))
+ self._alert(name="Disabled", enabled=False, next_check_at=now)
+ self._alert(name="Broken", state=BillingAlertConfiguration.State.BROKEN, next_check_at=now)
+ self._alert(name="Snoozed", snoozed_until=now + timedelta(hours=1), next_check_at=now)
+
+ alert_ids = set(due_billing_alerts_q(now).values_list("id", flat=True))
+
+ assert alert_ids == {due.id, never_checked.id}
+
+ def test_due_sweep_interleaves_organizations_inside_global_cap(self) -> None:
+ now = datetime(2026, 6, 23, 12, tzinfo=UTC)
+ first = self._alert(name="First organization A", next_check_at=None)
+ self._alert(name="First organization B", next_check_at=None)
+ other_organization = Organization.objects.create(name="Other")
+ other_team = Team.objects.create(organization=other_organization, name="Other project")
+ other = self._alert(
+ organization_id=other_organization.id,
+ team_id=other_team.id,
+ name="Other organization",
+ next_check_at=None,
+ )
+
+ with patch("products.billing_alerts.backend.temporal.activities.MAX_DUE_BILLING_ALERTS_PER_TICK", 2):
+ selected = list(_due_billing_alerts_for_sweep(now).values_list("id", flat=True))
+
+ assert len(selected) == 2
+ assert other.id in selected
+ selected_organization_ids = set(
+ BillingAlertConfiguration.objects.filter(id__in=selected).values_list("organization_id", flat=True)
+ )
+ assert selected_organization_ids == {first.organization_id, other.organization_id}
+
+ def test_group_key_separates_pending_evaluation_dates(self) -> None:
+ now = datetime(2026, 6, 23, 12, tzinfo=UTC)
+ first = self._alert(pending_evaluation_date=datetime(2026, 6, 21, tzinfo=UTC).date())
+ second = self._alert(pending_evaluation_date=datetime(2026, 6, 22, tzinfo=UTC).date())
+
+ assert _group_key(first, now) != _group_key(second, now)
+
+ @freeze_time("2026-06-23T12:00:00Z")
+ @patch("products.billing_alerts.backend.temporal.activities.fetch_billing_data")
+ def test_retry_skips_alert_already_rescheduled_by_prior_attempt(self, mock_fetch_billing_data) -> None:
+ alert = self._alert(next_check_at=datetime(2026, 6, 24, 12, tzinfo=UTC))
+
+ _evaluate_billing_alerts(EvaluateBillingAlertBatchActivityInputs(alert_ids=[str(alert.id)]))
+
+ mock_fetch_billing_data.assert_not_called()
+
+ @freeze_time("2026-06-23T12:00:00Z")
+ @patch("products.billing_alerts.backend.temporal.activities.fetch_billing_data")
+ def test_completed_claim_advances_a_still_due_alert(self, mock_fetch_billing_data) -> None:
+ now = datetime(2026, 6, 23, 12, tzinfo=UTC)
+ alert = self._alert(next_check_at=now)
+ BillingAlertEvaluationClaim.objects.create(
+ alert=alert,
+ evaluation_date=datetime(2026, 6, 22, tzinfo=UTC).date(),
+ configuration_revision=alert.configuration_revision,
+ status=BillingAlertEvaluationClaim.Status.COMPLETED,
+ )
+
+ _evaluate_billing_alerts(EvaluateBillingAlertBatchActivityInputs(alert_ids=[str(alert.id)]))
+
+ alert.refresh_from_db()
+ assert alert.next_check_at is not None
+ assert alert.next_check_at > now
+ assert alert.pending_evaluation_date is None
+ mock_fetch_billing_data.assert_called_once()
+
+ @freeze_time("2026-06-23T12:00:00Z")
+ @patch("products.billing_alerts.backend.temporal.activities.fetch_billing_data")
+ @patch("products.billing_alerts.backend.temporal.activities.commit_pending_billing_alert_dispatches")
+ @patch("products.billing_alerts.backend.temporal.activities.prepare_billing_alert_dispatch")
+ def test_alert_preparation_failure_retries_the_activity(
+ self,
+ mock_prepare_dispatch,
+ mock_commit_dispatch,
+ mock_fetch_billing_data,
+ ) -> None:
+ first = self._alert(name="First")
+ second = self._alert(name="Second")
+ mock_fetch_billing_data.return_value = (_billing_response(100), 12)
+ mock_prepare_dispatch.side_effect = RuntimeError("database unavailable")
+
+ with self.assertRaisesRegex(RuntimeError, "database unavailable"):
+ _evaluate_billing_alerts(EvaluateBillingAlertBatchActivityInputs(alert_ids=[str(first.id), str(second.id)]))
+
+ assert mock_prepare_dispatch.call_count == 1
+ mock_commit_dispatch.assert_not_called()
+
+ @freeze_time("2026-06-23T12:00:00Z")
+ @patch("products.billing_alerts.backend.temporal.activities.fetch_billing_data")
+ def test_transient_fetch_failure_retries_before_recording_an_event(self, mock_fetch_billing_data) -> None:
+ alert = self._alert()
+ mock_fetch_billing_data.side_effect = RuntimeError("billing unavailable")
+
+ with self.assertRaisesRegex(RuntimeError, "billing unavailable"):
+ _evaluate_billing_alerts(
+ EvaluateBillingAlertBatchActivityInputs(alert_ids=[str(alert.id)]),
+ activity_attempt=1,
+ )
+
+ assert BillingAlertEvent.objects.filter(claim__alert=alert).exists() is False
+
+ @freeze_time("2026-06-23T12:00:00Z")
+ @patch("products.billing_alerts.backend.temporal.activities.fetch_billing_data")
+ def test_transient_fetch_failure_commits_groups_already_prepared(self, mock_fetch_billing_data) -> None:
+ first_alert = self._alert(name="Spend alert")
+ second_alert = self._alert(name="Second spend alert", evaluation_delay_hours=7)
+ prepared_alert_ids: list[str] = []
+
+ def fetch_then_fail(alert, _organization, *, now):
+ if prepared_alert_ids:
+ raise RuntimeError("billing unavailable")
+ prepared_alert_ids.append(str(alert.id))
+ return _billing_response(100), 12
+
+ mock_fetch_billing_data.side_effect = fetch_then_fail
+
+ with (
+ patch(
+ "products.billing_alerts.backend.logic.notifications.produce_alert_internal_event",
+ return_value=MagicMock(),
+ ),
+ patch("products.billing_alerts.backend.logic.notifications.flush_alert_internal_events"),
+ patch(
+ "products.billing_alerts.backend.logic.notifications.alert_internal_event_delivered",
+ return_value=True,
+ ),
+ self.assertRaisesRegex(RuntimeError, "billing unavailable"),
+ ):
+ _evaluate_billing_alerts(
+ EvaluateBillingAlertBatchActivityInputs(alert_ids=[str(first_alert.id), str(second_alert.id)]),
+ activity_attempt=1,
+ )
+
+ prepared_id = prepared_alert_ids[0]
+ stranded_id = str(second_alert.id if prepared_id == str(first_alert.id) else first_alert.id)
+ prepared_claim = BillingAlertEvaluationClaim.objects.get(alert_id=prepared_id)
+
+ # The prepared group must be persisted rather than left leased, otherwise the Temporal
+ # retry sees EVALUATING with a live lease and skips it until the lease expires.
+ assert prepared_claim.status == BillingAlertEvaluationClaim.Status.COMPLETED
+ assert prepared_claim.lease_expires_at is None
+ assert BillingAlertEvent.objects.filter(claim__alert_id=prepared_id).exists() is True
+ assert BillingAlertEvent.objects.filter(claim__alert_id=stranded_id).exists() is False
diff --git a/products/billing_alerts/backend/test/test_alert_destinations.py b/products/billing_alerts/backend/test/test_alert_destinations.py
new file mode 100644
index 000000000000..8e2b40acf724
--- /dev/null
+++ b/products/billing_alerts/backend/test/test_alert_destinations.py
@@ -0,0 +1,251 @@
+from decimal import Decimal
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from rest_framework import status
+
+from posthog.models.organization import OrganizationMembership
+
+from products.billing_alerts.backend.alert_destinations import BILLING_ALERT_EVENT_IDS
+from products.billing_alerts.backend.models import BillingAlertConfiguration
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+
+
+class TestBillingAlertDestinations(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.url = f"/api/organizations/{self.organization.id}/billing/alerts/"
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ def _alert(self, name: str = "Period spend cap") -> BillingAlertConfiguration:
+ return BillingAlertConfiguration.objects.create(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ name=name,
+ metric=BillingAlertConfiguration.Metric.SPEND,
+ threshold_type=BillingAlertConfiguration.ThresholdType.ABSOLUTE_VALUE,
+ threshold_value=Decimal("100"),
+ )
+
+ def _alert_payload(self, **overrides) -> dict:
+ payload = {
+ "name": "Period spend cap",
+ "threshold_type": "absolute_value",
+ "threshold_value": "100",
+ }
+ payload.update(overrides)
+ return payload
+
+ def _destination(self, alert: BillingAlertConfiguration, event_id: str) -> HogFunction:
+ return HogFunction.objects.create(
+ team_id=alert.execution_team_id,
+ name="Billing alert destination",
+ type="internal_destination",
+ enabled=True,
+ hog="",
+ template_id="template-webhook",
+ filters={
+ "events": [{"id": event_id, "type": "events"}],
+ "properties": [
+ {
+ "key": "alert_id",
+ "value": str(alert.id),
+ "operator": "exact",
+ "type": "event",
+ }
+ ],
+ },
+ )
+
+ def _sync_webhook_template(self) -> None:
+ HogFunctionTemplate.objects.get_or_create(
+ template_id="template-webhook",
+ defaults={
+ "sha": "1.0.0",
+ "name": "Webhook",
+ "description": "Generic webhook template",
+ "code": "return event",
+ "code_language": "hog",
+ "inputs_schema": [{"key": "url", "type": "string"}, {"key": "body", "type": "json"}],
+ "type": "destination",
+ "status": "stable",
+ "category": ["Integrations"],
+ "free": True,
+ },
+ )
+
+ def test_create_destination_builds_one_hog_function_per_billing_event(self) -> None:
+ self._sync_webhook_template()
+ alert = self._alert()
+
+ response = self.client.post(
+ f"{self.url}{alert.id}/destinations/",
+ {"type": "webhook", "webhook_url": "https://example.com/billing-alert"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ hog_function_ids = response.json()["hog_function_ids"]
+ hog_functions = list(HogFunction.objects.filter(id__in=hog_function_ids))
+ assert len(hog_functions) == len(BILLING_ALERT_EVENT_IDS)
+ assert {(hog_function.filters or {})["events"][0]["id"] for hog_function in hog_functions} == set(
+ BILLING_ALERT_EVENT_IDS
+ )
+ for hog_function in hog_functions:
+ assert hog_function.template_id == "template-webhook"
+ assert (hog_function.filters or {})["properties"] == [
+ {
+ "key": "alert_id",
+ "value": str(alert.id),
+ "operator": "exact",
+ "type": "event",
+ }
+ ]
+
+ alert_response = self.client.get(f"{self.url}{alert.id}/")
+ assert alert_response.status_code == status.HTTP_200_OK
+ assert alert_response.json()["destinations"] == [
+ {"type": "webhook", "hog_function_ids": sorted(hog_function_ids)}
+ ]
+
+ def test_configuration_and_destination_changes_commit_atomically(self) -> None:
+ self._sync_webhook_template()
+
+ response = self.client.post(
+ self.url,
+ self._alert_payload(
+ destination_changes={
+ "create": [{"type": "webhook", "webhook_url": "https://example.com/billing-alert"}]
+ }
+ ),
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ alert = BillingAlertConfiguration.objects.get(id=response.json()["id"])
+ assert HogFunction.objects.filter(
+ team_id=alert.execution_team_id,
+ deleted=False,
+ filters__properties__contains=[{"key": "alert_id", "value": str(alert.id)}],
+ ).count() == len(BILLING_ALERT_EVENT_IDS)
+
+ def test_destination_only_change_does_not_bump_configuration_revision(self) -> None:
+ self._sync_webhook_template()
+ alert = self._alert()
+
+ response = self.client.patch(
+ f"{self.url}{alert.id}/",
+ {
+ "name": alert.name,
+ "destination_changes": {
+ "create": [{"type": "webhook", "webhook_url": "https://example.com/billing-alert"}]
+ },
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ alert.refresh_from_db()
+ assert alert.configuration_revision == 1
+
+ def test_destination_failure_rolls_back_configuration_write(self) -> None:
+ self._sync_webhook_template()
+
+ response = self.client.post(
+ self.url,
+ self._alert_payload(
+ name="Atomic rollback",
+ destination_changes={
+ "create": [
+ {"type": "webhook", "webhook_url": "https://example.com/first"},
+ {"type": "webhook", "webhook_url": "https://example.com/second"},
+ ]
+ },
+ ),
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert BillingAlertConfiguration.objects.filter(name="Atomic rollback").exists() is False
+ assert HogFunction.objects.filter(name__contains="Atomic rollback").exists() is False
+
+ def test_create_destination_rejects_duplicate_type(self) -> None:
+ self._sync_webhook_template()
+ alert = self._alert()
+ payload = {"type": "webhook", "webhook_url": "https://example.com/billing-alert"}
+
+ first = self.client.post(f"{self.url}{alert.id}/destinations/", payload, format="json")
+ second = self.client.post(f"{self.url}{alert.id}/destinations/", payload, format="json")
+
+ assert first.status_code == status.HTTP_201_CREATED
+ assert second.status_code == status.HTTP_400_BAD_REQUEST
+ assert HogFunction.objects.filter(deleted=False, id__in=first.json()["hog_function_ids"]).count() == len(
+ BILLING_ALERT_EVENT_IDS
+ )
+
+ def test_create_destination_locks_alert_before_duplicate_check(self) -> None:
+ self._sync_webhook_template()
+ alert = self._alert()
+
+ with patch.object(
+ BillingAlertConfiguration.objects,
+ "select_for_update",
+ wraps=BillingAlertConfiguration.objects.select_for_update,
+ ) as select_for_update:
+ response = self.client.post(
+ f"{self.url}{alert.id}/destinations/",
+ {"type": "webhook", "webhook_url": "https://example.com/billing-alert"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ select_for_update.assert_called_once_with()
+
+ def test_delete_destination_removes_complete_group(self) -> None:
+ alert = self._alert()
+ destinations = [self._destination(alert, event_id) for event_id in BILLING_ALERT_EVENT_IDS]
+
+ response = self.client.post(
+ f"{self.url}{alert.id}/destinations/delete/",
+ {"hog_function_ids": [str(destination.id) for destination in destinations]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert HogFunction.objects.filter(
+ id__in=[destination.id for destination in destinations], deleted=True
+ ).count() == len(destinations)
+
+ def test_delete_destination_rejects_another_alerts_hog_function(self) -> None:
+ alert = self._alert()
+ other_alert = self._alert("Other alert")
+ destination = self._destination(alert, BILLING_ALERT_EVENT_IDS[0])
+
+ response = self.client.post(
+ f"{self.url}{other_alert.id}/destinations/delete/",
+ {"hog_function_ids": [str(destination.id)]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ destination.refresh_from_db()
+ assert destination.deleted is False
+ assert destination.enabled is True
+
+ def test_delete_alert_only_removes_billing_destinations(self) -> None:
+ alert = self._alert()
+ billing_destination = self._destination(alert, BILLING_ALERT_EVENT_IDS[0])
+ unrelated_destination = self._destination(alert, "$unrelated_internal_event")
+
+ response = self.client.delete(f"{self.url}{alert.id}/")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ billing_destination.refresh_from_db()
+ unrelated_destination.refresh_from_db()
+ assert billing_destination.deleted is True
+ assert billing_destination.enabled is False
+ assert unrelated_destination.deleted is False
+ assert unrelated_destination.enabled is True
diff --git a/products/billing_alerts/backend/test/test_api.py b/products/billing_alerts/backend/test/test_api.py
new file mode 100644
index 000000000000..f0b76be7dcb3
--- /dev/null
+++ b/products/billing_alerts/backend/test/test_api.py
@@ -0,0 +1,528 @@
+from datetime import timedelta
+from decimal import Decimal
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.core.cache import cache
+from django.core.exceptions import ValidationError
+from django.utils import timezone
+
+from rest_framework import status
+
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.team.team import Team
+
+from products.billing_alerts.backend.alert_destinations import EVENT_KIND_CONFIG
+from products.billing_alerts.backend.facade.api import BillingAlertDispatchResult, BillingAlertPreview
+from products.billing_alerts.backend.logic.evaluator import BillingAlertEvaluation
+from products.billing_alerts.backend.models import (
+ BillingAlertConfiguration,
+ BillingAlertEvaluationClaim,
+ BillingAlertEvent,
+)
+from products.billing_alerts.backend.presentation.serializers import (
+ BillingAlertConfigurationSerializer,
+ BillingAlertDestinationCreateDataSerializer,
+)
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+
+
+class TestBillingAlertAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ self.url = f"/api/organizations/{self.organization.id}/billing/alerts/"
+
+ def _payload(self, **overrides) -> dict:
+ payload = {
+ "name": "Period spend cap",
+ "metric": "spend",
+ "threshold_type": "absolute_value",
+ "threshold_value": "100.00",
+ "minimum_value": "0",
+ "evaluation_delay_hours": 6,
+ "cooldown_hours": 24,
+ }
+ payload.update(overrides)
+ return payload
+
+ def _alert(self, **overrides) -> BillingAlertConfiguration:
+ defaults = {
+ "organization_id": self.organization.id,
+ "team_id": self.team.id,
+ "name": "Period spend cap",
+ "metric": BillingAlertConfiguration.Metric.SPEND,
+ "threshold_type": BillingAlertConfiguration.ThresholdType.ABSOLUTE_VALUE,
+ "threshold_value": Decimal("100"),
+ }
+ defaults.update(overrides)
+ return BillingAlertConfiguration.objects.create(**defaults)
+
+ def _destination(self, alert: BillingAlertConfiguration, template_id: str) -> HogFunction:
+ destinations = [
+ HogFunction.objects.create(
+ team_id=alert.execution_team_id,
+ name=f"Billing alert destination {template_id}",
+ type="internal_destination",
+ enabled=True,
+ hog="",
+ template_id=template_id,
+ filters={
+ "events": [{"id": config.event_id, "type": "events"}],
+ "properties": [
+ {
+ "key": "alert_id",
+ "value": str(alert.id),
+ "operator": "exact",
+ "type": "event",
+ }
+ ],
+ },
+ )
+ for config in EVENT_KIND_CONFIG.values()
+ ]
+ return destinations[0]
+
+ def test_create_billing_alert(self) -> None:
+ response = self.client.post(self.url, self._payload(), format="json")
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ data = response.json()
+ assert data["name"] == "Period spend cap"
+ assert data["organization_id"] == str(self.organization.id)
+ assert data["execution_team_id"] == self.team.id
+ assert data["created_by_id"] == self.user.id
+ assert data["state"] == BillingAlertConfiguration.State.NOT_FIRING
+
+ alert = BillingAlertConfiguration.objects.get(id=data["id"])
+ assert alert.threshold_value == Decimal("100.00")
+
+ def test_create_rejects_non_absolute_threshold_in_v1(self) -> None:
+ response = self.client.post(
+ self.url,
+ self._payload(threshold_type="relative_increase", threshold_percentage="50.00", threshold_value=None),
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "threshold_type"
+
+ def test_create_accepts_projected_spend_metric(self) -> None:
+ response = self.client.post(self.url, self._payload(metric="projected_spend"), format="json")
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ alert = BillingAlertConfiguration.objects.get(id=response.json()["id"])
+ assert alert.metric == BillingAlertConfiguration.Metric.PROJECTED_SPEND
+
+ def test_create_snoozed_alert_applies_snooze_transition(self) -> None:
+ snoozed_until = timezone.now() + timedelta(hours=2)
+
+ response = self.client.post(
+ self.url,
+ self._payload(snoozed_until=snoozed_until.isoformat()),
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ alert = BillingAlertConfiguration.objects.get(id=response.json()["id"])
+ assert alert.state == BillingAlertConfiguration.State.SNOOZED
+ assert alert.snoozed_until == snoozed_until
+
+ def test_enable_resets_lifecycle_state_and_failures(self) -> None:
+ alert = self._alert(
+ enabled=False,
+ state=BillingAlertConfiguration.State.BROKEN,
+ consecutive_failures=5,
+ )
+
+ response = self.client.patch(f"{self.url}{alert.id}/", {"enabled": True}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ alert.refresh_from_db()
+ assert alert.enabled is True
+ assert alert.state == BillingAlertConfiguration.State.NOT_FIRING
+ assert alert.consecutive_failures == 0
+
+ def test_disable_preserves_failure_count_and_resets_state(self) -> None:
+ alert = self._alert(
+ enabled=True,
+ state=BillingAlertConfiguration.State.FIRING,
+ consecutive_failures=3,
+ )
+
+ response = self.client.patch(f"{self.url}{alert.id}/", {"enabled": False}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ alert.refresh_from_db()
+ assert alert.enabled is False
+ assert alert.state == BillingAlertConfiguration.State.NOT_FIRING
+ assert alert.consecutive_failures == 3
+
+ def test_snooze_preserves_failure_count_and_sets_snoozed_state(self) -> None:
+ snoozed_until = timezone.now() + timedelta(hours=2)
+ alert = self._alert(
+ state=BillingAlertConfiguration.State.FIRING,
+ consecutive_failures=2,
+ )
+
+ response = self.client.patch(
+ f"{self.url}{alert.id}/",
+ {"snoozed_until": snoozed_until.isoformat()},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ alert.refresh_from_db()
+ assert alert.state == BillingAlertConfiguration.State.SNOOZED
+ assert alert.snoozed_until == snoozed_until
+ assert alert.consecutive_failures == 2
+
+ def test_unsnooze_resets_state_and_failures(self) -> None:
+ alert = self._alert(
+ state=BillingAlertConfiguration.State.SNOOZED,
+ snoozed_until=timezone.now() + timedelta(hours=2),
+ consecutive_failures=4,
+ )
+
+ response = self.client.patch(f"{self.url}{alert.id}/", {"snoozed_until": None}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ alert.refresh_from_db()
+ assert alert.state == BillingAlertConfiguration.State.NOT_FIRING
+ assert alert.snoozed_until is None
+ assert alert.consecutive_failures == 0
+
+ def test_threshold_edit_resets_firing_state_and_failures(self) -> None:
+ alert = self._alert(
+ state=BillingAlertConfiguration.State.FIRING,
+ consecutive_failures=3,
+ )
+
+ response = self.client.patch(
+ f"{self.url}{alert.id}/",
+ {"threshold_value": "150.00"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ alert.refresh_from_db()
+ assert alert.threshold_value == Decimal("150.00")
+ assert alert.state == BillingAlertConfiguration.State.NOT_FIRING
+ assert alert.consecutive_failures == 0
+ assert alert.configuration_revision == 2
+ assert response.json()["configuration_revision"] == 2
+
+ def test_copy_only_edit_does_not_bump_configuration_revision(self) -> None:
+ alert = self._alert()
+
+ response = self.client.patch(
+ f"{self.url}{alert.id}/",
+ {"name": "Renamed alert", "description": "Updated copy"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ alert.refresh_from_db()
+ assert alert.configuration_revision == 1
+
+ def test_evaluation_rule_edits_reset_firing_state_and_failures(self) -> None:
+ updates = [
+ ("baseline_window_days", 14),
+ ("evaluation_delay_hours", 12),
+ ]
+
+ for field, value in updates:
+ with self.subTest(field=field):
+ alert = self._alert(
+ state=BillingAlertConfiguration.State.FIRING,
+ consecutive_failures=3,
+ )
+
+ response = self.client.patch(f"{self.url}{alert.id}/", {field: value}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ alert.refresh_from_db()
+ assert getattr(alert, field) == value
+ assert alert.state == BillingAlertConfiguration.State.NOT_FIRING
+ assert alert.consecutive_failures == 0
+
+ def test_threshold_edit_preserves_snoozed_state(self) -> None:
+ snoozed_until = timezone.now() + timedelta(hours=2)
+ alert = self._alert(
+ state=BillingAlertConfiguration.State.SNOOZED,
+ snoozed_until=snoozed_until,
+ consecutive_failures=3,
+ )
+
+ response = self.client.patch(
+ f"{self.url}{alert.id}/",
+ {"minimum_value": "10.00"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ alert.refresh_from_db()
+ assert alert.minimum_value == Decimal("10.00")
+ assert alert.state == BillingAlertConfiguration.State.SNOOZED
+ assert alert.snoozed_until == snoozed_until
+ assert alert.consecutive_failures == 3
+
+ def test_model_rejects_execution_team_from_different_organization(self) -> None:
+ other_org = Organization.objects.create(name="Other")
+ other_team = Team.objects.create(organization=other_org, name="Other project")
+ alert = BillingAlertConfiguration(
+ organization_id=self.organization.id,
+ team_id=other_team.id,
+ name="Daily spend spike",
+ metric=BillingAlertConfiguration.Metric.SPEND,
+ threshold_type=BillingAlertConfiguration.ThresholdType.RELATIVE_INCREASE,
+ threshold_percentage=Decimal("50"),
+ )
+
+ with self.assertRaises(ValidationError):
+ alert.full_clean()
+
+ def test_list_is_scoped_to_organization(self) -> None:
+ other_org = Organization.objects.create(name="Other")
+ other_team = Team.objects.create(organization=other_org, name="Other project")
+ BillingAlertConfiguration.objects.create(
+ organization_id=other_org.id,
+ team_id=other_team.id,
+ name="Other alert",
+ metric=BillingAlertConfiguration.Metric.SPEND,
+ threshold_type=BillingAlertConfiguration.ThresholdType.RELATIVE_INCREASE,
+ threshold_percentage=Decimal("50"),
+ )
+ self.client.post(self.url, self._payload(name="Visible alert"), format="json")
+
+ response = self.client.get(self.url)
+
+ assert response.status_code == status.HTTP_200_OK
+ results = response.json()["results"]
+ assert [row["name"] for row in results] == ["Visible alert"]
+
+ def test_complete_destinations_are_loaded_once_for_alert_list_serializer(self) -> None:
+ slack_alert = self._alert(name="Slack alert")
+ webhook_alert = self._alert(name="Webhook alert")
+ empty_alert = self._alert(name="Empty alert")
+ self._destination(slack_alert, "template-slack")
+ self._destination(slack_alert, "template-slack")
+ self._destination(webhook_alert, "template-webhook")
+
+ serializer = BillingAlertConfigurationSerializer(
+ [slack_alert, webhook_alert, empty_alert],
+ many=True,
+ )
+
+ with self.assertNumQueries(1):
+ data = list(serializer.data)
+
+ assert len(data[0]["destinations"][0]["hog_function_ids"]) == len(EVENT_KIND_CONFIG)
+ assert len(data[1]["destinations"][0]["hog_function_ids"]) == len(EVENT_KIND_CONFIG)
+ assert data[2]["destinations"] == []
+
+ def test_non_admin_cannot_create(self) -> None:
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ response = self.client.post(self.url, self._payload(), format="json")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert not BillingAlertConfiguration.objects.exists()
+
+ def test_organization_write_key_can_create_and_update(self) -> None:
+ api_key = self.create_personal_api_key_with_scopes(["organization:write"])
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")
+
+ created = self.client.post(self.url, self._payload(), format="json")
+
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+ alert_id = created.json()["id"]
+
+ updated = self.client.patch(
+ f"{self.url}{alert_id}/",
+ {"threshold_value": "150.00"},
+ format="json",
+ )
+
+ assert updated.status_code == status.HTTP_200_OK, updated.json()
+ assert updated.json()["threshold_value"] == "150.000000"
+ assert updated.json()["configuration_revision"] == 2
+
+ def test_organization_read_key_cannot_create(self) -> None:
+ api_key = self.create_personal_api_key_with_scopes(["organization:read"])
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")
+
+ response = self.client.post(self.url, self._payload(), format="json")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert not BillingAlertConfiguration.objects.exists()
+
+ def test_webhook_destinations_require_https(self) -> None:
+ serializer = BillingAlertDestinationCreateDataSerializer(
+ data={"type": "webhook", "webhook_url": "http://example.com/billing-alert"},
+ )
+
+ assert serializer.is_valid() is False
+ assert "webhook_url" in serializer.errors
+
+ serializer = BillingAlertDestinationCreateDataSerializer(
+ data={"type": "webhook", "webhook_url": "https://"},
+ )
+
+ assert serializer.is_valid() is False
+ assert "webhook_url" in serializer.errors
+
+ serializer = BillingAlertDestinationCreateDataSerializer(
+ data={"type": "webhook", "webhook_url": "https://example.com/billing-alert"},
+ )
+
+ assert serializer.is_valid(), serializer.errors
+
+ def test_teams_destinations_require_a_microsoft_workflow_webhook(self) -> None:
+ invalid = BillingAlertDestinationCreateDataSerializer(
+ data={"type": "teams", "webhook_url": "https://example.com/teams"},
+ )
+ valid = BillingAlertDestinationCreateDataSerializer(
+ data={
+ "type": "teams",
+ "webhook_url": "https://example.powerautomate.com/workflows/abc",
+ },
+ )
+
+ assert invalid.is_valid() is False
+ assert "webhook_url" in invalid.errors
+ assert valid.is_valid(), valid.errors
+
+ def test_rejects_negative_minimum(self) -> None:
+ negative_minimum = self.client.post(self.url, self._payload(minimum_value="-1"), format="json")
+
+ assert negative_minimum.status_code == status.HTTP_400_BAD_REQUEST
+ assert negative_minimum.json()["attr"] == "minimum_value"
+
+ def test_check_now_uses_shared_organization_object_permissions(self) -> None:
+ alert = BillingAlertConfiguration.objects.create(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ name="Daily spend spike",
+ metric=BillingAlertConfiguration.Metric.SPEND,
+ threshold_type=BillingAlertConfiguration.ThresholdType.RELATIVE_INCREASE,
+ threshold_percentage=Decimal("50"),
+ )
+ claim = BillingAlertEvaluationClaim.objects.create(
+ alert=alert,
+ evaluation_date=timezone.now().date(),
+ configuration_revision=alert.configuration_revision,
+ attempt_count=1,
+ )
+ event = BillingAlertEvent.objects.create(
+ claim=claim,
+ team_id=alert.execution_team_id,
+ kind=BillingAlertEvent.Kind.CHECK,
+ source=BillingAlertEvent.Source.MANUAL,
+ attempt_number=1,
+ metric=BillingAlertConfiguration.Metric.SPEND,
+ state_before=BillingAlertConfiguration.State.NOT_FIRING,
+ state_after=BillingAlertConfiguration.State.NOT_FIRING,
+ reason="Manual check",
+ )
+
+ with patch(
+ "products.billing_alerts.backend.presentation.views.billing_alerts_api.evaluate_and_dispatch_alert",
+ return_value=BillingAlertDispatchResult(event=event, dispatched_destinations=0),
+ ):
+ response = self.client.post(f"{self.url}{alert.id}/check_now/", format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["event"]["id"] == str(event.id)
+
+ def test_check_now_on_paused_alert_previews_without_dispatching(self) -> None:
+ alert = self._alert(enabled=False)
+ evaluation = BillingAlertEvaluation(
+ evaluation_date=timezone.now().date(),
+ period_start=timezone.now(),
+ period_end=timezone.now(),
+ current_value=Decimal("120"),
+ baseline_value=None,
+ absolute_delta=None,
+ relative_delta_percentage=None,
+ threshold_breached=True,
+ reason="preview",
+ payload={},
+ )
+ outcome = MagicMock(notification=MagicMock())
+
+ with (
+ patch(
+ "products.billing_alerts.backend.presentation.views.billing_alerts_api.preview_alert",
+ return_value=BillingAlertPreview(evaluation=evaluation, outcome=outcome),
+ ) as preview,
+ patch(
+ "products.billing_alerts.backend.presentation.views.billing_alerts_api.evaluate_and_dispatch_alert",
+ ) as dispatch,
+ ):
+ response = self.client.post(f"{self.url}{alert.id}/check_now/", format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ body = response.json()
+ assert body["preview"] is True
+ assert body["event"] is None
+ assert body["threshold_breached"] is True
+ assert body["current_value"] == "120"
+ preview.assert_called_once()
+ dispatch.assert_not_called()
+
+ @patch(
+ "products.billing_alerts.backend.presentation.throttles.BillingAlertCheckNowThrottle.rate",
+ new="2/minute",
+ )
+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
+ def test_check_now_is_throttled_per_organization_across_revisions_and_alerts(
+ self, _rate_limit_enabled_mock
+ ) -> None:
+ first = self._alert(name="First")
+ second = self._alert(name="Second")
+ claim = BillingAlertEvaluationClaim.objects.create(
+ alert=first,
+ evaluation_date=timezone.now().date(),
+ configuration_revision=first.configuration_revision,
+ attempt_count=1,
+ )
+ event = BillingAlertEvent.objects.create(
+ claim=claim,
+ team_id=first.execution_team_id,
+ kind=BillingAlertEvent.Kind.CHECK,
+ source=BillingAlertEvent.Source.MANUAL,
+ attempt_number=1,
+ metric=BillingAlertConfiguration.Metric.SPEND,
+ state_before=BillingAlertConfiguration.State.NOT_FIRING,
+ state_after=BillingAlertConfiguration.State.NOT_FIRING,
+ reason="Manual check",
+ )
+ throttle_key = f"throttle_billing_alert_check_now_organization_{self.organization.id}"
+ cache.delete(throttle_key)
+ self.addCleanup(cache.delete, throttle_key)
+
+ with patch(
+ "products.billing_alerts.backend.presentation.views.billing_alerts_api.evaluate_and_dispatch_alert",
+ return_value=BillingAlertDispatchResult(event=event, dispatched_destinations=0),
+ ) as evaluate_and_dispatch:
+ first_check = self.client.post(f"{self.url}{first.id}/check_now/", format="json")
+ edit = self.client.patch(
+ f"{self.url}{first.id}/",
+ {"threshold_value": "150.00"},
+ format="json",
+ )
+ second_check = self.client.post(f"{self.url}{first.id}/check_now/", format="json")
+ throttled = self.client.post(f"{self.url}{second.id}/check_now/", format="json")
+
+ assert first_check.status_code == status.HTTP_200_OK
+ assert edit.status_code == status.HTTP_200_OK
+ assert edit.json()["configuration_revision"] == 2
+ assert second_check.status_code == status.HTTP_200_OK
+ assert throttled.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+ assert evaluate_and_dispatch.call_count == 2
diff --git a/products/billing_alerts/backend/test/test_evaluator.py b/products/billing_alerts/backend/test/test_evaluator.py
new file mode 100644
index 000000000000..50adce464163
--- /dev/null
+++ b/products/billing_alerts/backend/test/test_evaluator.py
@@ -0,0 +1,244 @@
+from datetime import UTC, datetime
+from decimal import Decimal
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from products.billing_alerts.backend.logic.evaluator import evaluate_billing_alert
+from products.billing_alerts.backend.logic.notifications import (
+ evaluate_and_dispatch_billing_alert,
+ preview_billing_alert,
+)
+from products.billing_alerts.backend.logic.state_machine import MAX_CONSECUTIVE_FAILURES
+from products.billing_alerts.backend.models import BillingAlertConfiguration, BillingAlertEvent
+
+NOW = datetime(2026, 6, 23, 12, 0, tzinfo=UTC)
+
+DESTINATION_ID = "00000000-0000-0000-0000-000000000001"
+
+
+def evaluate_and_record_billing_alert(*args, destination_ids: list[str] | None = None, **kwargs) -> BillingAlertEvent:
+ """Exercise the production delivery-first pipeline with an acknowledged internal event.
+
+ destination_ids defaults to one configured target; pass [] to simulate an alert with no
+ destination configured, where the internal event is delivered but no user is notified.
+ """
+ ids = [DESTINATION_ID] if destination_ids is None else destination_ids
+ with (
+ patch(
+ "products.billing_alerts.backend.logic.notifications.produce_alert_internal_event",
+ return_value=MagicMock(),
+ ),
+ patch(
+ "products.billing_alerts.backend.logic.notifications.alert_internal_event_delivered",
+ return_value=True,
+ ),
+ patch(
+ "products.billing_alerts.backend.logic.notifications._destination_ids",
+ return_value=(ids, bool(ids)),
+ ),
+ ):
+ event, _ = evaluate_and_dispatch_billing_alert(*args, **kwargs)
+ return event
+
+
+def _billing_response(
+ current: str | int | float | None = None,
+ *,
+ projected: str | int | float | None = None,
+ period_start: str = "2026-06-01T00:00:00Z",
+ period_end: str = "2026-07-01T00:00:00Z",
+ customer: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ if customer is None:
+ customer = {
+ "has_active_subscription": True,
+ "billing_period": {
+ "current_period_start": period_start,
+ "current_period_end": period_end,
+ "interval": "month",
+ },
+ "current_total_amount_usd_after_discount": None if current is None else str(current),
+ "projected_total_amount_usd_with_limit_after_discount": None if projected is None else str(projected),
+ }
+ return {"customer": customer}
+
+
+class TestBillingAlertEvaluator(BaseTest):
+ def _alert(self, **overrides) -> BillingAlertConfiguration:
+ defaults = {
+ "organization_id": self.organization.id,
+ "team_id": self.team.id,
+ "created_by_id": self.user.id,
+ "name": "Period spend cap",
+ "metric": BillingAlertConfiguration.Metric.SPEND,
+ "threshold_type": BillingAlertConfiguration.ThresholdType.ABSOLUTE_VALUE,
+ "threshold_value": Decimal("100"),
+ "minimum_value": Decimal("0"),
+ "baseline_window_days": 7,
+ "evaluation_delay_hours": 6,
+ }
+ defaults.update(overrides)
+ return BillingAlertConfiguration.objects.create(**defaults)
+
+ def test_absolute_value_breaches_on_current_period_spend(self) -> None:
+ alert = self._alert()
+
+ evaluation = evaluate_billing_alert(alert, now=NOW, billing_response=_billing_response(120))
+
+ assert evaluation.current_value == Decimal("120")
+ assert evaluation.threshold_breached is True
+ assert evaluation.payload["amount_field"] == "current_total_amount_usd_after_discount"
+ assert evaluation.period_start == datetime(2026, 6, 1, tzinfo=UTC)
+ assert evaluation.period_end == datetime(2026, 7, 1, tzinfo=UTC)
+
+ def test_projected_spend_metric_reads_projected_period_total(self) -> None:
+ alert = self._alert(metric=BillingAlertConfiguration.Metric.PROJECTED_SPEND)
+
+ evaluation = evaluate_billing_alert(alert, now=NOW, billing_response=_billing_response(40, projected=150))
+
+ assert evaluation.current_value == Decimal("150")
+ assert evaluation.threshold_breached is True
+ assert evaluation.payload["amount_field"] == "projected_total_amount_usd_with_limit_after_discount"
+
+ def test_value_below_threshold_does_not_breach(self) -> None:
+ alert = self._alert()
+
+ evaluation = evaluate_billing_alert(alert, now=NOW, billing_response=_billing_response(70))
+
+ assert evaluation.current_value == Decimal("70")
+ assert evaluation.threshold_breached is False
+
+ def test_value_below_minimum_never_breaches(self) -> None:
+ alert = self._alert(minimum_value=Decimal("50"), threshold_value=Decimal("10"))
+
+ evaluation = evaluate_billing_alert(alert, now=NOW, billing_response=_billing_response(20))
+
+ assert evaluation.threshold_breached is False
+ assert "below the minimum" in evaluation.reason
+
+ def test_missing_period_total_is_inconclusive(self) -> None:
+ alert = self._alert()
+
+ evaluation = evaluate_billing_alert(alert, now=NOW, billing_response=_billing_response(None))
+
+ assert evaluation.current_value is None
+ assert evaluation.threshold_breached is False
+ assert evaluation.is_inconclusive is True
+ assert "did not include a spend total" in evaluation.reason
+
+ def test_invalid_amount_records_error_event(self) -> None:
+ alert = self._alert()
+
+ event = evaluate_and_record_billing_alert(alert, now=NOW, billing_response=_billing_response("not-a-number"))
+ alert.refresh_from_db()
+
+ assert event.kind == BillingAlertEvent.Kind.ERRORED
+ assert event.error_code == "BillingAlertEvaluationError"
+ assert alert.state == BillingAlertConfiguration.State.NOT_FIRING
+ assert alert.consecutive_failures == 1
+
+ def test_missing_customer_records_error_event(self) -> None:
+ alert = self._alert()
+
+ event = evaluate_and_record_billing_alert(alert, now=NOW, billing_response={"detail": "billing unavailable"})
+ alert.refresh_from_db()
+
+ assert event.kind == BillingAlertEvent.Kind.ERRORED
+ assert alert.consecutive_failures == 1
+
+ def test_repeated_error_escalates_to_broken_and_disables(self) -> None:
+ alert = self._alert()
+ BillingAlertConfiguration.objects.filter(pk=alert.pk).update(consecutive_failures=MAX_CONSECUTIVE_FAILURES - 1)
+
+ event = evaluate_and_record_billing_alert(alert, now=NOW, billing_response={"detail": "still down"})
+ alert.refresh_from_db()
+
+ assert event.kind == BillingAlertEvent.Kind.BROKEN_CONFIG
+ assert alert.state == BillingAlertConfiguration.State.BROKEN
+ assert alert.enabled is False
+
+ def test_state_machine_records_firing_then_resolved(self) -> None:
+ alert = self._alert()
+
+ firing = evaluate_and_record_billing_alert(alert, now=NOW, billing_response=_billing_response(120))
+ alert.refresh_from_db()
+
+ assert firing.kind == BillingAlertEvent.Kind.FIRING
+ assert alert.state == BillingAlertConfiguration.State.FIRING
+ assert alert.last_notified_at == NOW
+
+ resolved = evaluate_and_record_billing_alert(
+ alert, now=NOW.replace(day=24), billing_response=_billing_response(70)
+ )
+ alert.refresh_from_db()
+
+ assert resolved.kind == BillingAlertEvent.Kind.RESOLVED
+ assert alert.state == BillingAlertConfiguration.State.NOT_FIRING
+
+ def test_completed_daily_evaluation_is_idempotent(self) -> None:
+ alert = self._alert()
+
+ firing = evaluate_and_record_billing_alert(alert, now=NOW, billing_response=_billing_response(120))
+ repeated = evaluate_and_record_billing_alert(
+ alert, now=NOW.replace(hour=13), billing_response=_billing_response(70)
+ )
+
+ assert repeated.id == firing.id
+ assert (
+ BillingAlertEvent.objects.filter(claim__alert=alert, claim__evaluation_date=firing.evaluation_date).count()
+ == 1
+ )
+
+ def test_cooldown_suppresses_repeated_firing_notification(self) -> None:
+ alert = self._alert(state=BillingAlertConfiguration.State.NOT_FIRING, cooldown_hours=48)
+
+ firing = evaluate_and_record_billing_alert(alert, now=NOW, billing_response=_billing_response(120))
+ alert.refresh_from_db()
+ assert firing.kind == BillingAlertEvent.Kind.FIRING
+
+ repeated = evaluate_and_record_billing_alert(
+ alert, now=NOW.replace(day=24), billing_response=_billing_response(120)
+ )
+ alert.refresh_from_db()
+
+ assert repeated.kind == BillingAlertEvent.Kind.CHECK
+ assert repeated.threshold_breached is True
+ assert alert.state == BillingAlertConfiguration.State.FIRING
+
+ def test_zero_destinations_do_not_start_cooldown(self) -> None:
+ alert = self._alert()
+
+ firing = evaluate_and_record_billing_alert(
+ alert, now=NOW, billing_response=_billing_response(120), destination_ids=[]
+ )
+ alert.refresh_from_db()
+
+ # The alert still fires (internal event tracked), but with nothing delivered the
+ # cooldown timestamp stays unset so a destination added later is not suppressed.
+ assert firing.kind == BillingAlertEvent.Kind.FIRING
+ assert alert.state == BillingAlertConfiguration.State.FIRING
+ assert firing.notification_sent_at is None
+ assert alert.last_notified_at is None
+
+ def test_snoozed_alert_clears_to_resolved(self) -> None:
+ alert = self._alert(state=BillingAlertConfiguration.State.SNOOZED)
+
+ resolved = evaluate_and_record_billing_alert(alert, now=NOW, billing_response=_billing_response(70))
+ alert.refresh_from_db()
+
+ assert resolved.kind == BillingAlertEvent.Kind.RESOLVED
+ assert alert.state == BillingAlertConfiguration.State.NOT_FIRING
+
+ def test_preview_evaluates_without_persisting_or_dispatching(self) -> None:
+ alert = self._alert(enabled=False)
+
+ with patch("products.billing_alerts.backend.logic.notifications.produce_alert_internal_event") as produce_mock:
+ preview = preview_billing_alert(alert, now=NOW, billing_response=_billing_response(120))
+
+ assert preview.evaluation.threshold_breached is True
+ assert preview.would_notify is True
+ produce_mock.assert_not_called()
+ assert BillingAlertEvent.objects.filter(claim__alert=alert).count() == 0
+ assert not alert.evaluation_claims.exists()
diff --git a/products/billing_alerts/backend/test/test_models.py b/products/billing_alerts/backend/test/test_models.py
index 26f56526f3d1..d550f03a81ee 100644
--- a/products/billing_alerts/backend/test/test_models.py
+++ b/products/billing_alerts/backend/test/test_models.py
@@ -12,6 +12,7 @@ from products.billing_alerts.backend.models import (
BillingAlertEvaluationClaim,
BillingAlertEvent,
)
+from products.billing_alerts.backend.presentation.serializers import BillingAlertEventSerializer
def test_relative_delta_percentage_supports_full_value_range() -> None:
@@ -133,3 +134,23 @@ def test_event_lineage_is_derived_from_its_claim() -> None:
assert {"alert", "organization_id", "evaluation_date"}.isdisjoint(
field.name for field in BillingAlertEvent._meta.fields
)
+
+
+def test_relative_delta_percentage_serializer_supports_model_value_range() -> None:
+ alert = BillingAlertConfiguration(metric="spend")
+ claim = BillingAlertEvaluationClaim(
+ alert=alert,
+ evaluation_date=date(2026, 7, 20),
+ configuration_revision=7,
+ )
+ event = BillingAlertEvent(
+ claim=claim,
+ metric="spend",
+ relative_delta_percentage=Decimal("9999999999999999999999.999999"),
+ reason="Large relative change",
+ )
+
+ data = BillingAlertEventSerializer(event).data
+
+ assert data["relative_delta_percentage"] == "9999999999999999999999.999999"
+ assert data["configuration_revision"] == claim.configuration_revision
diff --git a/products/billing_alerts/backend/test/test_notifications.py b/products/billing_alerts/backend/test/test_notifications.py
new file mode 100644
index 000000000000..062d6513fee8
--- /dev/null
+++ b/products/billing_alerts/backend/test/test_notifications.py
@@ -0,0 +1,472 @@
+from datetime import UTC, datetime
+from decimal import Decimal
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from products.billing_alerts.backend.alert_destinations import EVENT_KIND_CONFIG, EventKind
+from products.billing_alerts.backend.logic.notifications import (
+ commit_pending_billing_alert_dispatch,
+ evaluate_and_dispatch_billing_alert,
+ prepare_billing_alert_dispatch,
+)
+from products.billing_alerts.backend.logic.state_machine import (
+ BillingAlertConfigurationChanged,
+ BillingAlertEvaluationInProgress,
+ commit_billing_alert_check,
+ prepare_billing_alert_check,
+)
+from products.billing_alerts.backend.models import (
+ BillingAlertConfiguration,
+ BillingAlertEvaluationClaim,
+ BillingAlertEvent,
+)
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+
+NOW = datetime(2026, 6, 23, 12, 0, tzinfo=UTC)
+
+
+def _billing_response(current: int) -> dict:
+ return {
+ "customer": {
+ "has_active_subscription": True,
+ "billing_period": {
+ "current_period_start": "2026-06-01T00:00:00Z",
+ "current_period_end": "2026-07-01T00:00:00Z",
+ "interval": "month",
+ },
+ "current_total_amount_usd_after_discount": str(current),
+ "projected_total_amount_usd_with_limit_after_discount": str(current),
+ }
+ }
+
+
+class TestBillingAlertNotifications(BaseTest):
+ def _alert(self, **overrides) -> BillingAlertConfiguration:
+ defaults = {
+ "organization_id": self.organization.id,
+ "team_id": self.team.id,
+ "created_by_id": self.user.id,
+ "name": "Period spend cap",
+ "metric": BillingAlertConfiguration.Metric.SPEND,
+ "threshold_type": BillingAlertConfiguration.ThresholdType.ABSOLUTE_VALUE,
+ "threshold_value": Decimal("100"),
+ }
+ defaults.update(overrides)
+ return BillingAlertConfiguration.objects.create(**defaults)
+
+ def _destination(self, alert: BillingAlertConfiguration, event_kind: EventKind = "firing") -> HogFunction:
+ destinations = {
+ kind: HogFunction.objects.create(
+ team_id=alert.execution_team_id,
+ name="Billing alert destination",
+ type="internal_destination",
+ enabled=True,
+ hog="",
+ template_id="template-slack",
+ filters={
+ "events": [{"id": config.event_id, "type": "events"}],
+ "properties": [
+ {
+ "key": "alert_id",
+ "value": str(alert.id),
+ "operator": "exact",
+ "type": "event",
+ }
+ ],
+ },
+ )
+ for kind, config in EVENT_KIND_CONFIG.items()
+ }
+ return destinations[event_kind]
+
+ def test_delivery_ack_precedes_lifecycle_persistence(self) -> None:
+ alert = self._alert()
+ destination = self._destination(alert)
+ produce_result = MagicMock()
+
+ with (
+ patch(
+ "products.billing_alerts.backend.logic.notifications.produce_alert_internal_event",
+ return_value=produce_result,
+ ) as produce,
+ patch("products.billing_alerts.backend.logic.notifications.flush_alert_internal_events") as flush,
+ patch(
+ "products.billing_alerts.backend.logic.notifications.alert_internal_event_delivered",
+ return_value=True,
+ ) as delivered,
+ ):
+ event, dispatched = evaluate_and_dispatch_billing_alert(
+ alert,
+ now=NOW,
+ billing_response=_billing_response(100),
+ )
+
+ alert.refresh_from_db()
+ event.refresh_from_db()
+ assert dispatched == 1
+ assert alert.state == BillingAlertConfiguration.State.FIRING
+ assert alert.last_notified_at == NOW
+ assert event.notification_sent_at == NOW
+ assert event.targets_notified == {"hog_functions": [str(destination.id)]}
+ assert produce.call_args.kwargs["event_name"] == EVENT_KIND_CONFIG["firing"].event_id
+ assert produce.call_args.kwargs["uuid"] == str(event.claim.delivery_uuid)
+ assert "billing_alert_destination_ids" not in produce.call_args.kwargs["properties"]
+ flush.assert_called_once()
+ delivered.assert_called_once_with(
+ produce_result,
+ team_id=alert.execution_team_id,
+ alert_id=str(alert.id),
+ event_name=EVENT_KIND_CONFIG["firing"].event_id,
+ )
+
+ def test_no_destination_commits_event_without_starting_cooldown(self) -> None:
+ alert = self._alert()
+ produce_result = MagicMock()
+
+ with (
+ patch(
+ "products.billing_alerts.backend.logic.notifications.produce_alert_internal_event",
+ return_value=produce_result,
+ ) as produce,
+ patch("products.billing_alerts.backend.logic.notifications.flush_alert_internal_events"),
+ patch(
+ "products.billing_alerts.backend.logic.notifications.alert_internal_event_delivered",
+ return_value=True,
+ ) as delivered,
+ ):
+ event, dispatched = evaluate_and_dispatch_billing_alert(
+ alert,
+ now=NOW,
+ billing_response=_billing_response(100),
+ )
+
+ alert.refresh_from_db()
+ # The internal event is still emitted and the alert transitions to firing, but with no
+ # destination target nothing was delivered: cooldown must not start, so a destination
+ # added later is not suppressed.
+ assert dispatched == 0
+ assert alert.state == BillingAlertConfiguration.State.FIRING
+ assert event.notification_sent_at is None
+ assert event.targets_notified == {}
+ assert alert.last_notified_at is None
+ produce.assert_called_once()
+ delivered.assert_called_once_with(
+ produce_result,
+ team_id=alert.execution_team_id,
+ alert_id=str(alert.id),
+ event_name=EVENT_KIND_CONFIG["firing"].event_id,
+ )
+
+ def test_failed_error_delivery_preserves_last_successful_firing_state(self) -> None:
+ alert = self._alert(state=BillingAlertConfiguration.State.FIRING, consecutive_failures=2)
+ self._destination(alert, "errored")
+
+ with (
+ patch(
+ "products.billing_alerts.backend.logic.notifications.produce_alert_internal_event",
+ return_value=MagicMock(),
+ ),
+ patch("products.billing_alerts.backend.logic.notifications.flush_alert_internal_events"),
+ patch(
+ "products.billing_alerts.backend.logic.notifications.alert_internal_event_delivered",
+ return_value=False,
+ ),
+ ):
+ event, dispatched = evaluate_and_dispatch_billing_alert(
+ alert,
+ now=NOW,
+ error=RuntimeError("billing unavailable"),
+ is_transient_error=True,
+ )
+
+ alert.refresh_from_db()
+ assert dispatched == 0
+ assert alert.state == BillingAlertConfiguration.State.FIRING
+ assert alert.consecutive_failures == 2
+ assert alert.enabled is True
+ assert event.kind == BillingAlertEvent.Kind.ERRORED
+ assert event.state_after == BillingAlertConfiguration.State.FIRING
+ assert event.notification_sent_at is None
+ assert event.error_message == "Billing alert evaluation failed."
+ assert "billing unavailable" not in event.error_message
+
+ def test_same_day_retry_of_delivered_error_does_not_renotify(self) -> None:
+ alert = self._alert()
+ self._destination(alert, "errored")
+
+ with (
+ patch(
+ "products.billing_alerts.backend.logic.notifications.produce_alert_internal_event",
+ return_value=MagicMock(),
+ ) as produce,
+ patch("products.billing_alerts.backend.logic.notifications.flush_alert_internal_events"),
+ patch(
+ "products.billing_alerts.backend.logic.notifications.alert_internal_event_delivered",
+ return_value=True,
+ ),
+ ):
+ first_event, first_dispatched = evaluate_and_dispatch_billing_alert(
+ alert,
+ now=NOW,
+ error=RuntimeError("billing unavailable"),
+ is_transient_error=True,
+ )
+ second_event, second_dispatched = evaluate_and_dispatch_billing_alert(
+ alert,
+ now=NOW.replace(minute=16),
+ error=RuntimeError("billing unavailable"),
+ is_transient_error=True,
+ )
+
+ alert.refresh_from_db()
+ assert first_dispatched == 1
+ assert first_event.notification_sent_at == NOW
+ # The user already received this evaluation date's error, so the retry keeps its event row
+ # for attempt history but sends nothing.
+ assert produce.call_count == 1
+ assert second_dispatched == 0
+ assert second_event.kind == BillingAlertEvent.Kind.ERRORED
+ assert second_event.notification_sent_at is None
+ assert alert.enabled is True
+
+ def test_failed_broken_delivery_keeps_alert_enabled_for_retry(self) -> None:
+ alert = self._alert(consecutive_failures=4)
+ self._destination(alert, "broken")
+
+ with (
+ patch(
+ "products.billing_alerts.backend.logic.notifications.produce_alert_internal_event",
+ return_value=MagicMock(),
+ ),
+ patch("products.billing_alerts.backend.logic.notifications.flush_alert_internal_events"),
+ patch(
+ "products.billing_alerts.backend.logic.notifications.alert_internal_event_delivered",
+ return_value=False,
+ ),
+ ):
+ event, _ = evaluate_and_dispatch_billing_alert(alert, now=NOW, error=RuntimeError("bad config"))
+
+ alert.refresh_from_db()
+ assert alert.state == BillingAlertConfiguration.State.NOT_FIRING
+ assert alert.consecutive_failures == 4
+ assert alert.enabled is True
+ assert event.kind == BillingAlertEvent.Kind.BROKEN_CONFIG
+ assert event.state_after == BillingAlertConfiguration.State.NOT_FIRING
+
+ def test_acknowledged_broken_event_disables_alert(self) -> None:
+ alert = self._alert(consecutive_failures=4)
+ self._destination(alert, "broken")
+
+ with (
+ patch(
+ "products.billing_alerts.backend.logic.notifications.produce_alert_internal_event",
+ return_value=MagicMock(),
+ ),
+ patch("products.billing_alerts.backend.logic.notifications.flush_alert_internal_events"),
+ patch(
+ "products.billing_alerts.backend.logic.notifications.alert_internal_event_delivered",
+ return_value=True,
+ ),
+ ):
+ event, dispatched = evaluate_and_dispatch_billing_alert(
+ alert,
+ now=NOW,
+ error=RuntimeError("bad config"),
+ )
+
+ alert.refresh_from_db()
+ assert dispatched == 1
+ assert alert.state == BillingAlertConfiguration.State.BROKEN
+ assert alert.consecutive_failures == 5
+ assert alert.enabled is False
+ assert event.notification_sent_at == NOW
+
+ def test_clear_check_skips_delivery(self) -> None:
+ alert = self._alert()
+ with patch("products.billing_alerts.backend.logic.notifications.produce_alert_internal_event") as produce:
+ event, dispatched = evaluate_and_dispatch_billing_alert(
+ alert,
+ now=NOW,
+ billing_response=_billing_response(70),
+ )
+
+ assert dispatched == 0
+ assert event.kind == BillingAlertEvent.Kind.CHECK
+ produce.assert_not_called()
+
+ def test_stale_delivery_commit_is_fenced_after_concurrent_disable(self) -> None:
+ alert = self._alert()
+ check = prepare_billing_alert_check(
+ alert,
+ source=BillingAlertEvent.Source.SCHEDULED,
+ now=NOW,
+ billing_response=_billing_response(100),
+ )
+ BillingAlertConfiguration.objects.filter(pk=alert.pk).update(
+ enabled=False,
+ state=BillingAlertConfiguration.State.NOT_FIRING,
+ configuration_revision=alert.configuration_revision + 1,
+ updated_at=NOW,
+ )
+
+ with self.assertRaises(BillingAlertConfigurationChanged):
+ commit_billing_alert_check(check, notification_delivered=True)
+
+ alert.refresh_from_db()
+ assert alert.enabled is False
+ assert alert.state == BillingAlertConfiguration.State.NOT_FIRING
+ assert alert.last_notified_at is None
+ assert BillingAlertEvent.objects.filter(claim__alert=alert).exists() is False
+
+ def test_stale_delivery_commit_preserves_concurrent_snooze(self) -> None:
+ alert = self._alert()
+ check = prepare_billing_alert_check(
+ alert,
+ source=BillingAlertEvent.Source.SCHEDULED,
+ now=NOW,
+ billing_response=_billing_response(100),
+ )
+ snoozed_until = NOW.replace(day=24)
+ BillingAlertConfiguration.objects.filter(pk=alert.pk).update(
+ state=BillingAlertConfiguration.State.SNOOZED,
+ snoozed_until=snoozed_until,
+ configuration_revision=alert.configuration_revision + 1,
+ updated_at=NOW,
+ )
+
+ with self.assertRaises(BillingAlertConfigurationChanged):
+ commit_billing_alert_check(check, notification_delivered=True)
+
+ alert.refresh_from_db()
+ assert alert.state == BillingAlertConfiguration.State.SNOOZED
+ assert alert.snoozed_until == snoozed_until
+ assert alert.last_notified_at is None
+
+ def test_stale_delivery_commit_preserves_concurrent_threshold_reset(self) -> None:
+ alert = self._alert()
+ check = prepare_billing_alert_check(
+ alert,
+ source=BillingAlertEvent.Source.SCHEDULED,
+ now=NOW,
+ billing_response=_billing_response(100),
+ )
+ BillingAlertConfiguration.objects.filter(pk=alert.pk).update(
+ threshold_percentage=Decimal("75"),
+ state=BillingAlertConfiguration.State.NOT_FIRING,
+ configuration_revision=alert.configuration_revision + 1,
+ updated_at=NOW,
+ )
+
+ with self.assertRaises(BillingAlertConfigurationChanged):
+ commit_billing_alert_check(check, notification_delivered=True)
+
+ alert.refresh_from_db()
+ assert alert.threshold_percentage == Decimal("75")
+ assert alert.state == BillingAlertConfiguration.State.NOT_FIRING
+ assert alert.last_notified_at is None
+
+ def test_configuration_change_is_fenced_before_notification_production(self) -> None:
+ alert = self._alert()
+ self._destination(alert)
+ dispatch = prepare_billing_alert_dispatch(
+ alert,
+ now=NOW,
+ billing_response=_billing_response(100),
+ )
+ BillingAlertConfiguration.objects.filter(pk=alert.pk).update(
+ configuration_revision=alert.configuration_revision + 1,
+ threshold_percentage=Decimal("75"),
+ )
+
+ with (
+ patch("products.billing_alerts.backend.logic.notifications.produce_alert_internal_event") as produce,
+ self.assertRaises(BillingAlertConfigurationChanged),
+ ):
+ commit_pending_billing_alert_dispatch(dispatch)
+
+ produce.assert_not_called()
+
+ def test_lease_takeover_fences_stale_worker_commit(self) -> None:
+ alert = self._alert()
+ check = prepare_billing_alert_check(
+ alert,
+ source=BillingAlertEvent.Source.SCHEDULED,
+ now=NOW,
+ billing_response=_billing_response(100),
+ )
+ BillingAlertEvaluationClaim.objects.filter(pk=check.claim.pk).update(attempt_count=2)
+
+ with self.assertRaises(BillingAlertEvaluationInProgress):
+ commit_billing_alert_check(check, notification_delivered=True)
+
+ assert BillingAlertEvent.objects.filter(claim__alert=alert).exists() is False
+
+ def test_retry_reuses_delivery_uuid_and_preserves_attempt_history(self) -> None:
+ alert = self._alert()
+ self._destination(alert)
+
+ with (
+ patch(
+ "products.billing_alerts.backend.logic.notifications.produce_alert_internal_event",
+ return_value=MagicMock(),
+ ) as produce,
+ patch("products.billing_alerts.backend.logic.notifications.flush_alert_internal_events"),
+ patch(
+ "products.billing_alerts.backend.logic.notifications.alert_internal_event_delivered",
+ side_effect=[False, True],
+ ),
+ ):
+ first_event, first_dispatched = evaluate_and_dispatch_billing_alert(
+ alert,
+ now=NOW,
+ billing_response=_billing_response(100),
+ )
+ with self.assertRaises(BillingAlertEvaluationInProgress):
+ evaluate_and_dispatch_billing_alert(
+ alert,
+ now=NOW.replace(minute=10),
+ billing_response=_billing_response(100),
+ )
+ second_event, second_dispatched = evaluate_and_dispatch_billing_alert(
+ alert,
+ now=NOW.replace(minute=16),
+ billing_response=_billing_response(100),
+ )
+
+ claim = BillingAlertEvaluationClaim.objects.get(alert=alert)
+ assert first_dispatched == 0
+ assert second_dispatched == 1
+ assert first_event.attempt_number == 1
+ assert second_event.attempt_number == 2
+ assert BillingAlertEvent.objects.filter(claim=claim).count() == 2
+ assert [call.kwargs["uuid"] for call in produce.call_args_list] == [
+ str(claim.delivery_uuid),
+ str(claim.delivery_uuid),
+ ]
+
+ def test_incomplete_destination_group_is_not_dispatched(self) -> None:
+ alert = self._alert()
+ HogFunction.objects.create(
+ team_id=alert.execution_team_id,
+ name="Incomplete billing destination",
+ type="internal_destination",
+ enabled=True,
+ hog="",
+ template_id="template-slack",
+ filters={
+ "events": [{"id": EVENT_KIND_CONFIG["firing"].event_id, "type": "events"}],
+ "properties": [{"key": "alert_id", "value": str(alert.id), "type": "event"}],
+ },
+ )
+
+ with patch("products.billing_alerts.backend.logic.notifications.produce_alert_internal_event") as produce:
+ event, dispatched = evaluate_and_dispatch_billing_alert(
+ alert,
+ now=NOW,
+ billing_response=_billing_response(100),
+ )
+
+ assert dispatched == 0
+ assert event.notification_sent_at is None
+ produce.assert_not_called()
diff --git a/products/billing_alerts/backend/test/test_state_machine.py b/products/billing_alerts/backend/test/test_state_machine.py
new file mode 100644
index 000000000000..ef1bf1b98f59
--- /dev/null
+++ b/products/billing_alerts/backend/test/test_state_machine.py
@@ -0,0 +1,154 @@
+from datetime import UTC, date, datetime, timedelta
+from decimal import Decimal
+from uuid import UUID
+
+from products.alerts.backend.state_machine import AlertSnapshot, AlertState, NotificationAction
+from products.billing_alerts.backend.logic.evaluator import BillingAlertEvaluation
+from products.billing_alerts.backend.logic.state_machine import (
+ apply_outcome,
+ evaluate_alert_check,
+ evaluate_alert_failure,
+ next_billing_alert_check_at,
+)
+from products.billing_alerts.backend.models import BillingAlertConfiguration
+
+NOW = datetime(2026, 6, 23, 12, 30, tzinfo=UTC)
+
+
+def _snapshot(
+ *,
+ state: AlertState = AlertState.NOT_FIRING,
+ cooldown: timedelta = timedelta(hours=24),
+ last_notified_at: datetime | None = None,
+ snoozed_until: datetime | None = None,
+ consecutive_failures: int = 0,
+) -> AlertSnapshot:
+ return AlertSnapshot(
+ state=state,
+ cooldown=cooldown,
+ last_notified_at=last_notified_at,
+ snooze_until=snoozed_until,
+ consecutive_failures=consecutive_failures,
+ )
+
+
+def _evaluation(*, breached: bool, inconclusive: bool = False) -> BillingAlertEvaluation:
+ return BillingAlertEvaluation(
+ evaluation_date=date(2026, 6, 22),
+ period_start=datetime(2026, 6, 22, tzinfo=UTC),
+ period_end=datetime(2026, 6, 23, tzinfo=UTC),
+ current_value=Decimal("100"),
+ baseline_value=Decimal("60"),
+ absolute_delta=Decimal("40"),
+ relative_delta_percentage=Decimal("66.67"),
+ threshold_breached=breached,
+ reason="test",
+ payload={},
+ is_inconclusive=inconclusive,
+ )
+
+
+def test_failure_preserves_firing_state_and_counts_transient_errors() -> None:
+ outcome = evaluate_alert_failure(
+ _snapshot(state=AlertState.FIRING),
+ error_message="billing unavailable",
+ is_transient_error=True,
+ )
+
+ assert outcome.new_state == AlertState.FIRING
+ assert outcome.notification == NotificationAction.ERROR
+ assert outcome.consecutive_failures == 1
+
+
+def test_transient_failure_with_attempts_remaining_does_not_advance_the_counter() -> None:
+ # The retry backoff reaches the fifth attempt roughly four hours in, so counting every retry
+ # of one evaluation date would let a single upstream outage disable the alert the same day.
+ outcome = evaluate_alert_failure(
+ _snapshot(state=AlertState.FIRING, consecutive_failures=4),
+ error_message="billing unavailable",
+ is_transient_error=True,
+ attempts_remaining=True,
+ )
+
+ assert outcome.consecutive_failures == 4
+ assert outcome.new_state == AlertState.FIRING
+ assert outcome.disable is False
+ # The attempt still reports as an error, so the retry stays visible to the user.
+ assert outcome.notification == NotificationAction.ERROR
+
+
+def test_fifth_failure_breaks_and_disables_alert_through_adapter() -> None:
+ outcome = evaluate_alert_failure(
+ _snapshot(state=AlertState.FIRING, consecutive_failures=4),
+ error_message="invalid billing configuration",
+ is_transient_error=False,
+ )
+ alert = BillingAlertConfiguration(state=BillingAlertConfiguration.State.FIRING, enabled=True)
+
+ update_fields = apply_outcome(alert, outcome)
+
+ assert outcome.notification == NotificationAction.BROKEN
+ assert alert.state == BillingAlertConfiguration.State.BROKEN
+ assert alert.consecutive_failures == 5
+ assert alert.enabled is False
+ assert "enabled" in update_fields
+
+
+def test_cooldown_only_gates_repeated_firing() -> None:
+ last_notified_at = NOW - timedelta(hours=1)
+
+ initial = evaluate_alert_check(
+ _snapshot(last_notified_at=last_notified_at),
+ _evaluation(breached=True),
+ NOW,
+ )
+ repeated = evaluate_alert_check(
+ _snapshot(state=AlertState.FIRING, last_notified_at=last_notified_at),
+ _evaluation(breached=True),
+ NOW,
+ )
+ resolved = evaluate_alert_check(
+ _snapshot(state=AlertState.FIRING, last_notified_at=last_notified_at),
+ _evaluation(breached=False),
+ NOW,
+ )
+
+ assert initial.notification == NotificationAction.FIRE
+ assert repeated.notification == NotificationAction.NONE
+ assert resolved.notification == NotificationAction.RESOLVE
+
+
+def test_clear_check_resolves_and_ends_snooze() -> None:
+ snoozed_until = NOW + timedelta(hours=1)
+ outcome = evaluate_alert_check(
+ _snapshot(state=AlertState.SNOOZED, snoozed_until=snoozed_until),
+ _evaluation(breached=False),
+ NOW,
+ )
+ alert = BillingAlertConfiguration(
+ state=BillingAlertConfiguration.State.SNOOZED,
+ snoozed_until=snoozed_until,
+ )
+
+ apply_outcome(alert, outcome)
+
+ assert outcome.notification == NotificationAction.RESOLVE
+ assert alert.state == BillingAlertConfiguration.State.NOT_FIRING
+ assert alert.snoozed_until is None
+
+
+def test_next_daily_check_waits_for_the_data_delay_boundary() -> None:
+ alert = BillingAlertConfiguration(
+ id=UUID(int=3),
+ evaluation_delay_hours=6,
+ )
+
+ next_check_at = next_billing_alert_check_at(alert, NOW)
+
+ assert next_check_at == datetime(2026, 6, 24, 9, 0, tzinfo=UTC)
+
+
+def test_next_daily_check_uses_today_after_the_data_delay_boundary_when_due() -> None:
+ alert = BillingAlertConfiguration(id=UUID(int=3), evaluation_delay_hours=18)
+
+ assert next_billing_alert_check_at(alert, NOW) == datetime(2026, 6, 23, 21, 0, tzinfo=UTC)
diff --git a/products/billing_alerts/backend/test/test_team_lifecycle.py b/products/billing_alerts/backend/test/test_team_lifecycle.py
new file mode 100644
index 000000000000..42f91da41293
--- /dev/null
+++ b/products/billing_alerts/backend/test/test_team_lifecycle.py
@@ -0,0 +1,105 @@
+from decimal import Decimal
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from posthog.models.team.team import Team
+
+from products.alerts.backend.destinations import (
+ soft_delete_alert_destinations_for_alerts as shared_soft_delete_destinations,
+)
+from products.billing_alerts.backend.alert_destinations import BILLING_ALERT_EVENT_IDS, EVENT_KIND_CONFIG
+from products.billing_alerts.backend.models import (
+ BillingAlertConfiguration,
+ BillingAlertEvaluationClaim,
+ BillingAlertEvent,
+)
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+
+
+class TestBillingAlertTeamLifecycle(BaseTest):
+ def test_deleting_execution_team_rehomes_and_disables_alert(self) -> None:
+ original_team_id = self.team.id
+ replacement_team = Team.objects.create(organization=self.organization, name="Replacement project")
+ alert = BillingAlertConfiguration.objects.create(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ name="Daily spend spike",
+ enabled=True,
+ state=BillingAlertConfiguration.State.FIRING,
+ metric=BillingAlertConfiguration.Metric.SPEND,
+ threshold_type=BillingAlertConfiguration.ThresholdType.RELATIVE_INCREASE,
+ threshold_percentage=Decimal("50"),
+ )
+ claim = BillingAlertEvaluationClaim.objects.create(
+ alert=alert,
+ evaluation_date=alert.created_at.date(),
+ configuration_revision=alert.configuration_revision,
+ attempt_count=1,
+ )
+ event = BillingAlertEvent.objects.create(
+ claim=claim,
+ team_id=self.team.id,
+ kind=BillingAlertEvent.Kind.FIRING,
+ source=BillingAlertEvent.Source.SCHEDULED,
+ attempt_number=1,
+ metric=BillingAlertConfiguration.Metric.SPEND,
+ state_before=BillingAlertConfiguration.State.NOT_FIRING,
+ state_after=BillingAlertConfiguration.State.FIRING,
+ reason="Threshold breached",
+ )
+ destination = HogFunction.objects.create(
+ team_id=self.team.id,
+ name="Billing alert Slack destination",
+ type="internal_destination",
+ enabled=True,
+ hog="",
+ template_id="template-slack",
+ filters={
+ "events": [{"id": EVENT_KIND_CONFIG["firing"].event_id, "type": "events"}],
+ "properties": [
+ {
+ "key": "alert_id",
+ "value": str(alert.id),
+ "operator": "exact",
+ "type": "event",
+ }
+ ],
+ },
+ )
+
+ with patch(
+ "products.alerts.backend.destinations.soft_delete_alert_destinations_for_alerts",
+ wraps=shared_soft_delete_destinations,
+ ) as soft_delete_destinations:
+ self.team.delete()
+
+ alert.refresh_from_db()
+ event.refresh_from_db()
+ assert alert.team_id == replacement_team.id
+ assert alert.enabled is False
+ assert alert.state == BillingAlertConfiguration.State.NOT_FIRING
+ assert event.alert_id == alert.id
+ soft_delete_destinations.assert_called_once_with(
+ team_id=original_team_id,
+ alert_ids=[str(alert.id)],
+ allowed_event_ids=BILLING_ALERT_EVENT_IDS,
+ )
+ assert HogFunction.objects.filter(id=destination.id).exists() is False
+
+ def test_deleting_last_team_preserves_disabled_alert_history(self) -> None:
+ alert = BillingAlertConfiguration.objects.create(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ name="Daily spend spike",
+ metric=BillingAlertConfiguration.Metric.SPEND,
+ threshold_type=BillingAlertConfiguration.ThresholdType.RELATIVE_INCREASE,
+ threshold_percentage=Decimal("50"),
+ )
+
+ self.team.delete()
+
+ alert.refresh_from_db()
+ assert alert.team_id is None
+ assert alert.enabled is False
+ assert alert.state == BillingAlertConfiguration.State.NOT_FIRING
diff --git a/products/billing_alerts/frontend/generated/api.schemas.ts b/products/billing_alerts/frontend/generated/api.schemas.ts
new file mode 100644
index 000000000000..8462995242e9
--- /dev/null
+++ b/products/billing_alerts/frontend/generated/api.schemas.ts
@@ -0,0 +1,560 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+/**
+ * * `spend` - Spend
+ * * `projected_spend` - Projected spend
+ */
+export type BillingAlertMetricEnumApi = (typeof BillingAlertMetricEnumApi)[keyof typeof BillingAlertMetricEnumApi]
+
+export const BillingAlertMetricEnumApi = {
+ Spend: 'spend',
+ ProjectedSpend: 'projected_spend',
+} as const
+
+/**
+ * * `USD` - USD
+ */
+export type CurrencyEnumApi = (typeof CurrencyEnumApi)[keyof typeof CurrencyEnumApi]
+
+export const CurrencyEnumApi = {
+ Usd: 'USD',
+} as const
+
+/**
+ * * `relative_increase` - Relative increase
+ * * `absolute_value` - Absolute value
+ * * `absolute_increase` - Absolute increase
+ */
+export type ThresholdTypeEnumApi = (typeof ThresholdTypeEnumApi)[keyof typeof ThresholdTypeEnumApi]
+
+export const ThresholdTypeEnumApi = {
+ RelativeIncrease: 'relative_increase',
+ AbsoluteValue: 'absolute_value',
+ AbsoluteIncrease: 'absolute_increase',
+} as const
+
+/**
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken
+ */
+export type BillingAlertStateEnumApi = (typeof BillingAlertStateEnumApi)[keyof typeof BillingAlertStateEnumApi]
+
+export const BillingAlertStateEnumApi = {
+ NotFiring: 'not_firing',
+ Firing: 'firing',
+ Errored: 'errored',
+ Snoozed: 'snoozed',
+ Broken: 'broken',
+} as const
+
+/**
+ * * `slack` - slack
+ * * `webhook` - webhook
+ * * `teams` - teams
+ */
+export type NotificationDestinationTypeEnumApi =
+ (typeof NotificationDestinationTypeEnumApi)[keyof typeof NotificationDestinationTypeEnumApi]
+
+export const NotificationDestinationTypeEnumApi = {
+ Slack: 'slack',
+ Webhook: 'webhook',
+ Teams: 'teams',
+} as const
+
+export interface BillingAlertDestinationSummaryApi {
+ type: NotificationDestinationTypeEnumApi
+ hog_function_ids: string[]
+}
+
+export interface BillingAlertDestinationCreateDataApi {
+ /** Destination type.
+ *
+ * * `slack` - slack
+ * * `webhook` - webhook
+ * * `teams` - teams */
+ type: NotificationDestinationTypeEnumApi
+ /** Slack integration ID in the alert execution project. */
+ slack_workspace_id?: number
+ /** Slack channel ID for alert delivery. */
+ slack_channel_id?: string
+ /** Optional Slack channel name shown in the UI. */
+ slack_channel_name?: string
+ /** HTTPS webhook URL for webhook or Microsoft Teams delivery. */
+ webhook_url?: string
+}
+
+export interface BillingAlertDestinationChangesApi {
+ /**
+ * @items.minItems 4
+ * @items.maxItems 4
+ */
+ delete?: string[][]
+ create?: BillingAlertDestinationCreateDataApi[]
+}
+
+export interface BillingAlertConfigurationApi {
+ /** Unique identifier for this billing alert. */
+ readonly id: string
+ /** Organization this billing alert belongs to. */
+ readonly organization_id: string
+ /**
+ * Team used as the execution context for internal notification destinations.
+ * @nullable
+ */
+ readonly execution_team_id: number | null
+ /**
+ * User ID that created this alert.
+ * @nullable
+ */
+ readonly created_by_id: number | null
+ /**
+ * User ID that last updated this alert.
+ * @nullable
+ */
+ readonly updated_by_id: number | null
+ /**
+ * Display name for this billing alert.
+ * @maxLength 160
+ */
+ name: string
+ /** Optional internal description. */
+ description?: string
+ /** Whether scheduled checks should evaluate this alert. */
+ enabled?: boolean
+ /** Billing-period total to evaluate: current spend so far, or projected period-end spend.
+ *
+ * * `spend` - Spend
+ * * `projected_spend` - Projected spend */
+ metric?: BillingAlertMetricEnumApi
+ /** Server-controlled currency for spend values.
+ *
+ * * `USD` - USD */
+ readonly currency: CurrencyEnumApi
+ /** Revision incremented whenever evaluation behavior changes. */
+ readonly configuration_revision: number
+ /** Threshold rule type. The first version supports absolute value only.
+ *
+ * * `relative_increase` - Relative increase
+ * * `absolute_value` - Absolute value
+ * * `absolute_increase` - Absolute increase */
+ threshold_type?: ThresholdTypeEnumApi
+ /**
+ * Reserved for future increase-over-baseline rules. Not used by absolute value alerts.
+ * @nullable
+ * @pattern ^-?\d{0,6}(?:\.\d{0,2})?$
+ */
+ threshold_percentage?: string | null
+ /**
+ * Absolute value or absolute increase that triggers absolute threshold alerts.
+ * @nullable
+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$
+ */
+ threshold_value?: string | null
+ /**
+ * Minimum current value before the alert can fire.
+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$
+ */
+ minimum_value?: string
+ /**
+ * Reserved for future increase-over-baseline rules. Not used by absolute value alerts.
+ * @minimum 1
+ * @maximum 90
+ */
+ baseline_window_days?: number
+ /**
+ * Hours after a UTC billing date ends before it becomes eligible for evaluation.
+ * @minimum 0
+ * @maximum 72
+ */
+ evaluation_delay_hours?: number
+ /** Current lifecycle state of this alert.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state: BillingAlertStateEnumApi
+ /**
+ * Minimum hours between repeated firing notifications.
+ * @minimum 0
+ * @maximum 720
+ */
+ cooldown_hours?: number
+ /**
+ * ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume.
+ * @nullable
+ */
+ snoozed_until?: string | null
+ /**
+ * When the next scheduled evaluation is due.
+ * @nullable
+ */
+ readonly next_check_at: string | null
+ /**
+ * When this alert was last evaluated.
+ * @nullable
+ */
+ readonly last_checked_at: string | null
+ /**
+ * When notifications were last delivered for this alert.
+ * @nullable
+ */
+ readonly last_notified_at: string | null
+ /** Number of consecutive failed evaluations. */
+ readonly consecutive_failures: number
+ /** Notification destination groups configured for this alert, including their shared HogFunctions. */
+ readonly destinations: readonly BillingAlertDestinationSummaryApi[]
+ /** Destination groups to create or delete in the same transaction as this configuration write. */
+ destination_changes?: BillingAlertDestinationChangesApi
+ /** When this alert was created. */
+ readonly created_at: string
+ /**
+ * When this alert was last updated.
+ * @nullable
+ */
+ readonly updated_at: string | null
+}
+
+export interface PaginatedBillingAlertConfigurationListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: BillingAlertConfigurationApi[]
+}
+
+export interface PatchedBillingAlertConfigurationApi {
+ /** Unique identifier for this billing alert. */
+ readonly id?: string
+ /** Organization this billing alert belongs to. */
+ readonly organization_id?: string
+ /**
+ * Team used as the execution context for internal notification destinations.
+ * @nullable
+ */
+ readonly execution_team_id?: number | null
+ /**
+ * User ID that created this alert.
+ * @nullable
+ */
+ readonly created_by_id?: number | null
+ /**
+ * User ID that last updated this alert.
+ * @nullable
+ */
+ readonly updated_by_id?: number | null
+ /**
+ * Display name for this billing alert.
+ * @maxLength 160
+ */
+ name?: string
+ /** Optional internal description. */
+ description?: string
+ /** Whether scheduled checks should evaluate this alert. */
+ enabled?: boolean
+ /** Billing-period total to evaluate: current spend so far, or projected period-end spend.
+ *
+ * * `spend` - Spend
+ * * `projected_spend` - Projected spend */
+ metric?: BillingAlertMetricEnumApi
+ /** Server-controlled currency for spend values.
+ *
+ * * `USD` - USD */
+ readonly currency?: CurrencyEnumApi
+ /** Revision incremented whenever evaluation behavior changes. */
+ readonly configuration_revision?: number
+ /** Threshold rule type. The first version supports absolute value only.
+ *
+ * * `relative_increase` - Relative increase
+ * * `absolute_value` - Absolute value
+ * * `absolute_increase` - Absolute increase */
+ threshold_type?: ThresholdTypeEnumApi
+ /**
+ * Reserved for future increase-over-baseline rules. Not used by absolute value alerts.
+ * @nullable
+ * @pattern ^-?\d{0,6}(?:\.\d{0,2})?$
+ */
+ threshold_percentage?: string | null
+ /**
+ * Absolute value or absolute increase that triggers absolute threshold alerts.
+ * @nullable
+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$
+ */
+ threshold_value?: string | null
+ /**
+ * Minimum current value before the alert can fire.
+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$
+ */
+ minimum_value?: string
+ /**
+ * Reserved for future increase-over-baseline rules. Not used by absolute value alerts.
+ * @minimum 1
+ * @maximum 90
+ */
+ baseline_window_days?: number
+ /**
+ * Hours after a UTC billing date ends before it becomes eligible for evaluation.
+ * @minimum 0
+ * @maximum 72
+ */
+ evaluation_delay_hours?: number
+ /** Current lifecycle state of this alert.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state?: BillingAlertStateEnumApi
+ /**
+ * Minimum hours between repeated firing notifications.
+ * @minimum 0
+ * @maximum 720
+ */
+ cooldown_hours?: number
+ /**
+ * ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume.
+ * @nullable
+ */
+ snoozed_until?: string | null
+ /**
+ * When the next scheduled evaluation is due.
+ * @nullable
+ */
+ readonly next_check_at?: string | null
+ /**
+ * When this alert was last evaluated.
+ * @nullable
+ */
+ readonly last_checked_at?: string | null
+ /**
+ * When notifications were last delivered for this alert.
+ * @nullable
+ */
+ readonly last_notified_at?: string | null
+ /** Number of consecutive failed evaluations. */
+ readonly consecutive_failures?: number
+ /** Notification destination groups configured for this alert, including their shared HogFunctions. */
+ readonly destinations?: readonly BillingAlertDestinationSummaryApi[]
+ /** Destination groups to create or delete in the same transaction as this configuration write. */
+ destination_changes?: BillingAlertDestinationChangesApi
+ /** When this alert was created. */
+ readonly created_at?: string
+ /**
+ * When this alert was last updated.
+ * @nullable
+ */
+ readonly updated_at?: string | null
+}
+
+/**
+ * * `check` - Check
+ * * `firing` - Firing
+ * * `resolved` - Resolved
+ * * `errored` - Errored
+ * * `broken_config` - Broken config
+ */
+export type BillingAlertEventKindEnumApi =
+ (typeof BillingAlertEventKindEnumApi)[keyof typeof BillingAlertEventKindEnumApi]
+
+export const BillingAlertEventKindEnumApi = {
+ Check: 'check',
+ Firing: 'firing',
+ Resolved: 'resolved',
+ Errored: 'errored',
+ BrokenConfig: 'broken_config',
+} as const
+
+/**
+ * * `scheduled` - Scheduled
+ * * `manual` - Manual
+ */
+export type BillingAlertEventSourceEnumApi =
+ (typeof BillingAlertEventSourceEnumApi)[keyof typeof BillingAlertEventSourceEnumApi]
+
+export const BillingAlertEventSourceEnumApi = {
+ Scheduled: 'scheduled',
+ Manual: 'manual',
+} as const
+
+export interface BillingAlertEventApi {
+ /** Unique identifier for this billing alert event. */
+ readonly id: string
+ /** Event kind for a check, state transition, or delivery-worthy alert event.
+ *
+ * * `check` - Check
+ * * `firing` - Firing
+ * * `resolved` - Resolved
+ * * `errored` - Errored
+ * * `broken_config` - Broken config */
+ readonly kind: BillingAlertEventKindEnumApi
+ /** Whether this evaluation was scheduled or manually requested.
+ *
+ * * `scheduled` - Scheduled
+ * * `manual` - Manual */
+ readonly source: BillingAlertEventSourceEnumApi
+ /** Attempt number for this billing date and configuration revision. */
+ readonly attempt_number: number
+ /** When this event was recorded. */
+ readonly created_at: string
+ /**
+ * Billing data date evaluated by this event.
+ * @nullable
+ */
+ readonly evaluation_date: string | null
+ /** Configuration revision used for this evaluation. */
+ readonly configuration_revision: number
+ /**
+ * Start of the evaluated billing period.
+ * @nullable
+ */
+ readonly period_start: string | null
+ /**
+ * End of the evaluated billing period.
+ * @nullable
+ */
+ readonly period_end: string | null
+ /** Billing metric evaluated by this event.
+ *
+ * * `spend` - Spend
+ * * `projected_spend` - Projected spend */
+ readonly metric: BillingAlertMetricEnumApi
+ /**
+ * Metric value for the evaluated billing date.
+ * @nullable
+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$
+ */
+ readonly current_value: string | null
+ /**
+ * Average metric value across the baseline window.
+ * @nullable
+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$
+ */
+ readonly baseline_value: string | null
+ /**
+ * Current value minus the baseline value.
+ * @nullable
+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$
+ */
+ readonly absolute_delta: string | null
+ /**
+ * Percentage change against the baseline value.
+ * @nullable
+ * @pattern ^-?\d{0,22}(?:\.\d{0,6})?$
+ */
+ readonly relative_delta_percentage: string | null
+ /** Whether the evaluated value breached the configured threshold. */
+ readonly threshold_breached: boolean
+ /** Alert state before this event was applied.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state_before: BillingAlertStateEnumApi | null
+ /** Alert state after this event was applied.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state_after: BillingAlertStateEnumApi | null
+ /**
+ * When notifications for this event were delivered.
+ * @nullable
+ */
+ readonly notification_sent_at: string | null
+ /** Notification targets recorded for this event. */
+ readonly targets_notified: unknown
+ /**
+ * Milliseconds spent fetching billing data for this evaluation.
+ * @nullable
+ */
+ readonly query_duration_ms: number | null
+ /**
+ * Exception class name recorded when the evaluation failed.
+ * @nullable
+ */
+ readonly error_code: string | null
+ /**
+ * Failure description recorded when the evaluation failed.
+ * @nullable
+ */
+ readonly error_message: string | null
+ /** Human-readable explanation of the evaluation outcome. */
+ readonly reason: string
+}
+
+export interface BillingAlertCheckNowResponseApi {
+ /** Evaluation event recorded by the manual check, or null for a paused preview. */
+ event?: BillingAlertEventApi | null
+ /** Number of destination HogFunctions queued. */
+ dispatched_destinations: number
+ /** True when the alert is paused: it was evaluated but no notifications were sent. */
+ preview: boolean
+ /** Whether the evaluated billing-period total breached the configured threshold. */
+ threshold_breached: boolean
+ /**
+ * Evaluated billing-period total, or null when billing data was not available.
+ * @nullable
+ */
+ current_value?: string | null
+}
+
+export interface BillingAlertDestinationResponseApi {
+ hog_function_ids: string[]
+}
+
+export interface BillingAlertDeleteDestinationApi {
+ /**
+ * HogFunction IDs to delete as one atomic destination group.
+ * @minItems 4
+ * @maxItems 4
+ */
+ hog_function_ids: string[]
+}
+
+export interface PaginatedBillingAlertEventListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: BillingAlertEventApi[]
+}
+
+export type BillingAlertsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
+export type BillingAlertsEventsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
diff --git a/products/billing_alerts/frontend/generated/api.ts b/products/billing_alerts/frontend/generated/api.ts
new file mode 100644
index 000000000000..6e95a5594b52
--- /dev/null
+++ b/products/billing_alerts/frontend/generated/api.ts
@@ -0,0 +1,244 @@
+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import type {
+ BillingAlertCheckNowResponseApi,
+ BillingAlertConfigurationApi,
+ BillingAlertDeleteDestinationApi,
+ BillingAlertDestinationCreateDataApi,
+ BillingAlertDestinationResponseApi,
+ BillingAlertsEventsListParams,
+ BillingAlertsListParams,
+ PaginatedBillingAlertConfigurationListApi,
+ PaginatedBillingAlertEventListApi,
+ PatchedBillingAlertConfigurationApi,
+} from './api.schemas'
+
+// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B
+
+type WritableKeys<T> = {
+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>
+}[keyof T]
+
+type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never
+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never
+
+type Writable<T> = Pick<T, WritableKeys<T>>
+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
+ ? {
+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]
+ }
+ : DistributeReadOnlyOverUnions<T>
+
+export const getBillingAlertsListUrl = (organizationId: string, params?: BillingAlertsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/organizations/${organizationId}/billing/alerts/?${stringifiedParams}`
+ : `/api/organizations/${organizationId}/billing/alerts/`
+}
+
+export const billingAlertsList = async (
+ organizationId: string,
+ params?: BillingAlertsListParams,
+ options?: RequestInit
+): Promise<PaginatedBillingAlertConfigurationListApi> => {
+ return apiMutator<PaginatedBillingAlertConfigurationListApi>(getBillingAlertsListUrl(organizationId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getBillingAlertsCreateUrl = (organizationId: string) => {
+ return `/api/organizations/${organizationId}/billing/alerts/`
+}
+
+export const billingAlertsCreate = async (
+ organizationId: string,
+ billingAlertConfigurationApi: NonReadonly<BillingAlertConfigurationApi>,
+ options?: RequestInit
+): Promise<BillingAlertConfigurationApi> => {
+ return apiMutator<BillingAlertConfigurationApi>(getBillingAlertsCreateUrl(organizationId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(billingAlertConfigurationApi),
+ })
+}
+
+export const getBillingAlertsRetrieveUrl = (organizationId: string, id: string) => {
+ return `/api/organizations/${organizationId}/billing/alerts/${id}/`
+}
+
+export const billingAlertsRetrieve = async (
+ organizationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<BillingAlertConfigurationApi> => {
+ return apiMutator<BillingAlertConfigurationApi>(getBillingAlertsRetrieveUrl(organizationId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getBillingAlertsUpdateUrl = (organizationId: string, id: string) => {
+ return `/api/organizations/${organizationId}/billing/alerts/${id}/`
+}
+
+export const billingAlertsUpdate = async (
+ organizationId: string,
+ id: string,
+ billingAlertConfigurationApi: NonReadonly<BillingAlertConfigurationApi>,
+ options?: RequestInit
+): Promise<BillingAlertConfigurationApi> => {
+ return apiMutator<BillingAlertConfigurationApi>(getBillingAlertsUpdateUrl(organizationId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(billingAlertConfigurationApi),
+ })
+}
+
+export const getBillingAlertsPartialUpdateUrl = (organizationId: string, id: string) => {
+ return `/api/organizations/${organizationId}/billing/alerts/${id}/`
+}
+
+export const billingAlertsPartialUpdate = async (
+ organizationId: string,
+ id: string,
+ patchedBillingAlertConfigurationApi?: NonReadonly<PatchedBillingAlertConfigurationApi>,
+ options?: RequestInit
+): Promise<BillingAlertConfigurationApi> => {
+ return apiMutator<BillingAlertConfigurationApi>(getBillingAlertsPartialUpdateUrl(organizationId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedBillingAlertConfigurationApi),
+ })
+}
+
+export const getBillingAlertsDestroyUrl = (organizationId: string, id: string) => {
+ return `/api/organizations/${organizationId}/billing/alerts/${id}/`
+}
+
+export const billingAlertsDestroy = async (
+ organizationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getBillingAlertsDestroyUrl(organizationId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getBillingAlertsCheckNowCreateUrl = (organizationId: string, id: string) => {
+ return `/api/organizations/${organizationId}/billing/alerts/${id}/check_now/`
+}
+
+/**
+ * Evaluate this billing alert immediately against real billing spend data. An enabled alert can send notifications when the evaluation records a dispatchable event. A paused alert is evaluated as a preview only: it reports the current spend and would-be outcome without sending notifications or recording an evaluation.
+ */
+export const billingAlertsCheckNowCreate = async (
+ organizationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<BillingAlertCheckNowResponseApi> => {
+ return apiMutator<BillingAlertCheckNowResponseApi>(getBillingAlertsCheckNowCreateUrl(organizationId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getBillingAlertsDestinationsCreateUrl = (organizationId: string, id: string) => {
+ return `/api/organizations/${organizationId}/billing/alerts/${id}/destinations/`
+}
+
+/**
+ * Create a notification destination for this alert. One HogFunction is created per alert event kind.
+ */
+export const billingAlertsDestinationsCreate = async (
+ organizationId: string,
+ id: string,
+ billingAlertDestinationCreateDataApi: BillingAlertDestinationCreateDataApi,
+ options?: RequestInit
+): Promise<BillingAlertDestinationResponseApi> => {
+ return apiMutator<BillingAlertDestinationResponseApi>(getBillingAlertsDestinationsCreateUrl(organizationId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(billingAlertDestinationCreateDataApi),
+ })
+}
+
+export const getBillingAlertsDestinationsDeleteCreateUrl = (organizationId: string, id: string) => {
+ return `/api/organizations/${organizationId}/billing/alerts/${id}/destinations/delete/`
+}
+
+/**
+ * Delete a notification destination by deleting its HogFunction group atomically.
+ */
+export const billingAlertsDestinationsDeleteCreate = async (
+ organizationId: string,
+ id: string,
+ billingAlertDeleteDestinationApi: BillingAlertDeleteDestinationApi,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getBillingAlertsDestinationsDeleteCreateUrl(organizationId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(billingAlertDeleteDestinationApi),
+ })
+}
+
+export const getBillingAlertsEventsListUrl = (
+ organizationId: string,
+ id: string,
+ params?: BillingAlertsEventsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/organizations/${organizationId}/billing/alerts/${id}/events/?${stringifiedParams}`
+ : `/api/organizations/${organizationId}/billing/alerts/${id}/events/`
+}
+
+/**
+ * List evaluation and notification events for this billing alert, newest first.
+ */
+export const billingAlertsEventsList = async (
+ organizationId: string,
+ id: string,
+ params?: BillingAlertsEventsListParams,
+ options?: RequestInit
+): Promise<PaginatedBillingAlertEventListApi> => {
+ return apiMutator<PaginatedBillingAlertEventListApi>(getBillingAlertsEventsListUrl(organizationId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/products/billing_alerts/frontend/generated/api.zod.ts b/products/billing_alerts/frontend/generated/api.zod.ts
new file mode 100644
index 000000000000..2d5445e92614
--- /dev/null
+++ b/products/billing_alerts/frontend/generated/api.zod.ts
@@ -0,0 +1,372 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+export const billingAlertsCreateBodyNameMax = 160
+
+export const billingAlertsCreateBodyThresholdPercentageRegExp = new RegExp('^-?\\d{0,6}(?:\\.\\d{0,2})?$')
+export const billingAlertsCreateBodyThresholdValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')
+export const billingAlertsCreateBodyMinimumValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')
+export const billingAlertsCreateBodyBaselineWindowDaysMax = 90
+
+export const billingAlertsCreateBodyEvaluationDelayHoursMin = 0
+export const billingAlertsCreateBodyEvaluationDelayHoursMax = 72
+
+export const billingAlertsCreateBodyCooldownHoursMin = 0
+export const billingAlertsCreateBodyCooldownHoursMax = 720
+
+export const billingAlertsCreateBodyDestinationChangesOneDeleteItemMin = 4
+export const billingAlertsCreateBodyDestinationChangesOneDeleteItemMax = 4
+
+export const BillingAlertsCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(billingAlertsCreateBodyNameMax).describe('Display name for this billing alert.'),
+ description: zod.string().optional().describe('Optional internal description.'),
+ enabled: zod.boolean().optional().describe('Whether scheduled checks should evaluate this alert.'),
+ metric: zod
+ .enum(['spend', 'projected_spend'])
+ .describe('\* `spend` - Spend\n\* `projected_spend` - Projected spend')
+ .optional()
+ .describe(
+ 'Billing-period total to evaluate: current spend so far, or projected period-end spend.\n\n\* `spend` - Spend\n\* `projected_spend` - Projected spend'
+ ),
+ threshold_type: zod
+ .enum(['relative_increase', 'absolute_value', 'absolute_increase'])
+ .describe(
+ '\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'
+ )
+ .optional()
+ .describe(
+ 'Threshold rule type. The first version supports absolute value only.\n\n\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'
+ ),
+ threshold_percentage: zod
+ .stringFormat('decimal', billingAlertsCreateBodyThresholdPercentageRegExp)
+ .nullish()
+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),
+ threshold_value: zod
+ .stringFormat('decimal', billingAlertsCreateBodyThresholdValueRegExp)
+ .nullish()
+ .describe('Absolute value or absolute increase that triggers absolute threshold alerts.'),
+ minimum_value: zod
+ .stringFormat('decimal', billingAlertsCreateBodyMinimumValueRegExp)
+ .optional()
+ .describe('Minimum current value before the alert can fire.'),
+ baseline_window_days: zod
+ .number()
+ .min(1)
+ .max(billingAlertsCreateBodyBaselineWindowDaysMax)
+ .optional()
+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),
+ evaluation_delay_hours: zod
+ .number()
+ .min(billingAlertsCreateBodyEvaluationDelayHoursMin)
+ .max(billingAlertsCreateBodyEvaluationDelayHoursMax)
+ .optional()
+ .describe('Hours after a UTC billing date ends before it becomes eligible for evaluation.'),
+ cooldown_hours: zod
+ .number()
+ .min(billingAlertsCreateBodyCooldownHoursMin)
+ .max(billingAlertsCreateBodyCooldownHoursMax)
+ .optional()
+ .describe('Minimum hours between repeated firing notifications.'),
+ snoozed_until: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume.'),
+ destination_changes: zod
+ .object({
+ delete: zod
+ .array(
+ zod
+ .array(zod.uuid())
+ .min(billingAlertsCreateBodyDestinationChangesOneDeleteItemMin)
+ .max(billingAlertsCreateBodyDestinationChangesOneDeleteItemMax)
+ )
+ .optional(),
+ create: zod
+ .array(
+ zod.object({
+ type: zod
+ .enum(['slack', 'webhook', 'teams'])
+ .describe('\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams')
+ .describe(
+ 'Destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams'
+ ),
+ slack_workspace_id: zod
+ .number()
+ .optional()
+ .describe('Slack integration ID in the alert execution project.'),
+ slack_channel_id: zod.string().optional().describe('Slack channel ID for alert delivery.'),
+ slack_channel_name: zod
+ .string()
+ .optional()
+ .describe('Optional Slack channel name shown in the UI.'),
+ webhook_url: zod
+ .url()
+ .optional()
+ .describe('HTTPS webhook URL for webhook or Microsoft Teams delivery.'),
+ })
+ )
+ .optional(),
+ })
+ .optional()
+ .describe('Destination groups to create or delete in the same transaction as this configuration write.'),
+})
+
+export const billingAlertsUpdateBodyNameMax = 160
+
+export const billingAlertsUpdateBodyThresholdPercentageRegExp = new RegExp('^-?\\d{0,6}(?:\\.\\d{0,2})?$')
+export const billingAlertsUpdateBodyThresholdValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')
+export const billingAlertsUpdateBodyMinimumValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')
+export const billingAlertsUpdateBodyBaselineWindowDaysMax = 90
+
+export const billingAlertsUpdateBodyEvaluationDelayHoursMin = 0
+export const billingAlertsUpdateBodyEvaluationDelayHoursMax = 72
+
+export const billingAlertsUpdateBodyCooldownHoursMin = 0
+export const billingAlertsUpdateBodyCooldownHoursMax = 720
+
+export const billingAlertsUpdateBodyDestinationChangesOneDeleteItemMin = 4
+export const billingAlertsUpdateBodyDestinationChangesOneDeleteItemMax = 4
+
+export const BillingAlertsUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(billingAlertsUpdateBodyNameMax).describe('Display name for this billing alert.'),
+ description: zod.string().optional().describe('Optional internal description.'),
+ enabled: zod.boolean().optional().describe('Whether scheduled checks should evaluate this alert.'),
+ metric: zod
+ .enum(['spend', 'projected_spend'])
+ .describe('\* `spend` - Spend\n\* `projected_spend` - Projected spend')
+ .optional()
+ .describe(
+ 'Billing-period total to evaluate: current spend so far, or projected period-end spend.\n\n\* `spend` - Spend\n\* `projected_spend` - Projected spend'
+ ),
+ threshold_type: zod
+ .enum(['relative_increase', 'absolute_value', 'absolute_increase'])
+ .describe(
+ '\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'
+ )
+ .optional()
+ .describe(
+ 'Threshold rule type. The first version supports absolute value only.\n\n\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'
+ ),
+ threshold_percentage: zod
+ .stringFormat('decimal', billingAlertsUpdateBodyThresholdPercentageRegExp)
+ .nullish()
+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),
+ threshold_value: zod
+ .stringFormat('decimal', billingAlertsUpdateBodyThresholdValueRegExp)
+ .nullish()
+ .describe('Absolute value or absolute increase that triggers absolute threshold alerts.'),
+ minimum_value: zod
+ .stringFormat('decimal', billingAlertsUpdateBodyMinimumValueRegExp)
+ .optional()
+ .describe('Minimum current value before the alert can fire.'),
+ baseline_window_days: zod
+ .number()
+ .min(1)
+ .max(billingAlertsUpdateBodyBaselineWindowDaysMax)
+ .optional()
+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),
+ evaluation_delay_hours: zod
+ .number()
+ .min(billingAlertsUpdateBodyEvaluationDelayHoursMin)
+ .max(billingAlertsUpdateBodyEvaluationDelayHoursMax)
+ .optional()
+ .describe('Hours after a UTC billing date ends before it becomes eligible for evaluation.'),
+ cooldown_hours: zod
+ .number()
+ .min(billingAlertsUpdateBodyCooldownHoursMin)
+ .max(billingAlertsUpdateBodyCooldownHoursMax)
+ .optional()
+ .describe('Minimum hours between repeated firing notifications.'),
+ snoozed_until: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume.'),
+ destination_changes: zod
+ .object({
+ delete: zod
+ .array(
+ zod
+ .array(zod.uuid())
+ .min(billingAlertsUpdateBodyDestinationChangesOneDeleteItemMin)
+ .max(billingAlertsUpdateBodyDestinationChangesOneDeleteItemMax)
+ )
+ .optional(),
+ create: zod
+ .array(
+ zod.object({
+ type: zod
+ .enum(['slack', 'webhook', 'teams'])
+ .describe('\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams')
+ .describe(
+ 'Destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams'
+ ),
+ slack_workspace_id: zod
+ .number()
+ .optional()
+ .describe('Slack integration ID in the alert execution project.'),
+ slack_channel_id: zod.string().optional().describe('Slack channel ID for alert delivery.'),
+ slack_channel_name: zod
+ .string()
+ .optional()
+ .describe('Optional Slack channel name shown in the UI.'),
+ webhook_url: zod
+ .url()
+ .optional()
+ .describe('HTTPS webhook URL for webhook or Microsoft Teams delivery.'),
+ })
+ )
+ .optional(),
+ })
+ .optional()
+ .describe('Destination groups to create or delete in the same transaction as this configuration write.'),
+})
+
+export const billingAlertsPartialUpdateBodyNameMax = 160
+
+export const billingAlertsPartialUpdateBodyThresholdPercentageRegExp = new RegExp('^-?\\d{0,6}(?:\\.\\d{0,2})?$')
+export const billingAlertsPartialUpdateBodyThresholdValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')
+export const billingAlertsPartialUpdateBodyMinimumValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')
+export const billingAlertsPartialUpdateBodyBaselineWindowDaysMax = 90
+
+export const billingAlertsPartialUpdateBodyEvaluationDelayHoursMin = 0
+export const billingAlertsPartialUpdateBodyEvaluationDelayHoursMax = 72
+
+export const billingAlertsPartialUpdateBodyCooldownHoursMin = 0
+export const billingAlertsPartialUpdateBodyCooldownHoursMax = 720
+
+export const billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMin = 4
+export const billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax = 4
+
+export const BillingAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(billingAlertsPartialUpdateBodyNameMax)
+ .optional()
+ .describe('Display name for this billing alert.'),
+ description: zod.string().optional().describe('Optional internal description.'),
+ enabled: zod.boolean().optional().describe('Whether scheduled checks should evaluate this alert.'),
+ metric: zod
+ .enum(['spend', 'projected_spend'])
+ .describe('\* `spend` - Spend\n\* `projected_spend` - Projected spend')
+ .optional()
+ .describe(
+ 'Billing-period total to evaluate: current spend so far, or projected period-end spend.\n\n\* `spend` - Spend\n\* `projected_spend` - Projected spend'
+ ),
+ threshold_type: zod
+ .enum(['relative_increase', 'absolute_value', 'absolute_increase'])
+ .describe(
+ '\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'
+ )
+ .optional()
+ .describe(
+ 'Threshold rule type. The first version supports absolute value only.\n\n\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'
+ ),
+ threshold_percentage: zod
+ .stringFormat('decimal', billingAlertsPartialUpdateBodyThresholdPercentageRegExp)
+ .nullish()
+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),
+ threshold_value: zod
+ .stringFormat('decimal', billingAlertsPartialUpdateBodyThresholdValueRegExp)
+ .nullish()
+ .describe('Absolute value or absolute increase that triggers absolute threshold alerts.'),
+ minimum_value: zod
+ .stringFormat('decimal', billingAlertsPartialUpdateBodyMinimumValueRegExp)
+ .optional()
+ .describe('Minimum current value before the alert can fire.'),
+ baseline_window_days: zod
+ .number()
+ .min(1)
+ .max(billingAlertsPartialUpdateBodyBaselineWindowDaysMax)
+ .optional()
+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),
+ evaluation_delay_hours: zod
+ .number()
+ .min(billingAlertsPartialUpdateBodyEvaluationDelayHoursMin)
+ .max(billingAlertsPartialUpdateBodyEvaluationDelayHoursMax)
+ .optional()
+ .describe('Hours after a UTC billing date ends before it becomes eligible for evaluation.'),
+ cooldown_hours: zod
+ .number()
+ .min(billingAlertsPartialUpdateBodyCooldownHoursMin)
+ .max(billingAlertsPartialUpdateBodyCooldownHoursMax)
+ .optional()
+ .describe('Minimum hours between repeated firing notifications.'),
+ snoozed_until: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume.'),
+ destination_changes: zod
+ .object({
+ delete: zod
+ .array(
+ zod
+ .array(zod.uuid())
+ .min(billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMin)
+ .max(billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax)
+ )
+ .optional(),
+ create: zod
+ .array(
+ zod.object({
+ type: zod
+ .enum(['slack', 'webhook', 'teams'])
+ .describe('\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams')
+ .describe(
+ 'Destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams'
+ ),
+ slack_workspace_id: zod
+ .number()
+ .optional()
+ .describe('Slack integration ID in the alert execution project.'),
+ slack_channel_id: zod.string().optional().describe('Slack channel ID for alert delivery.'),
+ slack_channel_name: zod
+ .string()
+ .optional()
+ .describe('Optional Slack channel name shown in the UI.'),
+ webhook_url: zod
+ .url()
+ .optional()
+ .describe('HTTPS webhook URL for webhook or Microsoft Teams delivery.'),
+ })
+ )
+ .optional(),
+ })
+ .optional()
+ .describe('Destination groups to create or delete in the same transaction as this configuration write.'),
+})
+
+/**
+ * Create a notification destination for this alert. One HogFunction is created per alert event kind.
+ */
+export const BillingAlertsDestinationsCreateBody = /* @__PURE__ */ zod.object({
+ type: zod
+ .enum(['slack', 'webhook', 'teams'])
+ .describe('\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams')
+ .describe('Destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams'),
+ slack_workspace_id: zod.number().optional().describe('Slack integration ID in the alert execution project.'),
+ slack_channel_id: zod.string().optional().describe('Slack channel ID for alert delivery.'),
+ slack_channel_name: zod.string().optional().describe('Optional Slack channel name shown in the UI.'),
+ webhook_url: zod.url().optional().describe('HTTPS webhook URL for webhook or Microsoft Teams delivery.'),
+})
+
+/**
+ * Delete a notification destination by deleting its HogFunction group atomically.
+ */
+export const billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMin = 4
+export const billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax = 4
+
+export const BillingAlertsDestinationsDeleteCreateBody = /* @__PURE__ */ zod.object({
+ hog_function_ids: zod
+ .array(zod.uuid())
+ .min(billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMin)
+ .max(billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax)
+ .describe('HogFunction IDs to delete as one atomic destination group.'),
+})
diff --git a/products/billing_alerts/mcp/tools.yaml b/products/billing_alerts/mcp/tools.yaml
new file mode 100644
index 000000000000..107dfce76fb1
--- /dev/null
+++ b/products/billing_alerts/mcp/tools.yaml
@@ -0,0 +1,72 @@
+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.
+# The tool list and operation IDs are kept in sync automatically:
+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all
+#
+# To enable a tool, set enabled: true and add required scopes + annotations.
+# All other fields (title, description, enrich_url, etc.) are yours to configure.
+category: Billing alerts
+feature: billing_alerts
+url_prefix: /organization/billing
+ui_apps: {}
+tools:
+ billing-alert-check-now:
+ operation: billing_alerts_check_now_create
+ enabled: false
+ billing-alert-create:
+ operation: billing_alerts_create
+ enabled: true
+ scopes:
+ - organization:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Create billing alert
+ description: >
+ Create a billing-period spend alert in the active organization. The caller must be an organization Admin or
+ Owner. Billing owns the trigger configuration and evaluation; the shared alerting backend handles lifecycle,
+ scheduling, destinations, and delivery. The metric picks the billing-period total to watch: spend (current
+ period total so far) or projected_spend (projected period-end total). The first version supports only the
+ absolute_value threshold rule with threshold_value, in USD. Optional destination_changes can create Slack,
+ Microsoft Teams, or HTTPS webhook destinations atomically with the alert.
+ feature_flag: billing-alerts
+ billing-alert-delete:
+ operation: billing_alerts_destroy
+ enabled: false
+ billing-alert-destination-create:
+ operation: billing_alerts_destinations_create
+ enabled: false
+ billing-alert-destination-delete:
+ operation: billing_alerts_destinations_delete_create
+ enabled: false
+ billing-alert-events-list:
+ operation: billing_alerts_events_list
+ enabled: false
+ billing-alert-get:
+ operation: billing_alerts_retrieve
+ enabled: false
+ billing-alert-replace:
+ operation: billing_alerts_update
+ enabled: false
+ billing-alert-update:
+ operation: billing_alerts_partial_update
+ enabled: true
+ scopes:
+ - organization:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: false
+ title: Update billing alert
+ description: >
+ Partially update a billing alert by ID in the active organization. The caller must be an organization Admin
+ or Owner. Change only the supplied trigger fields, alert copy, enabled state, snooze, or cooldown. The
+ metric picks the billing-period total to watch (spend or projected_spend); the first version supports only
+ the absolute_value threshold rule with threshold_value, in USD. Optional destination_changes applies
+ destination creation or complete-group deletion in the same backend transaction as the configuration update.
+ Repeating a request that creates a destination of the same type is rejected, because an alert allows one
+ destination group per type.
+ feature_flag: billing-alerts
+ billing-alerts-list:
+ operation: billing_alerts_list
+ enabled: false
diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.py
index d3850146c971..d2c615847016 100644
--- a/products/cdp/backend/api/hog_function.py
+++ b/products/cdp/backend/api/hog_function.py
@@ -26,6 +26,7 @@ from posthog.api.log_entries import LogEntryMixin
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
from posthog.api.utils import action, log_activity_from_viewset
+from posthog.cdp.internal_events import MANAGED_ALERT_EVENT_PATTERN, is_managed_alert_internal_event
from posthog.cdp.services.icons import CDPIconsService
from posthog.cdp.site_functions import get_transpiled_function
from posthog.cdp.validation import (
@@ -541,6 +542,24 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):
self.context.get("view") and self.context["view"].action == "create"
)
+ if not self.context.get("allow_managed_alert_destination"):
+ current_filters = self.instance.filters if isinstance(self.instance, HogFunction) else {}
+ proposed_filters = attrs.get("filters", current_filters)
+ current_is_managed = any(
+ is_managed_alert_internal_event(event_filter.get("id"))
+ for event_filter in (current_filters or {}).get("events", [])
+ if isinstance(event_filter, dict)
+ )
+ proposed_is_managed = any(
+ is_managed_alert_internal_event(event_filter.get("id"))
+ for event_filter in (proposed_filters or {}).get("events", [])
+ if isinstance(event_filter, dict)
+ )
+ if current_is_managed or proposed_is_managed:
+ raise serializers.ValidationError(
+ {"filters": "Alert notification destinations are managed through the alert API."}
+ )
+
self._validate_hidden_template_not_enabled(attrs, bool(is_create))
# Existing functions keep working (and can be updated/disabled) if the flag is
@@ -928,6 +947,10 @@ class HogFunctionViewSet(
def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
queryset = queryset.exclude(type=HogFunctionType.WAREHOUSE_SOURCE_WEBHOOK.value)
+ # Managed alert destinations are single-event by construction, so events[0] is sufficient here.
+ queryset = queryset.filter(
+ Q(filters__events__0__id__isnull=True) | ~Q(filters__events__0__id__regex=MANAGED_ALERT_EVENT_PATTERN)
+ )
if not (self.action == "partial_update" and self.request.data.get("deleted") is False):
# We only want to include deleted functions if we are un-deleting them
diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.py
index 3dc3faf09604..0360a643c0a8 100644
--- a/products/cdp/backend/api/test/test_hog_function.py
+++ b/products/cdp/backend/api/test/test_hog_function.py
@@ -187,6 +187,59 @@ class TestHogFunctionAPIWithoutAvailableFeature(ClickhouseTestMixin, APIBaseTest
)
self.assertEqual(delete_response.status_code, status.HTTP_200_OK, delete_response.json())
+ def test_generic_api_cannot_subscribe_to_managed_alert_events(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_functions/",
+ data={
+ "name": "Forged billing destination",
+ "hog": "fetch('https://example.com');",
+ "type": "internal_destination",
+ "enabled": True,
+ "filters": {"events": [{"id": "$billing_alert_firing", "type": "events"}]},
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())
+ self.assertEqual(response.json()["attr"], "filters")
+ self.assertIn("managed through the alert API", response.json()["detail"])
+
+ def test_generic_api_hides_and_cannot_patch_managed_alert_destinations(self):
+ ordinary = HogFunction.objects.create(
+ team=self.team,
+ name="Ordinary destination",
+ hog="return event",
+ type="destination",
+ enabled=False,
+ filters={},
+ )
+ managed = HogFunction.objects.create(
+ team=self.team,
+ name="Billing alert destination",
+ hog="return event",
+ type="internal_destination",
+ enabled=True,
+ filters={
+ "events": [{"id": "$billing_alert_firing", "type": "events"}],
+ "properties": [{"key": "alert_id", "value": "alert-1"}],
+ },
+ )
+
+ list_response = self.client.get(f"/api/projects/{self.team.id}/hog_functions/?full=true")
+ ordinary_response = self.client.get(f"/api/projects/{self.team.id}/hog_functions/{ordinary.id}/")
+ retrieve_response = self.client.get(f"/api/projects/{self.team.id}/hog_functions/{managed.id}/")
+ patch_response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_functions/{managed.id}/",
+ data={"inputs": {"url": {"value": "https://attacker.example"}}},
+ )
+
+ self.assertEqual(list_response.status_code, status.HTTP_200_OK)
+ listed_ids = {item["id"] for item in list_response.json()["results"]}
+ self.assertEqual(ordinary_response.status_code, status.HTTP_200_OK, ordinary_response.json())
+ self.assertIn(str(ordinary.id), listed_ids)
+ self.assertNotIn(str(managed.id), listed_ids)
+ self.assertEqual(retrieve_response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(patch_response.status_code, status.HTTP_404_NOT_FOUND)
+
class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
def setUp(self):
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index ce2b7159bfd8..efd7cdf06e4c 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -891,6 +891,36 @@
"readOnlyHint": true
}
},
+ "billing-alert-create": {
+ "description": "Create a billing-period spend alert in the active organization. The caller must be an organization Admin or Owner. Billing owns the trigger configuration and evaluation; the shared alerting backend handles lifecycle, scheduling, destinations, and delivery. The metric picks the billing-period total to watch: spend (current period total so far) or projected_spend (projected period-end total). The first version supports only the absolute_value threshold rule with threshold_value, in USD. Optional destination_changes can create Slack, Microsoft Teams, or HTTPS webhook destinations atomically with the alert.",
+ "category": "Billing alerts",
+ "feature": "billing_alerts",
+ "summary": "Create billing alert",
+ "title": "Create billing alert",
+ "required_scopes": ["organization:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "billing-alerts"
+ },
+ "billing-alert-update": {
+ "description": "Partially update a billing alert by ID in the active organization. The caller must be an organization Admin or Owner. Change only the supplied trigger fields, alert copy, enabled state, snooze, or cooldown. The metric picks the billing-period total to watch (spend or projected_spend); the first version supports only the absolute_value threshold rule with threshold_value, in USD. Optional destination_changes applies destination creation or complete-group deletion in the same backend transaction as the configuration update. Repeating a request that creates a destination of the same type is rejected, because an alert allows one destination group per type.",
+ "category": "Billing alerts",
+ "feature": "billing_alerts",
+ "summary": "Update billing alert",
+ "title": "Update billing alert",
+ "required_scopes": ["organization:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "billing-alerts"
+ },
"business-knowledge-document-window-retrieve": {
"description": "Returns a window of content chunks from a business knowledge document, centered around a specific ordinal. Use after searching knowledge to get more surrounding context for a specific result.",
"category": "Business knowledge",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 09ecf60044e1..28b199dfbf02 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -906,6 +906,36 @@
"readOnlyHint": true
}
},
+ "billing-alert-create": {
+ "description": "Create a billing-period spend alert in the active organization. The caller must be an organization Admin or Owner. Billing owns the trigger configuration and evaluation; the shared alerting backend handles lifecycle, scheduling, destinations, and delivery. The metric picks the billing-period total to watch: spend (current period total so far) or projected_spend (projected period-end total). The first version supports only the absolute_value threshold rule with threshold_value, in USD. Optional destination_changes can create Slack, Microsoft Teams, or HTTPS webhook destinations atomically with the alert.",
+ "category": "Billing alerts",
+ "feature": "billing_alerts",
+ "summary": "Create billing alert",
+ "title": "Create billing alert",
+ "required_scopes": ["organization:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "billing-alerts"
+ },
+ "billing-alert-update": {
+ "description": "Partially update a billing alert by ID in the active organization. The caller must be an organization Admin or Owner. Change only the supplied trigger fields, alert copy, enabled state, snooze, or cooldown. The metric picks the billing-period total to watch (spend or projected_spend); the first version supports only the absolute_value threshold rule with threshold_value, in USD. Optional destination_changes applies destination creation or complete-group deletion in the same backend transaction as the configuration update. Repeating a request that creates a destination of the same type is rejected, because an alert allows one destination group per type.",
+ "category": "Billing alerts",
+ "feature": "billing_alerts",
+ "summary": "Update billing alert",
+ "title": "Update billing alert",
+ "required_scopes": ["organization:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "billing-alerts"
+ },
"business-knowledge-document-window-retrieve": {
"description": "Returns a window of content chunks from a business knowledge document, centered around a specific ordinal. Use after searching knowledge to get more surrounding context for a specific result.",
"category": "Business knowledge",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d85c8d1f6fc5..cfd9e854c8e1 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13046,6 +13046,398 @@ export namespace Schemas {
BigQuery: 'BigQuery',
} as const;
+ /**
+ * * `check` - Check
+ * * `firing` - Firing
+ * * `resolved` - Resolved
+ * * `errored` - Errored
+ * * `broken_config` - Broken config
+ */
+ export type BillingAlertEventKindEnum = typeof BillingAlertEventKindEnum[keyof typeof BillingAlertEventKindEnum];
+
+
+ export const BillingAlertEventKindEnum = {
+ Check: 'check',
+ Firing: 'firing',
+ Resolved: 'resolved',
+ Errored: 'errored',
+ BrokenConfig: 'broken_config',
+ } as const;
+
+ /**
+ * * `scheduled` - Scheduled
+ * * `manual` - Manual
+ */
+ export type BillingAlertEventSourceEnum = typeof BillingAlertEventSourceEnum[keyof typeof BillingAlertEventSourceEnum];
+
+
+ export const BillingAlertEventSourceEnum = {
+ Scheduled: 'scheduled',
+ Manual: 'manual',
+ } as const;
+
+ /**
+ * * `spend` - Spend
+ * * `projected_spend` - Projected spend
+ */
+ export type BillingAlertMetricEnum = typeof BillingAlertMetricEnum[keyof typeof BillingAlertMetricEnum];
+
+
+ export const BillingAlertMetricEnum = {
+ Spend: 'spend',
+ ProjectedSpend: 'projected_spend',
+ } as const;
+
+ /**
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken
+ */
+ export type BillingAlertStateEnum = typeof BillingAlertStateEnum[keyof typeof BillingAlertStateEnum];
+
+
+ export const BillingAlertStateEnum = {
+ NotFiring: 'not_firing',
+ Firing: 'firing',
+ Errored: 'errored',
+ Snoozed: 'snoozed',
+ Broken: 'broken',
+ } as const;
+
+ export interface BillingAlertEvent {
+ /** Unique identifier for this billing alert event. */
+ readonly id: string;
+ /** Event kind for a check, state transition, or delivery-worthy alert event.
+ *
+ * * `check` - Check
+ * * `firing` - Firing
+ * * `resolved` - Resolved
+ * * `errored` - Errored
+ * * `broken_config` - Broken config */
+ readonly kind: BillingAlertEventKindEnum;
+ /** Whether this evaluation was scheduled or manually requested.
+ *
+ * * `scheduled` - Scheduled
+ * * `manual` - Manual */
+ readonly source: BillingAlertEventSourceEnum;
+ /** Attempt number for this billing date and configuration revision. */
+ readonly attempt_number: number;
+ /** When this event was recorded. */
+ readonly created_at: string;
+ /**
+ * Billing data date evaluated by this event.
+ * @nullable
+ */
+ readonly evaluation_date: string | null;
+ /** Configuration revision used for this evaluation. */
+ readonly configuration_revision: number;
+ /**
+ * Start of the evaluated billing period.
+ * @nullable
+ */
+ readonly period_start: string | null;
+ /**
+ * End of the evaluated billing period.
+ * @nullable
+ */
+ readonly period_end: string | null;
+ /** Billing metric evaluated by this event.
+ *
+ * * `spend` - Spend
+ * * `projected_spend` - Projected spend */
+ readonly metric: BillingAlertMetricEnum;
+ /**
+ * Metric value for the evaluated billing date.
+ * @nullable
+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$
+ */
+ readonly current_value: string | null;
+ /**
+ * Average metric value across the baseline window.
+ * @nullable
+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$
+ */
+ readonly baseline_value: string | null;
+ /**
+ * Current value minus the baseline value.
+ * @nullable
+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$
+ */
+ readonly absolute_delta: string | null;
+ /**
+ * Percentage change against the baseline value.
+ * @nullable
+ * @pattern ^-?\d{0,22}(?:\.\d{0,6})?$
+ */
+ readonly relative_delta_percentage: string | null;
+ /** Whether the evaluated value breached the configured threshold. */
+ readonly threshold_breached: boolean;
+ /** Alert state before this event was applied.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state_before: BillingAlertStateEnum | null;
+ /** Alert state after this event was applied.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state_after: BillingAlertStateEnum | null;
+ /**
+ * When notifications for this event were delivered.
+ * @nullable
+ */
+ readonly notification_sent_at: string | null;
+ /** Notification targets recorded for this event. */
+ readonly targets_notified: unknown;
+ /**
+ * Milliseconds spent fetching billing data for this evaluation.
+ * @nullable
+ */
+ readonly query_duration_ms: number | null;
+ /**
+ * Exception class name recorded when the evaluation failed.
+ * @nullable
+ */
+ readonly error_code: string | null;
+ /**
+ * Failure description recorded when the evaluation failed.
+ * @nullable
+ */
+ readonly error_message: string | null;
+ /** Human-readable explanation of the evaluation outcome. */
+ readonly reason: string;
+ }
+
+ export interface BillingAlertCheckNowResponse {
+ /** Evaluation event recorded by the manual check, or null for a paused preview. */
+ event?: BillingAlertEvent | null;
+ /** Number of destination HogFunctions queued. */
+ dispatched_destinations: number;
+ /** True when the alert is paused: it was evaluated but no notifications were sent. */
+ preview: boolean;
+ /** Whether the evaluated billing-period total breached the configured threshold. */
+ threshold_breached: boolean;
+ /**
+ * Evaluated billing-period total, or null when billing data was not available.
+ * @nullable
+ */
+ current_value?: string | null;
+ }
+
+ /**
+ * * `USD` - USD
+ */
+ export type CurrencyEnum = typeof CurrencyEnum[keyof typeof CurrencyEnum];
+
+
+ export const CurrencyEnum = {
+ Usd: 'USD',
+ } as const;
+
+ /**
+ * * `relative_increase` - Relative increase
+ * * `absolute_value` - Absolute value
+ * * `absolute_increase` - Absolute increase
+ */
+ export type ThresholdTypeEnum = typeof ThresholdTypeEnum[keyof typeof ThresholdTypeEnum];
+
+
+ export const ThresholdTypeEnum = {
+ RelativeIncrease: 'relative_increase',
+ AbsoluteValue: 'absolute_value',
+ AbsoluteIncrease: 'absolute_increase',
+ } as const;
+
+ /**
+ * * `slack` - slack
+ * * `webhook` - webhook
+ * * `teams` - teams
+ */
+ export type NotificationDestinationTypeEnum = typeof NotificationDestinationTypeEnum[keyof typeof NotificationDestinationTypeEnum];
+
+
+ export const NotificationDestinationTypeEnum = {
+ Slack: 'slack',
+ Webhook: 'webhook',
+ Teams: 'teams',
+ } as const;
+
+ export interface BillingAlertDestinationSummary {
+ type: NotificationDestinationTypeEnum;
+ hog_function_ids: string[];
+ }
+
+ export interface BillingAlertDestinationCreateData {
+ /** Destination type.
+ *
+ * * `slack` - slack
+ * * `webhook` - webhook
+ * * `teams` - teams */
+ type: NotificationDestinationTypeEnum;
+ /** Slack integration ID in the alert execution project. */
+ slack_workspace_id?: number;
+ /** Slack channel ID for alert delivery. */
+ slack_channel_id?: string;
+ /** Optional Slack channel name shown in the UI. */
+ slack_channel_name?: string;
+ /** HTTPS webhook URL for webhook or Microsoft Teams delivery. */
+ webhook_url?: string;
+ }
+
+ export interface BillingAlertDestinationChanges {
+ /**
+ * @items.minItems 4
+ * @items.maxItems 4
+ */
+ delete?: string[][];
+ create?: BillingAlertDestinationCreateData[];
+ }
+
+ export interface BillingAlertConfiguration {
+ /** Unique identifier for this billing alert. */
+ readonly id: string;
+ /** Organization this billing alert belongs to. */
+ readonly organization_id: string;
+ /**
+ * Team used as the execution context for internal notification destinations.
+ * @nullable
+ */
+ readonly execution_team_id: number | null;
+ /**
+ * User ID that created this alert.
+ * @nullable
+ */
+ readonly created_by_id: number | null;
+ /**
+ * User ID that last updated this alert.
+ * @nullable
+ */
+ readonly updated_by_id: number | null;
+ /**
+ * Display name for this billing alert.
+ * @maxLength 160
+ */
+ name: string;
+ /** Optional internal description. */
+ description?: string;
+ /** Whether scheduled checks should evaluate this alert. */
+ enabled?: boolean;
+ /** Billing-period total to evaluate: current spend so far, or projected period-end spend.
+ *
+ * * `spend` - Spend
+ * * `projected_spend` - Projected spend */
+ metric?: BillingAlertMetricEnum;
+ /** Server-controlled currency for spend values.
+ *
+ * * `USD` - USD */
+ readonly currency: CurrencyEnum;
+ /** Revision incremented whenever evaluation behavior changes. */
+ readonly configuration_revision: number;
+ /** Threshold rule type. The first version supports absolute value only.
+ *
+ * * `relative_increase` - Relative increase
+ * * `absolute_value` - Absolute value
+ * * `absolute_increase` - Absolute increase */
+ threshold_type?: ThresholdTypeEnum;
+ /**
+ * Reserved for future increase-over-baseline rules. Not used by absolute value alerts.
+ * @nullable
+ * @pattern ^-?\d{0,6}(?:\.\d{0,2})?$
+ */
+ threshold_percentage?: string | null;
+ /**
+ * Absolute value or absolute increase that triggers absolute threshold alerts.
+ * @nullable
+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$
+ */
+ threshold_value?: string | null;
+ /**
+ * Minimum current value before the alert can fire.
+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$
+ */
+ minimum_value?: string;
+ /**
+ * Reserved for future increase-over-baseline rules. Not used by absolute value alerts.
+ * @minimum 1
+ * @maximum 90
+ */
+ baseline_window_days?: number;
+ /**
+ * Hours after a UTC billing date ends before it becomes eligible for evaluation.
+ * @minimum 0
+ * @maximum 72
+ */
+ evaluation_delay_hours?: number;
+ /** Current lifecycle state of this alert.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state: BillingAlertStateEnum;
+ /**
+ * Minimum hours between repeated firing notifications.
+ * @minimum 0
+ * @maximum 720
+ */
+ cooldown_hours?: number;
+ /**
+ * ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume.
+ * @nullable
+ */
+ snoozed_until?: string | null;
+ /**
+ * When the next scheduled evaluation is due.
+ * @nullable
+ */
+ readonly next_check_at: string | null;
+ /**
+ * When this alert was last evaluated.
+ * @nullable
+ */
+ readonly last_checked_at: string | null;
+ /**
+ * When notifications were last delivered for this alert.
+ * @nullable
+ */
+ readonly last_notified_at: string | null;
+ /** Number of consecutive failed evaluations. */
+ readonly consecutive_failures: number;
+ /** Notification destination groups configured for this alert, including their shared HogFunctions. */
+ readonly destinations: readonly BillingAlertDestinationSummary[];
+ /** Destination groups to create or delete in the same transaction as this configuration write. */
+ destination_changes?: BillingAlertDestinationChanges;
+ /** When this alert was created. */
+ readonly created_at: string;
+ /**
+ * When this alert was last updated.
+ * @nullable
+ */
+ readonly updated_at: string | null;
+ }
+
+ export interface BillingAlertDeleteDestination {
+ /**
+ * HogFunction IDs to delete as one atomic destination group.
+ * @minItems 4
+ * @maxItems 4
+ */
+ hog_function_ids: string[];
+ }
+
+ export interface BillingAlertDestinationResponse {
+ hog_function_ids: string[];
+ }
+
/**
* * `posthog_health_check` - PostHog health check
* * `posthog_onboarding` - PostHog onboarding
@@ -43544,20 +43936,6 @@ export namespace Schemas {
enabled: boolean;
}
- /**
- * * `slack` - slack
- * * `webhook` - webhook
- * * `teams` - teams
- */
- export type NotificationDestinationTypeEnum = typeof NotificationDestinationTypeEnum[keyof typeof NotificationDestinationTypeEnum];
-
-
- export const NotificationDestinationTypeEnum = {
- Slack: 'slack',
- Webhook: 'webhook',
- Teams: 'teams',
- } as const;
-
export interface LogsAlertConfiguration {
/** Unique identifier for this alert. */
readonly id: string;
@@ -48535,6 +48913,24 @@ export namespace Schemas {
results: BatchImportSupportList[];
}
+ export interface PaginatedBillingAlertConfigurationList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: BillingAlertConfiguration[];
+ }
+
+ export interface PaginatedBillingAlertEventList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: BillingAlertEvent[];
+ }
+
export interface PaginatedBriefConfigList {
count: number;
/** @nullable */
@@ -54733,6 +55129,130 @@ export namespace Schemas {
readonly import_config?: unknown;
}
+ export interface PatchedBillingAlertConfiguration {
+ /** Unique identifier for this billing alert. */
+ readonly id?: string;
+ /** Organization this billing alert belongs to. */
+ readonly organization_id?: string;
+ /**
+ * Team used as the execution context for internal notification destinations.
+ * @nullable
+ */
+ readonly execution_team_id?: number | null;
+ /**
+ * User ID that created this alert.
+ * @nullable
+ */
+ readonly created_by_id?: number | null;
+ /**
+ * User ID that last updated this alert.
+ * @nullable
+ */
+ readonly updated_by_id?: number | null;
+ /**
+ * Display name for this billing alert.
+ * @maxLength 160
+ */
+ name?: string;
+ /** Optional internal description. */
+ description?: string;
+ /** Whether scheduled checks should evaluate this alert. */
+ enabled?: boolean;
+ /** Billing-period total to evaluate: current spend so far, or projected period-end spend.
+ *
+ * * `spend` - Spend
+ * * `projected_spend` - Projected spend */
+ metric?: BillingAlertMetricEnum;
+ /** Server-controlled currency for spend values.
+ *
+ * * `USD` - USD */
+ readonly currency?: CurrencyEnum;
+ /** Revision incremented whenever evaluation behavior changes. */
+ readonly configuration_revision?: number;
+ /** Threshold rule type. The first version supports absolute value only.
+ *
+ * * `relative_increase` - Relative increase
+ * * `absolute_value` - Absolute value
+ * * `absolute_increase` - Absolute increase */
+ threshold_type?: ThresholdTypeEnum;
+ /**
+ * Reserved for future increase-over-baseline rules. Not used by absolute value alerts.
+ * @nullable
+ * @pattern ^-?\d{0,6}(?:\.\d{0,2})?$
+ */
+ threshold_percentage?: string | null;
+ /**
+ * Absolute value or absolute increase that triggers absolute threshold alerts.
+ * @nullable
+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$
+ */
+ threshold_value?: string | null;
+ /**
+ * Minimum current value before the alert can fire.
+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$
+ */
+ minimum_value?: string;
+ /**
+ * Reserved for future increase-over-baseline rules. Not used by absolute value alerts.
+ * @minimum 1
+ * @maximum 90
+ */
+ baseline_window_days?: number;
+ /**
+ * Hours after a UTC billing date ends before it becomes eligible for evaluation.
+ * @minimum 0
+ * @maximum 72
+ */
+ evaluation_delay_hours?: number;
+ /** Current lifecycle state of this alert.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state?: BillingAlertStateEnum;
+ /**
+ * Minimum hours between repeated firing notifications.
+ * @minimum 0
+ * @maximum 720
+ */
+ cooldown_hours?: number;
+ /**
+ * ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume.
+ * @nullable
+ */
+ snoozed_until?: string | null;
+ /**
+ * When the next scheduled evaluation is due.
+ * @nullable
+ */
+ readonly next_check_at?: string | null;
+ /**
+ * When this alert was last evaluated.
+ * @nullable
+ */
+ readonly last_checked_at?: string | null;
+ /**
+ * When notifications were last delivered for this alert.
+ * @nullable
+ */
+ readonly last_notified_at?: string | null;
+ /** Number of consecutive failed evaluations. */
+ readonly consecutive_failures?: number;
+ /** Notification destination groups configured for this alert, including their shared HogFunctions. */
+ readonly destinations?: readonly BillingAlertDestinationSummary[];
+ /** Destination groups to create or delete in the same transaction as this configuration write. */
+ destination_changes?: BillingAlertDestinationChanges;
+ /** When this alert was created. */
+ readonly created_at?: string;
+ /**
+ * When this alert was last updated.
+ * @nullable
+ */
+ readonly updated_at?: string | null;
+ }
+
export interface PatchedBriefConfig {
readonly id?: string;
/**
@@ -82005,6 +82525,28 @@ export namespace Schemas {
search?: string;
};
+ export type BillingAlertsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
+ export type BillingAlertsEventsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type CimdVerificationTokensListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/billing_alerts/api.ts b/services/mcp/src/generated/billing_alerts/api.ts
new file mode 100644
index 000000000000..11d8f500a49f
--- /dev/null
+++ b/services/mcp/src/generated/billing_alerts/api.ts
@@ -0,0 +1,250 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * MCP service uses these Zod schemas for generated tool handlers.
+ * To regenerate: hogli build:openapi
+ *
+ * PostHog API - MCP 2 enabled ops
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+export const BillingAlertsCreateParams = /* @__PURE__ */ zod.object({
+ organization_id: zod
+ .string()
+ .describe(
+ "ID of the organization you're trying to access. To find the ID of the organization, make a call to \/api\/organizations\/."
+ ),
+})
+
+export const billingAlertsCreateBodyNameMax = 160
+
+export const billingAlertsCreateBodyThresholdPercentageRegExp = new RegExp('^-?\\d{0,6}(?:\\.\\d{0,2})?$')
+export const billingAlertsCreateBodyThresholdValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')
+export const billingAlertsCreateBodyMinimumValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')
+export const billingAlertsCreateBodyBaselineWindowDaysMax = 90
+
+export const billingAlertsCreateBodyEvaluationDelayHoursMin = 0
+export const billingAlertsCreateBodyEvaluationDelayHoursMax = 72
+
+export const billingAlertsCreateBodyCooldownHoursMin = 0
+export const billingAlertsCreateBodyCooldownHoursMax = 720
+
+export const billingAlertsCreateBodyDestinationChangesOneDeleteItemMin = 4
+export const billingAlertsCreateBodyDestinationChangesOneDeleteItemMax = 4
+
+export const BillingAlertsCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(billingAlertsCreateBodyNameMax).describe('Display name for this billing alert.'),
+ description: zod.string().optional().describe('Optional internal description.'),
+ enabled: zod.boolean().optional().describe('Whether scheduled checks should evaluate this alert.'),
+ metric: zod
+ .enum(['spend', 'projected_spend'])
+ .describe('\* `spend` - Spend\n\* `projected_spend` - Projected spend')
+ .optional()
+ .describe(
+ 'Billing-period total to evaluate: current spend so far, or projected period-end spend.\n\n\* `spend` - Spend\n\* `projected_spend` - Projected spend'
+ ),
+ threshold_type: zod
+ .enum(['relative_increase', 'absolute_value', 'absolute_increase'])
+ .describe(
+ '\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'
+ )
+ .optional()
+ .describe(
+ 'Threshold rule type. The first version supports absolute value only.\n\n\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'
+ ),
+ threshold_percentage: zod
+ .stringFormat('decimal', billingAlertsCreateBodyThresholdPercentageRegExp)
+ .nullish()
+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),
+ threshold_value: zod
+ .stringFormat('decimal', billingAlertsCreateBodyThresholdValueRegExp)
+ .nullish()
+ .describe('Absolute value or absolute increase that triggers absolute threshold alerts.'),
+ minimum_value: zod
+ .stringFormat('decimal', billingAlertsCreateBodyMinimumValueRegExp)
+ .optional()
+ .describe('Minimum current value before the alert can fire.'),
+ baseline_window_days: zod
+ .number()
+ .min(1)
+ .max(billingAlertsCreateBodyBaselineWindowDaysMax)
+ .optional()
+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),
+ evaluation_delay_hours: zod
+ .number()
+ .min(billingAlertsCreateBodyEvaluationDelayHoursMin)
+ .max(billingAlertsCreateBodyEvaluationDelayHoursMax)
+ .optional()
+ .describe('Hours after a UTC billing date ends before it becomes eligible for evaluation.'),
+ cooldown_hours: zod
+ .number()
+ .min(billingAlertsCreateBodyCooldownHoursMin)
+ .max(billingAlertsCreateBodyCooldownHoursMax)
+ .optional()
+ .describe('Minimum hours between repeated firing notifications.'),
+ snoozed_until: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume.'),
+ destination_changes: zod
+ .object({
+ delete: zod
+ .array(
+ zod
+ .array(zod.string())
+ .min(billingAlertsCreateBodyDestinationChangesOneDeleteItemMin)
+ .max(billingAlertsCreateBodyDestinationChangesOneDeleteItemMax)
+ )
+ .optional(),
+ create: zod
+ .array(
+ zod.object({
+ type: zod
+ .enum(['slack', 'webhook', 'teams'])
+ .describe('\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams')
+ .describe(
+ 'Destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams'
+ ),
+ slack_workspace_id: zod
+ .number()
+ .optional()
+ .describe('Slack integration ID in the alert execution project.'),
+ slack_channel_id: zod.string().optional().describe('Slack channel ID for alert delivery.'),
+ slack_channel_name: zod
+ .string()
+ .optional()
+ .describe('Optional Slack channel name shown in the UI.'),
+ webhook_url: zod
+ .url()
+ .optional()
+ .describe('HTTPS webhook URL for webhook or Microsoft Teams delivery.'),
+ })
+ )
+ .optional(),
+ })
+ .optional()
+ .describe('Destination groups to create or delete in the same transaction as this configuration write.'),
+})
+
+export const BillingAlertsPartialUpdateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this billing alert configuration.'),
+ organization_id: zod
+ .string()
+ .describe(
+ "ID of the organization you're trying to access. To find the ID of the organization, make a call to \/api\/organizations\/."
+ ),
+})
+
+export const billingAlertsPartialUpdateBodyNameMax = 160
+
+export const billingAlertsPartialUpdateBodyThresholdPercentageRegExp = new RegExp('^-?\\d{0,6}(?:\\.\\d{0,2})?$')
+export const billingAlertsPartialUpdateBodyThresholdValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')
+export const billingAlertsPartialUpdateBodyMinimumValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')
+export const billingAlertsPartialUpdateBodyBaselineWindowDaysMax = 90
+
+export const billingAlertsPartialUpdateBodyEvaluationDelayHoursMin = 0
+export const billingAlertsPartialUpdateBodyEvaluationDelayHoursMax = 72
+
+export const billingAlertsPartialUpdateBodyCooldownHoursMin = 0
+export const billingAlertsPartialUpdateBodyCooldownHoursMax = 720
+
+export const billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMin = 4
+export const billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax = 4
+
+export const BillingAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(billingAlertsPartialUpdateBodyNameMax)
+ .optional()
+ .describe('Display name for this billing alert.'),
+ description: zod.string().optional().describe('Optional internal description.'),
+ enabled: zod.boolean().optional().describe('Whether scheduled checks should evaluate this alert.'),
+ metric: zod
+ .enum(['spend', 'projected_spend'])
+ .describe('\* `spend` - Spend\n\* `projected_spend` - Projected spend')
+ .optional()
+ .describe(
+ 'Billing-period total to evaluate: current spend so far, or projected period-end spend.\n\n\* `spend` - Spend\n\* `projected_spend` - Projected spend'
+ ),
+ threshold_type: zod
+ .enum(['relative_increase', 'absolute_value', 'absolute_increase'])
+ .describe(
+ '\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'
+ )
+ .optional()
+ .describe(
+ 'Threshold rule type. The first version supports absolute value only.\n\n\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'
+ ),
+ threshold_percentage: zod
+ .stringFormat('decimal', billingAlertsPartialUpdateBodyThresholdPercentageRegExp)
+ .nullish()
+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),
+ threshold_value: zod
+ .stringFormat('decimal', billingAlertsPartialUpdateBodyThresholdValueRegExp)
+ .nullish()
+ .describe('Absolute value or absolute increase that triggers absolute threshold alerts.'),
+ minimum_value: zod
+ .stringFormat('decimal', billingAlertsPartialUpdateBodyMinimumValueRegExp)
+ .optional()
+ .describe('Minimum current value before the alert can fire.'),
+ baseline_window_days: zod
+ .number()
+ .min(1)
+ .max(billingAlertsPartialUpdateBodyBaselineWindowDaysMax)
+ .optional()
+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),
+ evaluation_delay_hours: zod
+ .number()
+ .min(billingAlertsPartialUpdateBodyEvaluationDelayHoursMin)
+ .max(billingAlertsPartialUpdateBodyEvaluationDelayHoursMax)
+ .optional()
+ .describe('Hours after a UTC billing date ends before it becomes eligible for evaluation.'),
+ cooldown_hours: zod
+ .number()
+ .min(billingAlertsPartialUpdateBodyCooldownHoursMin)
+ .max(billingAlertsPartialUpdateBodyCooldownHoursMax)
+ .optional()
+ .describe('Minimum hours between repeated firing notifications.'),
+ snoozed_until: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume.'),
+ destination_changes: zod
+ .object({
+ delete: zod
+ .array(
+ zod
+ .array(zod.string())
+ .min(billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMin)
+ .max(billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax)
+ )
+ .optional(),
+ create: zod
+ .array(
+ zod.object({
+ type: zod
+ .enum(['slack', 'webhook', 'teams'])
+ .describe('\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams')
+ .describe(
+ 'Destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams'
+ ),
+ slack_workspace_id: zod
+ .number()
+ .optional()
+ .describe('Slack integration ID in the alert execution project.'),
+ slack_channel_id: zod.string().optional().describe('Slack channel ID for alert delivery.'),
+ slack_channel_name: zod
+ .string()
+ .optional()
+ .describe('Optional Slack channel name shown in the UI.'),
+ webhook_url: zod
+ .url()
+ .optional()
+ .describe('HTTPS webhook URL for webhook or Microsoft Teams delivery.'),
+ })
+ )
+ .optional(),
+ })
+ .optional()
+ .describe('Destination groups to create or delete in the same transaction as this configuration write.'),
+})
diff --git a/services/mcp/src/tools/generated/billing_alerts.ts b/services/mcp/src/tools/generated/billing_alerts.ts
new file mode 100644
index 000000000000..57127b3e8bb6
--- /dev/null
+++ b/services/mcp/src/tools/generated/billing_alerts.ts
@@ -0,0 +1,129 @@
+// AUTO-GENERATED from products/billing_alerts/mcp/tools.yaml + OpenAPI — do not edit
+import { z } from 'zod'
+
+import type { Schemas } from '@/api/generated'
+import {
+ BillingAlertsCreateBody,
+ BillingAlertsPartialUpdateBody,
+ BillingAlertsPartialUpdateParams,
+} from '@/generated/billing_alerts/api'
+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+
+const BillingAlertCreateSchema = BillingAlertsCreateBody
+
+const billingAlertCreate = (): ToolBase<typeof BillingAlertCreateSchema, Schemas.BillingAlertConfiguration> => ({
+ name: 'billing-alert-create',
+ schema: BillingAlertCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof BillingAlertCreateSchema>) => {
+ const orgId = await context.stateManager.getOrgID()
+ const body: Record<string, unknown> = {}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.description !== undefined) {
+ body['description'] = params.description
+ }
+ if (params.enabled !== undefined) {
+ body['enabled'] = params.enabled
+ }
+ if (params.metric !== undefined) {
+ body['metric'] = params.metric
+ }
+ if (params.threshold_type !== undefined) {
+ body['threshold_type'] = params.threshold_type
+ }
+ if (params.threshold_percentage !== undefined) {
+ body['threshold_percentage'] = params.threshold_percentage
+ }
+ if (params.threshold_value !== undefined) {
+ body['threshold_value'] = params.threshold_value
+ }
+ if (params.minimum_value !== undefined) {
+ body['minimum_value'] = params.minimum_value
+ }
+ if (params.baseline_window_days !== undefined) {
+ body['baseline_window_days'] = params.baseline_window_days
+ }
+ if (params.evaluation_delay_hours !== undefined) {
+ body['evaluation_delay_hours'] = params.evaluation_delay_hours
+ }
+ if (params.cooldown_hours !== undefined) {
+ body['cooldown_hours'] = params.cooldown_hours
+ }
+ if (params.snoozed_until !== undefined) {
+ body['snoozed_until'] = params.snoozed_until
+ }
+ if (params.destination_changes !== undefined) {
+ body['destination_changes'] = params.destination_changes
+ }
+ const result = await context.api.request<Schemas.BillingAlertConfiguration>({
+ method: 'POST',
+ path: `/api/organizations/${encodeURIComponent(String(orgId))}/billing/alerts/`,
+ body,
+ })
+ return result
+ },
+})
+
+const BillingAlertUpdateSchema = BillingAlertsPartialUpdateParams.omit({ organization_id: true }).extend(
+ BillingAlertsPartialUpdateBody.shape
+)
+
+const billingAlertUpdate = (): ToolBase<typeof BillingAlertUpdateSchema, Schemas.BillingAlertConfiguration> => ({
+ name: 'billing-alert-update',
+ schema: BillingAlertUpdateSchema,
+ handler: async (context: Context, params: z.infer<typeof BillingAlertUpdateSchema>) => {
+ const orgId = await context.stateManager.getOrgID()
+ const body: Record<string, unknown> = {}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.description !== undefined) {
+ body['description'] = params.description
+ }
+ if (params.enabled !== undefined) {
+ body['enabled'] = params.enabled
+ }
+ if (params.metric !== undefined) {
+ body['metric'] = params.metric
+ }
+ if (params.threshold_type !== undefined) {
+ body['threshold_type'] = params.threshold_type
+ }
+ if (params.threshold_percentage !== undefined) {
+ body['threshold_percentage'] = params.threshold_percentage
+ }
+ if (params.threshold_value !== undefined) {
+ body['threshold_value'] = params.threshold_value
+ }
+ if (params.minimum_value !== undefined) {
+ body['minimum_value'] = params.minimum_value
+ }
+ if (params.baseline_window_days !== undefined) {
+ body['baseline_window_days'] = params.baseline_window_days
+ }
+ if (params.evaluation_delay_hours !== undefined) {
+ body['evaluation_delay_hours'] = params.evaluation_delay_hours
+ }
+ if (params.cooldown_hours !== undefined) {
+ body['cooldown_hours'] = params.cooldown_hours
+ }
+ if (params.snoozed_until !== undefined) {
+ body['snoozed_until'] = params.snoozed_until
+ }
+ if (params.destination_changes !== undefined) {
+ body['destination_changes'] = params.destination_changes
+ }
+ const result = await context.api.request<Schemas.BillingAlertConfiguration>({
+ method: 'PATCH',
+ path: `/api/organizations/${encodeURIComponent(String(orgId))}/billing/alerts/${encodeURIComponent(String(params.id))}/`,
+ body,
+ })
+ return result
+ },
+})
+
+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'billing-alert-create': billingAlertCreate,
+ 'billing-alert-update': billingAlertUpdate,
+}
diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.ts
index 4cf8c8c494c5..81780fe29f1c 100644
--- a/services/mcp/src/tools/generated/index.ts
+++ b/services/mcp/src/tools/generated/index.ts
@@ -6,6 +6,7 @@ import { GENERATED_TOOLS as ai_observability } from './ai_observability'
import { GENERATED_TOOLS as alerts } from './alerts'
import { GENERATED_TOOLS as annotations } from './annotations'
import { GENERATED_TOOLS as batch_exports } from './batch_exports'
+import { GENERATED_TOOLS as billing_alerts } from './billing_alerts'
import { GENERATED_TOOLS as business_knowledge } from './business_knowledge'
import { GENERATED_TOOLS as canvas } from './canvas'
import { GENERATED_TOOLS as cdp_function_templates } from './cdp_function_templates'
@@ -66,6 +67,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =
...alerts,
...annotations,
...batch_exports,
+ ...billing_alerts,
...business_knowledge,
...canvas,
...cdp_function_templates,
diff --git a/services/mcp/tests/tools/billingAlerts.integration.test.ts b/services/mcp/tests/tools/billingAlerts.integration.test.ts
new file mode 100644
index 000000000000..8b47b1f341c7
--- /dev/null
+++ b/services/mcp/tests/tools/billingAlerts.integration.test.ts
@@ -0,0 +1,73 @@
+import { afterEach, beforeAll, describe, expect, it } from 'vitest'
+
+import {
+ TEST_ORG_ID,
+ TEST_PROJECT_ID,
+ createTestClient,
+ createTestContext,
+ generateUniqueKey,
+ parseToolResponse,
+ setActiveProjectAndOrg,
+ validateEnvironmentVariables,
+} from '@/shared/test-utils'
+import { GENERATED_TOOLS } from '@/tools/generated/billing_alerts'
+import type { Context } from '@/tools/types'
+
+describe('Billing alerts', { concurrent: false }, () => {
+ let context: Context
+ const createdAlertIds: string[] = []
+
+ const createTool = GENERATED_TOOLS['billing-alert-create']!()
+ const updateTool = GENERATED_TOOLS['billing-alert-update']!()
+
+ beforeAll(async () => {
+ validateEnvironmentVariables()
+ const client = createTestClient()
+ context = createTestContext(client)
+ await setActiveProjectAndOrg(context, TEST_PROJECT_ID!, TEST_ORG_ID!)
+ })
+
+ afterEach(async () => {
+ for (const id of createdAlertIds) {
+ try {
+ await context.api.request({
+ method: 'DELETE',
+ path: `/api/organizations/${encodeURIComponent(TEST_ORG_ID!)}/billing/alerts/${encodeURIComponent(id)}/`,
+ })
+ } catch {
+ // Best effort. The alert may already have been removed.
+ }
+ }
+ createdAlertIds.length = 0
+ })
+
+ it('creates and partially updates an organization billing alert', async () => {
+ const name = `MCP billing alert ${generateUniqueKey('billing')}`
+ const createResult = await createTool.handler(context, {
+ name,
+ enabled: false,
+ threshold_type: 'absolute_value',
+ threshold_value: '100.000000',
+ })
+ const created = parseToolResponse(createResult)
+ createdAlertIds.push(created.id)
+
+ expect(created.name).toBe(name)
+ expect(created.threshold_type).toBe('absolute_value')
+ expect(created.threshold_value).toBe('100.000000')
+ expect(created.configuration_revision).toBe(1)
+
+ const updatedName = `${name} updated`
+ const updateResult = await updateTool.handler(context, {
+ id: created.id,
+ name: updatedName,
+ threshold_value: '125.000000',
+ })
+ const updated = parseToolResponse(updateResult)
+
+ expect(updated.id).toBe(created.id)
+ expect(updated.name).toBe(updatedName)
+ expect(updated.threshold_value).toBe('125.000000')
+ expect(updated.configuration_revision).toBe(2)
+ })
+})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-alert-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-alert-create.json
new file mode 100644
index 000000000000..f837f92d233a
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-alert-create.json
@@ -0,0 +1,141 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "baseline_window_days": {
+ "description": "Reserved for future increase-over-baseline rules. Not used by absolute value alerts.",
+ "maximum": 90,
+ "minimum": 1,
+ "type": "number"
+ },
+ "cooldown_hours": {
+ "description": "Minimum hours between repeated firing notifications.",
+ "maximum": 720,
+ "minimum": 0,
+ "type": "number"
+ },
+ "description": {
+ "description": "Optional internal description.",
+ "type": "string"
+ },
+ "destination_changes": {
+ "description": "Destination groups to create or delete in the same transaction as this configuration write.",
+ "properties": {
+ "create": {
+ "items": {
+ "properties": {
+ "slack_channel_id": {
+ "description": "Slack channel ID for alert delivery.",
+ "type": "string"
+ },
+ "slack_channel_name": {
+ "description": "Optional Slack channel name shown in the UI.",
+ "type": "string"
+ },
+ "slack_workspace_id": {
+ "description": "Slack integration ID in the alert execution project.",
+ "type": "number"
+ },
+ "type": {
+ "description": "Destination type.\n\n* `slack` - slack\n* `webhook` - webhook\n* `teams` - teams",
+ "enum": ["slack", "webhook", "teams"],
+ "type": "string"
+ },
+ "webhook_url": {
+ "description": "HTTPS webhook URL for webhook or Microsoft Teams delivery.",
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "delete": {
+ "items": {
+ "items": {
+ "type": "string"
+ },
+ "maxItems": 4,
+ "minItems": 4,
+ "type": "array"
+ },
+ "type": "array"
+ }
+ },
+ "type": "object"
+ },
+ "enabled": {
+ "description": "Whether scheduled checks should evaluate this alert.",
+ "type": "boolean"
+ },
+ "evaluation_delay_hours": {
+ "description": "Hours after a UTC billing date ends before it becomes eligible for evaluation.",
+ "maximum": 72,
+ "minimum": 0,
+ "type": "number"
+ },
+ "metric": {
+ "description": "Billing-period total to evaluate: current spend so far, or projected period-end spend.\n\n* `spend` - Spend\n* `projected_spend` - Projected spend",
+ "enum": ["spend", "projected_spend"],
+ "type": "string"
+ },
+ "minimum_value": {
+ "description": "Minimum current value before the alert can fire.",
+ "format": "decimal",
+ "pattern": "^-?\\d{0,14}(?:\\.\\d{0,6})?$",
+ "type": "string"
+ },
+ "name": {
+ "description": "Display name for this billing alert.",
+ "maxLength": 160,
+ "type": "string"
+ },
+ "snoozed_until": {
+ "anyOf": [
+ {
+ "format": "date-time",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume."
+ },
+ "threshold_percentage": {
+ "anyOf": [
+ {
+ "format": "decimal",
+ "pattern": "^-?\\d{0,6}(?:\\.\\d{0,2})?$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Reserved for future increase-over-baseline rules. Not used by absolute value alerts."
+ },
+ "threshold_type": {
+ "description": "Threshold rule type. The first version supports absolute value only.\n\n* `relative_increase` - Relative increase\n* `absolute_value` - Absolute value\n* `absolute_increase` - Absolute increase",
+ "enum": ["relative_increase", "absolute_value", "absolute_increase"],
+ "type": "string"
+ },
+ "threshold_value": {
+ "anyOf": [
+ {
+ "format": "decimal",
+ "pattern": "^-?\\d{0,14}(?:\\.\\d{0,6})?$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Absolute value or absolute increase that triggers absolute threshold alerts."
+ }
+ },
+ "required": ["name"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-alert-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-alert-update.json
new file mode 100644
index 000000000000..0b8c7968a83e
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-alert-update.json
@@ -0,0 +1,145 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "baseline_window_days": {
+ "description": "Reserved for future increase-over-baseline rules. Not used by absolute value alerts.",
+ "maximum": 90,
+ "minimum": 1,
+ "type": "number"
+ },
+ "cooldown_hours": {
+ "description": "Minimum hours between repeated firing notifications.",
+ "maximum": 720,
+ "minimum": 0,
+ "type": "number"
+ },
+ "description": {
+ "description": "Optional internal description.",
+ "type": "string"
+ },
+ "destination_changes": {
+ "description": "Destination groups to create or delete in the same transaction as this configuration write.",
+ "properties": {
+ "create": {
+ "items": {
+ "properties": {
+ "slack_channel_id": {
+ "description": "Slack channel ID for alert delivery.",
+ "type": "string"
+ },
+ "slack_channel_name": {
+ "description": "Optional Slack channel name shown in the UI.",
+ "type": "string"
+ },
+ "slack_workspace_id": {
+ "description": "Slack integration ID in the alert execution project.",
+ "type": "number"
+ },
+ "type": {
+ "description": "Destination type.\n\n* `slack` - slack\n* `webhook` - webhook\n* `teams` - teams",
+ "enum": ["slack", "webhook", "teams"],
+ "type": "string"
+ },
+ "webhook_url": {
+ "description": "HTTPS webhook URL for webhook or Microsoft Teams delivery.",
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "delete": {
+ "items": {
+ "items": {
+ "type": "string"
+ },
+ "maxItems": 4,
+ "minItems": 4,
+ "type": "array"
+ },
+ "type": "array"
+ }
+ },
+ "type": "object"
+ },
+ "enabled": {
+ "description": "Whether scheduled checks should evaluate this alert.",
+ "type": "boolean"
+ },
+ "evaluation_delay_hours": {
+ "description": "Hours after a UTC billing date ends before it becomes eligible for evaluation.",
+ "maximum": 72,
+ "minimum": 0,
+ "type": "number"
+ },
+ "id": {
+ "description": "A UUID string identifying this billing alert configuration.",
+ "type": "string"
+ },
+ "metric": {
+ "description": "Billing-period total to evaluate: current spend so far, or projected period-end spend.\n\n* `spend` - Spend\n* `projected_spend` - Projected spend",
+ "enum": ["spend", "projected_spend"],
+ "type": "string"
+ },
+ "minimum_value": {
+ "description": "Minimum current value before the alert can fire.",
+ "format": "decimal",
+ "pattern": "^-?\\d{0,14}(?:\\.\\d{0,6})?$",
+ "type": "string"
+ },
+ "name": {
+ "description": "Display name for this billing alert.",
+ "maxLength": 160,
+ "type": "string"
+ },
+ "snoozed_until": {
+ "anyOf": [
+ {
+ "format": "date-time",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume."
+ },
+ "threshold_percentage": {
+ "anyOf": [
+ {
+ "format": "decimal",
+ "pattern": "^-?\\d{0,6}(?:\\.\\d{0,2})?$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Reserved for future increase-over-baseline rules. Not used by absolute value alerts."
+ },
+ "threshold_type": {
+ "description": "Threshold rule type. The first version supports absolute value only.\n\n* `relative_increase` - Relative increase\n* `absolute_value` - Absolute value\n* `absolute_increase` - Absolute increase",
+ "enum": ["relative_increase", "absolute_value", "absolute_increase"],
+ "type": "string"
+ },
+ "threshold_value": {
+ "anyOf": [
+ {
+ "format": "decimal",
+ "pattern": "^-?\\d{0,14}(?:\\.\\d{0,6})?$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Absolute value or absolute increase that triggers absolute threshold alerts."
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 43a6dd9d2336..ead33a0126f6 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -855,12 +855,13 @@ describe('Tool Filtering - Feature Flags', () => {
'loops',
'review-hog',
'warehouse-person-properties',
+ 'billing-alerts',
'streamlit-apps',
'posthog-connect',
'experiment-behavior-comparison',
])
)
- expect(flags).toHaveLength(28)
+ expect(flags).toHaveLength(29)
})
it('every loops tool is gated on the loops flag', () => {
diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
index 7d2c0383d01b..57da9541a5c1 100644
--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts
+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
@@ -97,6 +97,8 @@ describe('Tool schema snapshots', () => {
tasks: true,
loops: true,
'dashboard-widgets': true,
+ 'agent-platform': true,
+ 'billing-alerts': true,
}
const tools = [...(await getToolsFromContext(context, { featureFlags }))].sort((a, b) =>
a.name.localeCompare(b.name)
diff --git a/tach.toml b/tach.toml
index 8b15ddf3b4c2..43977adc0908 100644
--- a/tach.toml
+++ b/tach.toml
@@ -498,7 +498,10 @@ layer = "modules"
[[modules]]
path = "products.billing_alerts"
depends_on = [
+ "ee",
"posthog",
+ "products.alerts",
+ "products.cdp",
]
layer = "modules"
@@ -952,6 +955,18 @@ from = [
"products.experiments",
]
+# Billing alerts registers product-owned workflows and a schedule with the shared billing worker.
+
+[[interfaces]]
+expose = [
+ "backend\\.temporal\\.ACTIVITIES",
+ "backend\\.temporal\\.WORKFLOWS",
+ "backend\\.temporal\\.schedule\\.create_schedule_due_billing_alert_checks_schedule",
+]
+from = [
+ "products.billing_alerts",
+]
+
# Experiments is the first isolated product to register a Temporal workflow, so the canonical interface
# doesn't cover the registration surface yet. Narrowly expose the symbols core imports (worker registration,
# schedule registration, and the worker interceptor) rather than widening every isolated product's surface.