: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
fix(logs): flush kafka producer before persisting alert notification state (#68847)
Jon McCallum1c727f7fd140
diff --git a/posthog/cdp/internal_events.py b/posthog/cdp/internal_events.pyindex 481f1d0359d5..6072aaa4a99d 100644--- a/posthog/cdp/internal_events.py+++ b/posthog/cdp/internal_events.py@@ -6,6 +6,7 @@ from typing import Optionalimport structlogfrom rest_framework_dataclasses.serializers import DataclassSerializer+from posthog.kafka_client.client import ProduceResultfrom posthog.kafka_client.routing import get_producerfrom posthog.kafka_client.topics import KAFKA_CDP_INTERNAL_EVENTS@@ -59,14 +60,24 @@ def create_internal_event(return data-def produce_internal_event(team_id: int, event: InternalEventEvent, person: Optional[InternalEventPerson] = None):+def produce_internal_event(+ team_id: int, event: InternalEventEvent, person: Optional[InternalEventPerson] = None+) -> ProduceResult:data = create_internal_event(team_id, event, person)serialized_data = internal_event_to_dict(data)kafka_topic = KAFKA_CDP_INTERNAL_EVENTStry:producer = get_producer(topic=kafka_topic)- producer.produce(topic=kafka_topic, data=serialized_data, key=data.event.uuid)+ return producer.produce(topic=kafka_topic, data=serialized_data, key=data.event.uuid)except Exception as e:logger.exception("Failed to produce internal event", data=serialized_data, error=e)raise+++def flush_internal_events_producer(timeout: float) -> int:+ """Block until previously produced internal events are delivered (or `timeout`+ elapses), returning the number still undelivered. A zero only means all+ delivery callbacks have fired, not that they all succeeded — check each+ `ProduceResult` for per-message outcomes."""+ return get_producer(topic=KAFKA_CDP_INTERNAL_EVENTS).flush(timeout)diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.pyindex 7478cee0ea1c..175c9ea192ec 100644--- a/products/logs/backend/temporal/activities.py+++ b/products/logs/backend/temporal/activities.py@@ -20,8 +20,9 @@ from pydantic import ValidationError as PydanticValidationErrorfrom posthog.schema import PropertyGroupFilter-from posthog.cdp.internal_events import InternalEventEvent, produce_internal_event+from posthog.cdp.internal_events import InternalEventEvent, flush_internal_events_producer, produce_internal_eventfrom posthog.exceptions_capture import capture_exception+from posthog.kafka_client.client import ProduceResultfrom posthog.models import Teamfrom posthog.sync import database_sync_to_async_pool@@ -61,6 +62,7 @@ from products.logs.backend.temporal.constants import (MAX_ALERT_COHORT_SIZE,MAX_COHORTS_PER_BATCH,MAX_CONCURRENT_COHORTS_PER_BATCH,+ NOTIFICATION_FLUSH_TIMEOUT_SECONDS,)from products.logs.backend.temporal.metrics import (increment_check_errors,@@ -260,10 +262,18 @@ class _DispatchedAlert:`notification_failed` is the source of truth for state rollback: if True,the state machine's `new_state` is replaced with the alert's existing stateso the next cycle re-tries the notification.++ `produce_result` is the pending Kafka delivery for this alert's+ notification (None when no notification was attempted or the enqueue itself+ failed). `produce()` only buffers locally, so `notification_failed` isn't+ final until `_resolve_notification_deliveries` flushes the producer and+ folds delivery failures in — persisting before that point would record+ "notified" for a message that may never reach the broker."""evaluation: _AlertEvaluationnotification_failed: bool+ produce_result: ProduceResult | None = None@propertydef committed_outcome(self) -> AlertCheckOutcome:@@ -616,6 +626,14 @@ async def evaluate_cohort_batch_activity(input: EvaluateCohortBatchInput) -> Evadispatched.append(result)elapsed_ms_per_alert.append(int((phase_2_end - eval_start) * 1000))+ # Delivery barrier: block until Kafka acks (or the flush deadline+ # passes) BEFORE the save, so undelivered notifications roll state+ # back and get retried next cycle. flush() blocks, so run it off+ # the event loop — and only when something was actually produced,+ # sparing quiet cohorts the thread hop.+ if any(d.produce_result is not None for d in dispatched):+ dispatched = await asyncio.to_thread(_resolve_notification_deliveries, dispatched)+try:saved, failed = (await save_cohort_async(dispatched, now)) if dispatched else ([], [])except Exception as e:@@ -824,8 +842,10 @@ def _dispatch_notification(*,date_from: datetime,date_to: datetime,-) -> bool:- """Emit the notification for this outcome. Returns True if delivery failed.+) -> ProduceResult | None:+ """Emit the notification for this outcome. Returns the pending Kafka+ delivery, or None when nothing was enqueued (no action, or the enqueue+ failed synchronously — distinguishable via `outcome.notification`).Pure-effect: produces a Kafka message and logs. Does NOT mutate `stats` —the orchestrator owns stats accounting so it stays single-threaded after@@ -833,34 +853,36 @@ def _dispatch_notification("""action = outcome.notificationif action == NotificationAction.NONE:- return False+ return Nonelog = logger.bind(alert_id=str(alert.id), alert_name=alert.name, team_id=alert.team_id)if action == NotificationAction.FIRE:- notified = _emit_alert_event(- alert, "$logs_alert_firing", check_result, now, date_from=date_from, date_to=date_to- )- log.info("Alert fired", result_count=check_result.result_count, notified=notified)+ result = _emit_alert_event(alert, "$logs_alert_firing", check_result, now, date_from=date_from, date_to=date_to)+ log.info("Alert fired", result_count=check_result.result_count, enqueued=result is not None)elif action == NotificationAction.RESOLVE:- notified = _emit_alert_event(+ result = _emit_alert_event(alert, "$logs_alert_resolved", check_result, now, date_from=date_from, date_to=date_to)- log.info("Alert resolved", notified=notified)+ log.info("Alert resolved", enqueued=result is not None)elif action == NotificationAction.ERROR:- notified = _emit_alert_errored_event(alert, outcome, now)- log.info("Alert entered errored state", consecutive_failures=outcome.consecutive_failures, notified=notified)+ result = _emit_alert_errored_event(alert, outcome, now)+ log.info(+ "Alert entered errored state",+ consecutive_failures=outcome.consecutive_failures,+ enqueued=result is not None,+ )elif action == NotificationAction.BROKEN:- notified = _emit_auto_disabled_event(alert, outcome, now)+ result = _emit_auto_disabled_event(alert, outcome, now)log.warning("Alert broken after consecutive failures",consecutive_failures=outcome.consecutive_failures,- notified=notified,+ enqueued=result is not None,)else:raise ValueError(f"Unhandled NotificationAction: {action!r}")- return not notified+ return resultdef _dispatch_for_alert(evaluation: _AlertEvaluation, now: datetime) -> _DispatchedAlert:@@ -869,7 +891,7 @@ def _dispatch_for_alert(evaluation: _AlertEvaluation, now: datetime) -> _DispatcPure-effect (Kafka). The orchestrator updates `stats` serially after thedispatch phase so concurrent gather'd dispatches can't race on the dict."""- notification_failed = _dispatch_notification(+ produce_result = _dispatch_notification(evaluation.outcome,evaluation.alert,evaluation.check_result,@@ -877,7 +899,54 @@ def _dispatch_for_alert(evaluation: _AlertEvaluation, now: datetime) -> _Dispatcdate_from=evaluation.date_from,date_to=evaluation.date_to,)- return _DispatchedAlert(evaluation=evaluation, notification_failed=notification_failed)+ enqueue_failed = evaluation.outcome.notification != NotificationAction.NONE and produce_result is None+ return _DispatchedAlert(evaluation=evaluation, notification_failed=enqueue_failed, produce_result=produce_result)+++def _resolve_notification_deliveries(dispatched: list[_DispatchedAlert]) -> list[_DispatchedAlert]:+ """Phase 2.5: barrier between dispatch and save — wait for Kafka to ack the+ cohort's notifications, folding delivery failures into `notification_failed`.++ Without this, `produce()`'s local buffering makes "notified" state durable+ before the message ever reaches the broker: a broker outage after enqueue+ would advance the alert to FIRING with no notification delivered, and the+ transition-triggered FIRE would never be re-attempted.++ Flush failures are swallowed: the per-result checks below classify each+ alert individually (an unresolved result reads as undelivered), and a save+ with rolled-back state beats no save at all — the cohort erroring out here+ would skip the save entirely.+ """+ if all(d.produce_result is None for d in dispatched):+ return dispatched++ try:+ remaining = flush_internal_events_producer(NOTIFICATION_FLUSH_TIMEOUT_SECONDS)+ if remaining:+ logger.warning("Kafka flush timed out with undelivered messages", remaining=remaining)+ except Exception as e:+ logger.exception("Kafka flush failed", error=str(e))+ capture_exception(e, {"phase": "notification_flush"})++ resolved: list[_DispatchedAlert] = []+ for d in dispatched:+ if d.produce_result is None:+ resolved.append(d)+ continue+ try:+ # Delivery callbacks only fire while flush()/poll() pumps the queue,+ # so after the flush above each result is already resolved or never+ # will be this cycle — timeout=0 reads the outcome without blocking.+ d.produce_result.get(timeout=0)+ resolved.append(d)+ except Exception:+ logger.warning(+ "Notification not delivered before flush deadline; rolling back state for retry",+ alert_id=str(d.evaluation.alert.id),+ team_id=d.evaluation.alert.team_id,+ )+ resolved.append(dataclasses.replace(d, notification_failed=True))+ return resolveddef _stage_alert_for_save(dispatched: _DispatchedAlert, now: datetime) -> tuple[list[str], LogsAlertEvent | None]:@@ -1233,9 +1302,9 @@ def _produce_alert_internal_event(event_name: str,properties: dict,now: datetime,-) -> bool:+) -> ProduceResult | None:try:- produce_internal_event(+ return produce_internal_event(team_id=alert.team_id,event=InternalEventEvent(event=event_name,@@ -1244,10 +1313,9 @@ def _produce_alert_internal_event(timestamp=now.isoformat(),),)- return Trueexcept Exception as e:capture_exception(e, {"alert_id": str(alert.id), "event": event_name})- return False+ return Nonedef _emit_alert_event(@@ -1258,7 +1326,7 @@ def _emit_alert_event(*,date_from: datetime,date_to: datetime,-) -> bool:+) -> ProduceResult | None:properties: dict = {"alert_id": str(alert.id),"alert_name": alert.name,@@ -1296,7 +1364,7 @@ def _emit_auto_disabled_event(alert: LogsAlertConfiguration,outcome: AlertCheckOutcome,now: datetime,-) -> bool:+) -> ProduceResult | None:properties = {**_base_failure_properties(alert, outcome, now),"last_error_message": outcome.error_message or "",@@ -1308,7 +1376,7 @@ def _emit_alert_errored_event(alert: LogsAlertConfiguration,outcome: AlertCheckOutcome,now: datetime,-) -> bool:+) -> ProduceResult | None:properties = {**_base_failure_properties(alert, outcome, now),"error_message": outcome.error_message or "",diff --git a/products/logs/backend/temporal/constants.py b/products/logs/backend/temporal/constants.pyindex 5dc31cde8166..5124dd9dafb0 100644--- a/products/logs/backend/temporal/constants.py+++ b/products/logs/backend/temporal/constants.py@@ -40,6 +40,13 @@ MAX_COHORTS_PER_BATCH = int(os.environ.get("LOGS_ALERTING_MAX_COHORTS_PER_BATCH"# Per-pod CH parallelism = max_concurrent_activities × MAX_CONCURRENT_COHORTS_PER_BATCH.MAX_CONCURRENT_COHORTS_PER_BATCH = int(os.environ.get("LOGS_ALERTING_MAX_CONCURRENT_COHORTS_PER_BATCH", "5"))+# How long the per-cohort flush barrier waits for the Kafka broker to ack+# dispatched notifications before treating them as undelivered (state rolls+# back and the next cycle retries). The flush drains the process-wide internal+# events producer, so concurrent cohorts' flushes piggyback on each other+# rather than stacking up.+NOTIFICATION_FLUSH_TIMEOUT_SECONDS = float(os.environ.get("LOGS_ALERTING_NOTIFICATION_FLUSH_TIMEOUT_SECONDS", "10"))+# Bounded concurrency for fanning out emit_signal in emit_alert_signals_activity.# emit_signal is expensive (Postgres reads + Temporal workflow start), so this runs# off the eval hot path in its own activity with bounded parallelism.diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.pyindex 836cfc579be9..934398f1478f 100644--- a/products/logs/backend/test/test_alerts_api.py+++ b/products/logs/backend/test/test_alerts_api.py@@ -5,7 +5,7 @@ from uuid import uuid4from freezegun import freeze_timefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom parameterized import parameterizedfrom rest_framework import status@@ -1728,9 +1728,11 @@ class TestSimulateEvaluatorLifecycleParity(ClickhouseTestMixin, APIBaseTest):)self._checkpoint_patcher.start()self.addCleanup(self._checkpoint_patcher.stop)+ # A None return would read as "enqueue failed" and roll back every+ # notification, so the fake must return a (mock) ProduceResult.self._kafka_patcher = patch("products.logs.backend.temporal.activities.produce_internal_event",- return_value=None,+ return_value=MagicMock(),)self._kafka_patcher.start()self.addCleanup(self._kafka_patcher.stop)diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.pyindex cd50214ad391..55933b4aa93d 100644--- a/products/logs/backend/test/test_logs_alerting_activities.py+++ b/products/logs/backend/test/test_logs_alerting_activities.py@@ -273,6 +273,61 @@ class TestSaveCohortOutcomesFallback(APIBaseTest):_save_cohort_outcomes(dispatched, now)+class TestResolveNotificationDeliveries(unittest.TestCase):+ def _dispatched(self, produce_result, notification_failed=False):+ return _DispatchedAlert(+ evaluation=MagicMock(),+ notification_failed=notification_failed,+ produce_result=produce_result,+ )++ @parameterized.expand(+ [+ ("delivered", None, False),+ ("delivery_error", Exception("delivery failed"), True),+ ("still_pending_after_flush", TimeoutError("undelivered"), True),+ ]+ )+ @patch("products.logs.backend.temporal.activities.flush_internal_events_producer", return_value=0)+ def test_folds_delivery_outcome_into_notification_failed(self, _name, get_side_effect, expect_failed, mock_flush):+ from products.logs.backend.temporal.activities import _resolve_notification_deliveries++ result = MagicMock()+ if get_side_effect is not None:+ result.get.side_effect = get_side_effect++ resolved = _resolve_notification_deliveries([self._dispatched(result)])++ assert resolved[0].notification_failed is expect_failed+ mock_flush.assert_called_once()++ @patch("products.logs.backend.temporal.activities.flush_internal_events_producer")+ def test_skips_flush_when_nothing_was_produced(self, mock_flush):+ from products.logs.backend.temporal.activities import _resolve_notification_deliveries++ dispatched = self._dispatched(None)++ resolved = _resolve_notification_deliveries([dispatched])++ assert resolved == [dispatched]+ mock_flush.assert_not_called()++ @patch("products.logs.backend.temporal.activities.capture_exception")+ @patch(+ "products.logs.backend.temporal.activities.flush_internal_events_producer",+ side_effect=Exception("kafka down"),+ )+ def test_flush_failure_does_not_raise_and_marks_pending_failed(self, mock_flush, _mock_capture):+ from products.logs.backend.temporal.activities import _resolve_notification_deliveries++ result = MagicMock()+ result.get.side_effect = TimeoutError("undelivered")++ resolved = _resolve_notification_deliveries([self._dispatched(result)])++ assert resolved[0].notification_failed is True++class TestRunCohortQueryFallback(unittest.TestCase):@staticmethoddef _make_cohort(n: int) -> _AlertCohort:@@ -2029,3 +2084,61 @@ class TestEvaluateCohortBatchActivity(NonAtomicBaseTest):# First cohort errored → counts as 1 errored. Second succeeded → 1 checked.assert result.alerts_errored == 1assert result.alerts_checked == 1++ @freeze_time("2025-01-01T00:01:00Z")+ @patch("products.logs.backend.temporal.activities.flush_internal_events_producer", return_value=0)+ @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.logs.backend.temporal.activities._run_cohort_query")+ def test_undelivered_notification_rolls_back_state_before_save(+ self, mock_run_cohort_query, mock_produce, _mock_flush+ ):+ from products.logs.backend.temporal.activities import (+ CohortManifest,+ EvaluateCohortBatchInput,+ _CohortQueryResult,+ _PrefetchedQuery,+ evaluate_cohort_batch_activity,+ )++ alert = LogsAlertConfiguration.objects.create(+ team=self.team,+ name="a",+ threshold_count=10,+ threshold_operator="above",+ window_minutes=5,+ evaluation_periods=1,+ filters={"serviceNames": ["s"]},+ enabled=True,+ next_check_at=None,+ )++ def _mock_query(cohort):+ return _CohortQueryResult(+ per_alert={str(a.id): _PrefetchedQuery(buckets=_bucket_counts_for([50])) for a in cohort.alerts}+ )++ mock_run_cohort_query.side_effect = _mock_query+ # Enqueue succeeds, but the broker never acks: delivery is still pending+ # when the flush barrier gives up.+ undelivered = MagicMock()+ undelivered.get.side_effect = TimeoutError("undelivered")+ mock_produce.return_value = undelivered++ manifest = CohortManifest(+ team_id=self.team.id,+ projection_eligible=True,+ date_to_iso="2025-01-01T00:01:00+00:00",+ alert_ids=[str(alert.id)],+ )++ result = asyncio.run(evaluate_cohort_batch_activity(EvaluateCohortBatchInput(manifests=[manifest])))++ # A FIRE was attempted — the rollback (not absence of a breach) is what's proven below.+ mock_produce.assert_called_once()+ alert.refresh_from_db()+ assert alert.state == LogsAlertConfiguration.State.NOT_FIRING+ assert alert.last_notified_at is None+ assert result.alerts_fired == 0+ assert result.notified == []+ # The cycle still advances so the next cycle re-evaluates and retries the notification.+ assert alert.next_check_at is not None