Skip to content

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

feat(autoresearch): add the artifact and feature-materialization endpoints (17/22) (#89149)

Andrew Maguirec471c4c7dd97
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.py
index 842c346df120..901e9c32c264 100644
--- a/products/autoresearch/backend/facade/api.py
+++ b/products/autoresearch/backend/facade/api.py
@@ -10,9 +10,10 @@ filters on it. Business rules live in the modules behind this facade, not in the
"""
import json
+import base64
import hashlib
from typing import Any
-from uuid import UUID
+from uuid import UUID, uuid4
from django.db import transaction
from django.db.models import F, Q
@@ -20,6 +21,7 @@ from django.utils import timezone as django_timezone
from posthog.models.team import Team
from posthog.models.user import User
+from posthog.storage.object_storage import ObjectStorageError
from products.actions.backend.models.action import Action
@@ -41,12 +43,20 @@ from ..models import (
AutoresearchSuggestion,
AutoresearchTrainingRun,
)
-from ..training.recipe_validation import RecipeValidationError, validate_recipe
+from ..training import artifacts as artifact_store
+from ..training.recipe_validation import RecipeValidationError, validate_feature_sql, validate_recipe
from .contracts import (
+ ArtifactContent,
+ ArtifactDeleteResult,
+ ArtifactList,
+ ArtifactNotFound,
+ ArtifactStorageUnavailable,
AutoresearchConflict,
+ InvalidArtifactPath as InvalidArtifactPath,
InvalidTarget,
Iteration,
IterationTrailEntry,
+ MaterializedFeatures,
Model,
Pipeline,
PipelineNotFound,
@@ -54,6 +64,7 @@ from .contracts import (
PipelineWrite,
ResolvedTemplate,
Run,
+ StoredArtifact,
TemplateInfo,
TrainingRun,
TrainingRunHistory,
@@ -70,6 +81,13 @@ def flag_key() -> str:
return AUTORESEARCH_FLAG
+# Where materialized training parquet lands inside the agent's sandbox. The agent reads
+# these paths with pd.read_parquet — the rows never transit the model's context.
+_AGENT_FEATURE_DIR = "/tmp/workspace/autoresearch/data"
+
+# Every bundle file is capped at MAX_ARTIFACT_BYTES, so this also bounds the bundle's total size.
+MAX_BUNDLE_FILES = 32
+
HISTORY_LIMIT_MAX = 20
@@ -474,6 +492,14 @@ def validate_definition(
)
+def validate_features_sql(features_sql: str) -> None:
+ """Raise ``AutoresearchConflict`` if the agent's feature SQL is not a safe read-only SELECT."""
+ try:
+ validate_feature_sql(features_sql)
+ except RecipeValidationError as exc:
+ raise AutoresearchConflict(str(exc)) from exc
+
+
# ── Models ─────────────────────────────────────────────────────────────────
@@ -739,6 +765,256 @@ def _same_target_as(pipeline: AutoresearchPipeline) -> Q:
)
+# ── Feature materialization ────────────────────────────────────────────────
+
+
+def materialize_features(
+ team_id: int,
+ training_run_id: str | UUID,
+ *,
+ pipeline_id: str | UUID | None = None,
+ features_sql: str,
+ user: User,
+) -> MaterializedFeatures:
+ """Run ``features_sql`` server-side and write the parquet into this run's sandbox.
+
+ The rows never pass through the agent's context and there is no row cap. The destination
+ paths are fixed by the framework — the agent supplies the query, never where it lands.
+ """
+ # The inference sandbox imports pandas and pyarrow; the router imports this module for
+ # every web worker, so the heavy path loads only when a run materializes.
+ from ..inference.sandbox import SandboxInferenceError, label_classes, materialize_training_data # noqa: PLC0415
+
+ training_run = _training_run_row(team_id, training_run_id, pipeline_id=pipeline_id, with_iterations=False)
+ if training_run.status != AutoresearchTrainingRun.Status.RUNNING:
+ raise AutoresearchConflict("Can only materialize features for a running training run.")
+ validate_features_sql(features_sql)
+
+ sandbox_id = _resolve_run_sandbox_id(training_run)
+ team = Team.objects.get(pk=team_id)
+ try:
+ data = materialize_training_data(team=team, pipeline=training_run.pipeline, feature_sql=features_sql, user=user)
+ except (SandboxInferenceError, RecipeValidationError) as exc:
+ raise AutoresearchConflict(f"Feature materialization failed: {exc}") from exc
+ if not data.train_rows:
+ raise AutoresearchConflict("features_sql produced no training rows.")
+ if not data.feature_cols:
+ raise AutoresearchConflict("features_sql produced no numeric feature columns.")
+ # The folds are fixed per person, so another features_sql cannot repair a split that cannot
+ # be fitted or scored. Refusing here tells the agent the population is too thin instead of
+ # letting it spend the run on iterations completion can never score.
+ if not data.holdout_rows:
+ raise AutoresearchConflict("The population is too small to hold out an evaluation set. Widen the population.")
+ if len(label_classes(data.train_rows)) < 2:
+ raise AutoresearchConflict(
+ "The training set has only one label class, so no model can be fitted. Widen the population."
+ )
+ if len(label_classes(data.holdout_rows)) < 2:
+ raise AutoresearchConflict(
+ "The holdout set has only one label class, so no holdout AUC can be computed. Widen the population."
+ )
+
+ paths = _write_feature_parquets(sandbox_id, data)
+ return MaterializedFeatures(
+ train_features_path=paths["train_features_path"],
+ train_labels_path=paths["train_labels_path"],
+ holdout_features_path=paths["holdout_features_path"],
+ holdout_labels_path=paths["holdout_labels_path"],
+ n_train=len(data.train_rows),
+ n_holdout=len(data.holdout_rows),
+ n_features=len(data.feature_cols),
+ feature_cols=list(data.feature_cols),
+ )
+
+
+def _resolve_run_sandbox_id(training_run: AutoresearchTrainingRun) -> str:
+ """Resolve the live sandbox for this run from its TaskRun state.
+
+ The sandbox id comes from the team-scoped run record, never from the client, and is
+ verified to belong to this training run.
+ """
+ from products.tasks.backend.facade import api as tasks_facade # noqa: PLC0415
+
+ if not training_run.task_run_id:
+ raise AutoresearchConflict("This training run has no sandbox (e.g. a stub run). Cannot materialize features.")
+ task_run = tasks_facade.get_task_run(training_run.task_run_id)
+ if task_run is None:
+ raise AutoresearchConflict("Sandbox task run not found for this training run.")
+ state = task_run.state if isinstance(task_run.state, dict) else {}
+ if str(state.get("autoresearch_training_run_id")) != str(training_run.id):
+ raise AutoresearchConflict("Sandbox does not belong to this training run.")
+ sandbox_id = state.get("sandbox_id")
+ if not sandbox_id:
+ raise AutoresearchConflict("Sandbox is not ready yet — try again once the agent has started.")
+ return str(sandbox_id)
+
+
+def _write_feature_parquets(sandbox_id: str, data: Any) -> dict[str, str]:
+ """Serialize the train/holdout matrices to parquet and write them into the agent's sandbox."""
+ # Same reason as in materialize_features: the sandbox providers and pandas stay off the
+ # router's import path.
+ from products.tasks.backend.facade.sandbox import ( # noqa: PLC0415
+ SandboxExecutionError,
+ SandboxNotFoundError,
+ SandboxNotRunningError,
+ SandboxTimeoutError,
+ get_sandbox_class_for_sandbox_id,
+ )
+
+ from ..inference.sandbox import SandboxInferenceError, features_parquet, labels_parquet # noqa: PLC0415
+
+ try:
+ sandbox = get_sandbox_class_for_sandbox_id(sandbox_id).get_by_id(sandbox_id)
+ except Exception as exc:
+ raise AutoresearchConflict(f"Could not connect to the run's sandbox: {exc}") from exc
+ try:
+ files = {
+ "train_features_path": ("train_features.parquet", features_parquet(data.train_rows, data.feature_cols)),
+ "train_labels_path": ("train_labels.parquet", labels_parquet(data.train_rows)),
+ "holdout_features_path": (
+ "holdout_features.parquet",
+ features_parquet(data.holdout_rows, data.feature_cols),
+ ),
+ "holdout_labels_path": ("holdout_labels.parquet", labels_parquet(data.holdout_rows)),
+ }
+ except SandboxInferenceError as exc:
+ raise AutoresearchConflict(f"Feature materialization failed: {exc}") from exc
+ # Each request gets its own directory, so two overlapping materializations cannot read each
+ # other's files, and a request that fails part-way leaves nothing at a path it returned.
+ directory = f"{_AGENT_FEATURE_DIR}/{uuid4().hex}"
+ paths: dict[str, str] = {}
+ for key, (name, content) in files.items():
+ path = f"{directory}/{name}"
+ try:
+ result = sandbox.write_file(path, content)
+ except (SandboxNotRunningError, SandboxExecutionError, SandboxNotFoundError, SandboxTimeoutError) as exc:
+ raise AutoresearchConflict(f"Failed to write {path} into the sandbox: {exc}") from exc
+ if result.exit_code != 0:
+ raise AutoresearchConflict(f"Failed to write {path} into the sandbox: {result.stderr[:300]}")
+ paths[key] = path
+ return paths
+
+
+# ── Artifact bundle ────────────────────────────────────────────────────────
+
+
+def _bundle_prefix(team_id: int, training_run: AutoresearchTrainingRun) -> str:
+ return artifact_store.bundle_prefix(
+ team_id=team_id,
+ pipeline_id=str(training_run.pipeline_id),
+ training_run_id=str(training_run.id),
+ )
+
+
+def list_artifacts(team_id: int, training_run_id: str | UUID, *, pipeline_id: str | UUID | None = None) -> ArtifactList:
+ training_run = _training_run_row(team_id, training_run_id, pipeline_id=pipeline_id, with_iterations=False)
+ paths = artifact_store.list_artifacts(_bundle_prefix(team_id, training_run))
+ return ArtifactList(paths=paths, count=len(paths))
+
+
+def write_artifact(
+ team_id: int,
+ training_run_id: str | UUID,
+ *,
+ pipeline_id: str | UUID | None = None,
+ path: str,
+ content_base64: str,
+) -> StoredArtifact:
+ """Store one file of the run's bundle. The bundle freezes once the run leaves ``running``."""
+ try:
+ content = base64.b64decode(content_base64, validate=True)
+ except Exception as exc:
+ raise AutoresearchConflict("content_base64 is not valid base64.") from exc
+ try:
+ rel = artifact_store.normalize_artifact_path(path)
+ except artifact_store.InvalidArtifact as exc:
+ raise InvalidArtifactPath(str(exc)) from exc
+ if rel == artifact_store.MODEL_PKL:
+ # The fitted model is written by the framework after completion. An agent-written model.pkl
+ # would make scoring skip its self-healing fit and serve those bytes on every cadence.
+ raise InvalidArtifactPath(f"{artifact_store.MODEL_PKL} is written by the framework and cannot be uploaded.")
+ if rel == artifact_store.FEATURES_SQL:
+ _require_runnable_features_sql(content)
+ # Completion validates and freezes the bundle under the run row lock. Writing under the same
+ # lock means an upload that started while the run was RUNNING cannot land after completion
+ # read the bundle.
+ with transaction.atomic():
+ training_run = _running_run_for_write(team_id, training_run_id, pipeline_id=pipeline_id)
+ prefix = _bundle_prefix(team_id, training_run)
+ existing = artifact_store.list_artifacts(prefix)
+ if rel not in existing and len(existing) >= MAX_BUNDLE_FILES:
+ raise AutoresearchConflict(
+ f"This bundle already holds {MAX_BUNDLE_FILES} files. Delete a file before uploading another."
+ )
+ try:
+ stored = artifact_store.write_artifact(prefix, rel, content)
+ except artifact_store.InvalidArtifact as exc:
+ raise InvalidArtifactPath(str(exc)) from exc
+ except ObjectStorageError as exc:
+ raise ArtifactStorageUnavailable(f"The artifact could not be stored: {exc}") from exc
+ return StoredArtifact(path=stored.path, size_bytes=stored.size_bytes, sha256=stored.sha256)
+
+
+def _require_runnable_features_sql(content: bytes) -> None:
+ """Refuse feature SQL the fit would refuse, so a champion never lands without a model."""
+ from ..inference.sandbox import SandboxInferenceError, validate_runnable_feature_sql # noqa: PLC0415
+
+ try:
+ text = content.decode("utf-8")
+ except UnicodeDecodeError:
+ return # the store refuses the bytes with its own message
+ try:
+ validate_runnable_feature_sql(text, source=artifact_store.FEATURES_SQL)
+ except SandboxInferenceError as exc:
+ raise InvalidArtifactPath(str(exc)) from exc
+
+
+def _running_run_for_write(
+ team_id: int, training_run_id: str | UUID, *, pipeline_id: str | UUID | None
+) -> AutoresearchTrainingRun:
+ 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("The bundle is frozen because the training run is no longer running.")
+ return training_run
+
+
+def read_artifact(
+ team_id: int, training_run_id: str | UUID, *, pipeline_id: str | UUID | None = None, path: str
+) -> ArtifactContent:
+ training_run = _training_run_row(team_id, training_run_id, pipeline_id=pipeline_id, with_iterations=False)
+ prefix = _bundle_prefix(team_id, training_run)
+ try:
+ content = artifact_store.read_artifact(prefix, path)
+ except artifact_store.InvalidArtifactPath as exc:
+ raise InvalidArtifactPath(str(exc)) from exc
+ except artifact_store.BundleNotFound as exc:
+ raise ArtifactNotFound(str(exc)) from exc
+ return ArtifactContent(
+ path=artifact_store.normalize_artifact_path(path),
+ size_bytes=len(content),
+ sha256=hashlib.sha256(content).hexdigest(),
+ content_base64=base64.b64encode(content).decode("ascii"),
+ )
+
+
+def delete_artifact(
+ team_id: int, training_run_id: str | UUID, *, pipeline_id: str | UUID | None = None, path: str
+) -> ArtifactDeleteResult:
+ try:
+ normalized = artifact_store.normalize_artifact_path(path)
+ except artifact_store.InvalidArtifactPath as exc:
+ raise InvalidArtifactPath(str(exc)) from exc
+ with transaction.atomic():
+ training_run = _running_run_for_write(team_id, training_run_id, pipeline_id=pipeline_id)
+ try:
+ deleted = artifact_store.delete_artifact(_bundle_prefix(team_id, training_run), normalized)
+ except ObjectStorageError as exc:
+ raise ArtifactStorageUnavailable(f"The artifact could not be deleted: {exc}") from exc
+ return ArtifactDeleteResult(path=normalized, deleted=deleted)
+
+
# ── Recipe validation surface for the presentation layer ───────────────────
# The semantic population kinds the labeler can compile. Presentation validates a submitted
diff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.py
index 44823cc66d81..1b5a5fc5304a 100644
--- a/products/autoresearch/backend/facade/contracts.py
+++ b/products/autoresearch/backend/facade/contracts.py
@@ -49,6 +49,21 @@ class InvalidTarget(ValueError):
"""
+class ArtifactNotFound(LookupError):
+ """No artifact at that path in the run's bundle."""
+
+
+class InvalidArtifactPath(ValueError):
+ """The artifact path escapes the bundle prefix or is otherwise unusable."""
+
+
+class ArtifactStorageUnavailable(RuntimeError):
+ """Object storage refused or failed the artifact write, so nothing was stored.
+
+ The viewset maps it to a 503 with the message as-is, so the message is user-facing copy.
+ """
+
+
# ── Model-backed read contracts ────────────────────────────────────────────
@@ -304,3 +319,50 @@ class TrainingRunHistoryEntry:
@dataclass(frozen=True)
class TrainingRunHistory:
runs: list[TrainingRunHistoryEntry]
+
+
+# ── Artifact bundle ────────────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class ArtifactList:
+ paths: list[str]
+ count: int
+
+
+@dataclass(frozen=True)
+class StoredArtifact:
+ path: str
+ size_bytes: int
+ sha256: str
+
+
+@dataclass(frozen=True)
+class ArtifactContent:
+ path: str
+ size_bytes: int
+ sha256: str
+ content_base64: str
+
+
+@dataclass(frozen=True)
+class ArtifactDeleteResult:
+ path: str
+ deleted: bool
+
+
+# ── Feature materialization ────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class MaterializedFeatures:
+ """Sandbox paths and shape of the parquet the agent reads with ``pd.read_parquet``."""
+
+ train_features_path: str
+ train_labels_path: str
+ holdout_features_path: str
+ holdout_labels_path: str
+ n_train: int
+ n_holdout: int
+ n_features: int
+ feature_cols: list[str]
diff --git a/products/autoresearch/backend/inference/sandbox.py b/products/autoresearch/backend/inference/sandbox.py
index ba126fc92de1..4c3897a57ef7 100644
--- a/products/autoresearch/backend/inference/sandbox.py
+++ b/products/autoresearch/backend/inference/sandbox.py
@@ -683,12 +683,21 @@ def labels_parquet(rows: list[dict[str, Any]]) -> bytes:
df = pd.DataFrame(
{
"distinct_id": [str(r.get("distinct_id", "")) for r in rows],
- _LABEL_COL: [int(r.get(_LABEL_COL) or 0) for r in rows],
+ _LABEL_COL: [_label(r) for r in rows],
}
)
return _to_parquet_bytes(df)
+def label_classes(rows: list[dict[str, Any]]) -> set[int]:
+ """The distinct label values ``labels_parquet`` would write for ``rows``."""
+ return {_label(r) for r in rows}
+
+
+def _label(row: dict[str, Any]) -> int:
+ return int(row.get(_LABEL_COL) or 0)
+
+
def _to_parquet_bytes(df: pd.DataFrame) -> bytes:
buf = io.BytesIO()
df.to_parquet(buf, index=False)
diff --git a/products/autoresearch/backend/inference/test_materialize_features.py b/products/autoresearch/backend/inference/test_materialize_features.py
new file mode 100644
index 000000000000..a4e3e82bb7bf
--- /dev/null
+++ b/products/autoresearch/backend/inference/test_materialize_features.py
@@ -0,0 +1,224 @@
+import uuid
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models import Organization, Team
+
+from products.autoresearch.backend.inference.sandbox import MaterializedData
+from products.autoresearch.backend.models import AutoresearchPipeline, AutoresearchTrainingRun
+from products.autoresearch.backend.testing import TeamScopedTestMixin
+from products.tasks.backend.facade.sandbox import ExecutionResult, SandboxNotRunningError
+
+VALID_FEATURE_SQL = "SELECT a.person_id AS distinct_id, count() AS pv FROM {anchors} a GROUP BY a.person_id"
+
+
+class _FakeSandbox:
+ def __init__(self, exit_code: int = 0, raises: Exception | None = None):
+ self.writes: dict[str, bytes] = {}
+ self._exit_code = exit_code
+ self._raises = raises
+
+ def write_file(self, path: str, payload: bytes) -> ExecutionResult:
+ if self._raises is not None:
+ raise self._raises
+ self.writes[path] = payload
+ return ExecutionResult(stdout="", stderr="boom" if self._exit_code else "", exit_code=self._exit_code)
+
+
+def _rows(fold: int, labels: list[int], cols: list[str]) -> list[dict]:
+ return [
+ {"distinct_id": f"p{fold}{i}", "__label": label, "__fold": fold, **dict.fromkeys(cols, i)}
+ for i, label in enumerate(labels)
+ ]
+
+
+def _materialized(
+ train_labels: tuple[int, ...] = (1, 0),
+ holdout_labels: tuple[int, ...] = (0, 1),
+ feature_cols: list[str] | None = None,
+) -> MaterializedData:
+ cols = feature_cols or ["pv", "uploads"]
+ return MaterializedData(
+ feature_cols=cols,
+ train_rows=_rows(1, list(train_labels), cols),
+ holdout_rows=_rows(0, list(holdout_labels), cols),
+ )
+
+
+class TestMaterializeFeatures(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,
+ )
+
+ def _run(self, *, status_value=AutoresearchTrainingRun.Status.RUNNING, task_run_id=None) -> AutoresearchTrainingRun:
+ return AutoresearchTrainingRun.objects.create(
+ pipeline=self.pipeline, status=status_value, task_run_id=task_run_id
+ )
+
+ def _url(self, run: AutoresearchTrainingRun, pipeline=None) -> str:
+ pipeline = pipeline or self.pipeline
+ return f"/api/projects/{self.team.pk}/autoresearch/{pipeline.pk}/training_runs/{run.id}/materialize-features/"
+
+ def _fake_task_run(self, run: AutoresearchTrainingRun, *, sandbox_id="sb-123"):
+ return MagicMock(state={"autoresearch_training_run_id": str(run.id), "sandbox_id": sandbox_id})
+
+ def test_rejects_non_running_run(self):
+ run = self._run(status_value=AutoresearchTrainingRun.Status.COMPLETED)
+ resp = self.client.post(self._url(run), {"features_sql": VALID_FEATURE_SQL}, format="json")
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert "running" in str(resp.json()).lower()
+
+ def test_rejects_feature_sql_without_person_id(self):
+ run = self._run()
+ resp = self.client.post(self._url(run), {"features_sql": "SELECT 1 AS x FROM events"}, format="json")
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert "person_id" in str(resp.json())
+
+ def test_rejects_run_without_sandbox(self):
+ run = self._run(task_run_id=None)
+ resp = self.client.post(self._url(run), {"features_sql": VALID_FEATURE_SQL}, format="json")
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert "sandbox" in str(resp.json()).lower()
+
+ def test_is_team_scoped(self):
+ other_org = Organization.objects.create(name="Other")
+ other_team = Team.objects.create(organization=other_org, name="Other")
+ other_pipeline = AutoresearchPipeline.objects.create(
+ team=other_team, created_by=self.user, name="Other", target_event="$pageview", horizon_days=7
+ )
+ other_run = AutoresearchTrainingRun.objects.create(
+ pipeline=other_pipeline, status=AutoresearchTrainingRun.Status.RUNNING
+ )
+ # Address another team's run through our team's URL — must not resolve.
+ resp = self.client.post(
+ self._url(other_run, pipeline=other_pipeline), {"features_sql": VALID_FEATURE_SQL}, format="json"
+ )
+ assert resp.status_code in (status.HTTP_404_NOT_FOUND, status.HTTP_400_BAD_REQUEST)
+
+ def _materialize(self, run, *, task_run=None, materialized=None, sandbox=None):
+ with (
+ patch("products.tasks.backend.facade.sandbox.get_sandbox_class_for_sandbox_id") as mock_resolve,
+ patch(
+ "products.autoresearch.backend.inference.sandbox.materialize_training_data",
+ return_value=materialized or _materialized(),
+ ),
+ patch(
+ "products.tasks.backend.facade.api.get_task_run",
+ return_value=task_run or self._fake_task_run(run),
+ ),
+ ):
+ mock_resolve.return_value.get_by_id.return_value = sandbox or _FakeSandbox()
+ resp = self.client.post(self._url(run), {"features_sql": VALID_FEATURE_SQL}, format="json")
+ return resp, mock_resolve
+
+ def test_writes_parquet_and_returns_paths(self):
+ run = self._run(task_run_id=uuid.uuid4())
+ fake_sandbox = _FakeSandbox()
+
+ resp, mock_resolve = self._materialize(run, sandbox=fake_sandbox)
+ assert resp.status_code == status.HTTP_200_OK, resp.json()
+ body = resp.json()
+ assert body["n_train"] == 2
+ assert body["n_holdout"] == 2
+ assert body["n_features"] == 2
+ assert body["feature_cols"] == ["pv", "uploads"]
+ # All four parquet files land in one per-request directory under the framework-controlled base.
+ directory = body["train_features_path"].rsplit("/", 1)[0]
+ assert directory.startswith("/tmp/workspace/autoresearch/data/")
+ assert set(fake_sandbox.writes.keys()) == {
+ f"{directory}/train_features.parquet",
+ f"{directory}/train_labels.parquet",
+ f"{directory}/holdout_features.parquet",
+ f"{directory}/holdout_labels.parquet",
+ }
+ assert {body[k].rsplit("/", 1)[0] for k in body if k.endswith("_path")} == {directory}
+ mock_resolve.assert_called_once_with("sb-123")
+ mock_resolve.return_value.get_by_id.assert_called_once_with("sb-123")
+
+ def test_each_request_gets_its_own_directory(self):
+ run = self._run(task_run_id=uuid.uuid4())
+ first, _ = self._materialize(run)
+ second, _ = self._materialize(run)
+ assert first.json()["train_features_path"] != second.json()["train_features_path"]
+
+ @parameterized.expand(
+ [
+ ("state_names_another_run", {"autoresearch_training_run_id": "other", "sandbox_id": "sb-123"}),
+ ("state_is_not_an_object", ["not", "a", "dict"]),
+ ]
+ )
+ def test_rejects_sandbox_not_owned_by_run(self, _name: str, state):
+ run = self._run(task_run_id=uuid.uuid4())
+ resp, mock_resolve = self._materialize(run, task_run=MagicMock(state=state))
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert "does not belong" in str(resp.json()).lower()
+ mock_resolve.return_value.get_by_id.assert_not_called()
+
+ def test_sandbox_write_failure_is_a_400(self):
+ run = self._run(task_run_id=uuid.uuid4())
+ resp, _ = self._materialize(
+ run, sandbox=_FakeSandbox(raises=SandboxNotRunningError("gone", {}, RuntimeError("gone"), capture=False))
+ )
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert "gone" in str(resp.json())
+
+ def test_over_wide_feature_matrix_is_a_400(self):
+ run = self._run(task_run_id=uuid.uuid4())
+ resp, _ = self._materialize(run, materialized=_materialized(feature_cols=[f"f{i}" for i in range(513)]))
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert "column cap" in str(resp.json())
+
+ @parameterized.expand(
+ [
+ ("no_holdout_rows", (1, 0), (), "too small"),
+ ("single_class_holdout", (1, 0), (0,), "holdout set has only one label class"),
+ ("single_class_training", (1, 1), (0, 1), "training set has only one label class"),
+ ]
+ )
+ def test_rejects_unscorable_split(self, _name: str, train_labels, holdout_labels, message: str):
+ run = self._run(task_run_id=uuid.uuid4())
+ fake_sandbox = _FakeSandbox()
+ resp, _ = self._materialize(run, materialized=_materialized(train_labels, holdout_labels), sandbox=fake_sandbox)
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert message in str(resp.json())
+ assert fake_sandbox.writes == {}
+
+ def test_is_scoped_to_the_parent_pipeline(self):
+ other_pipeline = AutoresearchPipeline.objects.create(
+ team=self.team, created_by=self.user, name="Other", target_event="$pageview", horizon_days=7
+ )
+ run = self._run(task_run_id=uuid.uuid4())
+ resp = self.client.post(
+ self._url(run, pipeline=other_pipeline), {"features_sql": VALID_FEATURE_SQL}, format="json"
+ )
+ assert resp.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_needs_the_query_scope(self):
+ run = self._run(task_run_id=uuid.uuid4())
+ self.client.logout()
+ write_only = self.create_personal_api_key_with_scopes(["autoresearch:write"])
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {write_only}")
+ resp, _ = self._materialize(run)
+ assert resp.status_code == status.HTTP_403_FORBIDDEN
+ with_query = self.create_personal_api_key_with_scopes(["autoresearch:write", "query:read"])
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {with_query}")
+ resp, _ = self._materialize(run)
+ assert resp.status_code == status.HTTP_200_OK, resp.json()
diff --git a/products/autoresearch/backend/presentation/AGENTS.md b/products/autoresearch/backend/presentation/AGENTS.md
index 76d2f503d910..d0b24b019786 100644
--- a/products/autoresearch/backend/presentation/AGENTS.md
+++ b/products/autoresearch/backend/presentation/AGENTS.md
@@ -5,14 +5,14 @@ The HTTP surface — and, because of how PostHog's codegen works, considerably m
These serializers are the source of truth for three downstream artifacts: the REST API itself, the generated frontend TypeScript types, and the 29 `autoresearch-*` MCP tools that the sandbox agent uses to drive its own training run.
A vague `help_text` here becomes a vague tool description that a model has to guess at. Treat serializer annotations as agent-facing documentation, because they are.
-This package lands one endpoint group at a time. Pipeline CRUD, 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.
+This package lands one endpoint group at a time. Pipeline CRUD, the pre-create helpers, the read-only model and run viewsets, and the whole training-run agent surface are here; the lifecycle actions 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`.
- - `AutoresearchTrainingRunViewSet` — read plus create, and the agent's write surface so far: `iterations`, `complete`, plus `history`.
+ - `AutoresearchTrainingRunViewSet` — read plus create, and **the agent's entire write surface**: `iterations`, `materialize-features`, `complete`, `artifacts`, `artifacts/upload`, `artifacts/get`, `artifacts/delete`, 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.
@@ -32,15 +32,18 @@ This is the part that makes this package unusual. During a training run the sand
```text
agent server
│ POST training_runs/<id>/iterations → validated, stored as AutoresearchIteration
+ │ POST .../materialize-features → features + labels parquet into its sandbox
+ │ POST .../artifacts/upload → bundle files into object storage
│ 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.
+- **Everything the agent sends is untrusted.** SQL it submits gets executed; paths it supplies become storage keys. `iterations` runs it through `../training/recipe_validation.py` and `artifacts/upload` through `normalize_artifact_path()` / `MAX_ARTIFACT_BYTES` in `../training/artifacts.py`. A bundle holds at most `MAX_BUNDLE_FILES` (facade) files, and `model.pkl` is reserved for the framework's fit.
+- **The write surface closes when the run does.** `iterations`, `materialize-features`, `complete`, `artifacts/upload`, and `artifacts/delete` all require the run to be RUNNING (or PENDING for `complete`), so a finished run's artifact bundle is frozen — scoring reads it, nothing rewrites it. Artifact reads stay open. Recording, uploading and deleting take the run row lock that completion takes, so the status check and the write see one state: an iteration cannot land on a completed run, and a bundle file cannot change after completion validated the bundle. Recording also 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.
+- **`materialize-features` is sandbox-scoped.** It verifies the sandbox belongs to this training run before writing anything into it, resolves the sandbox provider from the persisted sandbox id, and writes each request's parquet into its own directory so overlapping requests cannot read each other's files. It runs caller-authored HogQL, so it needs `query:read` on a scoped token and takes the ClickHouse throttles, like the pipeline viewset's query-backed actions.
- 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
diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.py
index 59afc2ccfcfb..b9e9cb3e86d4 100644
--- a/products/autoresearch/backend/presentation/views/serializers.py
+++ b/products/autoresearch/backend/presentation/views/serializers.py
@@ -1393,6 +1393,110 @@ class CompleteTrainingRunSerializer(serializers.Serializer):
)
+# ── Feature materialization serializers ─────────────────────────────────────
+
+
+class MaterializeFeaturesRequestSerializer(serializers.Serializer):
+ """Input for materializing the labeled training feature matrix into the run's sandbox."""
+
+ features_sql = serializers.CharField(
+ help_text=(
+ "Your HogQL feature query, using the {anchors}/{lookback_days} contract. Must be a read-only "
+ "SELECT keyed on person_id (aliased to distinct_id), one row per user. The backend runs it "
+ "server-side against the labeled training population — no 500-row cap — and writes the resulting "
+ "train/holdout feature and label parquet files into your sandbox."
+ ),
+ )
+
+
+class MaterializeFeaturesResponseSerializer(serializers.Serializer):
+ """The local sandbox paths and shape of the materialized training matrix."""
+
+ train_features_path = serializers.CharField(
+ help_text="Sandbox path to the training feature matrix parquet (distinct_id + numeric feature columns)."
+ )
+ train_labels_path = serializers.CharField(
+ help_text="Sandbox path to the training labels parquet (distinct_id + __label)."
+ )
+ holdout_features_path = serializers.CharField(
+ help_text="Sandbox path to the holdout feature matrix parquet (same columns as train_features)."
+ )
+ holdout_labels_path = serializers.CharField(
+ help_text="Sandbox path to the holdout labels parquet (distinct_id + __label)."
+ )
+ n_train = serializers.IntegerField(help_text="Number of rows in the training split.")
+ n_holdout = serializers.IntegerField(help_text="Number of rows in the holdout split.")
+ n_features = serializers.IntegerField(help_text="Number of numeric feature columns produced by features_sql.")
+ feature_cols = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="The numeric feature column names (excludes distinct_id, __label, __fold).",
+ )
+
+
+# ── Artifact bundle serializers ─────────────────────────────────────────────
+
+
+class ArtifactUploadSerializer(serializers.Serializer):
+ """Input for uploading one file of a training run's artifact bundle."""
+
+ path = serializers.CharField(
+ max_length=500,
+ help_text=(
+ "Relative path within the bundle, e.g. 'train.py', 'predict.py', 'features.sql', "
+ "or 'eda/iter-3-gbm.ipynb'. Segments are limited to [A-Za-z0-9_.-]; "
+ "absolute paths and '..' traversal are rejected."
+ ),
+ )
+ content_base64 = serializers.CharField(
+ help_text=(
+ "File contents, base64-encoded. Decoded server-side and written to object storage. Max 10 MB decoded."
+ ),
+ )
+
+
+class ArtifactPathSerializer(serializers.Serializer):
+ """Input for fetching or deleting one bundle file by path."""
+
+ path = serializers.CharField(
+ max_length=500,
+ help_text="Relative path of the file within the bundle, e.g. 'train.py'.",
+ )
+
+
+class StoredArtifactSerializer(serializers.Serializer):
+ """Result of an upload: where the file landed and its content hash."""
+
+ path = serializers.CharField(help_text="Relative path the file was stored at.")
+ size_bytes = serializers.IntegerField(help_text="Decoded file size in bytes.")
+ sha256 = serializers.CharField(help_text="SHA-256 hex digest of the decoded file content.")
+
+
+class ArtifactContentSerializer(serializers.Serializer):
+ """A single bundle file's content, base64-encoded."""
+
+ path = serializers.CharField(help_text="Relative path of the file within the bundle.")
+ size_bytes = serializers.IntegerField(help_text="File size in bytes.")
+ sha256 = serializers.CharField(help_text="SHA-256 hex digest of the file content.")
+ content_base64 = serializers.CharField(help_text="File contents, base64-encoded.")
+
+
+class ArtifactListSerializer(serializers.Serializer):
+ """The relative paths present in a training run's bundle."""
+
+ paths = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Relative paths of every file stored under this training run's bundle prefix.",
+ )
+ count = serializers.IntegerField(help_text="Number of files in the bundle.")
+
+
+class ArtifactDeleteResultSerializer(serializers.Serializer):
+ """Whether a delete removed an existing file."""
+
+ path = serializers.CharField(help_text="Relative path targeted for deletion.")
+ deleted = serializers.BooleanField(help_text="True if a file existed and was removed; False if nothing was there.")
+
+
# ── Template serializers ───────────────────────────────────────────────────────
diff --git a/products/autoresearch/backend/presentation/views/views.py b/products/autoresearch/backend/presentation/views/views.py
index 2703af3b8709..56ac4e3e30c1 100644
--- a/products/autoresearch/backend/presentation/views/views.py
+++ b/products/autoresearch/backend/presentation/views/views.py
@@ -16,7 +16,7 @@ import structlog
from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import viewsets
from rest_framework.decorators import action
-from rest_framework.exceptions import NotFound, ValidationError
+from rest_framework.exceptions import APIException, NotFound, ValidationError
from rest_framework.fields import empty
from rest_framework.permissions import BasePermission
from rest_framework.request import Request
@@ -32,9 +32,21 @@ from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedR
from products.autoresearch.backend.facade import api
from products.autoresearch.backend.facade.access import has_autoresearch_access
-from products.autoresearch.backend.facade.contracts import AutoresearchConflict, PipelineNotFound, TrainingRunNotFound
+from products.autoresearch.backend.facade.contracts import (
+ ArtifactNotFound,
+ ArtifactStorageUnavailable,
+ AutoresearchConflict,
+ InvalidArtifactPath,
+ PipelineNotFound,
+ TrainingRunNotFound,
+)
from .serializers import (
+ ArtifactContentSerializer,
+ ArtifactDeleteResultSerializer,
+ ArtifactListSerializer,
+ ArtifactPathSerializer,
+ ArtifactUploadSerializer,
AutoresearchIterationSerializer,
AutoresearchModelSerializer,
AutoresearchPipelineCreateSerializer,
@@ -42,10 +54,13 @@ from .serializers import (
AutoresearchRunSerializer,
AutoresearchTrainingRunSerializer,
CompleteTrainingRunSerializer,
+ MaterializeFeaturesRequestSerializer,
+ MaterializeFeaturesResponseSerializer,
OpenTrainingRunSerializer,
RecordIterationSerializer,
ResolvedTemplateSerializer,
ResolveTemplateRequestSerializer,
+ StoredArtifactSerializer,
TemplateInfoSerializer,
TrainingRunHistoryQuerySerializer,
TrainingRunHistorySerializer,
@@ -119,6 +134,12 @@ class _FacadePaginationMixin:
return paginator.get_paginated_response(serializer.data)
+class ArtifactStorageUnavailableError(APIException):
+ status_code = 503
+ default_detail = "Object storage is unavailable, so the artifact could not be stored. Try again in a moment."
+ default_code = "artifact_storage_unavailable"
+
+
def _parent_pipeline_id(view: Any) -> str | None:
"""The pipeline this nested route is scoped to, or None on the unscoped collection route."""
pipeline_id = view.kwargs.get("parent_lookup_pipeline_id")
@@ -422,11 +443,26 @@ class AutoresearchTrainingRunViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMi
schema = FacadePathParamSchema()
uuid_path_parameters = {"id": "A UUID string identifying this autoresearch training run.", "pipeline_id": None}
scope_object = "autoresearch"
- scope_object_read_actions = ["list", "retrieve", "history"]
- scope_object_write_actions = ["create", "record_iteration", "complete"]
+ scope_object_read_actions = ["list", "retrieve", "list_artifacts", "get_artifact", "history"]
+ scope_object_write_actions = [
+ "create",
+ "record_iteration",
+ "complete",
+ "materialize_features",
+ "upload_artifact",
+ "delete_artifact",
+ ]
permission_classes = [AutoresearchAccessPermission]
serializer_class = AutoresearchTrainingRunSerializer
queryset = None # data is reached through the facade; declared for router/schema only
+
+ def get_throttles(self) -> list[BaseThrottle]:
+ # The feature query and the anchor count are unsampled ClickHouse scans, so a personal API
+ # key gets the ClickHouse budget here as on the pipeline viewset's query-backed actions.
+ if self.action == "materialize_features":
+ return [ClickHouseBurstRateThrottle(), ClickHouseSustainedRateThrottle()]
+ return super().get_throttles()
+
# A training run is opened and appended to, never edited or deleted.
http_method_names = ["get", "post", "head", "options"]
@@ -515,6 +551,56 @@ class AutoresearchTrainingRunViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMi
raise ValidationError(str(exc)) from exc
return Response(AutoresearchIterationSerializer(instance=iteration).data, status=201)
+ @validated_request(
+ request_serializer=MaterializeFeaturesRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=MaterializeFeaturesResponseSerializer,
+ description="Sandbox paths to the train/holdout feature and label parquet files, plus row counts and feature columns.",
+ ),
+ 400: OpenApiResponse(
+ description=(
+ "Run not running, features_sql invalid, sandbox unavailable, the query produced no usable "
+ "rows, or the holdout split cannot be scored."
+ )
+ ),
+ },
+ summary="Materialize training features to the sandbox",
+ description=(
+ "Run features_sql server-side against the labeled training population and write the resulting "
+ "train/holdout feature and label parquet files directly into this run's sandbox. Returns the local "
+ "sandbox paths, row counts, and feature columns. The rows never pass through the agent's context and "
+ "there is no 500-row cap. Read the returned paths with pd.read_parquet and iterate in Python."
+ ),
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="materialize-features",
+ required_scopes=["autoresearch:write", "query:read"],
+ )
+ def materialize_features(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ try:
+ result = api.materialize_features(
+ self.team_id,
+ self.kwargs["pk"],
+ pipeline_id=_parent_pipeline_id(self),
+ features_sql=request.validated_data["features_sql"],
+ user=cast(User, request.user),
+ )
+ except TrainingRunNotFound:
+ raise NotFound("Training run not found.")
+ except AutoresearchConflict as exc:
+ raise ValidationError(str(exc)) from exc
+ logger.info(
+ "autoresearch_features_materialized_to_sandbox",
+ training_run_id=str(self.kwargs["pk"]),
+ n_train=result.n_train,
+ n_holdout=result.n_holdout,
+ n_features=result.n_features,
+ )
+ return Response(MaterializeFeaturesResponseSerializer(instance=result).data)
+
@validated_request(
request_serializer=CompleteTrainingRunSerializer,
responses={
@@ -577,3 +663,128 @@ class AutoresearchTrainingRunViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMi
except PipelineNotFound as exc:
raise NotFound(str(exc)) from exc
return Response(TrainingRunHistorySerializer(instance=history).data)
+
+ @extend_schema(
+ responses={
+ 200: OpenApiResponse(
+ response=ArtifactListSerializer,
+ description="The relative paths of every file in this run's artifact bundle.",
+ ),
+ },
+ summary="List artifact bundle files",
+ description=(
+ "List the files an agent has uploaded for this training run's artifact bundle "
+ "(train.py, predict.py, features.sql, and any eda/ notebooks)."
+ ),
+ )
+ @action(detail=True, methods=["get"], url_path="artifacts")
+ def list_artifacts(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ try:
+ listing = api.list_artifacts(self.team_id, self.kwargs["pk"], pipeline_id=_parent_pipeline_id(self))
+ except TrainingRunNotFound:
+ raise NotFound("Training run not found.")
+ return Response(ArtifactListSerializer(instance=listing).data)
+
+ @validated_request(
+ request_serializer=ArtifactUploadSerializer,
+ responses={
+ 201: OpenApiResponse(
+ response=StoredArtifactSerializer,
+ description="The stored file's path, size, and content hash.",
+ ),
+ 400: OpenApiResponse(
+ description=(
+ "Invalid or reserved path, content is not base64, file exceeds the size limit, the bundle "
+ "holds its maximum number of files, or the run is no longer running."
+ )
+ ),
+ 503: OpenApiResponse(description="Object storage is unavailable; nothing was stored."),
+ },
+ summary="Upload an artifact bundle file",
+ description=(
+ "Upload one file of this training run's artifact bundle. Send the file contents "
+ "base64-encoded in content_base64. Re-uploading the same path overwrites it. "
+ "Use this — not curl/set_output — to author train.py, predict.py, and features.sql. "
+ "The bundle is frozen once the run completes or fails."
+ ),
+ )
+ @action(detail=True, methods=["post"], url_path="artifacts/upload")
+ def upload_artifact(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ data = request.validated_data
+ try:
+ stored = api.write_artifact(
+ self.team_id,
+ self.kwargs["pk"],
+ pipeline_id=_parent_pipeline_id(self),
+ path=data["path"],
+ content_base64=data["content_base64"],
+ )
+ except TrainingRunNotFound:
+ raise NotFound("Training run not found.")
+ except (AutoresearchConflict, InvalidArtifactPath) as exc:
+ raise ValidationError(str(exc)) from exc
+ except ArtifactStorageUnavailable as exc:
+ raise ArtifactStorageUnavailableError(str(exc)) from exc
+ return Response(StoredArtifactSerializer(instance=stored).data, status=201)
+
+ @validated_request(
+ request_serializer=ArtifactPathSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=ArtifactContentSerializer,
+ description="The file's content, base64-encoded, with its size and hash.",
+ ),
+ 404: OpenApiResponse(description="No file at that path in this run's bundle."),
+ },
+ summary="Get an artifact bundle file",
+ description="Fetch one file from this training run's artifact bundle, base64-encoded.",
+ )
+ @action(detail=True, methods=["post"], url_path="artifacts/get")
+ def get_artifact(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ try:
+ content = api.read_artifact(
+ self.team_id,
+ self.kwargs["pk"],
+ pipeline_id=_parent_pipeline_id(self),
+ path=request.validated_data["path"],
+ )
+ except TrainingRunNotFound:
+ raise NotFound("Training run not found.")
+ except InvalidArtifactPath as exc:
+ raise ValidationError(str(exc)) from exc
+ except ArtifactNotFound as exc:
+ raise NotFound(str(exc)) from exc
+ return Response(ArtifactContentSerializer(instance=content).data)
+
+ @validated_request(
+ request_serializer=ArtifactPathSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=ArtifactDeleteResultSerializer,
+ description="Whether a file existed at that path and was removed.",
+ ),
+ 400: OpenApiResponse(description="Invalid path, or the run is no longer running."),
+ 503: OpenApiResponse(description="Object storage is unavailable; nothing was deleted."),
+ },
+ summary="Delete an artifact bundle file",
+ description=(
+ "Remove one file from this training run's artifact bundle. Idempotent — deleting a missing "
+ "file is a no-op. The bundle is frozen once the run completes or fails."
+ ),
+ )
+ @action(detail=True, methods=["post"], url_path="artifacts/delete")
+ def delete_artifact(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ try:
+ result = api.delete_artifact(
+ self.team_id,
+ self.kwargs["pk"],
+ pipeline_id=_parent_pipeline_id(self),
+ path=request.validated_data["path"],
+ )
+ except TrainingRunNotFound:
+ raise NotFound("Training run not found.")
+ except (AutoresearchConflict, InvalidArtifactPath) as exc:
+ raise ValidationError(str(exc)) from exc
+ except ArtifactStorageUnavailable as exc:
+ raise ArtifactStorageUnavailableError(str(exc)) from exc
+ return Response(ArtifactDeleteResultSerializer(instance=result).data)
diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.py
index 960aae1b9e84..700112a08ce7 100644
--- a/products/autoresearch/backend/tests/test_api.py
+++ b/products/autoresearch/backend/tests/test_api.py
@@ -1,16 +1,20 @@
import uuid
+import base64
from typing import Any
import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
+from django.db import connection
from django.test import SimpleTestCase
+from django.test.utils import CaptureQueriesContext
from parameterized import parameterized
from rest_framework import status
from posthog.models import Organization, Team
+from posthog.storage.object_storage import ObjectStorageError
from products.actions.backend.models.action import Action
from products.autoresearch.backend.dataset.templates import TEMPLATES
@@ -568,6 +572,189 @@ class TestValidationWarningSerializer(SimpleTestCase):
assert all(f"'{code}'" in help_text for code in VALIDATION_WARNING_CODES)
+class _InMemoryStorage:
+ 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 None
+
+
+class TestAutoresearchArtifactAPI(TeamScopedTestMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.base_url = f"/api/projects/{self.team.pk}/autoresearch"
+ 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._storage_patcher = patch(
+ "products.autoresearch.backend.training.artifacts.object_storage",
+ _InMemoryStorage(),
+ )
+ self._storage_patcher.start()
+ self.addCleanup(self._storage_patcher.stop)
+
+ self.pipeline = AutoresearchPipeline.objects.create(
+ team=self.team,
+ created_by=self.user,
+ name="Artifacts Pipeline",
+ target_event="$pageview",
+ horizon_days=7,
+ )
+ self.training_run = AutoresearchTrainingRun.objects.create(
+ pipeline=self.pipeline, status="running", iteration_count=0
+ )
+
+ def _artifacts_url(self, suffix: str = "") -> str:
+ return f"{self.base_url}/{self.pipeline.id}/training_runs/{self.training_run.id}/artifacts{suffix}"
+
+ def _upload(self, path: str, body: bytes):
+ return self.client.post(
+ self._artifacts_url("/upload"),
+ {"path": path, "content_base64": base64.b64encode(body).decode("ascii")},
+ format="json",
+ )
+
+ def test_upload_then_get_roundtrip(self):
+ with CaptureQueriesContext(connection) as queries:
+ resp = self._upload("train.py", b"print('train')")
+ assert resp.status_code == status.HTTP_201_CREATED, resp.content
+ # The write happens under the run row lock completion takes, so it cannot land on a frozen bundle.
+ assert any("FOR UPDATE" in q["sql"] for q in queries.captured_queries)
+ assert resp.json()["path"] == "train.py"
+ assert resp.json()["size_bytes"] == 14
+
+ resp = self.client.post(self._artifacts_url("/get"), {"path": "train.py"}, format="json")
+ assert resp.status_code == status.HTTP_200_OK
+ assert base64.b64decode(resp.json()["content_base64"]) == b"print('train')"
+
+ def test_list_artifacts(self):
+ self._upload("train.py", b"a")
+ self._upload("predict.py", b"b")
+ resp = self.client.get(self._artifacts_url())
+ assert resp.status_code == status.HTTP_200_OK
+ data = resp.json()
+ assert data["count"] == 2
+ assert sorted(data["paths"]) == ["predict.py", "train.py"]
+
+ def test_delete_artifact(self):
+ self._upload("train.py", b"a")
+ resp = self.client.post(self._artifacts_url("/delete"), {"path": "train.py"}, format="json")
+ assert resp.status_code == status.HTTP_200_OK
+ assert resp.json()["deleted"] is True
+ resp = self.client.post(self._artifacts_url("/delete"), {"path": "train.py"}, format="json")
+ assert resp.json()["deleted"] is False
+
+ def test_bundle_frozen_once_run_is_no_longer_running(self):
+ self._upload("train.py", b"print('train')")
+ self.training_run.status = AutoresearchTrainingRun.Status.COMPLETED
+ self.training_run.save(update_fields=["status"])
+
+ resp = self._upload("predict.py", b"print('predict')")
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+
+ resp = self.client.post(self._artifacts_url("/delete"), {"path": "train.py"}, format="json")
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+
+ # Reads stay open — inference and future runs still consume the frozen bundle.
+ resp = self.client.post(self._artifacts_url("/get"), {"path": "train.py"}, format="json")
+ assert resp.status_code == status.HTTP_200_OK
+
+ def test_features_sql_must_be_runnable(self):
+ runnable = b"SELECT a.person_id AS distinct_id, count() AS c FROM {anchors} a GROUP BY a.person_id"
+ resp = self._upload("features.sql", runnable + b" LIMIT 10")
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert "LIMIT" in str(resp.json())
+ assert self._upload("features.sql", runnable).status_code == status.HTTP_201_CREATED
+
+ def test_model_pkl_cannot_be_uploaded(self):
+ resp = self._upload("model.pkl", b"\x80\x04")
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert "model.pkl" in str(resp.json())
+
+ @patch("products.autoresearch.backend.facade.api.MAX_BUNDLE_FILES", 2)
+ def test_bundle_file_count_is_capped(self):
+ assert self._upload("train.py", b"a").status_code == status.HTTP_201_CREATED
+ assert self._upload("predict.py", b"b").status_code == status.HTTP_201_CREATED
+ resp = self._upload("eda/notes.md", b"c")
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert "2 files" in str(resp.json())
+ # Overwriting a file that is already in the bundle does not count against the cap.
+ assert self._upload("train.py", b"a2").status_code == status.HTTP_201_CREATED
+
+ @parameterized.expand([("upload",), ("delete",)])
+ def test_storage_failure_is_a_503(self, action: str):
+ self._upload("train.py", b"a")
+ storage = self._storage_patcher.new
+ with (
+ patch.object(storage, "write", side_effect=ObjectStorageError("s3 down")),
+ patch.object(storage, "delete", side_effect=ObjectStorageError("s3 down")),
+ ):
+ if action == "upload":
+ resp = self._upload("predict.py", b"b")
+ else:
+ resp = self.client.post(self._artifacts_url("/delete"), {"path": "train.py"}, format="json")
+ assert resp.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+ assert "s3 down" in str(resp.json())
+
+ @parameterized.expand([("list",), ("upload",)])
+ def test_artifact_routes_are_scoped_to_the_parent_pipeline(self, action: str):
+ other_pipeline = AutoresearchPipeline.objects.create(
+ team=self.team, created_by=self.user, name="Other", target_event="$pageview", horizon_days=7
+ )
+ url = f"{self.base_url}/{other_pipeline.id}/training_runs/{self.training_run.id}/artifacts"
+ if action == "list":
+ resp = self.client.get(url)
+ else:
+ resp = self.client.post(f"{url}/upload", {"path": "train.py", "content_base64": "YQ=="}, format="json")
+ assert resp.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_get_missing_returns_404(self):
+ resp = self.client.post(self._artifacts_url("/get"), {"path": "nope.py"}, format="json")
+ assert resp.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_invalid_path_rejected(self):
+ resp = self._upload("../escape.py", b"a")
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_invalid_base64_rejected(self):
+ resp = self.client.post(
+ self._artifacts_url("/upload"),
+ {"path": "train.py", "content_base64": "not base64!!!"},
+ format="json",
+ )
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_training_run_from_other_team_returns_404(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
+ )
+ other_run = AutoresearchTrainingRun.objects.create(pipeline=other_pipeline, status="running")
+ # The viewset filters by request team; another team's run is not reachable here.
+ resp = self.client.get(f"{self.base_url}/{other_pipeline.id}/training_runs/{other_run.id}/artifacts")
+ assert resp.status_code in (status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND)
+
+
class TestPipelineCreateSerializerValidation(SimpleTestCase):
# Field- and target-shape validation runs in memory, so these cases never need a DB.
# The endpoint wiring (bad body -> 400) is covered by the APIBaseTest create tests above.
diff --git a/products/autoresearch/backend/training/promotion.py b/products/autoresearch/backend/training/promotion.py
index baeb6612a885..f2192fb410df 100644
--- a/products/autoresearch/backend/training/promotion.py
+++ b/products/autoresearch/backend/training/promotion.py
@@ -38,11 +38,7 @@ from products.autoresearch.backend.models import (
AutoresearchTrainingRun,
)
from products.autoresearch.backend.training import artifacts
-from products.autoresearch.backend.training.recipe_validation import (
- RecipeValidationError,
- validate_feature_sql,
- validate_model_class,
-)
+from products.autoresearch.backend.training.recipe_validation import RecipeValidationError, validate_model_class
logger = structlog.get_logger(__name__)
@@ -293,10 +289,11 @@ def _read_uploaded_bundle(training_run: AutoresearchTrainingRun) -> artifacts.Ar
logger.exception("autoresearch_bundle_read_failed", training_run_id=str(training_run.id), prefix=prefix)
raise
# The uploaded features.sql is what fitting and scoring actually execute, and the agent
- # can upload SQL that never went through iteration recording — validate the real file.
+ # can upload SQL that never went through iteration recording — validate the real file,
+ # with the rule inference adds, so a champion is never committed with SQL its fit refuses.
try:
- validate_feature_sql(bundle.features_sql)
- except RecipeValidationError as exc:
+ validate_runnable_feature_sql(bundle.features_sql, source="features.sql")
+ except SandboxInferenceError as exc:
raise PromotionError(f"Uploaded bundle's features.sql failed validation: {exc}") from exc
return bundle
@@ -320,12 +317,8 @@ def complete_training_run(
current = AutoresearchTrainingRun.objects.select_related("pipeline").get(pk=training_run.pk)
if current.status not in _FINALIZABLE_STATUSES:
return _already_finalized(current)
- # Reading the bundle is three object-storage calls. It happens before the transaction
- # so a slow or unavailable store cannot hold the training run and its pipeline locked.
- bundle = _read_uploaded_bundle(current)
return _finalize_under_lock(
current,
- bundle=bundle,
best_iteration_id=best_iteration_id,
model_explanation=model_explanation,
recommended_next=recommended_next,
@@ -367,7 +360,6 @@ def _schedule_champion_fit(*, pipeline: AutoresearchPipeline, prefix: str, train
def _finalize_under_lock(
training_run: AutoresearchTrainingRun,
*,
- bundle: artifacts.ArtifactBundle | None,
best_iteration_id: UUID | None,
model_explanation: dict[str, Any] | None,
recommended_next: str,
@@ -382,6 +374,11 @@ def _finalize_under_lock(
)
if training_run.status not in _FINALIZABLE_STATUSES:
return _already_finalized(training_run)
+ # The artifact endpoints write the bundle under this same row lock, so a bundle read here
+ # is the bundle the champion will point at. Read before the lock, an upload landing in
+ # between would be fitted without ever being validated. The cost is three object-storage
+ # reads of agent-authored text while the row is locked.
+ bundle = _read_uploaded_bundle(training_run)
pipeline = training_run.pipeline
now = django_timezone.now()
diff --git a/products/autoresearch/backend/training/test_promotion.py b/products/autoresearch/backend/training/test_promotion.py
index ba1ac098b1d2..f74aa77cc799 100644
--- a/products/autoresearch/backend/training/test_promotion.py
+++ b/products/autoresearch/backend/training/test_promotion.py
@@ -4,6 +4,8 @@ import hashlib
from posthog.test.base import BaseTest
from unittest.mock import patch
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
from django.utils import timezone as django_timezone
from parameterized import parameterized
@@ -242,7 +244,17 @@ class TestCompleteTrainingRun(TeamScopedTestMixin, BaseTest):
# different model.
reformatted = ANCHORED_FEATURE_SQL.replace(" FROM ", "\n FROM ") + "\n"
bundle = ArtifactBundle(train_py="pass", predict_py="pass", features_sql=reformatted)
- with patch("products.autoresearch.backend.training.artifacts.read_bundle", return_value=bundle):
+
+ def read_under_the_run_lock(prefix: str) -> ArtifactBundle:
+ # The artifact endpoints write under the run row lock, so a bundle read before it
+ # can be replaced before the champion points at it.
+ assert any("FOR UPDATE" in q["sql"] for q in queries.captured_queries)
+ return bundle
+
+ with (
+ CaptureQueriesContext(connection) as queries,
+ patch("products.autoresearch.backend.training.artifacts.read_bundle", side_effect=read_under_the_run_lock),
+ ):
result = complete_training_run(run)
assert result["promoted"] is True
@@ -284,18 +296,22 @@ class TestCompleteTrainingRun(TeamScopedTestMixin, BaseTest):
assert result["promoted"] is True
assert self._champion().holdout_score == 0.105
- def test_bundle_sql_without_anchors_blocks_promotion(self):
- # The uploaded features.sql is what fitting runs, so SQL without {anchors} reads the
- # outcome window whatever the iteration recorded.
+ @parameterized.expand(
+ [
+ # SQL without {anchors} reads the outcome window whatever the iteration recorded.
+ ("no_anchors", "SELECT person_id AS distinct_id, count() AS c FROM events GROUP BY person_id"),
+ # Recording accepts a trailing LIMIT, but the fit appends its own and refuses the query,
+ # which would leave the champion without a model.
+ ("trailing_limit", ANCHORED_FEATURE_SQL + " LIMIT 10"),
+ ]
+ )
+ def test_bundle_sql_the_fit_cannot_run_blocks_promotion(self, _name, features_sql):
+ # The uploaded features.sql is what fitting runs.
run = self._run()
- self._iteration(run, number=0, holdout=0.8)
+ self._iteration(run, number=0, holdout=0.8, feature_sql=features_sql)
- leaky = ArtifactBundle(
- train_py="pass",
- predict_py="pass",
- features_sql="SELECT person_id AS distinct_id, count() AS c FROM events GROUP BY person_id",
- )
- with patch("products.autoresearch.backend.training.artifacts.read_bundle", return_value=leaky):
+ bundle = ArtifactBundle(train_py="pass", predict_py="pass", features_sql=features_sql)
+ with patch("products.autoresearch.backend.training.artifacts.read_bundle", return_value=bundle):
with self.assertRaises(PromotionError):
complete_training_run(run)
diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.ts
index 261ae3db6ff9..9ed49fafee00 100644
--- a/products/autoresearch/frontend/generated/api.schemas.ts
+++ b/products/autoresearch/frontend/generated/api.schemas.ts
@@ -682,6 +682,76 @@ export interface OpenTrainingRunApi {
iteration_budget?: number
}
+/**
+ * The relative paths present in a training run's bundle.
+ */
+export interface ArtifactListApi {
+ /** Relative paths of every file stored under this training run's bundle prefix. */
+ paths: string[]
+ /** Number of files in the bundle. */
+ count: number
+}
+
+/**
+ * Input for fetching or deleting one bundle file by path.
+ */
+export interface ArtifactPathApi {
+ /**
+ * Relative path of the file within the bundle, e.g. 'train.py'.
+ * @maxLength 500
+ */
+ path: string
+}
+
+/**
+ * Whether a delete removed an existing file.
+ */
+export interface ArtifactDeleteResultApi {
+ /** Relative path targeted for deletion. */
+ path: string
+ /** True if a file existed and was removed; False if nothing was there. */
+ deleted: boolean
+}
+
+/**
+ * A single bundle file's content, base64-encoded.
+ */
+export interface ArtifactContentApi {
+ /** Relative path of the file within the bundle. */
+ path: string
+ /** File size in bytes. */
+ size_bytes: number
+ /** SHA-256 hex digest of the file content. */
+ sha256: string
+ /** File contents, base64-encoded. */
+ content_base64: string
+}
+
+/**
+ * Input for uploading one file of a training run's artifact bundle.
+ */
+export interface ArtifactUploadApi {
+ /**
+ * Relative path within the bundle, e.g. 'train.py', 'predict.py', 'features.sql', or 'eda/iter-3-gbm.ipynb'. Segments are limited to [A-Za-z0-9_.-]; absolute paths and '..' traversal are rejected.
+ * @maxLength 500
+ */
+ path: string
+ /** File contents, base64-encoded. Decoded server-side and written to object storage. Max 10 MB decoded. */
+ content_base64: string
+}
+
+/**
+ * Result of an upload: where the file landed and its content hash.
+ */
+export interface StoredArtifactApi {
+ /** Relative path the file was stored at. */
+ path: string
+ /** Decoded file size in bytes. */
+ size_bytes: number
+ /** SHA-256 hex digest of the decoded file content. */
+ sha256: string
+}
+
/**
* Global feature importance / directionality bundle for the champion model card.
*/
@@ -879,6 +949,36 @@ export interface AutoresearchIterationApi {
readonly created_at: string
}
+/**
+ * Input for materializing the labeled training feature matrix into the run's sandbox.
+ */
+export interface MaterializeFeaturesRequestApi {
+ /** Your HogQL feature query, using the {anchors}/{lookback_days} contract. Must be a read-only SELECT keyed on person_id (aliased to distinct_id), one row per user. The backend runs it server-side against the labeled training population — no 500-row cap — and writes the resulting train/holdout feature and label parquet files into your sandbox. */
+ features_sql: string
+}
+
+/**
+ * The local sandbox paths and shape of the materialized training matrix.
+ */
+export interface MaterializeFeaturesResponseApi {
+ /** Sandbox path to the training feature matrix parquet (distinct_id + numeric feature columns). */
+ train_features_path: string
+ /** Sandbox path to the training labels parquet (distinct_id + __label). */
+ train_labels_path: string
+ /** Sandbox path to the holdout feature matrix parquet (same columns as train_features). */
+ holdout_features_path: string
+ /** Sandbox path to the holdout labels parquet (distinct_id + __label). */
+ holdout_labels_path: string
+ /** Number of rows in the training split. */
+ n_train: number
+ /** Number of rows in the holdout split. */
+ n_holdout: number
+ /** Number of numeric feature columns produced by features_sql. */
+ n_features: number
+ /** The numeric feature column names (excludes distinct_id, __label, __fold). */
+ feature_cols: string[]
+}
+
/**
* Keyword arguments for the estimator's constructor; null or absent means the defaults.
* @nullable
diff --git a/products/autoresearch/frontend/generated/api.ts b/products/autoresearch/frontend/generated/api.ts
index 11722557d192..b9070d20929e 100644
--- a/products/autoresearch/frontend/generated/api.ts
+++ b/products/autoresearch/frontend/generated/api.ts
@@ -9,6 +9,11 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ ArtifactContentApi,
+ ArtifactDeleteResultApi,
+ ArtifactListApi,
+ ArtifactPathApi,
+ ArtifactUploadApi,
AutoresearchIterationApi,
AutoresearchListParams,
AutoresearchModelApi,
@@ -21,6 +26,8 @@ import type {
AutoresearchTrainingRunsHistoryRetrieveParams,
AutoresearchTrainingRunsListParams,
CompleteTrainingRunApi,
+ MaterializeFeaturesRequestApi,
+ MaterializeFeaturesResponseApi,
OpenTrainingRunApi,
PaginatedAutoresearchModelListApi,
PaginatedAutoresearchPipelineListApi,
@@ -30,6 +37,7 @@ import type {
RecordIterationApi,
ResolveTemplateRequestApi,
ResolvedTemplateApi,
+ StoredArtifactApi,
TemplateInfoApi,
TrainingRunHistoryApi,
ValidatePipelineRequestApi,
@@ -295,6 +303,109 @@ export const autoresearchTrainingRunsRetrieve = async (
})
}
+export const getAutoresearchTrainingRunsArtifactsRetrieveUrl = (projectId: string, pipelineId: string, id: string) => {
+ return `/api/projects/${projectId}/autoresearch/${pipelineId}/training_runs/${id}/artifacts/`
+}
+
+/**
+ * List the files an agent has uploaded for this training run's artifact bundle (train.py, predict.py, features.sql, and any eda/ notebooks).
+ * @summary List artifact bundle files
+ */
+export const autoresearchTrainingRunsArtifactsRetrieve = async (
+ projectId: string,
+ pipelineId: string,
+ id: string,
+ options?: RequestInit
+): Promise<ArtifactListApi> => {
+ return apiMutator<ArtifactListApi>(getAutoresearchTrainingRunsArtifactsRetrieveUrl(projectId, pipelineId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAutoresearchTrainingRunsArtifactsDeleteCreateUrl = (
+ projectId: string,
+ pipelineId: string,
+ id: string
+) => {
+ return `/api/projects/${projectId}/autoresearch/${pipelineId}/training_runs/${id}/artifacts/delete/`
+}
+
+/**
+ * Remove one file from this training run's artifact bundle. Idempotent — deleting a missing file is a no-op. The bundle is frozen once the run completes or fails.
+ * @summary Delete an artifact bundle file
+ */
+export const autoresearchTrainingRunsArtifactsDeleteCreate = async (
+ projectId: string,
+ pipelineId: string,
+ id: string,
+ artifactPathApi: ArtifactPathApi,
+ options?: RequestInit
+): Promise<ArtifactDeleteResultApi> => {
+ return apiMutator<ArtifactDeleteResultApi>(
+ getAutoresearchTrainingRunsArtifactsDeleteCreateUrl(projectId, pipelineId, id),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(artifactPathApi),
+ }
+ )
+}
+
+export const getAutoresearchTrainingRunsArtifactsGetCreateUrl = (projectId: string, pipelineId: string, id: string) => {
+ return `/api/projects/${projectId}/autoresearch/${pipelineId}/training_runs/${id}/artifacts/get/`
+}
+
+/**
+ * Fetch one file from this training run's artifact bundle, base64-encoded.
+ * @summary Get an artifact bundle file
+ */
+export const autoresearchTrainingRunsArtifactsGetCreate = async (
+ projectId: string,
+ pipelineId: string,
+ id: string,
+ artifactPathApi: ArtifactPathApi,
+ options?: RequestInit
+): Promise<ArtifactContentApi> => {
+ return apiMutator<ArtifactContentApi>(getAutoresearchTrainingRunsArtifactsGetCreateUrl(projectId, pipelineId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(artifactPathApi),
+ })
+}
+
+export const getAutoresearchTrainingRunsArtifactsUploadCreateUrl = (
+ projectId: string,
+ pipelineId: string,
+ id: string
+) => {
+ return `/api/projects/${projectId}/autoresearch/${pipelineId}/training_runs/${id}/artifacts/upload/`
+}
+
+/**
+ * Upload one file of this training run's artifact bundle. Send the file contents base64-encoded in content_base64. Re-uploading the same path overwrites it. Use this — not curl/set_output — to author train.py, predict.py, and features.sql. The bundle is frozen once the run completes or fails.
+ * @summary Upload an artifact bundle file
+ */
+export const autoresearchTrainingRunsArtifactsUploadCreate = async (
+ projectId: string,
+ pipelineId: string,
+ id: string,
+ artifactUploadApi: ArtifactUploadApi,
+ options?: RequestInit
+): Promise<StoredArtifactApi> => {
+ return apiMutator<StoredArtifactApi>(
+ getAutoresearchTrainingRunsArtifactsUploadCreateUrl(projectId, pipelineId, id),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(artifactUploadApi),
+ }
+ )
+}
+
export const getAutoresearchTrainingRunsCompleteCreateUrl = (projectId: string, pipelineId: string, id: string) => {
return `/api/projects/${projectId}/autoresearch/${pipelineId}/training_runs/${id}/complete/`
}
@@ -347,6 +458,36 @@ export const autoresearchTrainingRunsIterationsCreate = async (
)
}
+export const getAutoresearchTrainingRunsMaterializeFeaturesCreateUrl = (
+ projectId: string,
+ pipelineId: string,
+ id: string
+) => {
+ return `/api/projects/${projectId}/autoresearch/${pipelineId}/training_runs/${id}/materialize-features/`
+}
+
+/**
+ * Run features_sql server-side against the labeled training population and write the resulting train/holdout feature and label parquet files directly into this run's sandbox. Returns the local sandbox paths, row counts, and feature columns. The rows never pass through the agent's context and there is no 500-row cap. Read the returned paths with pd.read_parquet and iterate in Python.
+ * @summary Materialize training features to the sandbox
+ */
+export const autoresearchTrainingRunsMaterializeFeaturesCreate = async (
+ projectId: string,
+ pipelineId: string,
+ id: string,
+ materializeFeaturesRequestApi: MaterializeFeaturesRequestApi,
+ options?: RequestInit
+): Promise<MaterializeFeaturesResponseApi> => {
+ return apiMutator<MaterializeFeaturesResponseApi>(
+ getAutoresearchTrainingRunsMaterializeFeaturesCreateUrl(projectId, pipelineId, id),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(materializeFeaturesRequestApi),
+ }
+ )
+}
+
export const getAutoresearchTrainingRunsHistoryRetrieveUrl = (
projectId: string,
pipelineId: string,
diff --git a/products/autoresearch/frontend/generated/api.zod.ts b/products/autoresearch/frontend/generated/api.zod.ts
index cae263588a65..8b584b5a206c 100644
--- a/products/autoresearch/frontend/generated/api.zod.ts
+++ b/products/autoresearch/frontend/generated/api.zod.ts
@@ -138,6 +138,58 @@ export const AutoresearchTrainingRunsCreateBody = /* @__PURE__ */ zod
})
.describe('Input for opening an agent-driven training run.')
+/**
+ * Remove one file from this training run's artifact bundle. Idempotent — deleting a missing file is a no-op. The bundle is frozen once the run completes or fails.
+ * @summary Delete an artifact bundle file
+ */
+export const autoresearchTrainingRunsArtifactsDeleteCreateBodyPathMax = 500
+
+export const AutoresearchTrainingRunsArtifactsDeleteCreateBody = /* @__PURE__ */ zod
+ .object({
+ path: zod
+ .string()
+ .max(autoresearchTrainingRunsArtifactsDeleteCreateBodyPathMax)
+ .describe("Relative path of the file within the bundle, e.g. 'train.py'."),
+ })
+ .describe('Input for fetching or deleting one bundle file by path.')
+
+/**
+ * Fetch one file from this training run's artifact bundle, base64-encoded.
+ * @summary Get an artifact bundle file
+ */
+export const autoresearchTrainingRunsArtifactsGetCreateBodyPathMax = 500
+
+export const AutoresearchTrainingRunsArtifactsGetCreateBody = /* @__PURE__ */ zod
+ .object({
+ path: zod
+ .string()
+ .max(autoresearchTrainingRunsArtifactsGetCreateBodyPathMax)
+ .describe("Relative path of the file within the bundle, e.g. 'train.py'."),
+ })
+ .describe('Input for fetching or deleting one bundle file by path.')
+
+/**
+ * Upload one file of this training run's artifact bundle. Send the file contents base64-encoded in content_base64. Re-uploading the same path overwrites it. Use this — not curl/set_output — to author train.py, predict.py, and features.sql. The bundle is frozen once the run completes or fails.
+ * @summary Upload an artifact bundle file
+ */
+export const autoresearchTrainingRunsArtifactsUploadCreateBodyPathMax = 500
+
+export const AutoresearchTrainingRunsArtifactsUploadCreateBody = /* @__PURE__ */ zod
+ .object({
+ path: zod
+ .string()
+ .max(autoresearchTrainingRunsArtifactsUploadCreateBodyPathMax)
+ .describe(
+ "Relative path within the bundle, e.g. 'train.py', 'predict.py', 'features.sql', or 'eda\/iter-3-gbm.ipynb'. Segments are limited to [A-Za-z0-9_.-]; absolute paths and '..' traversal are rejected."
+ ),
+ content_base64: zod
+ .string()
+ .describe(
+ 'File contents, base64-encoded. Decoded server-side and written to object storage. Max 10 MB decoded.'
+ ),
+ })
+ .describe("Input for uploading one file of a training run's artifact bundle.")
+
/**
* 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
@@ -269,6 +321,20 @@ export const AutoresearchTrainingRunsIterationsCreateBody = /* @__PURE__ */ zod
})
.describe('Input for recording one training iteration. Validated against the recipe allowlist.')
+/**
+ * Run features_sql server-side against the labeled training population and write the resulting train/holdout feature and label parquet files directly into this run's sandbox. Returns the local sandbox paths, row counts, and feature columns. The rows never pass through the agent's context and there is no 500-row cap. Read the returned paths with pd.read_parquet and iterate in Python.
+ * @summary Materialize training features to the sandbox
+ */
+export const AutoresearchTrainingRunsMaterializeFeaturesCreateBody = /* @__PURE__ */ zod
+ .object({
+ features_sql: zod
+ .string()
+ .describe(
+ 'Your HogQL feature query, using the {anchors}\/{lookback_days} contract. Must be a read-only SELECT keyed on person_id (aliased to distinct_id), one row per user. The backend runs it server-side against the labeled training population — no 500-row cap — and writes the resulting train\/holdout feature and label parquet files into your sandbox.'
+ ),
+ })
+ .describe("Input for materializing the labeled training feature matrix into the run's sandbox.")
+
/**
* Manage autoresearch prediction pipelines.
*
diff --git a/products/tasks/backend/facade/sandbox.py b/products/tasks/backend/facade/sandbox.py
index c980b8d92c42..14b0730c9c6f 100644
--- a/products/tasks/backend/facade/sandbox.py
+++ b/products/tasks/backend/facade/sandbox.py
@@ -25,6 +25,7 @@ from products.tasks.backend.logic.services.sandbox import (
SandboxTemplate,
get_sandbox_class,
get_sandbox_class_for_backend,
+ get_sandbox_class_for_sandbox_id,
is_public_sandbox_repo,
sandbox_repo_path,
)
@@ -45,6 +46,7 @@ __all__ = [
"SandboxTimeoutError",
"get_sandbox_class",
"get_sandbox_class_for_backend",
+ "get_sandbox_class_for_sandbox_id",
"is_public_sandbox_repo",
"sandbox_repo_path",
]
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2177952ebd79..f3ade8079599 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -11143,6 +11143,51 @@ export namespace Schemas {
download_url: string | null;
}
+ /**
+ * A single bundle file's content, base64-encoded.
+ */
+ export interface ArtifactContent {
+ /** Relative path of the file within the bundle. */
+ path: string;
+ /** File size in bytes. */
+ size_bytes: number;
+ /** SHA-256 hex digest of the file content. */
+ sha256: string;
+ /** File contents, base64-encoded. */
+ content_base64: string;
+ }
+
+ /**
+ * Whether a delete removed an existing file.
+ */
+ export interface ArtifactDeleteResult {
+ /** Relative path targeted for deletion. */
+ path: string;
+ /** True if a file existed and was removed; False if nothing was there. */
+ deleted: boolean;
+ }
+
+ /**
+ * The relative paths present in a training run's bundle.
+ */
+ export interface ArtifactList {
+ /** Relative paths of every file stored under this training run's bundle prefix. */
+ paths: string[];
+ /** Number of files in the bundle. */
+ count: number;
+ }
+
+ /**
+ * Input for fetching or deleting one bundle file by path.
+ */
+ export interface ArtifactPath {
+ /**
+ * Relative path of the file within the bundle, e.g. 'train.py'.
+ * @maxLength 500
+ */
+ path: string;
+ }
+
/**
* * `slack_message` - slack_message
* * `slack_canvas` - slack_canvas
@@ -11165,6 +11210,19 @@ export namespace Schemas {
GithubPr: 'github_pr',
} as const;
+ /**
+ * Input for uploading one file of a training run's artifact bundle.
+ */
+ export interface ArtifactUpload {
+ /**
+ * Relative path within the bundle, e.g. 'train.py', 'predict.py', 'features.sql', or 'eda/iter-3-gbm.ipynb'. Segments are limited to [A-Za-z0-9_.-]; absolute paths and '..' traversal are rejected.
+ * @maxLength 500
+ */
+ path: string;
+ /** File contents, base64-encoded. Decoded server-side and written to object storage. Max 10 MB decoded. */
+ content_base64: string;
+ }
+
export interface AsknicelyFeedbackSignalExtra {
score: string | null;
status: string | null;
@@ -57738,6 +57796,36 @@ export namespace Schemas {
bucket_overrides?: MaterializationPreviewRequestBucketOverrides;
}
+ /**
+ * Input for materializing the labeled training feature matrix into the run's sandbox.
+ */
+ export interface MaterializeFeaturesRequest {
+ /** Your HogQL feature query, using the {anchors}/{lookback_days} contract. Must be a read-only SELECT keyed on person_id (aliased to distinct_id), one row per user. The backend runs it server-side against the labeled training population — no 500-row cap — and writes the resulting train/holdout feature and label parquet files into your sandbox. */
+ features_sql: string;
+ }
+
+ /**
+ * The local sandbox paths and shape of the materialized training matrix.
+ */
+ export interface MaterializeFeaturesResponse {
+ /** Sandbox path to the training feature matrix parquet (distinct_id + numeric feature columns). */
+ train_features_path: string;
+ /** Sandbox path to the training labels parquet (distinct_id + __label). */
+ train_labels_path: string;
+ /** Sandbox path to the holdout feature matrix parquet (same columns as train_features). */
+ holdout_features_path: string;
+ /** Sandbox path to the holdout labels parquet (distinct_id + __label). */
+ holdout_labels_path: string;
+ /** Number of rows in the training split. */
+ n_train: number;
+ /** Number of rows in the holdout split. */
+ n_holdout: number;
+ /** Number of numeric feature columns produced by features_sql. */
+ n_features: number;
+ /** The numeric feature column names (excludes distinct_id, __label, __fold). */
+ feature_cols: string[];
+ }
+
/**
* * `1` - event
* * `2` - person
@@ -92192,6 +92280,18 @@ export namespace Schemas {
readonly installations: readonly StamphogDiscoveredInstallation[];
}
+ /**
+ * Result of an upload: where the file landed and its content hash.
+ */
+ export interface StoredArtifact {
+ /** Relative path the file was stored at. */
+ path: string;
+ /** Decoded file size in bytes. */
+ size_bytes: number;
+ /** SHA-256 hex digest of the decoded file content. */
+ sha256: string;
+ }
+
/**
* Response containing a JWT token (and resolved base URL) for reading a task run's live event stream
*/