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-alerting): implement two-phase fan-out for logs alert checking (#57712)

Jon McCallum72765d118ab7
diff --git a/products/logs/backend/temporal/__init__.py b/products/logs/backend/temporal/__init__.py
index d0227cf69399..d96730d436f6 100644
--- a/products/logs/backend/temporal/__init__.py
+++ b/products/logs/backend/temporal/__init__.py
@@ -1,12 +1,13 @@
-from products.logs.backend.temporal.activities import check_alerts_activity
+from products.logs.backend.temporal.activities import discover_cohorts_activity, evaluate_cohort_batch_activity
from products.logs.backend.temporal.workflow import LogsAlertCheckWorkflow
WORKFLOWS: list = [LogsAlertCheckWorkflow]
-ACTIVITIES: list = [check_alerts_activity]
+ACTIVITIES: list = [discover_cohorts_activity, evaluate_cohort_batch_activity]
__all__ = [
+ "ACTIVITIES",
"LogsAlertCheckWorkflow",
- "check_alerts_activity",
"WORKFLOWS",
- "ACTIVITIES",
+ "discover_cohorts_activity",
+ "evaluate_cohort_batch_activity",
]
diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.py
index 46b9fa3b6d01..891fbc67b48b 100644
--- a/products/logs/backend/temporal/activities.py
+++ b/products/logs/backend/temporal/activities.py
@@ -5,6 +5,7 @@ import time
import asyncio
import contextlib
import dataclasses
+from collections import defaultdict
from collections.abc import Iterator, Sequence
from datetime import UTC, datetime, timedelta
from itertools import batched
@@ -46,7 +47,11 @@ from products.logs.backend.alert_state_machine import (
from products.logs.backend.alert_utils import advance_next_check_at
from products.logs.backend.logs_url_params import build_logs_url_params
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
-from products.logs.backend.temporal.constants import MAX_ALERT_COHORT_SIZE, MAX_CONCURRENT_ALERT_EVALS
+from products.logs.backend.temporal.constants import (
+ MAX_ALERT_COHORT_SIZE,
+ MAX_COHORTS_PER_BATCH,
+ MAX_CONCURRENT_COHORTS_PER_BATCH,
+)
from products.logs.backend.temporal.metrics import (
increment_check_errors,
increment_checkpoint_unavailable,
@@ -63,9 +68,7 @@ from products.logs.backend.temporal.metrics import (
record_cohort_save_duration,
record_cohort_size,
record_cohort_update_duration,
- record_pending_alerts,
record_scheduler_lag,
- record_semaphore_wait,
record_worker_memory_snapshot,
)
@@ -158,7 +161,7 @@ class CheckAlertsInput:
class _AlertCohort:
"""Group of alerts that share team + bucket grid and can be batched into one CH query.
- Cohort key (built in `_build_cohorts`): (team_id, window_minutes,
+ Cohort key matches `_cohort_manifests_from_alerts`: (team_id, window_minutes,
evaluation_periods, check_interval_minutes, projection_eligible, date_to).
"""
@@ -195,6 +198,21 @@ class _AlertCohort:
)
[email protected](frozen=True)
+class CohortManifest:
+ """Lightweight cohort identifier passed between workflow and activities.
+
+ Plain JSON-friendly types only — `datetime` becomes ISO string, UUIDs become
+ str, alert_ids is `list[str]` (NOT tuple — Temporal's default converter
+ deserialises JSON arrays to lists, not tuples).
+ """
+
+ team_id: int
+ projection_eligible: bool
+ date_to_iso: str
+ alert_ids: list[str]
+
+
@dataclasses.dataclass(frozen=True)
class _PrefetchedQuery:
"""CH query result for one alert: either `buckets` or `error` is set."""
@@ -258,45 +276,211 @@ class CheckAlertsOutput:
alerts_errored: int
[email protected](frozen=True)
+class DiscoverCohortsInput:
+ pass
+
+
[email protected](frozen=True)
+class DiscoverCohortsOutput:
+ manifests: list[CohortManifest]
+ # Recorded in workflow history so replays chunk identically even if the env
+ # var changes between runs.
+ batch_size: int
+
+
[email protected](frozen=True)
+class EvaluateCohortBatchInput:
+ manifests: list[CohortManifest]
+
+
[email protected](frozen=True)
+class EvaluateCohortBatchOutput:
+ alerts_checked: int
+ alerts_fired: int
+ alerts_resolved: int
+ alerts_errored: int
+
+
+def _due_alerts_qs(now: datetime):
+ return (
+ LogsAlertConfiguration.objects.filter(
+ Q(enabled=True),
+ Q(next_check_at__lte=now) | Q(next_check_at__isnull=True),
+ )
+ .exclude(state=LogsAlertConfiguration.State.SNOOZED, snooze_until__gt=now)
+ .exclude(state=LogsAlertConfiguration.State.BROKEN)
+ )
+
+
@temporalio.activity.defn
-async def check_alerts_activity(input: CheckAlertsInput) -> CheckAlertsOutput:
- """Find all due alerts and evaluate them with bounded concurrency.
-
- Per-team batching with three phases per cohort:
- 1. Batched ClickHouse `countIf` query (one query, N predicate columns).
- 2. Per-alert in-memory eval (state machine) + per-alert Kafka dispatch.
- 3. Single bulk Postgres save (`bulk_create` events + `bulk_update` configs).
-
- The semaphore bounds concurrent cohorts. Phase 2's per-alert work runs
- in-memory only — no Postgres connections involved — so its concurrency
- is bounded by Python's GIL plus the Kafka producer's queue, not by the
- DB connection pool.
+async def discover_cohorts_activity(input: DiscoverCohortsInput) -> DiscoverCohortsOutput:
+ """Phase 1: lightweight discovery. Returns serialisable manifests; no full ORM hydration.
+
+ Uses `.values()` to pull only the columns needed for grouping — at scale the
+ full `select_related('team')` would OOM. Team objects are loaded later, only
+ inside `evaluate_cohort_batch_activity`, scoped to a small batch.
"""
- now, all_alerts, checkpoint = await database_sync_to_async_pool(_load_alerts_and_checkpoint)()
+ return await database_sync_to_async_pool(_discover_cohorts_sync)()
- cohorts = _build_cohorts(all_alerts, now=now, checkpoint=checkpoint)
- semaphore = asyncio.Semaphore(MAX_CONCURRENT_ALERT_EVALS)
- # Eval is in-memory + GIL-bound — no parallelism benefit from gather, so
- # we run it as a sync list comprehension. Dispatch is Kafka I/O and gets
- # a thread-pool wrap + gather for actual concurrency.
- dispatch_async = database_sync_to_async_pool(_dispatch_for_alert)
+def _discover_cohorts_sync() -> DiscoverCohortsOutput:
+ now = datetime.now(UTC)
+ rows = list(
+ _due_alerts_qs(now).values(
+ "id",
+ "team_id",
+ "window_minutes",
+ "evaluation_periods",
+ "check_interval_minutes",
+ "filters",
+ "next_check_at",
+ )
+ )
+
+ _safe_record("alerts_active gauge", record_alerts_active, len(rows))
+
+ checkpoint: datetime | None = None
+ if rows:
+ try:
+ # Inline import: Django model imports trip Temporal's workflow
+ # sandbox (gettext.GNUTranslations.__mro_entries__). Activities
+ # don't run inside the sandbox, but workflow.py imports this
+ # module to reference the activity callable, which forces
+ # module-level evaluation. Keep this deferred.
+ from posthog.models import Team
+
+ first_team = Team.objects.get(pk=rows[0]["team_id"])
+ checkpoint = fetch_live_logs_checkpoint(first_team)
+ except Exception as e:
+ logger.exception(
+ "Failed to fetch logs ingestion checkpoint; falling back to wall-clock",
+ error=str(e),
+ )
+
+ with _safe_record_block("checkpoint metric"):
+ if checkpoint is None:
+ increment_checkpoint_unavailable()
+ else:
+ record_checkpoint_lag(now, checkpoint)
+
+ manifests = _cohort_manifests_from_alerts(rows, now=now, checkpoint=checkpoint)
+ # Read MAX_COHORTS_PER_BATCH inside the activity, not in workflow code:
+ # module-level env reads are non-deterministic on replay because Temporal's
+ # sandbox re-imports the workflow module each time.
+ return DiscoverCohortsOutput(manifests=manifests, batch_size=MAX_COHORTS_PER_BATCH)
+
+
+def _cohort_manifests_from_alerts(
+ rows: Sequence[dict],
+ *,
+ now: datetime,
+ checkpoint: datetime | None,
+) -> list[CohortManifest]:
+ """Group alert rows (from a `.values()` query) into `CohortManifest` objects.
+
+ Cohort key + size-cap logic on plain dicts (no Django model hydration)
+ so it stays cheap at scale and produces serialisable manifests for the
+ workflow.
+ """
+ grouped: defaultdict[tuple[int, int, int, int, bool, datetime], list[str]] = defaultdict(list)
+ for row in rows:
+ nca = row["next_check_at"] if row["next_check_at"] is not None else now
+ date_to = resolve_alert_date_to(nca, checkpoint)
+ projection_eligible = is_projection_eligible(row["filters"])
+ key = (
+ row["team_id"],
+ row["window_minutes"],
+ row["evaluation_periods"],
+ row["check_interval_minutes"],
+ projection_eligible,
+ date_to,
+ )
+ grouped[key].append(str(row["id"]))
+
+ manifests: list[CohortManifest] = []
+ for (team_id, _wm, _ep, _cim, projection_eligible, date_to), alert_ids in grouped.items():
+ for chunk in batched(alert_ids, MAX_ALERT_COHORT_SIZE):
+ manifests.append(
+ CohortManifest(
+ team_id=team_id,
+ projection_eligible=projection_eligible,
+ date_to_iso=date_to.isoformat(),
+ alert_ids=list(chunk),
+ )
+ )
+ return manifests
+
+
+def _cohort_from_manifest(
+ manifest: CohortManifest,
+ alerts_by_id: dict[str, LogsAlertConfiguration],
+) -> _AlertCohort:
+ """Reconstruct an `_AlertCohort` from a manifest and a pre-loaded alerts dict."""
+ alerts = tuple(alerts_by_id[alert_id] for alert_id in manifest.alert_ids)
+ return _AlertCohort(
+ alerts=alerts,
+ date_to=datetime.fromisoformat(manifest.date_to_iso),
+ projection_eligible=manifest.projection_eligible,
+ )
+
+
+async def evaluate_cohort_batch_activity(input: EvaluateCohortBatchInput) -> EvaluateCohortBatchOutput:
+ """Phase 2: process a batch of cohorts with bounded intra-batch parallelism.
+
+ Loads alerts once per batch (`id__in`), reconstructs `_AlertCohort`s from
+ manifests, then drives the existing per-cohort flow concurrently — bounded by
+ `MAX_CONCURRENT_COHORTS_PER_BATCH` via `asyncio.Semaphore`. Pure asyncio
+ (NOT a thread pool — nested thread pools deadlock under Temporal cancellation).
+
+ Per-cohort failure is contained: a single cohort's exception only counts its
+ alerts as errored. Per-batch failure (uncaught) bubbles up to the workflow,
+ which treats this batch's alerts as errored via `gather(return_exceptions=True)`.
+ """
+ now = datetime.now(UTC)
+
+ all_alert_ids = {aid for manifest in input.manifests for aid in manifest.alert_ids}
+ alerts_by_id = await database_sync_to_async_pool(_load_alerts_for_batch)(all_alert_ids)
+
cohort_query_async = database_sync_to_async_pool(_run_cohort_query)
save_cohort_async = database_sync_to_async_pool(_save_cohort_outcomes)
+ dispatch_async = database_sync_to_async_pool(_dispatch_for_alert)
- async def _bounded_cohort_eval(cohort: _AlertCohort) -> dict[str, int]:
- wait_start = time.perf_counter()
+ semaphore = asyncio.Semaphore(MAX_CONCURRENT_COHORTS_PER_BATCH)
+
+ async def _run_one_cohort(manifest: CohortManifest) -> dict[str, int]:
+ """Process one cohort, returning its stats delta. Always returns —
+ per-cohort failure is captured into local_stats, never raised."""
local_stats = {"checked": 0, "fired": 0, "resolved": 0, "errored": 0}
+
async with semaphore:
- wait_ms = int((time.perf_counter() - wait_start) * 1000)
+ try:
+ cohort = _cohort_from_manifest(manifest, alerts_by_id)
+ except KeyError:
+ logger.warning(
+ "Manifest references missing alert(s); skipping cohort",
+ team_id=manifest.team_id,
+ missing_count=len(manifest.alert_ids),
+ )
+ local_stats["errored"] += len(manifest.alert_ids)
+ return local_stats
+
_safe_record("cohort_size histogram", record_cohort_size, len(cohort.alerts))
- # Phase 1: cohort CH query (batched, with per-alert fallback on failure).
- query_result = await cohort_query_async(cohort)
+ try:
+ query_result = await cohort_query_async(cohort)
+ except Exception:
+ logger.exception(
+ "Cohort CH query failed unrecoverably",
+ team_id=cohort.team_id,
+ cohort_size=len(cohort.alerts),
+ )
+ local_stats["errored"] += len(cohort.alerts)
+ return local_stats
- # Phase 2a: evaluate all alerts (sync, in-memory).
evaluations: list[_AlertEvaluation] = []
- kept_eval_starts: list[float] = []
+ eval_starts: list[float] = []
for alert in cohort.alerts:
eval_start = time.perf_counter()
try:
@@ -304,37 +488,31 @@ async def check_alerts_activity(input: CheckAlertsInput) -> CheckAlertsOutput:
_evaluate_single_alert(
alert,
now,
- checkpoint=checkpoint,
+ checkpoint=None,
prefetched=query_result.for_alert(alert),
)
)
- kept_eval_starts.append(eval_start)
+ eval_starts.append(eval_start)
except Exception:
logger.exception(
"Unexpected error evaluating alert",
alert_id=str(alert.id),
- alert_name=alert.name,
team_id=alert.team_id,
)
local_stats["errored"] += 1
- # Phase 2b: dispatch all alerts in parallel (Kafka concurrency).
dispatched_or_errors = await asyncio.gather(
*(dispatch_async(ev, now) for ev in evaluations),
return_exceptions=True,
)
- # Capture per-alert elapsed_ms here — *before* Phase 3 starts — so the
- # `check_duration` metric measures eval + dispatch only, matching its
- # description. Cohort save time is recorded separately.
phase_2_end = time.perf_counter()
dispatched: list[_DispatchedAlert] = []
elapsed_ms_per_alert: list[int] = []
- for ev, result, eval_start in zip(evaluations, dispatched_or_errors, kept_eval_starts):
+ for ev, result, eval_start in zip(evaluations, dispatched_or_errors, eval_starts):
if isinstance(result, BaseException):
logger.exception(
"Unexpected error dispatching alert",
alert_id=str(ev.alert.id),
- alert_name=ev.alert.name,
team_id=ev.alert.team_id,
exc_info=result,
)
@@ -343,150 +521,59 @@ async def check_alerts_activity(input: CheckAlertsInput) -> CheckAlertsOutput:
dispatched.append(result)
elapsed_ms_per_alert.append(int((phase_2_end - eval_start) * 1000))
- # Phase 3: bulk save — one `bulk_create` + one `bulk_update` per cohort.
- saved: list[_DispatchedAlert] = []
- failed: list[_DispatchedAlert] = []
try:
- if dispatched:
- saved, failed = await save_cohort_async(dispatched, now)
+ saved, failed = (await save_cohort_async(dispatched, now)) if dispatched else ([], [])
except Exception as e:
- logger.exception(
- "Cohort bulk save failed (non-recoverable)",
- team_id=cohort.team_id,
- cohort_size=len(dispatched),
- )
+ logger.exception("Cohort bulk save failed (non-recoverable)", team_id=cohort.team_id)
capture_exception(e, {"team_id": cohort.team_id, "phase": "bulk_save"})
- # Saves failed — count alerts as errored so the cycle stat
- # reflects that this cohort didn't advance state.
local_stats["errored"] += len(dispatched)
local_stats["checked"] += len(dispatched)
- # Off-thread: gc.collect() is CPU-bound and would block the event loop.
- await asyncio.to_thread(_post_cohort_memory_cleanup)
return local_stats
- # Phase 4 (serial): finalize stats + per-alert post-save metrics.
- elapsed_by_alert_id = {str(d.evaluation.alert.id): ms for d, ms in zip(dispatched, elapsed_ms_per_alert)}
+ elapsed_by_id = {str(d.evaluation.alert.id): ms for d, ms in zip(dispatched, elapsed_ms_per_alert)}
for d in saved:
- _finalize_alert(d, elapsed_by_alert_id[str(d.evaluation.alert.id)], local_stats)
+ _finalize_alert(d, elapsed_by_id[str(d.evaluation.alert.id)], local_stats)
for _ in failed:
- # Alert's per-alert fallback save failed — count as errored.
local_stats["checked"] += 1
local_stats["errored"] += 1
- await asyncio.to_thread(_post_cohort_memory_cleanup)
- _safe_record("semaphore_wait histogram", record_semaphore_wait, wait_ms)
- return local_stats
-
- tasks: list[asyncio.Task[dict[str, int]]] = []
- async with asyncio.TaskGroup() as tg:
- for cohort in cohorts:
- tasks.append(tg.create_task(_bounded_cohort_eval(cohort)))
-
- aggregated = {"checked": 0, "fired": 0, "resolved": 0, "errored": 0}
- for task in tasks:
- for k, v in task.result().items():
- aggregated[k] += v
-
- if aggregated["checked"] > 0:
- logger.info("Alert check cycle complete", **aggregated)
-
- # DB failure here is actionable (connection/timeout/query error) so log at
- # error level with full error context — but skip `logger.exception` because
- # retained tracebacks pin cohort state alive across invocations (see
- # `_log_metric_failure` docstring). Metric record stays best-effort.
- try:
- pending = await database_sync_to_async_pool(_count_pending_alerts)()
- except Exception as e:
- # `logger.exception` would retain the traceback (and frame locals like
- # `cohorts`) across activity invocations via buffered LogRecords.
- logger.error( # noqa: TRY400
- "Failed to count pending alerts",
- error=str(e),
- error_type=type(e).__name__,
- )
- else:
- _safe_record("pending_alerts gauge", record_pending_alerts, pending)
-
- return CheckAlertsOutput(
- alerts_checked=aggregated["checked"],
- alerts_fired=aggregated["fired"],
- alerts_resolved=aggregated["resolved"],
- alerts_errored=aggregated["errored"],
- )
+ return local_stats
-def _due_alerts_qs(now: datetime):
- return (
- LogsAlertConfiguration.objects.filter(
- Q(enabled=True),
- Q(next_check_at__lte=now) | Q(next_check_at__isnull=True),
- )
- .exclude(state=LogsAlertConfiguration.State.SNOOZED, snooze_until__gt=now)
- .exclude(state=LogsAlertConfiguration.State.BROKEN)
+ cohort_results = await asyncio.gather(
+ *(_run_one_cohort(m) for m in input.manifests),
+ return_exceptions=False, # _run_one_cohort never raises; it captures failures into local_stats
)
+ # Single GC at batch end rather than per-cohort. With up to 20 cohorts × 50
+ # alerts retained inside the closure during gather, a stop-the-world per
+ # cohort costs more than the once-per-batch reclaim it buys.
+ await asyncio.to_thread(_post_cohort_memory_cleanup)
-def _count_pending_alerts() -> int:
- return _due_alerts_qs(datetime.now(UTC)).count()
-
-
-def _load_alerts_and_checkpoint() -> tuple[datetime, list[LogsAlertConfiguration], datetime | None]:
- """Sync setup: pin `now`, load due alerts, fetch ingestion checkpoint, emit cycle metrics."""
- now = datetime.now(UTC)
-
- all_alerts = list(_due_alerts_qs(now).select_related("team"))
-
- _safe_record("alerts_active gauge", record_alerts_active, len(all_alerts))
-
- checkpoint: datetime | None = None
- if all_alerts:
- try:
- checkpoint = fetch_live_logs_checkpoint(all_alerts[0].team)
- except Exception as e:
- # Real failure (CH unavailable, etc.) — traceback wanted; one record per cycle, not cohort-scoped.
- logger.exception("Failed to fetch logs ingestion checkpoint; falling back to wall-clock", error=str(e))
+ stats = {"checked": 0, "fired": 0, "resolved": 0, "errored": 0}
+ for r in cohort_results:
+ for k, v in r.items():
+ stats[k] += v
- with _safe_record_block("checkpoint metric"):
- if checkpoint is None:
- increment_checkpoint_unavailable()
- else:
- record_checkpoint_lag(now, checkpoint)
+ if stats["checked"] > 0:
+ logger.info("Cohort batch complete", **stats)
- return now, all_alerts, checkpoint
+ return EvaluateCohortBatchOutput(
+ alerts_checked=stats["checked"],
+ alerts_fired=stats["fired"],
+ alerts_resolved=stats["resolved"],
+ alerts_errored=stats["errored"],
+ )
-def _build_cohorts(
- alerts: Sequence[LogsAlertConfiguration],
- *,
- now: datetime,
- checkpoint: datetime | None,
-) -> list[_AlertCohort]:
- """Group alerts into cohorts that can share a batched CH query.
+def _load_alerts_for_batch(alert_ids: set[str]) -> dict[str, LogsAlertConfiguration]:
+ """Single `id__in` query for all alerts referenced by the batch.
- Each cohort holds at most `MAX_ALERT_COHORT_SIZE` alerts. Larger groups (same
- team / window / cadence / projection / date_to) split into multiple cohorts
- so each individual batched query stays bounded — and the existing outer
- semaphore (`MAX_CONCURRENT_ALERT_EVALS`) is the only concurrency control.
+ Alert IDs are UUID PKs (unique, indexed) so cross-team `id__in` is no
+ slower than per-team scoping — and saves one round-trip per team.
"""
- grouped: dict[tuple, tuple[list[LogsAlertConfiguration], datetime, bool]] = {}
- for alert in alerts:
- nca = alert.next_check_at if alert.next_check_at is not None else now
- date_to = resolve_alert_date_to(nca, checkpoint)
- projection_eligible = is_projection_eligible(alert.filters)
- key = (
- alert.team_id,
- alert.window_minutes,
- alert.evaluation_periods,
- alert.check_interval_minutes,
- projection_eligible,
- date_to,
- )
- grouped.setdefault(key, ([], date_to, projection_eligible))[0].append(alert)
-
- cohorts: list[_AlertCohort] = []
- for members, date_to, projection_eligible in grouped.values():
- for chunk in batched(members, MAX_ALERT_COHORT_SIZE):
- cohorts.append(_AlertCohort(alerts=chunk, date_to=date_to, projection_eligible=projection_eligible))
- return cohorts
+ return {
+ str(alert.id): alert for alert in LogsAlertConfiguration.objects.filter(id__in=alert_ids).select_related("team")
+ }
def _run_batched_query(cohort: _AlertCohort) -> BatchedBucketedResult:
@@ -531,10 +618,10 @@ def _run_per_alert_queries(cohort: _AlertCohort) -> _CohortQueryResult:
def _run_cohort_query(cohort: _AlertCohort) -> _CohortQueryResult:
"""Batched CH query for a cohort; per-alert fallback on non-transient failure.
- Cohorts are pre-sized at `_build_cohorts` time so this function operates on a
- single bounded group. Skip fallback for single-alert cohorts (would hit the
- same error) and transient cluster errors (would hammer a struggling cluster
- with N more failing queries).
+ Cohorts are pre-sized at `_cohort_manifests_from_alerts` time so this function
+ operates on a single bounded group. Skip fallback for single-alert cohorts
+ (would hit the same error) and transient cluster errors (would hammer a
+ struggling cluster with N more failing queries).
"""
try:
batched_result = _run_batched_query(cohort)
@@ -579,106 +666,6 @@ def _run_cohort_query(cohort: _AlertCohort) -> _CohortQueryResult:
)
-def _check_alerts_sync() -> CheckAlertsOutput:
- """Synchronous variant kept for unit tests. Production runs through `check_alerts_activity`.
-
- Mirrors the async cohort dispatch shape (CH batched query → per-alert eval +
- Kafka dispatch → bulk save) so tests cover the production code path.
- """
- now, all_alerts, checkpoint = _load_alerts_and_checkpoint()
- cohorts = _build_cohorts(all_alerts, now=now, checkpoint=checkpoint)
-
- stats = {"checked": 0, "fired": 0, "resolved": 0, "errored": 0}
- for cohort in cohorts:
- _safe_record("cohort_size histogram", record_cohort_size, len(cohort.alerts))
-
- # Phase 1: cohort CH query (batched, with per-alert fallback on failure).
- query_result = _run_cohort_query(cohort)
-
- # Phase 2a: evaluate all alerts.
- evaluations: list[_AlertEvaluation] = []
- eval_starts: list[float] = []
- for alert in cohort.alerts:
- eval_start = time.perf_counter()
- try:
- evaluation = _evaluate_single_alert(
- alert,
- now,
- checkpoint=checkpoint,
- prefetched=query_result.for_alert(alert),
- )
- except Exception:
- logger.exception(
- "Unexpected error evaluating alert",
- alert_id=str(alert.id),
- alert_name=alert.name,
- team_id=alert.team_id,
- )
- stats["errored"] += 1
- continue
- evaluations.append(evaluation)
- eval_starts.append(eval_start)
-
- # Phase 2b: dispatch all alerts.
- dispatched: list[_DispatchedAlert] = []
- kept_eval_starts_for_dispatch: list[float] = []
- for ev, eval_start in zip(evaluations, eval_starts):
- try:
- d = _dispatch_for_alert(ev, now)
- except Exception:
- logger.exception(
- "Unexpected error dispatching alert",
- alert_id=str(ev.alert.id),
- alert_name=ev.alert.name,
- team_id=ev.alert.team_id,
- )
- stats["errored"] += 1
- continue
- dispatched.append(d)
- kept_eval_starts_for_dispatch.append(eval_start)
-
- # Snapshot per-alert elapsed_ms here so it doesn't include Phase 3.
- phase_2_end = time.perf_counter()
- elapsed_ms_per_alert = [int((phase_2_end - es) * 1000) for es in kept_eval_starts_for_dispatch]
-
- # Phase 3: bulk save.
- saved: list[_DispatchedAlert] = []
- failed: list[_DispatchedAlert] = []
- try:
- if dispatched:
- saved, failed = _save_cohort_outcomes(dispatched, now)
- except Exception as e:
- logger.exception(
- "Cohort bulk save failed (non-recoverable)",
- team_id=cohort.team_id,
- cohort_size=len(dispatched),
- )
- capture_exception(e, {"team_id": cohort.team_id, "phase": "bulk_save"})
- stats["errored"] += len(dispatched)
- stats["checked"] += len(dispatched)
- _post_cohort_memory_cleanup()
- continue
-
- # Phase 4: finalize stats + per-alert post-save metrics.
- elapsed_by_alert_id = {str(d.evaluation.alert.id): ms for d, ms in zip(dispatched, elapsed_ms_per_alert)}
- for d in saved:
- _finalize_alert(d, elapsed_by_alert_id[str(d.evaluation.alert.id)], stats)
- for _ in failed:
- stats["checked"] += 1
- stats["errored"] += 1
- _post_cohort_memory_cleanup()
-
- if stats["checked"] > 0:
- logger.info("Alert check cycle complete", **stats)
-
- return CheckAlertsOutput(
- alerts_checked=stats["checked"],
- alerts_fired=stats["fired"],
- alerts_resolved=stats["resolved"],
- alerts_errored=stats["errored"],
- )
-
-
def _dispatch_notification(
outcome: AlertCheckOutcome,
alert: LogsAlertConfiguration,
diff --git a/products/logs/backend/temporal/constants.py b/products/logs/backend/temporal/constants.py
index 71dd2c92b219..1f080ddf2ab5 100644
--- a/products/logs/backend/temporal/constants.py
+++ b/products/logs/backend/temporal/constants.py
@@ -19,16 +19,23 @@ ACTIVITY_RETRY_POLICY = RetryPolicy(
backoff_coefficient=2.0,
)
-# Bounded concurrency for the per-alert evaluation loop. Each eval blocks on a
-# ~1.3-3.7s ClickHouse query post-stateless-eval; sequential execution overruns
-# the 60s cron interval past ~40 alerts at canonical-grid-aligned cadence.
-# Override via env when scaling the alert population without redeploying.
-MAX_CONCURRENT_ALERT_EVALS = int(os.environ.get("LOGS_ALERTING_MAX_CONCURRENT_EVALS", "5"))
-
# Cap on alerts in a single cohort. Larger groups (same team / window / cadence /
-# projection / date_to) split at cohort-build time into multiple cohorts of this
-# size, each of which becomes its own task in the outer evaluation loop and
-# competes for a `MAX_CONCURRENT_ALERT_EVALS` slot. Bounds per-query CH read
-# bytes and worker-side result materialization. The production per-team cap (20)
-# already keeps cohorts under this; the limit only matters for bypass-list teams.
+# projection / date_to) split at manifest-build time into multiple cohorts of
+# this size, each of which becomes its own activity-level unit. Bounds per-query
+# CH read bytes and worker-side result materialization. The production per-team
+# cap (20) already keeps cohorts under this; the limit only matters for
+# bypass-list teams.
MAX_ALERT_COHORT_SIZE = int(os.environ.get("LOGS_ALERTING_MAX_ALERT_COHORT_SIZE", "50"))
+
+# Number of cohorts assigned to one `evaluate_cohort_batch_activity` invocation.
+# Larger batches → fewer activities per cycle (lower Temporal cost), bigger blast
+# radius on failure (more cohorts re-run on retry), longer per-activity wall time.
+# At ~4s per cohort with intra-batch concurrency 5, batch=20 ≈ 16s wall time
+# (well under the 5-min activity timeout). Tune the cost/latency dial here.
+MAX_COHORTS_PER_BATCH = int(os.environ.get("LOGS_ALERTING_MAX_COHORTS_PER_BATCH", "20"))
+
+# How many cohorts within one batch activity run in parallel via asyncio.Semaphore +
+# asyncio.gather. Pure asyncio (NOT a thread pool — the previous nested
+# ThreadPoolExecutor inside asgiref's pool deadlocked under Temporal cancellation).
+# 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"))
diff --git a/products/logs/backend/temporal/metrics.py b/products/logs/backend/temporal/metrics.py
index b2ecafe4fd22..7a32d3b7dcb2 100644
--- a/products/logs/backend/temporal/metrics.py
+++ b/products/logs/backend/temporal/metrics.py
@@ -26,22 +26,24 @@ _NOTIFICATION_FAILURE_LABELS: dict[NotificationAction, str] = {
ALERTING_ACTIVITY_TYPES = frozenset(
{
- "check_alerts_activity",
+ "discover_cohorts_activity",
+ "evaluate_cohort_batch_activity",
}
)
Attributes = dict[str, str | int | float | bool]
+# Consumed by `posthog/temporal/common/worker.py` to override Prometheus default
+# buckets per-metric. Keep in sync with the latency histograms emitted below.
LOGS_ALERTING_LATENCY_HISTOGRAM_METRICS = (
"logs_alerting_check_duration_ms",
"logs_alerting_cycle_duration_ms",
"logs_alerting_scheduler_lag_ms",
"logs_alerting_schedule_to_start_ms",
"logs_alerting_clickhouse_duration_ms",
- "logs_alerting_semaphore_wait_ms",
- "logs_alerting_alert_save_ms",
- "logs_alerting_alert_event_create_ms",
- "logs_alerting_alert_update_ms",
+ "logs_alerting_cohort_save_ms",
+ "logs_alerting_cohort_event_insert_ms",
+ "logs_alerting_cohort_update_ms",
)
LOGS_ALERTING_LATENCY_HISTOGRAM_BUCKETS = [
@@ -127,15 +129,6 @@ def record_alerts_active(count: int) -> None:
gauge.set(count)
-def record_pending_alerts(count: int) -> None:
- meter = get_metric_meter()
- gauge = meter.create_gauge(
- "logs_alerting_pending_alerts",
- "Number of due alerts still waiting to be evaluated at end of cycle (backlog)",
- )
- gauge.set(count)
-
-
def record_checkpoint_lag(now: dt.datetime, checkpoint: dt.datetime) -> None:
meter = get_metric_meter()
gauge = meter.create_gauge(
@@ -171,14 +164,6 @@ def record_clickhouse_duration(duration_ms: int) -> None:
)
-def record_semaphore_wait(wait_ms: int) -> None:
- _record_histogram(
- "logs_alerting_semaphore_wait_ms",
- "Time an alert spent waiting on the per-cycle concurrency semaphore",
- wait_ms,
- )
-
-
def record_cohort_save_duration(duration_ms: int) -> None:
_record_histogram(
"logs_alerting_cohort_save_ms",
diff --git a/products/logs/backend/temporal/workflow.py b/products/logs/backend/temporal/workflow.py
index 2c44fdbf37e7..f4ec2588aef5 100644
--- a/products/logs/backend/temporal/workflow.py
+++ b/products/logs/backend/temporal/workflow.py
@@ -1,25 +1,107 @@
-"""Temporal workflow for logs alert checking."""
+"""Temporal workflow for logs alert checking — two-phase fan-out."""
+
+import asyncio
+from itertools import batched
import temporalio
from temporalio import workflow
+from temporalio.exceptions import ActivityError
from posthog.temporal.common.base import PostHogWorkflow
-from products.logs.backend.temporal.activities import CheckAlertsInput, CheckAlertsOutput, check_alerts_activity
+# Activities (and their dataclass payloads) live behind Django imports — gettext
+# in particular is blocked by Temporal's workflow sandbox. Mark these as
+# pass-through; we never call the activity functions from workflow code, only
+# pass them as references to `execute_activity`.
+with workflow.unsafe.imports_passed_through():
+ from products.logs.backend.temporal.activities import (
+ CheckAlertsInput,
+ CheckAlertsOutput,
+ DiscoverCohortsInput,
+ DiscoverCohortsOutput,
+ EvaluateCohortBatchInput,
+ EvaluateCohortBatchOutput,
+ discover_cohorts_activity,
+ evaluate_cohort_batch_activity,
+ )
+
from products.logs.backend.temporal.constants import ACTIVITY_RETRY_POLICY, ACTIVITY_TIMEOUT, WORKFLOW_NAME
@temporalio.workflow.defn(name=WORKFLOW_NAME)
class LogsAlertCheckWorkflow(PostHogWorkflow):
+ """Two-phase fan-out: discover cohort manifests, then evaluate batches in parallel.
+
+ Workflows can't do I/O; the discovery activity owns the Postgres query and
+ returns serialisable manifests recorded in workflow history. The workflow
+ then deterministically chunks the manifests into batches and dispatches one
+ activity per batch via `asyncio.gather` — Temporal spreads them across
+ available worker pods.
+ """
+
@staticmethod
def parse_inputs(inputs: list[str]) -> CheckAlertsInput:
return CheckAlertsInput()
@temporalio.workflow.run
async def run(self, input: CheckAlertsInput) -> CheckAlertsOutput:
- return await workflow.execute_activity(
- check_alerts_activity,
- input,
+ discovery: DiscoverCohortsOutput = await workflow.execute_activity(
+ discover_cohorts_activity,
+ DiscoverCohortsInput(),
start_to_close_timeout=ACTIVITY_TIMEOUT,
retry_policy=ACTIVITY_RETRY_POLICY,
)
+
+ if not discovery.manifests:
+ return CheckAlertsOutput(alerts_checked=0, alerts_fired=0, alerts_resolved=0, alerts_errored=0)
+
+ # Use the batch size recorded by discovery rather than reading env here —
+ # module-level env reads are non-deterministic across workflow replay.
+ batches = [
+ EvaluateCohortBatchInput(manifests=list(chunk))
+ for chunk in batched(discovery.manifests, discovery.batch_size)
+ ]
+
+ # `return_exceptions=True` isolates per-batch retry-exhaustion: one
+ # batch's `ActivityError` doesn't abort the cycle.
+ results: list[EvaluateCohortBatchOutput | BaseException] = await asyncio.gather(
+ *(
+ workflow.execute_activity(
+ evaluate_cohort_batch_activity,
+ batch,
+ start_to_close_timeout=ACTIVITY_TIMEOUT,
+ retry_policy=ACTIVITY_RETRY_POLICY,
+ )
+ for batch in batches
+ ),
+ return_exceptions=True,
+ )
+
+ alerts_checked = 0
+ alerts_fired = 0
+ alerts_resolved = 0
+ alerts_errored = 0
+ for batch, result in zip(batches, results):
+ if isinstance(result, ActivityError):
+ # Batch's retries exhausted — count its alerts as errored, keep going.
+ workflow.logger.warning(
+ "Cohort batch activity failed; counting batch alerts as errored",
+ cohort_count=len(batch.manifests),
+ )
+ alerts_errored += sum(len(m.alert_ids) for m in batch.manifests)
+ elif isinstance(result, BaseException):
+ # Unexpected exception type — re-raise so the workflow fails loudly
+ # rather than silently masking a bug.
+ raise result
+ else:
+ alerts_checked += result.alerts_checked
+ alerts_fired += result.alerts_fired
+ alerts_resolved += result.alerts_resolved
+ alerts_errored += result.alerts_errored
+
+ return CheckAlertsOutput(
+ alerts_checked=alerts_checked,
+ alerts_fired=alerts_fired,
+ alerts_resolved=alerts_resolved,
+ alerts_errored=alerts_errored,
+ )
diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.py
index 3348f2243a15..c7fc3c1ecff5 100644
--- a/products/logs/backend/test/test_alerts_api.py
+++ b/products/logs/backend/test/test_alerts_api.py
@@ -1700,15 +1700,46 @@ class TestSimulateEvaluatorLifecycleParity(ClickhouseTestMixin, APIBaseTest):
start_nca: datetime,
end_nca: datetime,
) -> list[tuple[datetime, str]]:
- from products.logs.backend.temporal.activities import _check_alerts_sync
+ # Run the sync helpers directly rather than the async activities. The
+ # async path uses `database_sync_to_async_pool`, whose thread-pool
+ # dispatch loses freezegun's clock-patching for this lifecycle test.
+ # The async orchestration is covered by `test_logs_alerting_workflow.py`.
+ from products.logs.backend.temporal.activities import (
+ _cohort_from_manifest,
+ _discover_cohorts_sync,
+ _dispatch_for_alert,
+ _evaluate_single_alert,
+ _finalize_alert,
+ _load_alerts_for_batch,
+ _run_cohort_query,
+ _save_cohort_outcomes,
+ )
alert.next_check_at = start_nca
alert.save(update_fields=["next_check_at"])
+ def _one_cycle() -> None:
+ discovery = _discover_cohorts_sync()
+ if not discovery.manifests:
+ return
+ all_ids = {aid for m in discovery.manifests for aid in m.alert_ids}
+ alerts_by_id = _load_alerts_for_batch(all_ids)
+ now = datetime.now(UTC)
+ stats = {"checked": 0, "fired": 0, "resolved": 0, "errored": 0}
+ for manifest in discovery.manifests:
+ cohort = _cohort_from_manifest(manifest, alerts_by_id)
+ query_result = _run_cohort_query(cohort)
+ for a in cohort.alerts:
+ evaluation = _evaluate_single_alert(a, now, prefetched=query_result.for_alert(a))
+ dispatched = _dispatch_for_alert(evaluation, now)
+ saved, _failed = _save_cohort_outcomes([dispatched], now)
+ for d in saved:
+ _finalize_alert(d, 0, stats)
+
nca = start_nca
while nca <= end_nca:
with freeze_time(nca):
- _check_alerts_sync()
+ _one_cycle()
nca += timedelta(minutes=alert.check_interval_minutes)
events: list[tuple[datetime, str]] = []
diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.py
index 60ca0093129a..0c57fc0f695f 100644
--- a/products/logs/backend/test/test_logs_alerting_activities.py
+++ b/products/logs/backend/test/test_logs_alerting_activities.py
@@ -2,13 +2,13 @@ import json
import time
import asyncio
import datetime as dt
-import threading
+import dataclasses
from datetime import UTC, datetime, timedelta
+from typing import Any, cast
-import pytest
import unittest
from freezegun import freeze_time
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, NonAtomicBaseTest
from unittest.mock import MagicMock, patch
from hypothesis import (
@@ -25,16 +25,12 @@ from products.logs.backend.alert_check_query import AlertCheckQuery, BatchedBuck
from products.logs.backend.alert_state_machine import AlertState, NotificationAction
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
from products.logs.backend.temporal.activities import (
- CheckAlertsInput,
- CheckAlertsOutput,
_AlertCohort,
- _check_alerts_sync,
_derive_breaches,
_dispatch_for_alert,
_evaluate_single_alert,
_finalize_alert,
_save_cohort_outcomes,
- check_alerts_activity,
)
@@ -91,386 +87,6 @@ def _mock_batched_buckets(mock_run_batched: MagicMock, counts: list[int]) -> Non
mock_run_batched.side_effect = fake
-class TestCheckAlertsSync(APIBaseTest):
- def setUp(self):
- super().setUp()
- # Stub the cycle-level CH queries and metric emitters so tests that aren't
- # asserting on them don't hit a real ClickHouse or raise outside Temporal.
- # fetch_live_logs_checkpoint must return None (not MagicMock) so the real
- # date-resolution path can run with a well-typed sentinel.
- checkpoint_patch = patch(
- "products.logs.backend.temporal.activities.fetch_live_logs_checkpoint", return_value=None
- )
- checkpoint_patch.start()
- self.addCleanup(checkpoint_patch.stop)
- for target in (
- "products.logs.backend.temporal.activities.record_checkpoint_lag",
- "products.logs.backend.temporal.activities.increment_checkpoint_unavailable",
- "products.logs.backend.temporal.activities.record_alerts_active",
- ):
- p = patch(target)
- p.start()
- self.addCleanup(p.stop)
-
- def _make_alert(self, **kwargs) -> LogsAlertConfiguration:
- defaults = {
- "team": self.team,
- "name": "Test Alert",
- "threshold_count": 10,
- "threshold_operator": "above",
- "window_minutes": 5,
- "filters": {"serviceNames": ["test-service"]},
- "next_check_at": datetime(2025, 1, 1, 0, 0, 0, tzinfo=UTC),
- }
- defaults.update(kwargs)
- return LogsAlertConfiguration.objects.create(**defaults)
-
- @freeze_time("2025-01-01T00:01:00Z")
- @patch("products.logs.backend.temporal.activities._run_batched_query")
- def test_no_alerts_returns_zero_stats(self, mock_run_batched):
- result = _check_alerts_sync()
- assert result == CheckAlertsOutput(alerts_checked=0, alerts_fired=0, alerts_resolved=0, alerts_errored=0)
- mock_run_batched.assert_not_called()
-
- @freeze_time("2025-01-01T00:01:00Z")
- @patch("products.logs.backend.temporal.activities._run_batched_query")
- def test_skips_disabled_alerts(self, mock_run_batched):
- self._make_alert(enabled=False)
- result = _check_alerts_sync()
- assert result.alerts_checked == 0
- mock_run_batched.assert_not_called()
-
- @freeze_time("2025-01-01T00:01:00Z")
- @patch("products.logs.backend.temporal.activities._run_batched_query")
- def test_skips_snoozed_alerts(self, mock_run_batched):
- self._make_alert(
- state=LogsAlertConfiguration.State.SNOOZED,
- snooze_until=datetime(2025, 1, 2, 0, 0, 0, tzinfo=UTC),
- )
- result = _check_alerts_sync()
- assert result.alerts_checked == 0
-
- @freeze_time("2025-01-01T00:01:00Z")
- @patch("products.logs.backend.temporal.activities._run_batched_query")
- def test_skips_broken_alerts(self, mock_run_batched):
- self._make_alert(state=LogsAlertConfiguration.State.BROKEN)
- result = _check_alerts_sync()
- assert result.alerts_checked == 0
- mock_run_batched.assert_not_called()
-
- @freeze_time("2025-01-01T00:01:00Z")
- @patch("products.logs.backend.temporal.activities._run_batched_query")
- def test_picks_up_due_alert(self, mock_run_batched):
- _mock_batched_buckets(mock_run_batched, [5])
- self._make_alert()
- result = _check_alerts_sync()
- assert result.alerts_checked == 1
-
- @freeze_time("2025-01-01T00:01:00Z")
- @patch("products.logs.backend.temporal.activities._run_batched_query")
- def test_picks_up_null_next_check_at(self, mock_run_batched):
- _mock_batched_buckets(mock_run_batched, [5])
- self._make_alert(next_check_at=None)
- result = _check_alerts_sync()
- assert result.alerts_checked == 1
-
- @freeze_time("2025-01-01T00:01:00Z")
- @patch("products.logs.backend.temporal.activities._run_batched_query")
- def test_skips_future_next_check_at(self, mock_run_batched):
- self._make_alert(next_check_at=datetime(2025, 1, 1, 1, 0, 0, tzinfo=UTC))
- result = _check_alerts_sync()
- assert result.alerts_checked == 0
-
- @freeze_time("2025-01-01T00:01:00Z")
- @patch("products.logs.backend.temporal.activities._run_batched_query")
- def test_clickhouse_error_records_errored_check(self, mock_run_batched):
- mock_run_batched.side_effect = RuntimeError("boom")
- self._make_alert()
- result = _check_alerts_sync()
- # ClickHouse error is caught inside _evaluate_single_alert, alert is still "checked"
- assert result.alerts_checked == 1
- assert result.alerts_errored == 1
-
- @freeze_time("2025-01-01T00:01:00Z")
- @patch("products.logs.backend.temporal.activities._evaluate_single_alert", side_effect=RuntimeError("unexpected"))
- def test_unexpected_error_increments_errored(self, _mock_evaluate):
- self._make_alert()
- result = _check_alerts_sync()
- # Truly unexpected error caught by outer except — not "checked"
- assert result.alerts_errored == 1
- assert result.alerts_checked == 0
-
- @parameterized.expand(
- [
- ("with_due_alerts", True, 2),
- ("none_due", False, 0),
- ]
- )
- @freeze_time("2025-01-01T00:01:00Z")
- @patch("products.logs.backend.temporal.activities.record_alerts_active")
- @patch("products.logs.backend.temporal.activities._run_batched_query")
- def test_records_alerts_active_gauge(self, _name, seed_alerts, expected_count, mock_run_batched, mock_record_gauge):
- if seed_alerts:
- _mock_batched_buckets(mock_run_batched, [5])
- self._make_alert()
- self._make_alert(name="Second")
- # Disabled and snoozed alerts should not count toward the gauge.
- self._make_alert(name="Disabled", enabled=False)
- self._make_alert(
- name="Snoozed",
- state=LogsAlertConfiguration.State.SNOOZED,
- snooze_until=datetime(2025, 1, 2, 0, 0, 0, tzinfo=UTC),
- )
-
- _check_alerts_sync()
-
- mock_record_gauge.assert_called_once_with(expected_count)
-
- @freeze_time("2025-01-01T00:01:00Z")
- @patch("products.logs.backend.temporal.activities.record_checkpoint_lag")
- @patch("products.logs.backend.temporal.activities.fetch_live_logs_checkpoint")
- @patch("products.logs.backend.temporal.activities._run_batched_query")
- def test_fetches_checkpoint_once_and_passes_to_evaluator(
- self, mock_run_batched, mock_fetch_checkpoint, mock_record_lag
- ):
- checkpoint = datetime(2025, 1, 1, 0, 0, 30, tzinfo=UTC)
- mock_fetch_checkpoint.return_value = checkpoint
- _mock_batched_buckets(mock_run_batched, [5])
- self._make_alert()
- self._make_alert(name="Second")
-
- _check_alerts_sync()
-
- # One checkpoint fetch per cycle, regardless of alert count.
- mock_fetch_checkpoint.assert_called_once()
- mock_record_lag.assert_called_once()
- (now_arg, checkpoint_arg), _ = mock_record_lag.call_args
- assert checkpoint_arg == checkpoint
-
- @freeze_time("2025-01-01T00:01:00Z")
- @patch("products.logs.backend.temporal.activities.increment_checkpoint_unavailable")
- @patch("products.logs.backend.temporal.activities.record_checkpoint_lag")
- @patch("products.logs.backend.temporal.activities.fetch_live_logs_checkpoint")
- @patch("products.logs.backend.temporal.activities._run_batched_query")
- def test_skips_checkpoint_fetch_when_no_due_alerts(
- self, _mock_run_batched, mock_fetch_checkpoint, mock_record_lag, mock_unavailable
- ):
- _check_alerts_sync()
-
- mock_fetch_checkpoint.assert_not_called()
- mock_record_lag.assert_not_called()
- mock_unavailable.assert_called_once()
-
- @freeze_time("2025-01-01T00:01:00Z")
- @patch("products.logs.backend.temporal.activities.increment_checkpoint_unavailable")
- @patch("products.logs.backend.temporal.activities.record_checkpoint_lag")
- @patch("products.logs.backend.temporal.activities.fetch_live_logs_checkpoint", side_effect=RuntimeError("CH down"))
- @patch("products.logs.backend.temporal.activities._run_batched_query")
- def test_checkpoint_fetch_failure_falls_back_to_wall_clock(
- self, mock_run_batched, _mock_fetch, mock_record_lag, mock_unavailable
- ):
- _mock_batched_buckets(mock_run_batched, [5])
- self._make_alert()
-
- result = _check_alerts_sync()
-
- # Alert still evaluated — failed checkpoint fetch must not block alerting.
- assert result.alerts_checked == 1
- mock_record_lag.assert_not_called()
- mock_unavailable.assert_called_once()
-
-
-def _stub_one_cohort_per_alert(alerts, *, now, checkpoint):
- """Wrap each MagicMock alert into its own single-alert cohort.
-
- Used by concurrency tests so the cohort dispatch loop fires one cohort per
- MagicMock alert — preserving the per-alert peak-concurrency assertions.
- """
- for a in alerts:
- a.window_minutes = 5
- a.evaluation_periods = 1
- return [_AlertCohort(alerts=(a,), date_to=now, projection_eligible=True) for a in alerts]
-
-
-def _stub_run_batched_query_empty(cohort: _AlertCohort) -> BatchedBucketedResult:
- """Return an empty BatchedBucketedResult — concurrency tests don't care about buckets, only call counts."""
- return BatchedBucketedResult(per_alert={}, query_duration_ms=0)
-
-
-def _stub_save_cohort_outcomes_passthrough(dispatched, now):
- """Return `(dispatched, [])` — concurrency tests bypass real PG access.
-
- `_save_cohort_outcomes` returns `(saved, failed)`; orchestrator finalizes the
- saved list. Pass-through treats every dispatched alert as saved.
- """
- return list(dispatched), []
-
-
-class TestCheckAlertsActivityConcurrency(unittest.TestCase):
- """Async path: bounded concurrency via asyncio.TaskGroup + Semaphore.
-
- The orchestrator runs three phases per cohort (CH batched query → per-alert
- eval (sequential) + Kafka dispatch (gathered) → bulk save → finalize). These
- tests stub every phase except the one under test and assert on the final
- aggregated `CheckAlertsOutput`. The single-alert eval logic is covered by
- `TestEvaluateSingleAlert` and `TestEvaluateSingleAlertEndToEnd`; the
- per-cycle DB read by `TestCheckAlertsSync`.
-
- Marked `django_db` because `database_sync_to_async_pool` calls
- `close_old_connections` even when the wrapped function is fully mocked.
- """
-
- @staticmethod
- def _mock_alerts(n: int) -> list[MagicMock]:
- return [MagicMock(id=f"alert-{i}", name=f"alert-{i}", team_id=1) for i in range(n)]
-
- @parameterized.expand([("fired",), ("resolved",), ("errored",)])
- def test_evaluates_all_alerts_and_aggregates_stats(self, outcome):
- """The activity finalizes each alert exactly once and aggregates stats correctly."""
- now = datetime(2025, 1, 1, 0, 1, 0, tzinfo=UTC)
- alerts = self._mock_alerts(4)
-
- def fake_finalize(dispatched, elapsed_ms, stats):
- stats["checked"] += 1
- stats[outcome] += 1
-
- with (
- patch(
- "products.logs.backend.temporal.activities._load_alerts_and_checkpoint",
- return_value=(now, alerts, None),
- ),
- patch(
- "products.logs.backend.temporal.activities._build_cohorts",
- side_effect=_stub_one_cohort_per_alert,
- ),
- patch(
- "products.logs.backend.temporal.activities._run_batched_query",
- side_effect=_stub_run_batched_query_empty,
- ),
- patch("products.logs.backend.temporal.activities._evaluate_single_alert", return_value=MagicMock()),
- patch("products.logs.backend.temporal.activities._dispatch_for_alert", return_value=MagicMock()),
- patch(
- "products.logs.backend.temporal.activities._save_cohort_outcomes",
- side_effect=_stub_save_cohort_outcomes_passthrough,
- ),
- patch(
- "products.logs.backend.temporal.activities._finalize_alert", side_effect=fake_finalize
- ) as mock_finalize,
- ):
- result = asyncio.run(check_alerts_activity(CheckAlertsInput()))
-
- assert mock_finalize.call_count == 4
- assert result.alerts_checked == 4
- assert getattr(result, f"alerts_{outcome}") == 4
- for other in ("fired", "resolved", "errored"):
- if other != outcome:
- assert getattr(result, f"alerts_{other}") == 0
-
- def test_bounded_concurrency_does_not_exceed_semaphore_limit(self):
- """Force overlap; peak concurrent in-flight cohorts must equal the semaphore limit.
-
- Concurrency is measured in `_dispatch_for_alert` because that's the phase
- wrapped in `database_sync_to_async_pool` — its calls run on a thread pool
- and thus overlap when multiple cohort tasks hold their semaphore slot.
- Eval runs sequentially inside the event loop, so it can't be used to
- observe cohort-level concurrency.
- """
- now = datetime(2025, 1, 1, 0, 1, 0, tzinfo=UTC)
- alerts = self._mock_alerts(10)
-
- peak = 0
- active = 0
- lock = threading.Lock()
-
- def fake_dispatch(evaluation, now, **_kwargs):
- nonlocal peak, active
- with lock:
- active += 1
- peak = max(peak, active)
- time.sleep(0.05)
- with lock:
- active -= 1
- return MagicMock()
-
- def fake_finalize(dispatched, elapsed_ms, stats):
- stats["checked"] += 1
-
- with (
- patch(
- "products.logs.backend.temporal.activities._load_alerts_and_checkpoint",
- return_value=(now, alerts, None),
- ),
- patch(
- "products.logs.backend.temporal.activities._build_cohorts",
- side_effect=_stub_one_cohort_per_alert,
- ),
- patch(
- "products.logs.backend.temporal.activities._run_batched_query",
- side_effect=_stub_run_batched_query_empty,
- ),
- patch("products.logs.backend.temporal.activities.MAX_CONCURRENT_ALERT_EVALS", 3),
- patch("products.logs.backend.temporal.activities._evaluate_single_alert", return_value=MagicMock()),
- patch("products.logs.backend.temporal.activities._dispatch_for_alert", side_effect=fake_dispatch),
- patch(
- "products.logs.backend.temporal.activities._save_cohort_outcomes",
- side_effect=_stub_save_cohort_outcomes_passthrough,
- ),
- patch("products.logs.backend.temporal.activities._finalize_alert", side_effect=fake_finalize),
- ):
- result = asyncio.run(check_alerts_activity(CheckAlertsInput()))
-
- assert peak <= 3, f"expected peak concurrency ≤ 3 (semaphore limit), got {peak}"
- assert peak > 1, f"expected concurrency to be utilised (peak={peak}), check thread pool availability"
- assert result.alerts_checked == 10
-
- def test_unexpected_error_isolates_to_single_alert(self):
- """One alert's eval raising must not block the others; the activity counts it as errored."""
- now = datetime(2025, 1, 1, 0, 1, 0, tzinfo=UTC)
- alerts = self._mock_alerts(3)
-
- call_count = 0
- lock = threading.Lock()
-
- def fake_eval(alert, now, **_kwargs):
- nonlocal call_count
- with lock:
- call_count += 1
- this_call = call_count
- if this_call == 2:
- raise RuntimeError("kaboom")
- return MagicMock()
-
- def fake_finalize(dispatched, elapsed_ms, stats):
- stats["checked"] += 1
-
- with (
- patch(
- "products.logs.backend.temporal.activities._load_alerts_and_checkpoint",
- return_value=(now, alerts, None),
- ),
- patch(
- "products.logs.backend.temporal.activities._build_cohorts",
- side_effect=_stub_one_cohort_per_alert,
- ),
- patch(
- "products.logs.backend.temporal.activities._run_batched_query",
- side_effect=_stub_run_batched_query_empty,
- ),
- patch("products.logs.backend.temporal.activities._evaluate_single_alert", side_effect=fake_eval),
- patch("products.logs.backend.temporal.activities._dispatch_for_alert", return_value=MagicMock()),
- patch(
- "products.logs.backend.temporal.activities._save_cohort_outcomes",
- side_effect=_stub_save_cohort_outcomes_passthrough,
- ),
- patch("products.logs.backend.temporal.activities._finalize_alert", side_effect=fake_finalize),
- ):
- result = asyncio.run(check_alerts_activity(CheckAlertsInput()))
-
- assert result.alerts_checked == 2
- assert result.alerts_errored == 1
-
-
class TestSaveCohortOutcomesFallback(APIBaseTest):
"""Bulk save fallback semantics: IntegrityError → per-alert UPDATE; other errors → propagate."""
@@ -673,38 +289,6 @@ class TestRunCohortQueryFallback(unittest.TestCase):
assert prefetched.buckets is not None and prefetched.buckets[0].count == i
assert prefetched.query_duration_ms == 42
- @patch("products.logs.backend.temporal.activities.MAX_ALERT_COHORT_SIZE", 2)
- def test_build_cohorts_splits_oversized_groups(self):
- # 5 alerts on the same grid at chunk size 2 → 3 cohorts of sizes (2, 2, 1).
- # Each cohort runs as its own task in the activity, with the existing outer
- # MAX_CONCURRENT_ALERT_EVALS semaphore as the only concurrency control —
- # no nested chunking inside _run_cohort_query.
- from products.logs.backend.temporal.activities import _build_cohorts
-
- alerts = [
- MagicMock(
- id=f"alert-{i}",
- team_id=1,
- window_minutes=5,
- evaluation_periods=1,
- check_interval_minutes=5,
- next_check_at=None,
- filters={},
- )
- for i in range(5)
- ]
- now = datetime(2025, 1, 1, 0, 5, tzinfo=UTC)
-
- with (
- patch("products.logs.backend.temporal.activities.is_projection_eligible", return_value=True),
- patch("products.logs.backend.temporal.activities.resolve_alert_date_to", return_value=now),
- ):
- cohorts = _build_cohorts(alerts, now=now, checkpoint=None)
-
- assert sorted(len(c.alerts) for c in cohorts) == [1, 2, 2]
- all_alert_ids = sorted(a.id for c in cohorts for a in c.alerts)
- assert all_alert_ids == [f"alert-{i}" for i in range(5)]
-
@patch("products.logs.backend.temporal.activities.increment_cohort_query_fallback")
@patch("products.logs.backend.temporal.activities.classify_alert_error")
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@@ -712,7 +296,7 @@ class TestRunCohortQueryFallback(unittest.TestCase):
def test_one_cohorts_failure_isolated_from_others(
self, mock_batched, mock_alert_check_query_cls, mock_classify, _mock_fallback_counter
):
- # With cohort splitting at _build_cohorts time, each post-split cohort is an
+ # With cohort splitting at _cohort_manifests_from_alerts time, each post-split cohort is an
# independent unit. _run_cohort_query operates on one bounded cohort at a time.
# This test confirms a single cohort's batched failure → per-alert fallback works
# as before. Cross-cohort isolation is structural (separate tasks, separate calls).
@@ -1929,3 +1513,297 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):
alert.refresh_from_db()
assert alert.state == LogsAlertConfiguration.State.FIRING
assert alert.next_check_at is not None # activity advanced it
+
+
+class TestCohortManifest(unittest.TestCase):
+ def test_manifest_round_trips_through_json(self):
+ # CohortManifest must be JSON-serialisable for Temporal payload conversion.
+ # Datetimes get serialised as ISO strings; UUIDs stay as plain strings.
+ # Use list[str] (not tuple) for alert_ids — JSON arrays deserialise to
+ # lists and Temporal's default converter doesn't round-trip tuples.
+ import json
+
+ from products.logs.backend.temporal.activities import CohortManifest
+
+ manifest = CohortManifest(
+ team_id=42,
+ projection_eligible=True,
+ date_to_iso="2026-05-05T10:00:00+00:00",
+ alert_ids=["019decab-1234-7000-8000-000000000001", "019decab-1234-7000-8000-000000000002"],
+ )
+
+ as_dict = dataclasses.asdict(manifest)
+ round_tripped = CohortManifest(**json.loads(json.dumps(as_dict)))
+
+ assert round_tripped.team_id == 42
+ assert round_tripped.alert_ids == manifest.alert_ids
+ assert round_tripped.date_to_iso == manifest.date_to_iso
+
+ def test_manifests_grouped_by_cohort_key(self):
+ # Three alerts: two share a key (same team, window, cadence, projection,
+ # date_to), one differs by window_minutes. Expect 2 manifests.
+ from products.logs.backend.temporal.activities import _cohort_manifests_from_alerts
+
+ rows = [
+ {
+ "id": "019dec00-0000-0000-0000-000000000001",
+ "team_id": 1,
+ "window_minutes": 5,
+ "evaluation_periods": 1,
+ "check_interval_minutes": 5,
+ "filters": {"serviceNames": ["a"]},
+ "next_check_at": None,
+ },
+ {
+ "id": "019dec00-0000-0000-0000-000000000002",
+ "team_id": 1,
+ "window_minutes": 5,
+ "evaluation_periods": 1,
+ "check_interval_minutes": 5,
+ "filters": {"serviceNames": ["b"]},
+ "next_check_at": None,
+ },
+ {
+ "id": "019dec00-0000-0000-0000-000000000003",
+ "team_id": 1,
+ "window_minutes": 15, # different window → different cohort
+ "evaluation_periods": 1,
+ "check_interval_minutes": 5,
+ "filters": {"serviceNames": ["a"]},
+ "next_check_at": None,
+ },
+ ]
+ now = datetime(2026, 5, 5, 10, 0, tzinfo=UTC)
+
+ with (
+ patch("products.logs.backend.temporal.activities.is_projection_eligible", return_value=True),
+ patch("products.logs.backend.temporal.activities.resolve_alert_date_to", return_value=now),
+ ):
+ manifests = _cohort_manifests_from_alerts(rows, now=now, checkpoint=None)
+
+ assert len(manifests) == 2
+ sizes = sorted(len(m.alert_ids) for m in manifests)
+ assert sizes == [1, 2]
+
+ def test_manifests_split_oversized_groups(self):
+ # 5 alerts on the same grid at MAX_ALERT_COHORT_SIZE=2 → 3 manifests
+ # (sizes [1, 2, 2]).
+ from products.logs.backend.temporal.activities import _cohort_manifests_from_alerts
+
+ rows: list[dict[str, Any]] = [
+ {
+ "id": f"019dec00-0000-0000-0000-{i:012d}",
+ "team_id": 1,
+ "window_minutes": 5,
+ "evaluation_periods": 1,
+ "check_interval_minutes": 5,
+ "filters": {},
+ "next_check_at": None,
+ }
+ for i in range(5)
+ ]
+ now = datetime(2026, 5, 5, 10, 0, tzinfo=UTC)
+
+ with (
+ patch("products.logs.backend.temporal.activities.is_projection_eligible", return_value=True),
+ patch("products.logs.backend.temporal.activities.resolve_alert_date_to", return_value=now),
+ patch("products.logs.backend.temporal.activities.MAX_ALERT_COHORT_SIZE", 2),
+ ):
+ manifests = _cohort_manifests_from_alerts(rows, now=now, checkpoint=None)
+
+ assert sorted(len(m.alert_ids) for m in manifests) == [1, 2, 2]
+
+
+class TestDiscoverCohortsActivity(NonAtomicBaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ @freeze_time("2026-05-05T10:00:00Z")
+ def test_returns_manifests_for_due_alerts_only(self):
+ from products.logs.backend.temporal.activities import DiscoverCohortsInput, discover_cohorts_activity
+
+ # Two due (next_check_at=None), one not due (next_check_at in future).
+ for i in range(2):
+ LogsAlertConfiguration.objects.create(
+ team=self.team,
+ name=f"due_{i}",
+ threshold_count=1,
+ threshold_operator="above",
+ window_minutes=5,
+ evaluation_periods=1,
+ filters={"serviceNames": [f"svc_{i}"]},
+ enabled=True,
+ next_check_at=None,
+ )
+ LogsAlertConfiguration.objects.create(
+ team=self.team,
+ name="future",
+ threshold_count=1,
+ threshold_operator="above",
+ window_minutes=5,
+ evaluation_periods=1,
+ filters={"serviceNames": ["svc_future"]},
+ enabled=True,
+ next_check_at=datetime(2026, 5, 5, 11, 0, tzinfo=UTC), # future
+ )
+
+ result = asyncio.run(discover_cohorts_activity(DiscoverCohortsInput()))
+
+ # Two due alerts share team + window + cadence → one cohort with 2 alert_ids.
+ # (One alert is in the future; not due, not discovered.)
+ assert len(result.manifests) == 1
+ assert len(result.manifests[0].alert_ids) == 2
+
+
+class TestCohortFromManifest(unittest.TestCase):
+ def test_reconstructs_cohort_from_manifest_and_alerts(self):
+ from products.logs.backend.temporal.activities import CohortManifest, _cohort_from_manifest
+
+ alert_a = MagicMock(id="alert-a", team_id=7)
+ alert_b = MagicMock(id="alert-b", team_id=7)
+ alerts_by_id = cast(dict[str, LogsAlertConfiguration], {"alert-a": alert_a, "alert-b": alert_b})
+
+ manifest = CohortManifest(
+ team_id=7,
+ projection_eligible=True,
+ date_to_iso="2026-05-05T10:00:00+00:00",
+ alert_ids=["alert-a", "alert-b"],
+ )
+
+ cohort = _cohort_from_manifest(manifest, alerts_by_id)
+
+ assert len(cohort.alerts) == 2
+ assert cohort.alerts[0] is alert_a
+ assert cohort.alerts[1] is alert_b
+ assert cohort.date_to == datetime(2026, 5, 5, 10, 0, tzinfo=UTC)
+ assert cohort.projection_eligible is True
+
+ def test_raises_if_manifest_alert_id_not_loaded(self):
+ # Defensive: if the evaluate activity's bulk-load missed an alert
+ # (e.g. it was deleted between discovery and evaluate), the manifest
+ # references an ID that's not in `alerts_by_id`. This is a programmer
+ # error / data race — fail loudly rather than silently dropping alerts.
+ from products.logs.backend.temporal.activities import CohortManifest, _cohort_from_manifest
+
+ manifest = CohortManifest(
+ team_id=7,
+ projection_eligible=True,
+ date_to_iso="2026-05-05T10:00:00+00:00",
+ alert_ids=["missing-id"],
+ )
+
+ with self.assertRaises(KeyError):
+ _cohort_from_manifest(manifest, alerts_by_id={})
+
+
+class TestEvaluateCohortBatchActivity(NonAtomicBaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ @freeze_time("2026-05-05T10:05:00Z")
+ @patch("products.logs.backend.temporal.activities._run_cohort_query")
+ def test_loads_alerts_by_id_and_processes_each_cohort(self, mock_run_cohort_query):
+ from products.logs.backend.temporal.activities import (
+ CohortManifest,
+ EvaluateCohortBatchInput,
+ _CohortQueryResult,
+ _PrefetchedQuery,
+ evaluate_cohort_batch_activity,
+ )
+
+ # Two alerts on the same grid → one manifest with 2 IDs.
+ alerts = [
+ LogsAlertConfiguration.objects.create(
+ team=self.team,
+ name=f"a{i}",
+ threshold_count=1,
+ threshold_operator="above",
+ window_minutes=5,
+ evaluation_periods=1,
+ filters={"serviceNames": [f"s{i}"]},
+ enabled=True,
+ next_check_at=None,
+ )
+ for i in range(2)
+ ]
+
+ # Mock the CH query so this is a pure orchestration test (per-cohort
+ # evaluation is covered by other test classes).
+ def _mock_query(cohort):
+ return _CohortQueryResult(per_alert={str(a.id): _PrefetchedQuery(buckets=[]) for a in cohort.alerts})
+
+ mock_run_cohort_query.side_effect = _mock_query
+
+ manifest = CohortManifest(
+ team_id=self.team.id,
+ projection_eligible=True,
+ date_to_iso="2026-05-05T10:05:00+00:00",
+ alert_ids=[str(a.id) for a in alerts],
+ )
+
+ result = asyncio.run(evaluate_cohort_batch_activity(EvaluateCohortBatchInput(manifests=[manifest])))
+
+ assert result.alerts_checked == 2
+ # _run_cohort_query was invoked exactly once (one cohort in this batch).
+ assert mock_run_cohort_query.call_count == 1
+
+ @freeze_time("2026-05-05T10:05:00Z")
+ @patch("products.logs.backend.temporal.activities._run_cohort_query")
+ def test_one_cohorts_failure_isolated_within_batch(self, mock_run_cohort_query):
+ # If one cohort raises, the remaining cohorts in the batch still run.
+ # (Failure isolation across BATCHES is structural — separate Temporal
+ # activities — so it's tested at workflow level, not here.)
+ from products.logs.backend.temporal.activities import (
+ CohortManifest,
+ EvaluateCohortBatchInput,
+ _CohortQueryResult,
+ _PrefetchedQuery,
+ evaluate_cohort_batch_activity,
+ )
+
+ alerts = [
+ LogsAlertConfiguration.objects.create(
+ team=self.team,
+ name=f"a{i}",
+ threshold_count=1,
+ threshold_operator="above",
+ window_minutes=5,
+ evaluation_periods=1,
+ filters={"serviceNames": [f"s{i}"]},
+ enabled=True,
+ next_check_at=None,
+ )
+ for i in range(3)
+ ]
+
+ # First cohort errors, second succeeds.
+ call_count = {"n": 0}
+
+ def _mock_query(cohort):
+ call_count["n"] += 1
+ if call_count["n"] == 1:
+ raise RuntimeError("boom")
+ return _CohortQueryResult(per_alert={str(a.id): _PrefetchedQuery(buckets=[]) for a in cohort.alerts})
+
+ mock_run_cohort_query.side_effect = _mock_query
+
+ # Two single-alert manifests so we can target one specific cohort to fail.
+ manifests = [
+ CohortManifest(
+ team_id=self.team.id,
+ projection_eligible=True,
+ date_to_iso="2026-05-05T10:05:00+00:00",
+ alert_ids=[str(alerts[0].id)],
+ ),
+ CohortManifest(
+ team_id=self.team.id,
+ projection_eligible=True,
+ date_to_iso="2026-05-05T10:05:00+00:00",
+ alert_ids=[str(alerts[1].id)],
+ ),
+ ]
+
+ result = asyncio.run(evaluate_cohort_batch_activity(EvaluateCohortBatchInput(manifests=manifests)))
+
+ assert mock_run_cohort_query.call_count == 2
+ # First cohort errored → counts as 1 errored. Second succeeded → 1 checked.
+ assert result.alerts_errored == 1
+ assert result.alerts_checked == 1
diff --git a/products/logs/backend/test/test_logs_alerting_metrics.py b/products/logs/backend/test/test_logs_alerting_metrics.py
index bf9aaf35cc54..63554c7b2165 100644
--- a/products/logs/backend/test/test_logs_alerting_metrics.py
+++ b/products/logs/backend/test/test_logs_alerting_metrics.py
@@ -28,10 +28,8 @@ from products.logs.backend.temporal.metrics import (
record_cohort_save_duration,
record_cohort_size,
record_cohort_update_duration,
- record_pending_alerts,
record_schedule_to_start_latency,
record_scheduler_lag,
- record_semaphore_wait,
)
@@ -48,7 +46,7 @@ class TestLogsAlertingMetricsInterceptor:
class TestActivityTypes:
def test_alerting_activity_types(self):
- assert ALERTING_ACTIVITY_TYPES == frozenset({"check_alerts_activity"})
+ assert ALERTING_ACTIVITY_TYPES == frozenset({"discover_cohorts_activity", "evaluate_cohort_batch_activity"})
class TestIncrementChecksTotal:
@@ -200,17 +198,6 @@ class TestRecordClickhouseDuration:
)
-class TestRecordSemaphoreWait:
- @patch("products.logs.backend.temporal.metrics._record_histogram")
- def test_records_histogram_with_wait(self, mock_record: MagicMock):
- record_semaphore_wait(800)
- mock_record.assert_called_once_with(
- "logs_alerting_semaphore_wait_ms",
- "Time an alert spent waiting on the per-cycle concurrency semaphore",
- 800,
- )
-
-
class TestRecordCohortSaveSubstageDurations:
@parameterized.expand(
[
@@ -268,31 +255,15 @@ class TestIncrementCohortSaveFallback:
mock_counter.add.assert_called_once_with(1)
-class TestRecordPendingAlerts:
- @pytest.mark.parametrize("count", [42, 0])
- @patch("products.logs.backend.temporal.metrics.get_metric_meter")
- def test_sets_gauge_value(self, mock_get_meter: MagicMock, count: int):
- mock_meter = MagicMock()
- mock_gauge = MagicMock()
- mock_meter.create_gauge.return_value = mock_gauge
- mock_get_meter.return_value = mock_meter
-
- record_pending_alerts(count)
-
- (name, _description), _ = mock_meter.create_gauge.call_args
- assert name == "logs_alerting_pending_alerts"
- mock_gauge.set.assert_called_once_with(count)
-
-
class TestRecordScheduleToStartLatency:
@patch("products.logs.backend.temporal.metrics._record_histogram")
def test_records_latency_with_activity_type(self, mock_record: MagicMock):
- record_schedule_to_start_latency("check_alerts_activity", 250)
+ record_schedule_to_start_latency("discover_cohorts_activity", 250)
mock_record.assert_called_once_with(
"logs_alerting_schedule_to_start_ms",
"Time between activity scheduling and start",
250,
- {"activity_type": "check_alerts_activity"},
+ {"activity_type": "discover_cohorts_activity"},
)
diff --git a/products/logs/backend/test/test_logs_alerting_workflow.py b/products/logs/backend/test/test_logs_alerting_workflow.py
new file mode 100644
index 000000000000..cca47b9fc0c0
--- /dev/null
+++ b/products/logs/backend/test/test_logs_alerting_workflow.py
@@ -0,0 +1,127 @@
+"""Integration tests for the two-phase fan-out workflow.
+
+Mirrors the pattern in `posthog/temporal/tests/test_alerts_workflows.py`:
+`WorkflowEnvironment.start_time_skipping()` + `UnsandboxedWorkflowRunner` so
+the sandbox doesn't trip on Django imports inside `activities.py`.
+"""
+
+import uuid
+
+import pytest
+
+from temporalio import activity
+from temporalio.exceptions import ApplicationError
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+
+from products.logs.backend.temporal.activities import (
+ CheckAlertsInput,
+ CheckAlertsOutput,
+ CohortManifest,
+ DiscoverCohortsInput,
+ DiscoverCohortsOutput,
+ EvaluateCohortBatchInput,
+ EvaluateCohortBatchOutput,
+)
+from products.logs.backend.temporal.workflow import LogsAlertCheckWorkflow
+
+TASK_QUEUE = "logs-alerting-test"
+
+
+async def test_workflow_chunks_manifests_and_aggregates_results() -> None:
+ # 7 manifests, batch_size=3 → 3 batches: sizes 3, 3, 1.
+ manifests = [
+ CohortManifest(
+ team_id=1,
+ projection_eligible=True,
+ date_to_iso="2026-05-05T10:05:00+00:00",
+ alert_ids=[f"alert-{i}"],
+ )
+ for i in range(7)
+ ]
+
+ @activity.defn(name="discover_cohorts_activity")
+ async def fake_discover(_input: DiscoverCohortsInput) -> DiscoverCohortsOutput:
+ return DiscoverCohortsOutput(manifests=manifests, batch_size=3)
+
+ @activity.defn(name="evaluate_cohort_batch_activity")
+ async def fake_evaluate(input: EvaluateCohortBatchInput) -> EvaluateCohortBatchOutput:
+ return EvaluateCohortBatchOutput(
+ alerts_checked=len(input.manifests),
+ alerts_fired=0,
+ alerts_resolved=0,
+ alerts_errored=0,
+ )
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=TASK_QUEUE,
+ workflows=[LogsAlertCheckWorkflow],
+ activities=[fake_discover, fake_evaluate],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ result: CheckAlertsOutput = await env.client.execute_workflow(
+ LogsAlertCheckWorkflow.run,
+ CheckAlertsInput(),
+ id=f"test-workflow-aggregate-{uuid.uuid4()}",
+ task_queue=TASK_QUEUE,
+ )
+
+ assert result.alerts_checked == 7
+ assert result.alerts_errored == 0
+
+
+async def test_workflow_isolates_per_batch_failure() -> None:
+ # One batch's retries exhaust → its alerts count as errored.
+ # Other batches' results still aggregate. Workflow does NOT fail.
+ manifests = [
+ CohortManifest(
+ team_id=1,
+ projection_eligible=True,
+ date_to_iso="2026-05-05T10:05:00+00:00",
+ alert_ids=[f"a-{i}", f"b-{i}"], # 2 alerts per cohort
+ )
+ for i in range(4)
+ ]
+
+ @activity.defn(name="discover_cohorts_activity")
+ async def fake_discover(_input: DiscoverCohortsInput) -> DiscoverCohortsOutput:
+ return DiscoverCohortsOutput(manifests=manifests, batch_size=2)
+
+ # 4 cohorts ÷ batch=2 → 2 batches. Second batch always fails.
+ call_count = {"n": 0}
+
+ @activity.defn(name="evaluate_cohort_batch_activity")
+ async def fake_evaluate(input: EvaluateCohortBatchInput) -> EvaluateCohortBatchOutput:
+ call_count["n"] += 1
+ if call_count["n"] == 2:
+ raise ApplicationError("simulated batch failure", non_retryable=True)
+ return EvaluateCohortBatchOutput(
+ alerts_checked=sum(len(m.alert_ids) for m in input.manifests),
+ alerts_fired=0,
+ alerts_resolved=0,
+ alerts_errored=0,
+ )
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=TASK_QUEUE,
+ workflows=[LogsAlertCheckWorkflow],
+ activities=[fake_discover, fake_evaluate],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ result: CheckAlertsOutput = await env.client.execute_workflow(
+ LogsAlertCheckWorkflow.run,
+ CheckAlertsInput(),
+ id=f"test-workflow-partial-fail-{uuid.uuid4()}",
+ task_queue=TASK_QUEUE,
+ )
+
+ # Successful batch: 2 cohorts × 2 alerts = 4 alerts checked.
+ # Failed batch: 2 cohorts × 2 alerts = 4 alerts counted as errored.
+ assert result.alerts_checked == 4
+ assert result.alerts_errored == 4