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(logs): sample and switch off the logs platform alert backfill (#114797)

Jimmy Zhu7585f027c5be
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.md
index adb7f8c24c22..442560bbfef0 100644
--- a/docs/internal/alerts-platform-temporal.md
+++ b/docs/internal/alerts-platform-temporal.md
@@ -462,6 +462,8 @@ python manage.py backfill_platform_alert_configurations
```
Pass `--team-id` to copy one team's configurations only.
+Pass `--sample-percent` to copy a sample of teams. Logs samples whole teams, not alerts, because one query checks a cohort of a team's alerts, so a sample of alerts spread across every team costs nearly as many queries as copying all of them. The sample is chosen by team id, so a rerun copies the same teams and a larger percentage only adds teams.
+An alert the copy rejects is logged and counted as failed, and the run carries on.
It is a seed, not a sync: the logs product keeps the control plane, and a later change to a logs alert reaches these tables only on the next run.
A second run updates rather than duplicates, because `legacy_configuration_id` carries the row each copy came from.
A second run of either backfill, logs or insight, leaves an enabled copy's `next_check_at` alone unless it has none yet or its cadence changed, because the platform owns its schedule once the row exists. The logs product parks its own next check at the end of quiet hours, while the platform checks through them and only mutes. A new or re-enabled copy still takes the source's due time, which spreads a large copy's first checks the way the source spreads them.
@@ -488,7 +490,7 @@ A full logs backfill hit ClickHouse's per-user concurrent query limit and had to
4. Widen the sample only while both stay flat. `ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS` caps the concurrent checks whatever the sample size. A batch refills the slots its finished checks free, in rounds within its tick, so the cap limits concurrency rather than checks per minute.
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.
+To stop either parallel run, logs or insight, pass `--disable` to its backfill, 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.
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index a3a745b2c14a..01664a150d3b 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -429,13 +429,17 @@ def take_ownership(handover: PlatformOwnershipHandover) -> bool:
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.
+ """Switches off a source's parallel-run 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)
+ # Cross-team on purpose, for an operator stopping a whole source at once. Only copies the source
+ # still owns: once the platform owns an alert, its copy is the production alert, and switching it
+ # off would silence real notifications rather than stop a parallel check.
+ rows = PlatformAlertConfiguration.objects.unscoped().filter(
+ source_kind=source_kind, enabled=True, owner=PlatformAlertOwner.SOURCE
+ )
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/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
index d444bf78e584..07f2a1c2ad4d 100644
--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py
+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
@@ -25,7 +25,7 @@ from products.alerts_platform.backend.facade.contracts import (
PlatformOwnershipHandover,
SourceKind,
)
-from products.alerts_platform.backend.facade.enums import PlatformAlertState
+from products.alerts_platform.backend.facade.enums import PlatformAlertOwner, PlatformAlertState
from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
from products.alerts_platform.backend.models.platform_alert_events_sql import SHARDED_PLATFORM_ALERT_EVENTS_TABLE
@@ -139,6 +139,24 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
assert self.configuration.enabled is False
assert due_checks(self.team.id, SourceKind.LOGS.value, self.slot, self.cutoff + timedelta(hours=1)) == ()
+ def test_switching_a_source_off_leaves_the_alerts_the_platform_owns(self) -> None:
+ with team_scope(self.team.id):
+ owned = PlatformAlertConfiguration.objects.create(
+ team=self.team,
+ name="Cut over",
+ source_kind=PlatformAlertConfiguration.SourceKind.LOGS,
+ source_config=self.configuration.source_config,
+ check_interval_minutes=10,
+ owner=PlatformAlertOwner.PLATFORM,
+ )
+
+ assert disable_configurations(SourceKind.LOGS, team_id=self.team.id) == 1
+
+ with team_scope(self.team.id):
+ self.configuration.refresh_from_db()
+ owned.refresh_from_db()
+ assert (self.configuration.enabled, owned.enabled) == (False, True)
+
def test_recording_a_batch_twice_advances_the_schedule_once(self) -> None:
self._record()
with team_scope(self.team.id):
diff --git a/products/logs/backend/management/commands/backfill_platform_alert_configurations.py b/products/logs/backend/management/commands/backfill_platform_alert_configurations.py
index f25407905eda..2f400a82479a 100644
--- a/products/logs/backend/management/commands/backfill_platform_alert_configurations.py
+++ b/products/logs/backend/management/commands/backfill_platform_alert_configurations.py
@@ -1,8 +1,11 @@
from typing import Any
-from django.core.management.base import BaseCommand
+from django.core.management.base import BaseCommand, CommandError
-from products.logs.backend.platform_alert_backfill import backfill_platform_alert_configurations
+from products.logs.backend.platform_alert_backfill import (
+ backfill_platform_alert_configurations,
+ disable_platform_alert_configurations,
+)
class Command(BaseCommand):
@@ -10,7 +13,31 @@ class Command(BaseCommand):
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 handle(self, *args: Any, **options: Any) -> None:
- counts = backfill_platform_alert_configurations(team_id=options["team_id"])
- self.stdout.write(f"Created {counts.created}, updated {counts.updated}")
+ 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}"
+ )
diff --git a/products/logs/backend/platform_alert_backfill.py b/products/logs/backend/platform_alert_backfill.py
index 3dd7b1c20bc5..60dd9d501a7e 100644
--- a/products/logs/backend/platform_alert_backfill.py
+++ b/products/logs/backend/platform_alert_backfill.py
@@ -13,7 +13,7 @@ import structlog
from posthog.dataclasses import frozen
-from products.alerts_platform.backend.facade.api import upsert_configuration
+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 PlatformAlertState
from products.logs.backend.alert_source_cycle import LogsAlertCondition
@@ -26,6 +26,8 @@ logger = structlog.get_logger(__name__)
class BackfillCounts:
created: int
updated: int
+ skipped: int
+ failed: int
def platform_upsert_of(alert: LogsAlertConfiguration) -> PlatformAlertUpsert:
@@ -65,20 +67,66 @@ PLATFORM_HANDOVER_STATE: Final[dict[str, PlatformAlertState]] = {
}
-def backfill_platform_alert_configurations(*, team_id: int | None = None) -> BackfillCounts:
- """Copies every logs alert configuration, or one team's."""
+def is_team_sampled(team_id: int, sample_percent: int) -> bool:
+ """Whether a team falls inside a sample.
+
+ Logs samples teams, not alerts, because one query checks a whole cohort of a team's alerts.
+ A sample of alerts spread across every team costs nearly as many queries as copying them all.
+ Decided by the team id, so a rerun picks the same teams and widening the sample only adds teams.
+ """
+ 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'.
+
+ 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 = LogsAlertConfiguration.objects.all()
if team_id is not None:
source = source.filter(team_id=team_id)
created = 0
updated = 0
+ skipped = 0
+ failed = 0
for configuration in source.iterator():
- was_created = upsert_configuration(platform_upsert_of(configuration))
+ if not is_team_sampled(configuration.team_id, sample_percent):
+ skipped += 1
+ continue
+ # One alert the copy rejects must not stop the rest.
+ try:
+ was_created = upsert_configuration(platform_upsert_of(configuration))
+ except Exception:
+ logger.exception(
+ "platform_alert_backfill.failed", alert_id=str(configuration.id), team_id=configuration.team_id
+ )
+ failed += 1
+ continue
if was_created:
created += 1
else:
updated += 1
- logger.info("platform_alert_backfill.complete", created=created, updated=updated, team_id=team_id)
- return BackfillCounts(created=created, updated=updated)
+ logger.info(
+ "platform_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_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.
+
+ 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)
+ logger.info("platform_alert_backfill.disabled", disabled=disabled, team_id=team_id)
+ return disabled
diff --git a/products/logs/backend/test/test_logs_platform_alert_backfill.py b/products/logs/backend/test/test_logs_platform_alert_backfill.py
new file mode 100644
index 000000000000..7de5c0a152f2
--- /dev/null
+++ b/products/logs/backend/test/test_logs_platform_alert_backfill.py
@@ -0,0 +1,61 @@
+from typing import Any
+from uuid import UUID
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from posthog.models import Team
+from posthog.models.scoping import team_scope
+
+from products.alerts_platform.backend.facade.api import list_configurations
+from products.alerts_platform.backend.facade.contracts import SourceKind
+from products.logs.backend.models import LogsAlertConfiguration
+from products.logs.backend.platform_alert_backfill import (
+ backfill_platform_alert_configurations,
+ disable_platform_alert_configurations,
+)
+
+
+class TestPlatformLogsAlertBackfill(APIBaseTest):
+ def _alert(self, team: Team, name: str = "API errors") -> LogsAlertConfiguration:
+ return LogsAlertConfiguration.objects.create(team=team, name=name, filters={"serviceNames": ["api"]})
+
+ def _copies(self, team: Team) -> dict[UUID | None, Any]:
+ with team_scope(team.id):
+ page = list_configurations(team_id=team.id, source_kinds=[SourceKind.LOGS.value], limit=10, offset=0)
+ return {view.legacy_configuration_id: view for view in page.configurations}
+
+ def test_a_sample_copies_whole_teams_and_widening_it_only_adds_teams(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ low, high = sorted([self.team, other_team], key=lambda team: team.id % 100)
+ low_alerts = {self._alert(low).id, self._alert(low, name="Slow requests").id}
+ high_alert = self._alert(high).id
+
+ backfill_platform_alert_configurations(sample_percent=low.id % 100 + 1)
+ assert (set(self._copies(low)), set(self._copies(high))) == (low_alerts, set())
+
+ backfill_platform_alert_configurations(sample_percent=high.id % 100 + 1)
+ assert (set(self._copies(low)), set(self._copies(high))) == (low_alerts, {high_alert})
+
+ def test_one_alert_the_copy_rejects_does_not_stop_the_rest(self) -> None:
+ self._alert(self.team)
+ self._alert(self.team, name="Slow requests")
+
+ with patch(
+ "products.logs.backend.platform_alert_backfill.upsert_configuration",
+ side_effect=[RuntimeError("rejected"), True],
+ ):
+ counts = backfill_platform_alert_configurations(team_id=self.team.id)
+
+ assert (counts.created, counts.failed) == (1, 1)
+
+ def test_disabling_stops_every_copy_and_a_rerun_turns_them_back_on(self) -> None:
+ self._alert(self.team)
+ self._alert(self.team, name="Slow requests")
+ backfill_platform_alert_configurations(team_id=self.team.id)
+
+ assert disable_platform_alert_configurations(team_id=self.team.id) == 2
+ assert {view.enabled for view in self._copies(self.team).values()} == {False}
+
+ backfill_platform_alert_configurations(team_id=self.team.id)
+ assert {view.enabled for view in self._copies(self.team).values()} == {True}