Skip to content

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

feat(aio): add offline evaluation ingestion and lifecycle apis (#106086)

Radu Raicea93df13b36b8a
diff --git a/docs/internal/ai-offline-evaluation-reporting.md b/docs/internal/ai-offline-evaluation-reporting.md
index 487e59f9c311..3cad849840f3 100644
--- a/docs/internal/ai-offline-evaluation-reporting.md
+++ b/docs/internal/ai-offline-evaluation-reporting.md
@@ -20,3 +20,94 @@ Ordinary PostHog SDK clients and trace clients retain their existing `TEST` and
Each event contains the existing experiment, case, and metric properties, including input, output, and expected values when available.
Result reporting uses the existing event schema.
The legacy SQL evaluation path in `ee/hogai/eval/offline/` has a separate reporter and is outside this behavior.
+
+## Postgres experiment ingestion
+
+The 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.
+
+Use the base path `/api/projects/{project_id}/ai_observability/offline_experiments/`.
+
+| Method and path | Purpose |
+| --------------------------------- | ------------------------------------------------------------------------------------ |
+| `POST /` | Create an experiment with a caller-generated UUID, name, and `started_at` timestamp. |
+| `POST /{experiment_id}/upload/` | Persist one or many results and their shared items in one transaction. |
+| `POST /{experiment_id}/complete/` | Check any declared expected counts and close the experiment. |
+| `POST /{experiment_id}/fail/` | Close an interrupted experiment without requiring expected counts to match. |
+
+Programmatic callers use a personal or project secret API key with `offline_evaluation_ingestion:write`.
+Project secret keys grant these operations across their project.
+Personal keys and logged-in users require evaluation editor access.
+They also require viewer access to the dataset when linking a revision or adding hosted items, and viewer access to the scorer definition when adding results.
+Missing and inaccessible references return the same validation error.
+Exact retries still acknowledge previously accepted records after reference access changes; they neither read payloads nor create new records.
+The ingestion scope grants neither stored payload reads nor scorer administration.
+Public project tokens used for event capture cannot authenticate these operations.
+
+Create scorers first, using the existing scorer API or UI, and pin their version UUIDs before submitting results.
+Older and archived versions remain valid references.
+The API validates numeric bounds and steps, boolean values, and categorical keys against the pinned configuration.
+Numeric scores use finite binary64 values; step validation allows rounding error of at most one millionth of the configured step.
+
+For example, this upload declares one item and its boolean result:
+
+```json
+{
+ "items": [
+ {
+ "id": "00000000-0000-4000-8000-000000000001",
+ "payload": { "input": "What is 2 + 2?", "output": "4" }
+ }
+ ],
+ "results": [
+ {
+ "item_id": "00000000-0000-4000-8000-000000000001",
+ "scorer_version_id": "00000000-0000-4000-8000-000000000002",
+ "status": "ok",
+ "value": true
+ }
+ ]
+}
+```
+
+The version UUID above is a placeholder for a pre-existing boolean scorer version.
+An additional scorer result can reference the same `item_id` without repeating its item declaration or payload.
+Each item declaration is complete and immutable.
+Missing payload properties and explicitly supplied JSON nulls remain distinct.
+
+Responses acknowledge committed writes and return stable item/result IDs, original acceptance times, and `created` flags.
+Retries with the same identities and content return the original records.
+Changed content returns HTTP 409; an invalid entry rejects the entire request with HTTP 400.
+Validation responses include an `errors` array with a `code`, `detail`, and `attr` for each detected failure.
+Field paths use zero-based request positions, such as `results.99.value` for the 100th result's score.
+The top-level `code`, `detail`, and `attr` describe the first error for compatibility.
+Request shape and field validation run before dataset and scorer validation; correct the reported errors and resend the batch to reach the next stage.
+Within dataset and scorer validation, all entries are checked before rejecting the batch, and no new items, results, or payloads are stored.
+Do not generate replacement item UUIDs when retrying a request.
+
+Numeric scores allow a small floating-point rounding tolerance at minimum and maximum boundaries, so `7 * 0.1` is accepted with `max=0.7`.
+The tolerance is capped at four floating-point units, `1e-12` absolute, `1e-12` relative to a nonzero boundary, and one millionth of the configured step when present.
+Zero boundaries use a unit scale to allow small residues from subtraction.
+Values outside that tolerance remain invalid, and accepted values are stored as submitted.
+
+Optional `expected_item_count` and `expected_result_count` declarations are fixed at experiment creation.
+Completion compares them with accepted unique counts, including error, skipped, and not-applicable outcomes.
+A mismatch returns HTTP 409 with the expected and accepted counts and leaves the experiment uploading.
+Repeated closure to the same state succeeds; changing a terminal state returns a conflict.
+Closed experiments accept exact retries, but reject new items/results.
+
+Uploads allow at most 1,000 results, 1,000 item declarations, and 5 MiB of request data.
+Each item payload is limited to 1 MiB; each result payload to 256 KiB; JSON nesting to 32 levels.
+Each upload must contain a result, and every declared item must be referenced by a result in that request.
+Requests exceeding the body limit return HTTP 413.
+Per-caller and shared project limits allow 60 requests per minute and 1,000 per hour; HTTP 429 responses include retry guidance.
+The shared project limits apply across the parent project and all its child environments, regardless of which credentials each request uses.
+
+The optional `run_source` accepts `ci`, `local`, `scheduled`, or null; empty strings are invalid.
+For hosted datasets, set `dataset_revision_id` to the UUID of a hosted dataset revision when you create the experiment.
+Each new item in that experiment must then set `dataset_item_version_id` to the UUID of an item version that is active in that revision.
+Local and external datasets do not require hosted links; they can use the `*_identifier` fields instead.
+
+Large payloads have separate storage and 30-day deadlines anchored to first acceptance.
+Retries neither extend deadlines nor restore deleted payloads.
+Automatic payload deletion and usage billing are not enabled by these endpoints.
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
index f31b6142d98b..f5575a45930e 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
@@ -461,6 +461,7 @@ export interface accessControlsLogicActions {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -636,6 +637,7 @@ export interface accessControlsLogicMeta {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -788,6 +790,7 @@ export interface accessControlsLogicMeta {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -912,6 +915,7 @@ export interface accessControlsLogicMeta {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
index b2de63a922d4..704af55c1347 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
@@ -286,6 +286,7 @@ export interface accessDetailLogicActions {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts
index 7ef96214a890..be66a3fcf324 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts
@@ -132,6 +132,7 @@ export interface addObjectOverrideModalLogicActions {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -254,6 +255,7 @@ export interface addObjectOverrideModalLogicActions {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -397,6 +399,7 @@ export interface addObjectOverrideModalLogicActions {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -524,6 +527,7 @@ export interface addObjectOverrideModalLogicActions {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -650,6 +654,7 @@ export interface addObjectOverrideModalLogicActions {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -797,6 +802,7 @@ export interface addObjectOverrideModalLogicMeta {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts
index 627655498d8c..4ace075c57ce 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts
@@ -95,6 +95,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -223,6 +224,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -343,6 +345,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -476,6 +479,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -614,6 +618,7 @@ export interface groupedAccessControlRuleModalLogicActions {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -754,6 +759,7 @@ export interface groupedAccessControlRuleModalLogicActions {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -874,6 +880,7 @@ export interface groupedAccessControlRuleModalLogicActions {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -1033,6 +1040,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -1155,6 +1163,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -1276,6 +1285,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -1397,6 +1407,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -1519,6 +1530,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -1640,6 +1652,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -1772,6 +1785,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -1893,6 +1907,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
index 9ea0a51241e6..55f48f7524e9 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
@@ -387,6 +387,7 @@ export interface accessControlLogicMeta {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -612,6 +613,7 @@ export interface accessControlLogicMeta {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
@@ -733,6 +735,7 @@ export interface accessControlLogicMeta {
| 'mcp_builtin_agent'
| 'metrics'
| 'notebook'
+ | 'offline_evaluation_ingestion'
| 'organization'
| 'organization_integration'
| 'organization_member'
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index e993b96d9120..a9c493bcf0d7 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -104,6 +104,13 @@ export const API_SCOPES: APIScope[] = [
{ key: 'event_filter', objectName: 'Event filter', objectPlural: 'event filters' },
{ key: 'error_tracking', objectName: 'Error tracking', objectPlural: 'error tracking' },
{ key: 'evaluation', objectName: 'Evaluation', objectPlural: 'evaluations' },
+ {
+ key: 'offline_evaluation_ingestion',
+ objectName: 'Offline evaluation ingestion',
+ objectPlural: 'offline evaluation uploads',
+ info: 'Create experiments, upload results, and mark experiments as completed or failed.',
+ disabledActions: ['read'],
+ },
{ key: 'experiment', objectName: 'Experiment', objectPlural: 'experiments' },
{ key: 'experiment_holdout', objectName: 'Holdout', objectPlural: 'holdouts' },
{ key: 'experiment_saved_metric', objectName: 'Shared metric', objectPlural: 'shared metrics' },
@@ -292,6 +299,7 @@ export const PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION = [
'account:read',
'loop:write',
'experiment:read',
+ 'offline_evaluation_ingestion:write',
] as const
export type ProjectSecretAPIKeyAllowedScope = (typeof PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION)[number]
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 469fec264399..555b686f400f 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5939,6 +5939,7 @@ export const API_SCOPE_OBJECTS = [
'mcp_analytics',
'metrics',
'notebook',
+ 'offline_evaluation_ingestion',
'organization',
'organization_integration',
'organization_member',
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 9c6099c182a4..dd218edcbc4b 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -91,6 +91,7 @@ APIScopeObject = Literal[
"mcp_registry",
"metrics",
"notebook",
+ "offline_evaluation_ingestion",
"organization",
"organization_integration",
"organization_member",
@@ -236,6 +237,7 @@ PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIS
# Read-only export of experiment definitions (list/retrieve), so services syncing
# experiments into a warehouse don't need a credential tied to one person's account.
("experiment", "read"),
+ ("offline_evaluation_ingestion", "write"),
]
# Server-side scope assignment string-set constants (see RFC: server-side scope
diff --git a/products/ai_observability/backend/api/__init__.py b/products/ai_observability/backend/api/__init__.py
index 41ba3079e3d5..8f031eb3e38a 100644
--- a/products/ai_observability/backend/api/__init__.py
+++ b/products/ai_observability/backend/api/__init__.py
@@ -12,6 +12,7 @@ from .evaluations import EvaluationViewSet
from .instrumentation_checklist import AIObservabilityInstrumentationChecklistViewSet
from .models import LLMModelsViewSet
from .offline_evaluations import AIObservabilityOfflineEvaluationsViewSet
+from .offline_experiments import OfflineExperimentViewSet
from .parser_recipes import ParserRecipeViewSet
from .personal_spend import PersonalSpendInternalViewSet, PersonalSpendViewSet
from .provider_keys import LLMProviderKeyValidationViewSet, LLMProviderKeyViewSet
@@ -50,6 +51,7 @@ __all__ = [
"ReviewQueueItemViewSet",
"ScoreDefinitionViewSet",
"AIObservabilityOfflineEvaluationsViewSet",
+ "OfflineExperimentViewSet",
"PersonalSpendInternalViewSet",
"PersonalSpendViewSet",
"TaggerViewSet",
diff --git a/products/ai_observability/backend/api/offline_experiment_access.py b/products/ai_observability/backend/api/offline_experiment_access.py
new file mode 100644
index 000000000000..e762b2f09985
--- /dev/null
+++ b/products/ai_observability/backend/api/offline_experiment_access.py
@@ -0,0 +1,48 @@
+from typing import TYPE_CHECKING, cast
+
+from posthog.auth import PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthentication
+from posthog.rate_limit import PersonalApiKeyOrUserRateThrottle, PersonalOrProjectSecretApiKeyRateThrottle
+
+if TYPE_CHECKING:
+ from rest_framework.request import Request
+ from rest_framework.views import APIView
+
+ from posthog.api.routing import TeamAndOrgViewSetMixin
+
+
+class _OfflineEvaluationCallerThrottle(PersonalOrProjectSecretApiKeyRateThrottle):
+ def allow_request(self, request: "Request", view: "APIView") -> bool:
+ return self._allow_request_internal(request, view, personal_api_key_only=False)
+
+ def get_cache_key(self, request: "Request", view: "APIView") -> str:
+ if isinstance(
+ request.successful_authenticator, (PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthentication)
+ ):
+ return super().get_cache_key(request, view)
+ ident = f"user:{request.user.pk}" if request.user.is_authenticated else self.get_ident(request)
+ return self.cache_format % {"scope": self.scope, "ident": ident}
+
+
+class OfflineEvaluationIngestionBurstThrottle(_OfflineEvaluationCallerThrottle):
+ scope = "offline_evaluation_ingestion_burst"
+ rate = "60/minute"
+
+
+class OfflineEvaluationIngestionSustainedThrottle(_OfflineEvaluationCallerThrottle):
+ scope = "offline_evaluation_ingestion_sustained"
+ rate = "1000/hour"
+
+
+class OfflineEvaluationIngestionTeamBurstThrottle(PersonalApiKeyOrUserRateThrottle):
+ scope = "offline_evaluation_ingestion_team_burst"
+ rate = "60/minute"
+
+ def get_cache_key(self, request: "Request", view: "APIView") -> str:
+ team = cast("TeamAndOrgViewSetMixin", view).team
+ team_id = team.parent_team_id or team.id
+ return self.cache_format % {"scope": self.scope, "ident": f"team:{team_id}"}
+
+
+class OfflineEvaluationIngestionTeamSustainedThrottle(OfflineEvaluationIngestionTeamBurstThrottle):
+ scope = "offline_evaluation_ingestion_team_sustained"
+ rate = "1000/hour"
diff --git a/products/ai_observability/backend/api/offline_experiment_parser.py b/products/ai_observability/backend/api/offline_experiment_parser.py
new file mode 100644
index 000000000000..345568abc784
--- /dev/null
+++ b/products/ai_observability/backend/api/offline_experiment_parser.py
@@ -0,0 +1,44 @@
+import json
+import math
+from collections.abc import Mapping
+from decimal import Decimal, DecimalException
+from typing import IO, cast
+
+from rest_framework.exceptions import APIException, ParseError
+from rest_framework.parsers import JSONParser
+
+MAX_UPLOAD_BODY_BYTES = 5 * 1024 * 1024
+
+
+class OfflineEvaluationRequestTooLarge(APIException):
+ status_code = 413
+ default_detail = "Request bodies must be 5 MiB or smaller. Split results into smaller batches."
+ default_code = "request_too_large"
+
+
+def _finite_float(value: str) -> float:
+ number = float(value)
+ if not math.isfinite(number) or number == 0 and Decimal(value) != 0:
+ raise ValueError("Number is outside the supported binary64 range.")
+ return number
+
+
+def _invalid_constant(value: str) -> None:
+ raise ValueError("Non-finite JSON numbers are not supported.")
+
+
+class OfflineEvaluationJSONParser(JSONParser):
+ def parse(
+ self, stream: IO[bytes], media_type: str | None = None, parser_context: Mapping[str, object] | None = None
+ ) -> dict[str, object]:
+ # Bound the stream itself; Content-Length can be absent or inaccurate.
+ body = stream.read(MAX_UPLOAD_BODY_BYTES + 1)
+ if len(body) > MAX_UPLOAD_BODY_BYTES:
+ raise OfflineEvaluationRequestTooLarge
+ try:
+ value = json.loads(body, parse_float=_finite_float, parse_constant=_invalid_constant)
+ if not isinstance(value, dict):
+ raise ValueError("Request bodies must be JSON objects.")
+ return cast(dict[str, object], value)
+ except (ValueError, UnicodeError, RecursionError, DecimalException) as error:
+ raise ParseError("Provide valid JSON with finite, representable numbers.") from error
diff --git a/products/ai_observability/backend/api/offline_experiment_serializers.py b/products/ai_observability/backend/api/offline_experiment_serializers.py
new file mode 100644
index 000000000000..fc7c9ec7204e
--- /dev/null
+++ b/products/ai_observability/backend/api/offline_experiment_serializers.py
@@ -0,0 +1,356 @@
+import json
+import math
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, cast
+from uuid import UUID
+
+from drf_spectacular.utils import extend_schema_field
+from rest_framework import serializers
+from rest_framework_dataclasses.serializers import DataclassSerializer
+
+from products.ai_observability.backend.models.offline_evaluations import OfflineEvaluationResult, OfflineExperiment
+from products.ai_observability.backend.offline_evaluation_types import (
+ ExperimentSubmission,
+ ItemSubmission,
+ JSONValue,
+ ResultSubmission,
+ ResultValue,
+ UploadSubmission,
+)
+
+if TYPE_CHECKING:
+ from rest_framework_dataclasses.types import Dataclass
+
+MAX_UPLOAD_ITEMS = 1000
+MAX_UPLOAD_RESULTS = 1000
+MAX_ITEM_PAYLOAD_BYTES = 1024 * 1024
+MAX_RESULT_PAYLOAD_BYTES = 256 * 1024
+MAX_JSON_DEPTH = 32
+
+
+class _StrictDataclassSerializer[T: Dataclass](DataclassSerializer[T]):
+ def to_internal_value(self, data: object) -> T:
+ if isinstance(data, Mapping):
+ writable_fields = {name for name, field in self.fields.items() if not field.read_only}
+ unsupported = set(data) - writable_fields
+ if unsupported:
+ raise serializers.ValidationError({str(name): ["This field is not supported."] for name in unsupported})
+ return super().to_internal_value(cast(dict[str, object], data))
+
+
+class _StrictCharField(serializers.CharField):
+ def to_internal_value(self, data: object) -> str:
+ if not isinstance(data, str):
+ self.fail("invalid")
+ return super().to_internal_value(data)
+
+
+class _CountField(serializers.IntegerField):
+ def to_internal_value(self, data: object) -> int:
+ if type(data) is not int:
+ self.fail("invalid")
+ return super().to_internal_value(data)
+
+
+class _UUIDField(serializers.UUIDField):
+ def to_internal_value(self, data: object) -> UUID:
+ if not isinstance(data, (str, UUID)):
+ self.fail("invalid")
+ return super().to_internal_value(data)
+
+
+def _identifier_field(help_text: str, *, max_length: int = 255) -> _StrictCharField:
+ return _StrictCharField(
+ required=False,
+ allow_null=True,
+ allow_blank=False,
+ trim_whitespace=False,
+ max_length=max_length,
+ help_text=help_text,
+ )
+
+
+def _json_value_schema() -> dict[str, object]:
+ return {
+ "oneOf": [
+ {"type": "object", "additionalProperties": True},
+ {"type": "array", "items": {}},
+ {"type": "string"},
+ {"type": "number"},
+ {"type": "boolean"},
+ {"type": "null"},
+ ]
+ }
+
+
+class _PayloadField(serializers.Field):
+ allowed_keys: frozenset[str]
+ string_keys: frozenset[str] = frozenset()
+ max_bytes: int
+
+ def _validate_json_values(self, data: dict[str, object]) -> None:
+ pending: list[tuple[object, int]] = [(data, 1)]
+ while pending:
+ value, depth = pending.pop()
+ if isinstance(value, (dict, list)):
+ if depth > MAX_JSON_DEPTH:
+ raise serializers.ValidationError(f"JSON nesting must not exceed {MAX_JSON_DEPTH} levels.")
+ if isinstance(value, dict):
+ if any(not isinstance(key, str) or "\x00" in key for key in value):
+ raise serializers.ValidationError("JSON object keys must be strings without null characters.")
+ pending.extend((child, depth + 1) for child in value.values())
+ else:
+ pending.extend((child, depth + 1) for child in value)
+ elif isinstance(value, str):
+ if "\x00" in value:
+ raise serializers.ValidationError("JSON strings must not contain null characters.")
+ elif value is not None and type(value) not in (bool, int, float):
+ raise serializers.ValidationError("Provide valid JSON values.")
+
+ def to_internal_value(self, data: object) -> dict[str, JSONValue]:
+ if not isinstance(data, dict):
+ raise serializers.ValidationError("Provide a JSON object.")
+ unsupported = set(data) - self.allowed_keys
+ if unsupported:
+ raise serializers.ValidationError({str(key): ["This field is not supported."] for key in unsupported})
+ if data.get("metadata") is not None and not isinstance(data["metadata"], dict):
+ raise serializers.ValidationError({"metadata": ["Provide a JSON object or null."]})
+ for key in self.string_keys:
+ if data.get(key) is not None and not isinstance(data[key], str):
+ raise serializers.ValidationError({key: ["Provide a string or null."]})
+
+ self._validate_json_values(data)
+ try:
+ encoded = json.dumps(data, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode("utf-8")
+ except (ValueError, UnicodeError) as error:
+ raise serializers.ValidationError("Provide valid JSON with finite numbers and valid Unicode.") from error
+ if len(encoded) > self.max_bytes:
+ raise serializers.ValidationError(f"Payload must not exceed {self.max_bytes} bytes of UTF-8 JSON.")
+ return cast(dict[str, JSONValue], data)
+
+ def to_representation(self, value: dict[str, JSONValue]) -> dict[str, JSONValue]:
+ return value
+
+
+@extend_schema_field(
+ {
+ "type": "object",
+ "additionalProperties": False,
+ "properties": {
+ "input": _json_value_schema(),
+ "output": _json_value_schema(),
+ "expected_output": _json_value_schema(),
+ "metadata": {"type": "object", "additionalProperties": True, "nullable": True},
+ },
+ },
+ component_name="OfflineExperimentItemPayloadInput",
+)
+class ItemPayloadField(_PayloadField):
+ allowed_keys = frozenset({"input", "output", "expected_output", "metadata"})
+ max_bytes = MAX_ITEM_PAYLOAD_BYTES
+
+
+@extend_schema_field(
+ {
+ "type": "object",
+ "additionalProperties": False,
+ "properties": {
+ "reasoning": {"type": "string", "nullable": True},
+ "error_message": {"type": "string", "nullable": True},
+ "metadata": {"type": "object", "additionalProperties": True, "nullable": True},
+ },
+ },
+ component_name="OfflineEvaluationResultPayloadInput",
+)
+class ResultPayloadField(_PayloadField):
+ allowed_keys = frozenset({"reasoning", "error_message", "metadata"})
+ string_keys = frozenset({"reasoning", "error_message"})
+ max_bytes = MAX_RESULT_PAYLOAD_BYTES
+
+
+@extend_schema_field(
+ {
+ "oneOf": [
+ {"type": "number", "format": "double"},
+ {"type": "boolean"},
+ {"type": "array", "items": {"type": "string", "maxLength": 128}, "minItems": 1, "uniqueItems": True},
+ ]
+ }
+)
+class ResultValueField(serializers.Field):
+ def to_internal_value(self, data: object) -> ResultValue:
+ if isinstance(data, bool):
+ return data
+ if isinstance(data, (int, float)):
+ try:
+ value = float(data)
+ except OverflowError as error:
+ raise serializers.ValidationError("Provide a finite number.") from error
+ if not math.isfinite(value):
+ raise serializers.ValidationError("Provide a finite number.")
+ return value
+ if isinstance(data, list) and data:
+ if any(not isinstance(value, str) or not value or len(value) > 128 for value in data):
+ raise serializers.ValidationError("Category keys must be nonempty strings of at most 128 characters.")
+ if any("\x00" in value or any("\ud800" <= character <= "\udfff" for character in value) for value in data):
+ raise serializers.ValidationError("Category keys must contain valid Unicode without null characters.")
+ if len(set(data)) != len(data):
+ raise serializers.ValidationError("Category keys must be distinct.")
+ return sorted(data)
+ raise serializers.ValidationError("Provide a number, boolean, or nonempty array of category keys.")
+
+ def to_representation(self, value: ResultValue) -> ResultValue:
+ return value
+
+
+class ExperimentSubmissionSerializer(_StrictDataclassSerializer[ExperimentSubmission]):
+ id = _UUIDField(help_text="Caller-generated experiment UUID. Reuse it for exact retries.")
+ name = _StrictCharField(max_length=400, help_text="Display name for this experiment execution.")
+ started_at = serializers.DateTimeField(help_text="Execution start time in ISO 8601 format, supplied by the caller.")
+ run_source = serializers.ChoiceField(
+ choices=OfflineExperiment.RunSource.choices,
+ required=False,
+ allow_null=True,
+ allow_blank=False,
+ help_text="Where the execution started: ci, local, or scheduled. Omit or use null when unknown.",
+ )
+ expected_item_count = _CountField(
+ required=False,
+ allow_null=True,
+ min_value=0,
+ max_value=2**63 - 1,
+ help_text="Expected number of distinct items. Completion must match this count when supplied.",
+ )
+ expected_result_count = _CountField(
+ required=False,
+ allow_null=True,
+ min_value=0,
+ max_value=2**63 - 1,
+ help_text="Expected number of distinct item/scorer-version results, including non-success statuses.",
+ )
+ suite_key = _identifier_field("Stable identifier for comparing executions of the same evaluation suite.")
+ dataset_source = _identifier_field(
+ "Source of an external dataset. Hosted dataset provenance is derived from its revision."
+ )
+ dataset_identifier = _identifier_field("Stable identifier for the external dataset.")
+ dataset_revision_identifier = _identifier_field("Pinned revision identifier of the external dataset.")
+ dataset_revision_id = _UUIDField(
+ required=False, allow_null=True, help_text="UUID of a hosted dataset revision in this project."
+ )
+ application_version = _identifier_field("Version of the application under evaluation.")
+ model_version = _identifier_field("Version of the model under evaluation.")
+ prompt_version = _identifier_field("Version of the prompt under evaluation.")
+
+ class Meta:
+ dataclass = ExperimentSubmission
+
+
+class ItemSubmissionSerializer(_StrictDataclassSerializer[ItemSubmission]):
+ id = _UUIDField(help_text="Caller-generated UUID for one input/output execution. Reuse for exact retries.")
+ case_key = _identifier_field("Stable case identifier for matching inputs across experiments.")
+ trial = _identifier_field("Identifier for a repeated execution of the same case.")
+ dataset_item_identifier = _identifier_field("Stable item identifier in an external dataset.")
+ dataset_item_version_identifier = _identifier_field("Pinned item-version identifier in an external dataset.")
+ dataset_item_version_id = _UUIDField(
+ required=False,
+ allow_null=True,
+ help_text="UUID of the hosted item version in the experiment's dataset revision.",
+ )
+ application_trace_id = _identifier_field(
+ "Trace identifier for the application execution that produced this output."
+ )
+ payload = ItemPayloadField(
+ required=False,
+ help_text="Optional input/output payload, up to 1 MiB and 32 JSON levels. Omission, {} and null properties differ.",
+ )
+
+ class Meta:
+ dataclass = ItemSubmission
+
+
+class ResultSubmissionSerializer(_StrictDataclassSerializer[ResultSubmission]):
+ item_id = _UUIDField(help_text="UUID of an item declared in this request or already accepted in this experiment.")
+ scorer_version_id = _UUIDField(help_text="Exact UUID of an existing scorer version in this project.")
+ status = serializers.ChoiceField(
+ choices=OfflineEvaluationResult.Status.choices, help_text="Outcome of this scorer execution."
+ )
+ value = ResultValueField(
+ required=False,
+ allow_null=True,
+ help_text="Required for ok: finite number, boolean, or distinct category keys matching the scorer version.",
+ )
+ error_code = _identifier_field("Optional stable error code, permitted only for error outcomes.", max_length=128)
+ evaluator_trace_id = _identifier_field("Trace identifier of the evaluator that produced this result.")
+ evaluated_at = serializers.DateTimeField(
+ required=False, allow_null=True, help_text="Caller-supplied evaluation time in ISO 8601 format."
+ )
+ payload = ResultPayloadField(
+ required=False,
+ help_text="Optional reasoning, error message, and metadata, up to 256 KiB and 32 JSON levels.",
+ )
+
+ class Meta:
+ dataclass = ResultSubmission
+
+ def validate(self, attrs: ResultSubmission) -> ResultSubmission:
+ errors: dict[str, list[str] | dict[str, list[str]]] = {}
+ if attrs.status == "ok" and attrs.value is None:
+ errors["value"] = ["A score is required for an ok result."]
+ if attrs.status != "ok" and attrs.value is not None:
+ errors["value"] = ["Only an ok result may contain a score."]
+ if attrs.status != "error" and attrs.error_code is not None:
+ errors["error_code"] = ["Only an error result may contain an error code."]
+ if attrs.status != "error" and attrs.payload and attrs.payload.get("error_message") is not None:
+ errors["payload"] = {"error_message": ["Only an error result may contain an error message."]}
+ if errors:
+ raise serializers.ValidationError(errors)
+ return attrs
+
+
+class UploadSubmissionSerializer(_StrictDataclassSerializer[UploadSubmission]):
+ items = serializers.ListField(
+ child=ItemSubmissionSerializer(),
+ required=False,
+ max_length=MAX_UPLOAD_ITEMS,
+ help_text="Complete immutable declarations for referenced items. Omit existing items to reuse them without a payload.",
+ )
+ results = serializers.ListField(
+ child=ResultSubmissionSerializer(),
+ allow_empty=False,
+ min_length=1,
+ max_length=MAX_UPLOAD_RESULTS,
+ help_text="One to 1,000 unique item/scorer-version results. The entire request commits atomically.",
+ )
+
+ class Meta:
+ dataclass = UploadSubmission
+
+ def validate(self, attrs: UploadSubmission) -> UploadSubmission:
+ item_ids: set[UUID] = set()
+ item_errors: dict[str, dict[str, list[str]]] = {}
+ referenced_ids = {result.item_id for result in attrs.results}
+ for index, item in enumerate(attrs.items):
+ if item.id in item_ids:
+ item_errors[str(index)] = {"id": ["Each item may be declared only once per request."]}
+ elif item.id not in referenced_ids:
+ item_errors[str(index)] = {
+ "id": ["Every declared item must be referenced by a result in this request."]
+ }
+ item_ids.add(item.id)
+ result_ids: set[tuple[UUID, UUID]] = set()
+ result_errors: dict[str, dict[str, list[str]]] = {}
+ for index, result in enumerate(attrs.results):
+ identity = (result.item_id, result.scorer_version_id)
+ if identity in result_ids:
+ result_errors[str(index)] = {
+ "scorer_version_id": ["Each item/scorer-version pair may appear only once per request."]
+ }
+ result_ids.add(identity)
+ errors = {}
+ if item_errors:
+ errors["items"] = item_errors
+ if result_errors:
+ errors["results"] = result_errors
+ if errors:
+ raise serializers.ValidationError(errors)
+ return attrs
diff --git a/products/ai_observability/backend/api/offline_experiments.py b/products/ai_observability/backend/api/offline_experiments.py
new file mode 100644
index 000000000000..ef9cb6a35d33
--- /dev/null
+++ b/products/ai_observability/backend/api/offline_experiments.py
@@ -0,0 +1,280 @@
+from dataclasses import asdict
+from typing import TYPE_CHECKING, TypedDict, cast
+from uuid import UUID
+
+from drf_spectacular.utils import OpenApiParameter
+from prometheus_client import Counter
+from rest_framework import serializers, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import ErrorDetail, NotFound, ValidationError
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.settings import api_settings
+
+from posthog.api.mixins import TypedRequest, validated_request
+from posthog.api.monitoring import monitor
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.auth import ProjectSecretAPIKeyAuthentication
+from posthog.permissions import AccessControlPermission, PostHogFeatureFlagPermission, is_service_auth
+
+from products.ai_observability.backend.api.metrics import llma_track_latency
+from products.ai_observability.backend.api.offline_experiment_access import (
+ OfflineEvaluationIngestionBurstThrottle,
+ OfflineEvaluationIngestionSustainedThrottle,
+ OfflineEvaluationIngestionTeamBurstThrottle,
+ OfflineEvaluationIngestionTeamSustainedThrottle,
+)
+from products.ai_observability.backend.api.offline_experiment_parser import OfflineEvaluationJSONParser
+from products.ai_observability.backend.api.offline_experiment_serializers import (
+ ExperimentSubmissionSerializer,
+ UploadSubmissionSerializer,
+)
+from products.ai_observability.backend.models.offline_evaluations import OfflineExperiment
+from products.ai_observability.backend.offline_evaluation_service import (
+ ExperimentReceipt,
+ OfflineEvaluationConflict,
+ OfflineEvaluationIngestionService,
+ OfflineEvaluationNotFound,
+ OfflineEvaluationValidationError,
+ OfflineExperimentService,
+)
+from products.ai_observability.backend.offline_evaluation_types import ExperimentSubmission, UploadSubmission
+
+if TYPE_CHECKING:
+ from products.access_control.backend.facade.user_access_control import UserAccessControl
+
+OFFLINE_UPLOAD_RESULTS = Counter(
+ "aio_offline_upload_results_total", "Acknowledged offline evaluation results", labelnames=["outcome"]
+)
+OFFLINE_UPLOAD_ERRORS = Counter(
+ "aio_offline_upload_errors_total", "Rejected offline evaluation API requests", labelnames=["outcome"]
+)
+
+
+class ExperimentReceiptSerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="Stable experiment UUID supplied at creation.")
+ status = serializers.ChoiceField(
+ choices=OfflineExperiment.Status.choices, help_text="Current upload lifecycle state."
+ )
+ created = serializers.BooleanField(help_text="Whether this request created the experiment.")
+ started_at = serializers.DateTimeField(help_text="Caller-supplied execution start time.")
+ created_at = serializers.DateTimeField(help_text="Time the experiment was first accepted.")
+ finished_at = serializers.DateTimeField(allow_null=True, help_text="Server closure time; null while uploading.")
+ expected_item_count = serializers.IntegerField(allow_null=True, help_text="Declared item count, when supplied.")
+ expected_result_count = serializers.IntegerField(allow_null=True, help_text="Declared result count, when supplied.")
+ accepted_item_count = serializers.IntegerField(help_text="Number of unique accepted items.")
+ accepted_result_count = serializers.IntegerField(help_text="Number of unique accepted results across all statuses.")
+
+
+class ItemReceiptSerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="Accepted item UUID.")
+ created = serializers.BooleanField(help_text="Whether this upload created the item.")
+ accepted_at = serializers.DateTimeField(help_text="Original server acceptance time, unchanged on retry.")
+
+
+class ResultReceiptSerializer(ItemReceiptSerializer):
+ item_id = serializers.UUIDField(help_text="Item this result evaluates.")
+ scorer_version_id = serializers.UUIDField(help_text="Pinned scorer version used by this result.")
+
+
+class UploadReceiptSerializer(serializers.Serializer):
+ items = ItemReceiptSerializer(many=True, help_text="One acknowledgment per referenced item.")
+ results = ResultReceiptSerializer(many=True, help_text="Acknowledgments in the submitted result order.")
+
+
+class OfflineEvaluationValidationErrorSerializer(serializers.Serializer):
+ code = serializers.CharField(help_text="Stable validation error code.")
+ detail = serializers.CharField(help_text="Explanation of the invalid value.")
+ attr = serializers.CharField(
+ allow_null=True, help_text="Invalid field path, with dot-separated fields and zero-based batch indexes."
+ )
+
+
+class OfflineEvaluationErrorSerializer(serializers.Serializer):
+ type = serializers.CharField(required=False, help_text="Error category for standard API errors.")
+ code = serializers.CharField(help_text="Stable error code.")
+ detail = serializers.CharField(help_text="Explanation of the rejected request.")
+ attr = serializers.CharField(
+ required=False, allow_null=True, help_text="Invalid field, including batch entry index."
+ )
+ expected_item_count = serializers.IntegerField(required=False, allow_null=True, help_text="Declared item count.")
+ expected_result_count = serializers.IntegerField(
+ required=False, allow_null=True, help_text="Declared result count."
+ )
+ accepted_item_count = serializers.IntegerField(required=False, help_text="Accepted items at failed completion.")
+ accepted_result_count = serializers.IntegerField(required=False, help_text="Accepted results at failed completion.")
+
+ def get_fields(self) -> dict[str, serializers.Field]:
+ fields = super().get_fields()
+ fields["errors"] = OfflineEvaluationValidationErrorSerializer(
+ many=True, required=False, help_text="All validation errors found in the request."
+ )
+ return fields
+
+
+class EmptyOfflineExperimentSerializer(serializers.Serializer):
+ def validate(self, attrs: dict[str, object]) -> dict[str, object]:
+ if self.initial_data:
+ raise serializers.ValidationError("This operation does not accept fields.")
+ return attrs
+
+
+class ValidationErrorEntry(TypedDict):
+ code: str
+ detail: str
+ attr: str | None
+
+
+def _validation_errors(detail: object, path: tuple[str, ...] = ()) -> list[ValidationErrorEntry]:
+ if isinstance(detail, dict):
+ errors: list[ValidationErrorEntry] = []
+ for field, value in cast(dict[str | int, object], detail).items():
+ field_path = path if field in (api_settings.NON_FIELD_ERRORS_KEY, "__all__") else (*path, str(field))
+ errors.extend(_validation_errors(value, field_path))
+ return errors
+ if isinstance(detail, list):
+ errors = []
+ for index, value in enumerate(cast(list[object], detail)):
+ item_path = (*path, str(index)) if isinstance(value, dict | list) else path
+ errors.extend(_validation_errors(value, item_path))
+ return errors
+ code = (detail.code or "invalid") if isinstance(detail, ErrorDetail) else "invalid"
+ return [
+ {"code": "invalid_input" if code == "invalid" else code, "detail": str(detail), "attr": ".".join(path) or None}
+ ]
+
+
+def _experiment_response(receipt: ExperimentReceipt, *, status: int = 200) -> Response:
+ experiment = receipt.experiment
+ return Response(
+ ExperimentReceiptSerializer(
+ {
+ "id": experiment.id,
+ "status": experiment.status,
+ "created": receipt.created,
+ "started_at": experiment.started_at,
+ "created_at": experiment.created_at,
+ "finished_at": experiment.finished_at,
+ **asdict(receipt.counts),
+ }
+ ).data,
+ status=status,
+ )
+
+
+ERROR_RESPONSES = dict.fromkeys((400, 401, 403, 404, 409, 413, 429), OfflineEvaluationErrorSerializer)
+
+
+EXPERIMENT_ID_PARAMETER = OpenApiParameter("id", UUID, OpenApiParameter.PATH, description="Experiment UUID.")
+
+
+class OfflineExperimentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "evaluation"
+ required_scopes = ["offline_evaluation_ingestion:write"]
+ scope_object_write_actions = ["create", "upload", "complete", "fail"]
+ requires_resource_level_access = True
+ authentication_classes = [ProjectSecretAPIKeyAuthentication]
+ psak_allowed_actions = ["create", "upload", "complete", "fail"]
+ permission_classes = [AccessControlPermission, PostHogFeatureFlagPermission]
+ posthog_feature_flag = "ai-observability-offline-evaluations"
+ parser_classes = [OfflineEvaluationJSONParser]
+ throttle_classes = [
+ OfflineEvaluationIngestionBurstThrottle,
+ OfflineEvaluationIngestionSustainedThrottle,
+ OfflineEvaluationIngestionTeamBurstThrottle,
+ OfflineEvaluationIngestionTeamSustainedThrottle,
+ ]
+ serializer_class = ExperimentSubmissionSerializer
+ http_method_names = ["post", "head", "options"]
+
+ def _reference_access_control(self) -> "UserAccessControl | None":
+ return None if is_service_auth(self.request) else self.user_access_control
+
+ def handle_exception(self, exc: Exception) -> Response:
+ if isinstance(exc, OfflineEvaluationConflict):
+ OFFLINE_UPLOAD_ERRORS.labels(outcome="conflict").inc()
+ return Response(
+ OfflineEvaluationErrorSerializer(
+ {
+ "code": exc.code,
+ "detail": exc.detail,
+ "attr": exc.field,
+ **(asdict(exc.counts) if exc.counts else {}),
+ }
+ ).data,
+ status=409,
+ )
+ if isinstance(exc, OfflineEvaluationValidationError):
+ exc = ValidationError(exc.errors)
+ elif isinstance(exc, OfflineEvaluationNotFound):
+ exc = NotFound("Experiment not found.")
+ response = super().handle_exception(exc)
+ if isinstance(exc, ValidationError):
+ errors = _validation_errors(exc.detail)
+ if errors:
+ response.data.update(errors[0], errors=errors)
+ OFFLINE_UPLOAD_ERRORS.labels(outcome="rejected" if response.status_code < 500 else "server_error").inc()
+ return response
+
+ @validated_request(
+ ExperimentSubmissionSerializer,
+ responses={200: ExperimentReceiptSerializer, 201: ExperimentReceiptSerializer, **ERROR_RESPONSES},
+ )
+ @llma_track_latency("aio_offline_experiment_create")
+ @monitor(feature=None, endpoint="aio_offline_experiment_create", method="POST")
+ def create(self, request: TypedRequest[ExperimentSubmission], **kwargs: object) -> Response:
+ receipt = OfflineExperimentService(
+ team_id=self.team_id, user_access_control=self._reference_access_control()
+ ).create(request.validated_data)
+ return _experiment_response(receipt, status=201 if receipt.created else 200)
+
+ def _experiment_id(self) -> UUID:
+ return cast(UUID, serializers.UUIDField().run_validation(self.kwargs["pk"]))
+
+ @validated_request(
+ UploadSubmissionSerializer,
+ parameters=[EXPERIMENT_ID_PARAMETER],
+ responses={200: UploadReceiptSerializer, **ERROR_RESPONSES},
+ )
+ @action(detail=True, methods=["post"])
+ @llma_track_latency("aio_offline_experiment_upload")
+ @monitor(feature=None, endpoint="aio_offline_experiment_upload", method="POST")
+ def upload(self, request: TypedRequest[UploadSubmission], **kwargs: object) -> Response:
+ receipt = OfflineEvaluationIngestionService(
+ team_id=self.team_id, user_access_control=self._reference_access_control()
+ ).upload(self._experiment_id(), request.validated_data)
+ for created in (True, False):
+ OFFLINE_UPLOAD_RESULTS.labels(outcome="created" if created else "duplicate").inc(
+ sum(result.created == created for result in receipt.results)
+ )
+ return Response(UploadReceiptSerializer(receipt).data)
+
+ @validated_request(
+ EmptyOfflineExperimentSerializer,
+ parameters=[EXPERIMENT_ID_PARAMETER],
+ responses={200: ExperimentReceiptSerializer, **ERROR_RESPONSES},
+ )
+ @action(detail=True, methods=["post"])
+ @llma_track_latency("aio_offline_experiment_complete")
+ @monitor(feature=None, endpoint="aio_offline_experiment_complete", method="POST")
+ def complete(self, request: Request, **kwargs: object) -> Response:
+ return _experiment_response(
+ OfflineExperimentService(team_id=self.team_id, user_access_control=self._reference_access_control()).close(
+ self._experiment_id(), status="completed"
+ )
+ )
+
+ @validated_request(
+ EmptyOfflineExperimentSerializer,
+ parameters=[EXPERIMENT_ID_PARAMETER],
+ responses={200: ExperimentReceiptSerializer, **ERROR_RESPONSES},
+ )
+ @action(detail=True, methods=["post"])
+ @llma_track_latency("aio_offline_experiment_fail")
+ @monitor(feature=None, endpoint="aio_offline_experiment_fail", method="POST")
+ def fail(self, request: Request, **kwargs: object) -> Response:
+ return _experiment_response(
+ OfflineExperimentService(team_id=self.team_id, user_access_control=self._reference_access_control()).close(
+ self._experiment_id(), status="failed"
+ )
+ )
diff --git a/products/ai_observability/backend/api/test/test_offline_experiment_parser.py b/products/ai_observability/backend/api/test/test_offline_experiment_parser.py
new file mode 100644
index 000000000000..13e958533aea
--- /dev/null
+++ b/products/ai_observability/backend/api/test/test_offline_experiment_parser.py
@@ -0,0 +1,63 @@
+from io import BytesIO
+from types import SimpleNamespace
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from rest_framework.exceptions import ParseError
+
+from products.ai_observability.backend.api.offline_experiment_parser import (
+ MAX_UPLOAD_BODY_BYTES,
+ OfflineEvaluationJSONParser,
+ OfflineEvaluationRequestTooLarge,
+)
+
+
+class TestOfflineEvaluationJSONParser(SimpleTestCase):
+ @parameterized.expand([("missing", None), ("understated", "1"), ("overstated", str(MAX_UPLOAD_BODY_BYTES * 2))])
+ def test_body_read_is_bounded_independently_of_content_length(self, _name: str, content_length: str | None) -> None:
+ metadata = {} if content_length is None else {"CONTENT_LENGTH": content_length}
+ stream = BytesIO(b" " * (MAX_UPLOAD_BODY_BYTES + 100))
+ with self.assertRaises(OfflineEvaluationRequestTooLarge) as error:
+ OfflineEvaluationJSONParser().parse(stream, parser_context={"request": SimpleNamespace(META=metadata)})
+ self.assertEqual(error.exception.status_code, 413)
+ self.assertEqual(stream.tell(), MAX_UPLOAD_BODY_BYTES + 1)
+
+ def test_body_exactly_at_limit_is_accepted(self) -> None:
+ body = b'{"value":0}'
+ stream = BytesIO(body + b" " * (MAX_UPLOAD_BODY_BYTES - len(body)))
+ self.assertEqual(OfflineEvaluationJSONParser().parse(stream), {"value": 0})
+
+ @parameterized.expand(
+ [
+ ("malformed", b'{"value":'),
+ ("null_body", b"null"),
+ ("array_body", b"[]"),
+ ("string_body", b'"experiment"'),
+ ("number_body", b"1"),
+ ("boolean_body", b"true"),
+ ("invalid_encoding", b'{"value":"\xff"}'),
+ ("nan", b'{"value":NaN}'),
+ ("infinity", b'{"value":Infinity}'),
+ ("negative_infinity", b'{"value":-Infinity}'),
+ ("overflow", b'{"value":1e999}'),
+ ("underflow", b'{"value":1e-999}'),
+ ("negative_underflow", b'{"value":-1e-999}'),
+ ("huge_exponent", b'{"value":1e-999999999999999999999999}'),
+ ("nested_nonfinite", b'{"items":[{"payload":{"input":{"value":NaN}}}]}'),
+ ("excessive_nesting", b'{"items":' + b"[" * 100_000 + b"0" + b"]" * 100_000 + b"}"),
+ ]
+ )
+ def test_invalid_json_and_unrepresentable_numbers_are_parse_errors(self, _name: str, body: bytes) -> None:
+ with self.assertRaises(ParseError):
+ OfflineEvaluationJSONParser().parse(BytesIO(body))
+
+ def test_preserves_false_zero_unicode_and_representable_small_numbers(self) -> None:
+ body = '{"boolean":false,"integer":0,"float":0.0,"zero_exponent":0e-999,"smallest":5e-324,"text":"café 🦔"}'
+ data = OfflineEvaluationJSONParser().parse(BytesIO(body.encode("utf-8")))
+ self.assertIs(data["boolean"], False)
+ self.assertEqual(data["integer"], 0)
+ self.assertEqual(data["float"], 0.0)
+ self.assertEqual(data["zero_exponent"], 0.0)
+ self.assertEqual(data["smallest"], 5e-324)
+ self.assertEqual(data["text"], "café 🦔")
diff --git a/products/ai_observability/backend/api/test/test_offline_experiment_serializers.py b/products/ai_observability/backend/api/test/test_offline_experiment_serializers.py
new file mode 100644
index 000000000000..f20c321b7854
--- /dev/null
+++ b/products/ai_observability/backend/api/test/test_offline_experiment_serializers.py
@@ -0,0 +1,227 @@
+from uuid import UUID, uuid4
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.ai_observability.backend.api.offline_experiment_serializers import (
+ MAX_ITEM_PAYLOAD_BYTES,
+ MAX_JSON_DEPTH,
+ MAX_RESULT_PAYLOAD_BYTES,
+ ExperimentSubmissionSerializer,
+ ItemSubmissionSerializer,
+ ResultSubmissionSerializer,
+ UploadSubmissionSerializer,
+)
+from products.ai_observability.backend.offline_evaluation_types import JSONValue, ResultValue
+
+ITEM_ID = UUID("01922222-2222-7222-8222-222222222222")
+SCORER_VERSION_ID = UUID("01923333-3333-7333-8333-333333333333")
+
+
+class TestOfflineExperimentSubmissionSerializers(SimpleTestCase):
+ def experiment_data(self, **overrides: object) -> dict[str, object]:
+ return {"id": str(uuid4()), "name": "Answer quality", "started_at": "2026-09-24T10:00:00Z", **overrides}
+
+ def result_data(self, **overrides: object) -> dict[str, object]:
+ return {
+ "item_id": str(ITEM_ID),
+ "scorer_version_id": str(SCORER_VERSION_ID),
+ "status": "ok",
+ "value": True,
+ **overrides,
+ }
+
+ @parameterized.expand(
+ [
+ ("run_source", ""),
+ ("run_source", "cron"),
+ ("suite_key", ""),
+ ("suite_key", 12),
+ ("name", 12),
+ ("name", "\x00"),
+ ("model_version", "\ud800"),
+ ("expected_item_count", True),
+ ("expected_item_count", "10"),
+ ("expected_result_count", 1.0),
+ ("expected_result_count", -1),
+ ("expected_result_count", 2**63),
+ ("id", 123),
+ ("id", "not-a-uuid"),
+ ("dataset_revision_id", 123),
+ ("team_id", 1),
+ ("submission_fingerprint", "0" * 64),
+ ("finished_at", "2026-09-24T10:01:00Z"),
+ ]
+ )
+ def test_experiment_rejects_invalid_or_server_owned_fields(self, field: str, value: object) -> None:
+ serializer = ExperimentSubmissionSerializer(data=self.experiment_data(**{field: value}))
+ self.assertFalse(serializer.is_valid())
+ self.assertIn(field, serializer.errors)
+
+ def test_omitted_and_null_optional_experiment_fields_have_the_same_meaning(self) -> None:
+ body = self.experiment_data()
+ omitted = ExperimentSubmissionSerializer(data=body)
+ explicit = ExperimentSubmissionSerializer(data={**body, "run_source": None, "suite_key": None})
+ self.assertTrue(omitted.is_valid(), omitted.errors)
+ self.assertTrue(explicit.is_valid(), explicit.errors)
+ self.assertEqual(omitted.validated_data, explicit.validated_data)
+
+ @parameterized.expand([(0, 0.0), (1.234567890123, 1.234567890123), (False, False), (["z", "a"], ["a", "z"])])
+ def test_result_preserves_score_types_and_normalizes_category_order(
+ self, supplied: object, expected: ResultValue
+ ) -> None:
+ serializer = ResultSubmissionSerializer(data=self.result_data(value=supplied))
+ self.assertTrue(serializer.is_valid(), serializer.errors)
+ self.assertEqual(serializer.validated_data.value, expected)
+ self.assertIs(type(serializer.validated_data.value), type(expected))
+
+ @parameterized.expand(
+ [
+ ("string_number", "0.5"),
+ ("string_boolean", "true"),
+ ("null", None),
+ ("nan", float("nan")),
+ ("infinity", float("inf")),
+ ("overflow", 10**400),
+ ("empty_categories", []),
+ ("duplicate_categories", ["a", "a"]),
+ ("coerced_categories", [1]),
+ ("empty_category", [""]),
+ ("long_category", ["a" * 129]),
+ ("nul_category", ["\x00"]),
+ ("surrogate_category", ["\ud800"]),
+ ("object", {}),
+ ]
+ )
+ def test_result_rejects_invalid_score_types(self, _name: str, value: object) -> None:
+ serializer = ResultSubmissionSerializer(data=self.result_data(value=value))
+ self.assertFalse(serializer.is_valid())
+ self.assertIn("value", serializer.errors)
+
+ @parameterized.expand(
+ [
+ ({"status": "error", "value": 0}, {"value"}),
+ ({"status": "skipped", "value": False}, {"value"}),
+ ({"status": "not_applicable", "value": ["a"]}, {"value"}),
+ ({"error_code": "timeout"}, {"error_code"}),
+ ({"payload": {"error_message": "Timed out"}}, {"payload"}),
+ ({"id": str(uuid4())}, {"id"}),
+ ({"scorer_definition_id": str(uuid4())}, {"scorer_definition_id"}),
+ ({"accepted_at": "2026-09-24T10:00:00Z"}, {"accepted_at"}),
+ ({"payload_state": "available"}, {"payload_state"}),
+ (
+ {
+ "status": "skipped",
+ "value": False,
+ "error_code": "timeout",
+ "payload": {"error_message": "Timed out"},
+ },
+ {"value", "error_code", "payload"},
+ ),
+ ]
+ )
+ def test_result_status_invariants_and_server_owned_fields(
+ self, overrides: dict[str, object], fields: set[str]
+ ) -> None:
+ serializer = ResultSubmissionSerializer(data=self.result_data(**overrides))
+ self.assertFalse(serializer.is_valid())
+ self.assertEqual(set(serializer.errors), fields)
+
+ def test_error_without_score_accepts_error_details(self) -> None:
+ data = self.result_data(status="error", error_code="timeout", payload={"error_message": "Timed out"})
+ del data["value"]
+ serializer = ResultSubmissionSerializer(data=data)
+ self.assertTrue(serializer.is_valid(), serializer.errors)
+ self.assertIsNone(serializer.validated_data.value)
+
+ def test_payload_omission_empty_object_and_null_property_remain_distinct(self) -> None:
+ values = []
+ payloads: list[dict[str, object]] = [{}, {"payload": {}}, {"payload": {"input": None}}]
+ for payload in payloads:
+ serializer = ItemSubmissionSerializer(data={"id": str(ITEM_ID), **payload})
+ self.assertTrue(serializer.is_valid(), serializer.errors)
+ values.append(serializer.validated_data.payload)
+ self.assertEqual(values, [None, {}, {"input": None}])
+
+ @parameterized.expand(
+ [
+ ("null_object", None),
+ ("array_object", []),
+ ("unknown_property", {"unknown": True}),
+ ("metadata_type", {"metadata": []}),
+ ("nested_nan", {"input": {"value": float("nan")}}),
+ ("nested_nul", {"input": ["\x00"]}),
+ ("nul_key", {"input": {"\x00": True}}),
+ ("surrogate_value", {"input": "\ud800"}),
+ ("surrogate_key", {"input": {"\ud800": None}}),
+ ("non_json_value", {"input": {"bytes": b"content"}}),
+ ]
+ )
+ def test_payload_rejects_values_that_cannot_be_safely_stored(self, _name: str, payload: object) -> None:
+ serializer = ItemSubmissionSerializer(data={"id": str(ITEM_ID), "payload": payload})
+ self.assertFalse(serializer.is_valid())
+ self.assertIn("payload", serializer.errors)
+
+ def test_payload_nesting_limit_includes_the_enclosing_object(self) -> None:
+ value: JSONValue = None
+ for _ in range(MAX_JSON_DEPTH - 1):
+ value = [value]
+ at_limit = ItemSubmissionSerializer(data={"id": str(ITEM_ID), "payload": {"input": value}})
+ self.assertTrue(at_limit.is_valid(), at_limit.errors)
+ too_deep = ItemSubmissionSerializer(data={"id": str(ITEM_ID), "payload": {"input": [value]}})
+ self.assertFalse(too_deep.is_valid())
+ self.assertIn("payload", too_deep.errors)
+
+ def test_payload_limits_count_utf8_bytes_and_apply_separately(self) -> None:
+ item = ItemSubmissionSerializer(
+ data={"id": str(ITEM_ID), "payload": {"input": "é" * (MAX_ITEM_PAYLOAD_BYTES // 2)}}
+ )
+ result = ResultSubmissionSerializer(
+ data=self.result_data(payload={"reasoning": "a" * MAX_RESULT_PAYLOAD_BYTES})
+ )
+ for serializer in (item, result):
+ self.assertFalse(serializer.is_valid())
+ self.assertIn("payload", serializer.errors)
+
+ def test_shared_item_supports_multiple_scorers_and_omitted_declarations(self) -> None:
+ serializer = UploadSubmissionSerializer(
+ data={
+ "items": [{"id": str(ITEM_ID), "payload": {"input": "question", "output": "answer"}}],
+ "results": [self.result_data(), self.result_data(scorer_version_id=str(uuid4()))],
+ }
+ )
+ self.assertTrue(serializer.is_valid(), serializer.errors)
+ self.assertEqual(len(serializer.validated_data.items), 1)
+ self.assertEqual(len(serializer.validated_data.results), 2)
+ reference = UploadSubmissionSerializer(data={"results": [self.result_data()]})
+ self.assertTrue(reference.is_valid(), reference.errors)
+ self.assertEqual(reference.validated_data.items, [])
+
+ @parameterized.expand(
+ [("duplicate_items", "items"), ("duplicate_results", "results"), ("unreferenced_item", "items")]
+ )
+ def test_upload_rejects_ambiguous_or_unreferenced_declarations(self, case: str, field: str) -> None:
+ data: dict[str, object] = {"items": [{"id": str(ITEM_ID)}], "results": [self.result_data()]}
+ if case == "duplicate_items":
+ data["items"] = [{"id": str(ITEM_ID)}, {"id": str(ITEM_ID)}]
+ elif case == "duplicate_results":
+ data["results"] = [self.result_data(), self.result_data()]
+ else:
+ data["items"] = [{"id": str(uuid4())}]
+ serializer = UploadSubmissionSerializer(data=data)
+ self.assertFalse(serializer.is_valid())
+ self.assertIn(field, serializer.errors)
+
+ @parameterized.expand([("empty_results", "results"), ("too_many_results", "results"), ("too_many_items", "items")])
+ def test_upload_batch_limits(self, case: str, field: str) -> None:
+ data: dict[str, object] = {"results": [self.result_data()]}
+ if case == "empty_results":
+ data["results"] = []
+ elif case == "too_many_results":
+ data["results"] = [self.result_data()] * 1001
+ else:
+ data["items"] = [{"id": str(ITEM_ID)}] * 1001
+ serializer = UploadSubmissionSerializer(data=data)
+ self.assertFalse(serializer.is_valid())
+ self.assertIn(field, serializer.errors)
diff --git a/products/ai_observability/backend/api/test/test_offline_experiment_throttles.py b/products/ai_observability/backend/api/test/test_offline_experiment_throttles.py
new file mode 100644
index 000000000000..409f0b2dea3b
--- /dev/null
+++ b/products/ai_observability/backend/api/test/test_offline_experiment_throttles.py
@@ -0,0 +1,126 @@
+from typing import cast
+
+from unittest.mock import patch
+
+from django.core.cache import cache
+from django.test import SimpleTestCase, override_settings
+
+from parameterized import parameterized
+from rest_framework.authentication import BaseAuthentication, SessionAuthentication
+from rest_framework.request import Request
+from rest_framework.test import APIRequestFactory
+from rest_framework.views import APIView
+
+from posthog.auth import PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthentication, ProjectSecretAPIKeyUser
+from posthog.models import Team, User
+from posthog.models.project_secret_api_key import ProjectSecretAPIKey
+from posthog.rate_limit import PersonalApiKeyRateThrottle
+
+from products.ai_observability.backend.api.offline_experiment_access import (
+ OfflineEvaluationIngestionBurstThrottle,
+ OfflineEvaluationIngestionSustainedThrottle,
+ OfflineEvaluationIngestionTeamBurstThrottle,
+ OfflineEvaluationIngestionTeamSustainedThrottle,
+)
+
+
+class _ProjectView(APIView):
+ def __init__(self, team_id: int = 1, parent_team_id: int | None = None) -> None:
+ super().__init__()
+ self.team_id = team_id
+ self.team = Team(id=team_id, parent_team_id=parent_team_id)
+
+
+class _AuthenticatedRequest(Request):
+ _authenticator: BaseAuthentication
+
+
+@override_settings(
+ CACHES={
+ "default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache", "LOCATION": "offline-eval-throttles"}
+ }
+)
+class TestOfflineExperimentThrottles(SimpleTestCase):
+ def setUp(self) -> None:
+ cache.clear()
+ self.addCleanup(cache.clear)
+ self.enterContext(patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True))
+ self.enterContext(patch("posthog.rate_limit.team_is_allowed_to_bypass_throttle", return_value=False))
+
+ def _request(self, auth_kind: str, identity: int = 1, team_id: int = 1) -> Request:
+ request = _AuthenticatedRequest(
+ APIRequestFactory().post(f"/api/projects/{team_id}/offline_experiments/", {}, format="json")
+ )
+ request.user = User(id=identity)
+ if auth_kind == "session":
+ request._authenticator = SessionAuthentication()
+ elif auth_kind == "personal_key":
+ auth = PersonalAPIKeyAuthentication()
+ auth.personal_api_key_hash = f"personal-key-{identity}"
+ request._authenticator = auth
+ elif auth_kind == "project_key":
+ project_auth = ProjectSecretAPIKeyAuthentication()
+ project_auth.project_secret_api_key = ProjectSecretAPIKey(
+ id=f"project-key-{identity}", team=Team(id=team_id)
+ )
+ request.user = cast(User, ProjectSecretAPIKeyUser(project_auth.project_secret_api_key))
+ request._authenticator = project_auth
+ else:
+ raise ValueError(auth_kind)
+ return cast(Request, request)
+
+ @parameterized.expand(
+ [
+ ("burst_session", OfflineEvaluationIngestionBurstThrottle, "session"),
+ ("burst_personal_key", OfflineEvaluationIngestionBurstThrottle, "personal_key"),
+ ("burst_project_key", OfflineEvaluationIngestionBurstThrottle, "project_key"),
+ ("sustained_session", OfflineEvaluationIngestionSustainedThrottle, "session"),
+ ("sustained_personal_key", OfflineEvaluationIngestionSustainedThrottle, "personal_key"),
+ ("sustained_project_key", OfflineEvaluationIngestionSustainedThrottle, "project_key"),
+ ]
+ )
+ def test_each_caller_is_throttled_independently(
+ self, _name: str, throttle_class: type[PersonalApiKeyRateThrottle], auth_kind: str
+ ) -> None:
+ view = _ProjectView()
+ with patch.object(throttle_class, "rate", "1/minute"):
+ self.assertTrue(throttle_class().allow_request(self._request(auth_kind), view))
+ self.assertFalse(throttle_class().allow_request(self._request(auth_kind), view))
+ self.assertTrue(throttle_class().allow_request(self._request(auth_kind, identity=2), view))
+
+ @parameterized.expand(
+ [
+ ("burst", OfflineEvaluationIngestionTeamBurstThrottle, False),
+ ("burst_child_environments", OfflineEvaluationIngestionTeamBurstThrottle, True),
+ ("sustained", OfflineEvaluationIngestionTeamSustainedThrottle, False),
+ ("sustained_child_environments", OfflineEvaluationIngestionTeamSustainedThrottle, True),
+ ]
+ )
+ def test_project_budget_is_shared_across_authentication_methods_and_environments(
+ self, _name: str, throttle_class: type[PersonalApiKeyRateThrottle], child_environments: bool
+ ) -> None:
+ view = _ProjectView()
+ personal_key_view = _ProjectView(team_id=2, parent_team_id=1) if child_environments else view
+ project_key_view = _ProjectView(team_id=3, parent_team_id=1) if child_environments else view
+ other_view = _ProjectView(team_id=4)
+ with patch.object(throttle_class, "rate", "2/minute"):
+ self.assertTrue(throttle_class().allow_request(self._request("session"), view))
+ self.assertTrue(
+ throttle_class().allow_request(
+ self._request("personal_key", team_id=personal_key_view.team_id), personal_key_view
+ )
+ )
+ self.assertFalse(
+ throttle_class().allow_request(
+ self._request("project_key", team_id=project_key_view.team_id), project_key_view
+ )
+ )
+ self.assertTrue(throttle_class().allow_request(self._request("project_key", team_id=4), other_view))
+
+ def test_unused_api_key_cannot_change_session_bucket(self) -> None:
+ view = _ProjectView()
+ request = self._request("session")
+ with patch.object(OfflineEvaluationIngestionBurstThrottle, "rate", "1/minute"):
+ self.assertTrue(OfflineEvaluationIngestionBurstThrottle().allow_request(request, view))
+ request.META["HTTP_AUTHORIZATION"] = "Bearer phx_unused_fake_key"
+ self.assertFalse(OfflineEvaluationIngestionBurstThrottle().allow_request(request, view))
diff --git a/products/ai_observability/backend/api/test/test_offline_experiments.py b/products/ai_observability/backend/api/test/test_offline_experiments.py
new file mode 100644
index 000000000000..82d3aa52a62f
--- /dev/null
+++ b/products/ai_observability/backend/api/test/test_offline_experiments.py
@@ -0,0 +1,476 @@
+from uuid import uuid4
+
+import pytest
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+from django.utils import timezone
+
+from drf_spectacular.generators import SchemaGenerator
+from parameterized import parameterized
+from rest_framework import status
+from rest_framework.exceptions import ErrorDetail, ValidationError
+from rest_framework.routers import SimpleRouter
+
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership, Project, User
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.project_secret_api_key import ProjectSecretAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.ai_observability.backend.api.offline_experiments import OfflineExperimentViewSet
+from products.ai_observability.backend.models.datasets import Dataset, DatasetItem, DatasetItemVersion, DatasetRevision
+from products.ai_observability.backend.models.offline_evaluations import (
+ OfflineEvaluationResult,
+ OfflineExperiment,
+ OfflineExperimentItem,
+)
+from products.ai_observability.backend.models.score_definitions import ScoreDefinition
+
+
+class TestOfflineExperimentsAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.feature_flag = self.enterContext(
+ patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True)
+ )
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+
+ def _endpoint(self, experiment_id: str = "", action: str = "", team_id: int | None = None) -> str:
+ base = f"/api/projects/{team_id or self.team.id}/ai_observability/offline_experiments/"
+ return f"{base}{experiment_id}/{action}/" if experiment_id else base
+
+ def _authenticate(self, auth_kind: str, scopes: list[str] | None = None, user: User | None = None) -> None:
+ self.client.logout()
+ self.client.credentials()
+ user = user or self.user
+ scopes = scopes if scopes is not None else ["offline_evaluation_ingestion:write"]
+ if auth_kind == "session":
+ self.client.force_login(user)
+ return
+ if auth_kind == "personal_key":
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=user,
+ label="Offline evaluation test",
+ secure_value=hash_key_value(token),
+ scopes=scopes,
+ scoped_teams=[self.team.id],
+ )
+ elif auth_kind == "project_key":
+ token = f"phs_{uuid4().hex}"
+ ProjectSecretAPIKey.objects.create(
+ team=self.team,
+ label="Offline evaluation test",
+ secure_value=hash_key_value(token),
+ scopes=scopes,
+ )
+ else:
+ raise ValueError(auth_kind)
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
+
+ def _experiment_body(self) -> dict[str, object]:
+ return {"id": str(uuid4()), "name": "Answer quality", "started_at": timezone.now().isoformat()}
+
+ def _evaluation_member(self, access_level: str = "editor") -> OrganizationMembership:
+ member = User.objects.create_and_join(self.organization, "[email protected]", "test-password")
+ membership = OrganizationMembership.objects.get(user=member, organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="project",
+ resource_id=str(self.team.id),
+ access_level="member",
+ organization_member=None,
+ )
+ AccessControl.objects.create(
+ team=self.team,
+ resource="evaluation",
+ resource_id=None,
+ access_level=access_level,
+ organization_member=membership,
+ )
+ return membership
+
+ def _dataset_item_version(self) -> DatasetItemVersion:
+ dataset = Dataset.objects.for_team(self.team.id).create(team=self.team, name="Questions")
+ revision = DatasetRevision.objects.for_team(self.team.id).create(team=self.team, dataset=dataset, revision=1)
+ item = DatasetItem.objects.for_team(self.team.id).create(team=self.team, dataset=dataset)
+ return DatasetItemVersion.objects.for_team(self.team.id).create(
+ team=self.team,
+ dataset=dataset,
+ dataset_item=item,
+ dataset_revision=revision,
+ version=1,
+ input="What is 2 + 2?",
+ )
+
+ @parameterized.expand([("session",), ("personal_key",), ("project_key",)])
+ def test_ingestion_and_both_lifecycle_actions(self, auth_kind: str) -> None:
+ definition = ScoreDefinition.objects.create(team=self.team, name="Correct", kind="boolean")
+ version = definition.create_new_version(config={"true_label": "Yes", "false_label": "No"}, created_by=self.user)
+ self._authenticate(auth_kind)
+ body = self._experiment_body() | {"expected_item_count": 1, "expected_result_count": 1}
+ created = self.client.post(self._endpoint(), body, format="json")
+ self.assertEqual(created.status_code, status.HTTP_201_CREATED, created.data)
+ experiment_id = str(body["id"])
+ self.assertEqual(created.data["id"], experiment_id)
+
+ incomplete = self.client.post(self._endpoint(experiment_id, "complete"), {}, format="json")
+ self.assertEqual(incomplete.status_code, status.HTTP_409_CONFLICT, incomplete.data)
+ self.assertEqual(incomplete.data["code"], "expected_count_mismatch")
+ self.assertEqual(incomplete.data["expected_item_count"], 1)
+ self.assertEqual(incomplete.data["expected_result_count"], 1)
+ self.assertEqual(incomplete.data["accepted_item_count"], 0)
+ self.assertEqual(incomplete.data["accepted_result_count"], 0)
+
+ item_id = str(uuid4())
+ uploaded = self.client.post(
+ self._endpoint(experiment_id, "upload"),
+ {
+ "items": [{"id": item_id, "payload": {"input": "What is 2 + 2?", "output": "5"}}],
+ "results": [{"item_id": item_id, "scorer_version_id": str(version.id), "status": "ok", "value": False}],
+ },
+ format="json",
+ )
+ self.assertEqual(uploaded.status_code, status.HTTP_200_OK, uploaded.data)
+ result = OfflineEvaluationResult.objects.for_team(self.team.id).get(pk=uploaded.data["results"][0]["id"])
+ self.assertIs(result.boolean_value, False)
+ self.assertEqual(result.scorer_version_id, version.id)
+
+ completed = self.client.post(self._endpoint(experiment_id, "complete"), {}, format="json")
+ self.assertEqual(completed.status_code, status.HTTP_200_OK, completed.data)
+ self.assertEqual(completed.data["status"], "completed")
+ self.assertEqual(completed.data["accepted_item_count"], 1)
+ self.assertEqual(completed.data["accepted_result_count"], 1)
+
+ failed_body = self._experiment_body() | {"expected_result_count": 10}
+ self.assertEqual(
+ self.client.post(self._endpoint(), failed_body, format="json").status_code, status.HTTP_201_CREATED
+ )
+ failed = self.client.post(self._endpoint(str(failed_body["id"]), "fail"), {}, format="json")
+ self.assertEqual(failed.status_code, status.HTTP_200_OK, failed.data)
+ self.assertEqual(failed.data["status"], "failed")
+ self.assertEqual(failed.data["accepted_result_count"], 0)
+
+ @parameterized.expand(
+ [
+ ("personal_missing", "personal_key", []),
+ ("personal_read", "personal_key", ["offline_evaluation_ingestion:read"]),
+ ("personal_evaluation_write", "personal_key", ["evaluation:write"]),
+ ("project_missing", "project_key", []),
+ ("project_read", "project_key", ["offline_evaluation_ingestion:read"]),
+ ("project_evaluation_write", "project_key", ["evaluation:write"]),
+ ]
+ )
+ def test_ingestion_requires_its_own_write_scope(self, _name: str, auth_kind: str, scopes: list[str]) -> None:
+ self._authenticate(auth_kind, scopes=scopes)
+ response = self.client.post(self._endpoint(), self._experiment_body(), format="json")
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertFalse(OfflineExperiment.objects.for_team(self.team.id).exists())
+
+ @parameterized.expand([("personal_key",), ("project_key",)])
+ def test_project_scoped_key_cannot_write_to_another_project(self, auth_kind: str) -> None:
+ _, other_team = Project.objects.create_with_team(organization=self.organization, initiating_user=self.user)
+ self._authenticate(auth_kind)
+ response = self.client.post(self._endpoint(team_id=other_team.id), self._experiment_body(), format="json")
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertFalse(OfflineExperiment.objects.for_team(other_team.id).exists())
+
+ @parameterized.expand([("session",), ("personal_key",), ("project_key",)])
+ def test_rollout_flag_is_required_for_every_authentication_method(self, auth_kind: str) -> None:
+ self._authenticate(auth_kind)
+ self.feature_flag.return_value = False
+ response = self.client.post(self._endpoint(), self._experiment_body(), format="json")
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertFalse(OfflineExperiment.objects.for_team(self.team.id).exists())
+
+ @parameterized.expand(
+ [
+ ("session_viewer", "session", "viewer", status.HTTP_403_FORBIDDEN),
+ ("session_editor", "session", "editor", status.HTTP_201_CREATED),
+ ("personal_key_viewer", "personal_key", "viewer", status.HTTP_403_FORBIDDEN),
+ ("personal_key_editor", "personal_key", "editor", status.HTTP_201_CREATED),
+ ("project_key", "project_key", "none", status.HTTP_201_CREATED),
+ ]
+ )
+ def test_human_callers_require_evaluation_editor_access(
+ self, _name: str, auth_kind: str, access_level: str, expected_status: int
+ ) -> None:
+ membership = self._evaluation_member(access_level)
+ self._authenticate(auth_kind, user=membership.user)
+ response = self.client.post(self._endpoint(), self._experiment_body(), format="json")
+ self.assertEqual(response.status_code, expected_status, response.data)
+
+ @parameterized.expand(
+ [
+ ("session_object_denied", "session", "viewer", "none", False),
+ ("personal_object_denied", "personal_key", "viewer", "none", False),
+ ("resource_denied", "session", "none", None, False),
+ ("session_object_viewer", "session", "none", "viewer", True),
+ ("personal_object_viewer", "personal_key", "none", "viewer", True),
+ ("project_key", "project_key", "none", "none", True),
+ ]
+ )
+ def test_references_require_viewer_access(
+ self, _name: str, auth_kind: str, resource_access: str, object_access: str | None, allowed: bool
+ ) -> None:
+ membership = self._evaluation_member()
+ dataset_version = self._dataset_item_version()
+ definition = ScoreDefinition.objects.create(team=self.team, name="Quality", kind="numeric")
+ version = definition.create_new_version(config={"min": 1, "max": 5}, created_by=self.user)
+ AccessControl.objects.create(
+ team=self.team, resource="llm_analytics", access_level=resource_access, organization_member=membership
+ )
+ if object_access is not None:
+ for resource, resource_id in (("dataset", dataset_version.dataset_id), ("llm_analytics", definition.id)):
+ AccessControl.objects.create(
+ team=self.team,
+ resource=resource,
+ resource_id=str(resource_id),
+ access_level=object_access,
+ organization_member=membership,
+ )
+ self._authenticate(auth_kind, user=membership.user)
+ body = self._experiment_body() | {"dataset_revision_id": str(dataset_version.dataset_revision_id)}
+
+ created = self.client.post(self._endpoint(), body, format="json")
+ self.assertEqual(
+ created.status_code, status.HTTP_201_CREATED if allowed else status.HTTP_400_BAD_REQUEST, created.data
+ )
+ if not allowed:
+ missing = self.client.post(self._endpoint(), body | {"dataset_revision_id": str(uuid4())}, format="json")
+ self.assertEqual(created.data, missing.data)
+ self.assertFalse(OfflineExperiment.objects.for_team(self.team.id).exists())
+ body = self._experiment_body()
+ created = self.client.post(self._endpoint(), body, format="json")
+ self.assertEqual(created.status_code, status.HTTP_201_CREATED, created.data)
+
+ item: dict[str, object] = {"id": str(uuid4())}
+ if allowed:
+ item["dataset_item_version_id"] = str(dataset_version.id)
+ result = {
+ "item_id": item["id"],
+ "scorer_version_id": str(version.id),
+ "status": "ok",
+ "value": 2 if allowed else 0,
+ }
+ uploaded = self.client.post(
+ self._endpoint(str(body["id"]), "upload"), {"items": [item], "results": [result]}, format="json"
+ )
+ self.assertEqual(
+ uploaded.status_code, status.HTTP_200_OK if allowed else status.HTTP_400_BAD_REQUEST, uploaded.data
+ )
+ if allowed:
+ self.assertEqual(OfflineEvaluationResult.objects.for_team(self.team.id).get().scorer_version_id, version.id)
+ else:
+ missing = self.client.post(
+ self._endpoint(str(body["id"]), "upload"),
+ {"items": [item], "results": [result | {"scorer_version_id": str(uuid4())}]},
+ format="json",
+ )
+ self.assertEqual(uploaded.data, missing.data)
+ self.assertFalse(OfflineExperimentItem.objects.for_team(self.team.id).exists())
+ self.assertFalse(OfflineEvaluationResult.objects.for_team(self.team.id).exists())
+
+ @parameterized.expand([("session",), ("personal_key",)])
+ def test_revoked_reference_access_blocks_new_data_but_allows_retries_and_completion(self, auth_kind: str) -> None:
+ membership = self._evaluation_member()
+ dataset_version = self._dataset_item_version()
+ definition = ScoreDefinition.objects.create(team=self.team, name="Correct", kind="boolean")
+ version = definition.create_new_version(config={}, created_by=self.user)
+ for resource, resource_id in (("dataset", dataset_version.dataset_id), ("llm_analytics", definition.id)):
+ AccessControl.objects.create(
+ team=self.team,
+ resource=resource,
+ resource_id=str(resource_id),
+ access_level="viewer",
+ organization_member=membership,
+ )
+ self._authenticate(auth_kind, user=membership.user)
+ body = self._experiment_body() | {"dataset_revision_id": str(dataset_version.dataset_revision_id)}
+ created = self.client.post(self._endpoint(), body, format="json")
+ self.assertEqual(created.status_code, status.HTTP_201_CREATED, created.data)
+ experiment_id = str(body["id"])
+ item = {"id": str(uuid4()), "dataset_item_version_id": str(dataset_version.id)}
+ result = {"item_id": item["id"], "scorer_version_id": str(version.id), "status": "ok", "value": True}
+ upload = {"items": [item], "results": [result]}
+ accepted = self.client.post(self._endpoint(experiment_id, "upload"), upload, format="json")
+ self.assertEqual(accepted.status_code, status.HTTP_200_OK, accepted.data)
+
+ AccessControl.objects.filter(organization_member=membership, resource__in=["dataset", "llm_analytics"]).update(
+ access_level="none"
+ )
+ create_retry = self.client.post(self._endpoint(), body, format="json")
+ self.assertEqual(create_retry.status_code, status.HTTP_200_OK, create_retry.data)
+ self.assertFalse(create_retry.data["created"])
+ upload_retry = self.client.post(self._endpoint(experiment_id, "upload"), upload, format="json")
+ self.assertEqual(upload_retry.status_code, status.HTTP_200_OK, upload_retry.data)
+ self.assertEqual(upload_retry.data["results"][0]["id"], accepted.data["results"][0]["id"])
+ self.assertFalse(upload_retry.data["results"][0]["created"])
+
+ next_version = definition.create_new_version(config={}, created_by=self.user)
+ new_result = self.client.post(
+ self._endpoint(experiment_id, "upload"),
+ {"results": [result | {"scorer_version_id": str(next_version.id)}]},
+ format="json",
+ )
+ self.assertEqual(new_result.status_code, status.HTTP_400_BAD_REQUEST, new_result.data)
+ self.assertEqual(new_result.data["attr"], "results.0.scorer_version_id")
+ new_item_id = str(uuid4())
+ new_item = self.client.post(
+ self._endpoint(experiment_id, "upload"),
+ {"items": [item | {"id": new_item_id}], "results": [result | {"item_id": new_item_id}]},
+ format="json",
+ )
+ self.assertEqual(new_item.status_code, status.HTTP_400_BAD_REQUEST, new_item.data)
+ self.assertEqual(new_item.data["attr"], "items")
+ self.assertEqual(OfflineExperimentItem.objects.for_team(self.team.id).count(), 1)
+ self.assertEqual(OfflineEvaluationResult.objects.for_team(self.team.id).count(), 1)
+ completed = self.client.post(self._endpoint(experiment_id, "complete"), {}, format="json")
+ self.assertEqual(completed.status_code, status.HTTP_200_OK, completed.data)
+ self.assertEqual(completed.data["status"], "completed")
+
+ def test_ingestion_key_cannot_manage_scorers(self) -> None:
+ self._authenticate("personal_key")
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/llm_analytics/score_definitions/",
+ {"name": "Correct", "kind": "boolean", "config": {"true_label": "Yes", "false_label": "No"}},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertFalse(ScoreDefinition.objects.filter(team=self.team).exists())
+
+ def test_create_validates_the_request_body(self) -> None:
+ body = self._experiment_body() | {"run_source": ""}
+ response = self.client.post(self._endpoint(), body, format="json")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertFalse(OfflineExperiment.objects.for_team(self.team.id).exists())
+
+ def test_upload_reports_all_invalid_scores_without_accepting_any_entries(self) -> None:
+ definition = ScoreDefinition.objects.create(team=self.team, name="Accuracy", kind="numeric")
+ version = definition.create_new_version(config={"min": 0, "max": 1}, created_by=self.user)
+ body = self._experiment_body()
+ created = self.client.post(self._endpoint(), body, format="json")
+ self.assertEqual(created.status_code, status.HTTP_201_CREATED, created.data)
+ items = [{"id": str(uuid4()), "payload": {"input": "What is 2 + 2?"}} for _ in range(3)]
+ response = self.client.post(
+ self._endpoint(str(body["id"]), "upload"),
+ {
+ "items": items,
+ "results": [
+ {"item_id": item["id"], "scorer_version_id": str(version.id), "status": "ok", "value": value}
+ for item, value in zip(items, [0.5, -0.1, 1.1])
+ ],
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.data)
+ self.assertEqual(
+ response.data["errors"],
+ [
+ {
+ "code": "invalid_input",
+ "detail": "Ensure this value is greater than or equal to 0.",
+ "attr": "results.1.value",
+ },
+ {
+ "code": "invalid_input",
+ "detail": "Ensure this value is less than or equal to 1.",
+ "attr": "results.2.value",
+ },
+ ],
+ )
+ self.assertEqual(response.data["attr"], "results.1.value")
+ self.assertFalse(OfflineExperimentItem.objects.for_team(self.team.id).exists())
+ self.assertFalse(OfflineEvaluationResult.objects.for_team(self.team.id).exists())
+
+
+class TestOfflineExperimentValidationErrors(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "nested_batch_fields",
+ ValidationError(
+ {
+ "results": [
+ {},
+ {"value": [ErrorDetail("A score is required.", code="required")]},
+ {
+ "scorer_version_id": [
+ ErrorDetail("Provide a UUID.", code="invalid"),
+ ErrorDetail("Identifier is too short.", code="min_length"),
+ ]
+ },
+ ]
+ }
+ ),
+ [
+ {"code": "required", "detail": "A score is required.", "attr": "results.1.value"},
+ {"code": "invalid_input", "detail": "Provide a UUID.", "attr": "results.2.scorer_version_id"},
+ {
+ "code": "min_length",
+ "detail": "Identifier is too short.",
+ "attr": "results.2.scorer_version_id",
+ },
+ ],
+ ),
+ (
+ "scalar",
+ ValidationError("Provide an object."),
+ [{"code": "invalid_input", "detail": "Provide an object.", "attr": None}],
+ ),
+ (
+ "non_field_errors",
+ ValidationError({"non_field_errors": ["Provide an item or result.", "The request is empty."]}),
+ [
+ {"code": "invalid_input", "detail": "Provide an item or result.", "attr": None},
+ {"code": "invalid_input", "detail": "The request is empty.", "attr": None},
+ ],
+ ),
+ (
+ "nested_non_field_errors",
+ ValidationError({"items": [{}, {}, {"non_field_errors": ["Provide an item object."]}]}),
+ [{"code": "invalid_input", "detail": "Provide an item object.", "attr": "items.2"}],
+ ),
+ ]
+ )
+ def test_validation_errors_preserve_every_message_and_field_path(
+ self, _name: str, exception: ValidationError, expected: list[dict[str, str | None]]
+ ) -> None:
+ response = OfflineExperimentViewSet().handle_exception(exception)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.data, {"type": "validation_error", **expected[0], "errors": expected})
+
+
+class TestOfflineExperimentActionSchemas(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("upload", {"items", "results"}, {"items", "results"}),
+ ("complete", None, {"id", "status", "accepted_item_count", "accepted_result_count"}),
+ ("fail", None, {"id", "status", "accepted_item_count", "accepted_result_count"}),
+ ]
+ )
+ def test_action_schema_matches_its_payload(
+ self, action: str, request_fields: set[str] | None, response_fields: set[str]
+ ) -> None:
+ router = SimpleRouter()
+ router.register("offline_experiments", OfflineExperimentViewSet, basename="offline_experiments")
+ schema = SchemaGenerator(patterns=router.urls).get_schema(request=None, public=True)
+ operation = schema["paths"][f"/offline_experiments/{{id}}/{action}/"]["post"]
+ components = schema["components"]["schemas"]
+
+ if request_fields is None:
+ self.assertNotIn("requestBody", operation)
+ else:
+ request_ref = operation["requestBody"]["content"]["application/json"]["schema"]["$ref"]
+ self.assertEqual(set(components[request_ref.rsplit("/", 1)[-1]]["properties"]), request_fields)
+
+ response_ref = operation["responses"]["200"]["content"]["application/json"]["schema"]["$ref"]
+ self.assertTrue(response_fields <= set(components[response_ref.rsplit("/", 1)[-1]]["properties"]))
diff --git a/products/ai_observability/backend/api/trace_reviews.py b/products/ai_observability/backend/api/trace_reviews.py
index 1646418e4a03..a42b68abe322 100644
--- a/products/ai_observability/backend/api/trace_reviews.py
+++ b/products/ai_observability/backend/api/trace_reviews.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-from decimal import Decimal, InvalidOperation
from typing import Any, cast
from django.conf import settings
@@ -28,12 +27,13 @@ from posthog.permissions import AccessControlPermission
from products.access_control.backend.presentation.access_control import AccessControlViewSetMixin
from products.ai_observability.backend.api.metrics import llma_track_latency
from products.ai_observability.backend.models.review_queues import ReviewQueueItem
-from products.ai_observability.backend.models.score_definitions import ScoreDefinition, ScoreDefinitionVersion
+from products.ai_observability.backend.models.score_definitions import ScoreDefinition
from products.ai_observability.backend.models.trace_reviews import TraceReview, TraceReviewScore
from products.ai_observability.backend.score_definition_configs import (
ScoreDefinitionConfigField,
normalize_score_definition_key,
)
+from products.ai_observability.backend.score_validation import validate_score_value
TRACE_REVIEW_SCORE_VALUE_FIELDS = ("categorical_values", "numeric_value", "boolean_value")
@@ -246,26 +246,6 @@ class BaseTraceReviewWriteSerializer(serializers.Serializer):
return attrs
- @staticmethod
- def _decimal_from_config(value: Any) -> Decimal | None:
- if value is None:
- return None
-
- try:
- return Decimal(str(value))
- except (InvalidOperation, TypeError, ValueError):
- return None
-
- @staticmethod
- def _int_from_config(value: Any) -> int | None:
- if value is None:
- return None
-
- try:
- return int(value)
- except (TypeError, ValueError):
- return None
-
def _resolve_scores(self, score_payloads: list[dict[str, Any]]) -> list[dict[str, Any]]:
team = cast(Team, self.context["team"])
score_errors: list[dict[str, str]] = [{} for _ in score_payloads]
@@ -328,7 +308,13 @@ class BaseTraceReviewWriteSerializer(serializers.Serializer):
score_errors[index]["definition_version_id"] = "This scorer version does not belong to the scorer."
continue
- validation_error = self._validate_score_value(definition, definition_version, score_payload)
+ validation_error = validate_score_value(
+ definition.kind,
+ definition_version.config,
+ numeric_value=score_payload.get("numeric_value"),
+ boolean_value=score_payload.get("boolean_value"),
+ categorical_values=score_payload.get("categorical_values"),
+ )
if validation_error:
score_errors[index].update(validation_error)
continue
@@ -348,74 +334,6 @@ class BaseTraceReviewWriteSerializer(serializers.Serializer):
return resolved_scores
- def _validate_score_value(
- self,
- definition: ScoreDefinition,
- definition_version: ScoreDefinitionVersion,
- score_payload: dict[str, Any],
- ) -> dict[str, str]:
- if definition.kind == ScoreDefinition.Kind.CATEGORICAL:
- categorical_values = score_payload.get("categorical_values")
- if categorical_values is None:
- return {"categorical_values": "This scorer requires `categorical_values`."}
-
- option_keys = {
- option["key"]
- for option in definition_version.config.get("options", [])
- if isinstance(option, dict) and isinstance(option.get("key"), str)
- }
-
- invalid_values = [option_key for option_key in categorical_values if option_key not in option_keys]
- if invalid_values:
- return {"categorical_values": "Select valid categorical option keys."}
-
- selection_mode = definition_version.config.get("selection_mode") or "single"
- selection_count = len(categorical_values)
-
- if selection_mode == "single":
- if selection_count != 1:
- return {"categorical_values": "This scorer allows exactly one categorical option."}
- return {}
-
- minimum = self._int_from_config(definition_version.config.get("min_selections"))
- maximum = self._int_from_config(definition_version.config.get("max_selections"))
-
- if minimum is not None and selection_count < minimum:
- return {"categorical_values": f"Select at least {minimum} categorical options."}
-
- if maximum is not None and selection_count > maximum:
- return {"categorical_values": f"Select no more than {maximum} categorical options."}
-
- return {}
-
- if definition.kind == ScoreDefinition.Kind.NUMERIC:
- numeric_value = score_payload.get("numeric_value")
- if numeric_value is None:
- return {"numeric_value": "This scorer requires `numeric_value`."}
-
- numeric_minimum = self._decimal_from_config(definition_version.config.get("min"))
- numeric_maximum = self._decimal_from_config(definition_version.config.get("max"))
- numeric_step = self._decimal_from_config(definition_version.config.get("step"))
-
- if numeric_minimum is not None and numeric_value < numeric_minimum:
- return {"numeric_value": f"Ensure this value is greater than or equal to {numeric_minimum}."}
-
- if numeric_maximum is not None and numeric_value > numeric_maximum:
- return {"numeric_value": f"Ensure this value is less than or equal to {numeric_maximum}."}
-
- if numeric_step is not None:
- base = numeric_minimum if numeric_minimum is not None else Decimal("0")
- if (numeric_value - base) % numeric_step != 0:
- return {"numeric_value": f"Ensure this value increments by {numeric_step}."}
-
- return {}
-
- boolean_value = score_payload.get("boolean_value")
- if boolean_value is None:
- return {"boolean_value": "This scorer requires `boolean_value`."}
-
- return {}
-
def _replace_scores(self, review: TraceReview, resolved_scores: list[dict[str, Any]]) -> None:
TraceReviewScore.objects.filter(review=review).delete()
diff --git a/products/ai_observability/backend/offline_evaluation_fingerprint.py b/products/ai_observability/backend/offline_evaluation_fingerprint.py
new file mode 100644
index 000000000000..9117ebc6c755
--- /dev/null
+++ b/products/ai_observability/backend/offline_evaluation_fingerprint.py
@@ -0,0 +1,31 @@
+import json
+import hashlib
+from dataclasses import asdict
+from datetime import UTC, datetime
+from uuid import UUID
+
+from products.ai_observability.backend.offline_evaluation_types import (
+ ExperimentSubmission,
+ ItemSubmission,
+ ResultSubmission,
+)
+
+
+def _normalize(value: object) -> object:
+ if isinstance(value, UUID):
+ return str(value)
+ if isinstance(value, datetime):
+ return value.astimezone(UTC).isoformat()
+ if isinstance(value, float) and value.is_integer():
+ return int(value)
+ if isinstance(value, dict):
+ return {key: _normalize(child) for key, child in value.items()}
+ if isinstance(value, list):
+ return [_normalize(child) for child in value]
+ return value
+
+
+def submission_fingerprint(submission: ExperimentSubmission | ItemSubmission | ResultSubmission) -> str:
+ # This format must stay stable across deployments and after payload deletion.
+ content = json.dumps(_normalize(asdict(submission)), sort_keys=True, separators=(",", ":"), allow_nan=False)
+ return hashlib.sha256(b"offline-evaluation:v1:" + content.encode("utf-8")).hexdigest()
diff --git a/products/ai_observability/backend/offline_evaluation_service.py b/products/ai_observability/backend/offline_evaluation_service.py
new file mode 100644
index 000000000000..ddae571a864b
--- /dev/null
+++ b/products/ai_observability/backend/offline_evaluation_service.py
@@ -0,0 +1,533 @@
+from __future__ import annotations
+
+from dataclasses import (
+ asdict,
+ fields as dataclass_fields,
+)
+from datetime import datetime, timedelta
+from typing import TYPE_CHECKING, Literal, NoReturn
+from uuid import UUID
+
+from django.db import IntegrityError, transaction
+from django.db.models import Q
+from django.utils import timezone
+
+from posthog.dataclasses import frozen
+from posthog.models.scoping.manager import resolve_effective_team_id
+
+from products.ai_observability.backend.dataset_queries import dataset_item_versions_at_revision
+from products.ai_observability.backend.models.datasets import Dataset, DatasetItemVersion, DatasetRevision
+from products.ai_observability.backend.models.offline_evaluations import (
+ OfflineEvaluationResult,
+ OfflineEvaluationResultPayload,
+ OfflineExperiment,
+ OfflineExperimentItem,
+ OfflineExperimentItemPayload,
+ PayloadState,
+)
+from products.ai_observability.backend.models.score_definitions import ScoreDefinition, ScoreDefinitionVersion
+from products.ai_observability.backend.offline_evaluation_fingerprint import submission_fingerprint
+from products.ai_observability.backend.offline_evaluation_types import (
+ ExperimentSubmission,
+ ItemSubmission,
+ ResultSubmission,
+ UploadSubmission,
+)
+from products.ai_observability.backend.score_validation import validate_score_value
+
+if TYPE_CHECKING:
+ from django.db.models import QuerySet
+
+ from products.access_control.backend.facade.user_access_control import UserAccessControl
+
+
+@frozen
+class ExperimentCounts:
+ accepted_item_count: int
+ accepted_result_count: int
+ expected_item_count: int | None
+ expected_result_count: int | None
+
+
+@frozen
+class ExperimentReceipt:
+ experiment: OfflineExperiment
+ counts: ExperimentCounts
+ created: bool = False
+
+
+@frozen
+class ItemReceipt:
+ id: UUID
+ accepted_at: datetime
+ created: bool
+
+
+@frozen
+class ResultIdentity:
+ item_id: UUID
+ scorer_version_id: UUID
+
+
+@frozen
+class ResultReceipt:
+ id: UUID
+ item_id: UUID
+ scorer_version_id: UUID
+ accepted_at: datetime
+ created: bool
+
+
+@frozen
+class UploadReceipt:
+ items: list[ItemReceipt]
+ results: list[ResultReceipt]
+
+
+class OfflineEvaluationValidationError(Exception):
+ def __init__(self, field: str, detail: str, *, errors: dict[str, str] | None = None) -> None:
+ super().__init__(detail)
+ self.field = field
+ self.detail = detail
+ self.errors = errors if errors is not None else {field: detail}
+
+ @classmethod
+ def from_errors(cls, errors: dict[str, str]) -> OfflineEvaluationValidationError:
+ field = next(iter(errors))
+ return cls(field, errors[field], errors=errors)
+
+
+class OfflineEvaluationNotFound(Exception):
+ pass
+
+
+class OfflineEvaluationConflict(Exception):
+ def __init__(
+ self, code: str, detail: str, *, field: str | None = None, counts: ExperimentCounts | None = None
+ ) -> None:
+ super().__init__(detail)
+ self.code = code
+ self.detail = detail
+ self.field = field
+ self.counts = counts
+
+
+def _raise_integrity_conflict(error: IntegrityError) -> NoReturn:
+ constraint = getattr(getattr(error.__cause__, "diag", None), "constraint_name", None)
+ if constraint in {"llm_analytics_offlineexperiment_pkey", "llm_analytics_offlineexperimentitem_pkey"}:
+ raise OfflineEvaluationConflict("identity_conflict", "This UUID cannot be used for this submission.") from error
+ if constraint in {
+ "aio_offline_exp_dataset_owner_fk",
+ "aio_offline_item_dataset_owner_fk",
+ "aio_offline_result_scorer_owner_fk",
+ "aio_offline_result_scorer_version_fk",
+ }:
+ raise OfflineEvaluationConflict(
+ "reference_conflict", "A referenced resource changed during the upload. Check its ID and retry."
+ ) from error
+ raise error
+
+
+def _check_fingerprint(actual: str, expected: str, *, field: str) -> None:
+ if actual != expected:
+ raise OfflineEvaluationConflict(
+ "content_conflict", "This identity was already accepted with different content.", field=field
+ )
+
+
+def _provenance_identifier(submitted: str | None, derived: str, *, field: str) -> str:
+ if submitted is not None and submitted != derived:
+ raise OfflineEvaluationValidationError(field, "This identifier does not match the linked PostHog dataset.")
+ return derived
+
+
+def _experiment_counts(experiment: OfflineExperiment) -> ExperimentCounts:
+ return ExperimentCounts(
+ accepted_item_count=OfflineExperimentItem.objects.for_team(experiment.team_id, canonical=True)
+ .filter(experiment_id=experiment.id)
+ .count(),
+ accepted_result_count=OfflineEvaluationResult.objects.for_team(experiment.team_id, canonical=True)
+ .filter(item__experiment_id=experiment.id)
+ .count(),
+ expected_item_count=experiment.expected_item_count,
+ expected_result_count=experiment.expected_result_count,
+ )
+
+
+def _locked_experiment(*, team_id: int, experiment_id: UUID) -> OfflineExperiment:
+ experiment = (
+ OfflineExperiment.objects.for_team(team_id, canonical=True).select_for_update().filter(id=experiment_id).first()
+ )
+ if experiment is None:
+ raise OfflineEvaluationNotFound
+ return experiment
+
+
+class _OfflineEvaluationService:
+ def __init__(self, *, team_id: int, user_access_control: UserAccessControl | None) -> None:
+ self.team_id = resolve_effective_team_id(team_id)
+ self._user_access_control = user_access_control
+
+ def _dataset_revisions(self) -> QuerySet[DatasetRevision]:
+ revisions = DatasetRevision.objects.for_team(self.team_id, canonical=True)
+ if self._user_access_control is not None:
+ datasets = self._user_access_control.filter_queryset_by_access_level(
+ Dataset.objects.for_team(self.team_id, canonical=True), include_all_if_admin=True, resource="dataset"
+ )
+ revisions = revisions.filter(dataset_id__in=datasets.values("id"))
+ return revisions
+
+ def _scorer_versions(self) -> QuerySet[ScoreDefinitionVersion]:
+ definitions = ScoreDefinition.objects.filter(team_id=self.team_id)
+ if self._user_access_control is not None:
+ definitions = self._user_access_control.filter_queryset_by_access_level(
+ definitions, include_all_if_admin=True, resource="llm_analytics"
+ )
+ # nosemgrep: idor-lookup-without-user -- Versions inherit team and caller access from their definitions.
+ return ScoreDefinitionVersion.objects.filter(definition__in=definitions)
+
+
+class OfflineExperimentService(_OfflineEvaluationService):
+ def _creation_fields(self, submission: ExperimentSubmission) -> dict[str, object]:
+ fields: dict[str, object] = asdict(submission)
+ if submission.dataset_revision_id is None:
+ if submission.dataset_source == "posthog":
+ raise OfflineEvaluationValidationError("dataset_revision_id", "Select a PostHog dataset revision.")
+ return fields
+ revision = self._dataset_revisions().filter(id=submission.dataset_revision_id).first()
+ if revision is None:
+ raise OfflineEvaluationValidationError("dataset_revision_id", "Select an existing dataset revision.")
+ errors: dict[str, str] = {}
+ for field, derived in {
+ "dataset_source": "posthog",
+ "dataset_identifier": str(revision.dataset_id),
+ "dataset_revision_identifier": str(revision.id),
+ }.items():
+ try:
+ fields[field] = _provenance_identifier(getattr(submission, field), derived, field=field)
+ except OfflineEvaluationValidationError as error:
+ errors.update(error.errors)
+ if errors:
+ raise OfflineEvaluationValidationError.from_errors(errors)
+ return fields
+
+ def create(self, submission: ExperimentSubmission) -> ExperimentReceipt:
+ fingerprint = submission_fingerprint(submission)
+ try:
+ with transaction.atomic():
+ experiments = OfflineExperiment.objects.for_team(self.team_id, canonical=True).select_for_update()
+ existing = experiments.filter(id=submission.id).first()
+ if existing is not None:
+ _check_fingerprint(existing.submission_fingerprint, fingerprint, field="id")
+ return ExperimentReceipt(experiment=existing, counts=_experiment_counts(existing))
+ fields = self._creation_fields(submission)
+ fields.pop("id")
+ experiment, created = experiments.get_or_create(
+ id=submission.id,
+ defaults={**fields, "team_id": self.team_id, "submission_fingerprint": fingerprint},
+ )
+ _check_fingerprint(experiment.submission_fingerprint, fingerprint, field="id")
+ receipt = ExperimentReceipt(
+ experiment=experiment, counts=_experiment_counts(experiment), created=created
+ )
+ except IntegrityError as error:
+ _raise_integrity_conflict(error)
+ return receipt
+
+ def close(self, experiment_id: UUID, *, status: Literal["completed", "failed"]) -> ExperimentReceipt:
+ with transaction.atomic():
+ experiment = _locked_experiment(team_id=self.team_id, experiment_id=experiment_id)
+ counts = _experiment_counts(experiment)
+ if experiment.status == status:
+ return ExperimentReceipt(experiment=experiment, counts=counts)
+ if experiment.status != OfflineExperiment.Status.UPLOADING:
+ raise OfflineEvaluationConflict("experiment_closed", "This experiment is already closed.")
+ if status == "completed" and (
+ counts.expected_item_count is not None
+ and counts.expected_item_count != counts.accepted_item_count
+ or counts.expected_result_count is not None
+ and counts.expected_result_count != counts.accepted_result_count
+ ):
+ raise OfflineEvaluationConflict(
+ "expected_count_mismatch",
+ "Accepted counts do not match the experiment's expected counts.",
+ counts=counts,
+ )
+ experiment.status = status
+ experiment.finished_at = timezone.now()
+ experiment.save(update_fields=["status", "finished_at"])
+ receipt = ExperimentReceipt(experiment=experiment, counts=counts)
+ return receipt
+
+
+class OfflineEvaluationIngestionService(_OfflineEvaluationService):
+ def _existing_results(
+ self, *, experiment_id: UUID, submissions: list[ResultSubmission]
+ ) -> dict[ResultIdentity, OfflineEvaluationResult]:
+ if not submissions:
+ return {}
+ items_by_version: dict[UUID, list[UUID]] = {}
+ for result in submissions:
+ items_by_version.setdefault(result.scorer_version_id, []).append(result.item_id)
+ requested_pairs = Q()
+ for version_id, item_ids in items_by_version.items():
+ requested_pairs |= Q(scorer_version_id=version_id, item_id__in=item_ids)
+ return {
+ ResultIdentity(item_id=result.item_id, scorer_version_id=result.scorer_version_id): result
+ for result in OfflineEvaluationResult.objects.for_team(self.team_id, canonical=True).filter(
+ requested_pairs, item__experiment_id=experiment_id
+ )
+ }
+
+ def _dataset_versions(
+ self, experiment: OfflineExperiment, submissions: list[ItemSubmission]
+ ) -> dict[UUID, DatasetItemVersion]:
+ if not submissions:
+ return {}
+ linked_ids = {item.dataset_item_version_id for item in submissions if item.dataset_item_version_id is not None}
+ if experiment.dataset_source != "posthog":
+ if linked_ids:
+ raise OfflineEvaluationValidationError(
+ "items", "PostHog item versions require a linked experiment revision."
+ )
+ return {}
+ revision_id = experiment.dataset_revision_id
+ if revision_id is None:
+ raise OfflineEvaluationValidationError("items", "The experiment's dataset revision is no longer available.")
+ revision = self._dataset_revisions().filter(id=revision_id).first()
+ if revision is None:
+ raise OfflineEvaluationValidationError("items", "The experiment's dataset revision is no longer available.")
+ return {
+ version.id: version
+ for version in dataset_item_versions_at_revision(
+ team_id=self.team_id, dataset_id=revision.dataset_id, revision=revision.revision, archived=False
+ )
+ .filter(id__in=linked_ids)
+ .only("id", "dataset_item_id")
+ .order_by()
+ }
+
+ def _new_item(
+ self,
+ submission: ItemSubmission,
+ *,
+ experiment: OfflineExperiment,
+ dataset_versions: dict[UUID, DatasetItemVersion],
+ fingerprint: str,
+ accepted_at: datetime,
+ index: int,
+ ) -> OfflineExperimentItem:
+ fields: dict[str, object] = {
+ field.name: getattr(submission, field.name)
+ for field in dataclass_fields(submission)
+ if field.name != "payload"
+ }
+ if experiment.dataset_source == "posthog":
+ version = (
+ dataset_versions.get(submission.dataset_item_version_id) if submission.dataset_item_version_id else None
+ )
+ if version is None:
+ raise OfflineEvaluationValidationError(
+ f"items.{index}.dataset_item_version_id",
+ "Select an active item version in the experiment's dataset revision.",
+ )
+ errors: dict[str, str] = {}
+ for field, derived in {
+ "dataset_item_identifier": str(version.dataset_item_id),
+ "dataset_item_version_identifier": str(version.id),
+ }.items():
+ try:
+ fields[field] = _provenance_identifier(
+ getattr(submission, field), derived, field=f"items.{index}.{field}"
+ )
+ except OfflineEvaluationValidationError as error:
+ errors.update(error.errors)
+ if errors:
+ raise OfflineEvaluationValidationError.from_errors(errors)
+ return OfflineExperimentItem(
+ **fields,
+ team_id=self.team_id,
+ experiment=experiment,
+ submission_fingerprint=fingerprint,
+ accepted_at=accepted_at,
+ payload_state=PayloadState.AVAILABLE if submission.payload is not None else PayloadState.NOT_PROVIDED,
+ payload_expires_at=accepted_at + timedelta(days=30) if submission.payload is not None else None,
+ )
+
+ def _new_result(
+ self,
+ submission: ResultSubmission,
+ *,
+ version: ScoreDefinitionVersion,
+ fingerprint: str,
+ accepted_at: datetime,
+ index: int,
+ ) -> OfflineEvaluationResult:
+ numeric_value = submission.value if isinstance(submission.value, float) else None
+ boolean_value = submission.value if isinstance(submission.value, bool) else None
+ categorical_values = submission.value if isinstance(submission.value, list) else None
+ if submission.status == "ok":
+ errors = validate_score_value(
+ version.definition.kind,
+ version.config,
+ numeric_value=numeric_value,
+ boolean_value=boolean_value,
+ categorical_values=categorical_values,
+ )
+ if errors:
+ raise OfflineEvaluationValidationError(f"results.{index}.value", next(iter(errors.values())))
+ return OfflineEvaluationResult(
+ team_id=self.team_id,
+ item_id=submission.item_id,
+ scorer_definition=version.definition,
+ scorer_version=version,
+ status=submission.status,
+ numeric_value=numeric_value,
+ boolean_value=boolean_value,
+ categorical_values=categorical_values,
+ error_code=submission.error_code,
+ evaluator_trace_id=submission.evaluator_trace_id,
+ evaluated_at=submission.evaluated_at,
+ submission_fingerprint=fingerprint,
+ accepted_at=accepted_at,
+ payload_state=PayloadState.AVAILABLE if submission.payload is not None else PayloadState.NOT_PROVIDED,
+ payload_expires_at=accepted_at + timedelta(days=30) if submission.payload is not None else None,
+ )
+
+ def upload(self, experiment_id: UUID, submission: UploadSubmission) -> UploadReceipt:
+ item_hashes = {item.id: submission_fingerprint(item) for item in submission.items}
+ result_hashes = [submission_fingerprint(result) for result in submission.results]
+ try:
+ with transaction.atomic():
+ experiment = _locked_experiment(team_id=self.team_id, experiment_id=experiment_id)
+ receipt = self._upload_locked(
+ experiment, submission, item_hashes=item_hashes, result_hashes=result_hashes
+ )
+ except IntegrityError as error:
+ _raise_integrity_conflict(error)
+ return receipt
+
+ def _upload_locked(
+ self,
+ experiment: OfflineExperiment,
+ submission: UploadSubmission,
+ *,
+ item_hashes: dict[UUID, str],
+ result_hashes: list[str],
+ ) -> UploadReceipt:
+ item_ids = list(dict.fromkeys(result.item_id for result in submission.results))
+ items = {
+ item.id: item
+ for item in OfflineExperimentItem.objects.for_team(self.team_id, canonical=True).filter(
+ experiment_id=experiment.id, id__in=item_ids
+ )
+ }
+ results = self._existing_results(experiment_id=experiment.id, submissions=submission.results)
+ for index, item in enumerate(submission.items):
+ if item.id in items:
+ _check_fingerprint(
+ items[item.id].submission_fingerprint, item_hashes[item.id], field=f"items.{index}.id"
+ )
+ new_results: list[tuple[int, ResultSubmission]] = []
+ for index, result in enumerate(submission.results):
+ existing = results.get(ResultIdentity(item_id=result.item_id, scorer_version_id=result.scorer_version_id))
+ if existing is not None:
+ _check_fingerprint(existing.submission_fingerprint, result_hashes[index], field=f"results.{index}")
+ else:
+ new_results.append((index, result))
+ new_item_submissions = [item for item in submission.items if item.id not in items]
+ if (new_item_submissions or new_results) and experiment.status != OfflineExperiment.Status.UPLOADING:
+ raise OfflineEvaluationConflict("experiment_closed", "This experiment is closed to new items and results.")
+ errors: dict[str, str] = {}
+ try:
+ dataset_versions = self._dataset_versions(experiment, new_item_submissions)
+ except OfflineEvaluationValidationError as error:
+ errors.update(error.errors)
+ dataset_versions = None
+ versions = {
+ version.id: version
+ for version in self._scorer_versions()
+ .filter(id__in={result.scorer_version_id for _, result in new_results})
+ .select_related("definition")
+ }
+ accepted_at = timezone.now()
+ new_items: list[OfflineExperimentItem] = []
+ if dataset_versions is not None:
+ for index, item in enumerate(submission.items):
+ if item.id in items:
+ continue
+ try:
+ new_items.append(
+ self._new_item(
+ item,
+ experiment=experiment,
+ dataset_versions=dataset_versions,
+ fingerprint=item_hashes[item.id],
+ accepted_at=accepted_at,
+ index=index,
+ )
+ )
+ except OfflineEvaluationValidationError as error:
+ errors.update(error.errors)
+ declared_item_ids = {item.id for item in submission.items}
+ items.update({item.id: item for item in new_items})
+ new_result_rows: list[OfflineEvaluationResult] = []
+ for index, result in new_results:
+ if result.item_id not in items and result.item_id not in declared_item_ids:
+ errors[f"results.{index}.item_id"] = "Declare the item or select an existing item in this experiment."
+ version = versions.get(result.scorer_version_id)
+ if version is None:
+ errors[f"results.{index}.scorer_version_id"] = "Select an existing scorer version in this project."
+ continue
+ try:
+ row = self._new_result(
+ result, version=version, fingerprint=result_hashes[index], accepted_at=accepted_at, index=index
+ )
+ except OfflineEvaluationValidationError as error:
+ errors.update(error.errors)
+ continue
+ new_result_rows.append(row)
+ results[ResultIdentity(item_id=result.item_id, scorer_version_id=result.scorer_version_id)] = row
+ if errors:
+ raise OfflineEvaluationValidationError.from_errors(errors)
+ OfflineExperimentItem.objects.for_team(self.team_id, canonical=True).bulk_create(new_items)
+ new_item_ids = {item.id for item in new_items}
+ OfflineExperimentItemPayload.objects.for_team(self.team_id, canonical=True).bulk_create(
+ [
+ OfflineExperimentItemPayload(team_id=self.team_id, item_id=item.id, data=item.payload)
+ for item in submission.items
+ if item.id in new_item_ids and item.payload is not None
+ ]
+ )
+ OfflineEvaluationResult.objects.for_team(self.team_id, canonical=True).bulk_create(new_result_rows)
+ new_result_ids = {result.id for result in new_result_rows}
+ OfflineEvaluationResultPayload.objects.for_team(self.team_id, canonical=True).bulk_create(
+ [
+ OfflineEvaluationResultPayload(
+ team_id=self.team_id,
+ result=results[ResultIdentity(item_id=result.item_id, scorer_version_id=result.scorer_version_id)],
+ data=result.payload,
+ )
+ for _, result in new_results
+ if result.payload is not None
+ ]
+ )
+ return UploadReceipt(
+ items=[
+ ItemReceipt(id=item.id, accepted_at=item.accepted_at, created=item.id in new_item_ids)
+ for item in (items[id] for id in item_ids)
+ ],
+ results=[
+ ResultReceipt(
+ id=row.id,
+ item_id=row.item_id,
+ scorer_version_id=row.scorer_version_id,
+ accepted_at=row.accepted_at,
+ created=row.id in new_result_ids,
+ )
+ for row in (
+ results[ResultIdentity(item_id=result.item_id, scorer_version_id=result.scorer_version_id)]
+ for result in submission.results
+ )
+ ],
+ )
diff --git a/products/ai_observability/backend/offline_evaluation_types.py b/products/ai_observability/backend/offline_evaluation_types.py
new file mode 100644
index 000000000000..1388f139cddd
--- /dev/null
+++ b/products/ai_observability/backend/offline_evaluation_types.py
@@ -0,0 +1,59 @@
+from dataclasses import field
+from datetime import datetime
+from typing import Literal
+from uuid import UUID
+
+from posthog.dataclasses import frozen
+
+type JSONValue = None | bool | int | float | str | list[JSONValue] | dict[str, JSONValue]
+type ResultValue = float | bool | list[str]
+type RunSource = Literal["ci", "local", "scheduled"]
+type ResultStatus = Literal["ok", "error", "skipped", "not_applicable"]
+
+
+@frozen
+class ExperimentSubmission:
+ id: UUID
+ name: str
+ started_at: datetime
+ run_source: RunSource | None = None
+ expected_item_count: int | None = None
+ expected_result_count: int | None = None
+ suite_key: str | None = None
+ dataset_source: str | None = None
+ dataset_identifier: str | None = None
+ dataset_revision_identifier: str | None = None
+ dataset_revision_id: UUID | None = None
+ application_version: str | None = None
+ model_version: str | None = None
+ prompt_version: str | None = None
+
+
+@frozen
+class ItemSubmission:
+ id: UUID
+ case_key: str | None = None
+ trial: str | None = None
+ dataset_item_identifier: str | None = None
+ dataset_item_version_identifier: str | None = None
+ dataset_item_version_id: UUID | None = None
+ application_trace_id: str | None = None
+ payload: dict[str, JSONValue] | None = field(default=None, repr=False)
+
+
+@frozen
+class ResultSubmission:
+ item_id: UUID
+ scorer_version_id: UUID
+ status: ResultStatus
+ value: ResultValue | None = None
+ error_code: str | None = None
+ evaluator_trace_id: str | None = None
+ evaluated_at: datetime | None = None
+ payload: dict[str, JSONValue] | None = field(default=None, repr=False)
+
+
+@frozen
+class UploadSubmission:
+ results: list[ResultSubmission]
+ items: list[ItemSubmission] = field(default_factory=list)
diff --git a/products/ai_observability/backend/routes.py b/products/ai_observability/backend/routes.py
index b4b57fa67f76..f9aa11522f41 100644
--- a/products/ai_observability/backend/routes.py
+++ b/products/ai_observability/backend/routes.py
@@ -23,6 +23,7 @@ from products.ai_observability.backend.api import (
LLMProviderKeyValidationViewSet,
LLMProviderKeyViewSet,
LLMProxyViewSet,
+ OfflineExperimentViewSet,
ParserRecipeViewSet,
PersonalSpendInternalViewSet,
PersonalSpendViewSet,
@@ -35,6 +36,12 @@ from products.ai_observability.backend.api import (
def register_routes(routers: RouterRegistry) -> None:
+ routers.projects.register(
+ r"ai_observability/offline_experiments",
+ OfflineExperimentViewSet,
+ "project_ai_observability_offline_experiments",
+ ["team_id"],
+ )
routers.projects.register(r"ai_blob", AIBlobViewSet, "project_ai_blob", ["project_id"])
# `ai_observability` is the canonical name; the `llm_analytics/` prefixes below are the
# unfinished half of a rename the frontend scene URLs already completed.
diff --git a/products/ai_observability/backend/score_validation.py b/products/ai_observability/backend/score_validation.py
new file mode 100644
index 000000000000..81401e57095d
--- /dev/null
+++ b/products/ai_observability/backend/score_validation.py
@@ -0,0 +1,140 @@
+import math
+from decimal import Decimal, InvalidOperation
+from fractions import Fraction
+
+
+def _decimal_from_config(value: object) -> Decimal | None:
+ if value is None:
+ return None
+
+ try:
+ return Decimal(str(value))
+ except (InvalidOperation, TypeError, ValueError):
+ return None
+
+
+def _int_from_config(value: object) -> int | None:
+ if not isinstance(value, str | int | float):
+ return None
+
+ try:
+ return int(value)
+ except (TypeError, ValueError, OverflowError):
+ return None
+
+
+def _is_float_on_step(value: float, base: Decimal, step: Decimal) -> bool:
+ # Fractions avoid overflow when a finite binary64 value is divided by a very small step.
+ remainder = (Fraction(Decimal(str(value))) - Fraction(base)) % Fraction(step)
+ distance = min(remainder, Fraction(step) - remainder)
+ # Allow SDK arithmetic such as 0.1 + 0.2 without letting large values skip step validation.
+ tolerance = Fraction(step) / 1_000_000
+ return distance <= tolerance
+
+
+def _is_float_at_boundary(value: float, boundary: Decimal, step: Decimal | None) -> bool:
+ # Zero has no relative scale, but SDK subtraction can leave a small residue.
+ scale = abs(Fraction(boundary)) if boundary else Fraction(1)
+ ulp = math.ulp(value) if boundary else math.ulp(1.0)
+ # The caps keep large and subnormal floats from meaningfully extending the range.
+ tolerance = min(Fraction(ulp) * 4, scale / 1_000_000_000_000, Fraction(1, 1_000_000_000_000))
+ if step is not None:
+ tolerance = min(tolerance, Fraction(step) / 1_000_000)
+ return abs(Fraction(Decimal(str(value))) - Fraction(boundary)) <= tolerance
+
+
+def _validate_categorical_score(config: dict[str, object], categorical_values: list[str] | None) -> dict[str, str]:
+ if categorical_values is None:
+ return {"categorical_values": "This scorer requires `categorical_values`."}
+
+ configured_options = config.get("options", [])
+ options = configured_options if isinstance(configured_options, list) else []
+ option_keys = {
+ option["key"] for option in options if isinstance(option, dict) and isinstance(option.get("key"), str)
+ }
+ if any(option_key not in option_keys for option_key in categorical_values):
+ return {"categorical_values": "Select valid categorical option keys."}
+
+ selection_mode = config.get("selection_mode") or "single"
+ selection_count = len(categorical_values)
+
+ if selection_mode == "single":
+ if selection_count != 1:
+ return {"categorical_values": "This scorer allows exactly one categorical option."}
+ return {}
+
+ minimum = _int_from_config(config.get("min_selections"))
+ maximum = _int_from_config(config.get("max_selections"))
+
+ if minimum is not None and selection_count < minimum:
+ return {"categorical_values": f"Select at least {minimum} categorical options."}
+
+ if maximum is not None and selection_count > maximum:
+ return {"categorical_values": f"Select no more than {maximum} categorical options."}
+
+ return {}
+
+
+def _validate_numeric_score(config: dict[str, object], numeric_value: Decimal | float | None) -> dict[str, str]:
+ if numeric_value is None:
+ return {"numeric_value": "This scorer requires `numeric_value`."}
+
+ if not math.isfinite(numeric_value):
+ return {"numeric_value": "Provide a finite numeric value."}
+
+ numeric_minimum = _decimal_from_config(config.get("min"))
+ numeric_maximum = _decimal_from_config(config.get("max"))
+ numeric_step = _decimal_from_config(config.get("step"))
+
+ if any(value is not None and not value.is_finite() for value in (numeric_minimum, numeric_maximum, numeric_step)):
+ return {"numeric_value": "This scorer has an invalid numeric configuration."}
+ if numeric_step is not None and numeric_step <= 0:
+ return {"numeric_value": "This scorer has an invalid numeric configuration."}
+
+ decimal_value = Decimal(str(numeric_value)) if isinstance(numeric_value, float) else numeric_value
+ if (
+ numeric_minimum is not None
+ and decimal_value < numeric_minimum
+ and not (
+ isinstance(numeric_value, float) and _is_float_at_boundary(numeric_value, numeric_minimum, numeric_step)
+ )
+ ):
+ return {"numeric_value": f"Ensure this value is greater than or equal to {numeric_minimum}."}
+
+ if (
+ numeric_maximum is not None
+ and decimal_value > numeric_maximum
+ and not (
+ isinstance(numeric_value, float) and _is_float_at_boundary(numeric_value, numeric_maximum, numeric_step)
+ )
+ ):
+ return {"numeric_value": f"Ensure this value is less than or equal to {numeric_maximum}."}
+
+ if numeric_step is not None:
+ base = numeric_minimum if numeric_minimum is not None else Decimal("0")
+ on_step = (
+ _is_float_on_step(numeric_value, base, numeric_step)
+ if isinstance(numeric_value, float)
+ else (Fraction(numeric_value) - Fraction(base)) % Fraction(numeric_step) == 0
+ )
+ if not on_step:
+ return {"numeric_value": f"Ensure this value increments by {numeric_step}."}
+
+ return {}
+
+
+def validate_score_value(
+ kind: str,
+ config: dict[str, object],
+ *,
+ numeric_value: Decimal | float | None = None,
+ boolean_value: bool | None = None,
+ categorical_values: list[str] | None = None,
+) -> dict[str, str]:
+ if kind == "categorical":
+ return _validate_categorical_score(config, categorical_values)
+ if kind == "numeric":
+ return _validate_numeric_score(config, numeric_value)
+ if boolean_value is None:
+ return {"boolean_value": "This scorer requires `boolean_value`."}
+ return {}
diff --git a/products/ai_observability/backend/test/test_offline_evaluation_fingerprint.py b/products/ai_observability/backend/test/test_offline_evaluation_fingerprint.py
new file mode 100644
index 000000000000..45728e53fca5
--- /dev/null
+++ b/products/ai_observability/backend/test/test_offline_evaluation_fingerprint.py
@@ -0,0 +1,75 @@
+from dataclasses import replace
+from datetime import datetime
+from uuid import UUID
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.ai_observability.backend.api.offline_experiment_serializers import ResultSubmissionSerializer
+from products.ai_observability.backend.offline_evaluation_fingerprint import submission_fingerprint
+from products.ai_observability.backend.offline_evaluation_types import ExperimentSubmission, ItemSubmission, JSONValue
+
+ITEM_ID = UUID("01922222-2222-7222-8222-222222222222")
+SCORER_VERSION_ID = UUID("01923333-3333-7333-8333-333333333333")
+
+
+class TestOfflineEvaluationFingerprint(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "nested_object_order",
+ {"input": {"question": "Hello", "context": ["A", "B"]}, "output": "World"},
+ {"output": "World", "input": {"context": ["A", "B"], "question": "Hello"}},
+ ),
+ ("integer_and_whole_float", {"input": [1, {"count": 2}]}, {"input": [1.0, {"count": 2.0}]}),
+ ("negative_zero", {"input": -0.0}, {"input": 0}),
+ ]
+ )
+ def test_equivalent_payloads_have_the_same_fingerprint(
+ self, _name: str, first: dict[str, JSONValue], second: dict[str, JSONValue]
+ ) -> None:
+ self.assertEqual(
+ submission_fingerprint(ItemSubmission(id=ITEM_ID, payload=first)),
+ submission_fingerprint(ItemSubmission(id=ITEM_ID, payload=second)),
+ )
+
+ @parameterized.expand(
+ [
+ ("omitted_and_empty", None, {}),
+ ("empty_and_null_property", {}, {"input": None}),
+ ("array_order", {"input": ["A", "B"]}, {"input": ["B", "A"]}),
+ ("boolean_and_number", {"input": True}, {"input": 1}),
+ ]
+ )
+ def test_distinct_payloads_have_different_fingerprints(
+ self, _name: str, first: dict[str, JSONValue] | None, second: dict[str, JSONValue] | None
+ ) -> None:
+ self.assertNotEqual(
+ submission_fingerprint(ItemSubmission(id=ITEM_ID, payload=first)),
+ submission_fingerprint(ItemSubmission(id=ITEM_ID, payload=second)),
+ )
+
+ def test_equivalent_timestamp_offsets_have_the_same_fingerprint(self) -> None:
+ submission = ExperimentSubmission(
+ id=ITEM_ID, name="Candidate model", started_at=datetime.fromisoformat("2026-09-24T10:00:00+00:00")
+ )
+ self.assertEqual(
+ submission_fingerprint(submission),
+ submission_fingerprint(replace(submission, started_at=datetime.fromisoformat("2026-09-24T06:00:00-04:00"))),
+ )
+
+ def test_serialized_category_order_has_the_same_fingerprint(self) -> None:
+ fingerprints = []
+ for values in (["accurate", "helpful"], ["helpful", "accurate"]):
+ serializer = ResultSubmissionSerializer(
+ data={
+ "item_id": str(ITEM_ID),
+ "scorer_version_id": str(SCORER_VERSION_ID),
+ "status": "ok",
+ "value": values,
+ }
+ )
+ self.assertTrue(serializer.is_valid(), serializer.errors)
+ fingerprints.append(submission_fingerprint(serializer.validated_data))
+ self.assertEqual(fingerprints[0], fingerprints[1])
diff --git a/products/ai_observability/backend/test/test_offline_evaluation_service.py b/products/ai_observability/backend/test/test_offline_evaluation_service.py
new file mode 100644
index 000000000000..0c20f183daaf
--- /dev/null
+++ b/products/ai_observability/backend/test/test_offline_evaluation_service.py
@@ -0,0 +1,500 @@
+from collections.abc import Callable
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import replace
+from datetime import timedelta
+from threading import Event
+from typing import Literal
+from uuid import uuid4
+
+from django.db import connection, transaction
+from django.test import TestCase, TransactionTestCase
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models import Organization, Team
+
+from products.ai_observability.backend.models.datasets import Dataset, DatasetItem, DatasetItemVersion, DatasetRevision
+from products.ai_observability.backend.models.offline_evaluations import (
+ OfflineEvaluationResult,
+ OfflineEvaluationResultPayload,
+ OfflineExperiment,
+ OfflineExperimentItem,
+ OfflineExperimentItemPayload,
+ PayloadState,
+)
+from products.ai_observability.backend.models.score_definitions import ScoreDefinition, ScoreDefinitionVersion
+from products.ai_observability.backend.offline_evaluation_service import (
+ ExperimentReceipt,
+ OfflineEvaluationConflict,
+ OfflineEvaluationIngestionService,
+ OfflineEvaluationNotFound,
+ OfflineEvaluationValidationError,
+ OfflineExperimentService,
+ UploadReceipt,
+)
+from products.ai_observability.backend.offline_evaluation_types import (
+ ExperimentSubmission,
+ ItemSubmission,
+ ResultSubmission,
+ UploadSubmission,
+)
+
+
+class TestOfflineEvaluationService(TestCase):
+ team: Team
+ other_team: Team
+ scorer: ScoreDefinition
+ version: ScoreDefinitionVersion
+ other_version: ScoreDefinitionVersion
+
+ @classmethod
+ def setUpTestData(cls) -> None:
+ organization, _, cls.team = Organization.objects.bootstrap(None)
+ cls.other_team = Team.objects.create(organization=organization)
+ cls.scorer = ScoreDefinition.objects.create(team=cls.team, name="Accuracy", kind="numeric")
+ cls.version = cls.scorer.create_new_version(config={"min": 0, "max": 1}, created_by=None)
+ other_scorer = ScoreDefinition.objects.create(team=cls.other_team, name="Other scorer", kind="numeric")
+ cls.other_version = other_scorer.create_new_version(config={}, created_by=None)
+
+ def setUp(self) -> None:
+ self.lifecycle = OfflineExperimentService(team_id=self.team.id, user_access_control=None)
+ self.ingestion = OfflineEvaluationIngestionService(team_id=self.team.id, user_access_control=None)
+ self.experiment_submission = ExperimentSubmission(
+ id=uuid4(), name="Candidate model", started_at=timezone.now(), run_source="ci"
+ )
+ self.experiment = self.lifecycle.create(self.experiment_submission).experiment
+ self.item = ItemSubmission(id=uuid4(), payload={"input": "A question", "output": "An answer"})
+ self.result = ResultSubmission(
+ item_id=self.item.id,
+ scorer_version_id=self.version.id,
+ status="ok",
+ value=0.8,
+ payload={"reasoning": "The answer addresses the question."},
+ )
+ self.submission = UploadSubmission(items=[self.item], results=[self.result])
+
+ def test_experiment_creation_is_idempotent_and_rejects_changed_content(self) -> None:
+ retry = self.lifecycle.create(self.experiment_submission)
+ self.assertFalse(retry.created)
+ self.assertEqual(retry.experiment.created_at, self.experiment.created_at)
+ self.assertEqual(retry.counts.accepted_item_count, 0)
+
+ with self.assertRaises(OfflineEvaluationConflict) as error:
+ self.lifecycle.create(replace(self.experiment_submission, name="Different model"))
+ self.assertEqual(error.exception.code, "content_conflict")
+ self.assertEqual(OfflineExperiment.objects.for_team(self.team.id).count(), 1)
+
+ def test_upload_retry_preserves_identity_acceptance_and_retention(self) -> None:
+ accepted = self.ingestion.upload(self.experiment.id, self.submission)
+ replay = self.ingestion.upload(self.experiment.id, self.submission)
+
+ self.assertEqual(replay.items, [replace(accepted.items[0], created=False)])
+ self.assertEqual(replay.results, [replace(accepted.results[0], created=False)])
+ self.assertTrue(accepted.items[0].created)
+ self.assertTrue(accepted.results[0].created)
+ item = OfflineExperimentItem.objects.for_team(self.team.id).get(id=self.item.id)
+ result = OfflineEvaluationResult.objects.for_team(self.team.id).get(id=accepted.results[0].id)
+ self.assertEqual(item.payload_expires_at, item.accepted_at + timedelta(days=30))
+ self.assertEqual(result.payload_expires_at, result.accepted_at + timedelta(days=30))
+ self.assertEqual(
+ OfflineExperimentItemPayload.objects.for_team(self.team.id).get(item=item).data, self.item.payload
+ )
+ self.assertEqual(
+ OfflineEvaluationResultPayload.objects.for_team(self.team.id).get(result=result).data, self.result.payload
+ )
+
+ @parameterized.expand([("item",), ("result",)])
+ def test_changed_accepted_content_conflicts(self, target: str) -> None:
+ self.ingestion.upload(self.experiment.id, self.submission)
+ changed = (
+ replace(self.submission, items=[replace(self.item, payload={"input": "A different question"})])
+ if target == "item"
+ else replace(self.submission, results=[replace(self.result, value=0.9)])
+ )
+
+ with self.assertRaises(OfflineEvaluationConflict) as error:
+ self.ingestion.upload(self.experiment.id, changed)
+ self.assertEqual(error.exception.code, "content_conflict")
+ self.assertEqual(OfflineEvaluationResult.objects.for_team(self.team.id).get().numeric_value, 0.8)
+
+ @parameterized.expand([("missing_scorer",), ("foreign_scorer",), ("invalid_score",), ("missing_item_and_scorer",)])
+ def test_invalid_batch_does_not_persist_any_rows(self, failure: str) -> None:
+ second_item = replace(self.item, id=uuid4())
+ second_result = replace(self.result, item_id=second_item.id)
+ third_item = replace(self.item, id=uuid4())
+ third_result = replace(self.result, item_id=third_item.id, value=-1.0)
+ expected_fields = {"results.2.value"}
+ if failure == "missing_scorer":
+ second_result = replace(second_result, scorer_version_id=uuid4())
+ expected_fields.add("results.1.scorer_version_id")
+ elif failure == "foreign_scorer":
+ second_result = replace(second_result, scorer_version_id=self.other_version.id)
+ expected_fields.add("results.1.scorer_version_id")
+ elif failure == "missing_item_and_scorer":
+ second_result = replace(second_result, item_id=uuid4(), scorer_version_id=uuid4())
+ expected_fields.update({"results.1.item_id", "results.1.scorer_version_id"})
+ else:
+ second_result = replace(second_result, value=2.0)
+ expected_fields.add("results.1.value")
+
+ with self.assertRaises(OfflineEvaluationValidationError) as error:
+ self.ingestion.upload(
+ self.experiment.id,
+ UploadSubmission(
+ items=[self.item, second_item, third_item], results=[self.result, second_result, third_result]
+ ),
+ )
+ self.assertTrue(error.exception.field.startswith("results.1."))
+ self.assertEqual(set(error.exception.errors), expected_fields)
+ self.assertFalse(OfflineExperimentItem.objects.for_team(self.team.id).exists())
+ self.assertFalse(OfflineEvaluationResult.objects.for_team(self.team.id).exists())
+ self.assertFalse(OfflineExperimentItemPayload.objects.for_team(self.team.id).exists())
+ self.assertFalse(OfflineEvaluationResultPayload.objects.for_team(self.team.id).exists())
+
+ def test_additional_scorer_uses_existing_item_without_payload(self) -> None:
+ self.ingestion.upload(self.experiment.id, self.submission)
+ scorer = ScoreDefinition.objects.create(team=self.team, name="Safety", kind="boolean")
+ version = scorer.create_new_version(config={}, created_by=None)
+
+ receipt = self.ingestion.upload(
+ self.experiment.id,
+ UploadSubmission(
+ results=[ResultSubmission(item_id=self.item.id, scorer_version_id=version.id, status="ok", value=False)]
+ ),
+ )
+
+ self.assertFalse(receipt.items[0].created)
+ self.assertTrue(receipt.results[0].created)
+ self.assertEqual(OfflineExperimentItem.objects.for_team(self.team.id).count(), 1)
+ self.assertEqual(OfflineExperimentItemPayload.objects.for_team(self.team.id).count(), 1)
+ self.assertEqual(OfflineEvaluationResult.objects.for_team(self.team.id).count(), 2)
+ self.assertIs(
+ OfflineEvaluationResult.objects.for_team(self.team.id).get(id=receipt.results[0].id).boolean_value, False
+ )
+
+ @parameterized.expand([("unknown",), ("foreign",)])
+ def test_inaccessible_experiment_is_not_found_for_upload_and_close(self, target: str) -> None:
+ experiment_id = uuid4() if target == "unknown" else self.experiment.id
+ team_id = self.team.id if target == "unknown" else self.other_team.id
+ with self.assertRaises(OfflineEvaluationNotFound):
+ OfflineEvaluationIngestionService(team_id=team_id, user_access_control=None).upload(
+ experiment_id, self.submission
+ )
+ with self.assertRaises(OfflineEvaluationNotFound):
+ OfflineExperimentService(team_id=team_id, user_access_control=None).close(experiment_id, status="failed")
+
+ @parameterized.expand([("unknown",), ("other_experiment",), ("other_project",)])
+ def test_result_cannot_reference_an_item_outside_its_experiment(self, target: str) -> None:
+ if target != "unknown":
+ self.ingestion.upload(self.experiment.id, self.submission)
+ team_id = self.other_team.id if target == "other_project" else self.team.id
+ experiment = (
+ OfflineExperimentService(team_id=team_id, user_access_control=None)
+ .create(replace(self.experiment_submission, id=uuid4()))
+ .experiment
+ )
+ result = (
+ replace(self.result, scorer_version_id=self.other_version.id) if target == "other_project" else self.result
+ )
+
+ with self.assertRaises(OfflineEvaluationValidationError) as error:
+ OfflineEvaluationIngestionService(team_id=team_id, user_access_control=None).upload(
+ experiment.id, UploadSubmission(results=[result])
+ )
+ self.assertEqual(error.exception.field, "results.0.item_id")
+
+ @parameterized.expand([("experiment",), ("item",)])
+ def test_global_uuid_collision_returns_a_controlled_conflict(self, target: str) -> None:
+ other_lifecycle = OfflineExperimentService(team_id=self.other_team.id, user_access_control=None)
+ if target == "experiment":
+ with self.assertRaises(OfflineEvaluationConflict) as error:
+ other_lifecycle.create(self.experiment_submission)
+ else:
+ self.ingestion.upload(self.experiment.id, self.submission)
+ other_experiment = other_lifecycle.create(replace(self.experiment_submission, id=uuid4())).experiment
+ with self.assertRaises(OfflineEvaluationConflict) as error:
+ OfflineEvaluationIngestionService(team_id=self.other_team.id, user_access_control=None).upload(
+ other_experiment.id,
+ replace(self.submission, results=[replace(self.result, scorer_version_id=self.other_version.id)]),
+ )
+ self.assertFalse(OfflineEvaluationResult.objects.for_team(self.other_team.id).exists())
+ self.assertEqual(error.exception.code, "identity_conflict")
+
+ def test_completion_checks_counts_and_counts_error_results(self) -> None:
+ experiment = self.lifecycle.create(
+ replace(self.experiment_submission, id=uuid4(), expected_item_count=1, expected_result_count=2)
+ ).experiment
+ self.ingestion.upload(experiment.id, self.submission)
+
+ with self.assertRaises(OfflineEvaluationConflict) as error:
+ self.lifecycle.close(experiment.id, status="completed")
+ self.assertEqual(error.exception.code, "expected_count_mismatch")
+ self.assertIsNotNone(error.exception.counts)
+ assert error.exception.counts is not None
+ self.assertEqual(error.exception.counts.accepted_result_count, 1)
+ self.assertEqual(error.exception.counts.expected_result_count, 2)
+ experiment.refresh_from_db()
+ self.assertEqual(experiment.status, "uploading")
+ self.assertIsNone(experiment.finished_at)
+
+ second_version = self.scorer.create_new_version(config={}, created_by=None)
+ self.ingestion.upload(
+ experiment.id,
+ UploadSubmission(
+ results=[
+ replace(
+ self.result,
+ scorer_version_id=second_version.id,
+ status="error",
+ value=None,
+ error_code="timeout",
+ )
+ ]
+ ),
+ )
+ closed = self.lifecycle.close(experiment.id, status="completed")
+ self.assertEqual(closed.experiment.status, "completed")
+ self.assertEqual(closed.counts.accepted_result_count, 2)
+
+ @parameterized.expand([("completed",), ("failed",)])
+ def test_closure_allows_exact_replays_and_rejects_new_data(self, status: Literal["completed", "failed"]) -> None:
+ accepted = self.ingestion.upload(self.experiment.id, self.submission)
+ closed = self.lifecycle.close(self.experiment.id, status=status)
+ repeated = self.lifecycle.close(self.experiment.id, status=status)
+ self.assertEqual(repeated.experiment.finished_at, closed.experiment.finished_at)
+ replay = self.ingestion.upload(self.experiment.id, self.submission)
+ self.assertEqual(replay.results[0], replace(accepted.results[0], created=False))
+ self.assertEqual(self.lifecycle.create(self.experiment_submission).experiment.status, status)
+
+ second_item = replace(self.item, id=uuid4())
+ with self.assertRaises(OfflineEvaluationConflict) as error:
+ self.ingestion.upload(
+ self.experiment.id,
+ UploadSubmission(
+ items=[second_item], results=[self.result, replace(self.result, item_id=second_item.id)]
+ ),
+ )
+ self.assertEqual(error.exception.code, "experiment_closed")
+ self.assertEqual(OfflineExperimentItem.objects.for_team(self.team.id).count(), 1)
+ with self.assertRaises(OfflineEvaluationConflict):
+ self.lifecycle.close(self.experiment.id, status="failed" if status == "completed" else "completed")
+
+ def test_failed_closure_preserves_results_despite_missing_expected_counts(self) -> None:
+ experiment = self.lifecycle.create(
+ replace(self.experiment_submission, id=uuid4(), expected_item_count=10, expected_result_count=30)
+ ).experiment
+ self.ingestion.upload(experiment.id, self.submission)
+
+ receipt = self.lifecycle.close(experiment.id, status="failed")
+ self.assertEqual(receipt.experiment.status, "failed")
+ self.assertEqual(receipt.counts.accepted_result_count, 1)
+
+ def test_retry_after_payload_expiry_does_not_restore_payloads_or_extend_retention(self) -> None:
+ accepted = self.ingestion.upload(self.experiment.id, self.submission)
+ item = OfflineExperimentItem.objects.for_team(self.team.id).get(id=self.item.id)
+ result = OfflineEvaluationResult.objects.for_team(self.team.id).get(id=accepted.results[0].id)
+ OfflineExperimentItemPayload.objects.for_team(self.team.id).filter(item=item).delete()
+ OfflineEvaluationResultPayload.objects.for_team(self.team.id).filter(result=result).delete()
+ OfflineExperimentItem.objects.for_team(self.team.id).filter(id=item.id).update(
+ payload_state=PayloadState.EXPIRED
+ )
+ OfflineEvaluationResult.objects.for_team(self.team.id).filter(id=result.id).update(
+ payload_state=PayloadState.EXPIRED
+ )
+
+ replay = self.ingestion.upload(self.experiment.id, self.submission)
+
+ self.assertEqual(replay.results[0], replace(accepted.results[0], created=False))
+ refreshed_item = OfflineExperimentItem.objects.for_team(self.team.id).get(id=item.id)
+ refreshed_result = OfflineEvaluationResult.objects.for_team(self.team.id).get(id=result.id)
+ self.assertEqual(refreshed_item.payload_expires_at, item.payload_expires_at)
+ self.assertEqual(refreshed_result.payload_expires_at, result.payload_expires_at)
+ self.assertEqual(refreshed_item.payload_state, PayloadState.EXPIRED)
+ self.assertEqual(refreshed_result.payload_state, PayloadState.EXPIRED)
+ self.assertFalse(OfflineExperimentItemPayload.objects.for_team(self.team.id).exists())
+ self.assertFalse(OfflineEvaluationResultPayload.objects.for_team(self.team.id).exists())
+
+ def test_previous_archived_version_uses_its_own_configuration(self) -> None:
+ self.scorer.create_new_version(config={"min": 10, "max": 20}, created_by=None)
+ self.scorer.archived = True
+ self.scorer.save(update_fields=["archived"])
+
+ receipt = self.ingestion.upload(self.experiment.id, self.submission)
+
+ result = OfflineEvaluationResult.objects.for_team(self.team.id).get(id=receipt.results[0].id)
+ self.assertEqual(result.scorer_version_id, self.version.id)
+ self.assertEqual(result.numeric_value, 0.8)
+
+ def test_dataset_snapshot_membership_and_retry_after_dataset_deletion(self) -> None:
+ dataset = Dataset.objects.for_team(self.team.id).create(team=self.team, name="Examples")
+ first_revision = DatasetRevision.objects.for_team(self.team.id).create(
+ team=self.team, dataset=dataset, revision=1
+ )
+ second_revision = DatasetRevision.objects.for_team(self.team.id).create(
+ team=self.team, dataset=dataset, revision=2
+ )
+ dataset_item = DatasetItem.objects.for_team(self.team.id).create(team=self.team, dataset=dataset)
+ old_version = DatasetItemVersion.objects.for_team(self.team.id).create(
+ team=self.team,
+ dataset=dataset,
+ dataset_item=dataset_item,
+ dataset_revision=first_revision,
+ version=1,
+ input={"question": "The original question"},
+ )
+ new_version = DatasetItemVersion.objects.for_team(self.team.id).create(
+ team=self.team,
+ dataset=dataset,
+ dataset_item=dataset_item,
+ dataset_revision=second_revision,
+ version=2,
+ input={"question": "A new question"},
+ )
+ experiment_submission = replace(self.experiment_submission, id=uuid4(), dataset_revision_id=first_revision.id)
+ experiment = self.lifecycle.create(experiment_submission).experiment
+ submission = replace(self.submission, items=[replace(self.item, dataset_item_version_id=old_version.id)])
+ second_item = replace(
+ self.item,
+ id=uuid4(),
+ dataset_item_version_id=old_version.id,
+ dataset_item_identifier="wrong-item",
+ dataset_item_version_identifier="wrong-version",
+ )
+ with self.assertRaises(OfflineEvaluationValidationError) as error:
+ self.ingestion.upload(
+ experiment.id,
+ replace(
+ submission,
+ items=[replace(self.item, dataset_item_version_id=new_version.id), second_item],
+ results=[self.result, replace(self.result, item_id=second_item.id, value=2.0)],
+ ),
+ )
+ self.assertEqual(
+ set(error.exception.errors),
+ {
+ "items.0.dataset_item_version_id",
+ "items.1.dataset_item_identifier",
+ "items.1.dataset_item_version_identifier",
+ "results.1.value",
+ },
+ )
+ self.assertFalse(OfflineExperimentItem.objects.for_team(self.team.id).exists())
+ self.assertFalse(OfflineEvaluationResult.objects.for_team(self.team.id).exists())
+ receipt = self.ingestion.upload(experiment.id, submission)
+ self.assertEqual(experiment.dataset_source, "posthog")
+ self.assertEqual(experiment.dataset_identifier, str(dataset.id))
+ item = OfflineExperimentItem.objects.for_team(self.team.id).get(id=self.item.id)
+ self.assertEqual(item.dataset_item_identifier, str(dataset_item.id))
+ self.assertEqual(item.dataset_item_version_identifier, str(old_version.id))
+ self.assertEqual(
+ OfflineExperimentItemPayload.objects.for_team(self.team.id).get(item=item).data, self.item.payload
+ )
+
+ dataset.delete()
+
+ replay_experiment = self.lifecycle.create(experiment_submission).experiment
+ replay_upload = self.ingestion.upload(experiment.id, submission)
+ self.assertIsNone(replay_experiment.dataset_revision_id)
+ self.assertEqual(replay_upload.results[0], replace(receipt.results[0], created=False))
+ item.refresh_from_db()
+ self.assertIsNone(item.dataset_item_version_id)
+ self.assertEqual(item.dataset_item_version_identifier, str(old_version.id))
+
+
+class TestOfflineEvaluationServiceConcurrency(TransactionTestCase):
+ def setUp(self) -> None:
+ _, _, self.team = Organization.objects.bootstrap(None)
+ self.lifecycle = OfflineExperimentService(team_id=self.team.id, user_access_control=None)
+ self.ingestion = OfflineEvaluationIngestionService(team_id=self.team.id, user_access_control=None)
+ self.experiment = self.lifecycle.create(
+ ExperimentSubmission(id=uuid4(), name="Concurrent upload", started_at=timezone.now())
+ ).experiment
+ scorer = ScoreDefinition.objects.create(team=self.team, name="Accuracy", kind="numeric")
+ version = scorer.create_new_version(config={}, created_by=None)
+ item = ItemSubmission(id=uuid4())
+ self.submission = UploadSubmission(
+ items=[item],
+ results=[ResultSubmission(item_id=item.id, scorer_version_id=version.id, status="ok", value=0.8)],
+ )
+
+ def _run_second_operation(
+ self, operation: Callable[[], UploadReceipt | ExperimentReceipt], started: Event
+ ) -> UploadReceipt | ExperimentReceipt:
+ def observe_query(
+ execute: Callable[..., object], sql: str, params: object, many: bool, context: object
+ ) -> object:
+ if sql.startswith("SELECT") and OfflineExperiment._meta.db_table in sql:
+ started.set()
+ return execute(sql, params, many, context)
+
+ try:
+ with connection.execute_wrapper(observe_query):
+ return operation()
+ finally:
+ connection.close()
+
+ def test_concurrent_duplicate_uploads_return_the_same_result(self) -> None:
+ second_started = Event()
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ with transaction.atomic():
+ first = self.ingestion.upload(self.experiment.id, self.submission)
+ pending = executor.submit(
+ self._run_second_operation,
+ lambda: self.ingestion.upload(self.experiment.id, self.submission),
+ second_started,
+ )
+ self.assertTrue(second_started.wait(timeout=10))
+ second = pending.result(timeout=10)
+
+ assert isinstance(second, UploadReceipt)
+ self.assertEqual(second.results, [replace(first.results[0], created=False)])
+ self.assertEqual(OfflineEvaluationResult.objects.for_team(self.team.id).count(), 1)
+
+ def test_concurrent_experiment_creation_returns_one_identity(self) -> None:
+ submission = ExperimentSubmission(id=uuid4(), name="Retried creation", started_at=timezone.now())
+ second_started = Event()
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ with transaction.atomic():
+ first = self.lifecycle.create(submission)
+ pending = executor.submit(
+ self._run_second_operation,
+ lambda: self.lifecycle.create(submission),
+ second_started,
+ )
+ self.assertTrue(second_started.wait(timeout=10))
+ second = pending.result(timeout=10)
+
+ assert isinstance(second, ExperimentReceipt)
+ self.assertTrue(first.created)
+ self.assertFalse(second.created)
+ self.assertEqual(first.experiment.id, second.experiment.id)
+ self.assertEqual(first.experiment.created_at, second.experiment.created_at)
+ self.assertEqual(OfflineExperiment.objects.for_team(self.team.id).filter(id=submission.id).count(), 1)
+
+ @parameterized.expand([("upload_first",), ("complete_first",)])
+ def test_upload_and_completion_serialize(self, first_operation: str) -> None:
+ second_started = Event()
+ operation: Callable[[], UploadReceipt | ExperimentReceipt]
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ with transaction.atomic():
+ if first_operation == "upload_first":
+ self.ingestion.upload(self.experiment.id, self.submission)
+ operation = lambda: self.lifecycle.close(self.experiment.id, status="completed")
+ else:
+ self.lifecycle.close(self.experiment.id, status="completed")
+ operation = lambda: self.ingestion.upload(self.experiment.id, self.submission)
+ pending = executor.submit(self._run_second_operation, operation, second_started)
+ self.assertTrue(second_started.wait(timeout=10))
+
+ if first_operation == "upload_first":
+ closed = pending.result(timeout=10)
+ assert isinstance(closed, ExperimentReceipt)
+ self.assertEqual(closed.counts.accepted_result_count, 1)
+ else:
+ with self.assertRaises(OfflineEvaluationConflict) as error:
+ pending.result(timeout=10)
+ self.assertEqual(error.exception.code, "experiment_closed")
+ self.assertFalse(OfflineEvaluationResult.objects.for_team(self.team.id).exists())
+ self.experiment.refresh_from_db()
+ self.assertEqual(self.experiment.status, "completed")
diff --git a/products/ai_observability/backend/test/test_score_validation.py b/products/ai_observability/backend/test/test_score_validation.py
new file mode 100644
index 000000000000..2bb94a592e9c
--- /dev/null
+++ b/products/ai_observability/backend/test/test_score_validation.py
@@ -0,0 +1,162 @@
+import math
+from decimal import Decimal
+from functools import reduce
+from operator import add
+
+import unittest
+
+from parameterized import parameterized
+
+from products.ai_observability.backend.score_validation import validate_score_value
+
+
+class TestScoreValueValidation(unittest.TestCase):
+ @parameterized.expand(
+ [
+ ("decimal_on_step", Decimal("0.3"), {"step": 0.1}, None),
+ (
+ "decimal_off_step",
+ Decimal("0.3000001"),
+ {"step": 0.1},
+ "Ensure this value increments by 0.1.",
+ ),
+ ("decimal_tiny_step", Decimal("1000.000000"), {"step": 1e-30}, None),
+ (
+ "decimal_tiny_off_step",
+ Decimal("1000.000000"),
+ {"step": 3e-30},
+ "Ensure this value increments by 3E-30.",
+ ),
+ ("float_rounding", 0.1 + 0.2, {"step": 0.1}, None),
+ ("float_subtraction_rounding", 1.1 - 1.0, {"step": 0.1}, None),
+ ("float_accumulated_rounding", reduce(add, [0.1] * 100), {"step": 0.1}, None),
+ ("float_at_step_tolerance", 0.3000001, {"step": 0.1}, None),
+ (
+ "float_beyond_step_tolerance",
+ math.nextafter(0.3000001, math.inf),
+ {"step": 0.1},
+ "Ensure this value increments by 0.1.",
+ ),
+ ("float_off_step", 0.300001, {"step": 0.1}, "Ensure this value increments by 0.1."),
+ ("float_negative_rounding", -0.1 - 0.2, {"step": 0.1}, None),
+ ("float_step_from_minimum", 0.15 + 0.3, {"min": 0.15, "step": 0.1}, None),
+ (
+ "float_step_uses_minimum",
+ 0.4,
+ {"min": 0.15, "step": 0.1},
+ "Ensure this value increments by 0.1.",
+ ),
+ ("float_no_six_decimal_limit", 0.123456789, {}, None),
+ ("float_large_on_step", float(2**52), {"step": 2}, None),
+ ("float_large_off_step", float(2**52 + 1), {"step": 2}, "Ensure this value increments by 2."),
+ ("float_large_negative_off_step", -float(2**52 + 1), {"step": 2}, "Ensure this value increments by 2."),
+ (
+ "float_step_below_precision",
+ 0.1 + 0.2,
+ {"step": 1e-16},
+ "Ensure this value increments by 1E-16.",
+ ),
+ ("float_extreme_step_ratio", 1e308, {"step": 1e-308}, None),
+ ("float_tiny_step", 3e-308, {"step": 1e-308}, None),
+ ("float_tiny_off_step", 3.1e-308, {"step": 1e-308}, "Ensure this value increments by 1E-308."),
+ ("float_subnormal", 5e-324, {"step": 5e-324}, None),
+ ("float_exact_maximum", 0.3, {"max": 0.3}, None),
+ ("float_rounded_maximum", 7 * 0.1, {"max": 0.7, "step": 0.1}, None),
+ ("float_rounded_minimum", 0.7 - 0.4, {"min": 0.3}, None),
+ ("float_rounded_negative_minimum", -7 * 0.1, {"min": -0.7, "step": 0.1}, None),
+ ("float_adjacent_to_maximum", math.nextafter(0.3, math.inf), {"max": 0.3}, None),
+ ("float_adjacent_to_minimum", math.nextafter(0.3, -math.inf), {"min": 0.3}, None),
+ ("float_cancellation_at_zero", 0.3 - 0.1 - 0.2, {"min": 0, "step": 0.1}, None),
+ (
+ "float_above_maximum",
+ 0.3000001,
+ {"max": 0.3},
+ "Ensure this value is less than or equal to 0.3.",
+ ),
+ (
+ "float_below_minimum",
+ 0.2999999,
+ {"min": 0.3},
+ "Ensure this value is greater than or equal to 0.3.",
+ ),
+ (
+ "decimal_above_maximum",
+ Decimal("0.7000000000000001"),
+ {"max": 0.7},
+ "Ensure this value is less than or equal to 0.7.",
+ ),
+ (
+ "decimal_below_minimum",
+ Decimal("-0.0000000000000001"),
+ {"min": 0},
+ "Ensure this value is greater than or equal to 0.",
+ ),
+ (
+ "float_large_above_maximum",
+ float(2**52 + 1),
+ {"max": 2**52},
+ "Ensure this value is less than or equal to 4503599627370496.",
+ ),
+ (
+ "float_subnormal_above_maximum",
+ 1e-323,
+ {"max": 5e-324},
+ "Ensure this value is less than or equal to 5E-324.",
+ ),
+ (
+ "float_boundary_step_below_precision",
+ 7 * 0.1,
+ {"max": 0.7, "step": 1e-16},
+ "Ensure this value is less than or equal to 0.7.",
+ ),
+ ("zero", 0.0, {"min": 0, "max": 1, "step": 0.1}, None),
+ ("non_finite_value", math.inf, {}, "Provide a finite numeric value."),
+ (
+ "non_finite_config",
+ 0.5,
+ {"step": math.nan},
+ "This scorer has an invalid numeric configuration.",
+ ),
+ ]
+ )
+ def test_numeric_validation(
+ self, _name: str, value: Decimal | float, config: dict[str, object], expected_error: str | None
+ ) -> None:
+ self.assertEqual(
+ validate_score_value("numeric", config, numeric_value=value),
+ {"numeric_value": expected_error} if expected_error else {},
+ )
+
+ @parameterized.expand(
+ [
+ ("too_few", ["good"], {"categorical_values": "Select at least 2 categorical options."}),
+ ("minimum_satisfied", ["good", "accurate"], {}),
+ ("unknown_key", ["good", "unknown"], {"categorical_values": "Select valid categorical option keys."}),
+ ]
+ )
+ def test_categorical_minimum(self, _name: str, values: list[str], expected_errors: dict[str, str]) -> None:
+ self.assertEqual(
+ validate_score_value(
+ "categorical",
+ {
+ "options": [{"key": "good"}, {"key": "accurate"}],
+ "selection_mode": "multiple",
+ "min_selections": 2,
+ },
+ categorical_values=values,
+ ),
+ expected_errors,
+ )
+
+ @parameterized.expand(
+ [
+ ("categorical", "categorical_values"),
+ ("numeric", "numeric_value"),
+ ("boolean", "boolean_value"),
+ ]
+ )
+ def test_missing_value_reports_kind_specific_field(self, kind: str, field: str) -> None:
+ self.assertEqual(validate_score_value(kind, {}), {field: f"This scorer requires `{field}`."})
+
+ def test_false_is_a_score(self) -> None:
+ self.assertEqual(validate_score_value("boolean", {}, boolean_value=False), {})
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index e167625cc191..b0c37dfef94b 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -294,6 +294,378 @@ export interface InstrumentationCheckActionApi {
check: AIObservabilityInstrumentationCheckEnumApi
}
+/**
+ * * `ci` - CI
+ * * `local` - Local
+ * * `scheduled` - Scheduled
+ */
+export type OfflineExperimentRunSourceEnumApi =
+ (typeof OfflineExperimentRunSourceEnumApi)[keyof typeof OfflineExperimentRunSourceEnumApi]
+
+export const OfflineExperimentRunSourceEnumApi = {
+ Ci: 'ci',
+ Local: 'local',
+ Scheduled: 'scheduled',
+} as const
+
+export interface ExperimentSubmissionApi {
+ /** Caller-generated experiment UUID. Reuse it for exact retries. */
+ id: string
+ /**
+ * Display name for this experiment execution.
+ * @maxLength 400
+ */
+ name: string
+ /** Execution start time in ISO 8601 format, supplied by the caller. */
+ started_at: string
+ /** Where the execution started: ci, local, or scheduled. Omit or use null when unknown.
+ *
+ * * `ci` - CI
+ * * `local` - Local
+ * * `scheduled` - Scheduled */
+ run_source?: OfflineExperimentRunSourceEnumApi | null
+ /**
+ * Expected number of distinct items. Completion must match this count when supplied.
+ * @minimum 0
+ * @maximum 2147483647
+ * @nullable
+ */
+ expected_item_count?: number | null
+ /**
+ * Expected number of distinct item/scorer-version results, including non-success statuses.
+ * @minimum 0
+ * @maximum 2147483647
+ * @nullable
+ */
+ expected_result_count?: number | null
+ /**
+ * Stable identifier for comparing executions of the same evaluation suite.
+ * @maxLength 255
+ * @nullable
+ */
+ suite_key?: string | null
+ /**
+ * Source of an external dataset. Hosted dataset provenance is derived from its revision.
+ * @maxLength 255
+ * @nullable
+ */
+ dataset_source?: string | null
+ /**
+ * Stable identifier for the external dataset.
+ * @maxLength 255
+ * @nullable
+ */
+ dataset_identifier?: string | null
+ /**
+ * Pinned revision identifier of the external dataset.
+ * @maxLength 255
+ * @nullable
+ */
+ dataset_revision_identifier?: string | null
+ /**
+ * UUID of a hosted dataset revision in this project.
+ * @nullable
+ */
+ dataset_revision_id?: string | null
+ /**
+ * Version of the application under evaluation.
+ * @maxLength 255
+ * @nullable
+ */
+ application_version?: string | null
+ /**
+ * Version of the model under evaluation.
+ * @maxLength 255
+ * @nullable
+ */
+ model_version?: string | null
+ /**
+ * Version of the prompt under evaluation.
+ * @maxLength 255
+ * @nullable
+ */
+ prompt_version?: string | null
+}
+
+/**
+ * * `uploading` - Uploading
+ * * `completed` - Completed
+ * * `failed` - Failed
+ */
+export type OfflineExperimentStatusEnumApi =
+ (typeof OfflineExperimentStatusEnumApi)[keyof typeof OfflineExperimentStatusEnumApi]
+
+export const OfflineExperimentStatusEnumApi = {
+ Uploading: 'uploading',
+ Completed: 'completed',
+ Failed: 'failed',
+} as const
+
+export interface ExperimentReceiptApi {
+ /** Stable experiment UUID supplied at creation. */
+ id: string
+ /** Current upload lifecycle state.
+ *
+ * * `uploading` - Uploading
+ * * `completed` - Completed
+ * * `failed` - Failed */
+ status: OfflineExperimentStatusEnumApi
+ /** Whether this request created the experiment. */
+ created: boolean
+ /** Caller-supplied execution start time. */
+ started_at: string
+ /** Time the experiment was first accepted. */
+ created_at: string
+ /**
+ * Server closure time; null while uploading.
+ * @nullable
+ */
+ finished_at: string | null
+ /**
+ * Declared item count, when supplied.
+ * @nullable
+ */
+ expected_item_count: number | null
+ /**
+ * Declared result count, when supplied.
+ * @nullable
+ */
+ expected_result_count: number | null
+ /** Number of unique accepted items. */
+ accepted_item_count: number
+ /** Number of unique accepted results across all statuses. */
+ accepted_result_count: number
+}
+
+export interface OfflineEvaluationValidationErrorApi {
+ /** Stable validation error code. */
+ code: string
+ /** Explanation of the invalid value. */
+ detail: string
+ /**
+ * Invalid field path, with dot-separated fields and zero-based batch indexes.
+ * @nullable
+ */
+ attr: string | null
+}
+
+export interface OfflineEvaluationErrorApi {
+ /** Error category for standard API errors. */
+ type?: string
+ /** Stable error code. */
+ code: string
+ /** Explanation of the rejected request. */
+ detail: string
+ /**
+ * Invalid field, including batch entry index.
+ * @nullable
+ */
+ attr?: string | null
+ /**
+ * Declared item count.
+ * @nullable
+ */
+ expected_item_count?: number | null
+ /**
+ * Declared result count.
+ * @nullable
+ */
+ expected_result_count?: number | null
+ /** Accepted items at failed completion. */
+ accepted_item_count?: number
+ /** Accepted results at failed completion. */
+ accepted_result_count?: number
+ /** All validation errors found in the request. */
+ errors?: OfflineEvaluationValidationErrorApi[]
+}
+
+export type OfflineExperimentItemPayloadInputApiInput =
+ | { [key: string]: unknown }
+ | unknown[]
+ | string
+ | number
+ | boolean
+ | null
+
+export type OfflineExperimentItemPayloadInputApiOutput =
+ | { [key: string]: unknown }
+ | unknown[]
+ | string
+ | number
+ | boolean
+ | null
+
+export type OfflineExperimentItemPayloadInputApiExpectedOutput =
+ | { [key: string]: unknown }
+ | unknown[]
+ | string
+ | number
+ | boolean
+ | null
+
+/**
+ * @nullable
+ */
+export type OfflineExperimentItemPayloadInputApiMetadata = { [key: string]: unknown } | null
+
+export interface OfflineExperimentItemPayloadInputApi {
+ input?: OfflineExperimentItemPayloadInputApiInput
+ output?: OfflineExperimentItemPayloadInputApiOutput
+ expected_output?: OfflineExperimentItemPayloadInputApiExpectedOutput
+ /** @nullable */
+ metadata?: OfflineExperimentItemPayloadInputApiMetadata
+}
+
+export interface ItemSubmissionApi {
+ /** Caller-generated UUID for one input/output execution. Reuse for exact retries. */
+ id: string
+ /**
+ * Stable case identifier for matching inputs across experiments.
+ * @maxLength 255
+ * @nullable
+ */
+ case_key?: string | null
+ /**
+ * Identifier for a repeated execution of the same case.
+ * @maxLength 255
+ * @nullable
+ */
+ trial?: string | null
+ /**
+ * Stable item identifier in an external dataset.
+ * @maxLength 255
+ * @nullable
+ */
+ dataset_item_identifier?: string | null
+ /**
+ * Pinned item-version identifier in an external dataset.
+ * @maxLength 255
+ * @nullable
+ */
+ dataset_item_version_identifier?: string | null
+ /**
+ * UUID of the hosted item version in the experiment's dataset revision.
+ * @nullable
+ */
+ dataset_item_version_id?: string | null
+ /**
+ * Trace identifier for the application execution that produced this output.
+ * @maxLength 255
+ * @nullable
+ */
+ application_trace_id?: string | null
+ /** Optional input/output payload, up to 1 MiB and 32 JSON levels. Omission, {} and null properties differ. */
+ payload?: OfflineExperimentItemPayloadInputApi
+}
+
+/**
+ * * `ok` - OK
+ * * `error` - Error
+ * * `skipped` - Skipped
+ * * `not_applicable` - Not applicable
+ */
+export type OfflineEvaluationResultStatusEnumApi =
+ (typeof OfflineEvaluationResultStatusEnumApi)[keyof typeof OfflineEvaluationResultStatusEnumApi]
+
+export const OfflineEvaluationResultStatusEnumApi = {
+ Ok: 'ok',
+ Error: 'error',
+ Skipped: 'skipped',
+ NotApplicable: 'not_applicable',
+} as const
+
+/**
+ * @nullable
+ */
+export type OfflineEvaluationResultPayloadInputApiMetadata = { [key: string]: unknown } | null
+
+export interface OfflineEvaluationResultPayloadInputApi {
+ /** @nullable */
+ reasoning?: string | null
+ /** @nullable */
+ error_message?: string | null
+ /** @nullable */
+ metadata?: OfflineEvaluationResultPayloadInputApiMetadata
+}
+
+export interface ResultSubmissionApi {
+ /** UUID of an item declared in this request or already accepted in this experiment. */
+ item_id: string
+ /** Exact UUID of an existing scorer version in this project. */
+ scorer_version_id: string
+ /** Outcome of this scorer execution.
+ *
+ * * `ok` - OK
+ * * `error` - Error
+ * * `skipped` - Skipped
+ * * `not_applicable` - Not applicable */
+ status: OfflineEvaluationResultStatusEnumApi
+ /** Required for ok: finite number, boolean, or distinct category keys matching the scorer version. */
+ value?: number | boolean | string[] | null
+ /**
+ * Optional stable error code, permitted only for error outcomes.
+ * @maxLength 128
+ * @nullable
+ */
+ error_code?: string | null
+ /**
+ * Trace identifier of the evaluator that produced this result.
+ * @maxLength 255
+ * @nullable
+ */
+ evaluator_trace_id?: string | null
+ /**
+ * Caller-supplied evaluation time in ISO 8601 format.
+ * @nullable
+ */
+ evaluated_at?: string | null
+ /** Optional reasoning, error message, and metadata, up to 256 KiB and 32 JSON levels. */
+ payload?: OfflineEvaluationResultPayloadInputApi
+}
+
+export interface UploadSubmissionApi {
+ /**
+ * Complete immutable declarations for referenced items. Omit existing items to reuse them without a payload.
+ * @maxItems 1000
+ */
+ items?: ItemSubmissionApi[]
+ /**
+ * One to 1,000 unique item/scorer-version results. The entire request commits atomically.
+ * @minItems 1
+ * @maxItems 1000
+ */
+ results: ResultSubmissionApi[]
+}
+
+export interface ItemReceiptApi {
+ /** Accepted item UUID. */
+ id: string
+ /** Whether this upload created the item. */
+ created: boolean
+ /** Original server acceptance time, unchanged on retry. */
+ accepted_at: string
+}
+
+export interface ResultReceiptApi {
+ /** Accepted item UUID. */
+ id: string
+ /** Whether this upload created the item. */
+ created: boolean
+ /** Original server acceptance time, unchanged on retry. */
+ accepted_at: string
+ /** Item this result evaluates. */
+ item_id: string
+ /** Pinned scorer version used by this result. */
+ scorer_version_id: string
+}
+
+export interface UploadReceiptApi {
+ /** One acknowledgment per referenced item. */
+ items: ItemReceiptApi[]
+ /** Acknowledgments in the submitted result order. */
+ results: ResultReceiptApi[]
+}
+
export type DatasetJSONValueApi = { [key: string]: unknown } | unknown[] | string | number | boolean
/**
diff --git a/products/ai_observability/frontend/generated/api.ts b/products/ai_observability/frontend/generated/api.ts
index c4aa6b149073..dd73abb7d027 100644
--- a/products/ai_observability/frontend/generated/api.ts
+++ b/products/ai_observability/frontend/generated/api.ts
@@ -43,6 +43,8 @@ import type {
EvaluationRunResponseApi,
EvaluationsBackfillsListParams,
EvaluationsListParams,
+ ExperimentReceiptApi,
+ ExperimentSubmissionApi,
InstrumentationCheckActionApi,
InstrumentationChecklistApi,
LLMModelsListResponseApi,
@@ -124,6 +126,8 @@ import type {
TraceReviewApi,
TraceReviewCreateApi,
TranslateRequestApi,
+ UploadReceiptApi,
+ UploadSubmissionApi,
} from './api.schemas'
// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
@@ -254,6 +258,71 @@ export const aiObservabilityInstrumentationChecklistRestoreCreate = async (
)
}
+export const getAiObservabilityOfflineExperimentsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/ai_observability/offline_experiments/`
+}
+
+export const aiObservabilityOfflineExperimentsCreate = async (
+ projectId: string,
+ experimentSubmissionApi: ExperimentSubmissionApi,
+ options?: RequestInit
+): Promise<ExperimentReceiptApi> => {
+ return apiMutator<ExperimentReceiptApi>(getAiObservabilityOfflineExperimentsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(experimentSubmissionApi),
+ })
+}
+
+export const getAiObservabilityOfflineExperimentsCompleteCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/ai_observability/offline_experiments/${id}/complete/`
+}
+
+export const aiObservabilityOfflineExperimentsCompleteCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<ExperimentReceiptApi> => {
+ return apiMutator<ExperimentReceiptApi>(getAiObservabilityOfflineExperimentsCompleteCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getAiObservabilityOfflineExperimentsFailCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/ai_observability/offline_experiments/${id}/fail/`
+}
+
+export const aiObservabilityOfflineExperimentsFailCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<ExperimentReceiptApi> => {
+ return apiMutator<ExperimentReceiptApi>(getAiObservabilityOfflineExperimentsFailCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getAiObservabilityOfflineExperimentsUploadCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/ai_observability/offline_experiments/${id}/upload/`
+}
+
+export const aiObservabilityOfflineExperimentsUploadCreate = async (
+ projectId: string,
+ id: string,
+ uploadSubmissionApi: UploadSubmissionApi,
+ options?: RequestInit
+): Promise<UploadReceiptApi> => {
+ return apiMutator<UploadReceiptApi>(getAiObservabilityOfflineExperimentsUploadCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(uploadSubmissionApi),
+ })
+}
+
export const getDatasetItemsListUrl = (projectId: string, params: DatasetItemsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.ts
index cc1127ecff64..90024459bec7 100644
--- a/products/ai_observability/frontend/generated/api.zod.ts
+++ b/products/ai_observability/frontend/generated/api.zod.ts
@@ -37,6 +37,260 @@ export const AiObservabilityInstrumentationChecklistRestoreCreateBody = /* @__PU
),
})
+export const aiObservabilityOfflineExperimentsCreateBodyNameMax = 400
+
+export const aiObservabilityOfflineExperimentsCreateBodyExpectedItemCountMin = 0
+export const aiObservabilityOfflineExperimentsCreateBodyExpectedItemCountMax = 2147483647
+
+export const aiObservabilityOfflineExperimentsCreateBodyExpectedResultCountMin = 0
+export const aiObservabilityOfflineExperimentsCreateBodyExpectedResultCountMax = 2147483647
+
+export const aiObservabilityOfflineExperimentsCreateBodySuiteKeyMax = 255
+
+export const aiObservabilityOfflineExperimentsCreateBodyDatasetSourceMax = 255
+
+export const aiObservabilityOfflineExperimentsCreateBodyDatasetIdentifierMax = 255
+
+export const aiObservabilityOfflineExperimentsCreateBodyDatasetRevisionIdentifierMax = 255
+
+export const aiObservabilityOfflineExperimentsCreateBodyApplicationVersionMax = 255
+
+export const aiObservabilityOfflineExperimentsCreateBodyModelVersionMax = 255
+
+export const aiObservabilityOfflineExperimentsCreateBodyPromptVersionMax = 255
+
+export const AiObservabilityOfflineExperimentsCreateBody = /* @__PURE__ */ zod.object({
+ id: zod.uuid().describe('Caller-generated experiment UUID. Reuse it for exact retries.'),
+ name: zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsCreateBodyNameMax)
+ .describe('Display name for this experiment execution.'),
+ started_at: zod.iso
+ .datetime({ offset: true })
+ .describe('Execution start time in ISO 8601 format, supplied by the caller.'),
+ run_source: zod
+ .union([
+ zod
+ .enum(['ci', 'local', 'scheduled'])
+ .describe('\* `ci` - CI\n\* `local` - Local\n\* `scheduled` - Scheduled'),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Where the execution started: ci, local, or scheduled. Omit or use null when unknown.\n\n\* `ci` - CI\n\* `local` - Local\n\* `scheduled` - Scheduled'
+ ),
+ expected_item_count: zod
+ .number()
+ .min(aiObservabilityOfflineExperimentsCreateBodyExpectedItemCountMin)
+ .max(aiObservabilityOfflineExperimentsCreateBodyExpectedItemCountMax)
+ .nullish()
+ .describe('Expected number of distinct items. Completion must match this count when supplied.'),
+ expected_result_count: zod
+ .number()
+ .min(aiObservabilityOfflineExperimentsCreateBodyExpectedResultCountMin)
+ .max(aiObservabilityOfflineExperimentsCreateBodyExpectedResultCountMax)
+ .nullish()
+ .describe('Expected number of distinct item\/scorer-version results, including non-success statuses.'),
+ suite_key: zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsCreateBodySuiteKeyMax)
+ .nullish()
+ .describe('Stable identifier for comparing executions of the same evaluation suite.'),
+ dataset_source: zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsCreateBodyDatasetSourceMax)
+ .nullish()
+ .describe('Source of an external dataset. Hosted dataset provenance is derived from its revision.'),
+ dataset_identifier: zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsCreateBodyDatasetIdentifierMax)
+ .nullish()
+ .describe('Stable identifier for the external dataset.'),
+ dataset_revision_identifier: zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsCreateBodyDatasetRevisionIdentifierMax)
+ .nullish()
+ .describe('Pinned revision identifier of the external dataset.'),
+ dataset_revision_id: zod.uuid().nullish().describe('UUID of a hosted dataset revision in this project.'),
+ application_version: zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsCreateBodyApplicationVersionMax)
+ .nullish()
+ .describe('Version of the application under evaluation.'),
+ model_version: zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsCreateBodyModelVersionMax)
+ .nullish()
+ .describe('Version of the model under evaluation.'),
+ prompt_version: zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsCreateBodyPromptVersionMax)
+ .nullish()
+ .describe('Version of the prompt under evaluation.'),
+})
+
+export const aiObservabilityOfflineExperimentsUploadCreateBodyItemsItemCaseKeyMax = 255
+
+export const aiObservabilityOfflineExperimentsUploadCreateBodyItemsItemTrialMax = 255
+
+export const aiObservabilityOfflineExperimentsUploadCreateBodyItemsItemDatasetItemIdentifierMax = 255
+
+export const aiObservabilityOfflineExperimentsUploadCreateBodyItemsItemDatasetItemVersionIdentifierMax = 255
+
+export const aiObservabilityOfflineExperimentsUploadCreateBodyItemsItemApplicationTraceIdMax = 255
+
+export const aiObservabilityOfflineExperimentsUploadCreateBodyItemsMax = 1000
+
+export const aiObservabilityOfflineExperimentsUploadCreateBodyResultsItemValueThreeItemMax = 128
+
+export const aiObservabilityOfflineExperimentsUploadCreateBodyResultsItemErrorCodeMax = 128
+
+export const aiObservabilityOfflineExperimentsUploadCreateBodyResultsItemEvaluatorTraceIdMax = 255
+
+export const aiObservabilityOfflineExperimentsUploadCreateBodyResultsMax = 1000
+
+export const AiObservabilityOfflineExperimentsUploadCreateBody = /* @__PURE__ */ zod.object({
+ items: zod
+ .array(
+ zod.object({
+ id: zod
+ .uuid()
+ .describe('Caller-generated UUID for one input\/output execution. Reuse for exact retries.'),
+ case_key: zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsUploadCreateBodyItemsItemCaseKeyMax)
+ .nullish()
+ .describe('Stable case identifier for matching inputs across experiments.'),
+ trial: zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsUploadCreateBodyItemsItemTrialMax)
+ .nullish()
+ .describe('Identifier for a repeated execution of the same case.'),
+ dataset_item_identifier: zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsUploadCreateBodyItemsItemDatasetItemIdentifierMax)
+ .nullish()
+ .describe('Stable item identifier in an external dataset.'),
+ dataset_item_version_identifier: zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsUploadCreateBodyItemsItemDatasetItemVersionIdentifierMax)
+ .nullish()
+ .describe('Pinned item-version identifier in an external dataset.'),
+ dataset_item_version_id: zod
+ .uuid()
+ .nullish()
+ .describe("UUID of the hosted item version in the experiment's dataset revision."),
+ application_trace_id: zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsUploadCreateBodyItemsItemApplicationTraceIdMax)
+ .nullish()
+ .describe('Trace identifier for the application execution that produced this output.'),
+ payload: zod
+ .object({
+ input: zod
+ .union([
+ zod.record(zod.string(), zod.unknown()),
+ zod.array(zod.unknown()),
+ zod.string(),
+ zod.number(),
+ zod.boolean(),
+ zod.null(),
+ ])
+ .optional(),
+ output: zod
+ .union([
+ zod.record(zod.string(), zod.unknown()),
+ zod.array(zod.unknown()),
+ zod.string(),
+ zod.number(),
+ zod.boolean(),
+ zod.null(),
+ ])
+ .optional(),
+ expected_output: zod
+ .union([
+ zod.record(zod.string(), zod.unknown()),
+ zod.array(zod.unknown()),
+ zod.string(),
+ zod.number(),
+ zod.boolean(),
+ zod.null(),
+ ])
+ .optional(),
+ metadata: zod.record(zod.string(), zod.unknown()).nullish(),
+ })
+ .optional()
+ .describe(
+ 'Optional input\/output payload, up to 1 MiB and 32 JSON levels. Omission, {} and null properties differ.'
+ ),
+ })
+ )
+ .max(aiObservabilityOfflineExperimentsUploadCreateBodyItemsMax)
+ .optional()
+ .describe(
+ 'Complete immutable declarations for referenced items. Omit existing items to reuse them without a payload.'
+ ),
+ results: zod
+ .array(
+ zod.object({
+ item_id: zod
+ .uuid()
+ .describe('UUID of an item declared in this request or already accepted in this experiment.'),
+ scorer_version_id: zod.uuid().describe('Exact UUID of an existing scorer version in this project.'),
+ status: zod
+ .enum(['ok', 'error', 'skipped', 'not_applicable'])
+ .describe(
+ '\* `ok` - OK\n\* `error` - Error\n\* `skipped` - Skipped\n\* `not_applicable` - Not applicable'
+ )
+ .describe(
+ 'Outcome of this scorer execution.\n\n\* `ok` - OK\n\* `error` - Error\n\* `skipped` - Skipped\n\* `not_applicable` - Not applicable'
+ ),
+ value: zod
+ .union([
+ zod.number(),
+ zod.boolean(),
+ zod
+ .array(
+ zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsUploadCreateBodyResultsItemValueThreeItemMax)
+ )
+ .min(1),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Required for ok: finite number, boolean, or distinct category keys matching the scorer version.'
+ ),
+ error_code: zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsUploadCreateBodyResultsItemErrorCodeMax)
+ .nullish()
+ .describe('Optional stable error code, permitted only for error outcomes.'),
+ evaluator_trace_id: zod
+ .string()
+ .max(aiObservabilityOfflineExperimentsUploadCreateBodyResultsItemEvaluatorTraceIdMax)
+ .nullish()
+ .describe('Trace identifier of the evaluator that produced this result.'),
+ evaluated_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('Caller-supplied evaluation time in ISO 8601 format.'),
+ payload: zod
+ .object({
+ reasoning: zod.string().nullish(),
+ error_message: zod.string().nullish(),
+ metadata: zod.record(zod.string(), zod.unknown()).nullish(),
+ })
+ .optional()
+ .describe('Optional reasoning, error message, and metadata, up to 256 KiB and 32 JSON levels.'),
+ })
+ )
+ .min(1)
+ .max(aiObservabilityOfflineExperimentsUploadCreateBodyResultsMax)
+ .describe('One to 1,000 unique item\/scorer-version results. The entire request commits atomically.'),
+})
+
/**
* Create an item and its first immutable version. An identical client item ID retry returns the existing item. A different payload or an archived match returns a conflict.
*/
diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yaml
index d607697fa48a..cd6078b70b6e 100644
--- a/products/ai_observability/mcp/tools.yaml
+++ b/products/ai_observability/mcp/tools.yaml
@@ -23,6 +23,18 @@ tools:
ai-observability-instrumentation-checklist-retrieve:
operation: ai_observability_instrumentation_checklist_retrieve
enabled: false
+ ai-observability-offline-experiments-complete-create:
+ operation: ai_observability_offline_experiments_complete_create
+ enabled: false
+ ai-observability-offline-experiments-create:
+ operation: ai_observability_offline_experiments_create
+ enabled: false
+ ai-observability-offline-experiments-fail-create:
+ operation: ai_observability_offline_experiments_fail_create
+ enabled: false
+ ai-observability-offline-experiments-upload-create:
+ operation: ai_observability_offline_experiments_upload_create
+ enabled: false
datasets-exports-content-retrieve:
operation: datasets_exports_content_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 708e7211d0a0..9972e0255636 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -40848,6 +40848,56 @@ export namespace Schemas {
estimated_rows_total?: number | null;
}
+ /**
+ * * `uploading` - Uploading
+ * * `completed` - Completed
+ * * `failed` - Failed
+ */
+ export type OfflineExperimentStatusEnum = typeof OfflineExperimentStatusEnum[keyof typeof OfflineExperimentStatusEnum];
+
+
+ export const OfflineExperimentStatusEnum = {
+ Uploading: 'uploading',
+ Completed: 'completed',
+ Failed: 'failed',
+ } as const;
+
+ export interface ExperimentReceipt {
+ /** Stable experiment UUID supplied at creation. */
+ id: string;
+ /** Current upload lifecycle state.
+ *
+ * * `uploading` - Uploading
+ * * `completed` - Completed
+ * * `failed` - Failed */
+ status: OfflineExperimentStatusEnum;
+ /** Whether this request created the experiment. */
+ created: boolean;
+ /** Caller-supplied execution start time. */
+ started_at: string;
+ /** Time the experiment was first accepted. */
+ created_at: string;
+ /**
+ * Server closure time; null while uploading.
+ * @nullable
+ */
+ finished_at: string | null;
+ /**
+ * Declared item count, when supplied.
+ * @nullable
+ */
+ expected_item_count: number | null;
+ /**
+ * Declared result count, when supplied.
+ * @nullable
+ */
+ expected_result_count: number | null;
+ /** Number of unique accepted items. */
+ accepted_item_count: number;
+ /** Number of unique accepted results across all statuses. */
+ accepted_result_count: number;
+ }
+
export type ExperimentResultsWidgetCatalogEntryOpenApiWidgetType = typeof ExperimentResultsWidgetCatalogEntryOpenApiWidgetType[keyof typeof ExperimentResultsWidgetCatalogEntryOpenApiWidgetType];
@@ -41992,6 +42042,99 @@ export namespace Schemas {
shared_metrics: ExperimentSetupSharedMetricsSection;
}
+ /**
+ * * `ci` - CI
+ * * `local` - Local
+ * * `scheduled` - Scheduled
+ */
+ export type OfflineExperimentRunSourceEnum = typeof OfflineExperimentRunSourceEnum[keyof typeof OfflineExperimentRunSourceEnum];
+
+
+ export const OfflineExperimentRunSourceEnum = {
+ Ci: 'ci',
+ Local: 'local',
+ Scheduled: 'scheduled',
+ } as const;
+
+ export interface ExperimentSubmission {
+ /** Caller-generated experiment UUID. Reuse it for exact retries. */
+ id: string;
+ /**
+ * Display name for this experiment execution.
+ * @maxLength 400
+ */
+ name: string;
+ /** Execution start time in ISO 8601 format, supplied by the caller. */
+ started_at: string;
+ /** Where the execution started: ci, local, or scheduled. Omit or use null when unknown.
+ *
+ * * `ci` - CI
+ * * `local` - Local
+ * * `scheduled` - Scheduled */
+ run_source?: OfflineExperimentRunSourceEnum | null;
+ /**
+ * Expected number of distinct items. Completion must match this count when supplied.
+ * @minimum 0
+ * @maximum 2147483647
+ * @nullable
+ */
+ expected_item_count?: number | null;
+ /**
+ * Expected number of distinct item/scorer-version results, including non-success statuses.
+ * @minimum 0
+ * @maximum 2147483647
+ * @nullable
+ */
+ expected_result_count?: number | null;
+ /**
+ * Stable identifier for comparing executions of the same evaluation suite.
+ * @maxLength 255
+ * @nullable
+ */
+ suite_key?: string | null;
+ /**
+ * Source of an external dataset. Hosted dataset provenance is derived from its revision.
+ * @maxLength 255
+ * @nullable
+ */
+ dataset_source?: string | null;
+ /**
+ * Stable identifier for the external dataset.
+ * @maxLength 255
+ * @nullable
+ */
+ dataset_identifier?: string | null;
+ /**
+ * Pinned revision identifier of the external dataset.
+ * @maxLength 255
+ * @nullable
+ */
+ dataset_revision_identifier?: string | null;
+ /**
+ * UUID of a hosted dataset revision in this project.
+ * @nullable
+ */
+ dataset_revision_id?: string | null;
+ /**
+ * Version of the application under evaluation.
+ * @maxLength 255
+ * @nullable
+ */
+ application_version?: string | null;
+ /**
+ * Version of the model under evaluation.
+ * @maxLength 255
+ * @nullable
+ */
+ model_version?: string | null;
+ /**
+ * Version of the prompt under evaluation.
+ * @maxLength 255
+ * @nullable
+ */
+ prompt_version?: string | null;
+ }
+
/**
* The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.
* @nullable
@@ -54585,6 +54728,76 @@ export namespace Schemas {
readonly unavailable: readonly string[];
}
+ export interface ItemReceipt {
+ /** Accepted item UUID. */
+ id: string;
+ /** Whether this upload created the item. */
+ created: boolean;
+ /** Original server acceptance time, unchanged on retry. */
+ accepted_at: string;
+ }
+
+ export type OfflineExperimentItemPayloadInputInput = { [key: string]: unknown } | unknown[] | string | number | boolean | null;
+
+ export type OfflineExperimentItemPayloadInputOutput = { [key: string]: unknown } | unknown[] | string | number | boolean | null;
+
+ export type OfflineExperimentItemPayloadInputExpectedOutput = { [key: string]: unknown } | unknown[] | string | number | boolean | null;
+
+ /**
+ * @nullable
+ */
+ export type OfflineExperimentItemPayloadInputMetadata = { [key: string]: unknown } | null;
+
+ export interface OfflineExperimentItemPayloadInput {
+ input?: OfflineExperimentItemPayloadInputInput;
+ output?: OfflineExperimentItemPayloadInputOutput;
+ expected_output?: OfflineExperimentItemPayloadInputExpectedOutput;
+ /** @nullable */
+ metadata?: OfflineExperimentItemPayloadInputMetadata;
+ }
+
+ export interface ItemSubmission {
+ /** Caller-generated UUID for one input/output execution. Reuse for exact retries. */
+ id: string;
+ /**
+ * Stable case identifier for matching inputs across experiments.
+ * @maxLength 255
+ * @nullable
+ */
+ case_key?: string | null;
+ /**
+ * Identifier for a repeated execution of the same case.
+ * @maxLength 255
+ * @nullable
+ */
+ trial?: string | null;
+ /**
+ * Stable item identifier in an external dataset.
+ * @maxLength 255
+ * @nullable
+ */
+ dataset_item_identifier?: string | null;
+ /**
+ * Pinned item-version identifier in an external dataset.
+ * @maxLength 255
+ * @nullable
+ */
+ dataset_item_version_identifier?: string | null;
+ /**
+ * UUID of the hosted item version in the experiment's dataset revision.
+ * @nullable
+ */
+ dataset_item_version_id?: string | null;
+ /**
+ * Trace identifier for the application execution that produced this output.
+ * @maxLength 255
+ * @nullable
+ */
+ application_trace_id?: string | null;
+ /** Optional input/output payload, up to 1 MiB and 32 JSON levels. Omission, {} and null properties differ. */
+ payload?: OfflineExperimentItemPayloadInput;
+ }
+
/**
* Keyword arguments for the estimator's constructor; null or absent means the defaults.
* @nullable
@@ -61760,6 +61973,78 @@ export namespace Schemas {
workflow_id: string;
}
+ export interface OfflineEvaluationValidationError {
+ /** Stable validation error code. */
+ code: string;
+ /** Explanation of the invalid value. */
+ detail: string;
+ /**
+ * Invalid field path, with dot-separated fields and zero-based batch indexes.
+ * @nullable
+ */
+ attr: string | null;
+ }
+
+ export interface OfflineEvaluationError {
+ /** Error category for standard API errors. */
+ type?: string;
+ /** Stable error code. */
+ code: string;
+ /** Explanation of the rejected request. */
+ detail: string;
+ /**
+ * Invalid field, including batch entry index.
+ * @nullable
+ */
+ attr?: string | null;
+ /**
+ * Declared item count.
+ * @nullable
+ */
+ expected_item_count?: number | null;
+ /**
+ * Declared result count.
+ * @nullable
+ */
+ expected_result_count?: number | null;
+ /** Accepted items at failed completion. */
+ accepted_item_count?: number;
+ /** Accepted results at failed completion. */
+ accepted_result_count?: number;
+ /** All validation errors found in the request. */
+ errors?: OfflineEvaluationValidationError[];
+ }
+
+ /**
+ * @nullable
+ */
+ export type OfflineEvaluationResultPayloadInputMetadata = { [key: string]: unknown } | null;
+
+ export interface OfflineEvaluationResultPayloadInput {
+ /** @nullable */
+ reasoning?: string | null;
+ /** @nullable */
+ error_message?: string | null;
+ /** @nullable */
+ metadata?: OfflineEvaluationResultPayloadInputMetadata;
+ }
+
+ /**
+ * * `ok` - OK
+ * * `error` - Error
+ * * `skipped` - Skipped
+ * * `not_applicable` - Not applicable
+ */
+ export type OfflineEvaluationResultStatusEnum = typeof OfflineEvaluationResultStatusEnum[keyof typeof OfflineEvaluationResultStatusEnum];
+
+
+ export const OfflineEvaluationResultStatusEnum = {
+ Ok: 'ok',
+ Error: 'error',
+ Skipped: 'skipped',
+ NotApplicable: 'not_applicable',
+ } as const;
+
export interface OfflineExperimentItemsRequest {
/** `$ai_experiment_id` whose offline-evaluation items to return. */
experiment_id: string;
@@ -86499,6 +86784,54 @@ export namespace Schemas {
Rejected: 'rejected',
} as const;
+ export interface ResultReceipt {
+ /** Accepted item UUID. */
+ id: string;
+ /** Whether this upload created the item. */
+ created: boolean;
+ /** Original server acceptance time, unchanged on retry. */
+ accepted_at: string;
+ /** Item this result evaluates. */
+ item_id: string;
+ /** Pinned scorer version used by this result. */
+ scorer_version_id: string;
+ }
+
+ export interface ResultSubmission {
+ /** UUID of an item declared in this request or already accepted in this experiment. */
+ item_id: string;
+ /** Exact UUID of an existing scorer version in this project. */
+ scorer_version_id: string;
+ /** Outcome of this scorer execution.
+ *
+ * * `ok` - OK
+ * * `error` - Error
+ * * `skipped` - Skipped
+ * * `not_applicable` - Not applicable */
+ status: OfflineEvaluationResultStatusEnum;
+ /** Required for ok: finite number, boolean, or distinct category keys matching the scorer version. */
+ value?: number | boolean | string[] | null;
+ /**
+ * Optional stable error code, permitted only for error outcomes.
+ * @maxLength 128
+ * @nullable
+ */
+ error_code?: string | null;
+ /**
+ * Trace identifier of the evaluator that produced this result.
+ * @maxLength 255
+ * @nullable
+ */
+ evaluator_trace_id?: string | null;
+ /**
+ * Caller-supplied evaluation time in ISO 8601 format.
+ * @nullable
+ */
+ evaluated_at?: string | null;
+ /** Optional reasoning, error message, and metadata, up to 256 KiB and 32 JSON levels. */
+ payload?: OfflineEvaluationResultPayloadInput;
+ }
+
export type RetrieveBasicOutputStatus = typeof RetrieveBasicOutputStatus[keyof typeof RetrieveBasicOutputStatus];
@@ -99682,6 +100015,27 @@ export namespace Schemas {
success: boolean;
}
+ export interface UploadReceipt {
+ /** One acknowledgment per referenced item. */
+ items: ItemReceipt[];
+ /** Acknowledgments in the submitted result order. */
+ results: ResultReceipt[];
+ }
+
+ export interface UploadSubmission {
+ /**
+ * Complete immutable declarations for referenced items. Omit existing items to reuse them without a payload.
+ * @maxItems 1000
+ */
+ items?: ItemSubmission[];
+ /**
+ * One to 1,000 unique item/scorer-version results. The entire request commits atomically.
+ * @minItems 1
+ * @maxItems 1000
+ */
+ results: ResultSubmission[];
+ }
+
export interface UploadVersionRequest {
/** Zip archive containing the Streamlit app sources (max 10 MB). */
file: string;
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index 81c55d9ff4b6..67a965677464 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -148,6 +148,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'metrics:write',
'notebook:read',
'notebook:write',
+ 'offline_evaluation_ingestion:read',
+ 'offline_evaluation_ingestion:write',
'organization:read',
'organization:write',
'organization_integration:read',