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(alerts): backfill insight alert configurations into the platform (#111205)

Jimmy Zhu5f78ff57dad3
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.md
index 136fac4a61f0..9895e9abb9f1 100644
--- a/docs/internal/alerts-platform-temporal.md
+++ b/docs/internal/alerts-platform-temporal.md
@@ -55,7 +55,7 @@ writes a source product's rows. What it does cost is the evaluation queries its
ones the source's own production fleet is already running for the same alerts.
The tick's work is whatever `PlatformAlertConfiguration` rows exist, and nothing creates those on its own:
-`python manage.py backfill_platform_alert_configurations [--team-id N]` is the only writer, and it is manual.
+`python manage.py backfill_platform_alert_configurations [--team-id N]` for logs and `python manage.py backfill_platform_insight_alert_configurations [--team-id N]` for insight are the only writers, and both are manual.
So the order below puts the schedule in place while there is no demand, and load arrives when the backfill
is run, one cohort at a time.
@@ -461,6 +461,32 @@ It is a seed, not a sync: the logs product keeps the control plane, and a later
A second run updates rather than duplicates, because `legacy_configuration_id` carries the row each copy came from.
Each run also copies the logs alert's snooze onto its platform alert row, so a snoozed alert stays silent, and an alert unsnoozed since the last run is unsnoozed here too.
+Insight alerts are copied the same way:
+
+```bash
+python manage.py backfill_platform_insight_alert_configurations
+```
+
+It copies threshold alerts on an hourly or slower cadence only, and skips detector alerts and the real-time and 15-minute cadences.
+Run it only after the evaluation worker's chart sets `CLICKHOUSE_ALERTS_PLATFORM_INSIGHT_USER` and its token file.
+Insight checks tag their queries with `ClickHouseUser.ALERTS_PLATFORM_INSIGHT`, a user of their own, so the parallel run never takes from the per-user budget of the user that production insight alerts query as.
+Without that env the tag resolves to the worker's default user, which other workloads on the same servers already push against its concurrent query limit.
+Logs checks use their own user, `alerts_platform_logs`, on the logs cluster.
+
+Every copy adds ClickHouse load beside production's, so roll it out in steps.
+A full logs backfill hit ClickHouse's per-user concurrent query limit and had to be removed.
+
+1. Copy one internal team with `--team-id`, then a small sample with `--sample-percent`, for example 5. The sample is chosen by alert id, so a rerun copies the same alerts and a larger percentage only adds alerts.
+2. Watch the parallel run's ClickHouse cost in `query_log`: its `client_query_id` starts with `alerts-platform-insight:`.
+3. Watch scheduler lag for `source=insight`, and the `capacity` skip reason on the platform's skipped-check counter. Capacity skips mean ClickHouse refused the query for load.
+4. Widen the sample only while both stay flat. `ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS` caps the concurrent checks whatever the sample size.
+5. Raise that cap from its default of 10 only while the daily count of refused queries, `exception_code = 202` in `query_log`, stays flat for both `alerts_platform_insight` and the user that production insight alerts query as. The first shows the parallel run's own contention. The second shows whether it reaches production through the server-wide limit. Do not size it from per-second concurrency, which overcounts because short queries that run back to back inside one second read as concurrent. Code 202 also covers the server-wide limit, so a rise is a reason to look rather than proof that the cap caused it.
+
+To stop the parallel run, pass `--disable`, with `--team-id` to stop one team.
+It switches the copies off and keeps their rows, state and history. Checks already running finish.
+Running the backfill again turns them back on at the production alert's next due time.
+An hourly alert on the platform checks on a UTC grid, while production checks it at the alert's creation minute, so the two stacks check an hourly alert at different minutes.
+
## Postgres connectivity probe
Each evaluation activity issues one explicit `SELECT 1` and checks for `(1,)` through Django's `default` main writer connection.
diff --git a/products/alerts/backend/management/commands/backfill_platform_insight_alert_configurations.py b/products/alerts/backend/management/commands/backfill_platform_insight_alert_configurations.py
new file mode 100644
index 000000000000..d79c0bd691b5
--- /dev/null
+++ b/products/alerts/backend/management/commands/backfill_platform_insight_alert_configurations.py
@@ -0,0 +1,43 @@
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError
+
+from products.alerts.backend.platform_alert_backfill import (
+ backfill_platform_insight_alert_configurations,
+ disable_platform_insight_alert_configurations,
+)
+
+
+class Command(BaseCommand):
+ help = "Copy insight alert configurations into the shared alert tables for a parallel evaluation."
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("--team-id", type=int, default=None, help="Copy one team's configurations only.")
+ parser.add_argument(
+ "--sample-percent",
+ type=int,
+ default=100,
+ help="Copy only this percentage of alerts, chosen by alert id so a rerun picks the same ones.",
+ )
+ parser.add_argument(
+ "--disable",
+ action="store_true",
+ help="Copy nothing. Switch off the existing insight copies instead, keeping their history.",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ if options["disable"]:
+ if options["sample_percent"] != 100:
+ raise CommandError("--disable switches off every copy in scope and takes no --sample-percent")
+ disabled = disable_platform_insight_alert_configurations(team_id=options["team_id"])
+ self.stdout.write(f"Disabled {disabled}")
+ return
+ try:
+ counts = backfill_platform_insight_alert_configurations(
+ team_id=options["team_id"], sample_percent=options["sample_percent"]
+ )
+ except ValueError as error:
+ raise CommandError(str(error)) from error
+ self.stdout.write(
+ f"Created {counts.created}, updated {counts.updated}, skipped {counts.skipped}, failed {counts.failed}"
+ )
diff --git a/products/alerts/backend/platform_alert_backfill.py b/products/alerts/backend/platform_alert_backfill.py
new file mode 100644
index 000000000000..f4c0bb3e3f53
--- /dev/null
+++ b/products/alerts/backend/platform_alert_backfill.py
@@ -0,0 +1,135 @@
+"""One-way copy of insight alert configurations into the shared alert tables.
+
+The control plane stays with this product: this reads, never writes back, and nothing keeps the
+copy in sync afterwards. Run it again to pick up changes.
+
+`legacy_configuration_id` carries the row each copy came from, so a second run updates rather
+than duplicates, and the platform's evaluation reads the insight and its bound through it.
+"""
+
+from uuid import UUID
+
+import structlog
+
+from posthog.dataclasses import frozen
+from posthog.schema_enums import AlertCalculationInterval
+
+from products.alerts.backend.models.alert import AlertConfiguration
+from products.alerts.backend.platform_source_cycle import is_evaluated_on_the_platform
+from products.alerts_platform.backend.facade.api import disable_configurations, upsert_configuration
+from products.alerts_platform.backend.facade.contracts import SOURCE_CONDITION_KEY, PlatformAlertUpsert, SourceKind
+from products.alerts_platform.backend.facade.enums import PlatformAlertConfigurationRecurrenceUnit as RecurrenceUnit
+
+logger = structlog.get_logger(__name__)
+
+# Minutes for the hourly cadence, a calendar unit for the rest. A calendar unit reads its cadence
+# from the unit, so its minutes only feed the shard offset, which an anchored unit ignores.
+_RECURRENCE: dict[str, tuple[int, str | None]] = {
+ AlertCalculationInterval.HOURLY: (60, None),
+ AlertCalculationInterval.DAILY: (60 * 24, RecurrenceUnit.DAY),
+ AlertCalculationInterval.WEEKLY: (60 * 24 * 7, RecurrenceUnit.WEEK),
+ AlertCalculationInterval.MONTHLY: (60 * 24 * 30, RecurrenceUnit.MONTH),
+}
+
+
+@frozen
+class BackfillCounts:
+ created: int
+ updated: int
+ skipped: int
+ failed: int
+
+
+def _upsert(alert: AlertConfiguration) -> PlatformAlertUpsert | None:
+ """The copy of one alert, or None when the platform does not evaluate it in parallel."""
+ recurrence = _RECURRENCE.get(alert.calculation_interval or "")
+ if recurrence is None or not is_evaluated_on_the_platform(alert):
+ return None
+ check_interval_minutes, recurrence_unit = recurrence
+ return PlatformAlertUpsert(
+ legacy_configuration_id=alert.id,
+ team_id=alert.team_id,
+ name=alert.name,
+ enabled=alert.enabled,
+ source_kind=SourceKind.INSIGHT,
+ source_config={
+ "insight_id": alert.insight_id,
+ SOURCE_CONDITION_KEY: {
+ "threshold": alert.threshold.configuration if alert.threshold else None,
+ "comparison": alert.condition,
+ },
+ },
+ check_interval_minutes=check_interval_minutes,
+ recurrence_unit=recurrence_unit,
+ # The hourly cadence has no anchor here: production fires it at the alert's creation
+ # minute, while sixty minutes on the platform lands on a UTC grid.
+ anchor_time=alert.schedule_start_time if recurrence_unit is not None else None,
+ evaluation_periods=1,
+ datapoints_to_alarm=1,
+ cooldown_minutes=0,
+ schedule_restriction=alert.schedule_restriction,
+ next_check_at=alert.next_check_at,
+ snooze_until=alert.snoozed_until,
+ )
+
+
+def is_sampled(alert_id: UUID, sample_percent: int) -> bool:
+ """Whether an alert falls inside a sample. Decided by its id, so a rerun picks the same alerts
+ and widening the sample only adds alerts."""
+ return alert_id.int % 100 < sample_percent
+
+
+def backfill_platform_insight_alert_configurations(
+ *, team_id: int | None = None, sample_percent: int = 100
+) -> BackfillCounts:
+ """Copies every insight alert the platform evaluates in parallel, or one team's, or a sample.
+
+ Every copy adds ClickHouse load beside production's, so a rollout copies a sample first and
+ widens it while the parallel run's query load stays inside its budget.
+ """
+ if not 1 <= sample_percent <= 100:
+ raise ValueError("sample_percent must be between 1 and 100")
+ source = AlertConfiguration.objects.select_related("threshold").filter(insight__deleted=False)
+ if team_id is not None:
+ source = source.filter(team_id=team_id)
+
+ created = 0
+ updated = 0
+ skipped = 0
+ failed = 0
+ for alert in source.iterator():
+ upsert = _upsert(alert) if is_sampled(alert.id, sample_percent) else None
+ if upsert is None:
+ skipped += 1
+ continue
+ # One alert the copy rejects, such as a start time it cannot parse, must not stop the rest.
+ try:
+ was_created = upsert_configuration(upsert)
+ except Exception:
+ logger.exception("platform_insight_alert_backfill.failed", alert_id=str(alert.id), team_id=alert.team_id)
+ failed += 1
+ continue
+ if was_created:
+ created += 1
+ else:
+ updated += 1
+
+ logger.info(
+ "platform_insight_alert_backfill.complete",
+ created=created,
+ updated=updated,
+ skipped=skipped,
+ failed=failed,
+ team_id=team_id,
+ )
+ return BackfillCounts(created=created, updated=updated, skipped=skipped, failed=failed)
+
+
+def disable_platform_insight_alert_configurations(*, team_id: int | None = None) -> int:
+ """Stops the parallel run for every insight copy, or one team's. Returns how many it stopped.
+
+ The copies stay, with their state and history. Running the backfill again turns them back on.
+ """
+ disabled = disable_configurations(SourceKind.INSIGHT, team_id=team_id)
+ logger.info("platform_insight_alert_backfill.disabled", disabled=disabled, team_id=team_id)
+ return disabled
diff --git a/products/alerts/backend/test/test_platform_alert_backfill.py b/products/alerts/backend/test/test_platform_alert_backfill.py
new file mode 100644
index 000000000000..e927b5e22c1c
--- /dev/null
+++ b/products/alerts/backend/test/test_platform_alert_backfill.py
@@ -0,0 +1,95 @@
+from typing import Any
+from uuid import UUID
+
+from posthog.test.base import APIBaseTest
+
+from posthog.schema import ChartDisplayType, EventsNode, IntervalType, TrendsFilter, TrendsQuery
+
+from posthog.models.scoping import team_scope
+from posthog.schema_enums import AlertCalculationInterval
+
+from products.alerts.backend.models.alert import AlertConfiguration, Threshold
+from products.alerts.backend.platform_alert_backfill import (
+ backfill_platform_insight_alert_configurations,
+ disable_platform_insight_alert_configurations,
+)
+from products.alerts_platform.backend.facade.api import list_configurations
+from products.alerts_platform.backend.facade.contracts import SourceKind
+from products.product_analytics.backend.facade.models import Insight
+
+THRESHOLD = {"type": "absolute", "bounds": {"upper": 100.0}}
+
+
+class TestPlatformInsightAlertBackfill(APIBaseTest):
+ def _alert(self, **overrides: Any) -> AlertConfiguration:
+ insight = Insight.objects.create(
+ team=self.team,
+ name="insight",
+ query=TrendsQuery(
+ series=[EventsNode(event="$pageview")],
+ interval=IntervalType.DAY,
+ trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),
+ ).model_dump(),
+ )
+ threshold = Threshold.objects.create(team=self.team, insight=insight, configuration=THRESHOLD)
+ fields: dict[str, Any] = {
+ "team": self.team,
+ "insight": insight,
+ "name": "alert",
+ "calculation_interval": AlertCalculationInterval.DAILY.value,
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "condition": {"type": "absolute_value"},
+ "threshold": threshold,
+ }
+ fields.update(overrides)
+ return AlertConfiguration.objects.create(**fields)
+
+ def _copies(self) -> dict[Any, Any]:
+ with team_scope(self.team.id):
+ page = list_configurations(
+ team_id=self.team.id, source_kinds=[SourceKind.INSIGHT.value], limit=10, offset=0
+ )
+ return {view.legacy_configuration_id: view for view in page.configurations}
+
+ def test_only_hourly_and_slower_threshold_alerts_are_copied_on_their_recurrence(self) -> None:
+ hourly = self._alert(calculation_interval=AlertCalculationInterval.HOURLY.value, schedule_start_time="09:30")
+ daily = self._alert(schedule_start_time="09:30")
+ self._alert(calculation_interval=AlertCalculationInterval.REAL_TIME.value)
+ self._alert(detector_config={"type": "zscore"})
+ unparseable = self._alert(schedule_start_time="25:99")
+
+ counts = backfill_platform_insight_alert_configurations(team_id=self.team.id)
+ again = backfill_platform_insight_alert_configurations(team_id=self.team.id)
+
+ assert (counts.created, counts.skipped, counts.failed, again.created, again.updated) == (2, 2, 1, 0, 2)
+ copies = self._copies()
+ assert unparseable.id not in copies
+ assert {key: (v.check_interval_minutes, v.recurrence_unit, v.anchor_time) for key, v in copies.items()} == {
+ hourly.id: (60, None, None),
+ daily.id: (60 * 24, "day", "09:30"),
+ }
+ assert copies[daily.id].source_config["condition"] == {
+ "threshold": THRESHOLD,
+ "comparison": {"type": "absolute_value"},
+ }
+
+ def test_a_sample_copies_the_same_alerts_on_every_run_and_widening_it_only_adds(self) -> None:
+ inside = self._alert(id=UUID(int=5))
+ outside = self._alert(id=UUID(int=50))
+
+ backfill_platform_insight_alert_configurations(team_id=self.team.id, sample_percent=10)
+ assert set(self._copies()) == {inside.id}
+
+ backfill_platform_insight_alert_configurations(team_id=self.team.id, sample_percent=60)
+ assert set(self._copies()) == {inside.id, outside.id}
+
+ def test_disabling_stops_every_copy_and_a_rerun_turns_them_back_on(self) -> None:
+ self._alert()
+ self._alert()
+ backfill_platform_insight_alert_configurations(team_id=self.team.id)
+
+ assert disable_platform_insight_alert_configurations(team_id=self.team.id) == 2
+ assert {view.enabled for view in self._copies().values()} == {False}
+
+ backfill_platform_insight_alert_configurations(team_id=self.team.id)
+ assert {view.enabled for view in self._copies().values()} == {True}
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.py
index ab1fb0acabfc..75253874acc4 100644
--- a/products/alerts_platform/backend/facade/api.py
+++ b/products/alerts_platform/backend/facade/api.py
@@ -17,6 +17,7 @@ from products.alerts_platform.backend.facade.contracts import (
PlatformAlertConfigurationView,
PlatformAlertOutcome,
PlatformAlertUpsert,
+ SourceKind,
)
from products.alerts_platform.backend.logic import platform_lifecycle, platform_reads
@@ -39,10 +40,15 @@ def slot_of(next_check_at: datetime | None, cutoff: datetime) -> str:
def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:
- """Copy one of a source's own configurations in. True when the row changed."""
+ """Copy one of a source's own configurations in. True when it created the row."""
return platform_lifecycle.upsert_configuration(upsert)
+def disable_configurations(source_kind: SourceKind, *, team_id: int | None = None) -> int:
+ """Switch off a source's copies, or one team's. Returns how many it switched off."""
+ return platform_lifecycle.disable_configurations(source_kind.value, team_id=team_id)
+
+
def list_configurations(
*, team_id: int, source_kinds: Sequence[str], limit: int, offset: int
) -> PlatformAlertConfigurationPage:
diff --git a/products/alerts_platform/backend/facade/enums.py b/products/alerts_platform/backend/facade/enums.py
index 238871970cf5..b63c6a421e68 100644
--- a/products/alerts_platform/backend/facade/enums.py
+++ b/products/alerts_platform/backend/facade/enums.py
@@ -12,6 +12,7 @@ class PlatformAlertConfigurationSourceKind(LabeledStrEnum):
"""The product whose data an alert evaluates."""
LOGS = "logs", "Logs"
+ INSIGHT = "insight", "Insight"
class PlatformAlertState(LabeledStrEnum):
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index 5d7df371556f..cd495650a32b 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -319,3 +319,16 @@ def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:
alert.snooze_until = upsert.snooze_until
alert.save(update_fields=["snooze_until"])
return created
+
+
+def disable_configurations(source_kind: str, *, team_id: int | None = None) -> int:
+ """Switches off a source's copies, or one team's, and returns how many it switched off.
+
+ Rows, state and history stay, so a comparison can still read what ran. Discovery and the batch
+ read both skip a disabled row, so no new check starts after this. Checks already running finish.
+ """
+ # Cross-team on purpose, for an operator stopping a whole source at once.
+ rows = PlatformAlertConfiguration.objects.unscoped().filter(source_kind=source_kind, enabled=True)
+ if team_id is not None:
+ rows = rows.filter(team_id=team_id)
+ return rows.update(enabled=False)
diff --git a/products/alerts_platform/backend/migrations/0006_source_kind_choices.py b/products/alerts_platform/backend/migrations/0006_source_kind_choices.py
new file mode 100644
index 000000000000..1f995492a9eb
--- /dev/null
+++ b/products/alerts_platform/backend/migrations/0006_source_kind_choices.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.17 on 2026-10-02 23:12
+
+from django.db import migrations, models
+
+import products.alerts_platform.backend.models.platform_alert
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("alerts_platform", "0005_threshold_into_source_config"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="platformalertconfiguration",
+ name="source_kind",
+ field=models.CharField(
+ choices=products.alerts_platform.backend.models.platform_alert.source_kind_choices,
+ max_length=32,
+ ),
+ ),
+ ]
diff --git a/products/alerts_platform/backend/migrations/max_migration.txt b/products/alerts_platform/backend/migrations/max_migration.txt
index 631c1b241ca1..e98e35718399 100644
--- a/products/alerts_platform/backend/migrations/max_migration.txt
+++ b/products/alerts_platform/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0005_threshold_into_source_config
+0006_source_kind_choices
diff --git a/products/alerts_platform/backend/models/platform_alert.py b/products/alerts_platform/backend/models/platform_alert.py
index 45a30044df9e..495619dcf775 100644
--- a/products/alerts_platform/backend/models/platform_alert.py
+++ b/products/alerts_platform/backend/models/platform_alert.py
@@ -20,6 +20,12 @@ from products.alerts_platform.backend.facade.enums import (
)
+# nosemgrep: tuple-return-prefer-dataclass -- Django's `choices` contract is (value, label) pairs.
+def source_kind_choices() -> list[tuple[str, str]]:
+ # A callable, so a new source does not write a state-only migration for its choice.
+ return PlatformAlertConfigurationSourceKind.choices
+
+
class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDModel):
"""What to evaluate, how often, and against what bound.
@@ -45,7 +51,7 @@ class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDModel):
name = models.CharField(max_length=255)
enabled = models.BooleanField(default=True, db_default=True)
- source_kind = models.CharField(max_length=32, choices=SourceKind.choices)
+ source_kind = models.CharField(max_length=32, choices=source_kind_choices)
source_config = models.JSONField(default=dict)
# Retired, because a source keeps its bound in `source_config["condition"]`. Nothing reads these.
diff --git a/products/alerts_platform/backend/presentation/views/platform_alert.py b/products/alerts_platform/backend/presentation/views/platform_alert.py
index 96ed6c93be3a..cb35ea51ace3 100644
--- a/products/alerts_platform/backend/presentation/views/platform_alert.py
+++ b/products/alerts_platform/backend/presentation/views/platform_alert.py
@@ -124,6 +124,11 @@ SOURCE_KIND_RESOURCE: dict[str, APIScopeObject] = {
PlatformAlertConfigurationSourceKind.LOGS.value: "logs",
}
+# Kinds the read API does not serve. An insight copy shows its insight's bound and firing state,
+# and a reader can hold access to insights in general but not to that insight. This product
+# cannot check access to one insight, so the copies stay out of the API until it can.
+UNSERVED_SOURCE_KINDS: frozenset[str] = frozenset({PlatformAlertConfigurationSourceKind.INSIGHT.value})
+
class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
scope_object = "alert"
diff --git a/products/alerts_platform/backend/tests/api/test_platform_alert.py b/products/alerts_platform/backend/tests/api/test_platform_alert.py
index a2a042cbc9a9..25fb8c680518 100644
--- a/products/alerts_platform/backend/tests/api/test_platform_alert.py
+++ b/products/alerts_platform/backend/tests/api/test_platform_alert.py
@@ -21,13 +21,17 @@ from products.alerts_platform.backend.models import PlatformAlert, PlatformAlert
class TestPlatformAlertAPI(APIBaseTest):
def _create_configuration(
- self, team: Team, name: str, legacy_configuration_id: UUID | None = None
+ self,
+ team: Team,
+ name: str,
+ legacy_configuration_id: UUID | None = None,
+ source_kind: str = PlatformAlertConfiguration.SourceKind.LOGS,
) -> PlatformAlertConfiguration:
with team_scope(team.id):
return PlatformAlertConfiguration.objects.create(
team=team,
name=name,
- source_kind=PlatformAlertConfiguration.SourceKind.LOGS,
+ source_kind=source_kind,
source_config={"service": "api"},
check_interval_minutes=10,
legacy_configuration_id=legacy_configuration_id,
@@ -103,16 +107,17 @@ class TestPlatformAlertAPI(APIBaseTest):
@parameterized.expand(
[
- ("member_without_logs_access", None, False),
- ("key_without_logs_scope", ["alert:read"], False),
- ("key_with_logs_scope", ["alert:read", "logs:read"], True),
+ ("logs_member_without_access", "logs", None, False),
+ ("logs_key_without_scope", "logs", ["alert:read"], False),
+ ("logs_key_with_scope", "logs", ["alert:read", "logs:read"], True),
+ ("insight_key_with_scope", "insight", ["alert:read", "insight:read"], False),
]
)
- def test_logs_configurations_need_logs_read_access(
- self, _name: str, key_scopes: list[str] | None, visible: bool
+ def test_a_configuration_needs_read_access_to_its_source_product(
+ self, _name: str, source_kind: str, key_scopes: list[str] | None, visible: bool
) -> None:
self._set_flag(True)
- configuration = self._create_configuration(self.team, "API errors")
+ configuration = self._create_configuration(self.team, "API errors", source_kind=source_kind)
if key_scopes is None:
self.organization.available_product_features = [
{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
@@ -121,7 +126,7 @@ class TestPlatformAlertAPI(APIBaseTest):
member = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
AccessControl.objects.create(
team=self.team,
- resource="logs",
+ resource=source_kind,
resource_id=None,
access_level="none",
organization_member=OrganizationMembership.objects.get(user=member, organization=self.organization),
diff --git a/products/alerts_platform/backend/tests/test_comparison_platform_history.py b/products/alerts_platform/backend/tests/test_comparison_platform_history.py
index 2d3a606a39fe..9fc8a9e1aa40 100644
--- a/products/alerts_platform/backend/tests/test_comparison_platform_history.py
+++ b/products/alerts_platform/backend/tests/test_comparison_platform_history.py
@@ -3,8 +3,10 @@ from uuid import uuid4
import pytest
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from unittest.mock import patch
from posthog.clickhouse.client import sync_execute
+from posthog.enums import LabeledStrEnum
from posthog.models.scoping import team_scope
from products.alerts_platform.backend.comparison.platform_history import (
@@ -25,6 +27,10 @@ def _key(window_end: str) -> str:
return f"slot:{OCCURRED_AT.isoformat()}|window:{window_end}"
+class _LogsOnlySourceKind(LabeledStrEnum):
+ LOGS = "logs", "Logs"
+
+
class TestReadPlatformChecks(ClickhouseTestMixin, APIBaseTest):
def _configuration(self, **overrides) -> PlatformAlertConfiguration:
with team_scope(self.team.id):
@@ -119,7 +125,12 @@ class TestReadPlatformChecks(ClickhouseTestMixin, APIBaseTest):
# the first insight comparison concludes the parallel run is quiet.
since, until = WINDOW
- with pytest.raises(UnregisteredSource):
+ # Every contract kind is registered today, so the model is narrowed to logs to stand in for
+ # the next source whose contract member lands before its model choice.
+ with (
+ patch.object(PlatformAlertConfiguration, "SourceKind", _LogsOnlySourceKind),
+ pytest.raises(UnregisteredSource),
+ ):
read_platform_checks(team_id=self.team.id, source=SourceKind.INSIGHT, since=since, until=until)
def test_only_teams_holding_a_configuration_for_the_source_are_worth_sweeping(self) -> None:
diff --git a/products/alerts_platform/backend/tests/test_source_kinds.py b/products/alerts_platform/backend/tests/test_source_kinds.py
index 769a86d51d7d..dd2620e01c32 100644
--- a/products/alerts_platform/backend/tests/test_source_kinds.py
+++ b/products/alerts_platform/backend/tests/test_source_kinds.py
@@ -1,6 +1,9 @@
from products.alerts_platform.backend.facade.contracts import SourceKind
from products.alerts_platform.backend.facade.enums import PlatformAlertConfigurationSourceKind
-from products.alerts_platform.backend.presentation.views.platform_alert import SOURCE_KIND_RESOURCE
+from products.alerts_platform.backend.presentation.views.platform_alert import (
+ SOURCE_KIND_RESOURCE,
+ UNSERVED_SOURCE_KINDS,
+)
def test_a_storable_source_kind_is_one_the_contract_names() -> None:
@@ -12,4 +15,7 @@ def test_a_storable_source_kind_is_one_the_contract_names() -> None:
def test_every_source_kind_names_the_resource_that_gates_reading_it() -> None:
# A kind absent from the map never enters `readable`, so its configurations are missing from
# the read API with nothing raised to say why.
- assert {kind.value for kind in PlatformAlertConfigurationSourceKind} == set(SOURCE_KIND_RESOURCE)
+ assert {kind.value for kind in PlatformAlertConfigurationSourceKind} == set(
+ SOURCE_KIND_RESOURCE
+ ) | UNSERVED_SOURCE_KINDS
+ assert not set(SOURCE_KIND_RESOURCE) & UNSERVED_SOURCE_KINDS
diff --git a/products/alerts_platform/frontend/generated/api.schemas.ts b/products/alerts_platform/frontend/generated/api.schemas.ts
index 06f4fe09ed34..fdf9bdbd5f26 100644
--- a/products/alerts_platform/frontend/generated/api.schemas.ts
+++ b/products/alerts_platform/frontend/generated/api.schemas.ts
@@ -9,12 +9,14 @@
*/
/**
* * `logs` - Logs
+ * * `insight` - Insight
*/
export type PlatformAlertConfigurationSourceKindEnumApi =
(typeof PlatformAlertConfigurationSourceKindEnumApi)[keyof typeof PlatformAlertConfigurationSourceKindEnumApi]
export const PlatformAlertConfigurationSourceKindEnumApi = {
Logs: 'logs',
+ Insight: 'insight',
} as const
/**
@@ -104,7 +106,8 @@ export interface PlatformAlertConfigurationApi {
readonly enabled: boolean
/** Product whose data the alert evaluates.
*
- * * `logs` - Logs */
+ * * `logs` - Logs
+ * * `insight` - Insight */
readonly source_kind: PlatformAlertConfigurationSourceKindEnumApi
/** Source-specific settings. The shape depends on source_kind. The bound the alert is evaluated against is under the condition key. */
readonly source_config: PlatformAlertConfigurationApiSourceConfig
diff --git a/products/alerts_platform/frontend/generated/api.zod.schemas.ts b/products/alerts_platform/frontend/generated/api.zod.schemas.ts
index 64f9f51b9a32..89c48c74605d 100644
--- a/products/alerts_platform/frontend/generated/api.zod.schemas.ts
+++ b/products/alerts_platform/frontend/generated/api.zod.schemas.ts
@@ -9,7 +9,9 @@
*/
import { z as zod } from 'zod'
-export const PlatformAlertConfigurationSourceKindEnumApi = zod.enum(['logs']).describe('\* `logs` - Logs')
+export const PlatformAlertConfigurationSourceKindEnumApi = zod
+ .enum(['logs', 'insight'])
+ .describe('\* `logs` - Logs\n\* `insight` - Insight')
export type PlatformAlertConfigurationSourceKindEnumApi = zod.input<typeof PlatformAlertConfigurationSourceKindEnumApi>
export type PlatformAlertConfigurationSourceKindEnumApiOutput = zod.output<
@@ -107,9 +109,9 @@ export const PlatformAlertConfigurationApi = zod.object({
name: zod.string().describe('Human-readable name of the alert.'),
enabled: zod.boolean().describe('Whether the alert is evaluated on schedule.'),
source_kind: zod
- .enum(['logs'])
- .describe('\* `logs` - Logs')
- .describe('Product whose data the alert evaluates.\n\n\* `logs` - Logs'),
+ .enum(['logs', 'insight'])
+ .describe('\* `logs` - Logs\n\* `insight` - Insight')
+ .describe('Product whose data the alert evaluates.\n\n\* `logs` - Logs\n\* `insight` - Insight'),
source_config: zod
.record(zod.string(), zod.unknown())
.describe(
@@ -224,9 +226,9 @@ export const PaginatedPlatformAlertConfigurationListApi = zod.object({
name: zod.string().describe('Human-readable name of the alert.'),
enabled: zod.boolean().describe('Whether the alert is evaluated on schedule.'),
source_kind: zod
- .enum(['logs'])
- .describe('\* `logs` - Logs')
- .describe('Product whose data the alert evaluates.\n\n\* `logs` - Logs'),
+ .enum(['logs', 'insight'])
+ .describe('\* `logs` - Logs\n\* `insight` - Insight')
+ .describe('Product whose data the alert evaluates.\n\n\* `logs` - Logs\n\* `insight` - Insight'),
source_config: zod
.record(zod.string(), zod.unknown())
.describe(
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 03ce83769998..cb2d014503cc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -69484,12 +69484,14 @@ export namespace Schemas {
/**
* * `logs` - Logs
+ * * `insight` - Insight
*/
export type PlatformAlertConfigurationSourceKindEnum = typeof PlatformAlertConfigurationSourceKindEnum[keyof typeof PlatformAlertConfigurationSourceKindEnum];
export const PlatformAlertConfigurationSourceKindEnum = {
Logs: 'logs',
+ Insight: 'insight',
} as const;
export interface PlatformAlert {
@@ -69536,7 +69538,8 @@ export namespace Schemas {
readonly enabled: boolean;
/** Product whose data the alert evaluates.
*
- * * `logs` - Logs */
+ * * `logs` - Logs
+ * * `insight` - Insight */
readonly source_kind: PlatformAlertConfigurationSourceKindEnum;
/** Source-specific settings. The shape depends on source_kind. The bound the alert is evaluated against is under the condition key. */
readonly source_config: PlatformAlertConfigurationSourceConfig;