:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(autoresearch): let the training agent open a run and record iterations (16/22) (#89148)
Andrew Maguire991f40b33085
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.pyindex d85298f09514..842c346df120 100644--- a/products/autoresearch/backend/facade/api.py+++ b/products/autoresearch/backend/facade/api.py@@ -9,9 +9,15 @@ Scope is set at the entry boundary, so every read and write here takes ``team_idfilters on it. Business rules live in the modules behind this facade, not in the views."""+import json+import hashlibfrom typing import Anyfrom uuid import UUID+from django.db import transaction+from django.db.models import F, Q+from django.utils import timezone as django_timezone+from posthog.models.team import Teamfrom posthog.models.user import User@@ -32,11 +38,14 @@ from ..models import (AutoresearchModel,AutoresearchPipeline,AutoresearchRun,+ AutoresearchSuggestion,AutoresearchTrainingRun,)+from ..training.recipe_validation import RecipeValidationError, validate_recipefrom .contracts import (AutoresearchConflict,InvalidTarget,+ Iteration,IterationTrailEntry,Model,Pipeline,@@ -47,6 +56,8 @@ from .contracts import (Run,TemplateInfo,TrainingRun,+ TrainingRunHistory,+ TrainingRunHistoryEntry,TrainingRunNotFound,ValidationWarning,)@@ -59,6 +70,9 @@ def flag_key() -> str:return AUTORESEARCH_FLAG+HISTORY_LIMIT_MAX = 20++def _as_uuid(value: str | UUID | None) -> UUID | None:"""A pk from a URL as a UUID, or None when it cannot be one.@@ -153,6 +167,7 @@ def _iteration_trail_entry(row: AutoresearchIteration) -> IterationTrailEntry:train_score=row.train_score,agent_description=row.agent_description,model_spec=row.model_spec or {},+ recipe_snapshot=row.recipe_snapshot or {},)@@ -176,6 +191,25 @@ def _training_run_to_contract(row: AutoresearchTrainingRun) -> TrainingRun:)+def _iteration_to_contract(row: AutoresearchIteration) -> Iteration:+ return Iteration(+ id=row.id,+ pipeline=row.pipeline_id,+ training_run=row.training_run_id,+ iteration_number=row.iteration_number,+ recipe_hash=row.recipe_hash,+ recipe_snapshot=row.recipe_snapshot or {},+ model_spec=row.model_spec or {},+ train_score=row.train_score,+ holdout_score=row.holdout_score,+ status=row.status,+ agent_description=row.agent_description,+ agent_confidence=row.agent_confidence,+ parent_suggestion=row.parent_suggestion_id,+ created_at=row.created_at,+ )++def _run_to_contract(row: AutoresearchRun) -> Run:return Run(id=row.id,@@ -216,12 +250,25 @@ def _pipeline_row(team_id: int, pipeline_id: str | UUID, *, live_only: bool = Fadef _training_run_row(- team_id: int, training_run_id: str | UUID, *, pipeline_id: str | UUID | None = None+ team_id: int,+ training_run_id: str | UUID,+ *,+ pipeline_id: str | UUID | None = None,+ with_iterations: bool = True,+ for_update: bool = False,) -> AutoresearchTrainingRun:+ """One training run in this team, and under ``pipeline_id`` when the route names one.++ ``for_update`` locks the run row only, not the joined pipeline row, which other claims lock.+ """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")+ qs = AutoresearchTrainingRun.objects.for_team(team_id).select_related("pipeline")+ if with_iterations:+ qs = qs.prefetch_related("iterations")+ if for_update:+ qs = qs.select_for_update(of=("self",))if pipeline_id:qs = qs.filter(pipeline_id=_as_uuid(pipeline_id))try:@@ -493,6 +540,205 @@ def get_training_run(return None+def open_training_run(team_id: int, pipeline_id: str | UUID, *, iteration_budget: int | None) -> TrainingRun:+ """Open a run an external agent will record iterations against."""+ pipeline = _pipeline_row(team_id, pipeline_id)+ if pipeline.status == AutoresearchPipeline.Status.ARCHIVED:+ raise AutoresearchConflict("Cannot open a training run on an archived pipeline.")+ row = AutoresearchTrainingRun.objects.create(+ pipeline=pipeline,+ status=AutoresearchTrainingRun.Status.RUNNING,+ iteration_budget=iteration_budget or pipeline.iteration_budget,+ started_at=django_timezone.now(),+ )+ return _training_run_to_contract(row)+++def record_iteration(+ team_id: int, training_run_id: str | UUID, *, pipeline_id: str | UUID | None = None, fields: dict[str, Any]+) -> Iteration:+ """Record one iteration of an open run. Idempotent on ``iteration_number``."""+ recipe_snapshot = fields["recipe_snapshot"]+ model_spec = fields["model_spec"]+ recipe_hash = hashlib.sha256(+ json.dumps({"recipe": recipe_snapshot, "spec": model_spec}, sort_keys=True).encode()+ ).hexdigest()+ iteration_number = fields["iteration_number"]++ # Completion locks the run row and freezes it. Recording takes the same lock so the status+ # check and the upsert see one state: an iteration can no longer land on a run that+ # completed in between and go missing from its champion selection and summary.+ with transaction.atomic():+ training_run = _training_run_row(+ team_id, training_run_id, pipeline_id=pipeline_id, with_iterations=False, for_update=True+ )+ if training_run.status != AutoresearchTrainingRun.Status.RUNNING:+ raise AutoresearchConflict("Can only record iterations on a running training run.")++ recorded = AutoresearchIteration.objects.filter(training_run=training_run)+ is_new_number = not recorded.filter(iteration_number=iteration_number).exists()+ if is_new_number and recorded.count() >= training_run.iteration_budget:+ raise AutoresearchConflict(+ f"Training run has used its iteration budget of {training_run.iteration_budget}. "+ "Re-sending a recorded iteration_number still updates that iteration."+ )++ defaults: dict[str, Any] = {+ "pipeline": training_run.pipeline,+ "recipe_hash": recipe_hash,+ "recipe_snapshot": recipe_snapshot,+ "model_spec": model_spec,+ "train_score": fields.get("train_score"),+ "holdout_score": fields.get("holdout_score"),+ "status": fields["status"],+ "agent_description": fields.get("agent_description", ""),+ "agent_confidence": fields.get("agent_confidence"),+ }+ # A re-send that omits parent_suggestion keeps the attribution it recorded the first+ # time; only an explicit null clears it.+ parent_suggestion = None+ if "parent_suggestion" in fields:+ parent_suggestion = _parent_suggestion_row(team_id, training_run, fields["parent_suggestion"])+ defaults["parent_suggestion"] = parent_suggestion++ iteration, _ = AutoresearchIteration.objects.update_or_create(+ team_id=team_id,+ training_run=training_run,+ iteration_number=iteration_number,+ defaults=defaults,+ )++ # Spawning an iteration from a suggestion is itself acting on it, so the suggestion+ # advances even if the agent never calls the respond endpoint.+ if parent_suggestion and parent_suggestion.status in (+ AutoresearchSuggestion.Status.QUEUED,+ AutoresearchSuggestion.Status.PICKED_UP,+ ):+ parent_suggestion.status = AutoresearchSuggestion.Status.ACTED_ON+ parent_suggestion.save(update_fields=["status", "updated_at"])++ return _iteration_to_contract(iteration)+++def _parent_suggestion_row(+ team_id: int, training_run: AutoresearchTrainingRun, suggestion_id: Any+) -> AutoresearchSuggestion | None:+ """The suggestion an iteration acts on, scoped to the run's pipeline so a foreign id cannot attach."""+ if not suggestion_id:+ return None+ suggestion_uuid = _as_uuid(suggestion_id)+ suggestion = None+ if suggestion_uuid is not None:+ suggestion = (+ AutoresearchSuggestion.objects.for_team(team_id)+ .filter(id=suggestion_uuid, pipeline=training_run.pipeline)+ .first()+ )+ if suggestion is None:+ raise AutoresearchConflict("parent_suggestion not found on this pipeline.")+ return suggestion+++def complete_run(+ team_id: int,+ training_run_id: str | UUID,+ *,+ pipeline_id: str | UUID | None = None,+ best_iteration_id: Any = None,+ model_explanation: dict[str, Any] | None = None,+ recommended_next: str = "",+ distillation: str = "",+) -> TrainingRun:+ """Finalize a run. Promotion is server-side, so an agent cannot set the champion."""+ # Promotion imports the inference sandbox, and with it pandas and pyarrow; the router imports+ # this facade on the first request, so the heavy chain loads only when a run completes.+ from ..training.promotion import PromotionError, complete_training_run # noqa: PLC0415++ training_run = _training_run_row(team_id, training_run_id, pipeline_id=pipeline_id, with_iterations=False)+ if training_run.status not in (+ AutoresearchTrainingRun.Status.RUNNING,+ AutoresearchTrainingRun.Status.PENDING,+ ):+ raise AutoresearchConflict("Training run is already completed or failed.")+ try:+ complete_training_run(+ training_run,+ best_iteration_id=best_iteration_id,+ model_explanation=model_explanation or {},+ recommended_next=recommended_next or "",+ distillation=distillation or "",+ )+ except PromotionError as exc:+ raise AutoresearchConflict(str(exc)) from exc+ training_run.refresh_from_db()+ if training_run.status != AutoresearchTrainingRun.Status.COMPLETED:+ # The TaskRun failure handler won the race for the row lock, so promotion answered with+ # its no-op and the run is failed, not completed.+ raise AutoresearchConflict("Training run failed before it could be completed.")+ return _training_run_to_contract(training_run)+++def training_run_history(team_id: int, pipeline_id: str | UUID, *, limit: int = 5) -> TrainingRunHistory:+ """Prior completed runs a new run reads to orient.++ This pipeline's own history first, backfilled with same-target sibling pipelines on the+ team, so a fresh pipeline still inherits what the team already learned about the target.+ """+ pipeline = _pipeline_row(team_id, pipeline_id)+ limit = max(1, min(limit, HISTORY_LIMIT_MAX))++ completed = (+ AutoresearchTrainingRun.objects.for_team(team_id)+ .filter(status=AutoresearchTrainingRun.Status.COMPLETED)+ .select_related("pipeline")+ .prefetch_related("iterations")+ )+ # Postgres puts NULLs first on a bare DESC, so an undated completed run would outrank every+ # dated one; the id breaks ties so a page is the same on every read.+ newest_first = (F("completed_at").desc(nulls_last=True), "-id")+ runs = list(completed.filter(pipeline=pipeline).order_by(*newest_first)[:limit])+ remaining = limit - len(runs)+ if remaining > 0:+ runs += list(+ completed.filter(_same_target_as(pipeline)).exclude(pipeline=pipeline).order_by(*newest_first)[:remaining]+ )++ return TrainingRunHistory(+ runs=[+ TrainingRunHistoryEntry(+ run_id=run.id,+ pipeline_id=run.pipeline_id,+ is_current_pipeline=run.pipeline_id == pipeline.id,+ target_event=run.pipeline.target_event,+ horizon_days=run.pipeline.horizon_days,+ best_holdout_score=run.best_holdout_score,+ iteration_count=run.iteration_count,+ completed_at=run.completed_at,+ summary=run.summary or None,+ iterations=[_iteration_trail_entry(i) for i in run.iterations.all()],+ )+ for run in runs+ ]+ )+++def _same_target_as(pipeline: AutoresearchPipeline) -> Q:+ """Sibling pipelines that predict the same outcome, not merely the same display name.++ An action and an event can share a name, so an action target matches on its id, and an+ event target also accepts the empty definition creation stored before it was normalized.+ """+ definition = pipeline.target_definition or {}+ if definition.get("type") == "action":+ return Q(+ pipeline__target_definition__type="action",+ pipeline__target_definition__action_id=definition.get("action_id"),+ )+ return Q(pipeline__target_event=pipeline.target_event) & (+ Q(pipeline__target_definition__type="event") | ~Q(pipeline__target_definition__has_key="type")+ )++# ── Recipe validation surface for the presentation layer ───────────────────# The semantic population kinds the labeler can compile. Presentation validates a submitted@@ -504,6 +750,14 @@ POPULATION_KINDS = _POPULATION_KINDSPREDICTION_EVENT_NAME = _PREDICTION_EVENT_NAME+def validate_iteration_recipe(*, model_spec: dict[str, Any], recipe_snapshot: dict[str, Any]) -> None:+ """Raise ``AutoresearchConflict`` if an agent-submitted recipe is outside the allowlist."""+ try:+ validate_recipe(model_spec=model_spec, recipe_snapshot=recipe_snapshot)+ except RecipeValidationError as exc:+ raise AutoresearchConflict(str(exc)) from exc++# ── Choice vocabularies for the presentation layer ─────────────────────────# The (value, label) pairs behind each status-like field. Presentation declares itsdiff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.pyindex d31453626f84..44823cc66d81 100644--- a/products/autoresearch/backend/facade/contracts.py+++ b/products/autoresearch/backend/facade/contracts.py@@ -120,6 +120,7 @@ class IterationTrailEntry:train_score: float | Noneagent_description: strmodel_spec: dict[str, Any]+ recipe_snapshot: dict[str, Any]@dataclass(frozen=True)@@ -166,6 +167,26 @@ class TrainingRun:created_at: datetime+@dataclass(frozen=True)+class Iteration:+ """One recipe attempt within a training run."""++ id: UUID+ pipeline: UUID+ training_run: UUID+ iteration_number: int+ recipe_hash: str+ recipe_snapshot: dict[str, Any]+ model_spec: dict[str, Any]+ train_score: float | None+ holdout_score: float | None+ status: str+ agent_description: str+ agent_confidence: float | None+ parent_suggestion: UUID | None+ created_at: datetime++@dataclass(frozen=True)class Run:"""Generic operational run: inference or validation."""@@ -261,3 +282,25 @@ class ResolvedTemplate:inference_population: dict[str, Any]output_person_property: strnotes: str+++# ── Training-run history ───────────────────────────────────────────────────+++@dataclass(frozen=True)+class TrainingRunHistoryEntry:+ run_id: UUID+ pipeline_id: UUID+ is_current_pipeline: bool+ target_event: str+ horizon_days: int+ best_holdout_score: float | None+ iteration_count: int+ completed_at: datetime | None+ summary: dict[str, Any] | None+ iterations: list[IterationTrailEntry]+++@dataclass(frozen=True)+class TrainingRunHistory:+ runs: list[TrainingRunHistoryEntry]diff --git a/products/autoresearch/backend/inference/scoring.py b/products/autoresearch/backend/inference/scoring.pyindex d3b0edadf8ff..263a1ae82b86 100644--- a/products/autoresearch/backend/inference/scoring.py+++ b/products/autoresearch/backend/inference/scoring.py@@ -830,6 +830,21 @@ def _stable_seed(pipeline_id: str) -> int:return int(hashlib.sha256(pipeline_id.encode()).hexdigest()[:8], 16)+def check_recipe_estimator(recipe: dict[str, Any]) -> None:+ """Raise ``RecipeValidationError`` when the recipe's class and params cannot build an estimator.++ Promotion calls this before a recipe-only champion is installed: the constructor is the+ only place an unknown hyperparameter is refused, and a champion that fails there would fail+ every scoring run instead of this one completion.+ """+ try:+ _estimator_for(recipe, seed=0)+ except RecipeValidationError:+ raise+ except Exception as exc:+ raise RecipeValidationError(f"model_params cannot construct {recipe.get('model_class')!r}: {exc}") from exc++def _estimator_for(recipe: dict[str, Any], *, seed: int) -> Any:"""Instantiate the recipe's allowlisted sklearn class. This is the one in-process importlib@@ -846,8 +861,9 @@ def _estimator_for(recipe: dict[str, Any], *, seed: int) -> Any:model_class = getattr(importlib.import_module(module_path), class_name)params = dict(recipe.get("model_params") or {})accepted = inspect.signature(model_class.__init__).parameters- if "random_state" in accepted:- params.setdefault("random_state", seed)+ if "random_state" in accepted and params.get("random_state") is None:+ # An explicit null would otherwise suppress the seed and make a retry refit differently.+ params["random_state"] = seedif "n_jobs" in accepted:# The fit runs in the worker process; an agent's n_jobs=-1 would take every core it has.params["n_jobs"] = 1diff --git a/products/autoresearch/backend/inference/test_inference.py b/products/autoresearch/backend/inference/test_inference.pyindex d721b393f6cd..4f352ee57333 100644--- a/products/autoresearch/backend/inference/test_inference.py+++ b/products/autoresearch/backend/inference/test_inference.py@@ -765,6 +765,7 @@ class TestRecipeFit(SimpleTestCase):[("seeded_from_the_pipeline", {}, 1234),("recipe_seed_wins", {"random_state": 7}, 7),+ ("null_seed_falls_back_to_the_pipeline", {"random_state": None}, 1234),])def test_stochastic_estimator_gets_a_stable_seed(self, _name, params, expected):diff --git a/products/autoresearch/backend/presentation/AGENTS.md b/products/autoresearch/backend/presentation/AGENTS.mdindex 429530187d8c..76d2f503d910 100644--- a/products/autoresearch/backend/presentation/AGENTS.md+++ b/products/autoresearch/backend/presentation/AGENTS.md@@ -5,14 +5,15 @@ The HTTP surface — and, because of how PostHog's codegen works, considerably mThese 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, 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.+This package lands one endpoint group at a time. Pipeline CRUD, the pre-create helpers, the read-only model and run viewsets, and the training-run surface the agent records its work through are here; the lifecycle actions, the artifact and feature-materialization endpoints, 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`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.+ - `AutoresearchTrainingRunViewSet` — read plus create, and the agent's write surface so far: `iterations`, `complete`, plus `history`.+ - `AutoresearchModelViewSet`, `AutoresearchRunViewSet` — 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.@@ -24,11 +25,29 @@ Every viewset sets `scope_object = "autoresearch"` and splits `scope_object_read**A new `@action` must be added to one of those two lists.** Omitting it is not a compile error and not a test failure — it is a permissions bug.+## The agent is a client here++This is the part that makes this package unusual. During a training run the sandbox agent is an authenticated API client, and `AutoresearchTrainingRunViewSet` is how it records everything it does:++```text+agent server+ │ POST training_runs/<id>/iterations → validated, stored as AutoresearchIteration+ │ POST .../complete → server-side champion selection+```++Consequences worth internalizing:++- **Everything the agent sends is untrusted.** SQL it submits gets executed. `iterations` runs it through `../training/recipe_validation.py`.+- **The write surface closes when the run does.** `iterations` and `complete` require the run to be RUNNING (or PENDING for `complete`), so a finished run is frozen. Recording takes the run row lock that completion takes, so the status check and the upsert see one state, and it refuses a new `iteration_number` once the run's `iteration_budget` is used.+- **Nested writes are bound to the pipeline in the URL.** A run id under another pipeline's route is a 404, the same as the nested reads.+- **`complete` does not accept a champion.** It triggers `complete_training_run()` in `../training/promotion.py`, which picks the champion server-side from the recorded iterations. The agent cannot promote itself.+- If the agent cannot reach these tools, a run burns its full budget doing nothing and fails with `"Agent recorded no iterations before the run ended."` That symptom is almost always MCP connectivity, not the model.+## Where the rest of the system meets this package- **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`).+- **Calls into** — `../training/` (complete), `../dataset/` (validate, templates, `resolve_target`).## Declare the response when it differs from the request@@ -42,5 +61,7 @@ Any action whose response shape differs from its request needs the same treatmen- **Annotate everything.** `help_text` on fields, `@extend_schema` on custom actions. These flow straight into MCP tool schemas and generated types; an unannotated action produces an empty schema an agent cannot use.- **Classify every new `@action`** into `scope_object_read_actions` or `scope_object_write_actions`.+- **Validate everything the agent can write**, in the viewset, before it reaches storage or the query engine.- Regenerate after serializer changes (`hogli build:openapi`) and commit the generated files — CI checks for drift.-- **If you add an endpoint, update this file to match.**+- Keep champion selection out of this layer. Endpoints record and trigger; `../training/promotion.py` decides.+- **If you add an endpoint or change the agent's write surface, update this file to match.**diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.pyindex c6937c3d2fca..59afc2ccfcfb 100644--- a/products/autoresearch/backend/presentation/views/serializers.py+++ b/products/autoresearch/backend/presentation/views/serializers.py@@ -1,4 +1,6 @@import re+import json+import mathfrom dataclasses import replacefrom typing import Any@@ -13,6 +15,8 @@ from posthog.permissions import get_authenticator_scopesfrom products.autoresearch.backend.facade import apifrom products.autoresearch.backend.facade.contracts import (+ AutoresearchConflict,+ Iteration,IterationTrailEntry,Model,Pipeline,@@ -35,6 +39,9 @@ TRAINING_RUN_STATUS_CHOICES = api.TRAINING_RUN_STATUS_CHOICESITERATION_STATUS_CHOICES = api.ITERATION_STATUS_CHOICESTARGET_EVENT_MAX_LENGTH = 255+AGENT_DESCRIPTION_MAX_LENGTH = 2000+OBJECT_JSON_MAX_BYTES = 64 * 1024+MODEL_SPEC_MAX_BYTES = 4 * 1024OUTPUT_PERSON_PROPERTY_MAX_LENGTH = 255# The target event is interpolated into the sandboxed training agent's prompt brief, so reject@@ -142,6 +149,55 @@ def resolve_target(# ── Typed schema wrappers for JSONField -----------------------------------+class ObjectJSONField(serializers.JSONField):+ """A JSON object the agent writes and Postgres stores.++ The schema says object, so a list or scalar is a 400 here rather than a 500 downstream. The+ value is re-encoded because ``STRICT_JSON`` is off: a nested NaN or a NUL character parses+ fine and then fails the ``jsonb`` insert, and the encoded size is capped because the+ object rides along on every iteration and comes back in every run and history response.+ """++ max_bytes = OBJECT_JSON_MAX_BYTES++ def to_internal_value(self, data: Any) -> Any:+ value = super().to_internal_value(data)+ if not isinstance(value, dict):+ raise serializers.ValidationError("Must be a JSON object.")+ try:+ # UTF-8 refuses the unpaired surrogate that a "\\ud800" escape parses to.+ encoded = json.dumps(value, allow_nan=False, ensure_ascii=False).encode("utf-8")+ except ValueError as exc:+ raise serializers.ValidationError(+ "Must not contain NaN, infinite numbers or unpaired surrogate characters."+ ) from exc+ if b"\\u0000" in encoded:+ raise serializers.ValidationError("Must not contain NUL characters.")+ if len(encoded) > self.max_bytes:+ raise serializers.ValidationError(f"Must be at most {self.max_bytes} bytes as JSON.")+ return value+++class FiniteFloatField(serializers.FloatField):+ """A float that refuses NaN and infinity.++ DRF coerces the strings "NaN" and "Infinity" to floats that pass every min/max check, and+ Postgres ranks NaN above every finite score, so an unchecked NaN would win champion selection.+ """++ def to_internal_value(self, data: Any) -> float:+ if isinstance(data, bool):+ raise serializers.ValidationError("Must be a number, not a boolean.")+ try:+ value = super().to_internal_value(data)+ except OverflowError as exc:+ # float() raises this, not ValueError, on an integer past the float range.+ raise serializers.ValidationError("Must be a finite number.") from exc+ if not math.isfinite(value):+ raise serializers.ValidationError("Must be a finite number.")+ return value++@extend_schema_field({"oneOf": [@@ -293,10 +349,73 @@ class ModelRecipeField(serializers.JSONField):),})-class ModelExplanationField(serializers.JSONField):+class ModelExplanationField(ObjectJSONField):+ pass+++@extend_schema_field(+ {+ "type": "object",+ "description": (+ "Compact recipe for this iteration: feature_sql, a read-only HogQL SELECT that reads from "+ "{anchors} and returns one row per person keyed on person_id, and optional feature_transforms."+ ),+ "properties": {+ "feature_sql": {+ "type": "string",+ "description": "A read-only HogQL SELECT from {anchors}, one row per person, keyed on person_id.",+ },+ "feature_transforms": {+ "type": "array",+ "nullable": True,+ "items": {"type": "object"},+ "description": (+ "Transforms the bundle applies to the feature columns; null or absent means none, and the "+ "in-process path accepts none."+ ),+ },+ },+ "required": ["feature_sql"],+ "example": {+ "feature_sql": (+ "SELECT a.person_id AS distinct_id, countIf(e.event = '$pageview') AS pageviews "+ "FROM {anchors} a LEFT JOIN events e ON e.person_id = a.person_id AND e.timestamp < a.cutoff_ts "+ "GROUP BY a.person_id, a.cutoff_ts"+ ),+ "feature_transforms": [],+ },+ }+)+class IterationRecipeField(ObjectJSONField):pass+@extend_schema_field(+ {+ "type": "object",+ "description": (+ "Model class and hyperparameters tried this iteration. Any model_class is accepted here, "+ "because a bundle runs its own code. A run that uploads no bundle scores in process, and "+ "completion then requires an allowlisted sklearn/xgboost classifier."+ ),+ "properties": {+ "model_class": {"type": "string", "description": "Dotted path of the estimator class."},+ "model_params": {+ "type": "object",+ "nullable": True,+ "additionalProperties": True,+ "description": "Keyword arguments for the estimator's constructor; null or absent means the defaults.",+ },+ },+ "required": ["model_class"],+ "example": {"model_class": "sklearn.linear_model.LogisticRegression", "model_params": {"C": 1.0}},+ }+)+class ModelSpecField(ObjectJSONField):+ # A class name and a few hyperparameters; the recipe field holds the SQL and gets the room.+ max_bytes = MODEL_SPEC_MAX_BYTES++@extend_schema_field({"type": "object",@@ -799,7 +918,7 @@ class IterationTrailSerializer(DataclassSerializer):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.")+ model_spec = ModelSpecField(help_text="Model class and hyperparameters tried in this iteration.")class Meta:dataclass = IterationTrailEntry@@ -813,6 +932,18 @@ class IterationTrailSerializer(DataclassSerializer):]+@extend_schema_serializer(component_name="IterationTrailWithRecipe")+class IterationTrailWithRecipeSerializer(IterationTrailSerializer):+ """The trail with each iteration's recipe, for history only: a run list page would otherwise carry every recipe of every run."""++ recipe_snapshot = IterationRecipeField(+ help_text="The recipe this iteration tried: its feature_sql and transforms, so a later run can reuse them."+ )++ class Meta(IterationTrailSerializer.Meta):+ fields = [*IterationTrailSerializer.Meta.fields, "recipe_snapshot"]++@extend_schema_serializer(component_name="AutoresearchTrainingRun")class AutoresearchTrainingRunSerializer(DataclassSerializer):id = serializers.UUIDField(read_only=True, help_text="Unique UUID of this training run.")@@ -888,6 +1019,105 @@ class AutoresearchTrainingRunSerializer(DataclassSerializer):]+@extend_schema_serializer(component_name="AutoresearchIteration")+class AutoresearchIterationSerializer(DataclassSerializer):+ id = serializers.UUIDField(read_only=True)+ pipeline = serializers.UUIDField()+ training_run = serializers.UUIDField()+ iteration_number = serializers.IntegerField(+ min_value=-2147483648,+ max_value=2147483647,+ )+ recipe_hash = serializers.CharField(max_length=64)+ recipe_snapshot = IterationRecipeField(+ help_text="Compact recipe snapshot at time of iteration. Full artifact lives in the model row."+ )+ model_spec = ModelSpecField(help_text="Model class and hyperparameters tried in this iteration.")+ train_score = serializers.FloatField(required=False, allow_null=True)+ holdout_score = serializers.FloatField(required=False, allow_null=True)+ status = serializers.ChoiceField(choices=ITERATION_STATUS_CHOICES)+ agent_description = serializers.CharField(required=False, allow_blank=True)+ agent_confidence = serializers.FloatField(+ required=False, allow_null=True, help_text="Agent's self-assessed confidence 0–1"+ )+ parent_suggestion = serializers.UUIDField(+ required=False,+ allow_null=True,+ help_text="UUID of the steering suggestion this iteration was spawned from, if any.",+ )+ created_at = serializers.DateTimeField(read_only=True)++ class Meta:+ dataclass = Iteration+ fields = [+ "id",+ "pipeline",+ "training_run",+ "iteration_number",+ "recipe_hash",+ "recipe_snapshot",+ "model_spec",+ "train_score",+ "holdout_score",+ "status",+ "agent_description",+ "agent_confidence",+ "parent_suggestion",+ "created_at",+ ]+++class TrainingRunHistoryEntrySerializer(serializers.Serializer):+ """One prior completed training run plus its full iteration trail."""++ run_id = serializers.UUIDField(help_text="UUID of the completed training run.")+ pipeline_id = serializers.UUIDField(help_text="UUID of the pipeline this run belongs to.")+ is_current_pipeline = serializers.BooleanField(+ help_text=(+ "True if this run is from the pipeline you are training; False if it is a same-target "+ "sibling pipeline on the team."+ )+ )+ target_event = serializers.CharField(help_text="Target event this run's pipeline predicts.")+ horizon_days = serializers.IntegerField(help_text="Prediction horizon (days) of this run's pipeline.")+ best_holdout_score = serializers.FloatField(+ allow_null=True, help_text="Best holdout AUC achieved across this run's iterations."+ )+ iteration_count = serializers.IntegerField(help_text="Number of iterations recorded in this run.")+ completed_at = serializers.DateTimeField(allow_null=True, help_text="When this run completed.")+ summary = TrainingRunSummarySerializer(+ allow_null=True,+ help_text="Distilled tier-1 summary of this run — read this first to orient. Null for older runs without one.",+ )+ iterations = IterationTrailWithRecipeSerializer(+ many=True,+ help_text="The iteration trail: every recipe tried, kept or discarded, with rationale and score.",+ )+++class TrainingRunHistoryQuerySerializer(serializers.Serializer):+ limit = serializers.IntegerField(+ required=False,+ default=5,+ min_value=1,+ max_value=api.HISTORY_LIMIT_MAX,+ help_text=f"Maximum number of prior runs to return (default 5, at most {api.HISTORY_LIMIT_MAX}).",+ )+++class TrainingRunHistorySerializer(serializers.Serializer):+ """Cross-run learning memory: prior runs the agent should read before iterating."""++ runs = TrainingRunHistoryEntrySerializer(+ many=True,+ help_text=(+ "Recent completed training runs — the current pipeline first, then same-target sibling "+ "pipelines on the team — newest first. Mine these to reuse winning features and avoid "+ "repeating discarded approaches."+ ),+ )++@extend_schema_serializer(component_name="AutoresearchRun")class AutoresearchRunSerializer(DataclassSerializer):id = serializers.UUIDField(read_only=True, help_text="Unique UUID of this run.")@@ -1042,6 +1272,127 @@ class ValidatePipelineResponseSerializer(serializers.Serializer):)+# ── Agent-recorded training serializers ────────────────────────────────────+++class OpenTrainingRunSerializer(serializers.Serializer):+ """Input for opening an agent-driven training run."""++ iteration_budget = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=500,+ help_text="Iteration budget for this run. Defaults to the pipeline's iteration_budget if omitted.",+ )+++class RecordIterationSerializer(serializers.Serializer):+ """Input for recording one training iteration. Validated against the recipe allowlist."""++ iteration_number = serializers.IntegerField(+ min_value=0,+ max_value=2147483647,+ help_text="Zero-based index of this iteration within the run. Re-sending the same number updates that iteration (idempotent).",+ )+ recipe_snapshot = IterationRecipeField(+ help_text="Compact recipe for this iteration: feature_sql (HogQL SELECT keyed on person_id) and transforms.",+ )+ model_spec = ModelSpecField(+ help_text=(+ "model_class and model_params tried this iteration. Any class is accepted here; the sklearn/xgboost "+ "allowlist applies at completion, to a run that uploaded no bundle."+ ),+ )+ status = serializers.ChoiceField(+ choices=["kept", "discarded", "crashed"],+ help_text="'kept' if this iteration improved on the best score, 'discarded' otherwise, 'crashed' on failure.",+ )+ train_score = FiniteFloatField(+ required=False,+ allow_null=True,+ min_value=0,+ max_value=1,+ help_text="Training-set AUC for this iteration (0-1).",+ )+ holdout_score = FiniteFloatField(+ required=False,+ allow_null=True,+ min_value=0,+ max_value=1,+ help_text="Held-out AUC for this iteration (0-1). Used to pick the champion at completion.",+ )+ agent_description = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ max_length=AGENT_DESCRIPTION_MAX_LENGTH,+ help_text=f"Agent's plain-English rationale for this iteration. Max {AGENT_DESCRIPTION_MAX_LENGTH} characters.",+ )+ agent_confidence = FiniteFloatField(+ required=False,+ allow_null=True,+ min_value=0,+ max_value=1,+ help_text="Agent's self-assessed confidence (0-1) that this iteration helps.",+ )+ parent_suggestion = serializers.UUIDField(+ required=False,+ allow_null=True,+ help_text=(+ "UUID of the steering suggestion this iteration was spawned from, if any. Set it whenever the "+ "iteration acts on a pending suggestion — it links the iteration back to the suggestion for "+ "attribution and advances the suggestion to 'acted_on'."+ ),+ )++ def validate(self, data: dict[str, Any]) -> dict[str, Any]:+ try:+ api.validate_iteration_recipe(+ model_spec=data.get("model_spec") or {}, recipe_snapshot=data.get("recipe_snapshot") or {}+ )+ except AutoresearchConflict as e:+ raise serializers.ValidationError(str(e)) from e+ return data+++class CompleteTrainingRunSerializer(serializers.Serializer):+ """Input for finalizing a training run. The backend selects/promotes the champion."""++ best_iteration_id = serializers.UUIDField(+ required=False,+ allow_null=True,+ help_text=(+ "Advisory nomination. The server promotes the kept iteration with the highest holdout_score; "+ "this id only breaks a tie at that score, and a lower-scoring nomination is logged and ignored."+ ),+ )+ model_explanation = ModelExplanationField(+ required=False,+ default=dict,+ help_text="Global feature importance / directionality bundle for the champion model card.",+ )+ recommended_next = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ max_length=2000,+ help_text=(+ "What a future run should try next, given what this run learned. Stored in the run summary so the "+ "next run reads it during orientation. Keep it short and concrete; max 2000 characters."+ ),+ )+ distillation = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ max_length=2000,+ help_text=(+ "A 1–2 sentence distillation of what this run learned — the winning signal, the key transform, the "+ "dead-ends. Stored in the run summary as the cheapest thing the next run reads. Max 2000 characters."+ ),+ )++# ── Template serializers ───────────────────────────────────────────────────────diff --git a/products/autoresearch/backend/presentation/views/views.py b/products/autoresearch/backend/presentation/views/views.pyindex b6e494cfda17..2703af3b8709 100644--- a/products/autoresearch/backend/presentation/views/views.py+++ b/products/autoresearch/backend/presentation/views/views.py@@ -32,17 +32,23 @@ from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRfrom products.autoresearch.backend.facade import apifrom products.autoresearch.backend.facade.access import has_autoresearch_access-from products.autoresearch.backend.facade.contracts import AutoresearchConflict, PipelineNotFound+from products.autoresearch.backend.facade.contracts import AutoresearchConflict, PipelineNotFound, TrainingRunNotFoundfrom .serializers import (+ AutoresearchIterationSerializer,AutoresearchModelSerializer,AutoresearchPipelineCreateSerializer,AutoresearchPipelineSerializer,AutoresearchRunSerializer,AutoresearchTrainingRunSerializer,+ CompleteTrainingRunSerializer,+ OpenTrainingRunSerializer,+ RecordIterationSerializer,ResolvedTemplateSerializer,ResolveTemplateRequestSerializer,TemplateInfoSerializer,+ TrainingRunHistoryQuerySerializer,+ TrainingRunHistorySerializer,ValidatePipelineRequestSerializer,ValidatePipelineResponseSerializer,resolve_target,@@ -119,6 +125,14 @@ def _parent_pipeline_id(view: Any) -> str | None:return str(pipeline_id) if pipeline_id else None+def _require_parent_pipeline_id(view: Any) -> str:+ """The pipeline id for a route that cannot act without one."""+ pipeline_id = _parent_pipeline_id(view)+ if pipeline_id is None:+ raise ValidationError("Pipeline not found.")+ return pipeline_id++def _pipeline_write_fields(validated: Any) -> dict[str, Any]:"""The fields to persist.@@ -397,7 +411,7 @@ class AutoresearchRunViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin, vie@extend_schema(tags=["autoresearch"])-class AutoresearchTrainingRunViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin, viewsets.ReadOnlyModelViewSet):+class AutoresearchTrainingRunViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin, viewsets.ModelViewSet):"""List and retrieve training runs for a pipeline.@@ -408,11 +422,13 @@ class AutoresearchTrainingRunViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMischema = 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] = []+ scope_object_read_actions = ["list", "retrieve", "history"]+ scope_object_write_actions = ["create", "record_iteration", "complete"]permission_classes = [AutoresearchAccessPermission]serializer_class = AutoresearchTrainingRunSerializerqueryset = None # data is reached through the facade; declared for router/schema only+ # A training run is opened and appended to, never edited or deleted.+ http_method_names = ["get", "post", "head", "options"]def _should_skip_parents_filter(self) -> bool:return True@@ -431,3 +447,133 @@ class AutoresearchTrainingRunViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMiif training_run is None:raise NotFound("Training run not found.")return Response(AutoresearchTrainingRunSerializer(instance=training_run).data)++ @validated_request(+ request_serializer=OpenTrainingRunSerializer,+ responses={+ 201: OpenApiResponse(+ response=AutoresearchTrainingRunSerializer,+ description="The opened training run. Record iterations against its id, then call complete.",+ ),+ 400: OpenApiResponse(description="Pipeline is archived."),+ },+ summary="Open a training run",+ description=(+ "Open a new training run for a pipeline and return its id. An agent — the in-house sandbox, an "+ "external bring-your-own agent, or a scheduled job — then records iterations against this run "+ "and finalizes it with the complete endpoint. The run starts in 'running'."+ ),+ )+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ try:+ training_run = api.open_training_run(+ self.team_id,+ _require_parent_pipeline_id(self),+ iteration_budget=request.validated_data.get("iteration_budget"),+ )+ except PipelineNotFound as exc:+ raise NotFound(str(exc)) from exc+ except AutoresearchConflict as exc:+ raise ValidationError(str(exc)) from exc+ return Response(AutoresearchTrainingRunSerializer(instance=training_run).data, status=201)++ @validated_request(+ request_serializer=RecordIterationSerializer,+ responses={+ 201: OpenApiResponse(+ response=AutoresearchIterationSerializer,+ description="The recorded iteration.",+ ),+ 400: OpenApiResponse(+ description=(+ "Recipe failed validation (feature_sql does not read from {anchors}, model_class missing, "+ "a non-object model_params), the run is not running, or its iteration budget is used."+ )+ ),+ },+ summary="Record a training iteration",+ description=(+ "Record one iteration of an open training run. Idempotent on iteration_number: re-sending the "+ "same number updates that iteration. A new iteration_number is refused once the run's "+ "iteration_budget is used. The recipe is validated server-side: feature_sql must be a read-only "+ "SELECT from {anchors} keyed on person_id, and model_class must be set. The class allowlist "+ "applies only at completion, to a run that uploaded no bundle."+ ),+ )+ @action(detail=True, methods=["post"], url_path="iterations")+ def record_iteration(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ try:+ iteration = api.record_iteration(+ self.team_id,+ self.kwargs["pk"],+ pipeline_id=_parent_pipeline_id(self),+ fields=dict(request.validated_data),+ )+ except TrainingRunNotFound:+ raise NotFound("Training run not found.")+ except AutoresearchConflict as exc:+ raise ValidationError(str(exc)) from exc+ return Response(AutoresearchIterationSerializer(instance=iteration).data, status=201)++ @validated_request(+ request_serializer=CompleteTrainingRunSerializer,+ responses={+ 200: OpenApiResponse(+ response=AutoresearchTrainingRunSerializer,+ description="The completed training run. Call autoresearch-models-list to see the resulting champion/challenger.",+ ),+ 400: OpenApiResponse(+ description="Run is already completed or failed, has no recorded iterations, or has no usable model artifact (no bundle and no feature SQL)."+ ),+ },+ summary="Complete a training run",+ description=(+ "Finalize a training run. The backend selects the kept iteration with the highest holdout score, "+ "decides champion vs challenger via the promotion ladder, and persists the model. "+ "best_iteration_id is advisory: it breaks a tie at the top score and is otherwise logged and "+ "ignored. Agents cannot set the champion directly, because promotion is server-side."+ ),+ )+ @action(detail=True, methods=["post"], url_path="complete")+ def complete(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ data = request.validated_data+ try:+ training_run = api.complete_run(+ self.team_id,+ self.kwargs["pk"],+ pipeline_id=_parent_pipeline_id(self),+ best_iteration_id=data.get("best_iteration_id"),+ model_explanation=data.get("model_explanation") or {},+ recommended_next=data.get("recommended_next") or "",+ distillation=data.get("distillation") or "",+ )+ except TrainingRunNotFound:+ raise NotFound("Training run not found.")+ except AutoresearchConflict as exc:+ raise ValidationError(str(exc)) from exc+ return Response(AutoresearchTrainingRunSerializer(instance=training_run).data)++ @validated_request(+ query_serializer=TrainingRunHistoryQuerySerializer,+ responses={+ 200: OpenApiResponse(+ response=TrainingRunHistorySerializer,+ description="Prior completed training runs with their iteration trails, for orienting a new run.",+ )+ },+ summary="Read prior training-run history",+ description=(+ "Return recent completed training runs and their iteration trails so a new run can learn "+ "from what was already tried. Scoped to this pipeline first, then same-target sibling "+ "pipelines on the team. Read this before iterating to reuse winning features and avoid "+ "repeating discarded approaches."+ ),+ )+ @action(detail=False, methods=["get"], url_path="history", pagination_class=None)+ def history(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ limit = request.validated_query_data["limit"]+ try:+ history = api.training_run_history(self.team_id, _require_parent_pipeline_id(self), limit=limit)+ except PipelineNotFound as exc:+ raise NotFound(str(exc)) from exc+ return Response(TrainingRunHistorySerializer(instance=history).data)diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.pyindex 1709d4c975d1..265beb688bd7 100644--- a/products/autoresearch/backend/tests/test_api.py+++ b/products/autoresearch/backend/tests/test_api.py@@ -16,6 +16,7 @@ from products.actions.backend.models.action import Actionfrom products.autoresearch.backend.dataset.templates import TEMPLATESfrom products.autoresearch.backend.dataset.validation import ValidationResult, ValidationWarningfrom products.autoresearch.backend.models import (+ AutoresearchIteration,AutoresearchModel,AutoresearchPipeline,AutoresearchRun,@@ -416,10 +417,23 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):def test_list_training_runs_for_pipeline(self):pipeline = self._make_pipeline()- AutoresearchTrainingRun.objects.create(pipeline=pipeline, status="completed", iteration_count=1)+ run = AutoresearchTrainingRun.objects.create(pipeline=pipeline, status="completed", iteration_count=1)+ AutoresearchIteration.objects.create(+ pipeline=pipeline,+ training_run=run,+ iteration_number=0,+ recipe_hash="abc",+ recipe_snapshot={"feature_sql": "SELECT 1"},+ model_spec={"model_class": "m"},+ status="kept",+ )resp = self.client.get(f"{self.base_url}/{pipeline.id}/training_runs/")assert resp.status_code == status.HTTP_200_OKassert resp.json()["count"] == 1+ # The list carries the trail without recipes; history is where a recipe is read back.+ trail_entry = resp.json()["results"][0]["iterations"][0]+ assert trail_entry["model_spec"] == {"model_class": "m"}+ assert "recipe_snapshot" not in trail_entrydef test_list_runs_for_pipeline(self):pipeline = self._make_pipeline()diff --git a/products/autoresearch/backend/training/promotion.py b/products/autoresearch/backend/training/promotion.pyindex 8e22f3de3506..baeb6612a885 100644--- a/products/autoresearch/backend/training/promotion.py+++ b/products/autoresearch/backend/training/promotion.py@@ -25,7 +25,12 @@ from posthog.hogql.visitor import clear_locationsfrom posthog.models.scoping import team_scope-from products.autoresearch.backend.inference.sandbox import fit_champion_model+from products.autoresearch.backend.inference.sandbox import (+ SandboxInferenceError,+ fit_champion_model,+ validate_runnable_feature_sql,+)+from products.autoresearch.backend.inference.scoring import check_recipe_estimatorfrom products.autoresearch.backend.models import (AutoresearchIteration,AutoresearchModel,@@ -112,9 +117,10 @@ def _build_recipe(iteration: AutoresearchIteration, *, trained_on: date) -> dictspec = iteration.model_spec or {}return {"feature_sql": snapshot.get("feature_sql", ""),- "feature_transforms": snapshot.get("feature_transforms", []),+ "feature_transforms": snapshot.get("feature_transforms") or [],"model_class": spec.get("model_class", "sklearn.linear_model.LogisticRegression"),- "model_params": spec.get("model_params", {}),+ # Recording accepts an absent or null model_params; both mean the constructor defaults.+ "model_params": spec.get("model_params") or {},"fit_signature": (iteration.recipe_hash or "")[:16],"trained_on": trained_on.isoformat(),"holdout_score": iteration.holdout_score or 0.0,@@ -229,8 +235,27 @@ def _require_legacy_recipe_is_runnable(recipe: dict[str, Any]) -> None:"Cannot persist a model: no complete bundle was uploaded and the selected ""iteration recorded no feature_sql for the legacy scoring path.")+ try:+ # Scoring runs the feature SQL as the top-level query and refuses a trailing LIMIT,+ # OFFSET or SETTINGS, so a champion that would fail every cadence is refused here.+ validate_runnable_feature_sql(str(recipe["feature_sql"]), source="feature_sql")+ except SandboxInferenceError as exc:+ raise PromotionError(f"Cannot persist a model on the legacy scoring path: {exc}") from exc+ if recipe.get("feature_transforms"):+ # The in-process scorer fits on the raw feature_sql columns and never applies the+ # transforms, so the served model would not be the one the holdout score describes.+ raise PromotionError(+ "Cannot persist a model on the legacy scoring path: it does not apply feature_transforms, "+ "so a recipe that needs them must ship as an uploaded bundle."+ )+ if not isinstance(recipe.get("model_params"), dict):+ raise PromotionError(+ "Cannot persist a model on the legacy scoring path: model_params must be a JSON object, "+ "because the in-process scorer expands it into the estimator's constructor."+ )try:validate_model_class(str(recipe["model_class"]))+ check_recipe_estimator(recipe)except RecipeValidationError as exc:raise PromotionError(f"Cannot persist a model on the legacy scoring path: {exc}") from exc@@ -370,6 +395,9 @@ def _finalize_under_lock(raise PromotionError("Agent recorded no iterations, so there is nothing to complete.")best = _select_best_iteration(training_run, best_iteration_id)+ if best_iteration_id is not None and best.id != best_iteration_id:+ # The explanation describes the nominated recipe, not the one the ranking selected.+ model_explanation = {}# If the agent uploaded a runnable bundle, the champion's artifact is that bundle# (inference runs train.py/predict.py in a sandbox).diff --git a/products/autoresearch/backend/training/recipe_validation.py b/products/autoresearch/backend/training/recipe_validation.pyindex 6ac52366580f..8b2e89d7cf24 100644--- a/products/autoresearch/backend/training/recipe_validation.py+++ b/products/autoresearch/backend/training/recipe_validation.py@@ -286,9 +286,17 @@ def validate_recipe(model_spec: object, recipe_snapshot: object) -> None:model_class = model_spec.get("model_class")if not isinstance(model_class, str) or not model_class.strip():raise RecipeValidationError("model_spec.model_class is required and must be a non-empty string.")+ model_params = model_spec.get("model_params")+ if model_params is not None and not isinstance(model_params, Mapping):+ raise RecipeValidationError("model_spec.model_params must be a JSON object when present.")if not isinstance(recipe_snapshot, Mapping):raise RecipeValidationError("recipe_snapshot must be a JSON object.")feature_sql = recipe_snapshot.get("feature_sql")if not isinstance(feature_sql, str) or not feature_sql.strip():raise RecipeValidationError("recipe_snapshot.feature_sql is required and must be a non-empty SELECT.")+ feature_transforms = recipe_snapshot.get("feature_transforms")+ if feature_transforms is not None and (+ not isinstance(feature_transforms, list) or not all(isinstance(item, Mapping) for item in feature_transforms)+ ):+ raise RecipeValidationError("recipe_snapshot.feature_transforms must be a list of JSON objects when present.")validate_feature_sql(feature_sql)diff --git a/products/autoresearch/backend/training/test_agent_recorded_training.py b/products/autoresearch/backend/training/test_agent_recorded_training.pynew file mode 100644index 000000000000..80f69889c2b1--- /dev/null+++ b/products/autoresearch/backend/training/test_agent_recorded_training.py@@ -0,0 +1,662 @@+from typing import Any+from uuid import UUID++from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++from parameterized import parameterized+from rest_framework import status++from posthog.models import Organization, Team++from products.autoresearch.backend.models import (+ AutoresearchIteration,+ AutoresearchModel,+ AutoresearchPipeline,+ AutoresearchSuggestion,+ AutoresearchTrainingRun,+)+from products.autoresearch.backend.presentation.views.serializers import (+ AGENT_DESCRIPTION_MAX_LENGTH,+ MODEL_SPEC_MAX_BYTES,+ OBJECT_JSON_MAX_BYTES,+ CompleteTrainingRunSerializer,+ RecordIterationSerializer,+)+from products.autoresearch.backend.testing import TeamScopedTestMixin+from products.autoresearch.backend.training import artifacts+from products.autoresearch.backend.training.ingestion import handle_task_run_completed+from products.autoresearch.backend.training.promotion import PromotionError, complete_training_run+from products.tasks.backend.models import TaskRun as TaskRunModel # tach-ignore++VALID_FEATURE_SQL = (+ "SELECT a.person_id AS distinct_id, countIf(e.event = '$pageview') AS pv "+ "FROM {anchors} a LEFT JOIN events e ON e.person_id = a.person_id "+ "GROUP BY a.person_id, a.cutoff_ts"+)+VALID_RECIPE = {"feature_sql": VALID_FEATURE_SQL, "feature_transforms": []}+VALID_SPEC = {"model_class": "sklearn.linear_model.LogisticRegression", "model_params": {"C": 1.0}}+++class TestAgentRecordedTraining(TeamScopedTestMixin, APIBaseTest):+ def setUp(self):+ super().setUp()+ self._flag_patcher = patch(+ "products.autoresearch.backend.access.posthoganalytics.feature_enabled",+ return_value=True,+ )+ self._flag_patcher.start()+ self.addCleanup(self._flag_patcher.stop)+ self.pipeline = AutoresearchPipeline.objects.create(+ team=self.team,+ created_by=self.user,+ name="Test Pipeline",+ target_event="$pageview",+ horizon_days=7,+ iteration_budget=50,+ iteration_budget_remaining=50,+ )+ self.runs_url = f"/api/projects/{self.team.pk}/autoresearch/{self.pipeline.pk}/training_runs"++ def _open_run(self, *, iteration_budget: int | None = None) -> str:+ body = {"iteration_budget": iteration_budget} if iteration_budget else {}+ resp = self.client.post(f"{self.runs_url}/", body, format="json")+ assert resp.status_code == status.HTTP_201_CREATED, resp.json()+ return resp.json()["id"]++ def _record(+ self,+ run_id: str,+ *,+ number: int,+ status_value: str = "kept",+ holdout: float = 0.8,+ spec: dict[str, Any] | None = None,+ recipe: dict[str, Any] | None = None,+ runs_url: str | None = None,+ ) -> Any:+ return self.client.post(+ f"{runs_url or self.runs_url}/{run_id}/iterations/",+ {+ "iteration_number": number,+ "recipe_snapshot": recipe or VALID_RECIPE,+ "model_spec": spec or VALID_SPEC,+ "status": status_value,+ "holdout_score": holdout,+ "agent_description": "test iteration",+ },+ format="json",+ )++ def test_open_training_run(self):+ resp = self.client.post(f"{self.runs_url}/", {"iteration_budget": 7}, format="json")+ assert resp.status_code == status.HTTP_201_CREATED+ data = resp.json()+ assert data["status"] == "running"+ assert data["iteration_budget"] == 7+ run = AutoresearchTrainingRun.objects.get(pk=data["id"], team_id=self.team.pk)+ assert run.pipeline.pk == self.pipeline.pk+ assert run.started_at is not None++ def test_record_iteration_creates_row(self):+ run_id = self._open_run()+ resp = self._record(run_id, number=0)+ assert resp.status_code == status.HTTP_201_CREATED, resp.json()+ assert AutoresearchIteration.objects.filter(training_run_id=UUID(run_id), iteration_number=0).exists()++ def test_record_iteration_links_parent_suggestion_and_marks_acted_on(self):+ suggestion = AutoresearchSuggestion.objects.create(+ pipeline=self.pipeline,+ created_by=self.user,+ prompt="try a calibrated logistic regression",+ priority=AutoresearchSuggestion.Priority.TRY_NEXT,+ source=AutoresearchSuggestion.Source.USER,+ )+ run_id = self._open_run()+ resp = self.client.post(+ f"{self.runs_url}/{run_id}/iterations/",+ {+ "iteration_number": 0,+ "recipe_snapshot": VALID_RECIPE,+ "model_spec": VALID_SPEC,+ "status": "kept",+ "holdout_score": 0.9,+ "agent_description": "acting on the steer",+ "parent_suggestion": str(suggestion.id),+ },+ format="json",+ )+ assert resp.status_code == status.HTTP_201_CREATED, resp.json()+ iteration = AutoresearchIteration.objects.get(training_run_id=UUID(run_id), iteration_number=0)+ assert str(iteration.parent_suggestion_id) == str(suggestion.id)+ # Spawning an iteration from a suggestion advances it to acted_on for the UI feedback loop.+ suggestion.refresh_from_db()+ assert suggestion.status == "acted_on"+ assert str(iteration.id) in [str(i) for i in suggestion.iterations.values_list("id", flat=True)]+ # A re-send that omits the field keeps the attribution; an explicit null clears it.+ assert self._record(run_id, number=0, holdout=0.95).status_code == status.HTTP_201_CREATED+ iteration.refresh_from_db()+ assert str(iteration.parent_suggestion_id) == str(suggestion.id)+ resp = self.client.post(+ f"{self.runs_url}/{run_id}/iterations/",+ {+ "iteration_number": 0,+ "recipe_snapshot": VALID_RECIPE,+ "model_spec": VALID_SPEC,+ "status": "kept",+ "parent_suggestion": None,+ },+ format="json",+ )+ assert resp.status_code == status.HTTP_201_CREATED, resp.json()+ iteration.refresh_from_db()+ assert iteration.parent_suggestion_id is None++ def test_record_iteration_rejects_foreign_parent_suggestion(self):+ other_pipeline = AutoresearchPipeline.objects.create(+ team=self.team, created_by=self.user, name="Other", target_event="$pageview", horizon_days=7+ )+ foreign = AutoresearchSuggestion.objects.create(+ pipeline=other_pipeline, created_by=self.user, prompt="foreign", source=AutoresearchSuggestion.Source.USER+ )+ run_id = self._open_run()+ resp = self.client.post(+ f"{self.runs_url}/{run_id}/iterations/",+ {+ "iteration_number": 0,+ "recipe_snapshot": VALID_RECIPE,+ "model_spec": VALID_SPEC,+ "status": "kept",+ "holdout_score": 0.9,+ "parent_suggestion": str(foreign.id),+ },+ format="json",+ )+ assert resp.status_code == status.HTTP_400_BAD_REQUEST++ def test_record_iteration_accepts_any_model_class(self):+ # model_class is informational at recording time — the agent's real model runs+ # as arbitrary code in a sandbox. The allowlist is enforced only at the legacy+ # in-process inference importlib site, not here.+ run_id = self._open_run()+ resp = self._record(run_id, number=0, spec={"model_class": "xgboost.XGBClassifier", "model_params": {}})+ assert resp.status_code == status.HTTP_201_CREATED, resp.json()+ assert AutoresearchIteration.objects.filter(training_run_id=UUID(run_id)).exists()++ def test_record_iteration_still_requires_model_class(self):+ run_id = self._open_run()+ resp = self._record(run_id, number=0, spec={"model_params": {}})+ assert resp.status_code == status.HTTP_400_BAD_REQUEST++ def test_record_iteration_rejects_feature_sql_without_person_id(self):+ run_id = self._open_run()+ resp = self._record(run_id, number=0, recipe={"feature_sql": "SELECT count() AS c FROM events"})+ assert resp.status_code == status.HTTP_400_BAD_REQUEST+ assert "person_id" in str(resp.json())++ def test_record_iteration_is_idempotent_on_number(self):+ run_id = self._open_run()+ self._record(run_id, number=0, holdout=0.7)+ self._record(run_id, number=0, holdout=0.9)+ rows = AutoresearchIteration.objects.filter(training_run_id=UUID(run_id), iteration_number=0)+ assert rows.count() == 1+ row = rows.first()+ assert row is not None and row.holdout_score == 0.9++ def test_record_iteration_refuses_a_new_number_past_the_budget(self):+ run_id = self._open_run(iteration_budget=1)+ assert self._record(run_id, number=0, holdout=0.7).status_code == status.HTTP_201_CREATED+ assert self._record(run_id, number=0, holdout=0.9).status_code == status.HTTP_201_CREATED+ resp = self._record(run_id, number=1)+ assert resp.status_code == status.HTTP_400_BAD_REQUEST+ assert "iteration budget" in str(resp.json())+ assert AutoresearchIteration.objects.filter(training_run_id=UUID(run_id)).count() == 1++ def test_write_actions_are_bound_to_the_pipeline_in_the_url(self):+ other_pipeline = AutoresearchPipeline.objects.create(+ team=self.team, created_by=self.user, name="Other", target_event="$pageview", horizon_days=7+ )+ other_runs_url = f"/api/projects/{self.team.pk}/autoresearch/{other_pipeline.pk}/training_runs"+ run_id = self._open_run()+ self._record(run_id, number=0)++ assert self._record(run_id, number=1, runs_url=other_runs_url).status_code == status.HTTP_404_NOT_FOUND+ resp = self.client.post(f"{other_runs_url}/{run_id}/complete/", {}, format="json")+ assert resp.status_code == status.HTTP_404_NOT_FOUND+ run = AutoresearchTrainingRun.objects.get(pk=run_id, team_id=self.team.pk)+ assert run.status == AutoresearchTrainingRun.Status.RUNNING+ assert run.iterations.count() == 1++ def test_record_iteration_rejects_when_run_not_running(self):+ run_id = self._open_run()+ self._record(run_id, number=0)+ self.client.post(f"{self.runs_url}/{run_id}/complete/", {}, format="json")+ resp = self._record(run_id, number=1)+ assert resp.status_code == status.HTTP_400_BAD_REQUEST++ def test_complete_promotes_cold_start_champion(self):+ run_id = self._open_run()+ self._record(run_id, number=0, status_value="discarded", holdout=0.7)+ self._record(run_id, number=1, status_value="kept", holdout=0.82)+ resp = self.client.post(f"{self.runs_url}/{run_id}/complete/", {}, format="json")+ assert resp.status_code == status.HTTP_200_OK+ data = resp.json()+ assert data["status"] == "completed"+ assert data["best_holdout_score"] == 0.82+ champion = AutoresearchModel.objects.get(pipeline=self.pipeline, role=AutoresearchModel.Role.CHAMPION)+ assert champion.holdout_score == 0.82+ assert champion.model_recipe["model_class"] == "sklearn.linear_model.LogisticRegression"++ def test_complete_keeps_weaker_model_as_challenger(self):+ # First run promotes a strong champion.+ run1 = self._open_run()+ self._record(run1, number=0, status_value="kept", holdout=0.85)+ self.client.post(f"{self.runs_url}/{run1}/complete/", {}, format="json")+ # Second run's best iteration is weaker — must not steal the champion.+ run2 = self._open_run()+ self._record(run2, number=0, status_value="kept", holdout=0.80)+ self.client.post(f"{self.runs_url}/{run2}/complete/", {}, format="json")+ assert (+ AutoresearchModel.objects.filter(pipeline=self.pipeline, role=AutoresearchModel.Role.CHAMPION).count() == 1+ )+ champion = AutoresearchModel.objects.get(pipeline=self.pipeline, role=AutoresearchModel.Role.CHAMPION)+ assert champion.holdout_score == 0.85+ assert AutoresearchModel.objects.filter(+ pipeline=self.pipeline, role=AutoresearchModel.Role.CHALLENGER, holdout_score=0.80+ ).exists()++ def test_complete_writes_backend_derived_summary(self):+ run_id = self._open_run()+ self._record(run_id, number=0, status_value="kept", holdout=0.75)+ self._record(run_id, number=1, status_value="discarded", holdout=0.70)+ self._record(+ run_id,+ number=2,+ status_value="kept",+ holdout=0.82,+ spec={"model_class": "xgboost.XGBClassifier", "model_params": {}},+ )+ resp = self.client.post(f"{self.runs_url}/{run_id}/complete/", {}, format="json")+ assert resp.status_code == status.HTTP_200_OK+ summary = resp.json()["summary"]+ assert summary["target_event"] == "$pageview"+ assert summary["best_holdout_score"] == 0.82+ assert summary["champion_promoted"] is True+ assert summary["champion_model_class"] == "xgboost.XGBClassifier"+ # kept iterations are ranked highest-AUC first; discarded land in dead_ends.+ assert [it["iteration_number"] for it in summary["kept_ladder"]] == [2, 0]+ assert [it["iteration_number"] for it in summary["dead_ends"]] == [1]+ # Backend leaves the two judgment fields empty when the agent does not supply them.+ assert summary["recommended_next"] == ""+ assert summary["distillation"] == ""++ def test_complete_persists_agent_summary_enrichment(self):+ run_id = self._open_run()+ self._record(run_id, number=0, status_value="kept", holdout=0.8)+ resp = self.client.post(+ f"{self.runs_url}/{run_id}/complete/",+ {"distillation": "log1p of counts won", "recommended_next": "try session recency"},+ format="json",+ )+ assert resp.status_code == status.HTTP_200_OK+ summary = resp.json()["summary"]+ assert summary["distillation"] == "log1p of counts won"+ assert summary["recommended_next"] == "try session recency"+ run = AutoresearchTrainingRun.objects.get(pk=run_id, team_id=self.team.pk)+ assert run.summary["recommended_next"] == "try session recency"++ def test_complete_that_loses_the_race_to_failure_is_refused(self):+ run_id = self._open_run()+ self._record(run_id, number=0)++ def fail_first(training_run, **kwargs):+ AutoresearchTrainingRun.objects.filter(pk=training_run.pk).update(+ status=AutoresearchTrainingRun.Status.FAILED+ )+ return {"promoted": False}++ with patch("products.autoresearch.backend.training.promotion.complete_training_run", side_effect=fail_first):+ resp = self.client.post(f"{self.runs_url}/{run_id}/complete/", {}, format="json")+ assert resp.status_code == status.HTTP_400_BAD_REQUEST+ assert "failed" in str(resp.json())++ def test_complete_with_no_iterations_is_refused(self):+ # Completing an empty run used to mark it COMPLETED with no champion, stranding a+ # BOOTSTRAPPING pipeline with nothing to score and no safety-net retry.+ run_id = self._open_run()+ run = AutoresearchTrainingRun.objects.get(pk=run_id, team_id=self.team.pk)+ with self.assertRaises(PromotionError):+ complete_training_run(run)+ run.refresh_from_db()+ assert run.status == AutoresearchTrainingRun.Status.RUNNING+ assert not AutoresearchModel.objects.filter(pipeline=self.pipeline).exists()++ def test_signal_handler_uses_agent_recorded_path_when_iterations_exist(self):+ # Agent opens a run and records an iteration via the new MCP write path.+ run_id = self._open_run()+ self._record(run_id, number=0, status_value="kept", holdout=0.81)++ # Simulate the TaskRun post_save signal firing on completion.+ fake_task_run = MagicMock()+ fake_task_run.state = {"autoresearch_training_run_id": run_id}+ fake_task_run.status = TaskRunModel.Status.COMPLETED+ fake_task_run.error_message = ""+ fake_task_run.id = UUID("00000000-0000-0000-0000-000000000000")+ fake_task_run.team_id = self.team.pk+ fake_task_run.output = None # no set_output blob — agent recorded via tools+ # Ingestion only trusts a task run that the training run was bound to at dispatch.+ AutoresearchTrainingRun.objects.filter(pk=run_id, team_id=self.team.pk).update(task_run_id=fake_task_run.id)++ handle_task_run_completed(fake_task_run)++ run = AutoresearchTrainingRun.objects.get(pk=run_id, team_id=self.team.pk)+ assert run.status == AutoresearchTrainingRun.Status.COMPLETED+ assert run.best_holdout_score == 0.81+ assert AutoresearchModel.objects.filter(+ pipeline=self.pipeline,+ role=AutoresearchModel.Role.CHAMPION,+ holdout_score=0.81,+ ).exists()++ def test_cross_team_isolation(self):+ other_org = Organization.objects.create(name="Other")+ other_team = Team.objects.create(organization=other_org, name="Other team")+ other_pipeline = AutoresearchPipeline.objects.create(+ team=other_team, created_by=self.user, name="Other", target_event="$pageview", horizon_days=7+ )+ resp = self.client.post(+ f"/api/projects/{self.team.pk}/autoresearch/{other_pipeline.pk}/training_runs/", {}, format="json"+ )+ # Pipeline belongs to another team — must not be reachable through this project.+ assert resp.status_code == status.HTTP_404_NOT_FOUND+ assert not AutoresearchTrainingRun.objects.filter(pipeline=other_pipeline).exists()+ resp = self.client.get(f"/api/projects/{self.team.pk}/autoresearch/{other_pipeline.pk}/training_runs/history/")+ assert resp.status_code == status.HTTP_404_NOT_FOUND++ def test_complete_records_artifact_prefix_when_bundle_uploaded(self):+ fake_storage = _InMemoryStorage()+ with patch.object(artifacts, "object_storage", fake_storage):+ run_id = self._open_run()+ self._record(run_id, number=0, status_value="kept", holdout=0.82)++ run = AutoresearchTrainingRun.objects.get(pk=run_id, team_id=self.team.pk)+ prefix = artifacts.bundle_prefix(+ team_id=self.team.pk, pipeline_id=str(self.pipeline.pk), training_run_id=str(run.pk)+ )+ artifacts.write_bundle(+ prefix,+ artifacts.ArtifactBundle(+ train_py="print('train')",+ predict_py="print('predict')",+ # Promotion refuses a bundle whose SQL differs from the selected iteration's recorded one.+ features_sql=VALID_FEATURE_SQL,+ ),+ )++ resp = self.client.post(f"{self.runs_url}/{run_id}/complete/", {}, format="json")+ assert resp.status_code == status.HTTP_200_OK++ champion = AutoresearchModel.objects.get(pipeline=self.pipeline, role=AutoresearchModel.Role.CHAMPION)+ assert champion.artifact_prefix == prefix+ assert champion.metrics["artifact_bundle"] is True+ # model_recipe is derived from the winning iteration's recorded model_spec.+ assert champion.model_recipe["model_class"] == "sklearn.linear_model.LogisticRegression"++ def test_complete_without_bundle_leaves_artifact_prefix_empty(self):+ run_id = self._open_run()+ self._record(run_id, number=0, status_value="kept", holdout=0.7)+ resp = self.client.post(f"{self.runs_url}/{run_id}/complete/", {}, format="json")+ assert resp.status_code == status.HTTP_200_OK+ champion = AutoresearchModel.objects.get(pipeline=self.pipeline, role=AutoresearchModel.Role.CHAMPION)+ assert champion.artifact_prefix == ""+ assert champion.metrics["artifact_bundle"] is False+++class TestTrainingRunHistory(TeamScopedTestMixin, APIBaseTest):+ """The cross-run learning-memory read-back endpoint (training_runs/history)."""++ def setUp(self):+ super().setUp()+ self._flag_patcher = patch(+ "products.autoresearch.backend.access.posthoganalytics.feature_enabled",+ return_value=True,+ )+ self._flag_patcher.start()+ self.addCleanup(self._flag_patcher.stop)+ self.pipeline = AutoresearchPipeline.objects.create(+ team=self.team, created_by=self.user, name="Main", target_event="downloaded_file", horizon_days=30+ )++ def _runs_url(self, pipeline) -> str:+ return f"/api/projects/{self.team.pk}/autoresearch/{pipeline.pk}/training_runs"++ def _completed_run(self, pipeline, *, iterations, distillation="", recommended_next="") -> str:+ runs_url = self._runs_url(pipeline)+ run_id = self.client.post(f"{runs_url}/", {}, format="json").json()["id"]+ for number, (status_value, holdout, desc) in enumerate(iterations):+ self.client.post(+ f"{runs_url}/{run_id}/iterations/",+ {+ "iteration_number": number,+ "recipe_snapshot": VALID_RECIPE,+ "model_spec": VALID_SPEC,+ "status": status_value,+ "holdout_score": holdout,+ "agent_description": desc,+ },+ format="json",+ )+ resp = self.client.post(+ f"{runs_url}/{run_id}/complete/",+ {"distillation": distillation, "recommended_next": recommended_next},+ format="json",+ )+ assert resp.status_code == status.HTTP_200_OK+ return run_id++ def _history(self, pipeline=None, **params):+ pipeline = pipeline or self.pipeline+ return self.client.get(f"{self._runs_url(pipeline)}/history/", params)++ def test_history_returns_iteration_trail_for_completed_run(self):+ run_id = self._completed_run(+ self.pipeline,+ iterations=[("discarded", 0.70, "baseline engagement"), ("kept", 0.82, "added file RFM")],+ )+ resp = self._history()+ assert resp.status_code == status.HTTP_200_OK+ runs = resp.json()["runs"]+ assert len(runs) == 1+ run = runs[0]+ assert run["run_id"] == run_id+ assert run["is_current_pipeline"] is True+ assert run["target_event"] == "downloaded_file"+ assert run["best_holdout_score"] == 0.82+ descriptions = [(it["status"], it["holdout_score"], it["agent_description"]) for it in run["iterations"]]+ assert descriptions == [+ ("discarded", 0.70, "baseline engagement"),+ ("kept", 0.82, "added file RFM"),+ ]+ assert run["iterations"][0]["model_spec"]["model_class"] == "sklearn.linear_model.LogisticRegression"+ assert run["iterations"][1]["recipe_snapshot"]["feature_sql"] == VALID_FEATURE_SQL++ def test_history_excludes_runs_that_are_not_completed(self):+ # An open (running) run with a recorded iteration must not surface as history.+ runs_url = self._runs_url(self.pipeline)+ run_id = self.client.post(f"{runs_url}/", {}, format="json").json()["id"]+ self.client.post(+ f"{runs_url}/{run_id}/iterations/",+ {+ "iteration_number": 0,+ "recipe_snapshot": VALID_RECIPE,+ "model_spec": VALID_SPEC,+ "status": "kept",+ "holdout_score": 0.8,+ "agent_description": "in progress",+ },+ format="json",+ )+ resp = self._history()+ assert resp.json()["runs"] == []++ def test_history_includes_same_target_sibling_flagged_not_current(self):+ sibling = AutoresearchPipeline.objects.create(+ team=self.team, created_by=self.user, name="Sibling", target_event="downloaded_file", horizon_days=30+ )+ other_target = AutoresearchPipeline.objects.create(+ team=self.team, created_by=self.user, name="OtherTarget", target_event="$pageview", horizon_days=30+ )+ # An action whose name matches the event is a different outcome, not a sibling.+ same_name_action = AutoresearchPipeline.objects.create(+ team=self.team,+ created_by=self.user,+ name="SameNameAction",+ target_event="downloaded_file",+ target_definition={"type": "action", "action_id": 42},+ horizon_days=30,+ )+ self._completed_run(sibling, iterations=[("kept", 0.75, "sibling run")])+ self._completed_run(other_target, iterations=[("kept", 0.90, "different target")])+ self._completed_run(same_name_action, iterations=[("kept", 0.91, "same-name action")])+ self._completed_run(self.pipeline, iterations=[("kept", 0.80, "own run")])++ runs = self._history().json()["runs"]+ by_target_desc = {r["iterations"][0]["agent_description"]: r for r in runs}+ # Own run + same-target sibling appear; the different-target pipeline does not.+ assert set(by_target_desc) == {"own run", "sibling run"}+ assert by_target_desc["own run"]["is_current_pipeline"] is True+ assert by_target_desc["sibling run"]["is_current_pipeline"] is False+ # Current pipeline is listed first.+ assert runs[0]["iterations"][0]["agent_description"] == "own run"++ def test_history_respects_limit(self):+ for _ in range(3):+ self._completed_run(self.pipeline, iterations=[("kept", 0.8, "run")])+ # An undated completed run sorts after the dated ones instead of taking the first slot.+ undated = AutoresearchTrainingRun.objects.create(+ pipeline=self.pipeline, status=AutoresearchTrainingRun.Status.COMPLETED, completed_at=None+ )+ assert [r["run_id"] for r in self._history(limit=4).json()["runs"]][-1] == str(undated.id)+ assert len(self._history(limit=2).json()["runs"]) == 2+ assert self._history(limit=0).status_code == status.HTTP_400_BAD_REQUEST+ assert self._history(limit="many").status_code == status.HTTP_400_BAD_REQUEST++ def test_history_includes_distilled_run_summary(self):+ self._completed_run(+ self.pipeline,+ iterations=[("discarded", 0.70, "baseline"), ("kept", 0.82, "winner")],+ distillation="log1p of file counts is the signal",+ recommended_next="try session-recency features",+ )+ summary = self._history().json()["runs"][0]["summary"]+ assert summary["distillation"] == "log1p of file counts is the signal"+ assert summary["recommended_next"] == "try session-recency features"+ assert summary["target_event"] == "downloaded_file"+ assert summary["best_holdout_score"] == 0.82+ assert summary["champion_promoted"] is True+ assert [it["iteration_number"] for it in summary["kept_ladder"]] == [1]+ assert [it["iteration_number"] for it in summary["dead_ends"]] == [0]++ def test_history_excludes_other_teams(self):+ other_org = Organization.objects.create(name="Other")+ other_team = Team.objects.create(organization=other_org, name="Other team")+ other_pipeline = AutoresearchPipeline.objects.create(+ team=other_team, created_by=self.user, name="Other", target_event="downloaded_file", horizon_days=30+ )+ # Build a completed run on the other team directly (its API is on a different project route).+ other_run = AutoresearchTrainingRun.objects.create(+ pipeline=other_pipeline, status=AutoresearchTrainingRun.Status.COMPLETED, best_holdout_score=0.99+ )+ AutoresearchIteration.objects.create(+ pipeline=other_pipeline,+ training_run=other_run,+ iteration_number=0,+ recipe_hash="x",+ recipe_snapshot=VALID_RECIPE,+ model_spec=VALID_SPEC,+ holdout_score=0.99,+ status="kept",+ agent_description="leaked",+ )+ self._completed_run(self.pipeline, iterations=[("kept", 0.8, "own")])+ runs = self._history().json()["runs"]+ assert all(r["iterations"][0]["agent_description"] != "leaked" for r in runs)+++class TestAgentWriteSerializers(SimpleTestCase):+ @parameterized.expand(+ [+ ("nan_holdout", {"holdout_score": "NaN"}, "holdout_score"),+ ("infinite_train_score", {"train_score": "Infinity"}, "train_score"),+ ("nan_confidence", {"agent_confidence": "nan"}, "agent_confidence"),+ ("iteration_number_past_int32", {"iteration_number": 2**31}, "iteration_number"),+ ("list_shaped_recipe", {"recipe_snapshot": [VALID_FEATURE_SQL]}, "recipe_snapshot"),+ ("string_shaped_spec", {"model_spec": "sklearn.linear_model.LogisticRegression"}, "model_spec"),+ ("non_string_feature_sql", {"recipe_snapshot": {"feature_sql": 123}}, "non_field_errors"),+ (+ "oversized_rationale",+ {"agent_description": "x" * (AGENT_DESCRIPTION_MAX_LENGTH + 1)},+ "agent_description",+ ),+ ("nested_nan_in_spec", {"model_spec": {**VALID_SPEC, "model_params": {"C": float("nan")}}}, "model_spec"),+ ("lone_surrogate_in_recipe", {"recipe_snapshot": {**VALID_RECIPE, "note": "\ud800"}}, "recipe_snapshot"),+ ("boolean_holdout", {"holdout_score": True}, "holdout_score"),+ ("integer_past_float_range", {"holdout_score": 10**400}, "holdout_score"),+ ("string_model_params", {"model_spec": {**VALID_SPEC, "model_params": "bad"}}, "non_field_errors"),+ ("oversized_spec", {"model_spec": {**VALID_SPEC, "pad": "x" * MODEL_SPEC_MAX_BYTES}}, "model_spec"),+ (+ "string_transforms",+ {"recipe_snapshot": {**VALID_RECIPE, "feature_transforms": "bad"}},+ "non_field_errors",+ ),+ ("nul_in_recipe", {"recipe_snapshot": {**VALID_RECIPE, "note": "a\x00b"}}, "recipe_snapshot"),+ (+ "oversized_recipe",+ {"recipe_snapshot": {**VALID_RECIPE, "pad": "x" * OBJECT_JSON_MAX_BYTES}},+ "recipe_snapshot",+ ),+ ]+ )+ def test_record_iteration_rejects(self, _name: str, overrides: dict[str, Any], error_key: str) -> None:+ data = {+ "iteration_number": 0,+ "recipe_snapshot": VALID_RECIPE,+ "model_spec": VALID_SPEC,+ "status": "kept",+ "holdout_score": 0.8,+ **overrides,+ }+ serializer = RecordIterationSerializer(data=data)+ assert not serializer.is_valid()+ assert error_key in serializer.errors, serializer.errors++ def test_complete_rejects_a_non_object_explanation(self) -> None:+ serializer = CompleteTrainingRunSerializer(data={"model_explanation": ["top_features"]})+ assert not serializer.is_valid()+ assert "model_explanation" in serializer.errors+++class _InMemoryStorage:+ """In-memory object_storage stand-in for bundle round-trips in tests."""++ def __init__(self) -> None:+ self.store: dict[str, bytes] = {}++ def write(self, key, content, extras=None, bucket=None) -> None:+ self.store[key] = content if isinstance(content, bytes) else content.encode("utf-8")++ def read_bytes(self, key, bucket=None, *, missing_ok: bool = False):+ if key in self.store:+ return self.store[key]+ if missing_ok:+ return None+ raise FileNotFoundError(key)++ def delete(self, key, bucket=None) -> None:+ self.store.pop(key, None)++ def list_objects(self, prefix):+ keys = [k for k in self.store if k.startswith(prefix)]+ return keys or Nonediff --git a/products/autoresearch/backend/training/test_promotion.py b/products/autoresearch/backend/training/test_promotion.pyindex ed41542d0733..ba1ac098b1d2 100644--- a/products/autoresearch/backend/training/test_promotion.py+++ b/products/autoresearch/backend/training/test_promotion.py@@ -22,6 +22,7 @@ from products.autoresearch.backend.training.artifacts import ArtifactBundle, Invfrom products.autoresearch.backend.training.promotion import PromotionError, complete_training_runANCHORED_FEATURE_SQL = "SELECT a.person_id AS distinct_id, count() AS c FROM {anchors} a GROUP BY a.person_id"+_DEFAULT_PARAMS = object()LITERAL_FEATURE_SQL = ("SELECT a.person_id AS distinct_id, count() AS c, 'plan upgraded' AS marker FROM {anchors} a GROUP BY a.person_id")@@ -56,15 +57,23 @@ class TestCompleteTrainingRun(TeamScopedTestMixin, BaseTest):status: str = AutoresearchIteration.Status.KEPT,holdout: float | None = 0.8,feature_sql: str = ANCHORED_FEATURE_SQL,+ feature_transforms: list[dict[str, str]] | None = None,model_class: str = "sklearn.linear_model.LogisticRegression",+ model_params: object = _DEFAULT_PARAMS,) -> AutoresearchIteration:+ recipe_snapshot: dict[str, object] = {"feature_sql": feature_sql} if feature_sql else {}+ if feature_transforms:+ recipe_snapshot["feature_transforms"] = feature_transformsreturn AutoresearchIteration.objects.create(pipeline=self.pipeline,training_run=run,iteration_number=number,recipe_hash=f"hash{number}",- recipe_snapshot={"feature_sql": feature_sql} if feature_sql else {},- model_spec={"model_class": model_class, "model_params": {}},+ recipe_snapshot=recipe_snapshot,+ model_spec={+ "model_class": model_class,+ "model_params": {} if model_params is _DEFAULT_PARAMS else model_params,+ },holdout_score=holdout,status=status,agent_description=f"iteration {number}",@@ -184,6 +193,14 @@ class TestCompleteTrainingRun(TeamScopedTestMixin, BaseTest):# in-process scorer resolves the class through importlib and refuses anything# off the allowlist, so this champion could never score.("bundle_only_model_class", {"model_class": "my_package.MyClassifier"}),+ # The in-process scorer fits on the raw columns, so a recipe whose holdout score+ # was measured on transformed features would serve a different model.+ ("feature_transforms", {"feature_transforms": [{"column": "c", "transform": "log1p"}]}),+ ("string_model_params", {"model_params": "bad"}),+ ("trailing_limit", {"feature_sql": ANCHORED_FEATURE_SQL + " LIMIT 10"}),+ # sklearn refuses an unknown keyword only in the constructor, which inference would hit on+ # every cadence.+ ("unknown_model_param", {"model_params": {"unexpected": 1}}),])def test_recipe_the_legacy_scorer_cannot_run_is_refused(self, _name, iteration_kwargs):@@ -197,6 +214,26 @@ class TestCompleteTrainingRun(TeamScopedTestMixin, BaseTest):assert run.status == AutoresearchTrainingRun.Status.RUNNINGassert not AutoresearchModel.objects.filter(pipeline=self.pipeline).exists()+ def test_overridden_nomination_drops_its_explanation(self):+ run = self._run()+ self._iteration(run, number=0, holdout=0.9)+ weaker = self._iteration(run, number=1, holdout=0.7)++ complete_training_run(run, best_iteration_id=weaker.id, model_explanation={"top_features": ["c"]})++ champion = self._champion()+ assert champion.source_training_run_id == run.id+ assert champion.model_explanation == {}++ def test_null_model_params_promote_with_constructor_defaults(self):+ run = self._run()+ self._iteration(run, number=0, holdout=0.8, model_params=None)++ result = complete_training_run(run)++ assert result["promoted"] is True+ assert self._champion().model_recipe["model_params"] == {}+def test_bundle_matching_the_selected_iteration_completes(self):run = self._run()self._iteration(run, number=0, holdout=0.8)diff --git a/products/autoresearch/backend/training/test_recipe_validation.py b/products/autoresearch/backend/training/test_recipe_validation.pyindex 67af2ff795e1..04d9f52d970b 100644--- a/products/autoresearch/backend/training/test_recipe_validation.py+++ b/products/autoresearch/backend/training/test_recipe_validation.py@@ -187,6 +187,9 @@ class TestRecipeValidation(SimpleTestCase):("feature_sql_missing", {"model_class": "m"}, {}),("feature_sql_not_a_string", {"model_class": "m"}, {"feature_sql": 1}),("feature_sql_blank", {"model_class": "m"}, {"feature_sql": " "}),+ ("model_params_not_an_object", {"model_class": "m", "model_params": "bad"}, {"feature_sql": ANCHORED}),+ ("transforms_not_a_list", {"model_class": "m"}, {"feature_sql": ANCHORED, "feature_transforms": "bad"}),+ ("transform_not_an_object", {"model_class": "m"}, {"feature_sql": ANCHORED, "feature_transforms": [1]}),])def test_validate_recipe_rejects_malformed_agent_input(self, _name, model_spec, recipe_snapshot):diff --git a/products/autoresearch/backend/training/test_training_ingestion.py b/products/autoresearch/backend/training/test_training_ingestion.pyindex 4e29c274b0a7..a512660f5eaf 100644--- a/products/autoresearch/backend/training/test_training_ingestion.py+++ b/products/autoresearch/backend/training/test_training_ingestion.py@@ -64,7 +64,9 @@ class TestHandleTaskRunCompleted(TeamScopedTestMixin, BaseTest):pipeline=training_run.pipeline,iteration_number=number,recipe_hash=f"hash{number}",- recipe_snapshot={"feature_sql": "SELECT person_id AS distinct_id FROM events"},+ recipe_snapshot={+ "feature_sql": "SELECT a.person_id AS distinct_id, count() AS c FROM {anchors} a GROUP BY a.person_id"+ },model_spec={"model_class": "sklearn.linear_model.LogisticRegression", "model_params": {}},holdout_score=holdout,status=status,diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.tsindex b2be0cbfc334..261ae3db6ff9 100644--- a/products/autoresearch/frontend/generated/api.schemas.ts+++ b/products/autoresearch/frontend/generated/api.schemas.ts@@ -551,6 +551,25 @@ export const AutoresearchIterationStatusEnumApi = {Crashed: 'crashed',} as const+/**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+export type IterationTrailApiModelSpecModelParams = { [key: string]: unknown } | null++/**+ * Model class and hyperparameters tried in this iteration.+ */+export type IterationTrailApiModelSpec = {+ /** Dotted path of the estimator class. */+ model_class: string+ /**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+ model_params?: IterationTrailApiModelSpecModelParams+}+/*** Compact, read-only view of one iteration for the cross-run history feed and the Training tab.*/@@ -580,7 +599,7 @@ export interface IterationTrailApi {/** 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+ model_spec: IterationTrailApiModelSpec}export interface AutoresearchTrainingRunApi {@@ -651,6 +670,323 @@ export interface PaginatedAutoresearchTrainingRunListApi {results: AutoresearchTrainingRunApi[]}+/**+ * Input for opening an agent-driven training run.+ */+export interface OpenTrainingRunApi {+ /**+ * Iteration budget for this run. Defaults to the pipeline's iteration_budget if omitted.+ * @minimum 1+ * @maximum 500+ */+ iteration_budget?: number+}++/**+ * Global feature importance / directionality bundle for the champion model card.+ */+export type CompleteTrainingRunApiModelExplanation = { [key: string]: unknown }++/**+ * Input for finalizing a training run. The backend selects/promotes the champion.+ */+export interface CompleteTrainingRunApi {+ /**+ * Advisory nomination. The server promotes the kept iteration with the highest holdout_score; this id only breaks a tie at that score, and a lower-scoring nomination is logged and ignored.+ * @nullable+ */+ best_iteration_id?: string | null+ /** Global feature importance / directionality bundle for the champion model card. */+ model_explanation?: CompleteTrainingRunApiModelExplanation+ /**+ * What a future run should try next, given what this run learned. Stored in the run summary so the next run reads it during orientation. Keep it short and concrete; max 2000 characters.+ * @maxLength 2000+ */+ recommended_next?: string+ /**+ * A 1–2 sentence distillation of what this run learned — the winning signal, the key transform, the dead-ends. Stored in the run summary as the cheapest thing the next run reads. Max 2000 characters.+ * @maxLength 2000+ */+ distillation?: string+}++export type RecordIterationApiRecipeSnapshotFeatureTransformsItem = { [key: string]: unknown }++/**+ * Compact recipe for this iteration: feature_sql (HogQL SELECT keyed on person_id) and transforms.+ */+export type RecordIterationApiRecipeSnapshot = {+ /** A read-only HogQL SELECT from {anchors}, one row per person, keyed on person_id. */+ feature_sql: string+ /**+ * Transforms the bundle applies to the feature columns; null or absent means none, and the in-process path accepts none.+ * @nullable+ */+ feature_transforms?: RecordIterationApiRecipeSnapshotFeatureTransformsItem[] | null+}++/**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+export type RecordIterationApiModelSpecModelParams = { [key: string]: unknown } | null++/**+ * model_class and model_params tried this iteration. Any class is accepted here; the sklearn/xgboost allowlist applies at completion, to a run that uploaded no bundle.+ */+export type RecordIterationApiModelSpec = {+ /** Dotted path of the estimator class. */+ model_class: string+ /**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+ model_params?: RecordIterationApiModelSpecModelParams+}++/**+ * * `kept` - kept+ * * `discarded` - discarded+ * * `crashed` - crashed+ */+export type RecordIterationStatusEnumApi =+ (typeof RecordIterationStatusEnumApi)[keyof typeof RecordIterationStatusEnumApi]++export const RecordIterationStatusEnumApi = {+ Kept: 'kept',+ Discarded: 'discarded',+ Crashed: 'crashed',+} as const++/**+ * Input for recording one training iteration. Validated against the recipe allowlist.+ */+export interface RecordIterationApi {+ /**+ * Zero-based index of this iteration within the run. Re-sending the same number updates that iteration (idempotent).+ * @minimum 0+ * @maximum 2147483647+ */+ iteration_number: number+ /** Compact recipe for this iteration: feature_sql (HogQL SELECT keyed on person_id) and transforms. */+ recipe_snapshot: RecordIterationApiRecipeSnapshot+ /** model_class and model_params tried this iteration. Any class is accepted here; the sklearn/xgboost allowlist applies at completion, to a run that uploaded no bundle. */+ model_spec: RecordIterationApiModelSpec+ /** 'kept' if this iteration improved on the best score, 'discarded' otherwise, 'crashed' on failure.+ *+ * * `kept` - kept+ * * `discarded` - discarded+ * * `crashed` - crashed */+ status: RecordIterationStatusEnumApi+ /**+ * Training-set AUC for this iteration (0-1).+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ train_score?: number | null+ /**+ * Held-out AUC for this iteration (0-1). Used to pick the champion at completion.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ holdout_score?: number | null+ /**+ * Agent's plain-English rationale for this iteration. Max 2000 characters.+ * @maxLength 2000+ */+ agent_description?: string+ /**+ * Agent's self-assessed confidence (0-1) that this iteration helps.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ agent_confidence?: number | null+ /**+ * UUID of the steering suggestion this iteration was spawned from, if any. Set it whenever the iteration acts on a pending suggestion — it links the iteration back to the suggestion for attribution and advances the suggestion to 'acted_on'.+ * @nullable+ */+ parent_suggestion?: string | null+}++export type AutoresearchIterationApiRecipeSnapshotFeatureTransformsItem = { [key: string]: unknown }++/**+ * Compact recipe snapshot at time of iteration. Full artifact lives in the model row.+ */+export type AutoresearchIterationApiRecipeSnapshot = {+ /** A read-only HogQL SELECT from {anchors}, one row per person, keyed on person_id. */+ feature_sql: string+ /**+ * Transforms the bundle applies to the feature columns; null or absent means none, and the in-process path accepts none.+ * @nullable+ */+ feature_transforms?: AutoresearchIterationApiRecipeSnapshotFeatureTransformsItem[] | null+}++/**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+export type AutoresearchIterationApiModelSpecModelParams = { [key: string]: unknown } | null++/**+ * Model class and hyperparameters tried in this iteration.+ */+export type AutoresearchIterationApiModelSpec = {+ /** Dotted path of the estimator class. */+ model_class: string+ /**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+ model_params?: AutoresearchIterationApiModelSpecModelParams+}++export interface AutoresearchIterationApi {+ readonly id: string+ pipeline: string+ training_run: string+ /**+ * @minimum -2147483648+ * @maximum 2147483647+ */+ iteration_number: number+ /** @maxLength 64 */+ recipe_hash: string+ /** Compact recipe snapshot at time of iteration. Full artifact lives in the model row. */+ recipe_snapshot: AutoresearchIterationApiRecipeSnapshot+ /** Model class and hyperparameters tried in this iteration. */+ model_spec: AutoresearchIterationApiModelSpec+ /** @nullable */+ train_score?: number | null+ /** @nullable */+ holdout_score?: number | null+ status: AutoresearchIterationStatusEnumApi+ agent_description?: string+ /**+ * Agent's self-assessed confidence 0–1+ * @nullable+ */+ agent_confidence?: number | null+ /**+ * UUID of the steering suggestion this iteration was spawned from, if any.+ * @nullable+ */+ parent_suggestion?: string | null+ readonly created_at: string+}++/**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+export type IterationTrailWithRecipeApiModelSpecModelParams = { [key: string]: unknown } | null++/**+ * Model class and hyperparameters tried in this iteration.+ */+export type IterationTrailWithRecipeApiModelSpec = {+ /** Dotted path of the estimator class. */+ model_class: string+ /**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+ model_params?: IterationTrailWithRecipeApiModelSpecModelParams+}++export type IterationTrailWithRecipeApiRecipeSnapshotFeatureTransformsItem = { [key: string]: unknown }++/**+ * The recipe this iteration tried: its feature_sql and transforms, so a later run can reuse them.+ */+export type IterationTrailWithRecipeApiRecipeSnapshot = {+ /** A read-only HogQL SELECT from {anchors}, one row per person, keyed on person_id. */+ feature_sql: string+ /**+ * Transforms the bundle applies to the feature columns; null or absent means none, and the in-process path accepts none.+ * @nullable+ */+ feature_transforms?: IterationTrailWithRecipeApiRecipeSnapshotFeatureTransformsItem[] | null+}++/**+ * The trail with each iteration's recipe, for history only: a run list page would otherwise carry every recipe of every run.+ */+export interface IterationTrailWithRecipeApi {+ /**+ * 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: IterationTrailWithRecipeApiModelSpec+ /** The recipe this iteration tried: its feature_sql and transforms, so a later run can reuse them. */+ recipe_snapshot: IterationTrailWithRecipeApiRecipeSnapshot+}++/**+ * One prior completed training run plus its full iteration trail.+ */+export interface TrainingRunHistoryEntryApi {+ /** UUID of the completed training run. */+ run_id: string+ /** UUID of the pipeline this run belongs to. */+ pipeline_id: string+ /** True if this run is from the pipeline you are training; False if it is a same-target sibling pipeline on the team. */+ is_current_pipeline: boolean+ /** Target event this run's pipeline predicts. */+ target_event: string+ /** Prediction horizon (days) of this run's pipeline. */+ horizon_days: number+ /**+ * Best holdout AUC achieved across this run's iterations.+ * @nullable+ */+ best_holdout_score: number | null+ /** Number of iterations recorded in this run. */+ iteration_count: number+ /**+ * When this run completed.+ * @nullable+ */+ completed_at: string | null+ /** Distilled tier-1 summary of this run — read this first to orient. Null for older runs without one. */+ summary: TrainingRunSummaryApi | null+ /** The iteration trail: every recipe tried, kept or discarded, with rationale and score. */+ iterations: IterationTrailWithRecipeApi[]+}++/**+ * Cross-run learning memory: prior runs the agent should read before iterating.+ */+export interface TrainingRunHistoryApi {+ /** Recent completed training runs — the current pipeline first, then same-target sibling pipelines on the team — newest first. Mine these to reuse winning features and avoid repeating discarded approaches. */+ runs: TrainingRunHistoryEntryApi[]+}+/*** 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.*/@@ -1005,3 +1341,12 @@ export type AutoresearchTrainingRunsListParams = {*/offset?: number}++export type AutoresearchTrainingRunsHistoryRetrieveParams = {+ /**+ * Maximum number of prior runs to return (default 5, at most 20).+ * @minimum 1+ * @maximum 20+ */+ limit?: number+}diff --git a/products/autoresearch/frontend/generated/api.ts b/products/autoresearch/frontend/generated/api.tsindex 742dd79fe3df..11722557d192 100644--- a/products/autoresearch/frontend/generated/api.ts+++ b/products/autoresearch/frontend/generated/api.ts@@ -9,6 +9,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ AutoresearchIterationApi,AutoresearchListParams,AutoresearchModelApi,AutoresearchModelsListParams,@@ -17,15 +18,20 @@ import type {AutoresearchRunApi,AutoresearchRunsListParams,AutoresearchTrainingRunApi,+ AutoresearchTrainingRunsHistoryRetrieveParams,AutoresearchTrainingRunsListParams,+ CompleteTrainingRunApi,+ OpenTrainingRunApi,PaginatedAutoresearchModelListApi,PaginatedAutoresearchPipelineListApi,PaginatedAutoresearchRunListApi,PaginatedAutoresearchTrainingRunListApi,PatchedAutoresearchPipelineCreateApi,+ RecordIterationApi,ResolveTemplateRequestApi,ResolvedTemplateApi,TemplateInfoApi,+ TrainingRunHistoryApi,ValidatePipelineRequestApi,ValidatePipelineResponseApi,} from './api.schemas'@@ -245,6 +251,28 @@ export const autoresearchTrainingRunsList = async ()}+export const getAutoresearchTrainingRunsCreateUrl = (projectId: string, pipelineId: string) => {+ return `/api/projects/${projectId}/autoresearch/${pipelineId}/training_runs/`+}++/**+ * Open a new training run for a pipeline and return its id. An agent — the in-house sandbox, an external bring-your-own agent, or a scheduled job — then records iterations against this run and finalizes it with the complete endpoint. The run starts in 'running'.+ * @summary Open a training run+ */+export const autoresearchTrainingRunsCreate = async (+ projectId: string,+ pipelineId: string,+ openTrainingRunApi?: OpenTrainingRunApi,+ options?: RequestInit+): Promise<AutoresearchTrainingRunApi> => {+ return apiMutator<AutoresearchTrainingRunApi>(getAutoresearchTrainingRunsCreateUrl(projectId, pipelineId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(openTrainingRunApi),+ })+}+export const getAutoresearchTrainingRunsRetrieveUrl = (projectId: string, pipelineId: string, id: string) => {return `/api/projects/${projectId}/autoresearch/${pipelineId}/training_runs/${id}/`}@@ -267,6 +295,97 @@ export const autoresearchTrainingRunsRetrieve = async (})}+export const getAutoresearchTrainingRunsCompleteCreateUrl = (projectId: string, pipelineId: string, id: string) => {+ return `/api/projects/${projectId}/autoresearch/${pipelineId}/training_runs/${id}/complete/`+}++/**+ * Finalize a training run. The backend selects the kept iteration with the highest holdout score, decides champion vs challenger via the promotion ladder, and persists the model. best_iteration_id is advisory: it breaks a tie at the top score and is otherwise logged and ignored. Agents cannot set the champion directly, because promotion is server-side.+ * @summary Complete a training run+ */+export const autoresearchTrainingRunsCompleteCreate = async (+ projectId: string,+ pipelineId: string,+ id: string,+ completeTrainingRunApi?: CompleteTrainingRunApi,+ options?: RequestInit+): Promise<AutoresearchTrainingRunApi> => {+ return apiMutator<AutoresearchTrainingRunApi>(+ getAutoresearchTrainingRunsCompleteCreateUrl(projectId, pipelineId, id),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(completeTrainingRunApi),+ }+ )+}++export const getAutoresearchTrainingRunsIterationsCreateUrl = (projectId: string, pipelineId: string, id: string) => {+ return `/api/projects/${projectId}/autoresearch/${pipelineId}/training_runs/${id}/iterations/`+}++/**+ * Record one iteration of an open training run. Idempotent on iteration_number: re-sending the same number updates that iteration. A new iteration_number is refused once the run's iteration_budget is used. The recipe is validated server-side: feature_sql must be a read-only SELECT from {anchors} keyed on person_id, and model_class must be set. The class allowlist applies only at completion, to a run that uploaded no bundle.+ * @summary Record a training iteration+ */+export const autoresearchTrainingRunsIterationsCreate = async (+ projectId: string,+ pipelineId: string,+ id: string,+ recordIterationApi: RecordIterationApi,+ options?: RequestInit+): Promise<AutoresearchIterationApi> => {+ return apiMutator<AutoresearchIterationApi>(+ getAutoresearchTrainingRunsIterationsCreateUrl(projectId, pipelineId, id),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(recordIterationApi),+ }+ )+}++export const getAutoresearchTrainingRunsHistoryRetrieveUrl = (+ projectId: string,+ pipelineId: string,+ params?: AutoresearchTrainingRunsHistoryRetrieveParams+) => {+ 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/history/?${stringifiedParams}`+ : `/api/projects/${projectId}/autoresearch/${pipelineId}/training_runs/history/`+}++/**+ * Return recent completed training runs and their iteration trails so a new run can learn from what was already tried. Scoped to this pipeline first, then same-target sibling pipelines on the team. Read this before iterating to reuse winning features and avoid repeating discarded approaches.+ * @summary Read prior training-run history+ */+export const autoresearchTrainingRunsHistoryRetrieve = async (+ projectId: string,+ pipelineId: string,+ params?: AutoresearchTrainingRunsHistoryRetrieveParams,+ options?: RequestInit+): Promise<TrainingRunHistoryApi> => {+ return apiMutator<TrainingRunHistoryApi>(+ getAutoresearchTrainingRunsHistoryRetrieveUrl(projectId, pipelineId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getAutoresearchRetrieveUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/autoresearch/${id}/`}diff --git a/products/autoresearch/frontend/generated/api.zod.ts b/products/autoresearch/frontend/generated/api.zod.tsindex e74410ed3d80..cae263588a65 100644--- a/products/autoresearch/frontend/generated/api.zod.ts+++ b/products/autoresearch/frontend/generated/api.zod.ts@@ -121,6 +121,154 @@ export const AutoresearchCreateBody = /* @__PURE__ */ zod.object({),})+/**+ * Open a new training run for a pipeline and return its id. An agent — the in-house sandbox, an external bring-your-own agent, or a scheduled job — then records iterations against this run and finalizes it with the complete endpoint. The run starts in 'running'.+ * @summary Open a training run+ */+export const autoresearchTrainingRunsCreateBodyIterationBudgetMax = 500++export const AutoresearchTrainingRunsCreateBody = /* @__PURE__ */ zod+ .object({+ iteration_budget: zod+ .number()+ .min(1)+ .max(autoresearchTrainingRunsCreateBodyIterationBudgetMax)+ .optional()+ .describe("Iteration budget for this run. Defaults to the pipeline's iteration_budget if omitted."),+ })+ .describe('Input for opening an agent-driven training run.')++/**+ * Finalize a training run. The backend selects the kept iteration with the highest holdout score, decides champion vs challenger via the promotion ladder, and persists the model. best_iteration_id is advisory: it breaks a tie at the top score and is otherwise logged and ignored. Agents cannot set the champion directly, because promotion is server-side.+ * @summary Complete a training run+ */+export const autoresearchTrainingRunsCompleteCreateBodyRecommendedNextDefault = ``+export const autoresearchTrainingRunsCompleteCreateBodyRecommendedNextMax = 2000++export const autoresearchTrainingRunsCompleteCreateBodyDistillationDefault = ``+export const autoresearchTrainingRunsCompleteCreateBodyDistillationMax = 2000++export const AutoresearchTrainingRunsCompleteCreateBody = /* @__PURE__ */ zod+ .object({+ best_iteration_id: zod+ .uuid()+ .nullish()+ .describe(+ 'Advisory nomination. The server promotes the kept iteration with the highest holdout_score; this id only breaks a tie at that score, and a lower-scoring nomination is logged and ignored.'+ ),+ model_explanation: zod+ .looseObject({})+ .optional()+ .describe('Global feature importance \/ directionality bundle for the champion model card.'),+ recommended_next: zod+ .string()+ .max(autoresearchTrainingRunsCompleteCreateBodyRecommendedNextMax)+ .default(autoresearchTrainingRunsCompleteCreateBodyRecommendedNextDefault)+ .describe(+ 'What a future run should try next, given what this run learned. Stored in the run summary so the next run reads it during orientation. Keep it short and concrete; max 2000 characters.'+ ),+ distillation: zod+ .string()+ .max(autoresearchTrainingRunsCompleteCreateBodyDistillationMax)+ .default(autoresearchTrainingRunsCompleteCreateBodyDistillationDefault)+ .describe(+ 'A 1–2 sentence distillation of what this run learned — the winning signal, the key transform, the dead-ends. Stored in the run summary as the cheapest thing the next run reads. Max 2000 characters.'+ ),+ })+ .describe('Input for finalizing a training run. The backend selects\/promotes the champion.')++/**+ * Record one iteration of an open training run. Idempotent on iteration_number: re-sending the same number updates that iteration. A new iteration_number is refused once the run's iteration_budget is used. The recipe is validated server-side: feature_sql must be a read-only SELECT from {anchors} keyed on person_id, and model_class must be set. The class allowlist applies only at completion, to a run that uploaded no bundle.+ * @summary Record a training iteration+ */+export const autoresearchTrainingRunsIterationsCreateBodyIterationNumberMin = 0+export const autoresearchTrainingRunsIterationsCreateBodyIterationNumberMax = 2147483647++export const autoresearchTrainingRunsIterationsCreateBodyTrainScoreMin = 0+export const autoresearchTrainingRunsIterationsCreateBodyTrainScoreMax = 1++export const autoresearchTrainingRunsIterationsCreateBodyHoldoutScoreMin = 0+export const autoresearchTrainingRunsIterationsCreateBodyHoldoutScoreMax = 1++export const autoresearchTrainingRunsIterationsCreateBodyAgentDescriptionDefault = ``+export const autoresearchTrainingRunsIterationsCreateBodyAgentDescriptionMax = 2000++export const autoresearchTrainingRunsIterationsCreateBodyAgentConfidenceMin = 0+export const autoresearchTrainingRunsIterationsCreateBodyAgentConfidenceMax = 1++export const AutoresearchTrainingRunsIterationsCreateBody = /* @__PURE__ */ zod+ .object({+ iteration_number: zod+ .number()+ .min(autoresearchTrainingRunsIterationsCreateBodyIterationNumberMin)+ .max(autoresearchTrainingRunsIterationsCreateBodyIterationNumberMax)+ .describe(+ 'Zero-based index of this iteration within the run. Re-sending the same number updates that iteration (idempotent).'+ ),+ recipe_snapshot: zod+ .object({+ feature_sql: zod+ .string()+ .describe('A read-only HogQL SELECT from {anchors}, one row per person, keyed on person_id.'),+ feature_transforms: zod+ .array(zod.looseObject({}))+ .nullish()+ .describe(+ 'Transforms the bundle applies to the feature columns; null or absent means none, and the in-process path accepts none.'+ ),+ })+ .describe(+ 'Compact recipe for this iteration: feature_sql (HogQL SELECT keyed on person_id) and transforms.'+ ),+ model_spec: zod+ .object({+ model_class: zod.string().describe('Dotted path of the estimator class.'),+ model_params: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe("Keyword arguments for the estimator's constructor; null or absent means the defaults."),+ })+ .describe(+ 'model_class and model_params tried this iteration. Any class is accepted here; the sklearn\/xgboost allowlist applies at completion, to a run that uploaded no bundle.'+ ),+ status: zod+ .enum(['kept', 'discarded', 'crashed'])+ .describe('\* `kept` - kept\n\* `discarded` - discarded\n\* `crashed` - crashed')+ .describe(+ "'kept' if this iteration improved on the best score, 'discarded' otherwise, 'crashed' on failure.\n\n\* `kept` - kept\n\* `discarded` - discarded\n\* `crashed` - crashed"+ ),+ train_score: zod+ .number()+ .min(autoresearchTrainingRunsIterationsCreateBodyTrainScoreMin)+ .max(autoresearchTrainingRunsIterationsCreateBodyTrainScoreMax)+ .nullish()+ .describe('Training-set AUC for this iteration (0-1).'),+ holdout_score: zod+ .number()+ .min(autoresearchTrainingRunsIterationsCreateBodyHoldoutScoreMin)+ .max(autoresearchTrainingRunsIterationsCreateBodyHoldoutScoreMax)+ .nullish()+ .describe('Held-out AUC for this iteration (0-1). Used to pick the champion at completion.'),+ agent_description: zod+ .string()+ .max(autoresearchTrainingRunsIterationsCreateBodyAgentDescriptionMax)+ .default(autoresearchTrainingRunsIterationsCreateBodyAgentDescriptionDefault)+ .describe("Agent's plain-English rationale for this iteration. Max 2000 characters."),+ agent_confidence: zod+ .number()+ .min(autoresearchTrainingRunsIterationsCreateBodyAgentConfidenceMin)+ .max(autoresearchTrainingRunsIterationsCreateBodyAgentConfidenceMax)+ .nullish()+ .describe("Agent's self-assessed confidence (0-1) that this iteration helps."),+ parent_suggestion: zod+ .uuid()+ .nullish()+ .describe(+ "UUID of the steering suggestion this iteration was spawned from, if any. Set it whenever the iteration acts on a pending suggestion — it links the iteration back to the suggestion for attribution and advances the suggestion to 'acted_on'."+ ),+ })+ .describe('Input for recording one training iteration. Validated against the recipe allowlist.')+/*** Manage autoresearch prediction pipelines.*diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex bc8df55fb4be..30456ca9738a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -11371,6 +11371,40 @@ export namespace Schemas {P4: 'P4',} as const;+ export type AutoresearchIterationRecipeSnapshotFeatureTransformsItem = { [key: string]: unknown };++ /**+ * Compact recipe snapshot at time of iteration. Full artifact lives in the model row.+ */+ export type AutoresearchIterationRecipeSnapshot = {+ /** A read-only HogQL SELECT from {anchors}, one row per person, keyed on person_id. */+ feature_sql: string;+ /**+ * Transforms the bundle applies to the feature columns; null or absent means none, and the in-process path accepts none.+ * @nullable+ */+ feature_transforms?: AutoresearchIterationRecipeSnapshotFeatureTransformsItem[] | null;+ };++ /**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+ export type AutoresearchIterationModelSpecModelParams = { [key: string]: unknown } | null;++ /**+ * Model class and hyperparameters tried in this iteration.+ */+ export type AutoresearchIterationModelSpec = {+ /** Dotted path of the estimator class. */+ model_class: string;+ /**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+ model_params?: AutoresearchIterationModelSpecModelParams;+ };+/*** * `kept` - Kept* * `discarded` - Discarded@@ -11385,6 +11419,40 @@ export namespace Schemas {Crashed: 'crashed',} as const;+ export interface AutoresearchIteration {+ readonly id: string;+ pipeline: string;+ training_run: string;+ /**+ * @minimum -2147483648+ * @maximum 2147483647+ */+ iteration_number: number;+ /** @maxLength 64 */+ recipe_hash: string;+ /** Compact recipe snapshot at time of iteration. Full artifact lives in the model row. */+ recipe_snapshot: AutoresearchIterationRecipeSnapshot;+ /** Model class and hyperparameters tried in this iteration. */+ model_spec: AutoresearchIterationModelSpec;+ /** @nullable */+ train_score?: number | null;+ /** @nullable */+ holdout_score?: number | null;+ status: AutoresearchIterationStatusEnum;+ agent_description?: string;+ /**+ * Agent's self-assessed confidence 0–1+ * @nullable+ */+ agent_confidence?: number | null;+ /**+ * UUID of the steering suggestion this iteration was spawned from, if any.+ * @nullable+ */+ parent_suggestion?: string | null;+ readonly created_at: string;+ }+/*** Portable recipe artifact. Feature SQL, transforms, model class, params, and metadata.*/@@ -11827,6 +11895,25 @@ export namespace Schemas {distillation: string;}+ /**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+ export type IterationTrailModelSpecModelParams = { [key: string]: unknown } | null;++ /**+ * Model class and hyperparameters tried in this iteration.+ */+ export type IterationTrailModelSpec = {+ /** Dotted path of the estimator class. */+ model_class: string;+ /**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+ model_params?: IterationTrailModelSpecModelParams;+ };+/*** Compact, read-only view of one iteration for the cross-run history feed and the Training tab.*/@@ -11856,7 +11943,7 @@ export namespace Schemas {/** 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;+ model_spec: IterationTrailModelSpec;}export interface AutoresearchTrainingRun {@@ -20175,6 +20262,34 @@ export namespace Schemas {value: string;}+ /**+ * Global feature importance / directionality bundle for the champion model card.+ */+ export type CompleteTrainingRunModelExplanation = { [key: string]: unknown };++ /**+ * Input for finalizing a training run. The backend selects/promotes the champion.+ */+ export interface CompleteTrainingRun {+ /**+ * Advisory nomination. The server promotes the kept iteration with the highest holdout_score; this id only breaks a tie at that score, and a lower-scoring nomination is logged and ignored.+ * @nullable+ */+ best_iteration_id?: string | null;+ /** Global feature importance / directionality bundle for the champion model card. */+ model_explanation?: CompleteTrainingRunModelExplanation;+ /**+ * What a future run should try next, given what this run learned. Stored in the run summary so the next run reads it during orientation. Keep it short and concrete; max 2000 characters.+ * @maxLength 2000+ */+ recommended_next?: string;+ /**+ * A 1–2 sentence distillation of what this run learned — the winning signal, the key transform, the dead-ends. Stored in the run summary as the cheapest thing the next run reads. Max 2000 characters.+ * @maxLength 2000+ */+ distillation?: string;+ }+export interface ComposeTicket {/** Recipient email address. */recipient_email: string;@@ -52224,6 +52339,74 @@ export namespace Schemas {readonly unavailable: readonly string[];}+ /**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+ export type IterationTrailWithRecipeModelSpecModelParams = { [key: string]: unknown } | null;++ /**+ * Model class and hyperparameters tried in this iteration.+ */+ export type IterationTrailWithRecipeModelSpec = {+ /** Dotted path of the estimator class. */+ model_class: string;+ /**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+ model_params?: IterationTrailWithRecipeModelSpecModelParams;+ };++ export type IterationTrailWithRecipeRecipeSnapshotFeatureTransformsItem = { [key: string]: unknown };++ /**+ * The recipe this iteration tried: its feature_sql and transforms, so a later run can reuse them.+ */+ export type IterationTrailWithRecipeRecipeSnapshot = {+ /** A read-only HogQL SELECT from {anchors}, one row per person, keyed on person_id. */+ feature_sql: string;+ /**+ * Transforms the bundle applies to the feature columns; null or absent means none, and the in-process path accepts none.+ * @nullable+ */+ feature_transforms?: IterationTrailWithRecipeRecipeSnapshotFeatureTransformsItem[] | null;+ };++ /**+ * The trail with each iteration's recipe, for history only: a run list page would otherwise carry every recipe of every run.+ */+ export interface IterationTrailWithRecipe {+ /**+ * 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: IterationTrailWithRecipeModelSpec;+ /** The recipe this iteration tried: its feature_sql and transforms, so a later run can reuse them. */+ recipe_snapshot: IterationTrailWithRecipeRecipeSnapshot;+ }+export interface JiraIssueSignalExtra {key: string;url: string | null;@@ -59139,6 +59322,18 @@ export namespace Schemas {p50_seconds: number | null;}+ /**+ * Input for opening an agent-driven training run.+ */+ export interface OpenTrainingRun {+ /**+ * Iteration budget for this run. Defaults to the pipeline's iteration_budget if omitted.+ * @minimum 1+ * @maximum 500+ */+ iteration_budget?: number;+ }+/*** * `latest` - latest* * `earliest` - earliest@@ -81943,6 +82138,107 @@ export namespace Schemas {recorded: boolean;}+ export type RecordIterationRecipeSnapshotFeatureTransformsItem = { [key: string]: unknown };++ /**+ * Compact recipe for this iteration: feature_sql (HogQL SELECT keyed on person_id) and transforms.+ */+ export type RecordIterationRecipeSnapshot = {+ /** A read-only HogQL SELECT from {anchors}, one row per person, keyed on person_id. */+ feature_sql: string;+ /**+ * Transforms the bundle applies to the feature columns; null or absent means none, and the in-process path accepts none.+ * @nullable+ */+ feature_transforms?: RecordIterationRecipeSnapshotFeatureTransformsItem[] | null;+ };++ /**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+ export type RecordIterationModelSpecModelParams = { [key: string]: unknown } | null;++ /**+ * model_class and model_params tried this iteration. Any class is accepted here; the sklearn/xgboost allowlist applies at completion, to a run that uploaded no bundle.+ */+ export type RecordIterationModelSpec = {+ /** Dotted path of the estimator class. */+ model_class: string;+ /**+ * Keyword arguments for the estimator's constructor; null or absent means the defaults.+ * @nullable+ */+ model_params?: RecordIterationModelSpecModelParams;+ };++ /**+ * * `kept` - kept+ * * `discarded` - discarded+ * * `crashed` - crashed+ */+ export type RecordIterationStatusEnum = typeof RecordIterationStatusEnum[keyof typeof RecordIterationStatusEnum];+++ export const RecordIterationStatusEnum = {+ Kept: 'kept',+ Discarded: 'discarded',+ Crashed: 'crashed',+ } as const;++ /**+ * Input for recording one training iteration. Validated against the recipe allowlist.+ */+ export interface RecordIteration {+ /**+ * Zero-based index of this iteration within the run. Re-sending the same number updates that iteration (idempotent).+ * @minimum 0+ * @maximum 2147483647+ */+ iteration_number: number;+ /** Compact recipe for this iteration: feature_sql (HogQL SELECT keyed on person_id) and transforms. */+ recipe_snapshot: RecordIterationRecipeSnapshot;+ /** model_class and model_params tried this iteration. Any class is accepted here; the sklearn/xgboost allowlist applies at completion, to a run that uploaded no bundle. */+ model_spec: RecordIterationModelSpec;+ /** 'kept' if this iteration improved on the best score, 'discarded' otherwise, 'crashed' on failure.+ *+ * * `kept` - kept+ * * `discarded` - discarded+ * * `crashed` - crashed */+ status: RecordIterationStatusEnum;+ /**+ * Training-set AUC for this iteration (0-1).+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ train_score?: number | null;+ /**+ * Held-out AUC for this iteration (0-1). Used to pick the champion at completion.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ holdout_score?: number | null;+ /**+ * Agent's plain-English rationale for this iteration. Max 2000 characters.+ * @maxLength 2000+ */+ agent_description?: string;+ /**+ * Agent's self-assessed confidence (0-1) that this iteration helps.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ agent_confidence?: number | null;+ /**+ * UUID of the steering suggestion this iteration was spawned from, if any. Set it whenever the iteration acts on a pending suggestion — it links the iteration back to the suggestion for attribution and advances the suggestion to 'acted_on'.+ * @nullable+ */+ parent_suggestion?: string | null;+ }+/*** The record itself, as a JSON object. Must validate against the scout config's `structured_output_schema` (shown in the run prompt); any invalid record fails the whole call with nothing written.*/@@ -95400,6 +95696,46 @@ export namespace Schemas {queue_id?: string | null;}+ /**+ * One prior completed training run plus its full iteration trail.+ */+ export interface TrainingRunHistoryEntry {+ /** UUID of the completed training run. */+ run_id: string;+ /** UUID of the pipeline this run belongs to. */+ pipeline_id: string;+ /** True if this run is from the pipeline you are training; False if it is a same-target sibling pipeline on the team. */+ is_current_pipeline: boolean;+ /** Target event this run's pipeline predicts. */+ target_event: string;+ /** Prediction horizon (days) of this run's pipeline. */+ horizon_days: number;+ /**+ * Best holdout AUC achieved across this run's iterations.+ * @nullable+ */+ best_holdout_score: number | null;+ /** Number of iterations recorded in this run. */+ iteration_count: number;+ /**+ * When this run completed.+ * @nullable+ */+ completed_at: string | null;+ /** Distilled tier-1 summary of this run — read this first to orient. Null for older runs without one. */+ summary: TrainingRunSummary | null;+ /** The iteration trail: every recipe tried, kept or discarded, with rationale and score. */+ iterations: IterationTrailWithRecipe[];+ }++ /**+ * Cross-run learning memory: prior runs the agent should read before iterating.+ */+ export interface TrainingRunHistory {+ /** Recent completed training runs — the current pipeline first, then same-target sibling pipelines on the team — newest first. Mine these to reuse winning features and avoid repeating discarded approaches. */+ runs: TrainingRunHistoryEntry[];+ }+export interface TranslateRequest {/*** The text to translate@@ -101638,6 +101974,15 @@ export namespace Schemas {offset?: number;};+ export type AutoresearchTrainingRunsHistoryRetrieveParams = {+ /**+ * Maximum number of prior runs to return (default 5, at most 20).+ * @minimum 1+ * @maximum 20+ */+ limit?: number;+ };+export type BatchExportsListParams = {/*** Number of results to return per page.