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 store and recipe validation (7/22) (#88795)

Andrew Maguired99df17c7d2e
diff --git a/products/autoresearch/backend/training/AGENTS.md b/products/autoresearch/backend/training/AGENTS.md
new file mode 100644
index 000000000000..3724dea99471
--- /dev/null
+++ b/products/autoresearch/backend/training/AGENTS.md
@@ -0,0 +1,69 @@
+# Training loop
+
+Finding a better model for a pipeline's question.
+One `run_training()` call → one `AutoresearchTrainingRun` → one sandbox agent session → zero or more `AutoresearchIteration` rows → at most one new champion `AutoresearchModel`.
+
+This is the expensive half of the product. A real run costs roughly a dollar in LLM spend and takes tens of minutes, so almost everything here is built around _not_ wasting a run: the stub path for plumbing tests, the safety net for agents that die mid-flight, and server-side champion selection so a confused agent cannot promote itself.
+
+The other half is `../inference/`, which consumes what this package produces and must never re-fit.
+
+This package landed ahead of its callers. `../presentation/`, `../temporal/`, `../management/`, and `../evaluation/` arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to them below describe where they will sit.
+
+## What lives here
+
+- `runner.py`
+ The real path. `run_training()` creates the `AutoresearchTrainingRun` (status `RUNNING`) and fires `Task.create_and_run()` with `internal=True` and no repository, so the run shows up as an internal Task rather than in the normal Tasks list.
+ `build_agent_description()` assembles the agent's brief — the target, the horizon, the population, and the contract for the bundle it must author.
+ The agent drives the rest _itself_ through the `autoresearch-*` MCP tools: it records each iteration, uploads the bundle, and calls complete. Nothing polls it.
+- `stub.py`
+ `run_stub_training()` — a hand-authored champion recipe with universal engagement features (event counts, distinct event types, days since first seen) that apply to any team and any target.
+ No agent, no LLM spend, deterministic. This is what `--stub` on `autoresearch_train` uses, and it is the right tool for testing anything downstream of training.
+- `ingestion.py`
+ The safety net. `handle_task_run_completed()` is called from the `TaskRun` `post_save` signal registered in `../apps.py`, and runs synchronously in the Temporal worker thread.
+ If the agent recorded iterations but never called complete, this finalizes through the same promotion path. If it recorded nothing, the run is marked failed — which is what produces `"Agent recorded no iterations before the run ended."`
+- `promotion.py`
+ Champion selection. `complete_training_run()` is the single entry point, used both by the training-run `complete` API action and by `ingestion.py`.
+ A challenger must beat the incumbent by `CHAMPION_PROMOTION_MARGIN` (0.005 holdout AUC) to be promoted — near-ties keep the incumbent rather than churning the champion on noise.
+ `_detect_uploaded_bundle()` decides whether the new model gets an `artifact_prefix` (bundle path) or only a recorded recipe (legacy path).
+- `artifacts.py`
+ Object storage for the bundle: `features.sql`, `train.py`, `predict.py`, plus the fitted `model.pkl` written at completion.
+ Keys are prefixed by team / pipeline / training-run (`bundle_prefix()`), so history is preserved naturally and bundles can never collide across tenants.
+ `normalize_artifact_path()`, `MAX_OBJECT_KEY_BYTES` (S3's 1024-byte key limit) and `MAX_ARTIFACT_BYTES` (10 MiB) are the guardrails on agent-supplied paths and sizes — the agent chooses these strings, so treat them as untrusted input.
+ An upload of one of the three bundle files is checked before it is acknowledged: the content must be non-empty UTF-8, and `features.sql` must pass `validate_feature_sql()`, because fitting and inference run the uploaded query rather than the recorded snapshot. A write raises `ObjectStorageError` when object storage is disabled instead of reporting a success the shared client silently dropped.
+- `recipe_validation.py`
+ Server-side validation of whatever an agent records. `validate_recipe()` first checks the shape of both JSON fields (objects, a string `model_class`, a string `feature_sql`), so malformed agent input is a validation error rather than a 500. `validate_feature_sql()` then parses the SQL and enforces the one-row-per-person contract on the AST: `{anchors}` must be a table in the top-level FROM (a placeholder inside a string literal or a comment does not count, because substitution only replaces it in code position, and behind a CTE the key could be transformed and renamed), the output columns are listed explicitly with exactly one `distinct_id` that is the anchors table's own `person_id` field, not an expression over it or a joined table's key, and none named `__label` or `__fold` (the training wrapper appends those), no reference to the wrapper's own CTEs (`labeled_users`, `labeled_anchors`, ...), which carry the label, and no wall-clock reads (`now()` in any case, aliases such as `current_timestamp()` that resolve to it, and bare keywords like `CURRENT_DATE`) because a window bound to "now" reads outcome-window events at training time (target leakage). It does not prove every event read is bounded by `cutoff_ts`; that remains the agent's contract. `validate_unique_distinct_ids()` re-checks the one-row-per-person contract on actual materialized rows, where duplicates first become visible; pass `expected_count` to also require one row per anchor, so an inner join cannot silently drop persons.
+ `validate_model_class()` is deliberately **not** applied at recording time — in the bundle world the agent's real model is arbitrary sandboxed code, so a recorded `model_class` is informational. The allowlist is enforced only where it is a genuine code-execution surface: the legacy in-process path in `../inference/scoring.py`, which resolves it through `importlib`.
+
+## Mental model
+
+The agent proposes, the backend disposes.
+
+1. `run_training()` inserts the run row and launches the sandbox. The run's id is handed to the agent so it can address its own run over MCP.
+2. The agent explores with HogQL, tries a feature set plus a model spec, evaluates on holdout, and records the result as an `AutoresearchIteration` with `status` `kept` or `discarded` and its own `agent_confidence`.
+ Recording is live — rows appear during the run, not in a batch at the end.
+3. When it is satisfied it uploads the bundle and calls complete.
+4. `complete_training_run()` reads the iterations, picks the best by holdout score, applies the promotion margin, and writes the `AutoresearchModel`.
+
+The agent's `status` on an iteration and its confidence are _evidence_, not a decision. `_select_best_iteration()` is what actually chooses.
+
+Two things routinely surprise people:
+
+- **`AutoresearchTrainingRun.iteration_count` is only written at completion.** Iteration rows land live, so a run in flight reads `0/5` with rows already in the table. Poll the rows, not the counter.
+- **`autoresearch_train` does not enforce `../dataset/validation.py`.** A target that fails validation on volume will still train. That is deliberate for local dev on thin datasets, but it means a run can "succeed" on far too few rows.
+
+## Where the rest of the system meets this package
+
+- **Launched by** — the `train` API action in `../presentation/views/views.py`, the `autoresearch_train` management command, and `activity_kickoff_training` in `../temporal/workflows.py`.
+- **Finalized by** — the `complete` action on the training-run viewset, or `ingestion.py` via the `TaskRun` `post_save` signal wired in `../apps.py`.
+- **Consumed by** — `../inference/`, which reads the champion's `artifact_prefix` and runs its bundle. `fit_champion_model()` in `../inference/sandbox.py` is what actually fits and persists `model.pkl` at completion time.
+- **Agent-facing surface** — the `autoresearch-training-runs-*` MCP tools in `../../mcp/tools.yaml`, backed by the viewsets in `../presentation/views/views.py`. The sandbox agent has no other way to write.
+- **Labels and features** — `../dataset/labeling.py` builds the training population the bundle is fitted against.
+
+## When editing this flow
+
+- **Never let agent output select the champion.** Everything that decides goes through `complete_training_run()`. If you add a new completion path, route it there rather than writing an `AutoresearchModel` directly.
+- **Any new agent-writable field needs validation in `recipe_validation.py`.** The agent is an untrusted author: SQL it writes is executed, paths it supplies become storage keys.
+- **Keep `stub.py` working.** It is the only way to test the whole downstream chain without spending money, and it is what local E2E leans on. If you change the recipe shape, change the stub too or every plumbing test silently starts covering nothing.
+- **Both model shapes must keep working.** A model with an `artifact_prefix` runs its bundle; one without carries only `model_recipe` and takes the legacy in-process path. Do not assume `artifact_prefix` is populated.
+- If you change the bundle file set or layout, update `artifacts.py`, the agent brief in `runner.py`, and `../../backend/test_fixtures/bundle/` together — the fixtures are what the tests fit against.
+- **If you change this package's layout or the agent contract, update this file to match.**
diff --git a/products/autoresearch/backend/training/CLAUDE.md b/products/autoresearch/backend/training/CLAUDE.md
new file mode 120000
index 000000000000..47dc3e3d863c
--- /dev/null
+++ b/products/autoresearch/backend/training/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/products/autoresearch/backend/training/__init__.py b/products/autoresearch/backend/training/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/autoresearch/backend/training/artifacts.py b/products/autoresearch/backend/training/artifacts.py
new file mode 100644
index 000000000000..6aabf6adc76f
--- /dev/null
+++ b/products/autoresearch/backend/training/artifacts.py
@@ -0,0 +1,253 @@
+"""
+Artifact bundle storage for autoresearch models.
+
+Each model is backed by a runnable bundle of agent-authored files in object
+storage: ``train.py``, ``predict.py``, ``features.sql``.
+Inference downloads the bundle and runs it in a sandbox (see
+``sandbox_inference.py``); the in-process recipe path is the legacy fallback.
+
+This module is a thin, team-scoped wrapper over ``posthog.storage.object_storage``.
+Keys are prefixed by team / pipeline / training-run so history is preserved
+naturally and bundles never collide across tenants.
+"""
+
+from __future__ import annotations
+
+import re
+import hashlib
+from pathlib import Path
+
+from django.conf import settings
+
+import structlog
+
+from posthog.dataclasses import frozen
+from posthog.storage import object_storage
+from posthog.storage.object_storage import ObjectStorageError
+
+from products.autoresearch.backend.training.recipe_validation import RecipeValidationError, validate_feature_sql
+
+logger = structlog.get_logger(__name__)
+
+# The files that make up a runnable model bundle.
+TRAIN_PY = "train.py"
+PREDICT_PY = "predict.py"
+FEATURES_SQL = "features.sql"
+BUNDLE_FILES: tuple[str, ...] = (TRAIN_PY, PREDICT_PY, FEATURES_SQL)
+
+# The fitted champion model, produced by the training run (train.py against the
+# training population) and persisted alongside the bundle so predict runs are pure
+# inference — they load this pickle and run predict.py only, never re-fitting.
+MODEL_PKL = "model.pkl"
+
+# Relative paths an agent may upload: bundle files at the top level plus optional
+# eda/ notebooks. Conservative on purpose — segment names are limited to word
+# chars, dot, and dash so nothing can climb out of the run prefix.
+_SAFE_PATH_SEGMENT = re.compile(r"^[\w.\-]+$")
+# A single file upload caps here so one base64 MCP payload can't blow memory.
+MAX_ARTIFACT_BYTES = 10 * 1024 * 1024
+# S3 rejects object keys longer than this many UTF-8 bytes.
+MAX_OBJECT_KEY_BYTES = 1024
+
+
+class InvalidArtifact(ValueError):
+ """Raised when an agent-supplied artifact is refused before it reaches storage."""
+
+
+class InvalidArtifactPath(InvalidArtifact):
+ """Raised when an upload/get path would escape the run prefix or is malformed."""
+
+
+class InvalidArtifactContent(InvalidArtifact):
+ """Raised when an upload is too large, or a bundle file is empty, not UTF-8, or fails validation."""
+
+
+def normalize_artifact_path(path: str) -> str:
+ """
+ Validate and normalize a relative artifact path. Rejects absolute paths,
+ traversal (``..``), and segments with unexpected characters.
+ """
+ candidate = (path or "").strip().lstrip("/")
+ if not candidate:
+ raise InvalidArtifactPath("Artifact path must not be empty.")
+ segments = candidate.split("/")
+ for seg in segments:
+ if seg in ("", ".", "..") or not _SAFE_PATH_SEGMENT.match(seg):
+ raise InvalidArtifactPath(
+ f"Invalid artifact path {path!r}: each segment must match [A-Za-z0-9_.-] and not be '.' or '..'."
+ )
+ return "/".join(segments)
+
+
+def _artifact_key(prefix: str, rel: str) -> str:
+ """The object key for the normalized relative path ``rel`` under ``prefix``, length-checked."""
+ key = f"{prefix}/{rel}"
+ if len(key.encode("utf-8")) > MAX_OBJECT_KEY_BYTES:
+ raise InvalidArtifactPath(
+ f"Artifact path {rel!r} is too long: the storage key is limited to {MAX_OBJECT_KEY_BYTES} bytes."
+ )
+ return key
+
+
+def _require_storage() -> None:
+ # The shared storage layer swaps in a client whose write() is a silent no-op when object
+ # storage is disabled. Acknowledging an upload that was never stored makes the bundle
+ # vanish on its next read, so refuse the write up front.
+ if not settings.OBJECT_STORAGE_ENABLED:
+ raise ObjectStorageError(
+ "Object storage is disabled (OBJECT_STORAGE_ENABLED), so the artifact cannot be stored."
+ )
+
+
+def _bundle_text(name: str, content: bytes) -> str:
+ """Decode one bundle file, refusing empty or non-UTF-8 content."""
+ if not content.strip():
+ raise InvalidArtifactContent(f"Bundle file {name!r} is empty.")
+ try:
+ return content.decode("utf-8")
+ except UnicodeDecodeError as e:
+ raise InvalidArtifactContent(f"Bundle file {name!r} is not valid UTF-8 text.") from e
+
+
+def _validate_bundle_file(name: str, content: bytes) -> None:
+ """
+ Check a bundle file at upload time, so a broken bundle is refused before it is acknowledged.
+
+ ``features.sql`` gets the same static checks as a recorded recipe: fitting and inference run
+ the uploaded query, not the recorded snapshot, so an upload that skipped validation could
+ read the wall clock or drop the ``{anchors}`` cutoff and leak the outcome window.
+ """
+ text = _bundle_text(name, content)
+ if name != FEATURES_SQL:
+ return
+ try:
+ validate_feature_sql(text)
+ except RecipeValidationError as e:
+ raise InvalidArtifactContent(f"Bundle file {name!r} was rejected: {e}") from e
+
+
+@frozen
+class ArtifactBundle:
+ """The agent-authored files describing one model. Stored as UTF-8 text."""
+
+ train_py: str
+ predict_py: str
+ features_sql: str
+
+ def as_files(self) -> dict[str, str]:
+ return {
+ TRAIN_PY: self.train_py,
+ PREDICT_PY: self.predict_py,
+ FEATURES_SQL: self.features_sql,
+ }
+
+ @classmethod
+ def from_files(cls, files: dict[str, bytes]) -> ArtifactBundle:
+ missing = [name for name in BUNDLE_FILES if name not in files]
+ if missing:
+ raise BundleNotFound(f"Bundle is missing required files: {', '.join(missing)}")
+ return cls(
+ train_py=_bundle_text(TRAIN_PY, files[TRAIN_PY]),
+ predict_py=_bundle_text(PREDICT_PY, files[PREDICT_PY]),
+ features_sql=_bundle_text(FEATURES_SQL, files[FEATURES_SQL]),
+ )
+
+ @classmethod
+ def from_dir(cls, directory: str | Path) -> ArtifactBundle:
+ """Load a bundle from a local directory (the fixture seed + future laptop-upload path)."""
+ base = Path(directory)
+ files = {name: (base / name).read_bytes() for name in BUNDLE_FILES if (base / name).exists()}
+ return cls.from_files(files)
+
+
+class BundleNotFound(Exception):
+ """Raised when a bundle prefix has no (or an incomplete) set of files."""
+
+
+def bundle_prefix(*, team_id: int, pipeline_id: str, training_run_id: str) -> str:
+ """Object-storage key prefix (no trailing slash) for one training run's bundle."""
+ folder = settings.OBJECT_STORAGE_TASKS_FOLDER
+ return f"{folder}/autoresearch/team_{team_id}/pipeline_{pipeline_id}/run_{training_run_id}"
+
+
+def write_bundle(prefix: str, bundle: ArtifactBundle) -> None:
+ """Write all bundle files under ``prefix``, with the same checks as a per-file upload."""
+ for name, content in bundle.as_files().items():
+ write_artifact(prefix, name, content.encode("utf-8"))
+ logger.info("autoresearch_bundle_written", prefix=prefix, files=len(BUNDLE_FILES))
+
+
+def read_bundle(prefix: str) -> ArtifactBundle:
+ """Read all bundle files from ``prefix``. Raises ``BundleNotFound`` if any is absent."""
+ files: dict[str, bytes] = {}
+ for name in BUNDLE_FILES:
+ content = object_storage.read_bytes(f"{prefix}/{name}", missing_ok=True)
+ if content is not None:
+ files[name] = content
+ return ArtifactBundle.from_files(files)
+
+
+def write_model(prefix: str, content: bytes) -> None:
+ """Persist the fitted champion model (``model.pkl``) under ``prefix``."""
+ _require_storage()
+ object_storage.write(f"{prefix}/{MODEL_PKL}", content)
+ logger.info("autoresearch_model_written", prefix=prefix, size=len(content))
+
+
+def read_model(prefix: str) -> bytes | None:
+ """Read the fitted champion model under ``prefix``, or None if it has not been fit yet."""
+ return object_storage.read_bytes(f"{prefix}/{MODEL_PKL}", missing_ok=True)
+
+
+# ── Per-file access (the MCP upload/get/list/delete surface) ─────────────────────
+
+
+@frozen
+class StoredArtifact:
+ path: str
+ size_bytes: int
+ sha256: str
+
+
+def write_artifact(prefix: str, path: str, content: bytes) -> StoredArtifact:
+ """Write one file under ``prefix`` at the validated relative ``path``."""
+ rel = normalize_artifact_path(path)
+ key = _artifact_key(prefix, rel)
+ if len(content) > MAX_ARTIFACT_BYTES:
+ raise InvalidArtifactContent(
+ f"Artifact {rel!r} is {len(content)} bytes; the limit is {MAX_ARTIFACT_BYTES} bytes."
+ )
+ if rel in BUNDLE_FILES:
+ _validate_bundle_file(rel, content)
+ _require_storage()
+ object_storage.write(key, content)
+ logger.info("autoresearch_artifact_written", prefix=prefix, path=rel, size=len(content))
+ return StoredArtifact(path=rel, size_bytes=len(content), sha256=hashlib.sha256(content).hexdigest())
+
+
+def read_artifact(prefix: str, path: str) -> bytes:
+ """Read one file under ``prefix``. Raises ``BundleNotFound`` if absent."""
+ rel = normalize_artifact_path(path)
+ key = _artifact_key(prefix, rel)
+ content = object_storage.read_bytes(key, missing_ok=True)
+ if content is None:
+ raise BundleNotFound(f"Artifact {rel!r} not found under {prefix}.")
+ return content
+
+
+def delete_artifact(prefix: str, path: str) -> bool:
+ """Delete one file under ``prefix``. Returns False if it was not present."""
+ rel = normalize_artifact_path(path)
+ key = _artifact_key(prefix, rel)
+ if object_storage.read_bytes(key, missing_ok=True) is None:
+ return False
+ object_storage.delete(key)
+ logger.info("autoresearch_artifact_deleted", prefix=prefix, path=rel)
+ return True
+
+
+def list_artifacts(prefix: str) -> list[str]:
+ """Return the relative paths present under ``prefix`` (sorted, prefix stripped)."""
+ keys = object_storage.list_objects(prefix) or []
+ rels = [key[len(prefix) + 1 :] for key in keys if key.startswith(f"{prefix}/")]
+ return sorted(rels)
diff --git a/products/autoresearch/backend/training/recipe_validation.py b/products/autoresearch/backend/training/recipe_validation.py
new file mode 100644
index 000000000000..6ac52366580f
--- /dev/null
+++ b/products/autoresearch/backend/training/recipe_validation.py
@@ -0,0 +1,294 @@
+"""Server-side validation of agent-authored model recipes.
+
+Any agent — the in-house sandbox or an external bring-your-own agent — that records
+a training iteration goes through ``validate_recipe``: the iteration's feature SQL must
+be a read-only ``SELECT`` that reads ``{anchors}``, keys each row as ``person_id AS
+distinct_id`` (the one-row-per-person contract), and never reads the wall clock.
+
+The ``model_class`` allowlist (``validate_model_class``) is NOT applied at recording
+time — in the artifact-bundle world the agent's real model runs as arbitrary code in a
+sandbox, so the recorded ``model_class`` is informational. The allowlist is enforced
+where it actually matters: the legacy in-process inference path
+(``inference.py``) resolves ``model_class`` via ``importlib`` (a code-execution surface)
+and calls ``validate_model_class`` there before importing.
+"""
+
+from collections.abc import Iterable, Mapping
+from typing import Any
+
+from posthog.hogql import ast
+from posthog.hogql.functions.mapping import find_hogql_function
+from posthog.hogql.parser import parse_select
+from posthog.hogql.visitor import TraversingVisitor
+
+# Classes the inference scorer is allowed to instantiate via importlib. Keep this in
+# sync with the fallback/resolution logic in inference.py — never widen it to accept
+# arbitrary import paths from agent input.
+ALLOWED_MODEL_CLASSES: frozenset[str] = frozenset(
+ {
+ "sklearn.linear_model.LogisticRegression",
+ "sklearn.ensemble.RandomForestClassifier",
+ "sklearn.ensemble.GradientBoostingClassifier",
+ "sklearn.ensemble.HistGradientBoostingClassifier",
+ "xgboost.XGBClassifier",
+ }
+)
+
+# Wall-clock functions bind a window to "now" instead of each anchor's cutoff_ts. At
+# training time that reads past the user's T0 into the outcome window, so the holdout
+# AUC is inflated by target leakage. The agent brief promises these are rejected.
+# Lowercase ClickHouse names: a call is checked both by the name the agent wrote and by
+# the name HogQL resolves it to, so `NOW()` and the `current_timestamp()` alias (which
+# resolves to now64) are caught alongside the plain spellings.
+_WALL_CLOCK_FUNCTIONS: frozenset[str] = frozenset({"now", "now64", "nowinblock", "today", "yesterday"})
+
+_ANCHORS = "anchors"
+_PERSON_ID = "person_id"
+_DISTINCT_ID = "distinct_id"
+
+# build_training_features_sql nests the feature query inside a WITH scope that defines these
+# relations. They carry the label, so a feature query that reads one of them selects the outcome
+# directly at training time; at inference they do not exist and the query fails.
+_TRAINING_CTE_NAMES: frozenset[str] = frozenset({"user_window", "user_t0", "labeled_users", "labeled_anchors"})
+# The training wrapper appends these columns to the feature rows, so a feature query that emits
+# them makes the label lookup ambiguous.
+_RESERVED_OUTPUT_NAMES: frozenset[str] = frozenset({"__label", "__fold"})
+
+
+class RecipeValidationError(ValueError):
+ """Raised when an agent-supplied recipe fails a server-side safety check."""
+
+
+def validate_model_class(model_class: str) -> None:
+ if model_class not in ALLOWED_MODEL_CLASSES:
+ allowed = ", ".join(sorted(ALLOWED_MODEL_CLASSES))
+ raise RecipeValidationError(f"model_class '{model_class}' is not allowed. Permitted classes: {allowed}.")
+
+
+def validate_feature_sql(feature_sql: str) -> None:
+ if not feature_sql or not feature_sql.strip():
+ raise RecipeValidationError("feature_sql is required and must be a non-empty SELECT.")
+ try:
+ node = parse_select(feature_sql)
+ except Exception as e:
+ raise RecipeValidationError(f"feature_sql is not valid HogQL: {e}") from e
+ if not isinstance(node, ast.SelectQuery):
+ raise RecipeValidationError("feature_sql must be a single SELECT statement (no unions or set operations).")
+ # The framework substitutes {anchors} with the per-user (person_id, cutoff_ts) table. The
+ # parser only produces a Placeholder node for the placeholder in code position, so a
+ # '{anchors}' string literal or a commented-out placeholder does not count: the query would
+ # run with no per-user T0 cutoff and read the outcome window (target leakage). It has to sit
+ # in the top-level FROM: behind a CTE or a derived table the anchor key can be transformed
+ # and renamed back to person_id, which nothing below can trace.
+ anchors_join = _top_level_anchors_join(node)
+ if anchors_join is None:
+ raise RecipeValidationError(
+ "feature_sql must read FROM the {anchors} placeholder table in its top-level FROM "
+ '(e.g. "FROM {anchors} a LEFT JOIN events e ON ..."; columns person_id, cutoff_ts) so '
+ "features are cut off at each user's T0 and cannot leak the outcome window."
+ )
+ problem = _output_problem(node, anchors_alias=anchors_join.alias)
+ if problem:
+ raise RecipeValidationError(problem)
+ cte_reads = _training_cte_reads(node)
+ if cte_reads:
+ raise RecipeValidationError(
+ f"feature_sql must not reference {', '.join(sorted(cte_reads))}: the training wrapper "
+ "defines those relations and they carry the label. Read the anchors through {anchors} only."
+ )
+ wall_clock = _wall_clock_reads(node)
+ if wall_clock:
+ raise RecipeValidationError(
+ f"feature_sql must not read the wall clock ({', '.join(sorted(wall_clock))}). Bound every "
+ "time window to fromUnixTimestamp(a.cutoff_ts) so features stop at each user's T0."
+ )
+
+
+class _WallClockReads(TraversingVisitor):
+ def __init__(self) -> None:
+ super().__init__()
+ self.names: set[str] = set()
+
+ def visit_call(self, node: ast.Call) -> None:
+ name = node.name.lower()
+ resolved = find_hogql_function(name)
+ if name in _WALL_CLOCK_FUNCTIONS or (resolved and resolved.clickhouse_name.lower() in _WALL_CLOCK_FUNCTIONS):
+ self.names.add(f"{node.name}()")
+ super().visit_call(node)
+
+ def visit_field(self, node: ast.Field) -> None:
+ # A bare CURRENT_TIMESTAMP / CURRENT_DATE has no parentheses, so it parses as a field and
+ # the resolver turns it into a wall-clock keyword.
+ if len(node.chain) == 1 and str(node.chain[0]).lower() in ast.VALID_KEYWORD_NAMES:
+ self.names.add(str(node.chain[0]))
+ super().visit_field(node)
+
+
+class _TrainingCteReads(TraversingVisitor):
+ def __init__(self) -> None:
+ super().__init__()
+ self.names: set[str] = set()
+
+ def visit_join_expr(self, node: ast.JoinExpr) -> None:
+ if isinstance(node.table, ast.Field) and node.table.chain:
+ self._check(str(node.table.chain[0]))
+ super().visit_join_expr(node)
+
+ def visit_select_query(self, node: ast.SelectQuery) -> None:
+ for name in node.ctes or {}:
+ self._check(name)
+ super().visit_select_query(node)
+
+ def _check(self, name: str) -> None:
+ if name.lower() in _TRAINING_CTE_NAMES:
+ self.names.add(name)
+
+
+def _is_anchors_placeholder(node: ast.Expr | None) -> bool:
+ return isinstance(node, ast.Placeholder) and node.field == _ANCHORS
+
+
+def _wall_clock_reads(node: ast.SelectQuery) -> set[str]:
+ """Every wall-clock function or keyword read anywhere in the query, subqueries included."""
+ visitor = _WallClockReads()
+ visitor.visit(node)
+ return visitor.names
+
+
+def _training_cte_reads(node: ast.SelectQuery) -> set[str]:
+ """Every training-wrapper relation the query reads or redefines, subqueries included."""
+ visitor = _TrainingCteReads()
+ visitor.visit(node)
+ return visitor.names
+
+
+def _top_level_anchors_join(node: ast.SelectQuery) -> ast.JoinExpr | None:
+ """The top-level FROM entry whose table is ``{anchors}``, or None when it is not there."""
+ join = node.select_from
+ while join is not None:
+ if _is_anchors_placeholder(join.table):
+ return join
+ join = join.next_join
+ return None
+
+
+def _output_problem(node: ast.SelectQuery, *, anchors_alias: str | None) -> str | None:
+ """
+ Why the top-level SELECT does not produce the columns the training join needs, or None.
+
+ The join reads ``distinct_id`` and appends ``__label`` / ``__fold``, so the output must
+ name ``distinct_id`` exactly once as the anchors table's own ``person_id`` field (an
+ expression over it or a joined table's key is unique enough to pass the row check yet
+ joins to no label), must not reuse the appended names, and must list every column: a
+ wildcard hides both.
+ """
+ names: list[str] = []
+ distinct_id_expr: ast.Expr | None = None
+ for col in node.select or []:
+ if isinstance(col, ast.Alias):
+ names.append(col.alias)
+ if col.alias == _DISTINCT_ID:
+ distinct_id_expr = col.expr
+ elif isinstance(col, ast.Field) and col.chain:
+ name = str(col.chain[-1])
+ if name == "*":
+ return (
+ "feature_sql must list its output columns explicitly. A wildcard (*) can hide a second "
+ "distinct_id or a reserved column."
+ )
+ names.append(name)
+ reserved = sorted(name for name in names if name in _RESERVED_OUTPUT_NAMES)
+ if reserved:
+ return (
+ f"feature_sql must not output {', '.join(reserved)}: the training wrapper appends "
+ "those columns to every feature row."
+ )
+ occurrences = names.count(_DISTINCT_ID)
+ if occurrences > 1:
+ return f"feature_sql outputs distinct_id {occurrences} times. Output it exactly once."
+ expected = [anchors_alias, _PERSON_ID] if anchors_alias else [_PERSON_ID]
+ if distinct_id_expr is None:
+ return (
+ f'feature_sql must select {".".join(expected)} AS distinct_id (e.g. "SELECT '
+ f'{".".join(expected)} AS distinct_id, ..."). Materialization and the training join '
+ "read that exact column, so each row keys one person."
+ )
+ if not isinstance(distinct_id_expr, ast.Field) or str(distinct_id_expr.chain[-1]) != _PERSON_ID:
+ return (
+ f"distinct_id must be the anchor person_id column itself ({'.'.join(expected)} AS distinct_id), "
+ "not an expression over it. The training join compares it to the anchor key as is."
+ )
+ if [str(part) for part in distinct_id_expr.chain] != expected:
+ return (
+ f"distinct_id must be {'.'.join(expected)}, the person_id of the {{anchors}} table, not "
+ "another relation's person_id. A joined table's key is null or missing for anchors it "
+ "does not cover."
+ )
+ return None
+
+
+def validate_unique_distinct_ids(
+ rows: Iterable[Mapping[str, Any]], *, source: str = "feature_sql", expected_count: int | None = None
+) -> None:
+ """
+ Enforce the one-row-per-person contract on materialized feature rows.
+
+ Static SQL validation cannot prove row uniqueness — duplicate distinct_ids only become
+ visible at materialization time, where they would flow into training as extra labeled
+ examples for the duplicated persons. Pass ``expected_count`` (the number of anchors) to
+ also require that every anchor produced exactly one row: an inner join or a WHERE on the
+ joined table silently drops persons, and a target-correlated drop inflates the holdout.
+ """
+ seen: set[str] = set()
+ duplicates: set[str] = set()
+ missing = 0
+ for row in rows:
+ distinct_id = row.get("distinct_id")
+ if distinct_id is None or not str(distinct_id).strip():
+ # A row with no person cannot be joined to a label or a fold; materializing it
+ # would serialize a synthetic empty identifier into the training data.
+ missing += 1
+ continue
+ key = str(distinct_id)
+ if key in seen:
+ duplicates.add(key)
+ seen.add(key)
+ if duplicates:
+ sample = ", ".join(sorted(duplicates)[:5])
+ raise RecipeValidationError(
+ f"{source} returned multiple rows for the same person ({len(duplicates)} duplicated "
+ f"distinct_ids, e.g. {sample}). Each person must aggregate to exactly one row. "
+ "Check the GROUP BY."
+ )
+ if missing:
+ raise RecipeValidationError(
+ f"{source} returned {missing} row(s) with a missing or blank person identifier. "
+ "Every row must key exactly one person. Check the SELECT and the joins."
+ )
+ if expected_count is not None and len(seen) != expected_count:
+ raise RecipeValidationError(
+ f"{source} returned {len(seen)} person(s) but the anchors table has {expected_count}. "
+ "Every anchor must produce exactly one row: drive the query FROM {anchors} with LEFT JOINs, "
+ "and do not filter on the joined tables in WHERE."
+ )
+
+
+def validate_recipe(model_spec: object, recipe_snapshot: object) -> None:
+ """
+ Validate one recorded iteration. Both fields arrive as unconstrained JSON from the agent,
+ so their shape is checked before anything is read. The ``model_class`` (in ``model_spec``)
+ is required but not allowlisted — it is informational metadata; the agent's real model runs
+ in a sandbox. The feature SQL (in ``recipe_snapshot``) is required and must pass
+ ``validate_feature_sql``: the promotion and inference paths consume it as is.
+ """
+ if not isinstance(model_spec, Mapping):
+ raise RecipeValidationError("model_spec must be a JSON object.")
+ 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.")
+ 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.")
+ validate_feature_sql(feature_sql)
diff --git a/products/autoresearch/backend/training/test_artifacts.py b/products/autoresearch/backend/training/test_artifacts.py
new file mode 100644
index 000000000000..2f918f41a342
--- /dev/null
+++ b/products/autoresearch/backend/training/test_artifacts.py
@@ -0,0 +1,142 @@
+from unittest.mock import patch
+
+from django.test import SimpleTestCase, override_settings
+
+from parameterized import parameterized
+
+from posthog.storage.object_storage import ObjectStorageError
+
+from products.autoresearch.backend.training import artifacts
+from products.autoresearch.backend.training.artifacts import (
+ BundleNotFound,
+ InvalidArtifactContent,
+ InvalidArtifactPath,
+ bundle_prefix,
+ delete_artifact,
+ list_artifacts,
+ normalize_artifact_path,
+ read_artifact,
+ write_artifact,
+)
+
+ANCHORED_SQL = b"SELECT a.person_id AS distinct_id, count() AS c FROM {anchors} a GROUP BY a.person_id"
+
+
+class _InMemoryStorage:
+ """Minimal stand-in for posthog.storage.object_storage's module functions."""
+
+ def __init__(self) -> None:
+ self.store: dict[str, bytes] = {}
+
+ def write(self, key: str, content, extras=None, bucket=None) -> None:
+ self.store[key] = content if isinstance(content, bytes) else content.encode("utf-8")
+
+ def read_bytes(self, key: str, 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: str, bucket=None) -> None:
+ self.store.pop(key, None)
+
+ def list_objects(self, prefix: str):
+ keys = [k for k in self.store if k.startswith(prefix)]
+ return keys or None
+
+
+class TestNormalizeArtifactPath(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("plain", "train.py", "train.py"),
+ ("leading_slash", "/train.py", "train.py"),
+ ("subdir", "eda/iter-3.ipynb", "eda/iter-3.ipynb"),
+ ("whitespace", " features.sql ", "features.sql"),
+ ]
+ )
+ def test_valid_paths(self, _name: str, path: str, expected: str) -> None:
+ self.assertEqual(normalize_artifact_path(path), expected)
+
+ @parameterized.expand(
+ [
+ ("empty", ""),
+ ("traversal", "../secrets"),
+ ("nested_traversal", "eda/../../etc/passwd"),
+ ("dot_segment", "eda/./x"),
+ ("space_in_segment", "my file.py"),
+ ("slash_only", "/"),
+ ]
+ )
+ def test_invalid_paths(self, _name: str, path: str) -> None:
+ with self.assertRaises(InvalidArtifactPath):
+ normalize_artifact_path(path)
+
+
+@override_settings(OBJECT_STORAGE_ENABLED=True)
+class TestArtifactStorage(SimpleTestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.fake = _InMemoryStorage()
+ patcher = patch.object(artifacts, "object_storage", self.fake)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.prefix = bundle_prefix(team_id=1, pipeline_id="pid", training_run_id="rid")
+
+ def test_write_then_read_roundtrip(self) -> None:
+ stored = write_artifact(self.prefix, "train.py", b"print('hi')")
+ self.assertEqual(stored.path, "train.py")
+ self.assertEqual(stored.size_bytes, 11)
+ self.assertEqual(read_artifact(self.prefix, "train.py"), b"print('hi')")
+
+ def test_read_missing_raises(self) -> None:
+ with self.assertRaises(BundleNotFound):
+ read_artifact(self.prefix, "nope.py")
+
+ def test_list_returns_relative_sorted_paths(self) -> None:
+ write_artifact(self.prefix, "train.py", b"a")
+ write_artifact(self.prefix, "predict.py", b"b")
+ write_artifact(self.prefix, "eda/iter-1.ipynb", b"c")
+ self.assertEqual(list_artifacts(self.prefix), ["eda/iter-1.ipynb", "predict.py", "train.py"])
+
+ def test_delete_reports_existence(self) -> None:
+ write_artifact(self.prefix, "train.py", b"a")
+ self.assertTrue(delete_artifact(self.prefix, "train.py"))
+ self.assertFalse(delete_artifact(self.prefix, "train.py"))
+
+ def test_oversize_upload_rejected(self) -> None:
+ with self.assertRaises(InvalidArtifactContent):
+ write_artifact(self.prefix, "eda/big.bin", b"x" * (artifacts.MAX_ARTIFACT_BYTES + 1))
+
+ @parameterized.expand([("traversal", "../escape.py"), ("key_too_long", "eda/" + "x" * 1100 + ".txt")])
+ def test_write_validates_path(self, _name: str, path: str) -> None:
+ with self.assertRaises(InvalidArtifactPath):
+ write_artifact(self.prefix, path, b"a")
+ self.assertEqual(self.fake.store, {})
+
+ @parameterized.expand(
+ [
+ ("empty_script", "train.py", b" \n"),
+ ("not_utf8", "predict.py", b"\xff\xfe"),
+ (
+ "feature_sql_reads_wall_clock",
+ "features.sql",
+ b"SELECT a.person_id AS distinct_id FROM {anchors} a WHERE now() > 0",
+ ),
+ ("feature_sql_unanchored", "features.sql", b"SELECT person_id AS distinct_id FROM events"),
+ ]
+ )
+ def test_bundle_files_are_validated_before_they_are_stored(self, _name: str, path: str, content: bytes) -> None:
+ with self.assertRaises(InvalidArtifactContent):
+ write_artifact(self.prefix, path, content)
+ self.assertEqual(self.fake.store, {})
+
+ def test_valid_feature_sql_upload_is_stored(self) -> None:
+ write_artifact(self.prefix, "features.sql", ANCHORED_SQL)
+ self.assertEqual(read_artifact(self.prefix, "features.sql"), ANCHORED_SQL)
+
+ @override_settings(OBJECT_STORAGE_ENABLED=False)
+ def test_write_refuses_when_object_storage_is_disabled(self) -> None:
+ with self.assertRaises(ObjectStorageError):
+ write_artifact(self.prefix, "train.py", b"a")
+ self.assertEqual(self.fake.store, {})
diff --git a/products/autoresearch/backend/training/test_recipe_validation.py b/products/autoresearch/backend/training/test_recipe_validation.py
new file mode 100644
index 000000000000..67af2ff795e1
--- /dev/null
+++ b/products/autoresearch/backend/training/test_recipe_validation.py
@@ -0,0 +1,197 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.autoresearch.backend.training.recipe_validation import (
+ RecipeValidationError,
+ validate_feature_sql,
+ validate_recipe,
+ validate_unique_distinct_ids,
+)
+
+ANCHORED = "SELECT a.person_id AS distinct_id, count() AS c FROM {anchors} a GROUP BY a.person_id, a.cutoff_ts"
+
+
+class TestRecipeValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("absent", "SELECT person_id AS distinct_id, count() AS c FROM events GROUP BY person_id"),
+ (
+ "in_a_comment",
+ "SELECT person_id AS distinct_id, count() AS c FROM events GROUP BY person_id -- reads from {anchors}",
+ ),
+ ("in_a_string_literal", "SELECT e.person_id AS distinct_id, '{anchors}' AS marker FROM events e"),
+ (
+ "behind_a_cte",
+ "WITH base AS (SELECT concat(person_id, 'x') AS person_id, cutoff_ts FROM {anchors}) "
+ "SELECT b.person_id AS distinct_id FROM base b",
+ ),
+ (
+ "in_a_derived_table",
+ "SELECT b.person_id AS distinct_id FROM (SELECT person_id, cutoff_ts FROM {anchors}) b",
+ ),
+ ]
+ )
+ def test_anchors_placeholder_must_be_the_top_level_table_source(self, _name, sql):
+ # labeling substitutes {anchors} in code position only; without it as a table the SQL
+ # runs with no per-user T0 cutoff (target leakage).
+ with self.assertRaises(RecipeValidationError) as ctx:
+ validate_feature_sql(sql)
+ assert "{anchors}" in str(ctx.exception)
+
+ @parameterized.expand(
+ [
+ ("bare_person_id", "SELECT a.person_id FROM {anchors} a"),
+ ("other_alias", "SELECT a.person_id AS foo FROM {anchors} a"),
+ ("events_distinct_id", "SELECT distinct_id FROM {anchors} a"),
+ ("transformed", "SELECT toString(a.person_id) AS distinct_id FROM {anchors} a"),
+ (
+ "joined_relations_key",
+ "SELECT e.person_id AS distinct_id FROM {anchors} a LEFT JOIN events e ON e.person_id = a.person_id",
+ ),
+ ("selected_twice", "SELECT a.person_id AS distinct_id, a.person_id AS distinct_id FROM {anchors} a"),
+ (
+ "implicit_second_output",
+ "SELECT a.person_id AS distinct_id, e.distinct_id FROM {anchors} a "
+ "LEFT JOIN events e ON e.person_id = a.person_id",
+ ),
+ ("wildcard_output", "SELECT a.person_id AS distinct_id, a.* FROM {anchors} a"),
+ ]
+ )
+ def test_feature_sql_requires_the_anchor_person_id_aliased_as_distinct_id(self, _name, sql):
+ # The training join reads f.distinct_id and materialization reads that column: a bare
+ # person_id fails fitting, and a transformed or foreign key is unique yet joins to no label.
+ with self.assertRaises(RecipeValidationError) as ctx:
+ validate_feature_sql(sql)
+ assert "distinct_id" in str(ctx.exception)
+
+ @parameterized.expand(
+ [
+ (
+ "where_clause",
+ "SELECT a.person_id AS distinct_id, count() AS c FROM {anchors} a "
+ "LEFT JOIN events e ON e.person_id = a.person_id WHERE e.timestamp < now() GROUP BY a.person_id",
+ ),
+ ("nested_call", "SELECT a.person_id AS distinct_id, toStartOfDay(today()) AS d FROM {anchors} a"),
+ (
+ "scalar_subquery",
+ "SELECT a.person_id AS distinct_id, (SELECT count() FROM events WHERE timestamp < now()) AS c "
+ "FROM {anchors} a",
+ ),
+ ("upper_case", "SELECT a.person_id AS distinct_id, NOW() AS t FROM {anchors} a"),
+ ("alias_resolving_to_now", "SELECT a.person_id AS distinct_id, current_timestamp() AS t FROM {anchors} a"),
+ ("bare_keyword", "SELECT a.person_id AS distinct_id, CURRENT_DATE AS d FROM {anchors} a"),
+ ]
+ )
+ def test_feature_sql_rejects_wall_clock_reads(self, _name, sql):
+ # Joining {anchors} proves nothing when the windows are bound to now(): at training
+ # time that reads past each user's T0 into the outcome window.
+ with self.assertRaises(RecipeValidationError) as ctx:
+ validate_feature_sql(sql)
+ assert "cutoff_ts" in str(ctx.exception)
+
+ @parameterized.expand(
+ [
+ (
+ "label_cte_joined",
+ "SELECT a.person_id AS distinct_id, lu.positive AS p FROM {anchors} a JOIN labeled_users lu ON lu.person_id = a.person_id",
+ ),
+ (
+ "label_cte_in_subquery",
+ "SELECT a.person_id AS distinct_id, (SELECT count() FROM labeled_anchors) AS n FROM {anchors} a",
+ ),
+ (
+ "label_cte_redefined",
+ "WITH labeled_users AS (SELECT 1 AS x) SELECT a.person_id AS distinct_id FROM {anchors} a",
+ ),
+ ]
+ )
+ def test_feature_sql_rejects_training_wrapper_relations(self, _name, sql):
+ with self.assertRaises(RecipeValidationError) as ctx:
+ validate_feature_sql(sql)
+ assert "training wrapper" in str(ctx.exception)
+
+ @parameterized.expand([("label", "__label"), ("fold", "__fold")])
+ def test_feature_sql_rejects_reserved_output_names(self, _name, column):
+ with self.assertRaises(RecipeValidationError) as ctx:
+ validate_feature_sql(f"SELECT a.person_id AS distinct_id, 1 AS {column} FROM {{anchors}} a")
+ assert column in str(ctx.exception)
+
+ @parameterized.expand(
+ [
+ (
+ "bound_to_cutoff_ts",
+ "SELECT a.person_id AS distinct_id, "
+ "dateDiff('day', max(e.timestamp), fromUnixTimestamp(a.cutoff_ts)) AS days_since_last_event "
+ "FROM {anchors} a LEFT JOIN events e ON e.person_id = a.person_id "
+ "AND e.timestamp < fromUnixTimestamp(a.cutoff_ts) GROUP BY a.person_id, a.cutoff_ts",
+ ),
+ (
+ "other_placeholders",
+ "SELECT a.person_id AS distinct_id, count(e.uuid) AS n FROM {anchors} a LEFT JOIN events e "
+ "ON e.person_id = a.person_id AND e.timestamp >= fromUnixTimestamp(a.cutoff_ts) "
+ "- toIntervalDay({lookback_days}) GROUP BY a.person_id",
+ ),
+ (
+ "own_cte_over_events",
+ "WITH recent AS (SELECT person_id, count() AS n FROM events GROUP BY person_id) "
+ "SELECT a.person_id AS distinct_id, r.n FROM {anchors} a LEFT JOIN recent r ON r.person_id = a.person_id",
+ ),
+ ("unaliased_anchors", "SELECT person_id AS distinct_id FROM {anchors}"),
+ ]
+ )
+ def test_feature_sql_shapes_that_keep_the_contract_pass(self, _name, sql):
+ validate_feature_sql(sql)
+
+ @parameterized.expand(
+ [
+ ("no_rows", [], None),
+ ("unique_rows", [{"distinct_id": "p1"}, {"distinct_id": "p2"}], None),
+ ("duplicate_rows", [{"distinct_id": "p1"}, {"distinct_id": "p1"}, {"distinct_id": "p2"}], "p1"),
+ # int and str forms of the same id are one person once coerced.
+ ("mixed_type_duplicates", [{"distinct_id": 42}, {"distinct_id": "42"}], "42"),
+ ]
+ )
+ def test_unique_distinct_ids(self, _name, rows, expected_duplicate):
+ if expected_duplicate is None:
+ validate_unique_distinct_ids(rows)
+ else:
+ with self.assertRaises(RecipeValidationError) as ctx:
+ validate_unique_distinct_ids(rows)
+ assert expected_duplicate in str(ctx.exception)
+
+ @parameterized.expand([("null", None), ("empty", ""), ("blank", " ")])
+ def test_rows_without_a_person_identifier_are_rejected(self, _name, distinct_id):
+ # Such a row joins to no label and no fold, so it would contaminate the holdout with
+ # a synthetic person rather than fail the iteration.
+ with self.assertRaises(RecipeValidationError) as ctx:
+ validate_unique_distinct_ids([{"distinct_id": "p1"}, {"distinct_id": distinct_id}])
+ assert "person identifier" in str(ctx.exception)
+
+ @parameterized.expand([("every_anchor_covered", 2, False), ("anchor_dropped", 3, True), ("extra_person", 1, True)])
+ def test_expected_count_requires_one_row_per_anchor(self, _name, expected_count, rejected):
+ rows = [{"distinct_id": "p1"}, {"distinct_id": "p2"}]
+ if not rejected:
+ validate_unique_distinct_ids(rows, expected_count=expected_count)
+ return
+ with self.assertRaises(RecipeValidationError) as ctx:
+ validate_unique_distinct_ids(rows, expected_count=expected_count)
+ assert str(expected_count) in str(ctx.exception)
+
+ @parameterized.expand(
+ [
+ ("model_spec_not_an_object", ["sklearn"], {"feature_sql": ANCHORED}),
+ ("model_class_missing", {}, {"feature_sql": ANCHORED}),
+ ("model_class_not_a_string", {"model_class": ["a"]}, {"feature_sql": ANCHORED}),
+ ("recipe_not_an_object", {"model_class": "m"}, "SELECT 1"),
+ ("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": " "}),
+ ]
+ )
+ def test_validate_recipe_rejects_malformed_agent_input(self, _name, model_spec, recipe_snapshot):
+ with self.assertRaises(RecipeValidationError):
+ validate_recipe(model_spec, recipe_snapshot)
+
+ def test_validate_recipe_accepts_a_valid_iteration(self):
+ validate_recipe({"model_class": "sklearn.linear_model.LogisticRegression"}, {"feature_sql": ANCHORED})