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): shadow-score the shadow set every cadence (#112392)

posthog[bot]cb126d8b6e28
diff --git a/products/autoresearch/backend/dataset/labeling.py b/products/autoresearch/backend/dataset/labeling.py
index d85e98782321..aa34a070de77 100644
--- a/products/autoresearch/backend/dataset/labeling.py
+++ b/products/autoresearch/backend/dataset/labeling.py
@@ -89,6 +89,8 @@ def _identified_users_and_clause() -> str:
# activity scan that counted it would keep a person eligible forever on nothing but their
# own predictions, and would count the prediction as the first or last thing they did.
PREDICTION_EVENT_NAME = "autoresearch_prediction"
+# The `$autoresearch_model_role` of a prediction a shadow-set model emits next to the champion's.
+SHADOW_MODEL_ROLE = "shadow"
def _own_events_excluded_clause(alias: str = "") -> str:
@@ -988,7 +990,8 @@ def build_inference_anchors_sql(
``rolling`` keeps only ``rolling.limit`` eligible persons: first the ones the pipeline never
scored, then the oldest last score, then the most recent member event, then a hash of the
person. Every key reads events before the cutoff, so a retry of the same prediction date
- selects the same people.
+ selects the same people. Shadow predictions do not count as scores, so shadow scoring does
+ not change who the champion scores next.
"""
inference_properties = (inference_population or {}).get("properties", []) if inference_population else []
compiled_filters = _compile_population_filters(inference_properties)
@@ -1039,6 +1042,7 @@ def build_inference_anchors_sql(
AND timestamp >= {cutoff_expr} - toIntervalDay({{rolling_scored_lookback}})
AND timestamp < {cutoff_expr}
AND properties.$autoresearch_pipeline_id = {{rolling_pipeline_id}}
+ AND ifNull(properties.$autoresearch_model_role, '') != '{SHADOW_MODEL_ROLE}'
GROUP BY person_id
) AS s ON a.person_id = s.person_id
LEFT JOIN (
diff --git a/products/autoresearch/backend/dataset/test_labeling.py b/products/autoresearch/backend/dataset/test_labeling.py
index f924c3d97913..8a86ce942245 100644
--- a/products/autoresearch/backend/dataset/test_labeling.py
+++ b/products/autoresearch/backend/dataset/test_labeling.py
@@ -23,6 +23,7 @@ from products.autoresearch.backend.dataset.labeling import (
LABELER_QUERY_MODIFIERS,
PREDICTION_EVENT_NAME,
ROLLING_SCORE_LIMIT,
+ SHADOW_MODEL_ROLE,
RollingSelection,
TrainingSample,
TrainingSampleTooLarge,
@@ -733,6 +734,14 @@ class TestAnchoredPopulationsAgainstClickhouse(ClickhouseTestMixin, APIBaseTest)
timestamp=first_cutoff - timedelta(days=1),
properties={"$autoresearch_pipeline_id": "22222222-2222-2222-2222-222222222222"},
)
+ # A shadow model's prediction is not a score of the person, so it must not move them down the ranking.
+ _create_event(
+ team=self.team,
+ event=PREDICTION_EVENT_NAME,
+ distinct_id="active_never_scored",
+ timestamp=first_cutoff - timedelta(days=1),
+ properties={"$autoresearch_pipeline_id": pipeline_id, "$autoresearch_model_role": SHADOW_MODEL_ROLE},
+ )
flush_persons_and_events()
def select(cutoff: Any) -> list[str]:
diff --git a/products/autoresearch/backend/evaluation/AGENTS.md b/products/autoresearch/backend/evaluation/AGENTS.md
index ae9862fd7afe..ba626f0c5192 100644
--- a/products/autoresearch/backend/evaluation/AGENTS.md
+++ b/products/autoresearch/backend/evaluation/AGENTS.md
@@ -21,7 +21,7 @@ It is the only honest number in the product. A holdout AUC of 0.93 says the mode
- **lift@k** (`_lift_at_k`) — how much better than random the top slice is; ties at the boundary score are split fractionally so the number does not depend on row order
- **weekday** — the ISO weekday of the prediction date
- Every model that emitted predictions on the date is scored, whatever its role now. Inference emits the champion only today; when challenger shadow scoring ships, their realized numbers land here without a change, which is what makes challenger promotion decidable on evidence rather than on holdout alone.
+ Every model that emitted predictions on the date is scored, whatever its role now. Inference shadow-scores every model in the shadow set on the champion's people, and each records its own inference run, so their realized numbers land here. That is what makes challenger promotion decidable on evidence rather than on holdout alone. A shadow model's events carry the emitted role `shadow`.
Results land on `AutoresearchModel.realized_score` / `.calibration_error` / `.metrics["realized"]` via `_update_model_realized_metrics()`, and each validated date records an `AutoresearchRun` whose `metrics["per_model"]` keeps the emitted role next to the current one.
The model row keeps only the newest date. The history is on the runs: `online_performance()` in `../facade/api.py` (the pipeline's `online_performance` action and the `autoresearch-online-performance-retrieve` MCP tool) reads the newest completed run per (date, horizon) and returns one row per model per date, so an archived former champion keeps its evidence after a promotion.
@@ -45,7 +45,7 @@ Candidate dates come from Postgres, not from a scan of the events table: the inf
`find_pending_validation_dates()` is what keeps this idempotent. A group is done once a `COMPLETED` validation run holds the same per-model counts as the group's inference runs, so the workflow can run daily without recomputing history, and a later rescore or a new model on the date makes the group pending again and replaces its evidence. A `FAILED` run does not count, so its group is retried. A `RUNNING` validation claim, and a `RUNNING` inference run, hold the group only while younger than `STALE_RUN_AFTER`, so a worker killed mid-run cannot block it forever. Models scored on one date under different horizons are separate groups with their own outcome windows. Maturity waits `OUTCOME_INGESTION_GRACE` past the window end so the last outcome events have reached ClickHouse.
-Both ClickHouse queries are bounded by what the inference runs say was emitted. The prediction fetch must return exactly `rows_scored` persons per model; fewer means ingestion has not caught up with a backfill, more means events the run did not emit, and either fails the date so it is retried instead of completing with wrong numbers. The realized-label scan is restricted to the predicted persons, and its window is the UTC one scoring bound the run to (`[D 00:00, D + horizon 00:00)`). Before the group is marked complete, its inference runs are read again inside the transaction: a run that finished or started while the queries ran fails the group, and a run that slips in after that check changes the counts and makes the group pending again on the next pass. The model rows are locked for the write, so two validators on different dates cannot race the newest-date guard.
+Every ClickHouse query is bounded by what the inference runs say was emitted. The prediction fetch runs one query per model, because HogQL returns at most 50,000 rows whatever the LIMIT, and the champion and its shadow models together can emit more. Each query must return exactly `rows_scored` persons for its model; fewer means ingestion has not caught up with a backfill, more means events the run did not emit, and either fails the date so it is retried instead of completing with wrong numbers. The realized-label scan is restricted to the predicted persons, and its window is the UTC one scoring bound the run to (`[D 00:00, D + horizon 00:00)`). Before the group is marked complete, its inference runs are read again inside the transaction: a run that finished or started while the queries ran fails the group, and a run that slips in after that check changes the counts and makes the group pending again on the next pass. The model rows are locked for the write, so two validators on different dates cannot race the newest-date guard.
All the heavy work — the HogQL queries and the sklearn metrics — happens inside a single Temporal activity. Nothing large crosses a workflow boundary, which is deliberate: activity payloads are capped, and prediction sets are big.
diff --git a/products/autoresearch/backend/evaluation/online_validation.py b/products/autoresearch/backend/evaluation/online_validation.py
index 00aa6f4ee4c4..9a5e15882452 100644
--- a/products/autoresearch/backend/evaluation/online_validation.py
+++ b/products/autoresearch/backend/evaluation/online_validation.py
@@ -47,9 +47,9 @@ from products.autoresearch.backend.query import INTERACTIVE_QUERY, HogQLResult,
logger = structlog.get_logger(__name__)
-# A validation run does two bounded queries and a scoring run is bounded by its sandbox
-# timeouts, so a RUNNING row older than this belongs to a worker that died mid-run and the
-# exception handler never ran. Neither kind may hold a date forever.
+# A validation run does one bounded query per model plus the labels query, and a scoring run
+# is bounded by its sandbox timeouts, so a RUNNING row older than this belongs to a worker that
+# died mid-run and the exception handler never ran. Neither kind may hold a date forever.
STALE_RUN_AFTER = timedelta(hours=6)
# An outcome event timestamped just before the window closes can still be in the ingestion
@@ -472,6 +472,10 @@ def _fetch_predictions(
``rows_scored``: fewer means ingestion has not caught up with a backfill yet, more
means events the run did not emit. Either way the metrics would be wrong, so the date
fails and is retried.
+
+ Each model is fetched in its own query. HogQL returns at most 50,000 rows whatever
+ LIMIT the query asks for. One run scores fewer people than that, but the champion and
+ its shadow models together can score more.
"""
# argMax picks the latest emission per (model, person). Backfills stamp every event of
# a date at the same instant, so the event UUID breaks those ties rather than leaving
@@ -486,28 +490,27 @@ def _fetch_predictions(
f" WHERE{_prediction_filter()}"
" GROUP BY model_id, person_id"
)
- result = _query(
- team=team,
- sql=sql,
- values=_prediction_values(pipeline, pending),
- user=user,
- limit=pending.expected_rows + 1,
- what="Predictions",
- query_context=query_context,
- )
-
roles: dict[str, str] = {}
scores: dict[str, dict[str, float]] = {}
- for model_id, person_id, p_y, emitted_role in result.rows:
- if p_y is None:
- raise OnlineValidationError(
- f"Prediction for person {person_id} of model {model_id} carries a non-numeric $autoresearch_p_y; "
- "refusing to compute metrics from it"
- )
- scores.setdefault(str(model_id), {})[str(person_id)] = float(p_y)
- roles.setdefault(str(model_id), str(emitted_role or ""))
-
for model_id, expected in pending.expected_rows_by_model.items():
+ result = _query(
+ team=team,
+ sql=sql,
+ values={**_prediction_values(pipeline, pending), "model_ids": (model_id,)},
+ user=user,
+ limit=expected + 1,
+ what="Predictions",
+ query_context=query_context,
+ )
+ for row_model_id, person_id, p_y, emitted_role in result.rows:
+ if p_y is None:
+ raise OnlineValidationError(
+ f"Prediction for person {person_id} of model {row_model_id} carries a non-numeric "
+ "$autoresearch_p_y; refusing to compute metrics from it"
+ )
+ scores.setdefault(str(row_model_id), {})[str(person_id)] = float(p_y)
+ roles.setdefault(str(row_model_id), str(emitted_role or ""))
+
found = len(scores.get(model_id, {}))
if found < expected:
raise OnlineValidationError(
diff --git a/products/autoresearch/backend/evaluation/test_online_validation.py b/products/autoresearch/backend/evaluation/test_online_validation.py
index 44bcf70cfd80..fa178bd5d07f 100644
--- a/products/autoresearch/backend/evaluation/test_online_validation.py
+++ b/products/autoresearch/backend/evaluation/test_online_validation.py
@@ -1,7 +1,7 @@
from datetime import UTC, date, datetime, timedelta
import time_machine
-from posthog.test.base import BaseTest
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
@@ -12,6 +12,7 @@ from parameterized import parameterized
from posthog.models.user import User
+from products.autoresearch.backend.dataset.labeling import PREDICTION_EVENT_NAME, SHADOW_MODEL_ROLE
from products.autoresearch.backend.evaluation import online_validation
from products.autoresearch.backend.evaluation.online_validation import (
OUTCOME_INGESTION_GRACE,
@@ -549,3 +550,43 @@ class TestRunOnlineValidationForPipeline(TeamScopedTestMixin, BaseTest):
hogql.assert_not_called()
assert not AutoresearchRun.objects.filter(run_type=AutoresearchRun.RunType.VALIDATION).exists()
+
+
+@time_machine.travel(FROZEN_NOW, tick=False)
+class TestPredictionFetchAgainstClickhouse(ClickhouseTestMixin, TeamScopedTestMixin, BaseTest):
+ def test_a_group_larger_than_the_hogql_row_cap_validates_every_model(self):
+ pipeline = _make_pipeline(self.team, self.user)
+ champion = _make_model(pipeline)
+ shadow = AutoresearchModel.objects.create(
+ pipeline=pipeline, role=AutoresearchModel.Role.CHALLENGER, model_recipe={"stub": True}, recipe_hash="def"
+ )
+ persons = ["person-0", "person-1", "person-2"]
+ for model, role in ((champion, "champion"), (shadow, SHADOW_MODEL_ROLE)):
+ _inference_run(pipeline, model, date(2026, 9, 1), rows_scored=len(persons))
+ for i, person_id in enumerate(persons):
+ _create_event(
+ team=self.team,
+ event=PREDICTION_EVENT_NAME,
+ distinct_id=person_id,
+ timestamp=datetime(2026, 9, 1, 1, tzinfo=UTC),
+ properties={
+ "$autoresearch_pipeline_id": str(pipeline.pk),
+ "$autoresearch_model_id": str(model.pk),
+ "$autoresearch_model_role": role,
+ "$autoresearch_horizon_days": 7,
+ "$autoresearch_p_y": 0.2 * (i + 1),
+ "$autoresearch_prediction_date": "2026-09-01",
+ "$autoresearch_person_id": person_id,
+ },
+ )
+
+ # The two models emitted six predictions together, one more than the cap.
+ with patch("posthog.hogql.constants.MAX_SELECT_RETURNED_ROWS", 5):
+ runs = run_online_validation_for_pipeline(pipeline)
+
+ assert [(r.status, r.error) for r in runs] == [(AutoresearchRun.Status.COMPLETED, "")]
+ per_model = runs[0].metrics["per_model"]
+ assert {model_id: metrics["n_scored"] for model_id, metrics in per_model.items()} == {
+ str(champion.pk): 3,
+ str(shadow.pk): 3,
+ }
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.py
index c60670d1e548..f375e23a23c9 100644
--- a/products/autoresearch/backend/facade/api.py
+++ b/products/autoresearch/backend/facade/api.py
@@ -744,6 +744,8 @@ def _running_inference_run(team_id: int, pipeline: AutoresearchPipeline) -> Auto
status=AutoresearchRun.Status.RUNNING,
started_at__gte=django_timezone.now() - _INFERENCE_RUN_STALE_AFTER,
)
+ # A shadow model's run belongs to the champion's cadence, not to a scoring the caller can poll.
+ .exclude(metrics__has_key="shadow")
.order_by("-started_at")
.first()
)
diff --git a/products/autoresearch/backend/inference/AGENTS.md b/products/autoresearch/backend/inference/AGENTS.md
index 758d02ac76bf..41fa2241552d 100644
--- a/products/autoresearch/backend/inference/AGENTS.md
+++ b/products/autoresearch/backend/inference/AGENTS.md
@@ -1,6 +1,6 @@
# Inference
-Scoring a population with the champion model and writing the result back into PostHog as `autoresearch_prediction` events.
+Scoring a population with the champion model and writing the result back into PostHog as `autoresearch_prediction` events, then scoring the same people with every other model in the shadow set.
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.
@@ -57,6 +57,17 @@ properties: $autoresearch_pipeline_id, $autoresearch_p_y, $autoresearch_p_y_raw
$autoresearch_negative_sample_rate, ...
```
+### Shadow scoring
+
+After a live champion run completes, `_score_shadow_set()` in `scoring.py` scores every other model in `shadow_set()` (`../training/shadow_set.py`). A backfill does not shadow-score.
+
+- **Same people.** Each shadow model scores exactly the persons the champion's run scored, including a rolling subset. Its anchors bind the same cutoff, and a feature result that keys a different set of persons fails that model, because unpaired scores do not compare.
+- **One feature query per distinct `features.sql`.** The digest of the bundle's SQL (`features_sql_digest()`) keys the materialized rows. The champion's rows serve a shadow model with the same SQL, and each other SQL runs once. A failed materialization is cached too. A result is released after the last model that uses it, so the phase does not hold one result per distinct SQL.
+- **Person-less events.** A shadow event has `$autoresearch_model_role` `shadow`, no `$set`, and no person processing, and its `distinct_id` is unique per model and person (`_shadow_distinct_id()`), because ingestion deduplicates on timestamp, distinct_id, token, and event name, not on the UUID. Validation keys on `$autoresearch_person_id`. A shadow score never reaches the output person property. Right before its batch goes out, a shadow model checks that it is still in the set (`_require_still_in_shadow_set()`), in place of `_require_still_champion()`.
+- **Isolated runs.** Each shadow model records its own inference run, with `metrics["shadow"]` set and `scheduled` false, so `find_unscorable_champion()` never reads it, even after the model becomes the champion. A shadow failure fails only that run. The champion's run records `metrics["shadow_models"]`: the models that completed, failed, or were skipped.
+- **The rolling ranking ignores shadow events.** `build_inference_anchors_sql()` counts only non-shadow predictions as scores, so shadow scoring does not change who the champion scores next.
+- **Cost bound.** No new shadow model starts after `SHADOW_TIME_BUDGET_S` (20 minutes). The rest are skipped for that cadence. The inference activity timeout covers the champion's worst case, the budget, and one more model.
+
**Scores are prior-corrected once, in `score_population()`.** A model fitted on a case-control sample (see `../dataset/AGENTS.md`) overstates the odds by `1 / r`, so `corrected_probability()` applies `logit(p) + log(r)`. `$autoresearch_p_y` and the output person property carry the corrected value, `$autoresearch_p_y_raw` the model's own score, and the run records `r` in `AutoresearchRun.negative_sample_rate`.
A bundle's `r` is `AutoresearchModel.negative_sample_rate`, which `fit_champion_model()` saves before it writes `model.pkl`. A recipe-only champion measures its sample at each fit and uses that rate. The stub formula never saw a sample, so its `r` is 1.0. Never correct in a scoring route; a second correction would shrink every probability again.
@@ -75,6 +86,7 @@ The prediction event is itself an event on the person, so every live cadence add
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. A run the daily sweep starts has `scheduled` set. A failed run records `metrics["failure_kind"]` from `classify_failure()` in `failures.py`: `limit_exceeded`, `query_failed` and `model_load_failed` fail again with the same champion, and `other` (transport, capture, cluster capacity, anything unknown) can pass on a retry. Promotion reads the scheduled runs to decide that a champion cannot score.
+6. On a live run that completed, score the other shadow-set models on the same people, each with its own run (see Shadow scoring above).
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.
@@ -91,7 +103,7 @@ Before suspecting the model, check that features, labels, and population all key
- **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`, for a promoted champion and for a challenger that enters the shadow set (`../training/shadow_set.py`). Scoring still reads the champion only. It lives here because it shares the materialization and sandbox machinery with scoring, not because it is part of the inference loop.
+- **Called by training** — `fit_champion_model()` is invoked from the completion path in `../training/promotion.py`, for a promoted champion and for a challenger that enters the shadow set (`../training/shadow_set.py`). Scoring then loads the fitted challengers for shadow scoring. 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.
diff --git a/products/autoresearch/backend/inference/sandbox.py b/products/autoresearch/backend/inference/sandbox.py
index 6aec485d7e7e..4887034399bc 100644
--- a/products/autoresearch/backend/inference/sandbox.py
+++ b/products/autoresearch/backend/inference/sandbox.py
@@ -40,6 +40,7 @@ import io
import json
import math
import base64
+import hashlib
import binascii
from dataclasses import field
from datetime import UTC, datetime
@@ -181,6 +182,14 @@ class InferenceRows:
eligible: int
+@frozen
+class MaterializedFeatures:
+ """The inference rows of one ``features.sql`` at one cutoff, so a second model with the same SQL reuses them."""
+
+ sql_digest: str
+ data: InferenceRows
+
+
@frozen
class SandboxScoreResult:
scored_rows: list[dict[str, Any]] # score rows with an added "p_y"
@@ -188,6 +197,11 @@ class SandboxScoreResult:
n_train: int
n_features: int
rows_eligible: int
+ features: MaterializedFeatures | None = None
+
+
+def features_sql_digest(feature_sql: str) -> str:
+ return hashlib.sha256(feature_sql.encode("utf-8")).hexdigest()
# ── Public entry point ─────────────────────────────────────────────────────────
@@ -260,15 +274,20 @@ def score_via_sandbox(
cutoff_ts: int | None = None,
user: User | None = None,
query_context: QueryContext = INTERACTIVE_QUERY,
+ bundle: ArtifactBundle | None = None,
+ score_data: InferenceRows | None = None,
) -> SandboxScoreResult:
"""
- Predict run: score the inference population with the champion's persisted model.
+ Predict run: score the inference population with the model's persisted ``model.pkl``.
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.
+ Shadow scoring passes the ``bundle`` it already read, and the ``score_data`` another
+ model materialized from the same ``features.sql``, so that query runs once per cadence.
+
Raises SandboxInferenceError on any failure (missing bundle or model, no data,
sandbox or script error). Never falls back to stub scoring.
"""
@@ -276,10 +295,11 @@ def score_via_sandbox(
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
+ 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)
@@ -287,14 +307,16 @@ def score_via_sandbox(
if not model_bytes:
raise ModelLoadError(f"Champion model.pkl is missing at {prefix}; the completion-time fit has not produced it")
- score_data = _materialize_score_data(
- team=team,
- pipeline=pipeline,
- feature_sql=bundle.features_sql,
- cutoff_ts=cutoff_ts,
- user=acting_user,
- query_context=query_context,
- )
+ if score_data is None:
+ score_data = _materialize_score_data(
+ team=team,
+ pipeline=pipeline,
+ feature_sql=bundle.features_sql,
+ cutoff_ts=cutoff_ts,
+ user=acting_user,
+ query_context=query_context,
+ )
+ features = MaterializedFeatures(sql_digest=features_sql_digest(bundle.features_sql), data=score_data)
score_rows = score_data.rows
n_train = int((model.metrics or {}).get("n_train") or 0)
# A population that matches nobody today is a real zero, not a failure: retrying cannot
@@ -306,6 +328,7 @@ def score_via_sandbox(
n_train=n_train,
n_features=0,
rows_eligible=score_data.eligible,
+ features=features,
)
feature_cols = _fitted_feature_cols(prefix) or _numeric_feature_cols(score_rows)
# Cheap guard before paying for a sandbox.
@@ -321,6 +344,7 @@ def score_via_sandbox(
n_train=n_train,
n_features=len(feature_cols),
rows_eligible=score_data.eligible,
+ features=features,
)
diff --git a/products/autoresearch/backend/inference/scoring.py b/products/autoresearch/backend/inference/scoring.py
index f06a433a66f5..2fab26023034 100644
--- a/products/autoresearch/backend/inference/scoring.py
+++ b/products/autoresearch/backend/inference/scoring.py
@@ -7,6 +7,9 @@ autoresearch_prediction event per person.
AutoresearchRun, scores, and emits.
- ``score_population()`` is the scoring half on its own, for a dry run that wants
the scores without the events.
+- After a live champion run completes, every other model in the shadow set scores the
+ same people (``_score_shadow_set()``). A shadow model emits person-less events with the
+ ``shadow`` role and no ``$set``, and records its own inference run.
Event shape:
event: autoresearch_prediction
@@ -14,7 +17,7 @@ Event shape:
properties:
$autoresearch_pipeline_id: str (UUID)
$autoresearch_model_id: str (UUID)
- $autoresearch_model_role: "champion" | "challenger"
+ $autoresearch_model_role: "champion" | "shadow"
$autoresearch_target_event: str
$autoresearch_horizon_days: int
$autoresearch_p_y: float (the score, prior-corrected for negative sampling)
@@ -28,11 +31,13 @@ Event shape:
import json
import math
+import time
import uuid
import hashlib
import inspect
import importlib
import dataclasses
+from collections.abc import Callable
from datetime import UTC, date, datetime
from typing import Any
@@ -55,6 +60,7 @@ from products.autoresearch.backend.dataset.labeling import (
IDENTIFIED_USERS_ONLY,
LABELER_QUERY_MODIFIERS,
PREDICTION_EVENT_NAME,
+ SHADOW_MODEL_ROLE,
RollingSelection,
build_inference_anchors_sql,
build_inference_features_sql,
@@ -69,23 +75,29 @@ from products.autoresearch.backend.inference.sandbox import (
_MATERIALIZE_ROW_LIMIT,
_MAX_FEATURE_COLS,
InferenceRows,
+ MaterializedFeatures,
SandboxInferenceError,
+ _materialize_score_data,
_num,
_numeric_feature_cols,
_resolve_acting_user,
+ _validate_bundle_feature_sql,
count_inference_anchors,
count_training_anchors,
+ features_sql_digest,
measure_training_sample,
score_via_sandbox,
validate_runnable_feature_sql,
)
from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRun
from products.autoresearch.backend.query import INTERACTIVE_QUERY, HogQLResult, QueryContext, run_hogql
+from products.autoresearch.backend.training.artifacts import ArtifactBundle, read_bundle
from products.autoresearch.backend.training.recipe_validation import (
RecipeValidationError,
validate_model_class,
validate_unique_distinct_ids,
)
+from products.autoresearch.backend.training.shadow_set import shadow_set
logger = structlog.get_logger(__name__)
@@ -101,6 +113,9 @@ _RESERVED_COLS = frozenset({"distinct_id", _LABEL_COL, _FOLD_COL})
_SCORE_KEYS = frozenset({"p_y", "p_y_raw"})
# A capture error description can hold a URL and an exception repr, so the run error clips it.
_MAX_EMIT_ERROR_DESCRIPTION_CHARS = 200
+# Shadow scoring starts no new model after this many seconds. The model in progress at the limit
+# still finishes, so the inference activity timeout covers the budget plus one more model.
+SHADOW_TIME_BUDGET_S = 20 * 60
# Namespace for deterministic prediction event UUIDs, so a retried scoring activity
@@ -147,6 +162,8 @@ class ScoredPopulation:
# Persons in the inference population at the cutoff. Above len(rows) when the population
# reached the cap and the run scored a rolling subset. None when the run did not count it.
rows_eligible: int | None = None
+ # The bundle's feature rows, so a shadow model with the same features.sql reuses them.
+ features: MaterializedFeatures | None = None
def corrected_probability(p: float, negative_sample_rate: float) -> float:
@@ -166,7 +183,11 @@ def _apply_prior_correction(scored: ScoredPopulation) -> ScoredPopulation:
rate = scored.negative_sample_rate
rows = [{**row, "p_y_raw": row["p_y"], "p_y": corrected_probability(row["p_y"], rate)} for row in scored.rows]
return ScoredPopulation(
- rows=rows, holdout_auc=scored.holdout_auc, negative_sample_rate=rate, rows_eligible=scored.rows_eligible
+ rows=rows,
+ holdout_auc=scored.holdout_auc,
+ negative_sample_rate=rate,
+ rows_eligible=scored.rows_eligible,
+ features=scored.features,
)
@@ -216,8 +237,23 @@ class _EmitResult:
def create_inference_run(
- *, pipeline: AutoresearchPipeline, model: AutoresearchModel, window: ScoringWindow, scheduled: bool = False
+ *,
+ pipeline: AutoresearchPipeline,
+ model: AutoresearchModel,
+ window: ScoringWindow,
+ scheduled: bool = False,
+ shadow: bool = False,
) -> AutoresearchRun:
+ # Online validation discovers matured dates from these two keys instead of scanning
+ # the events table, validates against the horizon scored here rather than the
+ # pipeline's current one, and waits for a run that is still scoring the date.
+ metrics: dict[str, Any] = {
+ "prediction_date": window.prediction_date.isoformat(),
+ "horizon_days": pipeline.horizon_days,
+ }
+ if shadow:
+ # Readers of the champion's runs, such as the manual-scoring dedupe, skip a run with this key.
+ metrics["shadow"] = True
return AutoresearchRun.objects.create(
pipeline=pipeline,
model=model,
@@ -225,10 +261,7 @@ def create_inference_run(
scheduled=scheduled,
status=AutoresearchRun.Status.RUNNING,
started_at=django_timezone.now(),
- # Online validation discovers matured dates from these two keys instead of scanning
- # the events table, validates against the horizon scored here rather than the
- # pipeline's current one, and waits for a run that is still scoring the date.
- metrics={"prediction_date": window.prediction_date.isoformat(), "horizon_days": pipeline.horizon_days},
+ metrics=metrics,
)
@@ -261,6 +294,10 @@ def run_inference_for_pipeline(
``scheduled`` marks a run the daily sweep started. Promotion counts only those runs when
it decides that the champion cannot score.
+
+ A live run that completes then scores the rest of the shadow set (``_score_shadow_set()``).
+ Shadow scoring never fails this run or changes its outcome; the run records which shadow
+ models completed, failed, or were skipped in ``metrics["shadow_models"]``.
"""
window = ScoringWindow.for_date(prediction_date)
if run is None:
@@ -312,7 +349,6 @@ def run_inference_for_pipeline(
rows_scored=emitted.rows_emitted,
rows_eligible=scored.rows_eligible,
)
- return run
except Exception as exc:
run.status = AutoresearchRun.Status.FAILED
@@ -325,6 +361,26 @@ def run_inference_for_pipeline(
)
raise
+ if not window.is_backfill:
+ try:
+ outcome = _score_shadow_set(
+ team=team,
+ pipeline=pipeline,
+ champion=model,
+ scored=scored,
+ window=window,
+ user=acting_user,
+ query_context=query_context,
+ )
+ except Exception:
+ # The champion's run is already complete. Nothing in the shadow phase may change that.
+ logger.exception("autoresearch_shadow_scoring_failed", pipeline_id=str(pipeline.pk))
+ else:
+ if outcome is not None:
+ run.metrics["shadow_models"] = outcome.as_metrics()
+ run.save(update_fields=["metrics"])
+ return run
+
def _acting_user(*, team: Team, pipeline: AutoresearchPipeline, user: User | None) -> User:
try:
@@ -428,6 +484,7 @@ def _score_population_raw(
holdout_auc=result.holdout_auc,
negative_sample_rate=model.negative_sample_rate,
rows_eligible=result.rows_eligible,
+ features=result.features,
)
if window.is_backfill:
@@ -476,12 +533,16 @@ def _emit_predictions(
scored: ScoredPopulation,
window: ScoringWindow,
user: User,
+ shadow: bool = False,
) -> _EmitResult:
"""
Send one prediction event per scored row in one batch. Any failed event fails the run:
the event UUIDs are deterministic, so the retry re-sends every row and ingestion keeps
one copy, whereas completing with a partial batch would advance the cadence past the
people who never received their prediction or output property.
+
+ A ``shadow`` batch is person-less, like a backfill: no person processing and no ``$set``,
+ so a shadow score never reaches the output person property or the person's timeline.
"""
if not scored.rows:
logger.warning("autoresearch_no_scored_rows", pipeline_id=str(pipeline.pk), team_id=team.pk)
@@ -491,14 +552,18 @@ def _emit_predictions(
prediction_date_str = window.prediction_date.isoformat()
emit_timestamp = window.emit_timestamp
- _require_still_champion(model)
+ person_less = is_backfill or shadow
+ if shadow:
+ _require_still_in_shadow_set(pipeline=pipeline, model=model)
+ else:
+ _require_still_champion(model)
# Live runs attach each prediction to the real person: a real distinct_id, a processed
- # person profile, and a $set of the output property. Backfills stay person-less (they
- # exist for online validation, which keys on $autoresearch_person_id) so a past-dated
- # $set cannot clobber a live score.
+ # person profile, and a $set of the output property. Backfills and shadow scores stay
+ # person-less (they exist for online validation, which keys on $autoresearch_person_id)
+ # so a past-dated or shadow $set cannot clobber the champion's live score.
distinct_id_by_person = (
{}
- if is_backfill
+ if person_less
else _resolve_distinct_ids(
team=team, pipeline=pipeline, person_ids=[str(row["distinct_id"]) for row in scored.rows], user=user
)
@@ -519,7 +584,7 @@ def _emit_predictions(
props: dict[str, Any] = {
"$autoresearch_pipeline_id": str(pipeline.pk),
"$autoresearch_model_id": str(model.pk),
- "$autoresearch_model_role": model.role,
+ "$autoresearch_model_role": SHADOW_MODEL_ROLE if shadow else model.role,
"$autoresearch_target_event": pipeline.target_event,
"$autoresearch_horizon_days": pipeline.horizon_days,
"$autoresearch_p_y": row["p_y"],
@@ -535,7 +600,9 @@ def _emit_predictions(
events.append(
{
"event": PREDICTION_EVENT_NAME,
- "distinct_id": real_distinct_id or person_id,
+ "distinct_id": _shadow_distinct_id(model_id=str(model.pk), person_id=person_id)
+ if shadow
+ else real_distinct_id or person_id,
"timestamp": emit_timestamp,
"properties": props,
"options": {"process_person_profile": attach_to_person},
@@ -555,7 +622,7 @@ def _emit_predictions(
events=events,
token=team.api_token,
event_source=EVENT_SOURCE,
- process_person_profile=not is_backfill,
+ process_person_profile=not person_less,
)
except Exception as exc:
logger.exception("autoresearch_prediction_emit_failed", pipeline_id=str(pipeline.pk))
@@ -591,6 +658,15 @@ def _emit_predictions(
)
+def _shadow_distinct_id(*, model_id: str, person_id: str) -> str:
+ """
+ Ingestion deduplicates events on timestamp, distinct_id, token, and event name, not on the UUID.
+ Every shadow event of a run shares one timestamp, so each model needs its own distinct_id per
+ person, or one model's prediction would drop another's, or the champion's for an unresolved person.
+ """
+ return f"autoresearch-shadow:{model_id}:{person_id}"
+
+
def _require_still_champion(model: AutoresearchModel) -> None:
"""
Promotion can swap the champion while a run is scoring with the old one. Re-reading the
@@ -606,6 +682,228 @@ def _require_still_champion(model: AutoresearchModel) -> None:
)
+def _require_still_in_shadow_set(*, pipeline: AutoresearchPipeline, model: AutoresearchModel) -> None:
+ """The shadow counterpart of ``_require_still_champion()``: a model that left the set does not emit."""
+ shadow_ids = {member.pk for member in shadow_set(pipeline) if member.role != AutoresearchModel.Role.CHAMPION}
+ if model.pk not in shadow_ids:
+ raise InferenceRunError(f"Model {model.pk} left the shadow set while this run was scoring")
+
+
+# ── Shadow set ─────────────────────────────────────────────────────────────────────
+
+
+@frozen
+class ShadowScoringOutcome:
+ completed: list[str]
+ failed: list[str]
+ # Models the time budget left unscored this cadence.
+ skipped: list[str]
+
+ def as_metrics(self) -> dict[str, list[str]]:
+ return {"completed": self.completed, "failed": self.failed, "skipped": self.skipped}
+
+
+def _score_shadow_set(
+ *,
+ team: Team,
+ pipeline: AutoresearchPipeline,
+ champion: AutoresearchModel,
+ scored: ScoredPopulation,
+ window: ScoringWindow,
+ user: User,
+ query_context: QueryContext = INTERACTIVE_QUERY,
+ clock: Callable[[], float] = time.monotonic,
+) -> ShadowScoringOutcome | None:
+ """
+ Score every shadow-set model other than the champion against the people the champion's run
+ scored, so online validation compares the models on the same people on the same date.
+
+ One feature query runs per distinct ``features.sql``: the champion's rows are reused when a
+ shadow model shares its SQL, and each other SQL materializes once for every model that uses
+ it. Each model records its own inference run, and its failure fails only that run. No new
+ model starts after ``SHADOW_TIME_BUDGET_S``. Returns None when there is nothing to score.
+ """
+ members = [model for model in shadow_set(pipeline) if model.pk != champion.pk]
+ if not members or not scored.rows:
+ return None
+ persons = {str(row["distinct_id"]) for row in scored.rows}
+ materialized: dict[str, InferenceRows | Exception] = {}
+ if scored.features is not None:
+ materialized[scored.features.sql_digest] = scored.features.data
+
+ completed: list[str] = []
+ failed: list[str] = []
+ skipped: list[str] = []
+ started = clock()
+ bundles = [_read_shadow_bundle(model) for model in members]
+ digests = [
+ None if isinstance(bundle, Exception) else features_sql_digest(bundle.features_sql) for bundle in bundles
+ ]
+ last_use = {digest: index for index, digest in enumerate(digests) if digest is not None}
+ for index, model in enumerate(members):
+ if clock() - started >= SHADOW_TIME_BUDGET_S:
+ skipped.append(str(model.pk))
+ continue
+ ok = _score_shadow_model(
+ team=team,
+ pipeline=pipeline,
+ model=model,
+ bundle=bundles[index],
+ persons=persons,
+ materialized=materialized,
+ window=window,
+ user=user,
+ query_context=query_context,
+ )
+ (completed if ok else failed).append(str(model.pk))
+ digest = digests[index]
+ if digest is not None and last_use[digest] == index:
+ # Each result can hold tens of thousands of wide rows, so the phase keeps only the
+ # results a later model still needs, not one result per distinct SQL.
+ materialized.pop(digest, None)
+ if skipped:
+ logger.warning("autoresearch_shadow_scoring_over_budget", pipeline_id=str(pipeline.pk), skipped=len(skipped))
+ return ShadowScoringOutcome(completed=completed, failed=failed, skipped=skipped)
+
+
+def _read_shadow_bundle(model: AutoresearchModel) -> ArtifactBundle | Exception:
+ """The model's runnable bundle, or the error that fails its run. The error never stops the other models."""
+ try:
+ bundle = read_bundle(model.artifact_prefix)
+ _validate_bundle_feature_sql(bundle)
+ except Exception as exc:
+ return exc
+ return bundle
+
+
+def _score_shadow_model(
+ *,
+ team: Team,
+ pipeline: AutoresearchPipeline,
+ model: AutoresearchModel,
+ bundle: ArtifactBundle | Exception,
+ persons: set[str],
+ materialized: dict[str, InferenceRows | Exception],
+ window: ScoringWindow,
+ user: User,
+ query_context: QueryContext,
+) -> bool:
+ """
+ Score one shadow model and record its run. The run is never ``scheduled``, so it cannot
+ count toward or break an unscorable streak, even after the model becomes the champion.
+ """
+ run = create_inference_run(pipeline=pipeline, model=model, window=window, shadow=True)
+ try:
+ if isinstance(bundle, Exception):
+ raise InferenceRunError(
+ f"Could not read a runnable bundle at {model.artifact_prefix}: {bundle}"
+ ) from bundle
+ score_data = _shadow_score_data(
+ team=team,
+ pipeline=pipeline,
+ feature_sql=bundle.features_sql,
+ persons=persons,
+ materialized=materialized,
+ window=window,
+ user=user,
+ query_context=query_context,
+ )
+ result = score_via_sandbox(
+ team=team,
+ pipeline=pipeline,
+ model=model,
+ cutoff_ts=window.cutoff_ts,
+ user=user,
+ query_context=query_context,
+ bundle=bundle,
+ score_data=score_data,
+ )
+ scored = _apply_prior_correction(
+ ScoredPopulation(
+ rows=result.scored_rows,
+ holdout_auc=result.holdout_auc,
+ negative_sample_rate=model.negative_sample_rate,
+ rows_eligible=result.rows_eligible,
+ )
+ )
+ emitted = _emit_predictions(
+ team=team, pipeline=pipeline, model=model, run=run, scored=scored, window=window, user=user, shadow=True
+ )
+ except Exception as exc:
+ run.status = AutoresearchRun.Status.FAILED
+ run.error = str(exc)[:2000]
+ run.metrics["failure_kind"] = classify_failure(exc)
+ run.completed_at = django_timezone.now()
+ run.save(update_fields=["status", "error", "metrics", "completed_at"])
+ logger.exception(
+ "autoresearch_shadow_model_failed",
+ pipeline_id=str(pipeline.pk),
+ model_id=str(model.pk),
+ failure_kind=run.metrics["failure_kind"],
+ )
+ return False
+
+ run.status = AutoresearchRun.Status.COMPLETED
+ run.rows_scored = emitted.rows_emitted
+ run.negative_sample_rate = scored.negative_sample_rate
+ run.metrics.update(
+ {
+ "score_distribution": emitted.score_distribution,
+ "stub": False,
+ "sandbox": True,
+ "holdout_auc": scored.holdout_auc,
+ "rows_eligible": scored.rows_eligible,
+ }
+ )
+ run.completed_at = django_timezone.now()
+ run.save(update_fields=["status", "rows_scored", "negative_sample_rate", "metrics", "completed_at"])
+ return True
+
+
+def _shadow_score_data(
+ *,
+ team: Team,
+ pipeline: AutoresearchPipeline,
+ feature_sql: str,
+ persons: set[str],
+ materialized: dict[str, InferenceRows | Exception],
+ window: ScoringWindow,
+ user: User,
+ query_context: QueryContext,
+) -> InferenceRows:
+ """
+ The feature rows for ``feature_sql``, materialized once per digest. A failure is cached too,
+ so a second model with the same broken SQL fails without a second query.
+
+ The anchors bind the run's cutoff, so the selection repeats the champion's. Rows that key a
+ different set of people (an event that landed late moved the rolling ranking) fail the
+ models that use them, because unpaired scores would not compare with the champion's.
+ """
+ digest = features_sql_digest(feature_sql)
+ if digest not in materialized:
+ try:
+ data = _materialize_score_data(
+ team=team,
+ pipeline=pipeline,
+ feature_sql=feature_sql,
+ cutoff_ts=window.cutoff_ts,
+ user=user,
+ query_context=query_context,
+ )
+ if {str(row["distinct_id"]) for row in data.rows} != persons:
+ raise InferenceRunError(
+ "The shadow feature query did not select the people the champion scored; "
+ "refusing to emit scores that do not pair with the champion's"
+ )
+ materialized[digest] = data
+ except Exception as exc:
+ materialized[digest] = exc
+ cached = materialized[digest]
+ if isinstance(cached, Exception):
+ raise cached
+ return cached
+
+
# ── Queries ────────────────────────────────────────────────────────────────────────
diff --git a/products/autoresearch/backend/inference/test_inference.py b/products/autoresearch/backend/inference/test_inference.py
index bcfb966a1cd7..a0726f747c7a 100644
--- a/products/autoresearch/backend/inference/test_inference.py
+++ b/products/autoresearch/backend/inference/test_inference.py
@@ -13,6 +13,7 @@ from parameterized import parameterized
from posthog.hogql.errors import QueryError
from posthog.api.capture import CaptureInternalResult
+from posthog.dataclasses import frozen
from posthog.exceptions import (
ClickHouseClusterMemoryLimitExceeded,
ClickHouseQueryMemoryLimitExceeded,
@@ -24,7 +25,15 @@ from products.autoresearch.backend.inference import (
sandbox as sandbox_inference,
scoring,
)
-from products.autoresearch.backend.inference.sandbox import _MATERIALIZE_ROW_LIMIT, InferenceRows, SandboxScoreResult
+from products.autoresearch.backend.inference.failures import find_unscorable_champion
+from products.autoresearch.backend.inference.sandbox import (
+ _MATERIALIZE_ROW_LIMIT,
+ InferenceRows,
+ MaterializedFeatures,
+ ModelLoadError,
+ SandboxScoreResult,
+ features_sql_digest,
+)
from products.autoresearch.backend.inference.scoring import (
InferenceRunError,
ScoredPopulation,
@@ -42,6 +51,7 @@ from products.autoresearch.backend.inference.scoring import (
from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRun
from products.autoresearch.backend.query import BATCH_QUERY, HogQLResult
from products.autoresearch.backend.testing import TeamScopedTestMixin
+from products.autoresearch.backend.training.artifacts import ArtifactBundle
_STUB_RECIPE = {
"feature_sql": "SELECT person_id AS distinct_id, count() AS events_total_30d FROM events GROUP BY person_id",
@@ -985,3 +995,164 @@ class TestRecipeFit(SimpleTestCase):
_fit_on_training_predict_on_inference(
training_rows=rows, inference_rows=rows[:2], recipe=_ANCHORS_RECIPE, pipeline_id="p"
)
+
+
+_SHADOW_ROWS = [
+ {"distinct_id": "user-1", "events_total": 3},
+ {"distinct_id": "user-2", "events_total": 1},
+]
+_OTHER_FEATURE_SQL = "SELECT a.person_id AS distinct_id, count() AS n FROM {anchors} a GROUP BY a.person_id"
+
+
+@frozen
+class _Cadence:
+ run: AutoresearchRun
+ capture: MagicMock
+ materialize: MagicMock
+
+
+@time_machine.travel("2026-09-11T12:00:00Z", tick=False)
+class TestShadowScoring(TeamScopedTestMixin, BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.pipeline = AutoresearchPipeline.objects.create(
+ team=self.team,
+ created_by=self.user,
+ name="Test",
+ target_event="$pageview",
+ horizon_days=7,
+ output_person_property="predicted_p_pageview",
+ )
+ self.sql_by_prefix: dict[str, str] = {}
+ self.champion = self._model("champion", _ANCHORS_FEATURE_SQL, role=AutoresearchModel.Role.CHAMPION)
+
+ def _model(self, name: str, features_sql: str, role: str = AutoresearchModel.Role.CHALLENGER) -> AutoresearchModel:
+ prefix = f"tasks/autoresearch/{name}"
+ self.sql_by_prefix[prefix] = features_sql
+ return AutoresearchModel.objects.create(
+ pipeline=self.pipeline,
+ role=role,
+ artifact_prefix=prefix,
+ model_recipe={"feature_sql": features_sql},
+ recipe_hash=name,
+ holdout_score=0.7,
+ metrics={"model_fitted": True},
+ )
+
+ def _run(self, *, failing: dict[str, Exception] | None = None, shadow_rows=_SHADOW_ROWS) -> _Cadence:
+ failing = failing or {}
+ materialize = MagicMock(return_value=InferenceRows(rows=shadow_rows, eligible=len(shadow_rows)))
+
+ def fake_sandbox(**kwargs):
+ model = kwargs["model"]
+ if str(model.pk) in failing:
+ raise failing[str(model.pk)]
+ data = kwargs.get("score_data") or InferenceRows(rows=_SHADOW_ROWS, eligible=len(_SHADOW_ROWS))
+ features_sql = self.sql_by_prefix[model.artifact_prefix]
+ return SandboxScoreResult(
+ scored_rows=[{**row, "p_y": 0.4} for row in data.rows],
+ holdout_auc=0.7,
+ n_train=10,
+ n_features=1,
+ rows_eligible=data.eligible,
+ features=MaterializedFeatures(sql_digest=features_sql_digest(features_sql), data=data),
+ )
+
+ capture = _capture_accepting_everything()
+ with (
+ patch.object(
+ scoring,
+ "read_bundle",
+ side_effect=lambda prefix: ArtifactBundle(
+ train_py="# train", predict_py="# predict", features_sql=self.sql_by_prefix[prefix]
+ ),
+ ),
+ patch.object(scoring, "score_via_sandbox", side_effect=fake_sandbox),
+ patch.object(scoring, "_materialize_score_data", materialize),
+ patch.object(scoring, "_resolve_distinct_ids", return_value={"user-1": "real-1", "user-2": "real-2"}),
+ patch.object(scoring, "capture_batch_internal", capture),
+ ):
+ run = run_inference_for_pipeline(pipeline=self.pipeline, model=self.champion)
+ return _Cadence(run=run, capture=capture, materialize=materialize)
+
+ def _shadow_runs(self, model: AutoresearchModel) -> list[AutoresearchRun]:
+ return list(AutoresearchRun.objects.filter(model=model, run_type=AutoresearchRun.RunType.INFERENCE))
+
+ def test_each_shadow_model_scores_the_champions_people_person_less(self):
+ other_a = self._model("other_a", _OTHER_FEATURE_SQL)
+ same_sql = self._model("same_sql", _ANCHORS_FEATURE_SQL)
+ other_b = self._model("other_b", _OTHER_FEATURE_SQL)
+
+ cadence = self._run()
+ run, capture, materialize = cadence.run, cadence.capture, cadence.materialize
+
+ assert run.status == AutoresearchRun.Status.COMPLETED
+ # The champion's rows serve the model with its SQL; the two models with the other SQL share one
+ # query, although the shadow set scores same_sql between them.
+ assert materialize.call_count == 1
+ assert materialize.call_args.kwargs["feature_sql"] == _OTHER_FEATURE_SQL
+ assert sorted(run.metrics["shadow_models"]["completed"]) == sorted(
+ str(m.pk) for m in (same_sql, other_a, other_b)
+ )
+ for model in (same_sql, other_a, other_b):
+ [shadow_run] = self._shadow_runs(model)
+ assert shadow_run.status == AutoresearchRun.Status.COMPLETED
+ assert shadow_run.rows_scored == run.rows_scored
+ assert shadow_run.scheduled is False
+ assert shadow_run.metrics["prediction_date"] == run.metrics["prediction_date"]
+ assert shadow_run.metrics["horizon_days"] == run.metrics["horizon_days"]
+
+ champion_call, *shadow_calls = capture.call_args_list
+ for event in champion_call.kwargs["events"]:
+ assert event["properties"]["$autoresearch_model_role"] == AutoresearchModel.Role.CHAMPION
+ assert "$set" in event["properties"]
+ assert len(shadow_calls) == 3
+ for call in shadow_calls:
+ assert call.kwargs["process_person_profile"] is False
+ for event in call.kwargs["events"]:
+ assert event["properties"]["$autoresearch_model_role"] == "shadow"
+ assert "$set" not in event["properties"]
+ assert event["options"] == {"process_person_profile": False}
+ # Ingestion deduplicates on (timestamp, distinct_id, event), so no two predictions may share that key.
+ all_events = [event for call in capture.call_args_list for event in call.kwargs["events"]]
+ dedup_keys = {(e["timestamp"], e["distinct_id"], e["event"]) for e in all_events}
+ assert len(dedup_keys) == len(all_events)
+
+ @parameterized.expand(
+ [
+ ("model_load_failure", ModelLoadError("predict.py failed"), _SHADOW_ROWS, "model_load_failed"),
+ ("unpaired_rows", None, _SHADOW_ROWS[:1], "other"),
+ ]
+ )
+ def test_a_failing_shadow_model_never_touches_the_champion(self, _name, error, shadow_rows, failure_kind):
+ challenger = self._model("challenger", _OTHER_FEATURE_SQL)
+ failing = {str(challenger.pk): error} if error else {}
+
+ for day in ("2026-09-11T12:00:00Z", "2026-09-12T12:00:00Z"):
+ with time_machine.travel(day, tick=False):
+ run = self._run(failing=failing, shadow_rows=shadow_rows).run
+ assert run.status == AutoresearchRun.Status.COMPLETED
+ assert run.metrics["shadow_models"]["failed"] == [str(challenger.pk)]
+
+ shadow_runs = self._shadow_runs(challenger)
+ assert [r.status for r in shadow_runs] == [AutoresearchRun.Status.FAILED] * 2
+ assert {r.metrics["failure_kind"] for r in shadow_runs} == {failure_kind}
+ self.pipeline.refresh_from_db()
+ assert self.pipeline.last_scored_at is not None
+ # Two failed days of shadow runs must not make the model read as unscorable once it is promoted.
+ AutoresearchModel.objects.filter(pk=self.champion.pk).update(role=AutoresearchModel.Role.ARCHIVED)
+ AutoresearchModel.objects.filter(pk=challenger.pk).update(role=AutoresearchModel.Role.CHAMPION)
+ challenger.refresh_from_db()
+ assert find_unscorable_champion(challenger) is None
+
+ def test_shadow_models_past_the_time_budget_are_skipped_and_recorded(self):
+ challenger = self._model("challenger", _OTHER_FEATURE_SQL)
+
+ with patch.object(scoring, "SHADOW_TIME_BUDGET_S", 0):
+ cadence = self._run()
+ run, capture = cadence.run, cadence.capture
+
+ assert run.status == AutoresearchRun.Status.COMPLETED
+ assert run.metrics["shadow_models"] == {"completed": [], "failed": [], "skipped": [str(challenger.pk)]}
+ assert self._shadow_runs(challenger) == []
+ assert capture.call_count == 1
diff --git a/products/autoresearch/backend/temporal/workflows.py b/products/autoresearch/backend/temporal/workflows.py
index 12c5d35cd6a8..1c7d1775ca96 100644
--- a/products/autoresearch/backend/temporal/workflows.py
+++ b/products/autoresearch/backend/temporal/workflows.py
@@ -192,7 +192,9 @@ def inference_workflow_id(pipeline_id: str, prediction_date: str) -> str:
# ── Workflow ─────────────────────────────────────────────────────────────────
# Scoring can take minutes for large populations. The recipe path runs at most five batch
-# queries in sequence, so one attempt covers all of them at the full limit.
+# queries in sequence (50 minutes at the full limit). Shadow scoring then starts models for up to
+# SHADOW_TIME_BUDGET_S (20 minutes), and the last model it starts runs an anchor count, a feature
+# query, and a predict sandbox (about 30 minutes at worst). One attempt covers all of it.
_SCORE_RETRY = RetryPolicy(maximum_attempts=2, initial_interval=timedelta(seconds=30))
_SCORE_ATTEMPT_TIMEOUT = timedelta(hours=2)
# A lost worker is detected in minutes rather than at the end of a multi-hour attempt.
@@ -289,12 +291,13 @@ class RunValidationResult:
# Validation does all its work (HogQL + sklearn) inside a single activity to
# keep the Temporal payload small — we only return summary counts, not raw data.
_VALIDATION_RETRY = RetryPolicy(maximum_attempts=2, initial_interval=timedelta(seconds=30))
-# Each date runs two batch queries of up to HOGQL_INCREASED_MAX_EXECUTION_TIME (600 s) each.
-# An attempt claims another date only while that worst case, plus the metrics and writes, still
-# fits in the attempt. The rest of a larger backlog stays pending for the next sweep, so the
-# attempt completes instead of timing out part-way.
+# Each date runs one predictions query per model that scored it, up to the five models of a
+# shadow set, plus one realized-labels query. Each takes up to HOGQL_INCREASED_MAX_EXECUTION_TIME
+# (600 s). An attempt claims another date only while that worst case, plus the metrics and
+# writes, still fits in the attempt. The rest of a larger backlog stays pending for the next
+# sweep, so the attempt completes instead of timing out part-way.
_VALIDATION_ATTEMPT_TIMEOUT = timedelta(hours=2)
-_VALIDATION_DATE_RESERVE = timedelta(minutes=30)
+_VALIDATION_DATE_RESERVE = timedelta(minutes=70)
# Covers both attempts plus their backoff, as for inference.
_VALIDATION_WORKFLOW_TIMEOUT = timedelta(hours=5)
diff --git a/products/autoresearch/backend/training/AGENTS.md b/products/autoresearch/backend/training/AGENTS.md
index f8bb92fb5f12..6854e62ff780 100644
--- a/products/autoresearch/backend/training/AGENTS.md
+++ b/products/autoresearch/backend/training/AGENTS.md
@@ -48,7 +48,7 @@ The other half is `../inference/`, which consumes what this package produces and
`shadow_set(pipeline)` computes the models worth scoring side by side. Nothing stores the set.
It holds the champion, the previous champion (the newest archived bundle-backed row with `promoted_at` set), and up to `SHADOW_CHALLENGER_LIMIT` (3) fitted bundle-backed challengers. No two members share a `recipe_hash`.
A challenger younger than `horizon_days + SHADOW_MIN_MATURED_DATES` days keeps its place, so a new challenger cannot displace it. Past that age, a newer challenger displaces it. A challenger that does not enter at completion is never fitted, so it cannot enter later.
- The models API exposes membership as `in_shadow_set`. Nothing scores or promotes from the set yet.
+ The models API exposes membership as `in_shadow_set`. Every live scoring cadence scores the set (see `../inference/AGENTS.md`). Nothing promotes from the set yet.
- `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.
@@ -80,7 +80,7 @@ Two things routinely surprise people:
- **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, for the champion and for a challenger that enters the shadow set.
+- **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, for the champion and for a challenger that enters the shadow set. Shadow scoring loads that `model.pkl` the same way the champion's scoring does.
- **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.