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): record prediction coverage on live champion runs (#114633)

posthog[bot]4bda41ece25a
diff --git a/products/autoresearch/backend/dataset/labeling.py b/products/autoresearch/backend/dataset/labeling.py
index 810ab2c8dd55..7398241a4146 100644
--- a/products/autoresearch/backend/dataset/labeling.py
+++ b/products/autoresearch/backend/dataset/labeling.py
@@ -215,19 +215,25 @@ class RollingSelection:
scored_lookback_days: int
-def rolling_selection(*, eligible: int, pipeline_id: str, cadence_days: int) -> RollingSelection | None:
+def scored_lookback_days(*, eligible: int, cadence_days: int) -> int:
"""
- The rolling subset for a scoring population of ``eligible`` persons, or None when it scores whole.
+ How far back the ranking reads the pipeline's own predictions for a population of ``eligible`` persons.
``cadence_days`` is the pipeline's days between runs, so the history window covers a cycle in days.
"""
limit = rolling_score_limit(eligible)
+ runs = 1 if limit is None else rolling_rescore_runs(eligible=eligible, scored=limit)
+ return max(ROLLING_SCORE_MIN_LOOKBACK_DAYS, 2 * runs * max(cadence_days, 1))
+
+
+def rolling_selection(*, eligible: int, pipeline_id: str, cadence_days: int) -> RollingSelection | None:
+ """The rolling subset for a scoring population of ``eligible`` persons, or None when it scores whole."""
+ limit = rolling_score_limit(eligible)
if limit is None:
return None
- cycle_days = rolling_rescore_runs(eligible=eligible, scored=limit) * max(cadence_days, 1)
return RollingSelection(
pipeline_id=pipeline_id,
limit=limit,
- scored_lookback_days=max(ROLLING_SCORE_MIN_LOOKBACK_DAYS, 2 * cycle_days),
+ scored_lookback_days=scored_lookback_days(eligible=eligible, cadence_days=cadence_days),
)
@@ -990,6 +996,23 @@ def build_eligible_count_sql(
return sql, values
+def _last_scored_sql(cutoff_expr: str) -> str:
+ """
+ One row per person with the pipeline's newest non-shadow prediction before the cutoff, as ``last_scored_ts``.
+ Binds ``rolling_scored_lookback`` and ``rolling_pipeline_id``.
+ """
+ return f"""
+ SELECT person_id, toInt(toUnixTimestamp(max(timestamp))) AS last_scored_ts
+ FROM events
+ WHERE event = '{PREDICTION_EVENT_NAME}'
+ 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
+ """
+
+
def build_inference_anchors_sql(
*,
lookback_days: int,
@@ -1063,16 +1086,7 @@ def build_inference_anchors_sql(
sql = f"""
SELECT a.person_id AS person_id, a.cutoff_ts AS cutoff_ts
FROM ({sql}) AS a
- LEFT JOIN (
- SELECT person_id, toInt(toUnixTimestamp(max(timestamp))) AS last_scored_ts
- FROM events
- WHERE event = '{PREDICTION_EVENT_NAME}'
- 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 ({_last_scored_sql(cutoff_expr)}) AS s ON a.person_id = s.person_id
LEFT JOIN (
SELECT person_id, toInt(toUnixTimestamp(max(timestamp))) AS last_active_ts
FROM events
@@ -1091,6 +1105,51 @@ def build_inference_anchors_sql(
return sql, values
+def build_prediction_coverage_sql(
+ *,
+ lookback_days: int,
+ inference_population: dict[str, Any] | None,
+ cutoff_ts: int,
+ pipeline_id: str,
+ scored_lookback_days: int,
+ target_event: str = "",
+ target_definition: dict[str, Any] | None = None,
+ team: "Team | None" = None,
+) -> tuple[str, dict[str, Any]]:
+ """
+ Build a HogQL query that returns one row: how much of the inference population has a score, and how old it is.
+
+ The query joins the inference anchors to the same last-score subquery that the rolling ranking
+ reads, so ``never_scored`` counts the people that the ranking puts first. Shadow predictions do
+ not count. Ages are in days before the cutoff, and are null when nobody has a score.
+ """
+ anchors_sql, values = build_inference_anchors_sql(
+ lookback_days=lookback_days,
+ inference_population=inference_population,
+ cutoff_ts=cutoff_ts,
+ target_event=target_event,
+ target_definition=target_definition,
+ team=team,
+ )
+ sql = f"""
+ SELECT
+ count() AS population,
+ countIf(scored) AS with_score,
+ avgIf(age_days, scored) AS age_days_avg,
+ quantileIf(0.5)(age_days, scored) AS age_days_p50,
+ quantileIf(0.9)(age_days, scored) AS age_days_p90,
+ maxIf(age_days, scored) AS age_days_max
+ FROM (
+ SELECT ifNull(s.last_scored_ts, 0) AS last_scored_ts, last_scored_ts > 0 AS scored, (a.cutoff_ts - last_scored_ts) / 86400 AS age_days
+ FROM ({anchors_sql}) AS a
+ LEFT JOIN ({_last_scored_sql("fromUnixTimestamp({cutoff_ts})")}) AS s ON a.person_id = s.person_id
+ )
+ """
+ values["rolling_scored_lookback"] = scored_lookback_days
+ values["rolling_pipeline_id"] = pipeline_id
+ return sql, values
+
+
_LINE_COMMENT_STARTS = ("--", "//")
_ANCHORS_PLACEHOLDER = "{anchors}"
diff --git a/products/autoresearch/backend/dataset/test_labeling.py b/products/autoresearch/backend/dataset/test_labeling.py
index 839ea1b63f46..42089e1634f1 100644
--- a/products/autoresearch/backend/dataset/test_labeling.py
+++ b/products/autoresearch/backend/dataset/test_labeling.py
@@ -34,6 +34,7 @@ from products.autoresearch.backend.dataset.labeling import (
build_eligible_count_sql,
build_inference_anchors_sql,
build_inference_features_sql,
+ build_prediction_coverage_sql,
build_random_t0_labeler_sql,
build_training_features_sql,
rolling_rescore_runs,
@@ -817,6 +818,20 @@ class TestAnchoredPopulationsAgainstClickhouse(ClickhouseTestMixin, APIBaseTest)
)
return sorted(name_by_uuid[str(row[0])] for row in rows)
+ coverage_sql, coverage_values = build_prediction_coverage_sql(
+ lookback_days=30,
+ inference_population={},
+ cutoff_ts=int(first_cutoff.timestamp()),
+ pipeline_id=pipeline_id,
+ scored_lookback_days=30,
+ )
+ [[population, with_score, age_avg, age_p50, _age_p90, age_max]] = run_hogql_rows(
+ team=self.team,
+ query=HogQLQuery(query=coverage_sql, values=coverage_values, modifiers=LABELER_QUERY_MODIFIERS),
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
+ )
+ assert (population, with_score, age_avg, age_p50, age_max) == (5, 2, 6.0, 6.0, 10.0)
+
selections: list[list[str]] = []
for day in range(3):
cutoff = first_cutoff + timedelta(days=day)
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.py
index c00432ee4801..05e46931d1aa 100644
--- a/products/autoresearch/backend/facade/api.py
+++ b/products/autoresearch/backend/facade/api.py
@@ -81,6 +81,7 @@ from .contracts import (
PipelineNotFound,
PipelineValidation,
PipelineWrite,
+ PredictionCoverage,
RealizedAucPoint,
ResolvedTemplate,
Run,
@@ -150,10 +151,16 @@ def _champion_lift_at_10(champion: AutoresearchModel | None) -> float | None:
return float(lift) if isinstance(lift, int | float) else None
+def _coverage_contract(coverage: Any) -> PredictionCoverage | None:
+ """The ``metrics["coverage"]`` of a live champion run. None for a run that did not measure it."""
+ return PredictionCoverage(**coverage) if isinstance(coverage, dict) else None
+
+
@frozen
class _PipelineActivity:
champion_realized_auc_trend: list[RealizedAucPoint]
people_scored: int | None
+ coverage: PredictionCoverage | None
training_run_count: int
experiment_count: int
live_training_run: LiveTrainingRun | None
@@ -171,6 +178,22 @@ def _live_training_run(run: AutoresearchTrainingRun, iterations: list[Autoresear
)
+def _newest_completed_inference(team_id: int, pipeline_ids: list[UUID], field: str, **filters: Any) -> dict[UUID, Any]:
+ """``field`` of the newest completed inference run per pipeline that matches ``filters``."""
+ return dict(
+ AutoresearchRun.objects.for_team(team_id)
+ .filter(
+ pipeline_id__in=pipeline_ids,
+ run_type=AutoresearchRun.RunType.INFERENCE,
+ status=AutoresearchRun.Status.COMPLETED,
+ **filters,
+ )
+ .order_by("pipeline_id", F("completed_at").desc(nulls_last=True), "-created_at")
+ .distinct("pipeline_id")
+ .values_list("pipeline_id", field)
+ )
+
+
def _pipeline_activity(
team_id: int, pipeline_ids: list[UUID], champions: dict[UUID, AutoresearchModel]
) -> dict[UUID, _PipelineActivity]:
@@ -191,18 +214,8 @@ def _pipeline_activity(
.annotate(n=Count("id"))
.values_list("pipeline_id", "n")
)
- people_scored = dict(
- AutoresearchRun.objects.for_team(team_id)
- .filter(
- pipeline_id__in=pipeline_ids,
- run_type=AutoresearchRun.RunType.INFERENCE,
- status=AutoresearchRun.Status.COMPLETED,
- rows_scored__isnull=False,
- )
- .order_by("pipeline_id", F("completed_at").desc(nulls_last=True), "-created_at")
- .distinct("pipeline_id")
- .values_list("pipeline_id", "rows_scored")
- )
+ people_scored = _newest_completed_inference(team_id, pipeline_ids, "rows_scored", rows_scored__isnull=False)
+ coverage = _newest_completed_inference(team_id, pipeline_ids, "metrics__coverage", metrics__has_key="coverage")
live_runs = {
run.pipeline_id: run
for run in AutoresearchTrainingRun.objects.for_team(team_id)
@@ -232,6 +245,7 @@ def _pipeline_activity(
RealizedAucPoint(prediction_date=d, realized_auc=auc) for d, auc in trends.get(pipeline_id, [])
],
people_scored=people_scored.get(pipeline_id),
+ coverage=_coverage_contract(coverage.get(pipeline_id)),
training_run_count=training_run_counts.get(pipeline_id, 0),
experiment_count=experiment_counts.get(pipeline_id, 0),
live_training_run=(
@@ -281,6 +295,7 @@ def _pipeline_to_contract(
champion_is_preliminary=champion.is_preliminary if champion else None,
champion_realized_auc_trend=activity.champion_realized_auc_trend,
people_scored=activity.people_scored,
+ coverage=activity.coverage,
training_run_count=activity.training_run_count,
experiment_count=activity.experiment_count,
live_training_run=activity.live_training_run,
@@ -394,6 +409,7 @@ def _run_to_contract(row: AutoresearchRun) -> Run:
status=row.status,
rows_scored=row.rows_scored,
metrics=row.metrics or {},
+ coverage=_coverage_contract((row.metrics or {}).get("coverage")),
error=row.error,
started_at=row.started_at,
completed_at=row.completed_at,
diff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.py
index 9814db7bba9b..549313800eeb 100644
--- a/products/autoresearch/backend/facade/contracts.py
+++ b/products/autoresearch/backend/facade/contracts.py
@@ -82,6 +82,20 @@ class LiveTrainingRun:
latest_agent_description: str
+@dataclass(frozen=True)
+class PredictionCoverage:
+ """How much of the inference population had a champion score when a live run scored, and how old the scores were."""
+
+ population: int
+ with_score: int
+ never_scored: int
+ age_days_avg: float | None
+ age_days_p50: float | None
+ age_days_p90: float | None
+ age_days_max: float | None
+ lookback_days: int
+
+
@dataclass(frozen=True)
class RealizedAucPoint:
prediction_date: date
@@ -123,6 +137,7 @@ class Pipeline:
champion_is_preliminary: bool | None
champion_realized_auc_trend: list[RealizedAucPoint]
people_scored: int | None
+ coverage: PredictionCoverage | None
training_run_count: int
experiment_count: int
live_training_run: LiveTrainingRun | None
@@ -260,6 +275,7 @@ class Run:
status: str
rows_scored: int | None
metrics: dict[str, Any]
+ coverage: PredictionCoverage | None
error: str
started_at: datetime | None
completed_at: datetime | None
diff --git a/products/autoresearch/backend/inference/AGENTS.md b/products/autoresearch/backend/inference/AGENTS.md
index 41fa2241552d..20777a459a2d 100644
--- a/products/autoresearch/backend/inference/AGENTS.md
+++ b/products/autoresearch/backend/inference/AGENTS.md
@@ -30,6 +30,7 @@ The cardinal rule: **inference never refits a persisted model.** A bundle is fit
Every query runs as the acting user (the pipeline's creator, or the `--user-id` a command passes), with an explicit bound and a truncation check, including the identity lookup: a bare `SELECT` that HogQL caps at 100 rows would emit most of the population person-less. Every result is refused above `_MAX_FEATURE_COLS` output columns as it is read, before any column is typed, because the numeric filter would otherwise discard the excess only after it was materialized. A run decides its dates once, in `ScoringWindow`: live or backfill, the cutoff every query binds to, and the emit timestamp. The cutoff is the start of the prediction date in UTC for every run, live included, so a retry recomputes the population the failed attempt had (the event UUIDs are the same either way), the feature query and the anchor count agree, and a backfill of a date gets the anchors a live run on that date got. A run that crosses midnight keeps the mode it started in.
Inference rows are checked against the anchor count on both paths (`count_inference_anchors()`), and training rows against the labeled anchor count (`count_training_anchors()`, at the negative sample rate the rows were drawn at), because feature SQL that inner joins or filters a joined table in `WHERE` drops people without any row looking wrong.
Scoring above the cap is rolling. Every path (bundle, agent recipe, stub) counts the whole inference population first. When the count reaches `MATERIALIZE_ROW_LIMIT`, `rolling_selection()` returns a `RollingSelection` of `ROLLING_SCORE_LIMIT` persons, and the feature query takes that many anchors, ranked by `build_inference_anchors_sql()`: never scored by this pipeline, then the oldest last score, then the most recent activity. The row check then expects exactly that many rows. The run records the whole count as `metrics["rows_eligible"]` next to `rows_scored`, so a run that scored part of its population completes, and consecutive runs cover everyone in `ceil(eligible / scored)` runs, which is that many times `cadence_days` in days. Below the cap the selection is unchanged. The stub path's population and ranking bind the run's cutoff at every size, so a retry selects the same people, though its feature SQL still reads at `now()`. The truncation check stays as the backstop for a query that misbehaves.
+ A completed live run also records `metrics["coverage"]`: the population, how many people have a non-shadow score, how many have none, and the age of the newest score per person (avg, p50, p90, max, in days before the cutoff). `build_prediction_coverage_sql()` reads the same last-score subquery as the ranking, over the same `scored_lookback_days()` window, so `never_scored` is the set the ranking puts first. The query runs under `BATCH_QUERY`. A failed coverage query only logs, and backfill and shadow runs do not record coverage.
`_resolve_distinct_ids()` maps the `person_id` everything is keyed on back to one current `distinct_id` through personhog (`get_persons_by_uuids`), never from event history, because an id read off old events can belong to someone else after a merge or split.
## Query budget
diff --git a/products/autoresearch/backend/inference/sandbox.py b/products/autoresearch/backend/inference/sandbox.py
index 4887034399bc..1a8f301d062f 100644
--- a/products/autoresearch/backend/inference/sandbox.py
+++ b/products/autoresearch/backend/inference/sandbox.py
@@ -72,9 +72,11 @@ from products.autoresearch.backend.dataset.labeling import (
TrainingSampleTooLarge,
build_inference_anchors_sql,
build_inference_features_sql,
+ build_prediction_coverage_sql,
build_random_t0_labeler_sql,
build_training_features_sql,
rolling_selection,
+ scored_lookback_days,
)
from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline
from products.autoresearch.backend.query import (
@@ -657,6 +659,49 @@ def count_inference_anchors(
)
+def measure_prediction_coverage(
+ *,
+ team: Team,
+ pipeline: AutoresearchPipeline,
+ cutoff_ts: int,
+ eligible: int,
+ user: User | None = None,
+) -> dict[str, Any]:
+ """
+ How much of the inference population has a champion score at ``cutoff_ts``, and how old the scores are.
+
+ ``eligible`` is the population count the run measured. It sets the same prediction window that the
+ rolling ranking reads, so ``never_scored`` holds the people that the next rolling run scores first.
+ """
+ lookback = scored_lookback_days(eligible=eligible, cadence_days=pipeline.cadence_days)
+ sql, values = build_prediction_coverage_sql(
+ lookback_days=_feature_lookback_days(pipeline),
+ inference_population=pipeline.inference_population,
+ cutoff_ts=cutoff_ts,
+ pipeline_id=str(pipeline.pk),
+ scored_lookback_days=lookback,
+ target_event=pipeline.target_event,
+ target_definition=pipeline.target_definition,
+ team=team,
+ )
+ population, with_score, *ages = _count_rows(
+ team=team, sql=sql, values=values, user=user, what="Prediction coverage", query_context=BATCH_QUERY
+ )
+ population, with_score = int(population), int(with_score)
+ # With nobody scored, ClickHouse returns nan or 0 for the ages, and neither is an age.
+ avg, p50, p90, max_age = (round(float(age), 2) if with_score else None for age in ages)
+ return {
+ "population": population,
+ "with_score": with_score,
+ "never_scored": population - with_score,
+ "age_days_avg": avg,
+ "age_days_p50": p50,
+ "age_days_p90": p90,
+ "age_days_max": max_age,
+ "lookback_days": lookback,
+ }
+
+
def _count(
*,
team: Team,
diff --git a/products/autoresearch/backend/inference/scoring.py b/products/autoresearch/backend/inference/scoring.py
index 2fab26023034..abc1bfd528cb 100644
--- a/products/autoresearch/backend/inference/scoring.py
+++ b/products/autoresearch/backend/inference/scoring.py
@@ -85,6 +85,7 @@ from products.autoresearch.backend.inference.sandbox import (
count_inference_anchors,
count_training_anchors,
features_sql_digest,
+ measure_prediction_coverage,
measure_training_sample,
score_via_sandbox,
validate_runnable_feature_sql,
@@ -362,6 +363,7 @@ def run_inference_for_pipeline(
raise
if not window.is_backfill:
+ _record_coverage(team=team, pipeline=pipeline, run=run, scored=scored, window=window, user=acting_user)
try:
outcome = _score_shadow_set(
team=team,
@@ -382,6 +384,34 @@ def run_inference_for_pipeline(
return run
+def _record_coverage(
+ *,
+ team: Team,
+ pipeline: AutoresearchPipeline,
+ run: AutoresearchRun,
+ scored: ScoredPopulation,
+ window: ScoringWindow,
+ user: User,
+) -> None:
+ """
+ Store ``metrics["coverage"]`` on a completed live champion run.
+
+ The measure binds the run's cutoff, so it describes the population that the run selected from.
+ The run is already complete, so a failed measure only logs.
+ """
+ if scored.rows_eligible is None:
+ return
+ try:
+ coverage = measure_prediction_coverage(
+ team=team, pipeline=pipeline, cutoff_ts=window.cutoff_ts, eligible=scored.rows_eligible, user=user
+ )
+ except Exception:
+ logger.exception("autoresearch_coverage_failed", pipeline_id=str(pipeline.pk), run_id=str(run.pk))
+ return
+ run.metrics["coverage"] = coverage
+ run.save(update_fields=["metrics"])
+
+
def _acting_user(*, team: Team, pipeline: AutoresearchPipeline, user: User | None) -> User:
try:
return _resolve_acting_user(team=team, pipeline=pipeline, user=user)
diff --git a/products/autoresearch/backend/inference/test_inference.py b/products/autoresearch/backend/inference/test_inference.py
index a0726f747c7a..0a49ae3518de 100644
--- a/products/autoresearch/backend/inference/test_inference.py
+++ b/products/autoresearch/backend/inference/test_inference.py
@@ -223,6 +223,28 @@ class TestRunInferencePipeline(TeamScopedTestMixin, BaseTest):
assert run.rows_scored == 2
assert run.metrics["rows_eligible"] == 250_000
+ @parameterized.expand(
+ [
+ (
+ "measured",
+ {"return_value": {"population": 250_000, "with_score": 1}},
+ {"population": 250_000, "with_score": 1},
+ ),
+ ("query_failed", {"side_effect": RuntimeError("clickhouse down")}, None),
+ ]
+ )
+ def test_a_live_run_stores_coverage_and_completes_when_the_measure_fails(self, _name, measure, expected):
+ pipeline, model = self._make_pipeline_and_model()
+
+ with patch.object(scoring, "measure_prediction_coverage", **measure) as coverage:
+ run = self._run_live(pipeline, model, _capture_accepting_everything(), eligible=250_000)
+
+ run.refresh_from_db()
+ assert run.status == AutoresearchRun.Status.COMPLETED
+ assert run.metrics.get("coverage") == expected
+ assert coverage.call_args.kwargs["eligible"] == 250_000
+ assert coverage.call_args.kwargs["cutoff_ts"] == ScoringWindow.for_date().cutoff_ts
+
def test_run_inference_zero_rows_completes_without_emitting(self):
pipeline, model = self._make_pipeline_and_model()
capture = _capture_accepting_everything()
@@ -404,12 +426,14 @@ class TestPredictionDateGuards(TeamScopedTestMixin, BaseTest):
with (
patch.object(scoring, "score_via_sandbox", return_value=sandbox_result) as sandbox,
patch.object(scoring, "capture_batch_internal", _capture_accepting_everything()) as capture,
+ patch.object(scoring, "measure_prediction_coverage") as coverage,
):
run = run_inference_for_pipeline(
pipeline=pipeline, model=model, prediction_date=date.today() - timedelta(days=30)
)
assert run.status == AutoresearchRun.Status.COMPLETED
+ coverage.assert_not_called()
assert capture.call_args.kwargs["process_person_profile"] is False
assert isinstance(sandbox.call_args.kwargs["cutoff_ts"], int)
pipeline.refresh_from_db()
diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.py
index 8334ed343c6f..8c9509320a1e 100644
--- a/products/autoresearch/backend/presentation/views/serializers.py
+++ b/products/autoresearch/backend/presentation/views/serializers.py
@@ -22,6 +22,7 @@ from products.autoresearch.backend.facade.contracts import (
Model,
Pipeline,
PipelineWrite,
+ PredictionCoverage,
RealizedAucPoint,
Run,
Suggestion,
@@ -506,6 +507,56 @@ class LiveTrainingRunSerializer(DataclassSerializer):
fields = ["id", "iteration_budget", "experiment_count", "best_holdout_score", "latest_agent_description"]
+@extend_schema_serializer(component_name="AutoresearchPredictionCoverage")
+class PredictionCoverageSerializer(DataclassSerializer):
+ population = serializers.IntegerField(
+ read_only=True, help_text="People in the inference population at the run's cutoff."
+ )
+ with_score = serializers.IntegerField(
+ read_only=True,
+ help_text="People with a champion score inside the lookback window before the cutoff. Shadow scores do not count.",
+ )
+ never_scored = serializers.IntegerField(
+ read_only=True,
+ help_text="People with no champion score inside the lookback window. A rolling run scores these people first.",
+ )
+ age_days_avg = serializers.FloatField(
+ read_only=True,
+ allow_null=True,
+ help_text="Mean age in days of the newest score per person. Null when nobody has a score.",
+ )
+ age_days_p50 = serializers.FloatField(
+ read_only=True,
+ allow_null=True,
+ help_text="Median age in days of the newest score per person. Null when nobody has a score.",
+ )
+ age_days_p90 = serializers.FloatField(
+ read_only=True,
+ allow_null=True,
+ help_text="90th percentile age in days of the newest score per person. Null when nobody has a score.",
+ )
+ age_days_max = serializers.FloatField(
+ read_only=True, allow_null=True, help_text="Oldest score age in days. Null when nobody has a score."
+ )
+ lookback_days = serializers.IntegerField(
+ read_only=True,
+ help_text="How many days before the cutoff the measure reads scores. Older scores count as never scored.",
+ )
+
+ class Meta:
+ dataclass = PredictionCoverage
+ fields = [
+ "population",
+ "with_score",
+ "never_scored",
+ "age_days_avg",
+ "age_days_p50",
+ "age_days_p90",
+ "age_days_max",
+ "lookback_days",
+ ]
+
+
@extend_schema_serializer(component_name="AutoresearchRealizedAucPoint")
class RealizedAucPointSerializer(DataclassSerializer):
prediction_date = serializers.DateField(read_only=True, help_text="Validated prediction date.")
@@ -620,6 +671,11 @@ class AutoresearchPipelineSerializer(DataclassSerializer):
allow_null=True,
help_text="People scored by the most recent completed inference run. Null before the first scoring run.",
)
+ coverage = PredictionCoverageSerializer(
+ read_only=True,
+ allow_null=True,
+ help_text="Score coverage and score age from the newest live champion run that measured them. Null before the first such run.",
+ )
training_run_count = serializers.IntegerField(read_only=True, help_text="Training runs started for this pipeline.")
experiment_count = serializers.IntegerField(
read_only=True, help_text="Experiments (iterations) recorded across every training run."
@@ -659,6 +715,7 @@ class AutoresearchPipelineSerializer(DataclassSerializer):
"champion_is_preliminary",
"champion_realized_auc_trend",
"people_scored",
+ "coverage",
"training_run_count",
"experiment_count",
"live_training_run",
@@ -1425,6 +1482,11 @@ class AutoresearchRunSerializer(DataclassSerializer):
"scored a rolling part of the population: users never scored first, then users whose last score was oldest."
)
)
+ coverage = PredictionCoverageSerializer(
+ read_only=True,
+ allow_null=True,
+ help_text="Score coverage and score age at the cutoff of a live champion run. Null for backfill, shadow, validation and older runs.",
+ )
error = serializers.CharField(required=False, allow_blank=True, help_text="Error message if the run failed.")
started_at = serializers.DateTimeField(required=False, allow_null=True, help_text="Timestamp when the run started.")
completed_at = serializers.DateTimeField(
@@ -1442,6 +1504,7 @@ class AutoresearchRunSerializer(DataclassSerializer):
"status",
"rows_scored",
"metrics",
+ "coverage",
"error",
"started_at",
"completed_at",
diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.py
index bb17cbcac99a..f158b8f0945d 100644
--- a/products/autoresearch/backend/tests/test_api.py
+++ b/products/autoresearch/backend/tests/test_api.py
@@ -224,13 +224,25 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
status="kept",
)
now = django_timezone.now()
- for rows_scored, minutes_ago in [(100, 60), (250, 5)]:
+ coverage = {
+ "population": 400,
+ "with_score": 300,
+ "never_scored": 100,
+ "age_days_avg": 1.5,
+ "age_days_p50": 1.0,
+ "age_days_p90": 3.0,
+ "age_days_max": 4.0,
+ "lookback_days": 30,
+ }
+ # The newest run, a backfill or shadow run, has no coverage, so the pipeline keeps the older measure.
+ for rows_scored, minutes_ago, metrics in [(100, 60, {"coverage": coverage}), (250, 5, {})]:
AutoresearchRun.objects.create(
pipeline=validated,
run_type=AutoresearchRun.RunType.INFERENCE,
status="completed",
rows_scored=rows_scored,
completed_at=now - timedelta(minutes=minutes_ago),
+ metrics=metrics,
)
for prediction_date, auc, minutes_ago in [
("2026-01-02", 0.7, 30),
@@ -312,6 +324,13 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
return sum('"autoresearch_' in q["sql"] for q in captured.captured_queries)
assert autoresearch_queries(more_queries) == autoresearch_queries(queries)
+ assert {name: row["coverage"] for name, row in by_name.items()} == {
+ "Validated": coverage,
+ "Preliminary": None,
+ "No positives": None,
+ "Zero lift": None,
+ "Untrained": None,
+ }
assert {
name: (
row["champion_holdout_auc"],
@@ -1039,9 +1058,33 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
holdout_score=0.6,
)
AutoresearchRun.objects.create(pipeline=pipeline, model=model, status="completed", rows_scored=100)
+ AutoresearchRun.objects.create(
+ pipeline=pipeline,
+ model=model,
+ status="completed",
+ rows_scored=50,
+ metrics={
+ "coverage": {
+ "population": 80,
+ "with_score": 0,
+ "never_scored": 80,
+ "age_days_avg": None,
+ "age_days_p50": None,
+ "age_days_p90": None,
+ "age_days_max": None,
+ "lookback_days": 30,
+ }
+ },
+ )
resp = self.client.get(f"{self.base_url}/{pipeline.id}/runs/")
assert resp.status_code == status.HTTP_200_OK
- assert resp.json()["count"] == 1
+ assert resp.json()["count"] == 2
+ assert sorted(
+ (run["rows_scored"], (run["coverage"] or {}).get("never_scored")) for run in resp.json()["results"]
+ ) == [
+ (50, 80),
+ (100, None),
+ ]
def test_online_performance_keeps_an_archived_former_champion(self):
pipeline = self._make_pipeline()
diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.ts
index 3711637d7531..6f6c04349235 100644
--- a/products/autoresearch/frontend/generated/api.schemas.ts
+++ b/products/autoresearch/frontend/generated/api.schemas.ts
@@ -91,6 +91,37 @@ export interface AutoresearchRealizedAucPointApi {
readonly realized_auc: number
}
+export interface AutoresearchPredictionCoverageApi {
+ /** People in the inference population at the run's cutoff. */
+ readonly population: number
+ /** People with a champion score inside the lookback window before the cutoff. Shadow scores do not count. */
+ readonly with_score: number
+ /** People with no champion score inside the lookback window. A rolling run scores these people first. */
+ readonly never_scored: number
+ /**
+ * Mean age in days of the newest score per person. Null when nobody has a score.
+ * @nullable
+ */
+ readonly age_days_avg: number | null
+ /**
+ * Median age in days of the newest score per person. Null when nobody has a score.
+ * @nullable
+ */
+ readonly age_days_p50: number | null
+ /**
+ * 90th percentile age in days of the newest score per person. Null when nobody has a score.
+ * @nullable
+ */
+ readonly age_days_p90: number | null
+ /**
+ * Oldest score age in days. Null when nobody has a score.
+ * @nullable
+ */
+ readonly age_days_max: number | null
+ /** How many days before the cutoff the measure reads scores. Older scores count as never scored. */
+ readonly lookback_days: number
+}
+
export interface AutoresearchLiveTrainingRunApi {
/** Unique UUID of the live training run. */
readonly id: string
@@ -240,6 +271,8 @@ export interface AutoresearchPipelineApi {
* @nullable
*/
readonly people_scored: number | null
+ /** Score coverage and score age from the newest live champion run that measured them. Null before the first such run. */
+ readonly coverage: AutoresearchPredictionCoverageApi | null
/** Training runs started for this pipeline. */
readonly training_run_count: number
/** Experiments (iterations) recorded across every training run. */
@@ -562,6 +595,8 @@ export interface AutoresearchRunApi {
rows_scored?: number | null
/** Run metrics: score distribution summary, validation AUC, etc. An inference run records 'rows_eligible', the users in the inference population. When it is larger than rows_scored, the run scored a rolling part of the population: users never scored first, then users whose last score was oldest. */
metrics: AutoresearchRunApiMetrics
+ /** Score coverage and score age at the cutoff of a live champion run. Null for backfill, shadow, validation and older runs. */
+ readonly coverage: AutoresearchPredictionCoverageApi | null
/** Error message if the run failed. */
error?: string
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 367732b44a74..cece8f9b6aa8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13839,6 +13839,37 @@ export namespace Schemas {
readonly realized_auc: number;
}
+ export interface AutoresearchPredictionCoverage {
+ /** People in the inference population at the run's cutoff. */
+ readonly population: number;
+ /** People with a champion score inside the lookback window before the cutoff. Shadow scores do not count. */
+ readonly with_score: number;
+ /** People with no champion score inside the lookback window. A rolling run scores these people first. */
+ readonly never_scored: number;
+ /**
+ * Mean age in days of the newest score per person. Null when nobody has a score.
+ * @nullable
+ */
+ readonly age_days_avg: number | null;
+ /**
+ * Median age in days of the newest score per person. Null when nobody has a score.
+ * @nullable
+ */
+ readonly age_days_p50: number | null;
+ /**
+ * 90th percentile age in days of the newest score per person. Null when nobody has a score.
+ * @nullable
+ */
+ readonly age_days_p90: number | null;
+ /**
+ * Oldest score age in days. Null when nobody has a score.
+ * @nullable
+ */
+ readonly age_days_max: number | null;
+ /** How many days before the cutoff the measure reads scores. Older scores count as never scored. */
+ readonly lookback_days: number;
+ }
+
export interface AutoresearchPipeline {
/** Unique UUID of this pipeline. */
readonly id: string;
@@ -13946,6 +13977,8 @@ export namespace Schemas {
* @nullable
*/
readonly people_scored: number | null;
+ /** Score coverage and score age from the newest live champion run that measured them. Null before the first such run. */
+ readonly coverage: AutoresearchPredictionCoverage | null;
/** Training runs started for this pipeline. */
readonly training_run_count: number;
/** Experiments (iterations) recorded across every training run. */
@@ -14105,6 +14138,8 @@ export namespace Schemas {
rows_scored?: number | null;
/** Run metrics: score distribution summary, validation AUC, etc. An inference run records 'rows_eligible', the users in the inference population. When it is larger than rows_scored, the run scored a rolling part of the population: users never scored first, then users whose last score was oldest. */
metrics: AutoresearchRunMetrics;
+ /** Score coverage and score age at the cutoff of a live champion run. Null for backfill, shadow, validation and older runs. */
+ readonly coverage: AutoresearchPredictionCoverage | null;
/** Error message if the run failed. */
error?: string;
/**