: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(ai-evals): unblock both failing AI evals CI jobs (#92479)
Daniel Parkercf81dcacccdd
diff --git a/ee/hogai/eval/ci/eval_funnel.py b/ee/hogai/eval/ci/eval_funnel.pyindex 4eb75a7906b5..17b5d0796afd 100644--- a/ee/hogai/eval/ci/eval_funnel.py+++ b/ee/hogai/eval/ci/eval_funnel.py@@ -13,8 +13,6 @@ from posthog.schema import (NodeKind,)-from ee.hogai.chat_agent.funnels.toolkit import FUNNEL_SCHEMA-from ..base import MaxPublicEvalfrom ..scorers import PlanAndQueryOutput, PlanCorrectness, QueryAndPlanAlignment, QueryKindSelection, TimeRangeRelevancy@@ -40,7 +38,7 @@ async def eval_funnel(call_root_for_insight_generation, pytestconfig):),QueryAndPlanAlignment(query_kind=NodeKind.FUNNELS_QUERY,- json_schema=FUNNEL_SCHEMA,+ query_model=AssistantFunnelsQuery,evaluation_criteria="""1. Series sequence: Verify that the funnel steps in the query's `series` array match the sequence order and events specified in the plan. The order must be preserved if funnel steps are set to be sequential (ordered).2. Event names: Ensure each funnel step uses the exact event name specified in the plan for that step position.@@ -68,7 +66,7 @@ async def eval_funnel(call_root_for_insight_generation, pytestconfig):9. Aggregation: Check if group aggregation is correctly set when plan specifies group-based funnels (`aggregation_group_type_index`).10. Missing implementation: Heavily penalize when key plan elements are missing (e.g., missing exclusions, wrong sequence order, incorrect breakdown).11. Unnecessary fields: Penalize inclusion of fields not mentioned in the plan or that don't align with the funnel intent.-12. Schema compliance: Ensure all query fields conform to the FUNNEL_SCHEMA structure and constraints.+12. Schema compliance: Ensure all query fields conform to the JSON schema structure and constraints above.""",),TimeRangeRelevancy(query_kind=NodeKind.FUNNELS_QUERY),diff --git a/ee/hogai/eval/ci/eval_retention.py b/ee/hogai/eval/ci/eval_retention.pyindex 23c91dcd0942..336901653782 100644--- a/ee/hogai/eval/ci/eval_retention.py+++ b/ee/hogai/eval/ci/eval_retention.py@@ -4,8 +4,6 @@ from braintrust import EvalCasefrom posthog.schema import AssistantRetentionEventsNode, AssistantRetentionFilter, AssistantRetentionQuery, NodeKind-from ee.hogai.chat_agent.retention.toolkit import RETENTION_SCHEMA-from ..base import MaxPublicEvalfrom ..scorers import PlanAndQueryOutput, PlanCorrectness, QueryAndPlanAlignment, QueryKindSelection, TimeRangeRelevancy@@ -30,7 +28,7 @@ async def eval_retention(call_root_for_insight_generation, pytestconfig):),QueryAndPlanAlignment(query_kind=NodeKind.RETENTION_QUERY,- json_schema=RETENTION_SCHEMA,+ query_model=AssistantRetentionQuery,evaluation_criteria="""1. Returning event alignment: Verify that the returning event in `retentionFilter.returningEntity.name` exactly matches the returning event specified in the plan.2. Target event alignment: Verify that the target event in `retentionFilter.targetEntity.name` exactly matches the target event specified in the plan.diff --git a/ee/hogai/eval/ci/eval_trends.py b/ee/hogai/eval/ci/eval_trends.pyindex f757e5833860..96a5851f4136 100644--- a/ee/hogai/eval/ci/eval_trends.py+++ b/ee/hogai/eval/ci/eval_trends.py@@ -15,8 +15,6 @@ from posthog.schema import (TrendsFormulaNode,)-from ee.hogai.chat_agent.trends.toolkit import TRENDS_SCHEMA-from ..base import MaxPublicEvalfrom ..scorers import PlanAndQueryOutput, PlanCorrectness, QueryAndPlanAlignment, QueryKindSelection, TimeRangeRelevancy@@ -433,7 +431,7 @@ async def eval_trends(call_root_for_insight_generation, pytestconfig):),QueryAndPlanAlignment(query_kind=NodeKind.TRENDS_QUERY,- json_schema=TRENDS_SCHEMA,+ query_model=AssistantTrendsQuery,evaluation_criteria="""1. Events alignment: Verify that all events mentioned in the plan are correctly represented in the query's `series` array. For "All events", the `event` field should be `null`.2. Series math: Ensure the math operation for each event in the query matches what's specified in the plan, for example:diff --git a/ee/hogai/eval/scorers/__init__.py b/ee/hogai/eval/scorers/__init__.pyindex ceaedecbd64a..67b8ddb7c42f 100644--- a/ee/hogai/eval/scorers/__init__.py+++ b/ee/hogai/eval/scorers/__init__.py@@ -5,6 +5,7 @@ from autoevals.llm import LLMClassifierfrom autoevals.partial import ScorerWithPartialfrom autoevals.ragas import AnswerSimilarityfrom braintrust import Score+from pydantic import BaseModelfrom posthog.schema import AssistantMessage, AssistantToolCall, NodeKind@@ -184,6 +185,25 @@ Details matter greatly here - including math types or property types - so be har)+MAX_JUDGE_JSON_SCHEMA_CHARS = 100_000+++def build_judge_json_schema(query_kind: NodeKind, query_model: type[BaseModel]) -> str:+ """Serialize a query schema for an LLM judge, keeping `$ref`s instead of inlining shared definitions.++ Insight toolkits dereference their schemas because the query generator's tool call needs a flat one.+ That repeats the property filter unions inside every series node and roughly doubles the size, while+ a judge reads references just as well.+ """+ json_schema_str = json.dumps(query_model.model_json_schema())+ if len(json_schema_str) > MAX_JUDGE_JSON_SCHEMA_CHARS:+ raise ValueError(+ f"JSON schema of {query_kind} has blown up in size, are you sure you want to put this into an LLM? "+ "You CAN increase this limit if you're sure"+ )+ return json_schema_str++class QueryAndPlanAlignment(LLMClassifier):"""Evaluate if the generated SQL query aligns with the plan generated in the previous step."""@@ -213,13 +233,8 @@ class QueryAndPlanAlignment(LLMClassifier):return Score(name=self._name(), score=0.0, metadata={"reason": "Query failed to be generated"})return super()._run_eval_sync(serialize_output(output), serialize_output(expected), **kwargs)- def __init__(self, query_kind: NodeKind, json_schema: dict, evaluation_criteria: str, **kwargs):- json_schema_str = json.dumps(json_schema)- if len(json_schema_str) > 100_000:- raise ValueError(- f"JSON schema of {query_kind} has blown up in size, are you sure you want to put this into an LLM? "- "You CAN increase this limit if you're sure"- )+ def __init__(self, query_kind: NodeKind, query_model: type[BaseModel], evaluation_criteria: str, **kwargs):+ json_schema_str = build_judge_json_schema(query_kind, query_model)super().__init__(name="query_and_plan_alignment",prompt_template="""diff --git a/ee/hogai/test/test_eval_scorers.py b/ee/hogai/test/test_eval_scorers.pynew file mode 100644index 000000000000..76a6c52ab9c5--- /dev/null+++ b/ee/hogai/test/test_eval_scorers.py@@ -0,0 +1,27 @@+import json++from django.test import SimpleTestCase++from parameterized import parameterized+from pydantic import BaseModel++from posthog.schema import AssistantFunnelsQuery, AssistantRetentionQuery, AssistantTrendsQuery, NodeKind++from ee.hogai.eval.scorers import MAX_JUDGE_JSON_SCHEMA_CHARS, build_judge_json_schema+++class TestBuildJudgeJsonSchema(SimpleTestCase):+ @parameterized.expand(+ [+ (NodeKind.TRENDS_QUERY, AssistantTrendsQuery),+ (NodeKind.FUNNELS_QUERY, AssistantFunnelsQuery),+ (NodeKind.RETENTION_QUERY, AssistantRetentionQuery),+ ]+ )+ def test_insight_query_schema_fits_the_judge_budget(+ self, query_kind: NodeKind, query_model: type[BaseModel]+ ) -> None:+ json_schema_str = build_judge_json_schema(query_kind, query_model)++ self.assertLessEqual(len(json_schema_str), MAX_JUDGE_JSON_SCHEMA_CHARS)+ self.assertEqual(json.loads(json_schema_str)["title"], query_model.__name__)diff --git a/posthog/models/group_type_mapping.py b/posthog/models/group_type_mapping.pyindex 355be6cae68b..24811ddd8ce4 100644--- a/posthog/models/group_type_mapping.py+++ b/posthog/models/group_type_mapping.py@@ -16,6 +16,7 @@ from django.utils import timezoneimport structlogfrom prometheus_client import Counter+import posthog.personhog_client.client as personhog_clientfrom posthog.models.utils import RootTeamMixinfrom posthog.personhog_client import ReadConsistency, consistency_to_read_optionsfrom posthog.personhog_client.client import personhog_call, require_personhog_client@@ -728,7 +729,14 @@ def clear_dashboard_from_group_type_mapping("""from posthog.personhog_client.proto import GetGroupTypeMappingByDashboardIdRequest, UpdateGroupTypeMappingRequest- client = require_personhog_client()+ client = personhog_client.get_personhog_client()+ if client is None:+ # personhog is the only group type mapping store, so without a client there is+ # no mapping that can reference this dashboard. Invalidate any cached mapping+ # before letting the delete proceed.+ if project_id is not None:+ invalidate_group_types_cache(project_id)+ returndef _fn() -> None:resp = client.get_group_type_mapping_by_dashboard_id(diff --git a/posthog/models/test/test_group_type_mapping.py b/posthog/models/test/test_group_type_mapping.pyindex 70cae658f84d..b4782342b9d8 100644--- a/posthog/models/test/test_group_type_mapping.py+++ b/posthog/models/test/test_group_type_mapping.py@@ -708,6 +708,17 @@ class TestClearDashboardFromGroupTypeMapping(SimpleTestCase):mock_client.update_group_type_mapping.assert_not_called()mock_invalidate.assert_not_called()+ @patch("posthog.models.group_type_mapping.personhog_call")+ @patch("posthog.models.group_type_mapping.invalidate_group_types_cache")+ @patch(_CLIENT_PATCH)+ def test_unconfigured_client_invalidates_project_cache(self, mock_get_client, mock_invalidate, mock_personhog_call):+ mock_get_client.return_value = None++ clear_dashboard_from_group_type_mapping(team_id=10, dashboard_id=42, project_id=314)++ mock_personhog_call.assert_not_called()+ mock_invalidate.assert_called_once_with(314)+# ── Terminal-failure hardening tests ──────────────────────────────────