:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(alerts): target named alerts and count deferred platform work (#114800)
Jimmy Zhue93431cf1be3
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.mdindex 93ae931a75f2..afdbb50db1cf 100644--- a/docs/internal/alerts-platform-temporal.md+++ b/docs/internal/alerts-platform-temporal.md@@ -438,15 +438,19 @@ The path emits through Temporal's own meter, so every series carries the worker,the runtime attaches. `products/alerts_platform/backend/temporal/metrics.py` holds them and a source reaches them through`facade/platform_metrics.py`.-| Metric | What it answers |-| --------------------------------------------------------- | ----------------------------------------------------------- |-| `alerts_platform_checks_total{source,outcome}` | How many checks the platform decided, and what they decided |-| `alerts_platform_state_transitions_total{source,from,to}` | Which transitions it reached |-| `alerts_platform_deliveries_previewed_total{source}` | How many deliveries it recorded instead of sending |-| `alerts_platform_deliveries_deferred_total{source}` | How many the payload bound left for a later tick |-| `alerts_platform_outcomes_recorded_total` | How many decisions reached the tables |-| `alerts_platform_batch_duration_ms{source}` | What one batch key costs |-| `alerts_platform_scheduler_lag_ms{source}` | How far past its due time a check was evaluated |+| Metric | What it answers |+| --------------------------------------------------------- | ----------------------------------------------------------------- |+| `alerts_platform_checks_total{source,outcome}` | How many checks the platform decided, and what they decided |+| `alerts_platform_state_transitions_total{source,from,to}` | Which transitions it reached |+| `alerts_platform_deliveries_previewed_total{source}` | How many deliveries it recorded instead of sending |+| `alerts_platform_deliveries_deferred_total{source}` | How many the payload bound left for a later tick |+| `alerts_platform_outcomes_recorded_total` | How many decisions reached the tables |+| `alerts_platform_batch_duration_ms{source}` | What one batch key costs |+| `alerts_platform_scheduler_lag_ms{source}` | How far past its due time a check was evaluated |+| `alerts_platform_discovery_omitted_total{source}` | How many due batch keys a tick left out under the discovery limit |+| `alerts_platform_checks_deferred_total{source}` | How many checks a full evaluation pool turned away |+| `alerts_platform_checks_unfinished_total{source}` | How many admitted insight checks reached no outcome |+| `alerts_platform_history_rows_dropped_total{source}` | How many check rows a failed history write lost |Histogram buckets are registered in `posthog/temporal/common/worker.py`; a histogram missing from`ALERTS_PLATFORM_LATENCY_HISTOGRAM_METRICS` gets Prometheus defaults instead.@@ -495,6 +499,7 @@ A full logs backfill hit ClickHouse's per-user concurrent query limit and had to5. 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 either parallel run, logs or insight, pass `--disable` to its backfill, with `--team-id` to stop one team.+Pass `--ids-file` to either backfill, with one alert id per line, to copy only those alerts or, with `--disable`, to switch only their copies off. A rollout uses it to retire the alerts a comparison has enough evidence for and spend the load on the ones it still lacks.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.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.pyindex d79c0bd691b5..c63aa2fbca17 100644--- a/products/alerts/backend/management/commands/backfill_platform_insight_alert_configurations.py+++ b/products/alerts/backend/management/commands/backfill_platform_insight_alert_configurations.py@@ -1,43 +1,25 @@-from typing import Any--from django.core.management.base import BaseCommand, CommandError+from collections.abc import Collection+from uuid import UUIDfrom products.alerts.backend.platform_alert_backfill import (+ BackfillCounts,backfill_platform_insight_alert_configurations,disable_platform_insight_alert_configurations,)+from products.alerts_platform.backend.facade.backfill_command import PlatformBackfillCommand-class Command(BaseCommand):+class Command(PlatformBackfillCommand):help = "Copy insight alert configurations into the shared alert tables for a parallel evaluation."+ source_name = "insight"+ sample_unit = "alert"- 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 backfill(+ self, *, team_id: int | None, sample_percent: int, alert_ids: Collection[UUID] | None+ ) -> BackfillCounts:+ return backfill_platform_insight_alert_configurations(+ team_id=team_id, sample_percent=sample_percent, alert_ids=alert_ids)- 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}"- )+ def disable(self, *, team_id: int | None, alert_ids: Collection[UUID] | None) -> int:+ return disable_platform_insight_alert_configurations(team_id=team_id, alert_ids=alert_ids)diff --git a/products/alerts/backend/platform_alert_backfill.py b/products/alerts/backend/platform_alert_backfill.pyindex 0d288bb0046d..99a675e688fb 100644--- a/products/alerts/backend/platform_alert_backfill.py+++ b/products/alerts/backend/platform_alert_backfill.py@@ -7,6 +7,7 @@ copy in sync afterwards. Run it again to pick up changes.than duplicates, and the platform's evaluation reads the insight and its bound through it."""+from collections.abc import Collectionfrom uuid import UUIDimport structlog@@ -81,18 +82,21 @@ def is_sampled(alert_id: UUID, sample_percent: int) -> bool:def backfill_platform_insight_alert_configurations(- *, team_id: int | None = None, sample_percent: int = 100+ *, team_id: int | None = None, sample_percent: int = 100, alert_ids: Collection[UUID] | None = None) -> BackfillCounts:- """Copies every insight alert the platform evaluates in parallel, or one team's, or a sample.+ """Copies every insight alert the platform evaluates in parallel, or one team's, or a sample, or named alerts.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.+ widens it while the parallel run's query load stays inside its budget. Named alerts let a+ rollout copy the ones a comparison still lacks evidence for."""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)+ if alert_ids is not None:+ source = source.filter(id__in=alert_ids)created = 0updated = 0@@ -126,11 +130,13 @@ def backfill_platform_insight_alert_configurations(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.+def disable_platform_insight_alert_configurations(+ *, team_id: int | None = None, alert_ids: Collection[UUID] | None = None+) -> int:+ """Stops the parallel run for every insight copy, or one team's, or named alerts'. 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)+ disabled = disable_configurations(SourceKind.INSIGHT, team_id=team_id, legacy_configuration_ids=alert_ids)logger.info("platform_insight_alert_backfill.disabled", disabled=disabled, team_id=team_id)return disableddiff --git a/products/alerts/backend/platform_source_cycle.py b/products/alerts/backend/platform_source_cycle.pyindex 7e3f4545e83b..4e8002a4f130 100644--- a/products/alerts/backend/platform_source_cycle.py+++ b/products/alerts/backend/platform_source_cycle.py@@ -63,6 +63,7 @@ from products.alerts_platform.backend.facade.lifecycle import ()from products.alerts_platform.backend.facade.platform_metrics import (increment_checks,+ increment_checks_deferred,increment_checks_skipped,increment_state_transition,record_scheduler_lag,@@ -157,6 +158,7 @@ def plan_insight_batch(admitted=len(admitted),deferred=len(candidates) - len(admitted),)+ safe_record(increment_checks_deferred, SourceKind.INSIGHT.value, len(candidates) - len(admitted))return tuple(admitted)diff --git a/products/alerts/backend/temporal/platform_evaluate.py b/products/alerts/backend/temporal/platform_evaluate.pyindex 3bc7697a5a30..ff43359a4b15 100644--- a/products/alerts/backend/temporal/platform_evaluate.py+++ b/products/alerts/backend/temporal/platform_evaluate.py@@ -32,6 +32,7 @@ with workflow.unsafe.imports_passed_through():SourceKind,SourceOutcomeInputs,)+ from products.alerts_platform.backend.facade.platform_metrics import increment_checks_unfinished, safe_recordfrom products.alerts_platform.backend.facade.temporal import source_evaluation_timeout, start_deliveriesPLAN_START_TO_CLOSE = dt.timedelta(seconds=10)@@ -163,6 +164,7 @@ class InsightAlertPlatformEvaluateWorkflow(PostHogWorkflow):workflow.logger.warning("%d of %d platform insight checks reached no outcome", len(settled) - len(outcomes), len(settled))+ safe_record(increment_checks_unfinished, SourceKind.INSIGHT.value, len(settled) - len(outcomes))if not outcomes:return 0diff --git a/products/alerts/backend/test/test_platform_alert_backfill.py b/products/alerts/backend/test/test_platform_alert_backfill.pyindex ef2536a5a0e7..0363d6b4b395 100644--- a/products/alerts/backend/test/test_platform_alert_backfill.py+++ b/products/alerts/backend/test/test_platform_alert_backfill.py@@ -85,6 +85,14 @@ class TestPlatformInsightAlertBackfill(APIBaseTest):backfill_platform_insight_alert_configurations(team_id=self.team.id, sample_percent=60)assert set(self._copies()) == {inside.id, outside.id}+ def test_named_alerts_are_the_only_ones_copied(self) -> None:+ named = self._alert()+ self._alert()++ backfill_platform_insight_alert_configurations(alert_ids=[named.id])++ assert set(self._copies()) == {named.id}+def test_disabling_stops_every_copy_and_a_rerun_turns_them_back_on(self) -> None:self._alert()self._alert()diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.pyindex f948954a3462..c50b0f21f729 100644--- a/products/alerts_platform/backend/facade/api.py+++ b/products/alerts_platform/backend/facade/api.py@@ -70,9 +70,13 @@ def take_ownership(handover: PlatformOwnershipHandover) -> bool:return platform_lifecycle.take_ownership(handover)-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 disable_configurations(+ source_kind: SourceKind, *, team_id: int | None = None, legacy_configuration_ids: Collection[UUID] | None = None+) -> int:+ """Switch off a source's copies, or one team's, or the copies of named source alerts. Returns how many it switched off."""+ return platform_lifecycle.disable_configurations(+ source_kind.value, team_id=team_id, legacy_configuration_ids=legacy_configuration_ids+ )def list_configurations(diff --git a/products/alerts_platform/backend/facade/backfill_command.py b/products/alerts_platform/backend/facade/backfill_command.pynew file mode 100644index 000000000000..a1c33de9955d--- /dev/null+++ b/products/alerts_platform/backend/facade/backfill_command.py@@ -0,0 +1,85 @@+"""The command-line surface a source's backfill shares: which alerts to copy, and how to stop them.++Each source keeps its own command module, so `manage.py` finds it by name, and subclasses this to+supply the copy and the stop.+"""++from collections.abc import Collection+from pathlib import Path+from typing import Any, Protocol+from uuid import UUID++from django.core.management.base import BaseCommand, CommandError+++class BackfillResult(Protocol):+ # Read-only, so a source's frozen counts satisfy it.+ @property+ def created(self) -> int: ...+ @property+ def updated(self) -> int: ...+ @property+ def skipped(self) -> int: ...+ @property+ def failed(self) -> int: ...+++class PlatformBackfillCommand(BaseCommand):+ """`--team-id`, `--sample-percent`, `--ids-file` and `--disable`, the same for every source."""++ source_name: str+ sample_unit: str++ def backfill(+ self, *, team_id: int | None, sample_percent: int, alert_ids: Collection[UUID] | None+ ) -> BackfillResult:+ raise NotImplementedError++ def disable(self, *, team_id: int | None, alert_ids: Collection[UUID] | None) -> int:+ raise NotImplementedError++ 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=f"Copy only this percentage of {self.sample_unit}s, chosen by {self.sample_unit} id so a rerun picks the same ones.",+ )+ parser.add_argument(+ "--ids-file",+ default=None,+ help=f"Copy only the {self.source_name} alerts whose ids this file lists, one per line.",+ )+ parser.add_argument(+ "--disable",+ action="store_true",+ help=f"Copy nothing. Switch off the existing {self.source_name} copies instead, keeping their history.",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ if options["sample_percent"] != 100 and (options["disable"] or options["ids_file"] is not None):+ raise CommandError("--disable and --ids-file name what they act on and take no --sample-percent")+ alert_ids = _alert_ids(options["ids_file"])+ if options["disable"]:+ disabled = self.disable(team_id=options["team_id"], alert_ids=alert_ids)+ self.stdout.write(f"Disabled {disabled}")+ return+ try:+ counts = self.backfill(+ team_id=options["team_id"], sample_percent=options["sample_percent"], alert_ids=alert_ids+ )+ 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}"+ )+++def _alert_ids(path: str | None) -> list[UUID] | None:+ if path is None:+ return None+ try:+ return [UUID(line.strip()) for line in Path(path).read_text().splitlines() if line.strip()]+ except ValueError as error:+ raise CommandError(f"{path} must hold one alert id per line: {error}") from errordiff --git a/products/alerts_platform/backend/facade/platform_metrics.py b/products/alerts_platform/backend/facade/platform_metrics.pyindex 569fe71e9cc9..6e46c1467dfc 100644--- a/products/alerts_platform/backend/facade/platform_metrics.py+++ b/products/alerts_platform/backend/facade/platform_metrics.py@@ -7,7 +7,9 @@ from `facade/temporal.py`, which pulls in the workflow module.from products.alerts_platform.backend.temporal.metrics import (increment_checks,+ increment_checks_deferred,increment_checks_skipped,+ increment_checks_unfinished,increment_deliveries_deferred,increment_history_rows_dropped,increment_notifications_muted,@@ -19,7 +21,9 @@ from products.alerts_platform.backend.temporal.metrics import (__all__ = ["increment_checks",+ "increment_checks_deferred","increment_checks_skipped",+ "increment_checks_unfinished","increment_deliveries_deferred","increment_history_rows_dropped","increment_notifications_muted",diff --git a/products/alerts_platform/backend/logic/platform_alert_events.py b/products/alerts_platform/backend/logic/platform_alert_events.pyindex c538a1abae65..bc3d1ed1b3ab 100644--- a/products/alerts_platform/backend/logic/platform_alert_events.py+++ b/products/alerts_platform/backend/logic/platform_alert_events.py@@ -46,6 +46,8 @@ class PlatformAlertEventRow:"""team_id: int+ # The source whose check this was, so a reader can tell sources apart without a Postgres join.+ source_kind: strconfiguration_id: UUIDalert_id: UUIDgrouping_key: strdiff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.pyindex 004fd650c5c7..76a4ca64b184 100644--- a/products/alerts_platform/backend/logic/platform_lifecycle.py+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py@@ -214,6 +214,7 @@ def _event_row() -> PlatformAlertEventRow:return PlatformAlertEventRow(team_id=configuration.team_id,+ source_kind=configuration.source_kind,configuration_id=configuration.id,alert_id=alert.id,grouping_key=alert.grouping_key,@@ -240,7 +241,8 @@ def _event_row(def _record_history(team_id: int, rows: Sequence[PlatformAlertEventRow]) -> None:recorded = insert_events(team_id, rows)if recorded < len(rows):- safe_record(increment_history_rows_dropped, len(rows) - recorded)+ # One batch holds one source's checks.+ safe_record(increment_history_rows_dropped, rows[0].source_kind, len(rows) - recorded)def _shard_offset_seconds(configuration: PlatformAlertConfiguration, outcome: PlatformAlertOutcome) -> int:@@ -380,6 +382,8 @@ def upsert_configuration(upsert: PlatformAlertUpsert, *, revive: bool = False) -"datapoints_to_alarm": upsert.datapoints_to_alarm,"cooldown_minutes": upsert.cooldown_minutes,"schedule_restriction": upsert.schedule_restriction,+ # Reached by a backfill run, which re-admits a copy an operator switched off.+ "switched_off_at": None,}if (existing is None@@ -418,8 +422,9 @@ def upsert_if_running(upsert: PlatformAlertUpsert, *, revive: bool = False) -> N"""Copies one configuration in when its team already runs that source here.A team runs a source here while any of its copies of that source is enabled. A team the backfill- left out of its sample, or one `disable_configurations` switched off, gets nothing, so a write- in the source never widens a sample or undoes an operator's switch-off.+ left out of its sample, or one `disable_configurations` switched off, gets nothing, and neither+ does a copy an operator switched off by name, so a write in the source never widens a sample or+ undoes an operator's switch-off."""with transaction.atomic():_hold_admission(upsert.source_kind.value, exclusive=False)@@ -428,7 +433,12 @@ def upsert_if_running(upsert: PlatformAlertUpsert, *, revive: bool = False) -> N.filter(source_kind=upsert.source_kind.value, enabled=True).exists())- if running:+ switched_off = (+ PlatformAlertConfiguration.objects.for_team(upsert.team_id)+ .filter(legacy_configuration_id=upsert.legacy_configuration_id, switched_off_at__isnull=False)+ .exists()+ )+ if running and not switched_off:upsert_configuration(upsert, revive=revive)@@ -502,8 +512,11 @@ def take_ownership(handover: PlatformOwnershipHandover) -> bool:return True-def disable_configurations(source_kind: str, *, team_id: int | None = None) -> int:- """Switches off a source's parallel-run copies, or one team's, and returns how many it switched off.+def disable_configurations(+ source_kind: str, *, team_id: int | None = None, legacy_configuration_ids: Collection[UUID] | None = None+) -> int:+ """Switches off a source's parallel-run copies, or one team's, or the copies of named source+ alerts, and returns how many it switched off.Rows, state and history stay, so a comparison can still read what ran. Discovery and the batchread both skip a disabled row, so no new check starts after this. Checks already running finish.@@ -518,4 +531,6 @@ def disable_configurations(source_kind: str, *, team_id: int | None = None) -> i)if team_id is not None:rows = rows.filter(team_id=team_id)- return rows.update(enabled=False)+ if legacy_configuration_ids is not None:+ rows = rows.filter(legacy_configuration_id__in=legacy_configuration_ids)+ return rows.update(enabled=False, switched_off_at=django_timezone.now())diff --git a/products/alerts_platform/backend/migrations/0009_platformalertconfiguration_switched_off_at.py b/products/alerts_platform/backend/migrations/0009_platformalertconfiguration_switched_off_at.pynew file mode 100644index 000000000000..39a45c08956e--- /dev/null+++ b/products/alerts_platform/backend/migrations/0009_platformalertconfiguration_switched_off_at.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.18 on 2026-10-14 16:09++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("alerts_platform", "0008_platformalertconfiguration_owner"),+ ]++ operations = [+ migrations.AddField(+ model_name="platformalertconfiguration",+ name="switched_off_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/products/alerts_platform/backend/migrations/max_migration.txt b/products/alerts_platform/backend/migrations/max_migration.txtindex f59b38c76b53..0265911b9bcb 100644--- a/products/alerts_platform/backend/migrations/max_migration.txt+++ b/products/alerts_platform/backend/migrations/max_migration.txt@@ -1 +1 @@-0008_platformalertconfiguration_owner+0009_platformalertconfiguration_switched_off_atdiff --git a/products/alerts_platform/backend/models/platform_alert.py b/products/alerts_platform/backend/models/platform_alert.pyindex cd099c0e8763..209c22aaf009 100644--- a/products/alerts_platform/backend/models/platform_alert.py+++ b/products/alerts_platform/backend/models/platform_alert.py@@ -79,6 +79,9 @@ class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDModel):# The row this was copied from, so a backfill can run twice and so a comparison can line# an evaluation up against the one the source's own stack produced.legacy_configuration_id = models.UUIDField(null=True, blank=True, unique=True)+ # When an operator switched this copy off. A write in the source never turns such a copy back+ # on, so a rollout that retires a copy keeps it retired. Only a backfill run clears it.+ switched_off_at = models.DateTimeField(null=True, blank=True)# The source's own row records the same owner. Only the cutover and rollback commands write# the two, in one transaction, so each stack can decide from its own row without reading thediff --git a/products/alerts_platform/backend/temporal/metrics.py b/products/alerts_platform/backend/temporal/metrics.pyindex 3120c2d0277f..c0dcecd8963c 100644--- a/products/alerts_platform/backend/temporal/metrics.py+++ b/products/alerts_platform/backend/temporal/metrics.py@@ -73,14 +73,14 @@ def increment_notifications_muted(source: str, reason: str) -> None:).add(1)-def increment_history_rows_dropped(count: int) -> None:+def increment_history_rows_dropped(source: str, count: int) -> None:"""Check rows the platform decided but could not record.The alert's state and schedule are already written when this rises, so the cost is a gap inhistory rather than a lost evaluation. A comparison against a source's own stack reads as adisagreement where the gap falls."""- get_metric_meter().create_counter(+ get_metric_meter({"source": source}).create_counter("alerts_platform_history_rows_dropped_total","Check history rows lost to a failed ClickHouse write",).add(count)@@ -104,6 +104,42 @@ def increment_deliveries_deferred(source: str, count: int) -> None:).add(count)+def increment_discovery_omitted(source: str, count: int) -> None:+ """Batch keys a tick found due and left out under the source's discovery limit.++ They keep their due time, so a later tick takes them. A count that stays above zero means the+ limit is below the demand, and scheduler lag grows for that source.+ """+ get_metric_meter({"source": source}).create_counter(+ "alerts_platform_discovery_omitted_total",+ "Due batch keys a tick left out under the source's discovery limit; the alerts stay due",+ ).add(count)+++def increment_checks_deferred(source: str, count: int) -> None:+ """Checks an evaluation pool turned away because it was full.++ They keep their due time, so this counts work a later tick repeats. A sustained count means the+ pool is the bottleneck rather than ClickHouse.+ """+ get_metric_meter({"source": source}).create_counter(+ "alerts_platform_checks_deferred_total",+ "Checks a full evaluation pool turned away; the alerts stay due",+ ).add(count)+++def increment_checks_unfinished(source: str, count: int) -> None:+ """Admitted checks that reached no outcome, because their activity failed or timed out.++ They keep their due time, so a later tick repeats them. Unlike a skipped check, nothing+ records them anywhere else.+ """+ get_metric_meter({"source": source}).create_counter(+ "alerts_platform_checks_unfinished_total",+ "Admitted checks that reached no outcome; the alerts stay due",+ ).add(count)++def increment_describer_failures(source: str) -> None:"""A source's describer raised, so its alerts went out in the platform's generic wording."""get_metric_meter({"source": source}).create_counter(diff --git a/products/alerts_platform/backend/temporal/workflows.py b/products/alerts_platform/backend/temporal/workflows.pyindex ced760e3a57f..15808bd15943 100644--- a/products/alerts_platform/backend/temporal/workflows.py+++ b/products/alerts_platform/backend/temporal/workflows.py@@ -19,7 +19,11 @@ from posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.errors import NonReportableApplicationError, unwrap_temporal_causefrom posthog.temporal.common.logger import get_write_only_logger-from products.alerts_platform.backend.temporal.metrics import increment_deliveries_previewed, safe_record+from products.alerts_platform.backend.temporal.metrics import (+ increment_deliveries_previewed,+ increment_discovery_omitted,+ safe_record,+)from products.alerts_platform.backend.temporal.outcomes import alerts_platform_record_outcomes_activityLOGGER = get_write_only_logger(__name__)@@ -90,7 +94,11 @@ class AlertsPlatformInputs:@activity.defnasync def alerts_platform_discover_demand_activity(inputs: DemandDiscoveryInputs) -> AlertDemand:- return await database_sync_to_async_pool(discover_demand)(inputs.cutoff, limits_by_source=discovery_limits())+ demand = await database_sync_to_async_pool(discover_demand)(inputs.cutoff, limits_by_source=discovery_limits())+ for source, omitted in demand.omitted_by_source.items():+ if omitted:+ safe_record(increment_discovery_omitted, source.value, omitted)+ return demand@activity.defndiff --git a/products/alerts_platform/backend/tests/test_comparison_platform_history.py b/products/alerts_platform/backend/tests/test_comparison_platform_history.pyindex 9fc8a9e1aa40..21c24c27e7e4 100644--- a/products/alerts_platform/backend/tests/test_comparison_platform_history.py+++ b/products/alerts_platform/backend/tests/test_comparison_platform_history.py@@ -50,6 +50,7 @@ class TestReadPlatformChecks(ClickhouseTestMixin, APIBaseTest):) -> PlatformAlertEventRow:return PlatformAlertEventRow(team_id=self.team.id,+ source_kind="logs",configuration_id=configuration.id,alert_id=overrides.pop("alert_id", uuid4()),grouping_key="",diff --git a/products/alerts_platform/backend/tests/test_platform_alert_events.py b/products/alerts_platform/backend/tests/test_platform_alert_events.pyindex 6d25bbbe187b..b5aa0f61ecfe 100644--- a/products/alerts_platform/backend/tests/test_platform_alert_events.py+++ b/products/alerts_platform/backend/tests/test_platform_alert_events.py@@ -10,6 +10,7 @@ EVALUATION_KEY = "slot:2026-09-16T10:00:00+00:00|window:2026-09-16T09:59:00+00:0def _row(grouping_key: str) -> PlatformAlertEventRow:return PlatformAlertEventRow(team_id=2,+ source_kind="logs",configuration_id=CONFIGURATION_ID,alert_id=uuid4(),grouping_key=grouping_key,diff --git a/products/alerts_platform/backend/tests/test_platform_announcement.py b/products/alerts_platform/backend/tests/test_platform_announcement.pyindex 3df31a5c2bae..05b8c187b35f 100644--- a/products/alerts_platform/backend/tests/test_platform_announcement.py+++ b/products/alerts_platform/backend/tests/test_platform_announcement.py@@ -34,6 +34,7 @@ class TestAnnouncement(ClickhouseTestMixin, APIBaseTest):def _row(self, **overrides) -> PlatformAlertEventRow:fields = {"team_id": self.team.id,+ "source_kind": "logs","configuration_id": self.configuration.id,"alert_id": self.configuration.id,"grouping_key": "",diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.pyindex 429a50f4c5d4..4f377257d035 100644--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py@@ -182,7 +182,7 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):rows = sync_execute("""SELECT kind, previous_state, state, value, alert_name, muted_notification,- JSONExtractInt(condition_snapshot, 'threshold_count'), episode_started_at+ JSONExtractInt(condition_snapshot, 'threshold_count'), episode_started_at, source_kindFROM platform_alert_eventsWHERE team_id = %(team_id)s AND configuration_id = %(configuration_id)s""",@@ -190,7 +190,7 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):)# `insert_events` never raises, so without reading a row back a broken write is invisible.- assert rows == [("firing", "not_firing", "firing", 47.0, "API errors", "fire", 10, self.cutoff)]+ assert rows == [("firing", "not_firing", "firing", 47.0, "API errors", "fire", 10, self.cutoff, "logs")]def test_a_resolve_row_keeps_the_firing_it_ended(self) -> None:# The alert row clears the firing on a resolve, so history is the only place left holdingdiff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.pyindex d1957c5e1d01..f3d40e604944 100644--- a/products/logs/backend/alert_source_cycle.py+++ b/products/logs/backend/alert_source_cycle.py@@ -61,6 +61,7 @@ from products.alerts_platform.backend.facade.lifecycle import ()from products.alerts_platform.backend.facade.platform_metrics import (increment_checks,+ increment_checks_deferred,increment_checks_skipped,increment_deliveries_deferred,increment_notifications_muted,@@ -729,6 +730,7 @@ def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatc)if held_until is None:logger.info("Deferred a platform logs batch over the pool limit", team_id=team_id, slot=slot)+ safe_record(increment_checks_deferred, SourceKind.LOGS.value, len(checks))return SourceBatchEvaluation(outcomes=(), deliveries=(), omitted=len(checks))try:return _evaluate_admitted(team_id, slot, cutoff, checks, started_at=started_at)diff --git a/products/logs/backend/management/commands/backfill_platform_alert_configurations.py b/products/logs/backend/management/commands/backfill_platform_alert_configurations.pyindex 2f400a82479a..ccc1a9739298 100644--- a/products/logs/backend/management/commands/backfill_platform_alert_configurations.py+++ b/products/logs/backend/management/commands/backfill_platform_alert_configurations.py@@ -1,43 +1,26 @@-from typing import Any--from django.core.management.base import BaseCommand, CommandError+from collections.abc import Collection+from uuid import UUID+from products.alerts_platform.backend.facade.backfill_command import PlatformBackfillCommandfrom products.logs.backend.platform_alert_backfill import (+ BackfillCounts,backfill_platform_alert_configurations,disable_platform_alert_configurations,)-class Command(BaseCommand):+class Command(PlatformBackfillCommand):help = "Copy logs alert configurations into the skeleton shared alert tables."+ source_name = "logs"+ # Logs samples whole teams, because one query checks a cohort of a team's alerts.+ sample_unit = "team"- 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 teams, chosen by team id so a rerun picks the same ones.",- )- parser.add_argument(- "--disable",- action="store_true",- help="Copy nothing. Switch off the existing logs copies instead, keeping their history.",+ def backfill(+ self, *, team_id: int | None, sample_percent: int, alert_ids: Collection[UUID] | None+ ) -> BackfillCounts:+ return backfill_platform_alert_configurations(+ team_id=team_id, sample_percent=sample_percent, alert_ids=alert_ids)- 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_alert_configurations(team_id=options["team_id"])- self.stdout.write(f"Disabled {disabled}")- return- try:- counts = backfill_platform_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}"- )+ def disable(self, *, team_id: int | None, alert_ids: Collection[UUID] | None) -> int:+ return disable_platform_alert_configurations(team_id=team_id, alert_ids=alert_ids)diff --git a/products/logs/backend/platform_alert_backfill.py b/products/logs/backend/platform_alert_backfill.pyindex 8a73cac40c68..76cb0e210971 100644--- a/products/logs/backend/platform_alert_backfill.py+++ b/products/logs/backend/platform_alert_backfill.py@@ -9,7 +9,9 @@ logs on the platform.rather than duplicates, and a later comparison can line the two stacks up per alert."""+from collections.abc import Collectionfrom typing import Final+from uuid import UUIDimport structlog@@ -82,17 +84,22 @@ def _is_team_sampled(team_id: int, sample_percent: int) -> bool:return team_id % 100 < sample_percent-def backfill_platform_alert_configurations(*, team_id: int | None = None, sample_percent: int = 100) -> BackfillCounts:- """Copies every logs alert configuration, or one team's, or a sample of teams'.+def backfill_platform_alert_configurations(+ *, team_id: int | None = None, sample_percent: int = 100, alert_ids: Collection[UUID] | None = None+) -> BackfillCounts:+ """Copies every logs alert configuration, or one team's, or a sample of teams', or named alerts.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.+ widens it while the parallel run's query load stays inside its budget. Named alerts let a+ rollout copy the ones a comparison still lacks evidence for."""if not 1 <= sample_percent <= 100:raise ValueError("sample_percent must be between 1 and 100")source = LogsAlertConfiguration.objects.all()if team_id is not None:source = source.filter(team_id=team_id)+ if alert_ids is not None:+ source = source.filter(id__in=alert_ids)created = 0updated = 0@@ -127,12 +134,14 @@ def backfill_platform_alert_configurations(*, team_id: int | None = None, samplereturn BackfillCounts(created=created, updated=updated, skipped=skipped, failed=failed)-def disable_platform_alert_configurations(*, team_id: int | None = None) -> int:- """Stops the parallel run for every logs copy, or one team's. Returns how many it stopped.+def disable_platform_alert_configurations(+ *, team_id: int | None = None, alert_ids: Collection[UUID] | None = None+) -> int:+ """Stops the parallel run for every logs copy, or one team's, or named alerts'. 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.LOGS, team_id=team_id)+ disabled = disable_configurations(SourceKind.LOGS, team_id=team_id, legacy_configuration_ids=alert_ids)logger.info("platform_alert_backfill.disabled", disabled=disabled, team_id=team_id)return disableddiff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.pyindex 49bca12a2896..3d13fafc6b39 100644--- a/products/logs/backend/test/test_alerts_api.py+++ b/products/logs/backend/test/test_alerts_api.py@@ -1,7 +1,7 @@import jsonfrom datetime import UTC, datetime, timedeltafrom typing import Any-from uuid import uuid4+from uuid import UUID, uuid4import pytestimport time_machine@@ -423,6 +423,23 @@ class TestLogsAlertAPI(APIBaseTest):copy = next((view for view in copies if str(view.legacy_configuration_id) == alert_id), None)assert (copy.enabled if copy else None) is copy_enabled+ def test_a_copy_an_operator_retired_by_name_stays_off_when_its_alert_comes_back_on(self) -> None:+ self._create_via_api(name="Already on the platform")+ retired = self._create_via_api(name="Retired by the rollout")+ backfill_platform_alert_configurations(team_id=self.team.id)+ disable_platform_alert_configurations(alert_ids=[UUID(retired["id"])])++ url = f"{self.base_url}{retired['id']}/"+ with self.captureOnCommitCallbacks(execute=True):+ assert self.client.patch(url, {"enabled": False}, format="json").status_code == status.HTTP_200_OK+ assert self.client.patch(url, {"enabled": True}, format="json").status_code == status.HTTP_200_OK++ with team_scope(self.team.id):+ copies = list_configurations(+ team_id=self.team.id, source_kinds=[SourceKind.LOGS.value], limit=10, offset=0+ ).configurations+ assert {str(view.legacy_configuration_id): view.enabled for view in copies}[retired["id"]] is False+def test_a_copy_that_fails_is_handed_to_celery_to_retry(self) -> None:self._create_via_api(name="Already on the platform")backfill_platform_alert_configurations(team_id=self.team.id)diff --git a/products/logs/backend/test/test_logs_platform_alert_backfill.py b/products/logs/backend/test/test_logs_platform_alert_backfill.pyindex 7de5c0a152f2..4a13f4fcef1f 100644--- a/products/logs/backend/test/test_logs_platform_alert_backfill.py+++ b/products/logs/backend/test/test_logs_platform_alert_backfill.py@@ -59,3 +59,13 @@ class TestPlatformLogsAlertBackfill(APIBaseTest):backfill_platform_alert_configurations(team_id=self.team.id)assert {view.enabled for view in self._copies(self.team).values()} == {True}++ def test_named_alerts_are_the_only_ones_copied_and_the_only_ones_switched_off(self) -> None:+ kept, rotated = self._alert(self.team).id, self._alert(self.team, name="Slow requests").id+ self._alert(self.team, name="Not named")++ backfill_platform_alert_configurations(alert_ids=[kept, rotated])+ assert set(self._copies(self.team)) == {kept, rotated}++ assert disable_platform_alert_configurations(alert_ids=[rotated]) == 1+ assert {key: view.enabled for key, view in self._copies(self.team).items()} == {kept: True, rotated: False}