: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(logs): write both rows of a logs alert the platform owns (#118309)
Jimmy Zhu8155e1632b31
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.pyindex 84009b0db9ce..b255d1e3e9ea 100644--- a/products/alerts_platform/backend/facade/api.py+++ b/products/alerts_platform/backend/facade/api.py@@ -148,3 +148,28 @@ def update_configuration(return platform_writes.update_configuration(team_id=team_id, source_kinds=source_kinds, configuration_id=configuration_id, change=change)+++def update_owned_copy(+ *,+ team_id: int,+ legacy_configuration_id: UUID,+ change: Callable[[PlatformAlertConfigurationEdit], PlatformAlertConfigurationEdit],+ snooze_until: datetime | None = None,+ snooze_changed: bool = False,+) -> None:+ """Applies an edit a source made to its own row onto the copy the platform owns.++ Raises `InvalidPlatformAlertEdit` for an edit the source kind's schema rejects.+ """+ platform_writes.update_owned_copy(+ team_id=team_id,+ legacy_configuration_id=legacy_configuration_id,+ change=change,+ snooze_until=snooze_until,+ snooze_changed=snooze_changed,+ )+++def delete_owned_copy(*, team_id: int, legacy_configuration_id: UUID) -> None:+ platform_writes.delete_owned_copy(team_id=team_id, legacy_configuration_id=legacy_configuration_id)diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex b1d9dd50ce36..4b3ddce5800f 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -848,16 +848,33 @@ class PlatformAlertNotEditable(Exception):"""A configuration the platform does not own, so its source's own API writes it."""+class SourceEditMirror(Protocol):+ """Writes an edit made through the platform API onto the source's own row.++ While a source keeps its own row for an alert the platform owns, the two must agree: the+ source's API reads that row, and a rollback hands it back. It runs before the platform locks+ its copy, because every other writer of both rows takes the source's row first. It locks the+ source's row and returns the writer for the edit, or None when the row is gone. It raises+ `PlatformAlertNotEditable` when the source's row belongs to another team than the copy, because+ the platform API checked access to the copy's team only.+ """++ def __call__(+ self, *, team_id: int, legacy_configuration_id: UUID+ ) -> Callable[[PlatformAlertConfigurationEdit], None] | None: ...++@frozenclass SourceConfigSpec:"""A source kind's schema for `source_config` and its rules for a whole edit.- `model` validates `source_config` and supplies its defaults. `validate` raises- `InvalidPlatformAlertEdit` for a rule that spans fields, such as one that reads `enabled`.+ `model` validates `source_config`. `validate` raises `InvalidPlatformAlertEdit` for a rule that+ spans fields, such as one that reads `enabled`. `mirror` runs in the edit's transaction."""model: type[BaseModel]validate: Callable[[PlatformAlertConfigurationEdit], None]+ mirror: SourceEditMirror | None = NoneSourceConfigLoader = Callable[[], SourceConfigSpec]diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.pyindex db216e5592a5..8f8d2f8aa905 100644--- a/products/alerts_platform/backend/logic/platform_lifecycle.py+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py@@ -579,6 +579,9 @@ _ADMISSION_LOCK_SQL: Final = {def upsert_configuration(upsert: PlatformAlertUpsert, *, revive: bool = False) -> bool:"""Copies one source configuration in. Returns True when it created a row.+ A copy the platform owns is left as it is. Every edit writes both of its rows, and a caller here+ reads its source row without a lock, so its snapshot can predate such an edit.+Keyed on the row it came from, so a second run updates rather than duplicates.`next_check_at` is copied into a new row, into a disabled copy, into a copy with no schedule@@ -601,9 +604,11 @@ def upsert_configuration(upsert: PlatformAlertUpsert, *, revive: bool = False) -PlatformAlertConfiguration.objects.unscoped().select_for_update().filter(legacy_configuration_id=upsert.legacy_configuration_id)- .values("enabled", "next_check_at", *_CADENCE_FIELDS)+ .values("enabled", "next_check_at", "owner", *_CADENCE_FIELDS).first())+ if existing is not None and existing["owner"] == PlatformAlertOwner.PLATFORM:+ return Falsedefaults = {"team_id": upsert.team_id,"name": upsert.name,@@ -705,9 +710,9 @@ def write_edit(def upsert_if_running(upsert: PlatformAlertUpsert, *, revive: bool = False) -> None:"""Copies one configuration in when its team already runs that source here.- A copy the platform owns is the production alert, so it always follows its source, including- back on after the source turns it off. Otherwise a team runs a source here while any of its- parallel-run copies of that source is enabled. A team the backfill left out of its sample, or one+ A copy the platform owns gets nothing, because every edit already writes both of its rows.+ Otherwise a team runs a source here while any of its parallel-run copies of that source is+ enabled. A team the backfill left out of its sample, or one`disable_configurations` switched off, gets nothing, and neither does a copy an operator switchedoff by name, so a write in the source never widens a sample or undoes an operator's switch-off."""@@ -718,7 +723,6 @@ def upsert_if_running(upsert: PlatformAlertUpsert, *, revive: bool = False) -> N)existing = team_copies.filter(legacy_configuration_id=upsert.legacy_configuration_id).first()if existing is not None and existing.owner == PlatformAlertOwner.PLATFORM:- upsert_configuration(upsert, revive=revive)returnrunning = team_copies.filter(owner=PlatformAlertOwner.SOURCE, enabled=True).exists()switched_off = existing is not None and existing.switched_off_at is not Nonediff --git a/products/alerts_platform/backend/logic/platform_writes.py b/products/alerts_platform/backend/logic/platform_writes.pyindex 4291cc8a5c98..079d6775f0dd 100644--- a/products/alerts_platform/backend/logic/platform_writes.py+++ b/products/alerts_platform/backend/logic/platform_writes.py@@ -6,6 +6,7 @@ and the next check reads back. Writing the copy here would fork it, so those arefrom collections.abc import Callable, Sequencefrom dataclasses import replace+from datetime import datetimefrom uuid import UUIDfrom django.db import transaction@@ -13,6 +14,8 @@ from django.utils import timezone as django_timezonefrom pydantic import ValidationError as PydanticValidationError+from posthog.exceptions_capture import capture_exception+from products.alerts_platform.backend.facade.contracts import (MAX_EVALUATION_PERIODS,MAX_STORED_INTEGER,@@ -29,6 +32,10 @@ from products.alerts_platform.backend.logic import platform_lifecycle, platform_from products.alerts_platform.backend.models import PlatformAlertConfiguration+class MissingPlatformCopy(Exception):+ """A source row marked platform-owned with no platform copy behind it."""++def edit_of(configuration: PlatformAlertConfiguration) -> PlatformAlertConfigurationEdit:return PlatformAlertConfigurationEdit(name=configuration.name,@@ -84,31 +91,103 @@ def update_configuration(configuration_id: UUID,change: Callable[[PlatformAlertConfigurationEdit], PlatformAlertConfigurationEdit],) -> PlatformAlertConfigurationView | None:- """Applies `change` to the configuration's current settings under its row lock.+ """Applies `change` to the configuration's current settings under its row lock, and mirrors the+ result onto the source's own row.None when the configuration does not exist or its kind is not among `source_kinds`. Taking afunction rather than the new settings lets a partial update merge with what is stored insidethe lock, so two partial updates of different fields both survive."""+ readable = PlatformAlertConfiguration.objects.for_team(team_id, canonical=True).filter(+ id=configuration_id, source_kind__in=list(source_kinds)+ )with transaction.atomic():- configuration = (- PlatformAlertConfiguration.objects.for_team(team_id, canonical=True)- .select_for_update()- .filter(id=configuration_id, source_kind__in=list(source_kinds))- .first()+ found = readable.values_list("source_kind", "legacy_configuration_id").first()+ if found is None:+ return None+ source_kind, legacy_configuration_id = found+ spec = source_configs.spec(SourceKind(source_kind))+ mirror = spec.mirror if spec is not None else None+ write_source = (+ mirror(team_id=team_id, legacy_configuration_id=legacy_configuration_id)+ if mirror is not None and legacy_configuration_id is not None+ else None)+ configuration = readable.select_for_update().first()if configuration is None:return None- if configuration.owner != PlatformAlertOwner.PLATFORM:- raise PlatformAlertNotEditable(- f"This alert is managed by the {configuration.source_kind} product. Edit it there."- )- current = edit_of(configuration)- edit = _validated(SourceKind(configuration.source_kind), current, change(current))-- regrouped = not edit.grouping.splits_like(current.grouping)- platform_lifecycle.write_edit(configuration, edit, regrouped=regrouped, now=django_timezone.now())+ edit = _apply(configuration, change)+ if write_source is not None:+ write_source(edit)return platform_reads.get_configuration(team_id=team_id, source_kinds=source_kinds, configuration_id=configuration_id)+++def update_owned_copy(+ *,+ team_id: int,+ legacy_configuration_id: UUID,+ change: Callable[[PlatformAlertConfigurationEdit], PlatformAlertConfigurationEdit],+ snooze_until: datetime | None,+ snooze_changed: bool,+) -> None:+ """Applies an edit the source made to its own row onto the platform's copy. Nothing is mirrored+ back, because the source already wrote its row. A snooze the edit set or cleared becomes the+ copy's mute."""+ with transaction.atomic():+ configuration = _locked_owned_copy(team_id, legacy_configuration_id)+ if configuration is None:+ return+ _apply(configuration, change)+ if snooze_changed:+ configuration.snooze_until = snooze_until+ configuration.save(update_fields=["snooze_until", "updated_at"])+++def delete_owned_copy(*, team_id: int, legacy_configuration_id: UUID) -> None:+ """Deletes the copy of a source alert the platform owns, with its instances and threads."""+ copies = PlatformAlertConfiguration.objects.for_team(team_id).filter(+ legacy_configuration_id=legacy_configuration_id, owner=PlatformAlertOwner.PLATFORM+ )+ with transaction.atomic():+ # The configuration before its children, the order `record_outcomes` locks them in. The+ # cascade deletes the children first, so without this the two can deadlock.+ list(copies.select_for_update())+ copies.delete()+++def _locked_owned_copy(team_id: int, legacy_configuration_id: UUID) -> PlatformAlertConfiguration | None:+ configuration = (+ PlatformAlertConfiguration.objects.for_team(team_id)+ .select_for_update()+ .filter(legacy_configuration_id=legacy_configuration_id, owner=PlatformAlertOwner.PLATFORM)+ .first()+ )+ if configuration is None:+ # A source row marked platform-owned without a copy is a broken handover. The source's own+ # edit still saves, so the user is not blocked, and the report makes the gap visible.+ capture_exception(+ MissingPlatformCopy(f"No platform copy owns source alert {legacy_configuration_id}"),+ {"team_id": team_id, "legacy_configuration_id": str(legacy_configuration_id)},+ )+ return configuration+++def _apply(+ configuration: PlatformAlertConfiguration,+ change: Callable[[PlatformAlertConfigurationEdit], PlatformAlertConfigurationEdit],+) -> PlatformAlertConfigurationEdit:+ """Validates and writes an edit onto a configuration locked by the caller."""+ if configuration.owner != PlatformAlertOwner.PLATFORM:+ raise PlatformAlertNotEditable(+ f"This alert is managed by the {configuration.source_kind} product. Edit it there."+ )+ current = edit_of(configuration)+ edit = _validated(SourceKind(configuration.source_kind), current, change(current))++ platform_lifecycle.write_edit(+ configuration, edit, regrouped=not edit.grouping.splits_like(current.grouping), now=django_timezone.now()+ )+ return editdiff --git a/products/alerts_platform/frontend/generated/api.schemas.ts b/products/alerts_platform/frontend/generated/api.schemas.tsindex c1583306e079..95efaf57526a 100644--- a/products/alerts_platform/frontend/generated/api.schemas.ts+++ b/products/alerts_platform/frontend/generated/api.schemas.ts@@ -661,6 +661,7 @@ export interface LogsPlatformAlertConditionApi {/*** Number of matching log entries in the window that breaches the threshold. Use 0 with the above operator to fire on any matching log.* @minimum 0+ * @maximum 2147483647*/threshold_count: number/** Whether the alert fires when the count is above or below the threshold. */diff --git a/products/alerts_platform/frontend/generated/api.zod.ts b/products/alerts_platform/frontend/generated/api.zod.tsindex 15da98c0a740..75fb53b932e6 100644--- a/products/alerts_platform/frontend/generated/api.zod.ts+++ b/products/alerts_platform/frontend/generated/api.zod.ts@@ -12,6 +12,7 @@ import * as zod from 'zod'export const platformAlertsUpdateBodyOneNameMax = 255export const platformAlertsUpdateBodyOneSourceConfigOneConditionThresholdCountMin = 0+export const platformAlertsUpdateBodyOneSourceConfigOneConditionThresholdCountMax = 2147483647export const platformAlertsUpdateBodyOneGroupingOneMaxInstancesDefault = 100export const platformAlertsUpdateBodyOneGroupingOneMaxInstancesMax = 100@@ -66,6 +67,7 @@ export const PlatformAlertsUpdateBody = /* @__PURE__ */ zodthreshold_count: zod.number().min(platformAlertsUpdateBodyOneSourceConfigOneConditionThresholdCountMin)+ .max(platformAlertsUpdateBodyOneSourceConfigOneConditionThresholdCountMax).describe('Number of matching log entries in the window that breaches the threshold. Use 0 with the above operator to fire on any matching log.'),@@ -160,6 +162,7 @@ export const PlatformAlertsUpdateBody = /* @__PURE__ */ zodexport const platformAlertsPartialUpdateBodyOneNameMax = 255export const platformAlertsPartialUpdateBodyOneSourceConfigOneConditionThresholdCountMin = 0+export const platformAlertsPartialUpdateBodyOneSourceConfigOneConditionThresholdCountMax = 2147483647export const platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesDefault = 100export const platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesMax = 100@@ -218,6 +221,7 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zodthreshold_count: zod.number().min(platformAlertsPartialUpdateBodyOneSourceConfigOneConditionThresholdCountMin)+ .max(platformAlertsPartialUpdateBodyOneSourceConfigOneConditionThresholdCountMax).describe('Number of matching log entries in the window that breaches the threshold. Use 0 with the above operator to fire on any matching log.'),diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.pyindex 4d0461623c1a..ebfbc76fcf52 100644--- a/products/logs/backend/alert_source_cycle.py+++ b/products/logs/backend/alert_source_cycle.py@@ -98,7 +98,7 @@ from products.logs.backend.alert_evaluation_key import WINDOW_MARKERfrom products.logs.backend.alert_group_columns import grouping_problemfrom products.logs.backend.alert_lookback import rolling_check_lookback_minutesfrom products.logs.backend.models import LogsAlertConfiguration-from products.logs.backend.platform_alert_backfill import platform_upsert_of+from products.logs.backend.platform_alert_backfill import SETTINGS_FIELDS, platform_upsert_offrom products.logs.backend.platform_source_config import filters_of# Private to the production activity. Reimplementing either would let this path drift from@@ -184,18 +184,8 @@ class _QuerySubject:return cls(id=check.id, team_id=check.team_id, filters=filters_of(check.source_config))-# The copy's settings a check takes from the logs alert as it is now. The schedule stays the-# platform's own once the copy exists.-_SETTINGS_FIELDS: Final = (- "name",- "source_config",- "evaluation_periods",- "datapoints_to_alarm",- "cooldown_minutes",- "schedule_restriction",-)# The snooze lives on the alert row rather than the copy, and no history row states it.-_LIVE_FIELDS: Final = (*_SETTINGS_FIELDS, "snooze_until")+_LIVE_FIELDS: Final = (*SETTINGS_FIELDS, "snooze_until")def _broken_condition(check: PlatformAlertCheckInput) -> str | None:@@ -672,6 +662,10 @@ def _as_configured_now(A copy whose logs alert is gone or disabled stops: the logs stack runs no check for it, so itswitches itself off, and the next backfill turns it back on if the alert is enabled again.++ A copy the platform owns is not a seed: every edit reaches it directly, from the logs API or the+ platform's, so it is evaluated as stored. It still needs its logs row on the copy's team. A row in+ a child environment has its logs there, and the query would read the project's instead."""legacy_ids = [check.legacy_configuration_id for check in checks]alerts = {alert.id: alert for alert in LogsAlertConfiguration.objects.filter(team_id=team_id, id__in=legacy_ids)}@@ -679,6 +673,9 @@ def _as_configured_now(stopped: list[Decision] = []for check in checks:alert = alerts.get(check.legacy_configuration_id)+ if check.owned_by_platform and alert is not None:+ current.append(check)+ continueif alert is None or not alert.enabled:stopped.append(_stopped(check, now=now))continue@@ -695,7 +692,7 @@ def _as_configured_now()continueupsert = platform_upsert_of(alert)- if any(getattr(check, field) != getattr(upsert, field) for field in _SETTINGS_FIELDS):+ if any(getattr(check, field) != getattr(upsert, field) for field in SETTINGS_FIELDS):try:refresh_settings(team_id, check.id, upsert)except Exception:diff --git a/products/logs/backend/alert_state_machine.py b/products/logs/backend/alert_state_machine.pyindex d7a37ad979fb..39ce36841deb 100644--- a/products/logs/backend/alert_state_machine.py+++ b/products/logs/backend/alert_state_machine.py@@ -175,3 +175,22 @@ def apply_outcome()return ["state", "consecutive_failures"]+++def apply_enabled(alert: LogsAlertConfiguration, enabled: bool, *, now: datetime) -> list[str]:+ """Turns an alert on or off with the transition and audit row the logs API writes for it.+ Returns modified field names for `save(update_fields=...)`, none when `enabled` is unchanged."""+ from products.logs.backend.models import LogsAlertEvent++ if alert.enabled == enabled:+ return []+ snapshot = alert.to_snapshot()+ if enabled:+ update_fields = apply_outcome(alert, apply_enable(snapshot), kind=LogsAlertEvent.Kind.ENABLE)+ if alert.first_enabled_at is None:+ alert.first_enabled_at = now+ update_fields.append("first_enabled_at")+ else:+ update_fields = apply_outcome(alert, apply_disable(snapshot), kind=LogsAlertEvent.Kind.DISABLE)+ alert.enabled = enabled+ return [*update_fields, "enabled"]diff --git a/products/logs/backend/facade/platform_ownership.py b/products/logs/backend/facade/platform_ownership.pynew file mode 100644index 000000000000..54732c9e947b--- /dev/null+++ b/products/logs/backend/facade/platform_ownership.py@@ -0,0 +1,37 @@+"""Facade for the logs API's half of keeping both rows of a platform-owned logs alert in step.++Each call reads the logs row by id inside the caller's transaction, after the caller saved or locked it.+"""++from datetime import datetime+from uuid import UUID++from products.logs.backend import platform_ownership+from products.logs.backend.models import LogsAlertConfiguration++__all__ = ["on_created", "on_deleted", "on_updated"]+++def _alert(team_id: int, alert_id: UUID) -> LogsAlertConfiguration | None:+ return LogsAlertConfiguration.objects.filter(team_id=team_id, id=alert_id).first()+++def on_created(*, team_id: int, alert_id: UUID, at: datetime) -> bool:+ """Hands a new alert to the platform when its team has begun the cutover. False when the alert+ stays with logs."""+ alert = _alert(team_id, alert_id)+ return alert is not None and platform_ownership.on_created(alert, at)+++def on_updated(*, team_id: int, alert_id: UUID, snooze_changed: bool) -> None:+ """Writes an edit the logs API saved onto the platform's copy.++ Raises `InvalidPlatformAlertEdit` when the platform's schema rejects the edit.+ """+ alert = _alert(team_id, alert_id)+ if alert is not None:+ platform_ownership.on_updated(alert, snooze_changed=snooze_changed)+++def on_deleted(*, team_id: int, alert_id: UUID) -> None:+ platform_ownership.on_deleted(team_id=team_id, alert_id=alert_id)diff --git a/products/logs/backend/platform_alert_backfill.py b/products/logs/backend/platform_alert_backfill.pyindex 53d457409976..41be923412a3 100644--- a/products/logs/backend/platform_alert_backfill.py+++ b/products/logs/backend/platform_alert_backfill.py@@ -20,7 +20,7 @@ from posthog.dataclasses import frozenfrom products.alerts_platform.backend.facade.api import disable_configurations, upsert_configuration, upsert_if_runningfrom products.alerts_platform.backend.facade.contracts import PlatformAlertUpsert, SourceKind-from products.alerts_platform.backend.facade.enums import PlatformAlertState+from products.alerts_platform.backend.facade.enums import PlatformAlertOwner, PlatformAlertStatefrom products.logs.backend.alert_state_machine import AlertStatefrom products.logs.backend.models import LogsAlertConfigurationfrom products.logs.backend.platform_source_config import logs_source_config@@ -36,6 +36,20 @@ class BackfillCounts:failed: int+# The settings a logs alert shares with its platform copy. The schedule stays the platform's own once+# the copy exists, and `enabled` follows its own rules on each side.+SETTINGS_FIELDS: Final = (+ "name",+ "source_config",+ "evaluation_periods",+ "datapoints_to_alarm",+ "cooldown_minutes",+ "schedule_restriction",+)+# The logs alert's columns that make up `source_config["condition"]` on the copy.+CONDITION_FIELDS: Final = ("threshold_count", "threshold_operator", "window_minutes")++def platform_upsert_of(alert: LogsAlertConfiguration) -> PlatformAlertUpsert:"""The platform copy of a logs alert, which the backfill writes and every check reads again.@@ -48,14 +62,7 @@ def platform_upsert_of(alert: LogsAlertConfiguration) -> PlatformAlertUpsert:name=alert.name,enabled=alert.enabled,source_kind=SourceKind.LOGS,- source_config=logs_source_config(- alert.filters,- {- "threshold_count": alert.threshold_count,- "threshold_operator": alert.threshold_operator,- "window_minutes": alert.window_minutes,- },- ),+ source_config=logs_source_config(alert.filters, {field: getattr(alert, field) for field in CONDITION_FIELDS}),check_interval_minutes=alert.check_interval_minutes,evaluation_periods=alert.evaluation_periods,datapoints_to_alarm=alert.datapoints_to_alarm,@@ -123,7 +130,8 @@ def backfill_platform_alert_configurations("""if not 1 <= sample_percent <= 100:raise ValueError("sample_percent must be between 1 and 100")- source = LogsAlertConfiguration.objects.all()+ # The platform owns these, and every edit writes both rows already.+ source = LogsAlertConfiguration.objects.exclude(owner=PlatformAlertOwner.PLATFORM)if team_id is not None:source = source.filter(team_id=team_id)if alert_ids is not None:diff --git a/products/logs/backend/platform_cutover.py b/products/logs/backend/platform_cutover.pyindex 8b69cd8b5bce..a8c5ac6262e9 100644--- a/products/logs/backend/platform_cutover.py+++ b/products/logs/backend/platform_cutover.py@@ -41,6 +41,8 @@ class CutoverSkip(StrEnum):CHECK_DUE = "check_due"# A team on live delivery can have the platform copy inside a firing of its own.PLATFORM_FIRING = "platform_firing"+ # The copy lives on the project, and the platform does not store which environment it checks.+ ENVIRONMENT = "environment"@frozen@@ -82,33 +84,15 @@ def _cut_over_alert(alert_id: UUID, now: datetime | None) -> CutoverSkip | None:at = now or timezone.now()if alert.platform_owned:return CutoverSkip.ALREADY_MOVED+ if in_an_environment(alert):+ return CutoverSkip.ENVIRONMENTif alert.state in FIRING_STATES:return CutoverSkip.FIRINGif _logs_check_owed(alert.id, at):return CutoverSkip.CHECK_DUE- savepoint = transaction.savepoint()- upsert_configuration(platform_upsert_of(alert))- taken = take_ownership(- PlatformOwnershipHandover(- legacy_configuration_id=alert.id,- team_id=alert.team_id,- state=PLATFORM_HANDOVER_STATE[alert.state],- last_notified_at=alert.last_notified_at,- consecutive_failures=alert.consecutive_failures,- next_check_at=alert.next_check_at or at,- at=at,- )- )- if not taken:- # The copy stays as live delivery left it. A copy disabled here would drop out of- # discovery and never resolve the firing it is inside.- transaction.savepoint_rollback(savepoint)+ if not hand_over(alert, at):return CutoverSkip.PLATFORM_FIRING- transaction.savepoint_commit(savepoint)- LogsAlertConfiguration.objects.filter(id=alert.id).update(- owner=PlatformAlertOwner.PLATFORM, owner_changed_at=at- )return None@@ -175,3 +159,42 @@ def _roll_back_alert(alert_id: UUID, now: datetime | None) -> RollbackSkip | Nonalert.next_check_at = handback.next_check_atalert.save(update_fields=[*update_fields, "owner", "owner_changed_at", "last_notified_at", "next_check_at"])return None+++def in_an_environment(alert: LogsAlertConfiguration) -> bool:+ """Whether the alert belongs to a child environment, whose copy would live on its project."""+ return alert.team.parent_team_id is not None+++def hand_over(alert: LogsAlertConfiguration, at: datetime) -> bool:+ """Copies a logs alert locked by the caller onto the platform and makes the platform its owner,+ on both rows. False, changing nothing, when the platform copy is inside a firing of its own."""+ savepoint = transaction.savepoint()+ upsert_configuration(platform_upsert_of(alert))+ taken = take_ownership(+ PlatformOwnershipHandover(+ legacy_configuration_id=alert.id,+ team_id=alert.team_id,+ state=PLATFORM_HANDOVER_STATE[alert.state],+ last_notified_at=alert.last_notified_at,+ consecutive_failures=alert.consecutive_failures,+ next_check_at=alert.next_check_at or at,+ at=at,+ )+ )+ if not taken:+ # The copy stays as live delivery left it. A copy disabled here would drop out of+ # discovery and never resolve the firing it is inside.+ transaction.savepoint_rollback(savepoint)+ return False+ transaction.savepoint_commit(savepoint)+ # `update()` rather than `save()`: a handover is not a user's edit, and `save()` would log one.+ LogsAlertConfiguration.objects.filter(id=alert.id).update(owner=PlatformAlertOwner.PLATFORM, owner_changed_at=at)+ alert.owner = PlatformAlertOwner.PLATFORM+ alert.owner_changed_at = at+ return True+++def has_begun_cutover(team_id: int) -> bool:+ """Whether the platform owns any of the team's logs alerts, which makes it the owner of new ones."""+ return LogsAlertConfiguration.objects.filter(team_id=team_id, owner=PlatformAlertOwner.PLATFORM).exists()diff --git a/products/logs/backend/platform_ownership.py b/products/logs/backend/platform_ownership.pynew file mode 100644index 000000000000..3bb6d8525a27--- /dev/null+++ b/products/logs/backend/platform_ownership.py@@ -0,0 +1,97 @@+"""Keeps both rows of a logs alert the platform owns in step.++A logs alert the platform owns keeps its logs row until every team is cut over: the logs page reads+it, the shadow evaluation runs it, and a rollback hands it back. So every write to either row reaches+the other in the same transaction, and every writer locks the logs row before the platform's copy.+"""++from collections.abc import Callable+from dataclasses import replace+from datetime import datetime+from uuid import UUID++from django.utils import timezone++from products.alerts_platform.backend.facade.api import delete_owned_copy, update_owned_copy+from products.alerts_platform.backend.facade.contracts import (+ SOURCE_CONDITION_KEY,+ PlatformAlertConfigurationEdit,+ PlatformAlertNotEditable,+)+from products.logs.backend.alert_state_machine import apply_enabled+from products.logs.backend.models import LogsAlertConfiguration+from products.logs.backend.platform_alert_backfill import CONDITION_FIELDS, SETTINGS_FIELDS, platform_upsert_of+from products.logs.backend.platform_cutover import hand_over, has_begun_cutover, in_an_environment+from products.logs.backend.platform_source_config import filters_of+++def on_created(alert: LogsAlertConfiguration, at: datetime) -> bool:+ """Hands a new alert to the platform when its team has begun the cutover, so the team never has+ to be cut over again for it. False when the alert stays with logs."""+ return not in_an_environment(alert) and has_begun_cutover(alert.team_id) and hand_over(alert, at)+++def on_updated(alert: LogsAlertConfiguration, *, snooze_changed: bool) -> None:+ """Writes an edit the logs API saved onto the platform's copy.++ Raises `InvalidPlatformAlertEdit` when the platform's schema rejects the edit.+ """+ update_owned_copy(+ team_id=alert.team_id,+ legacy_configuration_id=alert.id,+ change=_platform_change_of(alert),+ snooze_until=alert.snooze_until,+ snooze_changed=snooze_changed,+ )+++def on_deleted(*, team_id: int, alert_id: UUID) -> None:+ delete_owned_copy(team_id=team_id, legacy_configuration_id=alert_id)+++def _platform_change_of(+ alert: LogsAlertConfiguration,+) -> Callable[[PlatformAlertConfigurationEdit], PlatformAlertConfigurationEdit]:+ # Only the settings a logs alert has. The platform's own, such as grouping, keep what the copy+ # stores, so an edit through the logs API never resets them.+ upsert = platform_upsert_of(alert)+ shared = {field: getattr(upsert, field) for field in SETTINGS_FIELDS}+ return lambda stored: replace(stored, enabled=upsert.enabled, **shared)+++def mirror_platform_edit(+ *, team_id: int, legacy_configuration_id: UUID+) -> Callable[[PlatformAlertConfigurationEdit], None] | None:+ """Locks the logs row of an alert edited through the platform API, and returns its writer."""+ alert = LogsAlertConfiguration.objects.select_for_update().filter(id=legacy_configuration_id).first()+ if alert is None:+ return None+ if alert.team_id != team_id:+ # A copy lives on the project, and its logs row on the environment. The platform API checked+ # access to the project only.+ raise PlatformAlertNotEditable(+ "This alert belongs to one of this project's environments. Edit it on that environment's logs alerts page."+ )+ return lambda edit: _write_logs_row(alert, edit)+++def _write_logs_row(alert: LogsAlertConfiguration, edit: PlatformAlertConfigurationEdit) -> None:+ # The inverse of `platform_upsert_of`, over the same field lists.+ condition = edit.source_config[SOURCE_CONDITION_KEY]+ # The shadow evaluation still runs this row, so an on or off moves its state the way the logs API does.+ enabled_fields = apply_enabled(alert, edit.enabled, now=timezone.now())+ alert.filters = filters_of(edit.source_config)+ for field in CONDITION_FIELDS:+ setattr(alert, field, condition[field])+ for field in SETTINGS_FIELDS:+ if field != "source_config":+ setattr(alert, field, getattr(edit, field))+ alert.save(+ update_fields=[+ *enabled_fields,+ "filters",+ *CONDITION_FIELDS,+ *(field for field in SETTINGS_FIELDS if field != "source_config"),+ "updated_at",+ ]+ )diff --git a/products/logs/backend/platform_source_config_schema.py b/products/logs/backend/platform_source_config_schema.pyindex 208bf3be2e41..06b55c7ccdfe 100644--- a/products/logs/backend/platform_source_config_schema.py+++ b/products/logs/backend/platform_source_config_schema.py@@ -10,6 +10,7 @@ from pydantic import BaseModel, ConfigDict, Fieldfrom posthog.schema import LogsAlertFiltersfrom products.alerts_platform.backend.facade.contracts import (+ MAX_STORED_INTEGER,GroupingMode,InvalidPlatformAlertEdit,PlatformAlertConfigurationEdit,@@ -17,6 +18,7 @@ from products.alerts_platform.backend.facade.contracts import ()from products.logs.backend.alert_group_columns import grouping_problemfrom products.logs.backend.models import LogsAlertConfiguration+from products.logs.backend.platform_ownership import mirror_platform_editfrom products.logs.backend.platform_source_config import WindowMinutes, has_any_filter@@ -26,6 +28,8 @@ class LogsPlatformAlertCondition(BaseModel):threshold_count: int = Field(...,ge=0,+ # The logs row stores it in an `integer` column, which a mirrored edit writes.+ le=MAX_STORED_INTEGER,description="Number of matching log entries in the window that breaches the threshold. ""Use 0 with the above operator to fire on any matching log.",)@@ -59,4 +63,6 @@ def validate_logs_edit(edit: PlatformAlertConfigurationEdit) -> None:raise InvalidPlatformAlertEdit("grouping", problem)-LOGS_SOURCE_CONFIG = SourceConfigSpec(model=LogsPlatformAlertSourceConfig, validate=validate_logs_edit)+LOGS_SOURCE_CONFIG = SourceConfigSpec(+ model=LogsPlatformAlertSourceConfig, validate=validate_logs_edit, mirror=mirror_platform_edit+)diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.pyindex 989ca22cb7c1..8063199d957e 100644--- a/products/logs/backend/presentation/views/alerts_api.py+++ b/products/logs/backend/presentation/views/alerts_api.py@@ -51,6 +51,7 @@ from products.alerts_platform.backend.facade.contracts import (AlertDestinationData,AlertDestinationValidationError,DestinationType,+ InvalidPlatformAlertEdit,PagerDutyRegion,PagerDutySeverity,PlatformAlertHistory,@@ -93,6 +94,7 @@ from products.logs.backend.facade.api import (logs_state_of_platform,next_allowed_check_at,)+from products.logs.backend.facade.platform_ownership import on_created, on_deleted, on_updatedfrom products.logs.backend.models import MAX_EVALUATION_PERIODS, LogsAlertConfiguration, LogsAlertEventMAX_ALERTS_PER_TEAM = 20@@ -826,7 +828,14 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):instance.clear_next_check()updated = super().update(instance, validated_data)- if enabled_change is True:+ if updated.platform_owned:+ try:+ on_updated(+ team_id=updated.team_id, alert_id=updated.id, snooze_changed=snooze_data is not _SENTINEL+ )+ except InvalidPlatformAlertEdit as error:+ raise ValidationError({error.field_name: str(error)}) from error+ elif enabled_change is True:transaction.on_commit(lambda: follow_logs_alert(team_id=updated.team_id, alert_id=updated.id), robust=True)@@ -858,7 +867,9 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):schedule_restriction=schedule_restriction,)created = super().create(validated_data)- if created.enabled:+ if on_created(team_id=created.team_id, alert_id=created.id, at=timezone.now()):+ created.refresh_from_db(fields=["owner", "owner_changed_at"])+ elif created.enabled:transaction.on_commit(lambda: follow_logs_alert(team_id=created.team_id, alert_id=created.id), robust=True)@@ -1647,5 +1658,7 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):alert_id=str(locked_instance.id),allowed_event_ids=LOGS_ALERT_EVENT_IDS,)+ if locked_instance.platform_owned:+ on_deleted(team_id=locked_instance.team_id, alert_id=locked_instance.id)super().perform_destroy(locked_instance)transaction.on_commit(lambda: self._track("deleted", locked_instance), robust=True)diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.pyindex 26aaa9a393f7..3b261f412e17 100644--- a/products/logs/backend/test/test_alert_evaluate.py+++ b/products/logs/backend/test/test_alert_evaluate.py@@ -17,6 +17,7 @@ from posthog.hogql.errors import ExposedHogQLErrorfrom posthog import redisfrom posthog.exceptions import ClickHouseQueryTimeOutfrom posthog.models.scoping import team_scope+from posthog.models.team import Teamfrom posthog.temporal.alerts.admission import admit_evaluation_slotsfrom products.alerts_platform.backend.facade import testing as platform_testing@@ -617,6 +618,34 @@ class TestLogsAlertEvaluation(APIBaseTest):# History and messages read the stored copy, so it has to state what the check evaluated.assert copy.source_config["condition"]["threshold_count"] == stored_threshold+ def test_a_copy_the_platform_owns_runs_as_stored_whatever_its_logs_row_says(self) -> None:+ configuration = self._configuration(owner="platform")+ # Stored as "above 10", which 500 logs breach. The logs row now says otherwise, and is off.+ LogsAlertConfiguration.objects.filter(id=self._legacy_ids[configuration.id]).update(+ threshold_count=1000, enabled=False+ )++ evaluation, query = self._run(configuration)++ assert [g.kind for o in evaluation.outcomes for g in o.groups] == [AlertEventKind.FIRING]+ assert query.called++ def test_a_copy_the_platform_owns_stops_when_its_logs_row_is_in_an_environment(self) -> None:+ configuration = self._configuration(owner="platform")+ environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")+ # The environment's logs live under its own team, which the project's query would not read.+ LogsAlertConfiguration.objects.filter(id=self._legacy_ids[configuration.id]).update(team=environment)++ evaluation, query = self._run(configuration)+ self._record(evaluation)++ assert query.called is False+ with team_scope(self.team.id):+ (copy,) = list_configurations(+ team_id=self.team.id, source_kinds=[SourceKind.LOGS.value], limit=10, offset=0+ ).configurations+ assert copy.enabled is False+def test_a_redispatched_batch_does_not_share_the_slot_its_earlier_run_still_holds(self) -> None:configuration = self._configuration()# The earlier execution of this same batch, whose query outlived its activity.diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.pyindex 52bac2d31355..5961dd53a2c4 100644--- a/products/logs/backend/test/test_alerts_api.py+++ b/products/logs/backend/test/test_alerts_api.py@@ -1,4 +1,5 @@import json+from dataclasses import asdictfrom datetime import UTC, datetime, timedeltafrom typing import Anyfrom uuid import UUID, uuid4@@ -8,8 +9,9 @@ import time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import MagicMock, patch-from django.db import OperationalError, connection+from django.db import OperationalError, connection, transactionfrom django.test.utils import CaptureQueriesContext+from django.utils import timezonefrom celery.exceptions import Retryfrom parameterized import parameterized@@ -22,8 +24,8 @@ from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom products.alerts_platform.backend.facade import testing as platform_testing-from products.alerts_platform.backend.facade.api import list_configurations-from products.alerts_platform.backend.facade.contracts import SourceKind+from products.alerts_platform.backend.facade.api import get_configuration, list_configurations, upsert_configuration+from products.alerts_platform.backend.facade.contracts import PlatformConfigurationSnapshot, SourceKindfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplatefrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cdp.backend.templates.fixtures import template_pagerduty, template_slack@@ -34,8 +36,10 @@ from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEventfrom products.logs.backend.platform_alert_backfill import (backfill_platform_alert_configurations,disable_platform_alert_configurations,+ follow_logs_alert,+ platform_upsert_of,)-from products.logs.backend.platform_cutover import cut_over_team+from products.logs.backend.platform_cutover import cut_over_team, hand_overfrom products.logs.backend.presentation.views.alerts_api import (ALLOWED_WINDOW_MINUTES,MAX_ALERTS_PER_TEAM,@@ -2340,6 +2344,134 @@ class TestLogsAlertAPI(APIBaseTest):f"offset={offset_min}min: expected {expected_count}, got {rolling_by_offset.get(offset_min)}")+ # --- Alerts the platform owns ---++ def _owned_by_the_platform(self, **overrides) -> dict:+ created = self._create_via_api(**overrides)+ with transaction.atomic():+ alert = LogsAlertConfiguration.objects.select_for_update().get(pk=created["id"])+ assert hand_over(alert, timezone.now())+ return created++ def _copy(self, alert_id: str) -> PlatformConfigurationSnapshot:+ with team_scope(self.team.id):+ return platform_testing.copy_of(UUID(alert_id))++ def test_each_api_writes_both_rows_of_an_alert_the_platform_owns(self) -> None:+ created = self._owned_by_the_platform()+ copy = self._copy(created["id"])++ with patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True):+ platform_edit = self.client.patch(+ f"/api/projects/{self.team.id}/platform_alerts/{copy.id}/",+ {"name": "Edited on the platform", "grouping": {"mode": "by_result_labels", "keys": ["service_name"]}},+ format="json",+ )+ logs_edit = self.client.patch(f"{self.base_url}{created['id']}/", {"threshold_count": 50}, format="json")++ assert platform_edit.status_code == status.HTTP_200_OK, platform_edit.json()+ assert logs_edit.status_code == status.HTTP_200_OK, logs_edit.json()+ assert logs_edit.json()["name"] == "Edited on the platform"+ with team_scope(self.team.id):+ view = get_configuration(+ team_id=self.team.id, source_kinds=[SourceKind.LOGS.value], configuration_id=copy.id+ )+ assert view is not None+ assert (view.name, view.source_config["condition"]["threshold_count"], view.grouping.keys) == (+ "Edited on the platform",+ 50,+ ("service_name",),+ )++ @parameterized.expand(+ [+ ("backfill", lambda stale: upsert_configuration(platform_upsert_of(stale))),+ ("delayed_follow", follow_logs_alert),+ ]+ )+ def test_a_snapshot_read_before_a_disable_does_not_turn_the_copy_back_on(self, _name: str, write: Any) -> None:+ created = self._owned_by_the_platform()+ stale = LogsAlertConfiguration.objects.get(pk=created["id"])++ response = self.client.patch(f"{self.base_url}{created['id']}/", {"enabled": False}, format="json")+ assert response.status_code == status.HTTP_200_OK, response.json()+ write(stale)++ with team_scope(self.team.id):+ view = get_configuration(+ team_id=self.team.id,+ source_kinds=[SourceKind.LOGS.value],+ configuration_id=self._copy(created["id"]).id,+ )+ assert view is not None and view.enabled is False++ def test_the_platform_api_refuses_an_edit_of_an_environments_alert(self) -> None:+ environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")+ alert = LogsAlertConfiguration.objects.create(+ team=environment,+ name="Environment errors",+ filters={"severityLevels": ["error"]},+ threshold_count=10,+ owner="platform",+ )+ # The copy lands on the project, as every copy of an environment's alert does.+ with team_scope(self.team.id):+ copy = platform_testing.create_configuration(**{**asdict(platform_upsert_of(alert)), "owner": "platform"})++ with patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True):+ response = self.client.patch(+ f"/api/projects/{self.team.id}/platform_alerts/{copy.id}/",+ {"name": "Renamed", "enabled": False},+ format="json",+ )++ assert response.status_code == status.HTTP_409_CONFLICT, response.json()+ alert.refresh_from_db()+ with team_scope(self.team.id):+ view = get_configuration(+ team_id=self.team.id, source_kinds=[SourceKind.LOGS.value], configuration_id=copy.id+ )+ assert view is not None+ assert (alert.name, alert.enabled, view.name, view.enabled) == (+ "Environment errors",+ True,+ "Environment errors",+ True,+ )++ def test_a_new_alert_in_a_team_the_platform_has_begun_taking_over_starts_on_the_platform(self) -> None:+ self._owned_by_the_platform()++ created = self._create_via_api(name="Added after the cutover")++ assert LogsAlertConfiguration.objects.get(pk=created["id"]).platform_owned+ assert self._copy(created["id"]).owner == "platform"++ def test_turning_a_broken_platform_alert_off_and_on_on_the_logs_page_revives_it(self) -> None:+ created = self._owned_by_the_platform()+ with team_scope(self.team.id):+ platform_testing.set_check_status(self._copy(created["id"]).id, "broken")++ for enabled in (False, True):+ response = self.client.patch(f"{self.base_url}{created['id']}/", {"enabled": enabled}, format="json")+ assert response.status_code == status.HTTP_200_OK, response.json()++ assert self._copy(created["id"]).check_status == "ok"++ def test_deleting_an_alert_the_platform_owns_deletes_its_copy(self) -> None:+ created = self._owned_by_the_platform()++ response = self.client.delete(f"{self.base_url}{created['id']}/")++ assert response.status_code == status.HTTP_204_NO_CONTENT+ with team_scope(self.team.id):+ assert (+ list_configurations(+ team_id=self.team.id, source_kinds=[SourceKind.LOGS.value], limit=10, offset=0+ ).configurations+ == ()+ )+class TestSimulateEvaluatorParity(ClickhouseTestMixin, APIBaseTest):CLASS_DATA_LEVEL_SETUP = Truediff --git a/products/logs/backend/test/test_platform_cutover.py b/products/logs/backend/test/test_platform_cutover.pyindex 55a2040fb74d..656de659d611 100644--- a/products/logs/backend/test/test_platform_cutover.py+++ b/products/logs/backend/test/test_platform_cutover.py@@ -8,6 +8,7 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom posthog.models.scoping import team_scope+from posthog.models.team import Teamfrom products.alerts.backend.facade.contracts import HogFunctionPathReasonfrom products.alerts_platform.backend.facade import testing as platform_testing@@ -112,6 +113,16 @@ class TestPlatformCutover(APIBaseTest):alert.refresh_from_db()assert alert.owner == "source"+ def test_an_alert_in_an_environment_stays_with_logs(self) -> None:+ environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")+ alert = self._alert(team=environment)++ (result,) = cut_over_team(environment.id, now=NOW)++ assert result.skipped == CutoverSkip.ENVIRONMENT+ alert.refresh_from_db()+ assert alert.owner == "source"+def test_a_refused_cutover_leaves_the_firing_platform_copy_as_it_was(self) -> None:alert = self._alert()upsert_configuration(platform_upsert_of(alert))diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e230e6deb50b..1edc7fa1fefe 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -65332,6 +65332,7 @@ export namespace Schemas {/*** Number of matching log entries in the window that breaches the threshold. Use 0 with the above operator to fire on any matching log.* @minimum 0+ * @maximum 2147483647*/threshold_count: number;/** Whether the alert fires when the count is above or below the threshold. */