Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(aio): give ai observability its own clickhouse budget (#74663)

Carlos Marchal3eb4be76dbd3
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.py
index 43238a2a0618..f4752e651604 100644
--- a/posthog/clickhouse/client/connection.py
+++ b/posthog/clickhouse/client/connection.py
@@ -70,6 +70,7 @@ class ClickHouseUser(StrEnum):
META = "meta"
MESSAGING = "messaging" # a.k.a. behavioral cohorts
MAX_AI = "max_ai" # llm/a
+ LLM_ANALYTICS = "llm_analytics" # background AI observability workflows; interactive requests use APP
ERROR_TRACKING = "error_tracking"
ENDPOINTS = "endpoints"
BILLING = "billing"
diff --git a/posthog/clickhouse/client/execute.py b/posthog/clickhouse/client/execute.py
index 1bb2b5e7bd8c..d27183198caa 100644
--- a/posthog/clickhouse/client/execute.py
+++ b/posthog/clickhouse/client/execute.py
@@ -4,7 +4,7 @@ import types
import logging
import threading
import traceback
-from collections.abc import Sequence
+from collections.abc import Iterator, Sequence
from contextlib import contextmanager
from enum import StrEnum
from functools import lru_cache
@@ -26,6 +26,7 @@ from posthog.clickhouse.client.connection import (
get_default_clickhouse_workload_type,
)
from posthog.clickhouse.client.escape import substitute_params
+from posthog.clickhouse.client.limit import get_llm_analytics_rate_limiter
from posthog.clickhouse.client.tracing import trace_clickhouse_query_decorator
from posthog.clickhouse.query_tagging import (
Feature,
@@ -255,6 +256,23 @@ class ClickHouseExternalTable(TypedDict):
data: list[dict[str, Any]]
+@contextmanager
+def _llm_analytics_concurrency_slot(ch_user: ClickHouseUser, team_id: Optional[int]) -> Iterator[None]:
+ """Hold one of AI observability's ClickHouse slots, and nothing for every other user.
+
+ Acquired here rather than at the call sites because the ch_user routing above is tag-based and
+ so applies to every query this product issues, including ones that reach ClickHouse through
+ shared helpers like query_ai_events and TraceQueryRunner. A budget that call sites had to opt
+ into would cover only some of them, and would silently miss whatever gets added next.
+ """
+ if ch_user != ClickHouseUser.LLM_ANALYTICS:
+ yield
+ return
+
+ with get_llm_analytics_rate_limiter().run(team_id=team_id):
+ yield
+
+
@patchable
@trace_clickhouse_query_decorator
def sync_execute(
@@ -399,6 +417,11 @@ def sync_execute(
ch_user = ClickHouseUser.ENDPOINTS
elif tags.product == Product.BILLING:
ch_user = ClickHouseUser.BILLING
+ elif tags.product == Product.LLM_ANALYTICS and tags.kind == "temporal" and ch_user == ClickHouseUser.DEFAULT:
+ # Temporal only, because the interactive AI observability API shares this product tag and
+ # belongs on APP rather than behind a batch concurrency budget. Callers that named a user
+ # keep it, so HogQL's own metadata lookups don't spend the budget meant for real queries.
+ ch_user = ClickHouseUser.LLM_ANALYTICS
# To humans and bots reading this, you might be tempted to add a catch-all tag to avoid
# hitting this error. Please don't do this. This error is to let us know about queries
@@ -465,7 +488,10 @@ def sync_execute(
access_method=tags.access_method or "other",
chargeable=str(tags.chargeable or "0"),
).inc()
- with sync_client or get_client_from_pool(workload, team_id, readonly, ch_user) as client:
+ with (
+ _llm_analytics_concurrency_slot(ch_user, team_id),
+ sync_client or get_client_from_pool(workload, team_id, readonly, ch_user) as client,
+ ):
result = client.execute(
prepared_sql,
params=prepared_args,
diff --git a/posthog/clickhouse/client/limit.py b/posthog/clickhouse/client/limit.py
index b8a4141ddde5..9eec8964f294 100644
--- a/posthog/clickhouse/client/limit.py
+++ b/posthog/clickhouse/client/limit.py
@@ -216,6 +216,7 @@ __APP_CONCURRENT_QUERY_PER_ORG: Optional[RateLimit] = None
__APP_CONCURRENT_DASHBOARD_QUERIES_PER_ORG: Optional[RateLimit] = None
__MATERIALIZED_ENDPOINTS_CONCURRENT_QUERY_PER_TEAM: Optional[RateLimit] = None
__EVENTS_LIST_CONCURRENT_QUERY_PER_TEAM: Optional[RateLimit] = None
+__LLM_ANALYTICS_CONCURRENT_QUERIES: Optional[RateLimit] = None
def get_api_team_rate_limiter():
@@ -375,6 +376,32 @@ def get_events_list_rate_limiter():
return __EVENTS_LIST_CONCURRENT_QUERY_PER_TEAM
+def get_llm_analytics_rate_limiter():
+ """
+ Limits concurrent background AI observability queries (ClickHouseUser.LLM_ANALYTICS).
+
+ Slots are global rather than per team or per org because the resource being protected is the
+ ClickHouse user's server-side concurrency cap, which every team's queries draw from.
+ """
+ global __LLM_ANALYTICS_CONCURRENT_QUERIES
+ if __LLM_ANALYTICS_CONCURRENT_QUERIES is None:
+ __LLM_ANALYTICS_CONCURRENT_QUERIES = RateLimit(
+ max_concurrency=settings.CLICKHOUSE_LLM_ANALYTICS_MAX_CONCURRENT_QUERIES,
+ applicable=lambda *args, **kwargs: not TEST,
+ limit_name="llm_analytics_background",
+ get_task_name=lambda *args, **kwargs: "llm_analytics:query:background",
+ get_task_id=lambda *args, **kwargs: kwargs.get("task_id") or generate_short_id(),
+ # Exceeds the 600s QUERY_ASYNC ClickHouse timeout so a worker dying mid-query cannot
+ # release its slot while the query it stands for is still running on the cluster.
+ ttl=900,
+ retry=0.25,
+ # Must stay well under the tightest AIO activity heartbeat timeout of 30s, otherwise
+ # waiting for a slot looks like a dead worker.
+ retry_timeout=10.0,
+ )
+ return __LLM_ANALYTICS_CONCURRENT_QUERIES
+
+
class ConcurrencyLimitExceeded(Exception):
pass
diff --git a/posthog/clickhouse/client/test/test_execute.py b/posthog/clickhouse/client/test/test_execute.py
index f203de52525b..0f91acae0f19 100644
--- a/posthog/clickhouse/client/test/test_execute.py
+++ b/posthog/clickhouse/client/test/test_execute.py
@@ -3,7 +3,8 @@ from unittest.mock import MagicMock, patch
from posthog.clickhouse.client.connection import ClickHouseUser, Workload
from posthog.clickhouse.client.execute import sync_execute
-from posthog.clickhouse.query_tagging import tags_context
+from posthog.clickhouse.client.limit import RateLimit, get_llm_analytics_rate_limiter
+from posthog.clickhouse.query_tagging import Product, tags_context
@pytest.fixture
@@ -15,6 +16,15 @@ def client_from_pool():
yield mock
+def llm_analytics_slots():
+ """Counts concurrency slots taken per query, with the limiter forced on (it is inert in tests)."""
+ limiter = get_llm_analytics_rate_limiter()
+ with patch.object(limiter, "applicable", lambda *args, **kwargs: True):
+ with patch.object(RateLimit, "use", return_value=("key", "task")) as use, patch.object(RateLimit, "release"):
+ yield use
+
+
@pytest.mark.parametrize(
"workload,expected_workload",
[
@@ -48,3 +58,42 @@ def test_endpoints_tag_workload_routing(client_from_pool, workload, expected_wor
sync_execute("SELECT 1", workload=workload, flush=False)
assert client_from_pool.call_args[0][0] == expected_workload
+
+
+ "product,kind,tag_id,requested_ch_user,expected_ch_user",
+ [
+ (Product.LLM_ANALYTICS, "temporal", "llma-eval-reports", ClickHouseUser.DEFAULT, ClickHouseUser.LLM_ANALYTICS),
+ (Product.LLM_ANALYTICS, "request", "api/projects/2/llm_analytics", ClickHouseUser.DEFAULT, ClickHouseUser.APP),
+ (Product.WAREHOUSE, "temporal", "data-imports", ClickHouseUser.DEFAULT, ClickHouseUser.DEFAULT),
+ # The AI observability usage reports carry this product tag from Celery. The budget is sized
+ # for the per-team Temporal fan-out, so they stay off it.
+ (Product.LLM_ANALYTICS, "celery", "posthog.tasks.usage_report", ClickHouseUser.DEFAULT, ClickHouseUser.DEFAULT),
+ # HogQL's materialized-column lookups name their own user, and must keep it rather than
+ # spending a slot of the concurrency budget sized for real queries.
+ (Product.LLM_ANALYTICS, "temporal", "llma-eval-reports", ClickHouseUser.HOGQL, ClickHouseUser.HOGQL),
+ (Product.LLM_ANALYTICS, "temporal", "llma-eval-reports", ClickHouseUser.META, ClickHouseUser.META),
+ ],
+)
+def test_llm_analytics_ch_user_routing(client_from_pool, product, kind, tag_id, requested_ch_user, expected_ch_user):
+ with tags_context(product=product, kind=kind, id=tag_id):
+ sync_execute("SELECT 1", flush=False, ch_user=requested_ch_user)
+
+ assert client_from_pool.call_args[0][3] == expected_ch_user
+
+
+ "product,expected_slots",
+ [
+ (Product.LLM_ANALYTICS, 1),
+ (Product.WAREHOUSE, 0),
+ ],
+)
+def test_llm_analytics_queries_take_a_concurrency_slot(client_from_pool, llm_analytics_slots, product, expected_slots):
+ # Asserted here rather than at the AI observability call sites because those reach ClickHouse
+ # through shared helpers too (query_ai_events, TraceQueryRunner). Holding the slot at this
+ # single funnel is what makes the budget cover all of them.
+ with tags_context(product=product, kind="temporal", id="llma-eval-reports"):
+ sync_execute("SELECT 1", flush=False)
+
+ assert llm_analytics_slots.call_count == expected_slots
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index 400799ef853c..5030f9fd3b79 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -420,6 +420,12 @@ with suppress(Exception):
as_json = json.loads(os.getenv("API_QUERIES_PER_TEAM", "{}"))
API_QUERIES_PER_TEAM = {int(k): int(v) for k, v in as_json.items()}
+# Fleet-wide, unlike ClickHouse's per-node max_concurrent_queries_for_user, so keep it at or below
+# that user's per-node value for the bound to mean anything.
+CLICKHOUSE_LLM_ANALYTICS_MAX_CONCURRENT_QUERIES: int = get_from_env(
+ "CLICKHOUSE_LLM_ANALYTICS_MAX_CONCURRENT_QUERIES", 8, type_cast=int
+)
+
_clickhouse_http_protocol = "http://"
_clickhouse_http_port = "8123"
if CLICKHOUSE_SECURE:
diff --git a/posthog/temporal/ai_observability/trace_summarization/README.md b/posthog/temporal/ai_observability/trace_summarization/README.md
index e196e3a6a2b3..3eb5686410b0 100644
--- a/posthog/temporal/ai_observability/trace_summarization/README.md
+++ b/posthog/temporal/ai_observability/trace_summarization/README.md
@@ -140,7 +140,7 @@ Key constants in `constants.py`:
| ------------------------------------------- | -------------- | ----------------------------------------------- |
| `DEFAULT_MAX_ITEMS_PER_WINDOW` | 15 | Max items per window |
| `DEFAULT_BATCH_SIZE` | 5 | Concurrent item processing |
-| `DEFAULT_MAX_CONCURRENT_TEAMS` | 5 | Max teams to process in parallel |
+| `DEFAULT_MAX_CONCURRENT_TEAMS` | 20 | Max teams to process in parallel |
| `DEFAULT_MODE` | "detailed" | Summary detail level |
| `DEFAULT_MODEL` | "gpt-4.1-nano" | LLM model for summarization |
| `DEFAULT_WINDOW_MINUTES` | 60 | Time window to query |
@@ -152,7 +152,10 @@ Key constants in `constants.py`:
| `SUMMARIZE_AND_SAVE_START_TO_CLOSE_TIMEOUT` | 900s | Summarize + save activity timeout (per attempt) |
| `SUMMARIZE_AND_SAVE_HEARTBEAT_TIMEOUT` | 60s | Heartbeat window for summarize activity |
-Retry policies: `SAMPLE_RETRY_POLICY` (3 attempts), `FETCH_AND_FORMAT_RETRY_POLICY` (3 attempts), `SUMMARIZE_AND_SAVE_RETRY_POLICY` (4 attempts with backoff, `TextReprExpiredError` non-retryable), `COORDINATOR_CHILD_WORKFLOW_RETRY_POLICY` (2 attempts). All retry policies exclude `ValueError` and `TypeError` from retries.
+Retry policies: `SAMPLE_RETRY_POLICY` (5 attempts with backoff), `FETCH_AND_FORMAT_RETRY_POLICY` (2 attempts), `SUMMARIZE_AND_SAVE_RETRY_POLICY` (2 attempts with backoff, `TextReprExpiredError` non-retryable), `COORDINATOR_CHILD_WORKFLOW_RETRY_POLICY` (1 attempt). All retry policies exclude `ValueError` and `TypeError` from retries.
+
+Sampling keeps ClickHouse capacity errors retryable deliberately: each run covers a disjoint wall-clock window with no persisted cursor, so a run that gives up loses that hour of traces for that team permanently.
+Concurrency is bounded centrally by `CLICKHOUSE_LLM_ANALYTICS_MAX_CONCURRENT_QUERIES`, not by this workflow's fan-out, because trace clustering and eval reports draw on the same budget.
## Redis Intermediate Storage
diff --git a/posthog/temporal/ai_observability/trace_summarization/constants.py b/posthog/temporal/ai_observability/trace_summarization/constants.py
index 8f22edbc26fa..ad725af64faa 100644
--- a/posthog/temporal/ai_observability/trace_summarization/constants.py
+++ b/posthog/temporal/ai_observability/trace_summarization/constants.py
@@ -106,8 +106,14 @@ WORKFLOW_EXECUTION_TIMEOUT_MINUTES = 30 # Max time for single team workflow —
COORDINATOR_EXECUTION_TIMEOUT_MINUTES = 55 # Must finish before next hourly trigger to avoid silent skips
# Retry policies
+# Do not make ClickHouse capacity errors non-retryable here. Each run samples a disjoint window
+# with no persisted cursor, so a run that gives up drops that window of traces for that team
+# permanently.
SAMPLE_RETRY_POLICY = RetryPolicy(
- maximum_attempts=2,
+ maximum_attempts=5,
+ initial_interval=timedelta(seconds=10),
+ backoff_coefficient=2.0,
+ maximum_interval=timedelta(seconds=120),
non_retryable_error_types=["ValueError", "TypeError"],
)
COORDINATOR_CHILD_WORKFLOW_RETRY_POLICY = RetryPolicy(maximum_attempts=1)