:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(alerts): bound grouped outcome payloads and split large deliveries (#118166)
Jimmy Zhu1d607b93fe13
diff --git a/products/alerts/backend/platform_source_cycle.py b/products/alerts/backend/platform_source_cycle.pyindex 724aea1f435c..dcffb107f1fd 100644--- a/products/alerts/backend/platform_source_cycle.py+++ b/products/alerts/backend/platform_source_cycle.py@@ -55,6 +55,7 @@ from products.alerts_platform.backend.facade.grouping import (GroupObservation,bounded_grouping_key,decide_groups,+ delivery_parts,is_hashed_grouping_key,)from products.alerts_platform.backend.facade.lifecycle import (@@ -221,6 +222,7 @@ def _delivery(check: PlatformAlertCheckInput, outcome: PlatformAlertOutcome) ->destination_alert_id=legacy_id,event_ids_by_kind=_EVENT_IDS_BY_KIND,overflowed=outcome.overflowed,+ parts=delivery_parts(outcome),)diff --git a/products/alerts/backend/temporal/platform_evaluate.py b/products/alerts/backend/temporal/platform_evaluate.pyindex ff43359a4b15..9ca5c6f8a353 100644--- a/products/alerts/backend/temporal/platform_evaluate.py+++ b/products/alerts/backend/temporal/platform_evaluate.py@@ -32,6 +32,7 @@ with workflow.unsafe.imports_passed_through():SourceKind,SourceOutcomeInputs,)+ from products.alerts_platform.backend.facade.payload import outcome_chunksfrom products.alerts_platform.backend.facade.platform_metrics import increment_checks_unfinished, safe_recordfrom products.alerts_platform.backend.facade.temporal import source_evaluation_timeout, start_deliveries@@ -55,6 +56,8 @@ ADMISSION_POLL_INTERVAL = dt.timedelta(seconds=2)# the batch costs the admission rounds plus one check's budget, not one per check.EVALUATION_BUDGET = PLAN_SCHEDULE_TO_CLOSE + ADMISSION_RUN_BUDGET + CHECK_SCHEDULE_TO_CLOSE + RECORD_SCHEDULE_TO_CLOSE_PATCH_READMISSION = "platform-insight-readmission-2026-10"+# Runs started before it recorded every outcome in one activity, and replay must schedule the same.+_PATCH_CHUNKED_RECORD = "platform-insight-chunked-record-2026-10"@frozen@@ -168,16 +171,20 @@ class InsightAlertPlatformEvaluateWorkflow(PostHogWorkflow):if not outcomes:return 0- await workflow.execute_activity(- RECORD_OUTCOMES_ACTIVITY,- SourceOutcomeInputs(team_id=inputs.batch_key.team_id, cutoff=inputs.cutoff, outcomes=outcomes),- start_to_close_timeout=RECORD_START_TO_CLOSE,- schedule_to_close_timeout=RECORD_SCHEDULE_TO_CLOSE,- retry_policy=RetryPolicy(maximum_attempts=3),- )-- # Started only after the record, because a delivery reads the history row the record writes.- await start_deliveries(deliveries)+ # Each check's result fits a payload on its own, but the batch's together may not. A chunk's+ # deliveries start after its own record, so a later chunk that fails cannot strand them.+ chunks = outcome_chunks(outcomes) if workflow.patched(_PATCH_CHUNKED_RECORD) else [outcomes]+ for chunk in chunks:+ await workflow.execute_activity(+ RECORD_OUTCOMES_ACTIVITY,+ SourceOutcomeInputs(team_id=inputs.batch_key.team_id, cutoff=inputs.cutoff, outcomes=chunk),+ start_to_close_timeout=RECORD_START_TO_CLOSE,+ schedule_to_close_timeout=RECORD_SCHEDULE_TO_CLOSE,+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ # Started only after the record, because a delivery reads the history row the record writes.+ recorded = {str(outcome.configuration_id) for outcome in chunk}+ await start_deliveries([delivery for delivery in deliveries if delivery.configuration_id in recorded])return len(outcomes)async def _plan(diff --git a/products/alerts/backend/test/test_platform_evaluate_workflow.py b/products/alerts/backend/test/test_platform_evaluate_workflow.pyindex 3efe25012b21..4c93d1a4b2a7 100644--- a/products/alerts/backend/test/test_platform_evaluate_workflow.py+++ b/products/alerts/backend/test/test_platform_evaluate_workflow.py@@ -2,11 +2,12 @@ import uuidfrom collections.abc import AsyncIteratorimport pytest+from unittest.mock import patchfrom django.conf import settingsimport pytest_asyncio-from temporalio import activity+from temporalio import activity, converterfrom temporalio.api.enums.v1 import EventTypefrom temporalio.exceptions import ApplicationErrorfrom temporalio.testing import WorkflowEnvironment@@ -109,6 +110,81 @@ async def test_a_check_that_fails_does_not_stop_the_batch_recording_the_rest(envassert child.task_queue == settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE+async def test_a_batch_over_the_payload_budget_records_in_chunks_and_starts_one_delivery_per_check(+ environment: WorkflowEnvironment,+) -> None:+ recorded: list[SourceOutcomeInputs] = []++ @activity.defn(name="plan_platform_insight_round_activity")+ async def plan(inputs: InsightBatchPlanInputs) -> list[str]:+ return list(ADMITTED)++ @activity.defn(name="evaluate_platform_insight_check_activity")+ async def evaluate(inputs: InsightCheckInputs) -> SourceBatchEvaluation | None:+ outcome = PlatformAlertOutcome(+ configuration_id=uuid.UUID(inputs.configuration_id),+ evaluation_key="slot:2026-09-16T10:00:00+00:00",+ consecutive_failures=0,+ groups=(GroupOutcome(grouping_key="", kind=AlertEventKind.FIRING, new_state="firing", notified=True),),+ )+ split = inputs.configuration_id == ADMITTED[0]+ delivery = AlertDeliveryRequest(+ source=SourceKind.INSIGHT,+ team_id=1,+ configuration_id=inputs.configuration_id,+ evaluation_key=outcome.evaluation_key,+ destination_alert_id="legacy-alert",+ event_ids_by_kind={"firing": "$insight_alert_firing"},+ overflowed=3 if split else 0,+ parts=2 if split else 1,+ )+ return SourceBatchEvaluation(outcomes=(outcome,), deliveries=(delivery,))++ @activity.defn(name=RECORD_OUTCOMES_ACTIVITY)+ async def record(inputs: SourceOutcomeInputs) -> int:+ recorded.append(inputs)+ return len(inputs.outcomes)++ async with Worker(+ environment.client,+ task_queue=QUEUE,+ workflows=[InsightAlertPlatformEvaluateWorkflow],+ activities=[plan, evaluate, record],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ # Room for one outcome per record, so two checks need two.+ with patch("products.alerts_platform.backend.facade.payload.MAX_BATCH_PAYLOAD_BYTES", 1):+ handle = await environment.client.start_workflow(+ InsightAlertPlatformEvaluateWorkflow.run,+ SourceEvaluationInputs(+ source=SourceKind.INSIGHT,+ cutoff="2026-09-16T10:00:00+00:00",+ batch_key=AlertBatchKey(team_id=1, slot="2026-09-16T10:00:00+00:00"),+ ),+ id=f"test-{uuid.uuid4()}",+ task_queue=QUEUE,+ )+ result = await handle.result()+ history = await handle.fetch_history()++ assert result == 2+ assert sorted(str(o.configuration_id) for batch in recorded for o in batch.outcomes) == list(ADMITTED)+ assert [len(batch.outcomes) for batch in recorded] == [1, 1]+ started = {}+ for event in history.events:+ if event.event_type == EventType.EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED:+ attributes = event.start_child_workflow_execution_initiated_event_attributes+ (request,) = converter.default().payload_converter.from_payloads(+ attributes.input.payloads, [AlertDeliveryRequest]+ )+ started[attributes.workflow_id] = (request.parts, request.overflowed)+ key = "slot:2026-09-16T10:00:00+00:00"+ assert started == {+ f"alerts-deliver-preview-{ADMITTED[0]}:{key}": (2, 3),+ f"alerts-deliver-preview-{ADMITTED[1]}:{key}": (1, 0),+ }++@pytest.mark.parametrize("fail_second_plan, expected",[diff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.pyindex db5acca29cf5..e82efdc45ead 100644--- a/products/alerts_platform/backend/delivery/evaluation.py+++ b/products/alerts_platform/backend/delivery/evaluation.py@@ -32,12 +32,13 @@ from products.alerts_platform.backend.delivery.webhook import WebhookTransportfrom products.alerts_platform.backend.facade.contracts import (AlertDeliveryRequest,AlertDestinationData,+ AlertEventKind,AnnouncedTransition,DestinationType,EvaluationAnnouncement,IncidentAction,)-from products.alerts_platform.backend.logic.platform_alert_events import announcement+from products.alerts_platform.backend.logic.platform_alert_events import announced_kinds, announcementlogger = structlog.get_logger(__name__)@@ -152,9 +153,22 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:request.evaluation_key,source=request.source,incident_grouping_keys=request.incident_actions.keys(),+ part=request.part,+ parts=request.parts,)if announced is None:return DeliveryOutcome(live=True, sent=0, skipped_without_transport=0)+ notice_keys: dict[str, str] = {}+ if request.parts > 1 and request.overflowed:+ notice_keys = _overflow_notice_keys(+ request,+ announced_kinds(+ request.team_id,+ request.configuration_id,+ request.evaluation_key,+ incident_grouping_keys=request.incident_actions.keys(),+ ),+ )thread_store = DatabaseThreadStore(request.team_id)sent = 0@@ -176,7 +190,10 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:for target in _destinations(request, event_id):overflowed = 0destination = json.dumps(target, sort_keys=True)- if request.overflowed and event_id in message_event_ids and destination not in noticed:+ owns_notice = request.parts <= 1 or any(+ transition.grouping_key == notice_keys.get(destination) for transition in transitions+ )+ if request.overflowed and event_id in message_event_ids and destination not in noticed and owns_notice:overflowed = request.overflowednoticed.add(destination)transport_class = _TRANSPORTS.get(target["type"])@@ -233,6 +250,27 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:return DeliveryOutcome(live=True, sent=sent, skipped_without_transport=skipped)+def _overflow_notice_keys(request: AlertDeliveryRequest, kinds: dict[str, AlertEventKind]) -> dict[str, str]:+ """For each destination, the grouping key whose part tells it about the overflow.++ Read from the kinds of the whole announcement, so every part agrees, and a destination whose+ messages all land in a later part still hears the notice once.+ """+ if not request.sends_messages:+ return {}+ first_by_event_id: dict[str, str] = {}+ for grouping_key, kind in kinds.items():+ event_id = request.event_ids_by_kind.get(kind.value)+ if event_id is not None:+ first_by_event_id[event_id] = min(first_by_event_id.get(event_id, grouping_key), grouping_key)+ keys: dict[str, str] = {}+ for event_id, first in first_by_event_id.items():+ for target in _destinations(request, event_id):+ destination = json.dumps(target, sort_keys=True)+ keys[destination] = min(keys.get(destination, first), first)+ return keys++def _by_subscription(request: AlertDeliveryRequest, announced: EvaluationAnnouncement) -> dict[str, tuple[AnnouncedTransition, ...]]:diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex e660ee8ff8f6..f04d00d3fc3e 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -114,6 +114,9 @@ class OnOverflow(StrEnum):DEFAULT_MAX_INSTANCES: Final = 100+# One check's outcome carries a group per instance, and it crosses Temporal whole, so+# `MAX_BATCH_PAYLOAD_BYTES` is sized to hold this many groups with their keys and labels at full length.+MAX_INSTANCES_CEILING: Final = 100@frozen@@ -139,6 +142,8 @@ class Grouping:raise ValueError("a grouping names each key once")if self.max_instances < 1:raise ValueError("max_instances must be at least 1")+ if self.max_instances > MAX_INSTANCES_CEILING:+ raise ValueError(f"max_instances must be at most {MAX_INSTANCES_CEILING}")@classmethoddef from_stored(cls, stored: Mapping[str, Any]) -> Grouping:@@ -718,6 +723,10 @@ class AlertDeliveryRequest:source_alert_url: str | None = Noneowned_by_platform: bool = Falseoverflowed: int = 0+ # How many activities the delivery workflow splits an evaluation into, by `MAX_TRANSITIONS_PER_DELIVERY`,+ # and which of them one activity sends. The workflow sets `part`.+ parts: int = 1+ part: int = 0@frozendiff --git a/products/alerts_platform/backend/facade/grouping.py b/products/alerts_platform/backend/facade/grouping.pyindex 9f5bf3710516..1c4945caf6e5 100644--- a/products/alerts_platform/backend/facade/grouping.py+++ b/products/alerts_platform/backend/facade/grouping.py@@ -5,8 +5,10 @@ every source, so it lives here once: run the machine per group, leave out a newnothing, put firing groups first, and admit what `max_instances` has room for."""+import json+import mathimport hashlib-from collections.abc import Callable, Sequence+from collections.abc import Callable, Collection, Sequencefrom dataclasses import fieldfrom datetime import datetimefrom typing import Final@@ -15,6 +17,7 @@ from uuid import UUIDfrom posthog.dataclasses import frozenfrom products.alerts_platform.backend.facade.contracts import (+ AlertEventKind,GroupOutcome,InstanceCheckState,PlatformAlertCheckInput,@@ -50,6 +53,61 @@ def is_hashed_grouping_key(key: str) -> bool:return key.startswith(_HASHED_PREFIX)+# A label value can come from ingested data, such as a service name, so its size is the sender's+# choice. Every group's labels cross Temporal on the outcome, and a cap on the count and on each+# encoded size keeps a check's outcome inside `MAX_BATCH_PAYLOAD_BYTES` at `MAX_INSTANCES_CEILING`.+MAX_GROUP_LABELS: Final = 4+# In bytes of the JSON a payload carries, where a non-ASCII character is escaped to up to 12 bytes.+MAX_LABEL_BYTES: Final = 256+_TRUNCATED: Final = "…"+++def _bounded_label(value: str) -> str:+ if _encoded_length(value) <= MAX_LABEL_BYTES:+ return value+ budget = MAX_LABEL_BYTES - _encoded_length(_TRUNCATED)+ kept: list[str] = []+ for char in value:+ budget -= _encoded_length(char)+ if budget < 0:+ break+ kept.append(char)+ return "".join(kept) + _TRUNCATED+++def _encoded_length(value: str) -> int:+ return len(json.dumps(value)) - 2+++def bounded_labels(labels: dict[str, str]) -> dict[str, str]:+ """The labels a group may carry: the first `MAX_GROUP_LABELS`, each name and value cut to size.++ Display only. The grouping key is derived from the full values, so a cut label never merges two groups.+ """+ return {_bounded_label(name): _bounded_label(value) for name, value in list(labels.items())[:MAX_GROUP_LABELS]}+++# One delivery activity sends every message it holds, to every destination, inside its timeout. An+# evaluation with more transitions than this is split into parts that each retry on their own.+MAX_TRANSITIONS_PER_DELIVERY: Final = 5+++def delivery_parts(outcome: PlatformAlertOutcome, incident_grouping_keys: Collection[str] = ()) -> int:+ """How many delivery activities an outcome's transitions need.++ Counts the rows the delivery reads back: every group that announced, every group whose firing+ opened or closed, and a failure.+ """+ transitions = sum(+ 1+ for group in outcome.groups+ if group.kind != AlertEventKind.CHECK or group.grouping_key in incident_grouping_keys+ )+ if outcome.failure is not None and outcome.failure.kind != AlertEventKind.CHECK:+ transitions += 1+ return max(1, math.ceil(transitions / MAX_TRANSITIONS_PER_DELIVERY))++@frozenclass GroupObservation:"""What a source measured for one group. `prior_breached` is newest first, as the machine reads it."""@@ -163,7 +221,7 @@ def decide_groups(notified=outcome.update_last_notified_at,firing_episode=decide_firing_episode(snapshot, outcome, now, policy=policy),value=observation.value,- labels=observation.labels,+ labels=bounded_labels(observation.labels),muted_notification=muted_value(outcome),),)diff --git a/products/alerts_platform/backend/facade/payload.py b/products/alerts_platform/backend/facade/payload.pynew file mode 100644index 000000000000..e0596b7f720a--- /dev/null+++ b/products/alerts_platform/backend/facade/payload.py@@ -0,0 +1,42 @@+"""How much of a batch fits in one Temporal payload.++Temporal rejects an activity input or result above about 2 MiB, and the whole batch fails with it+rather than the part that did not fit. The encryption codec base64-encodes each payload, which+adds a third, so a batch is held to half the limit before encoding.+"""++from collections.abc import Sequence+from typing import Final++import temporalio.converter++from products.alerts_platform.backend.facade.contracts import PlatformAlertOutcome++# Workflow code chunks by it, so a change alters how many activities a replay schedules and needs a patch.+MAX_BATCH_PAYLOAD_BYTES: Final = 1024 * 1024+++def payload_bytes(value: object) -> int:+ """The size of `value` as the default converter encodes it, before the codec."""+ return temporalio.converter.default().payload_converter.to_payloads([value])[0].ByteSize()+++def outcome_chunks(outcomes: Sequence[PlatformAlertOutcome]) -> list[tuple[PlatformAlertOutcome, ...]]:+ """The outcomes in order, cut into runs that each fit the budget.++ An outcome larger than the budget on its own still gets a run of its own, because the source+ already sent it across Temporal as one activity result.+ """+ chunks: list[tuple[PlatformAlertOutcome, ...]] = []+ current: list[PlatformAlertOutcome] = []+ spent = 0+ for outcome in outcomes:+ size = payload_bytes(outcome)+ if current and spent + size > MAX_BATCH_PAYLOAD_BYTES:+ chunks.append(tuple(current))+ current, spent = [], 0+ current.append(outcome)+ spent += size+ if current:+ chunks.append(tuple(current))+ return chunksdiff --git a/products/alerts_platform/backend/logic/platform_alert_events.py b/products/alerts_platform/backend/logic/platform_alert_events.pyindex 11bd456e0ae6..468b8cd87754 100644--- a/products/alerts_platform/backend/logic/platform_alert_events.py+++ b/products/alerts_platform/backend/logic/platform_alert_events.py@@ -149,9 +149,7 @@ def insert_events(team_id: int, rows: Sequence[PlatformAlertEventRow]) -> int:return len(rows)-_ANNOUNCEMENT_SQL = f"""-SELECT grouping_key, kind, episode_started_at, value, labels, condition_snapshot,- source_config_snapshot, error_message, occurred_at, alert_name, consecutive_failures+_ANNOUNCED_ROWS = f"""FROM {PLATFORM_ALERT_EVENTS_TABLE}WHERE team_id = %(team_id)sAND configuration_id = %(configuration_id)s@@ -161,6 +159,25 @@ ORDER BY grouping_key, occurred_at DESCLIMIT 1 BY grouping_key"""+_ANNOUNCEMENT_COLUMNS = """grouping_key, kind, episode_started_at, value, labels, condition_snapshot,+ source_config_snapshot, error_message, occurred_at, alert_name, consecutive_failures"""++_ANNOUNCEMENT_SQL = f"SELECT {_ANNOUNCEMENT_COLUMNS} {_ANNOUNCED_ROWS}"++# Deals the announced groups out by their position in key order, so the parts of one evaluation+# cover every group exactly once, and each part decodes only its own rows.+_ANNOUNCEMENT_PART_SQL = f"""+SELECT {_ANNOUNCEMENT_COLUMNS}+FROM (+ SELECT *, row_number() OVER (ORDER BY grouping_key) - 1 AS position+ FROM ({_ANNOUNCEMENT_SQL})+)+WHERE modulo(position, %(parts)s) = %(part)s+ORDER BY grouping_key+"""++_ANNOUNCED_KINDS_SQL = f"SELECT grouping_key, kind {_ANNOUNCED_ROWS}"+def announcement(team_id: int,@@ -169,6 +186,8 @@ def announcement(*,source: SourceKind,incident_grouping_keys: Collection[str] = (),+ part: int = 0,+ parts: int = 1,) -> EvaluationAnnouncement | None:"""What one evaluation left for a destination to say, or None when it announced nothing.@@ -180,19 +199,21 @@ def announcement(`LIMIT 1 BY grouping_key` is the read's own deduplication. The insert carries a token theengine drops a repeat under, but it only remembers a bounded window of them, so a retry farenough behind writes a second row for a group. The newest is the one this evaluation meant.++ With `parts` above one, only the groups of that `part` come back, and None when it has none."""tag_queries(product=Product.PLATFORM_AND_SUPPORT, feature=Feature.ALERTING)- rows = sync_execute(- _ANNOUNCEMENT_SQL,- {- "team_id": team_id,- "configuration_id": configuration_id,- "evaluation_key": evaluation_key,- "check_kind": AlertEventKind.CHECK.value,- "incident_grouping_keys": list(incident_grouping_keys),- },- team_id=team_id,- )+ parameters: dict[str, Any] = {+ "team_id": team_id,+ "configuration_id": configuration_id,+ "evaluation_key": evaluation_key,+ "check_kind": AlertEventKind.CHECK.value,+ "incident_grouping_keys": list(incident_grouping_keys),+ }+ if parts > 1:+ rows = sync_execute(_ANNOUNCEMENT_PART_SQL, {**parameters, "part": part, "parts": parts}, team_id=team_id)+ else:+ rows = sync_execute(_ANNOUNCEMENT_SQL, parameters, team_id=team_id)if not rows:return None@@ -222,6 +243,29 @@ def announcement()+def announced_kinds(+ team_id: int,+ configuration_id: str,+ evaluation_key: str,+ *,+ incident_grouping_keys: Collection[str] = (),+) -> dict[str, AlertEventKind]:+ """The kind of every group `announcement` returns across all parts, without the rows' payloads."""+ tag_queries(product=Product.PLATFORM_AND_SUPPORT, feature=Feature.ALERTING)+ rows = sync_execute(+ _ANNOUNCED_KINDS_SQL,+ {+ "team_id": team_id,+ "configuration_id": configuration_id,+ "evaluation_key": evaluation_key,+ "check_kind": AlertEventKind.CHECK.value,+ "incident_grouping_keys": list(incident_grouping_keys),+ },+ team_id=team_id,+ )+ return {grouping_key: AlertEventKind(kind) for grouping_key, kind in rows}++def _snapshot(raw: str) -> dict[str, Any]:"""A snapshot column the writer may have left empty, or that predates the field it holds."""if not raw:diff --git a/products/alerts_platform/backend/temporal/workflows.py b/products/alerts_platform/backend/temporal/workflows.pyindex 15808bd15943..380356cd6143 100644--- a/products/alerts_platform/backend/temporal/workflows.py+++ b/products/alerts_platform/backend/temporal/workflows.py@@ -163,13 +163,31 @@ class AlertsPlatformDeliverPreviewWorkflow(PostHogWorkflow):@workflow.runasync def run(self, inputs: AlertDeliveryRequest) -> None:+ """Delivers each part in turn, so a split evaluation's sends to one destination never overlap.++ A part that fails does not stop the parts after it. The first failure fails the run once+ every part has had its attempts.+ """+ if inputs.parts <= 1:+ await self._deliver(inputs)+ return+ failures: list[ActivityError] = []+ for part in range(inputs.parts):+ try:+ await self._deliver(replace(inputs, part=part))+ except ActivityError as error:+ failures.append(error)+ if failures:+ raise failures[0]++ async def _deliver(self, request: AlertDeliveryRequest) -> None:busy_deadline: dt.datetime | None = Nonewhile True:started_at = workflow.now()try:await workflow.execute_activity(alerts_platform_deliver_preview_activity,- inputs,+ request,start_to_close_timeout=DELIVERY_START_TO_CLOSE,schedule_to_close_timeout=DELIVERY_SCHEDULE_TO_CLOSE,retry_policy=RetryPolicy(maximum_attempts=3),@@ -193,6 +211,9 @@ async def start_deliveries(deliveries: Sequence[AlertDeliveryRequest]) -> int:key names a window or a slot but not the alert, so two alerts in one slot do not collide. Are-run of the same occasion reuses the ids, and a reused id raises, so one delivery alreadystarted does not stop the rest.++ A request split into parts still starts one workflow, which delivers the parts in turn, so its+ deadline is one part's times the count."""results = await asyncio.gather(*(@@ -202,7 +223,7 @@ async def start_deliveries(deliveries: Sequence[AlertDeliveryRequest]) -> int:id=f"alerts-deliver-preview-{delivery.configuration_id}:{delivery.evaluation_key}",task_queue=settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,parent_close_policy=workflow.ParentClosePolicy.ABANDON,- execution_timeout=DELIVERY_EXECUTION_TIMEOUT,+ execution_timeout=DELIVERY_EXECUTION_TIMEOUT * max(1, delivery.parts),)for delivery in deliveries),diff --git a/products/alerts_platform/backend/tests/test_delivery_evaluation.py b/products/alerts_platform/backend/tests/test_delivery_evaluation.pyindex 0636ade4bc1c..ca19e7e67aab 100644--- a/products/alerts_platform/backend/tests/test_delivery_evaluation.py+++ b/products/alerts_platform/backend/tests/test_delivery_evaluation.py@@ -91,6 +91,8 @@ def _request(incident_actions: dict[str, IncidentAction] | None = None,owned_by_platform: bool = False,overflowed: int = 0,+ parts: int = 1,+ part: int = 0,) -> AlertDeliveryRequest:return AlertDeliveryRequest(source=SourceKind.LOGS,@@ -104,6 +106,8 @@ def _request(event_ids_by_incident_action={"trigger": OPENED_EVENT, "resolve": CLOSED_EVENT},owned_by_platform=owned_by_platform,overflowed=overflowed,+ parts=parts,+ part=part,)@@ -150,6 +154,9 @@ class TestDeliverEvaluation(APIBaseTest):incident_actions: dict[str, IncidentAction] | None = None,owned_by_platform: bool = False,overflowed: int = 0,+ parts: int = 1,+ part: int = 0,+ kinds: dict[str, AlertEventKind] | None = None,) -> Any:def groups(*, team_id: int, alert_id: str, allowed_event_ids: list[str]) -> list[AlertDestinationGroup]:return by_event.get(allowed_event_ids[0], [])@@ -160,6 +167,7 @@ class TestDeliverEvaluation(APIBaseTest):**({"side_effect": live} if isinstance(live, Exception) else {"return_value": live}),),patch(f"{_MODULE}.announcement", return_value=announced),+ patch(f"{_MODULE}.announced_kinds", return_value=kinds or {}),patch(f"{_MODULE}.list_alert_destination_groups", side_effect=groups),patch(f"{_MODULE}.DatabaseThreadStore"),patch.dict(@@ -178,6 +186,8 @@ class TestDeliverEvaluation(APIBaseTest):incident_actions=incident_actions,owned_by_platform=owned_by_platform,overflowed=overflowed,+ parts=parts,+ part=part,))@@ -215,6 +225,36 @@ class TestDeliverEvaluation(APIBaseTest):]assert len(overflow_notices) == 1+ def test_each_destination_hears_the_overflow_once_across_the_parts_of_a_split_delivery(self) -> None:+ # Sorted by key, the firing lands in part 0 and the resolve in part 1, so a destination+ # that asked only for resolves sends nothing from part 0.+ by_part = [_transition(AlertEventKind.FIRING, "checkout"), _transition(AlertEventKind.RESOLVED, "search")]+ fires_only = cast(AlertDestinationData, {**SLACK, "slack_channel_id": "C-fires"})+ resolves_only = cast(AlertDestinationData, {**SLACK, "slack_channel_id": "C-resolves"})++ notices: list[str] = []+ for part in range(2):+ RecordingTransport.sends = []+ self._run(+ _announcement(by_part[part]),+ {+ FIRING_EVENT: [_group(fires_only), _group(SLACK)],+ RESOLVED_EVENT: [_group(resolves_only), _group(SLACK)],+ },+ overflowed=3,+ parts=2,+ part=part,+ kinds={transition.grouping_key: transition.kind for transition in by_part},+ )+ notices += [+ channel+ for channel, m in RecordingTransport.sends+ for detail in m.details+ if detail.label == "Untracked groups"+ ]++ assert sorted(notices) == ["C-1", "C-fires", "C-resolves"]+def test_a_delivery_that_exists_only_for_its_incident_sends_no_message(self) -> None:# Even a kind its destinations subscribe to reaches none of them when the source announced nothing.outcome = self._run(diff --git a/products/alerts_platform/backend/tests/test_platform_announcement.py b/products/alerts_platform/backend/tests/test_platform_announcement.pyindex 05b8c187b35f..db8d6269a3c5 100644--- a/products/alerts_platform/backend/tests/test_platform_announcement.py+++ b/products/alerts_platform/backend/tests/test_platform_announcement.py@@ -144,3 +144,22 @@ class TestAnnouncement(ClickhouseTestMixin, APIBaseTest):assert result is not Noneassert [t.kind for t in result.transitions] == [AlertEventKind.FIRING]++ def test_the_parts_of_a_split_delivery_read_each_group_once(self) -> None:+ keys = [f"service-{index}" for index in range(7)]+ insert_events(+ self.team.id,+ [self._row(grouping_key=key) for key in reversed(keys)]+ + [self._row(grouping_key="quiet", kind=AlertEventKind.CHECK)],+ )++ by_part = []+ for part in range(3):+ result = announcement(+ self.team.id, str(self.configuration.id), "eval-1", source=SourceKind.LOGS, part=part, parts=3+ )+ assert result is not None+ by_part.append([t.grouping_key for t in result.transitions])++ assert sorted(key for keys_in_part in by_part for key in keys_in_part) == keys+ assert [len(keys_in_part) for keys_in_part in by_part] == [3, 2, 2]diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.pyindex dc9e07b8d1e1..5478513525d7 100644--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py@@ -22,6 +22,7 @@ from products.alerts_platform.backend.facade.api import (upsert_configuration,)from products.alerts_platform.backend.facade.contracts import (+ MAX_INSTANCES_CEILING,AlertEventKind,CheckFailure,FiringEpisode,@@ -38,6 +39,14 @@ from products.alerts_platform.backend.facade.contracts import (SourceKind,)from products.alerts_platform.backend.facade.enums import PlatformAlertOwner, PlatformAlertState+from products.alerts_platform.backend.facade.grouping import (+ MAX_TRANSITIONS_PER_DELIVERY,+ GroupObservation,+ decide_groups,+ delivery_parts,+)+from products.alerts_platform.backend.facade.lifecycle import LOGS_ALERT_POLICY, AlertSnapshot, AlertState+from products.alerts_platform.backend.facade.payload import MAX_BATCH_PAYLOAD_BYTES, payload_bytesfrom products.alerts_platform.backend.logic.platform_lifecycle import CONFIGURATION_ROW_ALERT_IDfrom products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfigurationfrom products.alerts_platform.backend.models.platform_alert_events_sql import SHARDED_PLATFORM_ALERT_EVENTS_TABLE@@ -793,6 +802,7 @@ def test_a_check_admits_existing_groups_and_new_ones_up_to_the_cap({"mode": GroupingMode.BY_RESULT_LABELS, "keys": ()},{"mode": GroupingMode.BY_RESULT_LABELS, "keys": ("service", "service")},{"mode": GroupingMode.BY_RESULT_LABELS, "keys": ("service",), "max_instances": 0},+ {"mode": GroupingMode.BY_RESULT_LABELS, "keys": ("service",), "max_instances": MAX_INSTANCES_CEILING + 1},],)def test_a_grouping_rejects_keys_its_mode_cannot_use(fields: dict[str, Any]) -> None:@@ -818,3 +828,79 @@ def test_an_outcome_rejects_an_invalid_shape(overrides: dict[str, Any]) -> None:fields.update(overrides)with pytest.raises(ValueError):PlatformAlertOutcome(**fields)+++def test_a_full_grouped_check_with_hostile_labels_fits_one_payload() -> None:+ check = PlatformAlertCheckInput(+ id=uuid4(),+ team_id=1,+ name="API errors",+ source_config={},+ check_interval_minutes=5,+ evaluation_periods=1,+ datapoints_to_alarm=1,+ cooldown_minutes=0,+ schedule_restriction=None,+ next_check_at=None,+ consecutive_failures=0,+ legacy_configuration_id=None,+ check_status="ok",+ snooze_until=None,+ grouping=Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service",), max_instances=MAX_INSTANCES_CEILING),+ )+ # Astral characters escape to 12 bytes each in a payload, the most a character can cost.+ hostile = "\U0001f600" * 32 * 1024+ observations = [+ GroupObservation(+ grouping_key=f"{index:03d}" + "\U0001f600" * 252,+ current_breached=True,+ value=1.0,+ labels={f"{name}{hostile}": hostile for name in range(10)},+ )+ for index in range(MAX_INSTANCES_CEILING)+ ]++ decision = decide_groups(+ check,+ observations,+ snapshot_of=lambda instance, prior: AlertSnapshot(+ state=AlertState(instance.state),+ cooldown=timedelta(0),+ last_notified_at=None,+ snooze_until=None,+ consecutive_failures=0,+ ),+ policy=LOGS_ALERT_POLICY,+ now=datetime(2026, 10, 15, tzinfo=UTC),+ )+ outcome = decision.as_outcome(configuration_id=check.id, evaluation_key="window:x", query_duration_ms=1)++ assert len(outcome.groups) == MAX_INSTANCES_CEILING+ assert payload_bytes(outcome) < MAX_BATCH_PAYLOAD_BYTES+++ "kinds, incident_keys, failure, expected",+ [+ ((AlertEventKind.FIRING,), (), None, 1),+ ((AlertEventKind.FIRING,) * (MAX_TRANSITIONS_PER_DELIVERY + 1), (), None, 2),+ ((AlertEventKind.CHECK,) * (MAX_TRANSITIONS_PER_DELIVERY * 3), (), None, 1),+ ((AlertEventKind.CHECK,) * (MAX_TRANSITIONS_PER_DELIVERY + 1), ("0", "1", "2", "3", "4", "5"), None, 2),+ ((), (), CheckFailure(kind=AlertEventKind.ERRORED, new_state="errored", notified=True), 1),+ ],+)+def test_an_outcome_splits_its_delivery_by_the_transitions_it_announces(+ kinds: tuple[AlertEventKind, ...], incident_keys: tuple[str, ...], failure: CheckFailure | None, expected: int+) -> None:+ outcome = PlatformAlertOutcome(+ configuration_id=uuid4(),+ evaluation_key="window:x",+ consecutive_failures=0,+ groups=tuple(+ GroupOutcome(grouping_key=str(index), kind=kind, new_state="firing", notified=True)+ for index, kind in enumerate(kinds)+ ),+ failure=failure,+ )++ assert delivery_parts(outcome, incident_keys) == expecteddiff --git a/products/alerts_platform/backend/tests/test_temporal_workflows.py b/products/alerts_platform/backend/tests/test_temporal_workflows.pyindex a87865c2d6c0..b87d2f77cc34 100644--- a/products/alerts_platform/backend/tests/test_temporal_workflows.py+++ b/products/alerts_platform/backend/tests/test_temporal_workflows.py@@ -369,6 +369,47 @@ async def test_delivery_waits_out_a_held_thread_and_fails_when_it_never_frees(assert attempts[-1] - attempts[0] >= PENDING_CLAIM_TTL+async def test_a_split_delivery_sends_every_part_in_turn_even_after_one_fails(+ environment: WorkflowEnvironment,+) -> None:+ sent_parts: list[int] = []++ @activity.defn(name="alerts_platform_deliver_preview_activity")+ async def deliver(request: AlertDeliveryRequest) -> None:+ sent_parts.append(request.part)+ if request.part == 0:+ raise ApplicationError("channel refused", non_retryable=True)++ async with Worker(+ environment.client,+ task_queue=settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,+ workflows=DELIVERY_WORKFLOWS,+ activities=[deliver],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ handle = await environment.client.start_workflow(+ "alerts-platform-deliver-preview",+ AlertDeliveryRequest(+ source=SourceKind.LOGS,+ team_id=1,+ configuration_id="cfg-1",+ evaluation_key="eval-1",+ destination_alert_id="legacy-1",+ event_ids_by_kind={},+ parts=3,+ ),+ id=str(uuid.uuid4()),+ task_queue=settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,+ execution_timeout=DELIVERY_EXECUTION_TIMEOUT * 3,+ )+ with pytest.raises(WorkflowFailureError) as failure:+ await handle.result()++ assert isinstance(failure.value.cause, ActivityError)+ assert sent_parts == [0, 1, 2]++@pytest.mark.parametrize("timeout_type", [TimeoutType.START_TO_CLOSE, TimeoutType.SCHEDULE_TO_CLOSE])async def test_probe_timeout_still_starts_independent_delivery(environment: WorkflowEnvironment,diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.pyindex a9c9885bfb04..49fe4bdf62ce 100644--- a/products/logs/backend/alert_source_cycle.py+++ b/products/logs/backend/alert_source_cycle.py@@ -52,6 +52,7 @@ from products.alerts_platform.backend.facade.grouping import (GroupObservation,bounded_grouping_key,decide_groups,+ delivery_parts,is_hashed_grouping_key,muted_value,)@@ -70,6 +71,7 @@ from products.alerts_platform.backend.facade.lifecycle import (decide_incident_action,evaluate_alert_check,)+from products.alerts_platform.backend.facade.payload import MAX_BATCH_PAYLOAD_BYTES, payload_bytesfrom products.alerts_platform.backend.facade.platform_metrics import (increment_checks,increment_checks_deferred,@@ -465,6 +467,7 @@ def _request(else None,owned_by_platform=check.owned_by_platform,overflowed=recorded.overflowed,+ parts=delivery_parts(recorded, actions),)@@ -890,29 +893,53 @@ def _triage(checks: Sequence[PlatformAlertCheckInput], *, now: datetime, tz_namedef _collect(decided: Sequence[Decision], team_id: int, slot: str, started_at: float) -> SourceBatchEvaluation:- """Applies the payload bound and reports the batch."""+ """Applies the payload bounds and reports the batch.++ A check that does not fit is left out with its delivery, so it keeps its due time and a later+ tick evaluates it again. The byte budget counts every check, including one with no delivery,+ because a grouped check's outcome grows with its groups whether or not it announces.+ """outcomes: list[PlatformAlertOutcome] = []deliveries: list[AlertDeliveryRequest] = []- omitted = 0+ deferred_deliveries = 0+ deferred_checks = 0+ spent = 0for outcome, delivery in decided:if delivery is not None and len(deliveries) >= MAX_DELIVERIES_PER_CYCLE:- omitted += 1+ deferred_deliveries += 1continue+ size = payload_bytes(outcome) + (payload_bytes(delivery) if delivery is not None else 0)+ if spent + size > MAX_BATCH_PAYLOAD_BYTES:+ deferred_checks += 1+ continue+ spent += sizeoutcomes.append(outcome)if delivery is not None:deliveries.append(delivery)- if omitted:+ if deferred_deliveries:logger.warning("Deferred logs alert deliveries over the batch payload bound",team_id=team_id,slot=slot,delivered=len(deliveries),- deferred=omitted,+ deferred=deferred_deliveries,+ )+ safe_record(increment_deliveries_deferred, SourceKind.LOGS.value, deferred_deliveries)+ if deferred_checks:+ logger.warning(+ "Deferred logs alert checks over the batch payload byte budget",+ team_id=team_id,+ slot=slot,+ recorded=len(outcomes),+ deferred=deferred_checks,+ budget_bytes=MAX_BATCH_PAYLOAD_BYTES,)- safe_record(increment_deliveries_deferred, SourceKind.LOGS.value, omitted)+ safe_record(increment_checks_deferred, SourceKind.LOGS.value, deferred_checks)safe_record(record_batch_duration, SourceKind.LOGS.value, int((time.monotonic() - started_at) * 1000))- return SourceBatchEvaluation(outcomes=tuple(outcomes), deliveries=tuple(deliveries), omitted=omitted)+ return SourceBatchEvaluation(+ outcomes=tuple(outcomes), deliveries=tuple(deliveries), omitted=deferred_deliveries + deferred_checks+ )def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatchEvaluation:diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.pyindex 8f3c9ba31a09..cd98b07cbfa8 100644--- a/products/logs/backend/test/test_alert_evaluate.py+++ b/products/logs/backend/test/test_alert_evaluate.py@@ -254,20 +254,28 @@ class TestLogsAlertEvaluation(APIBaseTest):assert platform_testing.alert_for(configuration.id) is Noneassert configuration.next_check_at == self.cutoff - timedelta(minutes=1)- def test_a_delivery_the_batch_cannot_carry_leaves_its_alert_due(self) -> None:+ @parameterized.expand(+ [+ # A firing alert does not fire again, so recording the second outcome would retire its+ # breach with no delivery to announce it.+ ("over_the_delivery_cap", "MAX_DELIVERIES_PER_CYCLE", 1, 500, 1, 1),+ # A quiet check announces nothing and still costs bytes, so the budget counts it too.+ ("over_the_byte_budget", "MAX_BATCH_PAYLOAD_BYTES", 1, 0, 0, 2),+ ]+ )+ def test_a_check_the_batch_cannot_carry_leaves_its_alert_due(+ self, _name: str, bound: str, limit: int, count: int, delivered: int, omitted: int+ ) -> None:configurations = [self._configuration(), self._configuration()]- with patch(f"{_MODULE}.MAX_DELIVERIES_PER_CYCLE", 1):- evaluation, _ = self._run(*configurations)+ with patch(f"{_MODULE}.{bound}", limit):+ evaluation, _ = self._run(*configurations, count=count)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.deliveries) == 1- assert evaluation.omitted == 1+ assert (len(evaluation.deliveries), evaluation.omitted) == (delivered, omitted)with team_scope(self.team.id):still_due = platform_testing.count_still_due([c.id for c in configurations], at=self.cutoff)- assert still_due == 1+ assert still_due == omitteddef test_two_scheduled_checks_clamped_to_one_window_keep_distinct_keys(self) -> None:# `resolve_alert_date_to` clamps the window end to the ingestion checkpoint, so a