Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(logs): emit Self-driving signals for logs alerts the platform owns (#116675)

Jimmy Zhuf416eeb84ce4
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index c2ed20d2061b..6f6142de42fa 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -236,6 +236,8 @@ from products.growth.backend.temporal import (
)
from products.logs.backend.facade.temporal import (
ACTIVITIES as LOGS_ALERTING_ACTIVITIES,
+ PLATFORM_SIGNAL_ACTIVITIES as LOGS_PLATFORM_SIGNAL_ACTIVITIES,
+ PLATFORM_SIGNAL_WORKFLOWS as LOGS_PLATFORM_SIGNAL_WORKFLOWS,
SOURCE_EVALUATION_ACTIVITIES as LOGS_SOURCE_EVALUATION_ACTIVITIES,
SOURCE_EVALUATION_WORKFLOWS as LOGS_SOURCE_EVALUATION_WORKFLOWS,
VOLUME_TICK_ACTIVITIES as LOGS_VOLUME_TICK_ACTIVITIES,
@@ -629,8 +631,8 @@ _task_queue_specs = [
),
(
settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,
- ALERTS_PLATFORM_DELIVERY_WORKFLOWS,
- ALERTS_PLATFORM_DELIVERY_ACTIVITIES,
+ ALERTS_PLATFORM_DELIVERY_WORKFLOWS + LOGS_PLATFORM_SIGNAL_WORKFLOWS,
+ ALERTS_PLATFORM_DELIVERY_ACTIVITIES + LOGS_PLATFORM_SIGNAL_ACTIVITIES,
),
]
diff --git a/products/logs/backend/alert_signal_emitter.py b/products/logs/backend/alert_signal_emitter.py
index cd54499d3614..fd2b518b7fce 100644
--- a/products/logs/backend/alert_signal_emitter.py
+++ b/products/logs/backend/alert_signal_emitter.py
@@ -10,6 +10,7 @@ import structlog
from posthog.models import Team
from products.logs.backend.alert_state_machine import NotificationAction
+from products.logs.backend.models import LogsAlertConfiguration
from products.signals.backend.facade.api import emit_signal
logger = structlog.get_logger(__name__)
@@ -47,6 +48,25 @@ class NotifiedAlert:
result_count: int | None
consecutive_failures: int
filters: dict
+ # Set by a caller that retries, so a repeated emission starts no second signal.
+ idempotency_key: str | None = None
+
+
+_WEIGHT_BY_ACTION: dict[AlertSignalAction, float] = dict(_ACTION_WEIGHT.values())
+
+
[email protected](frozen=True)
+class PlatformAlertSignal:
+ """One alert the platform announced as firing or auto-disabled, for which logs emits a signal.
+
+ Crosses the Temporal activity boundary, so every field is a primitive.
+ """
+
+ alert_id: str
+ action: AlertSignalAction
+ result_count: int | None
+ consecutive_failures: int
+ evaluation_key: str
def signal_action_and_weight(notification: NotificationAction) -> tuple[AlertSignalAction, float] | None:
@@ -109,8 +129,42 @@ async def emit_alert_state_change_signal(team: Team, na: NotifiedAlert) -> bool:
description=description,
weight=na.weight,
extra=extra,
+ idempotency_key=na.idempotency_key,
)
return True
except Exception:
logger.exception("Failed to emit logs alert signal", alert_id=na.alert_id, action=na.action)
return False
+
+
+def notified_alerts_for_platform(team_id: int, signals: list[PlatformAlertSignal]) -> list[NotifiedAlert]:
+ """The signal facts for alerts the platform announced, read from their logs alert rows.
+
+ An alert whose logs row is gone gets no signal, the way the logs stack sends none for it.
+ """
+ alerts = {
+ str(alert.id): alert
+ for alert in LogsAlertConfiguration.objects.filter(team_id=team_id, id__in=[s.alert_id for s in signals])
+ }
+ notified: list[NotifiedAlert] = []
+ for signal in signals:
+ alert = alerts.get(signal.alert_id)
+ if alert is None:
+ continue
+ notified.append(
+ NotifiedAlert(
+ alert_id=signal.alert_id,
+ team_id=team_id,
+ alert_name=alert.name,
+ action=signal.action,
+ weight=_WEIGHT_BY_ACTION[signal.action],
+ threshold_count=alert.threshold_count,
+ threshold_operator=alert.threshold_operator,
+ window_minutes=alert.window_minutes,
+ result_count=signal.result_count,
+ consecutive_failures=signal.consecutive_failures,
+ filters=alert.filters,
+ idempotency_key=f"{signal.alert_id}:{signal.action}:{signal.evaluation_key}",
+ )
+ )
+ return notified
diff --git a/products/logs/backend/facade/temporal.py b/products/logs/backend/facade/temporal.py
index 5d7792a9d159..66b9e1bebdbb 100644
--- a/products/logs/backend/facade/temporal.py
+++ b/products/logs/backend/facade/temporal.py
@@ -10,7 +10,12 @@ temporalio-heavy imports here, off the ``facade/api.py`` path.
from products.logs.backend.temporal import ACTIVITIES, WORKFLOWS
from products.logs.backend.temporal.activities import CheckAlertsInput
-from products.logs.backend.temporal.alert_evaluate import SOURCE_EVALUATION_ACTIVITIES, SOURCE_EVALUATION_WORKFLOWS
+from products.logs.backend.temporal.alert_evaluate import (
+ PLATFORM_SIGNAL_ACTIVITIES,
+ PLATFORM_SIGNAL_WORKFLOWS,
+ SOURCE_EVALUATION_ACTIVITIES,
+ SOURCE_EVALUATION_WORKFLOWS,
+)
from products.logs.backend.temporal.constants import SCHEDULE_CRON, SCHEDULE_ID, WORKFLOW_NAME
from products.logs.backend.temporal.metrics import (
LOGS_ALERTING_COUNT_HISTOGRAM_BUCKETS,
@@ -38,6 +43,8 @@ from products.logs.backend.temporal.volume_tick.schedule import disable_logs_vol
__all__ = [
"ACTIVITIES",
"WORKFLOWS",
+ "PLATFORM_SIGNAL_ACTIVITIES",
+ "PLATFORM_SIGNAL_WORKFLOWS",
"SOURCE_EVALUATION_ACTIVITIES",
"SOURCE_EVALUATION_WORKFLOWS",
"CheckAlertsInput",
diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.py
index 0cfbc735d938..9cfa11b68dd8 100644
--- a/products/logs/backend/temporal/activities.py
+++ b/products/logs/backend/temporal/activities.py
@@ -875,10 +875,15 @@ async def emit_alert_signals_activity(input: EmitAlertSignalsInput) -> int:
heartbeats, and per-emit isolation — mirrors the data_imports signal pipeline.
Returns the number of signals successfully emitted.
"""
- if not input.notified:
+ return await emit_notified_alert_signals(input.notified)
+
+
+async def emit_notified_alert_signals(notified: list[NotifiedAlert]) -> int:
+ """Emits one signal per alert, for whichever logs alerting path notified it. Never raises."""
+ if not notified:
return 0
- team_ids = {na.team_id for na in input.notified}
+ team_ids = {na.team_id for na in notified}
teams = await database_sync_to_async_pool(_load_teams_for_signals)(team_ids)
semaphore = asyncio.Semaphore(EMIT_SIGNAL_CONCURRENCY)
@@ -901,7 +906,7 @@ async def emit_alert_signals_activity(input: EmitAlertSignalsInput) -> int:
temporalio.activity.heartbeat()
return ok
- results = await asyncio.gather(*(_bounded(na) for na in input.notified))
+ results = await asyncio.gather(*(_bounded(na) for na in notified))
return sum(1 for ok in results if ok)
diff --git a/products/logs/backend/temporal/alert_evaluate.py b/products/logs/backend/temporal/alert_evaluate.py
index 963e6ceb610e..894f766f19d4 100644
--- a/products/logs/backend/temporal/alert_evaluate.py
+++ b/products/logs/backend/temporal/alert_evaluate.py
@@ -5,22 +5,33 @@ plain function a test can call without Temporal.
"""
import datetime as dt
+import dataclasses
from temporalio import activity, workflow
from temporalio.common import RetryPolicy
+from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.temporal.common.base import PostHogWorkflow
with workflow.unsafe.imports_passed_through():
+ from django.conf import settings
+
+ from posthog.sync import database_sync_to_async_pool
from posthog.temporal.common.utils import close_db_connections
from products.alerts_platform.backend.facade.contracts import (
RECORD_OUTCOMES_ACTIVITY,
+ AlertEventKind,
SourceBatchEvaluation,
SourceEvaluationInputs,
SourceOutcomeInputs,
)
from products.alerts_platform.backend.facade.temporal import start_deliveries
+ from products.logs.backend.alert_signal_emitter import (
+ AlertSignalAction,
+ PlatformAlertSignal,
+ notified_alerts_for_platform,
+ )
WORKFLOW_NAME = "logs-alert-evaluate"
@@ -40,9 +51,55 @@ EVALUATE_SCHEDULE_TO_CLOSE = EVALUATE_START_TO_CLOSE + EVALUATE_QUEUE_TOLERANCE
RECORD_START_TO_CLOSE = dt.timedelta(seconds=8)
RECORD_SCHEDULE_TO_CLOSE = dt.timedelta(seconds=12)
# What the source needs from its binding's `evaluation_timeout`, which has to hold both
-# activities and still leave room to start the delivery children.
+# activities and still leave room to start the delivery and signal children.
EVALUATION_BUDGET = EVALUATE_SCHEDULE_TO_CLOSE + RECORD_SCHEDULE_TO_CLOSE
+SIGNALS_WORKFLOW_NAME = "logs-alert-platform-signals"
+# A child workflow with its own budget, so a large batch of signals never competes with the
+# evaluation's.
+SIGNALS_EXECUTION_TIMEOUT = dt.timedelta(minutes=5)
+SIGNALS_START_TO_CLOSE = dt.timedelta(minutes=4)
+
+# Workflows started before the signal step replay without it.
+SIGNALS_PATCH = "logs-alert-evaluate-platform-signals"
+
+_SIGNAL_ACTIONS: dict[AlertEventKind, AlertSignalAction] = {
+ AlertEventKind.FIRING: "firing",
+ AlertEventKind.BROKEN: "broken",
+}
+
+
[email protected](frozen=True)
+class PlatformSignalInputs:
+ team_id: int
+ signals: list[PlatformAlertSignal]
+
+
+def platform_signals(evaluation: SourceBatchEvaluation) -> list[PlatformAlertSignal]:
+ """The firings and auto-disables the platform sends a message for, on alerts it owns.
+
+ The logs stack signals the same moments, keyed on a notification going out, which here is a
+ delivery that sends messages. An alert the logs stack still owns gets its signal from the logs
+ stack, so it is left out. The delivery names the owner and the logs alert id, so the platform's
+ outcome contract needs neither.
+ """
+ announced = {
+ delivery.configuration_id: delivery.destination_alert_id
+ for delivery in evaluation.deliveries
+ if delivery.owned_by_platform and delivery.sends_messages
+ }
+ return [
+ PlatformAlertSignal(
+ alert_id=announced[str(outcome.configuration_id)],
+ action=_SIGNAL_ACTIONS[outcome.kind],
+ result_count=int(outcome.value) if outcome.value is not None else None,
+ consecutive_failures=outcome.consecutive_failures,
+ evaluation_key=outcome.evaluation_key,
+ )
+ for outcome in evaluation.outcomes
+ if outcome.kind in _SIGNAL_ACTIONS and str(outcome.configuration_id) in announced
+ ]
+
@activity.defn
@close_db_connections
@@ -59,6 +116,34 @@ def evaluate_logs_alerts_activity(inputs: SourceEvaluationInputs) -> SourceBatch
)
+async def emit_platform_alert_signals_activity(inputs: PlatformSignalInputs) -> int:
+ """Emits the Self-driving signals for alerts the platform owns. Never raises."""
+ # In the body, like the import above, because the workflow's sandbox refuses Django models.
+ from products.logs.backend.temporal.activities import emit_notified_alert_signals # noqa: PLC0415
+
+ notified = await database_sync_to_async_pool(notified_alerts_for_platform)(inputs.team_id, inputs.signals)
+ return await emit_notified_alert_signals(notified)
+
+
[email protected](name=SIGNALS_WORKFLOW_NAME)
+class LogsPlatformAlertSignalsWorkflow(PostHogWorkflow):
+ """Emits one evaluation's Self-driving signals, apart from the evaluation itself."""
+
+ inputs_cls = PlatformSignalInputs
+
+ @workflow.run
+ async def run(self, inputs: PlatformSignalInputs) -> int:
+ # Retried, because each signal carries an idempotency key, so a retry sends only what the
+ # failed attempt had not.
+ return await workflow.execute_activity(
+ emit_platform_alert_signals_activity,
+ inputs,
+ start_to_close_timeout=SIGNALS_START_TO_CLOSE,
+ retry_policy=RetryPolicy(maximum_attempts=3, initial_interval=dt.timedelta(seconds=10)),
+ )
+
+
@workflow.defn(name=WORKFLOW_NAME)
class LogsAlertEvaluateWorkflow(PostHogWorkflow):
"""Evaluates one batch key, records what it decided, then previews one delivery per
@@ -92,8 +177,30 @@ class LogsAlertEvaluateWorkflow(PostHogWorkflow):
retry_policy=RetryPolicy(maximum_attempts=3),
)
- return await start_deliveries(evaluation.deliveries)
+ started = await start_deliveries(evaluation.deliveries)
+
+ # After the outcomes are recorded, so a signal never describes a firing that was not saved.
+ signals = platform_signals(evaluation)
+ if signals and workflow.patched(SIGNALS_PATCH):
+ try:
+ await workflow.start_child_workflow(
+ LogsPlatformAlertSignalsWorkflow.run,
+ PlatformSignalInputs(team_id=inputs.batch_key.team_id, signals=signals),
+ id=f"{SIGNALS_WORKFLOW_NAME}-{inputs.batch_key.team_id}:{inputs.batch_key.slot}:{inputs.cutoff}",
+ # The delivery queue, so a slow burst of signals never holds evaluation slots.
+ task_queue=settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,
+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,
+ execution_timeout=SIGNALS_EXECUTION_TIMEOUT,
+ )
+ except WorkflowAlreadyStartedError:
+ # A re-run of the same evaluation already started its signals.
+ pass
+
+ return started
SOURCE_EVALUATION_WORKFLOWS = [LogsAlertEvaluateWorkflow]
SOURCE_EVALUATION_ACTIVITIES = [evaluate_logs_alerts_activity]
+# Registered on the platform delivery queue, beside the deliveries the evaluation starts.
+PLATFORM_SIGNAL_WORKFLOWS = [LogsPlatformAlertSignalsWorkflow]
+PLATFORM_SIGNAL_ACTIVITIES = [emit_platform_alert_signals_activity]
diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.py
index 119a060435a2..7ef706a0be14 100644
--- a/products/logs/backend/test/test_alert_evaluate.py
+++ b/products/logs/backend/test/test_alert_evaluate.py
@@ -1,5 +1,6 @@
from datetime import UTC, datetime, timedelta
from typing import Any
+from uuid import UUID, uuid4
import pytest
from posthog.test.base import APIBaseTest
@@ -16,8 +17,10 @@ from posthog.models.scoping import team_scope
from products.alerts_platform.backend.facade import testing as platform_testing
from products.alerts_platform.backend.facade.api import due_checks, record_outcomes, slot_of
from products.alerts_platform.backend.facade.contracts import (
+ AlertDeliveryRequest,
AlertEventKind,
IncidentAction,
+ PlatformAlertOutcome,
PlatformConfigurationSnapshot,
SourceBatchEvaluation,
SourceKind,
@@ -26,6 +29,7 @@ from products.alerts_platform.backend.facade.lifecycle import AlertState
from products.alerts_platform.backend.facade.temporal import source_evaluation_timeout
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_signal_emitter import PlatformAlertSignal, notified_alerts_for_platform
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
@@ -33,6 +37,7 @@ from products.logs.backend.temporal.alert_evaluate import (
EVALUATE_SCHEDULE_TO_CLOSE,
EVALUATE_START_TO_CLOSE,
EVALUATION_BUDGET,
+ platform_signals,
)
_MODULE = "products.logs.backend.alert_source_cycle"
@@ -407,3 +412,87 @@ class TestEvaluationTimeoutLadder(SimpleTestCase):
assert (EVALUATE_SCHEDULE_TO_CLOSE - EVALUATE_START_TO_CLOSE).total_seconds() >= BATCH_QUERY_BUDGET_SECONDS / 2
# The platform's own timeout holds both activities and still leaves room for the deliveries.
assert source_evaluation_timeout(SourceKind.LOGS) > EVALUATION_BUDGET
+
+
+def _outcome(kind: AlertEventKind, *, notified: bool = True) -> PlatformAlertOutcome:
+ return PlatformAlertOutcome(
+ configuration_id=UUID("01936a2e-0000-7000-8000-000000000001"),
+ evaluation_key="slot:x|window:y",
+ kind=kind,
+ new_state="firing",
+ notified=notified,
+ consecutive_failures=5 if kind == AlertEventKind.BROKEN else 0,
+ value=500.0 if kind == AlertEventKind.FIRING else None,
+ )
+
+
+def _delivery_for(*, owned_by_platform: bool, sends_messages: bool = True) -> AlertDeliveryRequest:
+ return AlertDeliveryRequest(
+ source=SourceKind.LOGS,
+ team_id=1,
+ configuration_id="01936a2e-0000-7000-8000-000000000001",
+ evaluation_key="slot:x|window:y",
+ destination_alert_id="legacy-1",
+ event_ids_by_kind={},
+ owned_by_platform=owned_by_platform,
+ sends_messages=sends_messages,
+ )
+
+
+class TestPlatformAlertSignals(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("a_platform_owned_firing", AlertEventKind.FIRING, True, True, True, [("firing", 500, 0)]),
+ ("a_platform_owned_auto_disable", AlertEventKind.BROKEN, False, True, True, [("broken", None, 5)]),
+ ("a_firing_the_logs_stack_still_owns", AlertEventKind.FIRING, True, False, True, []),
+ ("a_broken_config_held_back", AlertEventKind.BROKEN, False, True, False, []),
+ ("a_resolve", AlertEventKind.RESOLVED, True, True, True, []),
+ ]
+ )
+ def test_only_announced_firings_and_auto_disables_of_platform_owned_alerts_signal(
+ self,
+ _name: str,
+ kind: AlertEventKind,
+ notified: bool,
+ owned: bool,
+ sends_messages: bool,
+ expected: list[tuple[Any, ...]],
+ ) -> None:
+ evaluation = SourceBatchEvaluation(
+ outcomes=(_outcome(kind, notified=notified),),
+ deliveries=(_delivery_for(owned_by_platform=owned, sends_messages=sends_messages),),
+ )
+
+ signals = platform_signals(evaluation)
+
+ assert all(signal.alert_id == "legacy-1" for signal in signals)
+ assert [(s.action, s.result_count, s.consecutive_failures) for s in signals] == expected
+
+
+class TestPlatformAlertSignalFacts(APIBaseTest):
+ def test_a_signal_carries_the_logs_alert_as_it_is_and_skips_a_deleted_one(self) -> None:
+ alert = LogsAlertConfiguration.objects.create(
+ team=self.team, name="API errors", filters={"serviceNames": ["api"]}, threshold_count=10, window_minutes=5
+ )
+
+ notified = notified_alerts_for_platform(
+ self.team.id,
+ [
+ PlatformAlertSignal(
+ alert_id=str(alert.id),
+ action="firing",
+ result_count=500,
+ consecutive_failures=0,
+ evaluation_key="k-1",
+ ),
+ PlatformAlertSignal(
+ alert_id=str(uuid4()), action="firing", result_count=1, consecutive_failures=0, evaluation_key="k-1"
+ ),
+ ],
+ )
+
+ assert [(n.alert_id, n.alert_name, n.threshold_count, n.result_count, n.filters) for n in notified] == [
+ (str(alert.id), "API errors", 10, 500, {"serviceNames": ["api"]})
+ ]
+ # A retried emission of the same announcement must not start a second signal.
+ assert notified[0].idempotency_key == f"{alert.id}:firing:k-1"