:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(alerts): run a logs evaluation cycle on the shared alerts tables (#101275)
Jimmy Zhu333777882dcb
diff --git a/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml b/.semgrep/rules/security/alert-state-must-go-through-state-machine.yamlindex a3ae2fc40ef0..97326e4ec11e 100644--- a/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml+++ b/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml@@ -114,9 +114,40 @@ rules:- '/.semgrep/rules/security/tests/insight-alert-state-must-go-through-state-machine.py'exclude:- '/products/alerts/backend/insight_alert_state_machine.py'+ # Shared skeleton state, covered by platform-alert-state-direct-mutation below.+ - '/products/alerts/backend/logic/platform_lifecycle.py'# Writes HogFunction.enabled (destination plumbing), not an alert.- '/products/alerts/backend/logic/destinations.py'- '/products/alerts/backend/test/**'- '/products/alerts/backend/tests/**'- '/products/alerts/backend/**/test_*.py'- '/posthog/tasks/alerts/test/**'++ - id: platform-alert-state-direct-mutation+ patterns:+ - pattern-either:+ - pattern: $ALERT.state = $VALUE+ - pattern: $ALERT.consecutive_failures = $VALUE+ - pattern: $ALERT.enabled = $VALUE+ - pattern: $QUERY.update(..., state=$VALUE, ...)+ - pattern: $QUERY.update(..., consecutive_failures=$VALUE, ...)+ - pattern: $QUERY.update(..., enabled=$VALUE, ...)+ message: |+ Direct mutation of shared alert lifecycle fields bypasses the shared mutator.+ A source decides whether its data breached; the shared lifecycle decides what+ that means. Route the change through+ products.alerts.backend.facade.platform_alerts.apply_outcome.+ languages: [python]+ severity: ERROR+ metadata:+ category: correctness+ subcategory: audit+ confidence: HIGH+ paths:+ include:+ - '/products/logs/backend/alert_source_cycle.py'+ - '/products/logs/backend/platform_alert_backfill.py'+ exclude:+ - '/products/**/test/**'+ - '/products/**/tests/**'+ - '/products/**/test_*.py'diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex ff4817164f98..20e3d859165d 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -369,6 +369,8 @@ rules:|Subscription|SubscriptionContext|SubscriptionDelivery+ |PlatformAlert+ |PlatformAlertConfiguration|Survey|SurveyResponseArchive|TableCertification@@ -781,6 +783,8 @@ rules:|Subscription|SubscriptionContext|SubscriptionDelivery+ |PlatformAlert+ |PlatformAlertConfiguration|Survey|SurveyResponseArchive|TableCertificationdiff --git a/docs/internal/alerts-product-temporal.md b/docs/internal/alerts-product-temporal.mdindex 48db32e0256d..d2cadf00427b 100644--- a/docs/internal/alerts-product-temporal.md+++ b/docs/internal/alerts-product-temporal.md@@ -9,8 +9,8 @@ The Alerts product registers three queues through `products/alerts/backend/facad| `ALERTS_PRODUCT_DELIVERY_TASK_QUEUE` | `alerts-product-delivery-task-queue` | `alerts-product-deliver` |These queue names are hardcoded and stay separate even with `DEBUG=True`.-Shared orchestration registers the orchestration workflow and a synthetic demand-discovery activity.-The evaluation queue registers the source dispatcher, the evaluation workflow (`alerts-product-evaluate`) and the probe activity.+Shared orchestration registers the orchestration workflow, the source dispatcher and a synthetic demand-discovery activity.+The evaluation queue registers the evaluation workflow (`alerts-product-evaluate`), each bound source evaluation, and the probe activity.Each schedule tick starts orchestration, which discovers demand once and then pages source dispatchers until the demand is exhausted or its dispatch budget is spent.Each dispatcher starts one evaluation child for its source. Evaluation runs the probe and starts its independent delivery child on the delivery queue.Start one worker for each queue:@@ -84,7 +84,7 @@ The empty `--input '{}'` becomes an `OrchestrateInputs` with every field defaultWatch orchestration, its source dispatcher children, their evaluation children, and the delivery great-grandchildren in the Temporal UI at <http://localhost:8081>.Evaluation and delivery accept an empty `AlertsProductInputs` dataclass; orchestration accepts `OrchestrateInputs` with all fields defaulted.-Orchestration pages source dispatchers, which start evaluation children with a 40-second execution timeout and one workflow attempt.+Orchestration pages source dispatchers, which start evaluation children with a 75-second execution timeout and one workflow attempt.Evaluation child IDs carry the tick ID, source and page, so each tick starts distinct evaluations.Evaluation runs a Postgres connectivity probe; delivery runs an empty activity with no I/O.Evaluation and delivery activities each have a 10-second start-to-close timeout and a 30-second schedule-to-close timeout.@@ -99,26 +99,32 @@ Real notification delivery guarantees remain undecided.The evaluation workflow is `alerts-product-evaluate` (class `AlertsProductEvaluateWorkflow`), the probe activity is `alerts_product_probe_postgres_activity`, and the schedule is registered by `create_alerts_product_tick_schedule`.These replace `alerts-product-check-due`, `alerts_product_check_due_activity` and `create_alerts_product_check_due_schedule`: discovery finds what is due and dispatchers hand it out, so this workflow only evaluates.-A workflow type rename breaks runs of the old type that are in flight at deploy time: no worker knows the old name, so they fail. Dev evaluations live under 40 seconds, and production is off.+A workflow type rename breaks runs of the old type that are in flight at deploy time: no worker knows the old name, so they fail. Dev evaluations live under their execution timeout, and production is off.The schedule ID stays `alerts-product-check-due-schedule`. Registration does not delete schedules, so a new ID would leave two schedules until someone deleted the old one by hand.## Tick loop and source dispatchersOne tick is one `alerts-product-orchestrate` execution. It takes an `OrchestrateInputs`; the schedule passes `{}` and every field defaults.The first run records the tick cutoff (the scheduled start time, or the workflow start time for manual runs) and a deadline 45 seconds after the run started.-Discovery runs once per tick. The loop then starts one `alerts-product-source-dispatch` child per source with demand, ID `{tick_id}-{source}-p{page}`, on the evaluation queue.+Discovery runs once per tick. The loop then starts one `alerts-product-source-dispatch` child per source with demand, ID `{tick_id}-{source}-p{page}`, on the orchestration queue.Dispatchers are part of the tick: the orchestrator awaits each dispatcher's report and keeps the default `TERMINATE` close policy on that edge.+They run on the tick's own fleet because the tick awaits them. On the evaluation queue, an evaluation fleet with no free slots+leaves the dispatcher unpicked, and the tick waits on a report that cannot arrive. A dispatcher starts no activities,+so it costs the orchestration fleet a workflow task per source per page and nothing else.+The evaluations it starts still name the evaluation queue, so moving the dispatcher does not move them.Each dispatcher has one attempt and an execution timeout of 30 seconds, or the time left before the tick's hard stop minus one second, whichever is shorter.The hard stop is the run's own execution timeout when it has one, and the budget plus five seconds otherwise. Both deadlines travel in the input across continued runs.The orchestrator passes a dispatcher every remaining ID for its source. The dispatcher decides how much to take and returns the rest.Today it takes everything: no adapter has said yet how many alerts one evaluation can hold, so nothing remains and a tick is one page.The limit that will matter is the evaluation workflow's own history, which depends on the adapter's query shape; it arrives with the first real adapter.-It starts one `alerts-product-evaluate` child, ID `{dispatcher_id}-eval`, with `ParentClosePolicy.ABANDON`, a 40-second execution timeout and one attempt.+It starts one `alerts-product-evaluate` child, ID `{dispatcher_id}-eval`, with `ParentClosePolicy.ABANDON`, a 75-second execution timeout (`SOURCE_EVALUATION_TIMEOUT`) and one attempt.+The timeout has to hold every attempt a source's activities allow, because an attempt cut off here is a batch that decided something and recorded nothing.+Evaluations are abandoned rather than awaited, so it does not have to fit inside the tick.It waits for the child to start, never for it to finish, then returns the dispatched count and the remaining IDs.Members are not passed to evaluation yet: evaluation keeps the probe path until claims exist.-After every page the orchestrator records a `TickPage` (page, run ID, dispatched, remaining).+After every page the orchestrator records a `TickPage` (page, run ID, dispatched, remaining, failed sources, undispatched).When nothing remains it returns `OrchestrateResult(remaining=0, deadline_reached=False)`.Before each page after the first, it checks the deadline. When work remains and the deadline has passed, or fewer than two seconds remain before the hard stop, it returns cleanly with the remaining count and `deadline_reached=True`; the next minute's tick discovers that work again.A tick always runs its first page: the deadline is a stop rule, not an admission rule.@@ -126,7 +132,11 @@ A tick that exits with remaining work is a load signal. A tick that hits the schThe orchestrator calls `continue_as_new` only when Temporal reports `is_continue_as_new_suggested()`. The continued run receives the cutoff, deadline, demand and pages in its input and does not rerun discovery.The schedule's execution timeout spans continued runs, so a rollover cannot extend the tick.-A dispatcher that overruns times out before the tick's hard stop, and the tick fails with that child error rather than being terminated mid-page. Evaluations already started by earlier dispatchers, and their delivery children, are abandoned and complete on their own.+A dispatcher that overruns times out before the tick's hard stop rather than the tick being terminated mid-page. Evaluations already started by earlier dispatchers, and their delivery children, are abandoned and complete on their own.+The orchestrator settles its pages rather than failing on the first error, so one source's dispatcher failing or timing out does not stop the sources dispatching alongside it in the same minute.+A failed source is counted in the page's `failed_sources`, its keys in `undispatched`, and it is logged with its error.+Only a `ChildWorkflowError` counts as a source failure. Anything else, a cancellation or a bug in the orchestrator included, still fails the tick rather than being absorbed on every tick behind a report that says it completed. Nothing advanced its keys' due time, and discovery orders by that time,+so those keys are rediscovered and win a later tick; the tick reports them in `remaining` rather than re-paging them.If the tick is terminated or times out anyway, Temporal terminates its in-flight dispatchers after the tick closes.The previous `workflow.patched` gate around discovery is gone: the loop cannot run without discovery, and dev histories live under a minute.@@ -147,6 +157,132 @@ The result feeds the tick loop above. Evaluation still runs the probe/delivery sTTL claims are not implemented here.Discovery has a five-second start-to-close timeout, a ten-second schedule-to-close timeout, and at most three attempts.+## Batch keys++Discovery returns batch keys, not configuration ids. A key is `(source, team_id, slot)`, where `slot` is+`next_check_at` floored to the minute. A key costs a fixed amount and does not grow with a team's alert+count, so the manifest bound is about how many chunks a tick starts rather than how many alerts it found.++The key names the chunk by what it holds, so the evaluation workflow id is+`alerts-eval-{source}-{team_id}-{slot}` and stays the same when a later tick rediscovers the same work.+A slow evaluation therefore blocks its own re-dispatch without a claim on the configuration rows.++Discovery orders by `next_check_at` ascending. A key the manifest bound leaves out grows more overdue+and wins a later tick; any stable ordering that is not by due time starves the same keys every tick.++Each dispatcher takes up to `MAX_EVALUATIONS_PER_DISPATCH` keys and hands the rest back as a later page.+The evaluation re-reads its own configurations from the key, which it has to do anyway to get thresholds+and filters, so it sees a fresher set than discovery did.++Flooring to the minute loses nothing that load spreading provides: `compute_shard_offset_seconds` returns+whole multiples of the 60-second schedule interval, so spreading moves an alert between minutes rather+than within one.++## Source evaluation bindings++`products/alerts/backend/temporal/sources.py` maps a `SourceKind` to the workflow name that evaluates it.+A source in that map gets its own workflow started by name, carrying one batch key and the tick cutoff.+A source absent from it keeps the noop `alerts-product-evaluate` path, which receives no key.+The alerts product imports nothing from a source: the binding holds a name, and `test_every_source_evaluation_binding_names_a_registered_workflow` fails if that name is not registered on the evaluation queue.++`logs` is bound to `logs-alert-evaluate`, which is the first real source evaluation.++## Logs source evaluation++`logs-alert-evaluate` evaluates one batch key, a team's alerts due in one minute, and previews one delivery per notification.+The evaluation is a plain function in `products/logs/backend/alert_source_cycle.py`, so a test calls it without Temporal.++It writes its own state and never the logs product's rows.+The production `logs-alerting-task-queue` fleet evaluates these same alerts every minute against `LogsAlertConfiguration`,+so a write to those rows, a `LogsAlertEvent` row or a Kafka message here would transition an alert twice and notify a person twice for one breach.+State transitions land on `PlatformAlert` and schedule advancement on `PlatformAlertConfiguration`, which the logs fleet never reads.+Delivery stops at `alerts-product-deliver-preview`, which records what would have been sent and contacts no destination.++The lifecycle decision comes from `products/alerts/backend/facade/lifecycle.py` configured with `LOGS_ALERT_POLICY`,+which is the shared machine the logs product's own state machine is a thin adapter over.+Going to the shared machine directly keeps the platform's lifecycle out of a source product's import path.++It evaluates against the tick cutoff rather than the clock, so a retried attempt selects the same alerts,+resolves the same windows and derives the same evaluation keys as the attempt it replaced.+The due predicate is applied a second time here, because discovery ran earlier in the tick and a configuration+can have been disabled, snoozed or broken since.++### Evaluating and writing are separate activities++`evaluate_logs_alerts_activity` reads and decides; it writes nothing.+It is a sync `def`, so Temporal runs it on the worker's own activity executor and the thread it blocks is a slot Temporal is accounting for.+An async activity handing the work to its own thread pool releases its slot the moment the activity times out, while the thread stays on a query Temporal can no longer see.+Being sync also means Django's connection recycling is the activity's own job, which `@close_db_connections` does for it.+The workflow then calls `alerts_product_record_outcomes`, the platform's own activity, which persists the batch.+Order matters more than the split does: Temporal holds the deliveries the batch decided on before any write+can advance a schedule past them, so an attempt lost between the two costs its queries and nothing else.+A source starts the write by name rather than importing it, so the products stay apart.++The write is safe to run twice. An attempt that commits leaves every configuration due after the cutoff,+and a replay skips those rows rather than advancing them again and skipping a cycle.+It runs in one transaction, so no alert is marked as notified while its schedule still says the check is due.++`MAX_PREVIEWS_PER_CYCLE` bounds an outcome together with the delivery it belongs to.+Recording an outcome whose preview the batch cannot carry would leave an alert firing with nothing announcing it,+and a firing alert does not fire again. Dropping the pair leaves it due, the way a truncated cohort already behaves.+`alerts_platform_deliveries_deferred_total` counts them.++Cohorting, the batched ClickHouse query, projection routing, the byte ceiling and ingestion-freshness gating+all come from the existing logs code, so a preview says what production would have sent.++### The query budget sits under the activity timeout++Four bounds, largest first: `SOURCE_EVALUATION_TIMEOUT` (75s) over the source's `EVALUATION_BUDGET` (62s) over `EVALUATE_START_TO_CLOSE` (30s) over `BATCH_QUERY_BUDGET_SECONDS` (25s) over `MAX_QUERY_SECONDS` (20s).+Temporal bounds an attempt by whichever of start-to-close and schedule-to-close expires first, so schedule-to-close is derived as start-to-close plus a queue tolerance rather than written as a literal.+A literal close to start-to-close lets queue time shorten the run below the query budget, which is the same inversion arriving by another route, on exactly the load that causes queueing.+`test_the_evaluation_timeout_ladder_holds` asserts the whole ladder in one place.+The order is the point. ClickHouse has to be what ends an overrunning query: with the activity timeout below the query's own limit,+the activity times out while the cluster is still running the query, the attempt's thread stays on it, and the retry starts an identical query alongside the first.+Above it, a slow query arrives as one failed cohort the batch reports and the rest of the batch continues.++A batch can run several cohort queries one after another, so a single per-query limit does not bound the batch.+Each query is given the time left before the batch deadline, capped at `MAX_QUERY_SECONDS`; below `MIN_QUERY_SECONDS` no further query starts+and the cohort keeps its due time, counted in an `unqueried` log line.+The budget covers the cohort queries only. The per-alert destination lookup is outside it, so a wide fan-out can still spend the activity's own timeout.+The cap reaches ClickHouse as `max_execution_time` on `BatchedAlertCheckQuery`, with `timeout_overflow_mode` set to throw,+because a partial count could resolve an alert that is actually breaching.++Delivery previews carry a list of group transitions with one entry and an empty grouping key.+Logs does not group yet; the list is the shape that lets fan-out change the evaluation and nothing downstream.++### Metrics++The path emits through Temporal's own meter, so every series carries the worker, queue and activity attributes+the runtime attaches. `products/alerts/backend/temporal/metrics.py` holds them and a source reaches them through+`facade/platform_metrics.py`.++| Metric | What it answers |+| --------------------------------------------------------- | ----------------------------------------------------------- |+| `alerts_platform_checks_total{source,outcome}` | How many checks the platform decided, and what they decided |+| `alerts_platform_state_transitions_total{source,from,to}` | Which transitions it reached |+| `alerts_platform_deliveries_previewed_total{source}` | How many deliveries it recorded instead of sending |+| `alerts_platform_deliveries_deferred_total{source}` | How many the payload bound left for a later tick |+| `alerts_platform_outcomes_recorded_total` | How many decisions reached the tables |+| `alerts_platform_batch_duration_ms{source}` | What one batch key costs |+| `alerts_platform_scheduler_lag_ms{source}` | How far past its due time a check was evaluated |++Histogram buckets are registered in `posthog/temporal/common/worker.py`; a histogram missing from+`ALERTS_PLATFORM_LATENCY_HISTOGRAM_METRICS` gets Prometheus defaults instead.+Every call site goes through `safe_record`, so a metric failure cannot fail a check.++### Seeding the shared tables++`PlatformAlertConfiguration` starts empty, so discovery finds nothing and no evaluation runs until configurations are copied in.+Run the copy once per environment from any pod that carries the application image and a database connection:++```bash+python manage.py backfill_platform_alert_configurations+```++Pass `--team-id` to copy one team's configurations only.+It is a seed, not a sync: the logs product keeps the control plane, and a later change to a logs alert reaches these tables only on the next run.+A second run updates rather than duplicates, because `legacy_configuration_id` carries the row each copy came from.+## Postgres connectivity probeEach evaluation activity issues one explicit `SELECT 1` and checks for `(1,)` through Django's `default` main writer connection.diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex 0577260ab5e7..4f17ce6ba2e8 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -223,6 +223,8 @@ from products.growth.backend.temporal import ()from products.logs.backend.facade.temporal import (ACTIVITIES as LOGS_ALERTING_ACTIVITIES,+ SOURCE_EVALUATION_ACTIVITIES as LOGS_SOURCE_EVALUATION_ACTIVITIES,+ SOURCE_EVALUATION_WORKFLOWS as LOGS_SOURCE_EVALUATION_WORKFLOWS,VOLUME_TICK_ACTIVITIES as LOGS_VOLUME_TICK_ACTIVITIES,VOLUME_TICK_WORKFLOWS as LOGS_VOLUME_TICK_WORKFLOWS,WORKFLOWS as LOGS_ALERTING_WORKFLOWS,@@ -564,8 +566,8 @@ _task_queue_specs = [),(settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,- ALERTS_PRODUCT_EVALUATION_WORKFLOWS,- ALERTS_PRODUCT_EVALUATION_ACTIVITIES,+ ALERTS_PRODUCT_EVALUATION_WORKFLOWS + LOGS_SOURCE_EVALUATION_WORKFLOWS,+ ALERTS_PRODUCT_EVALUATION_ACTIVITIES + LOGS_SOURCE_EVALUATION_ACTIVITIES,),(settings.ALERTS_PRODUCT_DELIVERY_TASK_QUEUE,diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 6bc08318238d..f001cef775f2 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -594,6 +594,8 @@ SPECTACULAR_SETTINGS = {"ScannerProviderEnum": "products.replay_vision.backend.models.replay_scanner.ScannerProvider",# Matches replay_vision's VisionAlertState."LogsAlertConfigurationStateEnum": "products.logs.backend.models.LogsAlertConfiguration.State",+ # Matches the shared alerts skeleton's PlatformAlert.State.+ "BillingAlertConfigurationStateEnum": "products.billing_alerts.backend.models.BillingAlertConfiguration.State","LogsPatternsSourceEnum": ["stored_patterns", "body_mining"],# AutoresearchRun.Status and AutoresearchTrainingRun.Status share this set."ZendeskImportJobStatusEnum": "products.conversations.backend.models.zendesk_import_job.ZendeskImportJob.Status",diff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.pyindex 34d11f0aaa7d..1b477e5d3dce 100644--- a/posthog/temporal/common/worker.py+++ b/posthog/temporal/common/worker.py@@ -58,7 +58,11 @@ from posthog.temporal.usage_report.metrics import (USAGE_REPORTS_LATENCY_HISTOGRAM_METRICS,)-from products.alerts.backend.facade.temporal import AlertsProductTelemetryInterceptor+from products.alerts.backend.facade.temporal import (+ ALERTS_PLATFORM_LATENCY_HISTOGRAM_BUCKETS,+ ALERTS_PLATFORM_LATENCY_HISTOGRAM_METRICS,+ AlertsProductTelemetryInterceptor,+)from products.batch_exports.backend.temporal.metrics import BatchExportsMetricsInterceptorfrom products.experiments.backend.temporal.recalculation_metrics import (EXPERIMENT_METRICS_RECALCULATION_ATTEMPT_HISTOGRAM_BUCKETS,@@ -329,6 +333,12 @@ async def create_worker(itertools.repeat(SURFACING_SCORING_LATENCY_HISTOGRAM_BUCKETS),))+ | dict(+ zip(+ ALERTS_PLATFORM_LATENCY_HISTOGRAM_METRICS,+ itertools.repeat(ALERTS_PLATFORM_LATENCY_HISTOGRAM_BUCKETS),+ )+ )| dict(zip(LOGS_ALERTING_LATENCY_HISTOGRAM_METRICS, itertools.repeat(LOGS_ALERTING_LATENCY_HISTOGRAM_BUCKETS)))| dict(zip(LOGS_ALERTING_COUNT_HISTOGRAM_METRICS, itertools.repeat(LOGS_ALERTING_COUNT_HISTOGRAM_BUCKETS)))| dict(diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.pyindex 5d7398bf3bf9..859aa9326931 100644--- a/products/alerts/backend/facade/contracts.py+++ b/products/alerts/backend/facade/contracts.py@@ -8,6 +8,7 @@ contract check watches this file to decide whether they must retest.from __future__ import annotationsfrom dataclasses import field+from datetime import datetimefrom enum import StrEnumfrom typing import Any, Final, NotRequired, TypedDictfrom uuid import UUID@@ -25,12 +26,25 @@ class DemandDiscoveryInputs:cutoff: str+@frozen+class AlertBatchKey:+ """Names a chunk of due work by what it holds rather than by where it was cut.++ `slot` is `next_check_at` floored to the minute, so a chunk keeps its identity across ticks:+ a slow evaluation of a key is still the same key when the next tick rediscovers it.+ """++ team_id: int+ slot: str++@frozenclass AlertDemand:- """Due configuration IDs per source, bounded so the payload stays small. `omitted_by_source` counts- what discovery left out; that work is due again next tick."""+ """Due batch keys per source, bounded so the payload stays small. A key costs a fixed amount and+ does not grow with a team's alert count. `omitted_by_source` counts keys discovery left out;+ that work is due again next tick."""- configuration_ids_by_source: dict[SourceKind, list[str]]+ batch_keys_by_source: dict[SourceKind, list[AlertBatchKey]]omitted_by_source: dict[SourceKind, int] = field(default_factory=dict)@@ -41,7 +55,8 @@ class SourceDispatchInputs:tick_id: strsource: SourceKindpage: int- configuration_ids: list[str]+ batch_keys: list[AlertBatchKey]+ cutoff: str@frozen@@ -49,8 +64,138 @@ class SourceDispatchReport:source: SourceKindpage: intdispatched: int- remaining_ids: list[str]- evaluation_workflow_id: str | None+ remaining_keys: list[AlertBatchKey]+ evaluation_workflow_ids: list[str]+ # Not remaining: the run that already holds the key is still working it.+ already_running: int = 0+++@frozen+class SourceEvaluationInputs:+ """What a source's own evaluation workflow receives from its dispatcher.++ The key, not a list of ids. The evaluation loads full configurations anyway, so shipping ids+ through the orchestrator would be transit cost, and re-reading gives it the fresher set.+ """++ source: SourceKind+ cutoff: str+ batch_key: AlertBatchKey+++@frozen+class PlatformAlertCheck:+ """One configuration and its runtime state, as a source adapter reads it.++ Flat rather than nested, because a source never holds the rows and has nothing to do with+ the split between what belongs to the configuration and what belongs to the instance.+ """++ id: UUID+ team_id: int+ name: str+ source_config: dict[str, Any]+ threshold_count: int+ threshold_operator: str+ window_minutes: int+ check_interval_minutes: int+ evaluation_periods: int+ datapoints_to_alarm: int+ cooldown_minutes: int+ schedule_restriction: dict[str, Any] | None+ next_check_at: datetime | None+ consecutive_failures: int+ legacy_configuration_id: UUID | None+ state: str+ last_notified_at: datetime | None+ snooze_until: datetime | None++ @property+ def filters(self) -> dict[str, Any]:+ """Satisfies the logs query layer, which names this field `filters`."""+ return self.source_config+++@frozen+class PlatformAlertUpsert:+ """One configuration a source wants copied into the shared tables."""++ legacy_configuration_id: UUID+ team_id: int+ name: str+ enabled: bool+ source_kind: SourceKind+ source_config: dict[str, Any]+ threshold_count: int+ threshold_operator: str+ window_minutes: int+ check_interval_minutes: int+ evaluation_periods: int+ datapoints_to_alarm: int+ cooldown_minutes: int+ schedule_restriction: dict[str, Any] | None+ next_check_at: datetime | None+++@frozen+class PlatformAlertOutcome:+ """What one check decided. The platform turns this into rows."""++ configuration_id: UUID+ new_state: str+ notified: bool+ consecutive_failures: int+ # Recording an outcome without it leaves a configuration discovery keeps handing back to an+ # evaluation that cannot succeed.+ disable: bool = False+++@frozen+class GroupTransition:+ """One transition a delivery would carry. `grouping_key` is empty until a source groups,+ so delivery reads a list of one today and a list of N when fan-out ships."""++ grouping_key: str+ notification: str+++@frozen+class AlertDeliveryPreview:+ """What delivery would send. The PoC records it instead of contacting a destination."""++ source: SourceKind+ alert_id: str+ alert_name: str+ evaluation_key: str+ destination_names: tuple[str, ...]+ transitions: tuple[GroupTransition, ...]+++@frozen+class SourceBatchEvaluation:+ """What one batch decided, before any of it is written.++ Evaluation returns this and the write runs as its own activity, so Temporal has the+ deliveries in history before anything can advance a schedule past them.+ """++ outcomes: tuple[PlatformAlertOutcome, ...]+ previews: tuple[AlertDeliveryPreview, ...]+ # Pairs the payload bound left out. They keep their due time and a later tick re-evaluates+ # them, the way a truncated cohort already behaves.+ omitted: int = 0+++# The platform's write, which a source's evaluation workflow starts by name. One definition,+# because a rename that misses a source breaks it at runtime and nothing else would catch it.+RECORD_OUTCOMES_ACTIVITY: Final[str] = "alerts_product_record_outcomes"+++@frozen+class SourceOutcomeInputs:+ team_id: int+ cutoff: str+ outcomes: tuple[PlatformAlertOutcome, ...]@frozen@@ -59,6 +204,11 @@ class TickPage:run_id: strdispatched: intremaining: int+ # Sources whose dispatcher failed on this page, and the keys they never took. Those keys keep+ # their due time, so a later tick rediscovers them; the page reports them rather than ending+ # the tick.+ failed_sources: int = 0+ undispatched: int = 0@frozen@@ -69,7 +219,7 @@ class OrchestrateInputs:deadline: str | None = None # stop starting pages after thishard_deadline: str | None = None # the execution timeout lands here; no page may run past itpage: int = 0- demand: dict[SourceKind, list[str]] | None = None+ demand: dict[SourceKind, list[AlertBatchKey]] | None = Nonepages: list[TickPage] | None = Noneomitted: int = 0 # due work discovery left out of the bounded manifest; counted as remainingdiff --git a/products/alerts/backend/facade/platform_alerts.py b/products/alerts/backend/facade/platform_alerts.pynew file mode 100644index 000000000000..77c59d7c2165--- /dev/null+++ b/products/alerts/backend/facade/platform_alerts.py@@ -0,0 +1,14 @@+"""The skeleton shared alert tables, as a source adapter sees them.++A source reads a batch of checks, reports what it decided, and can copy its own configurations+in. It never holds one of these rows, so every write and every scheduling rule has one home.+"""++from products.alerts.backend.logic.platform_lifecycle import due_checks, record_outcomes, slot_of, upsert_configuration++__all__ = [+ "due_checks",+ "record_outcomes",+ "slot_of",+ "upsert_configuration",+]diff --git a/products/alerts/backend/facade/platform_metrics.py b/products/alerts/backend/facade/platform_metrics.pynew file mode 100644index 000000000000..d0a72413c620--- /dev/null+++ b/products/alerts/backend/facade/platform_metrics.py@@ -0,0 +1,24 @@+"""Metric emitters for the shared alerts platform, as a source adapter sees them.++A source evaluates its own data but runs on the platform's schedule and writes the platform's+rows, so what a check cost and what it decided are the platform's numbers to name. Kept apart+from `facade/temporal.py`, which pulls in the workflow module.+"""++from products.alerts.backend.temporal.metrics import (+ increment_checks,+ increment_deliveries_deferred,+ increment_state_transition,+ record_batch_duration,+ record_scheduler_lag,+ safe_record,+)++__all__ = [+ "increment_checks",+ "increment_deliveries_deferred",+ "increment_state_transition",+ "record_batch_duration",+ "record_scheduler_lag",+ "safe_record",+]diff --git a/products/alerts/backend/facade/temporal.py b/products/alerts/backend/facade/temporal.pyindex 410cc6f95fb3..26ea7cb57e91 100644--- a/products/alerts/backend/facade/temporal.py+++ b/products/alerts/backend/facade/temporal.py@@ -1,3 +1,7 @@+from products.alerts.backend.temporal.metrics import (+ ALERTS_PLATFORM_LATENCY_HISTOGRAM_BUCKETS,+ ALERTS_PLATFORM_LATENCY_HISTOGRAM_METRICS,+)from products.alerts.backend.temporal.schedule import create_alerts_product_tick_schedulefrom products.alerts.backend.temporal.telemetry import AlertsProductTelemetryInterceptorfrom products.alerts.backend.temporal.workflows import (@@ -7,15 +11,19 @@ from products.alerts.backend.temporal.workflows import (EVALUATION_WORKFLOWS,SHARED_ORCHESTRATION_ACTIVITIES,SHARED_ORCHESTRATION_WORKFLOWS,+ SOURCE_EVALUATION_TIMEOUT,)__all__ = [+ "ALERTS_PLATFORM_LATENCY_HISTOGRAM_BUCKETS",+ "ALERTS_PLATFORM_LATENCY_HISTOGRAM_METRICS","DELIVERY_ACTIVITIES","DELIVERY_WORKFLOWS","EVALUATION_ACTIVITIES","EVALUATION_WORKFLOWS","SHARED_ORCHESTRATION_ACTIVITIES","SHARED_ORCHESTRATION_WORKFLOWS",+ "SOURCE_EVALUATION_TIMEOUT","AlertsProductTelemetryInterceptor","create_alerts_product_tick_schedule",]diff --git a/products/alerts/backend/logic/demand.py b/products/alerts/backend/logic/demand.pyindex eaa08a261e45..70134b8c902e 100644--- a/products/alerts/backend/logic/demand.py+++ b/products/alerts/backend/logic/demand.py@@ -1,69 +1,46 @@import datetime as dt-from posthog.dataclasses import frozen+from django.db.models import Q-from products.alerts.backend.facade.contracts import AlertDemand, SourceKind+from products.alerts.backend.facade.contracts import AlertBatchKey, AlertDemand, SourceKind+from products.alerts.backend.logic.platform_lifecycle import slot_of+from products.alerts.backend.models import PlatformAlertConfiguration--@frozen-class _SyntheticConfiguration:- id: str- source_kind: SourceKind- next_check_at: dt.datetime- enabled: bool = True---def _synthetic_configurations(cutoff: dt.datetime) -> tuple[_SyntheticConfiguration, ...]:- return (- _SyntheticConfiguration(- id="00000000-0000-4000-8000-000000000001",- source_kind=SourceKind.LOGS,- next_check_at=cutoff - dt.timedelta(minutes=1),- ),- _SyntheticConfiguration(- id="00000000-0000-4000-8000-000000000002",- source_kind=SourceKind.LOGS,- next_check_at=cutoff,- ),- _SyntheticConfiguration(- id="00000000-0000-4000-8000-000000000003",- source_kind=SourceKind.INSIGHT,- next_check_at=cutoff,- ),- _SyntheticConfiguration(- id="00000000-0000-4000-8000-000000000004",- source_kind=SourceKind.INSIGHT,- next_check_at=cutoff + dt.timedelta(minutes=1),- ),- _SyntheticConfiguration(- id="00000000-0000-4000-8000-000000000005",- source_kind=SourceKind.LOGS,- next_check_at=cutoff - dt.timedelta(minutes=1),- enabled=False,- ),- )---# IDs per source in one manifest. A UUID is about 40 bytes in JSON, so this keeps each source near 40 KB,-# well under the repository's 256 KB rule for Temporal payload fields. Work left out is due again next tick.+# Keys per source in one manifest. A key is a team id and a minute, so unlike an id list it does not+# grow with a team's alert count, and this bound is about how many distinct chunks one tick starts.DISCOVERY_LIMIT_PER_SOURCE = 1000-def discover_synthetic_demand(cutoff: str, limit_per_source: int = DISCOVERY_LIMIT_PER_SOURCE) -> AlertDemand:+def discover_demand(cutoff: str, limit_per_source: int = DISCOVERY_LIMIT_PER_SOURCE) -> AlertDemand:cutoff_time = dt.datetime.fromisoformat(cutoff)if cutoff_time.utcoffset() is None:raise ValueError("Demand discovery cutoff must include a timezone")if limit_per_source < 1:raise ValueError("Demand discovery limit must be at least 1")- configuration_ids_by_source: dict[SourceKind, list[str]] = {}+ # Discovery is cross-team by definition, so it opts out of team scoping rather than running+ # once per team. Oldest due first, so a key the bound leaves out grows more overdue and wins a+ # later tick; any stable ordering that is not by due time starves the same keys every tick.+ due = (+ PlatformAlertConfiguration.objects.unscoped()+ .filter(Q(enabled=True) & (Q(next_check_at__lte=cutoff_time) | Q(next_check_at__isnull=True)))+ .order_by("next_check_at", "id")+ .values_list("source_kind", "team_id", "next_check_at")+ )++ keys_by_source: dict[SourceKind, list[AlertBatchKey]] = {}+ seen: dict[SourceKind, set[AlertBatchKey]] = {}omitted_by_source: dict[SourceKind, int] = {}- for configuration in _synthetic_configurations(cutoff_time):- if not configuration.enabled or configuration.next_check_at > cutoff_time:+ for raw_source, team_id, next_check_at in due.iterator():+ source = SourceKind(raw_source)+ key = AlertBatchKey(team_id=team_id, slot=slot_of(next_check_at, cutoff_time))+ source_seen = seen.setdefault(source, set())+ if key in source_seen:continue- ids = configuration_ids_by_source.setdefault(configuration.source_kind, [])- if len(ids) < limit_per_source:- ids.append(configuration.id)+ source_seen.add(key)+ keys = keys_by_source.setdefault(source, [])+ if len(keys) < limit_per_source:+ keys.append(key)else:- omitted_by_source[configuration.source_kind] = omitted_by_source.get(configuration.source_kind, 0) + 1- return AlertDemand(configuration_ids_by_source=configuration_ids_by_source, omitted_by_source=omitted_by_source)+ omitted_by_source[source] = omitted_by_source.get(source, 0) + 1+ return AlertDemand(batch_keys_by_source=keys_by_source, omitted_by_source=omitted_by_source)diff --git a/products/alerts/backend/logic/platform_lifecycle.py b/products/alerts/backend/logic/platform_lifecycle.pynew file mode 100644index 000000000000..3b49bf5f0e6b--- /dev/null+++ b/products/alerts/backend/logic/platform_lifecycle.py@@ -0,0 +1,190 @@+"""Reads and writes for the skeleton shared alert tables.++A source decides whether its data breached; everything about what that means for the alert,+and every write to these rows, stays here. A source never holds one of these models.+"""++from collections.abc import Sequence+from datetime import datetime++from django.db import transaction+from django.db.models import Q++from products.alerts.backend.facade.contracts import PlatformAlertCheck, PlatformAlertOutcome, PlatformAlertUpsert+from products.alerts.backend.facade.scheduling import (+ advance_next_check_at,+ compute_shard_offset_seconds,+ parse_blocked_windows_tuples,+ scan_next_unblocked_utc,+)+from products.alerts.backend.models import PlatformAlert, PlatformAlertConfiguration+++def due_q(moment: datetime) -> Q:+ """Configurations a check is owed at `moment`. The read and the write share it, because the+ write skips a row already advanced past it and that is what makes a replay safe."""+ return Q(next_check_at__lte=moment) | Q(next_check_at__isnull=True)+++def _existing_alerts(team_id: int, configurations: Sequence[PlatformAlertConfiguration]) -> dict[str, PlatformAlert]:+ """The runtime rows that exist. A configuration with none has never been evaluated.++ The grouping key is empty until a source groups its results, so today this is the whole of+ an alert's state and a real key needs no new table.+ """+ return {+ str(alert.configuration_id): alert+ for alert in PlatformAlert.objects.for_team(team_id).filter(configuration__in=configurations, grouping_key="")+ }+++def _alerts_for_write(team_id: int, configurations: Sequence[PlatformAlertConfiguration]) -> dict[str, PlatformAlert]:+ """The runtime rows, creating any configuration that has none yet."""+ existing = _existing_alerts(team_id, configurations)+ missing = [c for c in configurations if str(c.id) not in existing]+ if missing:+ # ignore_conflicts leans on the unique constraint, so a concurrent cycle creating the+ # same row is not an error. `for_team` because these models are fail-closed and a+ # Temporal activity has no ambient scope; the rows still carry `team_id` themselves,+ # because a queryset filter does not propagate into row creation.+ PlatformAlert.objects.for_team(team_id).bulk_create(+ [PlatformAlert(team_id=team_id, configuration=c, grouping_key="") for c in missing],+ ignore_conflicts=True,+ )+ existing.update(_existing_alerts(team_id, missing))+ return existing+++def due_checks(team_id: int, source_kind: str, slot: str, cutoff: datetime) -> tuple[PlatformAlertCheck, ...]:+ """Every configuration in one batch key, with its runtime state, ready to evaluate."""+ configurations = list(+ PlatformAlertConfiguration.objects.for_team(team_id)+ .filter(enabled=True, source_kind=source_kind)+ .filter(due_q(cutoff))+ # Ordered so a retried attempt keeps the same alerts under any downstream cap.+ .order_by("id")+ )+ configurations = [c for c in configurations if slot_of(c.next_check_at, cutoff) == slot]+ if not configurations:+ return ()++ alerts = _existing_alerts(team_id, configurations)+ return tuple(_check(c, alerts.get(str(c.id))) for c in configurations)+++def _check(c: PlatformAlertConfiguration, alert: PlatformAlert | None) -> PlatformAlertCheck:+ return PlatformAlertCheck(+ id=c.id,+ team_id=c.team_id,+ name=c.name,+ source_config=c.source_config,+ threshold_count=c.threshold_count,+ threshold_operator=c.threshold_operator,+ window_minutes=c.window_minutes,+ check_interval_minutes=c.check_interval_minutes,+ evaluation_periods=c.evaluation_periods,+ datapoints_to_alarm=c.datapoints_to_alarm,+ cooldown_minutes=c.cooldown_minutes,+ schedule_restriction=c.schedule_restriction,+ next_check_at=c.next_check_at,+ consecutive_failures=c.consecutive_failures,+ legacy_configuration_id=c.legacy_configuration_id,+ state=alert.state if alert else PlatformAlert.State.NOT_FIRING.value,+ last_notified_at=alert.last_notified_at if alert else None,+ snooze_until=alert.snooze_until if alert else None,+ )+++def slot_of(next_check_at: datetime | None, cutoff: datetime) -> str:+ """The minute a configuration is due for. One that has never been checked has no due time+ of its own, so it belongs to the tick that found it.++ The single definition: discovery mints a key with it and this filters rows back down to+ one. If the two ever disagreed, every alert would evaluate nothing, silently.+ """+ return (next_check_at or cutoff).replace(second=0, microsecond=0).isoformat()+++def record_outcomes(+ team_id: int, outcomes: Sequence[PlatformAlertOutcome], now: datetime, *, team_timezone: str+) -> int:+ """Persists a batch's decisions and advances each configuration's schedule.++ Two statements rather than two per alert, in one transaction, so a crash between them cannot+ leave an alert marked as notified while its schedule still says the check is due. The schedule+ advances the way the source's own stack advances it: sharded across the cadence so a fleet does+ not converge on one minute, then pushed past any blocked window.++ Safe to run twice on the same batch. An attempt that commits leaves every configuration due+ after `now`, and a replay of that attempt skips those rows rather than advancing them a second+ time and skipping a cycle.+ Returns how many configurations it wrote, which is fewer than it was given when a replay+ finds rows an earlier attempt already advanced.+ """+ if not outcomes:+ return 0+ by_id = {str(o.configuration_id): o for o in outcomes}++ with transaction.atomic():+ configurations = list(+ PlatformAlertConfiguration.objects.for_team(team_id).filter(id__in=by_id).filter(due_q(now))+ )+ if not configurations:+ return 0+ alerts = _alerts_for_write(team_id, configurations)++ for configuration in configurations:+ outcome = by_id[str(configuration.id)]+ alert = alerts[str(configuration.id)]+ alert.state = outcome.new_state+ if outcome.notified:+ alert.last_notified_at = now++ configuration.consecutive_failures = outcome.consecutive_failures+ if outcome.disable:+ configuration.enabled = False+ next_check_at = advance_next_check_at(+ configuration.next_check_at,+ configuration.check_interval_minutes,+ now,+ shard_offset_seconds=compute_shard_offset_seconds(+ configuration.id, configuration.check_interval_minutes+ ),+ )+ windows = parse_blocked_windows_tuples(configuration.schedule_restriction)+ configuration.next_check_at = (+ scan_next_unblocked_utc(next_check_at, team_timezone, windows) or next_check_at+ )++ PlatformAlert.objects.for_team(team_id).bulk_update(list(alerts.values()), ["state", "last_notified_at"])+ PlatformAlertConfiguration.objects.for_team(team_id).bulk_update(+ configurations, ["consecutive_failures", "enabled", "next_check_at"]+ )+ return len(configurations)+++def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:+ """Copies one source configuration in. Returns True when it created a row.++ Keyed on the row it came from, so a second run updates rather than duplicates.+ """+ _, created = PlatformAlertConfiguration.objects.unscoped().update_or_create(+ legacy_configuration_id=upsert.legacy_configuration_id,+ defaults={+ "team_id": upsert.team_id,+ "name": upsert.name,+ "enabled": upsert.enabled,+ "source_kind": upsert.source_kind.value,+ "source_config": upsert.source_config,+ "threshold_count": upsert.threshold_count,+ "threshold_operator": upsert.threshold_operator,+ "window_minutes": upsert.window_minutes,+ "check_interval_minutes": upsert.check_interval_minutes,+ "evaluation_periods": upsert.evaluation_periods,+ "datapoints_to_alarm": upsert.datapoints_to_alarm,+ "cooldown_minutes": upsert.cooldown_minutes,+ "schedule_restriction": upsert.schedule_restriction,+ "next_check_at": upsert.next_check_at,+ },+ )+ return createddiff --git a/products/alerts/backend/migrations/0007_platformalertconfiguration_platformalert_and_more.py b/products/alerts/backend/migrations/0007_platformalertconfiguration_platformalert_and_more.pynew file mode 100644index 000000000000..51230858af9d--- /dev/null+++ b/products/alerts/backend/migrations/0007_platformalertconfiguration_platformalert_and_more.py@@ -0,0 +1,148 @@+# Generated by Django 5.2.17 on 2026-09-18 19:58++import django.db.models.deletion+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("alerts", "0006_alter_alert_insight_alter_alert_team_and_more"),+ ("posthog", "1366_project_deletion_scheduled_at"),+ ]++ operations = [+ migrations.CreateModel(+ name="PlatformAlertConfiguration",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ ("name", models.CharField(max_length=255)),+ ("enabled", models.BooleanField(db_default=True, default=True)),+ (+ "source_kind",+ models.CharField(choices=[("logs", "Logs")], max_length=32),+ ),+ ("source_config", models.JSONField(default=dict)),+ ("threshold_count", models.PositiveIntegerField()),+ ("threshold_operator", models.CharField(max_length=16)),+ ("window_minutes", models.PositiveIntegerField()),+ ("check_interval_minutes", models.PositiveIntegerField()),+ (+ "evaluation_periods",+ models.PositiveIntegerField(db_default=1, default=1),+ ),+ (+ "datapoints_to_alarm",+ models.PositiveIntegerField(db_default=1, default=1),+ ),+ (+ "cooldown_minutes",+ models.PositiveIntegerField(db_default=0, default=0),+ ),+ ("schedule_restriction", models.JSONField(blank=True, null=True)),+ ("next_check_at", models.DateTimeField(blank=True, null=True)),+ (+ "consecutive_failures",+ models.PositiveIntegerField(db_default=0, default=0),+ ),+ (+ "legacy_configuration_id",+ models.UUIDField(blank=True, null=True, unique=True),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ ),+ migrations.CreateModel(+ name="PlatformAlert",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "grouping_key",+ models.CharField(db_default="", default="", max_length=255),+ ),+ (+ "state",+ models.CharField(+ choices=[+ ("not_firing", "Not firing"),+ ("firing", "Firing"),+ ("errored", "Errored"),+ ("snoozed", "Snoozed"),+ ("broken", "Broken"),+ ],+ db_default="not_firing",+ default="not_firing",+ max_length=32,+ ),+ ),+ ("last_notified_at", models.DateTimeField(blank=True, null=True)),+ ("snooze_until", models.DateTimeField(blank=True, null=True)),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ (+ "configuration",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="alerts",+ to="alerts.platformalertconfiguration",+ ),+ ),+ ],+ ),+ migrations.AddIndex(+ model_name="platformalertconfiguration",+ index=models.Index(+ condition=models.Q(("enabled", True)),+ fields=["next_check_at", "id"],+ name="platform_alert_cfg_due_idx",+ ),+ ),+ migrations.AddIndex(+ model_name="platformalertconfiguration",+ index=models.Index(+ fields=["team_id", "enabled", "source_kind", "next_check_at"],+ name="platform_alert_cfg_batch_idx",+ ),+ ),+ migrations.AddConstraint(+ model_name="platformalert",+ constraint=models.UniqueConstraint(+ fields=("configuration", "grouping_key"),+ name="platform_alert_one_per_group",+ ),+ ),+ ]diff --git a/products/alerts/backend/migrations/max_migration.txt b/products/alerts/backend/migrations/max_migration.txtindex f5c8b630d573..1e366de471c1 100644--- a/products/alerts/backend/migrations/max_migration.txt+++ b/products/alerts/backend/migrations/max_migration.txt@@ -1 +1 @@-0006_alter_alert_insight_alter_alert_team_and_more+0007_platformalertconfiguration_platformalert_and_morediff --git a/products/alerts/backend/models/__init__.py b/products/alerts/backend/models/__init__.pyindex 883ad1df8074..c9dec6f66540 100644--- a/products/alerts/backend/models/__init__.py+++ b/products/alerts/backend/models/__init__.py@@ -1,9 +1,12 @@from .alert import Alert, AlertCheck, AlertConfiguration, AlertSubscription, Threshold+from .platform_alert import PlatformAlert, PlatformAlertConfiguration__all__ = ["Alert","AlertCheck","AlertConfiguration","AlertSubscription",+ "PlatformAlert",+ "PlatformAlertConfiguration","Threshold",]diff --git a/products/alerts/backend/models/platform_alert.py b/products/alerts/backend/models/platform_alert.pynew file mode 100644index 000000000000..fae66148fc7a--- /dev/null+++ b/products/alerts/backend/models/platform_alert.py@@ -0,0 +1,102 @@+"""The shared alert configuration and its runtime state, for any source.++Enough of the shape from the implementation RFC for a source adapter to stop reading its+product's own configuration table, and no more. Fields land as adapters need them.++`Platform` rather than the bare `AlertConfiguration` and `Alert`, which the insight alert+configuration already holds in this app. The prefix names what the rows are for: an alert any+source configures on the shared platform, rather than one product's own table.+"""++from django.db import models++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDTModel+++class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDTModel):+ """What to evaluate, how often, and against what bound.++ Evaluation-level state lives here rather than on `PlatformAlert`, because a failed check+ fails the whole evaluation rather than one group of its results.+ """++ class SourceKind(models.TextChoices):+ LOGS = "logs", "Logs"++ # No database constraint: creating one takes a lock on `posthog_team` that queues behind+ # live writes. Django still cascades in Python, which is the only path that deletes a team.+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")++ # `CreatedMetaFields` is deliberately not used: its `created_by` is a foreign key to+ # `posthog_user`, and creating that constraint locks a table every request writes.+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ name = models.CharField(max_length=255)+ enabled = models.BooleanField(default=True, db_default=True)++ source_kind = models.CharField(max_length=32, choices=SourceKind.choices)+ source_config = models.JSONField(default=dict)++ threshold_count = models.PositiveIntegerField()+ threshold_operator = models.CharField(max_length=16)++ window_minutes = models.PositiveIntegerField()+ check_interval_minutes = models.PositiveIntegerField()+ evaluation_periods = models.PositiveIntegerField(default=1, db_default=1)+ datapoints_to_alarm = models.PositiveIntegerField(default=1, db_default=1)+ cooldown_minutes = models.PositiveIntegerField(default=0, db_default=0)+ schedule_restriction = models.JSONField(null=True, blank=True)++ next_check_at = models.DateTimeField(null=True, blank=True)+ consecutive_failures = models.PositiveIntegerField(default=0, db_default=0)++ # The row this was copied from, so a backfill can run twice and so a comparison can line+ # an evaluation up against the one the source's own stack produced.+ legacy_configuration_id = models.UUIDField(null=True, blank=True, unique=True)++ class Meta:+ indexes = [+ # Discovery: enabled rows ordered by due time. Partial, because a disabled+ # configuration is never discovered and does not belong in the index.+ models.Index(+ fields=["next_check_at", "id"],+ name="platform_alert_cfg_due_idx",+ condition=models.Q(enabled=True),+ ),+ # One batch key's read. Equalities first, then the range, which is the order+ # `due_checks` filters in and the only order that lets all four columns be used.+ models.Index(+ fields=["team_id", "enabled", "source_kind", "next_check_at"],+ name="platform_alert_cfg_batch_idx",+ ),+ ]+++class PlatformAlert(TeamScopedRootMixin, UUIDTModel):+ """Runtime state for one instance of a configuration.++ `grouping_key` is empty until a source groups its results. The unique constraint is what+ makes one row per group, so grouping needs no schema change beyond writing a real key.+ """++ class State(models.TextChoices):+ NOT_FIRING = "not_firing", "Not firing"+ FIRING = "firing", "Firing"+ ERRORED = "errored", "Errored"+ SNOOZED = "snoozed", "Snoozed"+ BROKEN = "broken", "Broken"++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")+ configuration = models.ForeignKey(PlatformAlertConfiguration, on_delete=models.CASCADE, related_name="alerts")++ grouping_key = models.CharField(max_length=255, default="", db_default="")+ state = models.CharField(max_length=32, choices=State.choices, default=State.NOT_FIRING, db_default="not_firing")+ last_notified_at = models.DateTimeField(null=True, blank=True)+ snooze_until = models.DateTimeField(null=True, blank=True)++ class Meta:+ constraints = [+ models.UniqueConstraint(fields=["configuration", "grouping_key"], name="platform_alert_one_per_group")+ ]diff --git a/products/alerts/backend/temporal/metrics.py b/products/alerts/backend/temporal/metrics.pynew file mode 100644index 000000000000..b0c583582efe--- /dev/null+++ b/products/alerts/backend/temporal/metrics.py@@ -0,0 +1,98 @@+"""Prometheus metrics for the shared alerts platform's evaluation path.++Emitted through Temporal's own meter, so a counter carries the worker, queue and activity+attributes the runtime already attaches, and the worker's bucket overrides reach the histograms+below. Every call site wraps these in `safe_record`: a metric must never fail a check.+"""++import datetime as dt++from posthog.temporal.common.logger import get_write_only_logger+from posthog.temporal.common.metrics import get_metric_meter++logger = get_write_only_logger(__name__)++# Consumed by `posthog/temporal/common/worker.py` to override Prometheus default buckets.+# Keep in sync with the histograms below.+ALERTS_PLATFORM_LATENCY_HISTOGRAM_METRICS = (+ "alerts_platform_batch_duration_ms",+ "alerts_platform_scheduler_lag_ms",+)++ALERTS_PLATFORM_LATENCY_HISTOGRAM_BUCKETS = [+ 100.0,+ 500.0,+ 1_000.0,+ 5_000.0,+ 10_000.0,+ 30_000.0,+ 60_000.0,+ 120_000.0,+ 300_000.0,+ 600_000.0,+]+++def safe_record(fn, *args, **kwargs) -> None:+ """Best-effort metric recording. A batch that decided correctly must not fail on telemetry."""+ try:+ fn(*args, **kwargs)+ except Exception as error:+ logger.warning("alerts_platform_metric_failed", metric=fn.__name__, error=str(error))+++def increment_checks(source: str, outcome: str) -> None:+ get_metric_meter({"source": source, "outcome": outcome}).create_counter(+ "alerts_platform_checks_total",+ "Checks the shared platform decided, by source and notification outcome",+ ).add(1)+++def increment_state_transition(source: str, from_state: str, to_state: str) -> None:+ get_metric_meter({"source": source, "from": from_state, "to": to_state}).create_counter(+ "alerts_platform_state_transitions_total",+ "Alert state transitions the shared platform decided",+ ).add(1)+++def increment_deliveries_deferred(source: str, count: int) -> None:+ """Deliveries a batch decided on but could not carry inside its activity payload bound.++ They keep their due time, so this counts work a later tick repeats rather than work lost.+ """+ get_metric_meter({"source": source}).create_counter(+ "alerts_platform_deliveries_deferred_total",+ "Deliveries left out of a batch by its payload bound; the alerts stay due",+ ).add(count)+++def increment_deliveries_previewed(source: str) -> None:+ get_metric_meter({"source": source}).create_counter(+ "alerts_platform_deliveries_previewed_total",+ "Deliveries recorded as a preview instead of being sent",+ ).add(1)+++def increment_outcomes_recorded(count: int) -> None:+ get_metric_meter().create_counter(+ "alerts_platform_outcomes_recorded_total",+ "Check decisions written to the shared alert tables",+ ).add(count)+++def record_batch_duration(source: str, duration_ms: int) -> None:+ get_metric_meter({"source": source}).create_histogram_timedelta(+ name="alerts_platform_batch_duration_ms",+ description="Wall time for one batch key's evaluation, queries included",+ unit="ms",+ ).record(dt.timedelta(milliseconds=duration_ms))+++def record_scheduler_lag(source: str, lag_ms: int) -> None:+ """How far past its due time a check was evaluated. Rising lag means discovery's bound is+ biting, because a key it omits grows more overdue until a later tick takes it."""+ get_metric_meter({"source": source}).create_histogram_timedelta(+ name="alerts_platform_scheduler_lag_ms",+ description="Delay between a check's due time and the evaluation that took it",+ unit="ms",+ ).record(dt.timedelta(milliseconds=lag_ms))diff --git a/products/alerts/backend/temporal/outcomes.py b/products/alerts/backend/temporal/outcomes.pynew file mode 100644index 000000000000..326d64125f0b--- /dev/null+++ b/products/alerts/backend/temporal/outcomes.py@@ -0,0 +1,46 @@+"""The platform's write, as its own activity.++A source's evaluation reads and decides; this records. Splitting them is what makes an+evaluation replayable: it touches nothing, so a worker that dies before Temporal accepts its+result loses nothing but the queries. By the time this runs, the deliveries the batch decided+on are already in the workflow's history.++A source starts this by name rather than importing it, which keeps the products apart and keeps+this module off the import path of any workflow.+"""++import datetime as dt++from temporalio import activity++from products.alerts.backend.facade.contracts import RECORD_OUTCOMES_ACTIVITY, SourceOutcomeInputs+from products.alerts.backend.temporal.metrics import increment_outcomes_recorded, safe_record++[email protected](name=RECORD_OUTCOMES_ACTIVITY)+async def alerts_product_record_outcomes_activity(inputs: SourceOutcomeInputs) -> int:+ """Records one batch's decisions. Returns how many reached the tables."""+ # Imported in the activity body, not at module scope: a Django model import trips Temporal's+ # workflow sandbox, and the worker registration that reaches this module runs through one.+ from posthog.models import Team+ from posthog.sync import database_sync_to_async_pool++ from products.alerts.backend.facade.platform_alerts import record_outcomes++ if not inputs.outcomes:+ return 0++ def _record() -> int:+ timezone = Team.objects.filter(id=inputs.team_id).values_list("timezone", flat=True).first()+ if timezone is None:+ return 0+ return record_outcomes(+ inputs.team_id,+ inputs.outcomes,+ dt.datetime.fromisoformat(inputs.cutoff),+ team_timezone=timezone,+ )++ recorded = await database_sync_to_async_pool(_record)()+ safe_record(increment_outcomes_recorded, recorded)+ return recordeddiff --git a/products/alerts/backend/temporal/sources.py b/products/alerts/backend/temporal/sources.pynew file mode 100644index 000000000000..7c22d753aabe--- /dev/null+++ b/products/alerts/backend/temporal/sources.py@@ -0,0 +1,13 @@+"""Which sources evaluate for real, and under what workflow name.++A source's evaluation lives in that source's product, so the dispatcher starts it by name+rather than by class. The alerts product imports nothing from a source.++A source absent from this map keeps the noop evaluation path.+"""++from products.alerts.backend.facade.contracts import SourceKind++SOURCE_EVALUATION_WORKFLOWS: dict[SourceKind, str] = {+ SourceKind.LOGS: "logs-alert-evaluate",+}diff --git a/products/alerts/backend/temporal/workflows.py b/products/alerts/backend/temporal/workflows.pyindex 6a43b4cc74f0..ed89b387246f 100644--- a/products/alerts/backend/temporal/workflows.py+++ b/products/alerts/backend/temporal/workflows.py@@ -5,10 +5,24 @@ from dataclasses import replacefrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy, SearchAttributeKey-from temporalio.exceptions import ActivityError, ApplicationError, TimeoutError, TimeoutType+from temporalio.exceptions import (+ ActivityError,+ ApplicationError,+ ChildWorkflowError,+ TimeoutError,+ TimeoutType,+ WorkflowAlreadyStartedError,+)from posthog.dataclasses import frozenfrom posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.common.logger import get_write_only_logger++from products.alerts.backend.temporal.metrics import increment_deliveries_previewed, safe_record+from products.alerts.backend.temporal.outcomes import alerts_product_record_outcomes_activity+from products.alerts.backend.temporal.sources import SOURCE_EVALUATION_WORKFLOWS++LOGGER = get_write_only_logger(__name__)with workflow.unsafe.imports_passed_through():from django.conf import settings@@ -16,16 +30,20 @@ with workflow.unsafe.imports_passed_through():from asgiref.sync import sync_to_async+ from posthog.sync import database_sync_to_async_pool+from products.alerts.backend.facade.contracts import (+ AlertDeliveryPreview,AlertDemand,DemandDiscoveryInputs,OrchestrateInputs,OrchestrateResult,SourceDispatchInputs,SourceDispatchReport,+ SourceEvaluationInputs,TickPage,)- from products.alerts.backend.logic.demand import discover_synthetic_demand+ from products.alerts.backend.logic.demand import discover_demandfrom products.alerts.backend.temporal.postgres import check_postgres_connection@@ -34,12 +52,21 @@ POSTGRES_PROBE_FAILURE = "AlertsProductPostgresProbeFailure"# A tick stops starting pages once this much of its minute is spent. The schedule's 50-second# execution timeout is the backstop, and it spans continued runs.TICK_DISPATCH_BUDGET = dt.timedelta(seconds=45)+# Evaluations one dispatcher starts before handing the rest back as a later page. Bounds how many+# children a single page opens; the tick's budget decides whether that page gets to run.+MAX_EVALUATIONS_PER_DISPATCH = 50# Where the hard stop is assumed when the run has no execution timeout of its own.TICK_HARD_STOP_MARGIN = dt.timedelta(seconds=5)# A dispatcher gets this long, or the time left before the hard stop, whichever is shorter.SOURCE_DISPATCH_TIMEOUT = dt.timedelta(seconds=30)# Time kept between a dispatcher's timeout and the hard stop, so the child closes first.SOURCE_DISPATCH_HEADROOM = dt.timedelta(seconds=1)+# What an evaluation gets end to end: its reads, its write, and the delivery children it starts.+# It has to hold every attempt a source's activities allow, because an attempt cut off here is a+# batch that decided something and recorded nothing. Evaluations are abandoned rather than+# awaited, so this does not have to fit inside the tick. It does hold the key for its duration,+# which is what blocks a slow evaluation's own re-dispatch.+SOURCE_EVALUATION_TIMEOUT = dt.timedelta(seconds=75)@frozen@@ -49,7 +76,7 @@ class AlertsProductInputs:@activity.defnasync def alerts_product_discover_demand_activity(inputs: DemandDiscoveryInputs) -> AlertDemand:- return discover_synthetic_demand(inputs.cutoff)+ return await database_sync_to_async_pool(discover_demand)(inputs.cutoff)@activity.defn@@ -65,6 +92,39 @@ async def alerts_product_deliver_activity() -> None:pass+async def alerts_product_deliver_preview_activity(preview: AlertDeliveryPreview) -> None:+ """Records what delivery would have sent. The PoC contacts no destination."""+ await LOGGER.ainfo(+ "alerts_product_delivery_preview",+ source=preview.source.value,+ alert_id=preview.alert_id,+ alert_name=preview.alert_name,+ evaluation_key=preview.evaluation_key,+ destinations=list(preview.destination_names),+ transitions=[+ {"grouping_key": transition.grouping_key, "notification": transition.notification}+ for transition in preview.transitions+ ],+ )+ safe_record(increment_deliveries_previewed, preview.source.value)++[email protected](name="alerts-product-deliver-preview")+class AlertsProductDeliverPreviewWorkflow(PostHogWorkflow):+ inputs_cls = AlertDeliveryPreview++ @workflow.run+ async def run(self, inputs: AlertDeliveryPreview) -> None:+ await workflow.execute_activity(+ alerts_product_deliver_preview_activity,+ inputs,+ start_to_close_timeout=dt.timedelta(seconds=10),+ schedule_to_close_timeout=dt.timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )++@workflow.defn(name="alerts-product-deliver")class AlertsProductDeliverWorkflow(PostHogWorkflow):inputs_cls = AlertsProductInputs@@ -117,10 +177,10 @@ class AlertsProductEvaluateWorkflow(PostHogWorkflow):@workflow.defn(name="alerts-product-source-dispatch")class AlertsProductSourceDispatchWorkflow(PostHogWorkflow):"""One run per source per page. Receives all of the source's remaining demand, starts one- evaluation child for it, and reports what it did not take. Today it takes everything: no- adapter has said yet how much one evaluation can hold, so nothing remains and a tick is one page.+ evaluation child per batch key up to `MAX_EVALUATIONS_PER_DISPATCH`, and reports the keys it+ did not take so a later page picks them up.- Never waits for evaluation. The child is started with ABANDON so it outlives this+ Never waits for evaluation. Children are started with ABANDON so they outlive thisworkflow and the tick that owns it."""@@ -128,25 +188,54 @@ class AlertsProductSourceDispatchWorkflow(PostHogWorkflow):@workflow.runasync def run(self, inputs: SourceDispatchInputs) -> SourceDispatchReport:- evaluation_workflow_id: str | None = None- if inputs.configuration_ids:- # Members are not passed to evaluation until claims exist. The probe path stays as is.- evaluation_workflow_id = f"{workflow.info().workflow_id}-eval"- await workflow.start_child_workflow(- AlertsProductEvaluateWorkflow.run,- AlertsProductInputs(),- id=evaluation_workflow_id,- task_queue=settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,- parent_close_policy=workflow.ParentClosePolicy.ABANDON,- execution_timeout=dt.timedelta(seconds=40),- retry_policy=RetryPolicy(maximum_attempts=1),+ taken = inputs.batch_keys[:MAX_EVALUATIONS_PER_DISPATCH]+ remaining = inputs.batch_keys[MAX_EVALUATIONS_PER_DISPATCH:]+ source_workflow = SOURCE_EVALUATION_WORKFLOWS.get(inputs.source)++ started_ids: list[str] = []+ already_running = 0+ for key in taken:+ evaluation_workflow_id = f"alerts-eval-{inputs.source.value}-{key.team_id}-{key.slot}"+ try:+ if source_workflow is None:+ # No adapter yet. The key is not passed to the noop, and the probe path stays as is.+ await workflow.start_child_workflow(+ AlertsProductEvaluateWorkflow.run,+ AlertsProductInputs(),+ id=evaluation_workflow_id,+ task_queue=settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,+ execution_timeout=SOURCE_EVALUATION_TIMEOUT,+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ else:+ await workflow.start_child_workflow(+ source_workflow,+ SourceEvaluationInputs(source=inputs.source, cutoff=inputs.cutoff, batch_key=key),+ id=evaluation_workflow_id,+ task_queue=settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,+ execution_timeout=SOURCE_EVALUATION_TIMEOUT,+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ except WorkflowAlreadyStartedError:+ # Skipping is how a slow evaluation blocks its own re-dispatch. Letting the error+ # escape would fail this page, and the orchestrator awaits its pages, so the tick.+ already_running += 1+ continue+ started_ids.append(evaluation_workflow_id)++ if already_running:+ workflow.logger.info(+ "Skipped %d %s evaluations still running from an earlier tick", already_running, inputs.source.value)return SourceDispatchReport(source=inputs.source,page=inputs.page,- dispatched=len(inputs.configuration_ids),- remaining_ids=[],- evaluation_workflow_id=evaluation_workflow_id,+ dispatched=len(started_ids),+ remaining_keys=remaining,+ evaluation_workflow_ids=started_ids,+ already_running=already_running,)@@ -180,6 +269,7 @@ class AlertsProductOrchestrateWorkflow(PostHogWorkflow):hard_deadline=(now + hard_stop).isoformat(),)assert inputs.cutoff is not None and inputs.deadline is not None and inputs.hard_deadline is not None+ cutoff_iso = inputs.cutoffdeadline = dt.datetime.fromisoformat(inputs.deadline)hard_deadline = dt.datetime.fromisoformat(inputs.hard_deadline)@@ -191,7 +281,7 @@ class AlertsProductOrchestrateWorkflow(PostHogWorkflow):schedule_to_close_timeout=dt.timedelta(seconds=10),retry_policy=RetryPolicy(maximum_attempts=3),)- demand = discovered.configuration_ids_by_source+ demand = discovered.batch_keys_by_sourceinputs = replace(inputs, omitted=sum(discovered.omitted_by_source.values()))else:demand = inputs.demand@@ -205,8 +295,15 @@ class AlertsProductOrchestrateWorkflow(PostHogWorkflow):page_timeout = min(SOURCE_DISPATCH_TIMEOUT, hard_deadline - now - SOURCE_DISPATCH_HEADROOM)if (pages and now >= deadline) or page_timeout < SOURCE_DISPATCH_HEADROOM:workflow.logger.info("Tick dispatch budget spent with work remaining; the next tick takes it")- remaining = sum(len(ids) for ids in demand.values()) + inputs.omitted+ remaining = (+ sum(len(keys) for keys in demand.values())+ + inputs.omitted+ + sum(recorded.undispatched for recorded in pages)+ )return OrchestrateResult(pages=pages, remaining=remaining, deadline_reached=True)+ # One list, so the settled results below can be read back against the source that+ # produced each one.+ paged = sorted(demand.items())handles = [await workflow.start_child_workflow(AlertsProductSourceDispatchWorkflow.run,@@ -214,35 +311,75 @@ class AlertsProductOrchestrateWorkflow(PostHogWorkflow):tick_id=info.workflow_id,source=source,page=page,- configuration_ids=configuration_ids,+ batch_keys=batch_keys,+ cutoff=cutoff_iso,),id=f"{info.workflow_id}-{source.value}-p{page}",- task_queue=settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,+ # The tick awaits these, so they run on its own fleet. An evaluation fleet with+ # no free slots would otherwise leave the dispatcher unpicked and stall the tick.+ task_queue=settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE,execution_timeout=page_timeout,retry_policy=RetryPolicy(maximum_attempts=1),)- for source, configuration_ids in sorted(demand.items())+ for source, batch_keys in paged]- reports: list[SourceDispatchReport] = await asyncio.gather(*handles)- demand = {report.source: report.remaining_ids for report in reports if report.remaining_ids}+ settled = await asyncio.gather(*handles, return_exceptions=True)+ reports: list[SourceDispatchReport] = []+ failed_sources = 0+ undispatched = 0+ for (dispatched_source, dispatched_keys), outcome in zip(paged, settled, strict=True):+ if isinstance(outcome, SourceDispatchReport):+ reports.append(outcome)+ continue+ if not isinstance(outcome, ChildWorkflowError):+ # Only a dispatcher's own failure is a source failure. A cancellation, a+ # determinism error or a bug in this workflow would otherwise be absorbed on+ # every tick behind a report that says the tick completed.+ raise outcome+ # A broken adapter must not stop the sources dispatching alongside it. Nothing+ # advanced these keys' due time, and discovery orders by it, so they win a later+ # tick rather than being lost here.+ failed_sources += 1+ undispatched += len(dispatched_keys)+ workflow.logger.warning(+ "Dispatching %s failed; its keys stay due for a later tick: %s",+ dispatched_source.value,+ outcome,+ )+ demand = {report.source: report.remaining_keys for report in reports if report.remaining_keys}pages.append(TickPage(page=page,run_id=info.run_id,dispatched=sum(report.dispatched for report in reports),- remaining=sum(len(report.remaining_ids) for report in reports),+ remaining=sum(len(report.remaining_keys) for report in reports),+ failed_sources=failed_sources,+ undispatched=undispatched,))page += 1if demand and _should_continue_as_new():workflow.continue_as_new(replace(inputs, page=page, demand=demand, pages=pages))- return OrchestrateResult(pages=pages, remaining=inputs.omitted, deadline_reached=False)+ return OrchestrateResult(+ pages=pages,+ remaining=inputs.omitted + sum(recorded.undispatched for recorded in pages),+ deadline_reached=False,+ )-SHARED_ORCHESTRATION_WORKFLOWS: list[type[PostHogWorkflow]] = [AlertsProductOrchestrateWorkflow]+SHARED_ORCHESTRATION_WORKFLOWS: list[type[PostHogWorkflow]] = [+ AlertsProductOrchestrateWorkflow,+ AlertsProductSourceDispatchWorkflow,+]SHARED_ORCHESTRATION_ACTIVITIES: list[Callable[..., object]] = [alerts_product_discover_demand_activity]-EVALUATION_WORKFLOWS: list[type[PostHogWorkflow]] = [AlertsProductEvaluateWorkflow, AlertsProductSourceDispatchWorkflow]-EVALUATION_ACTIVITIES: list[Callable[..., object]] = [alerts_product_probe_postgres_activity]-DELIVERY_WORKFLOWS: list[type[PostHogWorkflow]] = [AlertsProductDeliverWorkflow]-DELIVERY_ACTIVITIES: list[Callable[..., object]] = [alerts_product_deliver_activity]+EVALUATION_WORKFLOWS: list[type[PostHogWorkflow]] = [AlertsProductEvaluateWorkflow]+EVALUATION_ACTIVITIES: list[Callable[..., object]] = [+ alerts_product_probe_postgres_activity,+ alerts_product_record_outcomes_activity,+]+DELIVERY_WORKFLOWS: list[type[PostHogWorkflow]] = [AlertsProductDeliverWorkflow, AlertsProductDeliverPreviewWorkflow]+DELIVERY_ACTIVITIES: list[Callable[..., object]] = [+ alerts_product_deliver_activity,+ alerts_product_deliver_preview_activity,+]diff --git a/products/alerts/backend/test/test_platform_lifecycle.py b/products/alerts/backend/test/test_platform_lifecycle.pynew file mode 100644index 000000000000..a9e76ed594b8--- /dev/null+++ b/products/alerts/backend/test/test_platform_lifecycle.py@@ -0,0 +1,59 @@+from datetime import UTC, datetime, timedelta++from posthog.test.base import APIBaseTest++from posthog.models.scoping import team_scope++from products.alerts.backend.facade.contracts import PlatformAlertOutcome, SourceKind+from products.alerts.backend.facade.platform_alerts import due_checks, record_outcomes+from products.alerts.backend.models import PlatformAlertConfiguration+++class TestPlatformAlertLifecycle(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.cutoff = datetime(2026, 9, 16, 10, tzinfo=UTC)+ with team_scope(self.team.id):+ self.configuration = PlatformAlertConfiguration.objects.create(+ team=self.team,+ name="API errors",+ source_kind=PlatformAlertConfiguration.SourceKind.LOGS,+ source_config={},+ threshold_count=10,+ threshold_operator="above",+ window_minutes=5,+ check_interval_minutes=10,+ next_check_at=self.cutoff - timedelta(minutes=1),+ )+ self.slot = (self.cutoff - timedelta(minutes=1)).isoformat()++ def _record(self, **overrides) -> None:+ fields = {+ "configuration_id": self.configuration.id,+ "new_state": "firing",+ "notified": True,+ "consecutive_failures": 0,+ }+ fields.update(overrides)+ record_outcomes(self.team.id, [PlatformAlertOutcome(**fields)], self.cutoff, team_timezone=self.team.timezone)++ def test_a_disabling_outcome_stops_the_configuration_being_discovered(self) -> None:+ self._record(new_state="broken", notified=False, consecutive_failures=5, disable=True)++ with team_scope(self.team.id):+ self.configuration.refresh_from_db()+ assert self.configuration.enabled is False+ assert due_checks(self.team.id, SourceKind.LOGS.value, self.slot, self.cutoff + timedelta(hours=1)) == ()++ def test_recording_a_batch_twice_advances_the_schedule_once(self) -> None:+ self._record()+ with team_scope(self.team.id):+ self.configuration.refresh_from_db()+ after_first = self.configuration.next_check_at++ self._record()++ # Advancing twice skips a whole cycle for every alert in the batch.+ with team_scope(self.team.id):+ self.configuration.refresh_from_db()+ assert self.configuration.next_check_at == after_firstdiff --git a/products/alerts/backend/tests/test_temporal_dispatch.py b/products/alerts/backend/tests/test_temporal_dispatch.pyindex 4053e56d4b6d..84aecc02d7ba 100644--- a/products/alerts/backend/tests/test_temporal_dispatch.py+++ b/products/alerts/backend/tests/test_temporal_dispatch.py@@ -25,12 +25,13 @@ import pytest_asynciofrom temporalio import activity, workflowfrom temporalio.api.enums.v1 import EventType, ParentClosePolicyfrom temporalio.api.history.v1 import HistoryEvent-from temporalio.client import Client, WorkflowExecutionStatus, WorkflowFailureError, WorkflowHistory-from temporalio.exceptions import ChildWorkflowError, TimeoutError+from temporalio.client import Client, WorkflowExecutionStatus, WorkflowHistory+from temporalio.exceptions import ApplicationErrorfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Workerfrom products.alerts.backend.facade.contracts import (+ AlertBatchKey,AlertDemand,DemandDiscoveryInputs,OrchestrateInputs,@@ -45,6 +46,7 @@ from products.alerts.backend.facade.temporal import (SHARED_ORCHESTRATION_WORKFLOWS,)from products.alerts.backend.temporal import postgres, workflows+from products.alerts.backend.temporal.sources import SOURCE_EVALUATION_WORKFLOWSfrom products.alerts.backend.temporal.workflows import (AlertsProductEvaluateWorkflow,AlertsProductInputs,@@ -52,6 +54,26 @@ from products.alerts.backend.temporal.workflows import (AlertsProductSourceDispatchWorkflow,)+_team_id = 0+++def key(name: str) -> AlertBatchKey:+ """One key per scenario name, so a test reads the way it did when demand was a list of ids.+ The minute is derived from the name so keys within a scenario stay distinct."""+ minute = sum(ord(character) for character in name) % 60+ return AlertBatchKey(team_id=_team_id, slot=f"2026-09-16T10:{minute:02d}:00+00:00")++[email protected](autouse=True)+def scenario_team() -> None:+ """The evaluation id is derived from the batch key and the Temporal environment is module-scoped,+ so two tests deriving the same key address one evaluation: the second dispatch finds the first+ test's abandoned evaluation still running and counts it as already running rather than+ dispatched. A team per test keeps the derived ids apart, reruns included."""+ global _team_id+ _team_id += 1++ORCHESTRATION_QUEUE = settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUEEVALUATION_QUEUE = settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE@@ -63,7 +85,7 @@ class PagingDispatcher:@workflow.runasync def run(self, inputs: SourceDispatchInputs) -> SourceDispatchReport:await workflow.execute_activity(- "test_page_gate", inputs.configuration_ids, start_to_close_timeout=dt.timedelta(seconds=30)+ "test_page_gate", [k.slot for k in inputs.batch_keys], start_to_close_timeout=dt.timedelta(seconds=30))evaluation_workflow_id = f"{workflow.info().workflow_id}-eval"await workflow.start_child_workflow(@@ -77,11 +99,39 @@ class PagingDispatcher:source=inputs.source,page=inputs.page,dispatched=1,- remaining_ids=inputs.configuration_ids[1:],- evaluation_workflow_id=evaluation_workflow_id,+ remaining_keys=inputs.batch_keys[1:],+ evaluation_workflow_ids=[evaluation_workflow_id],)[email protected](name="alerts-product-source-dispatch")+class BrokenLogsDispatcher:+ """Registered under the real dispatcher's name. Fails for logs, dispatches for every other+ source, the way a broken source adapter would."""++ @workflow.run+ async def run(self, inputs: SourceDispatchInputs) -> SourceDispatchReport:+ if inputs.source is SourceKind.LOGS:+ raise ApplicationError("the logs adapter is broken", non_retryable=True)+ return SourceDispatchReport(+ source=inputs.source,+ page=inputs.page,+ dispatched=len(inputs.batch_keys),+ remaining_keys=[],+ evaluation_workflow_ids=[],+ )++[email protected](name="test-blocking-evaluation")+class BlockingEvaluation:+ """Occupies an evaluation workflow id for as long as the test needs it."""++ @workflow.run+ async def run(self) -> None:+ # No timeout, so it registers no timer and the time-skipping server cannot skip past it.+ await workflow.wait_condition(lambda: False)++@pytest_asyncio.fixture(scope="module")async def environment() -> AsyncIterator[WorkflowEnvironment]:async with await WorkflowEnvironment.start_time_skipping() as env:@@ -95,6 +145,14 @@ async def local_environment() -> AsyncIterator[WorkflowEnvironment]:yield env[email protected](autouse=True)+def no_source_bindings() -> Iterator[None]:+ """These tests cover paging and the dispatch budget, not which source evaluates for real.+ Clearing the registry keeps every source on the noop path; the binding has its own test."""+ with patch.dict(SOURCE_EVALUATION_WORKFLOWS, clear=True):+ yield++@pytest.fixture(autouse=True)def postgres_cursor() -> Iterator[MagicMock]:with patch.object(postgres, "execute_with_timeout") as execute:@@ -107,40 +165,46 @@ GateActivity = Callable[[list[str]], Awaitable[None]]def demand_activity(- demand: dict[SourceKind, list[str]], omitted: dict[SourceKind, int] | None = None+ demand: dict[SourceKind, list[AlertBatchKey]], omitted: dict[SourceKind, int] | None = None) -> DiscoverActivity:@activity.defn(name="alerts_product_discover_demand_activity")async def discover(inputs: DemandDiscoveryInputs) -> AlertDemand:- return AlertDemand(configuration_ids_by_source=demand, omitted_by_source=omitted or {})+ return AlertDemand(batch_keys_by_source=demand, omitted_by_source=omitted or {})return discover@activity.defn(name="test_page_gate")-async def open_gate(configuration_ids: list[str]) -> None:+async def open_gate(slots: list[str]) -> None:passdef workers(- client: Client, discover: DiscoverActivity, *, paging: bool, gate: GateActivity = open_gate+ client: Client,+ discover: DiscoverActivity | None = None,+ *,+ dispatcher: type | None = None,+ gate: GateActivity = open_gate,) -> tuple[Worker, Worker]:+ """The two fleets a tick uses. A test dispatcher is registered under the real dispatcher's+ name, so it takes its place on the fleet the tick dispatches to."""runner = UnsandboxedWorkflowRunner()- evaluation_workflows: list[type] = (- [AlertsProductEvaluateWorkflow, PagingDispatcher] if paging else list(EVALUATION_WORKFLOWS)+ orchestration_workflows: list[type] = (+ [AlertsProductOrchestrateWorkflow, dispatcher] if dispatcher else list(SHARED_ORCHESTRATION_WORKFLOWS))return (Worker(client,task_queue=ORCHESTRATION_QUEUE,- workflows=SHARED_ORCHESTRATION_WORKFLOWS,- activities=[discover],+ workflows=orchestration_workflows,+ activities=[discover, gate] if discover else [gate],workflow_runner=runner,),Worker(client,task_queue=EVALUATION_QUEUE,- workflows=evaluation_workflows,- activities=[*EVALUATION_ACTIVITIES, gate],+ workflows=[*EVALUATION_WORKFLOWS, BlockingEvaluation],+ activities=EVALUATION_ACTIVITIES,workflow_runner=runner,),)@@ -163,59 +227,114 @@ async def run_tick(client: Client, tick_id: str) -> OrchestrateResult:async def test_real_dispatcher_takes_everything_and_abandons_one_evaluation(environment: WorkflowEnvironment) -> None:client = environment.clientdispatcher_id = f"dispatch-{uuid.uuid4()}"- async with Worker(- client,- task_queue=EVALUATION_QUEUE,- workflows=EVALUATION_WORKFLOWS,- activities=EVALUATION_ACTIVITIES,- workflow_runner=UnsandboxedWorkflowRunner(),- ):+ orchestration_worker, evaluation_worker = workers(client)+ async with orchestration_worker, evaluation_worker:report: SourceDispatchReport = await client.execute_workflow(AlertsProductSourceDispatchWorkflow.run,- SourceDispatchInputs(tick_id="tick", source=SourceKind.LOGS, page=0, configuration_ids=["a", "b", "c"]),+ SourceDispatchInputs(+ tick_id="tick",+ source=SourceKind.LOGS,+ page=0,+ batch_keys=[key("a"), key("b"), key("c")],+ cutoff="2026-09-16T10:00:00+00:00",+ ),id=dispatcher_id,- task_queue=EVALUATION_QUEUE,+ task_queue=ORCHESTRATION_QUEUE,execution_timeout=dt.timedelta(seconds=30),)assert report == SourceDispatchReport(source=SourceKind.LOGS,page=0,dispatched=3,- remaining_ids=[],- evaluation_workflow_id=f"{dispatcher_id}-eval",+ remaining_keys=[],+ evaluation_workflow_ids=[+ f"alerts-eval-logs-{key('a').team_id}-{key('a').slot}",+ f"alerts-eval-logs-{key('b').team_id}-{key('b').slot}",+ f"alerts-eval-logs-{key('c').team_id}-{key('c').slot}",+ ],)history = await client.get_workflow_handle(dispatcher_id).fetch_history()assert events_of(history, EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED) == []initiated = events_of(history, EventType.EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED)- assert len(initiated) == 1+ # One evaluation per key the dispatcher took, each named by the key it holds.+ assert len(initiated) == 3child = initiated[0].start_child_workflow_execution_initiated_event_attributesassert child.workflow_type.name == "alerts-product-evaluate"assert child.parent_close_policy == ParentClosePolicy.PARENT_CLOSE_POLICY_ABANDON- assert child.workflow_execution_timeout.ToTimedelta() == dt.timedelta(seconds=40)- # The dispatcher completed without waiting for the evaluation; the evaluation finishes on its own.- assert events_of(history, EventType.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_COMPLETED) == []- evaluation = client.get_workflow_handle(f"{dispatcher_id}-eval")+ assert child.workflow_execution_timeout.ToTimedelta() == workflows.SOURCE_EVALUATION_TIMEOUT+ # One task per child start, plus the one that completed the run. A dispatcher that awaited an+ # evaluation would need a further task to resume on its result. Counting tasks rather than+ # forbidding a child-completion event keeps this off the race with an abandoned evaluation.+ assert len(events_of(history, EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED)) == len(initiated) + 1+ evaluation = client.get_workflow_handle(f"alerts-eval-logs-{key('a').team_id}-{key('a').slot}")assert await evaluation.result() is Noneassert (await evaluation.describe()).status == WorkflowExecutionStatus.COMPLETED+async def test_a_key_whose_evaluation_still_runs_is_skipped_without_losing_the_page(+ environment: WorkflowEnvironment,+) -> None:+ client = environment.client+ held, free = key("held"), key("free")+ held_id = f"alerts-eval-logs-{held.team_id}-{held.slot}"+ orchestration_worker, evaluation_worker = workers(client)+ async with orchestration_worker, evaluation_worker:+ blocker = await client.start_workflow(BlockingEvaluation.run, id=held_id, task_queue=EVALUATION_QUEUE)+ try:+ report: SourceDispatchReport = await client.execute_workflow(+ AlertsProductSourceDispatchWorkflow.run,+ SourceDispatchInputs(+ tick_id="tick",+ source=SourceKind.LOGS,+ page=0,+ batch_keys=[held, free],+ cutoff="2026-09-16T10:00:00+00:00",+ ),+ id=f"dispatch-{uuid.uuid4()}",+ task_queue=ORCHESTRATION_QUEUE,+ execution_timeout=dt.timedelta(seconds=30),+ )+ finally:+ await blocker.terminate()++ assert report.already_running == 1+ assert report.dispatched == 1+ assert report.evaluation_workflow_ids == [f"alerts-eval-logs-{free.team_id}-{free.slot}"]+ assert report.remaining_keys == []++async def test_tick_with_real_dispatchers_is_one_page(environment: WorkflowEnvironment) -> None:client = environment.clienttick_id = f"tick-{uuid.uuid4()}"- demand = {SourceKind.LOGS: ["l1", "l2", "l3"], SourceKind.INSIGHT: ["i1"]}- orchestration, evaluation = workers(client, demand_activity(demand), paging=False)+ demand = {SourceKind.LOGS: [key("l1"), key("l2"), key("l3")], SourceKind.INSIGHT: [key("i1")]}+ orchestration, evaluation = workers(client, demand_activity(demand))async with orchestration, evaluation:result = await run_tick(client, tick_id)assert [(page.page, page.dispatched, page.remaining) for page in result.pages] == [(0, 4, 0)]assert result == OrchestrateResult(pages=result.pages, remaining=0, deadline_reached=False)+async def test_a_broken_source_dispatcher_does_not_stop_the_others(environment: WorkflowEnvironment) -> None:+ client = environment.client+ tick_id = f"tick-{uuid.uuid4()}"+ demand = {SourceKind.LOGS: [key("l1"), key("l2")], SourceKind.INSIGHT: [key("i1")]}+ orchestration, evaluation = workers(client, demand_activity(demand), dispatcher=BrokenLogsDispatcher)+ async with orchestration, evaluation:+ result = await run_tick(client, tick_id)+ # One source's dispatcher raising used to end the tick, which stopped every other source+ # evaluating for the same minute.+ assert [(page.page, page.dispatched, page.failed_sources) for page in result.pages] == [(0, 1, 1)]+ # Nothing advanced the two logs keys, so the tick reports them as still due.+ assert result.remaining == 2 and not result.deadline_reached++async def test_tick_counts_omitted_demand_as_remaining(environment: WorkflowEnvironment) -> None:"""Discovery bounds its manifest. What it left out is still due, so the tick reports it as remaining."""client = environment.clienttick_id = f"tick-{uuid.uuid4()}"orchestration, evaluation = workers(- client, demand_activity({SourceKind.LOGS: ["l1"]}, omitted={SourceKind.LOGS: 5}), paging=False+ client,+ demand_activity({SourceKind.LOGS: [key("l1")]}, omitted={SourceKind.LOGS: 5}),)async with orchestration, evaluation:result = await run_tick(client, tick_id)@@ -226,8 +345,8 @@ async def test_tick_counts_omitted_demand_as_remaining(environment: WorkflowEnviasync def test_tick_pages_until_demand_is_exhausted(environment: WorkflowEnvironment) -> None:client = environment.clienttick_id = f"tick-{uuid.uuid4()}"- demand = {SourceKind.LOGS: ["l1", "l2", "l3"], SourceKind.INSIGHT: ["i1"]}- orchestration, evaluation = workers(client, demand_activity(demand), paging=True)+ demand = {SourceKind.LOGS: [key("l1"), key("l2"), key("l3")], SourceKind.INSIGHT: [key("i1")]}+ orchestration, evaluation = workers(client, demand_activity(demand), dispatcher=PagingDispatcher)async with orchestration, evaluation:result = await run_tick(client, tick_id)assert [(page.page, page.dispatched, page.remaining) for page in result.pages] == [@@ -262,7 +381,7 @@ async def test_tick_pages_until_demand_is_exhausted(environment: WorkflowEnvironfor event in events_of(history, EventType.EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED):attributes = event.start_child_workflow_execution_initiated_event_attributesassert attributes.parent_close_policy == ParentClosePolicy.PARENT_CLOSE_POLICY_TERMINATE- assert attributes.task_queue.name == EVALUATION_QUEUE+ assert attributes.task_queue.name == ORCHESTRATION_QUEUEassert attributes.workflow_execution_timeout.ToTimedelta() == dt.timedelta(seconds=30)# The tick awaited every dispatcher report. Evaluations are grandchildren and never awaited here.assert len(events_of(history, EventType.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_COMPLETED)) == 4@@ -274,7 +393,9 @@ async def test_tick_pages_until_demand_is_exhausted(environment: WorkflowEnvironasync def test_tick_exits_cleanly_when_dispatch_budget_is_spent(environment: WorkflowEnvironment) -> None:client = environment.clienttick_id = f"tick-{uuid.uuid4()}"- orchestration, evaluation = workers(client, demand_activity({SourceKind.LOGS: ["l1", "l2", "l3"]}), paging=True)+ orchestration, evaluation = workers(+ client, demand_activity({SourceKind.LOGS: [key("l1"), key("l2"), key("l3")]}), dispatcher=PagingDispatcher+ )with patch.object(workflows, "TICK_DISPATCH_BUDGET", dt.timedelta(0)):async with orchestration, evaluation:result = await run_tick(client, tick_id)@@ -287,7 +408,9 @@ async def test_tick_exits_cleanly_when_dispatch_budget_is_spent(environment: Worasync def test_continued_run_carries_demand_and_skips_discovery(environment: WorkflowEnvironment) -> None:client = environment.clienttick_id = f"tick-{uuid.uuid4()}"- orchestration, evaluation = workers(client, demand_activity({SourceKind.LOGS: ["l1", "l2"]}), paging=True)+ orchestration, evaluation = workers(+ client, demand_activity({SourceKind.LOGS: [key("l1"), key("l2")]}), dispatcher=PagingDispatcher+ )with patch.object(workflows, "_should_continue_as_new", return_value=True):async with orchestration, evaluation:result = await run_tick(client, tick_id)@@ -300,7 +423,7 @@ async def test_continued_run_carries_demand_and_skips_discovery(environment: Worassert len(events_of(first, EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED)) == 1continued = first.events[-1].workflow_execution_continued_as_new_event_attributescarried = await client.data_converter.decode(continued.input.payloads, [OrchestrateInputs])- assert carried[0].demand == {SourceKind.LOGS: ["l2"]}+ assert carried[0].demand == {SourceKind.LOGS: [key("l2")]}assert carried[0].page == 1 and carried[0].cutoff is not Noneassert carried[0].deadline is not None and carried[0].hard_deadline is not None@@ -312,22 +435,25 @@ async def test_continued_run_carries_demand_and_skips_discovery(environment: Worasync def test_overrunning_dispatcher_times_out_before_the_tick_hard_stop(local_environment: WorkflowEnvironment,) -> None:- """The tick has a 3 s execution timeout, so each page gets at most 2 s. Page 1 blocks. Its dispatcher- times out first, the tick fails with that child error instead of being terminated mid-page, and- the evaluation page 0 started keeps running."""+ """The tick has a 3 s execution timeout, so each page gets at most 2 s. Page 1 blocks. Its+ dispatcher times out first rather than the tick being terminated mid-page, the tick reports that+ source as failed and still finishes, and the evaluation page 0 started keeps running."""client = local_environment.clienttick_id = f"tick-{uuid.uuid4()}"page_one_started = asyncio.Event()release = asyncio.Event()@activity.defn(name="test_page_gate")- async def block_page_one(configuration_ids: list[str]) -> None:- if configuration_ids == ["l2"]:+ async def block_page_one(slots: list[str]) -> None:+ if slots == [key("l2").slot]:page_one_started.set()await release.wait()orchestration, evaluation = workers(- client, demand_activity({SourceKind.LOGS: ["l1", "l2"]}), paging=True, gate=block_page_one+ client,+ demand_activity({SourceKind.LOGS: [key("l1"), key("l2")]}),+ dispatcher=PagingDispatcher,+ gate=block_page_one,)async with orchestration, evaluation:handle = await client.start_workflow(@@ -338,11 +464,8 @@ async def test_overrunning_dispatcher_times_out_before_the_tick_hard_stop(execution_timeout=dt.timedelta(seconds=3),)await asyncio.wait_for(page_one_started.wait(), timeout=20)- with pytest.raises(WorkflowFailureError) as failure:- await handle.result()+ result = await handle.result()release.set() # let the blocked activity return so the worker can shut down- assert isinstance(failure.value.cause, ChildWorkflowError)- assert isinstance(failure.value.cause.cause, TimeoutError)tick_status = (await handle.describe()).statusstatuses = {@@ -355,7 +478,12 @@ async def test_overrunning_dispatcher_times_out_before_the_tick_hard_stop(0].child_workflow_execution_started_event_attributes.workflow_execution.workflow_iddelivery_status = (await client.get_workflow_handle(delivery_id).describe()).status- assert tick_status == WorkflowExecutionStatus.FAILED # its own child error, not the execution timeout+ # The timed-out dispatcher is a failed source, not a failed tick: another source's dispatcher on+ # the same page would otherwise be terminated with it.+ assert tick_status == WorkflowExecutionStatus.COMPLETED+ assert [(page.page, page.dispatched, page.failed_sources) for page in result.pages] == [(0, 1, 0), (1, 0, 1)]+ # The key page 1 never dispatched is still due, so the tick reports it rather than dropping it.+ assert result.remaining == 1assert statuses["logs-p0"] == WorkflowExecutionStatus.COMPLETEDassert statuses["logs-p1"] == WorkflowExecutionStatus.TIMED_OUTassert page_one.start_time is not None and page_one.close_time is not Nonediff --git a/products/alerts/backend/tests/test_temporal_workflows.py b/products/alerts/backend/tests/test_temporal_workflows.pyindex 29545ab6fa14..ae8d643737f1 100644--- a/products/alerts/backend/tests/test_temporal_workflows.py+++ b/products/alerts/backend/tests/test_temporal_workflows.py@@ -6,6 +6,7 @@ from collections.abc import AsyncIterator, Iteratorfrom typing import Literalimport pytest+from posthog.test.base import APIBaseTestfrom unittest.mock import AsyncMock, MagicMock, patchfrom django.conf import settings@@ -14,6 +15,7 @@ from django.db import OperationalErrorimport pytest_asynciofrom opentelemetry import tracefrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter+from parameterized import parameterizedfrom temporalio import activity, workflowfrom temporalio.api.enums.v1 import EventTypefrom temporalio.client import WorkflowExecutionStatus, WorkflowFailureError@@ -31,7 +33,10 @@ from temporalio.runtime import MetricBuffer, Runtime, TelemetryConfigfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Worker+from posthog.models.scoping import team_scope+from products.alerts.backend.facade.contracts import (+ AlertBatchKey,AlertDemand,DemandDiscoveryInputs,OrchestrateInputs,@@ -48,11 +53,13 @@ from products.alerts.backend.facade.temporal import (AlertsProductTelemetryInterceptor,)from products.alerts.backend.logic import demand+from products.alerts.backend.models import PlatformAlertConfigurationfrom products.alerts.backend.temporal import postgresfrom products.alerts.backend.temporal.workflows import (AlertsProductEvaluateWorkflow,AlertsProductInputs,AlertsProductOrchestrateWorkflow,+ alerts_product_discover_demand_activity,)@@ -421,50 +428,80 @@ async def test_probe_workflow_cancellation_does_not_start_delivery() -> None:start_delivery.assert_not_awaited()- "cutoff_offset, expected_ids",- [- (-2, {}),- (-1, {SourceKind.LOGS: ["00000000-0000-4000-8000-000000000001"]}),- (- 0,- {- SourceKind.LOGS: ["00000000-0000-4000-8000-000000000001", "00000000-0000-4000-8000-000000000002"],- SourceKind.INSIGHT: ["00000000-0000-4000-8000-000000000003"],- },- ),- ],-)-def test_discovery_filters_and_groups_due_configurations(- cutoff_offset: int, expected_ids: dict[SourceKind, list[str]]-) -> None:- tick_time = dt.datetime(2026, 9, 16, 10, tzinfo=dt.UTC)- configurations = demand._synthetic_configurations(tick_time)- cutoff = (tick_time + dt.timedelta(minutes=cutoff_offset)).isoformat()- with patch.object(demand, "_synthetic_configurations", return_value=configurations):- for _ in range(2):- assert demand.discover_synthetic_demand(cutoff).configuration_ids_by_source == expected_ids+class TestDemandDiscovery(APIBaseTest):+ def _configuration(self, *, minutes_ago: int | None, enabled: bool = True, name: str = "alert"):+ with team_scope(self.team.id):+ return PlatformAlertConfiguration.objects.create(+ team=self.team,+ name=name,+ enabled=enabled,+ source_kind=PlatformAlertConfiguration.SourceKind.LOGS,+ source_config={},+ threshold_count=1,+ threshold_operator="above",+ window_minutes=5,+ check_interval_minutes=5,+ next_check_at=None if minutes_ago is None else self.tick - dt.timedelta(minutes=minutes_ago),+ )+ def setUp(self) -> None:+ super().setUp()+ self.tick = dt.datetime(2026, 9, 16, 10, tzinfo=dt.UTC)[email protected]("cutoff", ["invalid", "2026-09-16T10:00:00"])-def test_discovery_rejects_invalid_cutoff(cutoff: str) -> None:- with pytest.raises(ValueError):- demand.discover_synthetic_demand(cutoff)+ def _key(self, minutes_ago: int) -> AlertBatchKey:+ return AlertBatchKey(team_id=self.team.id, slot=(self.tick - dt.timedelta(minutes=minutes_ago)).isoformat())+ def test_only_enabled_and_due_configurations_become_keys(self) -> None:+ self._configuration(minutes_ago=1, name="due")+ self._configuration(minutes_ago=-1, name="not yet due")+ self._configuration(minutes_ago=1, enabled=False, name="disabled")-def test_discovery_bounds_ids_per_source_and_counts_the_rest() -> None:- cutoff = dt.datetime(2026, 9, 16, 10, tzinfo=dt.UTC).isoformat()- bounded = demand.discover_synthetic_demand(cutoff, limit_per_source=1)- assert bounded == AlertDemand(- configuration_ids_by_source={- SourceKind.LOGS: ["00000000-0000-4000-8000-000000000001"],- SourceKind.INSIGHT: ["00000000-0000-4000-8000-000000000003"],- },- omitted_by_source={SourceKind.LOGS: 1},- )- assert demand.discover_synthetic_demand(cutoff).omitted_by_source == {}- with pytest.raises(ValueError):- demand.discover_synthetic_demand(cutoff, limit_per_source=0)+ discovered = demand.discover_demand(self.tick.isoformat())++ assert discovered.batch_keys_by_source == {SourceKind.LOGS: [self._key(1)]}++ def test_configurations_due_in_one_minute_share_one_key(self) -> None:+ self._configuration(minutes_ago=1, name="first")+ self._configuration(minutes_ago=1, name="second")+ self._configuration(minutes_ago=2, name="older")++ discovered = demand.discover_demand(self.tick.isoformat())++ # Two configurations, one key: a key is a team and a minute, not an alert.+ assert discovered.batch_keys_by_source == {SourceKind.LOGS: [self._key(2), self._key(1)]}++ def test_the_bound_keeps_the_oldest_due_keys_and_counts_the_rest(self) -> None:+ self._configuration(minutes_ago=1, name="newer")+ self._configuration(minutes_ago=5, name="oldest")++ bounded = demand.discover_demand(self.tick.isoformat(), limit_per_source=1)++ # Oldest first, so a key the bound leaves out grows more overdue and wins a later tick.+ assert bounded.batch_keys_by_source == {SourceKind.LOGS: [self._key(5)]}+ assert bounded.omitted_by_source == {SourceKind.LOGS: 1}++ def test_a_configuration_never_checked_belongs_to_this_tick(self) -> None:+ self._configuration(minutes_ago=None, name="never checked")++ discovered = demand.discover_demand(self.tick.isoformat())++ assert discovered.batch_keys_by_source == {SourceKind.LOGS: [self._key(0)]}++ @parameterized.expand([("invalid",), ("2026-09-16T10:00:00",)])+ def test_discovery_rejects_invalid_cutoff(self, cutoff: str) -> None:+ with pytest.raises(ValueError):+ demand.discover_demand(cutoff)++ async def test_discovery_runs_off_the_event_loop(self) -> None:+ # The activity is async and discovery reads Postgres, so calling it inline raises+ # SynchronousOnlyOperation and takes the whole tick down. No mock catches that.+ result = await alerts_product_discover_demand_activity(DemandDiscoveryInputs(cutoff=self.tick.isoformat()))++ assert result.batch_keys_by_source == {}++ def test_discovery_rejects_a_limit_below_one(self) -> None:+ with pytest.raises(ValueError):+ demand.discover_demand(self.tick.isoformat(), limit_per_source=0)@pytest.mark.parametrize("scheduled", [False, True])@@ -487,7 +524,7 @@ async def test_discovery_uses_scheduled_cutoff_or_manual_start(scheduled: bool)patch.object(workflow, "info", return_value=info),patch.object(workflow, "now", return_value=actual_start),patch.object(- workflow, "execute_activity", AsyncMock(return_value=AlertDemand(configuration_ids_by_source={}))+ workflow, "execute_activity", AsyncMock(return_value=AlertDemand(batch_keys_by_source={}))) as discover,patch.object(workflow, "start_child_workflow", AsyncMock()) as dispatch,):@@ -498,3 +535,31 @@ async def test_discovery_uses_scheduled_cutoff_or_manual_start(scheduled: bool))dispatch.assert_not_awaited()assert result == OrchestrateResult(pages=[], remaining=0, deadline_reached=False)+++def test_the_dispatcher_is_registered_on_the_fleet_the_tick_starts_it_on() -> None:+ from posthog.management.commands.start_temporal_worker import WORKFLOWS_DICT++ from products.alerts.backend.temporal.workflows import AlertsProductSourceDispatchWorkflow++ # The tick awaits its dispatchers. One registered on a fleet the tick does not dispatch to+ # leaves every page queued until it times out, and fails the tick with it.+ registered = WORKFLOWS_DICT[settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE]+ assert AlertsProductSourceDispatchWorkflow in registered+++def test_every_source_evaluation_binding_names_a_registered_workflow() -> None:+ import temporalio.workflow++ from posthog.management.commands.start_temporal_worker import WORKFLOWS_DICT++ from products.alerts.backend.temporal.sources import SOURCE_EVALUATION_WORKFLOWS++ definitions = (+ temporalio.workflow._Definition.from_class(registered_workflow)+ for registered_workflow in WORKFLOWS_DICT[settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE]+ )+ registered = {definition.name for definition in definitions if definition is not None}+ # A binding naming a workflow no evaluation worker registers leaves every dispatch for+ # that source queued until it times out.+ assert set(SOURCE_EVALUATION_WORKFLOWS.values()) <= registereddiff --git a/products/logs/backend/alert_check_query.py b/products/logs/backend/alert_check_query.pyindex 2340b9357b61..3678b792e9b8 100644--- a/products/logs/backend/alert_check_query.py+++ b/products/logs/backend/alert_check_query.py@@ -1,6 +1,9 @@import timeimport datetime as dt+from collections.abc import Sequencefrom dataclasses import dataclass+from typing import Any, Protocol+from uuid import UUIDfrom zoneinfo import ZoneInfofrom posthog.schema import (@@ -27,7 +30,26 @@ from posthog.models import Teamfrom products.logs.backend.alert_utils import MAX_BYTES_TO_READfrom products.logs.backend.logs_query_runner import LIVE_LOGS_CHECKPOINT_QUERY, LogsFilterBuilder-from products.logs.backend.models import LogsAlertConfiguration+++class AlertQuerySubject(Protocol):+ """What the query layer needs from an alert.++ A `Protocol` rather than a concrete type so `LogsAlertConfiguration` satisfies it as it+ stands, and so a caller holding a configuration from elsewhere can build the query without+ a model instance. The query layer reads no other field: everything about thresholds,+ windows and cadence is the caller's to resolve before it gets here.+ """++ # Read-only, so a frozen dataclass satisfies this as readily as the model does.+ @property+ def id(self) -> UUID: ...++ @property+ def team_id(self) -> int: ...++ @property+ def filters(self) -> dict[str, Any]: ...@dataclass(frozen=True)@@ -42,7 +64,7 @@ class BucketedCount:count: int-def _build_logs_query(alert: LogsAlertConfiguration, date_range: DateRange) -> LogsQuery:+def _build_logs_query(alert: AlertQuerySubject, date_range: DateRange) -> LogsQuery:filters = alert.filtersfilter_group = filters.get("filterGroup")if filter_group:@@ -116,7 +138,7 @@ def _tag_alert_query(*, team: Team, alert_config_id: str, source: str) -> None:def build_alert_where_expr(*,team: Team,- alert: LogsAlertConfiguration,+ alert: AlertQuerySubject,date_from: dt.datetime,date_to: dt.datetime,) -> ast.Expr:@@ -194,7 +216,7 @@ class AlertCheckQuery:self,*,team: Team,- alert: LogsAlertConfiguration,+ alert: AlertQuerySubject,date_from: dt.datetime,date_to: dt.datetime,) -> None:@@ -360,10 +382,11 @@ class BatchedAlertCheckQuery:self,*,team: Team,- alerts: list[LogsAlertConfiguration],+ alerts: Sequence[AlertQuerySubject],date_from: dt.datetime,date_to: dt.datetime,projection_eligible: bool | None = None,+ max_execution_time: int | None = None,) -> None:if not alerts:raise ValueError("BatchedAlertCheckQuery requires at least one alert")@@ -373,6 +396,16 @@ class BatchedAlertCheckQuery:self.alerts = list(alerts)self.date_from = date_fromself.date_to = date_to+ # A caller that runs several of these inside one deadline needs each query to end before+ # the deadline does. Throw rather than break: a partial count could resolve an alert that+ # is actually breaching, and the caller already handles a failed cohort.+ self._settings = (+ self.SETTINGS+ if max_execution_time is None+ else self.SETTINGS.model_copy(+ update={"max_execution_time": max_execution_time, "timeout_overflow_mode": "throw"}+ )+ )self._alert_where_exprs: list[ast.Expr] = [build_alert_where_expr(team=team, alert=alert, date_from=date_from, date_to=date_to)for alert in self.alerts@@ -537,7 +570,7 @@ class BatchedAlertCheckQuery:query=query,team=self.team,workload=Workload.LOGS,- settings=self.SETTINGS,+ settings=self._settings,limit_context=LimitContext.QUERY,modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),)diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.pynew file mode 100644index 000000000000..33e910199a9a--- /dev/null+++ b/products/logs/backend/alert_source_cycle.py@@ -0,0 +1,310 @@+"""Evaluation of due logs alerts on the shared alerts platform.++Reads a batch of checks from the shared platform and reports what it decided. The logs+product's own tables are never touched: the production logs fleet evaluates the same alerts+against `LogsAlertConfiguration` on its own queue, so the two stacks keep separate state and+neither can notify on the other's behalf. Delivery stops at a recorded preview.++This reads and decides; it writes nothing. The platform records the batch in its own activity,+after Temporal has the deliveries this returned, so an attempt that dies mid-flight costs its+queries and nothing else.++Cohorting and query execution reuse the production helpers, so an evaluation says what the+logs stack would have said given the same configuration. The lifecycle decision comes from+the shared machine configured with this source's policy, not from the logs product.+"""++import time+from collections.abc import Sequence+from datetime import datetime, timedelta+from itertools import batched++import structlog++from posthog.models import Team++from products.alerts.backend.facade.contracts import (+ AlertDeliveryPreview,+ GroupTransition,+ PlatformAlertCheck,+ PlatformAlertOutcome,+ SourceBatchEvaluation,+ SourceKind,+)+from products.alerts.backend.facade.destinations import list_active_alert_destinations+from products.alerts.backend.facade.lifecycle import (+ LOGS_ALERT_POLICY,+ AlertSnapshot,+ AlertState,+ CheckInput,+ NotificationAction,+ evaluate_alert_check,+)+from products.alerts.backend.facade.platform_alerts import due_checks+from products.alerts.backend.facade.platform_metrics import (+ increment_checks,+ increment_deliveries_deferred,+ increment_state_transition,+ record_batch_duration,+ record_scheduler_lag,+ safe_record,+)+from products.logs.backend.alert_check_query import (+ BatchedAlertCheckQuery,+ BucketedCount,+ fetch_live_logs_checkpoint,+ is_projection_eligible,+ resolve_alert_date_to,+ rolling_check_lookback_minutes,+)+from products.logs.backend.alert_destinations import EVENT_KIND_CONFIG, EventKind+from products.logs.backend.alert_utils import next_allowed_check_at++# 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.constants import MAX_ALERT_COHORT_SIZE++logger = structlog.get_logger(__name__)++# A fleet-wide burst would otherwise return one activity payload over Temporal's ~2 MiB limit,+# which fails the whole batch rather than truncating it. The bound drops an outcome along with+# the preview it belongs to, so a breach this batch cannot announce keeps its due time.+MAX_PREVIEWS_PER_CYCLE = 500++# Cohorts run one after another, and the production runner measures about four seconds each. A+# higher bound spends the query budget below and returns fewer cohorts, not more; a cohort left+# out keeps its due time.+MAX_COHORTS_PER_CYCLE = 4++# The batch's ClickHouse time, which `EVALUATE_START_TO_CLOSE` in the workflow sits above, so an+# overrunning query is ended by ClickHouse rather than by the activity. It bounds the cohort+# queries only: the per-alert destination lookups below are not inside it.+BATCH_QUERY_BUDGET_SECONDS = 25+# No single cohort query may spend the whole batch budget, or the first slow one starves the rest.+MAX_QUERY_SECONDS = 20+# Below this there is no point starting another query; the cohort keeps its due time instead.+MIN_QUERY_SECONDS = 2++_NOTIFICATION_EVENT_KINDS: dict[NotificationAction, EventKind] = {+ NotificationAction.FIRE: "firing",+ NotificationAction.RESOLVE: "resolved",+ NotificationAction.ERROR: "errored",+ NotificationAction.BROKEN: "broken",+}+++def _cohort_key(check: PlatformAlertCheck, checkpoint: datetime | None, now: datetime) -> tuple:+ return (+ check.window_minutes,+ check.evaluation_periods,+ check.check_interval_minutes,+ is_projection_eligible(check.source_config),+ resolve_alert_date_to(check.next_check_at or now, checkpoint),+ )+++def _is_in_quiet_hours(check: PlatformAlertCheck, team: Team, now: datetime) -> bool:+ """True when the alert's schedule restriction blocks a check at `now`."""+ if not check.schedule_restriction:+ return False+ try:+ return (+ next_allowed_check_at(now, team_timezone=team.timezone, schedule_restriction=check.schedule_restriction)+ > now+ )+ except Exception as error:+ # A restriction we cannot parse must not decide the alert either way, so the check+ # proceeds and the production stack keeps ownership of the broken configuration.+ logger.exception(+ "Unparseable schedule restriction; evaluating anyway", check_id=str(check.id), error=str(error)+ )+ return False+++def _snapshot(check: PlatformAlertCheck, prior_breached: tuple[bool, ...]) -> AlertSnapshot:+ return AlertSnapshot(+ state=AlertState(check.state),+ cooldown=timedelta(minutes=check.cooldown_minutes),+ last_notified_at=check.last_notified_at,+ snooze_until=check.snooze_until,+ consecutive_failures=check.consecutive_failures,+ evaluation_periods=check.evaluation_periods,+ datapoints_to_alarm=check.datapoints_to_alarm,+ recent_events_breached=prior_breached,+ )+++def _evaluate_one(+ check: PlatformAlertCheck, buckets: list[BucketedCount], *, window_end: datetime, now: datetime+) -> tuple[PlatformAlertOutcome, AlertDeliveryPreview | None]:+ current_breached, *prior_windows_breached = _derive_breaches(+ buckets, check.threshold_count, check.threshold_operator, check.evaluation_periods+ ) or (False,)++ # `LOGS_ALERT_POLICY` is how the shared machine expresses this source's semantics, so the+ # decision is the one the logs stack reaches without routing through the logs product.+ outcome = evaluate_alert_check(+ _snapshot(check, tuple(prior_windows_breached)),+ CheckInput(threshold_breached=current_breached),+ now,+ policy=LOGS_ALERT_POLICY,+ )+ recorded = PlatformAlertOutcome(+ configuration_id=check.id,+ new_state=outcome.new_state.value,+ notified=outcome.update_last_notified_at,+ consecutive_failures=outcome.consecutive_failures,+ disable=outcome.disable,+ )+ safe_record(increment_checks, SourceKind.LOGS.value, outcome.notification.value)+ if check.state != outcome.new_state.value:+ safe_record(increment_state_transition, SourceKind.LOGS.value, check.state, outcome.new_state.value)+ if check.next_check_at is not None:+ lag_ms = int((now - check.next_check_at).total_seconds() * 1000)+ if lag_ms > 0:+ safe_record(record_scheduler_lag, SourceKind.LOGS.value, lag_ms)+ if outcome.notification == NotificationAction.NONE:+ return recorded, None++ spec = EVENT_KIND_CONFIG[_NOTIFICATION_EVENT_KINDS[outcome.notification]]+ destinations = list_active_alert_destinations(+ team_id=check.team_id,+ alert_id=str(check.legacy_configuration_id or check.id),+ allowed_event_ids=[spec.event_id],+ )+ return recorded, AlertDeliveryPreview(+ source=SourceKind.LOGS,+ alert_id=str(check.id),+ alert_name=check.name,+ evaluation_key=f"{check.id}:window:{window_end.isoformat()}",+ destination_names=tuple(destination.name for destination in destinations),+ # One transition with an empty grouping key. Logs does not group yet, and delivery+ # reads a list either way, so fan-out changes this call and nothing downstream.+ transitions=(GroupTransition(grouping_key="", notification=outcome.notification.value),),+ )+++def _evaluate_cohort(+ team: Team, checks: Sequence[PlatformAlertCheck], key: tuple, *, now: datetime, query_seconds: int+) -> list[tuple[PlatformAlertOutcome, AlertDeliveryPreview | None]]:+ window_minutes, evaluation_periods, cadence_minutes, projection_eligible, date_to = key+ lookback = rolling_check_lookback_minutes(window_minutes, cadence_minutes, evaluation_periods)++ try:+ result = BatchedAlertCheckQuery(+ team=team,+ alerts=checks,+ date_from=date_to - timedelta(minutes=lookback),+ date_to=date_to,+ projection_eligible=projection_eligible,+ max_execution_time=query_seconds,+ ).execute_rolling_checks(date_to, window_minutes, cadence_minutes, evaluation_periods)+ except Exception as error:+ # One cohort's query must not end the batch, which is how the production cohort runner+ # contains the same failure.+ logger.exception(+ "Logs alert cohort query failed; skipping the cohort",+ team_id=team.id,+ cohort_size=len(checks),+ error=str(error),+ )+ return []++ decided: list[tuple[PlatformAlertOutcome, AlertDeliveryPreview | None]] = []+ for check in checks:+ try:+ decided.append(_evaluate_one(check, result.per_alert.get(str(check.id), []), window_end=date_to, now=now))+ except Exception as error:+ logger.exception("Failed to evaluate a logs alert; skipping it", check_id=str(check.id), error=str(error))+ return decided+++def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatchEvaluation:+ """Evaluates one batch key: a team's alerts due in one minute, against the tick's cutoff.++ The dispatcher passes the key rather than a list of ids, so the set is read here and is the+ fresher one. `cutoff` is the tick occasion, not the clock, so a retried attempt evaluates+ the same alerts against the same windows and derives the same evaluation keys.++ Writes nothing, which is what lets an attempt be retried: the alerts stay due, so the second+ attempt reads the same batch and reaches the same decisions.+ """+ started_at = time.monotonic()+ checks = due_checks(team_id, SourceKind.LOGS.value, slot, cutoff)+ # Production excludes a structurally broken filter before evaluating, so including one+ # would record a transition production would never record.+ checks = tuple(c for c in checks if _detect_broken_filter_config(c.source_config) is None)+ if not checks:+ return SourceBatchEvaluation(outcomes=(), previews=())++ team = Team.objects.filter(id=team_id).first()+ if team is None:+ return SourceBatchEvaluation(outcomes=(), previews=())+ checks = tuple(c for c in checks if not _is_in_quiet_hours(c, team, cutoff))+ if not checks:+ return SourceBatchEvaluation(outcomes=(), previews=())++ # One checkpoint for the pass, matching the production discovery activity. A failure falls+ # back to wall-clock rather than ending the batch.+ try:+ checkpoint = fetch_live_logs_checkpoint(team)+ except Exception as error:+ logger.exception("Failed to fetch logs ingestion checkpoint; falling back to wall-clock", error=str(error))+ checkpoint = None++ cohorts: dict[tuple, list[PlatformAlertCheck]] = {}+ for check in checks:+ cohorts.setdefault(_cohort_key(check, checkpoint, cutoff), []).append(check)++ if len(cohorts) > MAX_COHORTS_PER_CYCLE:+ logger.warning(+ "Truncating logs alert cohorts to keep the batch inside its activity timeout",+ produced=len(cohorts),+ evaluated=MAX_COHORTS_PER_CYCLE,+ )++ outcomes: list[PlatformAlertOutcome] = []+ previews: list[AlertDeliveryPreview] = []+ omitted = 0+ deadline = started_at + BATCH_QUERY_BUDGET_SECONDS+ unqueried = 0+ # Capped the way the production cohort query requires: one batched query carries one countIf+ # column per alert, so an uncapped cohort is an unbounded query.+ chunks = [+ (cohort_key, list(chunk))+ for cohort_key, cohort in list(cohorts.items())[:MAX_COHORTS_PER_CYCLE]+ for chunk in batched(cohort, MAX_ALERT_COHORT_SIZE, strict=False)+ ]+ for cohort_key, chunk in chunks:+ query_seconds = min(MAX_QUERY_SECONDS, int(deadline - time.monotonic()))+ if query_seconds < MIN_QUERY_SECONDS:+ unqueried += len(chunk)+ continue+ for outcome, preview in _evaluate_cohort(team, chunk, cohort_key, now=cutoff, query_seconds=query_seconds):+ if preview is not None and len(previews) >= MAX_PREVIEWS_PER_CYCLE:+ omitted += 1+ continue+ outcomes.append(outcome)+ if preview is not None:+ previews.append(preview)++ if unqueried:+ logger.warning(+ "Left logs alert cohorts unqueried on the batch query budget",+ team_id=team_id,+ slot=slot,+ unqueried=unqueried,+ budget_seconds=BATCH_QUERY_BUDGET_SECONDS,+ )+ if omitted:+ logger.warning(+ "Deferred logs alert deliveries over the batch payload bound",+ team_id=team_id,+ slot=slot,+ delivered=len(previews),+ deferred=omitted,+ )+ safe_record(increment_deliveries_deferred, SourceKind.LOGS.value, omitted)+ safe_record(record_batch_duration, SourceKind.LOGS.value, int((time.monotonic() - started_at) * 1000))+ return SourceBatchEvaluation(outcomes=tuple(outcomes), previews=tuple(previews), omitted=omitted)diff --git a/products/logs/backend/facade/temporal.py b/products/logs/backend/facade/temporal.pyindex ad66dc2e59d2..2e75eccb88c2 100644--- a/products/logs/backend/facade/temporal.py+++ b/products/logs/backend/facade/temporal.py@@ -10,6 +10,7 @@ temporalio-heavy imports here, off the ``facade/api.py`` path.from products.logs.backend.temporal import ACTIVITIES, WORKFLOWSfrom products.logs.backend.temporal.activities import CheckAlertsInput+from products.logs.backend.temporal.alert_evaluate import SOURCE_EVALUATION_ACTIVITIES, SOURCE_EVALUATION_WORKFLOWSfrom products.logs.backend.temporal.constants import SCHEDULE_CRON, SCHEDULE_ID, WORKFLOW_NAMEfrom products.logs.backend.temporal.metrics import (LOGS_ALERTING_COUNT_HISTOGRAM_BUCKETS,@@ -37,6 +38,8 @@ from products.logs.backend.temporal.volume_tick.schedule import create_logs_volu__all__ = ["ACTIVITIES","WORKFLOWS",+ "SOURCE_EVALUATION_ACTIVITIES",+ "SOURCE_EVALUATION_WORKFLOWS","CheckAlertsInput","SCHEDULE_CRON","SCHEDULE_ID",diff --git a/products/logs/backend/management/__init__.py b/products/logs/backend/management/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/logs/backend/management/commands/__init__.py b/products/logs/backend/management/commands/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/logs/backend/management/commands/backfill_platform_alert_configurations.py b/products/logs/backend/management/commands/backfill_platform_alert_configurations.pynew file mode 100644index 000000000000..f25407905eda--- /dev/null+++ b/products/logs/backend/management/commands/backfill_platform_alert_configurations.py@@ -0,0 +1,16 @@+from typing import Any++from django.core.management.base import BaseCommand++from products.logs.backend.platform_alert_backfill import backfill_platform_alert_configurations+++class Command(BaseCommand):+ help = "Copy logs alert configurations into the skeleton shared alert tables."++ def add_arguments(self, parser: Any) -> None:+ parser.add_argument("--team-id", type=int, default=None, help="Copy one team's configurations only.")++ def handle(self, *args: Any, **options: Any) -> None:+ counts = backfill_platform_alert_configurations(team_id=options["team_id"])+ self.stdout.write(f"Created {counts.created}, updated {counts.updated}")diff --git a/products/logs/backend/platform_alert_backfill.py b/products/logs/backend/platform_alert_backfill.pynew file mode 100644index 000000000000..d5db9792b615--- /dev/null+++ b/products/logs/backend/platform_alert_backfill.py@@ -0,0 +1,61 @@+"""One-way copy of logs alert configurations into the skeleton shared tables.++The control plane stays with the logs product: this reads, never writes back, and nothing+keeps the copy in sync afterwards. Run it again to pick up changes.++`legacy_configuration_id` carries the row each copy came from, so a second run updates+rather than duplicates, and a later comparison can line the two stacks up per alert.+"""++import structlog++from posthog.dataclasses import frozen++from products.alerts.backend.facade.contracts import PlatformAlertUpsert, SourceKind+from products.alerts.backend.facade.platform_alerts import upsert_configuration+from products.logs.backend.models import LogsAlertConfiguration++logger = structlog.get_logger(__name__)+++@frozen+class BackfillCounts:+ created: int+ updated: int+++def backfill_platform_alert_configurations(*, team_id: int | None = None) -> BackfillCounts:+ """Copies every logs alert configuration, or one team's."""+ source = LogsAlertConfiguration.objects.all()+ if team_id is not None:+ source = source.filter(team_id=team_id)++ created = 0+ updated = 0+ for configuration in source.iterator():+ was_created = upsert_configuration(+ PlatformAlertUpsert(+ legacy_configuration_id=configuration.id,+ team_id=configuration.team_id,+ name=configuration.name,+ enabled=configuration.enabled,+ source_kind=SourceKind.LOGS,+ source_config=configuration.filters,+ threshold_count=configuration.threshold_count,+ threshold_operator=configuration.threshold_operator,+ window_minutes=configuration.window_minutes,+ check_interval_minutes=configuration.check_interval_minutes,+ evaluation_periods=configuration.evaluation_periods,+ datapoints_to_alarm=configuration.datapoints_to_alarm,+ cooldown_minutes=configuration.cooldown_minutes,+ schedule_restriction=configuration.schedule_restriction,+ next_check_at=configuration.next_check_at,+ )+ )+ if was_created:+ created += 1+ else:+ updated += 1++ logger.info("platform_alert_backfill.complete", created=created, updated=updated, team_id=team_id)+ return BackfillCounts(created=created, updated=updated)diff --git a/products/logs/backend/temporal/alert_evaluate.py b/products/logs/backend/temporal/alert_evaluate.pynew file mode 100644index 000000000000..dc1cd6edba01--- /dev/null+++ b/products/logs/backend/temporal/alert_evaluate.py@@ -0,0 +1,126 @@+"""Temporal wiring for the read-only logs evaluation.++The evaluation itself lives in `products/logs/backend/alert_source_cycle.py`, so it stays a+plain function a test can call without Temporal.+"""++import asyncio+import datetime as dt++from temporalio import activity, workflow+from temporalio.common import RetryPolicy+from temporalio.exceptions import WorkflowAlreadyStartedError++from posthog.temporal.common.base import PostHogWorkflow++with workflow.unsafe.imports_passed_through():+ from django.conf import settings++ from posthog.temporal.common.utils import close_db_connections++ from products.alerts.backend.facade.contracts import (+ RECORD_OUTCOMES_ACTIVITY,+ SourceBatchEvaluation,+ SourceEvaluationInputs,+ SourceOutcomeInputs,+ )++WORKFLOW_NAME = "logs-alert-evaluate"++# Above `BATCH_QUERY_BUDGET_SECONDS`, which is above the cap on any one cohort query. With the+# activity below the query, the activity times out while ClickHouse still runs the query, the+# attempt's thread stays on it, and the retry starts an identical query alongside. The ordering is+# asserted by `test_clickhouse_ends_a_slow_cohort_query_before_the_activity_does`.+EVALUATE_START_TO_CLOSE = dt.timedelta(seconds=30)+# How long the activity may wait for a free slot. Temporal bounds an attempt by whichever of the+# two timeouts expires first, so schedule-to-close is derived rather than set: a literal close to+# start-to-close would let queue time shorten the run below the query budget, which is the+# inversion above arriving by another route on exactly the load that causes queueing.+EVALUATE_QUEUE_TOLERANCE = dt.timedelta(seconds=20)+EVALUATE_SCHEDULE_TO_CLOSE = EVALUATE_START_TO_CLOSE + EVALUATE_QUEUE_TOLERANCE+# One attempt. A second is another full query budget spent on a batch whose keys are still due, so+# 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 the platform's `SOURCE_EVALUATION_TIMEOUT`, which has to hold both+# activities and still leave room to start the delivery children.+EVALUATION_BUDGET = EVALUATE_SCHEDULE_TO_CLOSE + RECORD_SCHEDULE_TO_CLOSE+++@close_db_connections+def evaluate_logs_alerts_activity(inputs: SourceEvaluationInputs) -> SourceBatchEvaluation:+ """Sync, so the thread this blocks is a slot Temporal is accounting for. An async activity+ handing the work to its own thread pool releases its slot the moment the activity times out,+ while the thread stays on the query Temporal can no longer see."""+ # Imported in the activity body, not at module scope. The workflow class below forces+ # this module to evaluate inside Temporal's sandbox, which a Django model import trips.+ from products.logs.backend.alert_source_cycle import evaluate_logs_batch++ return evaluate_logs_batch(+ inputs.batch_key.team_id, inputs.batch_key.slot, dt.datetime.fromisoformat(inputs.cutoff)+ )++[email protected](name=WORKFLOW_NAME)+class LogsAlertEvaluateWorkflow(PostHogWorkflow):+ """Evaluates one batch key, records what it decided, then previews one delivery per+ notification. Writes only the shared platform's own rows: the production logs fleet owns+ the logs tables."""++ inputs_cls = SourceEvaluationInputs++ @workflow.run+ 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 evaluation.outcomes:+ await workflow.execute_activity(+ RECORD_OUTCOMES_ACTIVITY,+ SourceOutcomeInputs(+ team_id=inputs.batch_key.team_id,+ cutoff=inputs.cutoff,+ outcomes=evaluation.outcomes,+ ),+ start_to_close_timeout=RECORD_START_TO_CLOSE,+ schedule_to_close_timeout=RECORD_SCHEDULE_TO_CLOSE,+ retry_policy=RetryPolicy(maximum_attempts=3),+ )++ # The evaluation key names the alert and its window, so a re-run of the same occasion+ # reuses these ids. A reused id raises, so one already-started preview must not stop+ # the rest.+ results = await asyncio.gather(+ *(+ workflow.start_child_workflow(+ "alerts-product-deliver-preview",+ preview,+ id=f"alerts-deliver-preview-{preview.evaluation_key}",+ task_queue=settings.ALERTS_PRODUCT_DELIVERY_TASK_QUEUE,+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,+ execution_timeout=dt.timedelta(minutes=1),+ )+ for preview in evaluation.previews+ ),+ return_exceptions=True,+ )+ started = 0+ for result in results:+ if isinstance(result, WorkflowAlreadyStartedError):+ continue+ if isinstance(result, BaseException):+ raise result+ started += 1+ return started+++SOURCE_EVALUATION_WORKFLOWS = [LogsAlertEvaluateWorkflow]+SOURCE_EVALUATION_ACTIVITIES = [evaluate_logs_alerts_activity]diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.pynew file mode 100644index 000000000000..36f8e86d7366--- /dev/null+++ b/products/logs/backend/test/test_alert_evaluate.py@@ -0,0 +1,177 @@+from datetime import UTC, datetime, timedelta++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.models.scoping import team_scope++from products.alerts.backend.facade.contracts import SourceBatchEvaluation+from products.alerts.backend.facade.platform_alerts import record_outcomes+from products.alerts.backend.facade.temporal import SOURCE_EVALUATION_TIMEOUT+from products.alerts.backend.models import PlatformAlert, PlatformAlertConfiguration+from products.logs.backend.alert_check_query import BatchedBucketedResult, BucketedCount+from products.logs.backend.alert_source_cycle import BATCH_QUERY_BUDGET_SECONDS, MAX_QUERY_SECONDS, evaluate_logs_batch+from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent+from products.logs.backend.temporal.alert_evaluate import (+ EVALUATE_SCHEDULE_TO_CLOSE,+ EVALUATE_START_TO_CLOSE,+ EVALUATION_BUDGET,+)++_MODULE = "products.logs.backend.alert_source_cycle"+_LOGS_OWNED_FIELDS = ("state", "consecutive_failures", "next_check_at", "last_notified_at", "snooze_until")+++class TestLogsAlertEvaluation(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.cutoff = datetime(2026, 9, 16, 10, tzinfo=UTC)++ def _configuration(self, **overrides) -> PlatformAlertConfiguration:+ defaults = {+ "team": self.team,+ "name": "API errors",+ "source_kind": PlatformAlertConfiguration.SourceKind.LOGS,+ "source_config": {},+ "threshold_count": 10,+ "threshold_operator": "above",+ "window_minutes": 5,+ "check_interval_minutes": 10,+ "next_check_at": self.cutoff - timedelta(minutes=1),+ }+ defaults.update(overrides)+ with team_scope(self.team.id):+ return PlatformAlertConfiguration.objects.create(**defaults)++ def _run(self, *configurations: PlatformAlertConfiguration):+ breaching = {str(c.id): [BucketedCount(timestamp=self.cutoff, count=500)] for c in configurations}+ with (+ patch(f"{_MODULE}.fetch_live_logs_checkpoint", return_value=None),+ patch(f"{_MODULE}.BatchedAlertCheckQuery") as query,+ ):+ query.return_value.execute_rolling_checks.return_value = BatchedBucketedResult(+ per_alert=breaching, query_duration_ms=1+ )+ slot = (configurations[0].next_check_at or self.cutoff).replace(second=0, microsecond=0).isoformat()+ return evaluate_logs_batch(self.team.id, slot, self.cutoff), query++ def _record(self, evaluation: SourceBatchEvaluation) -> None:+ """The write the platform's own activity runs after the evaluation returns.++ Deliberately outside `team_scope`: that activity has no ambient scope, and these models+ are fail-closed, so a write here through a bare manager raises.+ """+ record_outcomes(self.team.id, evaluation.outcomes, self.cutoff, team_timezone=self.team.timezone)++ def test_a_breaching_configuration_fires_and_records_its_own_state(self) -> None:+ configuration = self._configuration()++ evaluation, _ = self._run(configuration)+ self._record(evaluation)++ assert [t.notification for preview in evaluation.previews for t in preview.transitions] == ["fire"]+ with team_scope(self.team.id):+ alert = PlatformAlert.objects.get(configuration=configuration, grouping_key="")+ configuration.refresh_from_db()+ assert alert.state == PlatformAlert.State.FIRING+ assert alert.last_notified_at is not None+ # The schedule advanced, so the next tick does not rediscover this configuration.+ assert configuration.next_check_at is not None+ assert configuration.next_check_at > self.cutoff++ def test_a_cohort_query_is_capped_below_the_batch_budget(self) -> None:+ _, query = self._run(self._configuration())++ # An uncapped query runs to the class default, which is above the whole batch's budget.+ capped = query.call_args.kwargs["max_execution_time"]+ assert 0 < capped <= MAX_QUERY_SECONDS++ def test_the_evaluation_writes_nothing_until_its_outcomes_are_recorded(self) -> None:+ configuration = self._configuration()++ evaluation, _ = self._run(configuration)++ assert evaluation.previews+ with team_scope(self.team.id):+ configuration.refresh_from_db()+ assert not PlatformAlert.objects.filter(configuration=configuration).exists()+ assert configuration.next_check_at == self.cutoff - timedelta(minutes=1)++ def test_a_delivery_the_batch_cannot_carry_leaves_its_alert_due(self) -> None:+ configurations = [self._configuration(), self._configuration()]++ with patch(f"{_MODULE}.MAX_PREVIEWS_PER_CYCLE", 1):+ evaluation, _ = self._run(*configurations)+ self._record(evaluation)++ # A firing alert does not fire again, so recording the second outcome would retire its+ # breach with no delivery to announce it.+ assert len(evaluation.previews) == 1+ assert evaluation.omitted == 1+ with team_scope(self.team.id):+ still_due = PlatformAlertConfiguration.objects.filter(+ id__in=[c.id for c in configurations], next_check_at__lte=self.cutoff+ ).count()+ assert still_due == 1++ def test_the_logs_product_rows_are_never_written(self) -> None:+ legacy = LogsAlertConfiguration.objects.create(+ team=self.team,+ name="API errors",+ threshold_count=10,+ threshold_operator="above",+ window_minutes=5,+ filters={},+ next_check_at=self.cutoff - timedelta(minutes=1),+ )+ before = LogsAlertConfiguration.objects.values(*_LOGS_OWNED_FIELDS).get(id=legacy.id)++ evaluation, _ = self._run(self._configuration(legacy_configuration_id=legacy.id))+ self._record(evaluation)++ # The logs fleet evaluates this same alert on its own queue. Writing its rows here would+ # transition an alert twice and notify a person twice for one breach.+ assert LogsAlertConfiguration.objects.values(*_LOGS_OWNED_FIELDS).get(id=legacy.id) == before+ assert not LogsAlertEvent.objects.filter(alert=legacy).exists()++ @parameterized.expand([("single_period", 1, 5), ("three_periods", 3, 25)])+ def test_the_scanned_range_covers_every_rolling_window(+ self, _name: str, evaluation_periods: int, expected_lookback_minutes: int+ ) -> None:+ configuration = self._configuration(evaluation_periods=evaluation_periods, check_interval_minutes=10)++ _, query = self._run(configuration)++ kwargs = query.call_args.kwargs+ assert kwargs["date_to"] - kwargs["date_from"] == timedelta(minutes=expected_lookback_minutes)++ def test_the_evaluation_key_comes_from_the_tick_occasion_not_the_clock(self) -> None:+ configuration = self._configuration(next_check_at=None)++ evaluation, _ = self._run(configuration)++ assert [p.evaluation_key for p in evaluation.previews] == [+ f"{configuration.id}:window:{self.cutoff.isoformat()}"+ ]+++class TestEvaluationTimeoutLadder(SimpleTestCase):+ """Constants only, so this takes no database."""++ def test_the_evaluation_timeout_ladder_holds(self) -> None:+ # Each bound here has been wrong once. The activity sat under the query, and two+ # activities declared eighty seconds inside a forty-second workflow. A timeout that+ # lands between deciding and recording loses a batch that decided to fire, and nothing+ # else in the tree notices.+ # ClickHouse ends a slow query, not the activity timing out with the query still running.+ assert EVALUATE_START_TO_CLOSE.total_seconds() > BATCH_QUERY_BUDGET_SECONDS > MAX_QUERY_SECONDS+ # Temporal bounds an attempt by whichever timeout expires first, so queue time must not be+ # what shortens the run below the query budget.+ assert EVALUATE_SCHEDULE_TO_CLOSE > EVALUATE_START_TO_CLOSE+ 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 > EVALUATION_BUDGET