: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): record platform check history as the alerts_platform user (#118791)
Jimmy Zhu3592922ec90c
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.pyindex e57bfbf29e07..c39f05ceee08 100644--- a/posthog/clickhouse/client/connection.py+++ b/posthog/clickhouse/client/connection.py@@ -114,6 +114,10 @@ class ClickHouseUser(StrEnum):ALERTS_PLATFORM_INSIGHT = "alerts_platform_insight"# Exists on the logs cluster only. Pass it with Workload.LOGS, never as a query tag.ALERTS_PLATFORM_LOGS = "alerts_platform_logs"+ # The platform's own bookkeeping, shared by every source: its check history and the default+ # user of its evaluation worker. A source's checks keep their own user, so a new source never+ # takes from another source's budget.+ ALERTS_PLATFORM = "alerts_platform"# Backups - used by Dagster backup jobsBACKUPS = "backups"diff --git a/products/alerts_platform/backend/logic/platform_alert_events.py b/products/alerts_platform/backend/logic/platform_alert_events.pyindex 468b8cd87754..c72317a5c546 100644--- a/products/alerts_platform/backend/logic/platform_alert_events.py+++ b/products/alerts_platform/backend/logic/platform_alert_events.py@@ -22,6 +22,7 @@ from uuid import UUIDimport structlogfrom posthog.clickhouse.client import sync_execute+from posthog.clickhouse.client.connection import ClickHouseUserfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.dataclasses import frozen@@ -119,6 +120,12 @@ def _deduplication_token(team_id: int, rows: Sequence[PlatformAlertEventRow]) ->return digest.hexdigest()+def _execute(query: str, args: Any, *, team_id: int, settings: dict[str, Any] | None = None) -> Any:+ """`sync_execute` as the platform's own user, so this bookkeeping never takes from `default`'s+ per-user concurrency budget. A pod without that user wired falls back to its own default user."""+ return sync_execute(query, args, team_id=team_id, settings=settings, ch_user=ClickHouseUser.ALERTS_PLATFORM)++def insert_events(team_id: int, rows: Sequence[PlatformAlertEventRow]) -> int:"""Records a batch's history. Returns how many rows it wrote.@@ -132,7 +139,7 @@ def insert_events(team_id: int, rows: Sequence[PlatformAlertEventRow]) -> int:# `sync_execute` requires both tags. The platform product rather than a source's, because# the table serves every source and the write is the platform's own bookkeeping.tag_queries(product=Product.PLATFORM_AND_SUPPORT, feature=Feature.ALERTING)- sync_execute(+ _execute(_INSERT_SQL,[row.as_row() for row in rows],settings={"insert_deduplication_token": _deduplication_token(team_id, rows)},@@ -211,9 +218,9 @@ def announcement("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)+ rows = _execute(_ANNOUNCEMENT_PART_SQL, {**parameters, "part": part, "parts": parts}, team_id=team_id)else:- rows = sync_execute(_ANNOUNCEMENT_SQL, parameters, team_id=team_id)+ rows = _execute(_ANNOUNCEMENT_SQL, parameters, team_id=team_id)if not rows:return None@@ -252,7 +259,7 @@ def announced_kinds() -> 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(+ rows = _execute(_ANNOUNCED_KINDS_SQL,{"team_id": team_id,@@ -315,6 +322,8 @@ def history(if not configuration_ids:return {}tag_queries(product=Product.PLATFORM_AND_SUPPORT, feature=Feature.ALERTING)+ # Not `_execute`: the web API calls this too, and naming a user would replace the one+ # `sync_execute` picks for request traffic.rows = sync_execute(_HISTORY_SQL,{"team_id": team_id, "configuration_ids": list(configuration_ids), "since": since, "until": until},diff --git a/products/alerts_platform/backend/tests/test_platform_announcement.py b/products/alerts_platform/backend/tests/test_platform_announcement.pyindex db8d6269a3c5..76ec1039b3a3 100644--- a/products/alerts_platform/backend/tests/test_platform_announcement.py+++ b/products/alerts_platform/backend/tests/test_platform_announcement.py@@ -2,8 +2,10 @@ from datetime import UTC, datetime, timedeltafrom uuid import uuid4from posthog.test.base import APIBaseTest, ClickhouseTestMixin+from unittest.mock import patchfrom posthog.clickhouse.client import sync_execute+from posthog.clickhouse.client.connection import ClickHouseUserfrom posthog.models.scoping import team_scopefrom products.alerts_platform.backend.facade.contracts import AlertEventKind, SourceKind@@ -61,9 +63,15 @@ class TestAnnouncement(ClickhouseTestMixin, APIBaseTest):return announcement(self.team.id, str(self.configuration.id), evaluation_key, source=SourceKind.LOGS)def test_a_recorded_firing_comes_back_as_the_message_it_should_send(self) -> None:- insert_events(self.team.id, [self._row()])-- result = self._announcement()+ module = "products.alerts_platform.backend.logic.platform_alert_events"+ with patch(f"{module}.sync_execute", wraps=sync_execute) as executed:+ insert_events(self.team.id, [self._row()])+ result = self._announcement()++ # As `default`, the history write and read share that user's per-user concurrency limit+ # with every other caller, and a rejected insert loses the row.+ assert executed.call_args_list+ assert all(call.kwargs.get("ch_user") == ClickHouseUser.ALERTS_PLATFORM for call in executed.call_args_list)assert result is not Noneassert result.configuration_id == str(self.configuration.id)