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.

fix(logs): prevent malformed alert filters from bricking scheduler (#58827)

Frank Hamand48f19fd23863
diff --git a/products/logs/backend/alert_check_query.py b/products/logs/backend/alert_check_query.py
index 245e54eb6dd4..d357ee0e4c21 100644
--- a/products/logs/backend/alert_check_query.py
+++ b/products/logs/backend/alert_check_query.py
@@ -565,11 +565,19 @@ def is_projection_eligible(filters: dict) -> bool:
service_name, severity_text, resource_fingerprint), so it covers these two
filter types. Any filterGroup values reference columns outside the projection
and require a raw table scan.
+
+ Returns False on malformed shapes so the caller falls through to the raw-scan
+ path, where `PropertyGroupFilter.model_validate` surfaces a per-alert error
+ instead of crashing discovery for every alert in the project.
"""
filter_group = filters.get("filterGroup")
if not filter_group:
return True
+ if not isinstance(filter_group, dict):
+ return False
for group in filter_group.get("values", []):
+ if not isinstance(group, dict):
+ return False
if group.get("values"):
return False
return True
diff --git a/products/logs/backend/alerts_api.py b/products/logs/backend/alerts_api.py
index 5974e3f1f060..e6976bc05ab1 100644
--- a/products/logs/backend/alerts_api.py
+++ b/products/logs/backend/alerts_api.py
@@ -10,12 +10,15 @@ from django.utils import timezone
from drf_spectacular.utils import extend_schema, extend_schema_field
from loginas.utils import is_impersonated_session
+from pydantic import ValidationError as PydanticValidationError
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.schema import PropertyGroupFilter
+
from posthog.api.hog_function import HogFunctionSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
@@ -511,11 +514,20 @@ def _validate_filters(filters: dict) -> None:
raise ValidationError({"filters": "Must be a JSON object."})
has_severity = bool(filters.get("severityLevels"))
has_services = bool(filters.get("serviceNames"))
- has_filter_group = bool(filters.get("filterGroup"))
+ filter_group = filters.get("filterGroup")
+ has_filter_group = bool(filter_group)
if not (has_severity or has_services or has_filter_group):
raise ValidationError(
{"filters": "At least one filter is required (severityLevels, serviceNames, or filterGroup)."}
)
+ if has_filter_group:
+ # Validate filterGroup shape against PropertyGroupFilter so malformed
+ # payloads (e.g. a bare list at the top level) are rejected at write
+ # time rather than bricking the alerting worker's cohort discovery.
+ try:
+ PropertyGroupFilter.model_validate(filter_group)
+ except PydanticValidationError as e:
+ raise ValidationError({"filters": f"Invalid filterGroup shape: {e.errors()[0]['msg']}"})
class LogsAlertEventSerializer(serializers.ModelSerializer):
diff --git a/products/logs/backend/migrations/0012_alter_logsalertevent_kind.py b/products/logs/backend/migrations/0012_alter_logsalertevent_kind.py
new file mode 100644
index 000000000000..1d68efbdcfb8
--- /dev/null
+++ b/products/logs/backend/migrations/0012_alter_logsalertevent_kind.py
@@ -0,0 +1,30 @@
+# Generated by Django 5.2.13 on 2026-05-18 13:25
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("logs", "0011_backfill_first_enabled_at"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="logsalertevent",
+ name="kind",
+ field=models.CharField(
+ choices=[
+ ("check", "Check"),
+ ("reset", "Reset"),
+ ("enable", "Enable"),
+ ("disable", "Disable"),
+ ("snooze", "Snooze"),
+ ("unsnooze", "Unsnooze"),
+ ("threshold_change", "Threshold change"),
+ ("broken_config", "Broken config"),
+ ],
+ default="check",
+ max_length=32,
+ ),
+ ),
+ ]
diff --git a/products/logs/backend/migrations/max_migration.txt b/products/logs/backend/migrations/max_migration.txt
index 61366cd1c91e..a0a073983d26 100644
--- a/products/logs/backend/migrations/max_migration.txt
+++ b/products/logs/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0011_backfill_first_enabled_at
+0012_alter_logsalertevent_kind
diff --git a/products/logs/backend/models.py b/products/logs/backend/models.py
index c6ac5b525407..7e42a665dd3f 100644
--- a/products/logs/backend/models.py
+++ b/products/logs/backend/models.py
@@ -205,6 +205,7 @@ class LogsAlertEvent(UUIDModel):
SNOOZE = "snooze", "Snooze"
UNSNOOZE = "unsnooze", "Unsnooze"
THRESHOLD_CHANGE = "threshold_change", "Threshold change"
+ BROKEN_CONFIG = "broken_config", "Broken config"
alert = models.ForeignKey(
LogsAlertConfiguration,
diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.py
index 52fe3a63f674..abeb675ac147 100644
--- a/products/logs/backend/temporal/activities.py
+++ b/products/logs/backend/temporal/activities.py
@@ -17,6 +17,9 @@ from django.db.utils import IntegrityError
import structlog
import temporalio.activity
+from pydantic import ValidationError as PydanticValidationError
+
+from posthog.schema import PropertyGroupFilter
from posthog.cdp.internal_events import InternalEventEvent, produce_internal_event
from posthog.exceptions_capture import capture_exception
@@ -40,6 +43,7 @@ from products.logs.backend.alert_state_machine import (
AlertCheckOutcome,
AlertState,
CheckResult,
+ ControlPlaneOutcome,
NotificationAction,
apply_outcome,
evaluate_alert_check,
@@ -371,6 +375,59 @@ def _discover_cohorts_sync() -> DiscoverCohortsOutput:
return DiscoverCohortsOutput(manifests=manifests, batch_size=MAX_COHORTS_PER_BATCH)
+def _detect_broken_filter_config(filters: object) -> str | None:
+ """Returns a human-readable reason if `filters` is structurally broken in a way
+ that will permanently prevent the alert from running. Returns None if the shape
+ is valid enough to attempt evaluation.
+ """
+ if not isinstance(filters, dict):
+ return f"filters must be a JSON object, got {type(filters).__name__}"
+ filter_group = filters.get("filterGroup")
+ if not filter_group:
+ return None
+ try:
+ PropertyGroupFilter.model_validate(filter_group)
+ except PydanticValidationError as e:
+ return f"Invalid filterGroup shape: {e.errors()[0]['msg']}"
+ return None
+
+
+def _mark_alert_broken_for_bad_config(alert_id: str, reason: str) -> None:
+ """Transition an alert to BROKEN because its configuration is structurally
+ invalid and can never succeed. Runs in the same sync DB pool as discovery —
+ each call is its own short transaction so a failure on one row doesn't
+ roll back the others.
+ """
+ try:
+ with transaction.atomic():
+ alert = LogsAlertConfiguration.objects.select_for_update().get(pk=alert_id)
+ if alert.state == LogsAlertConfiguration.State.BROKEN:
+ return
+ state_before = alert.state
+ outcome = ControlPlaneOutcome(
+ new_state=AlertState.BROKEN,
+ consecutive_failures=alert.consecutive_failures,
+ )
+ update_fields = apply_outcome(alert, outcome)
+ LogsAlertEvent.objects.create(
+ alert=alert,
+ kind=LogsAlertEvent.Kind.BROKEN_CONFIG,
+ threshold_breached=False,
+ state_before=state_before,
+ state_after=outcome.new_state.value,
+ error_message=reason,
+ )
+ alert.save(update_fields=update_fields)
+ except Exception as e:
+ logger.exception(
+ "Failed to mark alert BROKEN for invalid config",
+ alert_id=alert_id,
+ reason=reason,
+ error=str(e),
+ )
+ capture_exception(e)
+
+
def _cohort_manifests_from_alerts(
rows: Sequence[dict],
*,
@@ -381,22 +438,46 @@ def _cohort_manifests_from_alerts(
Cohort key + size-cap logic on plain dicts (no Django model hydration)
so it stays cheap at scale and produces serialisable manifests for the
- workflow.
+ workflow. Alerts with structurally broken filter configs are transitioned
+ to BROKEN and excluded from the manifests — they would never succeed
+ anyway, and one bad row must not brick discovery for the rest of the
+ project.
"""
grouped: defaultdict[tuple[int, int, int, int, bool, datetime], list[str]] = defaultdict(list)
for row in rows:
- nca = row["next_check_at"] if row["next_check_at"] is not None else now
- date_to = resolve_alert_date_to(nca, checkpoint)
- projection_eligible = is_projection_eligible(row["filters"])
- key = (
- row["team_id"],
- row["window_minutes"],
- row["evaluation_periods"],
- row["check_interval_minutes"],
- projection_eligible,
- date_to,
- )
- grouped[key].append(str(row["id"]))
+ try:
+ broken_reason = _detect_broken_filter_config(row["filters"])
+ if broken_reason is not None:
+ logger.warning(
+ "Marking alert BROKEN due to invalid filter config",
+ alert_id=str(row["id"]),
+ team_id=row.get("team_id"),
+ reason=broken_reason,
+ )
+ _mark_alert_broken_for_bad_config(str(row["id"]), broken_reason)
+ continue
+ nca = row["next_check_at"] if row["next_check_at"] is not None else now
+ date_to = resolve_alert_date_to(nca, checkpoint)
+ projection_eligible = is_projection_eligible(row["filters"])
+ key = (
+ row["team_id"],
+ row["window_minutes"],
+ row["evaluation_periods"],
+ row["check_interval_minutes"],
+ projection_eligible,
+ date_to,
+ )
+ grouped[key].append(str(row["id"]))
+ except Exception as e:
+ # Any unexpected per-row failure must not brick discovery for the
+ # rest of the project.
+ logger.exception(
+ "Skipping alert in cohort discovery due to malformed row",
+ alert_id=str(row.get("id")),
+ team_id=row.get("team_id"),
+ error=str(e),
+ )
+ capture_exception(e)
manifests: list[CohortManifest] = []
for (team_id, _wm, _ep, _cim, projection_eligible, date_to), alert_ids in grouped.items():
diff --git a/products/logs/backend/test/test_alert_check_query.py b/products/logs/backend/test/test_alert_check_query.py
index 845ef1231564..5feaaa87ec99 100644
--- a/products/logs/backend/test/test_alert_check_query.py
+++ b/products/logs/backend/test/test_alert_check_query.py
@@ -85,6 +85,16 @@ class TestIsProjectionEligible(unittest.TestCase):
},
False,
),
+ (
+ "filter_group_is_list",
+ {"filterGroup": [{"type": "AND", "values": []}]},
+ False,
+ ),
+ (
+ "filter_group_inner_value_not_dict",
+ {"filterGroup": {"type": "AND", "values": ["not-a-dict"]}},
+ False,
+ ),
(
"attribute_filter_present",
{
diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.py
index c6e821009b99..053a667e21d0 100644
--- a/products/logs/backend/test/test_alerts_api.py
+++ b/products/logs/backend/test/test_alerts_api.py
@@ -367,6 +367,23 @@ class TestLogsAlertAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["attr"] == "filters"
+ @parameterized.expand(
+ [
+ ("filter_group_is_list", {"filterGroup": [{"type": "AND", "values": []}]}),
+ ("filter_group_is_string", {"filterGroup": "AND"}),
+ ("filter_group_missing_type", {"filterGroup": {"values": []}}),
+ ("filter_group_invalid_operator", {"filterGroup": {"type": "XOR", "values": []}}),
+ ]
+ )
+ def test_create_rejects_malformed_filter_group(self, _name, filters):
+ response = self.client.post(
+ self.base_url,
+ self._valid_payload(filters=filters),
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "filters"
+
@parameterized.expand(
[
("severity_levels", {"severityLevels": ["error"]}),
diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.py
index 0c57fc0f695f..5f5d33403452 100644
--- a/products/logs/backend/test/test_logs_alerting_activities.py
+++ b/products/logs/backend/test/test_logs_alerting_activities.py
@@ -1613,6 +1613,81 @@ class TestCohortManifest(unittest.TestCase):
assert sorted(len(m.alert_ids) for m in manifests) == [1, 2, 2]
+ def test_manifests_exclude_alert_with_malformed_filter_group(self):
+ # Exact prod-failure shape: `filterGroup` is a list, not a dict. Before
+ # the fix this crashed `is_projection_eligible` with AttributeError and
+ # bricked discovery for every alert in the project. After the fix the
+ # malformed alert is detected, transitioned to BROKEN out-of-band, and
+ # excluded from this batch's manifests; the healthy alert is still
+ # scheduled.
+ from products.logs.backend.temporal.activities import _cohort_manifests_from_alerts
+
+ rows: list[dict[str, Any]] = [
+ {
+ "id": "019dec00-0000-0000-0000-000000000001",
+ "team_id": 1,
+ "window_minutes": 5,
+ "evaluation_periods": 1,
+ "check_interval_minutes": 5,
+ "filters": {"serviceNames": ["healthy"]},
+ "next_check_at": None,
+ },
+ {
+ "id": "019dec00-0000-0000-0000-000000000002",
+ "team_id": 1,
+ "window_minutes": 5,
+ "evaluation_periods": 1,
+ "check_interval_minutes": 5,
+ "filters": {"filterGroup": [{"type": "AND", "values": []}]},
+ "next_check_at": None,
+ },
+ ]
+ now = datetime(2026, 5, 5, 10, 0, tzinfo=UTC)
+
+ with (
+ patch("products.logs.backend.temporal.activities.resolve_alert_date_to", return_value=now),
+ patch("products.logs.backend.temporal.activities._mark_alert_broken_for_bad_config") as mark_broken,
+ ):
+ manifests = _cohort_manifests_from_alerts(rows, now=now, checkpoint=None)
+
+ all_alert_ids = sorted(aid for m in manifests for aid in m.alert_ids)
+ assert all_alert_ids == ["019dec00-0000-0000-0000-000000000001"]
+ mark_broken.assert_called_once()
+ assert mark_broken.call_args.args[0] == "019dec00-0000-0000-0000-000000000002"
+
+ def test_manifests_skip_catastrophically_broken_row(self):
+ # A row missing required keys (e.g. corrupt projection) must not crash
+ # discovery for healthy alerts in the same project.
+ from products.logs.backend.temporal.activities import _cohort_manifests_from_alerts
+
+ rows: list[dict[str, Any]] = [
+ {
+ "id": "019dec00-0000-0000-0000-000000000001",
+ "team_id": 1,
+ "window_minutes": 5,
+ "evaluation_periods": 1,
+ "check_interval_minutes": 5,
+ "filters": {"serviceNames": ["healthy"]},
+ "next_check_at": None,
+ },
+ # Missing window_minutes — triggers KeyError, must be skipped.
+ {
+ "id": "019dec00-0000-0000-0000-000000000002",
+ "team_id": 1,
+ "evaluation_periods": 1,
+ "check_interval_minutes": 5,
+ "filters": {},
+ "next_check_at": None,
+ },
+ ]
+ now = datetime(2026, 5, 5, 10, 0, tzinfo=UTC)
+
+ with patch("products.logs.backend.temporal.activities.resolve_alert_date_to", return_value=now):
+ manifests = _cohort_manifests_from_alerts(rows, now=now, checkpoint=None)
+
+ all_alert_ids = [aid for m in manifests for aid in m.alert_ids]
+ assert all_alert_ids == ["019dec00-0000-0000-0000-000000000001"]
+
class TestDiscoverCohortsActivity(NonAtomicBaseTest):
CLASS_DATA_LEVEL_SETUP = False
@@ -1653,6 +1728,49 @@ class TestDiscoverCohortsActivity(NonAtomicBaseTest):
assert len(result.manifests) == 1
assert len(result.manifests[0].alert_ids) == 2
+ @freeze_time("2026-05-05T10:00:00Z")
+ def test_transitions_alert_with_broken_filter_config_to_broken(self):
+ from products.logs.backend.temporal.activities import DiscoverCohortsInput, discover_cohorts_activity
+
+ healthy = LogsAlertConfiguration.objects.create(
+ team=self.team,
+ name="healthy",
+ threshold_count=1,
+ threshold_operator="above",
+ window_minutes=5,
+ evaluation_periods=1,
+ filters={"serviceNames": ["ok"]},
+ enabled=True,
+ next_check_at=None,
+ )
+ broken = LogsAlertConfiguration.objects.create(
+ team=self.team,
+ name="broken",
+ threshold_count=1,
+ threshold_operator="above",
+ window_minutes=5,
+ evaluation_periods=1,
+ # Exact prod-failure shape that bricked discovery on 2026-05-13.
+ filters={"filterGroup": [{"type": "AND", "values": []}]},
+ enabled=True,
+ next_check_at=None,
+ )
+
+ result = asyncio.run(discover_cohorts_activity(DiscoverCohortsInput()))
+
+ manifest_alert_ids = {aid for m in result.manifests for aid in m.alert_ids}
+ assert str(healthy.id) in manifest_alert_ids
+ assert str(broken.id) not in manifest_alert_ids
+
+ broken.refresh_from_db()
+ assert broken.state == LogsAlertConfiguration.State.BROKEN
+
+ from products.logs.backend.models import LogsAlertEvent
+
+ event = LogsAlertEvent.objects.get(alert=broken, kind=LogsAlertEvent.Kind.BROKEN_CONFIG)
+ assert event.state_after == LogsAlertConfiguration.State.BROKEN
+ assert event.error_message is not None and "filterGroup" in event.error_message
+
class TestCohortFromManifest(unittest.TestCase):
def test_reconstructs_cohort_from_manifest_and_alerts(self):
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
index 5be7ee3c0b95..724aae0185d9 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
@@ -114,6 +114,7 @@ const CONTROL_PLANE_DESCRIPTIONS: Record<
[LogsAlertEventKindEnumApi.Snooze]: { label: 'Snoozed', type: 'highlight' },
[LogsAlertEventKindEnumApi.Unsnooze]: { label: 'Unsnoozed', type: 'highlight' },
[LogsAlertEventKindEnumApi.ThresholdChange]: { label: 'Threshold changed', type: 'completion' },
+ [LogsAlertEventKindEnumApi.BrokenConfig]: { label: 'Broken config', type: 'caution' },
}
function describeEvent(event: LogsAlertEventApi): EventDescription {
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 5395ac4e6ad0..9de9490380ff 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -420,6 +420,7 @@ export interface LogsAlertDeleteDestinationApi {
* `snooze` - Snooze
* `unsnooze` - Unsnooze
* `threshold_change` - Threshold change
+ * `broken_config` - Broken config
*/
export type LogsAlertEventKindEnumApi = (typeof LogsAlertEventKindEnumApi)[keyof typeof LogsAlertEventKindEnumApi]
@@ -431,6 +432,7 @@ export const LogsAlertEventKindEnumApi = {
Snooze: 'snooze',
Unsnooze: 'unsnooze',
ThresholdChange: 'threshold_change',
+ BrokenConfig: 'broken_config',
} as const
export interface LogsAlertEventApi {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index aac348d285cc..e354d579168c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19959,6 +19959,7 @@ export namespace Schemas {
* `snooze` - Snooze
* `unsnooze` - Unsnooze
* `threshold_change` - Threshold change
+ * `broken_config` - Broken config
*/
export type LogsAlertEventKindEnum = typeof LogsAlertEventKindEnum[keyof typeof LogsAlertEventKindEnum];
@@ -19971,6 +19972,7 @@ export namespace Schemas {
Snooze: 'snooze',
Unsnooze: 'unsnooze',
ThresholdChange: 'threshold_change',
+ BrokenConfig: 'broken_config',
} as const;
export interface LogsAlertEvent {