: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): bound the platform's parallel logs batches across the fleet (#114799)
Jimmy Zhu6511b3ece362
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.mdindex fb37036bfcfa..93ae931a75f2 100644--- a/docs/internal/alerts-platform-temporal.md+++ b/docs/internal/alerts-platform-temporal.md@@ -483,6 +483,7 @@ Run it only after the evaluation worker's chart sets `CLICKHOUSE_ALERTS_PLATFORMInsight checks tag their queries with `ClickHouseUser.ALERTS_PLATFORM_INSIGHT`, a user of their own, so the parallel run never takes from the per-user budget of the user that production insight alerts query as.Without that env the tag resolves to the worker's default user, which other workloads on the same servers already push against its concurrent query limit.Logs checks use their own user, `alerts_platform_logs`, on the logs cluster.+Logs checks also wait for room in a fleet-wide pool of batches, `ALERTS_PLATFORM_LOGS_MAX_INFLIGHT_BATCHES` (default 5). A batch runs its cohort queries one after another, so this bounds the parallel run's concurrent logs queries however many teams are copied. A batch the pool turns away keeps its due time and a later tick picks it up, so a pool that is too small shows up as scheduler lag for `source=logs`.Every copy adds ClickHouse load beside production's, so roll it out in steps.A full logs backfill hit ClickHouse's per-user concurrent query limit and had to be removed.diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 8a1f1d1b5d29..add2b4fe8eac 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -361,6 +361,15 @@ if ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS <= 0:raise ImproperlyConfigured("ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS must be a positive integer, or no platform insight check starts")+# The platform's parallel logs batches allowed to run at once, across every team. A batch runs its+# cohort queries one after another, so this bounds the parallel run's concurrent logs queries.+ALERTS_PLATFORM_LOGS_MAX_INFLIGHT_BATCHES: int = get_from_env(+ "ALERTS_PLATFORM_LOGS_MAX_INFLIGHT_BATCHES", 5, type_cast=int+)+if ALERTS_PLATFORM_LOGS_MAX_INFLIGHT_BATCHES <= 0:+ raise ImproperlyConfigured(+ "ALERTS_PLATFORM_LOGS_MAX_INFLIGHT_BATCHES must be a positive integer, or no platform logs check starts"+ )# Insight alert checks allowed to run against ClickHouse at once, across every team.ALERTS_MAX_INFLIGHT_EVALUATIONS: int = get_from_env("ALERTS_MAX_INFLIGHT_EVALUATIONS", 40, type_cast=int)if ALERTS_MAX_INFLIGHT_EVALUATIONS <= 0:diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex 05cf614641fd..5289225be193 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -380,8 +380,8 @@ class SourceBatchEvaluation:outcomes: tuple[PlatformAlertOutcome, ...]deliveries: tuple[AlertDeliveryRequest, ...]- # Pairs the payload bound left out. They keep their due time and a later tick re-evaluates- # them, the way a truncated cohort already behaves.+ # Pairs the payload bound or a full evaluation pool left out. They keep their due time and a+ # later tick re-evaluates them, the way a truncated cohort already behaves.omitted: int = 0diff --git a/products/logs/backend/alert_check_query.py b/products/logs/backend/alert_check_query.pyindex e8921a5f02b5..ace8d3e366cb 100644--- a/products/logs/backend/alert_check_query.py+++ b/products/logs/backend/alert_check_query.py@@ -595,7 +595,9 @@ class BatchedAlertCheckQuery:CHECKPOINT_MAX_STALENESS = dt.timedelta(minutes=5)-def fetch_live_logs_checkpoint(team: Team, *, ch_user: ClickHouseUser = ClickHouseUser.DEFAULT) -> dt.datetime | None:+def fetch_live_logs_checkpoint(+ team: Team, *, ch_user: ClickHouseUser = ClickHouseUser.DEFAULT, max_execution_time: int | None = None+) -> dt.datetime | None:tag_queries(product=Product.LOGS,feature=Feature.ALERTING,@@ -609,6 +611,9 @@ def fetch_live_logs_checkpoint(team: Team, *, ch_user: ClickHouseUser = ClickHouworkload=Workload.LOGS,ch_user=ch_user,modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),+ settings=None+ if max_execution_time is None+ else HogQLGlobalSettings(max_execution_time=max_execution_time, timeout_overflow_mode="throw"),)if not response.results or response.results[0][0] is None:return Nonediff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.pyindex a276518a3786..d1957c5e1d01 100644--- a/products/logs/backend/alert_source_cycle.py+++ b/products/logs/backend/alert_source_cycle.py@@ -20,13 +20,16 @@ from dataclasses import replacefrom datetime import datetime, timedeltafrom itertools import batchedfrom typing import Final, cast-from uuid import UUID+from uuid import UUID, uuid4++from django.conf import settingsimport structlogfrom posthog.clickhouse.client.connection import ClickHouseUserfrom posthog.dataclasses import frozenfrom posthog.models import Team+from posthog.temporal.alerts.admission import hold_evaluation_slot, release_evaluation_slotfrom posthog.utils import absolute_urifrom products.alerts.backend.facade.destinations import configured_destination_template_ids@@ -106,6 +109,14 @@ BATCH_QUERY_BUDGET_SECONDS = 25MAX_QUERY_SECONDS = 20# Below this there is no point starting another query; the cohort keeps its due time instead.MIN_QUERY_SECONDS = 2+# With the cohort budget this keeps every query of a batch inside `BATCH_SLOT_LEASE_SECONDS`, so a+# query never runs after its slot frees for another batch.+CHECKPOINT_QUERY_SECONDS = 10++INFLIGHT_KEY = "alerts:platform:logs:batches:inflight"+# Taken inside the evaluation activity, so it only has to outlast that activity's start-to-close. Short+# enough that a worker that dies mid-batch frees its slot within a minute.+BATCH_SLOT_LEASE_SECONDS = 60@frozen@@ -705,6 +716,29 @@ def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatcif not checks:return SourceBatchEvaluation(outcomes=(), deliveries=())+ # One slot per batch, because a batch runs its cohort queries one after another, so the batches+ # in flight bound the parallel run's concurrent queries across the fleet. A batch the pool turns+ # away records nothing, so its checks stay due and a later tick finds them again.+ # Unique per execution: a redispatch of a batch whose old query still runs must hold its own slot.+ member = f"{team_id}:{slot}:{uuid4().hex}"+ held_until = hold_evaluation_slot(+ member,+ limit=settings.ALERTS_PLATFORM_LOGS_MAX_INFLIGHT_BATCHES,+ lease_seconds=BATCH_SLOT_LEASE_SECONDS,+ key=INFLIGHT_KEY,+ )+ if held_until is None:+ logger.info("Deferred a platform logs batch over the pool limit", team_id=team_id, slot=slot)+ return SourceBatchEvaluation(outcomes=(), deliveries=(), omitted=len(checks))+ try:+ return _evaluate_admitted(team_id, slot, cutoff, checks, started_at=started_at)+ finally:+ release_evaluation_slot(member, held_until=held_until, key=INFLIGHT_KEY)+++def _evaluate_admitted(+ team_id: int, slot: str, cutoff: datetime, checks: Sequence[PlatformAlertCheckInput], *, started_at: float+) -> SourceBatchEvaluation:team = Team.objects.filter(id=team_id).first()if team is None:return SourceBatchEvaluation(outcomes=(), deliveries=())@@ -719,7 +753,9 @@ def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatc# One checkpoint for the pass, matching the production discovery activity. A failure falls# back to wall-clock rather than ending the batch.try:- checkpoint = fetch_live_logs_checkpoint(team, ch_user=ClickHouseUser.ALERTS_PLATFORM_LOGS)+ checkpoint = fetch_live_logs_checkpoint(+ team, ch_user=ClickHouseUser.ALERTS_PLATFORM_LOGS, max_execution_time=CHECKPOINT_QUERY_SECONDS+ )except Exception as error:logger.exception("Failed to fetch logs ingestion checkpoint; falling back to wall-clock", error=str(error))checkpoint = Nonediff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.pyindex 4d9511422c84..07684859d6b4 100644--- a/products/logs/backend/test/test_alert_evaluate.py+++ b/products/logs/backend/test/test_alert_evaluate.py@@ -1,3 +1,4 @@+import timefrom datetime import UTC, datetime, timedeltafrom typing import Anyfrom uuid import UUID, uuid4@@ -6,13 +7,15 @@ import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch-from django.test import SimpleTestCase+from django.test import SimpleTestCase, override_settingsfrom parameterized import parameterizedfrom posthog.hogql.errors import ExposedHogQLError+from posthog import redisfrom posthog.models.scoping import team_scope+from posthog.temporal.alerts.admission import admit_evaluation_slotsfrom products.alerts_platform.backend.facade import testing as platform_testingfrom products.alerts_platform.backend.facade.api import due_checks, list_configurations, record_outcomes, slot_of@@ -30,7 +33,12 @@ from products.alerts_platform.backend.facade.temporal import source_evaluation_tfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.logs.backend.alert_check_query import BatchedBucketedResult, BucketedCountfrom 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.alert_source_cycle import (+ BATCH_QUERY_BUDGET_SECONDS,+ INFLIGHT_KEY,+ MAX_QUERY_SECONDS,+ evaluate_logs_batch,+)from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEventfrom products.logs.backend.platform_alert_backfill import backfill_platform_alert_configurationsfrom products.logs.backend.temporal.alert_evaluate import (@@ -53,6 +61,7 @@ class TestLogsAlertEvaluation(APIBaseTest):self.cutoff = datetime(2026, 9, 16, 10, tzinfo=UTC)# A backfilled copy delivers to the logs alert it came from, so its destinations name that id.self._legacy_ids: dict[UUID, UUID] = {}+ redis.get_client().delete(INFLIGHT_KEY)def _legacy_alert(self, source_config: dict[str, Any], **fields: Any) -> LogsAlertConfiguration:filters = {key: value for key, value in source_config.items() if key != "condition"}@@ -407,6 +416,33 @@ 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_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.+ admit_evaluation_slots(+ [f"{self.team.id}:{self._slot()}"], limit=1, expires_at=time.time() + 60, key=INFLIGHT_KEY+ )++ with override_settings(ALERTS_PLATFORM_LOGS_MAX_INFLIGHT_BATCHES=1):+ deferred, query = self._run(configuration)++ assert (deferred.outcomes, query.called) == ((), False)++ def test_a_batch_waits_for_room_in_the_fleet_pool_and_frees_its_slot_when_done(self) -> None:+ configuration = self._configuration()+ admit_evaluation_slots(["another-team:slot"], limit=1, expires_at=time.time() + 60, key=INFLIGHT_KEY)++ with override_settings(ALERTS_PLATFORM_LOGS_MAX_INFLIGHT_BATCHES=1):+ deferred, query = self._run(configuration)+ assert (deferred.outcomes, deferred.omitted, query.called) == ((), 1, False)++ redis.get_client().delete(INFLIGHT_KEY)+ first, _ = self._run(configuration)+ # The first batch gave its slot back, or a pool of one would turn this one away.+ second, _ = self._run(configuration)++ assert [len(first.outcomes), len(second.outcomes)] == [1, 1]+def test_a_logs_alert_with_unreadable_filters_breaks_alone(self) -> None:unreadable, healthy = self._configuration(), self._configuration()LogsAlertConfiguration.objects.filter(id=self._legacy_ids[unreadable.id]).update(filters=[])