: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
refactor(signals): give inbox ranking models a feature-set contract (#98593)
posthog[bot]bbbab5852a5e
diff --git a/products/signals/backend/ranking/features.py b/products/signals/backend/ranking/features.pyindex 82c1f91db299..12ff651949ba 100644--- a/products/signals/backend/ranking/features.py+++ b/products/signals/backend/ranking/features.py@@ -1,19 +1,26 @@-"""Feature universe for the report-ranking model.+"""Feature universes for the report-ranking model.-One ordered list of feature names, one function that turns a report-state row into that vector.-Training (`products/signals/dags/inbox_ranking/training/`) and serving (the scoring sweep in this-package) must build features through the same code, so the booster's `feature_names` match the-serving matrix by construction; the model's `metadata.json` records FEATURE_SCHEMA_VERSION and the-serving side refuses a booster whose version or feature names disagree with what it can produce.+A `FeatureSet` is one universe: its name, its schema version, its ordered feature names, the+report-state columns it reads, and `build_matrix`, which turns a frame of those rows into the+matrix. A model records the set it was fit on in its `metadata.json`, so a run can hold several+sets at once: the examples Parquet, the training matrix and the scoring matrix are all built per+set, and a model whose declared set this build cannot produce is left unscored.-v0 is tabular only: the report-state columns the dataset dag snapshots from Postgres plus the+The tabular set is the first one. Training (`products/signals/dags/inbox_ranking/training/`) and+serving (the scoring sweep in this package) must build features through the same code, so the+booster's `feature_names` match the serving matrix by construction. The sweep reads the tabular+contract directly as FEATURE_NAMES / `feature_vector` / FEATURE_SCHEMA_VERSION.++The tabular set is: the report-state columns the dataset dag snapshots from Postgres plus thereport's age at the scoring moment. No report embedding and no impression-derived columns(`source_products`), so the sweep needs nothing beyond the SignalReport row and its latestjudgment artefacts. Embeddings wait for the score log to accrue (skill issue 14)."""+import abcimport mathfrom collections.abc import Mapping+from types import MappingProxyTypefrom typing import Anyimport pandas as pd@@ -40,6 +47,24 @@ FEATURE_NAMES: tuple[str, ...] = (*(f"actionability_{value}" for value in ACTIONABILITY_VALUES),)+# The report-state columns `feature_frame` reads. `age_hours` is not one of them: it is the+# report's age at the scoring moment, derived from the snapshot's own clock, and the caller adds+# it to the rows of every set.+TABULAR_STATE_COLUMNS: tuple[str, ...] = (+ "signal_count",+ "total_weight",+ "run_count",+ "title_chars",+ "summary_chars",+ "priority",+ "actionability",+)++# Side inputs a set may read next to the report-state rows, keyed by name and indexed by+# report_id. The tabular set needs none.+Extras = Mapping[str, pd.DataFrame]+NO_EXTRAS: Extras = MappingProxyType({})+def _number(value: Any) -> float:if value is None:@@ -89,3 +114,53 @@ def feature_frame(rows: pd.DataFrame) -> pd.DataFrame:for value in ACTIONABILITY_VALUES:out[f"actionability_{value}"] = (actionability == value).astype(float)return out[list(FEATURE_NAMES)]+++class FeatureSet(abc.ABC):+ """One feature universe a model can be fit on and scored with.++ `state_columns` are the report-state columns `build_matrix` reads. The caller always adds+ `age_hours`, so a set may read that without declaring it.+ """++ name: str+ schema_version: int+ feature_names: tuple[str, ...]+ state_columns: tuple[str, ...]++ @abc.abstractmethod+ def build_matrix(self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS) -> pd.DataFrame:+ """The matrix for `rows`, one column per name in `feature_names` order.++ `rows` carries the state columns the set declared plus `age_hours`, indexed by report_id.+ `extras` carries the side inputs a set needs beyond report state.+ """+++class TabularFeatureSet(FeatureSet):+ """The v0 set: the report-state counters, the title and summary lengths, the report's age, and+ the one-hot priority and actionability. This is the set `feature_vector` serves."""++ name = "tabular"+ schema_version = FEATURE_SCHEMA_VERSION+ feature_names = FEATURE_NAMES+ state_columns = TABULAR_STATE_COLUMNS++ def build_matrix(self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS) -> pd.DataFrame:+ return feature_frame(rows)+++TABULAR_FEATURE_SET = TabularFeatureSet()++# Every set this build can produce, by name. A model that names a set absent from here cannot be+# scored, the same way a model whose feature names have moved on cannot.+FEATURE_SETS: Mapping[str, FeatureSet] = MappingProxyType({TABULAR_FEATURE_SET.name: TABULAR_FEATURE_SET})++# What a model written before `feature_set` was recorded was fit on: every one of those is tabular.+DEFAULT_FEATURE_SET = TABULAR_FEATURE_SET+++def feature_set_by_name(name: str | None) -> FeatureSet | None:+ """The named set, the tabular default when the name is absent, or None when this build cannot+ produce it."""+ return DEFAULT_FEATURE_SET if name is None else FEATURE_SETS.get(name)diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.mdindex fea8ae231bde..3d675be23cc0 100644--- a/products/signals/dags/inbox_ranking/AGENTS.md+++ b/products/signals/dags/inbox_ranking/AGENTS.md@@ -9,7 +9,8 @@ Read `README.md` first for what the dataset is and how partitions behave. This f## Training dag specifics-- `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.+- `products/signals/backend/ranking/features.py` holds a `FeatureSet` per feature universe (it lives in the backend so the scoring sweep owns it and the dag imports it). The tabular set is also the serving contract the sweep reads as `FEATURE_NAMES` / `feature_vector`, and the sweep refuses a booster whose `feature_names` or `feature_schema_version` disagree. Adding a tabular 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.+- A model declares its feature set in `metadata.json` and is checked against that set, not against one global contract. Adding a set means an entry in `FEATURE_SETS`; the examples asset then writes its Parquet under `inbox_ranking_training_examples/v1/<feature_set>/dt=D/`, and the unseen scorer builds one matrix per set and shares it across the families that read it. Do not reintroduce a module-global feature list into the training path: two sets live side by side. A partition whose examples were written before the per-set layout has nothing under `<feature_set>/`, so re-run the examples asset for that day before re-running the candidate or the unseen scores on 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 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/<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 aff9dbbab65c..74f2c0c9cdca 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -63,7 +63,7 @@ The first four are report grain and land in one table. `inbox_signal_embeddings````texts3://<bucket>/<prefix>/-├── inbox_ranking_training_examples/v1/dt=YYYY-MM-DD/ # scoring-moment examples, all heads, one parquet+├── inbox_ranking_training_examples/v1/<feature_set>/dt=YYYY-MM-DD/ # scoring-moment examples, all heads, one parquet per feature set├── 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)@@ -72,11 +72,12 @@ s3://<bucket>/<prefix>/```- **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.+- **A feature set is one feature universe.** `products/signals/backend/ranking/features.py` holds a `FeatureSet` per universe: its name, its schema version, its ordered feature names, the report-state columns it reads, and `build_matrix`. `tabular` is the only one today. A candidate records the set it was fit on in its `metadata.json`, so the grader checks a model against its own set rather than one global contract, the examples asset writes one Parquet per set, and the unseen scorer builds one matrix per set and shares it across the families that read it. Adding a set means an entry in `FEATURE_SETS`; a model naming a set this build cannot produce is logged and left unscored.+- **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 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. 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.+- **The only feature set in v0 is `tabular`** (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_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.+- **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`, 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@@ -117,7 +118,7 @@ The training job is S3-only, so it can run on a laptop against copies of the proThe 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/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`:+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/tabular/dt=<day>/part-00000.parquet`:```bashAWS_ACCESS_KEY_ID=object_storage_root_user AWS_SECRET_ACCESS_KEY=object_storage_root_password \diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.pyindex 8b0d7d8e6386..49fc6768fc44 100644--- a/products/signals/dags/inbox_ranking/tests/test_training.py+++ b/products/signals/dags/inbox_ranking/tests/test_training.py@@ -19,6 +19,10 @@ from posthog import settingsfrom products.signals.backend.ranking.features import (FEATURE_NAMES,FEATURE_SCHEMA_VERSION,+ NO_EXTRAS,+ TABULAR_FEATURE_SET,+ Extras,+ FeatureSet,feature_frame,feature_vector,)@@ -27,7 +31,9 @@ from products.signals.dags.inbox_ranking.dataset.dag import LABELS_TABLE, STATE_from products.signals.dags.inbox_ranking.training.dag import (METADATA_FILE,_delete_other_objects,+ candidate_metadata,champion_object_key,+ examples_object_key,grade_metadata,inbox_ranking_training_examples,load_snapshots,@@ -36,11 +42,11 @@ from products.signals.dags.inbox_ranking.training.dag import (snapshot_dates,)from products.signals.dags.inbox_ranking.training.examples import (- EXAMPLE_COLUMNS,STATE_LAG_LIMIT,Snapshot,assemble_snapshot,build_examples,+ example_columns,holdout_mask,)from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, dismissed_as_wrong@@ -61,16 +67,21 @@ from products.signals.dags.inbox_ranking.training.telemetry import (from products.signals.dags.inbox_ranking.training.train import _head_readable, booster_holdout_auc, train_headfrom products.signals.dags.inbox_ranking.training.unseen import (CANDIDATE_ROLE,+ CHAMPION_ROLE,LEGACY_POOL_NAME,POOL_NAME,+ SCORE_COLUMNS,TABULAR_MODEL_NAME,+ UnseenModel,chance_band,empty_scores_write_allowed,graded_rows,head_grades,leaked_report_ids,+ model_mismatch,report_grade_rows,score_event_rows,+ score_pool,scored_pool,unseen_pool,with_model_names,@@ -171,8 +182,8 @@ def test_build_examples_is_a_scoring_moment_with_a_future_label():# A snapshot with no horizon partner contributes nothing.later + datetime.timedelta(days=1): Snapshot(date=later, state=_state(ids), labels=_labels(ids)),}- examples = build_examples(snapshots, open_head)- assert list(examples.columns) == list(EXAMPLE_COLUMNS)+ examples = build_examples(snapshots, open_head, TABULAR_FEATURE_SET)+ assert list(examples.columns) == list(example_columns(TABULAR_FEATURE_SET))assert examples.set_index("report_id")["label"].to_dict() == {"a": 1, "c": 0}assert (examples["snapshot_date"] == D0).all()assert (examples["age_hours"] == 12.0).all()@@ -209,10 +220,14 @@ def test_assemble_snapshot_makes_never_labeled_reports_negatives_and_drops_untruassert snapshots[D0].labels["label_provenance_ok"].to_dict() == {"a": False, "b": True, "c": True, "gone": True}assert snapshots[later].labels["label_provenance_ok"].to_dict() == {"a": False, "b": True, "c": True, "gone": False}# pr_created reads the tasks webhook, so a's untrusted status telemetry does not exclude it there.- pr = build_examples(snapshots, head).set_index("report_id")["label"].to_dict()+ pr = build_examples(snapshots, head, TABULAR_FEATURE_SET).set_index("report_id")["label"].to_dict()assert pr == {"a": 0, "b": 0, "c": 1, "gone": 1}# dismiss_wrong reads the status stream: a is dropped, b was never impressed, c is a positive.- wrong = build_examples(snapshots, HEADS_BY_NAME["dismiss_wrong"]).set_index("report_id")["label"].to_dict()+ wrong = (+ build_examples(snapshots, HEADS_BY_NAME["dismiss_wrong"], TABULAR_FEATURE_SET)+ .set_index("report_id")["label"]+ .to_dict()+ )assert wrong == {"c": 1}@@ -226,7 +241,7 @@ def test_build_examples_drops_state_rows_read_long_after_their_snapshot():D0: Snapshot(date=D0, state=state, labels=_labels(["a", "b"])),later: Snapshot(date=later, state=state, labels=_labels(["a", "b"])),}- assert build_examples(snapshots, head)["report_id"].tolist() == ["a"]+ assert build_examples(snapshots, head, TABULAR_FEATURE_SET)["report_id"].tolist() == ["a"]@pytest.mark.parametrize(@@ -311,7 +326,7 @@ def test_new_head_label_columns_survive_the_load_snapshots_projection(head_name)objects[partition_object_key("inbox_ranking", STATE_TABLE, key)] = _parquet(_state(["a"]))objects[partition_object_key("inbox_ranking", LABELS_TABLE, key)] = _parquet(labels)snapshots = load_snapshots(_ParquetS3(objects), "bucket", "inbox_ranking", [D0, later])- examples = build_examples(snapshots, head)+ examples = build_examples(snapshots, head, TABULAR_FEATURE_SET)assert examples.set_index("report_id")["label"].to_dict() == {"a": 1}@@ -326,7 +341,7 @@ def test_build_examples_skips_refund_pairs_when_the_scoring_snapshot_lacks_the_cD0: Snapshot(date=D0, state=_state(["a"]), labels=_labels(["a"])),later: Snapshot(date=later, state=_state(["a"]), labels=_labels(["a"], refund_count=[1])),}- assert build_examples(snapshots, head).empty+ assert build_examples(snapshots, head, TABULAR_FEATURE_SET).emptydef test_build_examples_skips_label_only_rows():@@ -337,7 +352,7 @@ def test_build_examples_skips_label_only_rows():D0: Snapshot(date=D0, state=state, labels=_labels(["a", "eu"])),later: Snapshot(date=later, state=state, labels=_labels(["a", "eu"], pr_created_count=[1, 1])),}- assert build_examples(snapshots, head)["report_id"].tolist() == ["a"]+ assert build_examples(snapshots, head, TABULAR_FEATURE_SET)["report_id"].tolist() == ["a"]def test_holdout_mask_cuts_by_report_not_by_row():@@ -375,7 +390,7 @@ def test_train_head_learns_a_separable_signal_and_names_its_features():examples.insert(3, "report_created_at", created)examples["label"] = (signal_count > 25).astype(int)- trained = train_head(examples, head, holdout_days=7)+ trained = train_head(examples, head, feature_names=FEATURE_NAMES, holdout_days=7)assert trained is not Noneassert trained.metrics.readableassert trained.metrics.holdout_auc is not None and trained.metrics.holdout_auc > 0.9@@ -393,13 +408,15 @@ 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(trained.holdout_booster_ubj, examples, head, holdout_days=7)+ paired = booster_holdout_auc(+ trained.holdout_booster_ubj, examples, head, feature_names=FEATURE_NAMES, holdout_days=7+ )assert paired == pytest.approx(trained.metrics.holdout_auc, abs=1e-6)# 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, holdout_days=7) is None+ assert booster_holdout_auc(other_ubj, examples, head, feature_names=FEATURE_NAMES, holdout_days=7) is Nonedef test_train_head_keeps_logloss_on_a_single_class_holdout():@@ -430,7 +447,7 @@ def test_train_head_keeps_logloss_on_a_single_class_holdout():in_holdout = holdout_mask(examples, 7).to_numpy()examples["label"] = ((signal_count > 25) & ~in_holdout).astype(int)- trained = train_head(examples, head, holdout_days=7)+ trained = train_head(examples, head, feature_names=FEATURE_NAMES, holdout_days=7)assert trained is not Noneassert trained.metrics.holdout_positives == 0assert trained.metrics.holdout_auc is None@@ -452,7 +469,7 @@ def test_train_head_returns_none_without_both_classes():)for name in FEATURE_NAMES:examples[name] = 1.0- assert train_head(examples, head, holdout_days=7) is None+ assert train_head(examples, head, feature_names=FEATURE_NAMES, holdout_days=7) is Noneclass _FakeClient:@@ -534,7 +551,7 @@ def test_build_examples_never_covers_a_report_born_on_the_partition_day():_labels(["old", "newborn"], open_count=[1, 1]),),}- assert set(build_examples(snapshots, head)["report_id"]) == {"old"}+ assert set(build_examples(snapshots, head, TABULAR_FEATURE_SET)["report_id"]) == {"old"}def test_leaked_report_ids_flags_a_pool_report_an_example_already_covers():@@ -678,6 +695,7 @@ def test_load_unseen_models_skips_a_family_with_nothing_to_score_that_day(monkeymetadata = {"model_name": TABULAR_MODEL_NAME,"model_version": partition_key,+ "feature_set": TABULAR_FEATURE_SET.name,"feature_schema_version": FEATURE_SCHEMA_VERSION,"feature_names": list(FEATURE_NAMES),"heads": [{"head": "open", "readable": True, "file": "open.ubj"}],@@ -761,6 +779,7 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):*examples_events(partition_key="2026-08-25",run_id="run-1",+ feature_set=TABULAR_FEATURE_SET.name,snapshots=20,backfilled_rows=0,per_head={"open": HeadExampleCounts(rows=10, positives=2)},@@ -810,7 +829,13 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):# A head with nothing to fit still reports, so the readability alert sees a bad day, not a gap.assert {"trained": False, "readable": False}.items() <= candidates[2]["properties"].items()examples_props = by_event["inbox_ranking_examples_built"][0]["properties"]- assert {"head": "open", "rows": 10, "positives": 2}.items() <= examples_props.items()+ # Examples are per feature set, not per family: this is the dimension the counts break down on.+ assert {+ "head": "open",+ "rows": 10,+ "positives": 2,+ "feature_set": TABULAR_FEATURE_SET.name,+ }.items() <= examples_props.items()promotion_props = by_event["inbox_ranking_promotion_decided"][0]["properties"]assert {"would_promote": True,@@ -992,3 +1017,140 @@ def test_model_key_layout_is_stable():datetime.date(2026, 8, 18),datetime.date(2026, 8, 19),]+++class _AgeOnlyFeatureSet(FeatureSet):+ """A second set for the tests: no trainer writes one yet, so this stands in for a family that+ reads different features on the same rows."""++ name = "age_only"+ schema_version = 1+ feature_names = ("age_hours",)+ state_columns = ()++ def build_matrix(self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS) -> pd.DataFrame:+ return rows[["age_hours"]].astype(float)+++class _CountingFeatureSet(FeatureSet):+ """`inner`, counting how many matrices are built from it."""++ def __init__(self, inner: FeatureSet) -> None:+ self.inner = inner+ self.name = inner.name+ self.schema_version = inner.schema_version+ self.feature_names = inner.feature_names+ self.state_columns = inner.state_columns+ self.builds = 0++ def build_matrix(self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS) -> pd.DataFrame:+ self.builds += 1+ return self.inner.build_matrix(rows, extras)+++def _booster_ubj(feature_names: tuple[str, ...]) -> bytes:+ rows = 20+ x = pd.DataFrame({name: np.linspace(0.0, 1.0, rows) for name in feature_names})+ model = xgb.XGBClassifier(n_estimators=2, max_depth=2)+ model.fit(x, np.arange(rows) % 2)+ return bytes(model.get_booster().save_raw("ubj"))+++def _unseen_model(model_name: str, feature_set: FeatureSet, role: str = CANDIDATE_ROLE) -> UnseenModel:+ return UnseenModel(+ model_name=model_name,+ model_version="2026-08-10",+ model_role=role,+ feature_set=feature_set,+ boosters={"open": _booster_ubj(tuple(feature_set.feature_names))},+ )+++def test_score_pool_builds_one_matrix_per_feature_set_and_shares_it():+ # Two models on one set must reuse its matrix, and a model on another set must get its own.+ # Scoring every model against a single matrix would feed the second set the wrong columns.+ tabular = _CountingFeatureSet(TABULAR_FEATURE_SET)+ age_only = _CountingFeatureSet(_AgeOnlyFeatureSet())+ models = [+ _unseen_model(TABULAR_MODEL_NAME, tabular),+ _unseen_model(TABULAR_MODEL_NAME, tabular, role=CHAMPION_ROLE),+ _unseen_model(EMBEDDINGS_MODEL_NAME, age_only),+ ]+ scores = score_pool(_state(["a", "b"]), _labels(["a", "b"]), models, snapshot_date=D0)++ assert (tabular.builds, age_only.builds) == (1, 1)+ assert list(scores.columns) == list(SCORE_COLUMNS)+ assert scores.groupby(["model_name", "model_role"]).size().to_dict() == {+ (TABULAR_MODEL_NAME, CANDIDATE_ROLE): 2,+ (TABULAR_MODEL_NAME, CHAMPION_ROLE): 2,+ (EMBEDDINGS_MODEL_NAME, CANDIDATE_ROLE): 2,+ }+ # Each row carries the schema version of the set its model was fit on, not one global version.+ assert set(scores.loc[scores["model_name"] == EMBEDDINGS_MODEL_NAME, "feature_schema_version"]) == {+ age_only.schema_version+ }+++def _model_metadata(**overrides) -> dict[str, Any]:+ base = {+ "feature_set": TABULAR_FEATURE_SET.name,+ "feature_schema_version": FEATURE_SCHEMA_VERSION,+ "feature_names": list(FEATURE_NAMES),+ }+ base.update(overrides)+ return base+++ "metadata,expected",+ [+ (_model_metadata(), None),+ # Written before the field existed: every one of those models is tabular.+ ({key: value for key, value in _model_metadata().items() if key != "feature_set"}, None),+ (_model_metadata(feature_set="report_embeddings"), "this build can produce"),+ (_model_metadata(feature_schema_version=99), "feature_schema_version 99"),+ (_model_metadata(feature_names=["age_hours"]), "feature_names differ"),+ ],+)+def test_model_mismatch_checks_a_model_against_its_own_feature_set(metadata, expected):+ # A family on a richer set must not be rejected for disagreeing with the tabular contract, and+ # a set this build cannot produce must not be scored on whatever matrix happens to be at hand.+ mismatch = model_mismatch(metadata)+ assert expected is None and mismatch is None or (mismatch is not None and expected in mismatch)+++def test_candidate_metadata_declares_the_set_it_was_fit_on():+ # The trainer's own record must pass the grader's check, or the day's candidate goes unscored.+ metadata = candidate_metadata(+ "2026-08-19",+ [],+ model_name=TABULAR_MODEL_NAME,+ feature_set=TABULAR_FEATURE_SET,+ skipped=[],+ trained_at=NOW,+ run_id="run-1",+ )+ assert metadata["feature_set"] == TABULAR_FEATURE_SET.name+ assert metadata["feature_schema_version"] == TABULAR_FEATURE_SET.schema_version+ assert model_mismatch(metadata) is None+++def test_build_examples_carries_the_columns_of_the_set_it_is_given():+ # The examples Parquet is per feature set, so a second set's object holds its own features.+ ids = ["a"]+ later = D0 + datetime.timedelta(days=3)+ snapshots = {+ D0: Snapshot(date=D0, state=_state(ids), labels=_labels(ids)),+ later: Snapshot(date=later, state=_state(ids), labels=_labels(ids, open_count=[2])),+ }+ examples = build_examples(snapshots, HEADS_BY_NAME["open"], _AgeOnlyFeatureSet())+ assert list(examples.columns) == ["head", "report_id", "snapshot_date", "report_created_at", "age_hours", "label"]+ assert examples["age_hours"].tolist() == [12.0]+++def test_examples_key_layout_is_per_feature_set():+ # Two sets carry different feature columns, so they cannot share a partition's object.+ assert (+ examples_object_key("inbox_ranking", TABULAR_FEATURE_SET.name, "2026-08-19")+ == "inbox_ranking/inbox_ranking_training_examples/v1/tabular/dt=2026-08-19/part-00000.parquet"+ )diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pyindex 362db2a08d20..9d649a709a9f 100644--- a/products/signals/dags/inbox_ranking/training/dag.py+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -30,7 +30,7 @@ comparable because both apply the same `Head` cohort, label and horizon.import jsonimport datetime-from collections.abc import Sequence+from collections.abc import Mapping, Sequencefrom typing import Anyimport pandas as pd@@ -40,9 +40,10 @@ from botocore.exceptions import ClientErrorfrom posthog import settings-from products.signals.backend.ranking.features import FEATURE_NAMES, FEATURE_SCHEMA_VERSION+from products.signals.backend.ranking.features import FEATURE_SETS, TABULAR_FEATURE_SET, FeatureSetfrom products.signals.dags.inbox_ranking.common import (DATASET_VERSION,+ PARQUET_PART_NAME,S3_BUCKET_ENV,dataset_bucket,dataset_unconfigured,@@ -58,13 +59,13 @@ from products.signals.dags.inbox_ranking.common import ()from products.signals.dags.inbox_ranking.dataset.dag import LABELS_TABLE, STATE_TABLEfrom products.signals.dags.inbox_ranking.training.examples import (- EXAMPLE_COLUMNS,+ BASE_STATE_COLUMNS,PROVENANCE_LABEL_COLUMNS,PROVENANCE_STATE_COLUMNS,- STATE_COLUMNS,Snapshot,assemble_snapshot,build_examples,+ example_columns,point_in_time_mask,)from products.signals.dags.inbox_ranking.training.heads import HEADS, HEADS_BY_HORIZON, HEADS_BY_NAME@@ -92,6 +93,7 @@ from products.signals.dags.inbox_ranking.training.unseen import (head_grades,leaked_report_ids,missing_label_columns,+ model_feature_set,model_mismatch,readable_head_files,report_grade_rows,@@ -122,7 +124,18 @@ _LABEL_COLUMNS = ("refund_count",*PROVENANCE_LABEL_COLUMNS,)-_STATE_READ_COLUMNS = (*STATE_COLUMNS, *PROVENANCE_STATE_COLUMNS, "features_observed_at")+# Every registered feature set's columns in one read: the state snapshot is loaded once and every+# set builds its examples from it.+_STATE_READ_COLUMNS = tuple(+ dict.fromkeys(+ (+ *BASE_STATE_COLUMNS,+ *(column for feature_set in FEATURE_SETS.values() for column in feature_set.state_columns),+ *PROVENANCE_STATE_COLUMNS,+ "features_observed_at",+ )+ )+)COMMON_ASSET_KWARGS: dict[str, Any] = {"group_name": "inbox_ranking_training",@@ -133,6 +146,12 @@ COMMON_ASSET_KWARGS: dict[str, Any] = {}+def examples_object_key(prefix: str, feature_set_name: str, partition_key: str) -> str:+ """One examples object per feature set: two sets carry different feature columns, so they+ cannot share a Parquet, and a family trains on the object of the set it declares."""+ return f"{prefix}/{EXAMPLES_TABLE}/{DATASET_VERSION}/{feature_set_name}/dt={partition_key}/{PARQUET_PART_NAME}"++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}"@@ -204,8 +223,8 @@ def load_snapshots(return snapshots-def examples_table(examples: pd.DataFrame) -> pa.Table:- return pa.Table.from_pandas(examples[list(EXAMPLE_COLUMNS)], preserve_index=False)+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)# The examples for dt=D read every snapshot back to D-lookback. The default same-partition mapping@@ -239,41 +258,67 @@ def inbox_ranking_training_examples(context: dagster.AssetExecutionContext) -> Nif backfilled_rows:context.log.warning(f"{backfilled_rows} state rows read after the snapshot window are excluded (backfill)")- per_head = {head.name: build_examples(snapshots, head) for head in HEADS}+ metadata: dict[str, dagster.MetadataValue] = {+ "snapshots": dagster.MetadataValue.int(len(snapshots)),+ "backfilled_state_rows_excluded": dagster.MetadataValue.int(backfilled_rows),+ }+ for feature_set in FEATURE_SETS.values():+ metadata |= _write_examples(+ context, client, bucket, prefix, partition_key, feature_set, snapshots, backfilled_rows+ )+ context.add_output_metadata(metadata)+++def _write_examples(+ context: dagster.AssetExecutionContext,+ client,+ bucket: str,+ prefix: str,+ partition_key: str,+ feature_set: FeatureSet,+ snapshots: Mapping[datetime.date, Snapshot],+ backfilled_rows: int,+) -> dict[str, dagster.MetadataValue]:+ """One feature set's examples for the partition, as its own object and its own events, with+ the asset metadata to record for it."""+ per_head = {head.name: build_examples(snapshots, head, feature_set) for head in HEADS}examples = (- pd.concat(per_head.values(), ignore_index=True) if per_head else pd.DataFrame(columns=list(EXAMPLE_COLUMNS))+ pd.concat(per_head.values(), ignore_index=True)+ if per_head+ else pd.DataFrame(columns=list(example_columns(feature_set))))- key = partition_object_key(prefix, EXAMPLES_TABLE, partition_key)- write_parquet(client, bucket, key, examples_table(examples), snapshot_date=partition_key)+ key = examples_object_key(prefix, feature_set.name, partition_key)+ write_parquet(client, bucket, key, examples_table(examples, feature_set), snapshot_date=partition_key)counts = {name: HeadExampleCounts(rows=len(frame), positives=int(frame["label"].sum()))for name, frame in per_head.items()}- context.add_output_metadata(- {- "rows": dagster.MetadataValue.int(len(examples)),- "snapshots": dagster.MetadataValue.int(len(snapshots)),- "backfilled_state_rows_excluded": dagster.MetadataValue.int(backfilled_rows),- **{f"{name}_rows": dagster.MetadataValue.int(head_counts.rows) for name, head_counts in counts.items()},- **{- f"{name}_positives": dagster.MetadataValue.int(head_counts.positives)- for name, head_counts in counts.items()- },- "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),- }- )+ metadata: dict[str, dagster.MetadataValue] = {+ f"{feature_set.name}_rows": dagster.MetadataValue.int(len(examples)),+ **{+ f"{feature_set.name}_{name}_rows": dagster.MetadataValue.int(head_counts.rows)+ for name, head_counts in counts.items()+ },+ **{+ f"{feature_set.name}_{name}_positives": dagster.MetadataValue.int(head_counts.positives)+ for name, head_counts in counts.items()+ },+ f"{feature_set.name}_s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),+ }capture_training_events(context,partition_key,examples_events(partition_key=partition_key,run_id=context.run.run_id,+ feature_set=feature_set.name,snapshots=len(snapshots),backfilled_rows=backfilled_rows,per_head=counts,),)+ return metadatadef candidate_metadata(@@ -281,6 +326,7 @@ def candidate_metadata(trained: list[TrainedHead],*,model_name: str,+ feature_set: FeatureSet,skipped: list[str],trained_at: datetime.datetime,run_id: str,@@ -289,8 +335,12 @@ def candidate_metadata("model_name": model_name,"model_version": partition_key,"dataset_version": DATASET_VERSION,- "feature_schema_version": FEATURE_SCHEMA_VERSION,- "feature_names": list(FEATURE_NAMES),+ # The feature universe this model was fit on. The grader checks the model against this set+ # rather than against one global contract, so a second family is not rejected for reading+ # different features.+ "feature_set": feature_set.name,+ "feature_schema_version": feature_set.schema_version,+ "feature_names": list(feature_set.feature_names),"trained_at": trained_at.isoformat(),"run_id": run_id,"lookback_days": settings.INBOX_RANKING_TRAINING_LOOKBACK_DAYS,@@ -310,7 +360,14 @@ def candidate_metadata(def paired_champion_aucs(- client, bucket: str, prefix: str, champion: dict[str, Any], examples: pd.DataFrame, *, holdout_days: int+ client,+ bucket: str,+ prefix: str,+ champion: dict[str, Any],+ examples: pd.DataFrame,+ *,+ feature_set: FeatureSet,+ holdout_days: int,) -> dict[str, float]:"""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 the@@ -327,7 +384,9 @@ def paired_champion_aucs()if body is None:continue- auc = booster_holdout_auc(body, examples, head, holdout_days=holdout_days)+ auc = booster_holdout_auc(+ body, examples, head, feature_names=feature_set.feature_names, holdout_days=holdout_days+ )if auc is not None:aucs[head.name] = aucreturn aucs@@ -340,11 +399,17 @@ def inbox_ranking_model_candidate(context: dagster.AssetExecutionContext) -> Nonpartition_key = context.partition_keybucket, prefix, client = dataset_bucket(), settings.INBOX_RANKING_DATASET_S3_PREFIX, s3_client()- examples = read_parquet(client, bucket, partition_object_key(prefix, EXAMPLES_TABLE, partition_key)).to_pandas()+ feature_set = TABULAR_FEATURE_SET+ examples = read_parquet(client, bucket, examples_object_key(prefix, feature_set.name, partition_key)).to_pandas()trained: list[TrainedHead] = []skipped: list[str] = []for head in HEADS:- result = train_head(examples, head, holdout_days=settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS)+ result = train_head(+ examples,+ head,+ feature_names=feature_set.feature_names,+ holdout_days=settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS,+ )if result is None:context.log.warning(f"{head.name}: nothing to fit, skipped")skipped.append(head.name)@@ -365,6 +430,7 @@ def inbox_ranking_model_candidate(context: dagster.AssetExecutionContext) -> Nonpartition_key,trained,model_name=TABULAR_MODEL_NAME,+ feature_set=feature_set,skipped=skipped,trained_at=datetime.datetime.now(datetime.UTC),run_id=context.run.run_id,@@ -410,11 +476,25 @@ def inbox_ranking_model_champion(context: dagster.AssetExecutionContext) -> Nonechampion = _read_json_if_exists(client, bucket, champion_key)champion_aucs: dict[str, float] = {}if champion is not None:- examples = read_parquet(client, bucket, partition_object_key(prefix, EXAMPLES_TABLE, partition_key)).to_pandas()- champion_aucs = paired_champion_aucs(- client, bucket, prefix, champion, examples, holdout_days=settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS- )- context.log.info(f"champion {champion['model_version']} on this holdout: {champion_aucs}")+ champion_feature_set = model_feature_set(champion)+ if champion_feature_set is None:+ context.log.warning(f"champion {champion['model_version']} reads a feature set this build cannot produce")+ else:+ # The champion is graded on the examples of its own feature set, the set the candidate+ # shares: promotion stays inside a family.+ examples = read_parquet(+ client, bucket, examples_object_key(prefix, champion_feature_set.name, partition_key)+ ).to_pandas()+ champion_aucs = paired_champion_aucs(+ client,+ bucket,+ prefix,+ champion,+ examples,+ feature_set=champion_feature_set,+ holdout_days=settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS,+ )+ context.log.info(f"champion {champion['model_version']} on this holdout: {champion_aucs}")decision = decide_promotion(candidate,champion,@@ -503,7 +583,9 @@ def load_family_models(context.log.warning(f"no {model_name} {role} metadata to score the unseen pool with")continuemismatch = model_mismatch(metadata)- if mismatch is not None:+ # A set the mismatch check accepted always resolves; the None arm is there to narrow it.+ feature_set = model_feature_set(metadata)+ if mismatch is not None or feature_set is None:context.log.warning(f"{model_name} {role} {metadata.get('model_version')} not scored: {mismatch}")continueboosters = {}@@ -521,7 +603,7 @@ def load_family_models(model_name=model_name,model_version=metadata["model_version"],model_role=role,- feature_schema_version=metadata["feature_schema_version"],+ feature_set=feature_set,boosters=boosters,))@@ -555,12 +637,16 @@ def inbox_ranking_unseen_scores(context: dagster.AssetExecutionContext) -> None:day = datetime.date.fromisoformat(partition_key)snapshot = load_snapshots(client, bucket, prefix, [day], required=day)[day]- # Only the ids: the examples table is one row per (report, snapshot, head) over the lookback.- example_ids = read_parquet(- client, bucket, partition_object_key(prefix, EXAMPLES_TABLE, partition_key), columns=["report_id"]- )+ # Only the ids, from every feature set: the examples table is one row per (report, snapshot,+ # head) over the lookback, and a report is leaked if any set trained on it.+ example_ids: set[object] = set()+ for feature_set in FEATURE_SETS.values():+ ids = read_parquet(+ client, bucket, examples_object_key(prefix, feature_set.name, partition_key), columns=["report_id"]+ )+ example_ids.update(ids.column("report_id").unique().to_pylist())pool = unseen_pool(snapshot.state, day)- leaked = leaked_report_ids(pool, example_ids.column("report_id").unique().to_pylist())+ leaked = leaked_report_ids(pool, example_ids)if leaked:raise dagster.Failure(f"{len(leaked)} reports created on {partition_key} already appear in that day's training examples, "diff --git a/products/signals/dags/inbox_ranking/training/examples.py b/products/signals/dags/inbox_ranking/training/examples.pyindex cc3c8b1fc9b7..3b993c50c0a4 100644--- a/products/signals/dags/inbox_ranking/training/examples.py+++ b/products/signals/dags/inbox_ranking/training/examples.py@@ -21,35 +21,48 @@ import pandas as pdfrom posthog.dataclasses import frozen-from products.signals.backend.ranking.features import FEATURE_NAMES, feature_frame+from products.signals.backend.ranking.features import NO_EXTRAS, Extras, FeatureSetfrom products.signals.dags.inbox_ranking.common import snapshot_boundsfrom products.signals.dags.inbox_ranking.dataset.dag import label_provenance_okfrom products.signals.dags.inbox_ranking.dataset.queries import LABEL_DEFAULTSfrom products.signals.dags.inbox_ranking.training.heads import Head-# Report-state columns an example carries, besides the features. `report_age_hours` is the-# snapshot's own clock and becomes the `age_hours` feature.-STATE_COLUMNS = (- "report_created_at",- "report_age_hours",- "signal_count",- "total_weight",- "run_count",- "title_chars",- "summary_chars",- "priority",- "actionability",-)+# Report-state columns every example needs, whatever the feature set: the report's creation time+# (the holdout is cut on it), its age at the snapshot (`report_age_hours`, which becomes the+# `age_hours` every set may read), and `signal_count`, which marks a row that carries state at all.+BASE_STATE_COLUMNS = ("report_created_at", "report_age_hours", "signal_count")# Inputs of the label provenance cross-check, read next to the features and labels.PROVENANCE_STATE_COLUMNS = ("report_team_id", "status", "pg_updated_at")PROVENANCE_LABEL_COLUMNS = ("latest_status_event", "status_event_team_id")-EXAMPLE_COLUMNS = ("head", "report_id", "snapshot_date", "report_created_at", *FEATURE_NAMES, "label")+# A forward run stamps features_observed_at a few hours after the snapshot end. Anything read later# than this is a backfill that carries current Postgres state, not the state as of the snapshot.STATE_LAG_LIMIT = datetime.timedelta(days=2)+def state_columns(feature_set: FeatureSet) -> tuple[str, ...]:+ """The report-state columns to read for `feature_set`: the base ones plus its own."""+ return (*BASE_STATE_COLUMNS, *(name for name in feature_set.state_columns if name not in BASE_STATE_COLUMNS))+++def example_columns(feature_set: FeatureSet) -> tuple[str, ...]:+ """The examples Parquet columns for `feature_set`. One object per set, because two sets carry+ different feature columns."""+ return ("head", "report_id", "snapshot_date", "report_created_at", *feature_set.feature_names, "label")+++def state_rows(state: pd.DataFrame, feature_set: FeatureSet) -> pd.DataFrame:+ """The `feature_set` slice of `state`, with the snapshot's `report_age_hours` as `age_hours`.++ Both the example builder and the unseen scorer go through this, so a report scored on the day+ it is born sees the vector it would have seen as a training example.+ """+ rows = state[list(state_columns(feature_set))].copy()+ rows["age_hours"] = rows.pop("report_age_hours").astype(float)+ return rows++@frozenclass Snapshot:"""One day's report-state and labels, both indexed by report_id."""@@ -114,10 +127,15 @@ def _flag_or_true(labels: pd.DataFrame, column: str) -> pd.Series:return labels[column].fillna(False).astype(bool) if column in labels else pd.Series(True, index=labels.index)-def build_examples(snapshots: Mapping[datetime.date, Snapshot], head: Head) -> pd.DataFrame:+def build_examples(+ snapshots: Mapping[datetime.date, Snapshot],+ head: Head,+ feature_set: FeatureSet,+ extras: Extras = NO_EXTRAS,+) -> pd.DataFrame:"""Every (report, snapshot) scoring moment for `head` whose label can be read, as one frame- with EXAMPLE_COLUMNS. Snapshots whose `horizon_days`-later snapshot is missing contribute no- examples (the label is unknowable), so a gap in the partitions simply thins the data."""+ with `feature_set`'s example columns. Snapshots whose `horizon_days`-later snapshot is missing+ contribute no examples (the label is unknowable), so a gap in the partitions thins the data."""frames: list[pd.DataFrame] = []for date in sorted(snapshots):later = snapshots.get(date + datetime.timedelta(days=head.horizon_days))@@ -145,9 +163,8 @@ def build_examples(snapshots: Mapping[datetime.date, Snapshot], head: Head) -> p)if not keep.any():continue- rows = state.loc[keep, list(STATE_COLUMNS)].copy()- rows["age_hours"] = rows.pop("report_age_hours").astype(float)- features = feature_frame(rows)+ rows = state_rows(state.loc[keep], feature_set)+ features = feature_set.build_matrix(rows, extras)examples = pd.DataFrame({"head": head.name,@@ -156,13 +173,14 @@ def build_examples(snapshots: Mapping[datetime.date, Snapshot], head: Head) -> p"report_created_at": pd.to_datetime(rows["report_created_at"], utc=True).to_numpy(),})- for name in FEATURE_NAMES:+ for name in feature_set.feature_names:examples[name] = features[name].to_numpy()examples["label"] = head.label(labels_later.loc[keep]).astype(int).to_numpy()frames.append(examples)+ columns = list(example_columns(feature_set))if not frames:- return pd.DataFrame(columns=list(EXAMPLE_COLUMNS))- return pd.concat(frames, ignore_index=True)[list(EXAMPLE_COLUMNS)]+ return pd.DataFrame(columns=columns)+ return pd.concat(frames, ignore_index=True)[columns]def holdout_mask(examples: pd.DataFrame, holdout_days: int) -> pd.Series:diff --git a/products/signals/dags/inbox_ranking/training/telemetry.py b/products/signals/dags/inbox_ranking/training/telemetry.pyindex bb5d2e8d3111..09b7081ac845 100644--- a/products/signals/dags/inbox_ranking/training/telemetry.py+++ b/products/signals/dags/inbox_ranking/training/telemetry.py@@ -91,16 +91,22 @@ def examples_events(*,partition_key: str,run_id: str,+ feature_set: str,snapshots: int,backfilled_rows: int,per_head: Mapping[str, HeadExampleCounts],) -> list[TrainingEvent]:- """One event per head with its example and positive counts; the run-level counts repeat on each."""+ """One event per head with its example and positive counts; the run-level counts repeat on each.++ Examples are per feature set, not per model family: every family on a set trains on one+ Parquet, so `feature_set` is the dimension that separates two of these series.+ """return [TrainingEvent(event=EXAMPLES_BUILT_EVENT,properties={"model_version": partition_key,+ "feature_set": feature_set,"run_id": run_id,"snapshots": snapshots,"backfilled_state_rows_excluded": backfilled_rows,diff --git a/products/signals/dags/inbox_ranking/training/train.py b/products/signals/dags/inbox_ranking/training/train.pyindex 8e4edd52526f..ffc60fb18059 100644--- a/products/signals/dags/inbox_ranking/training/train.py+++ b/products/signals/dags/inbox_ranking/training/train.py@@ -1,10 +1,13 @@"""Per-head XGBoost training over the scoring-moment examples.Deliberately plain: fixed hyperparameters, a time-based holdout by report, AUC plus a-label-permutation null per head. The booster is saved as UBJSON bytes with its feature names, so-the serving side can assert `booster.feature_names == FEATURE_NAMES` at load.+label-permutation null per head. The feature names come from the caller's feature set, so one+learner serves every family; the booster is saved as UBJSON bytes with those names, so the serving+side can assert them against the set the model declares."""+from collections.abc import Sequence+import numpy as npimport pandas as pdimport xgboost as xgb@@ -12,7 +15,6 @@ from sklearn.metrics import average_precision_score, log_loss, roc_auc_scorefrom posthog.dataclasses import frozen-from products.signals.backend.ranking.features import FEATURE_NAMESfrom products.signals.dags.inbox_ranking.training.examples import holdout_maskfrom products.signals.dags.inbox_ranking.training.heads import Head@@ -113,13 +115,15 @@ def _head_readable(return holdout_positives >= min_positives and holdout_auc > 0.5 and holdout_auc - null_auc >= NULL_MARGIN-def train_head(examples: pd.DataFrame, head: Head, *, holdout_days: int, seed: int = 0) -> TrainedHead | None:+def train_head(+ examples: pd.DataFrame, head: Head, *, feature_names: Sequence[str], holdout_days: int, seed: int = 0+) -> TrainedHead | None:"""Fit one head; None when there is nothing to fit (no positive or no negative in train)."""rows = examples[examples["head"] == head.name]if rows.empty:return Nonetest = holdout_mask(rows, holdout_days).to_numpy()- x = rows[list(FEATURE_NAMES)].astype(float)+ x = rows[list(feature_names)].astype(float)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):@@ -173,7 +177,9 @@ def train_head(examples: pd.DataFrame, head: Head, *, holdout_days: int, seed: i)-def booster_holdout_auc(booster_ubj: bytes, examples: pd.DataFrame, head: Head, *, holdout_days: int) -> float | None:+def booster_holdout_auc(+ 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."""rows = examples[examples["head"] == head.name]@@ -184,10 +190,10 @@ def booster_holdout_auc(booster_ubj: bytes, examples: pd.DataFrame, head: Head,return Nonebooster = xgb.Booster()booster.load_model(bytearray(booster_ubj))- # The booster's own names, not the current contract: a champion trained before an additive- # schema bump is still scorable on its subset. A name the examples lack means the schemas are- # incompatible, and the caller falls back to the stored AUC.- names = list(booster.feature_names or FEATURE_NAMES)+ # The booster's own names, not the set's: a champion trained before an additive schema bump is+ # still scorable on its subset. A name the examples lack means the schemas are incompatible,+ # and the caller falls back to the stored AUC.+ names = list(booster.feature_names or feature_names)if any(name not in rows for name in names):return Nonex = rows.loc[test, names].astype(float)diff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.pyindex b67c1e9dca12..4faf7ba3a1e0 100644--- a/products/signals/dags/inbox_ranking/training/unseen.py+++ b/products/signals/dags/inbox_ranking/training/unseen.py@@ -23,9 +23,9 @@ from sklearn.metrics import roc_auc_scorefrom posthog.dataclasses import frozen-from products.signals.backend.ranking.features import FEATURE_NAMES, FEATURE_SCHEMA_VERSION, feature_frame+from products.signals.backend.ranking.features import NO_EXTRAS, Extras, FeatureSet, feature_set_by_namefrom products.signals.dags.inbox_ranking.common import snapshot_bounds-from products.signals.dags.inbox_ranking.training.examples import STATE_COLUMNS, point_in_time_mask+from products.signals.dags.inbox_ranking.training.examples import point_in_time_mask, state_rowsfrom products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, Head# Stamped on every scored event, so a chart can tell this pool definition from a later one.@@ -86,12 +86,13 @@ FEATURE_INPUT_COLUMNS = (@frozenclass UnseenModel:- """One model to score the pool with, and the readable heads it can score."""+ """One model to score the pool with, the feature set it was fit on, and the readable heads it+ can score. Models that share a feature set share one matrix."""model_name: strmodel_version: strmodel_role: str- feature_schema_version: int+ feature_set: FeatureSetboosters: Mapping[str, bytes]@@ -188,13 +189,26 @@ def chance_band(outcomes: np.ndarray, scores: np.ndarray) -> ChanceBand:return ChanceBand(auc=float(np.mean(aucs)), auc_std=float(np.std(aucs)))+def model_feature_set(metadata: Mapping[str, Any]) -> FeatureSet | None:+ """The feature set the model declares, or None when this build cannot produce it. Metadata+ written before the field existed declares nothing and reads as the tabular set."""+ return feature_set_by_name(metadata.get("feature_set"))++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."""+ """Why the model cannot be scored, or None when it can.++ A model is checked against its own declared set rather than one global contract, so a family+ on a richer set is not rejected for disagreeing with the tabular one.+ """+ feature_set = model_feature_set(metadata)+ if feature_set is None:+ return f"feature set {metadata.get('feature_set')} is not one this build can produce"version = metadata.get("feature_schema_version")- if version != FEATURE_SCHEMA_VERSION:- return f"feature_schema_version {version} is not the serving contract's {FEATURE_SCHEMA_VERSION}"- if tuple(metadata.get("feature_names") or ()) != FEATURE_NAMES:- return "feature_names differ from the serving contract"+ if version != feature_set.schema_version:+ return f"feature_schema_version {version} is not {feature_set.name}'s {feature_set.schema_version}"+ if tuple(metadata.get("feature_names") or ()) != feature_set.feature_names:+ return f"feature_names differ from the {feature_set.name} feature set"return None@@ -276,46 +290,58 @@ def with_model_names(scores: pd.DataFrame) -> pd.DataFrame:def score_pool(- pool: pd.DataFrame, labels: pd.DataFrame, models: Sequence[UnseenModel], *, snapshot_date: datetime.date+ pool: pd.DataFrame,+ labels: pd.DataFrame,+ models: Sequence[UnseenModel],+ *,+ snapshot_date: datetime.date,+ extras: Extras = NO_EXTRAS,) -> pd.DataFrame:"""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- head's outcome had already happened on the scoring day; the grader drops those rows, the same- way the example builder drops a scoring moment whose label is already 1.+ same vector it would have seen as a training example. One matrix is built per feature set the+ models declare, and every model on that set scores against it. `label_at_scoring` records+ whether the head's outcome had already happened on the scoring day; the grader drops those+ rows, the same way the example builder drops a scoring moment whose label is already 1."""- rows = pool[list(STATE_COLUMNS)].copy()- rows["age_hours"] = rows.pop("report_age_hours").astype(float)- matrix = xgb.DMatrix(feature_frame(rows), feature_names=list(FEATURE_NAMES))aligned_labels = labels.reindex(pool.index)team_id = pool["report_team_id"] if "report_team_id" in pool else pd.Series(None, index=pool.index, dtype=object)report_ids = pool.index.to_numpy()team_ids = pd.to_numeric(team_id, errors="coerce").astype("Int64").to_numpy()- created_at = pd.to_datetime(rows["report_created_at"], utc=True).to_numpy()- age_hours = rows["age_hours"].to_numpy()- frames = [- pd.DataFrame(- {- "report_id": report_ids,- "team_id": team_ids,- "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,- "head": head_name,- "score": _predict(booster_ubj, matrix),- "age_hours": age_hours,- "label_at_scoring": HEADS_BY_NAME[head_name].label(aligned_labels).to_numpy(),- }+ created_at = pd.to_datetime(pool["report_created_at"], utc=True).to_numpy()+ age_hours = pool["report_age_hours"].astype(float).to_numpy()+ matrices: dict[str, xgb.DMatrix] = {}+ frames: list[pd.DataFrame] = []+ for model in models:+ feature_set = model.feature_set+ if feature_set.name not in matrices:+ matrices[feature_set.name] = xgb.DMatrix(+ feature_set.build_matrix(state_rows(pool, feature_set), extras),+ feature_names=list(feature_set.feature_names),+ )+ matrix = matrices[feature_set.name]+ frames.extend(+ pd.DataFrame(+ {+ "report_id": report_ids,+ "team_id": team_ids,+ "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": feature_set.schema_version,+ "head": head_name,+ "score": _predict(booster_ubj, matrix),+ "age_hours": age_hours,+ "label_at_scoring": HEADS_BY_NAME[head_name].label(aligned_labels).to_numpy(),+ }+ )+ for head_name, booster_ubj in model.boosters.items())- for model in models- for head_name, booster_ubj in model.boosters.items()- ]if not frames:return pd.DataFrame(columns=list(SCORE_COLUMNS))return pd.concat(frames, ignore_index=True)[list(SCORE_COLUMNS)]