:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(autoresearch): add the sandbox inference path (8/22) (#89133)
Andrew Maguire3044b455f3fe
diff --git a/products/autoresearch/backend/inference/AGENTS.md b/products/autoresearch/backend/inference/AGENTS.mdnew file mode 100644index 000000000000..4e1ce27a7dc5--- /dev/null+++ b/products/autoresearch/backend/inference/AGENTS.md@@ -0,0 +1,81 @@+# Inference++Scoring a population with the champion model and writing the result back into PostHog as `autoresearch_prediction` events.++This is the cheap, boring, high-frequency half of the product — it runs on the pipeline's cadence (default daily) for every active pipeline, forever.+`../training/` is the expensive half that produces what this package consumes.++The cardinal rule: **inference never fits.** Fitting happens once, at training completion. If you find yourself calling a `fit` here on the scoring path, something has gone wrong.++This package landed with `sandbox.py` only. `scoring.py`, `autoresearch_score`, `../presentation/`, `../temporal/`, 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++- `sandbox.py`+ The current path. Runs the agent-authored bundle in a Tasks sandbox, split by run type because train and predict have genuinely different data contracts:+ - `fit_champion_model()` — **train run**, called once at training completion. Materializes the _labeled_ training population, runs the bundle's `train.py`, runs `predict.py` once against the holdout features as a smoke test, and only then persists the fitted `model.pkl` next to the bundle. A bundle whose two scripts disagree fails here, not on the first cadence.+ - `score_via_sandbox()` — **predict run**, called every cadence. Loads the persisted `model.pkl`, materializes _only_ the inference population (cutoff `now()`, no labels, no holdout, no fold), runs `predict.py`, and hands scores to the emitter. A missing `model.pkl` fails the run.++ Both entry points validate the bundle's `features.sql` with `validate_feature_sql()` (plus no trailing `LIMIT`/`OFFSET`/`SETTINGS`) before any query runs, and run every HogQL query as the pipeline's creator (`_resolve_acting_user()`, or the explicit `user` a management command passes), with `CALCULATE_BLOCKING_ALWAYS` so a cadence never reuses a cached population, and with `LABELER_QUERY_MODIFIERS`, because the anchor SQL reads `person.is_identified` and only resolves under that persons-on-events mode.+ The train run persists `feature_columns.json` next to `model.pkl`; every predict run sends exactly those columns, in that order, filling an absent or null one with zeros, so the fitted model never sees a column set that depends on today's population. A champion fitted before the file existed falls back to deriving the columns from the scoring rows. A fitted column that holds a present non-numeric value fails the run, because the persisted list bypasses `_numeric_feature_cols()` and zero-filling schema drift would emit a plausible wrong prediction.+ `materialize_training_data()` writes feature and label parquet files into the sandbox; `MaterializedData` carries the paths and row counts back. Materialized rows must key exactly one person each (`validate_unique_distinct_ids()`), and a training row whose label failed to join fails the run. Feature SQL that returns two columns of the same name fails the run, because `HogQLResult.as_dicts()` keeps only the last value of a repeated name.+ Every upload goes through `_write_file()`, which fails the run on a non-zero result: the providers report a failed write through the exit code rather than an exception, and a discarded result would let a script run against a missing input. The train run's smoke test loads the model bytes read back from the sandbox, written to `_SMOKE_MODEL_PKL`, so the bytes the caller persists are the bytes `predict.py` proved it can load.+ Everything a script produces is untrusted: script output goes to `data/script.log` and only a bounded tail comes back on failure; every file readback is size-gated inside the sandbox (`_MAX_READBACK_BYTES`, the artifact cap), emits at most cap-plus-one bytes through `head -c` however the file grows, and fails on a missing, empty, or oversized file; `output.json` values are typed and ranged; `scores.parquet` is checked from its footer before it is decoded (column types, row count against the input, decoded byte size of the two contract columns against the cap), only those two columns are read, and a person scored twice fails the run.+ Timeouts are asymmetric on purpose — `_TRAIN_TIMEOUT_S` 300s versus `_PREDICT_TIMEOUT_S` 120s — with `_SANDBOX_TTL_S` as the backstop for a worker that dies mid-run. `_MATERIALIZE_ROW_LIMIT` and `_MAX_FEATURE_COLS` together cap what crosses into the sandbox: the row cap alone does not bound the matrix the worker expands, because the agent's SQL chooses the column count.++- `scoring.py`+ The legacy in-process path plus the event emission that both paths share.+ `run_inference_for_pipeline()` is the entry point called by the Temporal activity and by `autoresearch_score`.+ This is the only place that resolves `model_class` through `importlib`, so it is the one genuine code-execution surface — it calls `validate_model_class()` from `../training/recipe_validation.py` before importing. Do not weaken that.+ `_resolve_distinct_ids()` maps the `person_id` everything is keyed on back to a `distinct_id` for the emitted event.++## The emitted event++```text+event: autoresearch_prediction+distinct_id: <person distinct_id>+properties: $autoresearch_pipeline_id, $autoresearch_p_y, ...+```++One event per scored person per run. This is the product's actual output — the person property on the pipeline (`output_person_property`, e.g. `predicted_p_downloaded_file_30d`) is derived from these.++Because emission goes through normal ingestion, backdated scoring (`--prediction-date` / `--backfill-days`) is silently dropped when the team has `drop_events_older_than_seconds` set. The events never arrive and nothing errors.++## Mental model++1. Load the champion for the pipeline.+2. Resolve the inference population and build anchors at cutoff `now()` (`../dataset/labeling.py`).+3. If the champion has an `artifact_prefix`, materialize features into a sandbox and run `predict.py`. Otherwise compile the recorded recipe and score in-process.+4. Map `person_id` → `distinct_id` and emit one event each.+5. Record an `AutoresearchRun` for the execution.++Both model shapes are live and must stay that way: bundle-backed champions take the sandbox path, older recipe-only champions take the in-process path.++## The failure mode that will cost you a day++**A uniform or constant score distribution is an identifier mismatch, not a bad model.**++Everything is keyed on `person_id`, one row per person — the agent's `feature_sql`, the label query, and the population query all have to agree.+When they don't, nothing raises: labels fail to join, come back all-zero, the model degenerates, and every person gets the same score. A raw UUID leaking into the event path also breaks JSON serialization and emits zero events.++Before suspecting the model, check that features, labels, and population all key on `person_id` and coerce to `str`.++## Where the rest of the system meets this package++- **Scheduled by** — `AutoresearchInferenceWorkflow` and `activity_run_inference` in `../temporal/workflows.py`.+- **Run headlessly by** — `autoresearch_score` (see `../management/AGENTS.md`), which calls the same functions directly.+- **Called by training** — `fit_champion_model()` is invoked from the completion path in `../training/promotion.py`. It lives here because it shares the materialization and sandbox machinery with scoring, not because it is part of the inference loop.+- **Reads** — `AutoresearchModel` (champion role) and the bundle in object storage via `../training/artifacts.py`.+- **Feeds** — `../evaluation/online_validation.py`, which reads the emitted events back once their horizon has elapsed.+- **Population and anchors** — `../dataset/labeling.py`, shared with training so the cutoff contract cannot drift.++## When editing this flow++- **Never re-fit on the scoring path.** `score_via_sandbox()` loads `model.pkl` and runs `predict.py` only. A fallback that quietly re-fits would make every scoring run expensive and non-deterministic, and concurrent cadences would race to overwrite the pickle. A missing model is a failed run.+- **Keep both champion shapes working** — bundle-backed and recipe-only. Guard on `artifact_prefix` rather than assuming.+- `validate_model_class()` must stay on the in-process path. It is not defense in depth there, it is the only defense.+- Anything that changes the cutoff, the population, or the anchor SQL belongs in `../dataset/labeling.py`, not here — training and inference share it precisely so they cannot disagree.+- Nothing a script writes reaches the worker unbounded. Keep the size gate in `_readback_command()` and the log redirect in `_script_command()` when you add a new file to the contract.+- The sandbox providers differ: Modal honors `block_network`; the Docker provider (local dev) does not, and mounts `SANDBOX_REPO_MOUNT_MAP` checkouts read-write. The no-egress guarantee holds in production only. Hogland maps only `DEFAULT_BASE`, so this workload does not run there.+- A large `--backfill-days` run emits N × population events into Kafka in a tight loop and can overwhelm a local ingestion consumer. Prefer smaller backfills; a contiguous gap in prediction dates is the symptom.+- **If you change the run-type split or the event shape, update this file to match.**diff --git a/products/autoresearch/backend/inference/CLAUDE.md b/products/autoresearch/backend/inference/CLAUDE.mdnew file mode 120000index 000000000000..47dc3e3d863c--- /dev/null+++ b/products/autoresearch/backend/inference/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/products/autoresearch/backend/inference/__init__.py b/products/autoresearch/backend/inference/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/autoresearch/backend/inference/sandbox.py b/products/autoresearch/backend/inference/sandbox.pynew file mode 100644index 000000000000..89400a9ac96a--- /dev/null+++ b/products/autoresearch/backend/inference/sandbox.py@@ -0,0 +1,828 @@+"""+Sandbox execution of an artifact bundle, split by run type.++Train run and predict run are different run types with different data contracts:++- ``fit_champion_model`` (train run, called once at completion) materializes the+ LABELED training population, runs the bundle's ``train.py`` in a sandbox, smoke-tests+ ``predict.py`` against the holdout features, and persists the fitted ``model.pkl``+ alongside the bundle. This is where fitting happens.+- ``score_via_sandbox`` (predict run, called every scoring cadence) is pure+ inference: it loads the persisted ``model.pkl``, materializes ONLY the+ inference population (cutoff ``now()``, no labels, no holdout, no fold), runs+ the bundle's ``predict.py`` only, and hands scores to the emitter. It never+ fits. A missing ``model.pkl`` fails the run so the caller can retry once the+ completion-time fit has been repaired.++Unlike the in-process recipe path (inference._score_via_anchors), the model runs+as the agent-authored scripts inside a NOTEBOOK_BASE Tasks sandbox. The framework+owns everything around the scripts: materializing the leak-free feature matrices+(via labeling.py), serialization to parquet, sandbox lifecycle, and emitting. The+bundle never receives credentials or network egress.++The framework<->bundle interchange is parquet, which is typed, columnar, and compressed.+The sandbox image ships pyarrow, so the feature matrices move faster and smaller than CSV.+This is a contract change: bundles authored against the old CSV contract fail loudly here,+because a parquet read of a CSV path errors, and must be re-trained.++Everything the scripts produce is untrusted. Script stdout goes to a file and only a+bounded tail comes back; every file readback is size-gated before it leaves the sandbox;+metrics and scores are validated before anything is persisted or emitted.++Failure is loud: any materialization or sandbox error raises, the sandbox is destroyed,+and the caller fails the run. Unlike the legacy path, there is deliberately no stub fallback,+because a silent zero-information champion would poison the realized-AUC gold-standard gate.+"""++from __future__ import annotations++import io+import json+import math+import base64+import binascii+from dataclasses import field+from decimal import Decimal+from typing import Any, Protocol++import pandas as pd+import pyarrow as pa+import structlog+import pyarrow.parquet as pq++from posthog.schema import HogQLQuery++from posthog.hogql import ast+from posthog.hogql.parser import parse_select++from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.dataclasses import frozen+from posthog.hogql_queries.query_runner import ExecutionMode+from posthog.models.team.team import Team+from posthog.models.user import User++from products.autoresearch.backend.dataset.labeling import (+ LABELER_QUERY_MODIFIERS,+ build_inference_features_sql,+ build_training_features_sql,+)+from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline+from products.autoresearch.backend.query import run_hogql+from products.autoresearch.backend.training.artifacts import (+ MAX_ARTIFACT_BYTES,+ ArtifactBundle,+ BundleNotFound,+ read_artifact,+ read_bundle,+ read_model,+ write_artifact,+ write_model,+)+from products.autoresearch.backend.training.recipe_validation import (+ RecipeValidationError,+ validate_feature_sql,+ validate_unique_distinct_ids,+)+from products.tasks.backend.facade.sandbox import ExecutionResult, SandboxConfig, SandboxTemplate, get_sandbox_class++Sandbox = get_sandbox_class()+++class SandboxExecutor(Protocol):+ """The slice of a sandbox the file readers below need."""++ def execute(self, command: str, timeout_seconds: int | None = None) -> ExecutionResult: ...++ def write_file(self, path: str, payload: bytes, timeout_seconds: int | None = None) -> ExecutionResult: ...+++logger = structlog.get_logger(__name__)++# Internal columns added by labeling.build_training_features_sql.+_LABEL_COL = "__label"+_FOLD_COL = "__fold"+_HOLDOUT_FOLD = 0 # fold 0 is the holdout slice; folds 1..N-1 are training++_WORKDIR = "/tmp/workspace/autoresearch"+_SANDBOX_PYTHON = "python3" # NOTEBOOK_BASE puts its venv first on PATH+_TRAIN_TIMEOUT_S = 300+_PREDICT_TIMEOUT_S = 120+# A sandbox that outlives its command is a worker that died mid-run. The TTL is the+# backstop that reclaims it: long enough for uploads, the command, and readback.+_SANDBOX_TTL_S = 20 * 60+# Without an explicit bound HogQL caps a query at its default of 100 rows, which would+# shrink the train, holdout, and score matrices to a tiny sample. Mirrors FEATURE_QUERY_LIMIT.+_MATERIALIZE_ROW_LIMIT = 50_000+_OUTPUT_JSON = "data/output.json"+_SCORES_PARQUET = "data/scores.parquet"+_SCRIPT_LOG = "data/script.log"+# The fitted model the train run produces and the predict run loads (relative to _WORKDIR).+_MODEL_PKL = "model.pkl"+_SMOKE_MODEL_PKL = "smoke_model.pkl"+# The feature columns the champion was fitted on, persisted next to model.pkl so every+# predict run sends the same columns in the same order, whatever the scoring population+# happens to contain.+_FEATURE_COLUMNS_JSON = "feature_columns.json"+_FILE_BEGIN = "<<<AUTORESEARCH_FILE_BEGIN>>>"+_FILE_END = "<<<AUTORESEARCH_FILE_END>>>"+# The scripts write files of any size inside the sandbox; the readback buffers the whole+# file (base64-encoded, then decoded) in the worker. The cap matches what the artifact+# store accepts, so a model that passes readback also passes persistence.+_MAX_READBACK_BYTES = MAX_ARTIFACT_BYTES+_MAX_SCRIPT_LOG_BYTES = 4000+# Keys train.py must write into output.json.+_REQUIRED_METRIC_KEYS = ("holdout_auc", "n_train", "n_features")+# The worker expands every feature column across every row before the matrix reaches the+# sandbox. The row cap alone does not bound that, because the agent's SQL chooses the+# column count.+_MAX_FEATURE_COLS = 512+_NUMERIC_TYPES = (int, float, Decimal)+++class SandboxInferenceError(Exception):+ """Raised when materialization or the sandbox run fails. The caller fails the run."""+++@frozen+class MaterializedData:+ """Labeled training matrix for a train run: train + holdout folds. Predict runs return a plain row list."""++ feature_cols: list[str]+ train_rows: list[dict[str, Any]] = field(default_factory=list)+ holdout_rows: list[dict[str, Any]] = field(default_factory=list)+++@frozen+class SandboxScoreResult:+ scored_rows: list[dict[str, Any]] # score rows with an added "p_y"+ holdout_auc: float | None+ n_train: int+ n_features: int+++# ── Public entry point ─────────────────────────────────────────────────────────+++def fit_champion_model(+ *,+ team: Team,+ pipeline: AutoresearchPipeline,+ prefix: str,+ bundle: ArtifactBundle | None = None,+ user: User | None = None,+) -> dict[str, Any]:+ """+ Train run: fit the champion against the LABELED training population and persist+ the resulting ``model.pkl`` under ``prefix``. Idempotent: it overwrites any prior fit.++ ``predict.py`` runs once against the holdout features before the model is persisted,+ so a bundle whose two scripts disagree fails here rather than on the first cadence.++ Returns train.py's metrics (holdout_auc, n_train, n_features). Raises+ SandboxInferenceError on any materialization or sandbox failure.+ """+ if bundle is None:+ try:+ bundle = read_bundle(prefix)+ except Exception as exc:+ raise SandboxInferenceError(f"Could not read bundle at {prefix}: {exc}") from exc+ acting_user = _resolve_acting_user(team=team, pipeline=pipeline, user=user)+ _validate_bundle_feature_sql(bundle)++ data = materialize_training_data(team=team, pipeline=pipeline, feature_sql=bundle.features_sql, user=acting_user)+ if not data.train_rows:+ raise SandboxInferenceError("No training rows to fit on")+ if not data.feature_cols:+ raise SandboxInferenceError("No numeric feature columns produced by feature SQL")++ model_bytes, metrics = _run_train_in_sandbox(bundle=bundle, data=data, pipeline=pipeline)+ write_model(prefix, model_bytes)+ write_artifact(prefix, _FEATURE_COLUMNS_JSON, json.dumps(data.feature_cols).encode("utf-8"))+ logger.info(+ "autoresearch_champion_fitted",+ pipeline_id=str(pipeline.pk),+ prefix=prefix,+ model_bytes=len(model_bytes),+ holdout_auc=metrics.get("holdout_auc"),+ )+ return metrics+++def score_via_sandbox(+ *,+ team: Team,+ pipeline: AutoresearchPipeline,+ model: AutoresearchModel,+ cutoff_ts: int | None = None,+ user: User | None = None,+) -> SandboxScoreResult:+ """+ Predict run: score the inference population with the champion's persisted model.++ Pure inference: it loads ``model.pkl`` and runs only ``predict.py`` against the+ inference population (cutoff now(), no labels, no holdout). A missing model fails+ the run: fitting stays at training completion, so a cadence never becomes a+ five-minute fit that races other cadences for the same pickle.++ Raises SandboxInferenceError on any failure (missing bundle or model, no data,+ sandbox or script error). Never falls back to stub scoring.+ """+ if not model.artifact_prefix:+ raise SandboxInferenceError(f"Model {model.pk} has no artifact_prefix")+ prefix = model.artifact_prefix++ try:+ bundle = read_bundle(prefix)+ except Exception as exc:+ raise SandboxInferenceError(f"Could not read bundle at {prefix}: {exc}") from exc+ acting_user = _resolve_acting_user(team=team, pipeline=pipeline, user=user)+ _validate_bundle_feature_sql(bundle)++ model_bytes = read_model(prefix)+ if not model_bytes:+ raise SandboxInferenceError(+ f"Champion model.pkl is missing at {prefix}; the completion-time fit has not produced it"+ )++ score_rows = _materialize_score_data(+ team=team, pipeline=pipeline, feature_sql=bundle.features_sql, cutoff_ts=cutoff_ts, user=acting_user+ )+ feature_cols = _fitted_feature_cols(prefix) or _numeric_feature_cols(score_rows)+ # Cheap guards before paying for a sandbox.+ if not score_rows:+ raise SandboxInferenceError("No inference rows to score")+ if not feature_cols:+ raise SandboxInferenceError("No numeric feature columns produced by feature SQL")++ scored_rows = _run_predict_in_sandbox(+ bundle=bundle, model_bytes=model_bytes, score_rows=score_rows, feature_cols=feature_cols, pipeline=pipeline+ )+ return SandboxScoreResult(+ scored_rows=scored_rows,+ holdout_auc=model.holdout_score,+ n_train=int((model.metrics or {}).get("n_train") or 0),+ n_features=len(feature_cols),+ )+++# ── Guards on the bundle and the acting user ──────────────────────────────────────+++def _resolve_acting_user(*, team: Team, pipeline: AutoresearchPipeline, user: User | None) -> User:+ """+ The user HogQL applies access control for. An explicit ``user`` wins (a management+ command); otherwise the pipeline's creator. With no user HogQL fails closed and can+ mask the pipeline from data its creator may read, so a creator who has left the+ project fails the run instead of silently narrowing it. The coordinator pauses such+ a pipeline before it dispatches a run.+ """+ candidate = user or pipeline.created_by+ if candidate is None:+ raise SandboxInferenceError(f"Pipeline {pipeline.pk} has no creator to run its queries as")+ if not team.all_users_with_access().filter(pk=candidate.pk).exists():+ raise SandboxInferenceError(+ f"Pipeline {pipeline.pk}: user {candidate.pk} no longer has access to team {team.pk}"+ )+ return candidate+++def _validate_bundle_feature_sql(bundle: ArtifactBundle) -> None:+ """+ The recipe snapshot was validated at upload; the bundle's ``features.sql`` is what+ actually runs, so it goes through the same validator here. A trailing LIMIT, OFFSET,+ or SETTINGS clause is refused as well: inference runs the feature SQL as the top-level+ query and appends the framework's own LIMIT after it.+ """+ try:+ validate_feature_sql(bundle.features_sql)+ except RecipeValidationError as exc:+ raise SandboxInferenceError(f"Bundle features.sql failed validation: {exc}") from exc+ node = parse_select(bundle.features_sql)+ if not isinstance(node, ast.SelectQuery):+ raise SandboxInferenceError("Bundle features.sql must be a single SELECT")+ if node.limit is not None or node.offset is not None or node.limit_by is not None or node.settings is not None:+ raise SandboxInferenceError(+ "Bundle features.sql must not end with LIMIT, OFFSET, or SETTINGS; the framework bounds the result"+ )+++def _fitted_feature_cols(prefix: str) -> list[str] | None:+ """The columns the champion was fitted on, or None for a champion fitted before they were persisted."""+ try:+ raw = read_artifact(prefix, _FEATURE_COLUMNS_JSON)+ except BundleNotFound:+ return None+ try:+ columns = json.loads(raw)+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise SandboxInferenceError(f"{_FEATURE_COLUMNS_JSON} at {prefix} is not readable: {exc}") from exc+ if not isinstance(columns, list) or not all(isinstance(c, str) for c in columns):+ raise SandboxInferenceError(f"{_FEATURE_COLUMNS_JSON} at {prefix} must be a list of column names")+ return columns+++# ── Data materialization (framework-owned, reuses labeling.py) ───────────────────+++def _feature_lookback_days(pipeline: AutoresearchPipeline) -> int:+ # Same window contract as inference._score_via_anchors: the feature-window+ # {lookback_days} is 4x horizon (min 30). Shared by train and predict so a user's+ # features are computed over the same window length on either side of T0.+ return max(30, pipeline.horizon_days * 4)+++def materialize_training_data(+ *, team: Team, pipeline: AutoresearchPipeline, feature_sql: str, user: User | None = None+) -> MaterializedData:+ """+ Train run materialization: the bundle's feature SQL against the LABELED training+ anchors (per-user random T0, with __label + __fold). Splits train/holdout by fold+ so the bundle never sees __fold. The labeler window is the pipeline's configured+ training_lookback_days.+ """+ feature_sql_resolved = feature_sql.replace("{lookback_days}", str(_feature_lookback_days(pipeline)))+ train_sql, train_values = build_training_features_sql(+ feature_sql=feature_sql_resolved,+ target_event=pipeline.target_event,+ target_definition=pipeline.target_definition,+ team=team,+ horizon_days=pipeline.horizon_days,+ lookback_days=pipeline.training_lookback_days,+ training_population=pipeline.training_population,+ )+ training_rows = _materialize_rows(team=team, sql=train_sql, values=train_values, user=user)+ _validate_rows_key_one_person(training_rows, source="training feature_sql")+ # The training wrapper LEFT JOINs the labels onto the feature rows. A feature row+ # whose distinct_id matched no anchor comes back with NULL label and fold, and the+ # fold split below would file it as a negative holdout example.+ unlabeled = sum(1 for r in training_rows if r.get(_LABEL_COL) is None or r.get(_FOLD_COL) is None)+ if unlabeled:+ raise SandboxInferenceError(+ f"{unlabeled} feature row(s) matched no labeled anchor; distinct_id must be the anchor person_id"+ )+ feature_cols = _numeric_feature_cols(training_rows)+ train_rows = [r for r in training_rows if r[_FOLD_COL] != _HOLDOUT_FOLD]+ holdout_rows = [r for r in training_rows if r[_FOLD_COL] == _HOLDOUT_FOLD]+ logger.info(+ "autoresearch_training_materialized",+ pipeline_id=str(pipeline.pk),+ n_train=len(train_rows),+ n_holdout=len(holdout_rows),+ n_features=len(feature_cols),+ )+ return MaterializedData(feature_cols=feature_cols, train_rows=train_rows, holdout_rows=holdout_rows)+++def _materialize_score_data(+ *,+ team: Team,+ pipeline: AutoresearchPipeline,+ feature_sql: str,+ cutoff_ts: int | None = None,+ user: User | None = None,+) -> list[dict[str, Any]]:+ """+ Predict run materialization: the bundle's feature SQL against the inference anchors+ (cutoff_ts = now() per user, or a backdated instant when ``cutoff_ts`` is given for a+ historical backfill). One row per eligible scoring user with the agent's feature+ columns, with no labels and no fold. Touches only the inference population.+ """+ feature_sql_resolved = feature_sql.replace("{lookback_days}", str(_feature_lookback_days(pipeline)))+ score_sql, score_values = build_inference_features_sql(+ feature_sql=feature_sql_resolved,+ lookback_days=_feature_lookback_days(pipeline),+ inference_population=pipeline.inference_population,+ cutoff_ts=cutoff_ts,+ target_event=pipeline.target_event,+ target_definition=pipeline.target_definition,+ team=team,+ )+ score_rows = _materialize_rows(team=team, sql=score_sql, values=score_values, user=user)+ _validate_rows_key_one_person(score_rows, source="inference feature_sql")+ logger.info(+ "autoresearch_score_materialized", pipeline_id=str(pipeline.pk), n_score=len(score_rows), cutoff_ts=cutoff_ts+ )+ return score_rows+++def _validate_rows_key_one_person(rows: list[dict[str, Any]], *, source: str) -> None:+ try:+ validate_unique_distinct_ids(rows, source=source)+ except RecipeValidationError as exc:+ raise SandboxInferenceError(str(exc)) from exc+++def _materialize_rows(+ *, team: Team, sql: str, values: dict[str, Any], user: User | None = None+) -> list[dict[str, Any]]:+ """Run a HogQL query and return rows as dicts, coercing person_id (distinct_id) to str."""+ bounded_sql = sql.rstrip().rstrip(";") + f"\nLIMIT {_MATERIALIZE_ROW_LIMIT}"+ try:+ tag_queries(product=Product.AUTORESEARCH, feature=Feature.QUERY)+ # The query text is identical from one cadence to the next and reads now(), so a+ # cached result would score a stale population at a stale cutoff.+ result = run_hogql(+ team=team,+ query=HogQLQuery(query=bounded_sql, values=values, modifiers=LABELER_QUERY_MODIFIERS),+ user=user,+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,+ )+ except Exception as exc:+ raise SandboxInferenceError(f"Feature query failed: {exc}") from exc++ if not result.rows or not result.columns:+ return []+ # as_dicts() zips column names onto values, so two columns of the same name keep only+ # the last value. The agent's SQL can produce that with unaliased joined fields, and+ # the matrix would then hold fewer features than the SQL declares.+ duplicates = sorted({str(c) for c in result.columns if list(result.columns).count(c) > 1})+ if duplicates:+ raise SandboxInferenceError(f"Feature SQL returned duplicate output columns: {', '.join(duplicates)}")+ rows = result.as_dicts()+ # A result that fills the bound is almost certainly truncated, and completing anyway+ # would advance last_scored_at while skipping the users past the cap. Pagination is+ # follow-up work; until then, fail loudly.+ if result.has_more or len(rows) >= _MATERIALIZE_ROW_LIMIT:+ raise SandboxInferenceError(+ f"Materialization hit the {_MATERIALIZE_ROW_LIMIT}-row limit; "+ "the population is likely truncated, refusing to score a partial population"+ )+ for r in rows:+ if r.get("distinct_id") is not None:+ r["distinct_id"] = str(r["distinct_id"])+ return rows+++def _numeric_feature_cols(rows: list[dict[str, Any]]) -> list[str]:+ """+ Sorted numeric feature columns, excluding distinct_id and the label/fold columns.++ A column counts as numeric when every non-null value in every row is a number. The+ first row alone cannot decide it: a nullable string column that is null there would+ be serialized as zeros, and the column set would differ between train and predict+ whenever the first row's nullness differs.+ """+ if not rows:+ return []+ excluded = {"distinct_id", _LABEL_COL, _FOLD_COL}+ candidates = {col for col in rows[0] if col not in excluded}+ for row in rows:+ for col in list(candidates):+ value = row.get(col)+ if value is not None and not isinstance(value, _NUMERIC_TYPES):+ candidates.discard(col)+ return sorted(candidates)+++# ── Sandbox execution ────────────────────────────────────────────────────────────+++def _sandbox_config(pipeline: AutoresearchPipeline, kind: str, timeout_seconds: int) -> SandboxConfig:+ return SandboxConfig(+ name=f"autoresearch-{kind}-{pipeline.pk}",+ template=SandboxTemplate.NOTEBOOK_BASE,+ environment_variables=None, # no credentials+ # An empty allowlist means UNRESTRICTED egress; no-egress must be stated+ # explicitly. train.py/predict.py are pure local compute over parquet.+ block_network=True,+ default_execution_timeout_seconds=timeout_seconds,+ ttl_seconds=_SANDBOX_TTL_S,+ # One sandbox per cadence per pipeline: reserve a small floor and burst to the+ # limit for the fit instead of holding the full shape through upload and readback.+ burstable_resources=True,+ metadata={"product": "autoresearch", "pipeline_id": str(pipeline.pk)},+ )+++def _script_command(script: str, args: str) -> str:+ # Script output is unbounded agent output; it goes to a file the framework reads back+ # bounded, never into the worker through execute().stdout.+ return f"cd {_WORKDIR} && {_SANDBOX_PYTHON} bundle/{script} {args} > {_SCRIPT_LOG} 2>&1"+++def _prepare_workspace(sandbox: SandboxExecutor, bundle: ArtifactBundle) -> None:+ # The Modal provider writes files without creating parent directories.+ result = sandbox.execute(f"mkdir -p {_WORKDIR}/bundle {_WORKDIR}/data", timeout_seconds=60)+ if result.exit_code != 0:+ raise SandboxInferenceError(f"could not create the sandbox workspace (exit {result.exit_code})")+ for name, content in bundle.as_files().items():+ _write_file(sandbox, f"{_WORKDIR}/bundle/{name}", content.encode("utf-8"))+++def _write_file(sandbox: SandboxExecutor, path: str, payload: bytes) -> None:+ # The providers report a failed write through the exit code instead of raising. A+ # discarded result lets a script run against a missing or half-written input, and a+ # bundle that tolerates a missing model would emit complete-looking scores.+ result = sandbox.write_file(path, payload)+ if result.exit_code != 0:+ raise SandboxInferenceError(f"could not write {path} into the sandbox (exit {result.exit_code})")+++def _run_script(sandbox: SandboxExecutor, *, script: str, args: str, timeout_seconds: int) -> None:+ result = sandbox.execute(_script_command(script, args), timeout_seconds=timeout_seconds)+ if result.exit_code != 0:+ raise SandboxInferenceError(f"{script} failed (exit {result.exit_code}): {_read_log_tail(sandbox)}")+++def _run_train_in_sandbox(+ *,+ bundle: ArtifactBundle,+ data: MaterializedData,+ pipeline: AutoresearchPipeline,+) -> tuple[bytes, dict[str, Any]]:+ """Fit the bundle's train.py on the materialized training data; return (model.pkl bytes, metrics)."""+ cols = data.feature_cols+ # The smoke test scores the holdout; with no holdout the training rows stand in, so+ # the scripts' contract is still exercised before the model is persisted.+ smoke_rows = data.holdout_rows or data.train_rows+ with Sandbox.create(_sandbox_config(pipeline, "train", _TRAIN_TIMEOUT_S)) as sandbox:+ _prepare_workspace(sandbox, bundle)+ _write_file(sandbox, f"{_WORKDIR}/data/train_features.parquet", features_parquet(data.train_rows, cols))+ _write_file(sandbox, f"{_WORKDIR}/data/train_labels.parquet", labels_parquet(data.train_rows))+ _write_file(sandbox, f"{_WORKDIR}/data/holdout_features.parquet", features_parquet(data.holdout_rows, cols))+ _write_file(sandbox, f"{_WORKDIR}/data/holdout_labels.parquet", labels_parquet(data.holdout_rows))+ _write_file(sandbox, f"{_WORKDIR}/data/smoke_features.parquet", features_parquet(smoke_rows, cols))++ _run_script(+ sandbox,+ script="train.py",+ args=(+ f"data/train_features.parquet data/train_labels.parquet {_MODEL_PKL} {_OUTPUT_JSON} "+ "data/holdout_features.parquet data/holdout_labels.parquet --random-state 42"+ ),+ timeout_seconds=_TRAIN_TIMEOUT_S,+ )+ metrics = _read_metrics(sandbox)+ model_bytes = _read_binary_file(sandbox, _MODEL_PKL)++ # Smoke-test the bytes the caller persists, not the path train.py wrote. The two+ # differ if the script leaves anything still writing model.pkl, and the persisted+ # model would then be one predict.py never loaded.+ _write_file(sandbox, f"{_WORKDIR}/{_SMOKE_MODEL_PKL}", model_bytes)+ _run_script(+ sandbox,+ script="predict.py",+ args=f"data/smoke_features.parquet {_SMOKE_MODEL_PKL} {_SCORES_PARQUET}",+ timeout_seconds=_PREDICT_TIMEOUT_S,+ )+ _join_scores(score_rows=smoke_rows, scores=_read_scores(sandbox, expected_rows=len(smoke_rows)))++ return model_bytes, metrics+++def _run_predict_in_sandbox(+ *,+ bundle: ArtifactBundle,+ model_bytes: bytes,+ score_rows: list[dict[str, Any]],+ feature_cols: list[str],+ pipeline: AutoresearchPipeline,+) -> list[dict[str, Any]]:+ """Run only the bundle's predict.py against the persisted model + score features."""+ with Sandbox.create(_sandbox_config(pipeline, "predict", _PREDICT_TIMEOUT_S)) as sandbox:+ _prepare_workspace(sandbox, bundle)+ _write_file(sandbox, f"{_WORKDIR}/{_MODEL_PKL}", model_bytes)+ _write_file(sandbox, f"{_WORKDIR}/data/score_features.parquet", features_parquet(score_rows, feature_cols))++ _run_script(+ sandbox,+ script="predict.py",+ args=f"data/score_features.parquet {_MODEL_PKL} {_SCORES_PARQUET}",+ timeout_seconds=_PREDICT_TIMEOUT_S,+ )+ scores = _read_scores(sandbox, expected_rows=len(score_rows))++ return _join_scores(score_rows=score_rows, scores=scores)+++def features_parquet(rows: list[dict[str, Any]], feature_cols: list[str]) -> bytes:+ """Serialize the feature matrix to parquet bytes: string `distinct_id` + float feature columns."""+ if len(feature_cols) > _MAX_FEATURE_COLS:+ raise SandboxInferenceError(+ f"Feature SQL produced {len(feature_cols)} feature columns, over the {_MAX_FEATURE_COLS} column cap"+ )+ data: dict[str, list[Any]] = {"distinct_id": [str(r.get("distinct_id", "")) for r in rows]}+ for col in feature_cols:+ data[col] = [_num(r.get(col), col=col) for r in rows]+ return _to_parquet_bytes(pd.DataFrame(data))+++def labels_parquet(rows: list[dict[str, Any]]) -> bytes:+ """Serialize the label vector to parquet bytes: string `distinct_id` + int `__label`."""+ 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],+ }+ )+ return _to_parquet_bytes(df)+++def _to_parquet_bytes(df: pd.DataFrame) -> bytes:+ buf = io.BytesIO()+ df.to_parquet(buf, index=False)+ return buf.getvalue()+++def _num(value: Any, *, col: str) -> float:+ # An absent or null cell is a zero-filled feature. A present cell that is not a number+ # means the population drifted away from the fitted schema, because the fitted columns+ # bypass _numeric_feature_cols. Zero-filling it would emit a plausible wrong prediction.+ if value is None:+ return 0.0+ try:+ return float(value)+ except (TypeError, ValueError) as exc:+ raise SandboxInferenceError(+ f"Feature column {col!r} holds the non-numeric value {value!r}; "+ "the scoring population no longer matches the fitted schema"+ ) from exc+++def _read_metrics(sandbox: SandboxExecutor) -> dict[str, Any]:+ """Read + validate train.py's output.json. Nothing is parsed from stdout."""+ body = _read_file(sandbox, _OUTPUT_JSON)+ try:+ parsed = json.loads(body)+ except json.JSONDecodeError as exc:+ raise SandboxInferenceError(f"output.json is not valid JSON: {exc}") from exc+ if not isinstance(parsed, dict):+ raise SandboxInferenceError("output.json must be a JSON object")+ missing = [k for k in _REQUIRED_METRIC_KEYS if k not in parsed]+ if missing:+ raise SandboxInferenceError(f"output.json missing keys: {', '.join(missing)}")+ # json.loads accepts NaN and Infinity, and a string or a bool passes a key check, so+ # every value is typed and ranged here before it reaches the model row.+ auc = parsed["holdout_auc"]+ if auc is not None and (+ isinstance(auc, bool) or not isinstance(auc, int | float) or not math.isfinite(auc) or not 0.0 <= auc <= 1.0+ ):+ raise SandboxInferenceError(f"output.json holdout_auc must be null or a probability in [0, 1], got {auc!r}")+ for key in ("n_train", "n_features"):+ count = parsed[key]+ if isinstance(count, bool) or not isinstance(count, int) or count < 0:+ raise SandboxInferenceError(f"output.json {key} must be a non-negative integer, got {count!r}")+ if parsed["n_features"] == 0:+ raise SandboxInferenceError("output.json reports n_features 0; train.py fit on no features")+ return parsed+++def _read_scores(sandbox: SandboxExecutor, *, expected_rows: int) -> dict[str, float]:+ """+ Read scores.parquet back (binary, base64 over the sentinel cat), returning {distinct_id: p_y}.++ The footer is checked before the table is decoded: a compressed file under the+ readback cap can still expand to millions of rows, and only the two contract columns+ are read.+ """+ raw = _read_binary_file(sandbox, _SCORES_PARQUET)+ try:+ parquet = pq.ParquetFile(io.BytesIO(raw))+ except Exception as exc:+ raise SandboxInferenceError(f"scores.parquet was not readable: {exc}") from exc+ _check_scores_footer(parquet, expected_rows=expected_rows)+ try:+ df = parquet.read(columns=["distinct_id", "p_y"]).to_pandas()+ except Exception as exc:+ raise SandboxInferenceError(f"scores.parquet was not readable: {exc}") from exc+ scores: dict[str, float] = {}+ for distinct_id, p_y in zip(df["distinct_id"], df["p_y"]):+ did = str(distinct_id).strip()+ if not did:+ continue+ if did in scores:+ raise SandboxInferenceError(f"scores.parquet scores {did!r} more than once")+ scores[did] = _probability(did, p_y)+ if not scores:+ raise SandboxInferenceError("scores.parquet produced no parseable rows")+ return scores+++def _check_scores_footer(parquet: pq.ParquetFile, *, expected_rows: int) -> None:+ """Reject a scores.parquet from its metadata alone, before any column is decoded."""+ schema = parquet.schema_arrow+ if "distinct_id" not in schema.names or "p_y" not in schema.names:+ raise SandboxInferenceError("scores.parquet must have columns distinct_id, p_y")+ id_type, p_type = schema.field("distinct_id").type, schema.field("p_y").type+ if not (pa.types.is_string(id_type) or pa.types.is_large_string(id_type)):+ raise SandboxInferenceError(f"scores.parquet distinct_id must be a string column, got {id_type}")+ if not (pa.types.is_floating(p_type) or pa.types.is_integer(p_type)):+ raise SandboxInferenceError(f"scores.parquet p_y must be a numeric column, got {p_type}")+ # The compressed file passed the readback cap; the decoded columns must fit it too, or+ # a highly compressible table expands in the worker before any value is checked.+ metadata = parquet.metadata+ decoded_bytes = sum(+ metadata.row_group(g).column(c).total_uncompressed_size+ for g in range(metadata.num_row_groups)+ for c in range(metadata.num_columns)+ if metadata.row_group(g).column(c).path_in_schema in ("distinct_id", "p_y")+ )+ if decoded_bytes > _MAX_READBACK_BYTES:+ raise SandboxInferenceError(f"scores.parquet decodes to {decoded_bytes} bytes, over the readback cap")+ if metadata.num_rows > expected_rows:+ raise SandboxInferenceError(+ f"scores.parquet has {metadata.num_rows} rows for {expected_rows} input rows; "+ "predict.py must score each input once"+ )+++def _probability(did: str, p_y: Any) -> float:+ # predict.py is agent-authored and untrusted, so a NaN, inf, or out-of-range+ # probability would flow straight into emitted prediction events.+ try:+ score = float(p_y)+ except (TypeError, ValueError) as exc:+ raise SandboxInferenceError(f"scores.parquet has a non-numeric p_y ({p_y!r}) for {did!r}") from exc+ if not math.isfinite(score) or not (0.0 <= score <= 1.0):+ raise SandboxInferenceError(f"scores.parquet has an invalid probability p_y ({score!r}) for {did!r}")+ return score+++def _readback_command(rel_path: str, *, encode: bool) -> str:+ """+ A shell command that emits the file between sentinels, or exits non-zero.++ The file must exist and fit under the readback cap before a byte of it is emitted,+ and at most cap-plus-one bytes are emitted however large it becomes. Without the+ guard a missing file would read back as empty output with exit 0, since the trailing+ echo decides the exit code, and an oversized file would be buffered whole in the worker.+ """+ # head bounds the bytes that leave the sandbox even if the file grows after the stat+ # check; the caller rejects a readback that reaches the extra byte.+ emit = (+ f'head -c {_MAX_READBACK_BYTES + 1} "$f" | base64 -w0; echo'+ if encode+ else f'head -c {_MAX_READBACK_BYTES + 1} "$f"'+ )+ return (+ f'f="{_WORKDIR}/{rel_path}"; '+ '[ -f "$f" ] || { echo "missing $f" >&2; exit 3; }; '+ 's=$(stat -c %s "$f"); '+ f'[ "$s" -le {_MAX_READBACK_BYTES} ] || {{ echo "$f is $s bytes, over the {_MAX_READBACK_BYTES}-byte cap" >&2; exit 4; }}; '+ f"echo '{_FILE_BEGIN}'; {emit}; echo '{_FILE_END}'"+ )+++def _read_file(sandbox: SandboxExecutor, rel_path: str) -> str:+ """+ Read a file the bundle wrote into the workspace, via a sentinel-bracketed cat.+ write_file is the only input channel and execute→stdout the only output channel,+ so we cat the file and slice between sentinels to survive any stray shell output.+ """+ result = sandbox.execute(_readback_command(rel_path, encode=False), timeout_seconds=60)+ if result.exit_code != 0:+ raise SandboxInferenceError(f"reading {rel_path} failed (exit {result.exit_code}): {result.stderr[:500]}")+ body = _between_sentinels(result.stdout)+ if len(body.encode("utf-8")) > _MAX_READBACK_BYTES:+ raise SandboxInferenceError(f"{rel_path} is over the {_MAX_READBACK_BYTES}-byte readback cap")+ return body+++def _read_binary_file(sandbox: SandboxExecutor, rel_path: str) -> bytes:+ """Read a binary file (e.g. model.pkl) the bundle wrote, base64-encoded over the sentinel-bracketed cat."""+ result = sandbox.execute(_readback_command(rel_path, encode=True), timeout_seconds=120)+ if result.exit_code != 0:+ raise SandboxInferenceError(f"reading {rel_path} failed (exit {result.exit_code}): {result.stderr[:500]}")+ encoded = "".join(_between_sentinels(result.stdout).split())+ try:+ content = base64.b64decode(encoded, validate=True)+ except (binascii.Error, ValueError) as exc:+ raise SandboxInferenceError(f"{rel_path} base64 readback was not decodable: {exc}") from exc+ if not content:+ raise SandboxInferenceError(f"{rel_path} is empty")+ if len(content) > _MAX_READBACK_BYTES:+ raise SandboxInferenceError(f"{rel_path} is over the {_MAX_READBACK_BYTES}-byte readback cap")+ return content+++def _read_log_tail(sandbox: SandboxExecutor) -> str:+ result = sandbox.execute(f"tail -c {_MAX_SCRIPT_LOG_BYTES} {_WORKDIR}/{_SCRIPT_LOG}", timeout_seconds=60)+ return result.stdout if result.exit_code == 0 else "(script log unavailable)"+++def _between_sentinels(stdout: str) -> str:+ start = stdout.find(_FILE_BEGIN)+ end = stdout.find(_FILE_END)+ if start == -1 or end == -1 or end < start:+ raise SandboxInferenceError("file sentinels not found in sandbox stdout")+ return stdout[start + len(_FILE_BEGIN) : end].strip("\n")+++def _join_scores(*, score_rows: list[dict[str, Any]], scores: dict[str, float]) -> list[dict[str, Any]]:+ """Join predict.py's scores back onto the input rows. Every input row must be scored,+ because a silently skipped user would never be scored again once last_scored_at advances.+ The probability keeps its full precision; rounding is the emitter's call, and+ rounding here would tie distinct predictions before online validation ranks them."""+ scored: list[dict[str, Any]] = []+ missing: list[str] = []+ for row in score_rows:+ distinct_id = row.get("distinct_id")+ if not distinct_id or distinct_id not in scores:+ missing.append(str(distinct_id))+ continue+ scored.append({**row, "p_y": scores[distinct_id]})+ if missing:+ raise SandboxInferenceError(+ f"scores.parquet covered only {len(scored)} of {len(score_rows)} input rows; missing e.g. {missing[:5]!r}"+ )+ return scoreddiff --git a/products/autoresearch/backend/inference/test_sandbox_inference.py b/products/autoresearch/backend/inference/test_sandbox_inference.pynew file mode 100644index 000000000000..2e1d28f3d1cc--- /dev/null+++ b/products/autoresearch/backend/inference/test_sandbox_inference.py@@ -0,0 +1,630 @@+import io+import json+import base64+from decimal import Decimal++from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++import pandas as pd+from parameterized import parameterized++from posthog.hogql_queries.query_runner import ExecutionMode+from posthog.models.user import User++from products.autoresearch.backend.inference import sandbox as sandbox_inference+from products.autoresearch.backend.inference.sandbox import (+ _FEATURE_COLUMNS_JSON,+ _FILE_BEGIN,+ _FILE_END,+ SandboxInferenceError,+ SandboxScoreResult,+ _between_sentinels,+ _join_scores,+ _materialize_score_data,+ _numeric_feature_cols,+ _read_binary_file,+ _read_metrics,+ _read_scores,+ features_parquet,+ fit_champion_model,+ labels_parquet,+ materialize_training_data,+ score_via_sandbox,+)+from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline+from products.autoresearch.backend.query import HogQLResult+from products.autoresearch.backend.testing import TeamScopedTestMixin+from products.autoresearch.backend.training.artifacts import ArtifactBundle, BundleNotFound+from products.tasks.backend.facade.sandbox import ExecutionResult++_VALID_FEATURE_SQL = "SELECT a.person_id AS distinct_id, count() AS events_total FROM {anchors} a GROUP BY a.person_id"+++def _scores_parquet(rows: list[tuple[str, object]]) -> bytes:+ buf = io.BytesIO()+ pd.DataFrame({"distinct_id": [r[0] for r in rows], "p_y": [r[1] for r in rows]}).to_parquet(buf, index=False)+ return buf.getvalue()+++_TRAINING_ROWS = [+ {"distinct_id": "p1", "events_total": 10, "pageviews": 5, "__label": 1, "__fold": 1},+ {"distinct_id": "p2", "events_total": 0, "pageviews": 0, "__label": 0, "__fold": 2},+ {"distinct_id": "p3", "events_total": 3, "pageviews": 1, "__label": 1, "__fold": 0}, # holdout+]+_SCORE_ROWS = [+ {"distinct_id": "s1", "events_total": 7, "pageviews": 2},+ {"distinct_id": "s2", "events_total": 1, "pageviews": 0},+]+_METRICS_JSON = '{"holdout_auc": 0.73, "n_train": 2, "n_features": 2}'+++def _training_materialized() -> sandbox_inference.MaterializedData:+ return sandbox_inference.MaterializedData(+ feature_cols=["events_total", "pageviews"],+ train_rows=[r for r in _TRAINING_ROWS if r["__fold"] != 0],+ holdout_rows=[r for r in _TRAINING_ROWS if r["__fold"] == 0],+ )+++class _FakeSandbox:+ def __init__(+ self,+ *,+ scores_parquet: bytes = b"",+ metrics_json: str = "",+ model_bytes: bytes = b"PICKLE",+ train_exit: int = 0,+ predict_exit: int = 0,+ readback_exit: int = 0,+ write_exit_for: str = "",+ ):+ self.written: dict[str, bytes] = {}+ self.commands: list[str] = []+ self._scores_parquet = scores_parquet+ self._metrics_json = metrics_json+ self._model_bytes = model_bytes+ self._train_exit = train_exit+ self._predict_exit = predict_exit+ self._readback_exit = readback_exit+ self._write_exit_for = write_exit_for+ self.destroyed = False++ def __enter__(self) -> "_FakeSandbox":+ return self++ def __exit__(self, *exc) -> None:+ self.destroyed = True++ def write_file(self, path: str, payload: bytes, timeout_seconds: int | None = None) -> ExecutionResult:+ if self._write_exit_for and path.endswith(self._write_exit_for):+ return ExecutionResult(stdout="", stderr="no space left on device", exit_code=1)+ self.written[path] = payload+ return ExecutionResult(stdout="", stderr="", exit_code=0)++ def ran(self, script: str) -> bool:+ return any(f"bundle/{script}" in c for c in self.commands)++ def execute(self, command: str, timeout_seconds: int | None = None) -> ExecutionResult:+ self.commands.append(command)+ if _FILE_BEGIN in command:+ if self._readback_exit:+ return ExecutionResult(stdout="", stderr="missing", exit_code=self._readback_exit)+ if "base64" in command:+ raw = self._scores_parquet if "scores.parquet" in command else self._model_bytes+ payload = base64.b64encode(raw).decode()+ elif "output.json" in command:+ payload = self._metrics_json+ else:+ payload = ""+ return ExecutionResult(stdout=f"{_FILE_BEGIN}\n{payload}\n{_FILE_END}\n", stderr="", exit_code=0)+ if "tail -c" in command:+ return ExecutionResult(stdout="boom", stderr="", exit_code=0)+ if "bundle/train.py" in command:+ return ExecutionResult(stdout="", stderr="", exit_code=self._train_exit)+ if "bundle/predict.py" in command:+ return ExecutionResult(stdout="", stderr="", exit_code=self._predict_exit)+ return ExecutionResult(stdout="", stderr="", exit_code=0)+++class TestMaterializeData(TeamScopedTestMixin, BaseTest):+ def _pipeline(self) -> AutoresearchPipeline:+ return AutoresearchPipeline.objects.create(+ team=self.team,+ created_by=self.user,+ name="mat",+ target_event="downloaded_file",+ horizon_days=7,+ )++ def test_training_data_splits_folds_and_extracts_feature_cols(self):+ pipeline = self._pipeline()+ with patch.object(sandbox_inference, "_materialize_rows", return_value=_TRAINING_ROWS):+ data = materialize_training_data(team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}")++ assert data.feature_cols == ["events_total", "pageviews"]+ assert [r["distinct_id"] for r in data.train_rows] == ["p1", "p2"]+ assert [r["distinct_id"] for r in data.holdout_rows] == ["p3"]++ @parameterized.expand(+ [+ ("duplicate_person", [{"distinct_id": "p1", "__label": 1, "__fold": 1}] * 2),+ ("no_label_match", [{"distinct_id": "p1", "__label": None, "__fold": None}]),+ ]+ )+ def test_training_data_rejects_rows_that_do_not_key_one_labeled_person(self, _name, rows):+ pipeline = self._pipeline()+ with patch.object(sandbox_inference, "_materialize_rows", return_value=rows):+ with self.assertRaises(SandboxInferenceError):+ materialize_training_data(team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}")++ def test_score_data_is_inference_only_no_labels(self):+ pipeline = self._pipeline()+ with patch.object(sandbox_inference, "_materialize_rows", return_value=_SCORE_ROWS) as run:+ score_rows = _materialize_score_data(+ team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}"+ )++ # exactly one query (inference anchors only) — no training/holdout materialization+ assert run.call_count == 1+ assert [r["distinct_id"] for r in score_rows] == ["s1", "s2"]++ def test_score_data_rejects_duplicate_persons(self):+ pipeline = self._pipeline()+ with patch.object(sandbox_inference, "_materialize_rows", return_value=[_SCORE_ROWS[0]] * 2):+ with self.assertRaises(SandboxInferenceError):+ _materialize_score_data(team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}")++ @parameterized.expand(+ [+ ("labels_and_ids_excluded", _TRAINING_ROWS, ["events_total", "pageviews"]),+ (+ "string_column_null_in_first_row",+ [{"distinct_id": "a", "plan": None, "n": 1}, {"distinct_id": "b", "plan": "pro", "n": 2}],+ ["n"],+ ),+ (+ "decimal_and_all_null_are_numeric",+ [{"distinct_id": "a", "amount": Decimal("1.5"), "empty": None}],+ ["amount", "empty"],+ ),+ ]+ )+ def test_numeric_feature_cols(self, _name, rows, expected):+ assert _numeric_feature_cols(rows) == expected++ def test_materialize_rows_bounds_the_query_and_runs_it_fresh_as_the_user(self):+ # Without an explicit LIMIT, HogQL caps the materialization at 100 rows; a cached+ # result would score yesterday's population at yesterday's cutoff.+ captured: dict = {}++ def _capture(*, team, query, **kwargs):+ captured["query"] = query.query+ captured["modifiers"] = query.modifiers+ captured.update(kwargs)+ return HogQLResult(columns=[], rows=[])++ with patch.object(sandbox_inference, "run_hogql", _capture):+ sandbox_inference._materialize_rows(+ team=self.team, sql="SELECT person_id FROM events", values={}, user=self.user+ )++ assert captured["query"].rstrip().endswith(f"LIMIT {sandbox_inference._MATERIALIZE_ROW_LIMIT}")+ assert captured["execution_mode"] == ExecutionMode.CALCULATE_BLOCKING_ALWAYS+ assert captured["user"] == self.user+ # The anchor SQL reads person.is_identified, which only resolves under the labeler's+ # persons-on-events mode.+ assert captured["modifiers"] == sandbox_inference.LABELER_QUERY_MODIFIERS++ @parameterized.expand(+ [+ ("under_limit", 2, False, False),+ ("at_limit", 3, False, True),+ ("runner_reports_more", 2, True, True),+ ]+ )+ def test_materialize_rows_fails_when_result_is_truncated(self, _name, n_rows, has_more, expect_raise):+ # A result that fills the LIMIT is a truncated population — completing would+ # advance last_scored_at while silently skipping the users past the cap.+ page = HogQLResult(columns=["distinct_id"], rows=[[f"p{i}"] for i in range(n_rows)], has_more=has_more)+ with (+ patch.object(sandbox_inference, "_MATERIALIZE_ROW_LIMIT", 3),+ patch.object(sandbox_inference, "run_hogql") as mock_run_hogql,+ ):+ mock_run_hogql.return_value = page+ if expect_raise:+ with self.assertRaises(SandboxInferenceError):+ sandbox_inference._materialize_rows(team=self.team, sql="SELECT person_id FROM events", values={})+ else:+ rows = sandbox_inference._materialize_rows(+ team=self.team, sql="SELECT person_id FROM events", values={}+ )+ assert len(rows) == n_rows++ def test_materialize_rows_rejects_duplicate_output_columns(self):+ page = HogQLResult(columns=["distinct_id", "events_total", "events_total"], rows=[["p1", 1, 2]])+ with patch.object(sandbox_inference, "run_hogql", return_value=page):+ with self.assertRaises(SandboxInferenceError):+ sandbox_inference._materialize_rows(team=self.team, sql="SELECT person_id FROM events", values={})+++class TestParquetSerialization(SimpleTestCase):+ def test_features_parquet_columns_and_rows(self):+ df = pd.read_parquet(io.BytesIO(features_parquet(_SCORE_ROWS, ["events_total", "pageviews"])))+ assert list(df.columns) == ["distinct_id", "events_total", "pageviews"]+ assert df.iloc[0]["distinct_id"] == "s1"+ assert df.iloc[0]["events_total"] == 7.0+ assert df.iloc[0]["pageviews"] == 2.0++ def test_labels_parquet_columns_and_rows(self):+ df = pd.read_parquet(io.BytesIO(labels_parquet(_TRAINING_ROWS)))+ assert list(df.columns) == ["distinct_id", "__label"]+ assert df.iloc[0]["distinct_id"] == "p1"+ assert int(df.iloc[0]["__label"]) == 1++ def test_features_parquet_missing_value_becomes_zero(self):+ rows = [{"distinct_id": "x", "events_total": None}]+ df = pd.read_parquet(io.BytesIO(features_parquet(rows, ["events_total", "pageviews"])))+ # both feature cols present; missing/None coerced to 0.0+ assert df.iloc[0]["events_total"] == 0.0+ assert df.iloc[0]["pageviews"] == 0.0++ def test_features_parquet_rejects_a_non_numeric_value_in_a_fitted_column(self):+ rows = [{"distinct_id": "x", "events_total": "unknown"}]+ with self.assertRaises(SandboxInferenceError):+ features_parquet(rows, ["events_total"])++ def test_features_parquet_rejects_more_columns_than_the_cap(self):+ cols = [f"f{i}" for i in range(sandbox_inference._MAX_FEATURE_COLS + 1)]+ with self.assertRaises(SandboxInferenceError):+ features_parquet([{"distinct_id": "x"}], cols)++ def test_features_parquet_distinct_id_is_string(self):+ rows = [{"distinct_id": 12345, "events_total": 1}]+ df = pd.read_parquet(io.BytesIO(features_parquet(rows, ["events_total"])))+ assert df.iloc[0]["distinct_id"] == "12345"+++class TestFileReadback(SimpleTestCase):+ def test_between_sentinels_extracts_body(self):+ stdout = f"junk before\n{_FILE_BEGIN}\ndistinct_id,p_y\ns1,0.8\n{_FILE_END}\njunk after"+ body = _between_sentinels(stdout)+ assert body == "distinct_id,p_y\ns1,0.8"++ def test_between_sentinels_raises_when_missing(self):+ with self.assertRaises(SandboxInferenceError):+ _between_sentinels("no sentinels here")++ @parameterized.expand(+ [+ ("missing_or_oversized_file", _FakeSandbox(readback_exit=4)),+ ("empty_file", _FakeSandbox(model_bytes=b"")),+ ]+ )+ def test_read_binary_file_fails_instead_of_returning_nothing(self, _name, fake):+ with self.assertRaises(SandboxInferenceError):+ _read_binary_file(fake, "model.pkl")++ def test_readback_command_gates_on_size_before_emitting(self):+ command = sandbox_inference._readback_command("model.pkl", encode=True)+ assert command.index("stat -c %s") < command.index("head -c") < command.index("base64")+ assert str(sandbox_inference._MAX_READBACK_BYTES) in command++ def test_read_binary_file_rejects_a_file_that_grew_past_the_cap_after_the_stat(self):+ fake = _FakeSandbox(model_bytes=b"PICKLE")+ with patch.object(sandbox_inference, "_MAX_READBACK_BYTES", 4):+ with self.assertRaises(SandboxInferenceError):+ _read_binary_file(fake, "model.pkl")++ @parameterized.expand(+ [+ ("plain", _METRICS_JSON, 0.73),+ ("null_auc", '{"holdout_auc": null, "n_train": 5, "n_features": 1}', None),+ ]+ )+ def test_read_metrics_returns_validated_dict(self, _name, metrics_json, expected_auc):+ fake = _FakeSandbox(metrics_json=metrics_json)+ meta = _read_metrics(fake)+ assert meta["holdout_auc"] == expected_auc++ @parameterized.expand(+ [+ ("missing_keys", '{"holdout_auc": 0.7}'),+ ("invalid_json", "not json"),+ ("nan_auc", '{"holdout_auc": NaN, "n_train": 2, "n_features": 2}'),+ ("auc_above_one", '{"holdout_auc": 1.5, "n_train": 2, "n_features": 2}'),+ ("bool_auc", '{"holdout_auc": true, "n_train": 2, "n_features": 2}'),+ ("negative_count", '{"holdout_auc": 0.7, "n_train": -1, "n_features": 2}'),+ ("string_count", '{"holdout_auc": 0.7, "n_train": "2", "n_features": 2}'),+ ("zero_features", '{"holdout_auc": 0.7, "n_train": 2, "n_features": 0}'),+ ]+ )+ def test_read_metrics_rejects_malformed_output(self, _name, metrics_json):+ # train.py is agent-authored: json.loads accepts NaN, and a key check alone lets+ # a bool, a string, or an out-of-range AUC onto the model row.+ fake = _FakeSandbox(metrics_json=metrics_json)+ with self.assertRaises(SandboxInferenceError):+ _read_metrics(fake)++ def test_read_scores_parses_parquet(self):+ fake = _FakeSandbox(scores_parquet=_scores_parquet([("s1", 0.8), ("s2", 0.2)]))+ scores = _read_scores(fake, expected_rows=2)+ assert scores == {"s1": 0.8, "s2": 0.2}++ @parameterized.expand(+ [+ ("empty", [], 2),+ ("duplicate_person", [("s1", 0.8), ("s1", 0.2)], 2),+ ("more_rows_than_inputs", [("s1", 0.8), ("s2", 0.2), ("s3", 0.1)], 2),+ ("nan", [("s1", float("nan"))], 1),+ ("inf", [("s1", float("inf"))], 1),+ ("neg_inf", [("s1", float("-inf"))], 1),+ ("above_one", [("s1", 1.5)], 1),+ ("below_zero", [("s1", -0.01)], 1),+ ("non_numeric", [("s1", "not-a-probability")], 1),+ ("non_string_ids", [(1, 0.5)], 1),+ ]+ )+ def test_read_scores_rejects_malformed_output(self, _name, rows, expected_rows):+ # predict.py output is untrusted agent code: a NaN/inf/out-of-range score, a person+ # scored twice, or a table larger than the input must fail the run rather than+ # flow into emitted prediction events.+ fake = _FakeSandbox(scores_parquet=_scores_parquet(rows))+ with self.assertRaises(SandboxInferenceError):+ _read_scores(fake, expected_rows=expected_rows)++ def test_read_scores_rejects_a_table_that_decodes_past_the_cap(self):+ # A compressible parquet under the readback cap can still expand in the worker.+ fake = _FakeSandbox(scores_parquet=_scores_parquet([("s" * 500, 0.5)]))+ with patch.object(sandbox_inference, "_MAX_READBACK_BYTES", 200):+ with self.assertRaises(SandboxInferenceError):+ _read_scores(fake, expected_rows=1)++ def test_join_scores_fails_when_predictions_omit_rows(self):+ # A user missing from scores.parquet must fail the run — skipping them would+ # advance last_scored_at while silently leaving the user unscored.+ with self.assertRaises(SandboxInferenceError):+ _join_scores(score_rows=_SCORE_ROWS, scores={"s1": 0.8})++ def test_join_scores_keeps_full_precision(self):+ scored = _join_scores(score_rows=_SCORE_ROWS[:1], scores={"s1": 0.123456789})+ assert scored[0]["p_y"] == 0.123456789+++class TestScoreViaSandbox(TeamScopedTestMixin, BaseTest):+ def _pipeline_and_model(self, artifact_prefix: str = "tasks/autoresearch/team_1/pipeline_x/run_y", created_by=...):+ pipeline = AutoresearchPipeline.objects.create(+ team=self.team,+ created_by=self.user if created_by is ... else created_by,+ name="sandbox",+ target_event="downloaded_file",+ horizon_days=7,+ )+ model = AutoresearchModel.objects.create(+ pipeline=pipeline,+ role=AutoresearchModel.Role.CHAMPION,+ recipe_hash="fixture",+ model_recipe={},+ artifact_prefix=artifact_prefix,+ )+ return pipeline, model++ def _bundle(self, features_sql: str = _VALID_FEATURE_SQL) -> ArtifactBundle:+ return ArtifactBundle(train_py="# train", predict_py="# predict", features_sql=features_sql)++ def _no_fitted_columns(self):+ return patch.object(sandbox_inference, "read_artifact", side_effect=BundleNotFound("none"))++ def test_predict_run_uses_persisted_model_and_does_not_train(self):+ pipeline, model = self._pipeline_and_model()+ fake = _FakeSandbox(scores_parquet=_scores_parquet([("s1", 0.8), ("s2", 0.2)]))+ model.holdout_score = 0.73+ model.metrics = {"n_train": 5}+ model.save(update_fields=["holdout_score", "metrics"])+ fitted_columns = json.dumps(["events_total", "pageviews", "signups"]).encode()+ with (+ patch.object(sandbox_inference, "read_bundle", return_value=self._bundle()),+ patch.object(sandbox_inference, "read_model", return_value=b"PICKLE"),+ patch.object(sandbox_inference, "read_artifact", return_value=fitted_columns),+ patch.object(sandbox_inference, "_materialize_score_data", return_value=_SCORE_ROWS),+ patch.object(sandbox_inference.Sandbox, "create", return_value=fake),+ ):+ result = score_via_sandbox(team=self.team, pipeline=pipeline, model=model)++ assert isinstance(result, SandboxScoreResult)+ # predict.py sees the columns the champion was fitted on, not whatever this+ # population happens to contain; a column absent today is sent as zeros.+ sent = pd.read_parquet(io.BytesIO(fake.written[f"{sandbox_inference._WORKDIR}/data/score_features.parquet"]))+ assert list(sent.columns) == ["distinct_id", "events_total", "pageviews", "signups"]+ assert list(sent["signups"]) == [0.0, 0.0]+ assert result.holdout_auc == 0.73 # comes from the persisted model, not recomputed+ assert {r["distinct_id"] for r in result.scored_rows} == {"s1", "s2"}+ assert fake.destroyed is True+ # the persisted model + score features were uploaded; predict ran, train.py did NOT+ assert any(p.endswith("model.pkl") for p in fake.written)+ assert any(p.endswith("data/score_features.parquet") for p in fake.written)+ assert not any(p.endswith("data/train_features.parquet") for p in fake.written)+ assert fake.ran("predict.py") and not fake.ran("train.py")++ def test_missing_model_fails_without_fitting(self):+ # Fitting stays at training completion: a cadence that fits would race other+ # cadences for the pickle and turn a 120 s predict into a 300 s fit.+ pipeline, model = self._pipeline_and_model()+ create_mock = MagicMock()+ fit = MagicMock()+ with (+ patch.object(sandbox_inference, "read_bundle", return_value=self._bundle()),+ patch.object(sandbox_inference, "read_model", return_value=None),+ patch.object(sandbox_inference, "fit_champion_model", fit),+ patch.object(sandbox_inference.Sandbox, "create", create_mock),+ ):+ with self.assertRaises(SandboxInferenceError):+ score_via_sandbox(team=self.team, pipeline=pipeline, model=model)++ fit.assert_not_called()+ create_mock.assert_not_called()++ def test_no_artifact_prefix_raises(self):+ pipeline, model = self._pipeline_and_model(artifact_prefix="")+ with self.assertRaises(SandboxInferenceError):+ score_via_sandbox(team=self.team, pipeline=pipeline, model=model)++ @parameterized.expand(+ [+ ("no_anchors", "SELECT person_id AS distinct_id, count() AS n FROM events GROUP BY person_id"),+ (+ "wall_clock",+ "SELECT a.person_id AS distinct_id, countIf(now() > a.cutoff_ts) AS n FROM {anchors} a GROUP BY a.person_id",+ ),+ ("trailing_limit", _VALID_FEATURE_SQL + " LIMIT 10"),+ ("trailing_settings", _VALID_FEATURE_SQL + " SETTINGS max_threads=1"),+ ]+ )+ def test_bundle_feature_sql_is_validated_before_anything_runs(self, _name, features_sql):+ # The recipe snapshot was validated at upload; features.sql is what runs, and a+ # trailing LIMIT would collide with the framework's own on the inference path.+ pipeline, model = self._pipeline_and_model()+ create_mock = MagicMock()+ with (+ patch.object(sandbox_inference, "read_bundle", return_value=self._bundle(features_sql)),+ patch.object(sandbox_inference, "read_model", return_value=b"PICKLE"),+ patch.object(sandbox_inference, "_materialize_score_data") as materialize,+ patch.object(sandbox_inference.Sandbox, "create", create_mock),+ ):+ with self.assertRaises(SandboxInferenceError):+ score_via_sandbox(team=self.team, pipeline=pipeline, model=model)+ materialize.assert_not_called()+ create_mock.assert_not_called()++ def test_runs_as_the_creator_and_fails_when_the_creator_has_no_access(self):+ # HogQL fails closed without a user, so a departed creator would silently narrow+ # the pipeline's data instead of surfacing.+ outsider = User.objects.create_user(email="[email protected]", password=None, first_name="o")+ pipeline, model = self._pipeline_and_model(created_by=outsider)+ with (+ patch.object(sandbox_inference, "read_bundle", return_value=self._bundle()),+ patch.object(sandbox_inference, "read_model", return_value=b"PICKLE"),+ self._no_fitted_columns(),+ patch.object(sandbox_inference, "_materialize_score_data", return_value=[]) as materialize,+ ):+ with self.assertRaises(SandboxInferenceError):+ score_via_sandbox(team=self.team, pipeline=pipeline, model=model)+ materialize.assert_not_called()++ pipeline.created_by = None+ pipeline.save(update_fields=["created_by"])+ with self.assertRaises(SandboxInferenceError):+ score_via_sandbox(team=self.team, pipeline=pipeline, model=model)+ materialize.assert_not_called()++ with self.assertRaises(SandboxInferenceError): # no rows, after materialization ran as the user+ score_via_sandbox(team=self.team, pipeline=pipeline, model=model, user=self.user)+ assert materialize.call_args.kwargs["user"] == self.user++ def test_predict_failure_raises_and_destroys_sandbox(self):+ pipeline, model = self._pipeline_and_model()+ fake = _FakeSandbox(predict_exit=1)+ with (+ patch.object(sandbox_inference, "read_bundle", return_value=self._bundle()),+ patch.object(sandbox_inference, "read_model", return_value=b"PICKLE"),+ self._no_fitted_columns(),+ patch.object(sandbox_inference, "_materialize_score_data", return_value=_SCORE_ROWS),+ patch.object(sandbox_inference.Sandbox, "create", return_value=fake),+ ):+ with self.assertRaises(SandboxInferenceError) as ctx:+ score_via_sandbox(team=self.team, pipeline=pipeline, model=model)+ assert fake.destroyed is True+ assert "boom" in str(ctx.exception) # the bounded script log tail, not execute().stderr++ def test_model_upload_failure_aborts_before_predict_runs(self):+ pipeline, model = self._pipeline_and_model()+ fake = _FakeSandbox(write_exit_for=sandbox_inference._MODEL_PKL)+ with (+ patch.object(sandbox_inference, "read_bundle", return_value=self._bundle()),+ patch.object(sandbox_inference, "read_model", return_value=b"PICKLE"),+ self._no_fitted_columns(),+ patch.object(sandbox_inference, "_materialize_score_data", return_value=_SCORE_ROWS),+ patch.object(sandbox_inference.Sandbox, "create", return_value=fake),+ ):+ with self.assertRaises(SandboxInferenceError):+ score_via_sandbox(team=self.team, pipeline=pipeline, model=model)+ assert not fake.ran("predict.py")+ assert fake.destroyed is True++ def test_empty_score_rows_raises_before_sandbox(self):+ pipeline, model = self._pipeline_and_model()+ create_mock = MagicMock()+ with (+ patch.object(sandbox_inference, "read_bundle", return_value=self._bundle()),+ patch.object(sandbox_inference, "read_model", return_value=b"PICKLE"),+ self._no_fitted_columns(),+ patch.object(sandbox_inference, "_materialize_score_data", return_value=[]),+ patch.object(sandbox_inference.Sandbox, "create", create_mock),+ ):+ with self.assertRaises(SandboxInferenceError):+ score_via_sandbox(team=self.team, pipeline=pipeline, model=model)+ create_mock.assert_not_called() # cheap guard fires before paying for a sandbox++ def test_fit_champion_model_trains_smoke_tests_predict_and_persists(self):+ pipeline, model = self._pipeline_and_model()+ fake = _FakeSandbox(+ metrics_json=_METRICS_JSON, model_bytes=b"FITTED", scores_parquet=_scores_parquet([("p3", 0.5)])+ )+ stored: dict = {}+ with (+ patch.object(sandbox_inference, "read_bundle", return_value=self._bundle()),+ patch.object(sandbox_inference, "materialize_training_data", return_value=_training_materialized()),+ patch.object(+ sandbox_inference, "write_model", side_effect=lambda prefix, content: stored.update(model=content)+ ),+ patch.object(+ sandbox_inference,+ "write_artifact",+ side_effect=lambda prefix, path, content: stored.update({path: content}),+ ),+ patch.object(sandbox_inference.Sandbox, "create", return_value=fake),+ ):+ metrics = fit_champion_model(team=self.team, pipeline=pipeline, prefix=model.artifact_prefix)++ assert metrics["holdout_auc"] == 0.73+ assert stored["model"] == b"FITTED" # the fitted model.pkl read back + persisted+ assert json.loads(stored[_FEATURE_COLUMNS_JSON]) == ["events_total", "pageviews"]+ assert any(p.endswith("data/train_features.parquet") for p in fake.written) # train run materializes training+ assert not any(p.endswith("data/score_features.parquet") for p in fake.written)+ assert fake.ran("train.py") and fake.ran("predict.py") # predict.py exercised against the holdout+ assert fake.written[f"{sandbox_inference._WORKDIR}/{sandbox_inference._SMOKE_MODEL_PKL}"] == b"FITTED"+ assert any(sandbox_inference._SMOKE_MODEL_PKL in c for c in fake.commands if "predict.py" in c)++ @parameterized.expand(+ [+ ("predict_exits_nonzero", {"predict_exit": 1}),+ ("predict_skips_a_holdout_row", {"scores_parquet": _scores_parquet([("someone-else", 0.5)])}),+ (+ "train_features_upload_fails",+ {"write_exit_for": "data/train_features.parquet", "scores_parquet": _scores_parquet([("p3", 0.5)])},+ ),+ (+ "bundle_upload_fails",+ {"write_exit_for": "bundle/train.py", "scores_parquet": _scores_parquet([("p3", 0.5)])},+ ),+ ]+ )+ def test_fit_champion_model_does_not_persist_when_predict_smoke_test_fails(self, _name, fake_kwargs):+ # A bundle whose predict.py cannot load or apply the fitted model fails at+ # completion, not on the first cadence.+ pipeline, model = self._pipeline_and_model()+ fake = _FakeSandbox(metrics_json=_METRICS_JSON, model_bytes=b"FITTED", **fake_kwargs)+ write_model = MagicMock()+ with (+ patch.object(sandbox_inference, "read_bundle", return_value=self._bundle()),+ patch.object(sandbox_inference, "materialize_training_data", return_value=_training_materialized()),+ patch.object(sandbox_inference, "write_model", write_model),+ patch.object(sandbox_inference, "write_artifact", MagicMock()),+ patch.object(sandbox_inference.Sandbox, "create", return_value=fake),+ ):+ with self.assertRaises(SandboxInferenceError):+ fit_champion_model(team=self.team, pipeline=pipeline, prefix=model.artifact_prefix)+ write_model.assert_not_called()+ assert fake.destroyed is Truediff --git a/tach.toml b/tach.tomlindex 107e53f7bd4d..a4e883da4826 100644--- a/tach.toml+++ b/tach.toml@@ -196,6 +196,7 @@ depends_on = ["posthog","products.actions","products.feature_flags",+ "products.tasks",]layer = "modules"