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(autoresearch): add the read-only model, run and training-run endpoints (15/22) (#89146)

Andrew Maguirec98bd2790118
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 3ed94d47d4a0..80cc1d55d518 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -591,10 +591,14 @@ SPECTACULAR_SETTINGS = {
# Matches replay_vision's VisionAlertState.
"LogsAlertConfigurationStateEnum": "products.logs.backend.models.LogsAlertConfiguration.State",
"LogsPatternsSourceEnum": ["stored_patterns", "body_mining"],
+ # AutoresearchRun.Status and AutoresearchTrainingRun.Status share this set.
+ "ZendeskImportJobStatusEnum": "products.conversations.backend.models.zendesk_import_job.ZendeskImportJob.Status",
#
# The published name is already derived by a different choice set, so the
# entry holds this one apart.
"SlackSummaryCadenceEnum": ["daily", "weekly", "monthly"],
+ # signals' report-metric role; AutoresearchModel.Role also sits on a field named `role`.
+ "RoleEnum": ["primary", "supporting"],
# visual_review facade enums are framework-free StrEnums, so no Choices class derives a name.
"ShiftBandKindEnum": ["inserted", "deleted"],
"ExperimentStatusEnum": ["draft", "running", "paused", "exposure_frozen", "stopped"],
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.py
index c075666d7bf5..d85298f09514 100644
--- a/products/autoresearch/backend/facade/api.py
+++ b/products/autoresearch/backend/facade/api.py
@@ -27,16 +27,27 @@ from ..dataset.validation import (
ValidationWarningCode as _ValidationWarningCode,
validate_pipeline_definition as _validate_pipeline_definition,
)
-from ..models import AutoresearchModel, AutoresearchPipeline
+from ..models import (
+ AutoresearchIteration,
+ AutoresearchModel,
+ AutoresearchPipeline,
+ AutoresearchRun,
+ AutoresearchTrainingRun,
+)
from .contracts import (
AutoresearchConflict,
InvalidTarget,
+ IterationTrailEntry,
+ Model,
Pipeline,
PipelineNotFound,
PipelineValidation,
PipelineWrite,
ResolvedTemplate,
+ Run,
TemplateInfo,
+ TrainingRun,
+ TrainingRunNotFound,
ValidationWarning,
)
@@ -48,6 +59,20 @@ def flag_key() -> str:
return AUTORESEARCH_FLAG
+def _as_uuid(value: str | UUID | None) -> UUID | None:
+ """A pk from a URL as a UUID, or None when it cannot be one.
+
+ An id that is not a UUID matches nothing, so callers filter it down to an empty result
+ rather than letting the malformed value reach the database.
+ """
+ if value is None:
+ return None
+ try:
+ return value if isinstance(value, UUID) else UUID(str(value))
+ except (ValueError, AttributeError, TypeError):
+ return None
+
+
# ── Mappers ────────────────────────────────────────────────────────────────
@@ -96,6 +121,77 @@ def _pipeline_with_champion(row: AutoresearchPipeline) -> Pipeline:
)
+def _model_to_contract(row: AutoresearchModel) -> Model:
+ return Model(
+ id=row.id,
+ pipeline=row.pipeline_id,
+ role=row.role,
+ recipe_hash=row.recipe_hash,
+ model_recipe=row.model_recipe or {},
+ model_explanation=row.model_explanation or {},
+ holdout_score=row.holdout_score,
+ realized_score=row.realized_score,
+ calibration_error=row.calibration_error,
+ metrics=row.metrics or {},
+ source_training_run=row.source_training_run_id,
+ agent_description=row.agent_description,
+ trained_on_start=row.trained_on_start,
+ trained_on_end=row.trained_on_end,
+ is_preliminary=row.is_preliminary,
+ promoted_at=row.promoted_at,
+ archived_at=row.archived_at,
+ created_at=row.created_at,
+ updated_at=row.updated_at,
+ )
+
+
+def _iteration_trail_entry(row: AutoresearchIteration) -> IterationTrailEntry:
+ return IterationTrailEntry(
+ iteration_number=row.iteration_number,
+ status=row.status,
+ holdout_score=row.holdout_score,
+ train_score=row.train_score,
+ agent_description=row.agent_description,
+ model_spec=row.model_spec or {},
+ )
+
+
+def _training_run_to_contract(row: AutoresearchTrainingRun) -> TrainingRun:
+ return TrainingRun(
+ id=row.id,
+ pipeline=row.pipeline_id,
+ task_id=row.task_id,
+ task_run_id=row.task_run_id,
+ task_url=f"/tasks/{row.task_id}" if row.task_id else None,
+ status=row.status,
+ iteration_budget=row.iteration_budget,
+ iteration_count=row.iteration_count,
+ best_holdout_score=row.best_holdout_score,
+ summary=row.summary or None,
+ iterations=[_iteration_trail_entry(i) for i in row.iterations.all()],
+ error=row.error,
+ started_at=row.started_at,
+ completed_at=row.completed_at,
+ created_at=row.created_at,
+ )
+
+
+def _run_to_contract(row: AutoresearchRun) -> Run:
+ return Run(
+ id=row.id,
+ pipeline=row.pipeline_id,
+ model=row.model_id,
+ run_type=row.run_type,
+ status=row.status,
+ rows_scored=row.rows_scored,
+ metrics=row.metrics or {},
+ error=row.error,
+ started_at=row.started_at,
+ completed_at=row.completed_at,
+ created_at=row.created_at,
+ )
+
+
# ── Row lookups (internal) ─────────────────────────────────────────────────
@@ -107,15 +203,33 @@ def _pipeline_row(team_id: int, pipeline_id: str | UUID, *, live_only: bool = Fa
a refusal that admits it exists. Routes nested under a pipeline id keep seeing archived rows,
so they can explain why the write is refused.
"""
+ pipeline_uuid = _as_uuid(pipeline_id)
+ if pipeline_uuid is None:
+ raise PipelineNotFound("Pipeline not found.")
qs = AutoresearchPipeline.objects.for_team(team_id)
if live_only:
qs = qs.exclude(status=AutoresearchPipeline.Status.ARCHIVED)
try:
- return qs.get(pk=str(pipeline_id))
- except (AutoresearchPipeline.DoesNotExist, ValueError, TypeError):
+ return qs.get(pk=pipeline_uuid)
+ except AutoresearchPipeline.DoesNotExist:
raise PipelineNotFound("Pipeline not found.")
+def _training_run_row(
+ team_id: int, training_run_id: str | UUID, *, pipeline_id: str | UUID | None = None
+) -> AutoresearchTrainingRun:
+ training_run_uuid = _as_uuid(training_run_id)
+ if training_run_uuid is None:
+ raise TrainingRunNotFound("Training run not found.")
+ qs = AutoresearchTrainingRun.objects.for_team(team_id).select_related("pipeline").prefetch_related("iterations")
+ if pipeline_id:
+ qs = qs.filter(pipeline_id=_as_uuid(pipeline_id))
+ try:
+ return qs.get(pk=training_run_uuid)
+ except AutoresearchTrainingRun.DoesNotExist:
+ raise TrainingRunNotFound("Training run not found.")
+
+
# ── Pipelines ──────────────────────────────────────────────────────────────
@@ -313,6 +427,72 @@ def validate_definition(
)
+# ── Models ─────────────────────────────────────────────────────────────────
+
+
+def list_models(team_id: int, *, pipeline_id: str | UUID | None, offset: int, limit: int) -> tuple[list[Model], int]:
+ qs = AutoresearchModel.objects.for_team(team_id).order_by("-created_at")
+ if pipeline_id:
+ qs = qs.filter(pipeline_id=_as_uuid(pipeline_id))
+ count = qs.count()
+ return [_model_to_contract(row) for row in qs[offset : offset + limit]], count
+
+
+def get_model(team_id: int, model_id: str | UUID, *, pipeline_id: str | UUID | None = None) -> Model | None:
+ model_uuid = _as_uuid(model_id)
+ if model_uuid is None:
+ return None
+ qs = AutoresearchModel.objects.for_team(team_id).filter(pk=model_uuid)
+ if pipeline_id:
+ qs = qs.filter(pipeline_id=_as_uuid(pipeline_id))
+ row = qs.first()
+ return _model_to_contract(row) if row else None
+
+
+# ── Operational runs ───────────────────────────────────────────────────────
+
+
+def list_runs(team_id: int, *, pipeline_id: str | UUID | None, offset: int, limit: int) -> tuple[list[Run], int]:
+ qs = AutoresearchRun.objects.for_team(team_id).order_by("-created_at")
+ if pipeline_id:
+ qs = qs.filter(pipeline_id=_as_uuid(pipeline_id))
+ count = qs.count()
+ return [_run_to_contract(row) for row in qs[offset : offset + limit]], count
+
+
+def get_run(team_id: int, run_id: str | UUID, *, pipeline_id: str | UUID | None = None) -> Run | None:
+ run_uuid = _as_uuid(run_id)
+ if run_uuid is None:
+ return None
+ qs = AutoresearchRun.objects.for_team(team_id).filter(pk=run_uuid)
+ if pipeline_id:
+ qs = qs.filter(pipeline_id=_as_uuid(pipeline_id))
+ row = qs.first()
+ return _run_to_contract(row) if row else None
+
+
+# ── Training runs ──────────────────────────────────────────────────────────
+
+
+def list_training_runs(
+ team_id: int, *, pipeline_id: str | UUID | None, offset: int, limit: int
+) -> tuple[list[TrainingRun], int]:
+ qs = AutoresearchTrainingRun.objects.for_team(team_id).prefetch_related("iterations").order_by("-created_at")
+ if pipeline_id:
+ qs = qs.filter(pipeline_id=_as_uuid(pipeline_id))
+ count = qs.count()
+ return [_training_run_to_contract(row) for row in qs[offset : offset + limit]], count
+
+
+def get_training_run(
+ team_id: int, training_run_id: str | UUID, *, pipeline_id: str | UUID | None = None
+) -> TrainingRun | None:
+ try:
+ return _training_run_to_contract(_training_run_row(team_id, training_run_id, pipeline_id=pipeline_id))
+ except TrainingRunNotFound:
+ return None
+
+
# ── Recipe validation surface for the presentation layer ───────────────────
# The semantic population kinds the labeler can compile. Presentation validates a submitted
@@ -334,3 +514,8 @@ PIPELINE_STATUS_CHOICES = AutoresearchPipeline.Status.choices
TEMPLATE_KEY_CHOICES = _TemplateKey.choices
# A plain list, not choices: the serializer explains why `code` is not an enum.
VALIDATION_WARNING_CODES = [code.value for code in _ValidationWarningCode]
+MODEL_ROLE_CHOICES = AutoresearchModel.Role.choices
+TRAINING_RUN_STATUS_CHOICES = AutoresearchTrainingRun.Status.choices
+ITERATION_STATUS_CHOICES = AutoresearchIteration.Status.choices
+RUN_TYPE_CHOICES = AutoresearchRun.RunType.choices
+RUN_STATUS_CHOICES = AutoresearchRun.Status.choices
diff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.py
index c0bf52889503..d31453626f84 100644
--- a/products/autoresearch/backend/facade/contracts.py
+++ b/products/autoresearch/backend/facade/contracts.py
@@ -19,7 +19,7 @@ from dataclasses import (
dataclass as stdlib_dataclass,
field,
)
-from datetime import datetime
+from datetime import date, datetime
from typing import Any
from uuid import UUID
@@ -30,6 +30,10 @@ class PipelineNotFound(LookupError):
"""No pipeline with that id in this team."""
+class TrainingRunNotFound(LookupError):
+ """No training run with that id in this team."""
+
+
class AutoresearchConflict(ValueError):
"""The request is well-formed but the pipeline or run is in the wrong state for it.
@@ -81,6 +85,104 @@ class Pipeline:
champion_realized_auc: float | None
+@dataclass(frozen=True)
+class Model:
+ """A persisted, versioned champion or challenger recipe."""
+
+ id: UUID
+ pipeline: UUID
+ role: str
+ recipe_hash: str
+ model_recipe: dict[str, Any]
+ model_explanation: dict[str, Any]
+ holdout_score: float | None
+ realized_score: float | None
+ calibration_error: float | None
+ metrics: dict[str, Any]
+ source_training_run: UUID | None
+ agent_description: str
+ trained_on_start: date | None
+ trained_on_end: date | None
+ is_preliminary: bool
+ promoted_at: datetime | None
+ archived_at: datetime | None
+ created_at: datetime
+ updated_at: datetime
+
+
+@dataclass(frozen=True)
+class IterationTrailEntry:
+ """Compact view of one iteration, for the history feed and the Training tab."""
+
+ iteration_number: int
+ status: str
+ holdout_score: float | None
+ train_score: float | None
+ agent_description: str
+ model_spec: dict[str, Any]
+
+
+@dataclass(frozen=True)
+class TrainingRunSummaryLadderItem:
+ iteration_number: int
+ holdout_score: float | None
+ model_class: str
+ agent_description: str
+
+
+@dataclass(frozen=True)
+class TrainingRunSummary:
+ """Tier-1 distilled summary of a completed run — what a new run reads first."""
+
+ target_event: str
+ horizon_days: int
+ best_holdout_score: float | None
+ champion_promoted: bool
+ champion_model_class: str
+ kept_ladder: list[TrainingRunSummaryLadderItem]
+ dead_ends: list[TrainingRunSummaryLadderItem]
+ recommended_next: str
+ distillation: str
+
+
+@dataclass(frozen=True)
+class TrainingRun:
+ """One bounded training session backed by a Task/TaskRun sandbox."""
+
+ id: UUID
+ pipeline: UUID
+ task_id: UUID | None
+ task_run_id: UUID | None
+ task_url: str | None
+ status: str
+ iteration_budget: int
+ iteration_count: int
+ best_holdout_score: float | None
+ summary: dict[str, Any] | None
+ iterations: list[IterationTrailEntry]
+ error: str
+ started_at: datetime | None
+ completed_at: datetime | None
+ created_at: datetime
+
+
+@dataclass(frozen=True)
+class Run:
+ """Generic operational run: inference or validation."""
+
+ id: UUID
+ pipeline: UUID
+ model: UUID | None
+ run_type: str
+ status: str
+ rows_scored: int | None
+ metrics: dict[str, Any]
+ error: str
+ started_at: datetime | None
+ completed_at: datetime | None
+ created_at: datetime
+
+
# ── Write contracts ────────────────────────────────────────────────────────
diff --git a/products/autoresearch/backend/presentation/AGENTS.md b/products/autoresearch/backend/presentation/AGENTS.md
index 6c4b25c28cb5..429530187d8c 100644
--- a/products/autoresearch/backend/presentation/AGENTS.md
+++ b/products/autoresearch/backend/presentation/AGENTS.md
@@ -5,13 +5,14 @@ The HTTP surface — and, because of how PostHog's codegen works, considerably m
These serializers are the source of truth for three downstream artifacts: the REST API itself, the generated frontend TypeScript types, and the 29 `autoresearch-*` MCP tools that the sandbox agent uses to drive its own training run.
A vague `help_text` here becomes a vague tool description that a model has to guess at. Treat serializer annotations as agent-facing documentation, because they are.
-This package lands one endpoint group at a time. Pipeline CRUD and the pre-create helpers are here; the lifecycle actions, the read-only model and run viewsets, the training-run agent surface, and suggestions arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464). The MCP tools arrive at the end of it.
+This package lands one endpoint group at a time. Pipeline CRUD, the pre-create helpers, and the read-only model, run and training-run viewsets are here; the lifecycle actions, the training-run agent surface, and suggestions arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464). The MCP tools arrive at the end of it.
## What lives here
- `views/views.py`
- One viewset so far, registered in `../routes.py` under the `project_autoresearch_pipelines` basename.
+ Four viewsets, registered in `../routes.py` under `project_autoresearch_*` basenames and nested pipeline-first.
- `AutoresearchPipelineViewSet` — full CRUD plus the pre-create helpers `templates`, `resolve-template`, `validate`.
+ - `AutoresearchModelViewSet`, `AutoresearchRunViewSet`, `AutoresearchTrainingRunViewSet` — read-only.
- `views/serializers.py`
Request and response shapes, plus `resolve_target()`, which turns a pipeline's `target_event` or `target_definition` (an action reference) into the resolved target the rest of the product uses.
It refuses the product's own `autoresearch_prediction` event, and an action with a step that can match it, because the labeler and online validation exclude that event from every scan.
@@ -25,7 +26,7 @@ Every viewset sets `scope_object = "autoresearch"` and splits `scope_object_read
## Where the rest of the system meets this package
-- **Routing** — `../routes.py` (`register_routes`).
+- **Routing** — `../routes.py` (`register_routes`), nested pipeline → models / runs / training_runs.
- **Frontend types** — generated into `../../frontend/generated/` via drf-spectacular + Orval. Never hand-edit those; change the serializer and regenerate with `hogli build:openapi`.
- **Calls into** — `../dataset/` (validate, templates, `resolve_target`).
diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.py
index b6c80e8d2eb7..c6937c3d2fca 100644
--- a/products/autoresearch/backend/presentation/views/serializers.py
+++ b/products/autoresearch/backend/presentation/views/serializers.py
@@ -12,7 +12,14 @@ from posthog.api.shared import UserBasicSerializer
from posthog.permissions import get_authenticator_scopes
from products.autoresearch.backend.facade import api
-from products.autoresearch.backend.facade.contracts import Pipeline, PipelineWrite
+from products.autoresearch.backend.facade.contracts import (
+ IterationTrailEntry,
+ Model,
+ Pipeline,
+ PipelineWrite,
+ Run,
+ TrainingRun,
+)
POPULATION_KINDS = api.POPULATION_KINDS
@@ -21,6 +28,11 @@ POPULATION_KINDS = api.POPULATION_KINDS
PIPELINE_STATUS_CHOICES = api.PIPELINE_STATUS_CHOICES
TEMPLATE_KEY_CHOICES = api.TEMPLATE_KEY_CHOICES
VALIDATION_WARNING_CODES = api.VALIDATION_WARNING_CODES
+MODEL_ROLE_CHOICES = api.MODEL_ROLE_CHOICES
+RUN_STATUS_CHOICES = api.RUN_STATUS_CHOICES
+RUN_TYPE_CHOICES = api.RUN_TYPE_CHOICES
+TRAINING_RUN_STATUS_CHOICES = api.TRAINING_RUN_STATUS_CHOICES
+ITERATION_STATUS_CHOICES = api.ITERATION_STATUS_CHOICES
TARGET_EVENT_MAX_LENGTH = 255
OUTPUT_PERSON_PROPERTY_MAX_LENGTH = 255
@@ -248,6 +260,54 @@ class PopulationDefinitionField(serializers.JSONField):
return value
+@extend_schema_field(
+ {
+ "type": "object",
+ "description": (
+ "Portable recipe artifact. Contains feature_sql (HogQL), feature_transforms, "
+ "model_class, model_params, fit_signature, trained_on, holdout_score, and agent_description."
+ ),
+ "example": {
+ "feature_sql": "SELECT a.person_id AS distinct_id, countIf(e.event='$pageview') AS pageviews_30d FROM {anchors} a LEFT JOIN events e ON e.person_id = a.person_id AND e.timestamp < fromUnixTimestamp(a.cutoff_ts) GROUP BY a.person_id",
+ "feature_transforms": [],
+ "model_class": "sklearn.linear_model.LogisticRegression",
+ "model_params": {"C": 1.0, "max_iter": 200},
+ "fit_signature": "abc123",
+ "trained_on": "2026-04-01 to 2026-05-01",
+ "holdout_score": 0.72,
+ "agent_description": "Stub recipe: universal engagement features",
+ },
+ }
+)
+class ModelRecipeField(serializers.JSONField):
+ pass
+
+
+@extend_schema_field(
+ {
+ "type": "object",
+ "description": (
+ "Global feature importance bundle: top features by gain, directionality "
+ "(positive/negative impact on predicted probability), stability across runs, "
+ "and leakage warning annotations."
+ ),
+ }
+)
+class ModelExplanationField(serializers.JSONField):
+ pass
+
+
+@extend_schema_field(
+ {
+ "type": "object",
+ "additionalProperties": True,
+ "description": "A metrics bundle keyed by metric name. Empty until the producing run records anything.",
+ }
+)
+class MetricsBundleField(serializers.JSONField):
+ pass
+
+
# ── Core serializers ------------------------------------------------------
@@ -583,6 +643,299 @@ class AutoresearchPipelineCreateSerializer(DataclassSerializer):
return replace(data, **updates) if updates else data
+@extend_schema_serializer(component_name="AutoresearchModel")
+class AutoresearchModelSerializer(DataclassSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique UUID of this model version.")
+ pipeline = serializers.UUIDField(help_text="Pipeline this model belongs to.")
+ role = serializers.ChoiceField(
+ choices=MODEL_ROLE_CHOICES,
+ required=False,
+ help_text="Model role: 'champion' (active scoring model), 'challenger' (shadow model), or 'archived'.",
+ )
+ recipe_hash = serializers.CharField(
+ read_only=True,
+ help_text="SHA-256 of the serialized recipe. Used to deduplicate identical recipes across runs.",
+ )
+ model_recipe = ModelRecipeField(
+ help_text="Portable recipe artifact. Feature SQL, transforms, model class, params, and metadata."
+ )
+ model_explanation = ModelExplanationField(
+ help_text="Global feature importance and directionality. Used to explain top drivers on the model card."
+ )
+ holdout_score = serializers.FloatField(
+ required=False,
+ allow_null=True,
+ help_text="AUC on the held-out test split at training time. Preliminary signal before online labels mature.",
+ )
+ realized_score = serializers.FloatField(
+ required=False,
+ allow_null=True,
+ help_text="Online AUC computed from actual realized outcomes. Authoritative once enough labels have matured.",
+ )
+ calibration_error = serializers.FloatField(
+ required=False,
+ allow_null=True,
+ help_text="Expected calibration error (ECE). Lower is better; well-calibrated models have ECE < 0.05.",
+ )
+ metrics = MetricsBundleField(
+ required=False,
+ help_text="Extended metrics bundle: Brier score, precision/recall at thresholds, lift@k, base rate, row counts.",
+ )
+ source_training_run = serializers.UUIDField(
+ read_only=True,
+ allow_null=True,
+ help_text=(
+ "Training run that produced this model. Read that run's artifact bundle to reuse the "
+ "champion's train.py and features.sql as a starting point. Null for legacy models."
+ ),
+ )
+ agent_description = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="The agent's own plain-English description of what this recipe does and why it was chosen.",
+ )
+ trained_on_start = serializers.DateField(
+ required=False, allow_null=True, help_text="Start of the training data window (inclusive)."
+ )
+ trained_on_end = serializers.DateField(
+ required=False, allow_null=True, help_text="End of the training data window (exclusive)."
+ )
+ is_preliminary = serializers.BooleanField(
+ required=False,
+ help_text="True if this model has not yet been validated against realized online outcomes.",
+ )
+ promoted_at = serializers.DateTimeField(
+ required=False, allow_null=True, help_text="Timestamp when this model was promoted to champion."
+ )
+ archived_at = serializers.DateTimeField(
+ required=False,
+ allow_null=True,
+ help_text="Timestamp when this model was archived (superseded or retired).",
+ )
+ created_at = serializers.DateTimeField(read_only=True)
+ updated_at = serializers.DateTimeField(read_only=True)
+
+ class Meta:
+ dataclass = Model
+ fields = [
+ "id",
+ "pipeline",
+ "role",
+ "recipe_hash",
+ "model_recipe",
+ "model_explanation",
+ "holdout_score",
+ "realized_score",
+ "calibration_error",
+ "metrics",
+ "source_training_run",
+ "agent_description",
+ "trained_on_start",
+ "trained_on_end",
+ "is_preliminary",
+ "promoted_at",
+ "archived_at",
+ "created_at",
+ "updated_at",
+ ]
+
+
+class TrainingRunSummaryLadderItemSerializer(serializers.Serializer):
+ """One iteration referenced from a run summary's ladder or dead-ends list."""
+
+ iteration_number = serializers.IntegerField(help_text="Iteration index this entry refers to.")
+ holdout_score = serializers.FloatField(allow_null=True, help_text="Holdout AUC for this iteration.")
+ model_class = serializers.CharField(allow_blank=True, help_text="Model class tried in this iteration.")
+ agent_description = serializers.CharField(allow_blank=True, help_text="The agent's rationale for this attempt.")
+
+
+class TrainingRunSummarySerializer(serializers.Serializer):
+ """Tier-1 distilled summary of a completed run — the orientation memory a new run reads first."""
+
+ target_event = serializers.CharField(help_text="Target event the run's pipeline predicts.")
+ horizon_days = serializers.IntegerField(help_text="Prediction horizon, in days.")
+ best_holdout_score = serializers.FloatField(allow_null=True, help_text="Best holdout AUC achieved in the run.")
+ champion_promoted = serializers.BooleanField(
+ help_text="Whether this run's best model was promoted to champion (vs kept as challenger)."
+ )
+ champion_model_class = serializers.CharField(allow_blank=True, help_text="Model class of the run's best model.")
+ kept_ladder = TrainingRunSummaryLadderItemSerializer(
+ many=True,
+ help_text="Kept iterations, highest holdout AUC first — the winning approaches worth reusing.",
+ )
+ dead_ends = TrainingRunSummaryLadderItemSerializer(
+ many=True,
+ help_text="Discarded or crashed iterations — approaches already tried that did not help; avoid repeating.",
+ )
+ recommended_next = serializers.CharField(
+ allow_blank=True, help_text="Agent's suggested next experiments for a future run. Empty if not provided."
+ )
+ distillation = serializers.CharField(
+ allow_blank=True, help_text="Agent's 1–2 sentence distillation of what this run learned. Empty if not provided."
+ )
+
+
+@extend_schema_serializer(component_name="IterationTrail")
+class IterationTrailSerializer(DataclassSerializer):
+ """Compact, read-only view of one iteration for the cross-run history feed and the Training tab."""
+
+ iteration_number = serializers.IntegerField(
+ min_value=-2147483648, max_value=2147483647, help_text="Order of this attempt within its run (0-based)."
+ )
+ status = serializers.ChoiceField(
+ choices=ITERATION_STATUS_CHOICES,
+ help_text="Whether this recipe was kept (improved the best score), discarded, or crashed.",
+ )
+ holdout_score = serializers.FloatField(
+ required=False,
+ allow_null=True,
+ help_text="Holdout AUC this iteration achieved. Null if it was skipped/degenerate.",
+ )
+ train_score = serializers.FloatField(
+ required=False, allow_null=True, help_text="Train-fold AUC for this iteration, if recorded."
+ )
+ agent_description = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="The agent's one-line rationale for what it tried and why.",
+ )
+ model_spec = serializers.JSONField(help_text="Model class and hyperparameters tried in this iteration.")
+
+ class Meta:
+ dataclass = IterationTrailEntry
+ fields = [
+ "iteration_number",
+ "status",
+ "holdout_score",
+ "train_score",
+ "agent_description",
+ "model_spec",
+ ]
+
+
+@extend_schema_serializer(component_name="AutoresearchTrainingRun")
+class AutoresearchTrainingRunSerializer(DataclassSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique UUID of this training run.")
+ pipeline = serializers.UUIDField(help_text="Pipeline this training run belongs to.")
+ task_id = serializers.UUIDField(
+ required=False, allow_null=True, help_text="Parent Task ID in the tasks sandbox. Null for stub runs."
+ )
+ task_run_id = serializers.UUIDField(
+ required=False,
+ allow_null=True,
+ help_text="Task sandbox run ID. Null for stub/synchronous training runs.",
+ )
+ task_url = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text="Relative URL to the underlying sandbox Task detail page. Null for stub/synchronous training runs.",
+ )
+ status = serializers.ChoiceField(
+ choices=TRAINING_RUN_STATUS_CHOICES,
+ read_only=True,
+ help_text="Run status: pending, running, completed, or failed.",
+ )
+ iteration_budget = serializers.IntegerField(
+ min_value=-2147483648,
+ max_value=2147483647,
+ required=False,
+ help_text="Maximum iterations allowed for this run.",
+ )
+ iteration_count = serializers.IntegerField(read_only=True, help_text="Number of iterations completed.")
+ best_holdout_score = serializers.FloatField(
+ read_only=True,
+ allow_null=True,
+ help_text="Best holdout AUC achieved across all iterations in this run.",
+ )
+ summary = TrainingRunSummarySerializer(
+ read_only=True,
+ allow_null=True,
+ help_text="Distilled cross-run learning summary written on completion. Null until the run completes.",
+ )
+ iterations = IterationTrailSerializer(
+ many=True,
+ read_only=True,
+ help_text="Per-iteration breakdown — every recipe the agent tried this run, kept or discarded, "
+ "with its model spec, holdout/train AUC, and one-line rationale. Ordered by iteration_number.",
+ )
+ error = serializers.CharField(read_only=True, allow_blank=True, help_text="Error message if the run failed.")
+ started_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="Timestamp when the training run started."
+ )
+ completed_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="Timestamp when the training run completed or failed."
+ )
+ created_at = serializers.DateTimeField(read_only=True)
+
+ class Meta:
+ dataclass = TrainingRun
+ fields = [
+ "id",
+ "pipeline",
+ "task_id",
+ "task_run_id",
+ "task_url",
+ "status",
+ "iteration_budget",
+ "iteration_count",
+ "best_holdout_score",
+ "summary",
+ "iterations",
+ "error",
+ "started_at",
+ "completed_at",
+ "created_at",
+ ]
+
+
+@extend_schema_serializer(component_name="AutoresearchRun")
+class AutoresearchRunSerializer(DataclassSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique UUID of this run.")
+ pipeline = serializers.UUIDField(help_text="Pipeline this run belongs to.")
+ model = serializers.UUIDField(
+ required=False, allow_null=True, help_text="Model used for scoring. Null for validation runs."
+ )
+ run_type = serializers.ChoiceField(
+ choices=RUN_TYPE_CHOICES,
+ help_text="Type of run: 'inference' (daily scoring) or 'validation' (outcome evaluation).",
+ )
+ status = serializers.ChoiceField(
+ choices=RUN_STATUS_CHOICES,
+ required=False,
+ help_text="Run status: pending, running, completed, or failed.",
+ )
+ rows_scored = serializers.IntegerField(
+ min_value=-2147483648,
+ max_value=2147483647,
+ required=False,
+ allow_null=True,
+ help_text="Number of users scored in this inference run.",
+ )
+ metrics = MetricsBundleField(help_text="Run metrics: rows scored, score distribution summary, validation AUC, etc.")
+ error = serializers.CharField(required=False, allow_blank=True, help_text="Error message if the run failed.")
+ started_at = serializers.DateTimeField(required=False, allow_null=True, help_text="Timestamp when the run started.")
+ completed_at = serializers.DateTimeField(
+ required=False, allow_null=True, help_text="Timestamp when the run completed or failed."
+ )
+ created_at = serializers.DateTimeField(read_only=True)
+
+ class Meta:
+ dataclass = Run
+ fields = [
+ "id",
+ "pipeline",
+ "model",
+ "run_type",
+ "status",
+ "rows_scored",
+ "metrics",
+ "error",
+ "started_at",
+ "completed_at",
+ "created_at",
+ ]
+
+
# ── Validation serializers -------------------------------------------------
diff --git a/products/autoresearch/backend/presentation/views/views.py b/products/autoresearch/backend/presentation/views/views.py
index 6b9fefd8d139..b6e494cfda17 100644
--- a/products/autoresearch/backend/presentation/views/views.py
+++ b/products/autoresearch/backend/presentation/views/views.py
@@ -35,8 +35,11 @@ from products.autoresearch.backend.facade.access import has_autoresearch_access
from products.autoresearch.backend.facade.contracts import AutoresearchConflict, PipelineNotFound
from .serializers import (
+ AutoresearchModelSerializer,
AutoresearchPipelineCreateSerializer,
AutoresearchPipelineSerializer,
+ AutoresearchRunSerializer,
+ AutoresearchTrainingRunSerializer,
ResolvedTemplateSerializer,
ResolveTemplateRequestSerializer,
TemplateInfoSerializer,
@@ -110,6 +113,12 @@ class _FacadePaginationMixin:
return paginator.get_paginated_response(serializer.data)
+def _parent_pipeline_id(view: Any) -> str | None:
+ """The pipeline this nested route is scoped to, or None on the unscoped collection route."""
+ pipeline_id = view.kwargs.get("parent_lookup_pipeline_id")
+ return str(pipeline_id) if pipeline_id else None
+
+
def _pipeline_write_fields(validated: Any) -> dict[str, Any]:
"""The fields to persist.
@@ -313,3 +322,112 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin
user=cast(User, request.user),
)
return Response(ValidatePipelineResponseSerializer(instance=result).data)
+
+
+@extend_schema(tags=["autoresearch"])
+class AutoresearchModelViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin, viewsets.ReadOnlyModelViewSet):
+ """
+ List and retrieve champion/challenger models for a pipeline.
+
+ Models are the persisted artifacts produced by training runs. Each model
+ holds a portable recipe (feature SQL, transforms, model class, params) that
+ the daily inference workflow compiles to score users.
+ """
+
+ schema = FacadePathParamSchema()
+ uuid_path_parameters = {"id": "A UUID string identifying this autoresearch model.", "pipeline_id": None}
+ scope_object = "autoresearch"
+ scope_object_read_actions = ["list", "retrieve"]
+ scope_object_write_actions: list[str] = []
+ permission_classes = [AutoresearchAccessPermission]
+ serializer_class = AutoresearchModelSerializer
+ queryset = None # data is reached through the facade; declared for router/schema only
+
+ def _should_skip_parents_filter(self) -> bool:
+ return True
+
+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ return self._paginate_via_facade(
+ request,
+ lambda offset, limit: api.list_models(
+ self.team_id, pipeline_id=_parent_pipeline_id(self), offset=offset, limit=limit
+ ),
+ AutoresearchModelSerializer,
+ )
+
+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ model = api.get_model(self.team_id, self.kwargs["pk"], pipeline_id=_parent_pipeline_id(self))
+ if model is None:
+ raise NotFound("Model not found.")
+ return Response(AutoresearchModelSerializer(instance=model).data)
+
+
+@extend_schema(tags=["autoresearch"])
+class AutoresearchRunViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin, viewsets.ReadOnlyModelViewSet):
+ """
+ List and retrieve inference and validation runs for a pipeline.
+ """
+
+ schema = FacadePathParamSchema()
+ uuid_path_parameters = {"id": "A UUID string identifying this autoresearch run.", "pipeline_id": None}
+ scope_object = "autoresearch"
+ scope_object_read_actions = ["list", "retrieve"]
+ scope_object_write_actions: list[str] = []
+ permission_classes = [AutoresearchAccessPermission]
+ serializer_class = AutoresearchRunSerializer
+ queryset = None # data is reached through the facade; declared for router/schema only
+
+ def _should_skip_parents_filter(self) -> bool:
+ return True
+
+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ return self._paginate_via_facade(
+ request,
+ lambda offset, limit: api.list_runs(
+ self.team_id, pipeline_id=_parent_pipeline_id(self), offset=offset, limit=limit
+ ),
+ AutoresearchRunSerializer,
+ )
+
+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ run = api.get_run(self.team_id, self.kwargs["pk"], pipeline_id=_parent_pipeline_id(self))
+ if run is None:
+ raise NotFound("Run not found.")
+ return Response(AutoresearchRunSerializer(instance=run).data)
+
+
+@extend_schema(tags=["autoresearch"])
+class AutoresearchTrainingRunViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin, viewsets.ReadOnlyModelViewSet):
+ """
+ List and retrieve training runs for a pipeline.
+
+ A training run records the agent's search for a model: each iteration's recipe and holdout
+ score, and the summary of the run once it completes.
+ """
+
+ schema = FacadePathParamSchema()
+ uuid_path_parameters = {"id": "A UUID string identifying this autoresearch training run.", "pipeline_id": None}
+ scope_object = "autoresearch"
+ scope_object_read_actions = ["list", "retrieve"]
+ scope_object_write_actions: list[str] = []
+ permission_classes = [AutoresearchAccessPermission]
+ serializer_class = AutoresearchTrainingRunSerializer
+ queryset = None # data is reached through the facade; declared for router/schema only
+
+ def _should_skip_parents_filter(self) -> bool:
+ return True
+
+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ return self._paginate_via_facade(
+ request,
+ lambda offset, limit: api.list_training_runs(
+ self.team_id, pipeline_id=_parent_pipeline_id(self), offset=offset, limit=limit
+ ),
+ AutoresearchTrainingRunSerializer,
+ )
+
+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ training_run = api.get_training_run(self.team_id, self.kwargs["pk"], pipeline_id=_parent_pipeline_id(self))
+ if training_run is None:
+ raise NotFound("Training run not found.")
+ return Response(AutoresearchTrainingRunSerializer(instance=training_run).data)
diff --git a/products/autoresearch/backend/routes.py b/products/autoresearch/backend/routes.py
index 7b17d12560e0..b08168e5ea1a 100644
--- a/products/autoresearch/backend/routes.py
+++ b/products/autoresearch/backend/routes.py
@@ -4,9 +4,27 @@ import products.autoresearch.backend.presentation.views.views as autoresearch
def register_routes(routers: RouterRegistry) -> None:
- routers.projects.register(
+ autoresearch_router = routers.projects.register(
r"autoresearch",
autoresearch.AutoresearchPipelineViewSet,
"project_autoresearch_pipelines",
["project_id"],
)
+ autoresearch_router.register(
+ r"models",
+ autoresearch.AutoresearchModelViewSet,
+ "project_autoresearch_models",
+ ["project_id", "pipeline_id"],
+ )
+ autoresearch_router.register(
+ r"runs",
+ autoresearch.AutoresearchRunViewSet,
+ "project_autoresearch_runs",
+ ["project_id", "pipeline_id"],
+ )
+ autoresearch_router.register(
+ r"training_runs",
+ autoresearch.AutoresearchTrainingRunViewSet,
+ "project_autoresearch_training_runs",
+ ["project_id", "pipeline_id"],
+ )
diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.py
index c7fc5c1914ac..1709d4c975d1 100644
--- a/products/autoresearch/backend/tests/test_api.py
+++ b/products/autoresearch/backend/tests/test_api.py
@@ -15,7 +15,12 @@ from posthog.models import Organization, Team
from products.actions.backend.models.action import Action
from products.autoresearch.backend.dataset.templates import TEMPLATES
from products.autoresearch.backend.dataset.validation import ValidationResult, ValidationWarning
-from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline
+from products.autoresearch.backend.models import (
+ AutoresearchModel,
+ AutoresearchPipeline,
+ AutoresearchRun,
+ AutoresearchTrainingRun,
+)
from products.autoresearch.backend.presentation.views.serializers import (
VALIDATION_WARNING_CODES,
AutoresearchPipelineCreateSerializer,
@@ -391,6 +396,83 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
# ─────────────────────────────────── nested resources ─────────────────────────────────────────
+ def test_list_models_for_pipeline(self):
+ pipeline = self._make_pipeline()
+ training_run = AutoresearchTrainingRun.objects.create(pipeline=pipeline, status="completed")
+ AutoresearchModel.objects.create(
+ pipeline=pipeline,
+ role=AutoresearchModel.Role.CHAMPION,
+ model_recipe={"stub": True},
+ recipe_hash="abc123",
+ holdout_score=0.7,
+ source_training_run=training_run,
+ )
+ resp = self.client.get(f"{self.base_url}/{pipeline.id}/models/")
+ assert resp.status_code == status.HTTP_200_OK
+ assert resp.json()["count"] == 1
+ assert resp.json()["results"][0]["role"] == "champion"
+ # The agent brief tells agents to look up a champion's bundle via source_training_run.
+ assert resp.json()["results"][0]["source_training_run"] == str(training_run.id)
+
+ def test_list_training_runs_for_pipeline(self):
+ pipeline = self._make_pipeline()
+ AutoresearchTrainingRun.objects.create(pipeline=pipeline, status="completed", iteration_count=1)
+ resp = self.client.get(f"{self.base_url}/{pipeline.id}/training_runs/")
+ assert resp.status_code == status.HTTP_200_OK
+ assert resp.json()["count"] == 1
+
+ def test_list_runs_for_pipeline(self):
+ pipeline = self._make_pipeline()
+ model = AutoresearchModel.objects.create(
+ pipeline=pipeline,
+ role=AutoresearchModel.Role.CHAMPION,
+ model_recipe={"stub": True},
+ recipe_hash="def456",
+ holdout_score=0.6,
+ )
+ AutoresearchRun.objects.create(pipeline=pipeline, model=model, status="completed", rows_scored=100)
+ resp = self.client.get(f"{self.base_url}/{pipeline.id}/runs/")
+ assert resp.status_code == status.HTTP_200_OK
+ assert resp.json()["count"] == 1
+
+ def test_models_not_leaked_across_pipelines(self):
+ pipeline_a = self._make_pipeline(name="Pipeline A")
+ pipeline_b = self._make_pipeline(name="Pipeline B")
+ AutoresearchModel.objects.create(
+ pipeline=pipeline_a,
+ role=AutoresearchModel.Role.CHAMPION,
+ model_recipe={"stub": True},
+ recipe_hash="aaa",
+ holdout_score=0.7,
+ )
+ resp = self.client.get(f"{self.base_url}/{pipeline_b.id}/models/")
+ assert resp.status_code == status.HTTP_200_OK
+ assert resp.json()["count"] == 0
+
+ @parameterized.expand(["models", "runs", "training_runs"])
+ def test_nested_retrieve_is_scoped_to_the_parent_pipeline(self, resource: str):
+ pipeline_a = self._make_pipeline(name="Pipeline A")
+ pipeline_b = self._make_pipeline(name="Pipeline B")
+ training_run = AutoresearchTrainingRun.objects.create(pipeline=pipeline_a, status="completed")
+ model = AutoresearchModel.objects.create(
+ pipeline=pipeline_a,
+ role=AutoresearchModel.Role.CHAMPION,
+ model_recipe={"stub": True},
+ recipe_hash="aaa",
+ holdout_score=0.7,
+ source_training_run=training_run,
+ )
+ run = AutoresearchRun.objects.create(pipeline=pipeline_a, model=model, status="completed", rows_scored=1)
+ row_id = {"models": model.id, "runs": run.id, "training_runs": training_run.id}[resource]
+
+ resp = self.client.get(f"{self.base_url}/{pipeline_b.id}/{resource}/{row_id}/")
+ assert resp.status_code == status.HTTP_404_NOT_FOUND
+ resp = self.client.get(f"{self.base_url}/{pipeline_a.id}/{resource}/not-a-uuid/")
+ assert resp.status_code == status.HTTP_404_NOT_FOUND
+ resp = self.client.get(f"{self.base_url}/{pipeline_a.id}/{resource}/{row_id}/")
+ assert resp.status_code == status.HTTP_200_OK
+ assert resp.json()["id"] == str(row_id)
+
# ──────────────────────────────────────────── templates ────────────────────────────────────────────
def test_list_templates_returns_every_template(self):
diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.ts
index bce68997e31e..b2be0cbfc334 100644
--- a/products/autoresearch/frontend/generated/api.schemas.ts
+++ b/products/autoresearch/frontend/generated/api.schemas.ts
@@ -300,6 +300,357 @@ export interface AutoresearchPipelineCreateApi {
output_person_property?: string
}
+/**
+ * * `champion` - Champion
+ * * `challenger` - Challenger
+ * * `archived` - Archived
+ */
+export type AutoresearchModelRoleEnumApi =
+ (typeof AutoresearchModelRoleEnumApi)[keyof typeof AutoresearchModelRoleEnumApi]
+
+export const AutoresearchModelRoleEnumApi = {
+ Champion: 'champion',
+ Challenger: 'challenger',
+ Archived: 'archived',
+} as const
+
+/**
+ * Portable recipe artifact. Feature SQL, transforms, model class, params, and metadata.
+ */
+export type AutoresearchModelApiModelRecipe = { [key: string]: unknown }
+
+/**
+ * Global feature importance and directionality. Used to explain top drivers on the model card.
+ */
+export type AutoresearchModelApiModelExplanation = { [key: string]: unknown }
+
+/**
+ * Extended metrics bundle: Brier score, precision/recall at thresholds, lift@k, base rate, row counts.
+ */
+export type AutoresearchModelApiMetrics = { [key: string]: unknown }
+
+export interface AutoresearchModelApi {
+ /** Unique UUID of this model version. */
+ readonly id: string
+ /** Pipeline this model belongs to. */
+ pipeline: string
+ /** Model role: 'champion' (active scoring model), 'challenger' (shadow model), or 'archived'.
+ *
+ * * `champion` - Champion
+ * * `challenger` - Challenger
+ * * `archived` - Archived */
+ role?: AutoresearchModelRoleEnumApi
+ /** SHA-256 of the serialized recipe. Used to deduplicate identical recipes across runs. */
+ readonly recipe_hash: string
+ /** Portable recipe artifact. Feature SQL, transforms, model class, params, and metadata. */
+ model_recipe: AutoresearchModelApiModelRecipe
+ /** Global feature importance and directionality. Used to explain top drivers on the model card. */
+ model_explanation: AutoresearchModelApiModelExplanation
+ /**
+ * AUC on the held-out test split at training time. Preliminary signal before online labels mature.
+ * @nullable
+ */
+ holdout_score?: number | null
+ /**
+ * Online AUC computed from actual realized outcomes. Authoritative once enough labels have matured.
+ * @nullable
+ */
+ realized_score?: number | null
+ /**
+ * Expected calibration error (ECE). Lower is better; well-calibrated models have ECE < 0.05.
+ * @nullable
+ */
+ calibration_error?: number | null
+ /** Extended metrics bundle: Brier score, precision/recall at thresholds, lift@k, base rate, row counts. */
+ metrics?: AutoresearchModelApiMetrics
+ /**
+ * Training run that produced this model. Read that run's artifact bundle to reuse the champion's train.py and features.sql as a starting point. Null for legacy models.
+ * @nullable
+ */
+ readonly source_training_run: string | null
+ /** The agent's own plain-English description of what this recipe does and why it was chosen. */
+ agent_description?: string
+ /**
+ * Start of the training data window (inclusive).
+ * @nullable
+ */
+ trained_on_start?: string | null
+ /**
+ * End of the training data window (exclusive).
+ * @nullable
+ */
+ trained_on_end?: string | null
+ /** True if this model has not yet been validated against realized online outcomes. */
+ is_preliminary?: boolean
+ /**
+ * Timestamp when this model was promoted to champion.
+ * @nullable
+ */
+ promoted_at?: string | null
+ /**
+ * Timestamp when this model was archived (superseded or retired).
+ * @nullable
+ */
+ archived_at?: string | null
+ readonly created_at: string
+ readonly updated_at: string
+}
+
+export interface PaginatedAutoresearchModelListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: AutoresearchModelApi[]
+}
+
+/**
+ * * `inference` - Inference
+ * * `validation` - Validation
+ */
+export type AutoresearchRunRunTypeEnumApi =
+ (typeof AutoresearchRunRunTypeEnumApi)[keyof typeof AutoresearchRunRunTypeEnumApi]
+
+export const AutoresearchRunRunTypeEnumApi = {
+ Inference: 'inference',
+ Validation: 'validation',
+} as const
+
+/**
+ * * `pending` - Pending
+ * * `running` - Running
+ * * `completed` - Completed
+ * * `failed` - Failed
+ */
+export type ZendeskImportJobStatusEnumApi =
+ (typeof ZendeskImportJobStatusEnumApi)[keyof typeof ZendeskImportJobStatusEnumApi]
+
+export const ZendeskImportJobStatusEnumApi = {
+ Pending: 'pending',
+ Running: 'running',
+ Completed: 'completed',
+ Failed: 'failed',
+} as const
+
+/**
+ * Run metrics: rows scored, score distribution summary, validation AUC, etc.
+ */
+export type AutoresearchRunApiMetrics = { [key: string]: unknown }
+
+export interface AutoresearchRunApi {
+ /** Unique UUID of this run. */
+ readonly id: string
+ /** Pipeline this run belongs to. */
+ pipeline: string
+ /**
+ * Model used for scoring. Null for validation runs.
+ * @nullable
+ */
+ model?: string | null
+ /** Type of run: 'inference' (daily scoring) or 'validation' (outcome evaluation).
+ *
+ * * `inference` - Inference
+ * * `validation` - Validation */
+ run_type: AutoresearchRunRunTypeEnumApi
+ /** Run status: pending, running, completed, or failed.
+ *
+ * * `pending` - Pending
+ * * `running` - Running
+ * * `completed` - Completed
+ * * `failed` - Failed */
+ status?: ZendeskImportJobStatusEnumApi
+ /**
+ * Number of users scored in this inference run.
+ * @minimum -2147483648
+ * @maximum 2147483647
+ * @nullable
+ */
+ rows_scored?: number | null
+ /** Run metrics: rows scored, score distribution summary, validation AUC, etc. */
+ metrics: AutoresearchRunApiMetrics
+ /** Error message if the run failed. */
+ error?: string
+ /**
+ * Timestamp when the run started.
+ * @nullable
+ */
+ started_at?: string | null
+ /**
+ * Timestamp when the run completed or failed.
+ * @nullable
+ */
+ completed_at?: string | null
+ readonly created_at: string
+}
+
+export interface PaginatedAutoresearchRunListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: AutoresearchRunApi[]
+}
+
+/**
+ * One iteration referenced from a run summary's ladder or dead-ends list.
+ */
+export interface TrainingRunSummaryLadderItemApi {
+ /** Iteration index this entry refers to. */
+ iteration_number: number
+ /**
+ * Holdout AUC for this iteration.
+ * @nullable
+ */
+ holdout_score: number | null
+ /** Model class tried in this iteration. */
+ model_class: string
+ /** The agent's rationale for this attempt. */
+ agent_description: string
+}
+
+/**
+ * Tier-1 distilled summary of a completed run — the orientation memory a new run reads first.
+ */
+export interface TrainingRunSummaryApi {
+ /** Target event the run's pipeline predicts. */
+ target_event: string
+ /** Prediction horizon, in days. */
+ horizon_days: number
+ /**
+ * Best holdout AUC achieved in the run.
+ * @nullable
+ */
+ best_holdout_score: number | null
+ /** Whether this run's best model was promoted to champion (vs kept as challenger). */
+ champion_promoted: boolean
+ /** Model class of the run's best model. */
+ champion_model_class: string
+ /** Kept iterations, highest holdout AUC first — the winning approaches worth reusing. */
+ kept_ladder: TrainingRunSummaryLadderItemApi[]
+ /** Discarded or crashed iterations — approaches already tried that did not help; avoid repeating. */
+ dead_ends: TrainingRunSummaryLadderItemApi[]
+ /** Agent's suggested next experiments for a future run. Empty if not provided. */
+ recommended_next: string
+ /** Agent's 1–2 sentence distillation of what this run learned. Empty if not provided. */
+ distillation: string
+}
+
+/**
+ * * `kept` - Kept
+ * * `discarded` - Discarded
+ * * `crashed` - Crashed
+ */
+export type AutoresearchIterationStatusEnumApi =
+ (typeof AutoresearchIterationStatusEnumApi)[keyof typeof AutoresearchIterationStatusEnumApi]
+
+export const AutoresearchIterationStatusEnumApi = {
+ Kept: 'kept',
+ Discarded: 'discarded',
+ Crashed: 'crashed',
+} as const
+
+/**
+ * Compact, read-only view of one iteration for the cross-run history feed and the Training tab.
+ */
+export interface IterationTrailApi {
+ /**
+ * Order of this attempt within its run (0-based).
+ * @minimum -2147483648
+ * @maximum 2147483647
+ */
+ iteration_number: number
+ /** Whether this recipe was kept (improved the best score), discarded, or crashed.
+ *
+ * * `kept` - Kept
+ * * `discarded` - Discarded
+ * * `crashed` - Crashed */
+ status: AutoresearchIterationStatusEnumApi
+ /**
+ * Holdout AUC this iteration achieved. Null if it was skipped/degenerate.
+ * @nullable
+ */
+ holdout_score?: number | null
+ /**
+ * Train-fold AUC for this iteration, if recorded.
+ * @nullable
+ */
+ train_score?: number | null
+ /** The agent's one-line rationale for what it tried and why. */
+ agent_description?: string
+ /** Model class and hyperparameters tried in this iteration. */
+ model_spec: unknown
+}
+
+export interface AutoresearchTrainingRunApi {
+ /** Unique UUID of this training run. */
+ readonly id: string
+ /** Pipeline this training run belongs to. */
+ pipeline: string
+ /**
+ * Parent Task ID in the tasks sandbox. Null for stub runs.
+ * @nullable
+ */
+ task_id?: string | null
+ /**
+ * Task sandbox run ID. Null for stub/synchronous training runs.
+ * @nullable
+ */
+ task_run_id?: string | null
+ /**
+ * Relative URL to the underlying sandbox Task detail page. Null for stub/synchronous training runs.
+ * @nullable
+ */
+ readonly task_url: string | null
+ /** Run status: pending, running, completed, or failed.
+ *
+ * * `pending` - Pending
+ * * `running` - Running
+ * * `completed` - Completed
+ * * `failed` - Failed */
+ readonly status: ZendeskImportJobStatusEnumApi
+ /**
+ * Maximum iterations allowed for this run.
+ * @minimum -2147483648
+ * @maximum 2147483647
+ */
+ iteration_budget?: number
+ /** Number of iterations completed. */
+ readonly iteration_count: number
+ /**
+ * Best holdout AUC achieved across all iterations in this run.
+ * @nullable
+ */
+ readonly best_holdout_score: number | null
+ /** Distilled cross-run learning summary written on completion. Null until the run completes. */
+ readonly summary: TrainingRunSummaryApi | null
+ /** Per-iteration breakdown — every recipe the agent tried this run, kept or discarded, with its model spec, holdout/train AUC, and one-line rationale. Ordered by iteration_number. */
+ readonly iterations: readonly IterationTrailApi[]
+ /** Error message if the run failed. */
+ readonly error: string
+ /**
+ * Timestamp when the training run started.
+ * @nullable
+ */
+ readonly started_at: string | null
+ /**
+ * Timestamp when the training run completed or failed.
+ * @nullable
+ */
+ readonly completed_at: string | null
+ readonly created_at: string
+}
+
+export interface PaginatedAutoresearchTrainingRunListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: AutoresearchTrainingRunApi[]
+}
+
/**
* Omit (or pass {"type": "event"}) to predict target_event; pass {"type": "action", "action_id": N} to predict a PostHog action. No other shapes are accepted.
*/
@@ -621,3 +972,36 @@ export type AutoresearchListParams = {
*/
offset?: number
}
+
+export type AutoresearchModelsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
+export type AutoresearchRunsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
+export type AutoresearchTrainingRunsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
diff --git a/products/autoresearch/frontend/generated/api.ts b/products/autoresearch/frontend/generated/api.ts
index f32493cf9092..742dd79fe3df 100644
--- a/products/autoresearch/frontend/generated/api.ts
+++ b/products/autoresearch/frontend/generated/api.ts
@@ -10,9 +10,18 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
AutoresearchListParams,
+ AutoresearchModelApi,
+ AutoresearchModelsListParams,
AutoresearchPipelineApi,
AutoresearchPipelineCreateApi,
+ AutoresearchRunApi,
+ AutoresearchRunsListParams,
+ AutoresearchTrainingRunApi,
+ AutoresearchTrainingRunsListParams,
+ PaginatedAutoresearchModelListApi,
PaginatedAutoresearchPipelineListApi,
+ PaginatedAutoresearchRunListApi,
+ PaginatedAutoresearchTrainingRunListApi,
PatchedAutoresearchPipelineCreateApi,
ResolveTemplateRequestApi,
ResolvedTemplateApi,
@@ -79,6 +88,185 @@ export const autoresearchCreate = async (
})
}
+export const getAutoresearchModelsListUrl = (
+ projectId: string,
+ pipelineId: string,
+ params?: AutoresearchModelsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/autoresearch/${pipelineId}/models/?${stringifiedParams}`
+ : `/api/projects/${projectId}/autoresearch/${pipelineId}/models/`
+}
+
+/**
+ * List and retrieve champion/challenger models for a pipeline.
+ *
+ * Models are the persisted artifacts produced by training runs. Each model
+ * holds a portable recipe (feature SQL, transforms, model class, params) that
+ * the daily inference workflow compiles to score users.
+ */
+export const autoresearchModelsList = async (
+ projectId: string,
+ pipelineId: string,
+ params?: AutoresearchModelsListParams,
+ options?: RequestInit
+): Promise<PaginatedAutoresearchModelListApi> => {
+ return apiMutator<PaginatedAutoresearchModelListApi>(getAutoresearchModelsListUrl(projectId, pipelineId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAutoresearchModelsRetrieveUrl = (projectId: string, pipelineId: string, id: string) => {
+ return `/api/projects/${projectId}/autoresearch/${pipelineId}/models/${id}/`
+}
+
+/**
+ * List and retrieve champion/challenger models for a pipeline.
+ *
+ * Models are the persisted artifacts produced by training runs. Each model
+ * holds a portable recipe (feature SQL, transforms, model class, params) that
+ * the daily inference workflow compiles to score users.
+ */
+export const autoresearchModelsRetrieve = async (
+ projectId: string,
+ pipelineId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AutoresearchModelApi> => {
+ return apiMutator<AutoresearchModelApi>(getAutoresearchModelsRetrieveUrl(projectId, pipelineId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAutoresearchRunsListUrl = (
+ projectId: string,
+ pipelineId: string,
+ params?: AutoresearchRunsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/autoresearch/${pipelineId}/runs/?${stringifiedParams}`
+ : `/api/projects/${projectId}/autoresearch/${pipelineId}/runs/`
+}
+
+/**
+ * List and retrieve inference and validation runs for a pipeline.
+ */
+export const autoresearchRunsList = async (
+ projectId: string,
+ pipelineId: string,
+ params?: AutoresearchRunsListParams,
+ options?: RequestInit
+): Promise<PaginatedAutoresearchRunListApi> => {
+ return apiMutator<PaginatedAutoresearchRunListApi>(getAutoresearchRunsListUrl(projectId, pipelineId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAutoresearchRunsRetrieveUrl = (projectId: string, pipelineId: string, id: string) => {
+ return `/api/projects/${projectId}/autoresearch/${pipelineId}/runs/${id}/`
+}
+
+/**
+ * List and retrieve inference and validation runs for a pipeline.
+ */
+export const autoresearchRunsRetrieve = async (
+ projectId: string,
+ pipelineId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AutoresearchRunApi> => {
+ return apiMutator<AutoresearchRunApi>(getAutoresearchRunsRetrieveUrl(projectId, pipelineId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAutoresearchTrainingRunsListUrl = (
+ projectId: string,
+ pipelineId: string,
+ params?: AutoresearchTrainingRunsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/autoresearch/${pipelineId}/training_runs/?${stringifiedParams}`
+ : `/api/projects/${projectId}/autoresearch/${pipelineId}/training_runs/`
+}
+
+/**
+ * List and retrieve training runs for a pipeline.
+ *
+ * A training run records the agent's search for a model: each iteration's recipe and holdout
+ * score, and the summary of the run once it completes.
+ */
+export const autoresearchTrainingRunsList = async (
+ projectId: string,
+ pipelineId: string,
+ params?: AutoresearchTrainingRunsListParams,
+ options?: RequestInit
+): Promise<PaginatedAutoresearchTrainingRunListApi> => {
+ return apiMutator<PaginatedAutoresearchTrainingRunListApi>(
+ getAutoresearchTrainingRunsListUrl(projectId, pipelineId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getAutoresearchTrainingRunsRetrieveUrl = (projectId: string, pipelineId: string, id: string) => {
+ return `/api/projects/${projectId}/autoresearch/${pipelineId}/training_runs/${id}/`
+}
+
+/**
+ * List and retrieve training runs for a pipeline.
+ *
+ * A training run records the agent's search for a model: each iteration's recipe and holdout
+ * score, and the summary of the run once it completes.
+ */
+export const autoresearchTrainingRunsRetrieve = async (
+ projectId: string,
+ pipelineId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AutoresearchTrainingRunApi> => {
+ return apiMutator<AutoresearchTrainingRunApi>(getAutoresearchTrainingRunsRetrieveUrl(projectId, pipelineId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getAutoresearchRetrieveUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/autoresearch/${id}/`
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index dda2bd1f8310..4908c2611dfc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -11233,6 +11233,116 @@ export namespace Schemas {
P4: 'P4',
} as const;
+ /**
+ * * `kept` - Kept
+ * * `discarded` - Discarded
+ * * `crashed` - Crashed
+ */
+ export type AutoresearchIterationStatusEnum = typeof AutoresearchIterationStatusEnum[keyof typeof AutoresearchIterationStatusEnum];
+
+
+ export const AutoresearchIterationStatusEnum = {
+ Kept: 'kept',
+ Discarded: 'discarded',
+ Crashed: 'crashed',
+ } as const;
+
+ /**
+ * Portable recipe artifact. Feature SQL, transforms, model class, params, and metadata.
+ */
+ export type AutoresearchModelModelRecipe = { [key: string]: unknown };
+
+ /**
+ * Global feature importance and directionality. Used to explain top drivers on the model card.
+ */
+ export type AutoresearchModelModelExplanation = { [key: string]: unknown };
+
+ /**
+ * Extended metrics bundle: Brier score, precision/recall at thresholds, lift@k, base rate, row counts.
+ */
+ export type AutoresearchModelMetrics = { [key: string]: unknown };
+
+ /**
+ * * `champion` - Champion
+ * * `challenger` - Challenger
+ * * `archived` - Archived
+ */
+ export type AutoresearchModelRoleEnum = typeof AutoresearchModelRoleEnum[keyof typeof AutoresearchModelRoleEnum];
+
+
+ export const AutoresearchModelRoleEnum = {
+ Champion: 'champion',
+ Challenger: 'challenger',
+ Archived: 'archived',
+ } as const;
+
+ export interface AutoresearchModel {
+ /** Unique UUID of this model version. */
+ readonly id: string;
+ /** Pipeline this model belongs to. */
+ pipeline: string;
+ /** Model role: 'champion' (active scoring model), 'challenger' (shadow model), or 'archived'.
+ *
+ * * `champion` - Champion
+ * * `challenger` - Challenger
+ * * `archived` - Archived */
+ role?: AutoresearchModelRoleEnum;
+ /** SHA-256 of the serialized recipe. Used to deduplicate identical recipes across runs. */
+ readonly recipe_hash: string;
+ /** Portable recipe artifact. Feature SQL, transforms, model class, params, and metadata. */
+ model_recipe: AutoresearchModelModelRecipe;
+ /** Global feature importance and directionality. Used to explain top drivers on the model card. */
+ model_explanation: AutoresearchModelModelExplanation;
+ /**
+ * AUC on the held-out test split at training time. Preliminary signal before online labels mature.
+ * @nullable
+ */
+ holdout_score?: number | null;
+ /**
+ * Online AUC computed from actual realized outcomes. Authoritative once enough labels have matured.
+ * @nullable
+ */
+ realized_score?: number | null;
+ /**
+ * Expected calibration error (ECE). Lower is better; well-calibrated models have ECE < 0.05.
+ * @nullable
+ */
+ calibration_error?: number | null;
+ /** Extended metrics bundle: Brier score, precision/recall at thresholds, lift@k, base rate, row counts. */
+ metrics?: AutoresearchModelMetrics;
+ /**
+ * Training run that produced this model. Read that run's artifact bundle to reuse the champion's train.py and features.sql as a starting point. Null for legacy models.
+ * @nullable
+ */
+ readonly source_training_run: string | null;
+ /** The agent's own plain-English description of what this recipe does and why it was chosen. */
+ agent_description?: string;
+ /**
+ * Start of the training data window (inclusive).
+ * @nullable
+ */
+ trained_on_start?: string | null;
+ /**
+ * End of the training data window (exclusive).
+ * @nullable
+ */
+ trained_on_end?: string | null;
+ /** True if this model has not yet been validated against realized online outcomes. */
+ is_preliminary?: boolean;
+ /**
+ * Timestamp when this model was promoted to champion.
+ * @nullable
+ */
+ promoted_at?: string | null;
+ /**
+ * Timestamp when this model was archived (superseded or retired).
+ * @nullable
+ */
+ archived_at?: string | null;
+ readonly created_at: string;
+ readonly updated_at: string;
+ }
+
/**
* Resolved target definition: {"type": "event"} or {"type": "action", "action_id": N}.
*/
@@ -11456,6 +11566,220 @@ export namespace Schemas {
output_person_property?: string;
}
+ /**
+ * Run metrics: rows scored, score distribution summary, validation AUC, etc.
+ */
+ export type AutoresearchRunMetrics = { [key: string]: unknown };
+
+ /**
+ * * `inference` - Inference
+ * * `validation` - Validation
+ */
+ export type AutoresearchRunRunTypeEnum = typeof AutoresearchRunRunTypeEnum[keyof typeof AutoresearchRunRunTypeEnum];
+
+
+ export const AutoresearchRunRunTypeEnum = {
+ Inference: 'inference',
+ Validation: 'validation',
+ } as const;
+
+ /**
+ * * `pending` - Pending
+ * * `running` - Running
+ * * `completed` - Completed
+ * * `failed` - Failed
+ */
+ export type ZendeskImportJobStatusEnum = typeof ZendeskImportJobStatusEnum[keyof typeof ZendeskImportJobStatusEnum];
+
+
+ export const ZendeskImportJobStatusEnum = {
+ Pending: 'pending',
+ Running: 'running',
+ Completed: 'completed',
+ Failed: 'failed',
+ } as const;
+
+ export interface AutoresearchRun {
+ /** Unique UUID of this run. */
+ readonly id: string;
+ /** Pipeline this run belongs to. */
+ pipeline: string;
+ /**
+ * Model used for scoring. Null for validation runs.
+ * @nullable
+ */
+ model?: string | null;
+ /** Type of run: 'inference' (daily scoring) or 'validation' (outcome evaluation).
+ *
+ * * `inference` - Inference
+ * * `validation` - Validation */
+ run_type: AutoresearchRunRunTypeEnum;
+ /** Run status: pending, running, completed, or failed.
+ *
+ * * `pending` - Pending
+ * * `running` - Running
+ * * `completed` - Completed
+ * * `failed` - Failed */
+ status?: ZendeskImportJobStatusEnum;
+ /**
+ * Number of users scored in this inference run.
+ * @minimum -2147483648
+ * @maximum 2147483647
+ * @nullable
+ */
+ rows_scored?: number | null;
+ /** Run metrics: rows scored, score distribution summary, validation AUC, etc. */
+ metrics: AutoresearchRunMetrics;
+ /** Error message if the run failed. */
+ error?: string;
+ /**
+ * Timestamp when the run started.
+ * @nullable
+ */
+ started_at?: string | null;
+ /**
+ * Timestamp when the run completed or failed.
+ * @nullable
+ */
+ completed_at?: string | null;
+ readonly created_at: string;
+ }
+
+ /**
+ * One iteration referenced from a run summary's ladder or dead-ends list.
+ */
+ export interface TrainingRunSummaryLadderItem {
+ /** Iteration index this entry refers to. */
+ iteration_number: number;
+ /**
+ * Holdout AUC for this iteration.
+ * @nullable
+ */
+ holdout_score: number | null;
+ /** Model class tried in this iteration. */
+ model_class: string;
+ /** The agent's rationale for this attempt. */
+ agent_description: string;
+ }
+
+ /**
+ * Tier-1 distilled summary of a completed run — the orientation memory a new run reads first.
+ */
+ export interface TrainingRunSummary {
+ /** Target event the run's pipeline predicts. */
+ target_event: string;
+ /** Prediction horizon, in days. */
+ horizon_days: number;
+ /**
+ * Best holdout AUC achieved in the run.
+ * @nullable
+ */
+ best_holdout_score: number | null;
+ /** Whether this run's best model was promoted to champion (vs kept as challenger). */
+ champion_promoted: boolean;
+ /** Model class of the run's best model. */
+ champion_model_class: string;
+ /** Kept iterations, highest holdout AUC first — the winning approaches worth reusing. */
+ kept_ladder: TrainingRunSummaryLadderItem[];
+ /** Discarded or crashed iterations — approaches already tried that did not help; avoid repeating. */
+ dead_ends: TrainingRunSummaryLadderItem[];
+ /** Agent's suggested next experiments for a future run. Empty if not provided. */
+ recommended_next: string;
+ /** Agent's 1–2 sentence distillation of what this run learned. Empty if not provided. */
+ distillation: string;
+ }
+
+ /**
+ * Compact, read-only view of one iteration for the cross-run history feed and the Training tab.
+ */
+ export interface IterationTrail {
+ /**
+ * Order of this attempt within its run (0-based).
+ * @minimum -2147483648
+ * @maximum 2147483647
+ */
+ iteration_number: number;
+ /** Whether this recipe was kept (improved the best score), discarded, or crashed.
+ *
+ * * `kept` - Kept
+ * * `discarded` - Discarded
+ * * `crashed` - Crashed */
+ status: AutoresearchIterationStatusEnum;
+ /**
+ * Holdout AUC this iteration achieved. Null if it was skipped/degenerate.
+ * @nullable
+ */
+ holdout_score?: number | null;
+ /**
+ * Train-fold AUC for this iteration, if recorded.
+ * @nullable
+ */
+ train_score?: number | null;
+ /** The agent's one-line rationale for what it tried and why. */
+ agent_description?: string;
+ /** Model class and hyperparameters tried in this iteration. */
+ model_spec: unknown;
+ }
+
+ export interface AutoresearchTrainingRun {
+ /** Unique UUID of this training run. */
+ readonly id: string;
+ /** Pipeline this training run belongs to. */
+ pipeline: string;
+ /**
+ * Parent Task ID in the tasks sandbox. Null for stub runs.
+ * @nullable
+ */
+ task_id?: string | null;
+ /**
+ * Task sandbox run ID. Null for stub/synchronous training runs.
+ * @nullable
+ */
+ task_run_id?: string | null;
+ /**
+ * Relative URL to the underlying sandbox Task detail page. Null for stub/synchronous training runs.
+ * @nullable
+ */
+ readonly task_url: string | null;
+ /** Run status: pending, running, completed, or failed.
+ *
+ * * `pending` - Pending
+ * * `running` - Running
+ * * `completed` - Completed
+ * * `failed` - Failed */
+ readonly status: ZendeskImportJobStatusEnum;
+ /**
+ * Maximum iterations allowed for this run.
+ * @minimum -2147483648
+ * @maximum 2147483647
+ */
+ iteration_budget?: number;
+ /** Number of iterations completed. */
+ readonly iteration_count: number;
+ /**
+ * Best holdout AUC achieved across all iterations in this run.
+ * @nullable
+ */
+ readonly best_holdout_score: number | null;
+ /** Distilled cross-run learning summary written on completion. Null until the run completes. */
+ readonly summary: TrainingRunSummary | null;
+ /** Per-iteration breakdown — every recipe the agent tried this run, kept or discarded, with its model spec, holdout/train AUC, and one-line rationale. Ordered by iteration_number. */
+ readonly iterations: readonly IterationTrail[];
+ /** Error message if the run failed. */
+ readonly error: string;
+ /**
+ * Timestamp when the training run started.
+ * @nullable
+ */
+ readonly started_at: string | null;
+ /**
+ * Timestamp when the training run completed or failed.
+ * @nullable
+ */
+ readonly completed_at: string | null;
+ readonly created_at: string;
+ }
+
/**
* Discovered detail fields and their value distributions.
*/
@@ -57403,6 +57727,15 @@ export namespace Schemas {
results?: AsyncDeletionStatus[];
}
+ export interface PaginatedAutoresearchModelList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: AutoresearchModel[];
+ }
+
export interface PaginatedAutoresearchPipelineList {
count: number;
/** @nullable */
@@ -57412,6 +57745,24 @@ export namespace Schemas {
results: AutoresearchPipeline[];
}
+ export interface PaginatedAutoresearchRunList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: AutoresearchRun[];
+ }
+
+ export interface PaginatedAutoresearchTrainingRunList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: AutoresearchTrainingRun[];
+ }
+
export interface PaginatedBatchExportBackfillList {
/** @nullable */
next?: string | null;
@@ -94480,22 +94831,6 @@ export namespace Schemas {
detail: string;
}
- /**
- * * `pending` - Pending
- * * `running` - Running
- * * `completed` - Completed
- * * `failed` - Failed
- */
- export type ZendeskImportJobStatusEnum = typeof ZendeskImportJobStatusEnum[keyof typeof ZendeskImportJobStatusEnum];
-
-
- export const ZendeskImportJobStatusEnum = {
- Pending: 'pending',
- Running: 'running',
- Completed: 'completed',
- Failed: 'failed',
- } as const;
-
export interface ZendeskImportJob {
/** Unique identifier for the import job. */
readonly id: string;
@@ -98484,6 +98819,39 @@ export namespace Schemas {
offset?: number;
};
+ export type AutoresearchModelsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
+ export type AutoresearchRunsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
+ export type AutoresearchTrainingRunsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type BatchExportsListParams = {
/**
* Number of results to return per page.