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(signals): add the model_name family dimension to inbox ranking (#98324)

posthog[bot]ce6c7cf143de
diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.md
index a986bde3141b..fea8ae231bde 100644
--- a/products/signals/dags/inbox_ranking/AGENTS.md
+++ b/products/signals/dags/inbox_ranking/AGENTS.md
@@ -12,7 +12,9 @@ Read `README.md` first for what the dataset is and how partitions behave. This f
- `products/signals/backend/ranking/features.py` is the serving contract (it lives in the backend so the scoring sweep owns it and the dag imports it): the training code and the sweep both import `FEATURE_NAMES` / `feature_vector`, and the sweep refuses a booster whose `feature_names` or `feature_schema_version` disagree. Adding a feature means bumping `FEATURE_SCHEMA_VERSION`, and the sweep must be able to compute it from the `SignalReport` row at scoring time — nothing impression-derived, nothing that needs the label streams.
- `feature_vector` (one row, serving) and `feature_frame` (vectorized, training) must agree row for row; a test pins it. Change both together.
- Examples are scoring moments (every report × every snapshot), labeled from the snapshot `horizon_days` later. Keep the holdout cut by report; a row-level split leaks near-duplicate snapshots of the same report.
-- `inbox_ranking_models/v1/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). `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.
+- `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.
+- A re-run of `inbox_ranking_unseen_scores` that scores nothing is refused when the partition already holds rows, because the newborn state snapshot behind those rows ages out and the dt=D+horizon grade reads them. A partition trained before the per-family models layout has no candidate to load, so it hits this; delete the object by hand to replace it deliberately.
+- `model_name` is the model family, and every model object, scored row, grade and event carries it. Adding a family means an entry in `MODEL_FAMILIES` (`training/unseen.py`) and a trainer that writes `metadata.json` under the family's prefix; the loader, the grader and the events then need no change. Promotion stays inside a family, so a family never takes another family's `champion.json`. Do not fold the family into `model_version`, which the dashboard filters as a date.
- The champion is compared to a candidate on the candidate's holdout, through the champion's `<head>.holdout.ubj` (the train-only fit). Keep writing that file: without it the gate falls back to the champion's stored AUC, which was measured on a different set of reports.
- The example builder reads labels aligned to the state spine (`assemble_snapshot`): no label row means all-zero labels, not "absent". It drops rows whose `features_observed_at` is a backfill (`STATE_LAG_LIMIT`) and, for status-derived heads, rows that fail `label_provenance_ok`.
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.md
index f483698a818e..aff9dbbab65c 100644
--- a/products/signals/dags/inbox_ranking/README.md
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -64,18 +64,19 @@ The first four are report grain and land in one table. `inbox_signal_embeddings`
```text
s3://<bucket>/<prefix>/
├── inbox_ranking_training_examples/v1/dt=YYYY-MM-DD/ # scoring-moment examples, all heads, one parquet
-├── inbox_ranking_models/v1/
+├── inbox_ranking_models/v1/<model_name>/
│ ├── dt=YYYY-MM-DD/<head>.ubj + <head>.holdout.ubj # the day's candidate: serving fit + train-only fit
│ │ + metadata.json # (a re-run replaces this prefix in full)
│ └── champion.json # pointer the scoring sweep loads (the only object written across partitions)
└── inbox_ranking_unseen_scores/v1/dt=YYYY-MM-DD/ # the day's models on the reports born that day
```
+- **A model is a `(model_name, model_version, model_role)`.** `model_name` is the family: which features and which learner, `tabular_xgb` for the per-head XGBoost trained here. `model_version` is the partition day it was fit on, and `model_role` is `candidate` or `champion`. Each family owns a prefix under the models path and its own `champion.json`, so two families trained on the same day cannot collide, and promotion stays inside a family. A richer family is a second candidate graded on the same unseen rows, not a competitor for the tabular family's pointer.
- **Examples are scoring moments, not reports.** For partition `dt=D` the examples asset reads the report-state and labels snapshots `dt=D-lookback..D` and emits one row per (report, snapshot) whose head label is still 0 on that snapshot, labeled from the snapshot `horizon_days` later (3 for open, 7 for action / dismiss_wrong / pr_created / discuss, 14 for pr_merged / refund). Features are 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. This is the serving situation replayed over history; it measured better than one row per report on the engagement heads.
- **Serving population caveat.** Training keeps only moments where the head's outcome has not happened yet, but the scoring sweep cannot see outcome state, so it also scores reports that were already opened or acted on. `p_open` on an already-opened report is undefined; the shadow eval joins scores as of impression time, which keeps the read honest. Stopping a head once its outcome is observed is a sweep-side change.
- **Features are tabular only in v0** (`products/signals/backend/ranking/features.py`: 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.
- **Candidate**: per-head XGBoost with fixed params, holdout = the last `holdout_days` of reports (cut by report, never by row), AUC + a label-permutation null. 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` and `inbox_ranking_candidate_trained` once per head (`head`, holdout / train AUC, average precision, logloss, positive rate, the permutation-null mean and spread, counts, `readable`) and `inbox_ranking_promotion_decided` once per run, all carrying `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.
+- **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` and `inbox_ranking_candidate_trained` once per head (`head`, holdout / train AUC, average precision, logloss, positive rate, the permutation-null mean and spread, counts, `readable`) and `inbox_ranking_promotion_decided` 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**: `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`.
### The unseen read
@@ -83,8 +84,8 @@ s3://<bucket>/<prefix>/
The holdout grades the recipe, not the model that ships: the shipped booster is refit on train plus holdout, and every holdout row comes from the same snapshots the trainer saw.
Two assets add the missing number, an offline batch proxy for performance on reports the model never saw.
-- **`inbox_ranking_unseen_scores` (dt=D)** takes the dt=D state rows of the reports **created on D**, the pool the events tag `pool=newborn`. A newborn has no scoring moment before D, and the dt=D examples stop at D minus the head's horizon (3 days at the shortest), so no example can cover it: leakage-freedom is structural, not a property of what the example builder did that day. The set difference against the examples Parquet stays as a runtime guard — a non-empty overlap fails the asset instead of publishing the number. Every newborn is scored, not a sample, with the day's candidate and, when the pointer names a different version, the champion. Only readable heads are scored, and a model whose feature contract has moved on is logged and left out. One Parquet row per (report, model, head) carries the score, `age_hours`, `label_at_scoring` (the head outcome that had already happened when the report was scored), and `pool`, the pool definition that produced the row.
-- **`inbox_ranking_unseen_graded` (dt=D)** reads each head's scores back from `D - horizon_days` and grades them against the dt=D labels. It keeps the rows whose outcome had not already happened at scoring time and whose cohort holds at D, reads the outcome with `Head.label`, and reports the AUC per model and head next to `recency_auc`, the AUC of ranking newest first on the same outcomes.
+- **`inbox_ranking_unseen_scores` (dt=D)** takes the dt=D state rows of the reports **created on D**, the pool the events tag `pool=newborn`. A newborn has no scoring moment before D, and the dt=D examples stop at D minus the head's horizon (3 days at the shortest), so no example can cover it: leakage-freedom is structural, not a property of what the example builder did that day. The set difference against the examples Parquet stays as a runtime guard — a non-empty overlap fails the asset instead of publishing the number. Every newborn is scored, not a sample, with the day's candidate and, when the pointer names a different version, the champion. Only readable heads are scored, and a model whose feature contract has moved on is logged and left out. One Parquet row per (report, model, head) carries the score, `age_hours`, `label_at_scoring` (the head outcome that had already happened when the report was scored), `model_name`, and `pool`, the pool definition that produced the row. A re-run that scores nothing is refused when the partition already holds rows, so a day with no loadable model cannot erase the scores a later grade reads. A scores object written before `model_name` existed reads as `tabular_xgb`, the same way one written before `pool` existed keeps the old pool name.
+- **`inbox_ranking_unseen_graded` (dt=D)** reads each head's scores back from `D - horizon_days` and grades them against the dt=D labels. It keeps the rows whose outcome had not already happened at scoring time and whose cohort holds at D, reads the outcome with `Head.label`, and reports the AUC per model and head next to two comparison lines on the same rows: `recency_auc`, the AUC of ranking newest first, and `null_auc` / `null_auc_std`, the mean and spread of the AUC over seeded permutations of the scores. The mean is 0.5 by construction; the spread is the noise band a per-day AUC has to clear before a gap between two families means anything.
Because the cohort, the label, the horizon and the provenance rules are the trainer's own, the unseen AUC is directly comparable to the holdout AUC of the same head and model version. The gap between the two series is the overfitting read the promotion gate cannot see.
@@ -116,11 +117,11 @@ The training job is S3-only, so it can run on a laptop against copies of the pro
The schedule is stopped outside prod US, so nothing runs unasked. If the run sits in `QUEUED`, check the daemon log for `Maximum is 10, won't launch more`: runs from a killed `dagster dev` stay `STARTED` forever and count against the local queue. Terminate them from the Runs page (force termination).
-4. Read the result from `s3://posthog/inbox_ranking/inbox_ranking_models/v1/dt=<day>/metadata.json` (per-head AUCs, readability); the examples are at `s3://posthog/inbox_ranking/inbox_ranking_training_examples/v1/dt=<day>/part-00000.parquet`:
+4. Read the result from `s3://posthog/inbox_ranking/inbox_ranking_models/v1/tabular_xgb/dt=<day>/metadata.json` (per-head AUCs, readability); the examples are at `s3://posthog/inbox_ranking/inbox_ranking_training_examples/v1/dt=<day>/part-00000.parquet`:
```bash
AWS_ACCESS_KEY_ID=object_storage_root_user AWS_SECRET_ACCESS_KEY=object_storage_root_password \
- aws --endpoint-url http://localhost:19000 s3 cp s3://posthog/inbox_ranking/inbox_ranking_models/v1/dt=2026-08-25/metadata.json -
+ aws --endpoint-url http://localhost:19000 s3 cp s3://posthog/inbox_ranking/inbox_ranking_models/v1/tabular_xgb/dt=2026-08-25/metadata.json -
```
Nothing here touches the prod bucket: the reader credential is read-only and the dag writes only to the local bucket.
diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.py
index f2bb8f4ae14e..8b0d7d8e6386 100644
--- a/products/signals/dags/inbox_ranking/tests/test_training.py
+++ b/products/signals/dags/inbox_ranking/tests/test_training.py
@@ -1,4 +1,5 @@
import io
+import json
import math
import datetime
from typing import Any
@@ -15,15 +16,22 @@ from botocore.exceptions import ClientError
from posthog import settings
-from products.signals.backend.ranking.features import FEATURE_NAMES, feature_frame, feature_vector
+from products.signals.backend.ranking.features import (
+ FEATURE_NAMES,
+ FEATURE_SCHEMA_VERSION,
+ feature_frame,
+ feature_vector,
+)
from products.signals.dags.inbox_ranking.common import partition_object_key
from products.signals.dags.inbox_ranking.dataset.dag import LABELS_TABLE, STATE_TABLE
from products.signals.dags.inbox_ranking.training.dag import (
+ METADATA_FILE,
_delete_other_objects,
champion_object_key,
grade_metadata,
inbox_ranking_training_examples,
load_snapshots,
+ load_unseen_models,
model_object_key,
snapshot_dates,
)
@@ -55,6 +63,9 @@ from products.signals.dags.inbox_ranking.training.unseen import (
CANDIDATE_ROLE,
LEGACY_POOL_NAME,
POOL_NAME,
+ TABULAR_MODEL_NAME,
+ chance_band,
+ empty_scores_write_allowed,
graded_rows,
head_grades,
leaked_report_ids,
@@ -62,8 +73,12 @@ from products.signals.dags.inbox_ranking.training.unseen import (
score_event_rows,
scored_pool,
unseen_pool,
+ with_model_names,
)
+# No trainer writes this family yet: it stands in for a second family in the grouping tests.
+EMBEDDINGS_MODEL_NAME = "report_embeddings"
+
D0 = datetime.date(2026, 8, 10)
NOW = datetime.datetime(2026, 8, 20, tzinfo=datetime.UTC)
@@ -475,6 +490,7 @@ def _scores(report_ids: list[str], **overrides) -> pd.DataFrame:
"report_created_at": [pd.Timestamp("2026-08-09T12:00:00Z")] * n,
"snapshot_date": [D0] * n,
"pool": [POOL_NAME] * n,
+ "model_name": [TABULAR_MODEL_NAME] * n,
"model_version": ["2026-08-10"] * n,
"model_role": [CANDIDATE_ROLE] * n,
"feature_schema_version": [1] * n,
@@ -542,13 +558,14 @@ def test_grading_keeps_the_scoring_moment_rows_and_reads_the_outcome_later():
assert graded.loc[["b", "c", "d"], "outcome"].isna().all()
-def test_head_grades_report_counts_and_a_null_auc_on_a_single_class():
+def test_head_grades_report_counts_and_an_undefined_auc_on_a_single_class():
head = HEADS_BY_NAME["open"]
labels = _labels(["a", "e"], open_count=[1, 0])
two_classes = graded_rows(_scores(["a", "e"], score=[0.9, 0.1]), labels, head)
(grade,) = head_grades(two_classes, head, pool=POOL_NAME, scoring_partition="2026-08-10")
assert (grade.rows, grade.positives, grade.auc, grade.base_rate) == (2, 1, 1.0, 0.5)
assert grade.recency_auc == 0.5 # both reports are the same age, so newest-first cannot rank them
+ assert grade.null_auc is not None
# A head with rows but one outcome class still reports, so the daily series has no gap.
(single_class,) = head_grades(
graded_rows(_scores(["e"]), _labels(["e"], open_count=[0]), head),
@@ -557,11 +574,13 @@ def test_head_grades_report_counts_and_a_null_auc_on_a_single_class():
scoring_partition="2026-08-10",
)
assert (single_class.rows, single_class.positives, single_class.auc) == (1, 0, None)
- # Counts are ints and the null AUC is dropped: the graded asset writes these as Dagster metadata.
+ assert (single_class.null_auc, single_class.null_auc_std) == (None, None)
+ # Counts are ints and the undefined AUC is dropped: the graded asset writes these as Dagster
+ # metadata. The family is in the key, so a second family cannot overwrite the first's entries.
metadata = grade_metadata([grade])
- assert metadata["open_candidate_rows"] == dagster.MetadataValue.int(2)
- assert metadata["open_candidate_auc"] == dagster.MetadataValue.float(1.0)
- assert "open_candidate_auc" not in grade_metadata([single_class])
+ assert metadata["open_tabular_xgb_candidate_rows"] == dagster.MetadataValue.int(2)
+ assert metadata["open_tabular_xgb_candidate_auc"] == dagster.MetadataValue.float(1.0)
+ assert "open_tabular_xgb_candidate_auc" not in grade_metadata([single_class])
@pytest.mark.parametrize(
@@ -577,6 +596,110 @@ def test_scored_pool_names_the_definition_a_scores_object_was_written_under(scor
assert scored_pool(scores) == expected
+ "scores,expected",
+ [
+ (_scores(["a"]), TABULAR_MODEL_NAME),
+ (_scores(["a"], model_name=[EMBEDDINGS_MODEL_NAME]), EMBEDDINGS_MODEL_NAME),
+ # A pre-column object is still in the grader's 14-day window, and a null name splits the series.
+ (_scores(["a"]).drop(columns=["model_name"]), TABULAR_MODEL_NAME),
+ (_scores(["a"], model_name=[None]), TABULAR_MODEL_NAME),
+ ],
+)
+def test_scores_written_before_the_family_dimension_read_as_the_tabular_family(scores, expected):
+ assert with_model_names(scores)["model_name"].tolist() == [expected]
+
+
+def test_head_grades_keep_two_families_apart_on_the_same_rows():
+ # A grade keyed on version and role alone would pool two families into one meaningless AUC.
+ head = HEADS_BY_NAME["open"]
+ labels = _labels(["a", "e"], open_count=[1, 0])
+ tabular = _scores(["a", "e"], score=[0.9, 0.1])
+ embeddings = _scores(["a", "e"], score=[0.1, 0.9], model_name=[EMBEDDINGS_MODEL_NAME] * 2)
+ graded = pd.concat([graded_rows(tabular, labels, head), graded_rows(embeddings, labels, head)], ignore_index=True)
+ grades = head_grades(graded, head, pool=POOL_NAME, scoring_partition="2026-08-10")
+ assert [(grade.model_name, grade.model_version, grade.auc) for grade in grades] == [
+ (EMBEDDINGS_MODEL_NAME, "2026-08-10", 0.0),
+ (TABULAR_MODEL_NAME, "2026-08-10", 1.0),
+ ]
+
+
+def test_chance_band_is_seeded_and_sizes_the_noise_of_the_rows_it_grades():
+ # The band must not move between grades of the same rows, and must widen as the rows thin out.
+ rng = np.random.default_rng(7)
+ outcomes = np.array([True, False] * 40)
+ scores = rng.random(80)
+ band = chance_band(outcomes, scores)
+ assert band == chance_band(outcomes, scores)
+ spread = band.auc_std
+ assert spread is not None and spread > 0
+ thin_band = chance_band(outcomes[:8], scores[:8])
+ assert thin_band.auc_std is not None and thin_band.auc_std > spread
+ # No band where the AUC itself is undefined, so the chance line has the same gaps as `auc`.
+ assert chance_band(np.array([True, True]), scores[:2]) == chance_band(np.array([]), np.array([]))
+
+
[email protected]("rows", [80, 8, 2])
+def test_chance_band_holds_the_line_at_half_however_few_rows_it_grades(rows):
+ # A sampled mean drifts off 0.5 on a thin head, and two families on the same rows would then
+ # report chance lines differing by nothing but their shuffles. Two rows is the extreme case.
+ rng = np.random.default_rng(7)
+ outcomes = np.array([True, False] * (rows // 2))
+ assert chance_band(outcomes, rng.random(rows)).auc == pytest.approx(0.5, abs=1e-9)
+
+
+ "existing_row_count,expected",
+ [
+ (None, True), # no object at all, or one written before the row-count stamp
+ (0, True),
+ (12, False),
+ ],
+)
+def test_an_empty_scores_write_is_refused_over_a_partition_that_holds_rows(existing_row_count, expected):
+ # A partition whose candidate predates the family layout loads no model and scores nothing.
+ # Overwriting it would destroy rows the later grade reads and the state snapshot cannot rebuild.
+ assert empty_scores_write_allowed(existing_row_count) is expected
+
+
+class _ModelStoreS3:
+ def __init__(self, objects: dict[str, bytes]):
+ self.objects = objects
+
+ def get_object(self, *, Bucket, Key):
+ if Key not in self.objects:
+ raise ClientError({"Error": {"Code": "NoSuchKey"}}, "GetObject")
+ return {"Body": io.BytesIO(self.objects[Key])}
+
+
+def test_load_unseen_models_skips_a_family_with_nothing_to_score_that_day(monkeypatch):
+ # A family registered before its first trainer run, or one whose candidate failed, must cost only its own line.
+ partition_key = "2026-08-19"
+ metadata = {
+ "model_name": TABULAR_MODEL_NAME,
+ "model_version": partition_key,
+ "feature_schema_version": FEATURE_SCHEMA_VERSION,
+ "feature_names": list(FEATURE_NAMES),
+ "heads": [{"head": "open", "readable": True, "file": "open.ubj"}],
+ }
+ client = _ModelStoreS3(
+ {
+ model_object_key("inbox_ranking", TABULAR_MODEL_NAME, partition_key, METADATA_FILE): json.dumps(
+ metadata
+ ).encode(),
+ model_object_key("inbox_ranking", TABULAR_MODEL_NAME, partition_key, "open.ubj"): b"booster",
+ }
+ )
+ monkeypatch.setattr(
+ "products.signals.dags.inbox_ranking.training.dag.MODEL_FAMILIES",
+ (EMBEDDINGS_MODEL_NAME, TABULAR_MODEL_NAME),
+ )
+ models = load_unseen_models(dagster.build_asset_context(), client, "bucket", "inbox_ranking", partition_key)
+ assert [(model.model_name, model.model_role, sorted(model.boosters)) for model in models] == [
+ (TABULAR_MODEL_NAME, CANDIDATE_ROLE, ["open"])
+ ]
+
+
@pytest.mark.parametrize(
"cloud,debug,expected_distinct_id,expected_environment",
[
@@ -617,6 +740,7 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
# The per-head events are what the project-2 insights break down on; dropping the head
# property, the partition-day timestamp, or the person-profile opt-out breaks every chart.
metadata = {
+ "model_name": TABULAR_MODEL_NAME,
"model_version": "2026-08-25",
"run_id": "run-1",
"dataset_version": "v1",
@@ -644,6 +768,7 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
promotion_event(
partition_key="2026-08-25",
run_id="run-1",
+ model_name=TABULAR_MODEL_NAME,
decision=PromotionDecision(promote=True, reason="no champion yet"),
promoted=False,
champion_version="none",
@@ -667,6 +792,15 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
assert call["timestamp"] == datetime.datetime(2026, 8, 25, 12, tzinfo=datetime.UTC)
assert call["properties"]["$process_person_profile"] is False
assert call["properties"]["model_version"] == "2026-08-25"
+ # Every model event breaks down on the family; the examples event is per feature set instead.
+ for event_name in (
+ "inbox_ranking_candidate_trained",
+ "inbox_ranking_promotion_decided",
+ "inbox_ranking_unseen_report_scored",
+ "inbox_ranking_unseen_head_graded",
+ "inbox_ranking_unseen_report_graded",
+ ):
+ assert all(call["properties"]["model_name"] == TABULAR_MODEL_NAME for call in by_event[event_name])
candidates = by_event["inbox_ranking_candidate_trained"]
assert [c["properties"]["head"] for c in candidates] == ["open", "action", "dismiss_wrong"]
assert candidates[0]["properties"]["holdout_auc"] == 0.67
@@ -814,11 +948,12 @@ class _FakeS3:
def test_rerun_removes_stale_head_files_but_keeps_what_it_just_wrote():
- folder = model_object_key("inbox_ranking", "2026-08-19", "")
+ folder = model_object_key("inbox_ranking", TABULAR_MODEL_NAME, "2026-08-19", "")
+ champion = champion_object_key("inbox_ranking", TABULAR_MODEL_NAME)
written = {folder + "open.ubj", folder + "open.holdout.ubj", folder + "metadata.json"}
- client = _FakeS3([*written, folder + "action.ubj", "inbox_ranking/inbox_ranking_models/v1/champion.json"])
+ client = _FakeS3([*written, folder + "action.ubj", champion])
assert _delete_other_objects(client, "bucket", folder, written) == [folder + "action.ubj"]
- assert client.keys == written | {"inbox_ranking/inbox_ranking_models/v1/champion.json"}
+ assert client.keys == written | {champion}
class _EmptyS3:
@@ -843,12 +978,15 @@ def test_examples_depend_on_the_whole_lookback_window():
def test_model_key_layout_is_stable():
- # The scoring sweep resolves the champion pointer and booster files by these keys.
+ # The scoring sweep resolves these keys, and a prefix per family stops two families colliding.
+ assert (
+ model_object_key("inbox_ranking", TABULAR_MODEL_NAME, "2026-08-19", "open.ubj")
+ == "inbox_ranking/inbox_ranking_models/v1/tabular_xgb/dt=2026-08-19/open.ubj"
+ )
assert (
- model_object_key("inbox_ranking", "2026-08-19", "open.ubj")
- == "inbox_ranking/inbox_ranking_models/v1/dt=2026-08-19/open.ubj"
+ champion_object_key("inbox_ranking", TABULAR_MODEL_NAME)
+ == "inbox_ranking/inbox_ranking_models/v1/tabular_xgb/champion.json"
)
- assert champion_object_key("inbox_ranking") == "inbox_ranking/inbox_ranking_models/v1/champion.json"
assert snapshot_dates("2026-08-19", 2) == [
datetime.date(2026, 8, 17),
datetime.date(2026, 8, 18),
diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.py
index 4f973299a3e5..362db2a08d20 100644
--- a/products/signals/dags/inbox_ranking/training/dag.py
+++ b/products/signals/dags/inbox_ranking/training/dag.py
@@ -2,21 +2,23 @@
Three assets on the same daily partition as the dataset dag, each writing under the dataset prefix:
- inbox_ranking_training_examples/v1/dt=D/ scoring-moment examples over the trailing snapshots
- inbox_ranking_models/v1/dt=D/<head>.ubj one booster per head + metadata.json (the candidate)
- inbox_ranking_models/v1/champion.json pointer to the model version the scoring sweep loads
- inbox_ranking_unseen_scores/v1/dt=D/ the day's models on the reports born that day
+ inbox_ranking_training_examples/v1/dt=D/ scoring-moment examples over the trailing snapshots
+ inbox_ranking_models/v1/<name>/dt=D/<head>.ubj one booster per head + metadata.json (the candidate)
+ inbox_ranking_models/v1/<name>/champion.json pointer to the version the scoring sweep loads
+ inbox_ranking_unseen_scores/v1/dt=D/ the day's models on the reports born that day
Partition dt=D trains on the report-state/labels snapshots dt=D-lookback..D (issue 13's
scoring-moment join, `training/examples.py`), grades each head on the last `holdout_days` of
reports, and refits on everything. The champion asset applies `promotion.decide_promotion`; it
rewrites the pointer only when `INBOX_RANKING_AUTO_PROMOTE` is on, otherwise it logs the decision
so the daily candidate series doubles as monitoring while the first shadow read runs against a
-frozen champion. Every candidate is kept under `models/v1/dt=D/`; a re-run of a partition replaces
+frozen champion. Every candidate is kept under `models/v1/<model_name>/dt=D/`; a re-run of a partition replaces
that prefix in full (stale head files are removed), and `champion.json` carries the `run_id` it
was promoted from so a loader can tell a re-run apart from the version it pinned. The champion is
graded on the candidate's holdout through its `<head>.holdout.ubj` (the train-only fit), so the
-promotion rule compares both models on one set of reports.
+promotion rule compares both models on one set of reports. Every model object sits under its
+family's `model_name`, and promotion stays inside a family: a richer family is a second candidate
+graded on the same rows, not a competitor for the tabular family's pointer.
Two further assets grade the day's models on data no example covers. `inbox_ranking_unseen_scores`
scores every report born on D (`unseen_pool` explains why no example can cover one);
@@ -44,6 +46,7 @@ from products.signals.dags.inbox_ranking.common import (
S3_BUCKET_ENV,
dataset_bucket,
dataset_unconfigured,
+ object_row_count,
owner_tags,
partition_def,
partition_object_key,
@@ -80,8 +83,11 @@ from products.signals.dags.inbox_ranking.training.train import XGB_PARAMS, Train
from products.signals.dags.inbox_ranking.training.unseen import (
CANDIDATE_ROLE,
CHAMPION_ROLE,
+ MODEL_FAMILIES,
+ TABULAR_MODEL_NAME,
HeadGrade,
UnseenModel,
+ empty_scores_write_allowed,
graded_rows,
head_grades,
leaked_report_ids,
@@ -94,6 +100,7 @@ from products.signals.dags.inbox_ranking.training.unseen import (
scored_pool,
scores_table,
unseen_pool,
+ with_model_names,
)
EXAMPLES_TABLE = "inbox_ranking_training_examples"
@@ -126,12 +133,12 @@ COMMON_ASSET_KWARGS: dict[str, Any] = {
}
-def model_object_key(prefix: str, partition_key: str, filename: str) -> str:
- return f"{prefix}/{MODELS_TABLE}/{DATASET_VERSION}/dt={partition_key}/{filename}"
+def model_object_key(prefix: str, model_name: str, partition_key: str, filename: str) -> str:
+ return f"{prefix}/{MODELS_TABLE}/{DATASET_VERSION}/{model_name}/dt={partition_key}/{filename}"
-def champion_object_key(prefix: str) -> str:
- return f"{prefix}/{MODELS_TABLE}/{DATASET_VERSION}/{CHAMPION_FILE}"
+def champion_object_key(prefix: str, model_name: str) -> str:
+ return f"{prefix}/{MODELS_TABLE}/{DATASET_VERSION}/{model_name}/{CHAMPION_FILE}"
def _read_bytes_if_exists(client, bucket: str, key: str) -> bytes | None:
@@ -273,11 +280,13 @@ def candidate_metadata(
partition_key: str,
trained: list[TrainedHead],
*,
+ model_name: str,
skipped: list[str],
trained_at: datetime.datetime,
run_id: str,
) -> dict[str, Any]:
return {
+ "model_name": model_name,
"model_version": partition_key,
"dataset_version": DATASET_VERSION,
"feature_schema_version": FEATURE_SCHEMA_VERSION,
@@ -312,7 +321,9 @@ def paired_champion_aucs(
if head is None or not entry.get("readable") or not entry.get("holdout_file"):
continue
body = _read_bytes_if_exists(
- client, bucket, model_object_key(prefix, champion["model_version"], entry["holdout_file"])
+ client,
+ bucket,
+ model_object_key(prefix, champion["model_name"], champion["model_version"], entry["holdout_file"]),
)
if body is None:
continue
@@ -347,21 +358,24 @@ def inbox_ranking_model_candidate(context: dagster.AssetExecutionContext) -> Non
if model.holdout_booster_ubj is not None:
files[f"{model.head}.holdout.ubj"] = model.holdout_booster_ubj
for filename, body in files.items():
- key = model_object_key(prefix, partition_key, filename)
+ key = model_object_key(prefix, TABULAR_MODEL_NAME, partition_key, filename)
client.put_object(Bucket=bucket, Key=key, Body=body, ContentType="application/octet-stream")
written.add(key)
metadata = candidate_metadata(
partition_key,
trained,
+ model_name=TABULAR_MODEL_NAME,
skipped=skipped,
trained_at=datetime.datetime.now(datetime.UTC),
run_id=context.run.run_id,
)
- metadata_key = model_object_key(prefix, partition_key, METADATA_FILE)
+ metadata_key = model_object_key(prefix, TABULAR_MODEL_NAME, partition_key, METADATA_FILE)
_put_json(client, bucket, metadata_key, metadata)
written.add(metadata_key)
# A re-run that trains fewer heads must not leave the previous run's files behind.
- stale = _delete_other_objects(client, bucket, model_object_key(prefix, partition_key, ""), written)
+ stale = _delete_other_objects(
+ client, bucket, model_object_key(prefix, TABULAR_MODEL_NAME, partition_key, ""), written
+ )
if stale:
context.log.warning(f"removed {len(stale)} stale objects from a previous run of dt={partition_key}")
capture_training_events(context, partition_key, candidate_events(metadata))
@@ -387,10 +401,12 @@ def inbox_ranking_model_champion(context: dagster.AssetExecutionContext) -> None
partition_key = context.partition_key
bucket, prefix, client = dataset_bucket(), settings.INBOX_RANKING_DATASET_S3_PREFIX, s3_client()
- candidate = _read_json_if_exists(client, bucket, model_object_key(prefix, partition_key, METADATA_FILE))
+ candidate = _read_json_if_exists(
+ client, bucket, model_object_key(prefix, TABULAR_MODEL_NAME, partition_key, METADATA_FILE)
+ )
if candidate is None:
raise dagster.Failure(f"candidate metadata for dt={partition_key} is missing")
- champion_key = champion_object_key(prefix)
+ champion_key = champion_object_key(prefix, TABULAR_MODEL_NAME)
champion = _read_json_if_exists(client, bucket, champion_key)
champion_aucs: dict[str, float] = {}
if champion is not None:
@@ -417,7 +433,7 @@ def inbox_ranking_model_champion(context: dagster.AssetExecutionContext) -> None
{
**candidate,
"promoted_at": datetime.datetime.now(datetime.UTC).isoformat(),
- "metadata_key": model_object_key(prefix, partition_key, METADATA_FILE),
+ "metadata_key": model_object_key(prefix, TABULAR_MODEL_NAME, partition_key, METADATA_FILE),
},
)
promoted = True
@@ -448,6 +464,7 @@ def inbox_ranking_model_champion(context: dagster.AssetExecutionContext) -> None
promotion_event(
partition_key=partition_key,
run_id=context.run.run_id,
+ model_name=TABULAR_MODEL_NAME,
decision=decision,
promoted=promoted,
champion_version=champion_version,
@@ -467,14 +484,15 @@ _HORIZON_MAPPING = dagster.TimeWindowPartitionMapping(
)
-def load_unseen_models(
- context: dagster.AssetExecutionContext, client, bucket: str, prefix: str, partition_key: str
+def load_family_models(
+ context: dagster.AssetExecutionContext, client, bucket: str, prefix: str, partition_key: str, model_name: str
) -> list[UnseenModel]:
- """The models worth an unseen read on dt=D: the day's candidate, plus the champion when the
- pointer names a different version. A model whose feature contract has moved on is logged and
- left out rather than failing the asset, because its boosters cannot take the current matrix."""
- candidate = _read_json_if_exists(client, bucket, model_object_key(prefix, partition_key, METADATA_FILE))
- champion = _read_json_if_exists(client, bucket, champion_object_key(prefix))
+ """One family's models worth an unseen read on dt=D: the day's candidate, plus that family's
+ champion when its pointer names a different version. A model whose feature contract has moved
+ on is logged and left out rather than failing the asset, because its boosters cannot take the
+ current matrix."""
+ candidate = _read_json_if_exists(client, bucket, model_object_key(prefix, model_name, partition_key, METADATA_FILE))
+ champion = _read_json_if_exists(client, bucket, champion_object_key(prefix, model_name))
records = [(CANDIDATE_ROLE, candidate)]
if champion is not None and champion.get("model_version") != (candidate or {}).get("model_version"):
records.append((CHAMPION_ROLE, champion))
@@ -482,22 +500,25 @@ def load_unseen_models(
models: list[UnseenModel] = []
for role, metadata in records:
if metadata is None:
- context.log.warning(f"no {role} metadata to score the unseen pool with")
+ context.log.warning(f"no {model_name} {role} metadata to score the unseen pool with")
continue
mismatch = model_mismatch(metadata)
if mismatch is not None:
- context.log.warning(f"{role} {metadata.get('model_version')} not scored: {mismatch}")
+ context.log.warning(f"{model_name} {role} {metadata.get('model_version')} not scored: {mismatch}")
continue
boosters = {}
for head_name, filename in readable_head_files(metadata).items():
- body = _read_bytes_if_exists(client, bucket, model_object_key(prefix, metadata["model_version"], filename))
+ body = _read_bytes_if_exists(
+ client, bucket, model_object_key(prefix, model_name, metadata["model_version"], filename)
+ )
if body is not None:
boosters[head_name] = body
if not boosters:
- context.log.warning(f"{role} {metadata['model_version']} has no readable head to score")
+ context.log.warning(f"{model_name} {role} {metadata['model_version']} has no readable head to score")
continue
models.append(
UnseenModel(
+ model_name=model_name,
model_version=metadata["model_version"],
model_role=role,
feature_schema_version=metadata["feature_schema_version"],
@@ -507,6 +528,20 @@ def load_unseen_models(
return models
+def load_unseen_models(
+ context: dagster.AssetExecutionContext, client, bucket: str, prefix: str, partition_key: str
+) -> list[UnseenModel]:
+ """Every registered family's models, so one grading run puts every family on the same rows. A
+ family with nothing to score that day contributes nothing and does not stop the others: a
+ family can be registered before its trainer's first run, and a broken one costs its own series
+ rather than every family's."""
+ return [
+ model
+ for model_name in MODEL_FAMILIES
+ for model in load_family_models(context, client, bucket, prefix, partition_key, model_name)
+ ]
+
+
@dagster.asset(
name=UNSEEN_SCORES_TABLE,
deps=["inbox_ranking_model_champion", STATE_TABLE, LABELS_TABLE],
@@ -533,16 +568,27 @@ def inbox_ranking_unseen_scores(context: dagster.AssetExecutionContext) -> None:
)
models = load_unseen_models(context, client, bucket, prefix, partition_key)
scores = score_pool(pool, snapshot.labels, models, snapshot_date=day)
+ key = partition_object_key(prefix, UNSEEN_SCORES_TABLE, partition_key)
if scores.empty:
+ existing_rows = object_row_count(client, bucket, key)
+ if not empty_scores_write_allowed(existing_rows):
+ raise dagster.Failure(
+ f"{UNSEEN_SCORES_TABLE} dt={partition_key} already holds {existing_rows} rows and this run scored "
+ f"none, so writing would destroy the scores the dt=D+horizon grade reads. Candidates are loaded "
+ f"from {MODELS_TABLE}/{DATASET_VERSION}/<model_name>/, so a partition trained before that layout "
+ f"has no model to score with. To replace the object deliberately, delete it by hand first."
+ )
context.log.warning(f"nothing scored for dt={partition_key}: {len(pool)} newborn reports, {len(models)} models")
- key = partition_object_key(prefix, UNSEEN_SCORES_TABLE, partition_key)
write_parquet(client, bucket, key, scores_table(scores), snapshot_date=partition_key)
context.add_output_metadata(
{
"unseen_pool": dagster.MetadataValue.int(len(pool)),
"models_scored": dagster.MetadataValue.int(len(models)),
- **{f"{model.model_role}_heads_scored": dagster.MetadataValue.int(len(model.boosters)) for model in models},
+ **{
+ f"{model.model_name}_{model.model_role}_heads_scored": dagster.MetadataValue.int(len(model.boosters))
+ for model in models
+ },
"s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),
}
)
@@ -554,13 +600,15 @@ def inbox_ranking_unseen_scores(context: dagster.AssetExecutionContext) -> None:
def grade_metadata(grades: Sequence[HeadGrade]) -> dict[str, dagster.MetadataValue]:
- """One metadata entry per (head, model, metric). Counts stay ints: `MetadataValue.float` rejects them."""
+ """One metadata entry per (head, model, metric). The family is in the key, so two families
+ graded on the same rows do not overwrite each other. Counts stay ints: `MetadataValue.float`
+ rejects them."""
metadata: dict[str, dagster.MetadataValue] = {}
for grade in grades:
for name, value in grade.metrics().items():
if value is None:
continue
- key = f"{grade.head}_{grade.model_role}_{name}"
+ key = f"{grade.head}_{grade.model_name}_{grade.model_role}_{name}"
metadata[key] = (
dagster.MetadataValue.int(value) if isinstance(value, int) else dagster.MetadataValue.float(value)
)
@@ -595,7 +643,7 @@ def inbox_ranking_unseen_graded(context: dagster.AssetExecutionContext) -> None:
if table is None:
skipped.update({head.name: f"no unseen scores for dt={scoring_partition}" for head in heads})
continue
- scores = table.to_pandas()
+ scores = with_model_names(table.to_pandas())
pool = scored_pool(scores)
graded_by_head: dict[str, pd.DataFrame] = {}
for head in heads:
diff --git a/products/signals/dags/inbox_ranking/training/telemetry.py b/products/signals/dags/inbox_ranking/training/telemetry.py
index 2d4c27df3d81..bb5d2e8d3111 100644
--- a/products/signals/dags/inbox_ranking/training/telemetry.py
+++ b/products/signals/dags/inbox_ranking/training/telemetry.py
@@ -2,9 +2,10 @@
`metadata.json` is the durable record of a candidate, but one JSON object per day in S3 cannot be
charted. Every training run also captures its metrics as events into the dogfood project, the
-same project the label events land in, keyed by `model_version` and stamped with the partition
-day. Per-head stability is then a trends insight with a `head` breakdown, and a drop in
-readability is an insight alert. Delivery is best-effort and never fails an asset.
+same project the label events land in, keyed by `model_name` and `model_version` and stamped with
+the partition day. Per-head stability is then a trends insight with a `head` breakdown, one line
+per model family, and a drop in readability is an insight alert. Delivery is best-effort and never
+fails an asset.
"""
import datetime
@@ -36,6 +37,7 @@ UNSEEN_REPORT_GRADED_EVENT = "inbox_ranking_unseen_report_graded"
# Candidate metadata copied onto every per-head event so a chart can filter or break down on it.
_CANDIDATE_CONTEXT_KEYS = (
+ "model_name",
"model_version",
"run_id",
"dataset_version",
@@ -115,6 +117,7 @@ def promotion_event(
*,
partition_key: str,
run_id: str,
+ model_name: str,
decision: PromotionDecision,
promoted: bool,
champion_version: str,
@@ -122,10 +125,12 @@ def promotion_event(
champion_aucs: Mapping[str, float],
) -> TrainingEvent:
"""`champion_aucs` were scored by the incumbent on this candidate's holdout; after a promotion
- `champion_version` is the candidate, so the incumbent is carried separately."""
+ `champion_version` is the candidate, so the incumbent is carried separately. Every version here
+ belongs to `model_name`: promotion compares a candidate to the champion of its own family."""
return TrainingEvent(
event=PROMOTION_DECIDED_EVENT,
properties={
+ "model_name": model_name,
"model_version": partition_key,
"run_id": run_id,
"would_promote": decision.promote,
diff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.py
index dcbb9659bc2c..b67c1e9dca12 100644
--- a/products/signals/dags/inbox_ranking/training/unseen.py
+++ b/products/signals/dags/inbox_ranking/training/unseen.py
@@ -38,6 +38,18 @@ LEGACY_POOL_NAME = "sampled"
CANDIDATE_ROLE = "candidate"
CHAMPION_ROLE = "champion"
+# The model family: which features and which learner, as against `model_version`, the partition day
+# it was fit on. Both are in the identity, so two families trained on one day stay apart.
+TABULAR_MODEL_NAME = "tabular_xgb"
+# The families the unseen read scores and grades each day. A family with no metadata for the day is
+# skipped, so an entry can be added here before its trainer writes its first candidate.
+MODEL_FAMILIES: tuple[str, ...] = (TABULAR_MODEL_NAME,)
+
+# A shuffle plus one AUC rather than a refit, so this sits far above the trainer's NULL_PERMUTATIONS.
+NULL_PERMUTATIONS = 25
+# Fixed, so re-grading the same rows reports the same band.
+NULL_SEED = 0
+
# The scores Parquet is long (one row per report, model and head) so a head can be added without a
# schema change. Declared explicitly, so a day with no unseen report writes an empty object a
# reader can still open with the schema every other day has.
@@ -47,6 +59,7 @@ _SCORE_TYPES: dict[str, pa.DataType] = {
"report_created_at": pa.timestamp("us", tz="UTC"),
"snapshot_date": pa.date32(),
"pool": pa.string(),
+ "model_name": pa.string(),
"model_version": pa.string(),
"model_role": pa.string(),
"feature_schema_version": pa.int64(),
@@ -75,6 +88,7 @@ FEATURE_INPUT_COLUMNS = (
class UnseenModel:
"""One model to score the pool with, and the readable heads it can score."""
+ model_name: str
model_version: str
model_role: str
feature_schema_version: int
@@ -90,6 +104,7 @@ class HeadGrade:
# The pool definition the scored rows came from, carried so the AUC series can be read per pool
# rather than split by hand on the day a definition changed.
pool: str
+ model_name: str
model_version: str
model_role: str
rows: int
@@ -99,6 +114,9 @@ class HeadGrade:
# AUC of "newest first" on the same outcomes. A model that does not beat it has learned
# nothing the inbox could not do by sorting on age.
recency_auc: float | None
+ # The chance line on the same rows (see ChanceBand): the band a per-day AUC has to clear.
+ null_auc: float | None
+ null_auc_std: float | None
def metrics(self) -> dict[str, int | float | None]:
return {
@@ -107,6 +125,9 @@ class HeadGrade:
"base_rate": self.base_rate,
"auc": self.auc,
"recency_auc": self.recency_auc,
+ "null_auc": self.null_auc,
+ "null_auc_std": self.null_auc_std,
+ "null_permutations": NULL_PERMUTATIONS,
}
def as_dict(self) -> dict[str, object]:
@@ -115,6 +136,7 @@ class HeadGrade:
"horizon_days": self.horizon_days,
"scoring_partition": self.scoring_partition,
"pool": self.pool,
+ "model_name": self.model_name,
"model_version": self.model_version,
"model_role": self.model_role,
**self.metrics(),
@@ -131,6 +153,41 @@ def _auc(outcomes: np.ndarray, scores: np.ndarray) -> float | None:
return float(roc_auc_score(outcomes, scores))
+@frozen
+class ChanceBand:
+ """What a model with no signal scores on these outcomes.
+
+ The mean is 0.5 by construction, so the value is the spread, which sizes the noise on a per-day
+ unseen AUC. Both are None when the AUC is undefined, so the chance line has exactly the same
+ gaps as `auc` and `recency_auc`.
+ """
+
+ auc: float | None
+ auc_std: float | None
+
+
+def chance_band(outcomes: np.ndarray, scores: np.ndarray) -> ChanceBand:
+ """The AUC over NULL_PERMUTATIONS seeded permutations of `scores` against the same outcomes.
+
+ Permuting the model's own scores rather than drawing fresh ones keeps the score distribution
+ and its ties, so the band is the one this head's rows actually produce.
+
+ Each draw is counted with its own reverse, which scores `1 - auc` because a tie pays 0.5 either
+ way. The mean is therefore exactly 0.5 however few rows the head has. A plain sample mean lands
+ near 0.5 on a large head but not on a small one, and two families on the same rows would then
+ report different chance lines because their shuffles differed, which is a gap that means nothing.
+ """
+ rng = np.random.default_rng(NULL_SEED)
+ aucs: list[float] = []
+ for _ in range(NULL_PERMUTATIONS):
+ auc = _auc(outcomes, rng.permutation(scores))
+ if auc is not None:
+ aucs.extend((auc, 1.0 - auc))
+ if not aucs:
+ return ChanceBand(auc=None, auc_std=None)
+ return ChanceBand(auc=float(np.mean(aucs)), auc_std=float(np.std(aucs)))
+
+
def model_mismatch(metadata: Mapping[str, Any]) -> str | None:
"""Why the model cannot be scored against the current feature contract, or None when it can."""
version = metadata.get("feature_schema_version")
@@ -194,10 +251,35 @@ def scored_pool(scores: pd.DataFrame) -> str:
return str(values[0]) if len(values) else LEGACY_POOL_NAME
+def empty_scores_write_allowed(existing_row_count: int | None) -> bool:
+ """Whether a run that scored nothing may overwrite a partition's scores object.
+
+ A partition whose candidate sits under the pre-family models layout loads no model and so
+ scores nothing. Writing that empty result would destroy the rows the dt=D+horizon grade reads,
+ and those rows cannot be rebuilt once the state snapshot they came from ages out. An unknown
+ count (no object, or one written before the row-count stamp) is not a veto, which is the rule
+ `partition_write_allowed` already applies to the emission log.
+ """
+ return not existing_row_count
+
+
+def with_model_names(scores: pd.DataFrame) -> pd.DataFrame:
+ """`scores` with a `model_name` column, filling the tabular family where it is absent.
+
+ The grader reads scores objects up to 14 days old, so it still meets objects written before the
+ column existed. Every one of those holds tabular XGBoost rows, and grading them under a null
+ name would split the AUC series on the day the column arrived.
+ """
+ if "model_name" not in scores:
+ return scores.assign(model_name=TABULAR_MODEL_NAME)
+ return scores.assign(model_name=scores["model_name"].fillna(TABULAR_MODEL_NAME))
+
+
def score_pool(
pool: pd.DataFrame, labels: pd.DataFrame, models: Sequence[UnseenModel], *, snapshot_date: datetime.date
) -> pd.DataFrame:
- """One row per (report, model, head) in SCORE_COLUMNS order.
+ """One row per (report, model, head) in SCORE_COLUMNS order, where a model is a
+ (model_name, model_version, model_role).
Features are built exactly as `build_examples` builds them, so a report scored here sees the
same vector it would have seen as a training example. `label_at_scoring` records whether the
@@ -221,6 +303,7 @@ def score_pool(
"report_created_at": created_at,
"snapshot_date": snapshot_date,
"pool": POOL_NAME,
+ "model_name": model.model_name,
"model_version": model.model_version,
"model_role": model.model_role,
"feature_schema_version": model.feature_schema_version,
@@ -261,14 +344,15 @@ def score_event_rows(scores: pd.DataFrame, pool: pd.DataFrame) -> list[dict[str,
report_id: {column: _plain(value) for column, value in row.items()}
for report_id, row in pool[columns].to_dict("index").items()
}
- rows: dict[tuple[str, str], dict[str, object]] = {}
+ rows: dict[tuple[str, str, str], dict[str, object]] = {}
for record in scores.to_dict("records"):
- key = (str(record["report_id"]), str(record["model_role"]))
+ key = (str(record["report_id"]), str(record["model_name"]), str(record["model_role"]))
if key not in rows:
rows[key] = {
"report_id": record["report_id"],
"team_id": _int_or_none(record["team_id"]),
"report_created_at": _isoformat_or_none(record["report_created_at"]),
+ "model_name": record["model_name"],
"model_version": record["model_version"],
"model_role": record["model_role"],
"feature_schema_version": record["feature_schema_version"],
@@ -317,21 +401,28 @@ def head_grades(graded: pd.DataFrame, head: Head, *, pool: str, scoring_partitio
"""The unseen read per model that scored this head, over the in-cohort rows."""
grades: list[HeadGrade] = []
kept = graded[graded["in_cohort"]]
- for (model_version, model_role), rows in kept.groupby(["model_version", "model_role"], sort=True):
+ for (model_name, model_version, model_role), rows in kept.groupby(
+ ["model_name", "model_version", "model_role"], sort=True
+ ):
outcomes = rows["outcome"].to_numpy(dtype=bool)
+ scores = rows["score"].to_numpy(dtype=float)
+ band = chance_band(outcomes, scores)
grades.append(
HeadGrade(
head=head.name,
horizon_days=head.horizon_days,
scoring_partition=scoring_partition,
pool=pool,
+ model_name=str(model_name),
model_version=str(model_version),
model_role=str(model_role),
rows=len(rows),
positives=int(outcomes.sum()),
base_rate=float(outcomes.mean()) if len(rows) else None,
- auc=_auc(outcomes, rows["score"].to_numpy(dtype=float)),
+ auc=_auc(outcomes, scores),
recency_auc=_auc(outcomes, -rows["age_hours"].to_numpy(dtype=float)),
+ null_auc=band.auc,
+ null_auc_std=band.auc_std,
)
)
return grades
@@ -345,10 +436,10 @@ def report_grade_rows(
Heads are grouped by horizon because they were all scored on the same day, so one event holds a
report's whole outcome at that horizon.
"""
- rows: dict[tuple[str, str], dict[str, object]] = {}
+ rows: dict[tuple[str, str, str], dict[str, object]] = {}
for head_name, graded in sorted(graded_by_head.items()):
for record in graded.to_dict("records"):
- key = (str(record["report_id"]), str(record["model_role"]))
+ key = (str(record["report_id"]), str(record["model_name"]), str(record["model_role"]))
entry = rows.setdefault(
key,
{
@@ -356,6 +447,7 @@ def report_grade_rows(
"team_id": _int_or_none(record["team_id"]),
"scoring_partition": scoring_partition,
"pool": pool,
+ "model_name": record["model_name"],
"model_version": record["model_version"],
"model_role": record["model_role"],
"horizon_days": horizon_days,