: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): wait on a workflow timer for a platform logs pool slot (#118212)
Jimmy Zhu380218a9012f
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.mdindex c6ecac0b3b08..d75b81b64973 100644--- a/docs/internal/alerts-platform-temporal.md+++ b/docs/internal/alerts-platform-temporal.md@@ -513,7 +513,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`.+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 waits on a workflow timer and tries again for up to 20 seconds, so it usually still runs within its own minute. The wait holds no worker slot, because it is a timer in the workflow rather than a sleep in the evaluation activity. A batch still without a slot after that 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` and as `alerts_platform_checks_deferred_total{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/products/alerts_platform/backend/temporal/sources.py b/products/alerts_platform/backend/temporal/sources.pyindex b88ed46da570..de6a0576cd6b 100644--- a/products/alerts_platform/backend/temporal/sources.py+++ b/products/alerts_platform/backend/temporal/sources.py@@ -45,7 +45,7 @@ SOURCE_BINDINGS: dict[SourceKind, SourceBinding] = {SourceKind.LOGS: SourceBinding(workflow="logs-alert-evaluate",task_queue=settings.ALERTS_PLATFORM_EVALUATION_TASK_QUEUE,- evaluation_timeout=dt.timedelta(seconds=75),+ evaluation_timeout=dt.timedelta(seconds=120),discovery_limit=DISCOVERY_LIMIT_PER_SOURCE,),SourceKind.INSIGHT: SourceBinding(diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.pyindex 308907404908..6c865c34db97 100644--- a/products/logs/backend/alert_source_cycle.py+++ b/products/logs/backend/alert_source_cycle.py@@ -34,7 +34,7 @@ from posthog.temporal.alerts.admission import hold_evaluation_slot, release_evalfrom posthog.utils import absolute_urifrom products.alerts.backend.facade.destinations import configured_destination_template_ids-from products.alerts_platform.backend.facade.api import due_checks, refresh_settings, slot_of+from products.alerts_platform.backend.facade.api import due_check_ids, due_checks, refresh_settings, slot_offrom products.alerts_platform.backend.facade.contracts import (AlertDeliveryRequest,AlertEventKind,@@ -100,6 +100,7 @@ from products.logs.backend.platform_alert_backfill import platform_upsert_of# 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.from products.logs.backend.temporal.activities import _derive_breaches, _detect_broken_filter_config+from products.logs.backend.temporal.batch_slot import LogsBatchAdmission, LogsBatchSlotfrom products.logs.backend.temporal.constants import MAX_ALERT_COHORT_SIZElogger = structlog.get_logger(__name__)@@ -127,9 +128,12 @@ MIN_QUERY_SECONDS = 2CHECKPOINT_QUERY_SECONDS = 10INFLIGHT_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+# A workflow takes the slot before its evaluation activity starts, and the activity holds it again+# under a fresh lease when it starts. So the lease has to outlast the rest of the take and the+# activity's queue time, and also the activity's run, with room to spare. Short enough that a worker+# that dies mid-batch frees its slot within two minutes.+BATCH_SLOT_LEASE_SECONDS = 90+_DEFERRED_COUNT_LIMIT = 10_000@frozen@@ -937,6 +941,66 @@ def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatcrelease_evaluation_slot(member, held_until=held_until, key=INFLIGHT_KEY)+def take_logs_batch_slot(+ team_id: int, slot: str, cutoff: datetime, *, member: str, first: bool, final: bool+) -> LogsBatchAdmission:+ """One try at a pool slot for a batch, without waiting. The workflow waits between tries.++ `member` comes from the workflow, so a retried attempt finds the slot an earlier attempt took+ instead of taking a second one. Only the first try asks whether the batch is due: nothing else+ evaluates this batch key while its workflow waits, and the evaluation reads the checks again.+ `final` marks the last try: a batch that still finds no room misses its tick, and only that try+ counts its checks as deferred.+ """+ due: tuple[str, ...] = ()+ if first or final:+ # The last try counts every due check it defers, so only it reads more than one id.+ due = due_check_ids(team_id, SourceKind.LOGS.value, slot, cutoff, limit=_DEFERRED_COUNT_LIMIT if final else 1)+ if not due:+ return LogsBatchAdmission(due=False)+ 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:+ if final:+ logger.info("Deferred a platform logs batch over the pool limit", team_id=team_id, slot=slot)+ safe_record(increment_checks_deferred, SourceKind.LOGS.value, len(due))+ return LogsBatchAdmission(due=True)+ return LogsBatchAdmission(due=True, slot=LogsBatchSlot(member=member, held_until=held_until))+++def evaluate_held_logs_batch(team_id: int, slot: str, cutoff: datetime, held: LogsBatchSlot) -> SourceBatchEvaluation:+ """`evaluate_logs_batch` for a batch whose workflow already took its slot. Releases the slot."""+ started_at = time.monotonic()+ # Hold the slot again under a fresh lease. The take's lease can lapse while this activity waits in+ # the queue, and a timed-out take attempt can rewrite the expiry after its retry returned. A batch+ # whose slot lapsed while the pool filled finds no room here, and its checks stay due.+ held_until = hold_evaluation_slot(+ held.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 whose slot lapsed", team_id=team_id, slot=slot)+ return SourceBatchEvaluation(outcomes=(), deliveries=())+ try:+ checks = due_checks(team_id, SourceKind.LOGS.value, slot, cutoff)+ if not checks:+ return SourceBatchEvaluation(outcomes=(), deliveries=())+ return _evaluate_admitted(team_id, slot, cutoff, checks, started_at=started_at)+ finally:+ release_evaluation_slot(held.member, held_until=held_until, key=INFLIGHT_KEY)+++def release_logs_batch_slot(held: LogsBatchSlot) -> None:+ """Frees a slot whose evaluation never started. A no-op once that evaluation held the slot again."""+ release_evaluation_slot(held.member, held_until=held.held_until, key=INFLIGHT_KEY)++def _evaluate_admitted(team_id: int, slot: str, cutoff: datetime, checks: Sequence[PlatformAlertCheckInput], *, started_at: float) -> SourceBatchEvaluation:diff --git a/products/logs/backend/temporal/alert_evaluate.py b/products/logs/backend/temporal/alert_evaluate.pyindex 771ccc68ae03..782631baf0e0 100644--- a/products/logs/backend/temporal/alert_evaluate.py+++ b/products/logs/backend/temporal/alert_evaluate.py@@ -5,11 +5,12 @@ plain function a test can call without Temporal."""import datetime as dt+import contextlibimport dataclassesfrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy-from temporalio.exceptions import WorkflowAlreadyStartedError+from temporalio.exceptions import ActivityError, WorkflowAlreadyStartedErrorfrom posthog.temporal.common.base import PostHogWorkflow@@ -32,6 +33,7 @@ with workflow.unsafe.imports_passed_through():PlatformAlertSignal,notified_alerts_for_platform,)+ from products.logs.backend.temporal.batch_slot import LogsBatchAdmission, LogsBatchSlotWORKFLOW_NAME = "logs-alert-evaluate"@@ -50,9 +52,27 @@ EVALUATE_SCHEDULE_TO_CLOSE = EVALUATE_START_TO_CLOSE + EVALUATE_QUEUE_TOLERANCE# the next tick reaches it anyway, and holding the key meanwhile blocks its own re-dispatch.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 and signal children.-EVALUATION_BUDGET = EVALUATE_SCHEDULE_TO_CLOSE + RECORD_SCHEDULE_TO_CLOSE+# A batch the pool turns away waits on a workflow timer and tries again, so it runs inside its own+# tick instead of the next. The timer holds no worker slot, which a wait inside the sync activity+# would. A batch still without a slot after the budget keeps its checks due for a later tick. The+# budget is a third of the tick, so a batch let in late still finishes close to its own minute.+# A freed slot goes to whichever batch tries next, not to the one that waited longest.+SLOT_WAIT_BUDGET = dt.timedelta(seconds=20)+# The interval grows from the first to the last value, with jitter, so the batches of one tick do+# not all try again in the same second.+SLOT_POLL_FIRST_INTERVAL = dt.timedelta(seconds=1)+SLOT_POLL_MAX_INTERVAL = dt.timedelta(seconds=4)+SLOT_POLL_JITTER_SECONDS = 0.5+TAKE_SLOT_START_TO_CLOSE = dt.timedelta(seconds=5)+TAKE_SLOT_SCHEDULE_TO_CLOSE = dt.timedelta(seconds=10)+# What the source needs from its binding's `evaluation_timeout`, which has to hold the wait, both+# activities, and still leave room to start the delivery and signal children. The wait can run one+# try past its budget, because the last try starts before the budget ends.+EVALUATION_BUDGET = (+ SLOT_WAIT_BUDGET + 2 * TAKE_SLOT_SCHEDULE_TO_CLOSE + EVALUATE_SCHEDULE_TO_CLOSE + RECORD_SCHEDULE_TO_CLOSE+)+# Workflows started before the wait replay the single try inside the evaluation activity.+WAIT_FOR_SLOT_PATCH = "logs-alert-evaluate-wait-for-slot"SIGNALS_WORKFLOW_NAME = "logs-alert-platform-signals"# A child workflow with its own budget, so a large batch of signals never competes with the@@ -69,6 +89,20 @@ _SIGNAL_ACTIONS: dict[AlertEventKind, AlertSignalAction] = {}[email protected](frozen=True)+class TakeLogsBatchSlotInputs:+ evaluation: SourceEvaluationInputs+ member: str+ first: bool+ final: bool++[email protected](frozen=True)+class HeldLogsBatchInputs:+ evaluation: SourceEvaluationInputs+ slot: LogsBatchSlot++@dataclasses.dataclass(frozen=True)class PlatformSignalInputs:team_id: int@@ -125,6 +159,41 @@ def evaluate_logs_alerts_activity(inputs: SourceEvaluationInputs) -> SourceBatch)+@close_db_connections+def take_logs_batch_slot_activity(inputs: TakeLogsBatchSlotInputs) -> LogsBatchAdmission:+ from products.logs.backend.alert_source_cycle import take_logs_batch_slot++ key = inputs.evaluation.batch_key+ return take_logs_batch_slot(+ key.team_id,+ key.slot,+ dt.datetime.fromisoformat(inputs.evaluation.cutoff),+ member=inputs.member,+ first=inputs.first,+ final=inputs.final,+ )+++@close_db_connections+def evaluate_held_logs_batch_activity(inputs: HeldLogsBatchInputs) -> SourceBatchEvaluation:+ """Sync for the same reason as `evaluate_logs_alerts_activity`."""+ from products.logs.backend.alert_source_cycle import evaluate_held_logs_batch++ key = inputs.evaluation.batch_key+ return evaluate_held_logs_batch(+ key.team_id, key.slot, dt.datetime.fromisoformat(inputs.evaluation.cutoff), inputs.slot+ )+++def release_logs_batch_slot_activity(held: LogsBatchSlot) -> None:+ from products.logs.backend.alert_source_cycle import release_logs_batch_slot++ release_logs_batch_slot(held)++@activity.defnasync def emit_platform_alert_signals_activity(inputs: PlatformSignalInputs) -> int:"""Emits the Self-driving signals for alerts the platform owns. Never raises."""@@ -165,13 +234,38 @@ class LogsAlertEvaluateWorkflow(PostHogWorkflow):async def run(self, inputs: SourceEvaluationInputs) -> int:# The evaluation writes nothing, so a lost attempt costs its queries and the retry reads# the same still-due batch. Its result reaches history before the write below runs.- evaluation = await workflow.execute_activity(- evaluate_logs_alerts_activity,- inputs,- start_to_close_timeout=EVALUATE_START_TO_CLOSE,- schedule_to_close_timeout=EVALUATE_SCHEDULE_TO_CLOSE,- retry_policy=RetryPolicy(maximum_attempts=1),- )+ if workflow.patched(WAIT_FOR_SLOT_PATCH):+ held = await self._wait_for_slot(inputs)+ if held is None:+ return 0+ try:+ evaluation = await workflow.execute_activity(+ evaluate_held_logs_batch_activity,+ HeldLogsBatchInputs(evaluation=inputs, slot=held),+ start_to_close_timeout=EVALUATE_START_TO_CLOSE,+ schedule_to_close_timeout=EVALUATE_SCHEDULE_TO_CLOSE,+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ except ActivityError:+ # An evaluation that timed out in the queue never ran its release. The release checks+ # the take's expiry, so it does nothing to a slot an evaluation that did start holds.+ with contextlib.suppress(ActivityError):+ await workflow.execute_activity(+ release_logs_batch_slot_activity,+ held,+ start_to_close_timeout=TAKE_SLOT_START_TO_CLOSE,+ schedule_to_close_timeout=TAKE_SLOT_SCHEDULE_TO_CLOSE,+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ raise+ else:+ evaluation = await workflow.execute_activity(+ evaluate_logs_alerts_activity,+ inputs,+ start_to_close_timeout=EVALUATE_START_TO_CLOSE,+ schedule_to_close_timeout=EVALUATE_SCHEDULE_TO_CLOSE,+ retry_policy=RetryPolicy(maximum_attempts=1),+ )if evaluation.outcomes:await workflow.execute_activity(@@ -207,9 +301,45 @@ class LogsAlertEvaluateWorkflow(PostHogWorkflow):return started+ async def _wait_for_slot(self, inputs: SourceEvaluationInputs) -> LogsBatchSlot | None:+ """Tries for a pool slot until one frees or the wait budget ends. None when the batch has+ nothing left to evaluate, or when it still has no slot, which leaves its checks due."""+ # From the workflow, so it is the same on replay and on every retry of a try.+ member = f"{inputs.batch_key.team_id}:{inputs.batch_key.slot}:{workflow.uuid4().hex}"+ deadline = workflow.now() + SLOT_WAIT_BUDGET+ interval = SLOT_POLL_FIRST_INTERVAL+ first = True+ while True:+ final = workflow.now() >= deadline+ try:+ admission = await workflow.execute_activity(+ take_logs_batch_slot_activity,+ TakeLogsBatchSlotInputs(evaluation=inputs, member=member, first=first, final=final),+ start_to_close_timeout=TAKE_SLOT_START_TO_CLOSE,+ schedule_to_close_timeout=TAKE_SLOT_SCHEDULE_TO_CLOSE,+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ except ActivityError:+ # A failed try is a try without a slot. The next one asks again.+ admission = LogsBatchAdmission(due=True)+ if not admission.due:+ return None+ if admission.slot is not None:+ return admission.slot+ if final:+ return None+ first = False+ await workflow.sleep(interval.total_seconds() + workflow.random().uniform(0, SLOT_POLL_JITTER_SECONDS))+ interval = min(interval * 2, SLOT_POLL_MAX_INTERVAL)+SOURCE_EVALUATION_WORKFLOWS = [LogsAlertEvaluateWorkflow]-SOURCE_EVALUATION_ACTIVITIES = [evaluate_logs_alerts_activity]+SOURCE_EVALUATION_ACTIVITIES = [+ evaluate_logs_alerts_activity,+ take_logs_batch_slot_activity,+ evaluate_held_logs_batch_activity,+ release_logs_batch_slot_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/temporal/batch_slot.py b/products/logs/backend/temporal/batch_slot.pynew file mode 100644index 000000000000..016ff64254ca--- /dev/null+++ b/products/logs/backend/temporal/batch_slot.py@@ -0,0 +1,23 @@+"""The pool slot a logs evaluation workflow takes before it evaluates a batch.++Its own module, with no Django import, because the workflow code builds these and Temporal's+workflow sandbox refuses a module that imports a Django model.+"""++from posthog.dataclasses import frozen+++@frozen+class LogsBatchSlot:+ """A slot one workflow took for one batch. The evaluation it hands the slot to releases it."""++ member: str+ held_until: float+++@frozen+class LogsBatchAdmission:+ """The result of one try at a slot. `due` is false when the batch has nothing left to evaluate."""++ due: bool+ slot: LogsBatchSlot | None = Nonediff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.pyindex 9bf71bfdc4fa..15888f2bc005 100644--- a/products/logs/backend/test/test_alert_evaluate.py+++ b/products/logs/backend/test/test_alert_evaluate.py@@ -44,10 +44,13 @@ from products.logs.backend.alert_check_query import (from products.logs.backend.alert_signal_emitter import PlatformAlertSignal, notified_alerts_for_platformfrom products.logs.backend.alert_source_cycle import (BATCH_QUERY_BUDGET_SECONDS,+ BATCH_SLOT_LEASE_SECONDS,INFLIGHT_KEY,MAX_QUERY_SECONDS,+ evaluate_held_logs_batch,evaluate_logs_batch,grouping_key_of,+ take_logs_batch_slot,)from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEventfrom products.logs.backend.platform_alert_backfill import backfill_platform_alert_configurations@@ -55,8 +58,10 @@ from products.logs.backend.temporal.alert_evaluate import (EVALUATE_SCHEDULE_TO_CLOSE,EVALUATE_START_TO_CLOSE,EVALUATION_BUDGET,+ TAKE_SLOT_START_TO_CLOSE,platform_signals,)+from products.logs.backend.temporal.batch_slot import LogsBatchSlot_MODULE = "products.logs.backend.alert_source_cycle"CONDITION = {"threshold_count": 10, "threshold_operator": "above", "window_minutes": 5}@@ -105,6 +110,7 @@ class TestLogsAlertEvaluation(APIBaseTest):query_error: Exception | None = None,now: datetime | None = None,count: int = 500,+ held: LogsBatchSlot | None = None,) -> tuple[SourceBatchEvaluation, MagicMock]:now = now or self.cutoffbreaching = {str(c.id): [BucketedCount(timestamp=now, count=count)] for c in configurations}@@ -119,6 +125,8 @@ class TestLogsAlertEvaluation(APIBaseTest):per_alert=breaching, query_duration_ms=1)slot = slot_of(configurations[0].next_check_at, now)+ if held is not None:+ return evaluate_held_logs_batch(self.team.id, slot, now, held), queryreturn evaluate_logs_batch(self.team.id, slot, now), querydef _add_incident_destination(self, configuration: PlatformConfigurationSnapshot) -> None:@@ -538,6 +546,32 @@ class TestLogsAlertEvaluation(APIBaseTest):assert [len(first.outcomes), len(second.outcomes)] == [1, 1]+ def test_a_slot_taken_ahead_of_the_evaluation_bounds_the_pool_and_is_freed_by_it(self) -> None:+ configuration = self._configuration()+ slot = self._slot()++ with override_settings(ALERTS_PLATFORM_LOGS_MAX_INFLIGHT_BATCHES=1):+ taken = take_logs_batch_slot(self.team.id, slot, self.cutoff, member="first", first=True, final=False)+ turned_away = take_logs_batch_slot(+ self.team.id, slot, self.cutoff, member="second", first=True, final=False+ )+ # A retried try names the same member, so it finds its slot instead of taking another.+ retried = take_logs_batch_slot(self.team.id, slot, self.cutoff, member="first", first=True, final=False)+ assert taken.slot is not None and retried.slot is not None+ assert (turned_away.due, turned_away.slot) == (True, None)++ # The retry rewrote the expiry, so the first take's expiry is stale, as when a timed-out+ # take attempt lands after its retry returned.+ evaluation, _ = self._run(configuration, held=taken.slot)+ after = take_logs_batch_slot(self.team.id, slot, self.cutoff, member="second", first=True, final=False)+ # "first" no longer holds a slot and "second" fills the pool.+ lapsed, lapsed_query = self._run(configuration, held=taken.slot)++ assert len(evaluation.outcomes) == 1+ # The evaluation gave the slot back, or a pool of one would still turn the second batch away.+ assert after.slot is not None+ assert lapsed.outcomes == () and not lapsed_query.called+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=[])@@ -617,6 +651,8 @@ 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+ # See `BATCH_SLOT_LEASE_SECONDS`.+ assert BATCH_SLOT_LEASE_SECONDS > (TAKE_SLOT_START_TO_CLOSE + EVALUATE_SCHEDULE_TO_CLOSE).total_seconds()def _outcome(kind: AlertEventKind, *, notified: bool = True) -> PlatformAlertOutcome:diff --git a/products/logs/backend/test/test_alert_evaluate_workflow.py b/products/logs/backend/test/test_alert_evaluate_workflow.pynew file mode 100644index 000000000000..9546cbbf4eb9--- /dev/null+++ b/products/logs/backend/test/test_alert_evaluate_workflow.py@@ -0,0 +1,108 @@+import uuid+import datetime as dt+from collections.abc import AsyncIterator++import pytest++import pytest_asyncio+from temporalio import activity+from temporalio.client import WorkflowFailureError+from temporalio.exceptions import ApplicationError+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from products.alerts_platform.backend.facade.contracts import (+ AlertBatchKey,+ SourceBatchEvaluation,+ SourceEvaluationInputs,+ SourceKind,+)+from products.logs.backend.temporal.alert_evaluate import (+ HeldLogsBatchInputs,+ LogsAlertEvaluateWorkflow,+ TakeLogsBatchSlotInputs,+)+from products.logs.backend.temporal.batch_slot import LogsBatchAdmission, LogsBatchSlot++QUEUE = "test-logs-platform-evaluation"+++@pytest_asyncio.fixture+async def environment() -> AsyncIterator[WorkflowEnvironment]:+ async with await WorkflowEnvironment.start_time_skipping() as env:+ yield env+++ "full_tries, expected_evaluated, evaluation_fails",+ [+ # The pool frees after two tries, inside the wait budget, so the batch runs in its own tick.+ (2, True, False),+ # The pool never frees, so the batch gives up and its checks stay due for a later tick.+ (1000, False, False),+ # The evaluation fails, for example by timing out in the queue, so the workflow frees the slot.+ (0, True, True),+ ],+)+async def test_a_batch_waits_for_a_pool_slot_on_a_timer_before_it_evaluates(+ environment: WorkflowEnvironment, full_tries: int, expected_evaluated: bool, evaluation_fails: bool+) -> None:+ tries: list[TakeLogsBatchSlotInputs] = []+ evaluated: list[LogsBatchSlot] = []+ released: list[LogsBatchSlot] = []++ @activity.defn(name="take_logs_batch_slot_activity")+ async def take(inputs: TakeLogsBatchSlotInputs) -> LogsBatchAdmission:+ tries.append(inputs)+ if len(tries) <= full_tries:+ return LogsBatchAdmission(due=True)+ return LogsBatchAdmission(due=True, slot=LogsBatchSlot(member=inputs.member, held_until=1.0))++ @activity.defn(name="evaluate_held_logs_batch_activity")+ async def evaluate(inputs: HeldLogsBatchInputs) -> SourceBatchEvaluation:+ evaluated.append(inputs.slot)+ if evaluation_fails:+ raise ApplicationError("evaluation failed", non_retryable=True)+ return SourceBatchEvaluation(outcomes=(), deliveries=())++ @activity.defn(name="release_logs_batch_slot_activity")+ async def release(held: LogsBatchSlot) -> None:+ released.append(held)++ async with Worker(+ environment.client,+ task_queue=QUEUE,+ workflows=[LogsAlertEvaluateWorkflow],+ activities=[take, evaluate, release],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ run = environment.client.execute_workflow(+ LogsAlertEvaluateWorkflow.run,+ SourceEvaluationInputs(+ source=SourceKind.LOGS,+ 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,+ execution_timeout=dt.timedelta(minutes=5),+ )+ if evaluation_fails:+ with pytest.raises(WorkflowFailureError):+ await run+ else:+ await run++ # Every try names one member, so a retried try finds the slot an earlier one took.+ assert len({t.member for t in tries}) == 1+ # Only the first try reads whether the batch is due.+ assert [t.first for t in tries][:2] == [True, False][: len(tries)]+ if expected_evaluated:+ assert [slot.member for slot in evaluated] == [tries[0].member]+ assert len(tries) == full_tries + 1+ assert not any(t.final for t in tries)+ assert released == (evaluated if evaluation_fails else [])+ else:+ assert evaluated == []+ # Only the last try counts the batch as deferred.+ assert [t.final for t in tries].count(True) == 1 and tries[-1].final