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.

feat(aio): migrate signals evals and retire offline event results (#118593)

Radu Raicea7aadbf88592e
diff --git a/docs/internal/ai-offline-evaluation-reporting.md b/docs/internal/ai-offline-evaluation-reporting.md
index 188d1d7d2e6e..c5c3002b98c0 100644
--- a/docs/internal/ai-offline-evaluation-reporting.md
+++ b/docs/internal/ai-offline-evaluation-reporting.md
@@ -2,7 +2,8 @@
The evaluation harness in `products/posthog_ai/eval_harness/` reports public-suite scorer results to Braintrust.
The SQL suite also publishes those results to PostHog's offline experiment API when configured.
-The harness no longer emits legacy `$ai_evaluation` result events. Agent and judge trace capture remains available.
+The Signals pytest suites reuse the same publisher for their completed results.
+Agent and judge trace capture remains available.
Reporting does not run the agent or scorers again.
Use `hogli evals` to run PostHog AI 2.0 suites. See the [eval harness guide](../../products/posthog_ai/eval_harness/README.md) for suite discovery and execution.
@@ -146,6 +147,41 @@ result = Score(
The numeric `score` still controls existing Braintrust and local aggregates; `result` describes the offline outcome. Configure this example's scorer kind as `categorical`.
Scorer provisioning stays separate from uploading results, so publishing requires only the ingestion scope and does not create or modify scorer definitions.
+## Signals pytest suites
+
+The suites in `products/signals/eval/` keep their pytest runner and mocked infrastructure.
+They publish completed metrics through `OfflineEvalPublisher` without running the pipeline or judges again.
+Run them from the repository root:
+
+```bash
+pytest products/signals/eval/eval_grouping_e2e.py products/signals/eval/eval_scout_safety.py
+```
+
+The grouping suite has 111 input signals across 48 fixture groups; scout safety has 7 cases.
+Each suite execution publishes one experiment: `signals/grouping-e2e` or `signals/scout-safety`.
+Grouping records separate items for pipeline stages, generated reports, and aggregate statistics, so uploaded item counts exceed the input signal count.
+Scout safety records one item per case and one aggregate item.
+Use `--limit N` for a subset; the run metadata records the limit and checkout revision.
+
+Both suites target project `2` and pin immutable scorer version UUIDs in
+[`offline_config.py`](../../products/signals/eval/offline_config.py).
+There are 16 grouping scorers and 3 scout safety scorers, reused across inputs.
+Classification checks at different stages have separate scorers.
+Per-report `group_recall` and aggregate `mean_group_recall` also stay separate.
+Metrics that do not apply to an item's stage publish `not_applicable`.
+Numeric definitions allow ARI in `[-1, 1]` and query cosine distance in `[0, 2]`.
+
+Set `POSTHOG_OFFLINE_EVAL_API_KEY` with `offline_evaluation_ingestion:write` and optionally
+`POSTHOG_OFFLINE_EVAL_HOST`, as for the SQL suite.
+Missing or invalid configuration disables offline uploads with a message; upload failures also report a message without changing the eval outcome.
+Successful uploads print the experiment URL.
+Scout results upload before the existing assertion against unsafe payload leaks.
+Each execution has a fresh experiment ID, so repeated runs do not overwrite one another.
+
+`--no-capture` suppresses result uploads and trace capture.
+`POSTHOG_PROJECT_API_KEY` and `POSTHOG_HOST` remain the separate trace-capture settings.
+Runs appear in the offline experiments UI.
+
## Postgres experiment ingestion
The project API accepts offline experiment results behind the `ai-observability-offline-evaluations` feature flag.
@@ -245,7 +281,7 @@ Automatic payload deletion and usage billing are not enabled by these endpoints.
## Postgres experiment reads
Read endpoints use the same feature flag as ingestion.
-The offline UI uses these APIs. The configured SQL pilot publishes results here; legacy `$ai_evaluation` events do not populate these views.
+The offline UI uses these APIs. The configured SQL pilot and Signals suites publish results here.
The following GET paths are relative to `/api/projects/{project_id}/ai_observability/`:
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.json
index e2eb162be1de..a7200b58c990 100644
--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json
+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json
@@ -215,7 +215,7 @@
},
"$ai_eval_source": {
"description": "The source that triggered this evaluation.",
- "examples": ["signals-grouping", "sandboxed-agent", "one-shot"],
+ "examples": ["sandboxed-agent", "one-shot"],
"label": "AI eval source (LLM)"
},
"$ai_evaluation_allows_na": {
@@ -310,22 +310,10 @@
"examples": ["llm_judge", "hog"],
"label": "AI evaluation type (LLM)"
},
- "$ai_expected": {
- "description": "The expected output for comparison in this evaluation.",
- "label": "AI expected output (LLM)"
- },
"$ai_experiment_id": {
"description": "The unique identifier of the experiment this event belongs to.",
"label": "AI experiment ID (LLM)"
},
- "$ai_experiment_item_id": {
- "description": "The unique identifier of the individual item being evaluated in an experiment.",
- "label": "AI experiment item ID (LLM)"
- },
- "$ai_experiment_item_name": {
- "description": "The name of the individual item being evaluated in an experiment.",
- "label": "AI experiment item name (LLM)"
- },
"$ai_experiment_name": {
"description": "The name of the experiment this event belongs to.",
"label": "AI experiment name (LLM)"
@@ -441,10 +429,6 @@
"examples": ["negative", "95"],
"label": "AI Metric Value (LLM)"
},
- "$ai_metric_version": {
- "description": "The version of the metric used for evaluation.",
- "label": "AI metric version (LLM)"
- },
"$ai_model": {
"description": "The model used to generate the output from the LLM API.",
"examples": ["gpt-4o-mini"],
@@ -554,26 +538,6 @@
"examples": ["https://api.openai.com/v1/chat/completions"],
"label": "AI Request URL (LLM)"
},
- "$ai_result_type": {
- "description": "The type of result for this evaluation metric.",
- "examples": ["binary", "numeric", "categorical"],
- "label": "AI result type (LLM)"
- },
- "$ai_score": {
- "description": "The numeric score assigned by this evaluation metric.",
- "label": "AI score (LLM)",
- "type": "Numeric"
- },
- "$ai_score_max": {
- "description": "The maximum possible score for this evaluation metric.",
- "label": "AI score max (LLM)",
- "type": "Numeric"
- },
- "$ai_score_min": {
- "description": "The minimum possible score for this evaluation metric.",
- "label": "AI score min (LLM)",
- "type": "Numeric"
- },
"$ai_session_id": {
"description": "Groups related traces together in a session (e.g., a conversation or workflow). One session can contain many traces.",
"examples": ["session-abc-123", "conv-user-456"],
@@ -4080,7 +4044,7 @@
},
"$ai_eval_source": {
"description": "The source that triggered this evaluation.",
- "examples": ["signals-grouping", "sandboxed-agent", "one-shot"],
+ "examples": ["sandboxed-agent", "one-shot"],
"label": "AI eval source (LLM)"
},
"$ai_evaluation_allows_na": {
@@ -4175,22 +4139,10 @@
"examples": ["llm_judge", "hog"],
"label": "AI evaluation type (LLM)"
},
- "$ai_expected": {
- "description": "The expected output for comparison in this evaluation.",
- "label": "AI expected output (LLM)"
- },
"$ai_experiment_id": {
"description": "The unique identifier of the experiment this event belongs to.",
"label": "AI experiment ID (LLM)"
},
- "$ai_experiment_item_id": {
- "description": "The unique identifier of the individual item being evaluated in an experiment.",
- "label": "AI experiment item ID (LLM)"
- },
- "$ai_experiment_item_name": {
- "description": "The name of the individual item being evaluated in an experiment.",
- "label": "AI experiment item name (LLM)"
- },
"$ai_experiment_name": {
"description": "The name of the experiment this event belongs to.",
"label": "AI experiment name (LLM)"
@@ -4306,10 +4258,6 @@
"examples": ["negative", "95"],
"label": "AI Metric Value (LLM)"
},
- "$ai_metric_version": {
- "description": "The version of the metric used for evaluation.",
- "label": "AI metric version (LLM)"
- },
"$ai_model": {
"description": "The model used to generate the output from the LLM API.",
"examples": ["gpt-4o-mini"],
@@ -4419,26 +4367,6 @@
"examples": ["https://api.openai.com/v1/chat/completions"],
"label": "AI Request URL (LLM)"
},
- "$ai_result_type": {
- "description": "The type of result for this evaluation metric.",
- "examples": ["binary", "numeric", "categorical"],
- "label": "AI result type (LLM)"
- },
- "$ai_score": {
- "description": "The numeric score assigned by this evaluation metric.",
- "label": "AI score (LLM)",
- "type": "Numeric"
- },
- "$ai_score_max": {
- "description": "The maximum possible score for this evaluation metric.",
- "label": "AI score max (LLM)",
- "type": "Numeric"
- },
- "$ai_score_min": {
- "description": "The minimum possible score for this evaluation metric.",
- "label": "AI score min (LLM)",
- "type": "Numeric"
- },
"$ai_session_id": {
"description": "Groups related traces together in a session (e.g., a conversation or workflow). One session can contain many traces.",
"examples": ["session-abc-123", "conv-user-456"],
diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.py
index 919516052099..493c2c1df970 100644
--- a/posthog/taxonomy/taxonomy.py
+++ b/posthog/taxonomy/taxonomy.py
@@ -2768,29 +2768,17 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
"$ai_eval_source": {
"label": "AI eval source (LLM)",
"description": "The source that triggered this evaluation.",
- "examples": ["signals-grouping", "sandboxed-agent", "one-shot"],
+ "examples": ["sandboxed-agent", "one-shot"],
},
"$ai_evaluation_type": {
"label": "AI evaluation type (LLM)",
"description": "The type of evaluation that was run.",
"examples": ["llm_judge", "hog"],
},
- "$ai_expected": {
- "label": "AI expected output (LLM)",
- "description": "The expected output for comparison in this evaluation.",
- },
"$ai_experiment_id": {
"label": "AI experiment ID (LLM)",
"description": "The unique identifier of the experiment this event belongs to.",
},
- "$ai_experiment_item_id": {
- "label": "AI experiment item ID (LLM)",
- "description": "The unique identifier of the individual item being evaluated in an experiment.",
- },
- "$ai_experiment_item_name": {
- "label": "AI experiment item name (LLM)",
- "description": "The name of the individual item being evaluated in an experiment.",
- },
"$ai_experiment_name": {
"label": "AI experiment name (LLM)",
"description": "The name of the experiment this event belongs to.",
@@ -2827,10 +2815,6 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
"examples": [1024, 4096],
"type": "Numeric",
},
- "$ai_metric_version": {
- "label": "AI metric version (LLM)",
- "description": "The version of the metric used for evaluation.",
- },
"$ai_output": {
"label": "AI output (LLM)",
"description": "The output text from a generation or the text being evaluated.",
@@ -2839,26 +2823,6 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
"label": "AI project name (LLM)",
"description": "The project name associated with this AI event.",
},
- "$ai_result_type": {
- "label": "AI result type (LLM)",
- "description": "The type of result for this evaluation metric.",
- "examples": ["binary", "numeric", "categorical"],
- },
- "$ai_score": {
- "label": "AI score (LLM)",
- "description": "The numeric score assigned by this evaluation metric.",
- "type": "Numeric",
- },
- "$ai_score_max": {
- "label": "AI score max (LLM)",
- "description": "The maximum possible score for this evaluation metric.",
- "type": "Numeric",
- },
- "$ai_score_min": {
- "label": "AI score min (LLM)",
- "description": "The minimum possible score for this evaluation metric.",
- "type": "Numeric",
- },
"$ai_span_type": {
"label": "AI span type (LLM)",
"description": "The type of this span in the AI trace tree.",
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 153f66b28192..9338c1ac82b4 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -164,7 +164,6 @@
1 products/signals/backend/temporal/emit_eval_signal.py
1 products/signals/backend/temporal/emitter.py
1 products/signals/backend/temporal/grouping_v2.py
-1 products/signals/eval/capture.py
1 products/signals/eval/common.py
1 products/skills/backend/marketplace/git_smart_http.py
1 products/slack_app/backend/tests/services/test_run_preferences.py
diff --git a/products/ai_observability/backend/api/__init__.py b/products/ai_observability/backend/api/__init__.py
index 117dd4d33928..6e0ba691f316 100644
--- a/products/ai_observability/backend/api/__init__.py
+++ b/products/ai_observability/backend/api/__init__.py
@@ -11,7 +11,6 @@ from .evaluation_runs import EvaluationRunViewSet
from .evaluations import EvaluationViewSet
from .instrumentation_checklist import AIObservabilityInstrumentationChecklistViewSet
from .models import LLMModelsViewSet
-from .offline_evaluations import AIObservabilityOfflineEvaluationsViewSet
from .offline_experiment_reads import OfflineScorerViewSet
from .offline_experiments import OfflineExperimentViewSet
from .parser_recipes import ParserRecipeViewSet
@@ -51,7 +50,6 @@ __all__ = [
"ReviewQueueViewSet",
"ReviewQueueItemViewSet",
"ScoreDefinitionViewSet",
- "AIObservabilityOfflineEvaluationsViewSet",
"OfflineExperimentViewSet",
"OfflineScorerViewSet",
"PersonalSpendInternalViewSet",
diff --git a/products/ai_observability/backend/api/offline_evaluations.py b/products/ai_observability/backend/api/offline_evaluations.py
deleted file mode 100644
index c822fbd1fb69..000000000000
--- a/products/ai_observability/backend/api/offline_evaluations.py
+++ /dev/null
@@ -1,270 +0,0 @@
-from collections import namedtuple
-from typing import TYPE_CHECKING, cast
-
-import structlog
-from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import extend_schema
-from rest_framework import serializers, status, viewsets
-from rest_framework.decorators import action
-from rest_framework.request import Request
-from rest_framework.response import Response
-
-from posthog.hogql import ast
-from posthog.hogql.constants import LimitContext
-from posthog.hogql.parser import parse_select
-from posthog.hogql.query import execute_hogql_query
-
-from posthog.api.monitoring import monitor
-from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.clickhouse.query_tagging import Feature, Product, tags_context
-from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
-from posthog.permissions import AccessControlPermission
-
-from products.ai_observability.backend.api.metrics import llma_track_latency
-
-if TYPE_CHECKING:
- from posthog.models import User
-
-logger = structlog.get_logger(__name__)
-
-OFFLINE_EXPERIMENT_ITEMS_LIMIT = 20000
-
-# Preflight on `events` so the `(team_id, toDate(timestamp), event)` sort
-# key prunes by date; `posthog.ai_events` is keyed `(team_id, trace_id,
-# timestamp)` and can't prune until trace_id is bounded.
-_OFFLINE_EXPERIMENT_ITEMS_PREFLIGHT_SQL = """
-SELECT
- nullIf(properties.$ai_experiment_item_id, '') as item_id,
- argMax(properties.$ai_experiment_item_name, timestamp) as experiment_item_name,
- argMax(properties.$ai_experiment_name, timestamp) as experiment_name,
- nullIf(properties.$ai_metric_name, '') as metric_name,
- nullIf(properties.$ai_metric_version, '') as metric_version,
- argMax(properties.$ai_status, timestamp) as status,
- argMax(properties.$ai_score, timestamp) as score,
- argMax(properties.$ai_score_min, timestamp) as score_min,
- argMax(properties.$ai_score_max, timestamp) as score_max,
- argMax(properties.$ai_result_type, timestamp) as result_type,
- argMax(properties.$ai_reasoning, timestamp) as reasoning,
- argMax(properties.$ai_trace_id, timestamp) as trace_id,
- argMax(properties.$ai_target_id, timestamp) as target_id,
- argMax(properties.$ai_target_type, timestamp) as target_type,
- argMax(properties.$ai_dataset_id, timestamp) as dataset_id,
- argMax(properties.$ai_dataset_item_id, timestamp) as dataset_item_id,
- argMax(properties.$ai_expected, timestamp) as ai_expected,
- max(timestamp) as last_seen_at,
- min(timestamp) as first_seen_at
-FROM events
-WHERE
- event = '$ai_evaluation'
- AND properties.$ai_experiment_id = {experiment_id}
- AND nullIf(properties.$ai_experiment_item_id, '') IS NOT NULL
- AND ({date_from_is_null} OR timestamp >= parseDateTimeBestEffort({date_from}))
- AND ({date_to_is_null} OR timestamp <= parseDateTimeBestEffort({date_to}))
-GROUP BY item_id, metric_name, metric_version
-ORDER BY last_seen_at DESC
-LIMIT {limit}
-"""
-
-_OFFLINE_EXPERIMENT_ITEMS_HEAVY_SQL = """
-SELECT
- trace_id,
- argMax(input, timestamp) as ai_input,
- argMax(output, timestamp) as ai_output
-FROM posthog.ai_events AS ai_events
-WHERE event = '$ai_evaluation'
- AND trace_id IN {trace_ids}
- AND timestamp >= {ts_start}
- AND timestamp <= {ts_end}
-GROUP BY trace_id
-"""
-
-_PreflightRow = namedtuple(
- "_PreflightRow",
- [
- "item_id",
- "experiment_item_name",
- "experiment_name",
- "metric_name",
- "metric_version",
- "status",
- "score",
- "score_min",
- "score_max",
- "result_type",
- "reasoning",
- "trace_id",
- "target_id",
- "target_type",
- "dataset_id",
- "dataset_item_id",
- "ai_expected",
- "last_seen_at",
- "first_seen_at",
- ],
-)
-
-
-class OfflineExperimentItemsRequestSerializer(serializers.Serializer):
- experiment_id = serializers.CharField(
- required=True,
- allow_blank=False,
- help_text="`$ai_experiment_id` whose offline-evaluation items to return.",
- )
- date_from = serializers.CharField(
- required=False,
- allow_null=True,
- default=None,
- help_text="Lower bound on `timestamp` (ISO-8601). Omit to leave the lower bound open.",
- )
- date_to = serializers.CharField(
- required=False,
- allow_null=True,
- default=None,
- help_text="Upper bound on `timestamp` (ISO-8601). Omit to leave the upper bound open.",
- )
-
-
-class OfflineExperimentItemsResponseSerializer(serializers.Serializer):
- results = serializers.ListField(
- child=serializers.ListField(),
- help_text="Tuple-positional rows; positions match `RawOfflineExperimentMetricRow` in the frontend.",
- )
-
-
-class AIObservabilityOfflineEvaluationsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
- scope_object = "evaluation"
- scope_object_read_actions = ["experiment_items"]
- requires_resource_level_access = True
- permission_classes = [AccessControlPermission]
-
- @extend_schema(
- request=OfflineExperimentItemsRequestSerializer,
- responses={
- 200: OfflineExperimentItemsResponseSerializer,
- 400: OpenApiTypes.OBJECT,
- 500: OpenApiTypes.OBJECT,
- },
- tags=["AI observability"],
- )
- @action(detail=False, methods=["post"], url_path="experiment_items")
- @llma_track_latency("llma_offline_evaluations_experiment_items")
- @monitor(feature=None, endpoint="llma_offline_evaluations_experiment_items", method="POST")
- def experiment_items(self, request: Request, **kwargs) -> Response:
- serializer = OfflineExperimentItemsRequestSerializer(data=request.data)
- if not serializer.is_valid():
- return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
-
- experiment_id: str = serializer.validated_data["experiment_id"]
- date_from: str | None = serializer.validated_data.get("date_from") or None
- date_to: str | None = serializer.validated_data.get("date_to") or None
-
- # Parse-time, not execute-time: `properties.$ai_* + GROUP BY +
- # {placeholder}` trips `HogVMException: Global variable not found:
- # properties` in bytecode. parse_select-time substitution embeds
- # Constants into the AST and bypasses the bytecode path.
- preflight_placeholders: dict[str, ast.Expr] = {
- "experiment_id": ast.Constant(value=experiment_id),
- # `parseDateTimeBestEffort` rejects "", so the `_is_null` flags
- # short-circuit the range filter when no bound was passed.
- "date_from": ast.Constant(value=date_from or ""),
- "date_to": ast.Constant(value=date_to or ""),
- "date_from_is_null": ast.Constant(value=date_from is None),
- "date_to_is_null": ast.Constant(value=date_to is None),
- "limit": ast.Constant(value=OFFLINE_EXPERIMENT_ITEMS_LIMIT),
- }
- preflight_query = parse_select(_OFFLINE_EXPERIMENT_ITEMS_PREFLIGHT_SQL, placeholders=preflight_placeholders)
-
- with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=self.team_id):
- try:
- preflight_result = execute_hogql_query(
- query=preflight_query,
- placeholders={},
- team=self.team,
- user=cast("User", request.user),
- query_type="LLMOfflineEvaluationItemsResolve",
- limit_context=LimitContext.QUERY,
- )
- except Exception as e:
- logger.exception(
- "Failed to resolve offline evaluation experiment items",
- team_id=self.team_id,
- experiment_id=experiment_id,
- error=str(e),
- )
- return Response(
- {"error": "Failed to fetch offline evaluation items"},
- status=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
-
- preflight_rows = [_PreflightRow(*row) for row in (preflight_result.results or [])]
- if not preflight_rows:
- return Response({"results": []}, status=status.HTTP_200_OK)
-
- traced_rows = [row for row in preflight_rows if row.trace_id]
- trace_ids = [str(row.trace_id) for row in traced_rows]
- ai_input_output_by_trace: dict[str, tuple] = {}
-
- if trace_ids:
- ts_start = min(row.first_seen_at for row in traced_rows)
- ts_end = max(row.last_seen_at for row in traced_rows)
-
- heavy_query = parse_select(_OFFLINE_EXPERIMENT_ITEMS_HEAVY_SQL)
- try:
- heavy_result = query_ai_events(
- query=heavy_query,
- placeholders={
- "trace_ids": ast.Tuple(exprs=[ast.Constant(value=tid) for tid in trace_ids]),
- "ts_start": ast.Constant(value=ts_start),
- "ts_end": ast.Constant(value=ts_end),
- },
- team=self.team,
- user=cast("User", request.user),
- query_type="LLMOfflineEvaluationItems",
- fall_back_to_events=True,
- limit_context=LimitContext.QUERY,
- )
- except Exception as e:
- logger.exception(
- "Failed to fetch offline evaluation items heavy columns",
- team_id=self.team_id,
- experiment_id=experiment_id,
- error=str(e),
- )
- return Response(
- {"error": "Failed to fetch offline evaluation items"},
- status=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
-
- ai_input_output_by_trace = {
- str(trace_id): (ai_input, ai_output)
- for trace_id, ai_input, ai_output in (heavy_result.results or [])
- }
-
- results = []
- for row in preflight_rows:
- ai_input, ai_output = ai_input_output_by_trace.get(str(row.trace_id), (None, None))
- results.append(
- [
- row.item_id,
- row.experiment_item_name,
- row.experiment_name,
- row.metric_name,
- row.metric_version,
- row.status,
- row.score,
- row.score_min,
- row.score_max,
- row.result_type,
- row.reasoning,
- row.trace_id,
- row.dataset_id,
- row.dataset_item_id,
- ai_input,
- ai_output,
- row.ai_expected,
- row.last_seen_at,
- row.target_id,
- row.target_type,
- ]
- )
- return Response({"results": results}, status=status.HTTP_200_OK)
diff --git a/products/ai_observability/backend/api/test/test_offline_evaluations.py b/products/ai_observability/backend/api/test/test_offline_evaluations.py
deleted file mode 100644
index 30a0baab38ce..000000000000
--- a/products/ai_observability/backend/api/test/test_offline_evaluations.py
+++ /dev/null
@@ -1,383 +0,0 @@
-from datetime import UTC, datetime
-from typing import Any, cast
-
-from posthog.test.base import APIBaseTest
-from unittest.mock import MagicMock, patch
-
-from parameterized import parameterized
-from rest_framework import status
-
-from posthog.constants import AvailableFeature
-from posthog.models.organization import OrganizationMembership
-from posthog.models.user import User
-
-from products.access_control.backend.models.access_control import AccessControl
-from products.ai_observability.backend.models.evaluations import Evaluation
-
-
-class TestOfflineEvaluationItemsEndpoint(APIBaseTest):
- URL: str = ""
-
- def setUp(self) -> None:
- super().setUp()
- self.URL = f"/api/environments/{self.team.id}/llm_analytics/offline_evaluations/experiment_items/"
-
- def _make_response(self, rows: list[list[Any]]) -> MagicMock:
- response = MagicMock()
- response.results = rows
- return response
-
- def test_requires_resource_level_evaluation_access(self) -> None:
- self.organization.available_product_features = [
- {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
- {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
- ]
- self.organization.save()
- evaluation = Evaluation.objects.create(
- team=self.team,
- name="Visible Eval",
- evaluation_type="llm_judge",
- evaluation_config={"prompt": "test"},
- output_type="boolean",
- created_by=self.user,
- )
- other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
- membership = OrganizationMembership.objects.get(user=other_user, organization=self.organization)
- AccessControl.objects.create(
- team=self.team, resource="evaluation", access_level="none", organization_member=membership
- )
- AccessControl.objects.create(
- team=self.team,
- resource="evaluation",
- resource_id=str(evaluation.id),
- access_level="viewer",
- organization_member=membership,
- )
- self.client.force_login(other_user)
-
- response = self.client.post(self.URL, {"experiment_id": "unrelated"}, format="json")
-
- assert response.status_code == status.HTTP_403_FORBIDDEN
-
- def _preflight_row(
- self,
- item_id: str = "item-1",
- experiment_item_name: str | None = "case A",
- experiment_name: str | None = "exp-name",
- metric_name: str = "accuracy",
- metric_version: str = "1",
- eval_status: str | None = "completed",
- score: Any = 0.9,
- score_min: Any = 0.0,
- score_max: Any = 1.0,
- result_type: str | None = "numeric",
- reasoning: str | None = "looks good",
- trace_id: str | None = "trace-1",
- target_id: str | None = "trace-1",
- target_type: str | None = "trace_id",
- dataset_id: str | None = "ds-1",
- dataset_item_id: str | None = "ds-item-1",
- ai_expected: str | None = "expected",
- last_seen_at: Any = "2026-04-27T07:00:00+00:00",
- first_seen_at: Any = "2026-04-27T06:50:00+00:00",
- ) -> list[Any]:
- return [
- item_id,
- experiment_item_name,
- experiment_name,
- metric_name,
- metric_version,
- eval_status,
- score,
- score_min,
- score_max,
- result_type,
- reasoning,
- trace_id,
- target_id,
- target_type,
- dataset_id,
- dataset_item_id,
- ai_expected,
- last_seen_at,
- first_seen_at,
- ]
-
- @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
- def test_missing_experiment_id_returns_400(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
- response = self.client.post(self.URL, {}, content_type="application/json")
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert mock_preflight.call_count == 0
- assert mock_heavy.call_count == 0
-
- @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
- def test_empty_experiment_id_returns_400(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
- response = self.client.post(self.URL, {"experiment_id": ""}, content_type="application/json")
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert mock_preflight.call_count == 0
- assert mock_heavy.call_count == 0
-
- @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
- def test_returns_rows_in_20_column_tuple_order(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
- mock_preflight.return_value = self._make_response(
- [
- self._preflight_row(
- item_id="item-1",
- trace_id="trace-1",
- last_seen_at="2026-04-27T07:00:00+00:00",
- first_seen_at="2026-04-27T06:50:00+00:00",
- ),
- ]
- )
- mock_heavy.return_value = self._make_response(
- [["trace-1", '[{"role":"user","content":"hi"}]', '[{"role":"assistant","content":"hi"}]']]
- )
-
- response = self.client.post(
- self.URL,
- {"experiment_id": "exp-1"},
- content_type="application/json",
- )
- assert response.status_code == status.HTTP_200_OK
- body = response.json()
- assert body == {
- "results": [
- [
- "item-1",
- "case A",
- "exp-name",
- "accuracy",
- "1",
- "completed",
- 0.9,
- 0.0,
- 1.0,
- "numeric",
- "looks good",
- "trace-1",
- "ds-1",
- "ds-item-1",
- '[{"role":"user","content":"hi"}]',
- '[{"role":"assistant","content":"hi"}]',
- "expected",
- "2026-04-27T07:00:00+00:00",
- "trace-1",
- "trace_id",
- ]
- ]
- }
- assert mock_preflight.call_args.kwargs["query_type"] == "LLMOfflineEvaluationItemsResolve"
- assert mock_heavy.call_args.kwargs["query_type"] == "LLMOfflineEvaluationItems"
- assert mock_preflight.call_args.kwargs["user"] == self.user
- assert mock_heavy.call_args.kwargs["user"] == self.user
-
- @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
- def test_empty_preflight_skips_heavy_query(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
- mock_preflight.return_value = self._make_response([])
-
- response = self.client.post(
- self.URL,
- {"experiment_id": "exp-1"},
- content_type="application/json",
- )
- assert response.status_code == status.HTTP_200_OK
- assert response.json() == {"results": []}
- assert mock_heavy.call_count == 0
-
- @parameterized.expand(
- [
- ("blank_string", ""),
- ("none", None),
- ]
- )
- @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
- def test_blank_only_trace_ids_short_circuit_heavy(
- self, _name: str, blank_value: Any, mock_preflight: MagicMock, mock_heavy: MagicMock
- ) -> None:
- mock_preflight.return_value = self._make_response([self._preflight_row(item_id="item-1", trace_id=blank_value)])
-
- response = self.client.post(
- self.URL,
- {"experiment_id": "exp-1"},
- content_type="application/json",
- )
- assert response.status_code == status.HTTP_200_OK
- body = response.json()
- assert len(body["results"]) == 1
- assert body["results"][0][14] is None
- assert body["results"][0][15] is None
- assert mock_heavy.call_count == 0
-
- @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
- def test_preflight_failure_returns_500(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
- mock_preflight.side_effect = RuntimeError("clickhouse boom")
-
- response = self.client.post(
- self.URL,
- {"experiment_id": "exp-1"},
- content_type="application/json",
- )
- assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
- assert mock_heavy.call_count == 0
-
- @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
- def test_heavy_failure_returns_500(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
- mock_preflight.return_value = self._make_response([self._preflight_row()])
- mock_heavy.side_effect = RuntimeError("clickhouse boom")
-
- response = self.client.post(
- self.URL,
- {"experiment_id": "exp-1"},
- content_type="application/json",
- )
- assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
-
- @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
- def test_preflight_targets_events_and_heavy_targets_ai_events(
- self, mock_preflight: MagicMock, mock_heavy: MagicMock
- ) -> None:
- from posthog.hogql import ast
-
- mock_preflight.return_value = self._make_response(
- [
- self._preflight_row(
- item_id="item-1",
- trace_id="trace-1",
- last_seen_at=datetime(2026, 4, 27, 7, 0, tzinfo=UTC),
- first_seen_at=datetime(2026, 4, 27, 6, 50, tzinfo=UTC),
- ),
- self._preflight_row(
- item_id="item-2",
- trace_id="trace-2",
- last_seen_at=datetime(2026, 4, 27, 6, 30, tzinfo=UTC),
- first_seen_at=datetime(2026, 4, 27, 6, 0, tzinfo=UTC),
- ),
- ]
- )
- mock_heavy.return_value = self._make_response(
- [
- ["trace-1", '[{"role":"user","content":"hi"}]', '[{"role":"assistant","content":"hi"}]'],
- ["trace-2", '[{"role":"user","content":"hello"}]', '[{"role":"assistant","content":"hello"}]'],
- ]
- )
-
- response = self.client.post(
- self.URL,
- {"experiment_id": "exp-1"},
- content_type="application/json",
- )
- assert response.status_code == status.HTTP_200_OK
-
- preflight_query = mock_preflight.call_args.kwargs["query"]
- preflight_select = cast(ast.SelectQuery, preflight_query)
- # nosemgrep: hogql-no-string-table-chain
- assert preflight_select.select_from.table.chain == ["events"] # type: ignore[union-attr]
-
- heavy_query = mock_heavy.call_args.kwargs["query"]
- heavy_select = cast(ast.SelectQuery, heavy_query)
- # nosemgrep: hogql-no-string-table-chain
- assert heavy_select.select_from.table.chain == ["posthog", "ai_events"] # type: ignore[union-attr]
-
- heavy_placeholders = mock_heavy.call_args.kwargs["placeholders"]
- trace_id_values = [c.value for c in heavy_placeholders["trace_ids"].exprs]
- assert trace_id_values == ["trace-1", "trace-2"]
- assert heavy_placeholders["ts_start"].value == datetime(2026, 4, 27, 6, 0, tzinfo=UTC)
- assert heavy_placeholders["ts_end"].value == datetime(2026, 4, 27, 7, 0, tzinfo=UTC)
-
- @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
- def test_traces_without_heavy_match_get_null_input_output(
- self, mock_preflight: MagicMock, mock_heavy: MagicMock
- ) -> None:
- mock_preflight.return_value = self._make_response(
- [
- self._preflight_row(item_id="item-1", trace_id="trace-1"),
- self._preflight_row(item_id="item-2", trace_id="trace-2"),
- ]
- )
- mock_heavy.return_value = self._make_response(
- [["trace-1", '[{"role":"user","content":"hi"}]', '[{"role":"assistant","content":"hi"}]']]
- )
-
- response = self.client.post(
- self.URL,
- {"experiment_id": "exp-1"},
- content_type="application/json",
- )
- assert response.status_code == status.HTTP_200_OK
- body = response.json()
- assert len(body["results"]) == 2
- assert body["results"][0][14] == '[{"role":"user","content":"hi"}]'
- assert body["results"][0][15] == '[{"role":"assistant","content":"hi"}]'
- assert body["results"][1][14] is None
- assert body["results"][1][15] is None
-
- @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
- def test_omitted_dates_inline_as_null_guards(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
- from posthog.hogql import ast
- from posthog.hogql.visitor import TraversingVisitor
-
- mock_preflight.return_value = self._make_response([])
-
- response = self.client.post(
- self.URL,
- {"experiment_id": "exp-1"},
- content_type="application/json",
- )
- assert response.status_code == status.HTTP_200_OK
- assert mock_preflight.call_args.kwargs["placeholders"] == {}
-
- query = mock_preflight.call_args.kwargs["query"]
- true_constants: list[ast.Constant] = []
-
- class _BoolCounter(TraversingVisitor):
- def visit_constant(self, node: ast.Constant) -> None:
- if isinstance(node.value, bool) and node.value is True:
- true_constants.append(node)
- super().visit_constant(node)
-
- _BoolCounter().visit(query)
- assert len(true_constants) >= 2
-
- @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
- def test_provided_dates_are_inlined_into_query(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
- from posthog.hogql import ast
- from posthog.hogql.visitor import TraversingVisitor
-
- mock_preflight.return_value = self._make_response([])
-
- response = self.client.post(
- self.URL,
- {
- "experiment_id": "exp-1",
- "date_from": "2026-04-01T00:00:00Z",
- "date_to": "2026-04-30T00:00:00Z",
- },
- content_type="application/json",
- )
- assert response.status_code == status.HTTP_200_OK
- assert mock_preflight.call_args.kwargs["placeholders"] == {}
-
- query = mock_preflight.call_args.kwargs["query"]
- string_constants: list[str] = []
-
- class _StringCollector(TraversingVisitor):
- def visit_constant(self, node: ast.Constant) -> None:
- if isinstance(node.value, str):
- string_constants.append(node.value)
- super().visit_constant(node)
-
- _StringCollector().visit(query)
- assert "exp-1" in string_constants
- assert "2026-04-01T00:00:00Z" in string_constants
- assert "2026-04-30T00:00:00Z" in string_constants
diff --git a/products/ai_observability/backend/routes.py b/products/ai_observability/backend/routes.py
index 912000b24e4b..67eac460fcb2 100644
--- a/products/ai_observability/backend/routes.py
+++ b/products/ai_observability/backend/routes.py
@@ -5,7 +5,6 @@ from products.ai_observability.backend.api import (
AIBlobViewSet,
AIObservabilityClusteringRunViewSet,
AIObservabilityInstrumentationChecklistViewSet,
- AIObservabilityOfflineEvaluationsViewSet,
AIObservabilitySummarizationViewSet,
AIObservabilityTextReprViewSet,
AIObservabilityTranslateViewSet,
@@ -138,12 +137,6 @@ def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(
r"llm_analytics/clustering_jobs", ClusteringJobViewSet, "project_llm_analytics_clustering_jobs", ["team_id"]
)
- routers.projects.register(
- r"llm_analytics/offline_evaluations",
- AIObservabilityOfflineEvaluationsViewSet,
- "project_llm_analytics_offline_evaluations",
- ["team_id"],
- )
routers.projects.register(
r"llm_analytics/review_queue_items",
ReviewQueueItemViewSet,
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index cd592a7d48f4..004d552009fd 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -3483,26 +3483,6 @@ export interface LLMModelsListResponseApi {
providers: LLMProviderModelsSummaryApi[]
}
-export interface OfflineExperimentItemsRequestApi {
- /** `$ai_experiment_id` whose offline-evaluation items to return. */
- experiment_id: string
- /**
- * Lower bound on `timestamp` (ISO-8601). Omit to leave the lower bound open.
- * @nullable
- */
- date_from?: string | null
- /**
- * Upper bound on `timestamp` (ISO-8601). Omit to leave the upper bound open.
- * @nullable
- */
- date_to?: string | null
-}
-
-export interface OfflineExperimentItemsResponseApi {
- /** Tuple-positional rows; positions match `RawOfflineExperimentMetricRow` in the frontend. */
- results: unknown[][]
-}
-
export interface ParserRecipeApi {
readonly id: string
/**
@@ -5288,10 +5268,6 @@ export const LlmAnalyticsModelsRetrieveProvider = {
Zeabur: 'zeabur',
} as const
-export type LlmAnalyticsOfflineEvaluationsExperimentItemsCreate400 = { [key: string]: unknown }
-
-export type LlmAnalyticsOfflineEvaluationsExperimentItemsCreate500 = { [key: string]: unknown }
-
export type LlmAnalyticsParserRecipesListParams = {
/**
* Number of results to return per page.
diff --git a/products/ai_observability/frontend/generated/api.ts b/products/ai_observability/frontend/generated/api.ts
index 70953de2d17d..2f7cb90e4f82 100644
--- a/products/ai_observability/frontend/generated/api.ts
+++ b/products/ai_observability/frontend/generated/api.ts
@@ -79,8 +79,6 @@ import type {
LlmPromptsListParams,
LlmPromptsNameRetrieveParams,
LlmPromptsResolveNameRetrieveParams,
- OfflineExperimentItemsRequestApi,
- OfflineExperimentItemsResponseApi,
OfflineExperimentPageApi,
OfflineExperimentReadApi,
OfflineHistoryPageApi,
@@ -1855,26 +1853,6 @@ export const llmAnalyticsModelsRetrieve = async (
})
}
-export const getLlmAnalyticsOfflineEvaluationsExperimentItemsCreateUrl = (projectId: string) => {
- return `/api/projects/${projectId}/llm_analytics/offline_evaluations/experiment_items/`
-}
-
-export const llmAnalyticsOfflineEvaluationsExperimentItemsCreate = async (
- projectId: string,
- offlineExperimentItemsRequestApi: OfflineExperimentItemsRequestApi,
- options?: RequestInit
-): Promise<OfflineExperimentItemsResponseApi> => {
- return apiMutator<OfflineExperimentItemsResponseApi>(
- getLlmAnalyticsOfflineEvaluationsExperimentItemsCreateUrl(projectId),
- {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(offlineExperimentItemsRequestApi),
- }
- )
-}
-
export const getLlmAnalyticsParserRecipesListUrl = (
projectId: string,
params?: LlmAnalyticsParserRecipesListParams
diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.ts
index 0a6987d1b920..b1b24df3ee00 100644
--- a/products/ai_observability/frontend/generated/api.zod.ts
+++ b/products/ai_observability/frontend/generated/api.zod.ts
@@ -2058,18 +2058,6 @@ export const LlmAnalyticsEvaluationReportsPartialUpdateBody = /* @__PURE__ */ zo
),
})
-export const LlmAnalyticsOfflineEvaluationsExperimentItemsCreateBody = /* @__PURE__ */ zod.object({
- experiment_id: zod.string().describe('`$ai_experiment_id` whose offline-evaluation items to return.'),
- date_from: zod
- .string()
- .nullish()
- .describe('Lower bound on `timestamp` (ISO-8601). Omit to leave the lower bound open.'),
- date_to: zod
- .string()
- .nullish()
- .describe('Upper bound on `timestamp` (ISO-8601). Omit to leave the upper bound open.'),
-})
-
export const llmAnalyticsParserRecipesCreateBodyNameMax = 255
export const llmAnalyticsParserRecipesCreateBodySourceMax = 100000
diff --git a/products/ai_observability/skills/analyzing-offline-evaluations/SKILL.md b/products/ai_observability/skills/analyzing-offline-evaluations/SKILL.md
index 51eb5397c37e..cfb0138d0e0f 100644
--- a/products/ai_observability/skills/analyzing-offline-evaluations/SKILL.md
+++ b/products/ai_observability/skills/analyzing-offline-evaluations/SKILL.md
@@ -29,8 +29,7 @@ Date ranges include `date_from` and exclude `date_to`.
Lists include all upload states by default. Prefer `statuses: "completed"` for a
finished comparison; uploading and failed runs may be partial. Scorer history
-defaults to completed runs. An empty list means no matching stored experiments:
-legacy `$ai_evaluation` events are a separate source and are not imported by these tools.
+defaults to completed runs. An empty list means no matching stored experiments.
Check suite, dataset source/identifier/revision, scorer version, and trial coverage
before attributing a change to an application, model, or prompt revision. State which
diff --git a/products/data_catalog/docs/production-monitoring.md b/products/data_catalog/docs/production-monitoring.md
index 807617a1a487..b66868700318 100644
--- a/products/data_catalog/docs/production-monitoring.md
+++ b/products/data_catalog/docs/production-monitoring.md
@@ -54,7 +54,7 @@ Evaluation definitions are per-team database rows, not repo code; this document
- **Aug 2026, canonical metric bypass, first fail.** The first failing verdict was a scheduled Signals Scout run whose executed SQL was entirely schema and freshness validation (`information_schema` lookups, a max-date/row-count check), which is work the metric-discovery steering explicitly exempts as schema-first. The judge failed it on the run's surrounding context (a churn-scoring scout) rather than on the queries it executed. Two remediations: the scout harness prompt now carries a flag-gated catalog-first rule (`products/signals/backend/scout_harness/prompt.py`, the only repo surface reaching custom store-hosted scout skills, which steer with their own prescribed SQL), and the bypass rubric gained an applicability clause returning N/A when a trace computes no business measure. The offline suite (`products/data_catalog/evals/`) pins both sides: `scout_skill_prescribed_bypass` and `scout_schema_validation_control`.
- **Aug 2026, canonical metric bypass, second fail: the KPI-only scope split the surfaces.** The next failing verdict was a scheduled Signals Scout run that computed fleet operational telemetry (cost per run, terminal-failure rate) verbatim from its skill's prescribed sweeps, with the catalog-first harness rule live in its prompt. Every steering surface scoped catalog-first to business KPIs, so the scout was right to skip the catalog by its own rules, while the bypass judge counted operational rates as "KPI-shaped" and failed the run; the proposal judge classified the same trace as operational observation (N/A), so the two judges disagreed on applicability. Resolution: the definition broadened rather than the judge narrowing. "Metric" now means any named, reusable measure - business or operational telemetry computed for monitoring or reporting - across the harness rule, the MCP metric-discovery templates, and both judge rubrics; the scout fleet's own measures were seeded as governed metrics (`scout_cost_per_run`, `scout_run_fail_pct`) and the scouts-dashboard skill now runs them through `data-catalog-metric-run` with its raw sweeps demoted to labeled-noncanonical fallbacks. The offline suite pins the new boundary from both sides: `scout_operational_telemetry_bypass` and `scout_operational_no_match`.
-- **Aug 2026, full-window audit: prose steering alone produced probabilistic compliance, so the catalog lookup became structural.** A 30-day read of every verdict found the judges healthy (fail reasonings accurate, N/A correctly excluding ad-hoc debugging and support work) and the behavior real: the bypass judge logged 54 fails against 1 pass among applicable sessions, roughly two thirds of them scheduled Signals Scout runs following their skills' prescribed sweeps, the rest one-shot and interactive agent sessions. The single pass and several same-shaped fails landed in the same post-broadening window, which is the signature of a one-line rule losing to a skill cookbook most of the time. Resolution: the scout harness now pre-fetches the team's approved, non-drifted metric names itself (`approved_metric_names_for_team` on the data-catalog facade) and injects them into the run prompt - names only, to keep the injection to a handful of tokens - so every catalog-enabled scout run is catalog-aware by construction; a scout reads a listed name's definition only when it matches the measure at hand, and the probe-and-cache prose rule survives only as the fallback for a failed lookup. Companions in the same pass: two more governed scout measures (`mcp_tool_call_fail_pct`, `slo_explicit_burn_by_operation`) with their skills updated to run them canonically (inbox-report-rubrics deliberately skipped - its checks are versioned and still moving, and freezing a definition mid-churn is worse than none); the trust judge's one fail traced to the `answer-billing-questions` skill, whose data-sources reference now names the certified invoice source and requires a stated reason when dropping to the raw mirror; and an offline regression experiment over an AI-evals dataset of the observed failure shapes: `products/data_catalog/scripts/offline_governance_experiment.py` replays each dataset item as a fresh hosted-MCP session, scores the trace with the live judge rubrics, and reports into the offline experiments view (`/ai-evals/evaluations/offline/experiments`); the dataset itself is curated at `/ai-evals/datasets`.
+- **Aug 2026, full-window audit: prose steering alone produced probabilistic compliance, so the catalog lookup became structural.** A 30-day read of every verdict found the judges healthy (fail reasonings accurate, N/A correctly excluding ad-hoc debugging and support work) and the behavior real: the bypass judge logged 54 fails against 1 pass among applicable sessions, roughly two thirds of them scheduled Signals Scout runs following their skills' prescribed sweeps, the rest one-shot and interactive agent sessions. The single pass and several same-shaped fails landed in the same post-broadening window, which is the signature of a one-line rule losing to a skill cookbook most of the time. Resolution: the scout harness now pre-fetches the team's approved, non-drifted metric names itself (`approved_metric_names_for_team` on the data-catalog facade) and injects them into the run prompt - names only, to keep the injection to a handful of tokens - so every catalog-enabled scout run is catalog-aware by construction; a scout reads a listed name's definition only when it matches the measure at hand, and the probe-and-cache prose rule survives only as the fallback for a failed lookup. Companions in the same pass: two more governed scout measures (`mcp_tool_call_fail_pct`, `slo_explicit_burn_by_operation`) with their skills updated to run them canonically (inbox-report-rubrics deliberately skipped - its checks are versioned and still moving, and freezing a definition mid-churn is worse than none); the trust judge's one fail traced to the `answer-billing-questions` skill, whose data-sources reference now names the certified invoice source and requires a stated reason when dropping to the raw mirror; and an offline regression experiment over an AI-evals dataset of the observed failure shapes: `products/data_catalog/scripts/offline_governance_experiment.py` replays each dataset item as a fresh hosted-MCP session, scores the trace with the live judge rubrics, and prints verdicts and reasoning locally; the dataset itself is curated at `/ai-evals/datasets`.
- **Aug 2026, post-injection audit: compliance moved out of the judged trace, so the statement became the contract.** With the injected listing live and the orphan filter applied, the bypass judge's failing population split three ways. Most fails computed measures with no governed metric and showed no trace-visible catalog consultation at all: the injection had removed the in-session lookup, and the "say no catalog metric matched" clause was a buried trailer that runs dropped while keeping the cheap `noncanonical` label (which the rubric deliberately does not credit). Nearly every pass ran one of the seeded scout-ops metrics canonically, confirming that a governed metric for the exact measure is the one robustly passing shape. The fragmentation hypothesis was confirmed but bounded: about a third of failing traces held a single generation, and about a quarter of non-scout fails had a same-user catalog lookup in a different trace the same day, invisible to the judged trace; there is no server-side conversation id to join on, so the fix is per-turn self-documentation, not plumbing. Remediations: the harness injection variants and the MCP metric-discovery steering now require opening the derivation query's stated context with `governed catalog consulted: no listed metric matched <measure> (noncanonical)` (the empty-catalog variant gained the statement too, having previously offered no pass path at all); the rubric enumerates the accepted statement forms and clarifies that supplemental drill-down SQL after running the matching canonical metric passes, since near-identical drill-down sessions had drawn opposite verdicts; and the recurring ungoverned scout measures got a seeding batch of proposed metrics. The offline suite pins the new boundaries from both sides: `scout_injected_listing_no_match` and `governed_metric_canonical_then_drilldown`.
diff --git a/products/data_catalog/scripts/README.md b/products/data_catalog/scripts/README.md
index e5959f556fb0..575f40e9c4c3 100644
--- a/products/data_catalog/scripts/README.md
+++ b/products/data_catalog/scripts/README.md
@@ -88,7 +88,7 @@ A structured clarification question parks a permission request that stays open w
## Scoring a canary batch
-`semantic_layer_canary_score.py` grades a completed batch from the full ACP session log of each run, using the same scorers as the offline evals in `products/data_catalog/evals/`. It is the only scorer. The `signals-scout-semantic-layer-canary-report` scout reports the `$ai_evaluation` events this script emits; it does not grade session logs itself. A batch that was never scored here has no pass rate anywhere.
+`semantic_layer_canary_score.py` grades a completed batch from the full ACP session log of each run, using the same scorers as the offline evals in `products/data_catalog/evals/`. It prints verdicts locally; a batch that was never scored here has no pass rate.
Score the file the runner just wrote:
@@ -106,11 +106,11 @@ POSTHOG_API_KEY=phx_... flox activate -- .venv/bin/python \
--batch 2026-09-10T16:54:23Z 2026-09-10T17:17:23Z --revision 42
```
-`--batch` reads the pinned revision, then finds each enabled question's task among `origin_product=posthog_ai` tasks created inside the window. Only a task whose full description equals the question counts; there is no fuzzy matching. A case with no task in the window is `missing`; a case whose newest attempt is still running is `incomplete`; more than one completed attempt is `duplicate`; a failed attempt followed by a completed one scores the completed one. A run the runner cancelled behind a clarifying question is scored as completed, with the question text recovered from its log. The batch id is `tasks:<from>:<to>`, so scoring the same window twice publishes the same experiment id.
+`--batch` reads the pinned revision, then finds each enabled question's task among `origin_product=posthog_ai` tasks created inside the window. Only a task whose full description equals the question counts; there is no fuzzy matching. A case with no task in the window is `missing`; a case whose newest attempt is still running is `incomplete`; more than one completed attempt is `duplicate`; a failed attempt followed by a completed one scores the completed one. A run the runner cancelled behind a clarifying question is scored as completed, with the question text recovered from its log. The batch id is `tasks:<from>:<to>`, so scoring the same window twice uses the same batch identifier.
The personal API key needs `task:read`, plus `dataset:read` for `--batch`.
-It prints one JSON verdict row per case on stdout and a batch summary on stderr. `--emit` additionally publishes an `$ai_evaluation` event per case, tagged with the batch id, and needs `POSTHOG_CAPTURE_TOKEN`. Unscored cases are emitted too, with `$ai_evaluation_applicable` false and the case status as the reasoning, so the scout can report coverage gaps without reading logs. Every event carries `task_id`, `task_run_id`, and `task_url` for the report's links.
+It prints one JSON verdict row per case on stdout and a batch summary on stderr. Unscored cases include their status and reason so the output also shows coverage gaps. Every row carries `task_id`, `task_run_id`, and `task_url`. Redirect stdout to save the verdicts for comparison.
Each case is graded against its dataset `expected_routing`:
diff --git a/products/data_catalog/scripts/offline_governance_experiment.py b/products/data_catalog/scripts/offline_governance_experiment.py
index d8d647938ccc..73a86b4596dd 100644
--- a/products/data_catalog/scripts/offline_governance_experiment.py
+++ b/products/data_catalog/scripts/offline_governance_experiment.py
@@ -2,9 +2,7 @@
Runs a PostHog AI-evals dataset (curated at /ai-evals/datasets) through fresh hosted-MCP agent
sessions, scores each resulting trace with the three online judge rubrics (fetched live so
-offline scoring can never drift from them), and emits `$ai_evaluation` events tagged with
-`$ai_experiment_id` so runs land in the offline experiments view
-(/ai-evals/evaluations/offline/experiments) and are comparable run over run.
+offline scoring can never drift from them), and prints each verdict and its reasoning locally.
Dataset item shape:
input: {"prompt": "<the metric-shaped task>"}
@@ -17,8 +15,7 @@ Usage:
--compare runs every item twice: a control session (bare prompt, like a pre-fix scout) and a
treatment session whose system prompt carries the approved-metric-name listing the scout harness
-now injects, fetched live from the catalog. The two land as separate experiments in the offline
-experiments view, so the fix's effect is the verdict diff between them.
+now injects, fetched live from the catalog. The two variants print separate results for comparison.
Run it after each remediation deploy and on a cadence; a previously-passing item failing is the
regression signal. See products/data_catalog/docs/production-monitoring.md.
@@ -30,7 +27,6 @@ Environment:
POSTHOG_PROJECT_ID numeric project id the judges and dataset live in
POSTHOG_HOST default https://us.posthog.com
POSTHOG_MCP_URL default https://mcp.posthog.com/mcp
- POSTHOG_CAPTURE_TOKEN project API token the emitted evaluation events are captured with
"""
import os
@@ -61,7 +57,6 @@ DATASET_ITEM_PAGE_SIZE = 25
EXPERIMENT_NAME = "semantic-layer-governance-regressions"
DATASET_NAME = EXPERIMENT_NAME
-DISTINCT_ID = "offline-governance-experiment"
JUDGES = {
"canonical_metric_bypass": "019fd294-e77a-0000-8a4e-93af107576b5",
@@ -344,53 +339,6 @@ def judge_trace(client: anthropic.Anthropic, rubric: str, transcript: str) -> di
return json.loads(text)
-def emit_evaluation_event(
- *,
- experiment_id: str,
- experiment_name: str,
- dataset_id: str,
- item: ExperimentItem,
- metric_name: str,
- verdict: dict,
- trace_id: str,
-) -> None:
- properties = {
- "$ai_experiment_id": experiment_id,
- "$ai_experiment_name": experiment_name,
- "$ai_experiment_item_id": f"{experiment_id}:{item.name}",
- "$ai_experiment_item_name": item.name,
- "$ai_dataset_id": dataset_id,
- "$ai_dataset_item_id": item.id,
- "$ai_metric_name": metric_name,
- "$ai_metric_version": "1",
- "$ai_status": "completed",
- "$ai_result_type": "boolean",
- "$ai_reasoning": verdict["reasoning"],
- "$ai_trace_id": trace_id,
- "$ai_target_id": trace_id,
- "$ai_target_type": "trace",
- "$ai_expected": item.expected,
- "$ai_evaluation_applicable": verdict["applicable"],
- }
- # The offline experiments view aggregates `$ai_score` without reading
- # `$ai_evaluation_applicable`, so scoring an N/A verdict 0 would read as a governance failure.
- # Leave the score off entirely and let the applicable flag plus the reasoning carry the N/A.
- if verdict["applicable"]:
- properties |= {"$ai_score": 1 if verdict["result"] else 0, "$ai_score_min": 0, "$ai_score_max": 1}
- response = requests.post(
- f"{POSTHOG_HOST.replace('us.posthog.com', 'us.i.posthog.com')}/i/v0/e/",
- json={
- "api_key": os.environ["POSTHOG_CAPTURE_TOKEN"],
- "event": "$ai_evaluation",
- "distinct_id": DISTINCT_ID,
- "properties": properties,
- "timestamp": datetime.now(UTC).isoformat(),
- },
- timeout=30,
- )
- response.raise_for_status()
-
-
def run_experiment(dataset_id: str, only_items: list[str] | None, system: str | None, variant: str) -> int:
client = anthropic.Anthropic()
rubrics = fetch_judge_rubrics()
@@ -416,17 +364,8 @@ def run_experiment(dataset_id: str, only_items: list[str] | None, system: str |
for metric_name, rubric in rubrics.items():
verdict = judge_trace(client, rubric, session.transcript)
- emit_evaluation_event(
- experiment_id=experiment_id,
- experiment_name=experiment_name,
- dataset_id=dataset_id,
- item=item,
- metric_name=metric_name,
- verdict=verdict,
- trace_id=session.trace_id,
- )
label = "N/A" if not verdict["applicable"] else ("PASS" if verdict["result"] else "FAIL")
- print(f"[{item.name}] {metric_name}: {label}")
+ print(f"[{item.name}] {metric_name}: {label} — {verdict['reasoning']}")
if verdict["applicable"] and not verdict["result"]:
failures += 1
diff --git a/products/data_catalog/scripts/semantic_layer_canary_score.py b/products/data_catalog/scripts/semantic_layer_canary_score.py
index cd1939b639f0..849dfd35ef5d 100644
--- a/products/data_catalog/scripts/semantic_layer_canary_score.py
+++ b/products/data_catalog/scripts/semantic_layer_canary_score.py
@@ -4,16 +4,14 @@
Reads the runner's `CanaryRunResult` JSON, or rebuilds the batch from the Tasks API and a pinned
dataset revision, fetches every scored run's complete ACP session log, and grades each case with
-the same scorers the offline evals use. Emits one JSON verdict row per case, and optionally
-`$ai_evaluation` events tagged with the batch id.
+the same scorers the offline evals use. Prints one JSON verdict row per case and a batch summary.
Usage:
python semantic_layer_canary_score.py --results run.json
- python semantic_layer_canary_score.py --batch 2026-09-10T16:54:23Z 2026-09-10T17:17:23Z --revision 42 --emit
+ python semantic_layer_canary_score.py --batch 2026-09-10T16:54:23Z 2026-09-10T17:17:23Z --revision 42
Environment:
POSTHOG_API_KEY personal API key with task:read, plus dataset:read for --batch
- POSTHOG_CAPTURE_TOKEN project API token, required only with --emit
"""
from __future__ import annotations
@@ -54,8 +52,6 @@ TASK_LIST_PAGE_SIZE = 50
TASK_RUN_PAGE_SIZE = 100
REQUEST_TIMEOUT_SECONDS = 120.0
MAX_READ_TIMEOUT_RETRIES = 2
-EVALUATION_METRIC_NAME = "semantic_layer_canary_routing"
-EXPERIMENT_NAME = "semantic-layer-canary"
BATCH_ID_PREFIX = "tasks"
CANARY_ORIGIN_PRODUCT = "posthog_ai"
PERMISSION_REQUEST_METHOD = "session/request_permission"
@@ -485,51 +481,6 @@ def score_results(
return rows
-def evaluation_event(*, run_id: str, dataset_revision: int | None, row: dict[str, Any]) -> dict[str, Any]:
- scored = row["verdict"] != UNSCORED_VERDICT
- properties: dict[str, Any] = {
- "$ai_experiment_id": run_id,
- "$ai_experiment_name": EXPERIMENT_NAME,
- "$ai_experiment_item_id": f"{run_id}:{row['case_id']}",
- "$ai_experiment_item_name": row["case_id"],
- "$ai_metric_name": EVALUATION_METRIC_NAME,
- "$ai_metric_version": "1",
- "$ai_status": "completed",
- "$ai_result_type": "boolean",
- "$ai_expected": row["expected_routing"],
- "$ai_evaluation_applicable": scored,
- "$ai_reasoning": (
- json.dumps({"failed": row["failed_checks"], "advisory": row["advisory_checks"]})
- if scored
- else row["reason"]
- ),
- "batch_id": run_id,
- "case_status": row["status"],
- "category": row["category"],
- "dataset_revision": dataset_revision,
- "task_id": row["task_id"],
- "task_run_id": row["task_run_id"],
- "task_url": row["task_url"],
- }
- if scored:
- properties |= {"$ai_score": 1 if row["verdict"] == "pass" else 0, "$ai_score_min": 0, "$ai_score_max": 1}
- return {
- "event": "$ai_evaluation",
- "distinct_id": f"{EXPERIMENT_NAME}:{run_id}",
- "properties": properties,
- "timestamp": datetime.now(UTC).isoformat(),
- }
-
-
-def emit_evaluation_event(*, host: str, capture_token: str, event: dict[str, Any]) -> None:
- response = httpx.post(
- f"{host.replace('us.posthog.com', 'us.i.posthog.com').rstrip('/')}/i/v0/e/",
- json=event | {"api_key": capture_token},
- timeout=REQUEST_TIMEOUT_SECONDS,
- )
- response.raise_for_status()
-
-
def summarize(run_id: str, rows: Sequence[dict[str, Any]]) -> dict[str, Any]:
scored = [row for row in rows if row["verdict"] != UNSCORED_VERDICT]
passed = sum(row["verdict"] == "pass" for row in scored)
@@ -566,7 +517,6 @@ def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
help=f"Overrides the result file's project_id; defaults to {DEFAULT_PROJECT_ID}",
)
parser.add_argument("--case-id", action="append", dest="case_ids", default=[])
- parser.add_argument("--emit", action="store_true", help="Publish an $ai_evaluation event per case")
args = parser.parse_args(argv)
args.window = None
if args.batch:
@@ -599,11 +549,6 @@ def main(argv: Sequence[str] | None = None) -> int:
if not api_key:
print("POSTHOG_API_KEY is required", file=sys.stderr)
return 2
- capture_token = os.environ.get("POSTHOG_CAPTURE_TOKEN")
- if args.emit and not capture_token:
- print("POSTHOG_CAPTURE_TOKEN is required with --emit", file=sys.stderr)
- return 2
-
results = read_results_file(args)
with CanaryApiClient(host=args.host, project_id=resolve_project_id(args, results), api_key=api_key) as client:
if results is None:
@@ -619,9 +564,6 @@ def main(argv: Sequence[str] | None = None) -> int:
run_id = results["run_id"]
for row in rows:
print(json.dumps(row))
- if args.emit and capture_token:
- event = evaluation_event(run_id=run_id, dataset_revision=results.get("dataset_revision"), row=row)
- emit_evaluation_event(host=args.host, capture_token=capture_token, event=event)
print(json.dumps(summarize(run_id, rows)), file=sys.stderr)
return 0
diff --git a/products/data_catalog/scripts/test/test_semantic_layer_canary_score.py b/products/data_catalog/scripts/test/test_semantic_layer_canary_score.py
index 14dd61ed8736..cbea8b2cc02e 100644
--- a/products/data_catalog/scripts/test/test_semantic_layer_canary_score.py
+++ b/products/data_catalog/scripts/test/test_semantic_layer_canary_score.py
@@ -12,7 +12,6 @@ from products.data_catalog.scripts.semantic_layer_canary_score import (
CanaryApiClient,
UnknownRouting,
_parse_args,
- evaluation_event,
expectations_for,
reconstruct_batch,
resolve_project_id,
@@ -470,41 +469,6 @@ class TestCliArguments:
_parse_args(["--batch", "2026-09-10T17:17:23Z", "2026-09-10T16:54:23Z", "--revision", "42"])
-class TestEvaluationEvent:
- @pytest.mark.parametrize(
- "row,applicable,score,reasoning",
- [
- (
- {"verdict": "pass", "failed_checks": [], "advisory_checks": []},
- True,
- 1,
- '{"failed": [], "advisory": []}',
- ),
- (
- {"verdict": "unscored", "reason": "case status is missing, not completed"},
- False,
- None,
- "case status is missing, not completed",
- ),
- ],
- ids=["scored", "unscored"],
- )
- def test_marks_applicability_and_carries_the_task_link(
- self, row: dict, applicable: bool, score: int | None, reasoning: str
- ) -> None:
- base = _case(status="missing" if row["verdict"] == "unscored" else "completed")
-
- event = evaluation_event(run_id="tasks:a:b", dataset_revision=REVISION, row=base | row)
-
- properties = event["properties"]
- assert properties["$ai_evaluation_applicable"] is applicable
- assert properties.get("$ai_score") == score
- assert properties["$ai_reasoning"] == reasoning
- assert properties["batch_id"] == "tasks:a:b"
- assert properties["task_url"] == base["task_url"]
- assert "api_key" not in event
-
-
class TestCanaryApiClient:
def test_reads_every_page_before_scoring(self) -> None:
pages = [[{"page": 0}, {"page": 1}], [{"page": 2}]]
diff --git a/products/posthog_ai/eval_harness/README.md b/products/posthog_ai/eval_harness/README.md
index dac3fd99168b..2ce0cfe9aeee 100644
--- a/products/posthog_ai/eval_harness/README.md
+++ b/products/posthog_ai/eval_harness/README.md
@@ -395,7 +395,7 @@ See [evaluation result reporting](../../../docs/internal/ai-offline-evaluation-r
The `sql/eval_sql::eval_sql` suite can also send its seven scorer results to PostHog's offline experiment API.
It publishes the same completed case results through the Python SDK and keeps sending to Braintrust.
-The harness no longer emits legacy `$ai_evaluation` result events. Other public suites report scores to Braintrust until they opt into offline publishing.
+Other public suites report scores to Braintrust until they opt into offline publishing.
Agent and judge trace capture remains available, and `no_send_logs=True` suppresses offline result uploads.
Set `POSTHOG_OFFLINE_EVAL_API_KEY` to a personal or project secret key with `offline_evaluation_ingestion:write` and access to project `2`.
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index 0a05806bf38a..d77ea489b5e7 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -1738,7 +1738,6 @@ products/signals/
│ │ └── commands/
│ │ ├── analyze_report.py
│ │ ├── cleanup_signals.py
-│ │ ├── clear_eval_data.py
│ │ ├── delete_all_signal_reports_for_team.py
│ │ ├── enable_signals_autonomy.py # Sets team default priority + opts in users by email
│ │ ├── export_session_video.py
diff --git a/products/signals/backend/management/AGENTS.md b/products/signals/backend/management/AGENTS.md
index b2ff8e0f0c46..2c4e093b8047 100644
--- a/products/signals/backend/management/AGENTS.md
+++ b/products/signals/backend/management/AGENTS.md
@@ -3,6 +3,9 @@
Commands for emitting signals, tracking pipeline processing, and inspecting grouping results.
Use these to test grouping strategies against real signal data end-to-end.
+For offline grouping and scout safety evaluations with mocked infrastructure, use the
+[pytest suites](../../eval/AGENTS.md), which publish results to offline experiments.
+
## Full flow
Always clean up before re-ingesting to avoid stale data mixing with new results.
diff --git a/products/signals/backend/management/commands/clear_eval_data.py b/products/signals/backend/management/commands/clear_eval_data.py
deleted file mode 100644
index 8fe0c749dffb..000000000000
--- a/products/signals/backend/management/commands/clear_eval_data.py
+++ /dev/null
@@ -1,99 +0,0 @@
-from django.conf import settings
-from django.core.management.base import BaseCommand, CommandError
-
-from posthog.clickhouse.client import sync_execute
-
-DEFAULT_EVAL_SOURCE = "signals-grouping"
-
-TABLES = [
- "sharded_events",
- "sharded_events_recent",
-]
-
-COUNT_SQL = """
-SELECT count()
-FROM {table}
-WHERE event = '$ai_evaluation'
- AND JSONExtractString(properties, '$ai_eval_source') = %(eval_source)s
-"""
-
-DELETE_SQL = """
-ALTER TABLE {table} DELETE
-WHERE event = '$ai_evaluation'
- AND JSONExtractString(properties, '$ai_eval_source') = %(eval_source)s
-"""
-
-
-class Command(BaseCommand):
- help = "Delete eval pipeline data ($ai_evaluation events) from ClickHouse, filtered by $ai_eval_source tag. DEBUG only."
-
- def add_arguments(self, parser):
- parser.add_argument(
- "--source",
- type=str,
- default=DEFAULT_EVAL_SOURCE,
- help=f"Value of $ai_eval_source to filter on (default: {DEFAULT_EVAL_SOURCE})",
- )
- parser.add_argument(
- "--yes",
- action="store_true",
- help="Skip confirmation prompt",
- )
- parser.add_argument(
- "--dry-run",
- action="store_true",
- help="Show counts without deleting",
- )
-
- def handle(self, *args, **options):
- if not settings.DEBUG:
- raise CommandError("This command can only be run with DEBUG=True")
-
- eval_source = options["source"]
- params = {"eval_source": eval_source}
-
- total = 0
- for table in TABLES:
- rows = sync_execute(COUNT_SQL.format(table=table), params)
- count = rows[0][0] if rows else 0
- total += count
- self.stdout.write(f" {table}: {count} events")
-
- if total == 0:
- self.stdout.write(self.style.SUCCESS(f"No eval events to delete (source={eval_source})."))
- return
-
- if options["dry_run"]:
- self.stdout.write(f"Dry run: {total} events would be deleted (source={eval_source}).")
- return
-
- if not options["yes"]:
- self.stdout.write(
- self.style.WARNING(f"This will DELETE {total} eval events (source={eval_source}) from ClickHouse.")
- )
- confirm = input("Type 'yes' to confirm: ")
- if confirm != "yes":
- self.stdout.write("Aborted.")
- return
-
- for table in TABLES:
- self.stdout.write(f"Deleting from {table}...")
- sync_execute(
- DELETE_SQL.format(table=table),
- params,
- settings={"mutations_sync": 1},
- )
- self.stdout.write(" done.")
-
- # Verify
- remaining = 0
- for table in TABLES:
- rows = sync_execute(COUNT_SQL.format(table=table), params)
- remaining += rows[0][0] if rows else 0
-
- if remaining == 0:
- self.stdout.write(self.style.SUCCESS(f"Deleted {total} eval events from {len(TABLES)} tables."))
- else:
- self.stdout.write(
- self.style.WARNING(f"Deleted but {remaining} events still remain (mutations may be pending).")
- )
diff --git a/products/signals/backend/test/test_eval_reporting.py b/products/signals/backend/test/test_eval_reporting.py
new file mode 100644
index 000000000000..8469247a7885
--- /dev/null
+++ b/products/signals/backend/test/test_eval_reporting.py
@@ -0,0 +1,146 @@
+import os
+import json
+import asyncio
+from functools import partial
+from typing import Literal
+
+import pytest
+from unittest.mock import patch
+
+import httpx
+from parameterized import parameterized
+
+from products.posthog_ai.eval_harness.test.offline_api import OfflineServer
+from products.signals.eval.offline import EvalMetric, SignalsEvalRecorder
+from products.signals.eval.offline_config import GROUPING_SUITE, SCOUT_SAFETY_SUITE
+
+
+def test_grouping_publishes_stage_scores_and_aggregates_without_combining_recall() -> None:
+ server = OfflineServer()
+ with (
+ patch.dict(os.environ, {"POSTHOG_OFFLINE_EVAL_API_KEY": "test-only-token"}),
+ patch("httpx.AsyncClient", new=partial(httpx.AsyncClient, transport=httpx.MockTransport(server.respond))),
+ ):
+ recorder = SignalsEvalRecorder(GROUPING_SUITE, metadata={"git_sha": "test-revision", "limit": 3})
+ for stage in ["signal-safety-filter", "github-actionability-check", "report-safety-check"]:
+ recorder.record(
+ eval_name=stage,
+ item_name="case-0",
+ input={"text": "An invented test finding"},
+ output=False,
+ expected=True,
+ metrics=[EvalMetric(name="correct_classification", score=0.0, reasoning="Does not match fixture")],
+ )
+ recorder.record(
+ eval_name="grouping-quality",
+ item_name="report-0",
+ metrics=[EvalMetric(name="group_recall", score=0.5)],
+ )
+ recorder.record(
+ eval_name="grouping-aggregate",
+ item_name="aggregate",
+ metrics=[EvalMetric(name="group_recall", score=0.75), EvalMetric(name="ari", score=-0.25)],
+ )
+ recorder.record(
+ eval_name="match-quality",
+ item_name="case-0",
+ metrics=[EvalMetric(name="query_diversity", score=1.5)],
+ )
+ url = asyncio.run(recorder.publish())
+
+ bodies = [json.loads(request.content) for request in server.requests if request.url.path.endswith("/upload/")]
+ results = [result for body in bodies for result in body["results"]]
+ items = [item for body in bodies for item in body["items"]]
+ assert server.status == "completed"
+ assert server.experiment["suite_key"] == "signals/grouping-e2e"
+ assert server.experiment["application_version"] == "test-revision"
+ assert server.experiment["expected_item_count"] == 6
+ assert server.experiment["expected_result_count"] == 96
+ assert url is not None and recorder.experiment_id in url
+ assert len({item["case_key"] for item in items}) == 6
+ assert items[0]["payload"]["output"] is False
+ assert items[0]["payload"]["input"]["input"] == {"text": "An invented test finding"}
+ values = {r["scorer_version_id"]: r["value"] for r in results if r["status"] == "ok"}
+ for metric in [
+ "signal_safety_correct_classification",
+ "actionability_correct_classification",
+ "report_safety_correct_classification",
+ ]:
+ assert values[str(GROUPING_SUITE.scorer_versions[metric])] is False
+ assert values[str(GROUPING_SUITE.scorer_versions["group_recall"])] == 0.5
+ assert values[str(GROUPING_SUITE.scorer_versions["mean_group_recall"])] == 0.75
+ assert values[str(GROUPING_SUITE.scorer_versions["ari"])] == -0.25
+ assert values[str(GROUPING_SUITE.scorer_versions["query_diversity"])] == 1.5
+ assert sum(r["status"] == "not_applicable" for r in results) == 89
+ assert results[0]["payload"]["reasoning"] == "Does not match fixture"
+
+
[email protected]([("skipped", None, "ok", "skipped"), ("error", None, "error", "error")])
+def test_scout_outcomes_and_repeat_runs_keep_distinct_identities(
+ _name: str, score: float | None, status: Literal["ok", "error"], expected_status: str
+) -> None:
+ servers = [OfflineServer(), OfflineServer()]
+ for server in servers:
+ with (
+ patch.dict(os.environ, {"POSTHOG_OFFLINE_EVAL_API_KEY": "test-only-token"}),
+ patch("httpx.AsyncClient", new=partial(httpx.AsyncClient, transport=httpx.MockTransport(server.respond))),
+ ):
+ recorder = SignalsEvalRecorder(SCOUT_SAFETY_SUITE)
+ recorder.record(
+ eval_name="scout-safety-filter",
+ item_name="same-case",
+ metrics=[
+ EvalMetric(
+ name="correct_classification",
+ score=score,
+ status=status,
+ error_code="judge_error" if status == "error" else None,
+ )
+ ],
+ )
+ asyncio.run(recorder.publish())
+ outcomes = next(json.loads(r.content)["results"] for r in server.requests if r.url.path.endswith("/upload/"))
+ assert outcomes[0]["status"] == expected_status
+ assert "value" not in outcomes[0]
+ assert [outcome["status"] for outcome in outcomes[1:]] == ["not_applicable", "not_applicable"]
+ assert servers[0].experiment["id"] != servers[1].experiment["id"]
+ assert set(servers[0].items).isdisjoint(servers[1].items)
+
+
+ [("opt_out", True, "test-only-token"), ("no_key", False, ""), ("bad_key", False, "invalid token")]
+)
+def test_disabled_reporting_never_attempts_network(_name: str, disabled: bool, api_key: str) -> None:
+ def fail_network(request: httpx.Request) -> httpx.Response:
+ pytest.fail("Disabled reporting attempted a network request")
+
+ with (
+ patch.dict(os.environ, {"POSTHOG_OFFLINE_EVAL_API_KEY": api_key}),
+ patch("httpx.AsyncClient", new=partial(httpx.AsyncClient, transport=httpx.MockTransport(fail_network))),
+ ):
+ recorder = SignalsEvalRecorder(SCOUT_SAFETY_SUITE, disabled=disabled)
+ recorder.record(
+ eval_name="scout-safety-filter",
+ item_name="case",
+ metrics=[EvalMetric(name="correct_classification", score=1)],
+ )
+ assert asyncio.run(recorder.publish()) is None
+
+
+def test_upload_failure_is_reported_without_hiding_completed_scores(capsys: pytest.CaptureFixture[str]) -> None:
+ with (
+ patch.dict(os.environ, {"POSTHOG_OFFLINE_EVAL_API_KEY": "test-only-token"}),
+ patch(
+ "httpx.AsyncClient",
+ new=partial(httpx.AsyncClient, transport=httpx.MockTransport(lambda request: httpx.Response(403))),
+ ),
+ ):
+ recorder = SignalsEvalRecorder(SCOUT_SAFETY_SUITE)
+ recorder.record(
+ eval_name="scout-safety-filter",
+ item_name="case",
+ metrics=[EvalMetric(name="correct_classification", score=0)],
+ )
+ assert asyncio.run(recorder.publish()) is None
+ assert "upload failed" in capsys.readouterr().err
+ assert recorder.cases[0].scores["scout_safety_correct_classification"] == 0
diff --git a/products/signals/eval/AGENTS.md b/products/signals/eval/AGENTS.md
index 1774e3a44fe8..aad18c702141 100644
--- a/products/signals/eval/AGENTS.md
+++ b/products/signals/eval/AGENTS.md
@@ -1,5 +1,9 @@
# Signal grouping eval
+Offline runs publish to PostHog's offline experiments API through the shared eval-harness publisher.
+Read [offline evaluation reporting](../../../docs/internal/ai-offline-evaluation-reporting.md#signals-pytest-suites)
+for the two suites, pinned scorer versions, upload credentials, and result layout.
+
End-to-end evaluation of the signal grouping pipeline.
Measures how well the pipeline clusters incoming signals into reports, compared against hand-labeled ground-truth groups.
@@ -28,14 +32,11 @@ After all signals are processed:
## How to run
```bash
-# Full run — captures eval results to PostHog
+# Full run — uploads results to PostHog offline experiments
pytest products/signals/eval/eval_grouping_e2e.py -xvs
# Quick test — 10 signals, no capture
pytest products/signals/eval/eval_grouping_e2e.py -xvs --limit 10 --no-capture
-
-# Online eval mode (tags results as "online" instead of "offline")
-pytest products/signals/eval/eval_grouping_e2e.py -xvs --online
```
### Required environment variables
@@ -48,16 +49,17 @@ Set in `.env` at the repo root (loaded automatically):
| `LLM_GATEWAY_URL` | Internal LLM gateway base URL (all LLM calls: matching, specificity, summarization, actionability, safety) |
| `LLM_GATEWAY_PERSONAL_API_KEY` | Bearer token for the LLM gateway (PostHog personal API key) |
| `SIGNALS_EVAL_TEAM_ID` | Team id used for LLM cost attribution headers (defaults to `1`) |
-| `POSTHOG_PROJECT_API_KEY` | Capturing eval results (skip with `--no-capture`) |
-| `POSTHOG_HOST` | PostHog instance (defaults to `http://localhost:8010`) |
+| `POSTHOG_OFFLINE_EVAL_API_KEY` | Offline result uploads; requires `offline_evaluation_ingestion:write` |
+| `POSTHOG_OFFLINE_EVAL_HOST` | Offline API origin (defaults to `https://us.posthog.com`; project `2`) |
+| `POSTHOG_PROJECT_API_KEY` | Optional LLM trace capture |
+| `POSTHOG_HOST` | Trace destination (defaults to `http://localhost:8010`) |
### CLI options
-| Flag | Effect |
-| -------------- | ------------------------------------------------------ |
-| `--limit N` | Process only the first N signals from the stream |
-| `--no-capture` | Skip emitting `$ai_evaluation` events to PostHog |
-| `--online` | Tag captured results as online eval (default: offline) |
+| Flag | Effect |
+| -------------- | ------------------------------------------------ |
+| `--limit N` | Process only the first N signals from the stream |
+| `--no-capture` | Skip offline uploads and trace capture |
## What it produces
@@ -70,19 +72,19 @@ Two tqdm progress bars:
Followed by an aggregate results summary table.
-### Eval metrics captured to PostHog
+### Eval metrics uploaded to PostHog
-All metrics are captured as `$ai_evaluation` events with source `signals-grouping`.
-Five eval experiments, each with their own metrics:
+Offline runs produce one experiment per suite, with items for each stage and aggregate statistics.
+The table below lists grouping stage names. Inspect each run in the offline experiments UI.
-| Experiment | Granularity | Metrics |
+| Stage | Granularity | Metrics |
| ------------------------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `match-quality` | Per-signal | `correct_match` (binary), `correct_match_pre_specificity` (binary), failure mode: NONE/UNDERGROUP/OVERGROUP, `query_diversity` (numeric, cosine distance), `candidate_diversity` (numeric, 1 − Jaccard) |
-| `{source}-actionability-check` | Per-signal | `correct_classification` (binary) — did pre-emit filter agree with ground truth |
+| `signal-safety-filter` | Per-signal | `signal_safety_correct_classification` (binary) — safety filter vs ground truth |
+| `{source}-actionability-check` | Per-signal | `actionability_correct_classification` (binary) — pre-emit filter vs ground truth |
| `grouping-quality` | Per-report | `purity`, `is_pure`, `group_recall` |
-| `report-safety-check` | Per-report | `correct_classification` (binary) — safety judge vs ground truth |
-| `report-actionability-check` | Per-report | `correct_classification` (binary) — actionability judge vs ground truth |
-| `grouping-aggregate` | Global | `ari`, `homogeneity`, `completeness`, `mean_purity`, `group_recall`, `malicious_leaked_rate` |
+| `report-safety-check` | Per-report | `report_safety_correct_classification` (binary) — safety judge vs ground truth |
+| `grouping-aggregate` | Global | `ari`, `homogeneity`, `completeness`, `mean_purity`, `mean_group_recall`, `malicious_leaked_rate` |
### Aggregate metrics explained
@@ -97,217 +99,19 @@ Five eval experiments, each with their own metrics:
| File | Purpose |
| --------------------------- | --------------------------------------------------------------------------------- |
-| `eval_grouping_e2e.py` | Test class, pipeline orchestration, metric capture |
+| `eval_grouping_e2e.py` | Test class, pipeline orchestration, metric recording |
+| `eval_scout_safety.py` | Scout safety cases and aggregate metrics |
| `conftest.py` | pytest fixtures: API clients, CLI options, mock temporal |
| `mock.py` | `EmbeddingStore` (in-memory vector store) and `ReportStore` (in-memory report DB) |
-| `capture.py` | `capture_evaluation()` helper — formats and sends `$ai_evaluation` events |
+| `offline.py` | Adapts completed metrics to the shared offline publisher |
+| `offline_config.py` | Destination project and pinned scorer versions |
| `data_spec.py` | `EvalSignalSpec` / `EvalGroupSpec` — signal and group specifications |
| `fixtures/grouping_data.py` | Ground-truth: 48 groups, 111 signals across Zendesk/GitHub/Linear/error tracking |
| `cache/embeddings.json` | Disk cache for OpenAI embeddings (auto-generated, avoids redundant API calls) |
-## Clearing eval data
-
-To delete captured eval events from ClickHouse (DEBUG mode only):
-
-```bash
-python manage.py clear_eval_data --dry-run # preview counts
-python manage.py clear_eval_data --yes # delete all
-python manage.py clear_eval_data --source X # filter by eval source tag
-```
-
## Concurrency model
- Signals run through the pipeline concurrently (semaphore-bounded, 70 max).
- The match + persist step is serialized behind `asyncio.Lock` —
this ensures the embedding store and report store see a consistent view when deciding whether a signal joins an existing report or creates a new one.
- Report judging runs concurrently (all reports at once).
-
-# Reports
-
-## HogQL queries
-
-All queries filter on `$ai_eval_source = 'signals-grouping'` and `$ai_evaluation_type = 'offline'`.
-Run these in the PostHog SQL editor.
-
-### Aggregate metrics
-
-ARI, homogeneity, completeness, purity, recall, malicious leak rate.
-
-```sql
-SELECT
- properties.$ai_metric_name AS metric,
- properties.$ai_score AS score,
- properties.$ai_metric_description AS description,
- properties.$ai_reasoning AS reasoning,
- properties.$ai_input AS input,
- properties.$ai_output AS output,
- properties.$ai_expected AS expected
-FROM events
-WHERE event = '$ai_evaluation'
- AND properties.$ai_eval_source = 'signals-grouping'
- AND properties.$ai_evaluation_type = 'offline'
- AND properties.$ai_experiment_name = 'signals-grouping/grouping-aggregate'
-ORDER BY metric
-```
-
-### Match quality failure mode breakdown
-
-```sql
-SELECT
- multiIf(
- properties.$ai_score = 1.0, 'CORRECT',
- properties.$ai_reasoning LIKE '%UNDERGROUP%', 'UNDERGROUP',
- properties.$ai_reasoning LIKE '%OVERGROUP%', 'OVERGROUP',
- 'UNKNOWN'
- ) AS failure_mode,
- count() AS cnt,
- round(count() * 100.0 / (SELECT count() FROM events WHERE event = '$ai_evaluation' AND properties.$ai_eval_source = 'signals-grouping' AND properties.$ai_evaluation_type = 'offline' AND properties.$ai_experiment_name = 'signals-grouping/match-quality'), 1) AS pct
-FROM events
-WHERE event = '$ai_evaluation'
- AND properties.$ai_eval_source = 'signals-grouping'
- AND properties.$ai_evaluation_type = 'offline'
- AND properties.$ai_experiment_name = 'signals-grouping/match-quality'
- AND properties.$ai_metric_name = 'correct_match'
-GROUP BY failure_mode
-ORDER BY cnt DESC
-```
-
-### Specificity judge impact
-
-Compares pre- and post-specificity correctness to show
-how often the specificity judge helps (prevents overgroup),
-hurts (causes undergroup), or has no effect.
-
-```sql
-SELECT
- multiIf(
- pre.score = 1.0 AND post.score = 1.0, 'no_effect_correct',
- pre.score = 0.0 AND post.score = 0.0 AND pre.reasoning = post.reasoning, 'no_effect_wrong',
- pre.score = 0.0 AND post.score = 1.0, 'prevented_overgroup',
- pre.score = 1.0 AND post.score = 0.0, 'caused_undergroup',
- pre.score = 0.0 AND post.score = 0.0, 'changed_failure_mode',
- 'unknown'
- ) AS specificity_impact,
- count() AS cnt
-FROM (
- SELECT properties.$ai_experiment_item_name AS item, properties.$ai_score AS score, properties.$ai_reasoning AS reasoning
- FROM events
- WHERE event = '$ai_evaluation' AND properties.$ai_eval_source = 'signals-grouping' AND properties.$ai_evaluation_type = 'offline'
- AND properties.$ai_experiment_name = 'signals-grouping/match-quality' AND properties.$ai_metric_name = 'correct_match_pre_specificity'
-) pre
-JOIN (
- SELECT properties.$ai_experiment_item_name AS item, properties.$ai_score AS score, properties.$ai_reasoning AS reasoning
- FROM events
- WHERE event = '$ai_evaluation' AND properties.$ai_eval_source = 'signals-grouping' AND properties.$ai_evaluation_type = 'offline'
- AND properties.$ai_experiment_name = 'signals-grouping/match-quality' AND properties.$ai_metric_name = 'correct_match'
-) post ON pre.item = post.item
-GROUP BY specificity_impact
-ORDER BY cnt DESC
-```
-
-### Query and candidate diversity
-
-```sql
-SELECT
- properties.$ai_metric_name AS metric,
- count() AS n,
- round(avg(properties.$ai_score), 3) AS mean,
- round(min(properties.$ai_score), 3) AS min,
- round(max(properties.$ai_score), 3) AS max
-FROM events
-WHERE event = '$ai_evaluation'
- AND properties.$ai_eval_source = 'signals-grouping'
- AND properties.$ai_evaluation_type = 'offline'
- AND properties.$ai_experiment_name = 'signals-grouping/match-quality'
- AND properties.$ai_metric_name IN ('query_diversity', 'candidate_diversity')
-GROUP BY metric
-ORDER BY metric
-```
-
-### Pre-emit actionability by source type
-
-```sql
-SELECT
- replaceOne(properties.$ai_experiment_name, 'signals-grouping/', '') AS check_name,
- count() AS total,
- countIf(properties.$ai_score = 1.0) AS correct,
- countIf(properties.$ai_score != 1.0) AS failures,
- round(countIf(properties.$ai_score != 1.0) * 100.0 / count(), 1) AS failure_pct,
- countIf(properties.$ai_score != 1.0 AND properties.$ai_output = 'ACTIONABLE') AS false_positives,
- countIf(properties.$ai_score != 1.0 AND properties.$ai_output = 'NOT_ACTIONABLE') AS false_negatives
-FROM events
-WHERE event = '$ai_evaluation'
- AND properties.$ai_eval_source = 'signals-grouping'
- AND properties.$ai_evaluation_type = 'offline'
- AND properties.$ai_experiment_name IN (
- 'signals-grouping/zendesk-actionability-check',
- 'signals-grouping/github-actionability-check',
- 'signals-grouping/linear-actionability-check'
- )
- AND properties.$ai_metric_name = 'correct_classification'
-GROUP BY check_name
-ORDER BY check_name
-```
-
-### Report-level judges (safety + actionability)
-
-```sql
-SELECT
- replaceOne(properties.$ai_experiment_name, 'signals-grouping/', '') AS judge,
- count() AS total,
- countIf(properties.$ai_score = 1.0) AS correct,
- round(countIf(properties.$ai_score = 1.0) * 100.0 / count(), 1) AS accuracy_pct,
- countIf(properties.$ai_score != 1.0 AND properties.$ai_output IN ('SAFE', 'IMMEDIATELY_ACTIONABLE')) AS false_positives,
- countIf(properties.$ai_score != 1.0 AND properties.$ai_output NOT IN ('SAFE', 'IMMEDIATELY_ACTIONABLE')) AS false_negatives
-FROM events
-WHERE event = '$ai_evaluation'
- AND properties.$ai_eval_source = 'signals-grouping'
- AND properties.$ai_evaluation_type = 'offline'
- AND properties.$ai_experiment_name IN (
- 'signals-grouping/report-safety-check',
- 'signals-grouping/report-actionability-check'
- )
- AND properties.$ai_metric_name = 'correct_classification'
-GROUP BY judge
-ORDER BY judge
-```
-
-### Per-report grouping quality
-
-Purity, is_pure, group_recall distributions.
-
-```sql
-SELECT
- properties.$ai_metric_name AS metric,
- count() AS n,
- round(avg(properties.$ai_score), 3) AS mean_score,
- round(min(properties.$ai_score), 3) AS min_score,
- round(max(properties.$ai_score), 3) AS max_score,
- countIf(properties.$ai_score = 1.0) AS perfect_count
-FROM events
-WHERE event = '$ai_evaluation'
- AND properties.$ai_eval_source = 'signals-grouping'
- AND properties.$ai_evaluation_type = 'offline'
- AND properties.$ai_experiment_name = 'signals-grouping/grouping-quality'
-GROUP BY metric
-ORDER BY metric
-```
-
-### Detailed match failures (for debugging)
-
-```sql
-SELECT
- properties.$ai_experiment_item_name AS item,
- properties.$ai_reasoning AS failure_mode,
- properties.$ai_input AS signal_description,
- properties.$ai_expected AS expected,
- JSONExtractString(properties.$ai_output, 'report') AS actual_decision
-FROM events
-WHERE event = '$ai_evaluation'
- AND properties.$ai_eval_source = 'signals-grouping'
- AND properties.$ai_evaluation_type = 'offline'
- AND properties.$ai_experiment_name = 'signals-grouping/match-quality'
- AND properties.$ai_metric_name = 'correct_match'
- AND properties.$ai_score != 1.0
-ORDER BY properties.$ai_reasoning, item
-```
diff --git a/products/signals/eval/capture.py b/products/signals/eval/capture.py
deleted file mode 100644
index dab7efd97b53..000000000000
--- a/products/signals/eval/capture.py
+++ /dev/null
@@ -1,85 +0,0 @@
-import uuid
-from dataclasses import dataclass
-from typing import Any
-
-from posthoganalytics import Posthog
-
-DISTINCT_ID = "llma_eval"
-
-
-def deterministic_uuid(name: str) -> str:
- return str(uuid.uuid5(uuid.NAMESPACE_URL, f"llma-eval:{name}"))
-
-
-@dataclass
-class EvalMetric:
- name: str
- description: str | None = None
- version: str = "1"
- result_type: str = "binary"
- score: float | None = None
- score_min: float = 0
- score_max: float = 1
- reasoning: str | None = None
- status: str = "ok"
- error_code: str | None = None
- error_message: str | None = None
-
-
-def capture_evaluation(
- client: Posthog,
- experiment_id: str,
- experiment_name: str,
- item_id: str,
- item_name: str,
- metrics: list[EvalMetric],
- input: Any = None,
- output: Any = None,
- expected: Any = None,
- dataset_id: str | None = None,
- passed: bool = True,
- eval_type: str = "offline",
- eval_source: str = "signals-grouping",
-) -> None:
- for metric in metrics:
- properties: dict[str, Any] = {
- "$ai_eval_source": eval_source,
- "$ai_evaluation_type": eval_type,
- "$ai_experiment_id": experiment_id,
- "$ai_experiment_name": f"{eval_source}/{experiment_name}",
- "$ai_experiment_item_id": item_id,
- "$ai_experiment_item_name": item_name,
- "$ai_metric_name": metric.name,
- "$ai_metric_version": metric.version,
- "$ai_result_type": metric.result_type,
- "$ai_evaluation_result": 1.0 if passed else 0.0,
- "$ai_status": metric.status,
- "$ai_dataset_id": dataset_id,
- "$ai_trace_id": str(uuid.uuid4()),
- }
-
- if metric.description:
- properties["$ai_metric_description"] = metric.description
- if metric.status == "ok" and metric.score is not None:
- properties["$ai_score"] = metric.score
- properties["$ai_score_min"] = metric.score_min
- properties["$ai_score_max"] = metric.score_max
-
- if metric.reasoning:
- properties["$ai_reasoning"] = metric.reasoning
- if input is not None:
- properties["$ai_input"] = str(input)
- if output is not None:
- properties["$ai_output"] = str(output)
- if expected is not None:
- properties["$ai_expected"] = str(expected)
- if metric.error_code:
- properties["$ai_error_code"] = metric.error_code
- if metric.error_message:
- properties["$ai_error_message"] = metric.error_message
-
- client.capture(
- distinct_id=DISTINCT_ID,
- event="$ai_evaluation",
- properties=properties,
- )
diff --git a/products/signals/eval/conftest.py b/products/signals/eval/conftest.py
index a2e46940e6ec..4472cd369417 100644
--- a/products/signals/eval/conftest.py
+++ b/products/signals/eval/conftest.py
@@ -1,4 +1,5 @@
import os
+import subprocess
from pathlib import Path
import pytest
@@ -12,7 +13,6 @@ from posthoganalytics import Posthog
from posthoganalytics.ai.openai import AsyncOpenAI
from posthog.llm.gateway_client import get_async_anthropic_gateway_client
-from posthog.models import Organization, Team
# This eval runs via bare pytest (no hogli), so the conftest owns loading repo-root .env.
load_dotenv(Path(__file__).resolve().parents[3] / ".env")
@@ -42,8 +42,7 @@ EVAL_TEAM_ID = int(os.environ.get("SIGNALS_EVAL_TEAM_ID", "1"))
def pytest_addoption(parser):
parser.addoption("--limit", default=None, type=int, help="Limit number of items to process (e.g. --limit 3)")
- parser.addoption("--no-capture", action="store_true", default=False, help="Skip emitting eval results to PostHog")
- parser.addoption("--online", action="store_true", default=False, help="Capture as online eval")
+ parser.addoption("--no-capture", action="store_true", default=False, help="Skip eval uploads and trace capture")
parser.addoption("--strategy", default="example_strategy", help="Strategy module name (default: example_strategy)")
parser.addoption(
"--safe", action="store_true", default=False, help="Filter to safe signals only, skip safety_filter step"
@@ -61,31 +60,37 @@ def no_capture(request):
@pytest.fixture
-def online(request):
- return request.config.getoption("--online")
-
-
-def posthog_client(no_capture, db):
+def posthog_client(no_capture):
api_key = os.environ.get("POSTHOG_PROJECT_API_KEY", "")
- if not api_key:
- last_team = Team.objects.order_by("-pk").first()
- if last_team:
- api_key = last_team.api_token
- elif not no_capture:
- org = Organization.objects.create(name="Eval Org", is_ai_data_processing_approved=True)
- team = Team.objects.create(organization=org, name="Eval Team")
- api_key = team.api_token
- if not api_key and not no_capture:
- raise ValueError("POSTHOG_PROJECT_API_KEY needs to be set (or pass --no-capture).")
host = os.environ.get("POSTHOG_HOST", "http://localhost:8010")
client = Posthog(
- api_key or "phx_unused", host=host, disabled=no_capture, debug=bool(os.environ.get("POSTHOG_DEBUG"))
+ api_key or "phx_unused",
+ host=host,
+ disabled=no_capture or not api_key,
+ debug=bool(os.environ.get("POSTHOG_DEBUG")),
)
yield client
client.shutdown()
+def eval_metadata(limit: int | None) -> dict[str, object]:
+ metadata: dict[str, object] = {"limit": limit}
+ root = Path(__file__).resolve().parents[3]
+ try:
+ metadata["git_sha"] = subprocess.check_output(
+ ["git", "rev-parse", "HEAD"], cwd=root, text=True, stderr=subprocess.DEVNULL, timeout=5
+ ).strip()
+ metadata["git_dirty"] = bool(
+ subprocess.check_output(
+ ["git", "status", "--porcelain"], cwd=root, text=True, stderr=subprocess.DEVNULL, timeout=5
+ ).strip()
+ )
+ except (OSError, subprocess.SubprocessError):
+ pass
+ return metadata
+
+
@pytest.fixture
async def openai_client(posthog_client):
client = AsyncOpenAI(posthog_client=posthog_client)
diff --git a/products/signals/eval/eval_grouping_e2e.py b/products/signals/eval/eval_grouping_e2e.py
index c956d187991b..31ad808caa10 100644
--- a/products/signals/eval/eval_grouping_e2e.py
+++ b/products/signals/eval/eval_grouping_e2e.py
@@ -8,7 +8,7 @@ infrastructure (in-memory embedding store replaces ClickHouse + Kafka).
After grouping, each report is judged for safety (prompt injection detection).
-Captures four levels of metrics:
+Records four levels of metrics:
- Per-signal matching: correct_match (binary), correct_match_pre_specificity
(binary, LLM matcher decision before specificity judge),
failure_mode (categorical: NONE, UNDERGROUP, OVERGROUP),
@@ -30,8 +30,6 @@ import uuid
import asyncio
import logging
from itertools import combinations
-from time import time
-from typing import Any
import pytest
@@ -59,7 +57,6 @@ from products.signals.backend.temporal.types import (
SignalCandidate,
SpecificityMetadata,
)
-from products.signals.eval.capture import EvalMetric, capture_evaluation, deterministic_uuid
from products.signals.eval.common import (
MAX_CONCURRENT_RUNS,
EvalProgress,
@@ -70,6 +67,8 @@ from products.signals.eval.common import (
from products.signals.eval.conftest import EVAL_TEAM_ID
from products.signals.eval.fixtures.grouping_data import GROUP_DATA
from products.signals.eval.mock import EmbeddingStore, ReportStore
+from products.signals.eval.offline import EvalMetric, SignalsEvalRecorder
+from products.signals.eval.offline_config import GROUPING_SUITE
TRANSPORT_RETRIES = 3
@@ -82,17 +81,18 @@ class EvalGroupingPipeline:
return MagicMock(id=EVAL_TEAM_ID)
@pytest.fixture(autouse=True)
- def _setup(self, posthog_client, openai_client, gateway_client, mock_temporal, limit, no_capture, online):
- self.posthog_client = posthog_client
+ def _setup(self, openai_client, gateway_client, mock_temporal, limit, no_capture, eval_metadata):
+ self.results = SignalsEvalRecorder(
+ GROUPING_SUITE,
+ disabled=no_capture,
+ metadata=eval_metadata,
+ )
self.gateway_client = gateway_client
self.openai_client = openai_client
self.store = EmbeddingStore(openai_client)
self.report_store = ReportStore()
self.limit = limit
- self.no_capture = no_capture
- self.online = online
self._match_lock = asyncio.Lock()
- self.start_time = time()
# Suppress structlog noise from downstream modules during the eval
root_logger = logging.getLogger()
@@ -121,8 +121,9 @@ class EvalGroupingPipeline:
await self._judge_reports()
self.progress.done()
- self._capture_grouping_quality()
- self._capture_aggregate_metrics(stream)
+ self._record_grouping_quality()
+ self._record_aggregate_metrics(stream)
+ await self.results.publish()
async def run_signal_pipeline_concurrently(self, sem: asyncio.Semaphore, record_id: int, case: EvalSignalCase):
async with sem:
@@ -143,7 +144,7 @@ class EvalGroupingPipeline:
safety_result = await safety_filter(
EVAL_TEAM_ID, description, source_product=case.signal.content.source_product
)
- await self._capture_safety_filter(case, safety_result)
+ await self._record_safety_filter(case, safety_result)
if not safety_result.safe:
self.progress.signal_dropped()
@@ -157,7 +158,7 @@ class EvalGroupingPipeline:
match_result, specificity_result, candidates = await self._match(
description, case, queries, query_embeddings
)
- self._capture_match_quality(
+ self._record_match_quality(
case, match_result, specificity_result, queries, query_embeddings, candidates
)
self._persist_signal(record_id, description, case, specificity_result, signal_embedding)
@@ -308,15 +309,15 @@ class EvalGroupingPipeline:
config.actionability_prompt,
context_fields=config.actionability_context_fields,
)
- await self._capture_pre_emit_actionability(case, None, is_actionable)
+ await self._record_pre_emit_actionability(case, None, is_actionable)
if not is_actionable:
return None
return output.description or None
- async def _capture_safety_filter(self, case: EvalSignalCase, result):
+ async def _record_safety_filter(self, case: EvalSignalCase, result):
passed = result.safe == case.safe
- self._capture(
+ self.results.record(
eval_name="signal-safety-filter",
item_name=f"filter-{case.group_index}-{case.signal_index}",
input=case.signal.content.description,
@@ -325,19 +326,16 @@ class EvalGroupingPipeline:
metrics=[
EvalMetric(
name="correct_classification",
- result_type="binary",
score=1.0 if passed else 0.0,
- score_min=0,
- score_max=1,
reasoning=result.explanation,
),
],
passed=passed,
)
- async def _capture_pre_emit_actionability(self, case: EvalSignalCase, thoughts: str | None, outcome: bool):
+ async def _record_pre_emit_actionability(self, case: EvalSignalCase, thoughts: str | None, outcome: bool):
passed = outcome == case.actionable
- self._capture(
+ self.results.record(
eval_name=f"{case.signal.config.source_product.lower()}-actionability-check",
item_name=f"case-{case.group_index}-{case.signal_index}",
input=case.signal.content.description,
@@ -346,17 +344,14 @@ class EvalGroupingPipeline:
metrics=[
EvalMetric(
name="correct_classification",
- result_type="binary",
score=1.0 if passed else 0.0,
- score_min=0,
- score_max=1,
reasoning=thoughts,
)
],
passed=passed,
)
- def _capture_match_quality(
+ def _record_match_quality(
self,
case: EvalSignalCase,
match_result: MatchResult,
@@ -365,7 +360,7 @@ class EvalGroupingPipeline:
query_embeddings: list[list[float]],
candidates: list[list[SignalCandidate]],
):
- """Captures whether the matching decision was correct and classifies the failure mode."""
+ """Records whether the matching decision was correct and classifies the failure mode."""
expected_report = self.report_store.find_report_by_group_index(case.group_index)
expected_id = expected_report.context.report_id if expected_report else None
expected = "NEW_REPORT" if expected_report is None else "EXISTING_REPORT"
@@ -430,7 +425,7 @@ class EvalGroupingPipeline:
else None,
}
- self._capture(
+ self.results.record(
eval_name="match-quality",
item_name=f"match-{case.group_index}-{case.signal_index}",
input=case.signal.content.description,
@@ -439,30 +434,20 @@ class EvalGroupingPipeline:
metrics=[
EvalMetric(
name="correct_match",
- result_type="binary",
score=1.0 if correct else 0.0,
- score_min=0,
- score_max=1,
reasoning=None if correct else f"Failure mode: {specificity_failure_mode.value}",
),
EvalMetric(
name="correct_match_pre_specificity",
- result_type="binary",
score=1.0 if pre_specificity_correct else 0.0,
- score_min=0,
- score_max=1,
reasoning=None if pre_specificity_correct else f"Failure mode: {match_failure_mode.value}",
),
EvalMetric(
name="query_diversity",
- description="Average pairwise cosine distance between query embeddings (0 = identical, 1 = orthogonal)",
- result_type="numeric",
score=query_diversity,
),
EvalMetric(
name="candidate_diversity",
- description="Average (1 - Jaccard similarity) across query pairs' candidate sets (0 = identical, 1 = disjoint)",
- result_type="numeric",
score=candidate_diversity,
),
],
@@ -486,7 +471,7 @@ class EvalGroupingPipeline:
report.safety_choice = safety_result.choice
passed = safety_result.choice == expected_safe
- self._capture(
+ self.results.record(
eval_name="report-safety-check",
item_name=f"report-{report_id[:12]}",
input=f"report-{report_id[:12]} ({len(signals)} signals)",
@@ -495,7 +480,6 @@ class EvalGroupingPipeline:
metrics=[
EvalMetric(
name="correct_classification",
- result_type="binary",
score=1.0 if passed else 0.0,
reasoning=safety_result.explanation,
),
@@ -507,7 +491,7 @@ class EvalGroupingPipeline:
logging.getLogger(__name__).exception("Judging report %s failed", report_id[:12])
self.progress.report_judged()
- def _capture_grouping_quality(self):
+ def _record_grouping_quality(self):
"""Per-report metrics: purity, is_pure, group_recall."""
for report in self.report_store.all_reports():
groups = report.true_signal_groups
@@ -526,20 +510,20 @@ class EvalGroupingPipeline:
group_recall = dominant_count / total_in_group
input = [sig.content for sig in self.store.get_signals_for_report(report.context.report_id)]
- self._capture(
+ self.results.record(
eval_name="grouping-quality",
item_name=f"report-{report.context.report_id[:12]}",
input=input,
output=report.context.title,
expected=f"group-{dominant_group}",
metrics=[
- EvalMetric(name="purity", result_type="numeric", score=purity),
- EvalMetric(name="is_pure", result_type="binary", score=1.0 if is_pure else 0.0),
- EvalMetric(name="group_recall", result_type="numeric", score=group_recall),
+ EvalMetric(name="purity", score=purity),
+ EvalMetric(name="is_pure", score=1.0 if is_pure else 0.0),
+ EvalMetric(name="group_recall", score=group_recall),
],
)
- def _capture_aggregate_metrics(self, stream: list[EvalSignalCase]):
+ def _record_aggregate_metrics(self, stream: list[EvalSignalCase]):
"""Global clustering metrics: ARI, homogeneity, completeness, mean_purity, mean_group_recall, malicious_leaked_rate."""
true_labels: list[int] = []
@@ -594,7 +578,7 @@ class EvalGroupingPipeline:
file=sys.stderr,
)
- self._capture(
+ self.results.record(
eval_name="grouping-aggregate",
item_name="aggregate statistics",
input=f"{len(stream)} signals, {n_groups_expected} true groups",
@@ -603,71 +587,28 @@ class EvalGroupingPipeline:
metrics=[
EvalMetric(
name="ari",
- description="Adjusted rand index — chance-corrected clustering similarity, -1 (worst) to 1 (perfect)",
- result_type="numeric",
score=ari,
- score_min=0,
- score_max=1,
),
EvalMetric(
name="homogeneity",
- description="Each report contains only signals from a single true group (1.0 = no overgrouping)",
- result_type="numeric",
score=homogeneity,
),
EvalMetric(
name="completeness",
- description="All signals from a true group are assigned to the same report (1.0 = no undergrouping)",
- result_type="numeric",
score=completeness,
),
EvalMetric(
name="mean_purity",
- description="Average fraction of signals from the dominant group per report",
- result_type="numeric",
score=mean_purity,
),
EvalMetric(
name="group_recall",
- description="Average fraction of a true group's signals captured by its best report",
- result_type="numeric",
score=mean_group_recall,
),
EvalMetric(
name="malicious_leaked_rate",
- description="Fraction of unsafe signals that leaked through the pipeline (not dropped at pre-emit or caught by safety judge)",
- result_type="numeric",
score=unsafe_leaked_rate,
reasoning=f"{unsafe_leaked}/{total_unsafe} malicious signals leaked through",
),
],
)
-
- def _capture(
- self,
- eval_name: str,
- item_name: str,
- input: Any,
- output: Any,
- expected: Any,
- metrics: list[EvalMetric],
- passed: bool = True,
- ):
- if self.no_capture:
- return
- experiment_id = deterministic_uuid(eval_name)
- item_id = deterministic_uuid(f"{eval_name}:{item_name}:{self.start_time}")
- capture_evaluation(
- client=self.posthog_client,
- dataset_id=None,
- experiment_id=experiment_id,
- experiment_name=eval_name,
- item_id=item_id,
- item_name=item_name,
- input=input,
- output=output,
- expected=expected,
- metrics=metrics,
- eval_type="online" if self.online else "offline",
- passed=passed,
- )
diff --git a/products/signals/eval/eval_scout_safety.py b/products/signals/eval/eval_scout_safety.py
index 06cfc54c131a..a3a171f2e607 100644
--- a/products/signals/eval/eval_scout_safety.py
+++ b/products/signals/eval/eval_scout_safety.py
@@ -17,15 +17,20 @@ import sys
from tqdm import tqdm
from products.signals.backend.temporal.safety_filter import SCOUT_SOURCE_PRODUCT, safety_filter
-from products.signals.eval.capture import EvalMetric, capture_evaluation, deterministic_uuid
from products.signals.eval.conftest import EVAL_TEAM_ID
from products.signals.eval.fixtures.scout_safety_data import SCOUT_SAFETY_CASES
+from products.signals.eval.offline import EvalMetric, SignalsEvalRecorder
+from products.signals.eval.offline_config import SCOUT_SAFETY_SUITE
class EvalScoutSafety:
- async def eval_scout_safety_filter(self, posthog_client, no_capture, online, limit):
+ async def eval_scout_safety_filter(self, no_capture, limit, eval_metadata):
cases = SCOUT_SAFETY_CASES[:limit] if limit else SCOUT_SAFETY_CASES
- eval_type = "online" if online else "offline"
+ results = SignalsEvalRecorder(
+ SCOUT_SAFETY_SUITE,
+ disabled=no_capture,
+ metadata=eval_metadata,
+ )
n_safe = sum(1 for c in cases if c.safe)
n_unsafe = len(cases) - n_safe
@@ -41,16 +46,12 @@ class EvalScoutSafety:
leaks += 1
if not no_capture:
- capture_evaluation(
- client=posthog_client,
- experiment_id=deterministic_uuid("scout-safety-filter"),
- experiment_name="scout-safety-filter",
- item_id=deterministic_uuid(case.name),
+ results.record(
+ eval_name="scout-safety-filter",
item_name=case.name,
metrics=[
EvalMetric(
name="correct_classification",
- result_type="binary",
score=1.0 if correct else 0.0,
reasoning=result.explanation or "",
),
@@ -59,7 +60,6 @@ class EvalScoutSafety:
output="SAFE" if result.safe else f"UNSAFE ({result.threat_type})",
expected="SAFE" if case.safe else "UNSAFE",
passed=correct,
- eval_type=eval_type,
)
fp_rate = false_positives / n_safe if n_safe else 0.0
@@ -72,30 +72,24 @@ class EvalScoutSafety:
)
if not no_capture:
- capture_evaluation(
- client=posthog_client,
- experiment_id=deterministic_uuid("scout-safety-aggregate"),
- experiment_name="scout-safety-aggregate",
- item_id=deterministic_uuid("scout-safety-aggregate"),
+ results.record(
+ eval_name="scout-safety-aggregate",
item_name="aggregate statistics",
metrics=[
EvalMetric(
name="false_positive_rate",
- description="Fraction of legitimate scout findings the safety filter wrongly blocked",
- result_type="numeric",
score=fp_rate,
reasoning=f"{false_positives}/{n_safe} legit findings blocked",
),
EvalMetric(
name="payload_leak_rate",
- description="Fraction of dangerous scout findings the safety filter let through",
- result_type="numeric",
score=leak_rate,
reasoning=f"{leaks}/{n_unsafe} payloads leaked",
),
],
- eval_type=eval_type,
)
+ await results.publish()
+
# Guard the relaxation: a real payload leaking is a regression worth failing on.
assert leaks == 0, f"{leaks}/{n_unsafe} dangerous scout finding(s) leaked through the scout safety prompt"
diff --git a/products/signals/eval/offline.py b/products/signals/eval/offline.py
new file mode 100644
index 000000000000..43c9532f5e0d
--- /dev/null
+++ b/products/signals/eval/offline.py
@@ -0,0 +1,138 @@
+from __future__ import annotations
+
+import sys
+import asyncio
+from datetime import UTC, datetime
+from typing import TYPE_CHECKING, Literal
+from uuid import uuid4
+
+from tqdm import tqdm
+
+from posthog.dataclasses import frozen
+
+from products.posthog_ai.eval_harness.engines.types import CaseResult, EvalSummary, ExperimentResult, ScorerResult
+from products.posthog_ai.eval_harness.offline_results import (
+ OfflineEvalPublisher,
+ OfflineEvalSettings,
+ OfflineUploadError,
+)
+
+if TYPE_CHECKING:
+ from products.posthog_ai.eval_harness.offline_results import OfflineEvalSuite
+
+
+@frozen
+class EvalMetric:
+ name: str
+ score: float | None = None
+ reasoning: str | None = None
+ status: Literal["ok", "error", "skipped", "not_applicable"] = "ok"
+ error_code: str | None = None
+ error_message: str | None = None
+
+
+class SignalsEvalRecorder:
+ def __init__(
+ self,
+ suite: OfflineEvalSuite,
+ *,
+ disabled: bool = False,
+ metadata: dict[str, object] | None = None,
+ ) -> None:
+ self.suite = suite
+ self.disabled = disabled
+ self.metadata = metadata or {}
+ self.experiment_id = str(uuid4())
+ self.started_at = datetime.now(UTC)
+ self.cases: list[CaseResult] = []
+ self.publisher: OfflineEvalPublisher | None = None
+ if disabled:
+ return
+ try:
+ settings = OfflineEvalSettings.from_env(suite)
+ if settings is not None:
+ self.publisher = OfflineEvalPublisher(settings, suite)
+ else:
+ self._report("uploads disabled: POSTHOG_OFFLINE_EVAL_API_KEY is not set")
+ except OfflineUploadError as error:
+ self._report(f"uploads disabled: {error}")
+
+ def _report(self, message: str) -> None:
+ tqdm.write(f"PostHog offline ({self.suite.key}): {message}", file=sys.stderr)
+
+ @staticmethod
+ def _metric_name(stage: str, metric: str) -> str:
+ if metric == "correct_classification":
+ if stage.endswith("-actionability-check"):
+ return "actionability_correct_classification"
+ return {
+ "signal-safety-filter": "signal_safety_correct_classification",
+ "report-safety-check": "report_safety_correct_classification",
+ "scout-safety-filter": "scout_safety_correct_classification",
+ }[stage]
+ if stage == "grouping-aggregate" and metric == "group_recall":
+ return "mean_group_recall"
+ return metric
+
+ def record(
+ self,
+ *,
+ eval_name: str,
+ item_name: str,
+ metrics: list[EvalMetric],
+ input: object = None,
+ output: object = None,
+ expected: object = None,
+ passed: bool = True,
+ ) -> None:
+ if self.disabled:
+ return
+ if self.publisher is None:
+ return
+ outcomes = {name: ScorerResult(status="not_applicable") for name in self.suite.scorer_kinds}
+ scores: dict[str, float | None] = {}
+ for metric in metrics:
+ name = self._metric_name(eval_name, metric.name)
+ if name not in outcomes:
+ raise ValueError(f"Unconfigured offline metric: {name}")
+ scores[name] = metric.score
+ outcomes[name] = ScorerResult(
+ status="skipped" if metric.status == "ok" and metric.score is None else metric.status,
+ value=metric.score if metric.status == "ok" else None,
+ reasoning=metric.reasoning,
+ error_code=metric.error_code,
+ error_message=metric.error_message,
+ evaluated_at=datetime.now(UTC),
+ )
+ self.cases.append(
+ CaseResult(
+ input={"name": f"{eval_name}/{item_name}", "input": input},
+ output=output,
+ expected=expected,
+ scores=scores,
+ scorer_results=outcomes,
+ metadata={"stage": eval_name, "passed": passed},
+ )
+ )
+
+ async def publish(self) -> str | None:
+ if self.publisher is None or not self.cases:
+ return None
+ try:
+ upload = self.publisher.prepare(
+ experiment_id=self.experiment_id,
+ experiment_name=self.suite.key,
+ started_at=self.started_at,
+ result=ExperimentResult(
+ summary=EvalSummary(engine_name="signals", experiment_name=self.suite.key, scores={}),
+ results=self.cases,
+ ),
+ metadata=self.metadata,
+ )
+ url = await asyncio.wait_for(self.publisher.publish(upload), timeout=60)
+ except Exception as error:
+ reason = str(error) if isinstance(error, OfflineUploadError) else type(error).__name__
+ self._report(f"upload failed: {reason}. Results were not saved for retry.")
+ return None
+ self._report(f"uploaded: {url}")
+ return url
diff --git a/products/signals/eval/offline_config.py b/products/signals/eval/offline_config.py
new file mode 100644
index 000000000000..f829a71a0b00
--- /dev/null
+++ b/products/signals/eval/offline_config.py
@@ -0,0 +1,59 @@
+from uuid import UUID
+
+from products.posthog_ai.eval_harness.offline_results import OfflineEvalSuite
+
+GROUPING_SUITE = OfflineEvalSuite(
+ key="signals/grouping-e2e",
+ project_id=2,
+ scorer_kinds={
+ "signal_safety_correct_classification": "boolean",
+ "actionability_correct_classification": "boolean",
+ "correct_match": "boolean",
+ "correct_match_pre_specificity": "boolean",
+ "query_diversity": "numeric",
+ "candidate_diversity": "numeric",
+ "report_safety_correct_classification": "boolean",
+ "purity": "numeric",
+ "is_pure": "boolean",
+ "group_recall": "numeric",
+ "ari": "numeric",
+ "homogeneity": "numeric",
+ "completeness": "numeric",
+ "mean_purity": "numeric",
+ "mean_group_recall": "numeric",
+ "malicious_leaked_rate": "numeric",
+ },
+ scorer_versions={
+ "signal_safety_correct_classification": UUID("01a14506-416d-7357-a737-75804a20a316"),
+ "actionability_correct_classification": UUID("01a14506-87c8-7f79-b4f7-f0c685a6fa20"),
+ "correct_match": UUID("01a14506-8e69-79f7-b568-5a03c2f98a47"),
+ "correct_match_pre_specificity": UUID("01a14506-9622-78bb-93ab-4c049252329e"),
+ "query_diversity": UUID("01a14506-9cc2-7977-a3e0-5cc661506e6d"),
+ "candidate_diversity": UUID("01a14506-a39a-70c8-9f7e-c4b85e063ac1"),
+ "report_safety_correct_classification": UUID("01a14506-aa45-7e64-91eb-baa67a43a37a"),
+ "purity": UUID("01a14506-b1bd-7a5d-b1d9-2448036f5478"),
+ "is_pure": UUID("01a14506-ba01-7d34-9f1c-925f870111ca"),
+ "group_recall": UUID("01a14506-c495-74b6-b35d-c222b6ad116f"),
+ "ari": UUID("01a14506-cc21-7c7f-b04c-8e55f21f1aad"),
+ "homogeneity": UUID("01a14506-dba5-704e-953d-036417de6229"),
+ "completeness": UUID("01a14506-e267-708a-9806-eb73f5353f4f"),
+ "mean_purity": UUID("01a14506-eb0b-70e4-8b2c-ed5534529a93"),
+ "mean_group_recall": UUID("01a14506-f383-7742-96eb-13ab08cdd697"),
+ "malicious_leaked_rate": UUID("01a14506-fafc-75c0-8b15-73028c9cdeff"),
+ },
+)
+
+SCOUT_SAFETY_SUITE = OfflineEvalSuite(
+ key="signals/scout-safety",
+ project_id=2,
+ scorer_kinds={
+ "scout_safety_correct_classification": "boolean",
+ "false_positive_rate": "numeric",
+ "payload_leak_rate": "numeric",
+ },
+ scorer_versions={
+ "scout_safety_correct_classification": UUID("01a14507-0323-74ea-be20-8b9e858fa46c"),
+ "false_positive_rate": UUID("01a14507-0a28-7118-89c5-96f38d37878b"),
+ "payload_leak_rate": UUID("01a14507-101a-79a0-932f-40a8cee9cc72"),
+ },
+)
diff --git a/products/signals/eval/reports/2026-09-03.md b/products/signals/eval/reports/2026-09-03.md
index df0815b62564..01f51967808e 100644
--- a/products/signals/eval/reports/2026-09-03.md
+++ b/products/signals/eval/reports/2026-09-03.md
@@ -203,7 +203,7 @@ The effort runs forced `output_config.effort` from the eval wrapper; the PR code
The sonnet-4-5 request shape (assistant prefill, temperature, budget thinking) is byte-identical to master's, so the baseline is master's behavior.
All runs went straight to the Anthropic Messages API rather than through either LLM gateway, so gateway-side behavior (per-team attribution, model allowlists, Bedrock fallback) is not covered.
-Tokens, latency, and stop reasons come from a wrapper around the Anthropic client's `messages.create`; the eval's own `$ai_evaluation` metrics were written to disk instead of captured.
+Tokens, latency, and stop reasons come from a wrapper around the Anthropic client's `messages.create`; the eval metrics were written to disk.
Runs went one at a time, in the order 4-5, 5, 5, 4-5.
Signals run concurrently and only the match step is serialized, so lock-acquisition order varies between runs; the two-run spread above is that noise.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 74effa84e3c1..3b5289209d93 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -68872,26 +68872,6 @@ export namespace Schemas {
NotApplicable: 'not_applicable',
} as const;
- export interface OfflineExperimentItemsRequest {
- /** `$ai_experiment_id` whose offline-evaluation items to return. */
- experiment_id: string;
- /**
- * Lower bound on `timestamp` (ISO-8601). Omit to leave the lower bound open.
- * @nullable
- */
- date_from?: string | null;
- /**
- * Upper bound on `timestamp` (ISO-8601). Omit to leave the upper bound open.
- * @nullable
- */
- date_to?: string | null;
- }
-
- export interface OfflineExperimentItemsResponse {
- /** Tuple-positional rows; positions match `RawOfflineExperimentMetricRow` in the frontend. */
- results: unknown[][];
- }
-
export interface OfflineExperimentRead {
/** Stable experiment UUID. */
id: string;
@@ -127508,10 +127488,6 @@ export namespace Schemas {
Zeabur: 'zeabur',
} as const;
- export type LlmAnalyticsOfflineEvaluationsExperimentItemsCreate400 = { [key: string]: unknown };
-
- export type LlmAnalyticsOfflineEvaluationsExperimentItemsCreate500 = { [key: string]: unknown };
-
export type LlmAnalyticsParserRecipesListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/lib/trace-compaction.ts b/services/mcp/src/lib/trace-compaction.ts
index e192346c7b9a..8b89987fb4da 100644
--- a/services/mcp/src/lib/trace-compaction.ts
+++ b/services/mcp/src/lib/trace-compaction.ts
@@ -121,9 +121,6 @@ export const SUMMARY_METADATA_PROPERTIES = new Set([
'$ai_time_to_first_token',
'$ai_metric_name',
'$ai_metric_value',
- '$ai_score',
- '$ai_score_max',
- '$ai_score_min',
'$ai_span_type',
// Spend. A cost or latency survey is what summary detail is for, so the
// whole breakdown stays: every token count, every per-token price, and the
diff --git a/services/mcp/src/lib/trace-property-allowlist.generated.ts b/services/mcp/src/lib/trace-property-allowlist.generated.ts
index 5992e68772d5..c67a9d7edb37 100644
--- a/services/mcp/src/lib/trace-property-allowlist.generated.ts
+++ b/services/mcp/src/lib/trace-property-allowlist.generated.ts
@@ -47,10 +47,7 @@ export const AI_TAXONOMY_EVENT_PROPERTIES = [
'$ai_evaluation_runtime',
'$ai_evaluation_start_time',
'$ai_evaluation_type',
- '$ai_expected',
'$ai_experiment_id',
- '$ai_experiment_item_id',
- '$ai_experiment_item_name',
'$ai_experiment_name',
'$ai_feedback_text',
'$ai_framework',
@@ -73,7 +70,6 @@ export const AI_TAXONOMY_EVENT_PROPERTIES = [
'$ai_max_tokens',
'$ai_metric_name',
'$ai_metric_value',
- '$ai_metric_version',
'$ai_model',
'$ai_model_cost_used',
'$ai_model_parameters',
@@ -95,10 +91,6 @@ export const AI_TAXONOMY_EVENT_PROPERTIES = [
'$ai_request_count',
'$ai_request_price',
'$ai_request_url',
- '$ai_result_type',
- '$ai_score',
- '$ai_score_max',
- '$ai_score_min',
'$ai_session_id',
'$ai_span_id',
'$ai_span_name',
diff --git a/tach.toml b/tach.toml
index 0181865e7bf4..80ecd7393168 100644
--- a/tach.toml
+++ b/tach.toml
@@ -10,9 +10,11 @@ exclude = [
# lint:tach` (what CI runs) excludes test code from the dependency pass only.
# Eval trees are dev/CI-only tooling: the harness orchestrates many products by
# design, and product-owned suites under products/*/evals import the harness
- # contracts, so neither fits the production dependency graph.
+ # contracts, so neither fits the production dependency graph. Signals keeps its suite
+ # under eval/ rather than evals/, so it is listed by path.
"products/posthog_ai/eval_harness",
"products/*/evals",
+ "products/signals/eval",
]
source_roots = [
".",