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): sample training populations above the row cap (#110003)

posthog[bot]7ef35b80a054
diff --git a/products/autoresearch/backend/dataset/AGENTS.md b/products/autoresearch/backend/dataset/AGENTS.md
index 1b56e5b81fd0..465de7cc589a 100644
--- a/products/autoresearch/backend/dataset/AGENTS.md
+++ b/products/autoresearch/backend/dataset/AGENTS.md
@@ -16,11 +16,16 @@ Nothing here trains or scores anything. It is the shared vocabulary that `../tra
Three call sites share this module so they cannot drift: the wizard's live estimate (sampled), the trainer (full materialization with fold split), and inference (per-person cutoff = `now()`).
That is why the training-side `labeled_anchors` CTE (inside `build_training_features_sql()`) and `build_inference_anchors_sql()` live here rather than next to their callers.
+ **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.
+
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.
- `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 5450a6d7673c..102f576c2ea4 100644
--- a/products/autoresearch/backend/dataset/labeling.py
+++ b/products/autoresearch/backend/dataset/labeling.py
@@ -32,6 +32,7 @@ Integer handling notes:
uniformity, and the position arithmetic stays inside Int64.
"""
+import math
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
@@ -100,6 +101,63 @@ def _own_events_excluded_clause(alias: str = "") -> str:
# refuses a larger population before a run is spent on it.
MATERIALIZE_ROW_LIMIT = 50_000
+# The share of MATERIALIZE_ROW_LIMIT a sampled training population aims at. The rate is chosen
+# from one count and applied in a later query, so the population can grow in between.
+TRAINING_SAMPLE_HEADROOM = 0.8
+TRAINING_SAMPLE_BUDGET = int(MATERIALIZE_ROW_LIMIT * TRAINING_SAMPLE_HEADROOM)
+
+# Negative anchors are kept when the low 31 bits of this salted hash fall under the rate's
+# threshold. The salt keeps the draw independent of the T0 and fold hashes of the same person.
+_SAMPLE_HASH = "bitAnd(cityHash64(concat('sample:', toString(person_id))), 2147483647)"
+_HASH_RANGE = 2147483648
+
+
+class TrainingSampleTooLarge(ValueError):
+ """The positives alone do not fit the training budget, so no negative sample rate can help."""
+
+
+@frozen
+class TrainingSample:
+ """
+ The case-control sample of training anchors: every positive, and each negative with
+ probability ``negative_sample_rate``. A rate of 1.0 keeps the whole population.
+ """
+
+ population: int
+ positives: int
+ negative_sample_rate: float
+
+ @property
+ def negatives(self) -> int:
+ return self.population - self.positives
+
+ @property
+ def expected_size(self) -> int:
+ return self.positives + round(self.negatives * self.negative_sample_rate)
+
+ @classmethod
+ def plan(cls, *, population: int, positives: int, budget: int = TRAINING_SAMPLE_BUDGET) -> "TrainingSample":
+ """
+ Keep every anchor when the population fits ``budget``. Otherwise keep every positive and
+ the fraction of negatives that fills the rest of it.
+ """
+ negatives = population - positives
+ if population <= budget or negatives <= 0:
+ return cls(population=population, positives=positives, negative_sample_rate=1.0)
+ if positives >= budget:
+ raise TrainingSampleTooLarge(
+ f"The training population has {positives} positive examples, more than the {budget} that one "
+ "run trains on. Narrow the population or shorten the horizon."
+ )
+ return cls(population=population, positives=positives, negative_sample_rate=(budget - positives) / negatives)
+
+
+def negative_sample_threshold(negative_sample_rate: float) -> int:
+ """The bound on the salted 31-bit hash under which a negative anchor is kept."""
+ if not 0.0 < negative_sample_rate <= 1.0:
+ raise ValueError(f"negative_sample_rate must be in (0, 1], got {negative_sample_rate!r}")
+ return math.floor(negative_sample_rate * _HASH_RANGE)
+
@dataclass(frozen=True, kw_only=True)
class _CompiledPopulationFilters:
@@ -594,12 +652,17 @@ def _build_labeled_users_cte(
training_population: dict[str, Any] | None,
sample_limit: int | None,
anchor_ts: int | None = None,
+ negative_sample_rate: float = 1.0,
) -> tuple[str, dict[str, Any]]:
"""
Build the WITH clause that materialises the labeled_users table:
labeled_users(person_id, t0_ts, positive)
Caller appends `SELECT ... FROM labeled_users` to use it.
+ A ``negative_sample_rate`` below 1 keeps every positive and each negative whose salted
+ person hash falls under the rate, so the same people are drawn on every run. At 1.0 the
+ query is the unsampled one.
+
Population membership is decided per user at T0. Person-property filters and
identity come from ``raw_persons``, and the kinds' cheap superset fragments
narrow the events scan; event-property filters and the semantic kinds are
@@ -665,6 +728,9 @@ def _build_labeled_users_cte(
having_parts.extend(compiled_kind.anchor_having_parts)
anchor_having = f"\n HAVING {' AND '.join(having_parts)}" if having_parts else ""
+ # A sampled population labels into labeled_population, and labeled_users keeps the sample of it.
+ labeled_cte = "labeled_population" if negative_sample_rate < 1.0 else "labeled_users"
+
# ifNull on the label: a property-filtered action predicate is NULL on rows that lack
# the property, and a user whose every in-horizon row is NULL must label 0, not NULL.
# T0 sits at a fixed fraction (hash / 2^31) of the user's [first_ts, cutoff_ts) span. A
@@ -699,7 +765,7 @@ def _build_labeled_users_cte(
AS t0_ts
FROM user_window
),
- labeled_users AS (
+ {labeled_cte} AS (
SELECT
u.person_id AS person_id,
u.t0_ts AS t0_ts,
@@ -724,6 +790,15 @@ def _build_labeled_users_cte(
}
if anchor_ts is not None:
values["anchor_ts"] = anchor_ts
+ if negative_sample_rate < 1.0:
+ values["negative_sample_threshold"] = negative_sample_threshold(negative_sample_rate)
+ cte += f""" ,
+ labeled_users AS (
+ SELECT person_id, t0_ts, positive
+ FROM labeled_population
+ WHERE positive = 1 OR {_SAMPLE_HASH} < {{negative_sample_threshold}}
+ )
+ """
return cte, values
@@ -737,6 +812,7 @@ def build_random_t0_labeler_sql(
target_definition: dict[str, Any] | None = None,
team: "Team | None" = None,
anchor_ts: int | None = None,
+ negative_sample_rate: float = 1.0,
) -> tuple[str, dict[str, Any]]:
"""
Build a HogQL query that returns one row of (eligible, positives) for a
@@ -748,6 +824,8 @@ def build_random_t0_labeler_sql(
With sample_limit=None this gives the trainer's actual eligible count;
with sample_limit=N it gives an unbiased estimator computed over N users.
+ With a ``negative_sample_rate`` it counts the case-control sample the trainer
+ materializes at that rate.
"""
cte, values = _build_labeled_users_cte(
target_event=target_event,
@@ -758,6 +836,7 @@ def build_random_t0_labeler_sql(
training_population=training_population,
sample_limit=sample_limit,
anchor_ts=anchor_ts,
+ negative_sample_rate=negative_sample_rate,
)
sql = f"""
{cte}
@@ -1003,6 +1082,7 @@ def build_training_features_sql(
target_definition: dict[str, Any] | None = None,
team: "Team | None" = None,
anchor_ts: int | None = None,
+ negative_sample_rate: float = 1.0,
) -> tuple[str, dict[str, Any]]:
"""
Build the composite training-time query:
@@ -1012,7 +1092,8 @@ def build_training_features_sql(
Caller substitutes {lookback_days} in feature_sql before calling. Returns
one row per eligible user with the agent's feature columns plus __label
- and __fold for the train/holdout split.
+ and __fold for the train/holdout split. A ``negative_sample_rate`` below 1
+ restricts the rows to the case-control sample (see ``TrainingSample``).
"""
cte, values = _build_labeled_users_cte(
target_event=target_event,
@@ -1023,6 +1104,7 @@ def build_training_features_sql(
training_population=training_population,
sample_limit=None,
anchor_ts=anchor_ts,
+ negative_sample_rate=negative_sample_rate,
)
anchors_subquery = "(SELECT person_id, t0_ts AS cutoff_ts FROM labeled_anchors)"
substituted_feature_sql = _substitute_anchors(feature_sql, anchors_subquery)
diff --git a/products/autoresearch/backend/dataset/test_labeling.py b/products/autoresearch/backend/dataset/test_labeling.py
index 6cab0a54f643..9be64b6243fd 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,
+ TrainingSample,
+ TrainingSampleTooLarge,
_build_labeled_users_cte,
_build_population_kind_conditions,
_compile_population_filters,
@@ -30,6 +32,7 @@ from products.autoresearch.backend.dataset.labeling import (
build_inference_anchors_sql,
build_inference_features_sql,
build_random_t0_labeler_sql,
+ build_training_features_sql,
strip_sql_comments,
)
from products.autoresearch.backend.query import run_hogql_rows
@@ -451,6 +454,26 @@ class TestPopulationKindTrainingSemantics(SimpleTestCase):
_DAILY_PAGEVIEWS = [("$pageview", days_ago) for days_ago in range(100, 0, -1)]
+class TestTrainingSamplePlan(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("fits_the_budget", 40, 4, 1.0, 40),
+ ("all_positives", 100, 100, 1.0, 100),
+ ("above_the_budget", 1_000, 100, 0.1, 190),
+ ]
+ )
+ def test_plan_keeps_every_positive_and_fills_the_budget_with_negatives(
+ self, _name: str, population: int, positives: int, rate: float, size: int
+ ) -> None:
+ sample = TrainingSample.plan(population=population, positives=positives, budget=190)
+ assert sample.negative_sample_rate == rate
+ assert sample.expected_size == size
+
+ def test_plan_refuses_positives_that_alone_exceed_the_budget(self) -> None:
+ with self.assertRaises(TrainingSampleTooLarge):
+ TrainingSample.plan(population=1_000, positives=200, budget=190)
+
+
class TestAnchoredPopulationsAgainstClickhouse(ClickhouseTestMixin, APIBaseTest):
# Executes the labeler for each population shape so the per-user-at-T0 HAVING
# predicates are proven to resolve against the events scan, not only to print.
@@ -565,6 +588,52 @@ class TestAnchoredPopulationsAgainstClickhouse(ClickhouseTestMixin, APIBaseTest)
if expected_positives is not None:
assert int(rows[0][1]) == expected_positives
+ def test_negative_sampling_keeps_every_positive_and_the_training_rows_match_the_count(self) -> None:
+ now = timezone.now() # nosemgrep: test-datetime-now-without-freeze (must match ClickHouse server-side now())
+ positives = [f"positive_{i}" for i in range(3)]
+ negatives = [f"negative_{i}" for i in range(40)]
+ for distinct_id in positives + negatives:
+ _create_person(team_id=self.team.pk, distinct_ids=[distinct_id], is_identified=True)
+ for event, days_ago in _DAILY_PAGEVIEWS:
+ _create_event(
+ team=self.team, event=event, distinct_id=distinct_id, timestamp=now - timedelta(days=days_ago)
+ )
+ if distinct_id in positives:
+ _create_event(
+ team=self.team,
+ event="feature_used",
+ distinct_id=distinct_id,
+ timestamp=now - timedelta(days=days_ago),
+ )
+ flush_persons_and_events()
+ common: dict[str, Any] = {
+ "target_event": "feature_used",
+ "horizon_days": 7,
+ "lookback_days": 120,
+ "training_population": None,
+ "team": self.team,
+ "negative_sample_rate": 0.25,
+ }
+
+ def run(sql: str, values: dict[str, Any]) -> list[Any]:
+ return run_hogql_rows(
+ team=self.team,
+ query=HogQLQuery(query=sql, values=values, modifiers=LABELER_QUERY_MODIFIERS),
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
+ )
+
+ [[eligible, sampled_positives]] = run(*build_random_t0_labeler_sql(**common))
+ rows = run(
+ *build_training_features_sql(
+ feature_sql="SELECT a.person_id AS distinct_id, 1 AS one FROM {anchors} a", **common
+ )
+ )
+ assert sampled_positives == len(positives)
+ assert len(positives) < eligible < len(positives) + len(negatives)
+ # Columns: distinct_id, one, __label, __fold.
+ assert len(rows) == eligible
+ assert sum(row[2] for row in rows) == len(positives)
+
@parameterized.expand(
[
("any_event_population", None),
diff --git a/products/autoresearch/backend/dataset/test_validation.py b/products/autoresearch/backend/dataset/test_validation.py
index a2a5ebcca70c..3a501eb42504 100644
--- a/products/autoresearch/backend/dataset/test_validation.py
+++ b/products/autoresearch/backend/dataset/test_validation.py
@@ -15,14 +15,16 @@ from products.autoresearch.backend.dataset.validation import (
)
-def _mock_rows(positives: int, total: int, identified: int | None = None) -> list[list[list[int]]]:
+def _mock_rows(
+ positives: int, total: int, identified: int | None = None, inference: int | None = None
+) -> list[list[list[int]]]:
# Query order: eligible count, sampled labeler, inference count. Sample size
# equals total so the extrapolated positives line up with the input.
eligible_identified = total if identified is None else identified
return [
[[eligible_identified, total]],
[[eligible_identified, positives]],
- [[eligible_identified]],
+ [[eligible_identified if inference is None else inference]],
]
@@ -34,9 +36,10 @@ class TestValidationWarnings(BaseTest):
horizon_days: int = 7,
training_lookback_days: int = 180,
identified: int | None = None,
+ inference: int | None = None,
) -> ValidationResult:
with patch("products.autoresearch.backend.dataset.validation.run_hogql_rows") as mock_run:
- mock_run.side_effect = _mock_rows(positives, total, identified=identified)
+ mock_run.side_effect = _mock_rows(positives, total, identified=identified, inference=inference)
return _run_validation(
team=self.team,
target_event="$pageview",
@@ -59,7 +62,6 @@ class TestValidationWarnings(BaseTest):
("zero_users", 0, 0, "low_volume"),
("low_positives", 5, 1000, "low_positives"),
("low_negatives", 995, 1000, "low_negatives"),
- ("population_too_large", 5_000, 50_000, "population_too_large"),
]
)
def test_hard_errors_block_proceeding(self, _name: str, positives: int, total: int, code: str) -> None:
@@ -68,6 +70,21 @@ class TestValidationWarnings(BaseTest):
assert code in codes
assert result.can_proceed is False
+ @parameterized.expand(
+ [
+ ("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(
+ self, _name: str, positives: int, total: int, inference: int, severity: str, can_proceed: bool
+ ) -> None:
+ result = self._run(positives=positives, total=total, inference=inference)
+ [warning] = [w for w in result.warnings if w.code == "population_too_large"]
+ assert warning.severity == severity
+ assert result.can_proceed is can_proceed
+
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 1f108d81988e..5a3c4e74777e 100644
--- a/products/autoresearch/backend/dataset/validation.py
+++ b/products/autoresearch/backend/dataset/validation.py
@@ -25,6 +25,8 @@ from products.autoresearch.backend.dataset.labeling import (
IDENTIFIED_USERS_ONLY,
LABELER_QUERY_MODIFIERS,
MATERIALIZE_ROW_LIMIT,
+ TrainingSample,
+ TrainingSampleTooLarge,
build_eligible_count_sql,
build_inference_anchors_sql,
build_random_t0_labeler_sql,
@@ -377,15 +379,38 @@ def _build_warnings(
)
)
- largest = max(total_users, inference_size)
- if largest >= MATERIALIZE_ROW_LIMIT:
+ training_size = _training_size_warning(total_users=total_users, positives=positives)
+ if training_size is not None:
+ warnings.append(training_size)
+
+ if inference_size >= MATERIALIZE_ROW_LIMIT:
warnings.append(
ValidationWarning(
code=ValidationWarningCode.POPULATION_TOO_LARGE,
- message=f"This population has {largest} users. One run trains or scores at most "
+ message=f"The scoring population has {inference_size} users. One run scores at most "
f"{MATERIALIZE_ROW_LIMIT} users. Narrow the population.",
severity="error",
)
)
return warnings
+
+
+def _training_size_warning(*, total_users: int, positives: int) -> ValidationWarning | None:
+ """
+ Training samples a population above its budget, so a large population is advice, not a
+ refusal. Only positives that alone exceed the budget stop a run, because every positive is kept.
+ """
+ try:
+ sample = TrainingSample.plan(population=total_users, positives=min(positives, total_users))
+ except TrainingSampleTooLarge as exc:
+ return ValidationWarning(code=ValidationWarningCode.POPULATION_TOO_LARGE, message=str(exc), severity="error")
+ if sample.negative_sample_rate == 1.0:
+ return None
+ return ValidationWarning(
+ code=ValidationWarningCode.POPULATION_TOO_LARGE,
+ message=f"This population has {total_users} users, so training uses a sample of about "
+ f"{sample.expected_size}. The sample keeps every user who performed the target and "
+ f"{sample.negative_sample_rate:.1%} of the others. Predictions are corrected for the sample.",
+ severity="info",
+ )
diff --git a/products/autoresearch/backend/inference/AGENTS.md b/products/autoresearch/backend/inference/AGENTS.md
index 83d2c3978e1e..86616042791c 100644
--- a/products/autoresearch/backend/inference/AGENTS.md
+++ b/products/autoresearch/backend/inference/AGENTS.md
@@ -27,7 +27,7 @@ The cardinal rule: **inference never refits a persisted model.** A bundle is fit
A recipe-only champion routes on its recipe: a stub recipe (`stub: true`, SQL evaluated at `now()`) scores by the fixed engagement formula, with the inference population applied inside its query so the row bound measures the population and not the team, and its rows checked against the population count; an agent recipe goes through `validate_runnable_feature_sql()` like a bundle (so a trailing `LIMIT` or an `{anchors}` that sits only in a comment fails the run rather than running without a cutoff) and then fits on the anchored training rows and predicts on the inference anchors. Neither can be backfilled: the fit happens at scoring time on labels decided as of `now()`, so a fit for a past date would learn from outcomes after it. Only a bundle, whose `model.pkl` already exists, is re-scored in the past. The recipe fit validates its training rows the way the sandbox does (one row per person, every row labeled, at most `_MAX_FEATURE_COLS` numeric columns, no duplicate column names), sorts them by person before fitting, because an estimator that samples row indices fits a different model on a different row order despite its seed, seeds a stochastic estimator from the pipeline id unless the recipe sets `random_state`, so a retry refits the same model under the same event UUIDs, and pins `n_jobs=1`, because the fit runs in the worker process. Its probabilities keep full precision, as the bundle path's do.
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()`), because feature SQL that inner joins or filters a joined table in `WHERE` drops people without any row looking wrong.
+ 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.
`_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.
## The emitted event
@@ -35,9 +35,13 @@ The cardinal rule: **inference never refits a persisted model.** A bundle is fit
```text
event: autoresearch_prediction
distinct_id: <person distinct_id>
-properties: $autoresearch_pipeline_id, $autoresearch_p_y, ...
+properties: $autoresearch_pipeline_id, $autoresearch_p_y, $autoresearch_p_y_raw,
+ $autoresearch_negative_sample_rate, ...
```
+**Scores are prior-corrected once, in `score_population()`.** A model fitted on a case-control sample (see `../dataset/AGENTS.md`) overstates the odds by `1 / r`, so `corrected_probability()` applies `logit(p) + log(r)`. `$autoresearch_p_y` and the output person property carry the corrected value, `$autoresearch_p_y_raw` the model's own score, and the run records `r` in `AutoresearchRun.negative_sample_rate`.
+A bundle's `r` is `AutoresearchModel.negative_sample_rate`, which `fit_champion_model()` saves before it writes `model.pkl`. A recipe-only champion measures its sample at each fit and uses that rate. The stub formula never saw a sample, so its `r` is 1.0. Never correct in a scoring route; a second correction would shrink every probability again.
+
One event per scored person per run, sent as one `capture_batch_internal()` batch. This is the product's actual output — the person property on the pipeline (`output_person_property`, e.g. `predicted_p_downloaded_file_30d`) is derived from these.
Any event the batch does not accept, or accepts with a warning (capture stores the event but has switched something off, such as person processing for a rate-limited distinct id, so the `$set` never lands), fails the run: the event UUIDs are deterministic per (pipeline, model, date, person), so the retry re-sends every row and ingestion keeps one copy, whereas completing with a partial batch would advance the cadence past the people who never received their prediction.
Right before the batch goes out the run re-reads the model's role and fails if promotion has replaced the champion meanwhile, so a superseded model does not write its `$set` over the new champion's. The window between that read and capture is what remains of the race.
diff --git a/products/autoresearch/backend/inference/sandbox.py b/products/autoresearch/backend/inference/sandbox.py
index 185911e5f11a..2911b8471240 100644
--- a/products/autoresearch/backend/inference/sandbox.py
+++ b/products/autoresearch/backend/inference/sandbox.py
@@ -66,6 +66,8 @@ from posthog.models.user import User
from products.autoresearch.backend.dataset.labeling import (
LABELER_QUERY_MODIFIERS,
MATERIALIZE_ROW_LIMIT,
+ TrainingSample,
+ TrainingSampleTooLarge,
build_inference_anchors_sql,
build_inference_features_sql,
build_random_t0_labeler_sql,
@@ -153,6 +155,8 @@ class MaterializedData:
feature_cols: list[str]
train_rows: list[dict[str, Any]] = field(default_factory=list)
holdout_rows: list[dict[str, Any]] = field(default_factory=list)
+ # The rate the rows were drawn at; the fitted model's scores need its prior correction.
+ negative_sample_rate: float = 1.0
@frozen
@@ -174,12 +178,15 @@ def fit_champion_model(
bundle: ArtifactBundle | None = None,
user: User | None = None,
anchor_ts: int | None = None,
+ model_id: str | None = None,
) -> dict[str, Any]:
"""
Train run: fit the champion against the LABELED training population and persist
the resulting ``model.pkl`` under ``prefix``. Idempotent: it overwrites any prior fit.
Pass the training run's ``anchor_ts`` so the fit sees the anchor set the agent scored.
+ The fit's negative sample rate is saved on the ``model_id`` row before ``model.pkl`` is
+ written, so no scoring run can load the model without the rate its correction needs.
``predict.py`` runs once against the holdout features before the model is persisted,
so a bundle whose two scripts disagree fails here rather than on the first cadence.
@@ -204,6 +211,11 @@ def fit_champion_model(
raise SandboxInferenceError("No numeric feature columns produced by feature SQL")
model_bytes, metrics = _run_train_in_sandbox(bundle=bundle, data=data, pipeline=pipeline)
+ metrics = {**metrics, "negative_sample_rate": data.negative_sample_rate}
+ if model_id is not None:
+ AutoresearchModel.objects.for_team(team.pk).filter(pk=model_id).update(
+ negative_sample_rate=data.negative_sample_rate
+ )
write_model(prefix, model_bytes)
write_artifact(prefix, _FEATURE_COLUMNS_JSON, json.dumps(data.feature_cols).encode("utf-8"))
logger.info(
@@ -212,6 +224,7 @@ def fit_champion_model(
prefix=prefix,
model_bytes=len(model_bytes),
holdout_auc=metrics.get("holdout_auc"),
+ negative_sample_rate=data.negative_sample_rate,
)
return metrics
@@ -363,9 +376,12 @@ def materialize_training_data(
anchors (per-user random T0, with __label + __fold). Splits train/holdout by fold
so the bundle never sees __fold. The labeler window is the pipeline's configured
training_lookback_days, ending at ``anchor_ts`` (default: now).
+ training_lookback_days, ending at ``anchor_ts`` (default: now). A population above the training budget is case-control sampled
+ (see ``TrainingSample``), and the rows are checked against the sampled anchor count.
"""
if anchor_ts is None:
anchor_ts = int(django_timezone.now().timestamp())
+ sample = measure_training_sample(team=team, pipeline=pipeline, anchor_ts=anchor_ts, user=user)
feature_sql_resolved = feature_sql.replace("{lookback_days}", str(_feature_lookback_days(pipeline)))
train_sql, train_values = build_training_features_sql(
feature_sql=feature_sql_resolved,
@@ -376,9 +392,12 @@ def materialize_training_data(
lookback_days=pipeline.training_lookback_days,
training_population=pipeline.training_population,
anchor_ts=anchor_ts,
+ negative_sample_rate=sample.negative_sample_rate,
)
training_rows = _materialize_rows(team=team, sql=train_sql, values=train_values, user=user)
- expected = count_training_anchors(team=team, pipeline=pipeline, anchor_ts=anchor_ts, user=user)
+ expected = count_training_anchors(
+ team=team, pipeline=pipeline, anchor_ts=anchor_ts, user=user, negative_sample_rate=sample.negative_sample_rate
+ )
_validate_rows_key_one_person(training_rows, source="training feature_sql", expected_count=expected)
# The training wrapper LEFT JOINs the labels onto the feature rows. A feature row
# whose distinct_id matched no anchor comes back with NULL label and fold, and the
@@ -397,8 +416,14 @@ def materialize_training_data(
n_train=len(train_rows),
n_holdout=len(holdout_rows),
n_features=len(feature_cols),
+ negative_sample_rate=sample.negative_sample_rate,
+ )
+ return MaterializedData(
+ feature_cols=feature_cols,
+ train_rows=train_rows,
+ holdout_rows=holdout_rows,
+ negative_sample_rate=sample.negative_sample_rate,
)
- return MaterializedData(feature_cols=feature_cols, train_rows=train_rows, holdout_rows=holdout_rows)
def _materialize_score_data(
@@ -434,15 +459,26 @@ def _materialize_score_data(
return score_rows
-def count_training_anchors(
- *, team: Team, pipeline: AutoresearchPipeline, anchor_ts: int, user: User | None = None
-) -> int:
+def measure_training_sample(
+ *, team: Team, pipeline: AutoresearchPipeline, anchor_ts: int | None = None, user: User | None = None
+) -> TrainingSample:
"""
- How many labeled anchors the trainer materializes, so feature SQL that drops some of them
- fails: a selection-biased fit and a distorted holdout AUC look valid row by row. Pass the
- ``anchor_ts`` the feature query bound, or the two counts can differ at a window edge.
+ Count the whole labeled population and its positives, and choose the negative sample rate
+ that fits it under the training budget. The counts are aggregates, so no row cap applies.
"""
- sql, values = build_random_t0_labeler_sql(
+ sql, values = _labeler_sql(team=team, pipeline=pipeline, anchor_ts=anchor_ts)
+ row = _count_rows(team=team, sql=sql, values=values, user=user, what="Training population")
+ population, positives = int(row[0] or 0), int(row[1] or 0)
+ try:
+ return TrainingSample.plan(population=population, positives=positives)
+ except TrainingSampleTooLarge as exc:
+ raise SandboxInferenceError(str(exc)) from exc
+
+
+def _labeler_sql(
+ *, team: Team, pipeline: AutoresearchPipeline, anchor_ts: int | None = None, negative_sample_rate: float = 1.0
+) -> tuple[str, dict[str, Any]]:
+ return build_random_t0_labeler_sql(
target_event=pipeline.target_event,
target_definition=pipeline.target_definition,
team=team,
@@ -451,6 +487,25 @@ def count_training_anchors(
training_population=pipeline.training_population,
sample_limit=None,
anchor_ts=anchor_ts,
+ negative_sample_rate=negative_sample_rate,
+ )
+
+
+def count_training_anchors(
+ *,
+ team: Team,
+ pipeline: AutoresearchPipeline,
+ anchor_ts: int | None = None,
+ user: User | None = None,
+ negative_sample_rate: float = 1.0,
+) -> int:
+ """
+ How many labeled anchors the trainer materializes at ``negative_sample_rate``, so feature SQL
+ that drops some of them fails: a selection-biased fit and a distorted holdout AUC look valid
+ row by row. Pass the rate and anchor time the training rows used, or the counts cannot agree.
+ """
+ sql, values = _labeler_sql(
+ team=team, pipeline=pipeline, anchor_ts=anchor_ts, negative_sample_rate=negative_sample_rate
)
return _count(team=team, sql=sql, values=values, user=user, what="Training anchor count")
@@ -478,6 +533,11 @@ def count_inference_anchors(
def _count(*, team: Team, sql: str, values: dict[str, Any], user: User | None, what: str) -> int:
"""Run a query whose first column of its first row is the count the caller wants."""
+ return int(_count_rows(team=team, sql=sql, values=values, user=user, what=what)[0])
+
+
+def _count_rows(*, team: Team, sql: str, values: dict[str, Any], user: User | None, what: str) -> list[Any]:
+ """Run a query that returns one aggregate row, and return that row."""
try:
tag_queries(product=Product.AUTORESEARCH, feature=Feature.QUERY)
result = run_hogql(
@@ -490,7 +550,7 @@ def _count(*, team: Team, sql: str, values: dict[str, Any], user: User | None, w
raise SandboxInferenceError(f"{what} query failed: {exc}") from exc
if len(result.rows) != 1 or not result.rows[0]:
raise SandboxInferenceError(f"{what} query did not return a single row")
- return int(result.rows[0][0])
+ return list(result.rows[0])
def _validate_rows_key_one_person(
diff --git a/products/autoresearch/backend/inference/scoring.py b/products/autoresearch/backend/inference/scoring.py
index 989d94cc38ee..0fec1ceed245 100644
--- a/products/autoresearch/backend/inference/scoring.py
+++ b/products/autoresearch/backend/inference/scoring.py
@@ -17,7 +17,9 @@ Event shape:
$autoresearch_model_role: "champion" | "challenger"
$autoresearch_target_event: str
$autoresearch_horizon_days: int
- $autoresearch_p_y: float (the score)
+ $autoresearch_p_y: float (the score, prior-corrected for negative sampling)
+ $autoresearch_p_y_raw: float (the model's score before the correction)
+ $autoresearch_negative_sample_rate: float (the rate the correction used; 1.0 means none)
$autoresearch_prediction_date: str (YYYY-MM-DD)
$autoresearch_features_hash: str (SHA-256 prefix of the feature row)
$autoresearch_person_id: str (the person_id every row is keyed on)
@@ -67,6 +69,7 @@ from products.autoresearch.backend.inference.sandbox import (
_resolve_acting_user,
count_inference_anchors,
count_training_anchors,
+ measure_training_sample,
score_via_sandbox,
validate_runnable_feature_sql,
)
@@ -88,6 +91,8 @@ class InferenceRunError(Exception):
_RESERVED_COLS = frozenset({"distinct_id", _LABEL_COL, _FOLD_COL})
+# The score columns scoring adds to a feature row, kept out of the features hash.
+_SCORE_KEYS = frozenset({"p_y", "p_y_raw"})
# Namespace for deterministic prediction event UUIDs, so a retried scoring activity
@@ -115,6 +120,27 @@ class ScoredPopulation:
# The holdout AUC the serving model advertises: computed on the fly for a recipe-only
# champion, read from the model row for a bundle.
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
+
+
+def corrected_probability(p: float, negative_sample_rate: float) -> float:
+ """
+ The prior correction for case-control sampling, ``sigmoid(logit(p) + log(r))``.
+
+ Kept negatives at rate ``r`` inflate the training odds by ``1 / r``, so the model's raw
+ score overstates the probability. This closed form needs no logit, so 0 and 1 stay exact.
+ """
+ if negative_sample_rate == 1.0:
+ return p
+ return p * negative_sample_rate / (p * negative_sample_rate + (1.0 - p))
+
+
+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)
@frozen
@@ -203,6 +229,7 @@ def run_inference_for_pipeline(
run.status = AutoresearchRun.Status.COMPLETED
run.rows_scored = emitted.rows_emitted
+ run.negative_sample_rate = scored.negative_sample_rate
run.metrics.update(
{
"score_distribution": emitted.score_distribution,
@@ -212,7 +239,7 @@ def run_inference_for_pipeline(
}
)
run.completed_at = django_timezone.now()
- run.save(update_fields=["status", "rows_scored", "metrics", "completed_at"])
+ run.save(update_fields=["status", "rows_scored", "negative_sample_rate", "metrics", "completed_at"])
# Only a live run moves the cadence watermark. Backfilling a past date must not
# make the coordinator think today's scoring already happened.
@@ -300,14 +327,32 @@ def score_population(
The prediction-date guards run here rather than in the emitting caller, so the dry run
refuses exactly the dates the live run refuses.
+
+ Every route returns its raw scores, and the prior correction for the model's negative
+ sample rate is applied here, once, so no route can correct twice or not at all.
"""
+ return _apply_prior_correction(
+ _score_population_raw(team=team, pipeline=pipeline, model=model, window=window, user=user)
+ )
+
+
+def _score_population_raw(
+ *,
+ team: Team,
+ pipeline: AutoresearchPipeline,
+ model: AutoresearchModel,
+ window: ScoringWindow,
+ user: User | None = None,
+) -> ScoredPopulation:
_check_prediction_date(team=team, pipeline=pipeline, window=window)
acting_user = _acting_user(team=team, pipeline=pipeline, user=user)
cutoff_ts = window.cutoff_ts
if model.artifact_prefix:
result = score_via_sandbox(team=team, pipeline=pipeline, model=model, cutoff_ts=cutoff_ts, user=acting_user)
- return ScoredPopulation(rows=result.scored_rows, holdout_auc=result.holdout_auc)
+ return ScoredPopulation(
+ rows=result.scored_rows, holdout_auc=result.holdout_auc, negative_sample_rate=model.negative_sample_rate
+ )
if window.is_backfill:
# A recipe-only champion fits at scoring time, and its training labels are decided as of
@@ -376,7 +421,7 @@ def _emit_predictions(
# Feature values can be datetimes, Decimals, or UUIDs the model ignored; default=str
# keeps the hash stable for them instead of failing the whole batch.
features_hash = hashlib.sha256(
- json.dumps({k: v for k, v in row.items() if k != "p_y"}, sort_keys=True, default=str).encode()
+ json.dumps({k: v for k, v in row.items() if k not in _SCORE_KEYS}, sort_keys=True, default=str).encode()
).hexdigest()[:16]
props: dict[str, Any] = {
"$autoresearch_pipeline_id": str(pipeline.pk),
@@ -385,6 +430,8 @@ def _emit_predictions(
"$autoresearch_target_event": pipeline.target_event,
"$autoresearch_horizon_days": pipeline.horizon_days,
"$autoresearch_p_y": row["p_y"],
+ "$autoresearch_p_y_raw": row["p_y_raw"],
+ "$autoresearch_negative_sample_rate": scored.negative_sample_rate,
"$autoresearch_prediction_date": prediction_date_str,
"$autoresearch_features_hash": features_hash,
"$autoresearch_person_id": person_id,
@@ -665,7 +712,9 @@ def _score_via_anchors(
predictions instead of nothing.
"""
feature_sql = str(recipe.get("feature_sql") or "").replace("{lookback_days}", str(_feature_lookback_days(pipeline)))
- training_rows = _fetch_training_rows(team=team, pipeline=pipeline, feature_sql=feature_sql, user=user)
+ training_rows, negative_sample_rate = _fetch_training_rows(
+ team=team, pipeline=pipeline, feature_sql=feature_sql, user=user
+ )
inference_rows = _fetch_inference_rows(
team=team, pipeline=pipeline, feature_sql=feature_sql, cutoff_ts=cutoff_ts, user=user
)
@@ -676,15 +725,26 @@ def _score_via_anchors(
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(
- training_rows=training_rows, inference_rows=inference_rows, recipe=recipe, pipeline_id=str(pipeline.pk)
+ training_rows=training_rows,
+ inference_rows=inference_rows,
+ recipe=recipe,
+ pipeline_id=str(pipeline.pk),
+ negative_sample_rate=negative_sample_rate,
)
def _fetch_training_rows(
*, team: Team, pipeline: AutoresearchPipeline, feature_sql: str, user: User
-) -> list[dict[str, Any]]:
- """The recipe's feature SQL against the labeled anchors: one row per person with ``__label`` and ``__fold``."""
+) -> tuple[list[dict[str, Any]], float]:
+ """
+ The recipe's feature SQL against the labeled anchors: one row per person with ``__label``
+ and ``__fold``, and the negative sample rate the rows were drawn at.
+ """
anchor_ts = int(django_timezone.now().timestamp())
+ try:
+ sample = measure_training_sample(team=team, pipeline=pipeline, anchor_ts=anchor_ts, user=user)
+ except SandboxInferenceError as exc:
+ raise InferenceRunError(str(exc)) from exc
sql, values = build_training_features_sql(
feature_sql=feature_sql,
target_event=pipeline.target_event,
@@ -694,10 +754,17 @@ def _fetch_training_rows(
lookback_days=pipeline.training_lookback_days,
training_population=pipeline.training_population,
anchor_ts=anchor_ts,
+ negative_sample_rate=sample.negative_sample_rate,
)
rows = _person_rows(_query(team=team, sql=sql, values=values, user=user, what="Training features"))
try:
- expected = count_training_anchors(team=team, pipeline=pipeline, anchor_ts=anchor_ts, user=user)
+ expected = count_training_anchors(
+ team=team,
+ pipeline=pipeline,
+ anchor_ts=anchor_ts,
+ user=user,
+ negative_sample_rate=sample.negative_sample_rate,
+ )
except SandboxInferenceError as exc:
raise InferenceRunError(str(exc)) from exc
_require_one_row_per_person(rows, source="training feature_sql", expected_count=expected)
@@ -708,7 +775,7 @@ def _fetch_training_rows(
raise InferenceRunError(
f"{unlabeled} training feature row(s) matched no labeled anchor; distinct_id must be the anchor person_id"
)
- return rows
+ return rows, sample.negative_sample_rate
def _fetch_inference_rows(
@@ -745,11 +812,13 @@ def _fit_on_training_predict_on_inference(
inference_rows: list[dict[str, Any]],
recipe: dict[str, Any],
pipeline_id: str,
+ negative_sample_rate: float = 1.0,
) -> ScoredPopulation:
"""
Fit the recipe's allowlisted sklearn class on the training folds, score the holdout
fold for the AUC the run records, and predict on the inference rows. A fit or predict
- failure falls back to the stub formula so the cadence still emits.
+ failure falls back to the stub formula so the cadence still emits. Only the fitted
+ scores carry ``negative_sample_rate``; the stub formula never saw the sample.
"""
# Feature SQL without an ORDER BY returns rows in any order, and an estimator that
# samples row indices fits a different model on a different order despite its seed.
@@ -809,7 +878,7 @@ def _fit_on_training_predict_on_inference(
# Full precision, as _join_scores keeps for a bundle: rounding would tie predictions that
# online validation ranks against each other.
scored = [{**row, "p_y": float(p)} for row, p in zip(inference_rows, proba)]
- return ScoredPopulation(rows=scored, holdout_auc=holdout_auc)
+ return ScoredPopulation(rows=scored, holdout_auc=holdout_auc, negative_sample_rate=negative_sample_rate)
def _stable_seed(pipeline_id: str) -> int:
diff --git a/products/autoresearch/backend/inference/test_inference.py b/products/autoresearch/backend/inference/test_inference.py
index 201582b88fc4..2ec96cc96a33 100644
--- a/products/autoresearch/backend/inference/test_inference.py
+++ b/products/autoresearch/backend/inference/test_inference.py
@@ -156,6 +156,33 @@ class TestRunInferencePipeline(TeamScopedTestMixin, BaseTest):
pipeline.refresh_from_db()
assert pipeline.last_scored_at is not None
+ def test_a_sampled_model_emits_prior_corrected_scores_with_the_raw_score_and_rate(self):
+ pipeline, model = self._make_pipeline_and_model()
+ model.artifact_prefix = "tasks/autoresearch/team_1/pipeline_x/run_y"
+ model.negative_sample_rate = 0.25
+ model.save(update_fields=["artifact_prefix", "negative_sample_rate"])
+ sandbox_result = SandboxScoreResult(
+ scored_rows=[{"distinct_id": "user-1", "events_total": 3, "p_y": 0.5}],
+ holdout_auc=0.7,
+ n_train=10,
+ n_features=1,
+ )
+ capture = _capture_accepting_everything()
+ with (
+ patch.object(scoring, "score_via_sandbox", return_value=sandbox_result),
+ patch.object(scoring, "_resolve_distinct_ids", return_value={"user-1": "real-distinct-id"}),
+ patch.object(scoring, "capture_batch_internal", capture),
+ ):
+ run = run_inference_for_pipeline(pipeline=pipeline, model=model)
+
+ props = capture.call_args.kwargs["events"][0]["properties"]
+ assert props["$autoresearch_p_y"] == 0.2
+ assert props["$autoresearch_p_y_raw"] == 0.5
+ assert props["$autoresearch_negative_sample_rate"] == 0.25
+ assert props["$set"] == {"predicted_p_pageview": 0.2}
+ run.refresh_from_db()
+ assert run.negative_sample_rate == 0.25
+
def test_run_inference_zero_rows_completes_without_emitting(self):
pipeline, model = self._make_pipeline_and_model()
capture = _capture_accepting_everything()
@@ -386,7 +413,7 @@ class TestRecipeRouting(TeamScopedTestMixin, BaseTest):
result = score_population(
team=self.team, pipeline=pipeline, model=model, window=ScoringWindow.for_date(), user=self.user
)
- assert result == scored
+ assert result == ScoredPopulation(rows=[{"distinct_id": "p1", "p_y": 0.5, "p_y_raw": 0.5}], holdout_auc=0.66)
anchored.assert_called_once()
@parameterized.expand([("bundle", "score_via_sandbox"), ("recipe", "_score_via_anchors")])
@@ -431,7 +458,7 @@ class TestRecipeRouting(TeamScopedTestMixin, BaseTest):
{"distinct_id": "quiet", "events_total": 1, "plan": None},
]
with (
- patch.object(scoring, "_fetch_training_rows", return_value=training_rows),
+ 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, "_resolve_distinct_ids", return_value={}),
patch.object(scoring, "capture_batch_internal", _capture_accepting_everything()),
@@ -700,7 +727,9 @@ class TestAnchorsRecipeQueries(TeamScopedTestMixin, BaseTest):
with (
patch.object(scoring, "run_hogql", return_value=HogQLResult(columns=[], rows=[])) as features_run,
patch.object(
- sandbox_inference, "run_hogql", return_value=HogQLResult(columns=["eligible"], rows=[[0]])
+ sandbox_inference,
+ "run_hogql",
+ return_value=HogQLResult(columns=["eligible", "positives"], rows=[[0, 0]]),
) as count_run,
):
_fetch_training_rows(team=self.team, pipeline=pipeline, feature_sql=_ANCHORS_FEATURE_SQL, user=self.user)
diff --git a/products/autoresearch/backend/inference/test_sandbox_inference.py b/products/autoresearch/backend/inference/test_sandbox_inference.py
index ae658af1eb1c..049482d1b4f0 100644
--- a/products/autoresearch/backend/inference/test_sandbox_inference.py
+++ b/products/autoresearch/backend/inference/test_sandbox_inference.py
@@ -148,6 +148,7 @@ class TestMaterializeData(TeamScopedTestMixin, BaseTest):
sandbox_inference,
"run_hogql",
side_effect=[
+ HogQLResult(columns=["eligible", "positives"], rows=[[len(_TRAINING_ROWS), 2]]),
HogQLResult(columns=list(_TRAINING_ROWS[0]), rows=[list(r.values()) for r in _TRAINING_ROWS]),
HogQLResult(columns=["eligible", "positives"], rows=[[len(_TRAINING_ROWS), 2]]),
],
@@ -155,10 +156,9 @@ class TestMaterializeData(TeamScopedTestMixin, BaseTest):
):
data = materialize_training_data(team=self.team, pipeline=pipeline, feature_sql="SELECT 1 FROM {anchors}")
- # Each query would read its own now(), so a person at a window edge could be in one and not the other.
- features_query, count_query = (c.kwargs["query"] for c in run_hogql.call_args_list)
- assert "now()" not in features_query.query and "now()" not in count_query.query
- assert features_query.values["anchor_ts"] == count_query.values["anchor_ts"]
+ sample_query, features_query, count_query = (call.kwargs["query"] for call in run_hogql.call_args_list)
+ assert all("now()" not in query.query for query in (sample_query, features_query, count_query))
+ assert sample_query.values["anchor_ts"] == features_query.values["anchor_ts"] == count_query.values["anchor_ts"]
assert data.feature_cols == ["events_total", "pageviews"]
assert [r["distinct_id"] for r in data.train_rows] == ["p1", "p2"]
assert [r["distinct_id"] for r in data.holdout_rows] == ["p3"]
diff --git a/products/autoresearch/backend/management/commands/autoresearch_score.py b/products/autoresearch/backend/management/commands/autoresearch_score.py
index 10c1cda6ff86..46965e2c7390 100644
--- a/products/autoresearch/backend/management/commands/autoresearch_score.py
+++ b/products/autoresearch/backend/management/commands/autoresearch_score.py
@@ -213,7 +213,9 @@ class Command(BaseCommand):
)
prefix = bundle_prefix(team_id=pipeline.team_id, pipeline_id=str(pipeline.pk), training_run_id=str(model.pk))
write_bundle(prefix, bundle)
- metrics = fit_champion_model(team=pipeline.team, pipeline=pipeline, prefix=prefix, bundle=bundle, user=user)
+ metrics = fit_champion_model(
+ team=pipeline.team, pipeline=pipeline, prefix=prefix, bundle=bundle, user=user, model_id=str(model.pk)
+ )
model.holdout_score = metrics.get("holdout_auc")
model.metrics = metrics
now = timezone.now()
diff --git a/products/autoresearch/backend/migrations/0002_negative_sample_rate.py b/products/autoresearch/backend/migrations/0002_negative_sample_rate.py
new file mode 100644
index 000000000000..7d6398c812f4
--- /dev/null
+++ b/products/autoresearch/backend/migrations/0002_negative_sample_rate.py
@@ -0,0 +1,39 @@
+# Generated by Django 5.2.17 on 2026-10-01 12:57
+
+import django.core.validators
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("autoresearch", "0001_squash_2026_09_07_initial"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="autoresearchmodel",
+ name="negative_sample_rate",
+ field=models.FloatField(
+ db_default=1.0,
+ default=1.0,
+ help_text="Fraction of negative training anchors the fit kept by case-control sampling; every positive is kept. 1.0 means no sampling. Scoring adds log(rate) to the logit.",
+ validators=[
+ django.core.validators.MinValueValidator(0.0),
+ django.core.validators.MaxValueValidator(1.0),
+ ],
+ ),
+ ),
+ migrations.AddField(
+ model_name="autoresearchrun",
+ name="negative_sample_rate",
+ field=models.FloatField(
+ db_default=1.0,
+ default=1.0,
+ help_text="The negative sample rate whose prior correction this run applied. 1.0 means none.",
+ validators=[
+ django.core.validators.MinValueValidator(0.0),
+ django.core.validators.MaxValueValidator(1.0),
+ ],
+ ),
+ ),
+ ]
diff --git a/products/autoresearch/backend/migrations/max_migration.txt b/products/autoresearch/backend/migrations/max_migration.txt
index 6903cd5e3dc2..6b29d5fe0b3d 100644
--- a/products/autoresearch/backend/migrations/max_migration.txt
+++ b/products/autoresearch/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0001_squash_2026_09_07_initial
+0002_negative_sample_rate
diff --git a/products/autoresearch/backend/models.py b/products/autoresearch/backend/models.py
index 3f64849d8dea..daf3713e90fb 100644
--- a/products/autoresearch/backend/models.py
+++ b/products/autoresearch/backend/models.py
@@ -235,6 +235,13 @@ class AutoresearchModel(PipelineScopedModel):
)
calibration_error = models.FloatField(null=True, blank=True)
metrics = models.JSONField(default=dict, help_text="Full metrics bundle (train/holdout/realized)")
+ negative_sample_rate = models.FloatField(
+ default=1.0,
+ db_default=1.0,
+ validators=UNIT_INTERVAL_VALIDATORS,
+ help_text="Fraction of negative training anchors the fit kept by case-control sampling; every positive "
+ "is kept. 1.0 means no sampling. Scoring adds log(rate) to the logit.",
+ )
# Provenance
source_training_run = models.ForeignKey(
@@ -466,6 +473,12 @@ class AutoresearchRun(PipelineScopedModel):
rows_scored = models.IntegerField(null=True, blank=True, validators=[MinValueValidator(0)])
metrics = models.JSONField(default=dict)
+ negative_sample_rate = models.FloatField(
+ default=1.0,
+ db_default=1.0,
+ validators=UNIT_INTERVAL_VALIDATORS,
+ help_text="The negative sample rate whose prior correction this run applied. 1.0 means none.",
+ )
error = models.TextField(blank=True, default="")
started_at = models.DateTimeField(null=True, blank=True)
diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.py
index 8e332651dd3c..712deb36ba27 100644
--- a/products/autoresearch/backend/presentation/views/serializers.py
+++ b/products/autoresearch/backend/presentation/views/serializers.py
@@ -1174,8 +1174,9 @@ class ValidationWarningSerializer(serializers.Serializer):
# A CharField on purpose: a ChoiceField named `code` collides with another product's `code` enum in drf-spectacular.
code = serializers.CharField(
help_text=(
- "Machine-readable warning code. 'population_too_large' and 'horizon_exceeds_lookback' mean a "
- "training run would fail: fix the definition before creating. 'low_volume', 'low_positives' and "
+ "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'."
@@ -1238,7 +1239,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 "
- "'population_too_large' or 'horizon_exceeds_lookback' cannot train."
+ "an 'error' 'population_too_large' or 'horizon_exceeds_lookback' cannot train or score."
)
)
requires_acknowledgement = serializers.BooleanField(
diff --git a/products/autoresearch/backend/presentation/views/views.py b/products/autoresearch/backend/presentation/views/views.py
index 5fd9fe913c6f..adf87de2dbbc 100644
--- a/products/autoresearch/backend/presentation/views/views.py
+++ b/products/autoresearch/backend/presentation/views/views.py
@@ -403,7 +403,7 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin
description=(
"Validate a proposed pipeline's target event and population before creating it. "
"Returns volume estimates, base rate, and any warnings. Creation does not enforce the result: "
- "'population_too_large' and 'horizon_exceeds_lookback' mean a training run would fail, and the other "
+ "'horizon_exceeds_lookback' and an 'error' 'population_too_large' mean a run would fail, and the other "
"'error' codes mean the data is too thin for a reliable model. Call this before autoresearch-create."
),
)
diff --git a/products/autoresearch/backend/training/promotion.py b/products/autoresearch/backend/training/promotion.py
index 5d79e652e52f..cf43c70feed5 100644
--- a/products/autoresearch/backend/training/promotion.py
+++ b/products/autoresearch/backend/training/promotion.py
@@ -338,7 +338,7 @@ def _activate_pipeline(pipeline: AutoresearchPipeline) -> None:
def _schedule_champion_fit(
- *, pipeline: AutoresearchPipeline, prefix: str, training_run: AutoresearchTrainingRun
+ *, pipeline: AutoresearchPipeline, prefix: str, training_run: AutoresearchTrainingRun, model_id: str
) -> None:
"""The train run produces the serving artifact: fit the champion and persist model.pkl so
predict runs are pure inference. Deferred to on_commit, because the sandbox and the
@@ -354,7 +354,9 @@ def _schedule_champion_fit(
# committed, so raising here would report a failed completion for a finished run
# that a retry can only answer with its no-op.
try:
- fit_champion_model(team=pipeline.team, pipeline=pipeline, prefix=prefix, anchor_ts=anchor_ts)
+ fit_champion_model(
+ team=pipeline.team, pipeline=pipeline, prefix=prefix, anchor_ts=anchor_ts, model_id=model_id
+ )
except Exception:
logger.exception("autoresearch_champion_fit_failed", training_run_id=training_run_id, prefix=prefix)
@@ -474,7 +476,9 @@ def _finalize_under_lock(
# A rejected challenger is not fitted: inference reads the champion only, and no path
# promotes a challenger row later, so its fit would cost a sandbox run for nothing.
if artifact_prefix:
- _schedule_champion_fit(pipeline=pipeline, prefix=artifact_prefix, training_run=training_run)
+ _schedule_champion_fit(
+ pipeline=pipeline, prefix=artifact_prefix, training_run=training_run, model_id=str(model.pk)
+ )
return {
"promoted": promoted,
diff --git a/products/autoresearch/backend/training/runner.py b/products/autoresearch/backend/training/runner.py
index 938803ee367a..ba4293bcf27f 100644
--- a/products/autoresearch/backend/training/runner.py
+++ b/products/autoresearch/backend/training/runner.py
@@ -35,8 +35,8 @@ from posthog.hogql.property import action_to_expr
from posthog.dataclasses import frozen
from products.actions.backend.models.action import Action
-from products.autoresearch.backend.dataset.labeling import build_target_condition
-from products.autoresearch.backend.inference.sandbox import _resolve_acting_user
+from products.autoresearch.backend.dataset.labeling import TrainingSample, build_target_condition
+from products.autoresearch.backend.inference.sandbox import _resolve_acting_user, measure_training_sample
from products.autoresearch.backend.models import AutoresearchPipeline, AutoresearchSuggestion, AutoresearchTrainingRun
from products.tasks.backend.facade import (
api as tasks_facade,
@@ -124,11 +124,29 @@ def _describe_target(pipeline: AutoresearchPipeline) -> _TargetDescription:
return _TargetDescription(spec_line=f"event `{wrapped_event}`", inline_ref=f"`{wrapped_event}`")
+def _describe_training_sample(sample: TrainingSample | None) -> str:
+ """The brief's training sample bullets: sample size, positive count, and negative sample rate."""
+ if sample is None:
+ return ""
+ clause = (
+ f"\n- **Training sample**: about {sample.expected_size} people, {sample.positives} of them positive"
+ f"\n- **Negative sample rate (r)**: {sample.negative_sample_rate:.4g}"
+ )
+ if sample.negative_sample_rate < 1.0:
+ clause += (
+ f" — the population has {sample.population} people, so the framework keeps every positive and"
+ " this fraction of the negatives. Holdout AUC is not affected. Do not reweight classes to undo it:"
+ " scoring corrects each score with logit(p) + log(r)."
+ )
+ return clause
+
+
def build_agent_description(
pipeline: AutoresearchPipeline,
iteration_budget: int,
training_run_id: str,
pending_suggestions: list[AutoresearchSuggestion] | None = None,
+ training_sample: TrainingSample | None = None,
) -> str:
"""Build the Claude Code agent prompt for the autoresearch training loop."""
pop_clause = ""
@@ -151,6 +169,8 @@ def build_agent_description(
f"when {' or when '.join(stop_parts)}."
)
+ sample_clause = _describe_training_sample(training_sample)
+
today_iso = date.today().isoformat()
min_iters = min(3, iteration_budget)
target = _describe_target(pipeline)
@@ -180,7 +200,7 @@ def build_agent_description(
- **Target**: {target.spec_line}
- **Prediction horizon**: {pipeline.horizon_days} days
- **Output person property**: `{_wrap_untrusted(pipeline.output_person_property)}`
- - **Iteration budget**: {iteration_budget}{stop_clause}{pop_clause}
+ - **Iteration budget**: {iteration_budget}{stop_clause}{pop_clause}{sample_clause}
- **Today's date**: {today_iso}
## Identifiers for every tool call
@@ -572,6 +592,18 @@ def _cancel_dispatched_task_run(task_run_id: UUID, task_id: UUID, *, team_id: in
# ── Main entry point ──────────────────────────────────────────────────────────
+def _training_sample_for_brief(pipeline: AutoresearchPipeline) -> TrainingSample | None:
+ """
+ The training sample, for the brief only. Materialization measures it again, so a count that
+ fails here leaves the bullets out rather than failing the launch.
+ """
+ try:
+ return measure_training_sample(team=pipeline.team, pipeline=pipeline)
+ except Exception:
+ logger.warning("autoresearch_training_sample_unmeasured", pipeline_id=str(pipeline.pk), exc_info=True)
+ return None
+
+
def run_training(
pipeline: AutoresearchPipeline,
iteration_budget: int,
@@ -629,6 +661,7 @@ def run_training(
iteration_budget=iteration_budget,
training_run_id=str(training_run.id),
pending_suggestions=pending_suggestions or None,
+ training_sample=_training_sample_for_brief(pipeline),
)
title = f"[autoresearch] {pipeline.name}: learn to predict '{pipeline.target_event}'"
diff --git a/products/autoresearch/backend/training/test_training.py b/products/autoresearch/backend/training/test_training.py
index b80452328d14..3434935ddc89 100644
--- a/products/autoresearch/backend/training/test_training.py
+++ b/products/autoresearch/backend/training/test_training.py
@@ -10,6 +10,7 @@ from posthog.models.organization import Organization
from posthog.models.user import User
from products.actions.backend.models.action import Action
+from products.autoresearch.backend.dataset.labeling import TrainingSample
from products.autoresearch.backend.inference.sandbox import SandboxInferenceError
from products.autoresearch.backend.models import AutoresearchPipeline, AutoresearchSuggestion, AutoresearchTrainingRun
from products.autoresearch.backend.testing import TeamScopedTestMixin
@@ -58,6 +59,20 @@ class TestBuildAgentDescription(TeamScopedTestMixin, BaseTest):
assert "fit and evaluate" in prompt
assert "roc_auc_score" in prompt
+ @parameterized.expand(
+ [
+ ("sampled", TrainingSample(population=100_000, positives=2_000, negative_sample_rate=0.4), True),
+ ("unsampled", TrainingSample(population=1_000, positives=100, negative_sample_rate=1.0), False),
+ ]
+ )
+ def test_prompt_states_the_training_sample(self, _name: str, sample: TrainingSample, corrected: bool) -> None:
+ prompt = build_agent_description(
+ pipeline=self._make_pipeline(), iteration_budget=5, training_run_id="run-123", training_sample=sample
+ )
+ assert f"about {sample.expected_size} people, {sample.positives} of them positive" in prompt
+ assert f"**Negative sample rate (r)**: {sample.negative_sample_rate:g}" in prompt
+ assert ("logit(p) + log(r)" in prompt) is corrected
+
def test_prompt_drives_materialize_features_not_execute_sql_pull(self) -> None:
pipeline = self._make_pipeline()
prompt = build_agent_description(pipeline=pipeline, iteration_budget=5, training_run_id="run-123")
diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.ts
index 33ab992d5c77..2f4645ea3176 100644
--- a/products/autoresearch/frontend/generated/api.schemas.ts
+++ b/products/autoresearch/frontend/generated/api.schemas.ts
@@ -1495,7 +1495,7 @@ export const ValidationWarningSeverityEnumApi = {
} as const
export interface ValidationWarningApi {
- /** Machine-readable warning code. 'population_too_large' and 'horizon_exceeds_lookback' mean a training run would fail: fix the definition before creating. '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. '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
@@ -1508,7 +1508,7 @@ export interface ValidationWarningApi {
}
export interface ValidatePipelineResponseApi {
- /** False when any warning has severity 'error'. Creation does not enforce it, but a definition with 'population_too_large' or 'horizon_exceeds_lookback' cannot train. */
+ /** 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. */
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/generated/api.ts b/products/autoresearch/frontend/generated/api.ts
index a9b28472b93b..a9f4d838f8ad 100644
--- a/products/autoresearch/frontend/generated/api.ts
+++ b/products/autoresearch/frontend/generated/api.ts
@@ -891,7 +891,7 @@ export const getAutoresearchValidateCreateUrl = (projectId: string) => {
}
/**
- * Validate a proposed pipeline's target event and population before creating it. Returns volume estimates, base rate, and any warnings. Creation does not enforce the result: 'population_too_large' and 'horizon_exceeds_lookback' mean a training run would fail, and the other 'error' codes mean the data is too thin for a reliable model. Call this before autoresearch-create.
+ * Validate a proposed pipeline's target event and population before creating it. Returns volume estimates, base rate, and any warnings. Creation does not enforce the result: 'horizon_exceeds_lookback' and an 'error' 'population_too_large' mean a run would fail, and the other 'error' codes mean the data is too thin for a reliable model. Call this before autoresearch-create.
* @summary Validate a pipeline definition
*/
export const autoresearchValidateCreate = async (
diff --git a/products/autoresearch/frontend/generated/api.zod.ts b/products/autoresearch/frontend/generated/api.zod.ts
index 67e7b0ee9188..1d4df754342f 100644
--- a/products/autoresearch/frontend/generated/api.zod.ts
+++ b/products/autoresearch/frontend/generated/api.zod.ts
@@ -658,7 +658,7 @@ export const AutoresearchResolveTemplateCreateBody = /* @__PURE__ */ zod.object(
})
/**
- * Validate a proposed pipeline's target event and population before creating it. Returns volume estimates, base rate, and any warnings. Creation does not enforce the result: 'population_too_large' and 'horizon_exceeds_lookback' mean a training run would fail, and the other 'error' codes mean the data is too thin for a reliable model. Call this before autoresearch-create.
+ * Validate a proposed pipeline's target event and population before creating it. Returns volume estimates, base rate, and any warnings. Creation does not enforce the result: 'horizon_exceeds_lookback' and an 'error' 'population_too_large' mean a run would fail, and the other 'error' codes mean the data is too thin for a reliable model. Call this before autoresearch-create.
* @summary Validate a pipeline definition
*/
export const autoresearchValidateCreateBodyTargetEventDefault = ``
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 219be2891617..a9bf3f8fde33 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -105230,7 +105230,7 @@ export namespace Schemas {
} as const;
export interface ValidationWarning {
- /** Machine-readable warning code. 'population_too_large' and 'horizon_exceeds_lookback' mean a training run would fail: fix the definition before creating. '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. '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;
@@ -105243,7 +105243,7 @@ export namespace Schemas {
}
export interface ValidatePipelineResponse {
- /** False when any warning has severity 'error'. Creation does not enforce it, but a definition with 'population_too_large' or 'horizon_exceeds_lookback' cannot train. */
+ /** 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. */
can_proceed: boolean;
/** True if there are non-blocking warnings the user should acknowledge before proceeding. */
requires_acknowledgement: boolean;
diff --git a/services/mcp/src/generated/autoresearch/api.ts b/services/mcp/src/generated/autoresearch/api.ts
index b8ecf2b1c8f4..87ab4f67c46f 100644
--- a/services/mcp/src/generated/autoresearch/api.ts
+++ b/services/mcp/src/generated/autoresearch/api.ts
@@ -685,7 +685,7 @@ export const AutoresearchResolveTemplateCreateBody = () => zod.object({
})
/**
- * Validate a proposed pipeline's target event and population before creating it. Returns volume estimates, base rate, and any warnings. Creation does not enforce the result: 'population_too_large' and 'horizon_exceeds_lookback' mean a training run would fail, and the other 'error' codes mean the data is too thin for a reliable model. Call this before autoresearch-create.
+ * Validate a proposed pipeline's target event and population before creating it. Returns volume estimates, base rate, and any warnings. Creation does not enforce the result: 'horizon_exceeds_lookback' and an 'error' 'population_too_large' mean a run would fail, and the other 'error' codes mean the data is too thin for a reliable model. Call this before autoresearch-create.
* @summary Validate a pipeline definition
*/
export const AutoresearchValidateCreateParams = () => zod.object({