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): stop eval reads from building the full hogql catalog (#113580)

posthog[bot]cbfa299ceef7
diff --git a/posthog/hogql_queries/ai/ai_table_resolver.py b/posthog/hogql_queries/ai/ai_table_resolver.py
index f0430cf686f0..6057586bc290 100644
--- a/posthog/hogql_queries/ai/ai_table_resolver.py
+++ b/posthog/hogql_queries/ai/ai_table_resolver.py
@@ -6,6 +6,7 @@ from prometheus_client import Counter, Histogram
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Product, tag_queries, tags_context
@@ -83,6 +84,7 @@ def query_ai_events(
limit_context: LimitContext | None = None,
settings: HogQLGlobalSettings | None = None,
workload: Workload | None = None,
+ posthog_tables_only: bool = False,
) -> Any:
"""Execute a query written against the dedicated ai_events table.
@@ -111,6 +113,11 @@ def query_ai_events(
the thread default, but outside Celery (Django shell, pytest, management commands)
that signal does not fire — so callers that must run on a specific pool should not
rely on it implicitly.
+
+ ``posthog_tables_only=True`` compiles against PostHog's built-in tables only. Pass it when the
+ query and its placeholders reference no warehouse table, view or group type. Without it, every
+ call builds the team's full HogQL catalog, and on a team with thousands of warehouse tables
+ that build holds the GIL for longer than the query itself takes.
"""
kwargs: dict[str, Any] = {"query_type": query_type, "team": team, "user": user}
if timings is not None:
@@ -123,6 +130,13 @@ def query_ai_events(
kwargs["settings"] = settings
if workload is not None:
kwargs["workload"] = workload
+ if posthog_tables_only:
+ kwargs["context"] = HogQLContext(
+ team_id=team.pk,
+ team=team,
+ user=user,
+ database=Database.create_for_posthog_tables(team, modifiers=modifiers),
+ )
with tags_context(product=Product.LLM_ANALYTICS):
tag_queries(ai_query_source="dedicated_table")
@@ -146,6 +160,7 @@ def query_ai_events(
user=user,
use_new_events_schema=events_schema,
property_type_overrides=EVENTS_FALLBACK_PROPERTY_TYPE_OVERRIDES,
+ database=Database.create_for_posthog_tables(team, modifiers=modifiers) if posthog_tables_only else None,
),
}
diff --git a/posthog/hogql_queries/ai/session_query_runner.py b/posthog/hogql_queries/ai/session_query_runner.py
index f19f29754c26..4dc074c3858e 100644
--- a/posthog/hogql_queries/ai/session_query_runner.py
+++ b/posthog/hogql_queries/ai/session_query_runner.py
@@ -17,6 +17,7 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.constants import MAX_SELECT_TRACES_LIMIT_EXPORT, LimitContext
from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
from posthog.hogql.parser import parse_select
from posthog.clickhouse.query_tagging import Product, tag_queries, tags_context
@@ -87,6 +88,12 @@ class SessionQueryRunner(AnalyticsQueryRunner[SessionQueryResponse]):
query = self._build_query()
+ # Evaluation reads one session by id, so it skips the full per-team catalog build (see
+ # query_ai_events). Interactive reads keep the full catalog because their request modifiers
+ # can name warehouse tables.
+ database = (
+ Database.create_for_posthog_tables(self.team, modifiers=self.modifiers) if self.for_evaluation else None
+ )
with self.timings.measure("session_query_ai_events_execute"), tags_context(product=Product.LLM_ANALYTICS):
tag_queries(ai_query_source="dedicated_table")
query_result = self.paginator.execute_hogql_query(
@@ -101,6 +108,7 @@ class SessionQueryRunner(AnalyticsQueryRunner[SessionQueryResponse]):
timings=self.timings,
modifiers=self.modifiers,
limit_context=self.limit_context,
+ context=HogQLContext(team_id=self.team.pk, user=self.user, database=database),
)
if not query_result.results and not self.for_evaluation:
diff --git a/posthog/hogql_queries/ai/test/test_session_query_runner.py b/posthog/hogql_queries/ai/test/test_session_query_runner.py
index af02b27dd2d8..4e744b6fd39a 100644
--- a/posthog/hogql_queries/ai/test/test_session_query_runner.py
+++ b/posthog/hogql_queries/ai/test/test_session_query_runner.py
@@ -2,6 +2,7 @@ from datetime import UTC, datetime
from typing import Any
from posthog.test.base import BaseTest, ClickhouseTestMixin
+from unittest.mock import patch
from django.conf import settings
@@ -11,6 +12,7 @@ from posthog.schema import DateRange, SessionQuery
from posthog.hogql.constants import MAX_SELECT_TRACES_LIMIT_EXPORT, LimitContext
from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
from posthog.hogql.placeholders import replace_placeholders
from posthog.hogql.printer import prepare_and_print_ast
@@ -500,7 +502,11 @@ class TestSessionQueryRunner(ClickhouseTestMixin, BaseTest):
for_evaluation=True,
)
- with self.capture_select_queries() as queries:
+ # Evaluation reads skip the full catalog build, which is slow on large warehouse projects.
+ with (
+ self.capture_select_queries() as queries,
+ patch.object(Database, "create_for", side_effect=AssertionError("built the full HogQL catalog")),
+ ):
response = runner.calculate()
select_queries = _select_queries_without_metadata(queries)
diff --git a/posthog/hogql_queries/ai/trace_query_runner.py b/posthog/hogql_queries/ai/trace_query_runner.py
index 1c630d579f7f..2090b5b79592 100644
--- a/posthog/hogql_queries/ai/trace_query_runner.py
+++ b/posthog/hogql_queries/ai/trace_query_runner.py
@@ -89,12 +89,17 @@ class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):
query: TraceQuery
cached_response: CachedTraceQueryResponse
- def __init__(self, *args: Any, bound_events_to_date_range: bool = False, **kwargs: Any):
+ def __init__(
+ self, *args: Any, bound_events_to_date_range: bool = False, posthog_tables_only: bool = False, **kwargs: Any
+ ):
super().__init__(*args, **kwargs)
# The trace view wants the whole trace whatever the date picker says, so the default reads
# `ai_events` unbounded. A caller that grades a trace "as of" an instant opts in here, which
# holds the event rows to `dateRange.date_to` before the SQL aggregates the totals.
self._bound_events_to_date_range = bound_events_to_date_range
+ # See query_ai_events. The trace view keeps the full catalog because its property filters
+ # and modifiers can reference warehouse tables and group types.
+ self._posthog_tables_only = posthog_tables_only
def _calculate(self):
query_result = query_ai_events(
@@ -108,6 +113,7 @@ class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):
timings=self.timings,
modifiers=self.modifiers,
limit_context=self.limit_context,
+ posthog_tables_only=self._posthog_tables_only,
)
columns: list[str] = query_result.columns or []
diff --git a/posthog/temporal/ai_observability/run_aggregate_evaluation.py b/posthog/temporal/ai_observability/run_aggregate_evaluation.py
index d2c7df5dd606..8b2dfc1c380c 100644
--- a/posthog/temporal/ai_observability/run_aggregate_evaluation.py
+++ b/posthog/temporal/ai_observability/run_aggregate_evaluation.py
@@ -138,6 +138,7 @@ def check_trace_settled_activity(inputs: CheckTraceSettledInputs) -> str:
},
team=team,
query_type="TraceSettlePoll",
+ posthog_tables_only=True,
fall_back_to_events=False,
workload=Workload.OFFLINE,
)
@@ -218,6 +219,7 @@ def check_session_settled_activity(inputs: CheckSessionSettledInputs) -> str:
},
team=team,
query_type="SessionSettlePoll",
+ posthog_tables_only=True,
fall_back_to_events=False,
workload=Workload.OFFLINE,
)
@@ -321,6 +323,7 @@ def find_evaluation_quiet_point_activity(inputs: FindQuietPointInputs) -> str:
},
team=team,
query_type="EvaluationBackfillQuietPoint",
+ posthog_tables_only=True,
fall_back_to_events=False,
workload=Workload.OFFLINE,
)
diff --git a/posthog/temporal/ai_observability/run_session_evaluation.py b/posthog/temporal/ai_observability/run_session_evaluation.py
index b194cdcd1c13..5ba881dc7fdf 100644
--- a/posthog/temporal/ai_observability/run_session_evaluation.py
+++ b/posthog/temporal/ai_observability/run_session_evaluation.py
@@ -174,6 +174,7 @@ def _sum_session_payload_bytes(
team=team,
user=user,
query_type="SessionEvaluationPayloadBytes",
+ posthog_tables_only=True,
fall_back_to_events=False,
workload=Workload.OFFLINE,
)
@@ -228,6 +229,7 @@ def _count_session_events(
team=team,
user=user,
query_type="SessionEvaluationEventCount",
+ posthog_tables_only=True,
fall_back_to_events=False,
workload=Workload.OFFLINE,
)
diff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.py
index 2eb5b1d0fe95..4438662044fb 100644
--- a/posthog/temporal/ai_observability/run_trace_evaluation.py
+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py
@@ -216,6 +216,7 @@ def _count_trace_events(
team=team,
user=user,
query_type="TraceEvaluationEventCount",
+ posthog_tables_only=True,
fall_back_to_events=True,
)
if not result.results:
@@ -246,6 +247,7 @@ def _sum_trace_payload_bytes(
team=team,
user=user,
query_type="TraceEvaluationPayloadBytes",
+ posthog_tables_only=True,
fall_back_to_events=False,
)
if not result.results:
@@ -311,6 +313,7 @@ def _fetch_trace(
# latency from them. The runner applies the upper bound only. A lower bound would cut off the
# early events of the trace, which live runs do grade.
bound_events_to_date_range=bound_to_date_to,
+ posthog_tables_only=True,
)
response = runner.calculate()
if not response.results:
diff --git a/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
index 163f8029c920..5b11237373a4 100644
--- a/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
@@ -4,12 +4,15 @@ from typing import Any
import pytest
import time_machine
+from unittest.mock import patch
from temporalio import activity
from temporalio.exceptions import ApplicationError
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+from posthog.hogql.database.database import Database
+
from posthog.clickhouse.client import sync_execute
from posthog.models import Organization, Team
from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
@@ -45,6 +48,14 @@ def setup_data():
return {"organization": organization, "team": team}
+def no_full_catalog_build():
+ # A full build loads every warehouse table and view of the team. On a large warehouse project
+ # that holds the GIL long enough to starve the worker's event loop, so eval reads must not do it.
+ with patch.object(Database, "create_for", side_effect=AssertionError("eval read built the full HogQL catalog")):
+ yield
+
+
def _insert_ai_event(
*,
team: Team,
@@ -665,6 +676,7 @@ class TestRunAggregateEvaluationWorkflow:
assert elapsed < timedelta(hours=1)
[email protected]("no_full_catalog_build")
class TestCheckTraceSettledActivity:
@pytest.fixture(autouse=True)
def _frozen_clock(self):
@@ -744,6 +756,7 @@ class TestCheckTraceSettledActivity:
assert "trace active" in err.value.message
[email protected]("no_full_catalog_build")
class TestCheckSessionSettledActivity:
@pytest.fixture(autouse=True)
def _frozen_clock(self):
diff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.py
index 50a16ae300c3..6d606e1d2546 100644
--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py
@@ -13,10 +13,13 @@ from asgiref.sync import async_to_sync
from posthog.schema import LLMTrace, LLMTraceEvent
from posthog.hogql import ast
+from posthog.hogql.database.database import Database
from posthog.api.capture import CaptureInternalError
from posthog.constants import AvailableFeature
from posthog.models import Organization, PropertyDefinition, Team, User
+from posthog.models.ai_events.test_util import bulk_create_ai_events
+from posthog.models.event.util import bulk_create_events
from posthog.temporal.ai_observability.run_session_evaluation import fetch_session_for_evaluation
from products.access_control.backend.facade.contracts import PropertyAccessLevel
@@ -490,6 +493,46 @@ class TestFetchTraceForEvaluation:
assert outcome.skip_reason == "trace_not_found"
assert outcome.trace is None
+ @pytest.mark.django_db(transaction=True)
+ # Rows only in `events` send the count and the trace read down the events fallback.
+ @pytest.mark.parametrize("insert_events", [bulk_create_ai_events, bulk_create_events])
+ def test_reads_the_trace_without_building_the_full_catalog(self, setup_data, insert_events):
+ team = setup_data["team"]
+ trace_id = f"trace-{uuid.uuid4()}"
+ timestamp = FROZEN_NOW - timedelta(minutes=1)
+ insert_events(
+ [
+ {
+ "event": "$ai_trace",
+ "team": team,
+ "distinct_id": "user",
+ "timestamp": timestamp,
+ "properties": {"$ai_trace_id": trace_id},
+ },
+ {
+ "event": "$ai_generation",
+ "team": team,
+ "distinct_id": "user",
+ "timestamp": timestamp,
+ "properties": {
+ "$ai_trace_id": trace_id,
+ "$ai_input": [{"role": "user", "content": "What is the weather?"}],
+ "$ai_output_choices": [{"role": "assistant", "content": "Sunny all day."}],
+ },
+ },
+ ]
+ )
+
+ with (
+ time_machine.travel(FROZEN_NOW, tick=False),
+ patch.object(Database, "create_for", side_effect=AssertionError("eval read built the full HogQL catalog")),
+ ):
+ outcome = fetch_trace_for_evaluation(team.id, trace_id, FROZEN_NOW)
+
+ assert outcome.skip_reason is None
+ assert outcome.trace is not None
+ assert [event.event for event in outcome.trace.events] == ["$ai_generation"]
+
class TestRunHogEvalOverRecentTraces:
@patch("posthog.temporal.ai_observability.run_trace_evaluation.query_ai_events")