: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
feat(signals): train a report-embeddings family on the unseen read (#98663)
posthog[bot]a207f767cad6
diff --git a/products/signals/backend/ranking/features.py b/products/signals/backend/ranking/features.pyindex 12ff651949ba..2f69dea2b6f3 100644--- a/products/signals/backend/ranking/features.py+++ b/products/signals/backend/ranking/features.py@@ -14,15 +14,19 @@ 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 latest-judgment artefacts. Embeddings wait for the score log to accrue (skill issue 14).+judgment artefacts. The report-embeddings set is the second one, and the sweep does not serve it:+it is an offline candidate graded on the unseen read, and serving it needs the report vector at+scoring time (skill issue 14)."""import abcimport math+import datetimefrom collections.abc import Mappingfrom types import MappingProxyTypefrom typing import Any+import numpy as npimport pandas as pdFEATURE_SCHEMA_VERSION = 1@@ -65,6 +69,24 @@ TABULAR_STATE_COLUMNS: tuple[str, ...] = (Extras = Mapping[str, pd.DataFrame]NO_EXTRAS: Extras = MappingProxyType({})+# The report vector, under this key in `extras`: the dataset dag's `inbox_report_embeddings`+# snapshot, indexed by report_id, with the vector in `EMBEDDING_COLUMN` and the moment that vector+# landed in `EMBEDDING_INSERTED_AT_COLUMN`.+REPORT_EMBEDDINGS_EXTRA = "report_embeddings"+EMBEDDING_COLUMN = "embedding_small"+EMBEDDING_INSERTED_AT_COLUMN = "embedding_inserted_at"+# The width of text-embedding-3-small-1536, the model the report documents are embedded with. A+# row whose vector is a different length is not this model's, so it is treated as missing.+EMBEDDING_DIMENSIONS = 1536++# How many rows one report contributes to a head's examples.+# `scoring_moment` is one row per (report, snapshot): the serving situation replayed over the+# snapshots of the lookback. `report` is one row per report, at the first snapshot of the window+# where it is a usable scoring moment, which is the grain of the newborn pool the unseen read+# grades.+SCORING_MOMENT_GRAIN = "scoring_moment"+REPORT_GRAIN = "report"+def _number(value: Any) -> float:if value is None:@@ -119,22 +141,48 @@ def feature_frame(rows: pd.DataFrame) -> pd.DataFrame: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.+ `state_columns` are the report-state columns `build_matrix` reads, and `extras_keys` the side+ inputs it needs next to them. The caller always adds `age_hours`, so a set may read that+ without declaring it. `example_grain` and `max_examples_per_head` size the set's example+ population: a set 1536 columns wide cannot afford the row count a set 15 columns wide can."""name: strschema_version: intfeature_names: tuple[str, ...]state_columns: tuple[str, ...]+ extras_keys: tuple[str, ...] = ()+ example_grain: str = SCORING_MOMENT_GRAIN+ # Rows one head's examples may keep, or None for every row the grain produces.+ max_examples_per_head: int | None = None@abc.abstractmethod- def build_matrix(self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS) -> pd.DataFrame:+ def build_matrix(+ self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS, *, as_of: datetime.datetime | None = None+ ) -> 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.+ `extras` carries the side inputs a set needs beyond report state. `as_of` is the moment+ being scored, so a set reading a side input that changes over a report's life takes the+ value the report had then rather than the latest one.+ """++ def buildable(+ self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS, *, as_of: datetime.datetime | None = None+ ) -> pd.Series:+ """True for each row of `rows` this set can build a real vector for at `as_of`; every row by+ default.++ A set reading a side input has rows it cannot cover, and the example builder keeps only the+ rows that are True, so a training row never carries an all-missing vector. The scorer does+ not filter on this: every family scores the whole pool, or the grades stop being paired."""+ return pd.Series(True, index=rows.index)++ def missing_extras(self, extras: Extras) -> tuple[str, ...]:+ """The side inputs this set declares that `extras` does not carry."""+ return tuple(key for key in self.extras_keys if key not in extras)class TabularFeatureSet(FeatureSet):@@ -146,15 +194,113 @@ class TabularFeatureSet(FeatureSet):feature_names = FEATURE_NAMESstate_columns = TABULAR_STATE_COLUMNS- def build_matrix(self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS) -> pd.DataFrame:+ def build_matrix(+ self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS, *, as_of: datetime.datetime | None = None+ ) -> pd.DataFrame:return feature_frame(rows)TABULAR_FEATURE_SET = TabularFeatureSet()++class ReportEmbeddingsFeatureSet(FeatureSet):+ """The report's own embedding vector, and nothing else, at one example per report.++ Two modelling calls this set records, both open questions on the issue that asked for it+ (posthog#98243):++ Embedding only, no age. Age is the whole signal of the `recency_auc` line the unseen read+ already reports next to every grade, so leaving it out keeps the uplift claim clean: a gap to+ that line is content, not recency. A set that mixes the two is a third family, not a variant.++ One example per report, not one per scoring moment. A day's newborns over the whole lookback,+ times 1536 floats, is gigabytes of Parquet per partition and more than the training pod holds,+ which is what rules the moment grain out at this width. The first snapshot where a report is a+ usable scoring moment is also the grain of the newborn pool the unseen read grades, so the+ training population matches the graded one. `max_examples_per_head` bounds what is left; the+ lookback stays the tabular set's, so positives still accrue over the whole window.++ Vectors arrive through `extras`, from the dt=D `inbox_report_embeddings` snapshot, which holds+ the latest vector per report. A report is re-embedded whenever its text changes, and the+ summary workflow and each re-research run rewrite it, so the latest vector can postdate the+ moment being built. `as_of` is therefore load-bearing rather than a nicety: a moment takes the+ vector only when that vector had already landed, and at the report grain the example moves to+ the first snapshot where it had. Without the check the family would train on text that did not+ exist when the report was supposedly scored, which is the one thing that would invalidate the+ comparison this family exists for.++ A report the snapshot has no vector for at all is not buildable either: the source table's TTL+ runs from report creation, so a long-lived report loses its vector while still live, and an+ all-missing row would teach the booster nothing but the base rate.+ """++ name = "report_embeddings"+ schema_version = 1+ # Position order, so `emb_i` is the vector's ith component in every matrix this set builds.+ feature_names = tuple(f"emb_{index}" for index in range(EMBEDDING_DIMENSIONS))+ state_columns = ()+ extras_keys = (REPORT_EMBEDDINGS_EXTRA,)+ example_grain = REPORT_GRAIN+ # 1536 float32 columns, so a head's Parquet slice and its training matrix both scale with this.+ # Sized so every head of this family fits one partition's examples object and the fits stay+ # inside the training job's runtime budget, with the budget spent on positives first.+ max_examples_per_head = 25_000++ def build_matrix(+ self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS, *, as_of: datetime.datetime | None = None+ ) -> pd.DataFrame:+ vectors = self._aligned_vectors(rows, extras, as_of)+ buildable = self._is_vector(vectors).to_numpy()+ matrix = np.full((len(rows), EMBEDDING_DIMENSIONS), np.nan, dtype=np.float32)+ if buildable.any():+ matrix[buildable] = np.vstack(vectors.to_numpy()[buildable])+ return pd.DataFrame(matrix, index=rows.index, columns=list(self.feature_names))++ def buildable(+ self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS, *, as_of: datetime.datetime | None = None+ ) -> pd.Series:+ return self._is_vector(self._aligned_vectors(rows, extras, as_of))++ def _aligned_vectors(self, rows: pd.DataFrame, extras: Extras, as_of: datetime.datetime | None) -> pd.Series:+ """The vector per row of `rows`: a missing value where the snapshot holds none, and where it+ holds one that landed after `as_of`.++ A vector with no landing time is dropped rather than trusted, because the check cannot be+ made for it.+ """+ vectors = extras.get(REPORT_EMBEDDINGS_EXTRA)+ if vectors is None or EMBEDDING_COLUMN not in vectors:+ return pd.Series(None, index=rows.index, dtype=object)+ aligned = vectors[EMBEDDING_COLUMN].reindex(rows.index)+ if as_of is None:+ return aligned+ if EMBEDDING_INSERTED_AT_COLUMN not in vectors:+ raise ValueError(+ f"the {REPORT_EMBEDDINGS_EXTRA} side input needs {EMBEDDING_INSERTED_AT_COLUMN} "+ "to be read as of a moment"+ )+ landed = pd.to_datetime(vectors[EMBEDDING_INSERTED_AT_COLUMN].reindex(rows.index), utc=True)+ return aligned.where(landed.notna() & (landed <= as_of))++ @staticmethod+ def _is_vector(vectors: pd.Series) -> pd.Series:+ # An isinstance check rather than a null check: `reindex` fills a missing row with NaN,+ # which is neither None nor a vector, and a wrong-length row is another model's.+ return vectors.map(+ lambda vector: isinstance(vector, list | np.ndarray) and len(vector) == EMBEDDING_DIMENSIONS+ ).astype(bool)+++REPORT_EMBEDDINGS_FEATURE_SET = ReportEmbeddingsFeatureSet()+# 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})+FEATURE_SETS: Mapping[str, FeatureSet] = MappingProxyType(+ {+ TABULAR_FEATURE_SET.name: TABULAR_FEATURE_SET,+ REPORT_EMBEDDINGS_FEATURE_SET.name: REPORT_EMBEDDINGS_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_SETdiff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.mdindex 3d675be23cc0..349a37b10b89 100644--- a/products/signals/dags/inbox_ranking/AGENTS.md+++ b/products/signals/dags/inbox_ranking/AGENTS.md@@ -11,11 +11,16 @@ Read `README.md` first for what the dataset is and how partitions behave. This f- `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.+- A set that reads a side input declares it in `extras_keys`, and reports per-row availability through `buildable`. The example builder drops the rows `buildable` returns False for. The scorer deliberately does not drop rows: every family scores the whole newborn pool, or the AUCs stop being paired and the uplift read the families exist for is unmeasurable. Watch `<set>_pool_coverage` on the scores asset instead.+- Both `buildable` and `build_matrix` take the moment being built as `as_of`, and a side input that changes over a report's life must honor it. The report vector does: reports are re-embedded when their text changes, so the snapshot's latest vector often postdates the moment, and taking it would train on text that did not exist yet. Never widen a set's side input to the latest value for convenience.+- `example_grain` and `max_examples_per_head` are per set, because the examples object is. Keep the tabular set at the scoring-moment grain with no budget: `report_embeddings` is the reason both knobs exist (1536 columns per row), and a budget on the tabular set would thin the family the other lines are measured against. A budget keeps every positive, so it moves the base rate its scores calibrate to and not the ranking.- `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.+- Examples are scoring moments (every report × every snapshot) unless the set asks for the report grain, 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. The moments are chosen before the features are built, so a set under a row budget never builds columns for rows it then drops; keep that order.- `inbox_ranking_models/v1/<model_name>/dt=D/` is history like the dataset partitions: the only mutation is a re-run of the same partition, which replaces the prefix in full (stale head files are deleted). `<model_name>/champion.json` is the only object written outside its partition, and only the champion asset (or a human, deliberately) writes it; it carries the candidate's `run_id`, so a loader can detect a re-run behind a pinned version.- 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.+- `model_name` is the model family, and every model object, scored row, grade and event carries it. A family is an entry in `MODEL_FAMILIES` (`training/unseen.py`) naming the feature set it is fit on; the candidate and champion assets walk that registry, and the loader, the grader and the events need no change to gain a family. 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.+- A family whose `metadata.json`, examples object or side input is missing for a partition is logged and skipped, so one family does not cost every family's series. The champion asset raises only when no family has a candidate at all.+- Skipping is not the same as rebuilding from nothing, and the difference is destructive. An empty examples object produces an empty candidate, and the candidate's prefix cleanup then deletes the boosters that partition already holds, which a `champion.json` can be pointing at. So when a side input is unavailable, leave the partition's objects alone rather than writing empty ones over them.- 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.mdindex 74f2c0c9cdca..bb45a8e8b688 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -72,20 +72,24 @@ 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.-- **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.+- **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, `build_matrix`, and how many rows it wants per report and per head. `tabular` and `report_embeddings` are the two 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 by default.** For partition `dt=D` the examples asset reads the report-state and labels snapshots `dt=D-lookback..D` and emits one row per (report, 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.-- **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.+- **A set may ask for the report grain instead**, one example per report at its first usable scoring moment of the window, and cap the rows one head keeps (`max_examples_per_head`, all positives first, then a seeded sample of the negatives). Both knobs exist for `report_embeddings`: at 1536 columns the moment grain is gigabytes of Parquet per partition and more than the training pod holds. The row budget changes the base rate its scores are calibrated to, not the ranking the unseen AUC reads. The lookback is the tabular set's either way, so positives accrue over the whole window.+- **`tabular` is the serving set** (the state counters, title/summary length, age, one-hot priority/actionability). No embedding, no impression-derived columns, so the scoring sweep needs only the `SignalReport` row and its judgment artefacts. The sweep must build features through the same module; the booster's `feature_names` are checked against it at load.+- **`report_embeddings` is the report's own vector and nothing else**, read from the dt=D `inbox_report_embeddings` snapshot as a side input. Age is deliberately left out: it is the whole signal of the `recency_auc` line the unseen read already reports, so a gap to that line is content rather than recency. The scoring sweep does not serve this set: it is an offline candidate, and serving it needs the report vector at scoring time.+- **A moment only takes a vector that already existed for it.** The snapshot holds the latest vector per report, and a report is re-embedded whenever its text changes (the summary workflow and every re-research run rewrite it), so the latest vector often postdates an earlier moment. Each row carries `embedding_inserted_at`, and a moment keeps the vector only when it landed at or before that snapshot's end; at the report grain the example then moves to the first snapshot where the vector was already the report's own. Without that check the family would train on text that did not exist when the report was supposedly scored. A report the snapshot has no vector for at all is not an example either, because the source table's TTL runs from report creation and a long-lived report loses its vector while still live. The scores asset records each set's coverage of the newborn pool, so a thin side input is visible rather than silent.+- **A set whose side input is unavailable is skipped, not rebuilt from nothing.** The examples asset writes no object for it, the candidate asset leaves that family's partition as it stands, and the unseen scorer drops its models for the day. Rebuilding would write an empty examples object, then an empty candidate, and the candidate's prefix cleanup would delete boosters a champion pointer can name.+- **Candidate**: one per family, per-head XGBoost with fixed params, holdout = the last `holdout_days` of reports (cut by report, never by row), AUC + a label-permutation null. Each family trains on the examples of the feature set its registry entry names, and a family whose examples or metadata are missing that day is logged and skipped rather than failing the asset. A head is _readable_ when it has enough holdout positives and clears its null by 0.05. The shipped booster (`<head>.ubj`) is refit on everything; the train-only fit is kept as `<head>.holdout.ubj` so a later candidate can grade this model on its own holdout.- **Metrics telemetry**: each asset also captures its metrics as events into the dogfood project (the same project the label events land in), through `training/telemetry.py`: `inbox_ranking_examples_built` once per head and feature set, `inbox_ranking_candidate_trained` once per head (`head`, 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`.+- **Champion**: one decision per family against that family's own pointer. `promotion.decide_promotion` — promote when the candidate has a readable head, is within 0.02 AUC of the champion on every head the champion could read, and the champion is at least `INBOX_RANKING_PROMOTION_MIN_DAYS` old. The champion's AUCs come from its `<head>.holdout.ubj` scored on the candidate's holdout (`paired_champion_aucs`), so both models are compared on one set of reports; a champion without that file falls back to its stored AUC. The pointer is rewritten only when `INBOX_RANKING_AUTO_PROMOTE` is on; otherwise the decision is logged and surfaced as asset metadata, so the daily candidate series is monitoring while the first shadow read runs on a frozen champion. To promote by hand, copy a candidate's `metadata.json` to `champion.json` with a `promoted_at`.### The unseen readThe 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), `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_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. Every family scores the whole pool, including reports whose side input has no row for them, because grades are only comparable on paired rows; the `<set>_pool_coverage` metadata says how much of the pool each set could build a real vector for. 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.@@ -103,7 +107,7 @@ The training job is S3-only, so it can run on a laptop against copies of the proINBOX_RANKING_READER_SECRET_ID=<secret id> products/signals/dags/inbox_ranking/bin/sync_snapshots_local.sh```- This copies `inbox_report_state/v1/dt=*` and `inbox_report_labels/v1/dt=*` to `~/.cache/posthog/inbox_ranking/` and from there into `s3://posthog/inbox_ranking/` on SeaweedFS (`localhost:19000`). It prints the partition days present in both tables; pick the **newest** of those as the partition to run. The examples asset reads the `INBOX_RANKING_TRAINING_LOOKBACK_DAYS` snapshots behind the partition it runs for, so an early day has little history behind it and trains on almost nothing. Re-runs only move new days.+ This copies `inbox_report_state/v1/dt=*` and `inbox_report_labels/v1/dt=*` to `~/.cache/posthog/inbox_ranking/` and from there into `s3://posthog/inbox_ranking/` on SeaweedFS (`localhost:19000`). `INBOX_RANKING_SYNC_EMBEDDINGS=1` adds `inbox_report_embeddings`, which the `report_embeddings` family needs; it is off by default because that table carries a vector per live report per partition. Without it the job still runs, and that family builds no examples. It prints the partition days present in both tables; pick the **newest** of those as the partition to run. The examples asset reads the `INBOX_RANKING_TRAINING_LOOKBACK_DAYS` snapshots behind the partition it runs for, so an early day has little history behind it and trains on almost nothing. Re-runs only move new days.Note that the dev stack's object storage accepts unsigned requests and publishes port 19000 on every host interface, so anything synced here (and the disk cache) is readable by whoever can reach your machine. The snapshots are internal dogfood telemetry, not customer data, but run the sync on a network you trust.diff --git a/products/signals/dags/inbox_ranking/bin/sync_snapshots_local.sh b/products/signals/dags/inbox_ranking/bin/sync_snapshots_local.shindex 2e8a01fac342..5fb8812e29c8 100755--- a/products/signals/dags/inbox_ranking/bin/sync_snapshots_local.sh+++ b/products/signals/dags/inbox_ranking/bin/sync_snapshots_local.sh@@ -4,6 +4,12 @@## products/signals/dags/inbox_ranking/bin/sync_snapshots_local.sh#+# INBOX_RANKING_SYNC_EMBEDDINGS=1 also copies inbox_report_embeddings, the report vectors the+# report_embeddings family trains on. It is off by default because that table holds a 1536-float+# vector per live report per partition, which is orders of magnitude more to pull than the other+# two together. Without it the training job still runs: the family finds no vector for any report+# and builds no examples, and every other family is unaffected.+## Two hops: prod S3 -> a disk cache -> the local object-storage bucket. The disk copy is what# makes a re-sync cheap (aws s3 sync only moves new partitions) and doubles as input for# notebooks. Only the dt= partitions the training job reads are copied; latest/ is skipped.@@ -27,6 +33,9 @@ LOCAL_KEY="${OBJECT_STORAGE_ACCESS_KEY_ID:-object_storage_root_user}"LOCAL_SECRET="${OBJECT_STORAGE_SECRET_ACCESS_KEY:-object_storage_root_password}"CACHE_DIR="${INBOX_RANKING_SYNC_DIR:-$HOME/.cache/posthog/inbox_ranking}"TABLES=(inbox_report_state inbox_report_labels)+if [ -n "${INBOX_RANKING_SYNC_EMBEDDINGS:-}" ]; then+ TABLES+=(inbox_report_embeddings)+fiif [ -z "${INBOX_RANKING_READER_SECRET_ID:-}" ]; thenecho "Set INBOX_RANKING_READER_SECRET_ID to the Secrets Manager id of the dataset reader credential." >&2diff --git a/products/signals/dags/inbox_ranking/common.py b/products/signals/dags/inbox_ranking/common.pyindex 203f16508f03..9fc2ed92482d 100644--- a/products/signals/dags/inbox_ranking/common.py+++ b/products/signals/dags/inbox_ranking/common.py@@ -184,10 +184,10 @@ def read_parquet(client, bucket: str, key: str, columns: list[str] | None = Nonereturn pq.read_table(pa.BufferReader(body), columns=columns)-def read_parquet_if_exists(client, bucket: str, key: str) -> pa.Table | None:+def read_parquet_if_exists(client, bucket: str, key: str, columns: list[str] | None = None) -> pa.Table | None:"""The object's rows, or None when it was never written."""try:- return read_parquet(client, bucket, key)+ return read_parquet(client, bucket, key, columns)except ClientError as error:if error.response.get("Error", {}).get("Code") in ("404", "NoSuchKey", "NotFound"):return Nonediff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.pyindex 49fc6768fc44..6acd550fc1de 100644--- a/products/signals/dags/inbox_ranking/tests/test_training.py+++ b/products/signals/dags/inbox_ranking/tests/test_training.py@@ -17,9 +17,14 @@ from botocore.exceptions import ClientErrorfrom posthog import settingsfrom products.signals.backend.ranking.features import (+ EMBEDDING_COLUMN,+ EMBEDDING_DIMENSIONS,+ EMBEDDING_INSERTED_AT_COLUMN,FEATURE_NAMES,FEATURE_SCHEMA_VERSION,NO_EXTRAS,+ REPORT_EMBEDDINGS_EXTRA,+ REPORT_EMBEDDINGS_FEATURE_SET,TABULAR_FEATURE_SET,Extras,FeatureSet,@@ -31,6 +36,7 @@ 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,+ _train_candidate,candidate_metadata,champion_object_key,examples_object_key,@@ -39,6 +45,8 @@ from products.signals.dags.inbox_ranking.training.dag import (load_snapshots,load_unseen_models,model_object_key,+ models_with_extras,+ pool_feature_coverage,snapshot_dates,)from products.signals.dags.inbox_ranking.training.examples import (@@ -46,6 +54,7 @@ from products.signals.dags.inbox_ranking.training.examples import (Snapshot,assemble_snapshot,build_examples,+ cap_examples,example_columns,holdout_mask,)@@ -69,9 +78,12 @@ from products.signals.dags.inbox_ranking.training.unseen import (CANDIDATE_ROLE,CHAMPION_ROLE,LEGACY_POOL_NAME,+ MODEL_FAMILIES,POOL_NAME,+ REPORT_EMBEDDINGS_MODEL_NAME,SCORE_COLUMNS,TABULAR_MODEL_NAME,+ ModelFamily,UnseenModel,chance_band,empty_scores_write_allowed,@@ -87,8 +99,7 @@ from products.signals.dags.inbox_ranking.training.unseen import (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"+EMBEDDINGS_MODEL_NAME = REPORT_EMBEDDINGS_MODEL_NAMED0 = datetime.date(2026, 8, 10)NOW = datetime.datetime(2026, 8, 20, tzinfo=datetime.UTC)@@ -710,7 +721,10 @@ def test_load_unseen_models_skips_a_family_with_nothing_to_score_that_day(monkey)monkeypatch.setattr("products.signals.dags.inbox_ranking.training.dag.MODEL_FAMILIES",- (EMBEDDINGS_MODEL_NAME, TABULAR_MODEL_NAME),+ (+ ModelFamily(name=EMBEDDINGS_MODEL_NAME, feature_set=REPORT_EMBEDDINGS_FEATURE_SET),+ ModelFamily(name=TABULAR_MODEL_NAME, feature_set=TABULAR_FEATURE_SET),+ ),)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] == [@@ -1012,6 +1026,10 @@ def test_model_key_layout_is_stable():champion_object_key("inbox_ranking", TABULAR_MODEL_NAME)== "inbox_ranking/inbox_ranking_models/v1/tabular_xgb/champion.json")+ assert (+ model_object_key("inbox_ranking", EMBEDDINGS_MODEL_NAME, "2026-08-19", "open.ubj")+ == "inbox_ranking/inbox_ranking_models/v1/report_embeddings/dt=2026-08-19/open.ubj"+ )assert snapshot_dates("2026-08-19", 2) == [datetime.date(2026, 8, 17),datetime.date(2026, 8, 18),@@ -1028,7 +1046,9 @@ class _AgeOnlyFeatureSet(FeatureSet):feature_names = ("age_hours",)state_columns = ()- def build_matrix(self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS) -> pd.DataFrame:+ def build_matrix(+ self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS, *, as_of: datetime.datetime | None = None+ ) -> pd.DataFrame:return rows[["age_hours"]].astype(float)@@ -1041,11 +1061,14 @@ class _CountingFeatureSet(FeatureSet):self.schema_version = inner.schema_versionself.feature_names = inner.feature_namesself.state_columns = inner.state_columns+ self.extras_keys = inner.extras_keysself.builds = 0- def build_matrix(self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS) -> pd.DataFrame:+ def build_matrix(+ self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS, *, as_of: datetime.datetime | None = None+ ) -> pd.DataFrame:self.builds += 1- return self.inner.build_matrix(rows, extras)+ return self.inner.build_matrix(rows, extras, as_of=as_of)def _booster_ubj(feature_names: tuple[str, ...]) -> bytes:@@ -1107,7 +1130,16 @@ def _model_metadata(**overrides) -> dict[str, Any]:(_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_set=REPORT_EMBEDDINGS_FEATURE_SET.name,+ feature_schema_version=REPORT_EMBEDDINGS_FEATURE_SET.schema_version,+ feature_names=list(REPORT_EMBEDDINGS_FEATURE_SET.feature_names),+ ),+ None,+ ),+ # A set a later build introduced, or one that has been withdrawn.+ (_model_metadata(feature_set="mmoe_trunk"), "this build can produce"),(_model_metadata(feature_schema_version=99), "feature_schema_version 99"),(_model_metadata(feature_names=["age_hours"]), "feature_names differ"),],@@ -1119,19 +1151,22 @@ def test_model_mismatch_checks_a_model_against_its_own_feature_set(metadata, expassert 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():[email protected]("family", MODEL_FAMILIES, ids=[family.name for family in MODEL_FAMILIES])+def test_candidate_metadata_declares_the_set_it_was_fit_on(family):# The trainer's own record must pass the grader's check, or the day's candidate goes unscored.+ # Every registered family, because the trainer fits each on the set its registry entry names.metadata = candidate_metadata("2026-08-19",[],- model_name=TABULAR_MODEL_NAME,- feature_set=TABULAR_FEATURE_SET,+ model_name=family.name,+ feature_set=family.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 metadata["model_name"] == family.name+ assert metadata["feature_set"] == family.feature_set.name+ assert metadata["feature_schema_version"] == family.feature_set.schema_versionassert model_mismatch(metadata) is None@@ -1154,3 +1189,189 @@ def test_examples_key_layout_is_per_feature_set():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")+ assert (+ examples_object_key("inbox_ranking", REPORT_EMBEDDINGS_FEATURE_SET.name, "2026-08-19")+ == "inbox_ranking/inbox_ranking_training_examples/v1/report_embeddings/dt=2026-08-19/part-00000.parquet"+ )+++# Before every snapshot the tests build, so a vector counts as present unless a test says otherwise.+LANDED_EARLY = datetime.datetime(2026, 8, 1, tzinfo=datetime.UTC)+# The end of D0, the moment a D0 example or a D0 score is built as of.+SNAPSHOT_END = datetime.datetime(2026, 8, 11, tzinfo=datetime.UTC)+++def _report_vectors(vectors: dict[str, object], landed: datetime.datetime = LANDED_EARLY) -> Extras:+ """The report-vector side input, shaped like the dt=D `inbox_report_embeddings` snapshot."""+ frame = pd.DataFrame(+ {EMBEDDING_COLUMN: list(vectors.values()), EMBEDDING_INSERTED_AT_COLUMN: [landed] * len(vectors)},+ index=pd.Index(list(vectors), name="report_id"),+ )+ return {REPORT_EMBEDDINGS_EXTRA: frame}+++def _embedding(*, first: float = 0.0) -> list[float]:+ return [first, *([0.5] * (EMBEDDING_DIMENSIONS - 1))]+++def test_report_embeddings_matrix_puts_the_vector_in_position_order():+ # `emb_i` must be the vector's ith component: the booster is saved with these names, so a+ # transposed or reordered matrix would score a report against another dimension's splits.+ rows = _state(["a", "b"])+ ascending = [float(index) for index in range(EMBEDDING_DIMENSIONS)]+ extras = _report_vectors({"a": ascending, "b": list(reversed(ascending))})++ matrix = REPORT_EMBEDDINGS_FEATURE_SET.build_matrix(rows, extras)++ assert list(matrix.columns) == list(REPORT_EMBEDDINGS_FEATURE_SET.feature_names)+ last = f"emb_{EMBEDDING_DIMENSIONS - 1}"+ assert matrix.loc["a", ["emb_0", last]].tolist() == [0.0, float(EMBEDDING_DIMENSIONS - 1)]+ assert matrix.loc["b", ["emb_0", last]].tolist() == [float(EMBEDDING_DIMENSIONS - 1), 0.0]+++ "extras",+ [+ _report_vectors({"a": None}), # a tombstoned report keeps its row with a null vector+ _report_vectors({"a": [0.5] * 8}), # another model's width+ _report_vectors({"other": _embedding()}), # no row for this report at all+ NO_EXTRAS, # the day's embeddings snapshot is missing+ ],+)+def test_a_report_without_this_models_vector_is_not_an_embeddings_example(extras):+ # An all-missing row would teach the booster nothing but the base rate, and the source table's+ # TTL runs from report creation, so a long-lived report does lose its vector while still live.+ rows = _state(["a"])++ assert REPORT_EMBEDDINGS_FEATURE_SET.buildable(rows, extras).tolist() == [False]+ assert REPORT_EMBEDDINGS_FEATURE_SET.build_matrix(rows, extras).isna().to_numpy().all()+++def test_report_grain_keeps_one_example_per_report_and_needs_a_vector():+ # The scoring-moment grain emits a near-duplicate row per snapshot, which is what 1536 columns+ # cannot afford; the first usable moment is also the grain of the pool the unseen read grades.+ head = HEADS_BY_NAME["open"]+ ids = ["a", "b"]+ snapshots: dict[datetime.date, Snapshot] = {}+ for offset in (0, 1):+ day = D0 + datetime.timedelta(days=offset)+ later = day + datetime.timedelta(days=head.horizon_days)+ snapshots[day] = Snapshot(date=day, state=_state(ids), labels=_labels(ids, open_count=[0, 0]))+ snapshots[later] = Snapshot(date=later, state=_state(ids), labels=_labels(ids, open_count=[1, 1]))+ extras = _report_vectors({"a": _embedding()})++ examples = build_examples(snapshots, head, REPORT_EMBEDDINGS_FEATURE_SET, extras)++ assert examples["report_id"].tolist() == ["a"]+ assert examples["snapshot_date"].tolist() == [D0]+ assert examples["emb_0"].tolist() == [0.0]+ # The tabular set reads the same snapshots at the moment grain, both reports, both days.+ assert build_examples(snapshots, head, TABULAR_FEATURE_SET)["report_id"].tolist() == ["a", "b", "a", "b"]+++def test_cap_examples_keeps_every_positive_and_a_seeded_sample_of_the_negatives():+ # The budget is what keeps a 1536-column head inside one partition's object and the job's+ # runtime. Positives are the scarce side, and a re-run of a partition must keep the same rows.+ moments = pd.DataFrame({"report_id": [f"r{index}" for index in range(23)], "label": [1] * 3 + [0] * 20})++ capped = cap_examples(moments, 10)++ assert (len(capped), capped["label"].sum()) == (10, 3)+ assert capped.equals(cap_examples(moments, 10))+ assert cap_examples(moments, None) is moments+ # A head with more positives than the budget is not the case the budget is for.+ assert cap_examples(moments, 2)["label"].tolist() == [1, 1, 1]+++def test_score_pool_scores_every_newborn_even_without_a_vector():+ # Families are graded on paired rows, so a set whose side input is thin must still produce a row+ # per report; coverage is the metadata that makes a thin side input visible instead of silent.+ model = _unseen_model(EMBEDDINGS_MODEL_NAME, REPORT_EMBEDDINGS_FEATURE_SET)+ pool = _state(["a", "b"])+ extras = _report_vectors({"a": _embedding()})++ scores = score_pool(pool, _labels(["a", "b"]), [model], snapshot_date=D0, extras=extras)++ assert scores["report_id"].tolist() == ["a", "b"]+ assert scores["score"].notna().all()+ coverage = pool_feature_coverage(pool, [model], extras, SNAPSHOT_END)+ assert coverage[f"{REPORT_EMBEDDINGS_FEATURE_SET.name}_pool_coverage"].value == 0.5+++def test_a_vector_that_landed_after_the_moment_is_not_that_moments_feature():+ # The snapshot holds the latest vector per report, and a report is re-embedded whenever its text+ # changes (the summary workflow and every re-research run rewrite it). Taking the latest vector+ # for an earlier moment would train the family on text that did not exist when the report was+ # scored, which is the one defect that would invalidate the comparison it exists for.+ rows = _state(["a"])+ extras = _report_vectors({"a": _embedding()}, landed=SNAPSHOT_END + datetime.timedelta(days=1))++ assert REPORT_EMBEDDINGS_FEATURE_SET.buildable(rows, extras, as_of=SNAPSHOT_END).tolist() == [False]+ assert REPORT_EMBEDDINGS_FEATURE_SET.build_matrix(rows, extras, as_of=SNAPSHOT_END).isna().to_numpy().all()+ later = SNAPSHOT_END + datetime.timedelta(days=2)+ assert REPORT_EMBEDDINGS_FEATURE_SET.buildable(rows, extras, as_of=later).tolist() == [True]+++def test_report_grain_moves_the_example_to_the_first_moment_its_vector_existed_for():+ # A report whose vector landed after its first snapshot must not be dropped outright: its+ # example belongs on the first snapshot where that vector was already the report's own.+ head = HEADS_BY_NAME["open"]+ ids = ["a"]+ snapshots: dict[datetime.date, Snapshot] = {}+ for offset in (0, 1):+ day = D0 + datetime.timedelta(days=offset)+ later = day + datetime.timedelta(days=head.horizon_days)+ snapshots[day] = Snapshot(date=day, state=_state(ids), labels=_labels(ids, open_count=[0]))+ snapshots[later] = Snapshot(date=later, state=_state(ids), labels=_labels(ids, open_count=[1]))+ # Landed during D0 + 1, so D0 cannot have it and D0 + 1 can.+ extras = _report_vectors({"a": _embedding()}, landed=SNAPSHOT_END + datetime.timedelta(hours=6))++ examples = build_examples(snapshots, head, REPORT_EMBEDDINGS_FEATURE_SET, extras)++ assert examples["snapshot_date"].tolist() == [D0 + datetime.timedelta(days=1)]+++def test_reading_a_moment_needs_the_vectors_landing_time():+ # A side input without the landing time cannot answer "did this vector exist yet", and silently+ # treating it as current is the leak this check exists to stop.+ vectors = {REPORT_EMBEDDINGS_EXTRA: pd.DataFrame({EMBEDDING_COLUMN: [_embedding()]}, index=["a"])}+ with pytest.raises(ValueError, match=EMBEDDING_INSERTED_AT_COLUMN):+ REPORT_EMBEDDINGS_FEATURE_SET.buildable(_state(["a"]), vectors, as_of=SNAPSHOT_END)+++ "feature_set,extras,expected",+ [+ (TABULAR_FEATURE_SET, NO_EXTRAS, ()),+ (REPORT_EMBEDDINGS_FEATURE_SET, _report_vectors({"a": _embedding()}), ()),+ (REPORT_EMBEDDINGS_FEATURE_SET, NO_EXTRAS, (REPORT_EMBEDDINGS_EXTRA,)),+ ],+)+def test_a_set_declares_the_side_inputs_it_needs(feature_set, extras, expected):+ # The examples asset skips a set with a missing side input instead of rebuilding it from+ # nothing, and the scorer skips its models, so both need to ask the set what it reads.+ assert feature_set.missing_extras(extras) == expected+++def test_a_family_without_examples_keeps_the_partition_it_already_has():+ # Rebuilding from a missing examples object would write an empty candidate and delete this+ # partition's boosters, which a champion pointer can name. _EmptyS3 has no put_object or+ # delete_objects, so any write here raises instead of passing silently.+ family = ModelFamily(name=EMBEDDINGS_MODEL_NAME, feature_set=REPORT_EMBEDDINGS_FEATURE_SET)++ metadata = _train_candidate(+ dagster.build_asset_context(), _EmptyS3(), "bucket", "inbox_ranking", "2026-08-19", family+ )++ assert metadata[f"{EMBEDDINGS_MODEL_NAME}_skipped"].value is True+++def test_a_model_is_not_scored_without_the_side_input_its_set_reads():+ # Scoring every report off the booster's missing branch would put a line on the chart that says+ # nothing about the model, and the day's grade would read as the family's performance.+ tabular = _unseen_model(TABULAR_MODEL_NAME, TABULAR_FEATURE_SET)+ embeddings = _unseen_model(EMBEDDINGS_MODEL_NAME, REPORT_EMBEDDINGS_FEATURE_SET)++ kept = models_with_extras(dagster.build_asset_context(), [tabular, embeddings], NO_EXTRAS)++ assert [model.model_name for model in kept] == [TABULAR_MODEL_NAME]diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pyindex 9d649a709a9f..e5d528f33830 100644--- a/products/signals/dags/inbox_ranking/training/dag.py+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -2,7 +2,7 @@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_training_examples/v1/<set>/dt=D/ examples over the trailing snapshots, per feature setinbox_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 loadsinbox_ranking_unseen_scores/v1/dt=D/ the day's models on the reports born that day@@ -20,6 +20,11 @@ promotion rule compares both models on one set of reports. Every model object sifamily's `model_name`, and promotion stays inside a family: a richer family is a second candidategraded on the same rows, not a competitor for the tabular family's pointer.+Both the candidate and the champion asset walk `MODEL_FAMILIES`, so each family trains on the+examples of the feature set it declares and decides against its own pointer. A family whose+examples or metadata are missing that day is logged and skipped: its own series has a gap, and+every other family still trains, promotes and gets graded.+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);`inbox_ranking_unseen_graded` reads each head's scores from `D - horizon_days` and grades them@@ -40,7 +45,15 @@ from botocore.exceptions import ClientErrorfrom posthog import settings-from products.signals.backend.ranking.features import FEATURE_SETS, TABULAR_FEATURE_SET, FeatureSet+from products.signals.backend.ranking.features import (+ EMBEDDING_COLUMN,+ EMBEDDING_INSERTED_AT_COLUMN,+ FEATURE_SETS,+ NO_EXTRAS,+ REPORT_EMBEDDINGS_EXTRA,+ Extras,+ FeatureSet,+)from products.signals.dags.inbox_ranking.common import (DATASET_VERSION,PARQUET_PART_NAME,@@ -51,13 +64,13 @@ from products.signals.dags.inbox_ranking.common import (owner_tags,partition_def,partition_object_key,- read_parquet,read_parquet_if_exists,s3_client,skip_unconfigured,+ snapshot_bounds,write_parquet,)-from products.signals.dags.inbox_ranking.dataset.dag import LABELS_TABLE, STATE_TABLE+from products.signals.dags.inbox_ranking.dataset.dag import EMBEDDINGS_TABLE, LABELS_TABLE, STATE_TABLEfrom products.signals.dags.inbox_ranking.training.examples import (BASE_STATE_COLUMNS,PROVENANCE_LABEL_COLUMNS,@@ -67,6 +80,7 @@ from products.signals.dags.inbox_ranking.training.examples import (build_examples,example_columns,point_in_time_mask,+ state_rows,)from products.signals.dags.inbox_ranking.training.heads import HEADS, HEADS_BY_HORIZON, HEADS_BY_NAMEfrom products.signals.dags.inbox_ranking.training.promotion import decide_promotion@@ -85,8 +99,8 @@ from products.signals.dags.inbox_ranking.training.unseen import (CANDIDATE_ROLE,CHAMPION_ROLE,MODEL_FAMILIES,- TABULAR_MODEL_NAME,HeadGrade,+ ModelFamily,UnseenModel,empty_scores_write_allowed,graded_rows,@@ -223,6 +237,36 @@ def load_snapshots(return snapshots+def report_embeddings_extras(+ context: dagster.AssetExecutionContext, client, bucket: str, prefix: str, partition_key: str+) -> Extras:+ """The dt=D report vectors, indexed by report_id: the side input the report-embeddings set reads.++ One snapshot serves every moment of the run, and each vector carries the moment it landed, so a+ moment can only take a vector that already existed for it. A report is re-embedded whenever its+ text changes, so the latest vector is often newer than an earlier moment; the set drops those+ rather than dressing later text as earlier state. Reading one snapshot per day of the lookback+ would recover the superseded vectors, at the cost of pulling a fleet-wide vector table across+ the network once per day of the window.++ A missing snapshot is not a failure, and not an empty side input either: the caller skips the+ sets that read it, because rebuilding one of those from nothing would strip the family's+ partition.+ """+ table = read_parquet_if_exists(+ client,+ bucket,+ partition_object_key(prefix, EMBEDDINGS_TABLE, partition_key),+ columns=["report_id", EMBEDDING_COLUMN, EMBEDDING_INSERTED_AT_COLUMN],+ )+ if table is None:+ context.log.warning(f"no {EMBEDDINGS_TABLE} snapshot for dt={partition_key}; report vectors are unavailable")+ return NO_EXTRAS+ vectors = table.to_pandas().set_index("report_id")+ # `reindex` refuses a duplicated index, and one report is one document in the source.+ return {REPORT_EMBEDDINGS_EXTRA: vectors[~vectors.index.duplicated()]}++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)@@ -242,6 +286,8 @@ _LOOKBACK_MAPPING = dagster.TimeWindowPartitionMapping(deps=[dagster.AssetDep(STATE_TABLE, partition_mapping=_LOOKBACK_MAPPING),dagster.AssetDep(LABELS_TABLE, partition_mapping=_LOOKBACK_MAPPING),+ # Only dt=D: `report_embeddings_extras` explains why one snapshot serves the whole window.+ EMBEDDINGS_TABLE,],**COMMON_ASSET_KWARGS,)@@ -258,13 +304,25 @@ 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)")+ extras = report_embeddings_extras(context, client, bucket, prefix, partition_key)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():+ missing = feature_set.missing_extras(extras)+ # Rebuilding a set from a missing side input would write an empty examples object, which+ # makes the next candidate run train nothing, write metadata with no heads, and delete the+ # boosters this partition already holds. A champion pointer can name that version, so the+ # partition keeps what it has instead.+ if missing:+ context.log.warning(+ f"{feature_set.name} examples not rebuilt for dt={partition_key}: no {', '.join(missing)}"+ )+ metadata[f"{feature_set.name}_skipped"] = dagster.MetadataValue.bool(True)+ continuemetadata |= _write_examples(- context, client, bucket, prefix, partition_key, feature_set, snapshots, backfilled_rows+ context, client, bucket, prefix, partition_key, feature_set, snapshots, backfilled_rows, extras)context.add_output_metadata(metadata)@@ -278,10 +336,11 @@ def _write_examples(feature_set: FeatureSet,snapshots: Mapping[datetime.date, Snapshot],backfilled_rows: int,+ extras: Extras,) -> dict[str, dagster.MetadataValue]:"""One feature set's examples for the partition, as its own object and its own events, withthe asset metadata to record for it."""- per_head = {head.name: build_examples(snapshots, head, feature_set) for head in HEADS}+ per_head = {head.name: build_examples(snapshots, head, feature_set, extras) for head in HEADS}examples = (pd.concat(per_head.values(), ignore_index=True)if per_head@@ -399,8 +458,38 @@ 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()- feature_set = TABULAR_FEATURE_SET- examples = read_parquet(client, bucket, examples_object_key(prefix, feature_set.name, partition_key)).to_pandas()+ metadata: dict[str, dagster.MetadataValue] = {}+ for family in MODEL_FAMILIES:+ metadata |= _train_candidate(context, client, bucket, prefix, partition_key, family)+ context.add_output_metadata(metadata)+++def _train_candidate(+ context: dagster.AssetExecutionContext,+ client,+ bucket: str,+ prefix: str,+ partition_key: str,+ family: ModelFamily,+) -> dict[str, dagster.MetadataValue]:+ """One family's candidate: its heads fit on the examples of the feature set it declares, its+ boosters and `metadata.json` under its own prefix, and the asset metadata to record for it.++ Each family's examples object is read and released in turn rather than all of them up front:+ one family's object carries a column per embedding dimension, so holding two at once doubles+ the widest thing this asset touches.+ """+ feature_set = family.feature_set+ table = read_parquet_if_exists(client, bucket, examples_object_key(prefix, feature_set.name, partition_key))+ # The examples asset skips a set whose side input was unavailable, so its object can be absent.+ # Training on nothing would replace this partition's boosters with an empty candidate and leave+ # a champion pointer naming deleted files, so the family keeps this partition as it stands.+ if table is None:+ context.log.warning(+ f"no {feature_set.name} examples for dt={partition_key}; {family.name} keeps this partition as it stands"+ )+ return {f"{family.name}_skipped": dagster.MetadataValue.bool(True)}+ examples = table.to_pandas()trained: list[TrainedHead] = []skipped: list[str] = []for head in HEADS:@@ -411,10 +500,10 @@ def inbox_ranking_model_candidate(context: dagster.AssetExecutionContext) -> Nonholdout_days=settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS,)if result is None:- context.log.warning(f"{head.name}: nothing to fit, skipped")+ context.log.warning(f"{family.name} {head.name}: nothing to fit, skipped")skipped.append(head.name)continue- context.log.info(f"{head.name}: {result.metrics.as_dict()}")+ context.log.info(f"{family.name} {head.name}: {result.metrics.as_dict()}")trained.append(result)written: set[str] = set()@@ -423,41 +512,39 @@ def inbox_ranking_model_candidate(context: dagster.AssetExecutionContext) -> Nonif model.holdout_booster_ubj is not None:files[f"{model.head}.holdout.ubj"] = model.holdout_booster_ubjfor filename, body in files.items():- key = model_object_key(prefix, TABULAR_MODEL_NAME, partition_key, filename)+ key = model_object_key(prefix, family.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,+ model_name=family.name,feature_set=feature_set,skipped=skipped,trained_at=datetime.datetime.now(datetime.UTC),run_id=context.run.run_id,)- metadata_key = model_object_key(prefix, TABULAR_MODEL_NAME, partition_key, METADATA_FILE)+ metadata_key = model_object_key(prefix, family.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, TABULAR_MODEL_NAME, partition_key, ""), written- )+ stale = _delete_other_objects(client, bucket, model_object_key(prefix, family.name, partition_key, ""), written)if stale:- context.log.warning(f"removed {len(stale)} stale objects from a previous run of dt={partition_key}")+ context.log.warning(+ f"removed {len(stale)} stale {family.name} objects from a previous run of dt={partition_key}"+ )capture_training_events(context, partition_key, candidate_events(metadata))- context.add_output_metadata(- {- "stale_objects_removed": dagster.MetadataValue.int(len(stale)),- "heads_trained": dagster.MetadataValue.int(len(trained)),- "heads_readable": dagster.MetadataValue.int(sum(1 for head in trained if head.metrics.readable)),- **{- f"{head.head}_holdout_auc": dagster.MetadataValue.float(head.metrics.holdout_auc)- for head in trained- if head.metrics.holdout_auc is not None- },- "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{metadata_key}"),- }- )+ return {+ f"{family.name}_stale_objects_removed": dagster.MetadataValue.int(len(stale)),+ f"{family.name}_heads_trained": dagster.MetadataValue.int(len(trained)),+ f"{family.name}_heads_readable": dagster.MetadataValue.int(sum(1 for head in trained if head.metrics.readable)),+ **{+ f"{family.name}_{head.head}_holdout_auc": dagster.MetadataValue.float(head.metrics.holdout_auc)+ for head in trained+ if head.metrics.holdout_auc is not None+ },+ f"{family.name}_s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{metadata_key}"),+ }@dagster.asset(name="inbox_ranking_model_champion", deps=["inbox_ranking_model_candidate"], **COMMON_ASSET_KWARGS)@@ -467,34 +554,69 @@ def inbox_ranking_model_champion(context: dagster.AssetExecutionContext) -> Nonepartition_key = context.partition_keybucket, prefix, client = dataset_bucket(), settings.INBOX_RANKING_DATASET_S3_PREFIX, s3_client()+ metadata: dict[str, dagster.MetadataValue] = {}+ decided = 0+ for family in MODEL_FAMILIES:+ family_metadata = _decide_champion(context, client, bucket, prefix, partition_key, family)+ if family_metadata is None:+ continue+ decided += 1+ metadata |= family_metadata+ # Every family missing its candidate means the candidate asset wrote nothing at all, which is a+ # broken partition rather than one family's gap.+ if not decided:+ raise dagster.Failure(f"no candidate metadata for dt={partition_key}")+ context.add_output_metadata(metadata)+++def _decide_champion(+ context: dagster.AssetExecutionContext,+ client,+ bucket: str,+ prefix: str,+ partition_key: str,+ family: ModelFamily,+) -> dict[str, dagster.MetadataValue] | None:+ """One family's promotion decision against its own pointer, or None when the family has no+ candidate for the partition."""candidate = _read_json_if_exists(- client, bucket, model_object_key(prefix, TABULAR_MODEL_NAME, partition_key, METADATA_FILE)+ client, bucket, model_object_key(prefix, family.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, TABULAR_MODEL_NAME)+ context.log.warning(f"no {family.name} candidate metadata for dt={partition_key}; nothing to decide")+ return None+ champion_key = champion_object_key(prefix, family.name)champion = _read_json_if_exists(client, bucket, champion_key)champion_aucs: dict[str, float] = {}if champion is not None: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")+ context.log.warning(+ f"{family.name} 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(+ # shares: promotion stays inside a family. Without that object there is no shared+ # holdout, so the rule falls back to the champion's stored AUC.+ examples = read_parquet_if_exists(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}")+ if examples is None:+ context.log.warning(+ f"no {champion_feature_set.name} examples for dt={partition_key}; "+ f"the {family.name} champion is compared on its stored AUC"+ )+ else:+ champion_aucs = paired_champion_aucs(+ client,+ bucket,+ prefix,+ champion,+ examples.to_pandas(),+ feature_set=champion_feature_set,+ holdout_days=settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS,+ )+ context.log.info(f"{family.name} champion {champion['model_version']} on this holdout: {champion_aucs}")decision = decide_promotion(candidate,champion,@@ -502,7 +624,9 @@ def inbox_ranking_model_champion(context: dagster.AssetExecutionContext) -> Nonemin_days_between=settings.INBOX_RANKING_PROMOTION_MIN_DAYS,champion_aucs=champion_aucs,)- context.log.info(f"promotion decision for dt={partition_key}: promote={decision.promote} ({decision.reason})")+ context.log.info(+ f"{family.name} promotion decision for dt={partition_key}: promote={decision.promote} ({decision.reason})"+ )promoted = Falseif decision.promote and settings.INBOX_RANKING_AUTO_PROMOTE:@@ -513,30 +637,17 @@ def inbox_ranking_model_champion(context: dagster.AssetExecutionContext) -> None{**candidate,"promoted_at": datetime.datetime.now(datetime.UTC).isoformat(),- "metadata_key": model_object_key(prefix, TABULAR_MODEL_NAME, partition_key, METADATA_FILE),+ "metadata_key": model_object_key(prefix, family.name, partition_key, METADATA_FILE),},)promoted = Trueelif decision.promote:- context.log.info("INBOX_RANKING_AUTO_PROMOTE is off; candidate would have been promoted")+ context.log.info(f"INBOX_RANKING_AUTO_PROMOTE is off; the {family.name} candidate would have been promoted")# The paired AUCs belong to the incumbent: after a promotion `champion_version` names the# candidate, so the incumbent is recorded alongside to keep the scores attributable.incumbent_champion_version = (champion or {}).get("model_version", "none")champion_version = partition_key if promoted else incumbent_champion_version- context.add_output_metadata(- {- "would_promote": dagster.MetadataValue.bool(decision.promote),- "promoted": dagster.MetadataValue.bool(promoted),- "reason": dagster.MetadataValue.text(decision.reason),- **{- f"champion_{head}_auc_on_this_holdout": dagster.MetadataValue.float(auc)- for head, auc in champion_aucs.items()- },- "incumbent_champion_version": dagster.MetadataValue.text(incumbent_champion_version),- "champion_version": dagster.MetadataValue.text(champion_version),- }- )capture_training_events(context,partition_key,@@ -544,7 +655,7 @@ def inbox_ranking_model_champion(context: dagster.AssetExecutionContext) -> Nonepromotion_event(partition_key=partition_key,run_id=context.run.run_id,- model_name=TABULAR_MODEL_NAME,+ model_name=family.name,decision=decision,promoted=promoted,champion_version=champion_version,@@ -553,6 +664,17 @@ def inbox_ranking_model_champion(context: dagster.AssetExecutionContext) -> None)],)+ return {+ f"{family.name}_would_promote": dagster.MetadataValue.bool(decision.promote),+ f"{family.name}_promoted": dagster.MetadataValue.bool(promoted),+ f"{family.name}_reason": dagster.MetadataValue.text(decision.reason),+ **{+ f"{family.name}_champion_{head}_auc_on_this_holdout": dagster.MetadataValue.float(auc)+ for head, auc in champion_aucs.items()+ },+ f"{family.name}_incumbent_champion_version": dagster.MetadataValue.text(incumbent_champion_version),+ f"{family.name}_champion_version": dagster.MetadataValue.text(champion_version),+ }# dt=D grades the scores written on D - horizon_days, so the mapping reaches back as far as the@@ -619,14 +741,51 @@ def load_unseen_models(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)+ for family in MODEL_FAMILIES+ for model in load_family_models(context, client, bucket, prefix, partition_key, family.name)]+def models_with_extras(+ context: dagster.AssetExecutionContext, models: Sequence[UnseenModel], extras: Extras+) -> list[UnseenModel]:+ """The models whose feature set has the side inputs it reads.++ A model scored without its side input would score every report off the booster's missing+ branch. That is a line on the chart that says nothing about the model, so the family takes a+ gap for the day instead.+ """+ kept: list[UnseenModel] = []+ for model in models:+ missing = model.feature_set.missing_extras(extras)+ if missing:+ context.log.warning(+ f"{model.model_name} {model.model_role} {model.model_version} not scored: "+ f"no {', '.join(missing)} for this partition"+ )+ continue+ kept.append(model)+ return kept+++def pool_feature_coverage(+ pool: pd.DataFrame, models: Sequence[UnseenModel], extras: Extras, as_of: datetime.datetime+) -> dict[str, dagster.MetadataValue]:+ """The share of the pool each scored feature set can build a real vector for, by set name."""+ feature_sets = {model.feature_set.name: model.feature_set for model in models}+ return {+ f"{name}_pool_coverage": dagster.MetadataValue.float(+ float(feature_set.buildable(state_rows(pool, feature_set), extras, as_of=as_of).mean())+ if len(pool)+ else 0.0+ )+ for name, feature_set in feature_sets.items()+ }++@dagster.asset(name=UNSEEN_SCORES_TABLE,- deps=["inbox_ranking_model_champion", STATE_TABLE, LABELS_TABLE],+ deps=["inbox_ranking_model_champion", STATE_TABLE, LABELS_TABLE, EMBEDDINGS_TABLE],**COMMON_ASSET_KWARGS,)def inbox_ranking_unseen_scores(context: dagster.AssetExecutionContext) -> None:@@ -641,10 +800,12 @@ def inbox_ranking_unseen_scores(context: dagster.AssetExecutionContext) -> None:# 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(+ # A set the examples asset skipped has no object, and so no example to leak.+ ids = read_parquet_if_exists(client, bucket, examples_object_key(prefix, feature_set.name, partition_key), columns=["report_id"])- example_ids.update(ids.column("report_id").unique().to_pylist())+ if ids is not None:+ example_ids.update(ids.column("report_id").unique().to_pylist())pool = unseen_pool(snapshot.state, day)leaked = leaked_report_ids(pool, example_ids)if leaked:@@ -652,8 +813,9 @@ def inbox_ranking_unseen_scores(context: dagster.AssetExecutionContext) -> None:f"{len(leaked)} reports created on {partition_key} already appear in that day's training examples, "f"so the unseen read would grade a model on its own data: {leaked[:10]}")- models = load_unseen_models(context, client, bucket, prefix, partition_key)- scores = score_pool(pool, snapshot.labels, models, snapshot_date=day)+ extras = report_embeddings_extras(context, client, bucket, prefix, partition_key)+ models = models_with_extras(context, load_unseen_models(context, client, bucket, prefix, partition_key), extras)+ scores = score_pool(pool, snapshot.labels, models, snapshot_date=day, extras=extras)key = partition_object_key(prefix, UNSEEN_SCORES_TABLE, partition_key)if scores.empty:existing_rows = object_row_count(client, bucket, key)@@ -675,6 +837,10 @@ def inbox_ranking_unseen_scores(context: dagster.AssetExecutionContext) -> None:f"{model.model_name}_{model.model_role}_heads_scored": dagster.MetadataValue.int(len(model.boosters))for model in models},+ # Every family scores the whole pool, so the grades stay paired even where a set's side+ # input is thin. That makes coverage the number to watch: a family reading a side input+ # that covers few of the day's newborns is graded mostly on its missing branch.+ **pool_feature_coverage(pool, models, extras, snapshot_bounds(partition_key)[1]),"s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),})@@ -776,16 +942,20 @@ inbox_ranking_training_job = dagster.define_asset_job(partitions_def=partition_def,tags={**owner_tags,- "dagster/max_runtime": str(2 * 60 * 60),+ # The report-embeddings family fits 1536-column heads, and each head costs a fit per+ # permutation draw on top of the two it ships, so the wall clock is now the trainer's+ # rather than the ETL's. Matched to the dataset job's budget.+ "dagster/max_runtime": str(3 * 60 * 60),# The examples asset holds every snapshot of the lookback window in pandas at once (state- # plus labels per day) before the per-head builders run, so the peak grows with the- # lookback and the inventory. Sized like the dataset job rather than left at the 8Gi- # default so growth surfaces as a slow run, not an OOMKilled pod.+ # plus labels per day) before the per-head builders run, plus the day's report vectors as+ # the side input the embeddings set reads, so the peak grows with the lookback and the+ # inventory. The limit sits above the dataset job's because that vector table is only one+ # of the things held here; growth should surface as a slow run, not an OOMKilled pod."dagster-k8s/config": {"container_config": {"resources": {"requests": {"memory": "8Gi"},- "limits": {"memory": "16Gi"},+ "limits": {"memory": "24Gi"},}}},diff --git a/products/signals/dags/inbox_ranking/training/examples.py b/products/signals/dags/inbox_ranking/training/examples.pyindex 3b993c50c0a4..11d7431c94e9 100644--- a/products/signals/dags/inbox_ranking/training/examples.py+++ b/products/signals/dags/inbox_ranking/training/examples.py@@ -1,17 +1,22 @@-"""Training examples at the scoring-moment grain.+"""Training examples at the grain the feature set asks for.-One example = one report as one daily snapshot saw it. Its features are that snapshot's-report-state columns (plus `age_hours`, the report's age at the snapshot), and its label is-whether the head's outcome happened within the head's horizon: the label is 0 on the snapshot row-and read from the snapshot `horizon_days` later. That is the serving situation — a report gets-scored, then users see it — replayed over the daily snapshots, and it measured better than one-row per report on the engagement heads (skill issue 13). Once the scoring sweep's append-only-score log has accrued it becomes this table's source; the snapshots are the bootstrap.+The default grain is a scoring moment: one example = one report as one daily snapshot saw it.+Its features are that snapshot's report-state columns (plus `age_hours`, the report's age at the+snapshot), and its label is whether the head's outcome happened within the head's horizon: the+label is 0 on the snapshot row and read from the snapshot `horizon_days` later. That is the serving+situation — a report gets scored, then users see it — replayed over the daily snapshots, and it+measured better than one row per report on the engagement heads (skill issue 13). Once the scoring+sweep's append-only score log has accrued it becomes this table's source; the snapshots are the+bootstrap.Rows of one report are near-duplicates, so the holdout is cut BY REPORT (report_created_at),never by row. Label-only rows (EU reports, hard-deleted rows) carry no state and are skipped.A snapshot is assembled over the state spine (`assemble_snapshot`): a report with no label eventgets LABEL_DEFAULTS, so never-engaged reports are negatives rather than absent.++A wide set cannot afford that many rows, so a set may ask for the report grain instead (one+example per report, at its first usable scoring moment of the window) and cap the rows one head+keeps. Both knobs live on the `FeatureSet`, because the examples object is per set."""import datetime@@ -21,7 +26,7 @@ import pandas as pdfrom posthog.dataclasses import frozen-from products.signals.backend.ranking.features import NO_EXTRAS, Extras, FeatureSet+from products.signals.backend.ranking.features import NO_EXTRAS, REPORT_GRAIN, 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_DEFAULTS@@ -40,12 +45,20 @@ PROVENANCE_LABEL_COLUMNS = ("latest_status_event", "status_event_team_id")# than this is a backfill that carries current Postgres state, not the state as of the snapshot.STATE_LAG_LIMIT = datetime.timedelta(days=2)+# Fixed, so a re-run of a partition keeps the same rows under a row budget and two candidates of the+# same day are fit on one example set.+EXAMPLE_SAMPLE_SEED = 0+def state_columns(feature_set: FeatureSet) -> tuple[str, ...]:"""The report-state columns to read for `feature_set`: the base ones plus its own."""return (*BASE_STATE_COLUMNS, *(name for name in feature_set.state_columns if name not in BASE_STATE_COLUMNS))+# The moment spine, before any feature set's columns are added to it.+MOMENT_COLUMNS = ("head", "report_id", "snapshot_date", "report_created_at", "label")++def example_columns(feature_set: FeatureSet) -> tuple[str, ...]:"""The examples Parquet columns for `feature_set`. One object per set, because two sets carrydifferent feature columns."""@@ -133,10 +146,29 @@ def build_examples(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 `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."""+ """Every scoring moment for `head` that `feature_set` asks for, as one frame with its 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.++ The moments are chosen first and the features built second, so a set under a row budget builds+ 1536 columns for the rows it keeps rather than for every row it then throws away.+ """+ moments = example_moments(snapshots, head, feature_set, extras)+ kept = cap_examples(moments, feature_set.max_examples_per_head)+ return _with_features(kept, snapshots, feature_set, extras)+++def example_moments(+ snapshots: Mapping[datetime.date, Snapshot],+ head: Head,+ feature_set: FeatureSet,+ extras: Extras,+) -> pd.DataFrame:+ """The (report, snapshot) moments that are examples for `head`, with their labels and no+ features. One row per moment at the scoring-moment grain; at the report grain, only the first+ snapshot of the window where a report is a usable moment."""frames: list[pd.DataFrame] = []+ covered: set[object] = set()for date in sorted(snapshots):later = snapshots.get(date + datetime.timedelta(days=head.horizon_days))if later is None:@@ -152,6 +184,7 @@ def build_examples(if len(ids) == 0:continuestate, labels_now, labels_later = now.state.loc[ids], now.labels.loc[ids], later.labels.loc[ids]+ _, snapshot_end = snapshot_bounds(date.isoformat())# The cohort reads the later snapshot on purpose. The sweep scores a report before users see# it, so the impression that puts a report in the cohort usually lands after `now`. A cohort# read at `now` would drop those pre-impression scoring moments, which are the serving case.@@ -161,25 +194,67 @@ def build_examples(keep &= _flag_or_true(labels_now, "label_provenance_ok") & _flag_or_true(labels_later, "label_provenance_ok")+ # A set whose side input has no row for a report, or only a value that landed after this+ # snapshot, cannot build the vector this moment had, so the report is not a moment here. At+ # the report grain the report then takes its example on the first snapshot where it can.+ keep &= feature_set.buildable(state, extras, as_of=snapshot_end)+ if feature_set.example_grain == REPORT_GRAIN:+ keep &= ~state.index.isin(covered)if not keep.any():continue- rows = state_rows(state.loc[keep], feature_set)- features = feature_set.build_matrix(rows, extras)- examples = pd.DataFrame(- {- "head": head.name,- "report_id": rows.index.to_numpy(),- "snapshot_date": date,- "report_created_at": pd.to_datetime(rows["report_created_at"], utc=True).to_numpy(),- }+ kept_ids = state.index[keep.to_numpy()]+ covered.update(kept_ids)+ frames.append(+ pd.DataFrame(+ {+ "head": head.name,+ "report_id": kept_ids.to_numpy(),+ "snapshot_date": date,+ "report_created_at": pd.to_datetime(state.loc[kept_ids, "report_created_at"], utc=True).to_numpy(),+ "label": head.label(labels_later.loc[kept_ids]).astype(int).to_numpy(),+ }+ ))+ if not frames:+ return pd.DataFrame(columns=list(MOMENT_COLUMNS))+ return pd.concat(frames, ignore_index=True)+++def cap_examples(moments: pd.DataFrame, limit: int | None) -> pd.DataFrame:+ """`moments` within `limit` rows, keeping every positive and a seeded sample of the negatives.++ A row budget is how a wide set stays inside one partition's object and the training job's+ runtime. Positives are the scarce side of every head here and AUC is rank-based, so spending+ the budget on them costs the base rate the scores are calibrated to rather than the ranking read+ the family exists for. Positives are kept whole even past the budget: a head with that many+ positives is not the case the budget is for.+ """+ if limit is None or len(moments) <= limit:+ return moments+ positives = moments[moments["label"] == 1]+ negatives = moments[moments["label"] != 1]+ room = max(limit - len(positives), 0)+ sampled = negatives.sample(n=min(room, len(negatives)), random_state=EXAMPLE_SAMPLE_SEED)+ return pd.concat([positives, sampled]).sort_index().reset_index(drop=True)+++def _with_features(+ moments: pd.DataFrame, snapshots: Mapping[datetime.date, Snapshot], feature_set: FeatureSet, extras: Extras+) -> pd.DataFrame:+ """`moments` with `feature_set`'s columns, built from the state of the snapshot each moment+ belongs to, so a moment carries the features that snapshot would have scored it with."""+ columns = list(example_columns(feature_set))+ if moments.empty:+ return pd.DataFrame(columns=columns)+ frames: list[pd.DataFrame] = []+ for date, group in moments.groupby("snapshot_date", sort=True):+ _, snapshot_end = snapshot_bounds(date.isoformat())+ rows = state_rows(snapshots[date].state.loc[group["report_id"]], feature_set)+ features = feature_set.build_matrix(rows, extras, as_of=snapshot_end)+ examples = group.reset_index(drop=True)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=columns)return pd.concat(frames, ignore_index=True)[columns]diff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.pyindex 4faf7ba3a1e0..a88cea4088f0 100644--- a/products/signals/dags/inbox_ranking/training/unseen.py+++ b/products/signals/dags/inbox_ranking/training/unseen.py@@ -23,7 +23,14 @@ from sklearn.metrics import roc_auc_scorefrom posthog.dataclasses import frozen-from products.signals.backend.ranking.features import NO_EXTRAS, Extras, FeatureSet, feature_set_by_name+from products.signals.backend.ranking.features import (+ NO_EXTRAS,+ REPORT_EMBEDDINGS_FEATURE_SET,+ TABULAR_FEATURE_SET,+ Extras,+ FeatureSet,+ feature_set_by_name,+)from products.signals.dags.inbox_ranking.common import snapshot_boundsfrom 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@@ -41,9 +48,7 @@ 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,)+REPORT_EMBEDDINGS_MODEL_NAME = "report_embeddings"# A shuffle plus one AUC rather than a refit, so this sits far above the trainer's NULL_PERMUTATIONS.NULL_PERMUTATIONS = 25@@ -96,6 +101,25 @@ class UnseenModel:boosters: Mapping[str, bytes]+@frozen+class ModelFamily:+ """One family the training job fits and the unseen read grades: its name, and the feature set+ its trainer fits. Both families are per-head XGBoost, so the learner is not a field yet; a+ family with its own predict (the MMoE) adds one at the `UnseenModel` boundary."""++ name: str+ feature_set: FeatureSet+++# The families the training job trains and the unseen read grades, in the order they are trained. A+# family with no metadata for the day is skipped, so an entry can be added here before its trainer+# writes its first candidate, and a family that fails costs its own series rather than every one.+MODEL_FAMILIES: tuple[ModelFamily, ...] = (+ ModelFamily(name=TABULAR_MODEL_NAME, feature_set=TABULAR_FEATURE_SET),+ ModelFamily(name=REPORT_EMBEDDINGS_MODEL_NAME, feature_set=REPORT_EMBEDDINGS_FEATURE_SET),+)++@frozenclass HeadGrade:head: str@@ -300,12 +324,13 @@ def score_pool("""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. One matrix is built per feature set the+ Features are built exactly as `build_examples` builds them, as of the end of the pool's day, so+ a report scored here sees the same vector it would have seen as a training example. One matrix is built per feature set themodels declare, and every model on that set scores against it. `label_at_scoring` recordswhether the head's outcome had already happened on the scoring day; the grader drops thoserows, the same way the example builder drops a scoring moment whose label is already 1."""+ _, as_of = snapshot_bounds(snapshot_date.isoformat())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()@@ -318,7 +343,7 @@ def score_pool(feature_set = model.feature_setif feature_set.name not in matrices:matrices[feature_set.name] = xgb.DMatrix(- feature_set.build_matrix(state_rows(pool, feature_set), extras),+ feature_set.build_matrix(state_rows(pool, feature_set), extras, as_of=as_of),feature_names=list(feature_set.feature_names),)matrix = matrices[feature_set.name]