:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): cap inbox ranking training by recency so probabilities stay calibrated (#109124)
posthog[bot]3b6e7aa35fa9
diff --git a/docs/internal/inbox-ranking-training.md b/docs/internal/inbox-ranking-training.mdindex b26186a8f0e6..f778b94f3616 100644--- a/docs/internal/inbox-ranking-training.md+++ b/docs/internal/inbox-ranking-training.md@@ -20,6 +20,55 @@ The daily snapshots and selectable scoring-moment and report grains remain availSee the [ranking DAG README](../../products/signals/dags/inbox_ranking/README.md) for the feature-set contract and operating instructions.+## What each probability means++Each head is conditioned on its cohort (`training/heads.py`).+The cohort is read at the horizon snapshot, so "shown" means shown at any time before the horizon.+`p_open` and the other cohort-conditioned heads are not unconditional probabilities.+Each head is graded only on its cohort.++| Head | Probability | Horizon |+| --------------- | -------------------------------------- | ------- |+| `open` | P(opened \| shown) | 3d |+| `action` | P(create-PR click or discuss \| shown) | 7d |+| `discuss` | P(discuss \| shown) | 7d |+| `dismiss_wrong` | P(dismissed as wrong \| shown) | 14d |+| `reviewer_fix` | P(reviewers corrected \| shown) | 14d |+| `thumbs_up` | P(thumbs up \| opened) | 7d |+| `pr_created` | P(PR created) over every report | 7d |+| `pr_merged` | P(PR merged) over every report | 14d |+| `refund` | P(refund) over every report | 14d |++Each head in `metadata.json` records `cohort` (`impressed`, `opened` or `everyone`) and `horizon_days`.++## Row budget++A feature set can limit the rows one head keeps (`max_examples_per_head`).+The embedding families set it to 100,000; the tabular family has no budget.+The budget limits history, not the rows inside a day:++- The head's examples are grouped by report-creation day, newest first.+- Whole days are kept while the running total stays within the budget, and every older day is dropped.+- The newest day is always kept, even when it alone exceeds the budget.++Every kept day keeps all of its positives and negatives, so the kept label rate is the population rate of those days.+The scores stay calibrated to that population, and the holdout stays a clean time split.+A recency cut drops old positives with old negatives, so the budget must stay large enough to keep the rare heads fed.++Each head in `metadata.json` records `example_window_start`, the earliest report-creation day kept, and `example_cap_bound`, whether the budget dropped any day.+`inbox_ranking_examples_built` carries both fields, so a chart shows when the budget starts to bind.++## Promotion++A candidate replaces its family's champion only when, on every head the champion could read:++- its holdout AUC is at most `AUC_TOLERANCE` below the champion's, and+- its holdout calibration error (ECE) is at most `ECE_TOLERANCE` above the champion's.++Both champion numbers come from the champion's `<head>.holdout.ubj` scored on the candidate's holdout.+A head without a paired champion ECE skips the calibration check.+`inbox_ranking_promotion_decided` carries the paired values as `champion_<head>_auc_on_this_holdout` and `champion_<head>_ece_on_this_holdout`.+## Baked and unbaked unseen metrics`inbox_ranking_unseen_graded` evaluates the saved predictions for each scoring cohort every day, from its birth-day snapshot through each head's horizon.@@ -82,7 +131,7 @@ It means "at least as likely as the average fitting example", not a 50% probabil- A champion keeps its own threshold. A candidate and a champion graded on the same reports use different cuts.The threshold is specific to the head, family, version and fitting population.-A row budget keeps every positive and samples the negatives, so it raises the rate.+A row budget keeps only the newest report-creation days, so the rate is that window's rate, not the rate of the full lookback.Do not read the threshold as population prevalence, and do not compute it again from evaluation labels.### Metricsdiff --git a/products/signals/backend/ranking/features.py b/products/signals/backend/ranking/features.pyindex f15dfaeb1d2d..64ab87529b1c 100644--- a/products/signals/backend/ranking/features.py+++ b/products/signals/backend/ranking/features.py@@ -228,8 +228,8 @@ class ReportEmbeddingsFeatureSet(FeatureSet):One example per report, not one per scoring moment. A day's newborns over the whole lookback,times 1536 floats, is gigabytes of Parquet per partition and more than the training pod holds,which is what rules the moment grain out at this width. The default birth grain gives that.- `max_examples_per_head` bounds what is left; the lookback stays the tabular set's, so positives- still accrue over the whole window.+ `max_examples_per_head` bounds what is left by dropping the oldest report-creation days; the+ lookback stays the tabular set's, so positives accrue over the whole window until the budget binds.Vectors arrive through `extras`, from the rendering's own dt=D snapshot, which holds thelatest vector per report. A report is re-embedded whenever its text changes, and the@@ -252,8 +252,9 @@ class ReportEmbeddingsFeatureSet(FeatureSet):state_columns = ()# 1536 float32 columns, so a head's Parquet slice and its training matrix both scale with this.# Sized so every head of this family fits one partition's examples object and the fits stay- # inside the training job's runtime budget, with the budget spent on positives first.- max_examples_per_head = 25_000+ # inside the training job's runtime budget. The budget cuts the oldest report-creation days, so+ # it must stay large enough to keep the rare heads' positives.+ max_examples_per_head = 100_000def __init__(self, *, name: str, extras_key: str) -> None:self.name = namediff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.mdindex 21eb4f0a5a34..2c167cf3bdf1 100644--- a/products/signals/dags/inbox_ranking/AGENTS.md+++ b/products/signals/dags/inbox_ranking/AGENTS.md@@ -16,7 +16,7 @@ Read `README.md` first for what the dataset is and how partitions behave. This f- The two embedding sets are one `ReportEmbeddingsFeatureSet` parameterized by the `extras` key it reads, one rendering each. A set reads its own key only: never add a fallback to the other rendering's vector, and keep width, grain, row budget and booster params identical across the pair, or the paired AUC difference stops measuring the text choice. `embeddings_extras` loads one set's inputs at a time and the scores asset narrows each snapshot to the newborn pool, because a snapshot carries a vector per live report; keep both, so a further embedding family costs runtime rather than peak memory.- A **missing** side-input object leaves its key out, so only the sets reading it are skipped and their partitions stay as they are. An **empty** object keeps its key and takes the ordinary thin-input path. Do not collapse the two: the first must not write over a partition, and the second is a day the family really has nothing to fit.- Both `buildable` and `build_matrix` take the moment being built as `as_of`, and a side input that changes over a report's life must honor it. The report vector does: reports are re-embedded when their text changes, so the snapshot's latest vector often postdates the moment, and taking it would train on text that did not exist yet. Never widen a set's side input to the latest value for convenience.-- `example_grain` and `max_examples_per_head` are per set, because the examples object is. Every set defaults to the birth grain so the families target the same scoring moment; side-input availability and row budgets can still change their training populations. Keep the tabular set with no budget: `report_embeddings` is the reason the budget exists (1536 columns per row), and a budget on the tabular set would thin the family the other lines are measured against. A budget keeps every positive, so it moves the base rate its scores calibrate to and not the ranking.+- `example_grain` and `max_examples_per_head` are per set, because the examples object is. Every set defaults to the birth grain so the families target the same scoring moment; side-input availability and row budgets can still change their training populations. Keep the tabular set with no budget: `report_embeddings` is the reason the budget exists (1536 columns per row), and a budget on the tabular set would thin the family the other lines are measured against. A budget limits history and never samples inside a day: `cap_examples` keeps whole report-creation days, newest first, so the kept label rate stays the population rate and the scores stay calibrated. Never reintroduce a positive-keeping sample: it raises the base rate the booster fits, and a holdout cut from the same sample hides it.- `feature_vector` (one row, serving) and `feature_frame` (vectorized, training) must agree row for row; a test pins it. Change both together.- Examples are one row per report, on the snapshot of the day it was created, labeled from the snapshot `horizon_days` later. The scoring-moment and report grains stay selectable for re-scoring families, so keep the holdout cut by report: a row-level split leaks near-duplicate snapshots of the same report the moment a set asks for one of them. The moments are chosen before the features are built, so a set under a row budget never builds columns for rows it then drops; keep that order.- `inbox_ranking_models/v1/<model_name>/dt=D/` is history like the dataset partitions: the only mutation is a re-run of the same partition, which replaces the prefix in full (stale head files are deleted). `<model_name>/champion.json` is the only object written outside its partition, and only the champion asset (or a human, deliberately) writes it; it carries the candidate's `run_id`, so a loader can detect a re-run behind a pinned version.diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex fc31ab256701..d89d6bd1de89 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -85,7 +85,7 @@ s3://<bucket>/<prefix>/- **Examples are one row per report at its birth, by default.** For partition `dt=D` the examples asset reads the report-state and labels snapshots `dt=D-lookback..D` and emits one row per report, on the snapshot of the day it was created, labeled from the snapshot `horizon_days` later (3 for open, 7 for action / pr_created / discuss / thumbs_up, 14 for dismiss_wrong / pr_merged / refund / reviewer_fix). Features are built by the feature set from that snapshot's state columns plus `age_hours`, the report's age at the snapshot. Labels are aligned to the state spine, so a report with no label event is a negative (all-zero labels), not absent. Label-only rows (no Postgres state) are skipped, as are state rows read long after their snapshot day (backfills carry current Postgres state; see `features_observed_at`) and, for the `dismiss_wrong` head, rows whose status telemetry fails the dataset's `label_provenance_ok` check. Birth is the moment serving scores a report, and the label that comes out is a per-report probability, which is what the inbox ordering needs. A report born before the window, or one whose birth-day snapshot is missing from it, is no example; `reports_missing_birth_snapshot` on the asset counts the second case, which is a gap in the partitions.- **An outcome already visible on the birth day is a future positive.** A report born on day D has no scoring moment before D, so an outcome visible at D belongs to the moment being built rather than to an earlier one; the labels of D therefore read as their defaults for a report born on D. Most outcomes land on the birth day, so this is where the positives are: censoring on them costs the `pr_created` head most of its training signal. `<set>_<head>_birth_day_positives` on the examples asset, and `birth_day_positives` on the `inbox_ranking_examples_built` event, say how many positives the rule keeps. These rows carry a hindsight the other rows do not: the state snapshot reads `signal_count`, `total_weight`, `run_count` and the text sizes live from Postgres a few hours after day D ends, so a birth-day outcome happened before its own feature read. Both the holdout AUC and the newborn unseen grade therefore read optimistically on these rows, until the scoring sweep's timestamped score log replaces the daily snapshot as this table's source.- **Every head asks whether the outcome happened within N days of the scoring moment.** `pr_merged` includes every report, so the label covers the whole report-to-merge path without requiring a PR at birth or at the horizon.-- **A set may ask for another grain**, and cap the rows one head keeps (`max_examples_per_head`, all positives first, then a seeded sample of the negatives). The scoring-moment grain is one row per (report, snapshot) whose head label is still 0 on that snapshot: the serving situation replayed over history, but its label is a hazard conditional on the report still being live, and one long-lived report contributes dozens of near-duplicate rows. The report grain is the first snapshot of the window where the report is a usable moment, which is later than birth only when a side input landed late. Both stay selectable for re-scoring families; nothing ships on them today. The row budget changes the base rate a set's scores are calibrated to, not the ranking the unseen AUC reads. The lookback is the tabular set's whatever the grain, so positives accrue over the whole window.+- **A set may ask for another grain**, and cap the rows one head keeps (`max_examples_per_head`, whole report-creation days, newest first). The scoring-moment grain is one row per (report, snapshot) whose head label is still 0 on that snapshot: the serving situation replayed over history, but its label is a hazard conditional on the report still being live, and one long-lived report contributes dozens of near-duplicate rows. The report grain is the first snapshot of the window where the report is a usable moment, which is later than birth only when a side input landed late. Both stay selectable for re-scoring families; nothing ships on them today. The row budget shortens the history a head is fit on and keeps each kept day whole, so the scores stay calibrated to the population of that window. The lookback is the tabular set's whatever the grain, so positives accrue over the whole window until the budget binds.- **`tabular` is the serving set** (the state counters, title/summary length, age, one-hot priority/actionability). No embedding, no impression-derived columns, so the scoring sweep needs only the `SignalReport` row and its judgment artefacts. The sweep must build features through the same module; the booster's `feature_names` are checked against it at load.- **`report_embeddings` is the report's own vector and nothing else**, read from the dt=D `inbox_report_embeddings` snapshot as a side input. Age is deliberately left out: it is the whole signal of the `recency_auc` line the unseen read already reports, so a gap to that line is content rather than recency. The scoring sweep does not serve this set: it is an offline candidate, and serving it needs the report vector at scoring time.- **`title_embeddings` is the same set over the title-only vector**, read from the dt=D `inbox_report_title_embeddings` snapshot, a separate leaf partition with its own `embedding_inserted_at`. One `ReportEmbeddingsFeatureSet` class parameterized by the input it reads, so the two renderings share this width, this grain, this row budget and the trainer's booster params by construction: the pair measures the text choice, and a recipe that drifted on one side would read as a text effect. A set reads its own input only and never falls back to the other rendering's vector, so a report present in one snapshot and absent from the other is an example for one family and not the other. The inbox title is what a person reads before opening a report and the summary is read after, which is the question the pair answers: whether the summary carries `open` signal or only post-open signal.@@ -95,7 +95,7 @@ s3://<bucket>/<prefix>/- **One rendering's vectors are held at a time.** The examples asset loads a set's side inputs, builds that set's object, and releases them before the next set. Each snapshot carries a vector per live report, so a further embedding family costs runtime rather than peak memory. The scores asset narrows each snapshot to the newborn pool it scores for the same reason. Raising the pod memory limit is not the first move here.- **Candidate**: one per family, per-head XGBoost with fixed params, holdout = the last `holdout_days` of reports (cut by report, never by row), AUC + a label-permutation null. Each family trains on the examples of the feature set its registry entry names, and a family whose examples or metadata are missing that day is logged and skipped rather than failing the asset. A head is _readable_ when it has enough holdout positives and clears its null by 0.05. The shipped booster (`<head>.ubj`) is refit on everything; the train-only fit is kept as `<head>.holdout.ubj` so a later candidate can grade this model on its own holdout.- **Metrics telemetry**: each asset also captures its metrics as events into the dogfood project (the same project the label events land in), through `training/telemetry.py`: `inbox_ranking_examples_built` once per head and feature set, `inbox_ranking_candidate_trained` once per head (`head`, `model_role` always `candidate`, holdout / train AUC, average precision, logloss, positive rate, mean predicted score, the row-weighted decile calibration error, the permutation-null mean and spread, counts, `readable`), `inbox_ranking_holdout_calibration` once per head and holdout score decile `inbox_ranking_promotion_decided` once per run and `inbox_ranking_serving_manifest_published` once per run, all carrying `model_name` and `model_version` and stamped midday UTC on the partition day so re-runs and backfills chart on the day they describe. Per-head stability is a trends insight with a `head` breakdown; a readability drop is an insight alert. `metadata.json` stays the durable record. Capture is best-effort. Local dev runs (`DEBUG`) emit too, under `distinct_id` `inbox_ranking_training_local` with `environment=local`, so filter or break down on `environment` when reading the prod series; any other non-Cloud deployment emits nothing.-- **Champion**: one decision per family against that family's own pointer. `promotion.decide_promotion` — promote when the candidate has a readable head, is within 0.02 AUC of the champion on every head the champion could read, and the champion is at least `INBOX_RANKING_PROMOTION_MIN_DAYS` old. The champion's AUCs come from its `<head>.holdout.ubj` scored on the candidate's holdout (`paired_champion_aucs`), so both models are compared on one set of reports; a champion without that file falls back to its stored AUC. The pointer is rewritten only when `INBOX_RANKING_AUTO_PROMOTE` is on; otherwise the decision is logged and surfaced as asset metadata, so the daily candidate series is monitoring while the first shadow read runs on a frozen champion. To promote by hand, copy a candidate's `metadata.json` to `champion.json` with a `promoted_at`.+- **Champion**: one decision per family against that family's own pointer. `promotion.decide_promotion` — promote when the candidate has a readable head, is within 0.02 AUC and 0.02 holdout ECE of the champion on every head the champion could read, and the champion is at least `INBOX_RANKING_PROMOTION_MIN_DAYS` old. The champion's AUCs and ECEs come from its `<head>.holdout.ubj` scored on the candidate's holdout (`paired_champion_grades`), so both models are compared on one set of reports; a champion without that file falls back to its stored AUC and skips the calibration check. The pointer is rewritten only when `INBOX_RANKING_AUTO_PROMOTE` is on; otherwise the decision is logged and surfaced as asset metadata, so the daily candidate series is monitoring while the first shadow read runs on a frozen champion. To promote by hand, copy a candidate's `metadata.json` to `champion.json` with a `promoted_at`.- **Serving manifest**: the dag's decision about what the scoring sweep runs, published where the sweep can read it. The Temporal workers have no credential for the dataset bucket, so `inbox_ranking_serving_manifest` copies the models the sweep needs into the deployment's own object store and writes a manifest naming them:diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.pyindex 2a6254711b64..69672f4e5f1e 100644--- a/products/signals/dags/inbox_ranking/tests/test_training.py+++ b/products/signals/dags/inbox_ranking/tests/test_training.py@@ -81,7 +81,9 @@ from products.signals.dags.inbox_ranking.training.dag import (candidate_metadata,champion_object_key,embeddings_extras,+ example_windows,examples_object_key,+ examples_table,grade_metadata,inbox_ranking_training_examples,inbox_ranking_unseen_graded,@@ -105,7 +107,12 @@ from products.signals.dags.inbox_ranking.training.examples import (reports_missing_birth_snapshot,)from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, Head, dismissed_as_wrong-from products.signals.dags.inbox_ranking.training.promotion import AUC_TOLERANCE, PromotionDecision, decide_promotion+from products.signals.dags.inbox_ranking.training.promotion import (+ AUC_TOLERANCE,+ ECE_TOLERANCE,+ PromotionDecision,+ decide_promotion,+)from products.signals.dags.inbox_ranking.training.served import served_events, served_metadata, served_score_rowsfrom products.signals.dags.inbox_ranking.training.serving import FamilyModels, compose_manifestfrom products.signals.dags.inbox_ranking.training.telemetry import (@@ -124,7 +131,7 @@ from products.signals.dags.inbox_ranking.training.telemetry import (unseen_report_graded_events,unseen_score_events,)-from products.signals.dags.inbox_ranking.training.train import _head_readable, booster_holdout_auc, train_head+from products.signals.dags.inbox_ranking.training.train import _head_readable, booster_holdout_grade, train_headfrom products.signals.dags.inbox_ranking.training.unseen import (CANDIDATE_ROLE,CHAMPION_ROLE,@@ -564,15 +571,38 @@ def test_train_head_learns_a_separable_signal_and_names_its_features():# The saved holdout fit graded on the same rows must reproduce the stored metric: this is the# path the champion gate uses to compare two models on one holdout.assert trained.holdout_booster_ubj is not None- paired = booster_holdout_auc(+ paired = booster_holdout_grade(trained.holdout_booster_ubj, examples, head, feature_names=FEATURE_NAMES, holdout_days=7)- assert paired == pytest.approx(trained.metrics.holdout_auc, abs=1e-6)+ assert paired is not None+ assert paired.auc == pytest.approx(trained.metrics.holdout_auc, abs=1e-6)+ assert paired.expected_calibration_error == pytest.approx(+ trained.metrics.holdout_expected_calibration_error, abs=1e-6+ )+ # The metadata that ships says what the probability is conditioned on and how much history it saw.+ window = {"example_window_start": "2026-08-01", "example_cap_bound": False}+ table = examples_table(examples, TABULAR_FEATURE_SET, {head.name: window})+ buffer = io.BytesIO()+ pq.write_table(table, buffer)+ windows = example_windows(pq.read_table(pa.BufferReader(buffer.getvalue())))+ candidate_head = candidate_metadata(+ "2026-08-19",+ [trained],+ model_name=TABULAR_MODEL_NAME,+ feature_set=TABULAR_FEATURE_SET,+ skipped=[],+ trained_at=NOW,+ run_id="run-1",+ windows=windows,+ )["heads"][0]+ assert {"cohort": head.cohort.__name__, "horizon_days": head.horizon_days, **window}.items() <= (+ candidate_head.items()+ )# A booster from another feature schema is not scorable on these examples: the gate must fall# back to the stored AUC instead of failing the champion asset every day.other_schema = xgb.XGBClassifier(n_estimators=2).fit(pd.DataFrame({"not_a_feature": [0, 1, 0, 1]}), [0, 1, 0, 1])other_ubj = bytes(other_schema.get_booster().save_raw("ubj"))- assert booster_holdout_auc(other_ubj, examples, head, feature_names=FEATURE_NAMES, holdout_days=7) is None+ assert booster_holdout_grade(other_ubj, examples, head, feature_names=FEATURE_NAMES, holdout_days=7) is Nonedef test_train_head_keeps_logloss_on_a_single_class_holdout():@@ -1391,7 +1421,15 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):feature_set=TABULAR_FEATURE_SET.name,snapshots=20,backfilled_rows=0,- per_head={"open": HeadExampleCounts(rows=10, positives=2, birth_day_positives=1)},+ per_head={+ "open": HeadExampleCounts(+ rows=10,+ positives=2,+ birth_day_positives=1,+ example_window_start=datetime.date(2026, 7, 1),+ example_cap_bound=True,+ )+ },),promotion_event(partition_key="2026-08-25",@@ -1402,6 +1440,7 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):champion_version="none",incumbent_champion_version="none",champion_aucs={"open": 0.6},+ champion_eces={"open": 0.05},),*unseen_score_events(run_id="run-1", rows=score_event_rows(scores, _state(["a"]))),*unseen_head_graded_events(run_id="run-1", grades=grades),@@ -1466,6 +1505,8 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):"rows": 10,"positives": 2,"birth_day_positives": 1,+ "example_window_start": "2026-07-01",+ "example_cap_bound": True,"feature_set": TABULAR_FEATURE_SET.name,}.items() <= examples_props.items()promotion_props = by_event["inbox_ranking_promotion_decided"][0]["properties"]@@ -1474,6 +1515,7 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):"promoted": False,"incumbent_champion_version": "none","champion_open_auc_on_this_holdout": 0.6,+ "champion_open_ece_on_this_holdout": 0.05,}.items() <= promotion_props.items()# The unseen series is charted next to the holdout series, so it breaks down on the same head# property and carries the model it graded; the p_/outcome_ naming is what a calibration read joins on.@@ -1616,6 +1658,30 @@ def test_decide_promotion_grades_the_champion_on_the_candidate_holdout():assert not paired.promote and "regressed" in paired.reason+ "candidate_ece,champion_eces,expected_promote",+ [+ (0.10, {"open": 0.10 - ECE_TOLERANCE - 0.01}, False),+ (0.10, {"open": 0.10 - ECE_TOLERANCE + 0.01}, True),+ # A champion fit on sampled negatives is badly calibrated, so a corrected candidate passes.+ (0.02, {"open": 0.20}, True),+ # The stored error was read on the champion's own holdout, so no paired error means no check.+ (0.30, None, True),+ ],+)+def test_decide_promotion_refuses_a_worse_calibrated_candidate(candidate_ece, champion_eces, expected_promote):+ candidate = _metadata("d2", open=0.66)+ candidate["heads"][0]["holdout_expected_calibration_error"] = candidate_ece+ champion = {**_metadata("d1", open=0.66), "promoted_at": "2026-08-10T00:00:00+00:00"}++ decision = decide_promotion(+ candidate, champion, now=NOW, min_days_between=3, champion_aucs={"open": 0.66}, champion_eces=champion_eces+ )++ assert decision.promote is expected_promote+ assert expected_promote or "open calibration regressed" in decision.reason++class _FakeS3:def __init__(self, keys: list[str]):self.keys = set(keys)@@ -2140,18 +2206,41 @@ def test_report_grain_keeps_one_example_per_report_and_needs_a_vector(feature_seassert moments["report_id"].tolist() == ["a", "b", "a", "b"]-def test_cap_examples_keeps_every_positive_and_a_seeded_sample_of_the_negatives():- # The budget is what keeps a 1536-column head inside one partition's object and the job's- # runtime. Positives are the scarce side, and a re-run of a partition must keep the same rows.- moments = pd.DataFrame({"report_id": [f"r{index}" for index in range(23)], "label": [1] * 3 + [0] * 20})+def _dated_moments(labels_by_day: dict[int, list[int]]) -> pd.DataFrame:+ rows = [+ (f"r{day}-{index}", pd.Timestamp(D0, tz="UTC") + pd.Timedelta(days=day, hours=index % 20), label)+ for day, labels in labels_by_day.items()+ for index, label in enumerate(labels)+ ]+ return pd.DataFrame(rows, columns=["report_id", "report_created_at", "label"])- capped = cap_examples(moments, 10)- assert (len(capped), capped["label"].sum()) == (10, 3)- assert capped.equals(cap_examples(moments, 10))+ "limit,expected_days",+ [+ (None, {0, 1, 2}),+ (100, {0, 1, 2}),+ # Days 2 and 1 fit in 12 rows; day 0 would push the total past the budget.+ (12, {1, 2}),+ # Day 1 does not fit whole, so it goes rather than a subset of its reports.+ (7, {2}),+ # The newest day alone exceeds the budget and is still kept, so the head has something to fit.+ (3, {2}),+ ],+)+def test_cap_examples_keeps_whole_days_newest_first(limit, expected_days):+ # Day 0 is rich in positives, so a positive-keeping sample would raise the rate of what is kept.+ moments = _dated_moments({0: [1] * 6 + [0] * 4, 1: [1] + [0] * 5, 2: [1] + [0] * 5})++ capped = cap_examples(moments, limit)++ kept_days = set(pd.to_datetime(capped["report_created_at"]).dt.date - D0)+ assert {delta.days for delta in kept_days} == expected_days+ source_days = (pd.to_datetime(moments["report_created_at"]).dt.date - D0).map(lambda delta: delta.days)+ population = moments[source_days.isin(expected_days)]+ assert len(capped) == len(population)+ assert capped["label"].mean() == pytest.approx(population["label"].mean())assert cap_examples(moments, None) is moments- # A head with more positives than the budget is not the case the budget is for.- assert cap_examples(moments, 2)["label"].tolist() == [1, 1, 1]def test_score_pool_scores_every_newborn_even_without_a_vector():diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pyindex e668bbe72ac9..ab97449841ca 100644--- a/products/signals/dags/inbox_ranking/training/dag.py+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -104,10 +104,11 @@ from products.signals.dags.inbox_ranking.training.examples import (BASE_STATE_COLUMNS,PROVENANCE_LABEL_COLUMNS,PROVENANCE_STATE_COLUMNS,+ HeadExamples,Snapshot,assemble_snapshot,birth_day_positives,- build_examples,+ build_head_examples,example_columns,point_in_time_mask,reports_missing_birth_snapshot,@@ -132,8 +133,9 @@ from products.signals.dags.inbox_ranking.training.telemetry import ()from products.signals.dags.inbox_ranking.training.train import (XGB_PARAMS,+ HoldoutGrade,TrainedHead,- booster_holdout_auc,+ booster_holdout_grade,holdout_calibration_rows,train_head,)@@ -352,8 +354,26 @@ def embeddings_extras(return extras-def examples_table(examples: pd.DataFrame, feature_set: FeatureSet) -> pa.Table:- return pa.Table.from_pandas(examples[list(example_columns(feature_set))], preserve_index=False)+# Parquet schema metadata key of the examples object that carries each head's example window.+EXAMPLE_WINDOWS_METADATA_KEY = b"inbox_ranking_example_windows"+++def examples_table(+ examples: pd.DataFrame, feature_set: FeatureSet, windows: Mapping[str, Mapping[str, object]] | None = None+) -> pa.Table:+ table = pa.Table.from_pandas(examples[list(example_columns(feature_set))], preserve_index=False)+ if windows is None:+ return table+ return table.replace_schema_metadata(+ {**(table.schema.metadata or {}), EXAMPLE_WINDOWS_METADATA_KEY: json.dumps(windows).encode()}+ )+++def example_windows(table: pa.Table) -> dict[str, dict[str, object]]:+ """Each head's example window as the examples asset wrote it. An object written before the+ window was recorded carries none, so its heads record no window."""+ raw = (table.schema.metadata or {}).get(EXAMPLE_WINDOWS_METADATA_KEY)+ return json.loads(raw) if raw else {}# The examples for dt=D read every snapshot back to D-lookback. The default same-partition mapping@@ -453,7 +473,10 @@ def _write_examples() -> dict[str, dagster.MetadataValue]:"""One feature set's examples for the partition, as its own object and its own events, withthe asset metadata to record for it."""- per_head = {head.name: build_examples(snapshots, head, feature_set, extras) for head in HEADS}+ built: dict[str, HeadExamples] = {+ head.name: build_head_examples(snapshots, head, feature_set, extras) for head in HEADS+ }+ per_head = {name: head_examples.examples for name, head_examples in built.items()}examples = (pd.concat(per_head.values(), ignore_index=True)if per_head@@ -461,14 +484,17 @@ def _write_examples()key = examples_object_key(prefix, feature_set.name, partition_key)- write_parquet(client, bucket, key, examples_table(examples, feature_set), snapshot_date=partition_key)+ windows = {name: head_examples.window() for name, head_examples in built.items()}+ write_parquet(client, bucket, key, examples_table(examples, feature_set, windows), snapshot_date=partition_key)counts = {name: HeadExampleCounts(- rows=len(frame),- positives=int(frame["label"].sum()),- birth_day_positives=birth_day_positives(frame),+ rows=len(head_examples.examples),+ positives=int(head_examples.examples["label"].sum()),+ birth_day_positives=birth_day_positives(head_examples.examples),+ example_window_start=head_examples.window_start,+ example_cap_bound=head_examples.cap_bound,)- for name, frame in per_head.items()+ for name, head_examples in built.items()}metadata: dict[str, dagster.MetadataValue] = {f"{feature_set.name}_rows": dagster.MetadataValue.int(len(examples)),@@ -510,6 +536,7 @@ def candidate_metadata(skipped: list[str],trained_at: datetime.datetime,run_id: str,+ windows: Mapping[str, Mapping[str, object]] | None = None,) -> dict[str, Any]:return {"model_name": model_name,@@ -529,9 +556,15 @@ def candidate_metadata("lookback_days": settings.INBOX_RANKING_TRAINING_LOOKBACK_DAYS,"holdout_days": settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS,"xgb_params": XGB_PARAMS,+ # Per head: the cohort a probability is conditioned on, its horizon, and the report-creation+ # window its examples cover, so a stored score says what it means without the code."heads": [head.metrics.as_dict()| {+ "cohort": HEADS_BY_NAME[head.head].cohort.__name__,+ "horizon_days": HEADS_BY_NAME[head.head].horizon_days,+ "example_window_start": (windows or {}).get(head.head, {}).get("example_window_start"),+ "example_cap_bound": (windows or {}).get(head.head, {}).get("example_cap_bound"),"file": f"{head.head}.ubj","holdout_file": f"{head.head}.holdout.ubj" if head.holdout_booster_ubj is not None else None,}@@ -542,7 +575,7 @@ def candidate_metadata(}-def paired_champion_aucs(+def paired_champion_grades(client,bucket: str,prefix: str,@@ -551,11 +584,11 @@ def paired_champion_aucs(*,feature_set: FeatureSet,holdout_days: int,-) -> dict[str, float]:+) -> dict[str, HoldoutGrade]:"""The champion's readable heads graded on the candidate's holdout, through the champion's savedholdout boosters. Heads without a saved holdout booster are left out and fall back to thechampion's stored AUC in `decide_promotion`."""- aucs: dict[str, float] = {}+ grades: dict[str, HoldoutGrade] = {}for entry in champion.get("heads", []):head = HEADS_BY_NAME.get(entry.get("head"))if head is None or not entry.get("readable") or not entry.get("holdout_file"):@@ -567,12 +600,12 @@ def paired_champion_aucs()if body is None:continue- auc = booster_holdout_auc(+ grade = booster_holdout_grade(body, examples, head, feature_names=feature_set.feature_names, holdout_days=holdout_days)- if auc is not None:- aucs[head.name] = auc- return aucs+ if grade is not None:+ grades[head.name] = grade+ return grades@dagster.asset(name="inbox_ranking_model_candidate", deps=[EXAMPLES_TABLE], **COMMON_ASSET_KWARGS)@@ -613,6 +646,7 @@ def _train_candidate(f"no {feature_set.name} examples for dt={partition_key}; {family.name} keeps this partition as it stands")return {f"{family.name}_skipped": dagster.MetadataValue.bool(True)}+ windows = example_windows(table)examples = table.to_pandas()trained: list[TrainedHead] = []skipped: list[str] = []@@ -647,6 +681,7 @@ def _train_candidate(skipped=skipped,trained_at=datetime.datetime.now(datetime.UTC),run_id=context.run.run_id,+ windows=windows,)metadata_key = model_object_key(prefix, family.name, partition_key, METADATA_FILE)_put_json(client, bucket, metadata_key, metadata)@@ -724,6 +759,7 @@ def _decide_champion(champion_key = champion_object_key(prefix, family.name)champion = _read_json_if_exists(client, bucket, champion_key)champion_aucs: dict[str, float] = {}+ champion_eces: dict[str, float] = {}if champion is not None:champion_feature_set = model_feature_set(champion)if champion_feature_set is None:@@ -743,7 +779,7 @@ def _decide_champion(f"the {family.name} champion is compared on its stored AUC")else:- champion_aucs = paired_champion_aucs(+ grades = paired_champion_grades(client,bucket,prefix,@@ -752,13 +788,23 @@ def _decide_champion(feature_set=champion_feature_set,holdout_days=settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS,)- context.log.info(f"{family.name} champion {champion['model_version']} on this holdout: {champion_aucs}")+ champion_aucs = {head: grade.auc for head, grade in grades.items() if grade.auc is not None}+ champion_eces = {+ head: grade.expected_calibration_error+ for head, grade in grades.items()+ if grade.expected_calibration_error is not None+ }+ context.log.info(+ f"{family.name} champion {champion['model_version']} on this holdout: "+ f"AUC {champion_aucs}, ECE {champion_eces}"+ )decision = decide_promotion(candidate,champion,now=datetime.datetime.now(datetime.UTC),min_days_between=settings.INBOX_RANKING_PROMOTION_MIN_DAYS,champion_aucs=champion_aucs,+ champion_eces=champion_eces,)context.log.info(f"{family.name} promotion decision for dt={partition_key}: promote={decision.promote} ({decision.reason})"@@ -797,6 +843,7 @@ def _decide_champion(champion_version=champion_version,incumbent_champion_version=incumbent_champion_version,champion_aucs=champion_aucs,+ champion_eces=champion_eces,)],)@@ -808,6 +855,10 @@ def _decide_champion(f"{family.name}_champion_{head}_auc_on_this_holdout": dagster.MetadataValue.float(auc)for head, auc in champion_aucs.items()},+ **{+ f"{family.name}_champion_{head}_ece_on_this_holdout": dagster.MetadataValue.float(ece)+ for head, ece in champion_eces.items()+ },f"{family.name}_incumbent_champion_version": dagster.MetadataValue.text(incumbent_champion_version),f"{family.name}_champion_version": dagster.MetadataValue.text(champion_version),}diff --git a/products/signals/dags/inbox_ranking/training/examples.py b/products/signals/dags/inbox_ranking/training/examples.pyindex 400f2c6fe7d7..e16339a75b2c 100644--- a/products/signals/dags/inbox_ranking/training/examples.py+++ b/products/signals/dags/inbox_ranking/training/examples.py@@ -27,7 +27,9 @@ with no label event gets LABEL_DEFAULTS, so never-engaged reports are negativesA set may ask for the scoring-moment grain instead (one row per report per snapshot, whose label isa hazard conditional on the report still being live) or the report grain (the first snapshot of thewindow where the report is a usable moment), and cap the rows one head keeps. Both knobs live on-the `FeatureSet`, because the examples object is per set.+the `FeatureSet`, because the examples object is per set. The cap limits history, not rows inside a+day: it keeps whole report-creation days, newest first, so the kept label rate is the population+rate of those days and the scores stay calibrated."""import datetime@@ -56,10 +58,6 @@ PROVENANCE_LABEL_COLUMNS = ("latest_status_event", "status_event_team_id")# than this is a backfill that carries current Postgres state, not the state as of the snapshot.STATE_LAG_LIMIT = datetime.timedelta(days=2)-# Fixed, so a re-run of a partition keeps the same rows under a row budget and two candidates of the-# same day are fit on one example set.-EXAMPLE_SAMPLE_SEED = 0-def state_columns(feature_set: FeatureSet) -> tuple[str, ...]:"""The report-state columns to read for `feature_set`: the base ones plus its own."""@@ -178,9 +176,41 @@ def build_examples(The moments are chosen first and the features built second, so a set under a row budget builds1536 columns for the rows it keeps rather than for every row it then throws away."""+ return build_head_examples(snapshots, head, feature_set, extras).examples+++@frozen+class HeadExamples:+ """One head's examples and the report-creation window they cover."""++ examples: pd.DataFrame+ # The earliest report-creation day kept, or None when the head has no example.+ window_start: datetime.date | None+ # True when the row budget dropped at least one older day.+ cap_bound: bool++ def window(self) -> dict[str, object]:+ return {+ "example_window_start": self.window_start.isoformat() if self.window_start else None,+ "example_cap_bound": self.cap_bound,+ }+++def build_head_examples(+ snapshots: Mapping[datetime.date, Snapshot],+ head: Head,+ feature_set: FeatureSet,+ extras: Extras = NO_EXTRAS,+) -> HeadExamples:+ """`build_examples` with the window the row budget left, which the candidate records per head."""moments = example_moments(snapshots, head, feature_set, extras)kept = cap_examples(moments, feature_set.max_examples_per_head)- return _with_features(kept, snapshots, feature_set, extras)+ days = _creation_days(kept).dropna()+ return HeadExamples(+ examples=_with_features(kept, snapshots, feature_set, extras),+ window_start=days.min().date() if len(days) else None,+ cap_bound=len(kept) < len(moments),+ )def example_moments(@@ -281,22 +311,27 @@ def reports_missing_birth_snapshot(snapshots: Mapping[datetime.date, Snapshot],return sum(int(birth_day_mask(reports, date).sum()) for date in set(dates).difference(snapshots))+def _creation_days(moments: pd.DataFrame) -> pd.Series:+ return pd.to_datetime(moments["report_created_at"], utc=True).dt.floor("D")++def cap_examples(moments: pd.DataFrame, limit: int | None) -> pd.DataFrame:- """`moments` within `limit` rows, keeping every positive and a seeded sample of the negatives.+ """`moments` cut to the newest whole report-creation days that fit within `limit` rows.A row budget is how a wide set stays inside one partition's object and the training job's- runtime. Positives are the scarce side of every head here and AUC is rank-based, so spending- the budget on them costs the base rate the scores are calibrated to rather than the ranking read- the family exists for. Positives are kept whole even past the budget: a head with that many- positives is not the case the budget is for.+ runtime. The budget limits history: it keeps whole days, newest first, and never samples rows+ inside a day. A sample that keeps every positive raises the base rate the booster fits, so its+ scores overstate every probability. Whole days keep the population rate, keep the holdout a clean+ time split, and keep the population the sweep scores. The newest day is kept even when it alone+ exceeds `limit`, so a head never trains on nothing."""if limit is None or len(moments) <= limit:return moments- positives = moments[moments["label"] == 1]- negatives = moments[moments["label"] != 1]- room = max(limit - len(positives), 0)- sampled = negatives.sample(n=min(room, len(negatives)), random_state=EXAMPLE_SAMPLE_SEED)- return pd.concat([positives, sampled]).sort_index().reset_index(drop=True)+ days = _creation_days(moments)+ per_day = days.value_counts().sort_index(ascending=False)+ within = per_day.index[per_day.cumsum().to_numpy() <= limit]+ cutoff = within.min() if len(within) else per_day.index[0]+ return moments[days >= cutoff].reset_index(drop=True)def _with_features(diff --git a/products/signals/dags/inbox_ranking/training/promotion.py b/products/signals/dags/inbox_ranking/training/promotion.pyindex 63be0f07585c..37a95bba04f4 100644--- a/products/signals/dags/inbox_ranking/training/promotion.py+++ b/products/signals/dags/inbox_ranking/training/promotion.py@@ -6,6 +6,11 @@ read, has at least one readable head itself, and enough days have passed since tPure function over the two metadata records so the rule is testable without S3. The champion'sAUCs should be `champion_aucs`, its holdout booster graded on the candidate's holdout, so bothmodels are compared on one set of reports; the stored numbers are the fallback.++AUC reads the ranking only, so a candidate must also not be worse calibrated than the champion on+those heads. The champion's calibration error comes from `champion_eces`, graded on the candidate's+holdout the same way. There is no stored fallback: a champion's stored error was read on its own+holdout, which can hold a different base rate, so a head without a paired error skips this check."""import datetime@@ -17,6 +22,10 @@ from posthog.dataclasses import frozen# A candidate may be this much worse than the champion on a readable head and still promote: at# the readability floor the AUC's noise is about this size, so exact dominance would never trigger.AUC_TOLERANCE = 0.02+# A candidate's holdout calibration error may exceed the champion's paired one by this much and+# still promote. The error is in probability units and a decile read on one holdout is noisy by+# about this much at the readability floor.+ECE_TOLERANCE = 0.02@frozen@@ -40,8 +49,14 @@ def decide_promotion(now: datetime.datetime,min_days_between: int,champion_aucs: Mapping[str, float] | None = None,+ champion_eces: Mapping[str, float] | None = None,) -> PromotionDecision:candidate_aucs = _readable_aucs(candidate)+ candidate_eces = {+ head["head"]: float(head["holdout_expected_calibration_error"])+ for head in candidate.get("heads", [])+ if head.get("holdout_expected_calibration_error") is not None+ }if not candidate_aucs:return PromotionDecision(promote=False, reason="candidate has no readable head")if champion is None:@@ -70,4 +85,11 @@ def decide_promotion(return PromotionDecision(promote=False, reason=f"{head} regressed: {candidate_auc:.3f} vs champion {champion_auc:.3f}")+ champion_ece = (champion_eces or {}).get(head)+ candidate_ece = candidate_eces.get(head)+ if champion_ece is not None and candidate_ece is not None and candidate_ece > champion_ece + ECE_TOLERANCE:+ return PromotionDecision(+ promote=False,+ reason=f"{head} calibration regressed: ECE {candidate_ece:.3f} vs champion {champion_ece:.3f}",+ )return PromotionDecision(promote=True, reason="candidate at or above champion on every readable head")diff --git a/products/signals/dags/inbox_ranking/training/telemetry.py b/products/signals/dags/inbox_ranking/training/telemetry.pyindex 584d63599552..b9dabd008278 100644--- a/products/signals/dags/inbox_ranking/training/telemetry.py+++ b/products/signals/dags/inbox_ranking/training/telemetry.py@@ -67,6 +67,10 @@ class HeadExampleCounts:# Of the positives, how many sit on their report's birth day: most outcomes land there, so a# drop in this share is the first sign the birth-day rule stopped keeping them.birth_day_positives: int+ # The earliest report-creation day the head kept, and whether the row budget dropped older days,+ # so a chart shows when the budget starts to cut history.+ example_window_start: datetime.date | None+ example_cap_bound: booldef candidate_events(metadata: Mapping[str, Any]) -> list[TrainingEvent]:@@ -124,6 +128,10 @@ def examples_events("rows": counts.rows,"positives": counts.positives,"birth_day_positives": counts.birth_day_positives,+ "example_window_start": counts.example_window_start.isoformat()+ if counts.example_window_start+ else None,+ "example_cap_bound": counts.example_cap_bound,},)for head, counts in per_head.items()@@ -140,8 +148,9 @@ def promotion_event(champion_version: str,incumbent_champion_version: str,champion_aucs: Mapping[str, float],+ champion_eces: Mapping[str, float],) -> TrainingEvent:- """`champion_aucs` were scored by the incumbent on this candidate's holdout; after a promotion+ """`champion_aucs` and `champion_eces` were scored by the incumbent on this candidate's holdout; after a promotion`champion_version` is the candidate, so the incumbent is carried separately. Every version herebelongs to `model_name`: promotion compares a candidate to the champion of its own family."""return TrainingEvent(@@ -156,6 +165,7 @@ def promotion_event("champion_version": champion_version,"incumbent_champion_version": incumbent_champion_version,**{f"champion_{head}_auc_on_this_holdout": auc for head, auc in champion_aucs.items()},+ **{f"champion_{head}_ece_on_this_holdout": ece for head, ece in champion_eces.items()},},)diff --git a/products/signals/dags/inbox_ranking/training/train.py b/products/signals/dags/inbox_ranking/training/train.pyindex 880239cb2f7a..cfc042d16526 100644--- a/products/signals/dags/inbox_ranking/training/train.py+++ b/products/signals/dags/inbox_ranking/training/train.py@@ -69,9 +69,8 @@ class HeadMetrics:holdout_logloss: float | None = Noneholdout_positive_rate: float | None = None# The mean predicted score next to `holdout_positive_rate`, the rate it was predicting, and the- # decile error between them. Both read the rows the head was capped to, and `cap_examples` keeps- # every positive, so a family under a row budget reports its sample's raised rate. Read per family.- # Both also read the train-only fit, while the candidate that ships and the unseen side grades is+ # decile error between them. Both read the rows the head was capped to. `cap_examples` keeps whole+ # days, so the rate is the population rate of the kept window. Both also read the train-only fit, while the candidate that ships and the unseen side grades is# the refit on every row. A refit moves the predicted probabilities without moving their rank, so# part of a gap to the unseen numbers is the refit rather than holdout optimism.holdout_mean_score: float | None = None@@ -155,7 +154,8 @@ def train_head(if rows.empty:return Nonetest = holdout_mask(rows, holdout_days).to_numpy()- x = rows[list(feature_names)].astype(float)+ # float32 is what XGBoost bins internally, and it halves the largest allocation of a wide set.+ x = rows[list(feature_names)].astype(np.float32)y = rows["label"].to_numpy(dtype=int)x_train, y_train, x_test, y_test = x[~test], y[~test], x[test], y[test]if len(y_train) == 0 or y_train.sum() == 0 or y_train.sum() == len(y_train):@@ -221,11 +221,17 @@ def holdout_calibration_rows(trained: Sequence[TrainedHead]) -> list[dict[str, oreturn [row for model in trained for row in bucket_rows(model.calibration, {"head": model.head})]-def booster_holdout_auc(+@frozen+class HoldoutGrade:+ auc: float | None+ expected_calibration_error: float | None+++def booster_holdout_grade(booster_ubj: bytes, examples: pd.DataFrame, head: Head, *, feature_names: Sequence[str], holdout_days: int-) -> float | None:- """AUC of a saved booster on `head`'s holdout rows of `examples`: the same rows `train_head`- grades a candidate on, so a champion and a candidate can be compared on one set."""+) -> HoldoutGrade | None:+ """AUC and calibration error of a saved booster on `head`'s holdout rows of `examples`: the same+ rows `train_head` grades a candidate on, so a champion and a candidate can be compared on one set."""rows = examples[examples["head"] == head.name]if rows.empty:return None@@ -240,6 +246,10 @@ def booster_holdout_auc(names = list(booster.feature_names or feature_names)if any(name not in rows for name in names):return None- x = rows.loc[test, names].astype(float)+ x = rows.loc[test, names].astype(np.float32)y = rows.loc[test, "label"].to_numpy(dtype=int)- return _auc(y, booster.predict(xgb.DMatrix(x, feature_names=names)))+ scores = booster.predict(xgb.DMatrix(x, feature_names=names))+ return HoldoutGrade(+ auc=_auc(y, scores),+ expected_calibration_error=expected_calibration_error(calibration_buckets(y.astype(bool), scores)),+ )