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(alerts): refill the platform insight pool within a tick (#117367)

Jimmy Zhud55af7fe3615
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.md
index 4914b3f89f91..adb7f8c24c22 100644
--- a/docs/internal/alerts-platform-temporal.md
+++ b/docs/internal/alerts-platform-temporal.md
@@ -485,7 +485,7 @@ A full logs backfill hit ClickHouse's per-user concurrent query limit and had to
1. Copy one internal team with `--team-id`, then a small sample with `--sample-percent`, for example 5. The sample is chosen by alert id, so a rerun copies the same alerts and a larger percentage only adds alerts.
2. Watch the parallel run's ClickHouse cost in `query_log`: its `client_query_id` starts with `alerts-platform-insight:`.
3. Watch scheduler lag for `source=insight`, and the `capacity` skip reason on the platform's skipped-check counter. Capacity skips mean ClickHouse refused the query for load.
-4. Widen the sample only while both stay flat. `ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS` caps the concurrent checks whatever the sample size.
+4. Widen the sample only while both stay flat. `ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS` caps the concurrent checks whatever the sample size. A batch refills the slots its finished checks free, in rounds within its tick, so the cap limits concurrency rather than checks per minute.
5. Raise that cap from its default of 10 only while the daily count of refused queries, `exception_code = 202` in `query_log`, stays flat for both `alerts_platform_insight` and the user that production insight alerts query as. The first shows the parallel run's own contention. The second shows whether it reaches production through the server-wide limit. Do not size it from per-second concurrency, which overcounts because short queries that run back to back inside one second read as concurrent. Code 202 also covers the server-wide limit, so a rise is a reason to look rather than proof that the cap caused it.
To stop the parallel run, pass `--disable`, with `--team-id` to stop one team.
diff --git a/products/alerts/backend/platform_source_cycle.py b/products/alerts/backend/platform_source_cycle.py
index 9f66a3fcb9db..966b8d2b2c54 100644
--- a/products/alerts/backend/platform_source_cycle.py
+++ b/products/alerts/backend/platform_source_cycle.py
@@ -16,6 +16,7 @@ same set of checks.
"""
import time
+from collections.abc import Collection
from dataclasses import replace
from datetime import UTC, datetime
from typing import Final
@@ -37,7 +38,7 @@ from products.alerts.backend.evaluation.contract import AlertExtractionError
from products.alerts.backend.insight_alert_state_machine import INSIGHT_ALERT_POLICY, insight_snapshot
from products.alerts.backend.logic.alert_email import INSIGHT_ALERT_ERRORED_EVENT_ID
from products.alerts.backend.models.alert import AlertConfiguration
-from products.alerts_platform.backend.facade.api import due_checks, slot_of
+from products.alerts_platform.backend.facade.api import due_check_ids, due_checks, slot_of
from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
AlertEventKind,
@@ -115,29 +116,44 @@ def is_evaluated_on_the_platform(alert: AlertConfiguration) -> bool:
return not alert.detector_config and alert.calculation_interval in EVALUATED_INTERVALS
-def plan_insight_batch(team_id: int, slot: str, cutoff: datetime, *, expires_at: float) -> tuple[str, ...]:
+def plan_insight_batch(
+ team_id: int, slot: str, cutoff: datetime, *, expires_at: float, exclude: Collection[str] = ()
+) -> tuple[str, ...]:
"""Admits the batch's checks into the pool, in id order, while it has room, and returns the
ids it admitted.
The checks left out keep their due time, so a later tick finds them again. `expires_at` comes
from the workflow rather than the clock, so a retried attempt gets back the same admitted ids.
+
+ `exclude` names the checks the workflow already started. A running check holds its slot under
+ the same expiry, and a finished one stays due until the workflow records its outcome. Without
+ `exclude`, a later round would admit either one again.
"""
- checks = due_checks(team_id, SourceKind.INSIGHT.value, slot, cutoff)
- if not checks:
+ # The pool admits at most its size per round, so more candidates than that only add reads.
+ candidates = due_check_ids(
+ team_id,
+ SourceKind.INSIGHT.value,
+ slot,
+ cutoff,
+ exclude=exclude,
+ limit=settings.ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS,
+ )
+ if not candidates:
return ()
admitted = admit_evaluation_slots(
- [str(check.id) for check in checks],
+ list(candidates),
limit=settings.ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS,
expires_at=expires_at,
key=INFLIGHT_KEY,
)
- if len(admitted) < len(checks):
+ # Only on a batch's first round, because later rounds of a full pool would repeat it every few seconds.
+ if len(admitted) < len(candidates) and not exclude:
logger.info(
"Deferred platform insight checks over the pool limit",
team_id=team_id,
slot=slot,
admitted=len(admitted),
- deferred=len(checks) - len(admitted),
+ deferred=len(candidates) - len(admitted),
)
return tuple(admitted)
diff --git a/products/alerts/backend/temporal/platform_evaluate.py b/products/alerts/backend/temporal/platform_evaluate.py
index 31819f07da75..3bc7697a5a30 100644
--- a/products/alerts/backend/temporal/platform_evaluate.py
+++ b/products/alerts/backend/temporal/platform_evaluate.py
@@ -10,6 +10,7 @@ another would put the last check minutes behind the first.
import asyncio
import datetime as dt
+from collections.abc import Callable
from temporalio import activity, workflow
from temporalio.common import RetryPolicy
@@ -44,15 +45,22 @@ CHECK_QUEUE_TOLERANCE = dt.timedelta(minutes=1)
CHECK_SCHEDULE_TO_CLOSE = CHECK_START_TO_CLOSE + CHECK_QUEUE_TOLERANCE
RECORD_START_TO_CLOSE = dt.timedelta(seconds=8)
RECORD_SCHEDULE_TO_CLOSE = dt.timedelta(seconds=12)
+# The pool admits once per round, so a batch that admits only once evaluates at most one pool of
+# checks per tick. Rounds refill the slots that finished checks free, the way production's
+# scheduler does, until this budget ends. It stays under the one-minute tick.
+ADMISSION_RUN_BUDGET = dt.timedelta(seconds=50)
+ADMISSION_POLL_INTERVAL = dt.timedelta(seconds=2)
# What the source needs from its binding's `evaluation_timeout`. The checks run side by side, so
-# the batch costs one check's budget, not one per check.
-EVALUATION_BUDGET = PLAN_SCHEDULE_TO_CLOSE + CHECK_SCHEDULE_TO_CLOSE + RECORD_SCHEDULE_TO_CLOSE
+# the batch costs the admission rounds plus one check's budget, not one per check.
+EVALUATION_BUDGET = PLAN_SCHEDULE_TO_CLOSE + ADMISSION_RUN_BUDGET + CHECK_SCHEDULE_TO_CLOSE + RECORD_SCHEDULE_TO_CLOSE
+_PATCH_READMISSION = "platform-insight-readmission-2026-10"
@frozen
class InsightBatchPlanInputs:
evaluation: SourceEvaluationInputs
expires_at: float
+ exclude: tuple[str, ...] = ()
@frozen
@@ -72,7 +80,30 @@ def plan_platform_insight_batch_activity(inputs: InsightBatchPlanInputs) -> list
key = inputs.evaluation.batch_key
return list(
plan_insight_batch(
- key.team_id, key.slot, dt.datetime.fromisoformat(inputs.evaluation.cutoff), expires_at=inputs.expires_at
+ key.team_id,
+ key.slot,
+ dt.datetime.fromisoformat(inputs.evaluation.cutoff),
+ expires_at=inputs.expires_at,
+ exclude=inputs.exclude,
+ )
+ )
+
+
+@close_db_connections
+def plan_platform_insight_round_activity(inputs: InsightBatchPlanInputs) -> list[str]:
+ """`plan_platform_insight_batch_activity` with `exclude`, under its own name. A worker still on
+ the old code runs the old name and drops `exclude`, so the round path must not call that name."""
+ from products.alerts.backend.platform_source_cycle import plan_insight_batch # noqa: PLC0415
+
+ key = inputs.evaluation.batch_key
+ return list(
+ plan_insight_batch(
+ key.team_id,
+ key.slot,
+ dt.datetime.fromisoformat(inputs.evaluation.cutoff),
+ expires_at=inputs.expires_at,
+ exclude=inputs.exclude,
)
)
@@ -107,31 +138,19 @@ class InsightAlertPlatformEvaluateWorkflow(PostHogWorkflow):
# From the workflow's clock, so a retried plan reuses the expiry and gets its slots back. A
# check releases its slot only while the slot still carries this expiry.
expires_at = (workflow.now() + source_evaluation_timeout(SourceKind.INSIGHT)).timestamp()
- admitted = await workflow.execute_activity(
- plan_platform_insight_batch_activity,
- InsightBatchPlanInputs(evaluation=inputs, expires_at=expires_at),
- start_to_close_timeout=PLAN_START_TO_CLOSE,
- schedule_to_close_timeout=PLAN_SCHEDULE_TO_CLOSE,
- retry_policy=RetryPolicy(maximum_attempts=3),
- )
- if not admitted:
+ if workflow.patched(_PATCH_READMISSION):
+ settled = await self._evaluate_in_rounds(inputs, expires_at)
+ else:
+ admitted = await self._plan(
+ inputs, expires_at, exclude=(), activity_fn=plan_platform_insight_batch_activity
+ )
+ settled = await asyncio.gather(
+ *(self._check(inputs, configuration_id, expires_at) for configuration_id in admitted),
+ return_exceptions=True,
+ )
+ if not settled:
return 0
- # One attempt each. A check that does not finish leaves no outcome, so it keeps its due time
- # and a later tick evaluates it again, the way a cohort the logs budget left out behaves.
- settled = await asyncio.gather(
- *(
- workflow.execute_activity(
- evaluate_platform_insight_check_activity,
- InsightCheckInputs(evaluation=inputs, configuration_id=configuration_id, held_until=expires_at),
- start_to_close_timeout=CHECK_START_TO_CLOSE,
- schedule_to_close_timeout=CHECK_SCHEDULE_TO_CLOSE,
- retry_policy=RetryPolicy(maximum_attempts=1),
- )
- for configuration_id in admitted
- ),
- return_exceptions=True,
- )
for result in settled:
# Only a check's own failure is a missing outcome. A cancellation or a bug in this
# workflow would otherwise be recorded as a partial batch.
@@ -159,6 +178,67 @@ class InsightAlertPlatformEvaluateWorkflow(PostHogWorkflow):
await start_deliveries(deliveries)
return len(outcomes)
+ async def _plan(
+ self,
+ inputs: SourceEvaluationInputs,
+ expires_at: float,
+ *,
+ exclude: tuple[str, ...],
+ activity_fn: Callable[[InsightBatchPlanInputs], list[str]],
+ ) -> list[str]:
+ return await workflow.execute_activity(
+ activity_fn,
+ InsightBatchPlanInputs(evaluation=inputs, expires_at=expires_at, exclude=exclude),
+ start_to_close_timeout=PLAN_START_TO_CLOSE,
+ schedule_to_close_timeout=PLAN_SCHEDULE_TO_CLOSE,
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+ async def _check(
+ self, inputs: SourceEvaluationInputs, configuration_id: str, expires_at: float
+ ) -> SourceBatchEvaluation | None:
+ # One attempt each. A check that does not finish leaves no outcome, so it keeps its due time
+ # and a later tick evaluates it again, the way a cohort the logs budget left out behaves.
+ return await workflow.execute_activity(
+ evaluate_platform_insight_check_activity,
+ InsightCheckInputs(evaluation=inputs, configuration_id=configuration_id, held_until=expires_at),
+ start_to_close_timeout=CHECK_START_TO_CLOSE,
+ schedule_to_close_timeout=CHECK_SCHEDULE_TO_CLOSE,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+
+ async def _evaluate_in_rounds(
+ self, inputs: SourceEvaluationInputs, expires_at: float
+ ) -> list[SourceBatchEvaluation | None | BaseException]:
+ """Admits and starts checks in rounds until a round adds nothing and none of this batch's
+ checks still run, or until the admission budget ends."""
+ started: dict[str, asyncio.Task[SourceBatchEvaluation | None]] = {}
+ deadline = workflow.now() + ADMISSION_RUN_BUDGET
+ while True:
+ try:
+ admitted = await self._plan(
+ inputs, expires_at, exclude=tuple(started), activity_fn=plan_platform_insight_round_activity
+ )
+ except ActivityError:
+ if not started:
+ raise
+ # The started checks still record. Their outcomes are lost if this failure ends the run.
+ workflow.logger.warning("Stopped admitting platform insight checks after a failed plan")
+ break
+ for configuration_id in admitted:
+ started[configuration_id] = asyncio.create_task(self._check(inputs, configuration_id, expires_at))
+ running = [task for task in started.values() if not task.done()]
+ if not running or workflow.now() >= deadline:
+ break
+ await asyncio.wait(
+ running, timeout=ADMISSION_POLL_INTERVAL.total_seconds(), return_when=asyncio.FIRST_COMPLETED
+ )
+ return await asyncio.gather(*started.values(), return_exceptions=True)
+
PLATFORM_EVALUATION_WORKFLOWS = [InsightAlertPlatformEvaluateWorkflow]
-PLATFORM_EVALUATION_ACTIVITIES = [plan_platform_insight_batch_activity, evaluate_platform_insight_check_activity]
+PLATFORM_EVALUATION_ACTIVITIES = [
+ plan_platform_insight_batch_activity,
+ plan_platform_insight_round_activity,
+ evaluate_platform_insight_check_activity,
+]
diff --git a/products/alerts/backend/test/test_platform_evaluate_workflow.py b/products/alerts/backend/test/test_platform_evaluate_workflow.py
index bff1e29d553b..a71efccfca93 100644
--- a/products/alerts/backend/test/test_platform_evaluate_workflow.py
+++ b/products/alerts/backend/test/test_platform_evaluate_workflow.py
@@ -1,6 +1,8 @@
import uuid
from collections.abc import AsyncIterator
+import pytest
+
from django.conf import settings
import pytest_asyncio
@@ -42,7 +44,7 @@ async def environment() -> AsyncIterator[WorkflowEnvironment]:
async def test_a_check_that_fails_does_not_stop_the_batch_recording_the_rest(environment: WorkflowEnvironment) -> None:
recorded: list[SourceOutcomeInputs] = []
- @activity.defn(name="plan_platform_insight_batch_activity")
+ @activity.defn(name="plan_platform_insight_round_activity")
async def plan(inputs: InsightBatchPlanInputs) -> list[str]:
return list(ADMITTED)
@@ -108,5 +110,79 @@ async def test_a_check_that_fails_does_not_stop_the_batch_recording_the_rest(env
assert child.task_queue == settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE
+ "fail_second_plan, expected",
+ [
+ (
+ False,
+ [
+ "00000000-0000-0000-0000-000000000001",
+ "00000000-0000-0000-0000-000000000002",
+ "00000000-0000-0000-0000-000000000003",
+ ],
+ ),
+ # A later plan that fails stops admission, but the checks that already ran still record.
+ (True, ["00000000-0000-0000-0000-000000000001"]),
+ ],
+)
+async def test_a_batch_refills_the_slots_its_finished_checks_free(
+ environment: WorkflowEnvironment, fail_second_plan: bool, expected: list[str]
+) -> None:
+ due = [f"00000000-0000-0000-0000-00000000000{n}" for n in range(1, 4)]
+ plans: list[tuple[str, ...]] = []
+ evaluated: list[str] = []
+ recorded: list[SourceOutcomeInputs] = []
+
+ # A pool of one slot: each round admits the first due check that this batch did not start.
+ @activity.defn(name="plan_platform_insight_round_activity")
+ async def plan(inputs: InsightBatchPlanInputs) -> list[str]:
+ plans.append(inputs.exclude)
+ if fail_second_plan and len(plans) == 2:
+ raise ApplicationError("redis unavailable", non_retryable=True)
+ if set(inputs.exclude) - set(evaluated):
+ return []
+ return [configuration_id for configuration_id in due if configuration_id not in inputs.exclude][:1]
+
+ @activity.defn(name="evaluate_platform_insight_check_activity")
+ async def evaluate(inputs: InsightCheckInputs) -> SourceBatchEvaluation | None:
+ evaluated.append(inputs.configuration_id)
+ outcome = PlatformAlertOutcome(
+ configuration_id=uuid.UUID(inputs.configuration_id),
+ evaluation_key="slot:2026-09-16T10:00:00+00:00",
+ kind=AlertEventKind.CHECK,
+ new_state="not_firing",
+ notified=False,
+ consecutive_failures=0,
+ )
+ return SourceBatchEvaluation(outcomes=(outcome,), deliveries=())
+
+ @activity.defn(name=RECORD_OUTCOMES_ACTIVITY)
+ async def record(inputs: SourceOutcomeInputs) -> int:
+ recorded.append(inputs)
+ return len(inputs.outcomes)
+
+ async with Worker(
+ environment.client,
+ task_queue=QUEUE,
+ workflows=[InsightAlertPlatformEvaluateWorkflow],
+ activities=[plan, evaluate, record],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ result = await environment.client.execute_workflow(
+ InsightAlertPlatformEvaluateWorkflow.run,
+ SourceEvaluationInputs(
+ source=SourceKind.INSIGHT,
+ cutoff="2026-09-16T10:00:00+00:00",
+ batch_key=AlertBatchKey(team_id=1, slot="2026-09-16T10:00:00+00:00"),
+ ),
+ id=f"test-{uuid.uuid4()}",
+ task_queue=QUEUE,
+ )
+
+ assert result == len(expected)
+ assert sorted(evaluated) == expected
+ assert [sorted(str(o.configuration_id) for o in batch.outcomes) for batch in recorded] == [expected]
+
+
def test_the_binding_holds_the_whole_batch() -> None:
assert source_evaluation_timeout(SourceKind.INSIGHT) > EVALUATION_BUDGET
diff --git a/products/alerts/backend/test/test_platform_source_cycle.py b/products/alerts/backend/test/test_platform_source_cycle.py
index 813d4a11be49..0886daf695ad 100644
--- a/products/alerts/backend/test/test_platform_source_cycle.py
+++ b/products/alerts/backend/test/test_platform_source_cycle.py
@@ -26,13 +26,19 @@ from products.alerts.backend.platform_source_cycle import (
evaluate_insight_check,
plan_insight_batch,
)
+from products.alerts.backend.temporal.platform_evaluate import (
+ InsightBatchPlanInputs,
+ plan_platform_insight_round_activity,
+)
from products.alerts.backend.test.insight_alerts import create_insight_alert
from products.alerts_platform.backend.facade import testing as platform_testing
from products.alerts_platform.backend.facade.api import record_outcomes, slot_of
from products.alerts_platform.backend.facade.contracts import (
+ AlertBatchKey,
AlertEventKind,
PlatformAlertOutcome,
PlatformConfigurationSnapshot,
+ SourceEvaluationInputs,
SourceKind,
)
@@ -195,5 +201,16 @@ class TestPlatformInsightEvaluation(APIBaseTest):
with patch(f"{_MODULE}.check_alert_for_insight", return_value=AlertEvaluationResult(value=1.0, breaches=[])):
evaluate_insight_check(self.team.id, slot, CUTOFF, admitted, held_until=expires_at, evaluation_id="test")
- assert len(plan_insight_batch(self.team.id, slot, CUTOFF, expires_at=expires_at + 60)) == 1
- assert {str(first.id), str(second.id)} >= {admitted}
+ # Through the activity the workflow calls, so a dropped `exclude` there fails here too.
+ replanned = plan_platform_insight_round_activity(
+ InsightBatchPlanInputs(
+ evaluation=SourceEvaluationInputs(
+ source=SourceKind.INSIGHT,
+ cutoff=CUTOFF.isoformat(),
+ batch_key=AlertBatchKey(team_id=self.team.id, slot=slot),
+ ),
+ expires_at=expires_at,
+ exclude=(admitted,),
+ )
+ )
+ assert replanned == list({str(first.id), str(second.id)} - {admitted})
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.py
index 8c37389c3af9..34644aaf5920 100644
--- a/products/alerts_platform/backend/facade/api.py
+++ b/products/alerts_platform/backend/facade/api.py
@@ -30,6 +30,13 @@ def due_checks(
return platform_lifecycle.due_checks(team_id, source_kind, slot, cutoff, configuration_ids=configuration_ids)
+def due_check_ids(
+ team_id: int, source_kind: str, slot: str, cutoff: datetime, *, exclude: Collection[str] = (), limit: int
+) -> tuple[str, ...]:
+ """The first `limit` due ids of one batch key, skipping `exclude`, without their runtime state."""
+ return platform_lifecycle.due_check_ids(team_id, source_kind, slot, cutoff, exclude=exclude, limit=limit)
+
+
def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now: datetime) -> int:
"""The platform's only write of state and schedule. Returns how many rows it wrote."""
return platform_lifecycle.record_outcomes(team_id, outcomes, now)
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index 6a0d77dade9c..a3a745b2c14a 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -9,7 +9,7 @@ from datetime import datetime, timedelta
from typing import Final
from django.db import transaction
-from django.db.models import Exists, OuterRef, Q
+from django.db.models import Exists, OuterRef, Q, QuerySet
from posthog.models import Team
@@ -93,6 +93,39 @@ def suppressed() -> Exists:
)
+def _due(team_id: int, source_kind: str, cutoff: datetime) -> QuerySet[PlatformAlertConfiguration]:
+ return (
+ PlatformAlertConfiguration.objects.for_team(team_id)
+ .filter(enabled=True, source_kind=source_kind)
+ .filter(due_q(cutoff))
+ .exclude(suppressed())
+ )
+
+
+def due_check_ids(
+ team_id: int, source_kind: str, slot: str, cutoff: datetime, *, exclude: Collection[str] = (), limit: int
+) -> tuple[str, ...]:
+ """The first `limit` due ids of one batch key, in id order, without reading their runtime rows.
+
+ For a source that admits ids in rounds. A round reads only ids, so a large batch does not
+ reload every configuration and its alert row each time a check finishes.
+ """
+ rows = (
+ _due(team_id, source_kind, cutoff)
+ .exclude(id__in=list(exclude))
+ .order_by("id")
+ .values_list("id", "next_check_at")
+ )
+ ids: list[str] = []
+ for configuration_id, next_check_at in rows.iterator():
+ if slot_of(next_check_at, cutoff) != slot:
+ continue
+ ids.append(str(configuration_id))
+ if len(ids) == limit:
+ break
+ return tuple(ids)
+
+
def due_checks(
team_id: int, source_kind: str, slot: str, cutoff: datetime, *, configuration_ids: Collection[str] | None = None
) -> tuple[PlatformAlertCheckInput, ...]:
@@ -101,12 +134,7 @@ def due_checks(
`configuration_ids` narrows the batch to those rows, for a source that evaluates one check at
a time and must still read nothing the batch would not.
"""
- due = (
- PlatformAlertConfiguration.objects.for_team(team_id)
- .filter(enabled=True, source_kind=source_kind)
- .filter(due_q(cutoff))
- .exclude(suppressed())
- )
+ due = _due(team_id, source_kind, cutoff)
if configuration_ids is not None:
due = due.filter(id__in=list(configuration_ids))
# Ordered so a retried attempt keeps the same alerts under any downstream cap.