:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(aio): publish sql eval results to offline experiments (#114538)
Radu Raiceaee6310eae205
diff --git a/.github/workflows/ci-replay-vision-evals.yml b/.github/workflows/ci-replay-vision-evals.ymlindex 0690c632ba43..7d02dbd3d5c6 100644--- a/.github/workflows/ci-replay-vision-evals.yml+++ b/.github/workflows/ci-replay-vision-evals.yml@@ -46,13 +46,13 @@ jobs:# dataset before failing inside the eval.env:REPLAY_VISION_EVAL_POSTHOG_API_KEY: ${{ secrets.REPLAY_VISION_EVAL_POSTHOG_API_KEY }}- GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}- OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}- ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}+ GEMINI_OFFLINE_EVALS_API_KEY: ${{ secrets.GEMINI_OFFLINE_EVALS_API_KEY }}+ OPENAI_OFFLINE_EVALS_API_KEY: ${{ secrets.OPENAI_OFFLINE_EVALS_API_KEY }}+ ANTHROPIC_OFFLINE_EVALS_API_KEY: ${{ secrets.ANTHROPIC_OFFLINE_EVALS_API_KEY }}BRAINTRUST_API_KEY: ${{ secrets.BRAINTRUST_API_KEY }}run: |missing=""- for name in REPLAY_VISION_EVAL_POSTHOG_API_KEY GEMINI_API_KEY OPENAI_API_KEY ANTHROPIC_API_KEY BRAINTRUST_API_KEY; do+ for name in REPLAY_VISION_EVAL_POSTHOG_API_KEY GEMINI_OFFLINE_EVALS_API_KEY OPENAI_OFFLINE_EVALS_API_KEY ANTHROPIC_OFFLINE_EVALS_API_KEY BRAINTRUST_API_KEY; do[ -n "${!name}" ] || missing="$missing $name"doneif [ -n "$missing" ]; then@@ -156,12 +156,12 @@ jobs:shell: bashenv:REPLAY_VISION_EVAL_DATASET: ${{ env.DATASET_DIR }}- GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}+ GEMINI_API_KEY: ${{ secrets.GEMINI_OFFLINE_EVALS_API_KEY }}BRAINTRUST_API_KEY: ${{ secrets.BRAINTRUST_API_KEY }}# The one-shot preflight name for a plain Anthropic key (used directly, no gateway).- LLM_GATEWAY_ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}+ LLM_GATEWAY_ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_OFFLINE_EVALS_API_KEY }}# The summary_alignment judge (autoevals) calls its model with the OpenAI client.- OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}+ OPENAI_API_KEY: ${{ secrets.OPENAI_OFFLINE_EVALS_API_KEY }}TRIALS: ${{ inputs.trials }}run: |# To the runner-local file only, never the public job log: the eval calls run_scandiff --git a/docs/internal/ai-offline-evaluation-reporting.md b/docs/internal/ai-offline-evaluation-reporting.mdindex 1c16b0fd8222..188d1d7d2e6e 100644--- a/docs/internal/ai-offline-evaluation-reporting.md+++ b/docs/internal/ai-offline-evaluation-reporting.md@@ -1,25 +1,24 @@# Offline evaluation result reporting-The sandboxed evaluation harness in `products/posthog_ai/eval_harness/` reports scorer results as PostHog `$ai_evaluation` events.-With the Braintrust engine, each suite runs once and the harness sends the resulting scores to PostHog when uploads are enabled.+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.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.## Capture settingsEvaluation result uploads to Braintrust and PostHog share the `no_send_logs` setting.-`SandboxedPublicEval` sets `no_send_logs=False` and uploads to both services.+`SandboxedPublicEval` sets `no_send_logs=False` and uploads to Braintrust, plus PostHog when the suite has offline publishing configured.`SandboxedPrivateEval` sets `no_send_logs=True` and uploads to neither service; local logs are still written.-The harness creates one dedicated result client at startup, shares it across all suites, and shuts it down after the invocation.-Each suite waits for queued PostHog uploads in worker threads so other suites can keep running.-This client permits `$ai_evaluation` reporting independently of `TEST` and `OPT_OUT_CAPTURE`, so those settings do not separate the two result destinations.-Ordinary PostHog SDK clients and trace clients retain their existing `TEST` and `OPT_OUT_CAPTURE` guards.+Offline API uploads run through the Python SDK independently of `TEST` and `OPT_OUT_CAPTURE`.+The shared trace client retains its existing `TEST` and `OPT_OUT_CAPTURE` guards for `$ai_generation`, `$ai_span`, and `$ai_trace` events.## Result contents and scope-Each event contains the existing experiment, case, and metric properties, including input, output, and expected values when available.-Each event also carries the run's configuration: `agent_model`, `trials`, `git_sha`, `git_dirty`, and for sandboxed runs `agent_runtime`, `skill_delivery`, and `reasoning_effort`.+Published results include experiment, case, and scorer details, with input, output, and expected values when available.+Run metadata includes `agent_model`, `trials`, `git_sha`, `git_dirty`, and for sandboxed runs `agent_runtime`, `skill_delivery`, and `reasoning_effort`.Each trial has a unique ID in engine metadata. Local logs and summaries use that ID, so repeated trials retain separate output and scores.The harness shortens long case names in filenames to stay within 255 bytes. It keeps the complete trial ID and file extension.@@ -33,10 +32,124 @@ The scoring phase includes time waiting for the experiment results, rather thanA failed final metadata upload produces a warning and keeps the completed results available locally.A scorer failure marks the case as an error. Statistics still include scores from other successful scorers.+## SQL offline experiment pilot++The `sql/eval_sql::eval_sql` suite (`sandboxed-sql-cli`) opts into the offline experiment publisher.+Other public suites continue reporting scores to Braintrust until they opt into offline publishing.+After scoring, the harness prepares the completed results in memory and queues delivery through the Python SDK's `AsyncOfflineEvaluations` client. It does not execute another agent run or judge call.+`no_send_logs=True` suppresses this upload too.++The [SQL suite definition](../../products/posthog_ai/evals/sql/eval_sql.py) pins destination project `2` and the seven immutable scorer version UUIDs.+Provide the API key through the environment before running the suite:++| Variable | Purpose |+| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |+| `POSTHOG_OFFLINE_EVAL_API_KEY` | Personal or project secret API key with `offline_evaluation_ingestion:write`. A public project token cannot authenticate uploads. |+| `POSTHOG_OFFLINE_EVAL_HOST` | App origin; defaults to `https://us.posthog.com`. |++The publisher normalizes the cloud ingestion hosts (`us.i.posthog.com`, `eu.i.posthog.com`) and the legacy `app.posthog.com` host to their app origins.+Uploads, result links, and trace-destination checks use that same origin.++The suite uses these existing scorers:++| Metric name | Scorer kind |+| ------------------------------------ | -------------------------------- |+| `exit_code_zero` | Boolean |+| `no_persistent_insight_save` | Boolean |+| `execute_sql_called` | Boolean |+| `answer_tool_not_typed_query` | Boolean |+| `querying_posthog_data_skill_loaded` | Boolean |+| `sql_schema_alignment` | Numeric, minimum 0 and maximum 1 |+| `sql_result_message_alignment` | Numeric, minimum 0 and maximum 1 |++The harness loads the repo-root `.env` automatically; shell values take precedence.+For CI, store the key as the `POSTHOG_OFFLINE_EVAL_API_KEY` [organization Actions secret](https://github.com/organizations/PostHog/settings/secrets/actions), grant access to the selected repository `PostHog/posthog`, and expose it to the eval step under the same environment variable name.+No project ID or scorer mapping environment variables are required.++```bash+export POSTHOG_OFFLINE_EVAL_API_KEY='your-secret-key'+hogli evals sql/eval_sql::eval_sql+```++Without an API key, the SQL run reports that offline uploads are disabled.+Keys containing whitespace are rejected before evaluation starts; remove any spaces, tabs, or pasted trailing newlines.+Invalid configuration produces a warning and skips this destination; Braintrust and local reporting continue.+An upload failure also warns without changing the evaluation's score gate.+The final summary shows a PostHog results link only after a successful offline upload; otherwise it shows the upload status.++### CI configuration++CI jobs running this suite need `POSTHOG_OFFLINE_EVAL_API_KEY` and `BRAINTRUST_API_KEY` in the environment.+Map the dedicated `ANTHROPIC_OFFLINE_EVALS_API_KEY` and `OPENAI_OFFLINE_EVALS_API_KEY` Actions secrets to `LLM_GATEWAY_ANTHROPIC_API_KEY` and `OPENAI_API_KEY` for the harness and judges.+Publishing failures remain warnings, so check the final harness upload status even when a CI job is green.+The harness sets the SDK's `run_source` to `ci` when `CI` is set, including manual Actions runs, and to `local` otherwise.++### Published results++Each case and trial becomes a separate item, with one result per configured scorer.+Boolean scores convert `0` and `1` to `false` and `true`; numeric scores retain their values.+Both `false` and numeric zero have status `ok`: this status means scoring produced a value, not that the agent passed.+A `None` score becomes `skipped`; a task error or missing scorer result becomes `error`, with no score value.+LLM judge exceptions publish an `error` outcome with code `judge_error`; the existing zero fallback remains in Braintrust and local aggregates.+A failed scorer does not replace successful results from other scorers on the same case.+Scorer metadata and `reason` or `rationale` explanations are retained for each trial, including skip reasons and judge errors.+The scorer recorder observes return values and exceptions only when a suite has valid offline publishing configuration and allows uploads. Other runs pass scorers directly to Braintrust.+Braintrust still owns scorer execution, return-value validation, and numeric aggregation.+Application and evaluator trace links are included when capture is enabled and the trace and offline destinations match.+Application and dataset revisions use the commit captured at run start.++Items include available input, output, expected output, and case metadata.+The publisher excludes `raw_log` from the new API payload; the existing local logs and Braintrust output retain it.+The SDK validates optional fields and the combined payload as fields are added. An invalid or oversized field is omitted as a whole, with its name recorded in `metadata.omitted_fields`.+Item payloads prioritize input, output, expected output, then metadata. Output fields are not pruned individually, and accepted fields are not removed to make room for omission diagnostics.+Invalid optional case keys, dataset references, or trace identifiers are omitted individually, preserving the other cases and scores in the prepared upload.++The publisher retains the prepared experiment, items, scorer versions, and result payloads in memory until delivery finishes.+The SDK owns request validation, batching, acknowledgements, and retries. Requests use a 5-second timeout and up to two retries with the same experiment and item identities, subject to the overall upload deadline.+This leaves time for create, one upload batch, and completion to each retry timed-out requests within the 60-second upload budget. Larger uploads and server-requested retry delays still share that budget; retries are not guaranteed to finish before it expires.+Failure reports retain sanitized error codes and field paths, persistence state, retry guidance, and acknowledged batch/item/result counts without including raw responses or result payloads.+Local case exports finish before delivery is queued. Up to two uploads run concurrently, with at most 32 queued or active uploads and a 60-second deadline per active upload.+After suites finish, the harness pauses unfinished uploads before synchronous infrastructure teardown, then retries the same prepared objects with fresh request and upload deadlines.+These retries retain the experiment, item, and scorer version identities, including after partial acceptance or a lost completion response.+The harness waits up to the full upload deadline (60 seconds by default) for remaining uploads after teardown, including time waiting for a delivery slot.+After an API error following successful experiment creation, the publisher makes a best-effort attempt to mark the experiment failed, limited to 5 seconds, and retains the original upload error. Accepted results remain available on failed experiments.+Pausing or cancelling delivery does not mark the experiment failed, so teardown pauses can resume the same experiment. Timeouts, interruptions, and failed cleanup can leave an experiment in the uploading state.+Timeout, cancellation, a full queue, or a rejected request produces a warning without changing the score gate.+Failed or interrupted uploads are not saved for later retry. To try publishing again, correct the configuration or connectivity problem and rerun the suite.+Existing local logs, enabled case exports, and Braintrust results remain available.++### Enrolling other suites and richer results++Both `SandboxedEval` and `OneShotEval` accept `offline_suite=OfflineEvalSuite(...)`.+Each suite declares its destination `project_id`, selects at least one metric in `scorer_kinds`, and pins the corresponding immutable version UUIDs in `scorer_versions`.+These fields belong to `OfflineEvalSuite` in code. Scorer version UUIDs must be distinct for the suite's enrolled metrics.+Numeric scores can use the domain of their configured scorer version. The API validates bounds and steps; the harness does not restrict every numeric metric to `[0, 1]`.++`OfflineEvalSuite.experiment_options` accepts the SDK's `ExperimentOptions` for external dataset identifiers, `prompt_version`, model/application versions, and `run_source`.+The harness owns the experiment ID, start time, suite key, and expected counts.+For external datasets, case metadata can supply `dataset_item_identifier` and `dataset_item_version_identifier`.+The harness publisher does not support hosted datasets. A non-null `dataset_revision_id` stops preparation with a local error before any upload request.++Ordinary scorers continue returning numeric `Score` values. A scorer can additionally return a typed `ScorerResult` through `Score.result` to publish categorical values or `not_applicable`, explicit errors, reasoning, metadata, timestamps, and evaluator trace references:++```python+from products.posthog_ai.eval_harness.engines.types import ScorerResult+from products.posthog_ai.eval_harness.scorers.contract import Score++result = Score(+ name="answer_category",+ score=None,+ result=ScorerResult(status="ok", value=["correct"], reasoning="The answer matches the reference."),+)+```++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.+## Postgres experiment ingestionThe project API accepts offline experiment results behind the `ai-observability-offline-evaluations` feature flag.-The harness above still uses event capture; it does not call this API yet.+The configured SQL pilot calls this API to publish completed scorer results.Experiments and their items, results, and payloads belong to the exact project/environment in the request path.Scorers and hosted datasets must belong to that same environment.@@ -132,7 +245,7 @@ Automatic payload deletion and usage billing are not enabled by these endpoints.## Postgres experiment readsRead endpoints use the same feature flag as ingestion.-The offline UI uses these APIs. The harness above still reports through event capture until its producer migration.+The offline UI uses these APIs. The configured SQL pilot publishes results here; legacy `$ai_evaluation` events do not populate these views.The following GET paths are relative to `/api/projects/{project_id}/ai_observability/`:diff --git a/products/posthog_ai/eval_harness/README.md b/products/posthog_ai/eval_harness/README.mdindex 6d08e5e9c4be..dac3fd99168b 100644--- a/products/posthog_ai/eval_harness/README.md+++ b/products/posthog_ai/eval_harness/README.md@@ -386,7 +386,37 @@ The harness shortens long case names in filenames to stay within 255 bytes. It kThe summary includes the trial ID, the agent trace ID when available, phase durations in seconds, and the scores for that trial.Case names and `--eval` filters stay the same.-`SandboxedPublicEval` sets `no_send_logs=False` and reports results to both Braintrust and PostHog.+`SandboxedPublicEval` sets `no_send_logs=False` and reports results to Braintrust, plus PostHog when the suite has offline publishing configured.`SandboxedPrivateEval` sets `no_send_logs=True` and uploads results to neither service; local logs are still written.PostHog result uploads follow `no_send_logs` independently of `OPT_OUT_CAPTURE`, which still applies to ordinary SDK and trace clients.See [evaluation result reporting](../../../docs/internal/ai-offline-evaluation-reporting.md) for capture settings and scope.++### SQL offline experiment pilot++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.+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`.+The [SQL suite definition](../evals/sql/eval_sql.py) pins that project ID and all seven immutable scorer version UUIDs in code.+`POSTHOG_OFFLINE_EVAL_HOST` defaults to `https://us.posthog.com`.+The [pilot configuration](../../../docs/internal/ai-offline-evaluation-reporting.md#sql-offline-experiment-pilot) lists the metrics and explains local and CI key configuration.+Delivery runs in a bounded background queue after local results are saved. Prepared uploads stay in memory, with up to two uploads running concurrently, at most 32 queued or active uploads, and a 60-second deadline per active upload.+Unfinished uploads pause before infrastructure teardown. After teardown, the harness retries the same prepared objects and identities with fresh deadlines, waiting up to the full 60-second upload deadline for delivery to finish.+Requests use a 5-second timeout and up to two retries within that overall deadline. Terminal API failures trigger a best-effort attempt to mark the experiment failed, limited to 5 seconds; pauses and interruptions leave it resumable.+Both sandboxed and one-shot suites can opt in through `offline_suite`. Rich scorer recording runs only when offline publishing is configured and uploads are allowed.+The [reporting guide](../../../docs/internal/ai-offline-evaluation-reporting.md#enrolling-other-suites-and-richer-results) covers rich scorer outcomes, external dataset references, version fields, and suite configuration. Hosted datasets are not supported by the harness publisher.++```bash+hogli evals sql/eval_sql::eval_sql+```++With no API key, the SQL run reports that offline uploads are disabled.+Invalid configuration and upload failures produce warnings while Braintrust and local reporting continue.+Successful uploads use separate items for each case and trial; skipped scores and execution errors remain distinct from scores of zero.+Raw agent logs stay in the existing local and Braintrust outputs. The SDK validates payloads; invalid or oversized optional fields are omitted as a whole, with their names recorded in metadata.++Failed or interrupted uploads and uploads rejected by a full queue are not saved for later retry.+To try publishing again, correct the configuration or connectivity problem and rerun the suite.+Existing local logs, enabled case exports, and Braintrust results remain available; upload failures do not change the score gate.diff --git a/products/posthog_ai/eval_harness/base.py b/products/posthog_ai/eval_harness/base.pyindex 5d847e703f26..663c38261065 100644--- a/products/posthog_ai/eval_harness/base.py+++ b/products/posthog_ai/eval_harness/base.py@@ -9,6 +9,7 @@ import tracebackfrom collections.abc import Callable, Sequencefrom contextlib import suppressfrom dataclasses import replace+from datetime import UTC, datetimefrom functools import partialfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literal@@ -38,9 +39,10 @@ from .harness.retries import infrastructure_retry_delayfrom .harness.trial_stats import trial_statsfrom .log_parser import describe_tool_usefrom .log_sink import append_case_scores, build_case_dir, write_case_logs+from .offline_results import OfflineEvalPublisher, OfflineEvalSettings, OfflineEvalSuite, OfflineUploadErrorfrom .runner import AgentNeverRanError, EvalCaseResult, agent_never_ran, run_eval_casefrom .scorers import ExitCodeZero, wrap_scorers-from .trace_events import RunMetadata, emit_evaluation_events, emit_trace_events, emit_trace_root+from .trace_events import RunMetadata, emit_trace_events, emit_trace_rootif TYPE_CHECKING:from .harness.context import EvalContext@@ -152,8 +154,7 @@ class _BaseEvalRun:"""trace_namespace = "evals"- """How this run labels itself in PostHog: the experiment-name prefix on every emitted- event, and the `$ai_eval_source` on evaluation events. Subclasses set it per run kind."""+ """Experiment-name prefix on PostHog trace events. Subclasses set it per run kind."""def __init__(self,@@ -164,12 +165,16 @@ class _BaseEvalRun:is_public: bool,no_send_logs: bool,engine: EvalEngine | None = None,+ offline_suite: OfflineEvalSuite | None = None,) -> None:self.experiment_name = experiment_nameself.cases = casesself.ctx = ctxself.is_public = is_publicself.no_send_logs = no_send_logs+ self.offline_suite = offline_suite+ self.offline_publisher: OfflineEvalPublisher | None = None+ self.started_at = datetime.now(UTC)# The execution/reporting backend, resolved once per run and shared via# ctx.engine; an explicit engine (in tests) overrides it.self.engine = engine or ctx.engine@@ -321,7 +326,7 @@ class _BaseEvalRun:await self.ctx.reporter.case_phase(trial_id, phase)async def _finalize(self, result: ExperimentResult) -> None:- """Append scores to local summaries, emit PostHog evaluation/trace-root+ """Append scores to local summaries, emit PostHog trace-rootevents, and hand the summary to the reporter — after scoring completes."""# Append final scores to local summary files for every case we wrote.if result.results:@@ -340,23 +345,6 @@ class _BaseEvalRun:except Exception:logger.exception("Failed to append scores to local log summary for '%s'", case_name)- evaluation_client = self.ctx.posthog_evaluation_client- if not self.no_send_logs and evaluation_client is not None and result.results:- try:- emit_evaluation_events(- evaluation_client,- self.experiment_id,- self.experiment_name,- result.results,- namespace=self.trace_namespace,- scorer_traces=self.scorer_traces,- run_metadata=self._experiment_metadata(),- )- await asyncio.to_thread(evaluation_client.flush)- await self.ctx.reporter.record_posthog_evaluations_url(self.experiment_name, self.experiment_id)- except Exception:- logger.exception("Failed to emit evaluation events for '%s'", self.experiment_name)-# Emit trace roots to PostHog (after scoring)if self.posthog_client and result.results:try:@@ -403,6 +391,40 @@ class _BaseEvalRun:if os.getenv("EXPORT_EVAL_RESULTS"):self._export_case_results(result)+ await self._enqueue_offline_upload(result)++ async def _enqueue_offline_upload(self, result: ExperimentResult) -> None:+ if self.offline_publisher is None or self.no_send_logs:+ return+ try:+ upload = await asyncio.to_thread(+ self.offline_publisher.prepare,+ experiment_id=self.experiment_id,+ experiment_name=self.experiment_name,+ started_at=self.started_at,+ result=result,+ metadata=self._experiment_metadata(),+ )+ except Exception as error:+ detail = str(error) if isinstance(error, OfflineUploadError) else type(error).__name__+ await self.ctx.reporter.record_posthog_offline_result(+ self.experiment_name, f"upload preparation failed: {detail}"+ )+ return++ delivery = self.ctx.offline_delivery+ if delivery is None:+ await self.ctx.reporter.record_posthog_offline_result(+ self.experiment_name,+ "upload failed: background delivery is unavailable. Results were not saved for retry.",+ )+ return+ await self.ctx.reporter.record_posthog_offline_result(self.experiment_name, "upload queued")+ if not delivery.submit(self.offline_publisher, upload):+ await self.ctx.reporter.record_posthog_offline_result(+ self.experiment_name, "upload failed: upload queue is full or closed. Results were not saved for retry."+ )+def _export_case_results(self, result: ExperimentResult) -> None:"""Write one JSONL row per case x trial to the run's local log dir.@@ -449,6 +471,27 @@ class _BaseEvalRun:async def run(self) -> ExperimentResult:eval_cases = self._build_eval_cases()+ if self.offline_suite is not None and not self.no_send_logs:+ try:+ settings = OfflineEvalSettings.from_env(self.offline_suite)+ if settings is not None:+ self.offline_publisher = OfflineEvalPublisher(+ settings,+ self.offline_suite,+ application_trace_ids_enabled=(+ self.posthog_client is not None+ and not self.posthog_client.disabled+ and settings.host == self.ctx.posthog_trace_host+ and settings.project_id == self.ctx.posthog_trace_project_id+ ),+ )+ else:+ await self.ctx.reporter.record_posthog_offline_result(+ self.experiment_name, "disabled: set POSTHOG_OFFLINE_EVAL_* to enable uploads"+ )+ except OfflineUploadError as error:+ await self.ctx.reporter.record_posthog_offline_result(self.experiment_name, f"disabled: {error}")+# Register the case total (post-filter, times trials) so the reporter can# append a per-experiment progress counter to each case line.planned_cases = len(eval_cases) * self.ctx.trials@@ -468,6 +511,7 @@ class _BaseEvalRun:# runs; the metadata is what lets an engine filter or compare by them.metadata=self._experiment_metadata(),on_results=self._report_results,+ record_scorer_results=self.offline_publisher is not None,))await self._report_results(result)@@ -562,6 +606,7 @@ class _SandboxedEvalRun(_BaseEvalRun):ctx: EvalContext,is_public: bool,no_send_logs: bool,+ offline_suite: OfflineEvalSuite | None = None,) -> None:if any(isinstance(scorer, ExitCodeZero) for scorer in scorers):raise ValueError("ExitCodeZero is added by the sandboxed eval harness; remove it from scorers")@@ -572,6 +617,7 @@ class _SandboxedEvalRun(_BaseEvalRun):ctx=ctx,is_public=is_public,no_send_logs=no_send_logs,+ offline_suite=offline_suite,)# Narrow the infra-backed optionals once: they are None only when the# harness didn't boot sandbox infrastructure for this run.@@ -817,6 +863,7 @@ async def SandboxedEval(ctx: EvalContext,is_public: bool = False,no_send_logs: bool = True,+ offline_suite: OfflineEvalSuite | None = None,) -> ExperimentResult:"""Run a sandboxed agent evaluation suite via Braintrust.@@ -840,6 +887,7 @@ async def SandboxedEval(ctx=ctx,is_public=is_public,no_send_logs=no_send_logs,+ offline_suite=offline_suite,)return await run.run()diff --git a/products/posthog_ai/eval_harness/engines/braintrust.py b/products/posthog_ai/eval_harness/engines/braintrust.pyindex 7cd091e63cc8..a6ba71180f5d 100644--- a/products/posthog_ai/eval_harness/engines/braintrust.py+++ b/products/posthog_ai/eval_harness/engines/braintrust.py@@ -12,6 +12,8 @@ from braintrust import EvalAsync, EvalCase, EvalHooksfrom braintrust.framework import EvalResultWithSummary, Evaluator, ReporterDeffrom braintrust.logger import Span, SpanImpl+from ..scorers.recording import ScorerRecorder+# Imported for its side effect: braintrust's offline summary crashes on a skipped score.from . import braintrust_patches # noqa: F401from .types import AggregateScore, CaseResult, EnvVarSpec, EvalSummary, ExperimentResult, ExperimentSpec, SpanKind@@ -98,9 +100,12 @@ class BraintrustEngine:next(iter(trial_spans.values())).flush()async def run_experiment(self, spec: ExperimentSpec) -> ExperimentResult:+ recorder = ScorerRecorder() if spec.record_scorer_results else Nonetrial_spans: dict[str, Span] = {}async def bridged_task(input: dict[str, Any], hooks: EvalHooks) -> dict[str, Any] | None:+ if recorder is not None:+ recorder.register(hooks.metadata, hooks.trial_index)# Wrap braintrust's hooks so the suite task only ever sees neutral CaseHooks.try:return await spec.task(input, _BraintrustCaseHooks(hooks))@@ -116,7 +121,9 @@ class BraintrustEngine:spec.project_name,data=cases,task=bridged_task,- scores=list(spec.scorers),+ scores=[recorder.wrap(scorer, index) for index, scorer in enumerate(spec.scorers)]+ if recorder is not None+ else list(spec.scorers),trial_count=spec.trial_count,# Our global concurrency semaphores are the only limiters that should# bind. Braintrust's own per-suite limiter must never gate, so let it@@ -137,7 +144,7 @@ class BraintrustEngine:# across runs; the metadata is what lets Braintrust filter or compare.metadata=spec.metadata,)- translated = self._translate(result)+ translated = self._translate(result, recorder)if spec.on_results is not None:await spec.on_results(translated)if trial_spans:@@ -149,7 +156,7 @@ class BraintrustEngine:)return translated- def _translate(self, result: EvalResultWithSummary) -> ExperimentResult:+ def _translate(self, result: EvalResultWithSummary, recorder: ScorerRecorder | None = None) -> ExperimentResult:"""Map braintrust's ``EvalResultWithSummary`` onto the neutral model.``score=None`` is preserved per-case (the aggregate drops it, online@@ -175,6 +182,8 @@ class BraintrustEngine:scores=dict(case.scores or {}),expected=case.expected,metadata=dict(case.metadata or {}),+ scorer_results=recorder.outcomes(case.metadata, case.scores) if recorder is not None else {},+ trial_index=recorder.trial_index(case.metadata) if recorder is not None else None,error_kind="task" if case.error is not None else "scorer",error=(str(case.error)diff --git a/products/posthog_ai/eval_harness/engines/types.py b/products/posthog_ai/eval_harness/engines/types.pyindex d245af8a87c3..447b5df95ea1 100644--- a/products/posthog_ai/eval_harness/engines/types.py+++ b/products/posthog_ai/eval_harness/engines/types.py@@ -15,6 +15,7 @@ import jsonfrom collections.abc import Awaitable, Callable, Iterator, Sequencefrom contextlib import AbstractContextManager, contextmanagerfrom dataclasses import dataclass, field+from datetime import datetimefrom typing import Any, Literal, Protocol@@ -94,6 +95,21 @@ class ExperimentSpec:no_send_logs: boolmetadata: dict[str, Any]on_results: Callable[[ExperimentResult], Awaitable[None]] | None = None+ record_scorer_results: bool = False+++@dataclass(frozen=True, kw_only=True, slots=True)+class ScorerResult:+ """A scorer outcome for reporting, independent of its normalized aggregate score."""++ status: Literal["ok", "error", "skipped", "not_applicable"]+ value: float | int | bool | list[str] | None = None+ reasoning: str | None = None+ metadata: dict[str, object] = field(default_factory=dict)+ error_code: str | None = None+ error_message: str | None = None+ evaluator_trace_id: str | None = None+ evaluated_at: datetime | None = None@dataclass(frozen=False)@@ -112,6 +128,8 @@ class CaseResult:expected: Any = Nonemetadata: dict[str, Any] = field(default_factory=dict)error: str | None = None+ scorer_results: dict[str, ScorerResult] = field(default_factory=dict)+ trial_index: int | None = Noneerror_kind: Literal["task", "scorer"] = "task"diff --git a/products/posthog_ai/eval_harness/harness/context.py b/products/posthog_ai/eval_harness/harness/context.pyindex 73451bd43fe4..106cd46a8102 100644--- a/products/posthog_ai/eval_harness/harness/context.py+++ b/products/posthog_ai/eval_harness/harness/context.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport asynciofrom dataclasses import dataclass+from typing import TYPE_CHECKINGfrom posthoganalytics import Posthog@@ -10,6 +11,9 @@ from .cli import SkillDeliveryfrom .demo_data import SandboxedDemoDatafrom .providers import SandboxProvider, SandboxProviderStrategyfrom .reporting import ProgressReporter++if TYPE_CHECKING:+ from .offline_delivery import OfflineEvalDeliveryfrom .retries import DEFAULT_INFRA_RETRIES@@ -56,9 +60,6 @@ class EvalContext:posthog_client: Posthog | None"""Analytics client for eval traces, with the default capture guards."""- posthog_evaluation_client: Posthog | None- """Shared result client for suites that enable experiment uploads."""-sandbox_slots: asyncio.Semaphore | None"""The one global limiter on concurrently live sandboxes, shared by everysuite. ``None`` when no selected suite is sandboxed."""@@ -89,4 +90,10 @@ class EvalContext:git_dirty: bool | None"""Whether tracked files differed from ``git_sha``; ``None`` when unknown."""+ offline_delivery: OfflineEvalDelivery | None = None+ """Run-owned delivery worker, drained after infrastructure teardown."""++ posthog_trace_host: str | None = None+ posthog_trace_project_id: int | None = None+infrastructure_retries: int = DEFAULT_INFRA_RETRIESdiff --git a/products/posthog_ai/eval_harness/harness/lifecycle.py b/products/posthog_ai/eval_harness/harness/lifecycle.pyindex 1f6105cc8b9d..2cc5907ec928 100644--- a/products/posthog_ai/eval_harness/harness/lifecycle.py+++ b/products/posthog_ai/eval_harness/harness/lifecycle.py@@ -45,6 +45,7 @@ from .django_env import EvalDatabasefrom .env_preflight import validate_eval_envfrom .kernel_sandboxes import reclaim_kernelsfrom .live_server import EvalLiveServer+from .offline_delivery import OfflineEvalDeliveryfrom .ports import DJANGO_LIVE_PORTfrom .providers import PreflightError, SandboxProviderStrategy, build_providerfrom .reporting import ProgressReporter, SuiteRunResult@@ -133,9 +134,9 @@ class SandboxedEvalHarness:self._database: EvalDatabase | None = Noneself._live_server: EvalLiveServer | None = Noneself._posthog_client: Posthog | None = None- self._posthog_evaluation_client: Posthog | None = Noneself._demo_data: SandboxedDemoData | None = None- # Read before asyncio.run so the git subprocesses never block the event loop.+ self._offline_delivery: OfflineEvalDelivery | None = None+ # Capture the revision before any eval starts so every result describes the same run.self._git_sha = _git("rev-parse", "HEAD")self._git_dirty = _worktree_dirty()@@ -187,37 +188,53 @@ class SandboxedEvalHarness:started = time.monotonic()results: list[SuiteRunResult] | None = Noneinterrupted = False- try:- reporter.setup_started("check configuration")- validate_eval_env(self.options.agent_runtime, kinds=kinds, engine_env=self._engine.required_env())- if Infra.SANDBOX in required:- self.provider = build_provider(- self.options.provider,- keep_containers=self.options.keep_sandbox_containers,- rebuild_image=self.options.rebuild_sandbox_image,- )- self._validate_agent_options()- self.provider.preflight()- if Infra.PERSONHOG in required:- reporter.setup_started("build personhog")- ensure_personhog_binaries()- reporter.setup_started("start shared services and prepare demo data")- self._bootstrap(required, reporter)- if self._dashboard:- self._dashboard.setup_finished()- results = asyncio.run(self._run_suites(suites, required, reporter))- except KeyboardInterrupt:- logger.warning("Interrupted, tearing down")- interrupted = True- finally:+ self._offline_delivery = OfflineEvalDelivery(reporter)+ with asyncio.Runner() as runner:try:+ reporter.setup_started("check configuration")+ validate_eval_env(self.options.agent_runtime, kinds=kinds, engine_env=self._engine.required_env())+ if Infra.SANDBOX in required:+ self.provider = build_provider(+ self.options.provider,+ keep_containers=self.options.keep_sandbox_containers,+ rebuild_image=self.options.rebuild_sandbox_image,+ )+ self._validate_agent_options()+ self.provider.preflight()+ if Infra.PERSONHOG in required:+ reporter.setup_started("build personhog")+ ensure_personhog_binaries()+ reporter.setup_started("start shared services and prepare demo data")+ self._bootstrap(required, reporter)if self._dashboard:- self._dashboard.set_stage("Cleaning up shared services")- self._stack.close()+ self._dashboard.setup_finished()+ results = runner.run(self._run_suites(suites, required, reporter))+ except KeyboardInterrupt:+ logger.warning("Interrupted, tearing down")+ interrupted = Truefinally:- atexit.unregister(stop_all_subprocesses)- if self.provider is not None:- atexit.unregister(self.provider.cleanup)+ try:+ if self._dashboard:+ self._dashboard.set_stage("Cleaning up shared services")+ try:+ runner.run(self._offline_delivery.pause())+ finally:+ self._stack.close()+ except KeyboardInterrupt:+ interrupted = True+ finally:+ atexit.unregister(stop_all_subprocesses)+ if self.provider is not None:+ atexit.unregister(self.provider.cleanup)+ try:+ runner.run(+ self._offline_delivery.cancel()+ if interrupted or results is None+ else self._offline_delivery.drain()+ )+ except KeyboardInterrupt:+ interrupted = True+ runner.run(self._offline_delivery.cancel())duration_seconds = time.monotonic() - startedif interrupted:@@ -324,11 +341,6 @@ class SandboxedEvalHarness:if self._posthog_client is not None:self._stack.callback(self._posthog_client.shutdown)- # Each suite's no_send_logs setting controls result uploads to both services.- self._posthog_evaluation_client = get_client("US", disabled=False)- if self._posthog_evaluation_client is not None:- self._stack.callback(self._posthog_evaluation_client.shutdown)-if Infra.DEMO_DATA in required:reporter.setup_started("prepare demo data")assert self._database is not None@@ -413,6 +425,8 @@ class SandboxedEvalHarness:)else:logger.info("Running %d suite(s) without sandbox infrastructure", len(suites))+ if self._offline_delivery is not None:+ stack.push_async_callback(self._offline_delivery.pause)async with reporter.live_updates():results = await asyncio.gather(*(self._run_suite(suite, ctx) for suite in suites))return results@@ -441,7 +455,6 @@ class SandboxedEvalHarness:case_filter=self.options.case_filter,demo_data=self._demo_data,posthog_client=self._posthog_client,- posthog_evaluation_client=self._posthog_evaluation_client,sandbox_slots=asyncio.Semaphore(self.options.max_sandboxes) if Infra.SANDBOX in required else None,team_setup_slots=asyncio.Semaphore(self.options.team_setup_concurrency),one_shot_slots=asyncio.Semaphore(DEFAULT_ONE_SHOT_CONCURRENCY),@@ -451,6 +464,9 @@ class SandboxedEvalHarness:trials=self.options.trials,git_sha=self._git_sha,git_dirty=self._git_dirty,+ offline_delivery=self._offline_delivery,+ posthog_trace_host="https://us.posthog.com",+ posthog_trace_project_id=settings.LLM_ANALYTICS_INTERNAL_TEAM_ID,infrastructure_retries=self.options.infrastructure_retries,)diff --git a/products/posthog_ai/eval_harness/harness/offline_delivery.py b/products/posthog_ai/eval_harness/harness/offline_delivery.pynew file mode 100644index 000000000000..ab8eb84d9ab9--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/offline_delivery.py@@ -0,0 +1,130 @@+from __future__ import annotations++import asyncio+import logging+from collections.abc import Iterable+from typing import TYPE_CHECKING++from posthog.dataclasses import frozen++from ..offline_results import OfflineUploadError++if TYPE_CHECKING:+ from ..offline_results import OfflineEvalPublisher, OfflineEvalUpload+ from .reporting import ProgressReporter++logger = logging.getLogger(__name__)+++@frozen+class _PendingUpload:+ publisher: OfflineEvalPublisher+ upload: OfflineEvalUpload+++class OfflineEvalDelivery:+ def __init__(+ self,+ reporter: ProgressReporter,+ *,+ max_concurrency: int = 2,+ max_pending: int = 32,+ upload_timeout: float = 60.0,+ ) -> None:+ if max_concurrency < 1 or max_pending < 1 or upload_timeout < 0:+ raise ValueError("Upload concurrency and capacity must be positive, and timeout must be nonnegative")+ self._reporter = reporter+ self._slots = asyncio.Semaphore(max_concurrency)+ self._max_pending = max_pending+ self._upload_timeout = upload_timeout+ self._tasks: dict[asyncio.Task[None], _PendingUpload] = {}+ self._uploading: set[asyncio.Task[None]] = set()+ self._paused_jobs: dict[asyncio.Task[None], _PendingUpload] = {}+ self._paused = False+ self._closed = False++ async def _report_failed(self, job: _PendingUpload, reason: str) -> None:+ await self._reporter.record_posthog_offline_result(+ job.upload.experiment_name, f"upload failed: {reason}. Results were not saved for retry."+ )++ async def _deliver(self, job: _PendingUpload) -> None:+ task = asyncio.current_task()+ assert task is not None+ reason: str | None = None+ url: str | None = None+ try:+ async with self._slots:+ url = await asyncio.wait_for(job.publisher.publish(job.upload), timeout=self._upload_timeout)+ except TimeoutError:+ reason = "upload deadline exceeded"+ except Exception as error:+ reason = str(error) if isinstance(error, OfflineUploadError) else type(error).__name__+ finally:+ self._uploading.discard(task)+ if reason is not None:+ await self._report_failed(job, reason)+ else:+ await self._reporter.record_posthog_offline_result(job.upload.experiment_name, "uploaded", url=url)++ def _finished(self, task: asyncio.Task[None]) -> None:+ self._tasks.pop(task, None)+ self._uploading.discard(task)+ if not task.cancelled() and (error := task.exception()) is not None:+ logger.error("Failed to report offline evaluation upload", exc_info=error)++ def _start(self, job: _PendingUpload) -> None:+ task = asyncio.create_task(self._deliver(job))+ self._tasks[task] = job+ self._uploading.add(task)+ task.add_done_callback(self._finished)++ def submit(self, publisher: OfflineEvalPublisher, upload: OfflineEvalUpload) -> bool:+ if self._closed or self._paused or sum(not task.done() for task in self._tasks) >= self._max_pending:+ return False+ self._start(_PendingUpload(publisher=publisher, upload=upload))+ return True++ def _pending_uploads(self) -> dict[asyncio.Task[None], _PendingUpload]:+ return {task: job for task, job in self._tasks.items() if not task.done() and task in self._uploading}++ async def _cancel(self, tasks: Iterable[asyncio.Task[None]], reason: str | None) -> None:+ pending = {task: self._tasks[task] for task in tasks if not task.done()}+ uploads = [job for task, job in pending.items() if task in self._uploading]+ for task in pending:+ task.cancel()+ if pending:+ await asyncio.gather(*pending, return_exceptions=True)+ if reason is not None:+ for job in uploads:+ await self._report_failed(job, reason)++ async def pause(self) -> None:+ if self._closed:+ return+ self._paused = True+ self._paused_jobs.update(self._pending_uploads())+ await self._cancel(tuple(self._paused_jobs), None)++ async def cancel(self) -> None:+ self._closed = True+ pending = {**self._paused_jobs, **self._pending_uploads()}+ await self._cancel(tuple(self._tasks), None)+ self._paused_jobs.clear()+ for job in pending.values():+ await self._report_failed(job, "upload interrupted")++ async def drain(self, timeout: float | None = None) -> None:+ self._closed = True+ for job in self._paused_jobs.values():+ self._start(job)+ self._paused_jobs.clear()+ tasks = tuple(self._tasks)+ if not tasks:+ return+ try:+ _, pending = await asyncio.wait(tasks, timeout=self._upload_timeout if timeout is None else timeout)+ await self._cancel(pending, "shutdown deadline exceeded")+ except asyncio.CancelledError:+ await self.cancel()+ raisediff --git a/products/posthog_ai/eval_harness/harness/reporting.py b/products/posthog_ai/eval_harness/harness/reporting.pyindex 9588ef1ccc31..271ec323743d 100644--- a/products/posthog_ai/eval_harness/harness/reporting.py+++ b/products/posthog_ai/eval_harness/harness/reporting.py@@ -24,10 +24,6 @@ if TYPE_CHECKING:EVAL_RESULTS_JSONL = "eval_results.jsonl""""Machine-readable per-experiment summary export, opt-in via ``EXPORT_EVAL_RESULTS``."""-POSTHOG_EVALUATIONS_URL = (- "https://us.posthog.com/project/2/ai-evals/evaluations/offline/experiments/{experiment_id}?offline_date_from=-1d"-)-CaseStatus = Literal["ok", "timeout", "error"]@@ -86,6 +82,7 @@ class ProgressReporter:self._trial_stats: dict[str, Sequence[ScorerTrialStats]] = {}self._experiment_totals: dict[str, int] = {}self._posthog_urls: dict[str, str] = {}+ self._posthog_offline_statuses: dict[str, str] = {}self._log_dirs: dict[str, Path] = {}self._active_cases: dict[str, _CaseProgress] = {}self._started = time.monotonic()@@ -341,9 +338,12 @@ class ProgressReporter:progress = f"[{self._case_counts[experiment_name]}/{total} cases]" if total is not None else ""await asyncio.to_thread(_emit, f"EXPERIMENT DONE {experiment_name} {progress}")- async def record_posthog_evaluations_url(self, experiment_name: str, experiment_id: str) -> None:+ async def record_posthog_offline_result(self, experiment_name: str, status: str, *, url: str | None = None) -> None:async with self._lock:- self._posthog_urls[experiment_name] = POSTHOG_EVALUATIONS_URL.format(experiment_id=experiment_id)+ self._posthog_offline_statuses[experiment_name] = status+ if url is not None:+ self._posthog_urls[experiment_name] = url+ await asyncio.to_thread(_emit, f"POSTHOG OFFLINE {experiment_name} {url or status}")def print_final_summary(self,@@ -440,6 +440,8 @@ class ProgressReporter:posthog_url = self._posthog_urls.get(experiment_name)if posthog_url:lines.append(f" PostHog: {posthog_url}")+ if (offline_status := self._posthog_offline_statuses.get(experiment_name)) and offline_status != "uploaded":+ lines.append(f" PostHog offline: {offline_status}")lines.append(f" {summary.engine_name.title()}: {summary.experiment_url or '(local run, not uploaded)'}")log_dir = self._log_dirs.get(experiment_name)if log_dir:diff --git a/products/posthog_ai/eval_harness/offline_results.py b/products/posthog_ai/eval_harness/offline_results.pynew file mode 100644index 000000000000..5cfe9e1dcad9--- /dev/null+++ b/products/posthog_ai/eval_harness/offline_results.py@@ -0,0 +1,406 @@+from __future__ import annotations++import os+import re+import json+import asyncio+from collections import Counter+from collections.abc import Mapping+from contextlib import suppress+from dataclasses import field+from datetime import datetime+from typing import cast+from urllib.parse import urlsplit+from uuid import UUID, uuid5++from posthoganalytics.ai.evaluations import (+ AsyncOfflineEvaluations,+ BulkUploadError,+ EvaluationAPIError,+ EvaluationItem,+ EvaluationResult,+ ExperimentOptions,+ JSONValue,+ ResultOptions,+ ScorerKind,+)+from pydantic import BaseModel, ConfigDict, Field, SecretStr, ValidationError, field_validator++from posthog.dataclasses import frozen++from .engines.types import CaseResult, ExperimentResult, ScorerResult+++@frozen+class OfflineEvalSuite:+ key: str+ project_id: int+ scorer_kinds: Mapping[str, ScorerKind]+ scorer_versions: Mapping[str, UUID]+ experiment_options: ExperimentOptions = field(default_factory=lambda: ExperimentOptions())+++class OfflineUploadError(Exception):+ @staticmethod+ def _safe_token(value: object, *, path: bool) -> str | None:+ pattern = (+ r"[a-z][a-z0-9_]{0,63}(?:\.(?:[a-z][a-z0-9_]{0,63}|[0-9]{1,6})){0,5}" if path else r"[a-z][a-z0-9_]{0,63}"+ )+ return value if isinstance(value, str) and len(value) <= 128 and re.fullmatch(pattern, value) else None++ def __init__(self, message: str, *, api_error: EvaluationAPIError | None = None) -> None:+ self.status = api_error.status if api_error is not None else None+ self.code = self._safe_token(api_error.code, path=False) if api_error is not None else None+ self.attr = self._safe_token(api_error.attr, path=True) if api_error is not None else None+ self.persistence = api_error.persistence if api_error is not None else None+ self.retry_after = api_error.retry_after if api_error is not None else None+ self.completed_chunk_count: int | None = None+ self.acknowledged_item_count: int | None = None+ self.acknowledged_result_count: int | None = None+ self.pending_result_count: int | None = None+ self.failed_index: int | None = None+ details: list[str] = []+ if self.code is not None:+ details.append(f"code={self.code}")+ if self.attr is not None:+ details.append(f"field={self.attr}")+ if self.persistence is not None:+ details.append(f"persistence={self.persistence}")+ if self.retry_after is not None:+ details.append(f"retry after {self.retry_after:g}s")+ if isinstance(api_error, BulkUploadError):+ chunks = api_error.completed.chunks+ self.completed_chunk_count = len(chunks)+ self.acknowledged_item_count = len({item.id for chunk in chunks for item in chunk.items})+ self.acknowledged_result_count = len({result.id for chunk in chunks for result in chunk.results})+ self.pending_result_count = len(api_error.pending_results)+ self.failed_index = api_error.failed_index+ details.append(+ f"acknowledged {self.acknowledged_item_count} items and {self.acknowledged_result_count} results "+ f"in {self.completed_chunk_count} batches; {self.pending_result_count} results await acknowledgment"+ )+ if details:+ message += " " + "; ".join(details) + "."+ if self.status in (401, 403):+ message += " Check the key's offline_evaluation_ingestion:write scope and project access."+ super().__init__(message)+++class OfflineEvalSettings(BaseModel):+ model_config = ConfigDict(frozen=True, hide_input_in_errors=True)++ host: str = "https://us.posthog.com"+ project_id: int = Field(gt=0)+ api_key: SecretStr+ scorer_versions: dict[str, UUID]+ request_timeout: float = Field(default=5, gt=0, allow_inf_nan=False)+ max_retries: int = Field(default=2, ge=0)++ @field_validator("api_key")+ @classmethod+ def validate_api_key(cls, api_key: SecretStr) -> SecretStr:+ value = api_key.get_secret_value()+ if not value or any(character.isspace() for character in value):+ raise OfflineUploadError("POSTHOG_OFFLINE_EVAL_API_KEY must be nonempty and contain no whitespace")+ return api_key++ @field_validator("host")+ @classmethod+ def normalize_host(cls, host: str) -> str:+ try:+ parsed = urlsplit(host.strip().rstrip("/"))+ port = parsed.port+ except ValueError:+ raise OfflineUploadError("POSTHOG_OFFLINE_EVAL_HOST must be an HTTPS origin") from None+ if (+ parsed.scheme != "https"+ or not parsed.hostname+ or parsed.username is not None+ or parsed.password is not None+ or parsed.query+ or parsed.fragment+ or parsed.path+ ):+ raise OfflineUploadError("POSTHOG_OFFLINE_EVAL_HOST must be an HTTPS origin")+ origin = parsed.netloc.lower()+ if port in (None, 443):+ origin = {+ "app.posthog.com": "us.posthog.com",+ "us.i.posthog.com": "us.posthog.com",+ "eu.i.posthog.com": "eu.posthog.com",+ }.get(parsed.hostname, origin.removesuffix(":443"))+ return f"https://{origin}"++ @classmethod+ def from_env(cls, suite: OfflineEvalSuite) -> OfflineEvalSettings | None:+ prefix = "POSTHOG_OFFLINE_EVAL_"+ api_key = os.getenv(prefix + "API_KEY")+ if not api_key:+ return None+ try:+ settings = cls(+ host=os.getenv(prefix + "HOST", "https://us.posthog.com"),+ project_id=suite.project_id,+ api_key=SecretStr(api_key),+ scorer_versions=dict(suite.scorer_versions),+ )+ except ValidationError:+ raise OfflineUploadError(+ "Offline evaluation suite has an invalid project ID or scorer version mapping"+ ) from None+ if not set(suite.scorer_kinds) <= set(settings.scorer_versions):+ raise OfflineUploadError("Offline evaluation suite must map every enrolled metric to a scorer version UUID")+ enrolled_versions = [settings.scorer_versions[metric] for metric in suite.scorer_kinds]+ if len(set(enrolled_versions)) != len(enrolled_versions):+ raise OfflineUploadError("Each offline metric must have a distinct scorer version UUID")+ return settings+++@frozen+class OfflineEvalUpload:+ host: str+ project_id: int+ experiment_name: str+ experiment: ExperimentOptions+ results: tuple[EvaluationResult, ...]+++class OfflineEvalPublisher:+ def __init__(+ self,+ settings: OfflineEvalSettings,+ suite: OfflineEvalSuite,+ *,+ application_trace_ids_enabled: bool = False,+ ) -> None:+ self.settings = settings+ self.suite = suite+ self.application_trace_ids_enabled = application_trace_ids_enabled++ def _item_payload(+ self,+ case: CaseResult,+ metadata: Mapping[str, object],+ omitted: list[str],+ ) -> dict[str, JSONValue]:+ output = case.output+ if isinstance(output, dict) and "raw_log" in output:+ output = {key: value for key, value in output.items() if key != "raw_log"}+ omitted.append("output.raw_log")+ fields = {+ "input": case.input,+ "output": output,+ "expected_output": case.expected,+ "metadata": {**metadata, "case": case.metadata},+ }+ # Reserve fixed omission markers so diagnostics never displace accepted fields.+ reserved: dict[str, JSONValue] = {"omitted_fields": [*omitted, *fields]}+ payload: dict[str, JSONValue] = {"metadata": reserved}+ for key, value in fields.items():+ candidate = {**payload, key: cast(JSONValue, value)}+ if key == "metadata":+ candidate[key] = {**cast(dict[str, JSONValue], value), **reserved}+ try:+ EvaluationItem(payload=candidate)+ except (ValueError, TypeError, UnicodeError, RecursionError):+ omitted.append(key)+ else:+ payload = candidate+ payload["metadata"] = {**cast(dict[str, JSONValue], payload["metadata"]), "omitted_fields": [*omitted]}+ return payload++ def _item(+ self,+ case: CaseResult,+ *,+ item_id: UUID,+ name: str,+ trial: int,+ metadata: Mapping[str, object],+ ) -> EvaluationItem:+ declaration: dict[str, object] = {"id": str(item_id), "trial": str(trial)}+ omitted: list[str] = []+ for key, value in {+ "case_key": name,+ "application_trace_id": case.metadata.get("trace_id") if self.application_trace_ids_enabled else None,+ "dataset_item_identifier": case.metadata.get("dataset_item_identifier"),+ "dataset_item_version_identifier": case.metadata.get("dataset_item_version_identifier"),+ }.items():+ if value is None:+ continue+ candidate = {**declaration, key: value}+ try:+ EvaluationItem.from_dict(candidate)+ except (ValueError, TypeError, UnicodeError, RecursionError):+ omitted.append(key)+ else:+ declaration = candidate+ return EvaluationItem.from_dict({**declaration, "payload": self._item_payload(case, metadata, omitted)})++ def _outcome(self, case: CaseResult, metric: str) -> ScorerResult:+ if case.error is not None and case.error_kind == "task":+ return ScorerResult(status="error", error_code="task_error", error_message=case.error)+ if metric in case.scorer_results:+ return case.scorer_results[metric]+ if metric not in case.scores:+ scorer_errors = case.metadata.get("scorer_errors", {})+ detail = (+ str(scorer_errors.get(metric, "Scorer did not return a result"))+ if isinstance(scorer_errors, dict)+ else "Scorer did not return a result"+ )+ return ScorerResult(status="error", error_code="missing_score", error_message=detail)+ value = case.scores[metric]+ return ScorerResult(status="skipped" if value is None else "ok", value=value)++ def _score(self, case: CaseResult, metric: str, item: EvaluationItem) -> EvaluationResult:+ outcome = self._outcome(case, metric)+ value = outcome.value+ kind = self.suite.scorer_kinds[metric]+ try:+ if outcome.status == "ok":+ if kind == "boolean":+ if type(value) not in (bool, int, float) or value not in (0, 1):+ raise ValueError+ value = bool(value)+ elif kind == "numeric" and type(value) not in (int, float):+ raise ValueError+ elif kind == "categorical" and not isinstance(value, list):+ raise ValueError+ EvaluationResult(+ item=item,+ scorer_version_id=self.settings.scorer_versions[metric],+ value=value,+ status=outcome.status,+ )+ except (ValueError, TypeError, UnicodeError, RecursionError):+ return EvaluationResult(+ item=item,+ scorer_version_id=self.settings.scorer_versions[metric],+ status="error",+ error_code="invalid_score",+ error_message="Scorer returned an unsupported value or status",+ )+ options: dict[str, object] = {"value": value, "status": outcome.status}+ fields = {+ "reasoning": outcome.reasoning,+ "metadata": outcome.metadata,+ "error_code": outcome.error_code,+ "error_message": outcome.error_message,+ "evaluator_trace_id": outcome.evaluator_trace_id if self.application_trace_ids_enabled else None,+ "evaluated_at": outcome.evaluated_at,+ }+ omitted: list[str] = []+ for key, optional_value in fields.items():+ if optional_value is None:+ continue+ candidate = {**options, key: optional_value}+ try:+ EvaluationResult(+ item=item,+ scorer_version_id=self.settings.scorer_versions[metric],+ **cast(+ ResultOptions,+ {+ **candidate,+ "metadata": {+ **cast(dict[str, JSONValue], candidate.get("metadata", {})),+ "omitted_fields": list(fields),+ },+ },+ ),+ )+ except (ValueError, TypeError, UnicodeError, RecursionError):+ omitted.append(key)+ else:+ options = candidate+ if omitted:+ options["metadata"] = {+ **cast(dict[str, JSONValue], options.get("metadata", {})),+ "omitted_fields": omitted,+ }+ return EvaluationResult(+ item=item,+ scorer_version_id=self.settings.scorer_versions[metric],+ **cast(ResultOptions, options),+ )++ def prepare(+ self,+ *,+ experiment_id: str,+ experiment_name: str,+ started_at: datetime,+ result: ExperimentResult,+ metadata: Mapping[str, object],+ ) -> OfflineEvalUpload:+ if not self.suite.scorer_kinds:+ raise OfflineUploadError("An offline evaluation suite must enroll at least one scorer")+ if self.suite.experiment_options.get("dataset_revision_id") is not None:+ raise OfflineUploadError("Hosted datasets are not supported by the harness publisher")+ revision = metadata.get("git_sha")+ experiment: ExperimentOptions = {+ "run_source": "ci" if os.getenv("CI") else "local",+ "application_version": revision if isinstance(revision, str) else None,+ "model_version": str(metadata["agent_model"]) if metadata.get("agent_model") is not None else None,+ "dataset_source": "repository",+ "dataset_identifier": self.suite.key,+ "dataset_revision_identifier": revision if isinstance(revision, str) else None,+ **self.suite.experiment_options,+ "id": experiment_id,+ "started_at": started_at.isoformat(),+ "suite_key": self.suite.key,+ "expected_item_count": len(result.results),+ "expected_result_count": len(result.results) * len(self.suite.scorer_kinds),+ }+ experiment = cast(+ ExperimentOptions,+ {key: str(value) if isinstance(value, UUID) else value for key, value in experiment.items()},+ )+ trials: Counter[str] = Counter()+ scores: list[EvaluationResult] = []+ for index, case in enumerate(result.results):+ name = str(case.input.get("name", f"case-{index}"))+ trial = case.trial_index if case.trial_index is not None else trials[name]+ trials[name] += 1+ item = self._item(+ case,+ item_id=uuid5(UUID(experiment_id), json.dumps([name, trial])),+ name=name,+ trial=trial,+ metadata={**metadata, "braintrust_url": result.summary.experiment_url, "trial_index": trial},+ )+ scores.extend(self._score(case, metric, item) for metric in self.suite.scorer_kinds)+ return OfflineEvalUpload(+ host=self.settings.host,+ project_id=self.settings.project_id,+ experiment_name=experiment_name,+ experiment=experiment,+ results=tuple(scores),+ )++ async def publish(self, upload: OfflineEvalUpload) -> str:+ if upload.host != self.settings.host or upload.project_id != self.settings.project_id:+ raise OfflineUploadError("Upload destination differs from the configured host/project")+ try:+ async with AsyncOfflineEvaluations(+ host=self.settings.host,+ project_id=self.settings.project_id,+ secret_key=self.settings.api_key.get_secret_value(),+ timeout=self.settings.request_timeout,+ max_retries=self.settings.max_retries,+ ) as client:+ experiment = await client.create_experiment(name=upload.experiment_name, **upload.experiment)+ try:+ await experiment.upload_results(upload.results)+ await experiment.complete()+ except EvaluationAPIError:+ with suppress(Exception):+ await asyncio.wait_for(experiment.fail(), timeout=5)+ raise+ except EvaluationAPIError as error:+ raise OfflineUploadError(str(error), api_error=error) from None+ return (+ f"{upload.host}/project/{upload.project_id}"+ f"/ai-evals/evaluations/offline/experiments/{upload.experiment['id']}"+ )diff --git a/products/posthog_ai/eval_harness/one_shot.py b/products/posthog_ai/eval_harness/one_shot.pyindex 900d1e60bbe1..d7b79a8dfa6f 100644--- a/products/posthog_ai/eval_harness/one_shot.py+++ b/products/posthog_ai/eval_harness/one_shot.py@@ -20,6 +20,7 @@ from .base import _BaseEvalRunfrom .config import BaseEvalCasefrom .engines.types import CaseHooks, ExperimentResultfrom .log_sink import write_case_logs+from .offline_results import OfflineEvalSuiteif TYPE_CHECKING:from .harness.context import EvalContext@@ -50,6 +51,7 @@ class _OneShotEvalRun(_BaseEvalRun):is_public: bool,no_send_logs: bool,task_fn: OneShotTaskFn,+ offline_suite: OfflineEvalSuite | None = None,) -> None:super().__init__(experiment_name=experiment_name,@@ -58,6 +60,7 @@ class _OneShotEvalRun(_BaseEvalRun):ctx=ctx,is_public=is_public,no_send_logs=no_send_logs,+ offline_suite=offline_suite,)self._task_fn = task_fn@@ -110,6 +113,7 @@ async def OneShotEval(ctx: EvalContext,is_public: bool = False,no_send_logs: bool = True,+ offline_suite: OfflineEvalSuite | None = None,) -> ExperimentResult:"""Run a one-shot evaluation suite via Braintrust.@@ -127,6 +131,7 @@ async def OneShotEval(is_public=is_public,no_send_logs=no_send_logs,task_fn=task,+ offline_suite=offline_suite,)return await run.run()diff --git a/products/posthog_ai/eval_harness/scorers/contract.py b/products/posthog_ai/eval_harness/scorers/contract.pyindex eeeaf79c7d92..b0ab8fd02829 100644--- a/products/posthog_ai/eval_harness/scorers/contract.py+++ b/products/posthog_ai/eval_harness/scorers/contract.py@@ -1,23 +1,32 @@"""The PostHog-owned scorer contract.-Ships as a shim today: ``Score`` re-exports braintrust's and ``Scorer`` is an-empty subclass of braintrust's base — zero behavior change. Both still satisfy+``Score`` extends braintrust's normalized score with an optional reporting+outcome. ``Scorer`` retains braintrust's execution behavior. Both still satisfybraintrust's duck-typed dispatch (``hasattr(scorer, "eval_async")``) and scorecheck (``name``/``score``/``metadata``/``as_dict``), so scorers written againstthis module stay directly consumable by ``BraintrustEngine`` with no adapter.-A later flip replaces these with pure PostHog classes carrying the same surface-(``eval_async(output, expected, **kwargs)``, ``_name()``, ``Score.name/score/-metadata/as_dict``) — a single-file change that no scorer has to follow.+Set ``Score.result`` for categorical values, explicit statuses, or other+reporting details. ``Score.score`` still controls the existing score averages;+use ``None`` when the reporting outcome has no numeric aggregate."""from __future__ import annotationsfrom typing import Any-from braintrust import Score as Score+from braintrust import Score as BraintrustScorefrom braintrust_core.score import Scorer as _UpstreamScorer+from posthog.dataclasses import frozen++from ..engines.types import ScorerResult+++@frozen(frozen=False)+class Score(BraintrustScore):+ result: ScorerResult | None = None+class Scorer(_UpstreamScorer):"""PostHog's scorer base. An empty subclass of braintrust's base for now."""diff --git a/products/posthog_ai/eval_harness/scorers/judged.py b/products/posthog_ai/eval_harness/scorers/judged.pyindex e95b113ddca0..521e3fe205b8 100644--- a/products/posthog_ai/eval_harness/scorers/judged.py+++ b/products/posthog_ai/eval_harness/scorers/judged.py@@ -11,7 +11,9 @@ from __future__ import annotationsfrom typing import Anyfrom autoevals.llm import LLMClassifier+from braintrust import Score as BraintrustScore+from ..engines.types import ScorerResultfrom .contract import AsyncOnlyScorerMixin, Score# Re-exported for back-compat: AsyncOnlyScorerMixin now lives in the scorer contract.@@ -53,14 +55,19 @@ class JudgedScorer(AsyncOnlyScorerMixin, LLMClassifier):from ``_prepare`` deliberately."""- async def _run_eval_async(self, output: Any, expected: Any = None, **kwargs: Any) -> Score:+ async def _run_eval_async(self, output: Any, expected: Any = None, **kwargs: Any) -> BraintrustScore:prepared = self._prepare(output, expected)- if isinstance(prepared, Score):+ if isinstance(prepared, BraintrustScore):return preparedtry:return await super()._run_eval_async(prepared["output"], prepared.get("expected"), **kwargs)except Exception as exc:- return Score(name=self._name(), score=0.0, metadata={"reason": f"judge error: {exc}"})+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": f"judge error: {exc}"},+ result=ScorerResult(status="error", error_code="judge_error", error_message=str(exc)),+ )- def _prepare(self, output: Any, expected: Any) -> dict[str, Any] | Score:+ def _prepare(self, output: Any, expected: Any) -> dict[str, Any] | BraintrustScore:raise NotImplementedErrordiff --git a/products/posthog_ai/eval_harness/scorers/recording.py b/products/posthog_ai/eval_harness/scorers/recording.pynew file mode 100644index 000000000000..f7a3a0dbb66a--- /dev/null+++ b/products/posthog_ai/eval_harness/scorers/recording.py@@ -0,0 +1,131 @@+"""Capture reporting outcomes without changing the scores returned to the engine."""++from __future__ import annotations++from contextlib import contextmanager+from contextvars import ContextVar+from dataclasses import replace+from datetime import UTC, datetime+from functools import wraps+from typing import TYPE_CHECKING, Any++from braintrust.framework import _scorer_name+from braintrust.score import is_scorer+from braintrust.util import bt_iscoroutinefunction++from ..engines.types import ScorerResult++if TYPE_CHECKING:+ from collections.abc import Callable, Iterator, Mapping+++class ScorerRecorder:+ def __init__(self) -> None:+ self._results: dict[int, dict[str, ScorerResult]] = {}+ self._trial_indices: dict[int, int] = {}+ self._metadata: ContextVar[dict[str, Any]] = ContextVar("scorer_metadata")++ def register(self, metadata: dict[str, Any], trial_index: int) -> None:+ # Braintrust shares this dict between a trial's hooks, scorers and result.+ self._results[id(metadata)] = {}+ self._trial_indices[id(metadata)] = trial_index+ # Scorer tasks and Braintrust executor threads inherit their trial task's context.+ self._metadata.set(metadata)++ def _trace_id(self, metadata: dict[str, Any], name: str) -> str | None:+ traces = metadata.get("scorer_trace_ids")+ trace_id = traces.get(name) if isinstance(traces, dict) else None+ return trace_id if isinstance(trace_id, str) else None++ def _record(self, metadata: dict[str, Any], score: object, *, scorer_name: str) -> None:+ if isinstance(score, dict):+ name, value, score_metadata = score.get("name"), score.get("score"), score.get("metadata")+ else:+ name = getattr(score, "name", scorer_name)+ value = getattr(score, "score", score)+ score_metadata = getattr(score, "metadata", None)+ if not isinstance(name, str) or not isinstance(value, (float, int, type(None))):+ return+ score_metadata = dict(score_metadata) if isinstance(score_metadata, dict) else {}+ trace_id = self._trace_id(metadata, name) or self._trace_id(metadata, scorer_name)+ explicit_result = getattr(score, "result", None)+ if isinstance(explicit_result, ScorerResult):+ outcome = replace(+ explicit_result,+ metadata={**score_metadata, **explicit_result.metadata},+ evaluator_trace_id=explicit_result.evaluator_trace_id or trace_id,+ evaluated_at=explicit_result.evaluated_at or datetime.now(UTC),+ )+ else:+ reasoning = score_metadata.get("rationale") or score_metadata.get("reason")+ outcome = ScorerResult(+ status="skipped" if value is None else "ok",+ value=value,+ reasoning=reasoning if isinstance(reasoning, str) else None,+ metadata=score_metadata,+ evaluator_trace_id=trace_id,+ evaluated_at=datetime.now(UTC),+ )+ self._results[id(metadata)][name] = outcome++ def _record_error(self, metadata: dict[str, Any], name: str, error: Exception) -> None:+ self._results[id(metadata)][name] = ScorerResult(+ status="error",+ error_code="scorer_error",+ error_message=str(error),+ evaluator_trace_id=self._trace_id(metadata, name),+ evaluated_at=datetime.now(UTC),+ )++ def trial_index(self, metadata: dict[str, Any] | None) -> int | None:+ return self._trial_indices.get(id(metadata))++ def outcomes(self, metadata: dict[str, Any] | None, scores: Mapping[str, float | None]) -> dict[str, ScorerResult]:+ errors = metadata.get("scorer_errors", {}) if metadata is not None else {}+ return {+ name: outcome+ for name, outcome in self._results.get(id(metadata), {}).items()+ if name in scores or outcome.status == "error" and isinstance(errors, dict) and name in errors+ }++ @contextmanager+ def _capture(self, name: str) -> Iterator[Callable[[object], None]]:+ metadata = self._metadata.get()++ def record(result: object) -> None:+ for score in result if isinstance(result, (list, tuple)) else (result,):+ self._record(metadata, score, scorer_name=name)++ try:+ yield record+ except Exception as error:+ self._record_error(metadata, name, error)+ raise++ def _observe(self, scorer: Callable[..., Any], name: str) -> Callable[..., Any]:+ if bt_iscoroutinefunction(scorer):++ @wraps(scorer)+ async def observe_async(*args: Any, **kwargs: Any) -> Any:+ with self._capture(name) as record:+ result = await scorer(*args, **kwargs)+ record(result)+ return result++ return observe_async++ @wraps(scorer)+ def observe_sync(*args: Any, **kwargs: Any) -> Any:+ with self._capture(name) as record:+ result = scorer(*args, **kwargs)+ record(result)+ return result++ return observe_sync++ def wrap(self, scorer: Any, index: int) -> Callable[..., Any]:+ scorer = scorer() if isinstance(scorer, type) and is_scorer(scorer) else scorer+ name = _scorer_name(scorer, index)+ wrapped = self._observe(getattr(scorer, "eval_async", scorer), name)+ wrapped.__name__ = name+ return wrappeddiff --git a/products/posthog_ai/eval_harness/scorers/tracing.py b/products/posthog_ai/eval_harness/scorers/tracing.pyindex 4c922a55a29f..cedbba6729a7 100644--- a/products/posthog_ai/eval_harness/scorers/tracing.py+++ b/products/posthog_ai/eval_harness/scorers/tracing.py@@ -119,9 +119,9 @@ class TracedScorer(AsyncOnlyScorerMixin, Scorer):"""Wraps a Scorer to trace LLM calls and collect per-invocation trace IDs.For LLM-based scorers (those with a ``client`` attribute), injects a- PostHog-traced OpenAI client. For all scorers, generates a trace_id+ PostHog-traced OpenAI client. For LLM scorers, generates a trace_idper invocation and stores it in ``scorer_traces`` for later use in- ``$ai_evaluation`` events.+ offline evaluation results."""def __init__(@@ -180,6 +180,12 @@ class TracedScorer(AsyncOnlyScorerMixin, Scorer):async def _run_eval_async(self, output, expected=None, **kwargs):case_name = kwargs.get("metadata", {}).get("trial_id") or _case_name_from_kwargs(kwargs)with self._invocation_context(case_name) as is_llm_scorer:+ metadata = kwargs.get("metadata")+ context = _scorer_context.get()+ if isinstance(metadata, dict) and context is not None:+ if not isinstance(metadata.get("scorer_trace_ids"), dict):+ metadata["scorer_trace_ids"] = {}+ metadata["scorer_trace_ids"][self._name()] = context["trace_id"]# eval_async, not _run_eval_async: sync-only inner scorers rely on# the base class's async-to-sync delegation.result = await self._inner.eval_async(output, expected, **kwargs)diff --git a/products/posthog_ai/eval_harness/test/offline_api.py b/products/posthog_ai/eval_harness/test/offline_api.pynew file mode 100644index 000000000000..f1e75ada44bf--- /dev/null+++ b/products/posthog_ai/eval_harness/test/offline_api.py@@ -0,0 +1,61 @@+from __future__ import annotations++import json+from uuid import UUID, uuid5++import httpx+++class OfflineServer:+ def __init__(self) -> None:+ self.requests: list[httpx.Request] = []+ self.items: dict[str, object] = {}+ self.results: dict[tuple[str, str], object] = {}+ self.experiment: dict[str, object] = {}+ self.status = "uploading"++ def respond(self, request: httpx.Request) -> httpx.Response:+ self.requests.append(request)+ body = json.loads(request.content)+ now = str(self.experiment.get("started_at", body.get("started_at")))+ if request.url.path.endswith("/upload/"):+ item_receipts = []+ result_receipts = []+ for item in body["items"]:+ item_receipts.append({"id": item["id"], "created": item["id"] not in self.items, "accepted_at": now})+ assert self.items.setdefault(item["id"], item) == item+ for result in body["results"]:+ identity = (result["item_id"], result["scorer_version_id"])+ result_receipts.append(+ {+ "id": str(uuid5(UUID(str(self.experiment["id"])), str(identity))),+ "item_id": identity[0],+ "scorer_version_id": identity[1],+ "created": identity not in self.results,+ "accepted_at": now,+ }+ )+ assert self.results.setdefault(identity, result) == result+ return httpx.Response(200, json={"items": item_receipts, "results": result_receipts})+ closing = request.url.path.endswith(("/complete/", "/fail/"))+ if closing:+ self.status = "completed" if request.url.path.endswith("/complete/") else "failed"+ else:+ if self.experiment:+ assert body == self.experiment+ self.experiment = body+ return httpx.Response(+ 200,+ json={+ "id": self.experiment["id"],+ "status": self.status,+ "created": not closing,+ "started_at": now,+ "created_at": now,+ "finished_at": now if closing else None,+ "expected_item_count": self.experiment.get("expected_item_count"),+ "expected_result_count": self.experiment.get("expected_result_count"),+ "accepted_item_count": len(self.items),+ "accepted_result_count": len(self.results),+ },+ )diff --git a/products/posthog_ai/eval_harness/test/test_engine_conformance.py b/products/posthog_ai/eval_harness/test/test_engine_conformance.pyindex fa2fb82cca5f..013323898f2a 100644--- a/products/posthog_ai/eval_harness/test/test_engine_conformance.py+++ b/products/posthog_ai/eval_harness/test/test_engine_conformance.py@@ -2,14 +2,32 @@ from __future__ import annotationsimport asynciofrom typing import Any+from uuid import UUIDimport pytest+from unittest.mock import AsyncMock+from autoevals.score import Score as AutoevalsScorefrom braintrust import Scorefrom braintrust_core.score import Scorer+from pydantic import SecretStrfrom products.posthog_ai.eval_harness.engines.braintrust import BraintrustEngine-from products.posthog_ai.eval_harness.engines.types import CaseHooks, CaseSpec, ExperimentResult, ExperimentSpec+from products.posthog_ai.eval_harness.engines.types import (+ CaseHooks,+ CaseSpec,+ ExperimentResult,+ ExperimentSpec,+ ScorerResult,+)+from products.posthog_ai.eval_harness.offline_results import OfflineEvalPublisher, OfflineEvalSettings, OfflineEvalSuite+from products.posthog_ai.eval_harness.scorers.contract import (+ AsyncOnlyScorerMixin,+ Score as HarnessScore,+ Scorer as HarnessScorer,+)+from products.posthog_ai.eval_harness.scorers.judged import JudgedScorer+from products.posthog_ai.eval_harness.scorers.tracing import TracedClients, TracedScorer, _build_posthog_kwargs# Every ``EvalEngine`` must satisfy these obligations; a future ``PostHogEvalsEngine``# joins this parameter list and must pass the same suite unchanged.@@ -33,7 +51,7 @@ class _MaybeNoneScorer(Scorer):def _run_eval_sync(self, output: dict[str, Any] | None, expected: Any = None, **kwargs: Any) -> Score:if output and output.get("skip"):- return Score(name="maybe", score=None)+ return Score(name="maybe", score=None, metadata={"reason": "Does not apply"})return Score(name="maybe", score=1.0 if (output and output.get("good")) else 0.0)@@ -43,6 +61,7 @@ def _spec(*,scorers: list[Any] | None = None,trial_count: int = 1,+ record_scorer_results: bool = False,) -> ExperimentSpec:return ExperimentSpec(project_name="conformance",@@ -53,6 +72,7 @@ def _spec(is_public=False,no_send_logs=True,metadata={},+ record_scorer_results=record_scorer_results,)@@ -60,14 +80,18 @@ def _run(engine: BraintrustEngine, spec: ExperimentSpec) -> ExperimentResult:return asyncio.run(engine.run_experiment(spec))-def test_one_result_per_case_and_trial(engine: BraintrustEngine) -> None:[email protected]("record_scorer_results", [False, True])+def test_one_result_per_case_and_trial(engine: BraintrustEngine, record_scorer_results: bool) -> None:async def task(input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:return {"good": True}cases = [CaseSpec(input={"name": name}) for name in ("a", "b", "c")]- result = _run(engine, _spec(task, cases, trial_count=2))+ result = _run(engine, _spec(task, cases, trial_count=2, record_scorer_results=record_scorer_results))assert len(result.results) == 6+ assert [(case.input["name"], case.trial_index) for case in result.results] == [+ (name, index if record_scorer_results else None) for name in ("a", "b", "c") for index in (0, 1)+ ]def test_input_round_trips(engine: BraintrustEngine) -> None:@@ -107,21 +131,262 @@ def test_task_exception_becomes_error_and_is_excluded_from_aggregate(engine: Braassert result.summary.scores["maybe"].score == 1.0-def test_none_score_preserved_per_case_and_excluded_from_aggregate(engine: BraintrustEngine) -> None:[email protected]("record_scorer_results", [False, True])+def test_none_score_preserved_per_case_and_excluded_from_aggregate(+ engine: BraintrustEngine, record_scorer_results: bool+) -> None:async def task(input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:if input["name"] == "skip":return {"skip": True}return {"good": input["name"] == "hit"}cases = [CaseSpec(input={"name": name}) for name in ("hit", "skip", "miss")]- result = _run(engine, _spec(task, cases))+ result = _run(engine, _spec(task, cases, record_scorer_results=record_scorer_results))by_name = {r.input["name"]: r for r in result.results}assert by_name["skip"].scores == {"maybe": None}+ if record_scorer_results:+ assert by_name["skip"].scorer_results["maybe"].status == "skipped"+ assert by_name["skip"].scorer_results["maybe"].reasoning == "Does not apply"+ else:+ assert all(not case.scorer_results for case in result.results)# None is excluded, so the mean is over hit (1.0) and miss (0.0).assert result.summary.scores["maybe"].score == 0.5+def test_scorer_details_and_errors_stay_with_concurrent_trials(engine: BraintrustEngine) -> None:+ started = 0+ tasks = 0+ all_started = asyncio.Event()++ class _Judge(AsyncOnlyScorerMixin, HarnessScorer):+ client = object()++ def _name(self) -> str:+ return "judge"++ async def _run_eval_async(self, output: Any, expected: Any = None, **kwargs: Any) -> AutoevalsScore:+ nonlocal started+ started += 1+ if started == 3:+ all_started.set()+ await all_started.wait()+ trace_id = _build_posthog_kwargs()["posthog_trace_id"]+ if output["execution"] == 2:+ raise ValueError("Judge unavailable")+ return AutoevalsScore(+ name="judge",+ score=float(output["execution"]),+ metadata={"rationale": f"Reason {output['execution']}", "observed_trace": trace_id},+ )++ async def task(input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:+ nonlocal tasks+ execution = tasks+ tasks += 1+ hooks.metadata["trial_id"] = f"trial-{execution}"+ return {"execution": execution}++ scorer = TracedScorer(+ _Judge(),+ TracedClients(openai_llm_client=object(), anthropic_client=object()),+ {"run_metadata": {}},+ {},+ )+ result = _run(+ engine,+ _spec(task, [CaseSpec(input={"name": "same"})], scorers=[scorer], trial_count=3, record_scorer_results=True),+ )++ assert tasks == started == 3+ assert result.summary.scores["judge"].score == 0.5+ outcomes = [case.scorer_results["judge"] for case in result.results]+ assert len({outcome.evaluator_trace_id for outcome in outcomes}) == 3+ for case, outcome in zip(result.results, outcomes):+ assert outcome.evaluator_trace_id == case.metadata["scorer_trace_ids"]["judge"]+ assert outcome.evaluated_at is not None and outcome.evaluated_at.tzinfo is not None+ if case.output["execution"] == 2:+ assert outcome.status == "error"+ assert outcome.error_message == "Judge unavailable"+ assert "judge" not in case.scores+ else:+ assert outcome.status == "ok"+ assert outcome.reasoning == f"Reason {case.output['execution']}"+ assert outcome.metadata["observed_trace"] == outcome.evaluator_trace_id+ assert outcome.value == case.scores["judge"]+++def test_judge_failure_preserves_zero_aggregate_and_error_upload(+ engine: BraintrustEngine, monkeypatch: pytest.MonkeyPatch+) -> None:+ class _Judge(JudgedScorer):+ def _prepare(self, output: Any, expected: Any) -> dict[str, Any]:+ return {"output": output}++ async def task(input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:+ return {"answer": "Synthetic answer"}++ monkeypatch.setattr(+ "autoevals.llm.arun_cached_request", AsyncMock(side_effect=ConnectionError("Judge unavailable"))+ )+ scorer = _Judge(+ name="judge", prompt_template="{{output}}", choice_scores={"yes": 1.0, "no": 0.0}, model="test-model"+ )+ result = _run(engine, _spec(task, [CaseSpec(input={"name": "a"})], scorers=[scorer], record_scorer_results=True))++ case = result.results[0]+ assert case.error is None+ assert case.scores == {"judge": 0.0}+ assert result.summary.scores["judge"].score == 0.0+ outcome = case.scorer_results["judge"]+ assert outcome.status == "error"+ assert outcome.value is None+ assert outcome.error_code == "judge_error"+ assert outcome.error_message == "Judge unavailable"+ assert outcome.evaluated_at is not None++ publisher = OfflineEvalPublisher(+ OfflineEvalSettings(+ project_id=123,+ api_key=SecretStr("test-only-token"),+ scorer_versions={"judge": UUID("00000000-0000-4000-8000-000000000002")},+ ),+ OfflineEvalSuite(+ key="test/judge",+ project_id=123,+ scorer_kinds={"judge": "numeric"},+ scorer_versions={"judge": UUID("00000000-0000-4000-8000-000000000002")},+ ),+ )+ upload = publisher.prepare(+ experiment_id="00000000-0000-4000-8000-000000000001",+ experiment_name="judge-error",+ started_at=outcome.evaluated_at,+ result=result,+ metadata={},+ )+ uploaded = upload.results[0].to_dict()+ assert uploaded["status"] == "error"+ assert "value" not in uploaded+ assert uploaded["error_code"] == "judge_error"+ assert uploaded["payload"]["error_message"] == "Judge unavailable"+++ "outcome",+ [+ ScorerResult(status="ok", value=["relevant"], reasoning="Matches the requested topic", metadata={"rubric": 2}),+ ScorerResult(status="not_applicable", reasoning="No answer to classify"),+ ],+)+def test_explicit_scorer_outcome_keeps_numeric_aggregation_compatible(+ engine: BraintrustEngine, outcome: ScorerResult+) -> None:+ class _ReportingScorer(HarnessScorer):+ def _name(self) -> str:+ return "reporting"++ def _run_eval_sync(self, output: Any, expected: Any = None, **kwargs: Any) -> HarnessScore:+ return HarnessScore("reporting", None, metadata={"source": "classifier"}, result=outcome)++ async def task(input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:+ return {}++ result = _run(+ engine, _spec(task, [CaseSpec(input={"name": "a"})], scorers=[_ReportingScorer()], record_scorer_results=True)+ )++ actual = result.results[0].scorer_results["reporting"]+ assert actual.status == outcome.status+ assert actual.value == outcome.value+ assert actual.reasoning == outcome.reasoning+ assert actual.metadata == {"source": "classifier", **outcome.metadata}+ assert result.results[0].scores == {"reporting": None}+ assert "reporting" not in result.summary.scores+++ "score_output, expected_scores, expected_trace_ids",+ [+ (0.5, {"score": 0.5}, {"score": "origin-trace"}),+ (1.1, {}, {}),+ ([Score(name="first", score=1.0), {"name": "invalid", "score": 0.5}], {}, {}),+ (+ {"name": "metric", "score": 0.25, "metadata": {"reason": "Partial match"}},+ {"metric": 0.25},+ {"metric": "origin-trace"},+ ),+ (+ [+ Score(name="first", score=1.0),+ Score(name="second", score=None),+ HarnessScore(+ name="third",+ score=0.25,+ result=ScorerResult(status="ok", value=0.25, evaluator_trace_id="explicit-trace"),+ ),+ ],+ {"first": 1.0, "second": None, "third": 0.25},+ {"first": "metric-trace", "second": "origin-trace", "third": "explicit-trace"},+ ),+ ],+)[email protected]("scorer_form", ["sync", "async", "instance", "class"])[email protected]("record_scorer_results", [False, True])+def test_callable_scorers_keep_their_supported_return_shapes(+ engine: BraintrustEngine,+ score_output: object,+ expected_scores: dict[str, float | None],+ expected_trace_ids: dict[str, str],+ scorer_form: str,+ record_scorer_results: bool,+) -> None:+ calls = 0++ async def task(input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:+ return {"answer": "match"}++ scorer_name = "async_score" if scorer_form == "async" else "score"++ def score(output: dict[str, Any], metadata: dict[str, Any]) -> object:+ nonlocal calls+ calls += 1+ assert output == {"answer": "match"}+ metadata["scorer_trace_ids"] = {+ scorer_name: "origin-trace",+ "first": "metric-trace",+ "third": "metric-trace",+ }+ return score_output++ async def async_score(output: dict[str, Any], metadata: dict[str, Any]) -> object:+ return score(output, metadata)++ class _CallableScorer(Scorer):+ def _name(self) -> str:+ return "score"++ def _run_eval_sync(self, output: Any, expected: Any = None, **kwargs: Any) -> Any:+ return score(output, kwargs["metadata"])++ scorer = {"sync": score, "async": async_score, "instance": _CallableScorer(), "class": _CallableScorer}[scorer_form]+ expected_scores = {scorer_name if name == "score" else name: value for name, value in expected_scores.items()}+ expected_trace_ids = {scorer_name if name == "score" else name: value for name, value in expected_trace_ids.items()}+ result = _run(+ engine,+ _spec(task, [CaseSpec(input={"name": "a"})], scorers=[scorer], record_scorer_results=record_scorer_results),+ )++ assert calls == 1+ assert result.results[0].scores == expected_scores+ assert {name: outcome.value for name, outcome in result.results[0].scorer_results.items()} == (+ expected_scores if record_scorer_results else {}+ )+ assert {name: outcome.evaluator_trace_id for name, outcome in result.results[0].scorer_results.items()} == (+ expected_trace_ids if record_scorer_results else {}+ )++def test_engine_does_not_throttle_concurrency(engine: BraintrustEngine) -> None:active = 0peak = 0diff --git a/products/posthog_ai/eval_harness/test/test_offline_delivery.py b/products/posthog_ai/eval_harness/test/test_offline_delivery.pynew file mode 100644index 000000000000..db7746051d82--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_offline_delivery.py@@ -0,0 +1,349 @@+from __future__ import annotations++import json+import asyncio+import threading+from collections.abc import Callable, Coroutine+from dataclasses import replace+from functools import partial+from typing import Literal+from uuid import UUID++import pytest++import httpx+from posthoganalytics.ai.evaluations import EvaluationItem, EvaluationResult+from pydantic import SecretStr++from products.posthog_ai.eval_harness.engines.types import EvalSummary+from products.posthog_ai.eval_harness.harness import reporting+from products.posthog_ai.eval_harness.harness.offline_delivery import OfflineEvalDelivery+from products.posthog_ai.eval_harness.harness.reporting import ProgressReporter+from products.posthog_ai.eval_harness.offline_results import (+ OfflineEvalPublisher,+ OfflineEvalSettings,+ OfflineEvalSuite,+ OfflineEvalUpload,+)+from products.posthog_ai.eval_harness.test.offline_api import OfflineServer++STARTED_AT = "2026-01-01T00:00:00+00:00"++[email protected]("status", ["disabled: missing configuration", "upload queued", "upload failed", "uploaded"])+async def test_offline_status_links_only_uploaded_results(capsys: pytest.CaptureFixture[str], status: str) -> None:+ reporter = ProgressReporter(total_suites=1)+ await reporter.record_summary(+ "example", EvalSummary(engine_name="braintrust", experiment_name="example", scores={})+ )+ offline_url = "https://posthog.example.com/project/123/ai-evals/evaluations/offline/experiments/example"+ await reporter.record_posthog_offline_result("example", status, url=offline_url if status == "uploaded" else None)+ capsys.readouterr()++ reporter.print_final_summary([], exit_code=0, fail_under=None, duration_seconds=0)++ output = capsys.readouterr().out+ if status == "uploaded":+ assert f"PostHog: {offline_url}" in output+ assert "PostHog offline:" not in output+ else:+ assert "PostHog:" not in output+ assert f"PostHog offline: {status}" in output+++def _upload(index: int) -> OfflineEvalUpload:+ return OfflineEvalUpload(+ host="https://posthog.example.com",+ project_id=123,+ experiment_name=f"experiment-{index}",+ experiment={+ "id": str(UUID(int=index)),+ "started_at": STARTED_AT,+ "expected_item_count": 0,+ "expected_result_count": 0,+ },+ results=(),+ )+++def _receipt(request: httpx.Request, servers: dict[str, OfflineServer]) -> httpx.Response:+ action = request.url.path.endswith(("/upload/", "/complete/", "/fail/"))+ experiment_id = request.url.path.split("/")[-3] if action else json.loads(request.content)["id"]+ return servers.setdefault(experiment_id, OfflineServer()).respond(request)+++def _publisher(+ monkeypatch: pytest.MonkeyPatch, respond: Callable[[httpx.Request], Coroutine[None, None, httpx.Response]]+) -> OfflineEvalPublisher:+ monkeypatch.setattr(httpx, "AsyncClient", partial(httpx.AsyncClient, transport=httpx.MockTransport(respond)))+ return OfflineEvalPublisher(+ OfflineEvalSettings(+ host="https://posthog.example.com",+ project_id=123,+ api_key=SecretStr("test-only-token"),+ scorer_versions={},+ max_retries=0,+ ),+ OfflineEvalSuite(key="example/suite", project_id=123, scorer_kinds={}, scorer_versions={}),+ )++[email protected]("pause", [False, True])+async def test_delivery_limits_queued_work_without_waiting_for_uploads(+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], pause: bool+) -> None:+ started = asyncio.Event()+ release = asyncio.Event()+ second_started = asyncio.Event()+ release_second = asyncio.Event()+ requests: list[httpx.Request] = []+ servers: dict[str, OfflineServer] = {}++ async def respond(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ if len(requests) == 1:+ started.set()+ await release.wait()+ elif pause and len(requests) == 3:+ second_started.set()+ await release_second.wait()+ return _receipt(request, servers)++ publisher = _publisher(monkeypatch, respond)+ uploads = [_upload(index) for index in (1, 2, 3)]+ delivery = OfflineEvalDelivery(ProgressReporter(total_suites=3), max_concurrency=1, max_pending=2)++ assert delivery.submit(publisher, uploads[0])+ assert delivery.submit(publisher, uploads[1])+ assert not delivery.submit(publisher, uploads[2])+ await asyncio.wait_for(started.wait(), timeout=5)+ assert len(requests) == 1+ release.set()+ if pause:+ await asyncio.wait_for(second_started.wait(), timeout=5)+ await delivery.pause()+ assert not delivery.submit(publisher, uploads[2])+ release_second.set()+ await delivery.drain()++ assert [request.url.path.endswith("/complete/") for request in requests] == (+ [False, True, False, False, True] if pause else [False, True, False, True]+ )+ if pause:+ assert requests[2].content == requests[3].content+ assert not delivery.submit(publisher, uploads[2])+ output = capsys.readouterr().out+ assert output.count("POSTHOG OFFLINE") == 2+ assert "experiment-1 https://posthog.example.com/project/123/" in output+ assert "experiment-2 https://posthog.example.com/project/123/" in output++[email protected]("http_status", [200, 403])[email protected]("shutdown", ["pause", "deadline", "interrupt"])+async def test_finished_uploads_are_not_retried_or_marked_interrupted_while_reporting(+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+ http_status: int,+ shutdown: Literal["pause", "deadline", "interrupt"],+) -> None:+ report_started = asyncio.Event()+ report_finished = asyncio.Event()+ release_report = threading.Event()+ loop = asyncio.get_running_loop()+ emit = reporting._emit+ requests: list[httpx.Request] = []+ servers: dict[str, OfflineServer] = {}++ def blocked_emit(text: str) -> None:+ loop.call_soon_threadsafe(report_started.set)+ if not release_report.wait(timeout=5):+ raise TimeoutError("Report was not released")+ emit(text)+ loop.call_soon_threadsafe(report_finished.set)++ async def respond(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ return _receipt(request, servers) if http_status == 200 else httpx.Response(http_status, json={})++ monkeypatch.setattr(reporting, "_emit", blocked_emit)+ publisher = _publisher(monkeypatch, respond)+ delivery = OfflineEvalDelivery(ProgressReporter(total_suites=1))+ assert delivery.submit(publisher, _upload(1))+ try:+ await asyncio.wait_for(report_started.wait(), timeout=5)+ if shutdown == "pause":+ await asyncio.wait_for(delivery.pause(), timeout=5)+ elif shutdown == "deadline":+ await asyncio.wait_for(delivery.drain(timeout=0), timeout=5)+ else:+ await asyncio.wait_for(delivery.cancel(), timeout=5)+ finally:+ release_report.set()+ await delivery.drain()+ await asyncio.wait_for(report_finished.wait(), timeout=5)++ assert len(requests) == (2 if http_status == 200 else 1)+ output = capsys.readouterr().out+ assert output.count("POSTHOG OFFLINE") == 1+ assert "upload interrupted" not in output+ assert "shutdown deadline exceeded" not in output+ if http_status == 200:+ assert "experiment-1 https://posthog.example.com/project/123/" in output+ else:+ assert "upload failed:" in output+ assert "Results were not saved for retry." in output+ assert "403" in output++[email protected]("shutdown", ["deadline", "interrupt", "before_start", "paused"])+async def test_shutdown_cancels_active_and_waiting_uploads_and_reports_unsaved_results(+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+ shutdown: Literal["deadline", "interrupt", "before_start", "paused"],+) -> None:+ started = asyncio.Event()+ cancelled = asyncio.Event()+ blocked = asyncio.Event()+ requests: list[httpx.Request] = []+ servers: dict[str, OfflineServer] = {}++ async def respond(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ started.set()+ try:+ await blocked.wait()+ except asyncio.CancelledError:+ cancelled.set()+ raise+ return _receipt(request, servers)++ publisher = _publisher(monkeypatch, respond)+ uploads = [_upload(index) for index in (1, 2)]+ delivery = OfflineEvalDelivery(ProgressReporter(total_suites=2), max_concurrency=1)+ for upload in uploads:+ assert delivery.submit(publisher, upload)++ if shutdown != "before_start":+ await asyncio.wait_for(started.wait(), timeout=5)+ if shutdown == "paused":+ await delivery.pause()+ assert capsys.readouterr().out == ""+ if shutdown == "deadline":+ await delivery.drain(timeout=0)+ else:+ await delivery.cancel()++ assert len(requests) == (0 if shutdown == "before_start" else 1)+ assert cancelled.is_set() is (shutdown != "before_start")+ output = capsys.readouterr().out+ assert output.count("upload failed:") == 2+ assert output.count("Results were not saved for retry.") == 2+ for upload in uploads:+ assert f"POSTHOG OFFLINE {upload.experiment_name}" in output+ await delivery.drain()+ assert capsys.readouterr().out == ""+++async def test_default_delivery_budget_allows_request_timeout_retries_through_completion(+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+) -> None:+ clock_offset = 0.0+ loop = asyncio.get_running_loop()+ original_time = loop.time+ monkeypatch.setattr(loop, "time", lambda: original_time() + clock_offset)+ monkeypatch.setattr("posthoganalytics.ai.evaluations._transport.random.uniform", lambda *_: 1.2)+ attempts: dict[str, int] = {}+ server = OfflineServer()++ async def advance(seconds: float) -> None:+ nonlocal clock_offset+ clock_offset += seconds+ resumed = asyncio.Event()+ loop.call_later(0, resumed.set)+ await resumed.wait()++ async def respond(request: httpx.Request) -> httpx.Response:+ path = request.url.path+ attempts[path] = attempts.get(path, 0) + 1+ await advance(settings.request_timeout)+ if attempts[path] <= settings.max_retries:+ raise httpx.ReadTimeout("Synthetic timeout", request=request)+ return server.respond(request)++ monkeypatch.setattr("posthoganalytics.ai.evaluations._transport.asyncio.sleep", advance)+ monkeypatch.setattr(httpx, "AsyncClient", partial(httpx.AsyncClient, transport=httpx.MockTransport(respond)))+ settings = OfflineEvalSettings(+ host="https://posthog.example.com", project_id=123, api_key=SecretStr("test"), scorer_versions={}+ )+ publisher = OfflineEvalPublisher(+ settings, OfflineEvalSuite(key="test/suite", project_id=123, scorer_kinds={}, scorer_versions={})+ )+ upload = replace(+ _upload(1),+ experiment={"id": str(UUID(int=1)), "started_at": STARTED_AT},+ results=(EvaluationResult(item=EvaluationItem(id=UUID(int=2)), scorer_version_id=UUID(int=3), value=1),),+ )+ delivery = OfflineEvalDelivery(ProgressReporter(total_suites=1))+ assert delivery.submit(publisher, upload)+ await delivery.drain()++ assert server.status == "completed"+ assert len(server.results) == 1+ assert len(attempts) == 3+ assert all(count == settings.max_retries + 1 for count in attempts.values())+ assert "upload failed:" not in capsys.readouterr().out+++async def test_upload_deadline_reports_unsaved_results_before_network(+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+) -> None:+ requests: list[httpx.Request] = []+ servers: dict[str, OfflineServer] = {}++ async def respond(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ return _receipt(request, servers)++ publisher = _publisher(monkeypatch, respond)+ delivery = OfflineEvalDelivery(ProgressReporter(total_suites=1), upload_timeout=0)+ assert delivery.submit(publisher, _upload(1))+ await delivery.drain(timeout=5)++ assert requests == []+ output = capsys.readouterr().out+ assert "upload failed: upload deadline exceeded" in output+ assert "Results were not saved for retry." in output+++async def test_rejected_delivery_does_not_prevent_other_uploads(+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+) -> None:+ requests: list[httpx.Request] = []+ servers: dict[str, OfflineServer] = {}++ async def respond(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ if not request.url.path.endswith("/complete/") and json.loads(request.content)["name"] == "experiment-1":+ return httpx.Response(403, json={"detail": "Access denied"})+ return _receipt(request, servers)++ publisher = _publisher(monkeypatch, respond)+ uploads = [_upload(index) for index in (1, 2)]+ delivery = OfflineEvalDelivery(ProgressReporter(total_suites=2), max_concurrency=1)+ for upload in uploads:+ assert delivery.submit(publisher, upload)+ await delivery.drain()++ assert sum(request.url.path.endswith("/complete/") for request in requests) == 1+ output = capsys.readouterr().out+ assert "POSTHOG OFFLINE experiment-1 upload failed:" in output+ assert "Results were not saved for retry." in output+ assert "POSTHOG OFFLINE experiment-2 https://posthog.example.com/project/123/" in outputdiff --git a/products/posthog_ai/eval_harness/test/test_offline_delivery_lifecycle.py b/products/posthog_ai/eval_harness/test/test_offline_delivery_lifecycle.pynew file mode 100644index 000000000000..bf8e7958d855--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_offline_delivery_lifecycle.py@@ -0,0 +1,124 @@+from __future__ import annotations++import asyncio+import threading+from contextlib import AsyncExitStack+from functools import partial+from typing import Literal+from uuid import UUID++import pytest+from unittest.mock import MagicMock++import httpx+from pydantic import SecretStr++from products.posthog_ai.eval_harness.harness import lifecycle+from products.posthog_ai.eval_harness.harness.cli import parse_args+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.harness.discovery import EvalSuite+from products.posthog_ai.eval_harness.harness.requirements import Infra, SuiteKind+from products.posthog_ai.eval_harness.offline_results import (+ OfflineEvalPublisher,+ OfflineEvalSettings,+ OfflineEvalSuite,+ OfflineEvalUpload,+)+from products.posthog_ai.eval_harness.test.offline_api import OfflineServer++[email protected]("interrupted", [False, True])[email protected]("teardown_phase", ["async", "sync"])+def test_harness_tears_down_infrastructure_before_draining_uploads(+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+ interrupted: bool,+ teardown_phase: Literal["async", "sync"],+) -> None:+ monkeypatch.setenv("BRAINTRUST_API_KEY", "test-only-key")+ monkeypatch.setenv("LLM_GATEWAY_ANTHROPIC_API_KEY", "test-only-key")+ monkeypatch.delenv("EXPORT_EVAL_RESULTS", raising=False)+ started = asyncio.Event()+ torn_down = asyncio.Event()+ clock_offset = 0.0+ cleanup_thread_id = threading.get_ident()+ server = OfflineServer()+ upload = OfflineEvalUpload(+ host="https://posthog.example.com",+ project_id=123,+ experiment_name="test-experiment",+ experiment={"id": str(UUID(int=1)), "started_at": "2026-01-01T00:00:00Z"},+ results=(),+ )+ publisher = OfflineEvalPublisher(+ OfflineEvalSettings(+ host="https://posthog.example.com", project_id=123, api_key=SecretStr("test"), scorer_versions={}+ ),+ OfflineEvalSuite(key="test/suite", project_id=123, scorer_kinds={}, scorer_versions={}),+ )++ async def respond(request: httpx.Request) -> httpx.Response:+ nonlocal clock_offset+ started.set()+ await torn_down.wait()+ if not server.requests:+ clock_offset += 45+ resumed = asyncio.Event()+ asyncio.get_running_loop().call_later(0, resumed.set)+ await resumed.wait()+ return server.respond(request)++ monkeypatch.setattr(httpx, "AsyncClient", partial(httpx.AsyncClient, transport=httpx.MockTransport(respond)))++ async def suite(ctx: EvalContext) -> None:+ loop = asyncio.get_running_loop()+ original_time = loop.time+ monkeypatch.setattr(loop, "time", lambda: original_time() + clock_offset)+ assert ctx.offline_delivery is not None+ assert ctx.offline_delivery.submit(publisher, upload)+ await asyncio.wait_for(started.wait(), 5)+ assert not torn_down.is_set()++ monkeypatch.setattr(+ lifecycle,+ "discover_suites",+ lambda _: [+ EvalSuite(domain="test", module_name="eval_test", fn_name="eval_test", fn=suite, kind=SuiteKind.ONE_SHOT)+ ],+ )+ monkeypatch.setattr(lifecycle, "ensure_personhog_binaries", lambda: None)+ harness = lifecycle.SandboxedEvalHarness(parse_args([]))++ def teardown() -> None:+ nonlocal clock_offset+ assert threading.get_ident() == cleanup_thread_id+ clock_offset += 120+ torn_down.set()+ if interrupted:+ raise KeyboardInterrupt++ def bootstrap(required: frozenset[Infra], reporter: lifecycle.ProgressReporter) -> None:+ harness._demo_data = MagicMock()+ if teardown_phase == "sync":+ harness._stack.callback(teardown)++ def async_stack() -> AsyncExitStack:+ stack = AsyncExitStack()+ if teardown_phase == "async":+ stack.callback(teardown)+ return stack++ monkeypatch.setattr(harness, "_bootstrap", bootstrap)+ monkeypatch.setattr(lifecycle, "AsyncExitStack", async_stack)++ assert harness.run() == (130 if interrupted else 0)+ assert torn_down.is_set()+ output = capsys.readouterr().out+ if interrupted:+ assert server.requests == []+ assert output.count("upload failed: upload interrupted") == 1+ assert "Results were not saved for retry." in output+ else:+ assert server.requests[-1].url.path.endswith("/complete/")+ assert "POSTHOG OFFLINE test-experiment https://posthog.example.com/project/123/" in output+ assert "upload failed:" not in outputdiff --git a/products/posthog_ai/eval_harness/test/test_offline_results.py b/products/posthog_ai/eval_harness/test/test_offline_results.pynew file mode 100644index 000000000000..83436608c9e5--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_offline_results.py@@ -0,0 +1,659 @@+from __future__ import annotations++import json+import asyncio+from dataclasses import replace+from datetime import UTC, datetime+from functools import partial+from uuid import UUID++import pytest+from unittest.mock import AsyncMock, patch++import httpx+from parameterized import parameterized+from posthoganalytics.ai.evaluations import EvaluationItem+from pydantic import SecretStr++from products.posthog_ai.eval_harness.engines.types import CaseResult, EvalSummary, ExperimentResult, ScorerResult+from products.posthog_ai.eval_harness.offline_results import (+ OfflineEvalPublisher,+ OfflineEvalSettings,+ OfflineEvalSuite,+ OfflineEvalUpload,+ OfflineUploadError,+)+from products.posthog_ai.eval_harness.test.offline_api import OfflineServer++EXPERIMENT_ID = "00000000-0000-4000-8000-000000000001"+SCORER_VERSIONS = {+ "boolean_metric": UUID("00000000-0000-4000-8000-000000000002"),+ "numeric_metric": UUID("00000000-0000-4000-8000-000000000003"),+}+SUITE = OfflineEvalSuite(+ key="sql/test",+ project_id=123,+ scorer_kinds={"boolean_metric": "boolean", "numeric_metric": "numeric"},+ scorer_versions=SCORER_VERSIONS,+)+STARTED_AT = datetime(2026, 1, 1, tzinfo=UTC)+++def _publisher(*, link_traces: bool = False) -> OfflineEvalPublisher:+ return OfflineEvalPublisher(+ OfflineEvalSettings(project_id=123, api_key=SecretStr("test-only-token"), scorer_versions=SCORER_VERSIONS),+ SUITE,+ application_trace_ids_enabled=link_traces,+ )+++def _case(name: str = "query") -> CaseResult:+ return CaseResult(+ input={"name": name, "prompt": "Count example events"}, output={}, scores=dict.fromkeys(SCORER_VERSIONS, 1.0)+ )+++def _prepare(+ publisher: OfflineEvalPublisher, cases: list[CaseResult], metadata: dict[str, object] | None = None+) -> OfflineEvalUpload:+ return publisher.prepare(+ experiment_id=EXPERIMENT_ID,+ experiment_name="sql-test",+ started_at=STARTED_AT,+ result=ExperimentResult(+ summary=EvalSummary(+ engine_name="braintrust",+ experiment_name="sql-test",+ scores={},+ experiment_url="https://braintrust.example.com/experiment/test",+ ),+ results=cases,+ ),+ metadata={"agent_model": "test-model", "git_sha": "captured-revision", **(metadata or {})},+ )+++def _items(upload: OfflineEvalUpload) -> list[EvaluationItem]:+ items: dict[str, EvaluationItem] = {}+ for result in upload.results:+ assert isinstance(result.item, EvaluationItem)+ items[result.item_id] = result.item+ return list(items.values())+++ [+ ("zero", {"boolean_metric": 0.0, "numeric_metric": 0.0}, None, "ok", None),+ ("one", {"boolean_metric": 1.0, "numeric_metric": 1.0}, None, "ok", None),+ ("skipped", {"boolean_metric": None, "numeric_metric": None}, None, "skipped", None),+ ("missing", {}, None, "error", "missing_score"),+ ("task_error", {"boolean_metric": 1.0, "numeric_metric": 1.0}, "Agent failed", "error", "task_error"),+ (+ "not_finite",+ {"boolean_metric": float("nan"), "numeric_metric": float("inf")},+ None,+ "error",+ "invalid_score",+ ),+ ]+)+def test_prepare_preserves_score_types_and_distinguishes_missing_from_skipped(+ _name: str, scores: dict[str, float | None], error: str | None, status: str, error_code: str | None+) -> None:+ case = _case()+ case.scores = scores+ case.error = error+ case.metadata = {"scorer_errors": {"boolean_metric": "Judge failed"}}++ results = [result.to_dict() for result in _prepare(_publisher(), [case]).results]++ assert [result["scorer_version_id"] for result in results] == [str(version) for version in SCORER_VERSIONS.values()]+ assert [result["status"] for result in results] == [status, status]+ if status == "ok":+ assert results[0]["value"] is bool(scores["boolean_metric"])+ assert type(results[1]["value"]) is float+ assert results[1]["value"] == scores["numeric_metric"]+ else:+ assert all("value" not in result for result in results)+ if error_code is not None:+ assert [result["error_code"] for result in results] == [error_code, error_code]+ if error_code == "missing_score":+ assert results[0]["payload"]["error_message"] == "Judge failed"+++def test_prepare_preserves_successful_scores_when_another_scorer_fails() -> None:+ case = _case()+ case.error = "Scorer errors: boolean_metric"+ case.error_kind = "scorer"+ case.scorer_results = {+ "boolean_metric": ScorerResult(status="error", error_code="scorer_error", error_message="Judge failed")+ }++ results = [result.to_dict() for result in _prepare(_publisher(), [case]).results]++ assert results[0]["status"] == "error"+ assert results[0]["error_code"] == "scorer_error"+ assert results[1]["status"] == "ok"+ assert results[1]["value"] == 1.0+++def test_prepare_assigns_stable_trial_ids_and_uses_captured_revision() -> None:+ publisher = _publisher()+ cases = [_case("query-a"), _case("query-b"), _case("query-a")]+ cases[0].trial_index = 1+ cases[2].trial_index = 0+ cases[1].scores = {"boolean_metric": None}++ upload = _prepare(publisher, cases)+ reordered = _prepare(publisher, list(reversed(cases)))+ items = [item.to_dict() for item in _items(upload)]++ assert {item.id for item in _items(upload)} == {item.id for item in _items(reordered)}+ assert [(item["case_key"], item["trial"]) for item in items] == [+ ("query-a", "1"),+ ("query-b", "0"),+ ("query-a", "0"),+ ]+ assert upload.experiment["expected_item_count"] == 3+ assert upload.experiment["expected_result_count"] == 6+ assert upload.experiment["application_version"] == "captured-revision"+ assert upload.experiment["dataset_revision_identifier"] == "captured-revision"+ assert items[0]["payload"]["metadata"]["braintrust_url"] == "https://braintrust.example.com/experiment/test"+++def test_prepare_omits_raw_logs_and_oversized_fields_without_mutating_results() -> None:+ case = _case()+ original_output = {"raw_log": "local trace", "tool_result": "x" * (1100 * 1024), "answer": "There are 3 events"}+ case.output = original_output.copy()+ case.expected = {"large_fixture": "x" * (1100 * 1024)}+ case.metadata["not_json"] = object()++ payload = _items(_prepare(_publisher(), [case]))[0].to_dict()["payload"]++ assert "output" not in payload+ assert "expected_output" not in payload+ assert set(payload["metadata"]["omitted_fields"]) == {+ "output.raw_log",+ "output",+ "expected_output",+ "metadata",+ }+ assert case.output == original_output+++ [+ ("null_output_key", {"invalid\x00key": "value"}, {}, "output"),+ ("null_metadata_key", {}, {"invalid\x00key": "value"}, "metadata"),+ ("surrogate_metadata_key", {}, {"invalid\ud800key": "value"}, "metadata"),+ (+ "many_output_fields",+ {f"field-{index}-" + "k" * 512: "x" * 1024 for index in range(2000)},+ {},+ "output",+ ),+ (+ "aggregate_metadata",+ {"details": "x" * (240 * 1024)},+ {f"metadata-{index}": "x" * (60 * 1024) for index in range(8)},+ "metadata",+ ),+ ]+)+def test_prepare_bounds_payload_details_without_losing_scores(+ _name: str, output: dict[str, object], metadata: dict[str, object], omitted_field: str+) -> None:+ case = _case()+ case.input["prompt"] = "i" * (240 * 1024)+ case.expected = "e" * (240 * 1024)+ original_output = {**output, "answer": "There are 3 events"}+ case.output = original_output.copy()++ upload = _prepare(_publisher(), [case], metadata)+ payload = _items(upload)[0].to_dict()["payload"]+ omitted = payload["metadata"]["omitted_fields"]++ if omitted_field == "output":+ assert "output" not in payload+ else:+ assert payload["output"] == original_output+ assert payload["input"] == case.input+ assert payload["expected_output"] == case.expected+ assert all(result.to_dict()["status"] == "ok" for result in upload.results)+ assert omitted == [omitted_field]+ assert len(json.dumps(payload, ensure_ascii=False).encode("utf-8")) < 1024 * 1024+ assert case.output == original_output++[email protected]([("linked", True), ("unlinked", False)])+def test_prepare_preserves_rich_results_and_dataset_references(_name: str, link_traces: bool) -> None:+ publisher = _publisher(link_traces=link_traces)+ publisher.suite = OfflineEvalSuite(+ key="sql/rich",+ project_id=123,+ scorer_kinds={"boolean_metric": "categorical", "numeric_metric": "numeric"},+ scorer_versions=SCORER_VERSIONS,+ experiment_options={+ "prompt_version": "prompt-2",+ "run_source": "scheduled",+ },+ )+ case = _case()+ case.metadata.update(+ trace_id="application-trace", dataset_item_identifier="case-1", dataset_item_version_identifier="v2"+ )+ case.scorer_results = {+ "boolean_metric": ScorerResult(+ status="ok",+ value=["correct"],+ reasoning="Matches expected answer",+ metadata={"confidence": 0.9},+ evaluator_trace_id="judge-trace",+ evaluated_at=STARTED_AT,+ ),+ "numeric_metric": ScorerResult(status="ok", value=35.0),+ }+ upload = _prepare(publisher, [case])+ item = _items(upload)[0].to_dict()+ outcome = upload.results[0].to_dict()+ assert item.get("application_trace_id") == ("application-trace" if link_traces else None)+ assert item["dataset_item_identifier"] == "case-1"+ assert item["dataset_item_version_identifier"] == "v2"+ assert "dataset_item_version_id" not in item+ assert outcome["value"] == ["correct"]+ assert outcome["payload"]["reasoning"] == "Matches expected answer"+ assert outcome["payload"]["metadata"] == {"confidence": 0.9}+ assert outcome.get("evaluator_trace_id") == ("judge-trace" if link_traces else None)+ assert outcome["evaluated_at"] == STARTED_AT.isoformat()+ assert upload.results[1].to_dict()["value"] == 35.0+ assert upload.experiment["dataset_source"] == "repository"+ assert upload.experiment["dataset_identifier"] == "sql/rich"+ assert upload.experiment["dataset_revision_identifier"] == "captured-revision"+ assert upload.experiment["prompt_version"] == "prompt-2"+ assert upload.experiment["run_source"] == "scheduled"++ case.scorer_results["numeric_metric"] = ScorerResult(status="not_applicable", reasoning="No applicable operation")+ assert _prepare(publisher, [case]).results[1].to_dict()["status"] == "not_applicable"+++def test_prepare_rejects_hosted_dataset_configuration() -> None:+ publisher = _publisher()+ publisher.suite = replace(SUITE, experiment_options={"dataset_revision_id": EXPERIMENT_ID})++ with pytest.raises(OfflineUploadError, match="Hosted datasets are not supported"):+ _prepare(publisher, [_case()])+++def test_prepare_rejects_empty_scorer_enrollment() -> None:+ publisher = _publisher()+ publisher.suite = replace(SUITE, scorer_kinds={})++ with pytest.raises(OfflineUploadError, match="must enroll at least one scorer"):+ _prepare(publisher, [_case()])+++ [+ (+ "oversized_metadata",+ ScorerResult(status="ok", value=0.75, metadata={"details": "x" * (256 * 1024)}),+ "metadata",+ ),+ ("unsupported_metadata", ScorerResult(status="ok", value=0.75, metadata={"details": object()}), "metadata"),+ ("unsupported_reasoning", ScorerResult(status="ok", value=0.75, reasoning="\ud800"), "reasoning"),+ ("oversized_reasoning", ScorerResult(status="ok", value=0.75, reasoning="x" * (256 * 1024)), "reasoning"),+ (+ "invalid_trace",+ ScorerResult(status="ok", value=0.75, evaluator_trace_id="invalid\x00trace"),+ "evaluator_trace_id",+ ),+ (+ "naive_time",+ ScorerResult(status="ok", value=0.75, evaluated_at=STARTED_AT.replace(tzinfo=None)),+ "evaluated_at",+ ),+ (+ "diagnostic_room",+ ScorerResult(status="ok", value=0.75, reasoning="x" * (256 * 1024 - 256), metadata={"details": object()}),+ "metadata",+ ),+ ]+)+def test_prepare_preserves_valid_scores_when_optional_details_cannot_be_uploaded(+ _name: str, scorer_result: ScorerResult, omitted_field: str+) -> None:+ case = _case()+ case.scorer_results["numeric_metric"] = scorer_result++ result = _prepare(_publisher(link_traces=True), [case]).results[1].to_dict()++ assert result["status"] == "ok"+ assert result["value"] == 0.75+ assert "error_code" not in result+ assert result["payload"]["metadata"]["omitted_fields"] == [omitted_field]+ if scorer_result.reasoning is not None and omitted_field != "reasoning":+ assert result["payload"]["reasoning"] == scorer_result.reasoning++[email protected]([("rate_limit", 429), ("server_error", 503), ("timeout", 408), ("network_error", None)])+def test_publish_retries_identical_batches_and_completes_after_all_acknowledgments(+ _name: str, failure_status: int | None+) -> None:+ publisher = _publisher()+ upload = _prepare(publisher, [_case(f"query-{index}") for index in range(501)])+ server = OfflineServer()+ attempts: list[httpx.Request] = []++ def respond(request: httpx.Request) -> httpx.Response:+ attempts.append(request)+ if len(attempts) == 2:+ if failure_status is None:+ raise httpx.ConnectError("connection lost", request=request)+ return httpx.Response(failure_status, headers={"Retry-After": "0"})+ return server.respond(request)++ with (+ patch("httpx.AsyncClient", new=partial(httpx.AsyncClient, transport=httpx.MockTransport(respond))),+ patch("posthoganalytics.ai.evaluations._transport.asyncio.sleep", new_callable=AsyncMock),+ ):+ url = asyncio.run(publisher.publish(upload))++ assert len(attempts) == 5+ assert attempts[1].content == attempts[2].content+ assert attempts[2].content != attempts[3].content+ assert attempts[-1].url.path.endswith("/complete/")+ assert attempts[0].headers["Authorization"] == "Bearer test-only-token"+ assert len(server.items) == 501+ assert len(server.results) == 1002+ assert url.endswith(f"/ai-evals/evaluations/offline/experiments/{EXPERIMENT_ID}")+++ [+ ("bad_request", 400),+ ("forbidden", 403),+ ("retry_exhausted", 503),+ ("invalid_ack", 200),+ ("long_retry_after", 429),+ ("unsafe_diagnostics", 400, False),+ ]+)+def test_publish_does_not_complete_without_confirmed_persistence(+ _name: str, failure_status: int, safe_diagnostics: bool = True+) -> None:+ publisher = _publisher()+ upload = _prepare(publisher, [_case()])+ server = OfflineServer()+ attempts: list[httpx.Request] = []+ code = {+ 400: "invalid_input",+ 403: "permission_denied",+ 503: "unavailable",+ 429: "throttled",+ 200: "invalid_response",+ }[failure_status]+ private_detail = "do-not-log-example-evaluation-payload"+ retry_after = 45 if failure_status == 429 else 0++ def respond(request: httpx.Request) -> httpx.Response:+ attempts.append(request)+ if len(attempts) == 1 or request.url.path.endswith("/fail/"):+ return server.respond(request)+ return httpx.Response(+ failure_status,+ json={+ "code": code if safe_diagnostics else "invalid\n" + private_detail,+ "attr": "results.0.value" if safe_diagnostics else "results.0.value\n" + private_detail,+ "detail": private_detail,+ "errors": [{"code": "invalid_input", "attr": "results.0.value", "detail": private_detail}],+ },+ headers={"Retry-After": str(retry_after)},+ )++ with (+ patch("httpx.AsyncClient", new=partial(httpx.AsyncClient, transport=httpx.MockTransport(respond))),+ patch("posthoganalytics.ai.evaluations._transport.asyncio.sleep", new_callable=AsyncMock),+ pytest.raises(OfflineUploadError) as raised,+ ):+ asyncio.run(publisher.publish(upload))+ assert len(attempts) == (5 if failure_status == 503 else 3)+ assert all(request.url.path.endswith("/upload/") for request in attempts[1:-1])+ assert server.status == "failed"+ error = raised.value+ assert error.status == (None if failure_status == 200 else failure_status)+ assert error.code == (code if safe_diagnostics else None)+ assert error.attr == ("results.0.value" if safe_diagnostics and failure_status != 200 else None)+ assert error.persistence == ("unknown" if failure_status in (200, 503) else "rejected")+ assert error.retry_after == (None if failure_status == 200 else retry_after)+ assert error.acknowledged_item_count == error.acknowledged_result_count == error.completed_chunk_count == 0+ assert error.pending_result_count == 2+ assert error.failed_index == 0+ assert private_detail not in str(error)+ if failure_status == 403:+ assert "offline_evaluation_ingestion:write" in str(error)+ if failure_status == 429:+ assert "retry after 45s" in str(error)+++ ("failure_path", "cleanup_error"), [("complete", None), ("upload", "api"), ("upload", "timeout")]+)+async def test_publish_preserves_original_error_when_closing_a_failed_experiment(+ monkeypatch: pytest.MonkeyPatch, failure_path: str, cleanup_error: str | None+) -> None:+ publisher = _publisher()+ server = OfflineServer()+ paths: list[str] = []+ loop = asyncio.get_running_loop()+ original_time = loop.time+ clock_offset = 0.0+ monkeypatch.setattr(loop, "time", lambda: original_time() + clock_offset)++ async def respond(request: httpx.Request) -> httpx.Response:+ nonlocal clock_offset+ paths.append(request.url.path)+ if request.url.path.endswith("/fail/"):+ if cleanup_error == "api":+ return httpx.Response(403, json={"code": "permission_denied"})+ if cleanup_error == "timeout":+ clock_offset += 10+ await asyncio.Event().wait()+ if request.url.path.endswith(f"/{failure_path}/"):+ return httpx.Response(400, json={"code": "invalid_input"})+ return server.respond(request)++ monkeypatch.setattr(httpx, "AsyncClient", partial(httpx.AsyncClient, transport=httpx.MockTransport(respond)))+ with pytest.raises(OfflineUploadError) as raised:+ await publisher.publish(_prepare(publisher, [_case()]))++ assert raised.value.status == 400+ assert raised.value.code == "invalid_input"+ assert paths[-1].endswith("/fail/")+ assert server.status == ("failed" if cleanup_error is None else "uploading")++[email protected]("interrupted", [False, True])+def test_publish_preserves_partial_success_after_failure_or_interruption(interrupted: bool) -> None:+ publisher = _publisher()+ cases = [_case(f"query-{index}") for index in range(501)]+ cases[0].output = {"large_integer": 2**80}+ upload = _prepare(publisher, cases)+ server = OfflineServer()+ attempts: list[httpx.Request] = []+ reject = True++ def respond(request: httpx.Request) -> httpx.Response:+ attempts.append(request)+ if reject and request.url.path.endswith("/upload/") and server.results:+ if interrupted:+ raise asyncio.CancelledError+ return httpx.Response(400)+ return server.respond(request)++ with patch("httpx.AsyncClient", new=partial(httpx.AsyncClient, transport=httpx.MockTransport(respond))):+ with pytest.raises(asyncio.CancelledError if interrupted else OfflineUploadError) as raised:+ asyncio.run(publisher.publish(upload))+ assert len(server.results) == 1000+ if interrupted:+ assert server.status == "uploading"+ reject = False+ asyncio.run(publisher.publish(upload))+ assert len(server.results) == 1002+ assert len(server.items) == 501+ assert attempts[0].content == attempts[3].content+ assert attempts[1].content == attempts[4].content+ else:+ error = raised.value+ assert isinstance(error, OfflineUploadError)+ assert error.acknowledged_item_count == 500+ assert error.acknowledged_result_count == 1000+ assert error.completed_chunk_count == 1+ assert error.pending_result_count == 2+ assert error.failed_index == 1000+ assert "acknowledged 500 items and 1000 results" in str(error)+ assert "2 results await acknowledgment" in str(error)+ assert server.status == "failed"+ assert len(server.items) == 500+ first_item = json.loads(attempts[1].content)["items"][0]+ assert first_item["payload"]["output"]["large_integer"] == 2**80++[email protected]([("project", "https://us.posthog.com", 456), ("host", "https://eu.posthog.com", 123)])+def test_publish_refuses_a_different_destination(_name: str, host: str, project_id: int) -> None:+ publisher = _publisher()+ upload = replace(_prepare(publisher, [_case()]), host=host, project_id=project_id)+ server = OfflineServer()+ with (+ patch("httpx.AsyncClient", new=partial(httpx.AsyncClient, transport=httpx.MockTransport(server.respond))),+ pytest.raises(OfflineUploadError, match="destination differs"),+ ):+ asyncio.run(publisher.publish(upload))+ assert server.requests == []+++ [+ ("us_ingestion", "https://us.i.posthog.com", "https://us.posthog.com"),+ ("eu_ingestion", "https://eu.i.posthog.com/", "https://eu.posthog.com"),+ ("legacy_app", "https://app.posthog.com", "https://us.posthog.com"),+ ("default_port", " https://US.I.POSTHOG.COM:443/ ", "https://us.posthog.com"),+ ("app", "https://us.posthog.com", "https://us.posthog.com"),+ ("custom", "https://posthog.example.com:8443", "https://posthog.example.com:8443"),+ ("custom_cloud_port", "https://us.i.posthog.com:8443", "https://us.i.posthog.com:8443"),+ ("ipv6", "https://[::1]:8443", "https://[::1]:8443"),+ ]+)+def test_publish_uses_the_same_origin_for_requests_and_result_links(_name: str, host: str, origin: str) -> None:+ environment = {+ "POSTHOG_OFFLINE_EVAL_API_KEY": "test-only-token",+ "POSTHOG_OFFLINE_EVAL_HOST": host,+ }+ with patch.dict("os.environ", environment, clear=True):+ settings = OfflineEvalSettings.from_env(SUITE)+ assert settings is not None+ assert settings.host == origin+ publisher = OfflineEvalPublisher(settings, SUITE)+ upload = _prepare(publisher, [_case()])+ server = OfflineServer()++ with patch("httpx.AsyncClient", new=partial(httpx.AsyncClient, transport=httpx.MockTransport(server.respond))):+ url = asyncio.run(publisher.publish(upload))++ assert all(str(request.url).startswith(f"{origin}/api/") for request in server.requests)+ assert url == f"{origin}/project/123/ai-evals/evaluations/offline/experiments/{EXPERIMENT_ID}"+++def test_settings_use_each_suite_destination_with_only_an_api_key() -> None:+ environment = {"POSTHOG_OFFLINE_EVAL_API_KEY": "test-only-token"}+ with patch.dict("os.environ", environment, clear=True):+ for project_id, (metric, version) in enumerate(SCORER_VERSIONS.items(), start=123):+ suite = OfflineEvalSuite(+ key=metric,+ project_id=project_id,+ scorer_kinds={metric: "numeric"},+ scorer_versions={metric: version},+ )+ settings = OfflineEvalSettings.from_env(suite)+ assert settings is not None+ upload = _prepare(OfflineEvalPublisher(settings, suite), [_case()])+ assert upload.project_id == project_id+ assert [result.scorer_version_id for result in upload.results] == [str(version)]+++ [+ ("invalid_project", replace(SUITE, project_id=0)),+ (+ "missing_metric",+ replace(SUITE, scorer_versions={"boolean_metric": SCORER_VERSIONS["boolean_metric"]}),+ ),+ (+ "duplicate_versions",+ replace(SUITE, scorer_versions=dict.fromkeys(SCORER_VERSIONS, SCORER_VERSIONS["boolean_metric"])),+ ),+ ]+)+def test_settings_reject_invalid_suite_configuration(_name: str, suite: OfflineEvalSuite) -> None:+ with (+ patch.dict("os.environ", {"POSTHOG_OFFLINE_EVAL_API_KEY": "test-only-token"}, clear=True),+ pytest.raises(OfflineUploadError),+ ):+ OfflineEvalSettings.from_env(suite)+++ [+ ("blank_key", {"POSTHOG_OFFLINE_EVAL_API_KEY": " "}),+ ("key_newline", {"POSTHOG_OFFLINE_EVAL_API_KEY": "test-only-token\n"}),+ ("key_internal_space", {"POSTHOG_OFFLINE_EVAL_API_KEY": "test-only token"}),+ ("key_leading_tab", {"POSTHOG_OFFLINE_EVAL_API_KEY": "\ttest-only-token"}),+ ("insecure_host", {"POSTHOG_OFFLINE_EVAL_HOST": "http://posthog.example.com"}),+ ("malformed_host", {"POSTHOG_OFFLINE_EVAL_HOST": "https://["}),+ ("invalid_port", {"POSTHOG_OFFLINE_EVAL_HOST": "https://posthog.example.com:invalid"}),+ ("host_credentials", {"POSTHOG_OFFLINE_EVAL_HOST": "https://[email protected]"}),+ ]+)+def test_settings_reject_invalid_environment(_name: str, overrides: dict[str, str]) -> None:+ environment = {+ "POSTHOG_OFFLINE_EVAL_API_KEY": "test-only-token",+ **overrides,+ }+ with patch.dict("os.environ", environment, clear=True), pytest.raises(OfflineUploadError):+ OfflineEvalSettings.from_env(SUITE)+++ [+ ("dataset_identifier_type", "dataset_item_identifier", 42, "dataset_item_identifier"),+ (+ "dataset_version_identifier",+ "dataset_item_version_identifier",+ "bad\x00version",+ "dataset_item_version_identifier",+ ),+ ("trace_identifier", "trace_id", "bad\x00trace", "application_trace_id"),+ ("long_case_key", "name", "x" * 256, "case_key"),+ ]+)+def test_prepare_preserves_every_case_when_optional_item_references_are_invalid(+ _name: str, field: str, value: str | int, omitted_field: str+) -> None:+ healthy, malformed = _case("healthy"), _case("malformed")+ if field == "name":+ malformed.input["name"] = value+ else:+ malformed.metadata[field] = value+ malformed.metadata["dataset_item_identifier"] = malformed.metadata.get("dataset_item_identifier", "valid-case")++ upload = _prepare(_publisher(link_traces=True), [healthy, malformed])++ assert len(_items(upload)) == 2+ assert len(upload.results) == 4+ assert all(result.to_dict()["status"] == "ok" for result in upload.results)+ assert _items(upload)[0].to_dict()["case_key"] == "healthy"+ item = _items(upload)[1].to_dict()+ assert omitted_field not in item+ assert omitted_field in item["payload"]["metadata"]["omitted_fields"]+ if omitted_field != "dataset_item_identifier":+ assert item["dataset_item_identifier"] == "valid-case"diff --git a/products/posthog_ai/eval_harness/test/test_one_shot_runner.py b/products/posthog_ai/eval_harness/test/test_one_shot_runner.pyindex f204b9c2ba28..fb60ac4eade3 100644--- a/products/posthog_ai/eval_harness/test/test_one_shot_runner.py+++ b/products/posthog_ai/eval_harness/test/test_one_shot_runner.py@@ -39,7 +39,6 @@ class _StubReporter:self.done: list[tuple[str, str]] = []self.started: list[tuple[str, int]] = []self.summaries: list[tuple[str, Any, int]] = []- self.posthog_urls: list[tuple[str, str]] = []async def case_started(self, experiment: str, name: str, trial_id: str, trial_index: int) -> dict[str, float]:return {}@@ -76,9 +75,6 @@ class _StubReporter:) -> None:self.summaries.append((experiment_name, summary, error_count))- async def record_posthog_evaluations_url(self, experiment_name: str, experiment_id: str) -> None:- self.posthog_urls.append((experiment_name, experiment_id))-class _StubEngine:name: ClassVar[str] = "stub"@@ -108,7 +104,6 @@ def _build_ctx(timeout_seconds: int = 30, one_shot_slots: int = 2, case_filter:case_filter=case_filter,demo_data=None,posthog_client=None,- posthog_evaluation_client=None,sandbox_slots=None,team_setup_slots=asyncio.Semaphore(1),one_shot_slots=asyncio.Semaphore(one_shot_slots),@@ -299,22 +294,9 @@ def test_run_routes_through_the_engine(assert ctx.posthog_client.disabledctx.posthog_client.capture(event="ordinary_test_event", distinct_id="test")- assert create_client.call_count == 2- assert ctx.posthog_evaluation_client is not None- assert ctx.posthog_evaluation_client.capture(event="$ai_evaluation", distinct_id="after-shutdown") is None-- if no_send_logs:- batch_post.assert_not_called()- assert reporter.posthog_urls == []- else:- assert batch_post.call_count == 2- for run, upload_call in zip(runs, batch_post.call_args_list):- event = upload_call.kwargs["batch"][0]- assert event["event"] == "$ai_evaluation"- assert event["properties"]["$ai_metric_name"] == "correctness"- assert event["properties"]["$ai_score"] == 1.0- assert event["properties"]["$ai_experiment_id"] == run.experiment_id- assert reporter.posthog_urls == [("one-shot-test", run.experiment_id) for run in runs]+ assert create_client.call_count == 1++ batch_post.assert_not_called()assert len(engine.calls) == 2for experiment in engine.calls:diff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.pyindex 0129fd34db0b..19d29c050f55 100644--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py@@ -14,12 +14,14 @@ from functools import partialfrom pathlib import Pathfrom threading import Event, Thread, get_identfrom typing import Any, Literal+from uuid import UUIDimport pytestfrom unittest.mock import AsyncMock, MagicMockfrom django.db import OperationalError+import httpxfrom botocore.exceptions import ClientErrorfrom clickhouse_driver.errors import ErrorCodes, NetworkError, ServerExceptionfrom psycopg import OperationalError as PsycopgOperationalError@@ -27,7 +29,7 @@ from psycopg.errors import AdminShutdown, InvalidPasswordfrom posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut-from products.posthog_ai.eval_harness import base+from products.posthog_ai.eval_harness import base, log_sinkfrom products.posthog_ai.eval_harness.acp_log import GenerationDescriptor, ParsedLogfrom products.posthog_ai.eval_harness.config import AgentArtifacts, SandboxedEvalCasefrom products.posthog_ai.eval_harness.engines.types import (@@ -39,10 +41,15 @@ from products.posthog_ai.eval_harness.engines.types import ()from products.posthog_ai.eval_harness.harness import reportingfrom products.posthog_ai.eval_harness.harness.cli import SkillDelivery+from products.posthog_ai.eval_harness.harness.offline_delivery import OfflineEvalDeliveryfrom products.posthog_ai.eval_harness.harness.reporting import ProgressReporter, SuiteRunResultfrom products.posthog_ai.eval_harness.harness.transcript import RunTranscriptfrom products.posthog_ai.eval_harness.harness.trial_stats import ScorerTrialStats+from products.posthog_ai.eval_harness.offline_results import OfflineEvalSuite+from products.posthog_ai.eval_harness.one_shot import OneShotEvalfrom products.posthog_ai.eval_harness.scorers import ExitCodeZero+from products.posthog_ai.eval_harness.test.offline_api import OfflineServer+from products.posthog_ai.evals.sql import eval_sql as sql_evalfrom products.tasks.backend.facade.agents import CustomPromptSandboxContext@@ -145,8 +152,10 @@ async def test_reporter_output_is_labeled_and_reserves_pass_for_the_run(experiment_url="https://experiments.example/e",),)- await reporter.record_posthog_evaluations_url(- "sandboxed-cli-mcp-verify-event-cli", "bd8b7f0d-7cc3-4ea3-a3a6-53be0d9e6eb4"+ await reporter.record_posthog_offline_result(+ "sandboxed-cli-mcp-verify-event-cli",+ "uploaded",+ url="https://us.posthog.com/project/2/ai-evals/evaluations/offline/experiments/bd8b7f0d-7cc3-4ea3-a3a6-53be0d9e6eb4",)await reporter.suite_finished(SuiteRunResult(@@ -222,7 +231,7 @@ async def test_reporter_output_is_labeled_and_reserves_pass_for_the_run(pass_any=None,flaky_cases=0,),- " s: 72.0% (95% CI 61.0-83.0%)\n PostHog",+ " s: 72.0% (95% CI 61.0-83.0%)\n Braintrust",id="single_trial",),pytest.param(@@ -253,7 +262,6 @@ async def test_reporter_shows_the_engine_score_with_trial_stats(EvalSummary(engine_name="Braintrust", experiment_name="exp", scores={"s": AggregateScore("s", 0.72)}),trial_stats=[stats],)- await reporter.record_posthog_evaluations_url("exp", "bd8b7f0d-7cc3-4ea3-a3a6-53be0d9e6eb4")reporter.print_final_summary([], exit_code=0, fail_under=None, duration_seconds=1.0)assert expected in capsys.readouterr().out@@ -370,6 +378,188 @@ def test_sandboxed_eval_run_adds_exit_code_scorer(monkeypatch: pytest.MonkeyPatc)+ "suite_kind,enrolled,no_send_logs,configuration,http_status,delivery_state",+ [+ ("sandboxed", True, False, "valid", 200, "ready"),+ ("sandboxed", True, False, "valid", 403, "ready"),+ ("sandboxed", True, False, "invalid", 200, "ready"),+ ("sandboxed", True, False, "absent", 200, "ready"),+ ("sandboxed", True, True, "valid", 200, "ready"),+ ("sandboxed", False, False, "valid", 200, "ready"),+ ("one-shot", True, False, "valid", 200, "ready"),+ ("sandboxed", True, False, "valid", 200, "unavailable"),+ ("sandboxed", True, False, "valid", 200, "closed"),+ ],+)+async def test_sandboxed_eval_publishes_existing_results_without_disrupting_reporting(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ capsys: pytest.CaptureFixture[str],+ suite_kind: Literal["sandboxed", "one-shot"],+ enrolled: bool,+ no_send_logs: bool,+ configuration: Literal["valid", "invalid", "absent"],+ http_status: int,+ delivery_state: Literal["ready", "unavailable", "closed"],+) -> None:+ for key in ("API_KEY", "HOST"):+ monkeypatch.delenv(f"POSTHOG_OFFLINE_EVAL_{key}", raising=False)+ monkeypatch.setenv("EXPORT_EVAL_RESULTS", "1")+ monkeypatch.chdir(tmp_path)+ monkeypatch.setattr(log_sink, "LOGS_ROOT", tmp_path)+ monkeypatch.setattr(log_sink, "INDEX_FILE", tmp_path / "runs.jsonl")+ version_id = "00000000-0000-4000-8000-000000000001"+ if configuration != "absent":+ monkeypatch.setenv("POSTHOG_OFFLINE_EVAL_API_KEY", "fake-offline-test-key" if configuration == "valid" else " ")+ if configuration == "valid":+ monkeypatch.setenv("POSTHOG_OFFLINE_EVAL_HOST", "https://posthog.example.com")++ requests: list[httpx.Request] = []+ server = OfflineServer()+ release_upload = asyncio.Event()++ async def respond(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ await release_upload.wait()+ return server.respond(request) if http_status == 200 else httpx.Response(http_status, json={})++ client_type = httpx.AsyncClient+ monkeypatch.setattr(+ httpx, "AsyncClient", lambda **kwargs: client_type(transport=httpx.MockTransport(respond), **kwargs)+ )+ result = ExperimentResult(+ summary=EvalSummary(+ engine_name="braintrust",+ experiment_name="offline-pilot",+ scores={"exit_code_zero": AggregateScore("exit_code_zero", 1.0)},+ experiment_url="https://braintrust.example.com/experiment/test",+ ),+ results=[+ CaseResult(+ input={"name": "example-case", "prompt": "Run the task"},+ output={"last_message": "Done", "large_integer": 2**64},+ scores={"exit_code_zero": 1.0},+ )+ ],+ )+ engine = MagicMock(run_experiment=AsyncMock(return_value=result))+ reporter = ProgressReporter(total_suites=1)+ delivery = OfflineEvalDelivery(reporter)+ if delivery_state == "closed":+ await delivery.drain()+ ctx = MagicMock(+ posthog_client=None,+ case_filter=None,+ agent_model="test-model",+ agent_runtime="claude",+ skill_delivery="bundled",+ reasoning_effort=None,+ trials=1,+ git_sha="test-sha",+ git_dirty=False,+ engine=engine,+ reporter=reporter,+ offline_delivery=delivery if delivery_state != "unavailable" else None,+ )++ run_eval = base.SandboxedEval if suite_kind == "sandboxed" else partial(OneShotEval, task=AsyncMock())+ returned = await asyncio.wait_for(+ run_eval(+ experiment_name="offline-pilot",+ cases=[SandboxedEvalCase(name="example-case", prompt="Run the task")],+ scorers=[],+ ctx=ctx,+ is_public=not no_send_logs,+ no_send_logs=no_send_logs,+ offline_suite=OfflineEvalSuite(+ key="example/suite",+ project_id=123,+ scorer_kinds={"exit_code_zero": "boolean"},+ scorer_versions={"exit_code_zero": UUID(version_id)},+ )+ if enrolled+ else None,+ ),+ timeout=5,+ )++ assert returned is result+ export_path = tmp_path / "offline-pilot" / "latest" / "case_results.jsonl"+ assert json.loads(export_path.read_text())["scores"] == {"exit_code_zero": 1.0}+ assert not release_upload.is_set()+ release_upload.set()+ await delivery.drain()+ engine.run_experiment.assert_awaited_once()+ engine_spec = engine.run_experiment.call_args.args[0]+ assert engine_spec.no_send_logs is no_send_logs+ assert engine_spec.record_scorer_results is (enrolled and not no_send_logs and configuration == "valid")+ assert reporter.mean_score() == 1.0+ reporter.print_final_summary([], exit_code=0, fail_under=None, duration_seconds=0)+ output = capsys.readouterr().out+ assert "Braintrust: https://braintrust.example.com/experiment/test" in output+ assert "exit_code_zero: 100.0%" in output+ assert not (tmp_path / "offline-pilot" / "latest" / "posthog-offline-upload.json").exists()+ if enrolled and not no_send_logs and configuration == "valid" and delivery_state == "ready":+ declaration = json.loads(requests[0].content)+ assert declaration["name"] == "offline-pilot"+ assert declaration["expected_item_count"] == 1+ assert declaration["expected_result_count"] == 1+ if http_status == 200:+ assert len(requests) == 3+ batch = json.loads(requests[1].content)+ assert batch["results"][0]["scorer_version_id"] == version_id+ assert batch["results"][0]["value"] is True+ assert batch["results"][0]["item_id"] == batch["items"][0]["id"]+ assert batch["items"][0]["payload"]["output"]["large_integer"] == 2**64+ assert requests[2].url.path.endswith("/complete/")+ assert "PostHog: https://posthog.example.com/project/123/" in output+ else:+ assert len(requests) == 1+ assert "PostHog:" not in output+ assert "upload failed:" in output+ assert "403" in output+ assert "Results were not saved for retry." in output+ else:+ assert requests == []+ assert "PostHog:" not in output+ if delivery_state != "ready":+ reason = (+ "background delivery is unavailable" if delivery_state == "unavailable" else "queue is full or closed"+ )+ assert reason in output+ assert "Results were not saved for retry." in output+ elif enrolled and not no_send_logs:+ assert "PostHog offline: disabled:" in output+ assert "POSTHOG_OFFLINE_EVAL_" in output+ else:+ assert "POSTHOG OFFLINE" not in output+++async def test_sql_suite_enrolls_every_scorer_in_offline_publishing(monkeypatch: pytest.MonkeyPatch) -> None:+ run = AsyncMock()+ monkeypatch.setattr(sql_eval, "SandboxedPublicEval", run)++ await sql_eval.eval_sql(MagicMock())++ run.assert_awaited_once()+ suite = run.call_args.kwargs["offline_suite"]+ assert suite.key == "sql/eval_sql::eval_sql"+ assert suite.scorer_kinds == {+ "exit_code_zero": "boolean",+ "no_persistent_insight_save": "boolean",+ "execute_sql_called": "boolean",+ "answer_tool_not_typed_query": "boolean",+ "querying_posthog_data_skill_loaded": "boolean",+ "sql_schema_alignment": "numeric",+ "sql_result_message_alignment": "numeric",+ }+ configured_names = {scorer._name() for scorer in run.call_args.kwargs["scorers"]}+ assert set(suite.scorer_kinds) == {"exit_code_zero", *configured_names}++@pytest.mark.parametrize("delivery,origin,has_original,expected_origin",[@@ -679,7 +869,6 @@ async def test_sandboxed_trials_keep_separate_logs_and_trace_roots(monkeypatch.delenv("EXPORT_EVAL_RESULTS", raising=False)monkeypatch.setattr(base, "build_case_dir", lambda *_: tmp_path)ctx = MagicMock(posthog_client=None, reporter=ProgressReporter(total_suites=1))- ctx.posthog_evaluation_client = Nonectx.trials = 3run = base._SandboxedEvalRun("trials", [], [], ctx, is_public=False, no_send_logs=True)run.posthog_client = MagicMock()diff --git a/products/posthog_ai/eval_harness/test/test_skill_usage_scorers.py b/products/posthog_ai/eval_harness/test/test_skill_usage_scorers.pyindex 726f37e380de..57d5d74b1ab7 100644--- a/products/posthog_ai/eval_harness/test/test_skill_usage_scorers.py+++ b/products/posthog_ai/eval_harness/test/test_skill_usage_scorers.py@@ -1,5 +1,7 @@from __future__ import annotations+import asyncio+import pytestfrom braintrust import Score@@ -149,14 +151,14 @@ def test_search_recovery_rejects_a_product_call_parallel_with_the_learn(learn_fidef test_skill_answer_correctness_self_skips_when_not_requested() -> None:- prepared = SkillAnswerCorrectness()._prepare({"last_message": "anything"}, {})+ prepared = asyncio.run(SkillAnswerCorrectness().eval_async({"last_message": "anything"}, {}))assert isinstance(prepared, Score)assert prepared.score is Nonedef test_skill_answer_correctness_fails_without_final_message() -> None:expected = {"skill_answer_correctness": {"expected_answer": "the answer"}}- prepared = SkillAnswerCorrectness()._prepare({"last_message": " "}, expected)+ prepared = asyncio.run(SkillAnswerCorrectness().eval_async({"last_message": " "}, expected))assert isinstance(prepared, Score)assert prepared.score == 0.0diff --git a/products/posthog_ai/eval_harness/test/test_trace_events.py b/products/posthog_ai/eval_harness/test/test_trace_events.pyindex ddff25fa334e..ec0c469b9550 100644--- a/products/posthog_ai/eval_harness/test/test_trace_events.py+++ b/products/posthog_ai/eval_harness/test/test_trace_events.py@@ -9,7 +9,6 @@ from posthoganalytics import Posthogfrom products.posthog_ai.eval_harness.acp_log import GenerationDescriptor, ParsedLog, SpanDescriptorfrom products.posthog_ai.eval_harness.base import _SandboxedEvalRun-from products.posthog_ai.eval_harness.engines.types import CaseResultfrom products.posthog_ai.eval_harness.one_shot import _OneShotEvalRunfrom products.posthog_ai.eval_harness.scorers.contract import Score, Scorerfrom products.posthog_ai.eval_harness.scorers.tracing import (@@ -18,12 +17,7 @@ from products.posthog_ai.eval_harness.scorers.tracing import (_build_posthog_kwargs,_scorer_context,)-from products.posthog_ai.eval_harness.trace_events import (- RunMetadata,- emit_evaluation_events,- emit_trace_events,- emit_trace_root,-)+from products.posthog_ai.eval_harness.trace_events import RunMetadata, emit_trace_events, emit_trace_rootNAMESPACES = [(_SandboxedEvalRun.trace_namespace,), (_OneShotEvalRun.trace_namespace,)]RUN_METADATA: RunMetadata = {"agent_model": "claude-test", "trials": 3, "git_sha": "abc123", "git_dirty": False}@@ -37,20 +31,6 @@ class _CapturingClient:self.calls.append(kwargs)[email protected](NAMESPACES)-def test_evaluation_events_carry_the_run_namespace(namespace: str) -> None:- client = _CapturingClient()- result = CaseResult(input={"name": "case-1"}, output={}, scores={"a_scorer": 1.0})-- emit_evaluation_events(- cast(Posthog, client), "exp-1", "my-suite", [result], namespace=namespace, run_metadata=RUN_METADATA- )-- properties = client.calls[0]["properties"]- assert properties["$ai_experiment_name"] == f"{namespace}/my-suite"- assert properties["$ai_eval_source"] == namespace--@parameterized.expand(NAMESPACES)def test_trace_root_carries_the_run_namespace(namespace: str) -> None:client = _CapturingClient()@@ -72,15 +52,6 @@ def test_trace_root_carries_the_run_namespace(namespace: str) -> None:assert properties["$ai_experiment_name"] == f"{namespace}/my-suite"-def _evaluation_properties(run_metadata: RunMetadata) -> dict[str, Any]:- client = _CapturingClient()- result = CaseResult(input={"name": "case-1"}, output={}, scores={"a_scorer": 1.0})- emit_evaluation_events(- cast(Posthog, client), "exp-1", "my-suite", [result], namespace="ns", run_metadata=run_metadata- )- return client.calls[0]["properties"]--def _trace_root_properties(run_metadata: RunMetadata) -> dict[str, Any]:client = _CapturingClient()emit_trace_root(@@ -156,7 +127,6 @@ def _judge_generation_properties(run_metadata: RunMetadata) -> dict[str, Any]:@parameterized.expand([- ("evaluation", _evaluation_properties),("trace_root", _trace_root_properties),("agent_generation", _parsed_event_properties("$ai_generation")),("agent_span", _parsed_event_properties("$ai_span")),@@ -194,34 +164,12 @@ def test_repeated_case_scores_link_to_their_own_trial_traces() -> None:posthog_client=cast(Posthog, client),agent_trace_id_lookup={"trial-1": "agent-1", "trial-2": "agent-2"},)- results = []for index in (1, 2):trial_id = f"trial-{index}"metadata = {"trial_id": trial_id, "trace_id": f"agent-{index}"}asyncio.run(scorer.eval_async({}, input={"name": "same-case"}, metadata=metadata))- scorer_traces[(trial_id, "judge")] = f"judge-{index}"- results.append(- CaseResult(- input={"name": "same-case"},- output={},- scores={"stub": 1.0, "judge": 0.5},- metadata=metadata,- )- )- emit_evaluation_events(- cast(Posthog, client),- "exp-1",- "my-suite",- list(reversed(results)),- namespace="ns",- run_metadata=RUN_METADATA,- scorer_traces=scorer_traces,- )assert [call["properties"]["$ai_trace_id"] for call in client.calls] == ["agent-1","agent-2",- "agent-2",- "judge-2",- "agent-1",- "judge-1",]+ assert len({call["properties"]["$ai_span_id"] for call in client.calls}) == 2diff --git a/products/posthog_ai/eval_harness/trace_events.py b/products/posthog_ai/eval_harness/trace_events.pyindex a586afca503b..4c8bbf28b127 100644--- a/products/posthog_ai/eval_harness/trace_events.py+++ b/products/posthog_ai/eval_harness/trace_events.py@@ -1,5 +1,4 @@-"""Emit sandboxed eval trace events ($ai_generation, $ai_span, $ai_trace,-$ai_evaluation) to a PostHog client.+"""Emit sandboxed eval trace events ($ai_generation, $ai_span, $ai_trace) to PostHog.Consumes a ``ParsedLog`` produced by ``acp_log.parse_log`` plus scoringresults from Braintrust. Owns the constants shared with scorer tracing@@ -16,7 +15,6 @@ from typing import Anyfrom posthoganalytics import Posthogfrom .acp_log import GenerationDescriptor, ParsedLog, SpanDescriptor-from .engines.types import CaseResultlogger = logging.getLogger(__name__)@@ -288,78 +286,3 @@ def emit_trace_root(scores=scores,token_usage=token_usage,)---def emit_evaluation_events(- client: Posthog,- experiment_id: str,- experiment_name: str,- eval_results: list[CaseResult],- *,- namespace: str,- run_metadata: RunMetadata,- scorer_traces: dict[tuple[str, str], str] | None = None,-) -> None:- """Emit ``$ai_evaluation`` events for each scorer result in each eval case.-- ``scorer_traces`` maps ``(trial_id, scorer_name)`` to the trace_id of- the scorer's LLM call. If available, ``$ai_trace_id`` on the event- points to the scorer trace (for inspecting the scorer's reasoning).- """- formatted_name = f"{namespace}/{experiment_name}"-- for result in eval_results:- case_name = result.input.get("name", "unknown") if isinstance(result.input, dict) else "unknown"- metadata = result.metadata or {}- trial_id = str(metadata.get("trial_id") or case_name)- agent_trace_id = metadata.get("trace_id")- item_id = str(uuid.uuid4())-- # $ai_output = last assistant message- last_message = ""- if isinstance(result.output, dict):- last_message = result.output.get("last_message", "")-- for scorer_name, score_value in (result.scores or {}).items():- # Prefer scorer trace_id (links to scorer's LLM reasoning);- # fall back to agent trace_id- scorer_trace_id = scorer_traces.get((trial_id, scorer_name)) if scorer_traces else None- trace_id = scorer_trace_id or agent_trace_id-- properties: dict[str, Any] = {- **run_metadata,- "$ai_eval_source": namespace,- "$ai_evaluation_type": "offline",- "$ai_experiment_id": experiment_id,- "$ai_experiment_name": formatted_name,- "$ai_experiment_item_id": item_id,- "$ai_experiment_item_name": case_name,- "$ai_metric_name": scorer_name,- "$ai_metric_version": "1",- "$ai_result_type": "numeric",- "$ai_score_min": 0,- "$ai_score_max": 1,- "$ai_status": "ok" if score_value is not None else "error",- }- if score_value is not None:- properties["$ai_score"] = score_value- properties["$ai_trace_id"] = trace_id or str(uuid.uuid4())- if trace_id:- properties["$ai_target_id"] = trace_id- properties["$ai_target_type"] = "trace_id"- if isinstance(result.input, dict):- prompt = result.input.get("prompt", "")- if prompt:- properties["$ai_input"] = prompt- if last_message:- properties["$ai_output"] = last_message- if result.expected is not None:- properties["$ai_expected"] = result.expected-- client.capture(distinct_id=DISTINCT_ID, event="$ai_evaluation", properties=properties)-- logger.info(- "Emitted evaluation events for experiment '%s' (%d results)",- experiment_name,- len(eval_results),- )diff --git a/products/posthog_ai/evals/sql/eval_sql.py b/products/posthog_ai/evals/sql/eval_sql.pyindex 4f358ddc8f07..12d78f18dd8b 100644--- a/products/posthog_ai/evals/sql/eval_sql.py+++ b/products/posthog_ai/evals/sql/eval_sql.py@@ -10,9 +10,12 @@ To run:from __future__ import annotations+from uuid import UUID+from products.posthog_ai.eval_harness.base import SandboxedPublicEvalfrom products.posthog_ai.eval_harness.config import SandboxedEvalCasefrom products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.offline_results import OfflineEvalSuitefrom products.posthog_ai.eval_harness.scorers import AnswerToolCallNot, NoToolCallfrom products.posthog_ai.evals.product_analytics.scorers import INSIGHT_WRITE_TOOLSfrom products.posthog_ai.evals.retrieval.scorers import SkillLoaded@@ -372,6 +375,28 @@ WHERE properties.interests IS NOT NULLawait SandboxedPublicEval(experiment_name="sandboxed-sql-cli",+ offline_suite=OfflineEvalSuite(+ key="sql/eval_sql::eval_sql",+ project_id=2,+ scorer_kinds={+ "exit_code_zero": "boolean",+ "no_persistent_insight_save": "boolean",+ "execute_sql_called": "boolean",+ "answer_tool_not_typed_query": "boolean",+ "querying_posthog_data_skill_loaded": "boolean",+ "sql_schema_alignment": "numeric",+ "sql_result_message_alignment": "numeric",+ },+ scorer_versions={+ "exit_code_zero": UUID("01a11724-d52d-704a-af08-2ceaf5c65a6d"),+ "no_persistent_insight_save": UUID("01a11725-17f6-7673-93e9-4d525fa121ab"),+ "execute_sql_called": UUID("01a11725-20aa-78c3-af96-1aae34bca429"),+ "answer_tool_not_typed_query": UUID("01a11725-3002-7a3f-b9b5-3426bdec5f00"),+ "querying_posthog_data_skill_loaded": UUID("01a11725-54c1-71e0-b606-132d5f4cb339"),+ "sql_schema_alignment": UUID("01a11725-5da7-7dae-ab09-1c0beaa77224"),+ "sql_result_message_alignment": UUID("01a11725-6940-7f49-b979-11b3d6521393"),+ },+ ),cases=cases,scorers=[NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),diff --git a/products/replay_vision/evals/README.md b/products/replay_vision/evals/README.mdindex f8ccb73f110c..66bd62afb511 100644--- a/products/replay_vision/evals/README.md+++ b/products/replay_vision/evals/README.md@@ -66,9 +66,9 @@ This suite does not calculate recommendation precision.It is deliberately not attached to `pull_request`: Gemini is nondeterministic and the dataset is re-sampled per run, so the score is a directional signal rather than a merge gate, and spending secrets and LLM calls on every push buys nothing that a dispatch after a prompt change does not.It collects a fresh dataset on the runner (so consent is re-verified every run; nothing is cached, uploaded, or persisted), runs the suite, and writes the aggregate scores to the job's step summary.-The summary also links the run's `/ai-evals` offline experiment, where the harness publishes the same scores.Only those allowlisted summary lines are public: collector and harness output stay in runner-local files, because they carry session and observation ids.-The job needs `REPLAY_VISION_EVAL_POSTHOG_API_KEY` (a personal API key with scanner, session recording, export, and query read access to the dogfood project) plus the `GEMINI_API_KEY`, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, and `BRAINTRUST_API_KEY` secrets; if any is missing the job skips green and warns which.+The job needs `REPLAY_VISION_EVAL_POSTHOG_API_KEY` (a personal API key with scanner, session recording, export, and query read access to the dogfood project) plus the `GEMINI_OFFLINE_EVALS_API_KEY`, `OPENAI_OFFLINE_EVALS_API_KEY`, `ANTHROPIC_OFFLINE_EVALS_API_KEY`, and `BRAINTRUST_API_KEY` secrets; if any is missing the job skips green and warns which.+The dedicated provider secrets are exposed to the suite as `GEMINI_API_KEY`, `OPENAI_API_KEY`, and `LLM_GATEWAY_ANTHROPIC_API_KEY`.## Data handling@@ -78,7 +78,7 @@ The dataset contains real session recordings and event data.- A dataset expires 30 days after its last collection: the suite refuses to run it, because the consent verification (and the recordings themselves) can lapse after collection. Re-running collect.py re-verifies consent and refreshes the manifest.- The suite is `OneShotPrivateEval`, so per-case logs stay in the local `eval_harness/logs/` directory and nothing goes to Braintrust.- The retained `signals` can contain session content. Keep these payloads private; never include them in public CI summaries, commits, or pull requests.-- Dataset-derived content still leaves the machine on three paths. Two reach a model provider: the Gemini scans, which are the same provider call production already makes through `run_scan`, and the `summary_alignment` judge, which sends the recorded and fresh summaries to `gpt-5.4`. The third is the harness's `$ai_evaluation` capture, which stays inside PostHog.+- Dataset-derived content reaches two model providers: the Gemini scans use the same provider call production makes through `run_scan`, and the `summary_alignment` judge sends the recorded and fresh summaries to `gpt-5.4`.- The judge calls the OpenAI API directly with `OPENAI_API_KEY`. It does not go through the internal LLM gateway, which a one-shot suite never starts, so nothing sits in front of the provider on that path.-- That capture posts every run's scores to project 2, keyed `<scanner_type>-<observation_id>`, with the scanner prompt as `$ai_input` and the recorded and fresh outcomes as `$ai_expected`/`$ai_output`. The scores land in that project's offline experiments view, which is where to compare runs over time.+- This private suite does not publish scores to PostHog's offline experiments. Results remain in local logs and the aggregate CI summary.- Collecting from projects other than PostHog's own requires a data-governance decision first; see the product's consent gating (`backend/consent.py`) and note that customer-facing copy does not cover internal reuse today.