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 schema (#66353)

willwearing4305f60dd6f9
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index 287c886087e6..285edec7efad 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -380,6 +380,14 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
user_scoped: set[str] = set()
no_scope: set[str] = set()
+ # Billing alerts are organization-scoped through BillingAlertConfiguration. Team is only an
+ # execution context; claim and event records inherit scope through their canonical parent.
+ organization_scoped_overrides = {
+ "BillingAlertConfiguration",
+ "BillingAlertEvaluationClaim",
+ "BillingAlertEvent",
+ }
+
for model in apps.get_models():
model_name = model.__name__
@@ -391,6 +399,10 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
if model._meta.proxy:
continue
+ if model_name in organization_scoped_overrides:
+ org_scoped.add(model_name)
+ continue
+
# Check for FK fields and plain team_id (ProductTeamModel uses BigIntegerField)
has_team_fk = False
has_org_fk = False
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index f7e4f15315d5..919beff8c792 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -810,7 +810,10 @@ rules:
metavariable: $MODEL
regex: |
(?x)(
- CIMDVerificationToken
+ BillingAlertConfiguration
+ |BillingAlertEvaluationClaim
+ |BillingAlertEvent
+ |CIMDVerificationToken
|IdentityProviderConfig
|LegalDocument
|OrganizationMembership
@@ -878,7 +881,10 @@ rules:
metavariable: $MODEL
regex: |
(?x)(
- CIMDVerificationToken
+ BillingAlertConfiguration
+ |BillingAlertEvaluationClaim
+ |BillingAlertEvent
+ |CIMDVerificationToken
|IdentityProviderConfig
|LegalDocument
|OrganizationMembership
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f20a5f9dc13f..0e76e6e62153 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2512,6 +2512,8 @@ importers:
products/batch_exports: {}
+ products/billing_alerts: {}
+
products/business_knowledge:
dependencies:
'@posthog/icons':
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 4b458300444b..58ab5d948d9f 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -77,6 +77,7 @@ PRODUCTS_APPS = [
"products.event_definitions.backend.apps.EventDefinitionsConfig",
"products.review_hog.backend.apps.ReviewHogConfig",
"products.logs.backend.apps.LogsConfig",
+ "products.billing_alerts.backend.apps.BillingAlertsConfig",
"products.tracing.backend.apps.TracingConfig",
"products.metrics.backend.apps.MetricsConfig",
"products.apm.backend.apps.ApmConfig",
diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txt
index ea052c2db3c0..421b269b84b4 100644
--- a/posthog/test/setup_receivers_baseline.txt
+++ b/posthog/test/setup_receivers_baseline.txt
@@ -225,6 +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.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/billing_alerts/__init__.py b/products/billing_alerts/__init__.py
new file mode 100644
index 000000000000..8b137891791f
--- /dev/null
+++ b/products/billing_alerts/__init__.py
@@ -0,0 +1 @@
+
diff --git a/products/billing_alerts/backend/__init__.py b/products/billing_alerts/backend/__init__.py
new file mode 100644
index 000000000000..8b137891791f
--- /dev/null
+++ b/products/billing_alerts/backend/__init__.py
@@ -0,0 +1 @@
+
diff --git a/products/billing_alerts/backend/apps.py b/products/billing_alerts/backend/apps.py
new file mode 100644
index 000000000000..4f6c6cf05c43
--- /dev/null
+++ b/products/billing_alerts/backend/apps.py
@@ -0,0 +1,11 @@
+from django.apps import AppConfig
+
+
+class BillingAlertsConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "products.billing_alerts.backend"
+ label = "billing_alerts"
+ verbose_name = "Billing alerts"
+
+ def ready(self) -> None:
+ from products.billing_alerts.backend import team_lifecycle # noqa: F401, PLC0415
diff --git a/products/billing_alerts/backend/migrations/0001_initial.py b/products/billing_alerts/backend/migrations/0001_initial.py
new file mode 100644
index 000000000000..37288e24a987
--- /dev/null
+++ b/products/billing_alerts/backend/migrations/0001_initial.py
@@ -0,0 +1,350 @@
+# Generated manually for additive billing alert tables.
+
+from decimal import Decimal
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = [
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ("posthog", "1256_userproductlist_default_reason"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="BillingAlertConfiguration",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "organization",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.organization",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ blank=True,
+ db_column="execution_team_id",
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.DO_NOTHING,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "updated_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.DO_NOTHING,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ("name", models.CharField(max_length=160)),
+ ("description", models.TextField(blank=True)),
+ ("enabled", models.BooleanField(default=True)),
+ (
+ "metric",
+ models.CharField(
+ choices=[("spend", "Spend"), ("projected_spend", "Projected spend")],
+ default="spend",
+ max_length=20,
+ ),
+ ),
+ ("currency", models.CharField(choices=[("USD", "USD")], default="USD", max_length=3)),
+ ("configuration_revision", models.PositiveIntegerField(default=1)),
+ (
+ "threshold_type",
+ models.CharField(
+ choices=[
+ ("relative_increase", "Relative increase"),
+ ("absolute_value", "Absolute value"),
+ ("absolute_increase", "Absolute increase"),
+ ],
+ default="absolute_value",
+ max_length=32,
+ ),
+ ),
+ ("threshold_percentage", models.DecimalField(blank=True, decimal_places=2, max_digits=8, null=True)),
+ ("threshold_value", models.DecimalField(blank=True, decimal_places=6, max_digits=20, null=True)),
+ ("minimum_value", models.DecimalField(decimal_places=6, default=Decimal("0"), max_digits=20)),
+ ("baseline_window_days", models.PositiveSmallIntegerField(default=7)),
+ ("evaluation_delay_hours", models.PositiveSmallIntegerField(default=6)),
+ (
+ "state",
+ models.CharField(
+ choices=[
+ ("not_firing", "Not firing"),
+ ("firing", "Firing"),
+ ("errored", "Errored"),
+ ("snoozed", "Snoozed"),
+ ("broken", "Broken"),
+ ],
+ default="not_firing",
+ max_length=20,
+ ),
+ ),
+ ("cooldown_hours", models.PositiveSmallIntegerField(default=24)),
+ ("snoozed_until", models.DateTimeField(blank=True, null=True)),
+ ("next_check_at", models.DateTimeField(blank=True, null=True)),
+ ("pending_evaluation_date", models.DateField(blank=True, null=True)),
+ ("retry_attempt_count", models.PositiveSmallIntegerField(default=0)),
+ ("last_checked_at", models.DateTimeField(blank=True, null=True)),
+ ("last_notified_at", models.DateTimeField(blank=True, null=True)),
+ ("consecutive_failures", models.PositiveIntegerField(default=0)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, blank=True, null=True)),
+ ],
+ options={
+ "db_table": "billing_alerts_configuration",
+ "indexes": [
+ models.Index(fields=["organization", "-created_at"], name="billing_alert_org_created_idx"),
+ models.Index(
+ models.F("enabled"),
+ models.OrderBy(models.F("next_check_at"), nulls_first=True),
+ name="billing_alert_scheduler_idx",
+ ),
+ ],
+ "constraints": [
+ models.CheckConstraint(
+ condition=models.Q(("baseline_window_days__gte", 1)),
+ name="billing_alert_baseline_window_positive",
+ ),
+ models.CheckConstraint(
+ condition=models.Q(("minimum_value__gte", 0)),
+ name="billing_alert_minimum_nonnegative",
+ ),
+ models.CheckConstraint(
+ condition=models.Q(
+ ("threshold_percentage__gt", 0),
+ ("threshold_percentage__isnull", False),
+ ("threshold_type", "relative_increase"),
+ )
+ | models.Q(
+ ("threshold_type__in", ("absolute_value", "absolute_increase")),
+ ("threshold_value__gte", 0),
+ ("threshold_value__isnull", False),
+ ),
+ name="billing_alert_threshold_configuration_valid",
+ ),
+ ],
+ },
+ ),
+ migrations.CreateModel(
+ name="BillingAlertEvaluationClaim",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("evaluation_date", models.DateField()),
+ ("configuration_revision", models.PositiveIntegerField()),
+ ("delivery_uuid", models.UUIDField(default=posthog.models.utils.uuid7, editable=False, unique=True)),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("pending", "Pending"),
+ ("evaluating", "Evaluating"),
+ ("retryable", "Retryable"),
+ ("completed", "Completed"),
+ ("superseded", "Superseded"),
+ ],
+ default="pending",
+ max_length=20,
+ ),
+ ),
+ ("lease_expires_at", models.DateTimeField(blank=True, null=True)),
+ ("next_retry_at", models.DateTimeField(blank=True, null=True)),
+ ("attempt_count", models.PositiveIntegerField(default=0)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "alert",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="evaluation_claims",
+ to="billing_alerts.billingalertconfiguration",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "billing_alerts_evaluation_claim",
+ "indexes": [
+ models.Index(fields=["status", "next_retry_at"], name="billing_claim_retry_idx"),
+ ],
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("alert", "evaluation_date", "configuration_revision"),
+ name="unique_billing_alert_evaluation_claim",
+ )
+ ],
+ },
+ ),
+ migrations.CreateModel(
+ name="BillingAlertEvent",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "kind",
+ models.CharField(
+ choices=[
+ ("check", "Check"),
+ ("firing", "Firing"),
+ ("resolved", "Resolved"),
+ ("errored", "Errored"),
+ ("broken_config", "Broken config"),
+ ],
+ default="check",
+ max_length=32,
+ ),
+ ),
+ ("source", models.CharField(choices=[("scheduled", "Scheduled"), ("manual", "Manual")], max_length=16)),
+ ("attempt_number", models.PositiveIntegerField()),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("period_start", models.DateTimeField(blank=True, null=True)),
+ ("period_end", models.DateTimeField(blank=True, null=True)),
+ (
+ "metric",
+ models.CharField(
+ choices=[("spend", "Spend"), ("projected_spend", "Projected spend")],
+ max_length=20,
+ ),
+ ),
+ ("current_value", models.DecimalField(blank=True, decimal_places=6, max_digits=20, null=True)),
+ ("baseline_value", models.DecimalField(blank=True, decimal_places=6, max_digits=20, null=True)),
+ ("absolute_delta", models.DecimalField(blank=True, decimal_places=6, max_digits=20, null=True)),
+ (
+ "relative_delta_percentage",
+ models.DecimalField(blank=True, decimal_places=6, max_digits=28, null=True),
+ ),
+ (
+ "threshold_value_snapshot",
+ models.DecimalField(blank=True, decimal_places=6, max_digits=20, null=True),
+ ),
+ (
+ "threshold_percentage_snapshot",
+ models.DecimalField(blank=True, decimal_places=2, max_digits=8, null=True),
+ ),
+ (
+ "minimum_value_snapshot",
+ models.DecimalField(blank=True, decimal_places=6, max_digits=20, null=True),
+ ),
+ ("threshold_breached", models.BooleanField(default=False)),
+ (
+ "state_before",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("not_firing", "Not firing"),
+ ("firing", "Firing"),
+ ("errored", "Errored"),
+ ("snoozed", "Snoozed"),
+ ("broken", "Broken"),
+ ],
+ max_length=20,
+ null=True,
+ ),
+ ),
+ (
+ "state_after",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("not_firing", "Not firing"),
+ ("firing", "Firing"),
+ ("errored", "Errored"),
+ ("snoozed", "Snoozed"),
+ ("broken", "Broken"),
+ ],
+ max_length=20,
+ null=True,
+ ),
+ ),
+ ("notification_sent_at", models.DateTimeField(blank=True, null=True)),
+ ("targets_notified", models.JSONField(default=dict)),
+ ("query_duration_ms", models.PositiveIntegerField(blank=True, null=True)),
+ ("error_code", models.CharField(blank=True, max_length=80, null=True)),
+ ("error_message", models.TextField(blank=True, null=True)),
+ ("is_transient_error", models.BooleanField(default=False)),
+ ("reason", models.TextField(blank=True)),
+ ("payload", models.JSONField(default=dict)),
+ (
+ "claim",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="attempts",
+ to="billing_alerts.billingalertevaluationclaim",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.DO_NOTHING,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "billing_alerts_event",
+ "indexes": [
+ models.Index(fields=["team", "-created_at"], name="billing_event_team_ts_idx"),
+ ],
+ },
+ ),
+ migrations.AddConstraint(
+ model_name="billingalertevent",
+ constraint=models.UniqueConstraint(
+ fields=("claim", "attempt_number"),
+ name="unique_billing_alert_evaluation_attempt",
+ ),
+ ),
+ ]
diff --git a/products/billing_alerts/backend/migrations/__init__.py b/products/billing_alerts/backend/migrations/__init__.py
new file mode 100644
index 000000000000..8b137891791f
--- /dev/null
+++ b/products/billing_alerts/backend/migrations/__init__.py
@@ -0,0 +1 @@
+
diff --git a/products/billing_alerts/backend/migrations/max_migration.txt b/products/billing_alerts/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..cbab66dde92a
--- /dev/null
+++ b/products/billing_alerts/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_initial
diff --git a/products/billing_alerts/backend/models.py b/products/billing_alerts/backend/models.py
new file mode 100644
index 000000000000..298508e20040
--- /dev/null
+++ b/products/billing_alerts/backend/models.py
@@ -0,0 +1,281 @@
+from __future__ import annotations
+
+from datetime import date
+from decimal import Decimal
+from typing import cast
+from uuid import UUID
+
+from django.core.exceptions import ValidationError
+from django.db import models
+from django.db.models import F, Q
+
+from posthog.models.team.team import Team
+from posthog.models.utils import UUIDModel, uuid7
+
+DAILY_CHECK_INTERVAL_HOURS = 24
+
+
+class BillingAlertConfiguration(UUIDModel):
+ class Metric(models.TextChoices):
+ SPEND = "spend", "Spend"
+ PROJECTED_SPEND = "projected_spend", "Projected spend"
+
+ class ThresholdType(models.TextChoices):
+ RELATIVE_INCREASE = "relative_increase", "Relative increase"
+ ABSOLUTE_VALUE = "absolute_value", "Absolute value"
+ ABSOLUTE_INCREASE = "absolute_increase", "Absolute increase"
+
+ class State(models.TextChoices):
+ NOT_FIRING = "not_firing", "Not firing"
+ FIRING = "firing", "Firing"
+ ERRORED = "errored", "Errored"
+ SNOOZED = "snoozed", "Snoozed"
+ BROKEN = "broken", "Broken"
+
+ organization = models.ForeignKey(
+ "posthog.Organization",
+ on_delete=models.CASCADE,
+ related_name="+",
+ db_constraint=False,
+ )
+ # Team deletion disables and detaches the alert; feature code may re-home it to another execution team.
+ team = models.ForeignKey(
+ "posthog.Team",
+ db_column="execution_team_id",
+ db_constraint=False,
+ null=True,
+ blank=True,
+ on_delete=models.SET_NULL,
+ related_name="+",
+ )
+ # Constraint-free FKs avoid locking posthog_user; DO_NOTHING preserves audit history after user deletion.
+ created_by = models.ForeignKey(
+ "posthog.User",
+ null=True,
+ blank=True,
+ on_delete=models.DO_NOTHING,
+ db_constraint=False,
+ related_name="+",
+ )
+ updated_by = models.ForeignKey(
+ "posthog.User",
+ null=True,
+ blank=True,
+ on_delete=models.DO_NOTHING,
+ db_constraint=False,
+ related_name="+",
+ )
+
+ name = models.CharField(max_length=160)
+ description = models.TextField(blank=True)
+ enabled = models.BooleanField(default=True)
+
+ metric = models.CharField(max_length=20, choices=Metric.choices, default=Metric.SPEND)
+ currency = models.CharField(max_length=3, choices=(("USD", "USD"),), default="USD")
+ configuration_revision = models.PositiveIntegerField(default=1)
+
+ threshold_type = models.CharField(
+ max_length=32,
+ choices=ThresholdType.choices,
+ default=ThresholdType.ABSOLUTE_VALUE,
+ )
+ threshold_percentage = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True)
+ threshold_value = models.DecimalField(max_digits=20, decimal_places=6, null=True, blank=True)
+ minimum_value = models.DecimalField(max_digits=20, decimal_places=6, default=Decimal("0"))
+ baseline_window_days = models.PositiveSmallIntegerField(default=7)
+ evaluation_delay_hours = models.PositiveSmallIntegerField(default=6)
+
+ state = models.CharField(max_length=20, choices=State.choices, default=State.NOT_FIRING)
+ cooldown_hours = models.PositiveSmallIntegerField(default=24)
+ snoozed_until = models.DateTimeField(null=True, blank=True)
+ next_check_at = models.DateTimeField(null=True, blank=True)
+ pending_evaluation_date = models.DateField(null=True, blank=True)
+ retry_attempt_count = models.PositiveSmallIntegerField(default=0)
+ last_checked_at = models.DateTimeField(null=True, blank=True)
+ last_notified_at = models.DateTimeField(null=True, blank=True)
+ consecutive_failures = models.PositiveIntegerField(default=0)
+
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)
+
+ class Meta:
+ db_table = "billing_alerts_configuration"
+ indexes = [
+ models.Index(fields=["organization", "-created_at"], name="billing_alert_org_created_idx"),
+ models.Index(
+ "enabled",
+ F("next_check_at").asc(nulls_first=True),
+ name="billing_alert_scheduler_idx",
+ ),
+ ]
+ constraints = [
+ models.CheckConstraint(
+ condition=Q(baseline_window_days__gte=1),
+ name="billing_alert_baseline_window_positive",
+ ),
+ models.CheckConstraint(condition=Q(minimum_value__gte=0), name="billing_alert_minimum_nonnegative"),
+ models.CheckConstraint(
+ condition=(
+ Q(
+ threshold_type="relative_increase",
+ threshold_percentage__isnull=False,
+ threshold_percentage__gt=0,
+ )
+ | Q(
+ threshold_type__in=("absolute_value", "absolute_increase"),
+ threshold_value__isnull=False,
+ threshold_value__gte=0,
+ )
+ ),
+ name="billing_alert_threshold_configuration_valid",
+ ),
+ ]
+
+ @property
+ def execution_team_id(self) -> int:
+ if self.team_id is None:
+ raise ValueError("Billing alert does not have an execution team.")
+ return cast(int, self.team_id)
+
+ def __str__(self) -> str:
+ return f"{self.name} ({self.organization_id})"
+
+ def clean(self) -> None:
+ super().clean()
+
+ 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()
+ )
+ 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."})
+
+
+class BillingAlertEvaluationClaim(UUIDModel):
+ class Status(models.TextChoices):
+ PENDING = "pending", "Pending"
+ EVALUATING = "evaluating", "Evaluating"
+ RETRYABLE = "retryable", "Retryable"
+ COMPLETED = "completed", "Completed"
+ SUPERSEDED = "superseded", "Superseded"
+
+ alert = models.ForeignKey(BillingAlertConfiguration, on_delete=models.CASCADE, related_name="evaluation_claims")
+ evaluation_date = models.DateField()
+ configuration_revision = models.PositiveIntegerField()
+ delivery_uuid = models.UUIDField(default=uuid7, unique=True, editable=False)
+ status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)
+ lease_expires_at = models.DateTimeField(null=True, blank=True)
+ next_retry_at = models.DateTimeField(null=True, blank=True)
+ attempt_count = models.PositiveIntegerField(default=0)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ db_table = "billing_alerts_evaluation_claim"
+ constraints = [
+ models.UniqueConstraint(
+ fields=["alert", "evaluation_date", "configuration_revision"],
+ name="unique_billing_alert_evaluation_claim",
+ )
+ ]
+ indexes = [
+ models.Index(fields=["status", "next_retry_at"], name="billing_claim_retry_idx"),
+ ]
+
+ @property
+ def organization_id(self) -> UUID:
+ return self.alert.organization_id
+
+
+class BillingAlertEvent(UUIDModel):
+ class Source(models.TextChoices):
+ SCHEDULED = "scheduled", "Scheduled"
+ MANUAL = "manual", "Manual"
+
+ class Kind(models.TextChoices):
+ CHECK = "check", "Check"
+ FIRING = "firing", "Firing"
+ RESOLVED = "resolved", "Resolved"
+ ERRORED = "errored", "Errored"
+ BROKEN_CONFIG = "broken_config", "Broken config"
+
+ claim = models.ForeignKey(BillingAlertEvaluationClaim, on_delete=models.CASCADE, related_name="attempts")
+ # Preserve the original execution team ID as audit history after that team is deleted.
+ team = models.ForeignKey("posthog.Team", db_constraint=False, on_delete=models.DO_NOTHING, related_name="+")
+ kind = models.CharField(max_length=32, choices=Kind.choices, default=Kind.CHECK)
+ source = models.CharField(max_length=16, choices=Source.choices)
+ attempt_number = models.PositiveIntegerField()
+
+ created_at = models.DateTimeField(auto_now_add=True)
+ period_start = models.DateTimeField(null=True, blank=True)
+ period_end = models.DateTimeField(null=True, blank=True)
+
+ metric = models.CharField(max_length=20, choices=BillingAlertConfiguration.Metric.choices)
+ current_value = models.DecimalField(max_digits=20, decimal_places=6, null=True, blank=True)
+ baseline_value = models.DecimalField(max_digits=20, decimal_places=6, null=True, blank=True)
+ absolute_delta = models.DecimalField(max_digits=20, decimal_places=6, null=True, blank=True)
+ relative_delta_percentage = models.DecimalField(max_digits=28, decimal_places=6, null=True, blank=True)
+ threshold_value_snapshot = models.DecimalField(max_digits=20, decimal_places=6, null=True, blank=True)
+ threshold_percentage_snapshot = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True)
+ minimum_value_snapshot = models.DecimalField(max_digits=20, decimal_places=6, null=True, blank=True)
+ threshold_breached = models.BooleanField(default=False)
+
+ state_before = models.CharField(
+ max_length=20, choices=BillingAlertConfiguration.State.choices, null=True, blank=True
+ )
+ state_after = models.CharField(
+ max_length=20, choices=BillingAlertConfiguration.State.choices, null=True, blank=True
+ )
+ notification_sent_at = models.DateTimeField(null=True, blank=True)
+ targets_notified = models.JSONField(default=dict)
+
+ query_duration_ms = models.PositiveIntegerField(null=True, blank=True)
+ error_code = models.CharField(max_length=80, null=True, blank=True)
+ error_message = models.TextField(null=True, blank=True)
+ is_transient_error = models.BooleanField(default=False)
+
+ reason = models.TextField(blank=True)
+ payload = models.JSONField(default=dict)
+
+ class Meta:
+ db_table = "billing_alerts_event"
+ indexes = [
+ models.Index(fields=["team", "-created_at"], name="billing_event_team_ts_idx"),
+ ]
+ constraints = [
+ models.UniqueConstraint(
+ fields=["claim", "attempt_number"],
+ name="unique_billing_alert_evaluation_attempt",
+ )
+ ]
+
+ @property
+ def alert(self) -> BillingAlertConfiguration:
+ return self.claim.alert
+
+ @property
+ def alert_id(self) -> UUID:
+ return self.claim.alert_id
+
+ @property
+ def organization_id(self) -> UUID:
+ return self.claim.organization_id
+
+ @property
+ def evaluation_date(self) -> date:
+ return self.claim.evaluation_date
diff --git a/products/billing_alerts/backend/team_lifecycle.py b/products/billing_alerts/backend/team_lifecycle.py
new file mode 100644
index 000000000000..bd7d7b895c6c
--- /dev/null
+++ b/products/billing_alerts/backend/team_lifecycle.py
@@ -0,0 +1,36 @@
+from __future__ import annotations
+
+from django.db import connections
+from django.db.models import F
+from django.db.models.signals import pre_delete
+from django.dispatch import receiver
+from django.utils import timezone
+
+from posthog.models.team.team import Team
+
+from products.billing_alerts.backend.models import BillingAlertConfiguration
+
+
+@receiver(pre_delete, sender=Team, dispatch_uid="billing_alerts_rehome_before_team_delete")
+def disable_billing_alerts_before_team_delete(
+ sender: type[Team],
+ instance: Team,
+ using: str,
+ **kwargs: object,
+) -> None:
+ """Skip quietly when this receiver's code is deployed before its migration has run."""
+ table_name = BillingAlertConfiguration._meta.db_table
+ 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(),
+ )
diff --git a/products/billing_alerts/backend/test/test_models.py b/products/billing_alerts/backend/test/test_models.py
new file mode 100644
index 000000000000..26f56526f3d1
--- /dev/null
+++ b/products/billing_alerts/backend/test/test_models.py
@@ -0,0 +1,135 @@
+from datetime import UTC, date, datetime
+from decimal import Decimal
+
+import pytest
+
+from django.core.exceptions import ValidationError
+
+from posthog.models import Organization, Team
+
+from products.billing_alerts.backend.models import (
+ BillingAlertConfiguration,
+ BillingAlertEvaluationClaim,
+ BillingAlertEvent,
+)
+
+
+def test_relative_delta_percentage_supports_full_value_range() -> None:
+ field = BillingAlertEvent._meta.get_field("relative_delta_percentage")
+
+ assert field.max_digits == 28
+ assert field.decimal_places == 6
+
+
+def test_scheduler_index_matches_nulls_first_due_ordering() -> None:
+ index = next(
+ index for index in BillingAlertConfiguration._meta.indexes if index.name == "billing_alert_scheduler_idx"
+ )
+
+ assert index.expressions[0].name == "enabled"
+ assert index.expressions[1].expression.name == "next_check_at"
+ assert index.expressions[1].nulls_first is True
+
+
+def test_organization_deletion_cascades_all_billing_alert_rows() -> None:
+ organization = Organization.objects.create(name="Acme")
+ team = Team.objects.create(organization=organization, name="Default")
+ alert = BillingAlertConfiguration.objects.create(
+ organization=organization,
+ team=team,
+ name="Period spend cap",
+ threshold_value=Decimal("10"),
+ )
+ claim = BillingAlertEvaluationClaim.objects.create(
+ alert=alert,
+ evaluation_date=date(2026, 7, 20),
+ configuration_revision=alert.configuration_revision,
+ )
+ BillingAlertEvent.objects.create(
+ claim=claim,
+ team=team,
+ source=BillingAlertEvent.Source.SCHEDULED,
+ attempt_number=1,
+ metric=alert.metric,
+ )
+
+ organization.delete()
+
+ assert BillingAlertConfiguration.objects.count() == 0
+ assert BillingAlertEvaluationClaim.objects.count() == 0
+ assert BillingAlertEvent.objects.count() == 0
+
+
+def test_team_deletion_leaves_alert_disabled_and_detached() -> None:
+ organization = Organization.objects.create(name="Acme")
+ team = Team.objects.create(organization=organization, name="Default")
+ alert = BillingAlertConfiguration.objects.create(
+ organization=organization,
+ team=team,
+ name="Spend increase",
+ threshold_value=Decimal("10"),
+ state=BillingAlertConfiguration.State.FIRING,
+ next_check_at=datetime(2026, 7, 21, 12, tzinfo=UTC),
+ pending_evaluation_date=date(2026, 7, 20),
+ )
+
+ team.delete()
+
+ alert.refresh_from_db()
+ assert alert.team_id is None
+ assert alert.enabled is False
+ assert alert.state == BillingAlertConfiguration.State.NOT_FIRING
+ assert alert.configuration_revision == 2
+ assert alert.next_check_at is None
+ assert alert.pending_evaluation_date is None
+
+
+def test_execution_team_must_belong_to_alert_organization() -> None:
+ alert_organization = Organization.objects.create(name="Acme")
+ other_organization = Organization.objects.create(name="Other")
+ other_team = Team.objects.create(organization=other_organization, name="Other team")
+ alert = BillingAlertConfiguration(
+ organization=alert_organization,
+ team=other_team,
+ name="Spend increase",
+ threshold_value=Decimal("10"),
+ )
+
+ with pytest.raises(ValidationError) as error:
+ alert.clean()
+
+ assert error.value.message_dict == {"team": ["Execution team must belong to the billing alert organization."]}
+
+
+def test_event_lineage_is_derived_from_its_claim() -> None:
+ organization = Organization.objects.create(name="Acme")
+ team = Team.objects.create(organization=organization, name="Default")
+ alert = BillingAlertConfiguration.objects.create(
+ organization=organization,
+ team=team,
+ name="Spend increase",
+ threshold_value=Decimal("10"),
+ )
+ claim = BillingAlertEvaluationClaim.objects.create(
+ alert=alert,
+ evaluation_date=date(2026, 7, 20),
+ configuration_revision=alert.configuration_revision,
+ )
+ event = BillingAlertEvent.objects.create(
+ claim=claim,
+ team=team,
+ source=BillingAlertEvent.Source.SCHEDULED,
+ attempt_number=1,
+ metric=alert.metric,
+ )
+
+ assert event.alert_id == alert.id
+ assert event.organization_id == organization.id
+ assert event.evaluation_date == claim.evaluation_date
+ assert {"alert", "organization_id", "evaluation_date"}.isdisjoint(
+ field.name for field in BillingAlertEvent._meta.fields
+ )
diff --git a/products/billing_alerts/package.json b/products/billing_alerts/package.json
new file mode 100644
index 000000000000..d2c2bbd5d878
--- /dev/null
+++ b/products/billing_alerts/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "@posthog/products-billing-alerts",
+ "scripts": {
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short || test $? -eq 5"
+ }
+}
diff --git a/products/billing_alerts/product.yaml b/products/billing_alerts/product.yaml
new file mode 100644
index 000000000000..3e27899339c4
--- /dev/null
+++ b/products/billing_alerts/product.yaml
@@ -0,0 +1,3 @@
+name: Billing alerts
+owners:
+ - team-billing
diff --git a/tach.toml b/tach.toml
index 4fe22a0a0263..8b15ddf3b4c2 100644
--- a/tach.toml
+++ b/tach.toml
@@ -83,6 +83,7 @@ depends_on = [
"products.analytics_platform",
"products.approvals",
"products.batch_exports",
+ "products.billing_alerts",
"products.business_knowledge",
"products.canvas",
"products.cdp",
@@ -494,6 +495,13 @@ depends_on = [
]
layer = "modules"
+[[modules]]
+path = "products.billing_alerts"
+depends_on = [
+ "posthog",
+]
+layer = "modules"
+
[[modules]]
path = "products.managed_migrations"
depends_on = [