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): score populations above the row cap on a rolling basis (#110125)

posthog[bot]39a866daaeba
diff --git a/products/autoresearch/backend/dataset/AGENTS.md b/products/autoresearch/backend/dataset/AGENTS.md
index 465de7cc589a..aa7d20e00b7c 100644
--- a/products/autoresearch/backend/dataset/AGENTS.md
+++ b/products/autoresearch/backend/dataset/AGENTS.md
@@ -18,14 +18,16 @@ Nothing here trains or scores anything. It is the shared vocabulary that `../tra
**Training anchors are case-control sampled above the budget.** `TrainingSample.plan()` keeps every anchor when the labeled population fits `TRAINING_SAMPLE_BUDGET` (`MATERIALIZE_ROW_LIMIT` times `TRAINING_SAMPLE_HEADROOM`), and the SQL is then the unsampled SQL. Above it, the plan keeps every positive and sets the negative sample rate `r` so the expected sample fills the budget. Positives that alone exceed the budget raise `TrainingSampleTooLarge`.
A negative is kept when its salted hash, `cityHash64(concat('sample:', person_id))`, falls under `r`. The draw is per person, so it is stable across runs and independent of the T0 and fold hashes. `build_training_features_sql()` and `build_random_t0_labeler_sql()` take the same `negative_sample_rate`, so the trainer's rows and the anchor count describe one sample. Holdout AUC does not change under negative sampling; probabilities do, so scoring applies the prior correction (see `../inference/AGENTS.md`).
- Only training samples. Inference above `MATERIALIZE_ROW_LIMIT` still fails the run.
+ Only training samples. Inference above `MATERIALIZE_ROW_LIMIT` scores a rolling subset instead (below).
+
+ `build_inference_anchors_sql()` takes an optional `RollingSelection` (from `rolling_selection()`) for a scoring population at or above the cap. It keeps `limit` anchors: first the people the pipeline never scored, then the oldest last score, then the most recent member event, then a person hash. The last score is the latest live `autoresearch_prediction` event of the pipeline before the cutoff, within `scored_lookback_days`. That window is twice the rotation length in days (runs times `cadence_days`), and at least `ROLLING_SCORE_MIN_LOOKBACK_DAYS`, so a person scored at the start of a rotation never ranks with the never-scored. A backfill event is person-less, so it does not count. Every key reads events before the cutoff, so a retry of the same prediction date selects the same people.
Also here: `_compile_population_filters()` (property filters → HogQL; a cohort filter, an unknown operator, or a filter without a `type` raises rather than being skipped), `_build_population_kind_conditions()` (semantic population kinds → HogQL, see below), `build_target_condition()` (event or action target → predicate), `NUM_FOLDS = 5` with fold 0 as holdout, and `IDENTIFIED_USERS_ONLY`.
- `validation.py`
Pre-flight viability. `validate_pipeline_definition()` answers "is there enough here to learn anything?" before a run is launched — `MIN_TRAINING_ROWS` (100), `MIN_POSITIVE_EXAMPLES` and `MIN_NEGATIVE_EXAMPLES` (20 each, because holdout AUC is undefined with one class), `MIN_IDENTIFIED_FRACTION` (0.5). The window validated is the configured `training_lookback_days`, unclamped, so the estimate describes the data training will see.
Returns a `ValidationResult` carrying `ValidationWarning`s rather than raising, because the API surfaces them as advice.
- `population_too_large` is severity `info` when training will sample the population, and `error` when the positives alone exceed the training budget or the scoring population reaches `MATERIALIZE_ROW_LIMIT`. `low_positives`, `low_negatives` and `horizon_exceeds_lookback` stay errors.
+ `population_too_large` is severity `info` when training will sample the population or scoring rolls through a population at or above `MATERIALIZE_ROW_LIMIT`, and `error` when the positives alone exceed the training budget. `low_positives`, `low_negatives` and `horizon_exceeds_lookback` stay errors.
- `templates.py`
Built-in starting points. A template resolves to the same pipeline config shape as a fully custom pipeline, so creation and validation behave identically either way — there is no separate template code path downstream.
Population specs use a semantic format (`performed_event_within_days`, `person_first_seen_within_days`, `active_not_performed_target`, `ever_performed_event`, `ever_performed_target`) that is compiled to HogQL by `labeling.py`. The target-relative kinds compile against the pipeline's target predicate, so an action target is matched by its matcher and not by its display name.
diff --git a/products/autoresearch/backend/dataset/labeling.py b/products/autoresearch/backend/dataset/labeling.py
index 102f576c2ea4..d85e98782321 100644
--- a/products/autoresearch/backend/dataset/labeling.py
+++ b/products/autoresearch/backend/dataset/labeling.py
@@ -98,7 +98,8 @@ def _own_events_excluded_clause(alias: str = "") -> str:
# The most persons one training or scoring run materializes. HogQL otherwise caps a query at its
# default of 100 rows; the materializers fail a result that fills this bound, and validation
-# refuses a larger population before a run is spent on it.
+# refuses a larger training population before a run is spent on it. A larger scoring population
+# scores on a rolling basis instead (ROLLING_SCORE_LIMIT).
MATERIALIZE_ROW_LIMIT = 50_000
# The share of MATERIALIZE_ROW_LIMIT a sampled training population aims at. The rate is chosen
@@ -159,6 +160,53 @@ def negative_sample_threshold(negative_sample_rate: float) -> int:
return math.floor(negative_sample_rate * _HASH_RANGE)
+# The most persons one scoring run scores when its population reaches MATERIALIZE_ROW_LIMIT. The
+# run takes the people whose last score is oldest, so consecutive runs cycle through the whole
+# population. The headroom keeps a materialized result clear of the truncation check.
+ROLLING_SCORE_LIMIT = MATERIALIZE_ROW_LIMIT * 9 // 10
+
+# The shortest window a rolling selection reads the pipeline's own predictions over. A larger
+# population gets a longer window, see `rolling_selection()`.
+ROLLING_SCORE_MIN_LOOKBACK_DAYS = 30
+
+
+def rolling_score_limit(eligible: int) -> int | None:
+ """The rolling selection size for a scoring population of ``eligible`` persons, or None when it scores whole."""
+ return ROLLING_SCORE_LIMIT if eligible >= MATERIALIZE_ROW_LIMIT else None
+
+
+def rolling_rescore_runs(*, eligible: int, scored: int) -> int:
+ """How many scoring runs a rolling selection of ``scored`` persons takes to cover ``eligible`` persons."""
+ return max(1, -(-eligible // max(scored, 1)))
+
+
+@frozen
+class RollingSelection:
+ """The subset one scoring run takes from a population at or above the cap."""
+
+ pipeline_id: str
+ limit: int
+ # How far back the ranking reads the pipeline's own predictions. A person scored before the
+ # window ranks with the never-scored, so the window covers a whole cycle with room to grow.
+ scored_lookback_days: int
+
+
+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.
+ ``cadence_days`` is the pipeline's days between runs, so the history window covers a cycle in days.
+ """
+ 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),
+ )
+
+
@dataclass(frozen=True, kw_only=True)
class _CompiledPopulationFilters:
# Person-property fragments on `raw_persons` columns, decided on each person's latest version.
@@ -920,6 +968,7 @@ def build_inference_anchors_sql(
target_event: str = "",
target_definition: dict[str, Any] | None = None,
team: "Team | None" = None,
+ rolling: RollingSelection | None = None,
) -> tuple[str, dict[str, Any]]:
"""
Build a HogQL query producing (person_id, cutoff_ts) rows for scoring.
@@ -935,6 +984,11 @@ def build_inference_anchors_sql(
Substituted as the {anchors} table when running the agent's feature_sql
at inference time. Same SQL the trainer executed against per-user T0;
only the anchors table changes.
+
+ ``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.
"""
inference_properties = (inference_population or {}).get("properties", []) if inference_population else []
compiled_filters = _compile_population_filters(inference_properties)
@@ -955,13 +1009,12 @@ def build_inference_anchors_sql(
row_clause = f" AND ({' AND '.join(row_parts)})" if row_parts else ""
member_clause = _member_clause(compiled_filters, compiled_kind)
- members_sql = (
- "SELECT person_id FROM events"
- f" WHERE timestamp >= {cutoff_expr} - toIntervalDay({{lookback}})"
+ member_scan = (
+ f"timestamp >= {cutoff_expr} - toIntervalDay({{lookback}})"
f" AND timestamp < {cutoff_expr}{_own_events_excluded_clause()}{member_clause}{row_clause}"
)
sql = _person_rows_sql(
- members_sql,
+ f"SELECT person_id FROM events WHERE {member_scan}",
compiled_filters.person_parts + compiled_kind.person_parts,
select=f"id AS person_id, {cutoff_select} AS cutoff_ts",
)
@@ -973,6 +1026,36 @@ def build_inference_anchors_sql(
}
if cutoff_ts is not None:
values["cutoff_ts"] = cutoff_ts
+ if rolling is not None:
+ # A live prediction attaches to the real person, so its person_id joins the anchor. A
+ # backfill is person-less, so it does not count as a score that refreshed the person.
+ 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}}
+ GROUP BY person_id
+ ) AS s ON a.person_id = s.person_id
+ LEFT JOIN (
+ SELECT person_id, toInt(toUnixTimestamp(max(timestamp))) AS last_active_ts
+ FROM events
+ WHERE {member_scan}
+ GROUP BY person_id
+ ) AS m ON a.person_id = m.person_id
+ ORDER BY
+ ifNull(s.last_scored_ts, 0) ASC,
+ ifNull(m.last_active_ts, 0) DESC,
+ cityHash64(toString(a.person_id)) ASC,
+ toString(a.person_id) ASC
+ LIMIT {int(rolling.limit)}
+ """
+ values["rolling_scored_lookback"] = rolling.scored_lookback_days
+ values["rolling_pipeline_id"] = rolling.pipeline_id
return sql, values
@@ -1140,6 +1223,7 @@ def build_inference_features_sql(
target_event: str = "",
target_definition: dict[str, Any] | None = None,
team: "Team | None" = None,
+ rolling: RollingSelection | None = None,
) -> tuple[str, dict[str, Any]]:
"""
Build the inference-time query: the agent's feature_sql with {anchors}
@@ -1149,6 +1233,7 @@ def build_inference_features_sql(
columns — no labels, no fold.
Caller substitutes {lookback_days} in feature_sql before calling.
+ ``rolling`` selects a rolling subset of the anchors, as in ``build_inference_anchors_sql``.
"""
anchors_sql, anchors_values = build_inference_anchors_sql(
lookback_days=lookback_days,
@@ -1157,6 +1242,7 @@ def build_inference_features_sql(
target_event=target_event,
target_definition=target_definition,
team=team,
+ rolling=rolling,
)
# Wrap the inference anchors query as the {anchors} subquery — agent's
# feature_sql references columns (person_id, cutoff_ts) just like training.
diff --git a/products/autoresearch/backend/dataset/test_labeling.py b/products/autoresearch/backend/dataset/test_labeling.py
index 9be64b6243fd..f924c3d97913 100644
--- a/products/autoresearch/backend/dataset/test_labeling.py
+++ b/products/autoresearch/backend/dataset/test_labeling.py
@@ -22,6 +22,8 @@ from posthog.hogql_queries.query_runner import ExecutionMode
from products.autoresearch.backend.dataset.labeling import (
LABELER_QUERY_MODIFIERS,
PREDICTION_EVENT_NAME,
+ ROLLING_SCORE_LIMIT,
+ RollingSelection,
TrainingSample,
TrainingSampleTooLarge,
_build_labeled_users_cte,
@@ -33,6 +35,8 @@ from products.autoresearch.backend.dataset.labeling import (
build_inference_features_sql,
build_random_t0_labeler_sql,
build_training_features_sql,
+ rolling_rescore_runs,
+ rolling_selection,
strip_sql_comments,
)
from products.autoresearch.backend.query import run_hogql_rows
@@ -107,6 +111,26 @@ class TestBuildInferenceFeaturesSql(BaseTest):
self.assertNotIn("--", sql)
+class TestRollingSelection(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("at_the_cap", 50_000, 1),
+ ("one_cycle_past_the_minimum_window", 1_400_000, 1),
+ ("huge", 9_000_000, 1),
+ ("weekly_cadence", 1_400_000, 7),
+ ]
+ )
+ def test_score_history_window_outlasts_a_full_cycle(self, _name: str, eligible: int, cadence_days: int) -> None:
+ rolling = rolling_selection(eligible=eligible, pipeline_id="p", cadence_days=cadence_days)
+ assert rolling is not None
+ assert rolling.limit == ROLLING_SCORE_LIMIT
+ cycle_days = rolling_rescore_runs(eligible=eligible, scored=rolling.limit) * cadence_days
+ assert rolling.scored_lookback_days > cycle_days
+
+ def test_a_population_below_the_cap_scores_whole(self) -> None:
+ assert rolling_selection(eligible=49_999, pipeline_id="p", cadence_days=1) is None
+
+
class TestPopulationFilterCompilation(SimpleTestCase):
# A filter that cannot be compiled must raise: skipping it would silently widen the
# population, and inference writes person properties for everyone it scores.
@@ -671,3 +695,78 @@ class TestAnchoredPopulationsAgainstClickhouse(ClickhouseTestMixin, APIBaseTest)
anchors_sql, anchors_values = build_inference_anchors_sql(lookback_days=30, inference_population=population)
assert [int(v) for v in run(eligible_sql, eligible_values)] == [1, 2]
assert int(run(f"SELECT count() FROM ({anchors_sql.strip()})", anchors_values)[0]) == 1
+
+ def test_rolling_selection_ranks_by_staleness_and_covers_everyone_in_ceil_m_over_n_runs(self) -> None:
+ now = timezone.now() # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())
+ first_cutoff = now.replace(microsecond=0) - timedelta(days=3)
+ pipeline_id = "11111111-1111-1111-1111-111111111111"
+ # (days of activity before the first cutoff, days of this pipeline's last score before it)
+ people: dict[str, tuple[int, int | None]] = {
+ "active_never_scored": (1, None),
+ "idle_never_scored": (5, None),
+ "scored_by_another_pipeline": (3, None),
+ "scored_long_ago": (1, 10),
+ "scored_recently": (1, 2),
+ }
+ name_by_uuid: dict[str, str] = {}
+ for name, (active_days_ago, scored_days_ago) in people.items():
+ person = _create_person(team_id=self.team.pk, distinct_ids=[name], is_identified=True)
+ name_by_uuid[str(person.uuid)] = name
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=name,
+ timestamp=first_cutoff - timedelta(days=active_days_ago),
+ )
+ if scored_days_ago is not None:
+ _create_event(
+ team=self.team,
+ event=PREDICTION_EVENT_NAME,
+ distinct_id=name,
+ timestamp=first_cutoff - timedelta(days=scored_days_ago),
+ properties={"$autoresearch_pipeline_id": pipeline_id},
+ )
+ _create_event(
+ team=self.team,
+ event=PREDICTION_EVENT_NAME,
+ distinct_id="scored_by_another_pipeline",
+ timestamp=first_cutoff - timedelta(days=1),
+ properties={"$autoresearch_pipeline_id": "22222222-2222-2222-2222-222222222222"},
+ )
+ flush_persons_and_events()
+
+ def select(cutoff: Any) -> list[str]:
+ sql, values = build_inference_anchors_sql(
+ lookback_days=30,
+ inference_population={},
+ cutoff_ts=int(cutoff.timestamp()),
+ rolling=RollingSelection(pipeline_id=pipeline_id, limit=2, scored_lookback_days=30),
+ )
+ rows = run_hogql_rows(
+ team=self.team,
+ query=HogQLQuery(query=sql, values=values, modifiers=LABELER_QUERY_MODIFIERS),
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
+ )
+ return sorted(name_by_uuid[str(row[0])] for row in rows)
+
+ selections: list[list[str]] = []
+ for day in range(3):
+ cutoff = first_cutoff + timedelta(days=day)
+ selected = select(cutoff)
+ assert select(cutoff) == selected
+ selections.append(selected)
+ for name in selected:
+ _create_event(
+ team=self.team,
+ event=PREDICTION_EVENT_NAME,
+ distinct_id=name,
+ timestamp=cutoff + timedelta(hours=1),
+ properties={"$autoresearch_pipeline_id": pipeline_id},
+ )
+ flush_persons_and_events()
+
+ assert selections == [
+ ["active_never_scored", "scored_by_another_pipeline"],
+ ["idle_never_scored", "scored_long_ago"],
+ ["active_never_scored", "scored_recently"],
+ ]
diff --git a/products/autoresearch/backend/dataset/test_validation.py b/products/autoresearch/backend/dataset/test_validation.py
index 3a501eb42504..02e7dd27fb33 100644
--- a/products/autoresearch/backend/dataset/test_validation.py
+++ b/products/autoresearch/backend/dataset/test_validation.py
@@ -74,7 +74,6 @@ class TestValidationWarnings(BaseTest):
[
("training_above_the_cap_is_sampled", 5_000, 100_000, 1_000, "info", True),
("positives_alone_over_the_training_budget", 45_000, 100_000, 1_000, "error", False),
- ("scoring_population_above_the_cap", 500, 5_000, 50_000, "error", False),
]
)
def test_population_too_large_is_advisory_only_for_a_samplable_training_population(
@@ -85,6 +84,25 @@ class TestValidationWarnings(BaseTest):
assert warning.severity == severity
assert result.can_proceed is can_proceed
+ @parameterized.expand(
+ [
+ ("below_the_cap", 49_999, None),
+ ("at_the_cap", 50_000, "every 2 scoring runs"),
+ ("far_above_the_cap", 250_000, "every 6 scoring runs"),
+ ]
+ )
+ def test_a_large_scoring_population_is_advisory(self, _name: str, inference: int, rescore: str | None) -> None:
+ result = self._run(positives=100, total=1000, inference=inference)
+ size_warnings = [w for w in result.warnings if w.code == "population_too_large"]
+ assert result.can_proceed is True
+ assert result.requires_acknowledgement is False
+ if rescore is None:
+ assert size_warnings == []
+ else:
+ [warning] = size_warnings
+ assert warning.severity == "info"
+ assert rescore in warning.message
+
def test_moderate_volume_is_warning(self) -> None:
result = self._run(positives=30, total=200)
codes = [w.code for w in result.warnings]
diff --git a/products/autoresearch/backend/dataset/validation.py b/products/autoresearch/backend/dataset/validation.py
index 5a3c4e74777e..ffae1d136aed 100644
--- a/products/autoresearch/backend/dataset/validation.py
+++ b/products/autoresearch/backend/dataset/validation.py
@@ -24,12 +24,14 @@ from posthog.models.user import User
from products.autoresearch.backend.dataset.labeling import (
IDENTIFIED_USERS_ONLY,
LABELER_QUERY_MODIFIERS,
- MATERIALIZE_ROW_LIMIT,
+ ROLLING_SCORE_LIMIT,
TrainingSample,
TrainingSampleTooLarge,
build_eligible_count_sql,
build_inference_anchors_sql,
build_random_t0_labeler_sql,
+ rolling_rescore_runs,
+ rolling_score_limit,
)
from products.autoresearch.backend.query import run_hogql_rows
@@ -383,13 +385,16 @@ def _build_warnings(
if training_size is not None:
warnings.append(training_size)
- if inference_size >= MATERIALIZE_ROW_LIMIT:
+ # Scoring above the cap rolls through the population, so a large one is advice, not a refusal.
+ if rolling_score_limit(inference_size) is not None:
+ rescore_runs = rolling_rescore_runs(eligible=inference_size, scored=ROLLING_SCORE_LIMIT)
warnings.append(
ValidationWarning(
code=ValidationWarningCode.POPULATION_TOO_LARGE,
- message=f"The scoring population has {inference_size} users. One run scores at most "
- f"{MATERIALIZE_ROW_LIMIT} users. Narrow the population.",
- severity="error",
+ message=f"The scoring population has {inference_size} users. Each run scores "
+ f"{ROLLING_SCORE_LIMIT} of them, starting with users never scored, then users whose last "
+ f"score is oldest. Everyone is rescored about every {rescore_runs} scoring runs.",
+ severity="info",
)
)
diff --git a/products/autoresearch/backend/inference/AGENTS.md b/products/autoresearch/backend/inference/AGENTS.md
index adc9b109da75..89878eed883d 100644
--- a/products/autoresearch/backend/inference/AGENTS.md
+++ b/products/autoresearch/backend/inference/AGENTS.md
@@ -19,7 +19,7 @@ The cardinal rule: **inference never refits a persisted model.** A bundle is fit
`materialize_training_data()` writes feature and label parquet files into the sandbox; `MaterializedData` carries the paths and row counts back. Materialized rows must key exactly one person each (`validate_unique_distinct_ids()`), and a training row whose label failed to join fails the run. Feature SQL that returns two columns of the same name fails the run, because `HogQLResult.as_dicts()` keeps only the last value of a repeated name.
Every upload goes through `_write_file()`, which fails the run on a non-zero result: the providers report a failed write through the exit code rather than an exception, and a discarded result would let a script run against a missing input. The train run's smoke test loads the model bytes read back from the sandbox, written to `_SMOKE_MODEL_PKL`, so the bytes the caller persists are the bytes `predict.py` proved it can load.
Everything a script produces is untrusted: script output goes to `data/script.log` and only a bounded tail comes back on failure; every file readback is size-gated inside the sandbox (`_MAX_READBACK_BYTES`, the artifact cap), emits at most cap-plus-one bytes through `head -c` however the file grows, and fails on a missing, empty, or oversized file; `output.json` values are typed and ranged; `scores.parquet` is checked from its footer before it is decoded (column types, row count against the input, decoded byte size of the two contract columns against the cap), only those two columns are read, and a person scored twice fails the run.
- Timeouts are asymmetric on purpose — `_TRAIN_TIMEOUT_S` 300s versus `_PREDICT_TIMEOUT_S` 120s — with `_SANDBOX_TTL_S` as the backstop for a worker that dies mid-run. `_MATERIALIZE_ROW_LIMIT` and `_MAX_FEATURE_COLS` together cap what crosses into the sandbox: the row cap alone does not bound the matrix the worker expands, because the agent's SQL chooses the column count.
+ Timeouts are asymmetric on purpose — `_TRAIN_TIMEOUT_S` 300s versus `_PREDICT_TIMEOUT_S` 120s — with `_SANDBOX_TTL_S` as the backstop for a worker that dies mid-run. `_MATERIALIZE_ROW_LIMIT` (with the rolling selection below it for scoring) and `_MAX_FEATURE_COLS` together cap what crosses into the sandbox: the row cap alone does not bound the matrix the worker expands, because the agent's SQL chooses the column count.
- `scoring.py`
The recipe-only in-process path plus the event emission that both paths share.
@@ -28,6 +28,7 @@ The cardinal rule: **inference never refits a persisted model.** A bundle is fit
This is the only place that resolves `model_class` through `importlib`, so it is the one genuine code-execution surface — it calls `validate_model_class()` from `../training/recipe_validation.py` before importing. Do not weaken that.
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.
`_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 051bb224ce8a..9bdc3673cc64 100644
--- a/products/autoresearch/backend/inference/sandbox.py
+++ b/products/autoresearch/backend/inference/sandbox.py
@@ -72,6 +72,7 @@ from products.autoresearch.backend.dataset.labeling import (
build_inference_features_sql,
build_random_t0_labeler_sql,
build_training_features_sql,
+ rolling_selection,
)
from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline
from products.autoresearch.backend.query import INTERACTIVE_QUERY, QueryContext, run_hogql
@@ -159,12 +160,22 @@ class MaterializedData:
negative_sample_rate: float = 1.0
+@frozen
+class InferenceRows:
+ """The feature rows one scoring run materialized, and how many persons were eligible for it."""
+
+ rows: list[dict[str, Any]]
+ # Above len(rows) when the population reached the cap and the run scores a rolling subset.
+ eligible: int
+
+
@frozen
class SandboxScoreResult:
scored_rows: list[dict[str, Any]] # score rows with an added "p_y"
holdout_auc: float | None
n_train: int
n_features: int
+ rows_eligible: int
# ── Public entry point ─────────────────────────────────────────────────────────
@@ -266,7 +277,7 @@ def score_via_sandbox(
f"Champion model.pkl is missing at {prefix}; the completion-time fit has not produced it"
)
- score_rows = _materialize_score_data(
+ score_data = _materialize_score_data(
team=team,
pipeline=pipeline,
feature_sql=bundle.features_sql,
@@ -274,11 +285,18 @@ def score_via_sandbox(
user=acting_user,
query_context=query_context,
)
+ 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
# change it, and the recipe path completes the same cadence with no rows.
if not score_rows:
- return SandboxScoreResult(scored_rows=[], holdout_auc=model.holdout_score, n_train=n_train, n_features=0)
+ return SandboxScoreResult(
+ scored_rows=[],
+ holdout_auc=model.holdout_score,
+ n_train=n_train,
+ n_features=0,
+ rows_eligible=score_data.eligible,
+ )
feature_cols = _fitted_feature_cols(prefix) or _numeric_feature_cols(score_rows)
# Cheap guard before paying for a sandbox.
if not feature_cols:
@@ -292,6 +310,7 @@ def score_via_sandbox(
holdout_auc=model.holdout_score,
n_train=n_train,
n_features=len(feature_cols),
+ rows_eligible=score_data.eligible,
)
@@ -440,13 +459,20 @@ def _materialize_score_data(
cutoff_ts: int | None = None,
user: User | None = None,
query_context: QueryContext = INTERACTIVE_QUERY,
-) -> list[dict[str, Any]]:
+) -> InferenceRows:
"""
Predict run materialization: the bundle's feature SQL against the inference anchors
(cutoff_ts = now() per user, or a backdated instant when ``cutoff_ts`` is given for a
historical backfill). One row per eligible scoring user with the agent's feature
columns, with no labels and no fold. Touches only the inference population.
+
+ A population at or above the cap scores a rolling subset: the ``ROLLING_SCORE_LIMIT``
+ persons whose last score by this pipeline is oldest.
"""
+ eligible = count_inference_anchors(
+ team=team, pipeline=pipeline, cutoff_ts=cutoff_ts, user=user, query_context=query_context
+ )
+ rolling = rolling_selection(eligible=eligible, pipeline_id=str(pipeline.pk), cadence_days=pipeline.cadence_days)
feature_sql_resolved = feature_sql.replace("{lookback_days}", str(_feature_lookback_days(pipeline)))
score_sql, score_values = build_inference_features_sql(
feature_sql=feature_sql_resolved,
@@ -456,18 +482,24 @@ def _materialize_score_data(
target_event=pipeline.target_event,
target_definition=pipeline.target_definition,
team=team,
+ rolling=rolling,
)
score_rows = _materialize_rows(
team=team, sql=score_sql, values=score_values, user=user, query_context=query_context
)
- expected = count_inference_anchors(
- team=team, pipeline=pipeline, cutoff_ts=cutoff_ts, user=user, query_context=query_context
+ _validate_rows_key_one_person(
+ score_rows,
+ source="inference feature_sql",
+ expected_count=eligible if rolling is None else rolling.limit,
)
- _validate_rows_key_one_person(score_rows, source="inference feature_sql", expected_count=expected)
logger.info(
- "autoresearch_score_materialized", pipeline_id=str(pipeline.pk), n_score=len(score_rows), cutoff_ts=cutoff_ts
+ "autoresearch_score_materialized",
+ pipeline_id=str(pipeline.pk),
+ n_score=len(score_rows),
+ n_eligible=eligible,
+ cutoff_ts=cutoff_ts,
)
- return score_rows
+ return InferenceRows(rows=score_rows, eligible=eligible)
def measure_training_sample(
@@ -543,6 +575,8 @@ def count_inference_anchors(
How many people the inference anchors hold, so a feature query that drops some of them
fails: an inner join or a WHERE on the joined table loses anchors without any row looking
wrong, and a lost person is never scored again once the cadence advances past them.
+
+ This is the whole population. A rolling run scores ``rolling_selection().limit`` of them.
"""
anchors_sql, values = build_inference_anchors_sql(
lookback_days=_feature_lookback_days(pipeline),
@@ -644,8 +678,8 @@ def _materialize_rows(
raise SandboxInferenceError(f"Feature SQL returned duplicate output columns: {', '.join(duplicates)}")
rows = result.as_dicts()
# A result that fills the bound is almost certainly truncated, and completing anyway
- # would advance last_scored_at while skipping the users past the cap. Pagination is
- # follow-up work; until then, fail loudly.
+ # would advance last_scored_at while skipping the users past the cap. A scoring population
+ # that large takes a rolling subset below the bound, so reaching it here is a failure.
if result.has_more or len(rows) >= _MATERIALIZE_ROW_LIMIT:
raise SandboxInferenceError(
f"Materialization hit the {_MATERIALIZE_ROW_LIMIT}-row limit; "
diff --git a/products/autoresearch/backend/inference/scoring.py b/products/autoresearch/backend/inference/scoring.py
index 70f29133b582..f78153827ef3 100644
--- a/products/autoresearch/backend/inference/scoring.py
+++ b/products/autoresearch/backend/inference/scoring.py
@@ -32,6 +32,7 @@ import uuid
import hashlib
import inspect
import importlib
+import dataclasses
from datetime import UTC, date, datetime
from typing import Any
@@ -54,9 +55,11 @@ from products.autoresearch.backend.dataset.labeling import (
IDENTIFIED_USERS_ONLY,
LABELER_QUERY_MODIFIERS,
PREDICTION_EVENT_NAME,
+ RollingSelection,
build_inference_anchors_sql,
build_inference_features_sql,
build_training_features_sql,
+ rolling_selection,
)
from products.autoresearch.backend.inference.sandbox import (
_FOLD_COL,
@@ -64,6 +67,7 @@ from products.autoresearch.backend.inference.sandbox import (
_LABEL_COL,
_MATERIALIZE_ROW_LIMIT,
_MAX_FEATURE_COLS,
+ InferenceRows,
SandboxInferenceError,
_num,
_numeric_feature_cols,
@@ -139,6 +143,9 @@ class ScoredPopulation:
holdout_auc: float | None
# The fraction of negatives the scoring model was fitted on. 1.0 means no sampling.
negative_sample_rate: float = 1.0
+ # 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
def corrected_probability(p: float, negative_sample_rate: float) -> float:
@@ -157,7 +164,9 @@ def _apply_prior_correction(scored: ScoredPopulation) -> ScoredPopulation:
"""Keep each row's raw score as ``p_y_raw`` and replace ``p_y`` with the corrected probability."""
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)
+ return ScoredPopulation(
+ rows=rows, holdout_auc=scored.holdout_auc, negative_sample_rate=rate, rows_eligible=scored.rows_eligible
+ )
@frozen
@@ -276,6 +285,8 @@ def run_inference_for_pipeline(
"stub": bool((model.model_recipe or {}).get("stub", False)),
"sandbox": bool(model.artifact_prefix),
"holdout_auc": scored.holdout_auc,
+ # The coverage of a rolling run: rows_scored of rows_eligible were scored today.
+ "rows_eligible": scored.rows_eligible,
}
)
run.completed_at = django_timezone.now()
@@ -292,6 +303,7 @@ def run_inference_for_pipeline(
pipeline_id=str(pipeline.pk),
model_id=str(model.pk),
rows_scored=emitted.rows_emitted,
+ rows_eligible=scored.rows_eligible,
)
return run
@@ -402,7 +414,10 @@ def _score_population_raw(
query_context=query_context,
)
return ScoredPopulation(
- rows=result.scored_rows, holdout_auc=result.holdout_auc, negative_sample_rate=model.negative_sample_rate
+ rows=result.scored_rows,
+ holdout_auc=result.holdout_auc,
+ negative_sample_rate=model.negative_sample_rate,
+ rows_eligible=result.rows_eligible,
)
if window.is_backfill:
@@ -415,10 +430,17 @@ def _score_population_raw(
)
recipe = model.model_recipe or {}
if recipe.get("stub"):
- rows = _fetch_stub_feature_rows(
- team=team, pipeline=pipeline, recipe=recipe, user=acting_user, query_context=query_context
+ stub_rows = _fetch_stub_feature_rows(
+ team=team,
+ pipeline=pipeline,
+ recipe=recipe,
+ cutoff_ts=cutoff_ts,
+ user=acting_user,
+ query_context=query_context,
+ )
+ return ScoredPopulation(
+ rows=_score_rows(stub_rows.rows), holdout_auc=model.holdout_score, rows_eligible=stub_rows.eligible
)
- return ScoredPopulation(rows=_score_rows(rows), holdout_auc=model.holdout_score)
feature_sql = str(recipe.get("feature_sql") or "")
try:
@@ -591,7 +613,8 @@ def _query(
HogQL caps a bare SELECT at 100 rows without an error, so every query here carries an
explicit bound, and a result that fills it is treated as truncated: completing would
- advance the cadence past the people beyond the cap. The persons-on-events modifiers
+ advance the cadence past the people beyond the cap. A scoring population that large takes a
+ rolling subset below the bound, so only a query that misbehaves reaches it. The persons-on-events modifiers
keep ``person_id`` resolving the way the labeler's queries do, and the always-calculate mode stops a
cadence reusing a cached population at a stale cutoff.
"""
@@ -659,9 +682,10 @@ def _fetch_stub_feature_rows(
team: Team,
pipeline: AutoresearchPipeline,
recipe: dict[str, Any],
+ cutoff_ts: int,
user: User,
query_context: QueryContext = INTERACTIVE_QUERY,
-) -> list[dict[str, Any]]:
+) -> InferenceRows:
"""
Run a stub recipe's feature SQL restricted to the inference population.
@@ -670,35 +694,54 @@ def _fetch_stub_feature_rows(
applied inside the query rather than on the returned rows, so the row bound measures
the population being scored and not every person on the team. The rows are checked
against the population count, as the anchored paths check theirs against the anchors,
- because stub SQL that drops a member leaves every returned row looking valid.
+ because stub SQL that drops a member leaves every returned row looking valid. A population
+ at or above the cap scores a rolling subset, as the anchored paths do. The population and the
+ rolling ranking bind the run's ``cutoff_ts``, so a retry selects the same people, while the
+ stub SQL itself keeps reading at now().
"""
feature_sql = str(recipe.get("feature_sql") or "")
if not feature_sql:
logger.warning("autoresearch_empty_feature_sql", pipeline_id=str(pipeline.pk))
- return []
+ return InferenceRows(rows=[], eligible=0)
lookback_days = _feature_lookback_days(pipeline)
feature_sql = feature_sql.replace("{lookback_days}", str(lookback_days)).rstrip().rstrip(";")
population = _population_query(
population=pipeline.inference_population,
lookback_days=lookback_days,
+ cutoff_ts=cutoff_ts,
target_event=pipeline.target_event,
target_definition=pipeline.target_definition,
team=team,
)
- sql, values = feature_sql, {}
- if population is not None:
- sql = f"SELECT * FROM ({feature_sql}) AS f WHERE f.distinct_id IN ({population.sql})"
- values = population.values
+ if population is None:
+ rows = _person_rows(
+ _query(team=team, sql=feature_sql, values={}, user=user, what="Feature", query_context=query_context)
+ )
+ _require_one_row_per_person(rows, source="stub feature_sql", expected_count=None)
+ return InferenceRows(rows=rows, eligible=len(rows))
+ eligible = _count_population(team=team, population=population, user=user, query_context=query_context)
+ rolling = rolling_selection(eligible=eligible, pipeline_id=str(pipeline.pk), cadence_days=pipeline.cadence_days)
+ if rolling is not None:
+ population = (
+ _population_query(
+ population=pipeline.inference_population,
+ lookback_days=lookback_days,
+ cutoff_ts=cutoff_ts,
+ target_event=pipeline.target_event,
+ target_definition=pipeline.target_definition,
+ team=team,
+ rolling=rolling,
+ )
+ or population
+ )
+ sql = f"SELECT * FROM ({feature_sql}) AS f WHERE f.distinct_id IN ({population.sql})"
rows = _person_rows(
- _query(team=team, sql=sql, values=values, user=user, what="Feature", query_context=query_context)
+ _query(team=team, sql=sql, values=population.values, user=user, what="Feature", query_context=query_context)
)
- expected = (
- _count_population(team=team, population=population, user=user, query_context=query_context)
- if population is not None
- else None
+ _require_one_row_per_person(
+ rows, source="stub feature_sql", expected_count=eligible if rolling is None else rolling.limit
)
- _require_one_row_per_person(rows, source="stub feature_sql", expected_count=expected)
- return rows
+ return InferenceRows(rows=rows, eligible=eligible)
@frozen
@@ -711,24 +754,28 @@ def _population_query(
*,
population: dict[str, Any] | None,
lookback_days: int,
+ cutoff_ts: int | None = None,
target_event: str = "",
target_definition: dict[str, Any] | None = None,
team: Team | None = None,
+ rolling: RollingSelection | None = None,
) -> _PopulationQuery | None:
"""
A ``SELECT person_id`` for the people in the inference population, one row each, from the
scorer's own anchor query, so it is restricted to identified users under the v1 scope. None only when nothing restricts the population.
A configured filter that cannot be compiled raises, because widening to everyone is
- the failure being prevented.
+ the failure being prevented. ``rolling`` keeps only a rolling subset of the people.
"""
if not IDENTIFIED_USERS_ONLY and not (population or {}).get("properties") and not (population or {}).get("kind"):
return None
anchors_sql, values = build_inference_anchors_sql(
lookback_days=lookback_days,
inference_population=population,
+ cutoff_ts=cutoff_ts,
target_event=target_event,
target_definition=target_definition,
team=team,
+ rolling=rolling,
)
return _PopulationQuery(sql=f"SELECT person_id FROM ({anchors_sql.strip()})", values=values)
@@ -806,7 +853,7 @@ def _score_via_anchors(
training_rows, negative_sample_rate = _fetch_training_rows(
team=team, pipeline=pipeline, feature_sql=feature_sql, user=user, query_context=query_context
)
- inference_rows = _fetch_inference_rows(
+ inference = _fetch_inference_rows(
team=team,
pipeline=pipeline,
feature_sql=feature_sql,
@@ -814,19 +861,20 @@ def _score_via_anchors(
user=user,
query_context=query_context,
)
- if not inference_rows:
+ if not inference.rows:
logger.warning("autoresearch_no_inference_rows", pipeline_id=str(pipeline.pk))
- return ScoredPopulation(rows=[], holdout_auc=None)
+ return ScoredPopulation(rows=[], holdout_auc=None, rows_eligible=inference.eligible)
if not training_rows:
logger.warning("autoresearch_no_training_rows_anchored_fallback_stub", pipeline_id=str(pipeline.pk))
- return ScoredPopulation(rows=_score_rows(inference_rows), holdout_auc=None)
- return _fit_on_training_predict_on_inference(
+ return ScoredPopulation(rows=_score_rows(inference.rows), holdout_auc=None, rows_eligible=inference.eligible)
+ scored = _fit_on_training_predict_on_inference(
training_rows=training_rows,
- inference_rows=inference_rows,
+ inference_rows=inference.rows,
recipe=recipe,
pipeline_id=str(pipeline.pk),
negative_sample_rate=negative_sample_rate,
)
+ return dataclasses.replace(scored, rows_eligible=inference.eligible)
def _fetch_training_rows(
@@ -892,14 +940,22 @@ def _fetch_inference_rows(
cutoff_ts: int | None,
user: User,
query_context: QueryContext = INTERACTIVE_QUERY,
-) -> list[dict[str, Any]]:
+) -> InferenceRows:
"""
- The recipe's feature SQL against the inference anchors: one row per eligible person.
+ The recipe's feature SQL against the inference anchors: one row per eligible person, or
+ per person in the rolling subset when the population reached the cap.
The row count is checked against the anchor count, because feature SQL that inner
joins or filters a joined table drops people without any row looking wrong. The training
rows get the same check against the labeled anchors.
"""
+ try:
+ eligible = count_inference_anchors(
+ team=team, pipeline=pipeline, cutoff_ts=cutoff_ts, user=user, query_context=query_context
+ )
+ except SandboxInferenceError as exc:
+ raise InferenceRunError(str(exc)) from exc
+ rolling = rolling_selection(eligible=eligible, pipeline_id=str(pipeline.pk), cadence_days=pipeline.cadence_days)
sql, values = build_inference_features_sql(
feature_sql=feature_sql,
lookback_days=_feature_lookback_days(pipeline),
@@ -908,18 +964,15 @@ def _fetch_inference_rows(
target_event=pipeline.target_event,
target_definition=pipeline.target_definition,
team=team,
+ rolling=rolling,
)
rows = _person_rows(
_query(team=team, sql=sql, values=values, user=user, what="Inference features", query_context=query_context)
)
- try:
- expected = count_inference_anchors(
- team=team, pipeline=pipeline, cutoff_ts=cutoff_ts, user=user, query_context=query_context
- )
- except SandboxInferenceError as exc:
- raise InferenceRunError(str(exc)) from exc
- _require_one_row_per_person(rows, source="inference feature_sql", expected_count=expected)
- return rows
+ _require_one_row_per_person(
+ rows, source="inference feature_sql", expected_count=eligible if rolling is None else rolling.limit
+ )
+ return InferenceRows(rows=rows, eligible=eligible)
def _fit_on_training_predict_on_inference(
diff --git a/products/autoresearch/backend/inference/test_inference.py b/products/autoresearch/backend/inference/test_inference.py
index 8d41b666d750..cb987ea60118 100644
--- a/products/autoresearch/backend/inference/test_inference.py
+++ b/products/autoresearch/backend/inference/test_inference.py
@@ -11,12 +11,12 @@ from parameterized import parameterized
from posthog.api.capture import CaptureInternalResult
-from products.autoresearch.backend.dataset.labeling import PREDICTION_EVENT_NAME
+from products.autoresearch.backend.dataset.labeling import PREDICTION_EVENT_NAME, ROLLING_SCORE_LIMIT
from products.autoresearch.backend.inference import (
sandbox as sandbox_inference,
scoring,
)
-from products.autoresearch.backend.inference.sandbox import _MATERIALIZE_ROW_LIMIT, SandboxScoreResult
+from products.autoresearch.backend.inference.sandbox import _MATERIALIZE_ROW_LIMIT, InferenceRows, SandboxScoreResult
from products.autoresearch.backend.inference.scoring import (
InferenceRunError,
ScoredPopulation,
@@ -49,6 +49,8 @@ _ANCHORS_RECIPE = {
"model_class": "sklearn.linear_model.LogisticRegression",
"model_params": {},
}
+_STUB_CUTOFF_TS = 1_757_548_800
+
_STUB_ROWS = [
{"distinct_id": "user-1", "events_total_30d": 50, "days_since_last_seen": 2},
{"distinct_id": "user-2", "events_total_30d": 10, "days_since_last_seen": 15},
@@ -123,9 +125,12 @@ class TestRunInferencePipeline(TeamScopedTestMixin, BaseTest):
)
return pipeline, model
- def _run_live(self, pipeline, model, capture: MagicMock, rows=_STUB_ROWS, resolved=None) -> AutoresearchRun:
+ def _run_live(
+ self, pipeline, model, capture: MagicMock, rows=_STUB_ROWS, resolved=None, eligible: int | None = None
+ ) -> AutoresearchRun:
+ stub_rows = InferenceRows(rows=rows, eligible=len(rows) if eligible is None else eligible)
with (
- patch.object(scoring, "_fetch_stub_feature_rows", return_value=rows),
+ patch.object(scoring, "_fetch_stub_feature_rows", return_value=stub_rows),
patch.object(scoring, "_resolve_distinct_ids", return_value=resolved or {}),
patch.object(scoring, "capture_batch_internal", capture),
):
@@ -173,6 +178,7 @@ class TestRunInferencePipeline(TeamScopedTestMixin, BaseTest):
holdout_auc=0.7,
n_train=10,
n_features=1,
+ rows_eligible=1,
)
capture = _capture_accepting_everything()
with (
@@ -190,6 +196,15 @@ class TestRunInferencePipeline(TeamScopedTestMixin, BaseTest):
run.refresh_from_db()
assert run.negative_sample_rate == 0.25
+ def test_a_rolling_run_records_the_eligible_total_next_to_the_rows_scored(self):
+ pipeline, model = self._make_pipeline_and_model()
+
+ run = self._run_live(pipeline, model, _capture_accepting_everything(), eligible=250_000)
+
+ assert run.status == AutoresearchRun.Status.COMPLETED
+ assert run.rows_scored == 2
+ assert run.metrics["rows_eligible"] == 250_000
+
def test_run_inference_zero_rows_completes_without_emitting(self):
pipeline, model = self._make_pipeline_and_model()
capture = _capture_accepting_everything()
@@ -256,7 +271,7 @@ class TestRunInferencePipeline(TeamScopedTestMixin, BaseTest):
def archive_then_return_rows(**_kwargs):
AutoresearchModel.objects.filter(pk=model.pk).update(role=AutoresearchModel.Role.ARCHIVED)
- return _STUB_ROWS
+ return InferenceRows(rows=_STUB_ROWS, eligible=len(_STUB_ROWS))
with (
patch.object(scoring, "_fetch_stub_feature_rows", side_effect=archive_then_return_rows),
@@ -362,7 +377,11 @@ class TestPredictionDateGuards(TeamScopedTestMixin, BaseTest):
model.artifact_prefix = "tasks/autoresearch/team_1/pipeline_x/run_y"
model.save(update_fields=["artifact_prefix"])
sandbox_result = SandboxScoreResult(
- scored_rows=[{"distinct_id": str(uuid4()), "p_y": 0.4}], holdout_auc=0.6, n_train=1, n_features=1
+ scored_rows=[{"distinct_id": str(uuid4()), "p_y": 0.4}],
+ holdout_auc=0.6,
+ n_train=1,
+ n_features=1,
+ rows_eligible=1,
)
with (
patch.object(scoring, "score_via_sandbox", return_value=sandbox_result) as sandbox,
@@ -487,7 +506,7 @@ class TestRecipeRouting(TeamScopedTestMixin, BaseTest):
]
with (
patch.object(scoring, "_fetch_training_rows", return_value=(training_rows, 1.0)),
- patch.object(scoring, "_fetch_inference_rows", return_value=inference_rows),
+ patch.object(scoring, "_fetch_inference_rows", return_value=InferenceRows(rows=inference_rows, eligible=2)),
patch.object(scoring, "_resolve_distinct_ids", return_value={}),
patch.object(scoring, "capture_batch_internal", _capture_accepting_everything()),
):
@@ -533,12 +552,12 @@ class TestStubFeatureRows(TeamScopedTestMixin, BaseTest):
)
def _sent(self, mock_run: MagicMock) -> tuple[str, dict]:
- query = mock_run.call_args_list[0].kwargs["query"]
+ query = mock_run.call_args_list[1].kwargs["query"]
return query.query, query.values
@staticmethod
- def _feature_then_count(rows: list[list], count: int) -> list[HogQLResult]:
- return [HogQLResult(columns=["distinct_id"], rows=rows), HogQLResult(columns=["count()"], rows=[[count]])]
+ def _count_then_feature(rows: list[list], count: int) -> list[HogQLResult]:
+ return [HogQLResult(columns=["count()"], rows=[[count]]), HogQLResult(columns=["distinct_id"], rows=rows)]
@patch("products.autoresearch.backend.inference.scoring.run_hogql")
def test_population_is_applied_inside_the_bounded_query(self, mock_run: MagicMock):
@@ -547,20 +566,25 @@ class TestStubFeatureRows(TeamScopedTestMixin, BaseTest):
pipeline = self._make_pipeline(
{"properties": [{"key": "plan", "type": "person", "operator": "exact", "value": "pro"}]}
)
- mock_run.side_effect = self._feature_then_count([["user-1"], ["user-3"]], count=2)
+ mock_run.side_effect = self._count_then_feature([["user-1"], ["user-3"]], count=2)
- rows = _fetch_stub_feature_rows(
- team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, user=self.user, query_context=BATCH_QUERY
+ stub_rows = _fetch_stub_feature_rows(
+ team=self.team,
+ pipeline=pipeline,
+ recipe=_STUB_RECIPE,
+ cutoff_ts=_STUB_CUTOFF_TS,
+ user=self.user,
+ query_context=BATCH_QUERY,
)
- assert {r["distinct_id"] for r in rows} == {"user-1", "user-3"}
+ assert {r["distinct_id"] for r in stub_rows.rows} == {"user-1", "user-3"}
assert [call.kwargs["query_context"] for call in mock_run.call_args_list] == [BATCH_QUERY, BATCH_QUERY]
sql, values = self._sent(mock_run)
assert "f.distinct_id IN (SELECT person_id FROM (SELECT id AS person_id" in sql
assert "argMax(ifNull((properties[{pop_k_0}] = {pop_0}), 0), version) = 1" in sql
assert values["pop_0"] == "pro"
assert sql.rstrip().endswith(f"LIMIT {_MATERIALIZE_ROW_LIMIT}")
- count_query = mock_run.call_args_list[1].kwargs["query"]
+ count_query = mock_run.call_args_list[0].kwargs["query"]
assert count_query.query.startswith("SELECT count() FROM (SELECT person_id FROM (SELECT id AS person_id")
assert count_query.values["pop_0"] == "pro"
assert all(call.kwargs["user"] == self.user for call in mock_run.call_args_list)
@@ -570,14 +594,17 @@ class TestStubFeatureRows(TeamScopedTestMixin, BaseTest):
# v1 scores identified users only; the scan must skip the product's own event, or a
# scored person stays eligible forever, and a future-dated event must not count.
pipeline = self._make_pipeline({})
- mock_run.side_effect = self._feature_then_count([["user-1"]], count=1)
+ mock_run.side_effect = self._count_then_feature([["user-1"]], count=1)
- _fetch_stub_feature_rows(team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, user=self.user)
+ _fetch_stub_feature_rows(
+ team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, cutoff_ts=_STUB_CUTOFF_TS, user=self.user
+ )
sql, values = self._sent(mock_run)
assert "argMax(is_identified, version) = 1" in sql
assert f"event != '{PREDICTION_EVENT_NAME}'" in sql
- assert "timestamp < now()" in sql
+ assert "timestamp < fromUnixTimestamp({cutoff_ts})" in sql
+ assert values["cutoff_ts"] == _STUB_CUTOFF_TS
assert values["lookback"] == 30
@parameterized.expand(
@@ -606,9 +633,11 @@ class TestStubFeatureRows(TeamScopedTestMixin, BaseTest):
# Template populations carry semantic kind specs; the stub path must compile them or
# a template pipeline silently scores all identified users.
pipeline = self._make_pipeline(population, target_event="downloaded_file")
- mock_run.side_effect = self._feature_then_count([["user-1"]], count=1)
+ mock_run.side_effect = self._count_then_feature([["user-1"]], count=1)
- _fetch_stub_feature_rows(team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, user=self.user)
+ _fetch_stub_feature_rows(
+ team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, cutoff_ts=_STUB_CUTOFF_TS, user=self.user
+ )
sql, _values = self._sent(mock_run)
for fragment in expected_fragments:
@@ -619,7 +648,9 @@ class TestStubFeatureRows(TeamScopedTestMixin, BaseTest):
# Widening to "all identified users" is the failure mode being prevented.
pipeline = self._make_pipeline({"kind": "ever_performed_event"})
with self.assertRaises(ValueError):
- _fetch_stub_feature_rows(team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, user=self.user)
+ _fetch_stub_feature_rows(
+ team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, cutoff_ts=_STUB_CUTOFF_TS, user=self.user
+ )
mock_run.assert_not_called()
@parameterized.expand(
@@ -635,9 +666,11 @@ class TestStubFeatureRows(TeamScopedTestMixin, BaseTest):
# twice; either way the run completed and reported a row count nobody received. Stub
# SQL that drops a member leaves valid rows behind, so only the population count notices.
pipeline = self._make_pipeline({})
- mock_run.side_effect = self._feature_then_count(rows, count=population_count)
+ mock_run.side_effect = self._count_then_feature(rows, count=population_count)
with self.assertRaises(InferenceRunError):
- _fetch_stub_feature_rows(team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, user=self.user)
+ _fetch_stub_feature_rows(
+ team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, cutoff_ts=_STUB_CUTOFF_TS, user=self.user
+ )
@parameterized.expand([("full_page", False), ("has_more", True)])
@patch("products.autoresearch.backend.inference.scoring.run_hogql")
@@ -646,11 +679,32 @@ class TestStubFeatureRows(TeamScopedTestMixin, BaseTest):
# certainly truncated; scoring the partial set would skip users while the cadence advanced.
pipeline = self._make_pipeline({})
n = 1 if has_more else _MATERIALIZE_ROW_LIMIT
- mock_run.return_value = HogQLResult(
- columns=["distinct_id"], rows=[[f"person-{i}"] for i in range(n)], has_more=has_more
- )
+ mock_run.side_effect = [
+ HogQLResult(columns=["count()"], rows=[[n]]),
+ HogQLResult(columns=["distinct_id"], rows=[[f"person-{i}"] for i in range(n)], has_more=has_more),
+ ]
with self.assertRaises(InferenceRunError):
- _fetch_stub_feature_rows(team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, user=self.user)
+ _fetch_stub_feature_rows(
+ team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, cutoff_ts=_STUB_CUTOFF_TS, user=self.user
+ )
+
+ @patch("products.autoresearch.backend.inference.scoring.run_hogql")
+ def test_a_population_at_the_cap_scores_a_rolling_subset(self, mock_run: MagicMock):
+ pipeline = self._make_pipeline({})
+ mock_run.side_effect = self._count_then_feature(
+ [[f"person-{i}"] for i in range(ROLLING_SCORE_LIMIT)], count=_MATERIALIZE_ROW_LIMIT * 5
+ )
+
+ stub_rows = _fetch_stub_feature_rows(
+ team=self.team, pipeline=pipeline, recipe=_STUB_RECIPE, cutoff_ts=_STUB_CUTOFF_TS, user=self.user
+ )
+
+ assert len(stub_rows.rows) == ROLLING_SCORE_LIMIT
+ assert stub_rows.eligible == _MATERIALIZE_ROW_LIMIT * 5
+ sql, values = self._sent(mock_run)
+ assert f"LIMIT {ROLLING_SCORE_LIMIT}" in sql
+ assert values["rolling_pipeline_id"] == str(pipeline.pk)
+ assert values["cutoff_ts"] == _STUB_CUTOFF_TS
class TestResolveDistinctIds(TeamScopedTestMixin, BaseTest):
diff --git a/products/autoresearch/backend/inference/test_sandbox_inference.py b/products/autoresearch/backend/inference/test_sandbox_inference.py
index 88f8689fcbcd..2711df02dc54 100644
--- a/products/autoresearch/backend/inference/test_sandbox_inference.py
+++ b/products/autoresearch/backend/inference/test_sandbox_inference.py
@@ -15,11 +15,13 @@ from posthog.api.capture import CaptureInternalResult
from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models.user import User
+from products.autoresearch.backend.dataset.labeling import ROLLING_SCORE_LIMIT
from products.autoresearch.backend.inference import sandbox as sandbox_inference
from products.autoresearch.backend.inference.sandbox import (
_FEATURE_COLUMNS_JSON,
_FILE_BEGIN,
_FILE_END,
+ InferenceRows,
SandboxInferenceError,
SandboxScoreResult,
_between_sentinels,
@@ -187,14 +189,42 @@ class TestMaterializeData(TeamScopedTestMixin, BaseTest):
patch.object(sandbox_inference, "count_inference_anchors", return_value=len(_SCORE_ROWS)) as count,
patch.object(sandbox_inference, "_materialize_rows", return_value=_SCORE_ROWS) as run,
):
- score_rows = _materialize_score_data(
+ score_data = _materialize_score_data(
team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}", query_context=BATCH_QUERY
)
# exactly one query (inference anchors only) — no training/holdout materialization
assert run.call_count == 1
assert run.call_args.kwargs["query_context"] == count.call_args.kwargs["query_context"] == BATCH_QUERY
- assert [r["distinct_id"] for r in score_rows] == ["s1", "s2"]
+ assert [r["distinct_id"] for r in score_data.rows] == ["s1", "s2"]
+ assert score_data.eligible == 2
+
+ @parameterized.expand(
+ [
+ ("rolling_subset_scores", ROLLING_SCORE_LIMIT, False),
+ ("rolling_subset_that_drops_a_person", ROLLING_SCORE_LIMIT - 1, True),
+ ]
+ )
+ def test_score_data_above_the_cap_takes_a_rolling_subset(self, _name, n_rows, expect_raise):
+ pipeline = self._pipeline()
+ rows = [{"distinct_id": f"p{i}", "events_total": 1} for i in range(n_rows)]
+ eligible = sandbox_inference._MATERIALIZE_ROW_LIMIT * 5
+ with (
+ patch.object(sandbox_inference, "count_inference_anchors", return_value=eligible),
+ patch.object(sandbox_inference, "_materialize_rows", return_value=rows) as run,
+ ):
+ if expect_raise:
+ with self.assertRaises(SandboxInferenceError):
+ _materialize_score_data(team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}")
+ return
+ score_data = _materialize_score_data(
+ team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}"
+ )
+
+ assert len(score_data.rows) == ROLLING_SCORE_LIMIT
+ assert score_data.eligible == eligible
+ assert f"LIMIT {ROLLING_SCORE_LIMIT}" in run.call_args.kwargs["sql"]
+ assert run.call_args.kwargs["values"]["rolling_pipeline_id"] == str(pipeline.pk)
@parameterized.expand(
[
@@ -464,7 +494,9 @@ class TestScoreViaSandbox(TeamScopedTestMixin, BaseTest):
patch.object(sandbox_inference, "read_bundle", return_value=self._bundle()),
patch.object(sandbox_inference, "read_model", return_value=b"PICKLE"),
patch.object(sandbox_inference, "read_artifact", return_value=fitted_columns),
- patch.object(sandbox_inference, "_materialize_score_data", return_value=_SCORE_ROWS),
+ patch.object(
+ sandbox_inference, "_materialize_score_data", return_value=InferenceRows(rows=_SCORE_ROWS, eligible=2)
+ ),
patch.object(sandbox_inference.Sandbox, "create", return_value=fake),
):
result = score_via_sandbox(team=self.team, pipeline=pipeline, model=model)
@@ -543,7 +575,9 @@ class TestScoreViaSandbox(TeamScopedTestMixin, BaseTest):
patch.object(sandbox_inference, "read_bundle", return_value=self._bundle()),
patch.object(sandbox_inference, "read_model", return_value=b"PICKLE"),
self._no_fitted_columns(),
- patch.object(sandbox_inference, "_materialize_score_data", return_value=[]) as materialize,
+ patch.object(
+ sandbox_inference, "_materialize_score_data", return_value=InferenceRows(rows=[], eligible=0)
+ ) as materialize,
):
with self.assertRaises(SandboxInferenceError):
score_via_sandbox(team=self.team, pipeline=pipeline, model=model)
@@ -566,7 +600,9 @@ class TestScoreViaSandbox(TeamScopedTestMixin, BaseTest):
patch.object(sandbox_inference, "read_bundle", return_value=self._bundle()),
patch.object(sandbox_inference, "read_model", return_value=b"PICKLE"),
self._no_fitted_columns(),
- patch.object(sandbox_inference, "_materialize_score_data", return_value=_SCORE_ROWS),
+ patch.object(
+ sandbox_inference, "_materialize_score_data", return_value=InferenceRows(rows=_SCORE_ROWS, eligible=2)
+ ),
patch.object(sandbox_inference.Sandbox, "create", return_value=fake),
):
with self.assertRaises(SandboxInferenceError) as ctx:
@@ -581,7 +617,9 @@ class TestScoreViaSandbox(TeamScopedTestMixin, BaseTest):
patch.object(sandbox_inference, "read_bundle", return_value=self._bundle()),
patch.object(sandbox_inference, "read_model", return_value=b"PICKLE"),
self._no_fitted_columns(),
- patch.object(sandbox_inference, "_materialize_score_data", return_value=_SCORE_ROWS),
+ patch.object(
+ sandbox_inference, "_materialize_score_data", return_value=InferenceRows(rows=_SCORE_ROWS, eligible=2)
+ ),
patch.object(sandbox_inference.Sandbox, "create", return_value=fake),
):
with self.assertRaises(SandboxInferenceError):
@@ -599,7 +637,7 @@ class TestScoreViaSandbox(TeamScopedTestMixin, BaseTest):
patch.object(sandbox_inference, "read_bundle", return_value=self._bundle()),
patch.object(sandbox_inference, "read_model", return_value=b"PICKLE"),
self._no_fitted_columns(),
- patch.object(sandbox_inference, "_materialize_score_data", return_value=[]),
+ patch.object(sandbox_inference, "_materialize_score_data", return_value=InferenceRows(rows=[], eligible=0)),
patch.object(sandbox_inference.Sandbox, "create", create_mock),
):
result = score_via_sandbox(team=self.team, pipeline=pipeline, model=model)
@@ -696,6 +734,7 @@ class TestInferenceRouting(TeamScopedTestMixin, BaseTest):
holdout_auc=0.71,
n_train=2,
n_features=2,
+ rows_eligible=2,
)
emit = MagicMock(
side_effect=lambda **kwargs: CaptureInternalResult(
diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.py
index 9f406fa81749..168d04ed8ce3 100644
--- a/products/autoresearch/backend/presentation/views/serializers.py
+++ b/products/autoresearch/backend/presentation/views/serializers.py
@@ -1148,7 +1148,13 @@ class AutoresearchRunSerializer(DataclassSerializer):
allow_null=True,
help_text="Number of users scored in this inference run.",
)
- metrics = MetricsBundleField(help_text="Run metrics: rows scored, score distribution summary, validation AUC, etc.")
+ metrics = MetricsBundleField(
+ help_text=(
+ "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."
+ )
+ )
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(
@@ -1182,7 +1188,9 @@ class ValidationWarningSerializer(serializers.Serializer):
help_text=(
"Machine-readable warning code. 'horizon_exceeds_lookback', and 'population_too_large' with severity "
"'error', mean a run would fail: fix the definition before creating. 'population_too_large' with "
- "severity 'info' means training uses a sample of the population. 'low_volume', 'low_positives' and "
+ "severity 'info' means training uses a sample of the population, or each scoring run scores a rolling "
+ "part of it: users never scored first, then users whose last score was oldest. 'low_volume', "
+ "'low_positives' and "
"'low_negatives' mean the data is too thin for a reliable model (severity 'error', advisory). "
"'moderate_volume', 'mostly_anonymous_population', 'extreme_imbalance' and 'near_universal' are "
"severity 'warning'."
@@ -1245,7 +1253,7 @@ class ValidatePipelineResponseSerializer(serializers.Serializer):
can_proceed = serializers.BooleanField(
help_text=(
"False when any warning has severity 'error'. Creation does not enforce it, but a definition with "
- "an 'error' 'population_too_large' or 'horizon_exceeds_lookback' cannot train or score."
+ "an 'error' 'population_too_large' or 'horizon_exceeds_lookback' cannot train."
)
)
requires_acknowledgement = serializers.BooleanField(
diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts
index e14dde9edadd..704010943010 100644
--- a/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts
+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts
@@ -5,7 +5,12 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { initKeaTests } from '~/test/init'
-import { SCORE_RUN_POLL_INTERVAL_MS, autoresearchPipelineLogic, trainingRunProgress } from './autoresearchPipelineLogic'
+import {
+ SCORE_RUN_POLL_INTERVAL_MS,
+ autoresearchPipelineLogic,
+ scoringCoverage,
+ trainingRunProgress,
+} from './autoresearchPipelineLogic'
import {
autoresearchModelsList,
autoresearchRetrieve,
@@ -76,6 +81,19 @@ function makeIteration(overrides: Partial<IterationTrailApi>): IterationTrailApi
} as IterationTrailApi
}
+function makeScoringRun(overrides: Partial<AutoresearchRunApi>): AutoresearchRunApi {
+ return {
+ id: 'scoring-run',
+ pipeline: 'pipeline-1',
+ run_type: 'inference',
+ status: 'completed',
+ rows_scored: 45000,
+ metrics: { rows_eligible: 250000 },
+ created_at: '2026-01-02T00:00:00Z',
+ ...overrides,
+ } as AutoresearchRunApi
+}
+
describe('autoresearchPipelineLogic', () => {
it('follows every page of models so a champion past the first page still counts', async () => {
jest.clearAllMocks()
@@ -171,6 +189,40 @@ describe('autoresearchPipelineLogic', () => {
logic.unmount()
})
+ describe('scoringCoverage', () => {
+ it.each([
+ ['a rolling run', [makeScoringRun({})], { scored: 45000, eligible: 250000, rescoreDays: 6 }],
+ ['a run that scored everyone', [makeScoringRun({ metrics: { rows_eligible: 45000 } })], null],
+ ['a run from before the eligible count was recorded', [makeScoringRun({ metrics: {} })], null],
+ [
+ 'an older rolling run superseded by a full one',
+ [
+ makeScoringRun({ id: 'old', created_at: '2026-01-01T00:00:00Z' }),
+ makeScoringRun({ id: 'new', rows_scored: 900, metrics: { rows_eligible: 900 } }),
+ ],
+ null,
+ ],
+ [
+ 'a newer run that failed',
+ [
+ makeScoringRun({}),
+ makeScoringRun({ id: 'failed', status: 'failed', created_at: '2026-01-03T00:00:00Z' }),
+ ],
+ { scored: 45000, eligible: 250000, rescoreDays: 6 },
+ ],
+ ])('reads the coverage of %s', (_name, runs, expected) => {
+ expect(scoringCoverage(runs, 1)).toEqual(expected)
+ })
+
+ it('counts the rescore interval in days for a non-daily cadence', () => {
+ expect(scoringCoverage([makeScoringRun({})], 7)).toEqual({
+ scored: 45000,
+ eligible: 250000,
+ rescoreDays: 42,
+ })
+ })
+ })
+
describe('trainingRunProgress', () => {
it('derives progress from live iteration rows while the run is in flight', () => {
// Persisted fields are only written at completion, so they read 0 / null here.
diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.ts
index 1e2c5fa11069..19a50f0327ff 100644
--- a/products/autoresearch/frontend/autoresearchPipelineLogic.ts
+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.ts
@@ -174,6 +174,33 @@ export function trainingRunProgress(run: AutoresearchTrainingRunApi): TrainingRu
}
}
+/** How much of the inference population the latest scoring run covered, when it scored only part of it. */
+export interface ScoringCoverage {
+ scored: number
+ eligible: number
+ /** Days it takes to score everyone once: the runs a rotation needs times the days between runs. */
+ rescoreDays: number
+}
+
+/**
+ * A population at or above the scoring cap is scored on a rolling basis: each run scores the
+ * people whose last score is oldest. Returns null when the latest completed run scored everyone.
+ */
+export function scoringCoverage(runs: AutoresearchRunApi[], cadenceDays: number): ScoringCoverage | null {
+ const latest = runs
+ .filter((run) => run.run_type === 'inference' && run.status === 'completed')
+ .reduce<AutoresearchRunApi | null>(
+ (newest, run) => (newest === null || run.created_at > newest.created_at ? run : newest),
+ null
+ )
+ const scored = latest?.rows_scored ?? 0
+ const eligible = latest?.metrics?.rows_eligible
+ if (scored <= 0 || typeof eligible !== 'number' || eligible <= scored) {
+ return null
+ }
+ return { scored, eligible, rescoreDays: Math.ceil(eligible / scored) * Math.max(cadenceDays, 1) }
+}
+
/** One scoring day's volume: emitted prediction events and their average probability as a 0-100 percentage. */
export interface DailyVolumePoint {
day: string
@@ -228,6 +255,7 @@ export interface autoresearchPipelineLogicValues {
runsLoading: boolean
scoreResult: AutoresearchRunApi | null
scoreResultLoading: boolean
+ scoringCoverage: ScoringCoverage | null
startTrainingResult: AutoresearchTrainingRunApi | null
startTrainingResultLoading: boolean
suggestionDraft: string
@@ -584,6 +612,10 @@ export interface autoresearchPipelineLogicMeta {
__keaTypeGenInternalSelectorTypes: {
breadcrumbs: (pipeline: AutoresearchPipelineApi | null) => Breadcrumb[]
validationRuns: (runs: AutoresearchRunApi[]) => AutoresearchRunApi[]
+ scoringCoverage: (
+ runs: AutoresearchRunApi[],
+ pipeline: AutoresearchPipelineApi | null
+ ) => ScoringCoverage | null
onlinePerformanceRows: (validationRuns: AutoresearchRunApi[]) => OnlinePerformanceRow[]
probabilityHistogram: (probabilityDistribution: ProbabilityBucket[] | null) => ProbabilityBucket[] | null
}
@@ -961,6 +993,11 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
(runs: AutoresearchRunApi[]): AutoresearchRunApi[] =>
runs.filter((r) => r.run_type === 'validation' && r.status === 'completed'),
],
+ scoringCoverage: [
+ (s) => [s.runs, s.pipeline],
+ (runs: AutoresearchRunApi[], pipeline: AutoresearchPipelineApi | null): ScoringCoverage | null =>
+ scoringCoverage(runs, pipeline?.cadence_days ?? 1),
+ ],
onlinePerformanceRows: [
(s) => [s.validationRuns],
(validationRuns: AutoresearchRunApi[]): OnlinePerformanceRow[] => {
diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.ts
index 368ca65827e3..a6d5871d14e5 100644
--- a/products/autoresearch/frontend/generated/api.schemas.ts
+++ b/products/autoresearch/frontend/generated/api.schemas.ts
@@ -434,7 +434,7 @@ export const ZendeskImportJobStatusEnumApi = {
} as const
/**
- * Run metrics: rows scored, score distribution summary, validation AUC, etc.
+ * 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.
*/
export type AutoresearchRunApiMetrics = { [key: string]: unknown }
@@ -467,7 +467,7 @@ export interface AutoresearchRunApi {
* @nullable
*/
rows_scored?: number | null
- /** Run metrics: rows scored, score distribution summary, validation AUC, etc. */
+ /** 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
/** Error message if the run failed. */
error?: string
@@ -1499,7 +1499,7 @@ export const ValidationWarningSeverityEnumApi = {
} as const
export interface ValidationWarningApi {
- /** Machine-readable warning code. 'horizon_exceeds_lookback', and 'population_too_large' with severity 'error', mean a run would fail: fix the definition before creating. 'population_too_large' with severity 'info' means training uses a sample of the population. 'low_volume', 'low_positives' and 'low_negatives' mean the data is too thin for a reliable model (severity 'error', advisory). 'moderate_volume', 'mostly_anonymous_population', 'extreme_imbalance' and 'near_universal' are severity 'warning'. */
+ /** Machine-readable warning code. 'horizon_exceeds_lookback', and 'population_too_large' with severity 'error', mean a run would fail: fix the definition before creating. 'population_too_large' with severity 'info' means training uses a sample of the population, or each scoring run scores a rolling part of it: users never scored first, then users whose last score was oldest. 'low_volume', 'low_positives' and 'low_negatives' mean the data is too thin for a reliable model (severity 'error', advisory). 'moderate_volume', 'mostly_anonymous_population', 'extreme_imbalance' and 'near_universal' are severity 'warning'. */
code: string
/** Human-readable warning description. */
message: string
@@ -1512,7 +1512,7 @@ export interface ValidationWarningApi {
}
export interface ValidatePipelineResponseApi {
- /** False when any warning has severity 'error'. Creation does not enforce it, but a definition with an 'error' 'population_too_large' or 'horizon_exceeds_lookback' cannot train or score. */
+ /** False when any warning has severity 'error'. Creation does not enforce it, but a definition with an 'error' 'population_too_large' or 'horizon_exceeds_lookback' cannot train. */
can_proceed: boolean
/** True if there are non-blocking warnings the user should acknowledge before proceeding. */
requires_acknowledgement: boolean
diff --git a/products/autoresearch/frontend/pipeline/PredictionsTab.tsx b/products/autoresearch/frontend/pipeline/PredictionsTab.tsx
index 6224301641c9..0e02d275d5b4 100644
--- a/products/autoresearch/frontend/pipeline/PredictionsTab.tsx
+++ b/products/autoresearch/frontend/pipeline/PredictionsTab.tsx
@@ -1,7 +1,9 @@
import { useValues } from 'kea'
import { IconGraph } from '@posthog/icons'
-import { LemonCollapse, LemonSkeleton } from '@posthog/lemon-ui'
+import { LemonBanner, LemonCollapse, LemonSkeleton } from '@posthog/lemon-ui'
+
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'
import { DailyVolumeChart } from '../DailyVolumeChart'
@@ -52,6 +54,20 @@ function ProbabilityDistributionPanel(): JSX.Element {
return <ProbabilityHistogram buckets={probabilityHistogram} />
}
+function ScoringCoverageBanner(): JSX.Element | null {
+ const { scoringCoverage } = useValues(autoresearchPipelineLogic)
+ if (!scoringCoverage) {
+ return null
+ }
+ const { scored, eligible, rescoreDays } = scoringCoverage
+ return (
+ <LemonBanner type="info">
+ The latest run scored {humanFriendlyNumber(scored)} of {humanFriendlyNumber(eligible)} users, starting with
+ users never scored, then those scored longest ago. Everyone is rescored about every {rescoreDays} days.
+ </LemonBanner>
+ )
+}
+
export function PredictionsTab(): JSX.Element {
const { pipeline } = useValues(autoresearchPipelineLogic)
if (!pipeline) {
@@ -76,6 +92,8 @@ export function PredictionsTab(): JSX.Element {
<code>autoresearch_prediction</code> event. These views read straight from those events.
</p>
+ <ScoringCoverageBanner />
+
<LemonCollapse
multiple
defaultActiveKeys={['distribution', 'highest']}
diff --git a/products/autoresearch/mcp/tools.yaml b/products/autoresearch/mcp/tools.yaml
index 87c83c366bc2..3f8b554c8621 100644
--- a/products/autoresearch/mcp/tools.yaml
+++ b/products/autoresearch/mcp/tools.yaml
@@ -242,7 +242,8 @@ tools:
title: List inference runs
description: >
List inference and validation runs for a pipeline, ordered most recent first. Check rows_scored and status
- to understand scoring history. run_type is 'inference' for daily scoring runs.
+ to understand scoring history. run_type is 'inference' for daily scoring runs. An inference run whose
+ metrics.rows_eligible is above rows_scored scored a rolling part of a population larger than one run allows.
feature_flag: autoresearch
response:
include:
@@ -644,9 +645,12 @@ tools:
autoresearch-create: if false, resolve errors first. 'requires_acknowledgement' means there are non-blocking
warnings worth noting. Errors (can_proceed is false): low_volume (fewer than 100 users), low_positives or
low_negatives (fewer than 20 examples), horizon_exceeds_lookback (raise training_lookback_days above
- horizon_days), and population_too_large (narrow the training or inference population). Non-blocking warnings
- include extreme_imbalance (base rate below 1%) and near_universal (above 95%). An action target needs the
- action:read scope. Always validate before creating.
+ horizon_days), and population_too_large with severity error (narrow the training population). Non-blocking
+ warnings include extreme_imbalance (base rate below 1%) and near_universal (above 95%). population_too_large
+ with severity info means the inference population is above the cap, so each scoring run scores users never
+ scored first, then those scored longest ago. The warning message gives how many scoring runs it takes to
+ rescore everyone (ceil(eligible / 45000)), which in days is that many times the pipeline's cadence_days. An
+ action target needs the action:read scope. Always validate before creating.
feature_flag: autoresearch
autoresearch-validate-online-create:
operation: autoresearch_validate_online_create
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 1420bddb7fd4..252f2e1c2f57 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1195,7 +1195,7 @@
"feature_flag": "autoresearch"
},
"autoresearch-runs-list": {
- "description": "List inference and validation runs for a pipeline, ordered most recent first. Check rows_scored and status to understand scoring history. run_type is 'inference' for daily scoring runs.",
+ "description": "List inference and validation runs for a pipeline, ordered most recent first. Check rows_scored and status to understand scoring history. run_type is 'inference' for daily scoring runs. An inference run whose metrics.rows_eligible is above rows_scored scored a rolling part of a population larger than one run allows.",
"category": "Autoresearch",
"feature": "autoresearch",
"summary": "List inference runs",
@@ -1405,7 +1405,7 @@
"feature_flag": "autoresearch"
},
"autoresearch-validate-create": {
- "description": "Validate a proposed autoresearch pipeline before creating it. The target is either an event (pass target_event) or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N}); base-rate and volume estimates are computed against whichever you provide. Returns volume estimates, base rate, positive and negative example counts, and a list of warnings. Check 'can_proceed' before calling autoresearch-create: if false, resolve errors first. 'requires_acknowledgement' means there are non-blocking warnings worth noting. Errors (can_proceed is false): low_volume (fewer than 100 users), low_positives or low_negatives (fewer than 20 examples), horizon_exceeds_lookback (raise training_lookback_days above horizon_days), and population_too_large (narrow the training or inference population). Non-blocking warnings include extreme_imbalance (base rate below 1%) and near_universal (above 95%). An action target needs the action:read scope. Always validate before creating.",
+ "description": "Validate a proposed autoresearch pipeline before creating it. The target is either an event (pass target_event) or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N}); base-rate and volume estimates are computed against whichever you provide. Returns volume estimates, base rate, positive and negative example counts, and a list of warnings. Check 'can_proceed' before calling autoresearch-create: if false, resolve errors first. 'requires_acknowledgement' means there are non-blocking warnings worth noting. Errors (can_proceed is false): low_volume (fewer than 100 users), low_positives or low_negatives (fewer than 20 examples), horizon_exceeds_lookback (raise training_lookback_days above horizon_days), and population_too_large with severity error (narrow the training population). Non-blocking warnings include extreme_imbalance (base rate below 1%) and near_universal (above 95%). population_too_large with severity info means the inference population is above the cap, so each scoring run scores users never scored first, then those scored longest ago. The warning message gives how many scoring runs it takes to rescore everyone (ceil(eligible / 45000)), which in days is that many times the pipeline's cadence_days. An action target needs the action:read scope. Always validate before creating.",
"category": "Autoresearch",
"feature": "autoresearch",
"summary": "Validate a pipeline definition",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 7841b4886df1..bb7c464d40f2 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1210,7 +1210,7 @@
"feature_flag": "autoresearch"
},
"autoresearch-runs-list": {
- "description": "List inference and validation runs for a pipeline, ordered most recent first. Check rows_scored and status to understand scoring history. run_type is 'inference' for daily scoring runs.",
+ "description": "List inference and validation runs for a pipeline, ordered most recent first. Check rows_scored and status to understand scoring history. run_type is 'inference' for daily scoring runs. An inference run whose metrics.rows_eligible is above rows_scored scored a rolling part of a population larger than one run allows.",
"category": "Autoresearch",
"feature": "autoresearch",
"summary": "List inference runs",
@@ -1420,7 +1420,7 @@
"feature_flag": "autoresearch"
},
"autoresearch-validate-create": {
- "description": "Validate a proposed autoresearch pipeline before creating it. The target is either an event (pass target_event) or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N}); base-rate and volume estimates are computed against whichever you provide. Returns volume estimates, base rate, positive and negative example counts, and a list of warnings. Check 'can_proceed' before calling autoresearch-create: if false, resolve errors first. 'requires_acknowledgement' means there are non-blocking warnings worth noting. Errors (can_proceed is false): low_volume (fewer than 100 users), low_positives or low_negatives (fewer than 20 examples), horizon_exceeds_lookback (raise training_lookback_days above horizon_days), and population_too_large (narrow the training or inference population). Non-blocking warnings include extreme_imbalance (base rate below 1%) and near_universal (above 95%). An action target needs the action:read scope. Always validate before creating.",
+ "description": "Validate a proposed autoresearch pipeline before creating it. The target is either an event (pass target_event) or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N}); base-rate and volume estimates are computed against whichever you provide. Returns volume estimates, base rate, positive and negative example counts, and a list of warnings. Check 'can_proceed' before calling autoresearch-create: if false, resolve errors first. 'requires_acknowledgement' means there are non-blocking warnings worth noting. Errors (can_proceed is false): low_volume (fewer than 100 users), low_positives or low_negatives (fewer than 20 examples), horizon_exceeds_lookback (raise training_lookback_days above horizon_days), and population_too_large with severity error (narrow the training population). Non-blocking warnings include extreme_imbalance (base rate below 1%) and near_universal (above 95%). population_too_large with severity info means the inference population is above the cap, so each scoring run scores users never scored first, then those scored longest ago. The warning message gives how many scoring runs it takes to rescore everyone (ceil(eligible / 45000)), which in days is that many times the pipeline's cadence_days. An action target needs the action:read scope. Always validate before creating.",
"category": "Autoresearch",
"feature": "autoresearch",
"summary": "Validate a pipeline definition",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 40b989870b0b..9cb1c80f5349 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13489,7 +13489,7 @@ export namespace Schemas {
}
/**
- * Run metrics: rows scored, score distribution summary, validation AUC, etc.
+ * 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.
*/
export type AutoresearchRunMetrics = { [key: string]: unknown };
@@ -13550,7 +13550,7 @@ export namespace Schemas {
* @nullable
*/
rows_scored?: number | null;
- /** Run metrics: rows scored, score distribution summary, validation AUC, etc. */
+ /** 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;
/** Error message if the run failed. */
error?: string;
@@ -106504,7 +106504,7 @@ export namespace Schemas {
} as const;
export interface ValidationWarning {
- /** Machine-readable warning code. 'horizon_exceeds_lookback', and 'population_too_large' with severity 'error', mean a run would fail: fix the definition before creating. 'population_too_large' with severity 'info' means training uses a sample of the population. 'low_volume', 'low_positives' and 'low_negatives' mean the data is too thin for a reliable model (severity 'error', advisory). 'moderate_volume', 'mostly_anonymous_population', 'extreme_imbalance' and 'near_universal' are severity 'warning'. */
+ /** Machine-readable warning code. 'horizon_exceeds_lookback', and 'population_too_large' with severity 'error', mean a run would fail: fix the definition before creating. 'population_too_large' with severity 'info' means training uses a sample of the population, or each scoring run scores a rolling part of it: users never scored first, then users whose last score was oldest. 'low_volume', 'low_positives' and 'low_negatives' mean the data is too thin for a reliable model (severity 'error', advisory). 'moderate_volume', 'mostly_anonymous_population', 'extreme_imbalance' and 'near_universal' are severity 'warning'. */
code: string;
/** Human-readable warning description. */
message: string;
@@ -106517,7 +106517,7 @@ export namespace Schemas {
}
export interface ValidatePipelineResponse {
- /** False when any warning has severity 'error'. Creation does not enforce it, but a definition with an 'error' 'population_too_large' or 'horizon_exceeds_lookback' cannot train or score. */
+ /** False when any warning has severity 'error'. Creation does not enforce it, but a definition with an 'error' 'population_too_large' or 'horizon_exceeds_lookback' cannot train. */
can_proceed: boolean;
/** True if there are non-blocking warnings the user should acknowledge before proceeding. */
requires_acknowledgement: boolean;