: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(ingestion): add investigation context to acceptance test alerts (#90624)
Nick Best1066505935e2
diff --git a/posthog/temporal/ingestion_acceptance_test/README.md b/posthog/temporal/ingestion_acceptance_test/README.mdindex d1030cf8ce29..edef427b4d30 100644--- a/posthog/temporal/ingestion_acceptance_test/README.md+++ b/posthog/temporal/ingestion_acceptance_test/README.md@@ -85,14 +85,18 @@ class TestExample(AcceptanceTest):All configuration is loaded from environment variables with the `INGESTION_ACCEPTANCE_TEST_` prefix:-| Variable | Required | Default | Description |-| ----------------------- | -------- | ------- | ------------------------------------------------- |-| `API_HOST` | Yes | - | PostHog API host (e.g., `https://us.posthog.com`) |-| `PROJECT_API_KEY` | Yes | - | Project token for capturing events |-| `TEAM_ID` | Yes | - | Team ID for ClickHouse queries |-| `EVENT_TIMEOUT_SECONDS` | No | 90 | Max time to wait for events to appear |-| `POLL_INTERVAL_SECONDS` | No | 10.0 | Interval between query attempts |-| `SLACK_WEBHOOK_URL` | No | - | Slack incoming webhook for failure notifications |+| Variable | Required | Default | Description |+| ----------------------- | -------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |+| `API_HOST` | Yes | - | PostHog API host (e.g., `https://us.posthog.com`) |+| `PROJECT_API_KEY` | Yes | - | Project token for capturing events |+| `TEAM_ID` | Yes | - | Team ID for ClickHouse queries |+| `EVENT_TIMEOUT_SECONDS` | No | 90 | Max time to wait for events to appear |+| `POLL_INTERVAL_SECONDS` | No | 10.0 | Interval between query attempts |+| `SLACK_WEBHOOK_URL` | No | - | Slack incoming webhook for failure notifications |+| `ENVIRONMENT` | No | derived | Deployment name in alerts (`prod-us`, `prod-eu`, `dev`); derived from `API_HOST` |+| `GRAFANA_URL` | No | derived | Grafana base URL for the Loki link; `https://grafana.<environment>.posthog.dev` for `prod-us`, `prod-eu`, `dev` |+| `LOKI_DATASOURCE_UID` | No | `P44D702D3E93867EC` | Loki datasource UID used in the Grafana Explore link |+| `RUNBOOK_URL` | No | [ingestion-acceptance-test](https://runbooks.posthog.com/services/ingestion/runbooks/ingestion-acceptance-test) | Runbook link included in alerts |## Running Locally@@ -145,8 +149,23 @@ Event queries include a timestamp filter (`timestamp >= test_start_date - 1 day`## Notifications-Slack notifications are sent only when tests fail or error. Successful runs are silent to avoid noise. The notification includes:+Slack notifications are sent only when tests fail or error. Successful runs are silent to avoid noise. The notification is shaped so a person or SherlockHog can start investigating from the message alone:- Pass/fail/error counts-- Failed test names with error messages-- Environment info (API host, project ID, duration)+- Per failed test: a failure class, the exception type and message, and the events the test sent (uuid, event name, distinct_id)+- `Environment:` / `Severity:` / `Team:` / `Lane:` / `Project:` / `Failure class:` metadata lines+- Links to the Temporal run, the worker logs in Loki, and the runbook when configured++Failure classes:++| Class | Meaning | Start looking at |+| ------------------ | ----------------------------------------------------------------- | --------------------------------------------------------------- |+| `connection_error` | The test could not reach ClickHouse or the API | The harness and ClickHouse offline health |+| `event_missing` | An event was accepted by capture but never appeared in ClickHouse | Ingestion, then the ClickHouse write path for the event's shard |+| `person_missing` | A person never appeared in ClickHouse | Person processing |+| `assertion` | Data was found but did not match | The test and recent ingestion changes |+| `error` | Any other exception in the test | The traceback in the Temporal run |++The suite-level class is the most serious one present. `connection_error` and `error` are reported as `Severity: warning`; the others as `critical`.++The timeout alert classifies the run by what the still-running tests were waiting for: an event poll gives `event_missing`, a person poll `person_missing`, and no pending poll `error`.diff --git a/posthog/temporal/ingestion_acceptance_test/activities.py b/posthog/temporal/ingestion_acceptance_test/activities.pyindex b7fc929571af..8f5335e48966 100644--- a/posthog/temporal/ingestion_acceptance_test/activities.py+++ b/posthog/temporal/ingestion_acceptance_test/activities.py@@ -3,6 +3,8 @@import asynciofrom concurrent.futures import ThreadPoolExecutor+from django.conf import settings+import structlogimport posthoganalyticsimport temporalio.activity@@ -11,13 +13,31 @@ from posthog.temporal.ingestion_acceptance_test.client import PostHogClientfrom posthog.temporal.ingestion_acceptance_test.config import load_configfrom posthog.temporal.ingestion_acceptance_test.results import TestSuiteResultfrom posthog.temporal.ingestion_acceptance_test.runner import RunningTests, run_tests-from posthog.temporal.ingestion_acceptance_test.slack import send_slack_notification, send_slack_timeout_notification+from posthog.temporal.ingestion_acceptance_test.slack import (+ RunContext,+ send_slack_notification,+ send_slack_timeout_notification,+)from posthog.temporal.ingestion_acceptance_test.test_cases_discovery import discover_testsfrom posthog.temporal.ingestion_acceptance_test.types import IngestionAcceptanceTestInputlogger = structlog.get_logger(__name__)+def _current_run_context() -> RunContext | None:+ if not temporalio.activity.in_activity():+ return None+ info = temporalio.activity.info()+ if not (info.workflow_id and info.workflow_run_id and info.workflow_namespace):+ return None+ return RunContext(+ workflow_id=info.workflow_id,+ workflow_run_id=info.workflow_run_id,+ namespace=info.workflow_namespace,+ temporal_ui_host=settings.TEMPORAL_UI_HOST,+ )++@temporalio.activity.defnasync def run_ingestion_acceptance_tests(inputs: IngestionAcceptanceTestInput) -> dict:"""Run ingestion acceptance tests and return results.@@ -32,6 +52,8 @@ async def run_ingestion_acceptance_tests(inputs: IngestionAcceptanceTestInput) -- INGESTION_ACCEPTANCE_TEST_POLL_INTERVAL_SECONDS (optional, default 10.0)- INGESTION_ACCEPTANCE_TEST_ACTIVITY_TIMEOUT_SECONDS (optional, default 3600)- INGESTION_ACCEPTANCE_TEST_SLACK_WEBHOOK_URL (optional, for Slack notifications)+ - INGESTION_ACCEPTANCE_TEST_ENVIRONMENT, _GRAFANA_URL, _LOKI_DATASOURCE_UID,+ _RUNBOOK_URL (optional, enrich the Slack notification with links)Returns:Dict containing test results with summary, individual test outcomes,@@ -55,6 +77,7 @@ async def run_ingestion_acceptance_tests(inputs: IngestionAcceptanceTestInput) -sync_mode=True,)+ run_context = _current_run_context()tests = discover_tests()client = PostHogClient(config, posthog_sdk)running_tests = RunningTests()@@ -66,7 +89,7 @@ async def run_ingestion_acceptance_tests(inputs: IngestionAcceptanceTestInput) -)except TimeoutError:still_running = running_tests.snapshot_with_polls(client)- send_slack_timeout_notification(config, running_tests=still_running)+ send_slack_timeout_notification(config, running_tests=still_running, run_context=run_context)raisefinally:executor.shutdown(wait=False, cancel_futures=True)@@ -80,6 +103,6 @@ async def run_ingestion_acceptance_tests(inputs: IngestionAcceptanceTestInput) -success=result.success,)- send_slack_notification(config, result)+ send_slack_notification(config, result, run_context=run_context)return result.to_dict()diff --git a/posthog/temporal/ingestion_acceptance_test/client.py b/posthog/temporal/ingestion_acceptance_test/client.pyindex b9eebaf71427..aba1b3ef3ec5 100644--- a/posthog/temporal/ingestion_acceptance_test/client.py+++ b/posthog/temporal/ingestion_acceptance_test/client.py@@ -16,6 +16,7 @@ from clickhouse_driver.errors import ErrorCodesfrom posthog.clickhouse.client.execute import sync_executefrom posthog.errors import InternalCHQueryErrorfrom posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut+from posthog.temporal.ingestion_acceptance_test.results import CapturedEventReffrom .config import Config@@ -86,6 +87,20 @@ class PostHogClient:self._test_start_date = (datetime.now(UTC) - timedelta(days=1)).date()self._pending_polls: dict[int, str] = {}self._pending_polls_lock = threading.Lock()+ # Keyed by thread ID: each test runs in its own thread, so this is the+ # per-test list of events the test sent (see take_captured_events).+ self._captured_events: dict[int, list[CapturedEventRef]] = {}+ self._captured_events_lock = threading.Lock()++ def _record_captured(self, event_uuid: str, event_name: str, distinct_id: str) -> None:+ ref = CapturedEventRef(uuid=event_uuid, event=event_name, distinct_id=distinct_id)+ with self._captured_events_lock:+ self._captured_events.setdefault(threading.get_ident(), []).append(ref)++ def take_captured_events(self) -> list[CapturedEventRef]:+ """Return and clear the events captured by the calling thread's test."""+ with self._captured_events_lock:+ return self._captured_events.pop(threading.get_ident(), [])def _retry_on_error(self, fn: Callable[[], T], description: str) -> T:"""Retry a function on transient errors with exponential backoff.@@ -145,6 +160,7 @@ class PostHogClient:)logger.info("Event captured", event_uuid=event_uuid)+ self._record_captured(event_uuid, event_name, distinct_id)return event_uuid@@ -164,6 +180,7 @@ class PostHogClient:description=f"alias {alias} -> {distinct_id}",)logger.info("Alias created", alias=alias, distinct_id=distinct_id, event_uuid=event_uuid)+ self._record_captured(event_uuid, "$create_alias", distinct_id)return event_uuiddef merge_dangerously(self, merge_into_distinct_id: str, merge_from_distinct_id: str) -> str:@@ -202,6 +219,7 @@ class PostHogClient:)logger.info("Merge event captured", event_uuid=event_uuid)+ self._record_captured(event_uuid, "$merge_dangerously", merge_into_distinct_id)return event_uuiddiff --git a/posthog/temporal/ingestion_acceptance_test/config.py b/posthog/temporal/ingestion_acceptance_test/config.pyindex 52b08a201158..a0da3f517dcc 100644--- a/posthog/temporal/ingestion_acceptance_test/config.py+++ b/posthog/temporal/ingestion_acceptance_test/config.py@@ -28,16 +28,40 @@ class Config(BaseSettings):poll_interval_seconds: float = Field(default=10.0)activity_timeout_seconds: int = Field(default=3600)slack_webhook_url: str | None = Field(default=None)+ # Deployment name used in alert metadata and Grafana links. Derived from+ # api_host when unset.+ environment: str | None = Field(default=None)+ grafana_url: str | None = Field(default=None)+ loki_datasource_uid: str = Field(default="P44D702D3E93867EC")+ runbook_url: str | None = Field(+ default="https://runbooks.posthog.com/services/ingestion/runbooks/ingestion-acceptance-test"+ )@field_validator("api_host")@classmethoddef strip_trailing_slash(cls, v: str) -> str:return v.rstrip("/")+ @property+ def environment_name(self) -> str:+ if self.environment:+ return self.environment+ return _environment_from_api_host(self.api_host)++ @property+ def grafana_base_url(self) -> str | None:+ if self.grafana_url:+ return self.grafana_url.rstrip("/")+ env = self.environment_name+ if env in _KNOWN_ENVIRONMENTS:+ return f"https://grafana.{env}.posthog.dev"+ return None+def to_safe_dict(self) -> dict[str, str]:"""Return configuration as a dictionary with sensitive values redacted."""return {"api_host": self.api_host,+ "environment": self.environment_name,"team_id": str(self.team_id),"lane": self.lane,"event_timeout_seconds": str(self.event_timeout_seconds),@@ -46,6 +70,18 @@ class Config(BaseSettings):}+_ENVIRONMENT_BY_API_HOST = {+ "us.posthog.com": "prod-us",+ "eu.posthog.com": "prod-eu",+}+_KNOWN_ENVIRONMENTS = frozenset({"prod-us", "prod-eu", "dev"})+++def _environment_from_api_host(api_host: str) -> str:+ host = api_host.removeprefix("https://").removeprefix("http://").split("/", 1)[0]+ return _ENVIRONMENT_BY_API_HOST.get(host, "dev")++def _lane_env_segment(lane: str) -> str:"""Normalize a lane name into its env var segment (e.g. "turbo" -> "TURBO")."""return lane.strip().upper().replace("-", "_")diff --git a/posthog/temporal/ingestion_acceptance_test/results.py b/posthog/temporal/ingestion_acceptance_test/results.pyindex 641a365bd36a..c5c4b33f1c65 100644--- a/posthog/temporal/ingestion_acceptance_test/results.py+++ b/posthog/temporal/ingestion_acceptance_test/results.py@@ -1,11 +1,41 @@"""Test result types and reporters for alerting integration."""-from dataclasses import asdict, dataclass, field+from dataclasses import asdict, fieldfrom datetime import UTC, datetimefrom typing import Any, Literal+from posthog.dataclasses import frozen-@dataclass+FailureClass = Literal["connection_error", "event_missing", "person_missing", "assertion", "error"]++# Exception types raised when the test cannot reach ClickHouse or the API at+# all. These are infrastructure or harness problems, not ingestion problems.+CONNECTION_ERROR_TYPES = frozenset(+ {+ "SocketTimeoutError",+ "NetworkError",+ "ConnectionError",+ "ConnectionResetError",+ "ConnectionRefusedError",+ "EOFError",+ "OSError",+ "TimeoutError",+ "ReadTimeout",+ "ConnectTimeout",+ }+)+++@frozen+class CapturedEventRef:+ """An event the test sent through the SDK, kept so a failure can name it."""++ uuid: str+ event: str+ distinct_id: str+++@frozenclass TestResult:"""Result of a single test execution."""@@ -16,9 +46,35 @@ class TestResult:timestamp: str = field(default_factory=lambda: datetime.now(UTC).isoformat())error_message: str | None = Noneerror_details: dict[str, Any] | None = None+ captured_events: list[CapturedEventRef] = field(default_factory=list)+ @property+ def error_type(self) -> str | None:+ if not self.error_details:+ return None+ error_type = self.error_details.get("type")+ return str(error_type) if error_type else None-@dataclass++def classify_failure(result: TestResult) -> FailureClass | None:+ """Sort a failed test into the bucket an investigator should start from.++ Returns None for passing tests.+ """+ if result.status == "passed":+ return None+ error_type = result.error_type or ""+ if error_type in CONNECTION_ERROR_TYPES or "Timeout" in error_type or "Connection" in error_type:+ return "connection_error"+ if error_type != "AssertionError":+ return "error"+ message = result.error_message or ""+ if "not found within" not in message:+ return "assertion"+ return "person_missing" if message.startswith("Person") else "event_missing"+++@frozenclass TestSuiteResult:"""Result of a full test suite execution."""@@ -47,6 +103,10 @@ class TestSuiteResult:def success(self) -> bool:return self.failed_count == 0 and self.error_count == 0+ @property+ def failed_results(self) -> list[TestResult]:+ return [r for r in self.results if r.status != "passed"]+def to_dict(self) -> dict[str, Any]:return {"results": [asdict(r) for r in self.results],diff --git a/posthog/temporal/ingestion_acceptance_test/runner.py b/posthog/temporal/ingestion_acceptance_test/runner.pyindex 95af1bf77d76..d28e7dd6075b 100644--- a/posthog/temporal/ingestion_acceptance_test/runner.py+++ b/posthog/temporal/ingestion_acceptance_test/runner.py@@ -134,6 +134,7 @@ def _run_single_test(}running_tests.remove(test_case.full_name)+ captured_events = list(ctx.client.take_captured_events())duration = time.time() - start_timelogger.info("Test finished",@@ -142,6 +143,7 @@ def _run_single_test(duration_seconds=round(duration, 1),error_message=error_message,error_details=error_details,+ captured_events=captured_events,)return TestResult(@@ -151,6 +153,7 @@ def _run_single_test(duration_seconds=duration,error_message=error_message,error_details=error_details,+ captured_events=captured_events,)diff --git a/posthog/temporal/ingestion_acceptance_test/slack.py b/posthog/temporal/ingestion_acceptance_test/slack.pyindex 510f3ade8871..f9a5767e2a7d 100644--- a/posthog/temporal/ingestion_acceptance_test/slack.py+++ b/posthog/temporal/ingestion_acceptance_test/slack.py@@ -1,18 +1,72 @@-"""Slack notifications for test results using incoming webhooks."""+"""Slack notifications for test results using incoming webhooks.+The failure message is shaped so an on-call engineer or SherlockHog can start+an investigation from it alone: a failure class per test, the events the test+sent (uuid, distinct_id), `Environment:` / `Severity:` metadata lines, and+links to the Temporal run, the worker logs in Loki, and the runbook.+"""++import json+from datetime import datetime, timedeltafrom typing import Any+from urllib.parse import quoteimport requestsimport structlog+from posthog.dataclasses import frozen+from .config import Config-from .results import TestSuiteResult+from .results import FailureClass, TestResult, TestSuiteResult, classify_failurefrom .runner import RunningTestSnapshotlogger = structlog.get_logger(__name__)--def send_slack_notification(config: Config, result: TestSuiteResult) -> bool:+TEMPORAL_WORKER_APP = "temporal-worker-general-purpose"++# Slack Block Kit limits: 50 blocks per message, 3000 characters of section+# text, 10 elements per context block. Context text has no documented cap;+# 2000 is a safe ceiling.+MAX_BLOCKS = 50+MAX_SECTION_TEXT_CHARS = 3000+MAX_CONTEXT_TEXT_CHARS = 2000+MAX_ERROR_MESSAGE_CHARS = 700+MAX_CAPTURED_EVENTS_LISTED = 6++# Ordered from "harness or infra problem" to "ingestion lost data" so the+# suite-level class reflects the most serious failure present.+_FAILURE_CLASS_SEVERITY: tuple[FailureClass, ...] = (+ "connection_error",+ "error",+ "assertion",+ "person_missing",+ "event_missing",+)++_FAILURE_CLASS_LABELS: dict[FailureClass, str] = {+ "connection_error": "connection error (test could not reach ClickHouse or the API)",+ "error": "unexpected error in the test",+ "assertion": "assertion failed on data that was found",+ "person_missing": "person never appeared in ClickHouse",+ "event_missing": "event never appeared in ClickHouse",+}+++@frozen+class RunContext:+ """Identifiers of the Temporal run that produced the notification."""++ workflow_id: str+ workflow_run_id: str+ namespace: str+ temporal_ui_host: str++ @property+ def url(self) -> str:+ return f"{self.temporal_ui_host.rstrip('/')}/namespaces/{self.namespace}/workflows/{self.workflow_id}/{self.workflow_run_id}/history"+++def send_slack_notification(config: Config, result: TestSuiteResult, run_context: RunContext | None = None) -> bool:"""Send test results to Slack via incoming webhook.Only sends notifications when there are failures or errors. Successful runs@@ -21,6 +75,7 @@ def send_slack_notification(config: Config, result: TestSuiteResult) -> bool:Args:config: Configuration containing the Slack webhook URL.result: The test suite result to report.+ run_context: The Temporal run, when known, for the run link.Returns:True if notification was sent successfully or skipped, False on send failure.@@ -33,45 +88,131 @@ def send_slack_notification(config: Config, result: TestSuiteResult) -> bool:logger.debug("All tests passed, skipping Slack notification")return True- blocks = _build_slack_blocks(config, result)- payload = {"blocks": blocks}+ blocks = _build_slack_blocks(config, result, run_context)+ return _post(config.slack_webhook_url, blocks, "Slack notification")- try:- response = requests.post(- config.slack_webhook_url,- json=payload,- timeout=10,++def send_slack_timeout_notification(+ config: Config,+ running_tests: list[RunningTestSnapshot] | None = None,+ run_context: RunContext | None = None,+) -> bool:+ """Send a timeout notification to Slack via incoming webhook.++ Args:+ config: Configuration containing the Slack webhook URL.+ running_tests: List of RunningTestSnapshot with test names and their pending+ poll descriptions (what each test was waiting for in ClickHouse).+ run_context: The Temporal run, when known, for the run link.++ Returns:+ True if notification was sent successfully or skipped, False on send failure.+ """+ if not config.slack_webhook_url:+ logger.debug("Slack webhook URL not configured, skipping timeout notification")+ return True++ blocks: list[dict[str, Any]] = [+ _section(f":hourglass: *Ingestion Acceptance Tests Timed Out in {config.lane} lane*"),+ _context(+ f":traffic_light: Lane: {config.lane} | "+ f":globe_with_meridians: Env: {config.api_host} | "+ f":file_folder: Team: {config.team_id} | "+ f":stopwatch: Timeout: {config.activity_timeout_seconds}s | "+ f":key: Token: `{config.project_api_key[:10]}...`"+ ),+ ]++ if running_tests:+ lines = []+ for info in running_tests:+ line = f"• {info.name}"+ if info.pending_poll:+ line += f" — waiting for: {info.pending_poll}"+ lines.append(line)+ blocks.append(_section(f":red_circle: *Still running ({len(running_tests)}):*\n" + "\n".join(lines)))++ timeout_class = _timeout_failure_class(running_tests or [])+ blocks.append(_metadata_section(config, failure_class=timeout_class, severity=_severity(timeout_class)))+ now = datetime.now().astimezone()+ blocks.append(+ _links_context(+ config,+ run_context,+ log_start=now - timedelta(seconds=config.activity_timeout_seconds + 300),+ log_end=now + timedelta(minutes=5),)+ )++ return _post(config.slack_webhook_url, blocks, "Slack timeout notification")+++def _post(webhook_url: str, blocks: list[dict[str, Any]], what: str) -> bool:+ blocks = _fit_slack_limits(blocks)+ try:+ response = requests.post(webhook_url, json={"blocks": blocks}, timeout=10)response.raise_for_status()- logger.info("Slack notification sent successfully")+ logger.info(f"{what} sent successfully")return Trueexcept requests.RequestException as e:- logger.warning("Failed to send Slack notification", error=str(e))+ logger.warning(f"Failed to send {what}", error=str(e))return False-def _build_slack_blocks(config: Config, result: TestSuiteResult) -> list[dict[str, Any]]:- """Build Slack blocks for the test result notification."""+def _fit_slack_limits(blocks: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Trim a block list so Slack accepts it, keeping the header and the links footer."""+ if len(blocks) > MAX_BLOCKS:+ dropped = len(blocks) - (MAX_BLOCKS - 1)+ blocks = [+ *blocks[: MAX_BLOCKS - 2],+ _section(f"... {dropped} more block(s) not shown; see the Temporal run result for every test."),+ *blocks[-1:],+ ]+ fitted = []+ for block in blocks:+ if block.get("type") == "section":+ block = _section(_truncate(block["text"]["text"], MAX_SECTION_TEXT_CHARS))+ elif block.get("type") == "context":+ block = _context(_truncate(block["elements"][0]["text"], MAX_CONTEXT_TEXT_CHARS))+ fitted.append(block)+ return fitted+++def _truncate(text: str, limit: int) -> str:+ return text if len(text) <= limit else text[: limit - 3] + "..."+++def _build_slack_blocks(+ config: Config, result: TestSuiteResult, run_context: RunContext | None+) -> list[dict[str, Any]]:+ failed = result.failed_results+ suite_class = _suite_failure_class(failed)+ end = _parse_timestamp(result.timestamp)+ start = end - timedelta(seconds=result.total_duration_seconds)+blocks: list[dict[str, Any]] = [_build_header_block(config),_build_summary_block(result),{"type": "divider"},]- blocks.extend(_build_failed_tests_blocks(result))+ blocks.extend(_build_failed_test_block(r) for r in failed)blocks.append({"type": "divider"})- blocks.append(_build_context_block(config, result))+ blocks.append(_metadata_section(config, failure_class=suite_class, severity=_severity(suite_class)))+ blocks.append(+ _links_context(+ config,+ run_context,+ log_start=start - timedelta(minutes=5),+ log_end=end + timedelta(minutes=5),+ duration_seconds=result.total_duration_seconds,+ )+ )return blocksdef _build_header_block(config: Config) -> dict[str, Any]:# Only called when there are failures (send_slack_notification returns early on success)- return {- "type": "section",- "text": {- "type": "mrkdwn",- "text": f":bomb: *Unsuccessful run in {config.lane} lane for Ingestion Acceptance Tests*",- },- }+ return _section(f":bomb: *Unsuccessful run in {config.lane} lane for Ingestion Acceptance Tests*")def _build_summary_block(result: TestSuiteResult) -> dict[str, Any]:@@ -87,129 +228,122 @@ def _build_summary_block(result: TestSuiteResult) -> dict[str, Any]:else:parts.append(f":boom: Error: {result.error_count}")- return {- "type": "context",- "elements": [- {- "type": "mrkdwn",- "text": " ".join(parts),- },- ],- }+ return _context(" ".join(parts))-def _build_context_block(config: Config, result: TestSuiteResult) -> dict[str, Any]:- text = (- f":traffic_light: Lane: {config.lane} | "- f":globe_with_meridians: Env: {config.api_host} | "- f":file_folder: Team: {config.team_id} | "- f":hourglass: Duration: {result.total_duration_seconds:.2f}s"- )- return {- "type": "context",- "elements": [- {- "type": "mrkdwn",- "text": text,- },- ],+def _build_failed_test_block(test_result: TestResult) -> dict[str, Any]:+ emoji = ":red_circle:" if test_result.status == "failed" else ":boom:"+ failure_class = classify_failure(test_result) or "error"+ error_text = test_result.error_message or "No error message"+ if len(error_text) > MAX_ERROR_MESSAGE_CHARS:+ error_text = error_text[:MAX_ERROR_MESSAGE_CHARS] + "..."+ error_type = test_result.error_type++ lines = [+ f"{emoji} *{test_result.test_file}*",+ f"Failure class: `{failure_class}` ({_FAILURE_CLASS_LABELS[failure_class]})",+ f"Error: {error_type + ': ' if error_type else ''}{error_text}",+ ]+ if test_result.captured_events:+ lines.append("Events sent by this test:")+ for ref in test_result.captured_events[:MAX_CAPTURED_EVENTS_LISTED]:+ lines.append(f"• `{ref.event}` uuid `{ref.uuid}` distinct_id `{ref.distinct_id}`")+ hidden = len(test_result.captured_events) - MAX_CAPTURED_EVENTS_LISTED+ if hidden > 0:+ lines.append(f"• ... and {hidden} more (see the Temporal run result)")+ return _section("\n".join(lines))+++def _metadata_section(config: Config, failure_class: FailureClass, severity: str) -> dict[str, Any]:+ # One `Key: value` per line. Alert tooling (SherlockHog's alert parser) keys+ # on lines that start with Environment / Severity / Team.+ lines = [+ f"Environment: {config.environment_name}",+ f"Severity: {severity}",+ "Team: ingestion",+ f"Lane: {config.lane}",+ f"Project: {config.team_id}",+ f"Failure class: {failure_class}",+ ]+ return _section("\n".join(lines))+++def _links_context(+ config: Config,+ run_context: RunContext | None,+ log_start: datetime,+ log_end: datetime,+ duration_seconds: float | None = None,+) -> dict[str, Any]:+ parts = [+ f":traffic_light: Lane: {config.lane}",+ f":globe_with_meridians: Env: {config.api_host}",+ f":file_folder: Team: {config.team_id}",+ ]+ if duration_seconds is not None:+ parts.append(f":hourglass: Duration: {duration_seconds:.2f}s")++ links = []+ if run_context:+ links.append(f"<{run_context.url}|Temporal run>")+ loki_url = _loki_explore_url(config, log_start, log_end)+ if loki_url:+ links.append(f"<{loki_url}|Worker logs (Loki)>")+ if config.runbook_url:+ links.append(f"<{config.runbook_url}|Runbook>")+ if links:+ parts.append(":link: " + " · ".join(links))+ return _context(" | ".join(parts))+++def _loki_explore_url(config: Config, start: datetime, end: datetime) -> str | None:+ grafana = config.grafana_base_url+ if not grafana:+ return None+ logql = f'{{app="{TEMPORAL_WORKER_APP}"}} |= "ingestion_acceptance_test" | json'+ state = {+ "datasource": config.loki_datasource_uid,+ "queries": [{"refId": "A", "datasource": {"type": "loki", "uid": config.loki_datasource_uid}, "expr": logql}],+ "range": {"from": str(int(start.timestamp() * 1000)), "to": str(int(end.timestamp() * 1000))},}+ return f"{grafana}/explore?left={quote(json.dumps(state, separators=(',', ':')), safe='')}"-def send_slack_timeout_notification(config: Config, running_tests: list[RunningTestSnapshot] | None = None) -> bool:- """Send a timeout notification to Slack via incoming webhook.+def _timeout_failure_class(running_tests: list[RunningTestSnapshot]) -> FailureClass:+ """Classify an activity timeout by what the still-running tests were waiting for.- Args:- config: Configuration containing the Slack webhook URL.- running_tests: List of RunningTestSnapshot with test names and their pending- poll descriptions (what each test was waiting for in ClickHouse).-- Returns:- True if notification was sent successfully or skipped, False on send failure.+ A test still polling for an event or a person when the budget runs out is+ the same failure as its assertion timing out. No pending poll means the+ harness itself was stuck."""- if not config.slack_webhook_url:- logger.debug("Slack webhook URL not configured, skipping timeout notification")- return True+ pending = [t.pending_poll for t in running_tests if t.pending_poll]+ if any(p.startswith("event") for p in pending):+ return "event_missing"+ if any(p.startswith("person") for p in pending):+ return "person_missing"+ return "error"- blocks: list[dict[str, Any]] = [- {- "type": "section",- "text": {- "type": "mrkdwn",- "text": f":hourglass: *Ingestion Acceptance Tests Timed Out in {config.lane} lane*",- },- },- {- "type": "context",- "elements": [- {- "type": "mrkdwn",- "text": (- f":traffic_light: Lane: {config.lane} | "- f":globe_with_meridians: Env: {config.api_host} | "- f":file_folder: Team: {config.team_id} | "- f":stopwatch: Timeout: {config.activity_timeout_seconds}s | "- f":key: Token: `{config.project_api_key[:10]}...`"- ),- },- ],- },- ]- if running_tests:- lines = []- for info in running_tests:- line = f"• {info.name}"- if info.pending_poll:- line += f" — waiting for: {info.pending_poll}"- lines.append(line)- test_list = "\n".join(lines)- blocks.append(- {- "type": "section",- "text": {- "type": "mrkdwn",- "text": f":red_circle: *Still running ({len(running_tests)}):*\n{test_list}",- },- }- )+def _suite_failure_class(failed: list[TestResult]) -> FailureClass:+ classes = {classify_failure(r) or "error" for r in failed}+ for candidate in reversed(_FAILURE_CLASS_SEVERITY):+ if candidate in classes:+ return candidate+ return "error"- try:- response = requests.post(- config.slack_webhook_url,- json={"blocks": blocks},- timeout=10,- )- response.raise_for_status()- logger.info("Slack timeout notification sent successfully")- return True- except requests.RequestException as e:- logger.warning("Failed to send Slack timeout notification", error=str(e))- return False+def _severity(failure_class: FailureClass) -> str:+ return "warning" if failure_class in ("connection_error", "error") else "critical"-def _build_failed_tests_blocks(result: TestSuiteResult) -> list[dict[str, Any]]:- failed_tests = [r for r in result.results if r.status in ("failed", "error")]- if not failed_tests:- return []-- blocks: list[dict[str, Any]] = []- for test_result in failed_tests:- emoji = ":red_circle:" if test_result.status == "failed" else ":boom:"- error_text = test_result.error_message or "No error message"- if len(error_text) > 200:- error_text = error_text[:200] + "..."-- blocks.append(- {- "type": "context",- "elements": [- {- "type": "mrkdwn",- "text": f"{emoji} *{test_result.test_name}*\n{error_text}",- },- ],- }- )- return blocks+def _parse_timestamp(value: str) -> datetime:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ return parsed if parsed.tzinfo else parsed.astimezone()+++def _section(text: str) -> dict[str, Any]:+ return {"type": "section", "text": {"type": "mrkdwn", "text": text}}+++def _context(text: str) -> dict[str, Any]:+ return {"type": "context", "elements": [{"type": "mrkdwn", "text": text}]}diff --git a/posthog/temporal/tests/ingestion_acceptance_test/test_activities.py b/posthog/temporal/tests/ingestion_acceptance_test/test_activities.pyindex 7e6f584f7201..baa359c0bea4 100644--- a/posthog/temporal/tests/ingestion_acceptance_test/test_activities.py+++ b/posthog/temporal/tests/ingestion_acceptance_test/test_activities.py@@ -51,7 +51,7 @@ class TestRunIngestionAcceptanceTestsTimeout:with pytest.raises(asyncio.TimeoutError):await run_ingestion_acceptance_tests(IngestionAcceptanceTestInput())- mock_send_timeout.assert_called_once_with(config, running_tests=[])+ mock_send_timeout.assert_called_once_with(config, running_tests=[], run_context=None)mock_send_slack.assert_not_called()@patch("posthog.temporal.ingestion_acceptance_test.activities.send_slack_timeout_notification")diff --git a/posthog/temporal/tests/ingestion_acceptance_test/test_client.py b/posthog/temporal/tests/ingestion_acceptance_test/test_client.pyindex fb30c01959f2..aca25d736200 100644--- a/posthog/temporal/tests/ingestion_acceptance_test/test_client.py+++ b/posthog/temporal/tests/ingestion_acceptance_test/test_client.py@@ -51,6 +51,22 @@ class TestCaptureEvent:uuid=event_uuid,)+ def test_captured_events_are_tracked_per_test_and_cleared_when_taken(+ self, client: PostHogClient, mock_posthog_sdk: MagicMock+ ) -> None:+ event_uuid = client.capture_event(event_name="$test", distinct_id="user_1")+ alias_uuid = client.alias("alias_1", "user_1")+ merge_uuid = client.merge_dangerously("user_1", "user_2")++ captured = client.take_captured_events()++ assert [(c.uuid, c.event, c.distinct_id) for c in captured] == [+ (event_uuid, "$test", "user_1"),+ (alias_uuid, "$create_alias", "user_1"),+ (merge_uuid, "$merge_dangerously", "user_1"),+ ]+ assert client.take_captured_events() == []+def test_uses_empty_dict_when_no_properties(self, client: PostHogClient, mock_posthog_sdk: MagicMock) -> None:client.capture_event(event_name="test_event", distinct_id="user_123")diff --git a/posthog/temporal/tests/ingestion_acceptance_test/test_config.py b/posthog/temporal/tests/ingestion_acceptance_test/test_config.pyindex 4ec83f8437ce..942107f8e779 100644--- a/posthog/temporal/tests/ingestion_acceptance_test/test_config.py+++ b/posthog/temporal/tests/ingestion_acceptance_test/test_config.py@@ -4,7 +4,7 @@ import osimport pytest-from posthog.temporal.ingestion_acceptance_test.config import DEFAULT_LANE, configured_lanes, load_config+from posthog.temporal.ingestion_acceptance_test.config import DEFAULT_LANE, Config, configured_lanes, load_configFLAT_ENV = {"INGESTION_ACCEPTANCE_TEST_API_HOST": "https://flat.example.com",@@ -93,3 +93,24 @@ class TestConfiguredLanes:def test_parses_lanes(self, clean_env: pytest.MonkeyPatch, raw: str, expected: list[str]) -> None:clean_env.setenv("INGESTION_ACCEPTANCE_TEST_LANES", raw)assert configured_lanes() == expected+++class TestEnvironmentName:+ @pytest.mark.parametrize(+ "api_host, environment, expected_name, expected_grafana",+ [+ ("https://us.posthog.com", None, "prod-us", "https://grafana.prod-us.posthog.dev"),+ ("https://eu.posthog.com/", None, "prod-eu", "https://grafana.prod-eu.posthog.dev"),+ ("https://app.dev.posthog.dev", None, "dev", "https://grafana.dev.posthog.dev"),+ ("https://us.posthog.com", "staging", "staging", None),+ ],+ ids=["us", "eu", "dev", "explicit_override"],+ )+ def test_derives_environment_and_grafana_url(+ self, api_host: str, environment: str | None, expected_name: str, expected_grafana: str | None+ ) -> None:+ config = Config(api_host=api_host, project_api_key="phc_x", team_id=1, environment=environment)++ assert config.environment_name == expected_name+ assert config.grafana_base_url == expected_grafana+ assert config.to_safe_dict()["environment"] == expected_namediff --git a/posthog/temporal/tests/ingestion_acceptance_test/test_runner.py b/posthog/temporal/tests/ingestion_acceptance_test/test_runner.pyindex 43f47fb1a411..57ec0058e8d4 100644--- a/posthog/temporal/tests/ingestion_acceptance_test/test_runner.py+++ b/posthog/temporal/tests/ingestion_acceptance_test/test_runner.py@@ -4,6 +4,7 @@ import pytestfrom unittest.mock import MagicMock, patchfrom posthog.temporal.ingestion_acceptance_test.config import Config+from posthog.temporal.ingestion_acceptance_test.results import CapturedEventReffrom posthog.temporal.ingestion_acceptance_test.runner import (AcceptanceTest,RunningTests,@@ -60,6 +61,25 @@ class TestRunTests:assert call_order == ["init", "setup", "test_method"]+ def test_attaches_events_captured_by_the_test_to_its_result(+ self, config: Config, mock_client: MagicMock, executor: ThreadPoolExecutor, running_tests: RunningTests+ ) -> None:+ captured = [CapturedEventRef(uuid="u-1", event="$test", distinct_id="d-1")]+ mock_client.take_captured_events.return_value = captured++ class FailingTest(AcceptanceTest):+ def test_fail(self) -> None:+ raise AssertionError("Event u-1 not found within 1s timeout")++ tests = [TestCase(module_name="test_mod", test_class=FailingTest, method_name="test_fail")]++ result = run_tests(config, tests, mock_client, executor, running_tests)++ assert result.results[0].captured_events == captured+ assert result.to_dict()["results"][0]["captured_events"] == [+ {"uuid": "u-1", "event": "$test", "distinct_id": "d-1"}+ ]+def test_returns_passed_status_and_correct_names(self, config: Config, mock_client: MagicMock, executor: ThreadPoolExecutor, running_tests: RunningTests) -> None:diff --git a/posthog/temporal/tests/ingestion_acceptance_test/test_slack.py b/posthog/temporal/tests/ingestion_acceptance_test/test_slack.pyindex aec62c0fbaf1..263ccc9c723a 100644--- a/posthog/temporal/tests/ingestion_acceptance_test/test_slack.py+++ b/posthog/temporal/tests/ingestion_acceptance_test/test_slack.py@@ -1,10 +1,16 @@+from urllib.parse import unquote+import pytestfrom unittest.mock import MagicMock, patchfrom posthog.temporal.ingestion_acceptance_test.config import Config-from posthog.temporal.ingestion_acceptance_test.results import TestResult, TestSuiteResult+from posthog.temporal.ingestion_acceptance_test.results import CapturedEventRef, TestResult, TestSuiteResultfrom posthog.temporal.ingestion_acceptance_test.runner import RunningTestSnapshot-from posthog.temporal.ingestion_acceptance_test.slack import send_slack_notification, send_slack_timeout_notification+from posthog.temporal.ingestion_acceptance_test.slack import (+ RunContext,+ send_slack_notification,+ send_slack_timeout_notification,+)@pytest.fixture@@ -164,12 +170,158 @@ class TestSendSlackNotification:payload = mock_post.call_args[1]["json"]blocks = payload["blocks"]- context_blocks = [b for b in blocks if b.get("type") == "context"]- all_text = " ".join(str(b) for b in context_blocks)+ all_text = " ".join(str(b) for b in blocks)- assert "test_failing" in all_text+ assert "test_file.py" in all_textassert "AssertionError" in all_text+ @pytest.mark.parametrize(+ "error_type, error_message, expected_class, expected_severity",+ [+ ("SocketTimeoutError", "Code: 209. (ch-offline:9440)", "connection_error", "warning"),+ ("AssertionError", "Event abc-123 not found within 3600s timeout", "event_missing", "critical"),+ ("AssertionError", "Person A not found within time budget", "person_missing", "critical"),+ ("AssertionError", "Expected name='a', got 'b'", "assertion", "critical"),+ ],+ ids=["connection_error", "event_missing", "person_missing", "assertion"],+ )+ @patch("posthog.temporal.ingestion_acceptance_test.slack.requests.post")+ def test_payload_carries_failure_class_and_alert_metadata(+ self,+ mock_post: MagicMock,+ config: Config,+ error_type: str,+ error_message: str,+ expected_class: str,+ expected_severity: str,+ ) -> None:+ mock_post.return_value.raise_for_status = MagicMock()+ result = TestSuiteResult(+ results=[+ TestResult(+ test_name="test_x",+ test_file="acceptance_test_x::TestX::test_x",+ status="failed" if error_type == "AssertionError" else "error",+ duration_seconds=1.0,+ error_message=error_message,+ error_details={"type": error_type, "traceback": "..."},+ captured_events=[CapturedEventRef(uuid="abc-123", event="$test", distinct_id="did-1")],+ )+ ],+ total_duration_seconds=1.0,+ environment={},+ timestamp="2024-01-01T00:00:00Z",+ )++ send_slack_notification(config, result)++ blocks = mock_post.call_args[1]["json"]["blocks"]+ sections = [b["text"]["text"] for b in blocks if b.get("type") == "section"]+ failed_block = next(t for t in sections if "acceptance_test_x::TestX::test_x" in t)+ assert f"Failure class: `{expected_class}`" in failed_block+ assert f"{error_type}: {error_message}" in failed_block+ assert "uuid `abc-123` distinct_id `did-1`" in failed_block++ metadata_block = next(t for t in sections if t.startswith("Environment:"))+ assert "Environment: dev" in metadata_block+ assert f"Severity: {expected_severity}" in metadata_block+ assert f"Failure class: {expected_class}" in metadata_block++ @patch("posthog.temporal.ingestion_acceptance_test.slack.requests.post")+ def test_payload_stays_within_slack_block_kit_limits(self, mock_post: MagicMock, config: Config) -> None:+ mock_post.return_value.raise_for_status = MagicMock()+ results = [+ TestResult(+ test_name=f"t{i}",+ test_file=f"acceptance_test_x::TestX::t{i}",+ status="failed",+ duration_seconds=1.0,+ error_message="x" * 5000,+ error_details={"type": "AssertionError"},+ captured_events=[CapturedEventRef(uuid=f"u-{i}-{j}", event="$e", distinct_id="d") for j in range(40)],+ )+ for i in range(80)+ ]+ result = TestSuiteResult(+ results=results, total_duration_seconds=1.0, environment={}, timestamp="2024-01-01T00:00:00Z"+ )++ send_slack_notification(config, result)++ blocks = mock_post.call_args[1]["json"]["blocks"]+ assert len(blocks) <= 50+ assert all(len(b["text"]["text"]) <= 3000 for b in blocks if b["type"] == "section")+ assert all(len(b["elements"][0]["text"]) <= 2000 for b in blocks if b["type"] == "context")+ assert "Unsuccessful run" in blocks[0]["text"]["text"]+ assert "Env: https://test.posthog.com" in blocks[-1]["elements"][0]["text"]+ assert "more block(s) not shown" in blocks[-2]["text"]["text"]++ @patch("posthog.temporal.ingestion_acceptance_test.slack.requests.post")+ def test_suite_failure_class_is_the_most_serious_one(self, mock_post: MagicMock, config: Config) -> None:+ mock_post.return_value.raise_for_status = MagicMock()+ result = TestSuiteResult(+ results=[+ TestResult(+ test_name="a",+ test_file="a",+ status="error",+ duration_seconds=1.0,+ error_message="Code: 209.",+ error_details={"type": "SocketTimeoutError"},+ ),+ TestResult(+ test_name="b",+ test_file="b",+ status="failed",+ duration_seconds=1.0,+ error_message="Event x not found within 3600s timeout",+ error_details={"type": "AssertionError"},+ ),+ ],+ total_duration_seconds=1.0,+ environment={},+ timestamp="2024-01-01T00:00:00Z",+ )++ send_slack_notification(config, result)++ blocks = mock_post.call_args[1]["json"]["blocks"]+ metadata_block = next(+ b["text"]["text"] for b in blocks if b["type"] == "section" and "Severity:" in b["text"]["text"]+ )+ assert "Failure class: event_missing" in metadata_block+ assert "Severity: critical" in metadata_block++ @patch("posthog.temporal.ingestion_acceptance_test.slack.requests.post")+ def test_links_to_temporal_run_loki_and_runbook(+ self, mock_post: MagicMock, failing_result: TestSuiteResult+ ) -> None:+ mock_post.return_value.raise_for_status = MagicMock()+ config = Config(+ api_host="https://us.posthog.com",+ project_api_key="phc_test_key",+ team_id=12345,+ slack_webhook_url="https://hooks.slack.com/services/T00/B00/XXX",+ )+ run_context = RunContext(+ workflow_id="wf-1",+ workflow_run_id="run-1",+ namespace="ns.abc",+ temporal_ui_host="https://cloud.temporal.io",+ )++ send_slack_notification(config, failing_result, run_context=run_context)++ blocks = mock_post.call_args[1]["json"]["blocks"]+ links_text = blocks[-1]["elements"][0]["text"]+ assert "<https://cloud.temporal.io/namespaces/ns.abc/workflows/wf-1/run-1/history|Temporal run>" in links_text+ assert "https://grafana.prod-us.posthog.dev/explore?left=" in links_text+ assert "temporal-worker-general-purpose" in unquote(links_text)+ assert (+ "<https://runbooks.posthog.com/services/ingestion/runbooks/ingestion-acceptance-test|Runbook>" in links_text+ )+ assert "Environment: prod-us" in " ".join(str(b) for b in blocks)+@patch("posthog.temporal.ingestion_acceptance_test.slack.requests.post")def test_does_nothing_when_no_webhook_url(self, mock_post: MagicMock, failing_result: TestSuiteResult) -> None:config_no_webhook = Config(@@ -219,6 +371,38 @@ class TestSendSlackTimeoutNotification:assert "12345" in context_textassert "3600s" in context_textassert "phc_test_k..." in context_text+ all_text = " ".join(str(b) for b in payload["blocks"])+ assert "Environment: dev" in all_text+ assert "Failure class: error" in all_text+ assert "Severity: warning" in all_text++ @pytest.mark.parametrize(+ "pending_polls, expected_class, expected_severity",+ [+ (["event UUID 'abc'"], "event_missing", "critical"),+ (["person with distinct_id 'abc'"], "person_missing", "critical"),+ (["events for person 'p1'", "person with distinct_id 'abc'"], "event_missing", "critical"),+ ([None], "error", "warning"),+ ],+ ids=["event_poll", "person_poll", "mixed_polls", "no_poll"],+ )+ @patch("posthog.temporal.ingestion_acceptance_test.slack.requests.post")+ def test_timeout_is_classified_by_what_was_pending(+ self,+ mock_post: MagicMock,+ config: Config,+ pending_polls: list[str | None],+ expected_class: str,+ expected_severity: str,+ ) -> None:+ mock_post.return_value.raise_for_status = MagicMock()+ running = [RunningTestSnapshot(name=f"t{i}", pending_poll=p) for i, p in enumerate(pending_polls)]++ send_slack_timeout_notification(config, running_tests=running)++ all_text = " ".join(str(b) for b in mock_post.call_args[1]["json"]["blocks"])+ assert f"Failure class: {expected_class}" in all_text+ assert f"Severity: {expected_severity}" in all_text@patch("posthog.temporal.ingestion_acceptance_test.slack.requests.post")def test_does_nothing_when_no_webhook_url(self, mock_post: MagicMock) -> None: