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.

refactor(alerts): move the threshold bound into source_config (#111201)

Jimmy Zhu81155e1e0c92
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index e16f02f2d22d..88e540ce3d7c 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -89,6 +89,18 @@ class SourceEvaluationInputs:
batch_key: AlertBatchKey
+# Where a source keeps its bound inside `source_config`. Each source gives it its own shape and
+# the platform interprets none of it: the history row snapshots it, so a reader sees the bound a
+# check was evaluated against.
+SOURCE_CONDITION_KEY: Final = "condition"
+
+
+def source_condition(source_config: dict[str, Any]) -> dict[str, Any]:
+ """A source's bound, or an empty one when the stored value is missing or not an object."""
+ condition = source_config.get(SOURCE_CONDITION_KEY)
+ return condition if isinstance(condition, dict) else {}
+
+
@frozen
class PlatformAlertCheckInput:
"""One configuration and its runtime state, as a source adapter reads it.
@@ -101,9 +113,6 @@ class PlatformAlertCheckInput:
team_id: int
name: str
source_config: dict[str, Any]
- threshold_count: int
- threshold_operator: str
- window_minutes: int
check_interval_minutes: int
evaluation_periods: int
datapoints_to_alarm: int
@@ -122,6 +131,10 @@ class PlatformAlertCheckInput:
"""Satisfies the logs query layer, which names this field `filters`."""
return self.source_config
+ @property
+ def condition(self) -> dict[str, Any]:
+ return source_condition(self.source_config)
+
@frozen
class PlatformAlertUpsert:
@@ -133,9 +146,6 @@ class PlatformAlertUpsert:
enabled: bool
source_kind: SourceKind
source_config: dict[str, Any]
- threshold_count: int
- threshold_operator: str
- window_minutes: int
check_interval_minutes: int
evaluation_periods: int
datapoints_to_alarm: int
@@ -378,9 +388,6 @@ class PlatformAlertConfigurationView:
enabled: bool
source_kind: str
source_config: dict[str, Any]
- threshold_count: int
- threshold_operator: str
- window_minutes: int
check_interval_minutes: int
recurrence_unit: str | None
anchor_time: str | None
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index 1081ad55f549..d70bd3c739ec 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -16,6 +16,7 @@ from products.alerts_platform.backend.facade.contracts import (
PlatformAlertCheckInput,
PlatformAlertOutcome,
PlatformAlertUpsert,
+ source_condition,
)
from products.alerts_platform.backend.facade.platform_metrics import increment_history_rows_dropped, safe_record
from products.alerts_platform.backend.facade.scheduling import (
@@ -112,9 +113,6 @@ def _check(c: PlatformAlertConfiguration, alert: PlatformAlert | None) -> Platfo
team_id=c.team_id,
name=c.name,
source_config=c.source_config,
- threshold_count=c.threshold_count,
- threshold_operator=c.threshold_operator,
- window_minutes=c.window_minutes,
check_interval_minutes=c.check_interval_minutes,
evaluation_periods=c.evaluation_periods,
datapoints_to_alarm=c.datapoints_to_alarm,
@@ -151,11 +149,12 @@ def _condition_snapshot(configuration: PlatformAlertConfiguration) -> dict[str,
only through a hand-run backfill command, and only for a configuration already copied whose
source row changed since. The row then states the new condition beside a verdict measured
against the old one. Carry the snapshot on the outcome if that stops being acceptable.
+
+ The source's bound is flattened in beside the platform's own fields, so a reader finds it at
+ the top level whatever shape the source gives it.
"""
return {
- "threshold_count": configuration.threshold_count,
- "threshold_operator": configuration.threshold_operator,
- "window_minutes": configuration.window_minutes,
+ **source_condition(configuration.source_config),
"evaluation_periods": configuration.evaluation_periods,
"datapoints_to_alarm": configuration.datapoints_to_alarm,
"cooldown_minutes": configuration.cooldown_minutes,
@@ -297,9 +296,6 @@ def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:
"enabled": upsert.enabled,
"source_kind": upsert.source_kind.value,
"source_config": upsert.source_config,
- "threshold_count": upsert.threshold_count,
- "threshold_operator": upsert.threshold_operator,
- "window_minutes": upsert.window_minutes,
"check_interval_minutes": upsert.check_interval_minutes,
"recurrence_unit": upsert.recurrence_unit,
"anchor_time": anchor_time,
diff --git a/products/alerts_platform/backend/logic/platform_reads.py b/products/alerts_platform/backend/logic/platform_reads.py
index 623bb56e4b53..cb214db27dcc 100644
--- a/products/alerts_platform/backend/logic/platform_reads.py
+++ b/products/alerts_platform/backend/logic/platform_reads.py
@@ -36,9 +36,6 @@ def _configuration_view(configuration: PlatformAlertConfiguration) -> PlatformAl
enabled=configuration.enabled,
source_kind=configuration.source_kind,
source_config=configuration.source_config,
- threshold_count=configuration.threshold_count,
- threshold_operator=configuration.threshold_operator,
- window_minutes=configuration.window_minutes,
check_interval_minutes=configuration.check_interval_minutes,
recurrence_unit=configuration.recurrence_unit,
anchor_time=configuration.anchor_time,
diff --git a/products/alerts_platform/backend/migrations/0004_threshold_fields_nullable.py b/products/alerts_platform/backend/migrations/0004_threshold_fields_nullable.py
new file mode 100644
index 000000000000..ce443b0a9a10
--- /dev/null
+++ b/products/alerts_platform/backend/migrations/0004_threshold_fields_nullable.py
@@ -0,0 +1,27 @@
+# Generated by Django 5.2.17 on 2026-10-02 22:34
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("alerts_platform", "0003_recurrence"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="platformalertconfiguration",
+ name="threshold_count",
+ field=models.PositiveIntegerField(blank=True, null=True),
+ ),
+ migrations.AlterField(
+ model_name="platformalertconfiguration",
+ name="threshold_operator",
+ field=models.CharField(blank=True, max_length=16, null=True),
+ ),
+ migrations.AlterField(
+ model_name="platformalertconfiguration",
+ name="window_minutes",
+ field=models.PositiveIntegerField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/alerts_platform/backend/migrations/0005_threshold_into_source_config.py b/products/alerts_platform/backend/migrations/0005_threshold_into_source_config.py
new file mode 100644
index 000000000000..686de3ff7f29
--- /dev/null
+++ b/products/alerts_platform/backend/migrations/0005_threshold_into_source_config.py
@@ -0,0 +1,28 @@
+from django.db import migrations
+
+# Only the logs backfill wrote these columns, so the three of them are a logs row's whole bound.
+# A row that already has a condition is left alone, which makes a retry under `bin/migrate` a no-op.
+COPY_BOUND_INTO_SOURCE_CONFIG = """
+-- migration-analyzer: safe reason=holds only the copies a manual logs backfill made, one row per logs alert, and nothing reads it on a request path
+UPDATE alerts_platformalertconfiguration
+SET source_config = source_config || jsonb_build_object(
+ 'condition',
+ jsonb_build_object(
+ 'threshold_count', threshold_count,
+ 'threshold_operator', threshold_operator,
+ 'window_minutes', window_minutes
+ )
+)
+WHERE threshold_count IS NOT NULL
+ AND NOT source_config ? 'condition'
+"""
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("alerts_platform", "0004_threshold_fields_nullable"),
+ ]
+
+ operations = [
+ migrations.RunSQL(COPY_BOUND_INTO_SOURCE_CONFIG, reverse_sql=migrations.RunSQL.noop),
+ ]
diff --git a/products/alerts_platform/backend/migrations/max_migration.txt b/products/alerts_platform/backend/migrations/max_migration.txt
index e732f6f57e43..631c1b241ca1 100644
--- a/products/alerts_platform/backend/migrations/max_migration.txt
+++ b/products/alerts_platform/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0003_recurrence
+0005_threshold_into_source_config
diff --git a/products/alerts_platform/backend/models/platform_alert.py b/products/alerts_platform/backend/models/platform_alert.py
index 2adc7f4cb99b..45a30044df9e 100644
--- a/products/alerts_platform/backend/models/platform_alert.py
+++ b/products/alerts_platform/backend/models/platform_alert.py
@@ -48,10 +48,10 @@ class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDModel):
source_kind = models.CharField(max_length=32, choices=SourceKind.choices)
source_config = models.JSONField(default=dict)
- threshold_count = models.PositiveIntegerField()
- threshold_operator = models.CharField(max_length=16)
-
- window_minutes = models.PositiveIntegerField()
+ # Retired, because a source keeps its bound in `source_config["condition"]`. Nothing reads these.
+ threshold_count = models.PositiveIntegerField(null=True, blank=True)
+ threshold_operator = models.CharField(max_length=16, null=True, blank=True)
+ window_minutes = models.PositiveIntegerField(null=True, blank=True)
check_interval_minutes = models.PositiveIntegerField()
diff --git a/products/alerts_platform/backend/presentation/views/platform_alert.py b/products/alerts_platform/backend/presentation/views/platform_alert.py
index a4a236cf74d2..96ed6c93be3a 100644
--- a/products/alerts_platform/backend/presentation/views/platform_alert.py
+++ b/products/alerts_platform/backend/presentation/views/platform_alert.py
@@ -61,16 +61,10 @@ class PlatformAlertConfigurationSerializer(serializers.Serializer):
source_config = serializers.DictField(
child=serializers.JSONField(),
read_only=True,
- help_text="Source-specific query settings. The shape depends on source_kind.",
- )
- threshold_count = serializers.IntegerField(
- read_only=True, help_text="Count the evaluated value is compared against."
- )
- threshold_operator = serializers.CharField(
- read_only=True, help_text="Comparison operator applied between the value and threshold_count."
- )
- window_minutes = serializers.IntegerField(
- read_only=True, help_text="Length of the evaluated time window, in minutes."
+ help_text=(
+ "Source-specific settings. The shape depends on source_kind. The bound the alert is evaluated "
+ "against is under the condition key."
+ ),
)
check_interval_minutes = serializers.IntegerField(
read_only=True,
diff --git a/products/alerts_platform/backend/tests/api/test_platform_alert.py b/products/alerts_platform/backend/tests/api/test_platform_alert.py
index 3d00e9e06e0c..a2a042cbc9a9 100644
--- a/products/alerts_platform/backend/tests/api/test_platform_alert.py
+++ b/products/alerts_platform/backend/tests/api/test_platform_alert.py
@@ -29,9 +29,6 @@ class TestPlatformAlertAPI(APIBaseTest):
name=name,
source_kind=PlatformAlertConfiguration.SourceKind.LOGS,
source_config={"service": "api"},
- threshold_count=10,
- threshold_operator="above",
- window_minutes=5,
check_interval_minutes=10,
legacy_configuration_id=legacy_configuration_id,
)
diff --git a/products/alerts_platform/backend/tests/test_delivery_thread_store.py b/products/alerts_platform/backend/tests/test_delivery_thread_store.py
index 3b51cb2b253f..335745a9c5ad 100644
--- a/products/alerts_platform/backend/tests/test_delivery_thread_store.py
+++ b/products/alerts_platform/backend/tests/test_delivery_thread_store.py
@@ -35,9 +35,6 @@ class TestDatabaseThreadStore(APIBaseTest):
name="API errors",
source_kind=PlatformAlertConfiguration.SourceKind.LOGS,
source_config={},
- threshold_count=10,
- threshold_operator="above",
- window_minutes=5,
check_interval_minutes=10,
)
self.store = DatabaseThreadStore(self.team.id)
diff --git a/products/alerts_platform/backend/tests/test_migration_0005_threshold_into_source_config.py b/products/alerts_platform/backend/tests/test_migration_0005_threshold_into_source_config.py
new file mode 100644
index 000000000000..fc31d9cca01f
--- /dev/null
+++ b/products/alerts_platform/backend/tests/test_migration_0005_threshold_into_source_config.py
@@ -0,0 +1,38 @@
+from typing import Any
+
+from posthog.test.base import TestMigrations
+
+FILTERS = {"serviceNames": ["api"], "severityLevels": ["error"]}
+
+
+class TestThresholdIntoSourceConfig(TestMigrations):
+ app = "alerts_platform"
+ migrate_from = "0004_threshold_fields_nullable"
+ migrate_to = "0005_threshold_into_source_config"
+
+ def setUpBeforeMigration(self, apps: Any) -> None:
+ Configuration = apps.get_model("alerts_platform", "PlatformAlertConfiguration")
+
+ def make(source_config: dict[str, Any]) -> Any:
+ return Configuration.objects.create(
+ team_id=self.team.id,
+ name="API errors",
+ source_kind="logs",
+ source_config=source_config,
+ threshold_count=10,
+ threshold_operator="above",
+ window_minutes=5,
+ check_interval_minutes=5,
+ )
+
+ self.copied = make(FILTERS).id
+ self.already_moved = make({**FILTERS, "condition": {"threshold_count": 99}}).id
+
+ def test_the_bound_moves_into_source_config_beside_the_filters(self) -> None:
+ Configuration = self.apps.get_model("alerts_platform", "PlatformAlertConfiguration") # type: ignore[union-attr]
+
+ assert Configuration.objects.get(id=self.copied).source_config == {
+ **FILTERS,
+ "condition": {"threshold_count": 10, "threshold_operator": "above", "window_minutes": 5},
+ }
+ assert Configuration.objects.get(id=self.already_moved).source_config["condition"] == {"threshold_count": 99}
diff --git a/products/alerts_platform/backend/tests/test_platform_announcement.py b/products/alerts_platform/backend/tests/test_platform_announcement.py
index f55831ff08ca..dff1b3b25af8 100644
--- a/products/alerts_platform/backend/tests/test_platform_announcement.py
+++ b/products/alerts_platform/backend/tests/test_platform_announcement.py
@@ -28,9 +28,6 @@ class TestAnnouncement(ClickhouseTestMixin, APIBaseTest):
name="API errors",
source_kind=PlatformAlertConfiguration.SourceKind.LOGS,
source_config={},
- threshold_count=10,
- threshold_operator="above",
- window_minutes=5,
check_interval_minutes=10,
)
diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
index e1535a82c0e5..d5b5073d91d7 100644
--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py
+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
@@ -33,10 +33,9 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
team=self.team,
name="API errors",
source_kind=PlatformAlertConfiguration.SourceKind.LOGS,
- source_config={},
- threshold_count=10,
- threshold_operator="above",
- window_minutes=5,
+ source_config={
+ "condition": {"threshold_count": 10, "threshold_operator": "above", "window_minutes": 5}
+ },
check_interval_minutes=10,
next_check_at=self.cutoff - timedelta(minutes=1),
)
@@ -148,10 +147,9 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
name="Snoozed alert",
enabled=True,
source_kind=SourceKind.LOGS,
- source_config={},
- threshold_count=1,
- threshold_operator="above",
- window_minutes=5,
+ source_config={
+ "condition": {"threshold_count": 1, "threshold_operator": "above", "window_minutes": 5}
+ },
check_interval_minutes=5,
evaluation_periods=1,
datapoints_to_alarm=1,
diff --git a/products/alerts_platform/backend/tests/test_temporal_workflows.py b/products/alerts_platform/backend/tests/test_temporal_workflows.py
index e56856f5d0cd..b6083fd0ac66 100644
--- a/products/alerts_platform/backend/tests/test_temporal_workflows.py
+++ b/products/alerts_platform/backend/tests/test_temporal_workflows.py
@@ -494,9 +494,6 @@ class TestDemandDiscovery(APIBaseTest):
enabled=enabled,
source_kind=PlatformAlertConfiguration.SourceKind.LOGS,
source_config={},
- threshold_count=1,
- threshold_operator="above",
- window_minutes=5,
check_interval_minutes=5,
next_check_at=None if minutes_ago is None else self.tick - dt.timedelta(minutes=minutes_ago),
)
diff --git a/products/alerts_platform/frontend/generated/api.schemas.ts b/products/alerts_platform/frontend/generated/api.schemas.ts
index 1c838aae4b0f..06f4fe09ed34 100644
--- a/products/alerts_platform/frontend/generated/api.schemas.ts
+++ b/products/alerts_platform/frontend/generated/api.schemas.ts
@@ -91,7 +91,7 @@ export interface PlatformAlertApi {
}
/**
- * Source-specific query settings. The shape depends on source_kind.
+ * Source-specific settings. The shape depends on source_kind. The bound the alert is evaluated against is under the condition key.
*/
export type PlatformAlertConfigurationApiSourceConfig = { [key: string]: unknown }
@@ -106,14 +106,8 @@ export interface PlatformAlertConfigurationApi {
*
* * `logs` - Logs */
readonly source_kind: PlatformAlertConfigurationSourceKindEnumApi
- /** Source-specific query settings. The shape depends on source_kind. */
+ /** Source-specific settings. The shape depends on source_kind. The bound the alert is evaluated against is under the condition key. */
readonly source_config: PlatformAlertConfigurationApiSourceConfig
- /** Count the evaluated value is compared against. */
- readonly threshold_count: number
- /** Comparison operator applied between the value and threshold_count. */
- readonly threshold_operator: string
- /** Length of the evaluated time window, in minutes. */
- readonly window_minutes: number
/** Minutes between scheduled checks. Applies when recurrence_unit is null. */
readonly check_interval_minutes: number
/** Calendar unit the alert recurs on. Null means it recurs on check_interval_minutes.
diff --git a/products/alerts_platform/frontend/generated/api.zod.schemas.ts b/products/alerts_platform/frontend/generated/api.zod.schemas.ts
index 748f37921c15..64f9f51b9a32 100644
--- a/products/alerts_platform/frontend/generated/api.zod.schemas.ts
+++ b/products/alerts_platform/frontend/generated/api.zod.schemas.ts
@@ -112,10 +112,9 @@ export const PlatformAlertConfigurationApi = zod.object({
.describe('Product whose data the alert evaluates.\n\n\* `logs` - Logs'),
source_config: zod
.record(zod.string(), zod.unknown())
- .describe('Source-specific query settings. The shape depends on source_kind.'),
- threshold_count: zod.number().describe('Count the evaluated value is compared against.'),
- threshold_operator: zod.string().describe('Comparison operator applied between the value and threshold_count.'),
- window_minutes: zod.number().describe('Length of the evaluated time window, in minutes.'),
+ .describe(
+ 'Source-specific settings. The shape depends on source_kind. The bound the alert is evaluated against is under the condition key.'
+ ),
check_interval_minutes: zod
.number()
.describe('Minutes between scheduled checks. Applies when recurrence_unit is null.'),
@@ -230,12 +229,9 @@ export const PaginatedPlatformAlertConfigurationListApi = zod.object({
.describe('Product whose data the alert evaluates.\n\n\* `logs` - Logs'),
source_config: zod
.record(zod.string(), zod.unknown())
- .describe('Source-specific query settings. The shape depends on source_kind.'),
- threshold_count: zod.number().describe('Count the evaluated value is compared against.'),
- threshold_operator: zod
- .string()
- .describe('Comparison operator applied between the value and threshold_count.'),
- window_minutes: zod.number().describe('Length of the evaluated time window, in minutes.'),
+ .describe(
+ 'Source-specific settings. The shape depends on source_kind. The bound the alert is evaluated against is under the condition key.'
+ ),
check_interval_minutes: zod
.number()
.describe('Minutes between scheduled checks. Applies when recurrence_unit is null.'),
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index ebcf7805a335..531ef11bc3e2 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -74,6 +74,7 @@ from products.logs.backend.alert_check_query import (
)
from products.logs.backend.alert_destinations import EVENT_KIND_CONFIG, EventKind
from products.logs.backend.alert_error_classifier import classify as classify_alert_error
+from products.logs.backend.models import LogsAlertConfiguration
# Private to the production activity. Reimplementing either would let this path drift from
# what the logs stack evaluates. Promoting them to a shared home is the deeper fix.
@@ -113,6 +114,54 @@ _NOTIFICATION_OUTCOME_KINDS: dict[NotificationAction, AlertEventKind] = {
}
+@frozen
+class LogsAlertCondition:
+ """The logs bound, which the platform keeps under `source_config["condition"]`."""
+
+ threshold_count: int
+ threshold_operator: str
+ window_minutes: int
+
+ def __post_init__(self) -> None:
+ # `_derive_breaches` reads any operator but `above` as `below`, so an unknown one would
+ # decide the alert against the wrong side of its bound instead of failing.
+ if self.threshold_operator not in LogsAlertConfiguration.ThresholdOperator.values:
+ raise ValueError(f"Unknown threshold operator {self.threshold_operator!r}")
+ # A threshold of 0 is valid: with `above` it fires on any matching log, as the logs API documents.
+ for name, minimum in (("threshold_count", 0), ("window_minutes", 1)):
+ value = getattr(self, name)
+ if isinstance(value, bool) or not isinstance(value, int) or value < minimum:
+ raise ValueError(f"{name} must be an integer of at least {minimum}, got {value!r}")
+
+ @classmethod
+ def of(cls, check: PlatformAlertCheckInput) -> "LogsAlertCondition":
+ condition = check.condition
+ return cls(
+ threshold_count=condition["threshold_count"],
+ threshold_operator=condition["threshold_operator"],
+ window_minutes=condition["window_minutes"],
+ )
+
+ def as_source_config(self) -> dict[str, int | str]:
+ return {
+ "threshold_count": self.threshold_count,
+ "threshold_operator": self.threshold_operator,
+ "window_minutes": self.window_minutes,
+ }
+
+
+def _broken_condition(check: PlatformAlertCheckInput) -> str | None:
+ """A bound the cohort query cannot read. Caught here, because the cohort key reads it for
+ every check in the batch, so one malformed row would otherwise stop the whole batch."""
+ try:
+ LogsAlertCondition.of(check)
+ except (KeyError, TypeError):
+ return "The alert's threshold is missing from its configuration"
+ except ValueError as error:
+ return f"The alert's threshold is invalid: {error}"
+ return None
+
+
_WINDOW_MARKER = "window:"
@@ -148,7 +197,7 @@ def window_end_of(evaluation_key: str) -> datetime | None:
def _cohort_key(check: PlatformAlertCheckInput, checkpoint: datetime | None, now: datetime) -> tuple:
return (
- check.window_minutes,
+ LogsAlertCondition.of(check).window_minutes,
check.evaluation_periods,
check.check_interval_minutes,
is_projection_eligible(check.source_config),
@@ -378,8 +427,9 @@ _EVENT_IDS_BY_INCIDENT_ACTION: Final[dict[str, str]] = {
def _evaluate_one(
check: PlatformAlertCheckInput, buckets: list[BucketedCount], *, now: datetime, muted: bool
) -> AlertCheckOutcome:
+ condition = LogsAlertCondition.of(check)
current_breached, *prior_windows_breached = _derive_breaches(
- buckets, check.threshold_count, check.threshold_operator, check.evaluation_periods
+ buckets, condition.threshold_count, condition.threshold_operator, check.evaluation_periods
) or (False,)
return _verdict(
check,
@@ -512,7 +562,7 @@ def _triage(checks: Sequence[PlatformAlertCheckInput], *, now: datetime, tz_name
evaluable: list[PlatformAlertCheckInput] = []
muted_ids: set[UUID] = set()
for check in checks:
- broken_reason = _detect_broken_filter_config(check.source_config)
+ broken_reason = _detect_broken_filter_config(check.source_config) or _broken_condition(check)
if broken_reason is not None:
logger.warning(
"Marking a logs alert BROKEN for an invalid filter config",
diff --git a/products/logs/backend/platform_alert_backfill.py b/products/logs/backend/platform_alert_backfill.py
index 06c2afad3a50..7814cfd652d4 100644
--- a/products/logs/backend/platform_alert_backfill.py
+++ b/products/logs/backend/platform_alert_backfill.py
@@ -12,7 +12,8 @@ import structlog
from posthog.dataclasses import frozen
from products.alerts_platform.backend.facade.api import upsert_configuration
-from products.alerts_platform.backend.facade.contracts import PlatformAlertUpsert, SourceKind
+from products.alerts_platform.backend.facade.contracts import SOURCE_CONDITION_KEY, PlatformAlertUpsert, SourceKind
+from products.logs.backend.alert_source_cycle import LogsAlertCondition
from products.logs.backend.models import LogsAlertConfiguration
logger = structlog.get_logger(__name__)
@@ -40,10 +41,14 @@ def backfill_platform_alert_configurations(*, team_id: int | None = None) -> Bac
name=configuration.name,
enabled=configuration.enabled,
source_kind=SourceKind.LOGS,
- source_config=configuration.filters,
- threshold_count=configuration.threshold_count,
- threshold_operator=configuration.threshold_operator,
- window_minutes=configuration.window_minutes,
+ source_config={
+ **configuration.filters,
+ SOURCE_CONDITION_KEY: LogsAlertCondition(
+ threshold_count=configuration.threshold_count,
+ threshold_operator=configuration.threshold_operator,
+ window_minutes=configuration.window_minutes,
+ ).as_source_config(),
+ },
check_interval_minutes=configuration.check_interval_minutes,
evaluation_periods=configuration.evaluation_periods,
datapoints_to_alarm=configuration.datapoints_to_alarm,
diff --git a/products/logs/backend/test/test_alert_comparison.py b/products/logs/backend/test/test_alert_comparison.py
index f65d450c9a67..4baec737b823 100644
--- a/products/logs/backend/test/test_alert_comparison.py
+++ b/products/logs/backend/test/test_alert_comparison.py
@@ -9,6 +9,7 @@ from unittest.mock import patch
from parameterized import parameterized
from products.alerts_platform.backend.facade.contracts import (
+ SOURCE_CONDITION_KEY,
PlatformAlertCheckInput,
PlatformCheck,
SourceCoverage,
@@ -17,7 +18,7 @@ from products.alerts_platform.backend.facade.contracts import (
)
from products.alerts_platform.backend.facade.testing import undeclared_policy_divergences
from products.logs.backend.alert_comparison import LOGS_INTENTIONAL_DIVERGENCES, LogsCorrespondence
-from products.logs.backend.alert_source_cycle import _evaluation_key, window_end_of
+from products.logs.backend.alert_source_cycle import LogsAlertCondition, _evaluation_key, window_end_of
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
CHECKED_AT = datetime(2026, 9, 30, 12, 0, tzinfo=UTC)
@@ -29,10 +30,11 @@ def _check_input(alert_id, *, next_check_at) -> PlatformAlertCheckInput:
id=alert_id,
team_id=1,
name="API errors",
- source_config={},
- threshold_count=10,
- threshold_operator="above",
- window_minutes=5,
+ source_config={
+ SOURCE_CONDITION_KEY: LogsAlertCondition(
+ threshold_count=10, threshold_operator="above", window_minutes=5
+ ).as_source_config()
+ },
check_interval_minutes=5,
evaluation_periods=1,
datapoints_to_alarm=1,
diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.py
index 0ef5ea3abe6d..c411071e8e20 100644
--- a/products/logs/backend/test/test_alert_evaluate.py
+++ b/products/logs/backend/test/test_alert_evaluate.py
@@ -28,6 +28,7 @@ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.logs.backend.alert_check_query import BatchedBucketedResult, BucketedCount
from products.logs.backend.alert_source_cycle import BATCH_QUERY_BUDGET_SECONDS, MAX_QUERY_SECONDS, evaluate_logs_batch
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
+from products.logs.backend.platform_alert_backfill import backfill_platform_alert_configurations
from products.logs.backend.temporal.alert_evaluate import (
EVALUATE_SCHEDULE_TO_CLOSE,
EVALUATE_START_TO_CLOSE,
@@ -35,6 +36,7 @@ from products.logs.backend.temporal.alert_evaluate import (
)
_MODULE = "products.logs.backend.alert_source_cycle"
+CONDITION = {"threshold_count": 10, "threshold_operator": "above", "window_minutes": 5}
_LOGS_OWNED_FIELDS = ("state", "consecutive_failures", "next_check_at", "last_notified_at", "snooze_until")
@@ -48,10 +50,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
"team_id": self.team.id,
"name": "API errors",
"source_kind": SourceKind.LOGS,
- "source_config": {},
- "threshold_count": 10,
- "threshold_operator": "above",
- "window_minutes": 5,
+ "source_config": {"condition": CONDITION},
"check_interval_minutes": 10,
"next_check_at": self.cutoff - timedelta(minutes=1),
}
@@ -134,6 +133,28 @@ class TestLogsAlertEvaluation(APIBaseTest):
assert configuration.next_check_at is not None
assert configuration.next_check_at > self.cutoff
+ @parameterized.expand([("below_a_high_bound", 1000, "below"), ("above_zero", 0, "above")])
+ def test_a_backfilled_alert_evaluates_against_the_bound_it_was_copied_with(
+ self, _name: str, threshold_count: int, threshold_operator: str
+ ) -> None:
+ LogsAlertConfiguration.objects.create(
+ team=self.team,
+ name="API errors",
+ threshold_count=threshold_count,
+ threshold_operator=threshold_operator,
+ window_minutes=5,
+ filters={"serviceNames": ["api"]},
+ next_check_at=self.cutoff - timedelta(minutes=1),
+ )
+ backfill_platform_alert_configurations(team_id=self.team.id)
+ with team_scope(self.team.id):
+ (check,) = due_checks(self.team.id, SourceKind.LOGS.value, self._slot(), self.cutoff)
+ copied = platform_testing.configuration(check.id)
+
+ evaluation, _ = self._run(copied)
+
+ assert [(o.kind, o.value) for o in evaluation.outcomes] == [(AlertEventKind.FIRING, 500.0)]
+
def test_a_cohort_query_is_capped_below_the_batch_budget(self) -> None:
_, query = self._run(self._configuration())
@@ -245,8 +266,18 @@ class TestLogsAlertEvaluation(APIBaseTest):
(False, {"": IncidentAction.RESOLVE})
]
- def test_a_broken_filter_config_stops_being_discovered(self) -> None:
- configuration = self._configuration(source_config={"filterGroup": {"type": "nonsense"}})
+ @parameterized.expand(
+ [
+ ("filter_group", {"condition": CONDITION, "filterGroup": {"type": "nonsense"}}),
+ ("missing_condition", {}),
+ ("null_condition", {"condition": None}),
+ ("unknown_operator", {"condition": {**CONDITION, "threshold_operator": "equals"}}),
+ ("non_numeric_window", {"condition": {**CONDITION, "window_minutes": "5"}}),
+ ("zero_window", {"condition": {**CONDITION, "window_minutes": 0}}),
+ ]
+ )
+ def test_a_broken_config_stops_being_discovered(self, _name: str, source_config: dict[str, Any]) -> None:
+ configuration = self._configuration(source_config=source_config)
evaluation, query = self._run(configuration)
self._record(evaluation)
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 639a500255b7..03ce83769998 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -69523,7 +69523,7 @@ export namespace Schemas {
}
/**
- * Source-specific query settings. The shape depends on source_kind.
+ * Source-specific settings. The shape depends on source_kind. The bound the alert is evaluated against is under the condition key.
*/
export type PlatformAlertConfigurationSourceConfig = { [key: string]: unknown };
@@ -69538,14 +69538,8 @@ export namespace Schemas {
*
* * `logs` - Logs */
readonly source_kind: PlatformAlertConfigurationSourceKindEnum;
- /** Source-specific query settings. The shape depends on source_kind. */
+ /** Source-specific settings. The shape depends on source_kind. The bound the alert is evaluated against is under the condition key. */
readonly source_config: PlatformAlertConfigurationSourceConfig;
- /** Count the evaluated value is compared against. */
- readonly threshold_count: number;
- /** Comparison operator applied between the value and threshold_count. */
- readonly threshold_operator: string;
- /** Length of the evaluated time window, in minutes. */
- readonly window_minutes: number;
/** Minutes between scheduled checks. Applies when recurrence_unit is null. */
readonly check_interval_minutes: number;
/** Calendar unit the alert recurs on. Null means it recurs on check_interval_minutes.