Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): train and grade a title-only inbox ranking family (#102641)

posthog[bot]9bf14b08f389
diff --git a/docs/internal/inbox-ranking-training.md b/docs/internal/inbox-ranking-training.md
index 10896ae8b5e5..b7730f472871 100644
--- a/docs/internal/inbox-ranking-training.md
+++ b/docs/internal/inbox-ranking-training.md
@@ -1,6 +1,6 @@
# Inbox ranking training examples
-The tabular and report-embedding ranking families use one example per report per head, from the report's birth-day snapshot.
+The tabular, report-embedding and title-embedding ranking families use one example per report per head, from the report's birth-day snapshot.
This prevents long-lived reports from receiving more weight in training because they appear in more daily snapshots.
Birth days use the UTC interval returned by `snapshot_bounds`, including the start and excluding the end.
The label comes from the snapshot `horizon_days` later, including outcomes already present on the birth day.
@@ -12,6 +12,7 @@ The examples asset records `reports_missing_birth_snapshot` for observed reports
These reports produce no birth-grain example; reports born before the lookback do not contribute to this count.
A missing horizon snapshot also prevents an example because its label is unknown.
Point-in-time state, label provenance, and embedding availability checks still apply.
+Each embedding family reads its own rendering's snapshot, so a report missing from one snapshot is an example for the other family only.
Every training series resets on the first partition after deploy.
Before and after holdout numbers are not comparable because the example population changes.
diff --git a/products/signals/backend/ranking/features.py b/products/signals/backend/ranking/features.py
index d342190cc28f..f15dfaeb1d2d 100644
--- a/products/signals/backend/ranking/features.py
+++ b/products/signals/backend/ranking/features.py
@@ -14,9 +14,9 @@ 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 the
report'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. 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).
+judgment artefacts. The two embedding sets are the report's combined-text vector and its title-only
+vector, one rendering each, and the sweep serves neither: they are offline candidates graded on the
+unseen read, and serving one needs its vector at scoring time (skill issue 14).
"""
import abc
@@ -73,6 +73,11 @@ NO_EXTRAS: Extras = MappingProxyType({})
# 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"
+# The title-only vector, under its own key, from the dataset dag's own
+# `inbox_report_title_embeddings` snapshot. Two keys rather than one, because the two families
+# exist to be compared: a row that fell back to the combined-text vector would measure nothing, and
+# a summary-only edit re-embeds only the combined rendering, so the two landing times differ.
+TITLE_EMBEDDINGS_EXTRA = "title_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
@@ -205,7 +210,13 @@ TABULAR_FEATURE_SET = TabularFeatureSet()
class ReportEmbeddingsFeatureSet(FeatureSet):
- """The report's own embedding vector, and nothing else, at one example per report.
+ """One text rendering's embedding vector, and nothing else, at one example per report.
+
+ Parameterized by the `extras` key it reads, so a rendering is a second instance rather than a
+ second class: the combined-text rendering and the title-only rendering then share this width,
+ this grain and this row budget by construction, and a regularization change lands on both. That
+ is what makes the two families' grades a measurement of the text choice rather than of the
+ recipe. A set reads its own key only, and never falls back to another rendering's vector.
Two modelling calls this set records, both open questions on the issue that asked for it
(posthog#98243):
@@ -220,8 +231,8 @@ class ReportEmbeddingsFeatureSet(FeatureSet):
`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
+ Vectors arrive through `extras`, from the rendering's own dt=D 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, so a report whose birth-day snapshot holds
@@ -235,17 +246,19 @@ class ReportEmbeddingsFeatureSet(FeatureSet):
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,)
# 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 __init__(self, *, name: str, extras_key: str) -> None:
+ self.name = name
+ self.extras_keys = (extras_key,)
+
def build_matrix(
self, rows: pd.DataFrame, extras: Extras = NO_EXTRAS, *, as_of: datetime.datetime | None = None
) -> pd.DataFrame:
@@ -268,7 +281,7 @@ class ReportEmbeddingsFeatureSet(FeatureSet):
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)
+ vectors = extras.get(self.extras_keys[0])
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)
@@ -276,8 +289,7 @@ class ReportEmbeddingsFeatureSet(FeatureSet):
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"
+ f"the {self.extras_keys[0]} 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))
@@ -291,7 +303,11 @@ class ReportEmbeddingsFeatureSet(FeatureSet):
).astype(bool)
-REPORT_EMBEDDINGS_FEATURE_SET = ReportEmbeddingsFeatureSet()
+REPORT_EMBEDDINGS_FEATURE_SET = ReportEmbeddingsFeatureSet(name="report_embeddings", extras_key=REPORT_EMBEDDINGS_EXTRA)
+# The title-only rendering of the same reports, so a family can measure the title against the
+# title-plus-summary vectors on identical rows. The inbox title is what a person reads before
+# opening a report; the summary is read after. Everything else matches the set above, deliberately.
+TITLE_EMBEDDINGS_FEATURE_SET = ReportEmbeddingsFeatureSet(name="title_embeddings", extras_key=TITLE_EMBEDDINGS_EXTRA)
# 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.
@@ -299,6 +315,7 @@ FEATURE_SETS: Mapping[str, FeatureSet] = MappingProxyType(
{
TABULAR_FEATURE_SET.name: TABULAR_FEATURE_SET,
REPORT_EMBEDDINGS_FEATURE_SET.name: REPORT_EMBEDDINGS_FEATURE_SET,
+ TITLE_EMBEDDINGS_FEATURE_SET.name: TITLE_EMBEDDINGS_FEATURE_SET,
}
)
diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.md
index 3456c72c414b..731e74e1476a 100644
--- a/products/signals/dags/inbox_ranking/AGENTS.md
+++ b/products/signals/dags/inbox_ranking/AGENTS.md
@@ -11,14 +11,16 @@ Read `README.md` first for what the dataset is and how partitions behave. This f
## Training dag specifics
- `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 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: three 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.
+- The two embedding sets are one `ReportEmbeddingsFeatureSet` parameterized by the `extras` key it reads, one rendering each. A set reads its own key only: never add a fallback to the other rendering's vector, and keep width, grain, row budget and booster params identical across the pair, or the paired AUC difference stops measuring the text choice. `embeddings_extras` loads one set's inputs at a time and the scores asset narrows each snapshot to the newborn pool, because a snapshot carries a vector per live report; keep both, so a further embedding family costs runtime rather than peak memory.
+- A **missing** side-input object leaves its key out, so only the sets reading it are skipped and their partitions stay as they are. An **empty** object keeps its key and takes the ordinary thin-input path. Do not collapse the two: the first must not write over a partition, and the second is a day the family really has nothing to fit.
- Both `buildable` and `build_matrix` take the moment being built as `as_of`, and a side input that changes over a report's life must honor it. The report vector does: reports are re-embedded when their text changes, so the snapshot's latest vector often postdates the moment, and taking it would train on text that did not exist yet. Never widen a set's side input to the latest value for convenience.
-- `example_grain` and `max_examples_per_head` are per set, because the examples object is. Both sets default to the birth grain so both families target the same scoring moment; side-input availability and row budgets can still change their training populations. Keep the tabular set with no budget: `report_embeddings` is the reason the budget exists (1536 columns per row), and a budget on the tabular set would thin the family the other lines are measured against. A budget keeps every positive, so it moves the base rate its scores calibrate to and not the ranking.
+- `example_grain` and `max_examples_per_head` are per set, because the examples object is. Every set defaults to the birth grain so the families target the same scoring moment; side-input availability and row budgets can still change their training populations. Keep the tabular set with no budget: `report_embeddings` is the reason the budget exists (1536 columns per row), and a budget on the tabular set would thin the family the other lines are measured against. A budget 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 one row per report, on the snapshot of the day it was created, labeled from the snapshot `horizon_days` later. The scoring-moment and report grains stay selectable for re-scoring families, so keep the holdout cut by report: a row-level split leaks near-duplicate snapshots of the same report the moment a set asks for one of them. The moments are chosen before the features are built, so a set under a row budget never builds columns for rows it then drops; keep that order.
- `inbox_ranking_models/v1/<model_name>/dt=D/` is history like the dataset partitions: the only mutation is a re-run of the same partition, which replaces the prefix in full (stale head files are deleted). `<model_name>/champion.json` is the only object written outside its partition, and only the champion asset (or a human, deliberately) writes it; it carries the candidate's `run_id`, so a loader can detect a re-run behind a pinned version.
-- 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.
+- 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. One object holds every family, so a re-run that scored some families and not every family the object already holds is refused for the same reason: skipping a family costs its own day, while rewriting the object without it deletes a day it already has.
- `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.
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.md
index 5ec25b00194f..2480ab1ce615 100644
--- a/products/signals/dags/inbox_ranking/README.md
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -81,15 +81,18 @@ 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, `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.
+- **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`, `report_embeddings` and `title_embeddings` are the three 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 one row per report at its birth, by default.** For partition `dt=D` the examples asset reads the report-state and labels snapshots `dt=D-lookback..D` and emits one row per report, on the snapshot of the day it was created, labeled from the snapshot `horizon_days` later (3 for open, 7 for action / pr_created / discuss, 14 for dismiss_wrong / 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. Birth is the moment serving scores a report, and the label that comes out is a per-report probability, which is what the inbox ordering needs. A report born before the window, or one whose birth-day snapshot is missing from it, is no example; `reports_missing_birth_snapshot` on the asset counts the second case, which is a gap in the partitions.
- **An outcome already visible on the birth day is a future positive.** A report born on day D has no scoring moment before D, so an outcome visible at D belongs to the moment being built rather than to an earlier one; the labels of D therefore read as their defaults for a report born on D. Most outcomes land on the birth day, so this is where the positives are: censoring on them costs the `pr_created` head most of its training signal. `<set>_<head>_birth_day_positives` on the examples asset, and `birth_day_positives` on the `inbox_ranking_examples_built` event, say how many positives the rule keeps. These rows carry a hindsight the other rows do not: the state snapshot reads `signal_count`, `total_weight`, `run_count` and the text sizes live from Postgres a few hours after day D ends, so a birth-day outcome happened before its own feature read. Both the holdout AUC and the newborn unseen grade therefore read optimistically on these rows, until the scoring sweep's timestamped score log replaces the daily snapshot as this table's source.
- **Every head asks whether the outcome happened within N days of the scoring moment.** `pr_merged` includes every report, so the label covers the whole report-to-merge path without requiring a PR at birth or at the horizon.
- **A set may ask for another grain**, and cap the rows one head keeps (`max_examples_per_head`, all positives first, then a seeded sample of the negatives). The scoring-moment grain is one row per (report, snapshot) whose head label is still 0 on that snapshot: the serving situation replayed over history, but its label is a hazard conditional on the report still being live, and one long-lived report contributes dozens of near-duplicate rows. The report grain is the first snapshot of the window where the report is a usable moment, which is later than birth only when a side input landed late. Both stay selectable for re-scoring families; nothing ships on them today. The row budget changes the base rate a set's scores are calibrated to, not the ranking the unseen AUC reads. The lookback is the tabular set's whatever the grain, so positives accrue over the whole window.
- **`tabular` is the serving set** (the state counters, title/summary length, age, one-hot priority/actionability). No embedding, no impression-derived columns, so the scoring sweep needs only the `SignalReport` row and its judgment artefacts. The sweep must build features through the same module; the booster's `feature_names` are checked against it at load.
- **`report_embeddings` is the report's own vector and nothing else**, read from the dt=D `inbox_report_embeddings` snapshot as a side input. Age is deliberately left out: it is the whole signal of the `recency_auc` line the unseen read already reports, so a gap to that line is content rather than recency. The scoring sweep does not serve this set: it is an offline candidate, and serving it needs the report vector at scoring time.
+- **`title_embeddings` is the same set over the title-only vector**, read from the dt=D `inbox_report_title_embeddings` snapshot, a separate leaf partition with its own `embedding_inserted_at`. One `ReportEmbeddingsFeatureSet` class parameterized by the input it reads, so the two renderings share this width, this grain, this row budget and the trainer's booster params by construction: the pair measures the text choice, and a recipe that drifted on one side would read as a text effect. A set reads its own input only and never falls back to the other rendering's vector, so a report present in one snapshot and absent from the other is an example for one family and not the other. The inbox title is what a person reads before opening a report and the summary is read after, which is the question the pair answers: whether the summary carries `open` signal or only post-open signal.
- **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 birth grain a report whose birth-day snapshot holds only a later vector is no example, and at the report grain it moves to the first snapshot where the vector was already its 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.
+- **Missing and empty are different inputs.** The case above is a snapshot object that is absent. A snapshot that exists and carries no usable vector keeps its key, so the family builds no row and the ordinary thin-input path applies. Each rendering is a separate dependency of the examples and scores assets, so a failed title snapshot costs the title family's day and nothing else.
+- **One rendering's vectors are held at a time.** The examples asset loads a set's side inputs, builds that set's object, and releases them before the next set. Each snapshot carries a vector per live report, so a further embedding family costs runtime rather than peak memory. The scores asset narrows each snapshot to the newborn pool it scores for the same reason. Raising the pod memory limit is not the first move here.
- **Candidate**: one per family, per-head XGBoost with fixed params, holdout = the last `holdout_days` of reports (cut by report, never by row), AUC + a label-permutation null. Each family trains on the examples of the feature set its registry entry names, and a family whose examples or metadata are missing that day is logged and skipped rather than failing the asset. A head is _readable_ when it has enough holdout positives and clears its null by 0.05. The shipped booster (`<head>.ubj`) is refit on everything; the train-only fit is kept as `<head>.holdout.ubj` so a later candidate can grade this model on its own holdout.
- **Metrics telemetry**: each asset also captures its metrics as events into the dogfood project (the same project the label events land in), through `training/telemetry.py`: `inbox_ranking_examples_built` once per head and feature set, `inbox_ranking_candidate_trained` once per head (`head`, `model_role` always `candidate`, holdout / train AUC, average precision, logloss, positive rate, mean predicted score, the row-weighted decile calibration error, the permutation-null mean and spread, counts, `readable`), `inbox_ranking_holdout_calibration` once per head and holdout score decile 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**: 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`.
@@ -115,13 +118,26 @@ See [training example semantics](../../../../docs/internal/inbox-ranking-trainin
The holdout grades the recipe, not the model that ships: the shipped booster is refit on train plus holdout, and every holdout row comes from the same snapshots the trainer saw.
Two assets add the missing number, an offline batch proxy for performance on reports the model never saw.
-- **`inbox_ranking_unseen_scores` (dt=D)** takes the dt=D state rows of the reports **created on D**, the pool the events tag `pool=newborn`. A newborn has no scoring moment before D, and the dt=D examples stop at D minus the head's horizon (3 days at the shortest), so no example can cover it: leakage-freedom is structural, not a property of what the example builder did that day. The set difference against the examples Parquet stays as a runtime guard — a non-empty overlap fails the asset instead of publishing the number. Every newborn is scored, not a sample, with the day's candidate and, when the pointer names a different version, the champion. Only readable heads are scored, and a model whose feature contract has moved on is logged and left out. 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, which for a newborn is one that landed on its own birth day, so the grade keeps it; an older pool's rows are still dropped on it, and so are a status-label head's rows in every pool, because no scores column carries the scoring-day `label_provenance_ok` that the example builder checks), `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, which for a newborn is one that landed on its own birth day, so the grade keeps it; an older pool's rows are still dropped on it, and so are a status-label head's rows in every pool, because no scores column carries the scoring-day `label_provenance_ok` that the example builder checks), `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; one object holds every family, so a re-run that scored fewer families than the object already holds is refused too, and names them. 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 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. It also reads the calibration of those scores, which no AUC can see: the in-cohort rows are cut into score deciles by rank (`training/calibration.py`, shared with the trainer so both sides cut them the same way), and each decile's mean score is compared against the rate the outcome actually happened at. A run of equal scores stays in one decile, so a head reports fewer deciles rather than a gap that only reflects the row order. That read spans the whole pool, the reports whose side input has no row for them included, and the examples drop those rows, so on a thin `<set>_pool_coverage` day the unseen error carries a population the holdout error cannot: read the two per family.
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.
Four events carry it to the dashboard, next to the training events: `inbox_ranking_unseen_report_scored` per (report, model) with `p_<head>`, the raw feature inputs, and `pool` (which pool definition produced the row), `inbox_ranking_unseen_head_graded` per (model, head) with `rows`, `positives`, `birth_day_positives` (of the positives, how many landed on the report's birth day), `base_rate`, `mean_score`, `expected_calibration_error`, `auc` and `recency_auc`, `inbox_ranking_unseen_calibration` per (model, head, decile) with `bucket`, `rows`, `positives`, `mean_score` and `realized_rate` (one event per decile, because a table on the head event would be an array no insight can break down), and `inbox_ranking_unseen_report_graded` per (report, model, horizon) with `p_<head>`, `in_cohort_<head>` and `outcome_<head>` for a calibration read on the raw rows. Both graded events are stamped on the day the outcome was read and carry `scoring_partition`, the day the report was scored, so a chart can be built on either axis. Both also carry `pool`, read back from the scores object, so an AUC series never mixes two pool definitions: the grader reads scores from up to 14 days earlier, so the days after a pool change grade both populations. A scores object written before the column existed reads as `sampled`, the pool the old seeded sample defined.
+#### Reading one rendering against another
+
+The `title_embeddings` and `report_embeddings` families are trained and graded to be compared, not promoted. The read:
+
+- **Pair the rows, then take the difference.** Both families score every newborn, so for one head and one day they are graded on the same reports. Break the unseen grade down by `model_name` and difference the two AUCs on the rows both grades had. An unpaired difference of two full-population AUCs is not this comparison: keep each family's full-population number, and the matched one, as separate figures.
+- **Read the uncertainty before the sign.** `null_auc_std` on each grade is the spread a per-day AUC has on those rows. A difference inside that band is inconclusive, not evidence that the two renderings carry the same signal. Pool about 30 days before treating a direction as real.
+- **Carry coverage and positives with every figure.** `<set>_pool_coverage` on the scores asset says how much of the pool a rendering had a vector for, and `rows` / `positives` / `birth_day_positives` on each grade say how much outcome the AUC rests on. A family graded largely on its missing branch reads low for a reason that is not the text.
+- **Keep the baselines on the same rows.** `tabular_xgb` and `recency_auc` are reported on the same grade, so the reading is title against combined against tabular against newest-first, not against numbers from another day.
+- **Read `open` first.** It has the shortest horizon (3 days), so its labels mature first; `action` and `pr_created` follow at 7 days. Emission is forward-only and a moment only takes a vector that had already landed, so both families accrue from the first partition after their input starts flowing.
+- **This is not an online test.** Every row is a birth-day snapshot graded against a later snapshot, and the outcomes it grades happened under the order the inbox actually served. A gap between two families is a difference in offline rank quality on logged outcomes, not a causal claim about what the inbox would do differently.
+
+Nothing in this read changes what the inbox serves. The scoring sweep loads the tabular family's pointer, promotion stays inside a family, and `INBOX_RANKING_AUTO_PROMOTE` gates the pointer rewrite; a rendering that wins here earns a separate decision, not an automatic promotion.
+
### Running the training job locally
The training job is S3-only, so it can run on a laptop against copies of the prod snapshots. The dataset job cannot: it needs the dogfood project's ClickHouse and cross-region Postgres.
@@ -133,7 +149,7 @@ The training job is S3-only, so it can run on a laptop against copies of the pro
INBOX_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`). `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. `INBOX_RANKING_SYNC_TITLE_EMBEDDINGS=1` adds `inbox_report_title_embeddings` on its own switch, for the same reason. 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. `INBOX_RANKING_SYNC_TITLE_EMBEDDINGS=1` adds `inbox_report_title_embeddings`, which the `title_embeddings` family needs, on its own switch and for the same reason. 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/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.py
index 1621dc20fdbc..81fbfa252392 100644
--- a/products/signals/dags/inbox_ranking/tests/test_training.py
+++ b/products/signals/dags/inbox_ranking/tests/test_training.py
@@ -30,27 +30,38 @@ from products.signals.backend.ranking.features import (
REPORT_GRAIN,
SCORING_MOMENT_GRAIN,
TABULAR_FEATURE_SET,
+ TITLE_EMBEDDINGS_EXTRA,
+ TITLE_EMBEDDINGS_FEATURE_SET,
Extras,
FeatureSet,
feature_frame,
+ feature_set_by_name,
feature_vector,
)
from products.signals.dags.inbox_ranking.common import partition_object_key
-from products.signals.dags.inbox_ranking.dataset.dag import LABELS_TABLE, STATE_TABLE
+from products.signals.dags.inbox_ranking.dataset.dag import (
+ EMBEDDINGS_TABLE,
+ LABELS_TABLE,
+ STATE_TABLE,
+ TITLE_EMBEDDINGS_TABLE,
+)
from products.signals.dags.inbox_ranking.training.calibration import (
BUCKETS,
calibration_buckets,
expected_calibration_error,
)
from products.signals.dags.inbox_ranking.training.dag import (
+ _EXTRA_SNAPSHOT_TABLES,
METADATA_FILE,
_delete_other_objects,
_train_candidate,
candidate_metadata,
champion_object_key,
+ embeddings_extras,
examples_object_key,
grade_metadata,
inbox_ranking_training_examples,
+ inbox_ranking_unseen_scores,
load_snapshots,
load_unseen_models,
model_object_key,
@@ -96,11 +107,13 @@ from products.signals.dags.inbox_ranking.training.unseen import (
REPORT_EMBEDDINGS_MODEL_NAME,
SCORE_COLUMNS,
TABULAR_MODEL_NAME,
+ TITLE_EMBEDDINGS_MODEL_NAME,
ModelFamily,
UnseenModel,
calibration_rows,
chance_band,
empty_scores_write_allowed,
+ families_lost_by_rewrite,
graded_rows,
head_grades,
leaked_report_ids,
@@ -114,6 +127,11 @@ from products.signals.dags.inbox_ranking.training.unseen import (
)
EMBEDDINGS_MODEL_NAME = REPORT_EMBEDDINGS_MODEL_NAME
+# The two renderings' sets. Every rule about a vector holds for both, because they are one class
+# parameterized by the input it reads, so the embedding tests below run over the pair.
+EMBEDDING_FEATURE_SETS = (REPORT_EMBEDDINGS_FEATURE_SET, TITLE_EMBEDDINGS_FEATURE_SET)
+EMBEDDING_SET_IDS = [feature_set.name for feature_set in EMBEDDING_FEATURE_SETS]
+_EMBEDDING_EXTRA_KEYS = (REPORT_EMBEDDINGS_EXTRA, TITLE_EMBEDDINGS_EXTRA)
D0 = datetime.date(2026, 8, 10)
NOW = datetime.datetime(2026, 8, 20, tzinfo=datetime.UTC)
@@ -621,7 +639,7 @@ def test_build_examples_never_covers_a_report_born_on_the_partition_day(grain):
assert set(examples["report_id"]) == {"old"}
[email protected]("feature_set", [TABULAR_FEATURE_SET, REPORT_EMBEDDINGS_FEATURE_SET])
[email protected]("feature_set", [TABULAR_FEATURE_SET, *EMBEDDING_FEATURE_SETS])
def test_birth_grain_keeps_one_row_per_report_on_the_day_it_was_created(feature_set):
head = HEADS_BY_NAME["open"]
ids = ["newborn", "older", "utc_start", "utc_end"]
@@ -633,7 +651,9 @@ def test_birth_grain_keeps_one_row_per_report_on_the_day_it_was_created(feature_
]
snapshots = _daily_snapshots(ids, head, created, days=3)
snapshots[D0 + datetime.timedelta(days=head.horizon_days)].labels.loc[:, "open_count"] = 0
- extras = _report_vectors({report_id: _embedding() for report_id in ids})
+ # Both renderings' inputs, so the parameter that varies is the set under test and not what it
+ # was handed. The tabular set reads neither.
+ extras = {key: _vector_frame({report_id: _embedding() for report_id in ids}) for key in _EMBEDDING_EXTRA_KEYS}
examples = build_examples(snapshots, head, feature_set, extras)
@@ -696,7 +716,7 @@ def test_reports_missing_birth_snapshot_counts_only_the_ones_a_partition_gap_cos
monkeypatch.setattr(f"{module}.s3_client", lambda: None)
monkeypatch.setattr(f"{module}.snapshot_dates", lambda *args: dates)
monkeypatch.setattr(f"{module}.load_snapshots", lambda *args, **kwargs: snapshots)
- monkeypatch.setattr(f"{module}.report_embeddings_extras", lambda *args: NO_EXTRAS)
+ monkeypatch.setattr(f"{module}.embeddings_extras", lambda *args: NO_EXTRAS)
monkeypatch.setattr(f"{module}._write_examples", lambda *args: {})
with dagster.build_asset_context(partition_key=dates[-1].isoformat()) as context:
inbox_ranking_training_examples(context)
@@ -896,21 +916,32 @@ def test_scores_written_before_the_family_dimension_read_as_the_tabular_family(s
assert with_model_names(scores)["model_name"].tolist() == [expected]
-def test_head_grades_keep_two_families_apart_on_the_same_rows():
- # A grade keyed on version and role alone would pool two families into one meaningless AUC.
+def test_head_grades_keep_every_family_apart_on_the_same_rows():
+ # A grade keyed on version and role alone would pool the families into one meaningless AUC.
+ # Three of them now, and the paired title-against-combined read is a difference of two of these
+ # grades, so a family whose rows leaked into another's would be read as a text effect.
head = HEADS_BY_NAME["open"]
labels = _labels(["a", "e"], open_count=[1, 0])
- tabular = _scores(["a", "e"], score=[0.9, 0.1])
- embeddings = _scores(["a", "e"], score=[0.1, 0.9], model_name=[EMBEDDINGS_MODEL_NAME] * 2)
+ per_family = {
+ TABULAR_MODEL_NAME: [0.9, 0.1],
+ EMBEDDINGS_MODEL_NAME: [0.1, 0.9],
+ TITLE_EMBEDDINGS_MODEL_NAME: [0.8, 0.2],
+ }
graded = pd.concat(
- [graded_rows(tabular, labels, head, pool=POOL_NAME), graded_rows(embeddings, labels, head, pool=POOL_NAME)],
+ [
+ graded_rows(_scores(["a", "e"], score=score, model_name=[model_name] * 2), labels, head, pool=POOL_NAME)
+ for model_name, score in per_family.items()
+ ],
ignore_index=True,
)
grades = head_grades(graded, head, pool=POOL_NAME, scoring_partition="2026-08-10")
- assert [(grade.model_name, grade.model_version, grade.auc) for grade in grades] == [
- (EMBEDDINGS_MODEL_NAME, "2026-08-10", 0.0),
- (TABULAR_MODEL_NAME, "2026-08-10", 1.0),
+ assert [(grade.model_name, grade.rows, grade.auc) for grade in grades] == [
+ (EMBEDDINGS_MODEL_NAME, 2, 0.0),
+ (TABULAR_MODEL_NAME, 2, 1.0),
+ (TITLE_EMBEDDINGS_MODEL_NAME, 2, 1.0),
]
+ # And the calibration read follows the grade, so each family has its own deciles.
+ assert {row["model_name"] for row in calibration_rows(grades)} == set(per_family)
def test_chance_band_is_seeded_and_sizes_the_noise_of_the_rows_it_grades():
@@ -951,6 +982,43 @@ def test_an_empty_scores_write_is_refused_over_a_partition_that_holds_rows(exist
assert empty_scores_write_allowed(existing_row_count) is expected
+ "existing,scored,expected",
+ [
+ (
+ [TABULAR_MODEL_NAME, EMBEDDINGS_MODEL_NAME, TITLE_EMBEDDINGS_MODEL_NAME],
+ [TABULAR_MODEL_NAME, EMBEDDINGS_MODEL_NAME],
+ [TITLE_EMBEDDINGS_MODEL_NAME],
+ ),
+ (
+ [TABULAR_MODEL_NAME, EMBEDDINGS_MODEL_NAME],
+ [TABULAR_MODEL_NAME, EMBEDDINGS_MODEL_NAME],
+ [],
+ ),
+ ([TABULAR_MODEL_NAME], [], [TABULAR_MODEL_NAME]),
+ ([], [TABULAR_MODEL_NAME], []),
+ ],
+ ids=["one_family_skipped", "every_family_scored", "nothing_scored", "first_write"],
+)
+def test_a_rewrite_that_drops_a_family_names_the_rows_it_would_delete(existing, scored, expected):
+ # One object holds every family, so a re-run in a state where a family is not loadable would
+ # replace the object without that family's rows, and the dt=D+horizon grade reads them off a
+ # state snapshot that has aged out. The empty-write guard does not see this: two families out
+ # of three is not an empty frame.
+ assert (
+ families_lost_by_rewrite(pd.DataFrame({"model_name": existing}), pd.DataFrame({"model_name": scored}))
+ == expected
+ )
+
+
+def test_a_rewrite_reads_a_pre_family_scores_object_as_the_tabular_family():
+ # A partition written before `model_name` existed holds tabular rows. Reading it as a family of
+ # its own would refuse every re-run of those days, which is the opposite of the guard's point.
+ existing = pd.DataFrame({"report_id": ["a"], "score": [0.5]})
+
+ assert families_lost_by_rewrite(existing, pd.DataFrame({"model_name": [TABULAR_MODEL_NAME]})) == []
+
+
class _ModelStoreS3:
def __init__(self, objects: dict[str, bytes]):
self.objects = objects
@@ -1496,6 +1564,34 @@ def test_examples_key_layout_is_per_feature_set():
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"
)
+ assert (
+ examples_object_key("inbox_ranking", TITLE_EMBEDDINGS_FEATURE_SET.name, "2026-08-19")
+ == "inbox_ranking/inbox_ranking_training_examples/v1/title_embeddings/dt=2026-08-19/part-00000.parquet"
+ )
+ # And one models prefix per family, so a title booster never lands on the combined family's.
+ assert (
+ model_object_key("inbox_ranking", TITLE_EMBEDDINGS_MODEL_NAME, "2026-08-19", "open.ubj")
+ == "inbox_ranking/inbox_ranking_models/v1/title_embeddings/dt=2026-08-19/open.ubj"
+ )
+
+
[email protected]("feature_set", [TABULAR_FEATURE_SET, *EMBEDDING_FEATURE_SETS])
+def test_every_registered_set_is_reachable_by_the_name_a_model_records(feature_set):
+ # A model names its set in `metadata.json`, and a name this build cannot resolve is left
+ # unscored, so registering the set is what makes the family's boosters loadable at all.
+ assert feature_set_by_name(feature_set.name) is feature_set
+
+
+def test_the_two_embedding_families_share_one_recipe():
+ # The pair measures the text choice, so everything except the input must match. A budget, grain
+ # or width that drifted on one side would make the paired AUC difference read as content.
+ report, title = REPORT_EMBEDDINGS_FEATURE_SET, TITLE_EMBEDDINGS_FEATURE_SET
+ assert report.extras_keys != title.extras_keys
+ for attribute in ("schema_version", "feature_names", "state_columns", "example_grain", "max_examples_per_head"):
+ assert getattr(report, attribute) == getattr(title, attribute)
+ families = {family.name: family.feature_set for family in MODEL_FAMILIES}
+ assert families[TITLE_EMBEDDINGS_MODEL_NAME] is title
+ assert families[EMBEDDINGS_MODEL_NAME] is report
# Before every snapshot the tests build, so a vector counts as present unless a test says otherwise.
@@ -1504,60 +1600,205 @@ LANDED_EARLY = datetime.datetime(2026, 8, 1, tzinfo=datetime.UTC)
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(
+def _vector_frame(vectors: dict[str, object], landed: datetime.datetime = LANDED_EARLY) -> pd.DataFrame:
+ """One rendering's snapshot rows, shaped like a dt=D embeddings partition."""
+ return 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 _report_vectors(
+ vectors: dict[str, object],
+ landed: datetime.datetime = LANDED_EARLY,
+ *,
+ feature_set: FeatureSet = REPORT_EMBEDDINGS_FEATURE_SET,
+) -> Extras:
+ """The side input one embedding set reads, under that set's own extras key."""
+ return {feature_set.extras_keys[0]: _vector_frame(vectors, landed)}
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():
[email protected]("feature_set", EMBEDDING_FEATURE_SETS, ids=EMBEDDING_SET_IDS)
+def test_report_embeddings_matrix_puts_the_vector_in_position_order(feature_set):
# `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))})
+ extras = _report_vectors({"a": ascending, "b": list(reversed(ascending))}, feature_set=feature_set)
- matrix = REPORT_EMBEDDINGS_FEATURE_SET.build_matrix(rows, extras)
+ matrix = feature_set.build_matrix(rows, extras)
- assert list(matrix.columns) == list(REPORT_EMBEDDINGS_FEATURE_SET.feature_names)
+ assert list(matrix.columns) == list(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]
[email protected]("feature_set", EMBEDDING_FEATURE_SETS, ids=EMBEDDING_SET_IDS)
@pytest.mark.parametrize(
- "extras",
+ "vectors",
[
- _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
+ pytest.param({"a": None}, id="tombstoned"), # the report keeps its row with a null vector
+ pytest.param({"a": [0.5] * 8}, id="another_models_width"),
+ pytest.param({"other": _embedding()}, id="no_row_for_this_report"),
+ pytest.param(None, id="snapshot_missing"), # the day's snapshot for this rendering is gone
],
)
-def test_a_report_without_this_models_vector_is_not_an_embeddings_example(extras):
+def test_a_report_without_this_models_vector_is_not_an_embeddings_example(feature_set, vectors):
# 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"])
+ extras = NO_EXTRAS if vectors is None else _report_vectors(vectors, feature_set=feature_set)
+
+ assert feature_set.buildable(rows, extras).tolist() == [False]
+ assert feature_set.build_matrix(rows, extras).isna().to_numpy().all()
+
+
+def _snapshot_objects(**frames: pd.DataFrame | None) -> dict[str, bytes]:
+ """The dt=D embeddings partitions to serve, by extras key. A key mapped to None has no object."""
+ return {
+ partition_object_key("inbox_ranking", _EXTRA_SNAPSHOT_TABLES[key], "2026-08-10"): _parquet(frame)
+ for key, frame in frames.items()
+ if frame is not None
+ }
+
+
+def _extras_for(objects: dict[str, bytes], keys=_EMBEDDING_EXTRA_KEYS, **kwargs) -> Extras:
+ return embeddings_extras(
+ dagster.build_asset_context(), _ParquetS3(objects), "bucket", "inbox_ranking", "2026-08-10", keys, **kwargs
+ )
+
+
+def test_a_missing_rendering_is_left_out_while_an_empty_one_keeps_its_key():
+ # The two cases must not be folded together. A missing snapshot has to leave the family's
+ # partition as it stands, because rebuilding from nothing writes an empty candidate over
+ # boosters a champion pointer can name. A snapshot that exists and holds no usable vector is a
+ # day the family genuinely has nothing to fit, and takes the ordinary thin-input path.
+ empty = _vector_frame({}).astype({EMBEDDING_COLUMN: object})
- assert REPORT_EMBEDDINGS_FEATURE_SET.buildable(rows, extras).tolist() == [False]
- assert REPORT_EMBEDDINGS_FEATURE_SET.build_matrix(rows, extras).isna().to_numpy().all()
+ missing_title = _extras_for(
+ _snapshot_objects(report_embeddings=_vector_frame({"a": _embedding()}), title_embeddings=None)
+ )
+ assert set(missing_title) == {REPORT_EMBEDDINGS_EXTRA}
+ assert TITLE_EMBEDDINGS_FEATURE_SET.missing_extras(missing_title) == (TITLE_EMBEDDINGS_EXTRA,)
+ assert REPORT_EMBEDDINGS_FEATURE_SET.missing_extras(missing_title) == ()
+
+ empty_title = _extras_for(
+ _snapshot_objects(report_embeddings=_vector_frame({"a": _embedding()}), title_embeddings=empty)
+ )
+ assert TITLE_EMBEDDINGS_FEATURE_SET.missing_extras(empty_title) == ()
+ assert TITLE_EMBEDDINGS_FEATURE_SET.buildable(_state(["a"]), empty_title).tolist() == [False]
+
+
+def test_a_rendering_is_read_only_when_a_set_asks_for_it():
+ # The examples asset reads one set's inputs at a time, so a family it is not building must not
+ # pull a fleet-wide vector table across the network.
+ objects = _snapshot_objects(
+ report_embeddings=_vector_frame({"a": _embedding()}), title_embeddings=_vector_frame({"a": _embedding()})
+ )
+ assert set(_extras_for(objects, TITLE_EMBEDDINGS_FEATURE_SET.extras_keys)) == {TITLE_EMBEDDINGS_EXTRA}
+ assert _extras_for(objects, ()) == {}
+
+
+def _retained_vector_bytes(vectors: pd.DataFrame) -> int:
+ """The bytes the frame's vectors keep alive, counting each shared buffer once.
+
+ `to_pandas` gives every row a view on the Arrow child buffer the whole column was decoded
+ into, so a frame of one row can hold the whole snapshot. `.base` is that buffer.
+ """
+ buffers = {id(value.base): value.base.nbytes for value in vectors[EMBEDDING_COLUMN] if value.base is not None}
+ return sum(buffers.values())
+
+
+def test_a_snapshot_is_narrowed_to_the_rows_the_caller_scores():
+ # A snapshot holds a vector per live report while the scored population is one day's newborns,
+ # so the scorer passes the pool's index rather than holding a table per rendering at full size.
+ # Narrowing the frame is not enough: filtered in pandas, the one kept row still holds every
+ # decoded vector alive, and the two renderings then sit in the pod together at full size.
+ vectors = {f"old_{index}": _embedding() for index in range(64)}
+ objects = _snapshot_objects(title_embeddings=_vector_frame({"newborn": _embedding(), **vectors}))
+ keys = TITLE_EMBEDDINGS_FEATURE_SET.extras_keys
+
+ narrowed = _extras_for(objects, keys, report_ids=pd.Index(["newborn", "never_embedded"]))
+ whole = _extras_for(objects, keys)
+
+ assert narrowed[TITLE_EMBEDDINGS_EXTRA].index.tolist() == ["newborn"]
+ assert whole[TITLE_EMBEDDINGS_EXTRA].index.tolist() == ["newborn", *vectors]
+ assert _retained_vector_bytes(narrowed[TITLE_EMBEDDINGS_EXTRA]) * 8 < _retained_vector_bytes(
+ whole[TITLE_EMBEDDINGS_EXTRA]
+ )
+
+
+def test_only_the_set_whose_snapshot_is_missing_is_skipped(monkeypatch):
+ # One rendering's failed snapshot must cost one family's day. The others have to keep building,
+ # or a title-side gap silently stops the combined family the title is measured against.
+ module = "products.signals.dags.inbox_ranking.training.dag"
+ written: list[str] = []
+ monkeypatch.setattr(f"{module}.skip_unconfigured", lambda context: False)
+ monkeypatch.setattr(f"{module}.s3_client", lambda: None)
+ monkeypatch.setattr(f"{module}.load_snapshots", lambda *args, **kwargs: {})
+ monkeypatch.setattr(
+ f"{module}.embeddings_extras",
+ lambda context, client, bucket, prefix, partition_key, keys: {
+ key: _vector_frame({}) for key in keys if key != TITLE_EMBEDDINGS_EXTRA
+ },
+ )
+
+ def _record(context, client, bucket, prefix, partition_key, feature_set, *args) -> dict[str, Any]:
+ written.append(feature_set.name)
+ return {}
+
+ monkeypatch.setattr(f"{module}._write_examples", _record)
+
+ with dagster.build_asset_context(partition_key="2026-08-10") as context:
+ inbox_ranking_training_examples(context)
+ metadata = context.get_output_metadata("result")
+
+ assert written == [TABULAR_FEATURE_SET.name, REPORT_EMBEDDINGS_FEATURE_SET.name]
+ assert metadata[f"{TITLE_EMBEDDINGS_FEATURE_SET.name}_skipped"].value is True
-def test_report_grain_keeps_one_example_per_report_and_needs_a_vector():
+ "asset",
+ [inbox_ranking_training_examples, inbox_ranking_unseen_scores],
+ ids=["examples", "unseen_scores"],
+)
+def test_both_renderings_snapshots_are_upstream_of_the_assets_that_read_them(asset):
+ # An asset that reads a snapshot without declaring it can run before the day's snapshot lands
+ # and record the family as having no input. One dependency per rendering, so the two renderings
+ # are scheduled independently rather than as one edge that either family's failure breaks.
+ deps = {key.path[-1] for key in asset.keys_by_input_name.values()}
+ assert {EMBEDDINGS_TABLE, TITLE_EMBEDDINGS_TABLE} <= deps
+
+
+def test_a_rendering_never_falls_back_to_the_other_renderings_vector():
+ # The families exist to measure the title against the title plus summary, so a row that took
+ # the other rendering's vector would compare the two models on partly the same text. The inputs
+ # also diverge in practice: a summary-only edit re-embeds only the combined rendering, and
+ # either snapshot can hold a report the other does not.
+ rows = _state(["combined_only", "title_only"])
+ extras = {
+ **_report_vectors({"combined_only": _embedding()}, feature_set=REPORT_EMBEDDINGS_FEATURE_SET),
+ **_report_vectors({"title_only": _embedding()}, feature_set=TITLE_EMBEDDINGS_FEATURE_SET),
+ }
+
+ assert REPORT_EMBEDDINGS_FEATURE_SET.buildable(rows, extras).tolist() == [True, False]
+ assert TITLE_EMBEDDINGS_FEATURE_SET.buildable(rows, extras).tolist() == [False, True]
+
+
[email protected]("feature_set", EMBEDDING_FEATURE_SETS, ids=EMBEDDING_SET_IDS)
+def test_report_grain_keeps_one_example_per_report_and_needs_a_vector(feature_set):
# The scoring-moment grain emits a near-duplicate row per snapshot, which is what 1536 columns
# cannot afford; the report grain keeps the first snapshot a report is usable on.
head = HEADS_BY_NAME["open"]
snapshots = _daily_snapshots(["a", "b"], head, [BIRTH, BIRTH])
- extras = _report_vectors({"a": _embedding()})
+ extras = _report_vectors({"a": _embedding()}, feature_set=feature_set)
- examples = build_examples(snapshots, head, _at_grain(REPORT_EMBEDDINGS_FEATURE_SET, REPORT_GRAIN), extras)
+ examples = build_examples(snapshots, head, _at_grain(feature_set, REPORT_GRAIN), extras)
assert examples["report_id"].tolist() == ["a"]
assert examples["snapshot_date"].tolist() == [D0]
@@ -1584,53 +1825,68 @@ def test_cap_examples_keeps_every_positive_and_a_seeded_sample_of_the_negatives(
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)
+ # Both renderings at once, because the paired read is the whole point of the second one, and
+ # each reports its own coverage: one thin rendering must not read as the other's.
+ models = [_unseen_model(family.name, family.feature_set) for family in MODEL_FAMILIES]
pool = _state(["a", "b"])
- extras = _report_vectors({"a": _embedding()})
+ extras = {
+ **_report_vectors({"a": _embedding()}, feature_set=REPORT_EMBEDDINGS_FEATURE_SET),
+ **_report_vectors({"a": _embedding(), "b": _embedding()}, feature_set=TITLE_EMBEDDINGS_FEATURE_SET),
+ }
- scores = score_pool(pool, _labels(["a", "b"]), [model], snapshot_date=D0, extras=extras)
+ scores = score_pool(pool, _labels(["a", "b"]), models, snapshot_date=D0, extras=extras)
- assert scores["report_id"].tolist() == ["a", "b"]
+ assert set(scores["model_name"]) == {family.name for family in MODEL_FAMILIES}
+ for model_name in scores["model_name"].unique():
+ assert scores[scores["model_name"] == model_name]["report_id"].tolist() == ["a", "b"]
assert scores["score"].notna().all()
- coverage = pool_feature_coverage(pool, [model], extras, SNAPSHOT_END)
+ coverage = pool_feature_coverage(pool, models, extras, SNAPSHOT_END)
assert coverage[f"{REPORT_EMBEDDINGS_FEATURE_SET.name}_pool_coverage"].value == 0.5
+ assert coverage[f"{TITLE_EMBEDDINGS_FEATURE_SET.name}_pool_coverage"].value == 1.0
-def test_a_vector_that_landed_after_the_moment_is_not_that_moments_feature():
[email protected]("feature_set", EMBEDDING_FEATURE_SETS, ids=EMBEDDING_SET_IDS)
+def test_a_vector_that_landed_after_the_moment_is_not_that_moments_feature(feature_set):
# 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))
+ extras = _report_vectors(
+ {"a": _embedding()}, landed=SNAPSHOT_END + datetime.timedelta(days=1), feature_set=feature_set
+ )
- 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()
+ assert feature_set.buildable(rows, extras, as_of=SNAPSHOT_END).tolist() == [False]
+ assert 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]
+ assert 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():
[email protected]("feature_set", EMBEDDING_FEATURE_SETS, ids=EMBEDDING_SET_IDS)
+def test_report_grain_moves_the_example_to_the_first_moment_its_vector_existed_for(feature_set):
# 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"]
snapshots = _daily_snapshots(["a"], head, [BIRTH])
# 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))
+ extras = _report_vectors(
+ {"a": _embedding()}, landed=SNAPSHOT_END + datetime.timedelta(hours=6), feature_set=feature_set
+ )
- examples = build_examples(snapshots, head, _at_grain(REPORT_EMBEDDINGS_FEATURE_SET, REPORT_GRAIN), extras)
+ examples = build_examples(snapshots, head, _at_grain(feature_set, REPORT_GRAIN), extras)
assert examples["snapshot_date"].tolist() == [D0 + datetime.timedelta(days=1)]
# At the birth grain there is no later moment to move to, so the report is no example at all.
- assert build_examples(snapshots, head, REPORT_EMBEDDINGS_FEATURE_SET, extras).empty
+ assert build_examples(snapshots, head, feature_set, extras).empty
-def test_reading_a_moment_needs_the_vectors_landing_time():
[email protected]("feature_set", EMBEDDING_FEATURE_SETS, ids=EMBEDDING_SET_IDS)
+def test_reading_a_moment_needs_the_vectors_landing_time(feature_set):
# 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"])}
+ vectors = {feature_set.extras_keys[0]: 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.buildable(_state(["a"]), vectors, as_of=SNAPSHOT_END)
@pytest.mark.parametrize(
@@ -1639,6 +1895,14 @@ def test_reading_a_moment_needs_the_vectors_landing_time():
(TABULAR_FEATURE_SET, NO_EXTRAS, ()),
(REPORT_EMBEDDINGS_FEATURE_SET, _report_vectors({"a": _embedding()}), ()),
(REPORT_EMBEDDINGS_FEATURE_SET, NO_EXTRAS, (REPORT_EMBEDDINGS_EXTRA,)),
+ # Each rendering answers for its own input: the other one being present is not its input.
+ (
+ TITLE_EMBEDDINGS_FEATURE_SET,
+ _report_vectors({"a": _embedding()}, feature_set=TITLE_EMBEDDINGS_FEATURE_SET),
+ (),
+ ),
+ (TITLE_EMBEDDINGS_FEATURE_SET, NO_EXTRAS, (TITLE_EMBEDDINGS_EXTRA,)),
+ (TITLE_EMBEDDINGS_FEATURE_SET, _report_vectors({"a": _embedding()}), (TITLE_EMBEDDINGS_EXTRA,)),
],
)
def test_a_set_declares_the_side_inputs_it_needs(feature_set, extras, expected):
diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.py
index 17c56ff5f3cd..17e6c00a8ba9 100644
--- a/products/signals/dags/inbox_ranking/training/dag.py
+++ b/products/signals/dags/inbox_ranking/training/dag.py
@@ -23,7 +23,8 @@ graded 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.
+every other family still trains, promotes and gets graded. The two embedding families read one text
+rendering each, from separate snapshots, so a missing snapshot costs one family and not the pair.
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);
@@ -36,11 +37,13 @@ comparable because both apply the same `Head` cohort, label and horizon.
import json
import datetime
from collections.abc import Mapping, Sequence
+from types import MappingProxyType
from typing import Any
import pandas as pd
import dagster
import pyarrow as pa
+import pyarrow.compute as pc
from botocore.exceptions import ClientError
from posthog import settings
@@ -49,8 +52,8 @@ from products.signals.backend.ranking.features import (
EMBEDDING_COLUMN,
EMBEDDING_INSERTED_AT_COLUMN,
FEATURE_SETS,
- NO_EXTRAS,
REPORT_EMBEDDINGS_EXTRA,
+ TITLE_EMBEDDINGS_EXTRA,
Extras,
FeatureSet,
)
@@ -70,7 +73,12 @@ from products.signals.dags.inbox_ranking.common import (
snapshot_bounds,
write_parquet,
)
-from products.signals.dags.inbox_ranking.dataset.dag import EMBEDDINGS_TABLE, LABELS_TABLE, STATE_TABLE
+from products.signals.dags.inbox_ranking.dataset.dag import (
+ EMBEDDINGS_TABLE,
+ LABELS_TABLE,
+ STATE_TABLE,
+ TITLE_EMBEDDINGS_TABLE,
+)
from products.signals.dags.inbox_ranking.training.examples import (
BASE_STATE_COLUMNS,
PROVENANCE_LABEL_COLUMNS,
@@ -115,6 +123,7 @@ from products.signals.dags.inbox_ranking.training.unseen import (
UnseenModel,
calibration_rows,
empty_scores_write_allowed,
+ families_lost_by_rewrite,
graded_rows,
head_grades,
leaked_report_ids,
@@ -248,10 +257,28 @@ def load_snapshots(
return snapshots
-def report_embeddings_extras(
- context: dagster.AssetExecutionContext, client, bucket: str, prefix: str, partition_key: str
+# The dt=D snapshot table behind each embedding side input. One table per rendering, read on its
+# own: a rendering's snapshot can be missing while the other's is present, and the families must
+# not share a fate.
+_EXTRA_SNAPSHOT_TABLES: Mapping[str, str] = MappingProxyType(
+ {
+ REPORT_EMBEDDINGS_EXTRA: EMBEDDINGS_TABLE,
+ TITLE_EMBEDDINGS_EXTRA: TITLE_EMBEDDINGS_TABLE,
+ }
+)
+
+
+def embeddings_extras(
+ context: dagster.AssetExecutionContext,
+ client,
+ bucket: str,
+ prefix: str,
+ partition_key: str,
+ extras_keys: Sequence[str],
+ *,
+ report_ids: pd.Index | None = None,
) -> Extras:
- """The dt=D report vectors, indexed by report_id: the side input the report-embeddings set reads.
+ """The dt=D vectors for `extras_keys`, each indexed by report_id and read from its own snapshot.
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
@@ -260,22 +287,41 @@ def report_embeddings_extras(
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.
+ A **missing** snapshot is not a failure, and not an empty side input either: the key is left
+ out, so the caller skips only the sets that read it. Rebuilding one of those from nothing would
+ strip the family's partition. A snapshot that **exists** and carries no usable vector is the
+ other case, and keeps its key: no row is then buildable, the family's heads read as unfit, and
+ the ordinary thin-input path applies. The two cannot be folded together, because the first must
+ leave a partition alone and the second is a day the family genuinely has nothing to fit.
+
+ `report_ids` narrows each frame to the rows the caller will ask for. Every snapshot holds a
+ vector per live report, so a caller that only scores one day's newborns passes the pool's index
+ rather than holding a fleet-wide vector table per rendering at once. The narrowing happens in
+ Arrow, before the frame exists: `to_pandas` gives each row a view on the snapshot's whole
+ vector buffer, so a pandas filter would leave a thin frame holding the fleet-wide table alive.
"""
- 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()]}
+ extras: dict[str, pd.DataFrame] = {}
+ for extras_key in extras_keys:
+ table_name = _EXTRA_SNAPSHOT_TABLES[extras_key]
+ table = read_parquet_if_exists(
+ client,
+ bucket,
+ partition_object_key(prefix, table_name, partition_key),
+ columns=["report_id", EMBEDDING_COLUMN, EMBEDDING_INSERTED_AT_COLUMN],
+ )
+ if table is None:
+ context.log.warning(
+ f"no {table_name} snapshot for dt={partition_key}; the {extras_key} side input is unavailable"
+ )
+ continue
+ if report_ids is not None:
+ wanted = pa.array(report_ids.to_numpy(), type=table.schema.field("report_id").type)
+ table = table.filter(pc.is_in(table.column("report_id"), value_set=wanted))
+ vectors = table.to_pandas().set_index("report_id")
+ # `reindex` refuses a duplicated index, and one report is one document per rendering.
+ vectors = vectors[~vectors.index.duplicated()]
+ extras[extras_key] = vectors
+ return extras
def examples_table(examples: pd.DataFrame, feature_set: FeatureSet) -> pa.Table:
@@ -297,8 +343,10 @@ _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.
+ # Only dt=D: `embeddings_extras` explains why one snapshot serves the whole window. One
+ # dependency per rendering, so a missing title snapshot costs only the title family.
EMBEDDINGS_TABLE,
+ TITLE_EMBEDDINGS_TABLE,
],
**COMMON_ASSET_KWARGS,
)
@@ -321,30 +369,49 @@ def inbox_ranking_training_examples(context: dagster.AssetExecutionContext) -> N
if unreachable_reports:
context.log.warning(f"{unreachable_reports} reports born inside the window have no birth-day snapshot")
- 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),
"reports_missing_birth_snapshot": dagster.MetadataValue.int(unreachable_reports),
}
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)
- continue
- metadata |= _write_examples(
- context, client, bucket, prefix, partition_key, feature_set, snapshots, backfilled_rows, extras
+ metadata |= _examples_for_set(
+ context, client, bucket, prefix, partition_key, feature_set, snapshots, backfilled_rows
)
context.add_output_metadata(metadata)
+def _examples_for_set(
+ 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, side inputs included, and its asset metadata.
+
+ The side inputs are read and released inside this call, so the next set's snapshot is read
+ after this set's is gone. Each embeddings snapshot carries a vector per live report, and a
+ name still bound in the caller's loop would hold the previous rendering through the next read,
+ which is what makes the peak scale with the number of families.
+ """
+ extras = embeddings_extras(context, client, bucket, prefix, partition_key, feature_set.extras_keys)
+ 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)}")
+ return {f"{feature_set.name}_skipped": dagster.MetadataValue.bool(True)}
+ return _write_examples(
+ context, client, bucket, prefix, partition_key, feature_set, snapshots, backfilled_rows, extras
+ )
+
+
def _write_examples(
context: dagster.AssetExecutionContext,
client,
@@ -823,7 +890,7 @@ def pool_feature_coverage(
@dagster.asset(
name=UNSEEN_SCORES_TABLE,
- deps=["inbox_ranking_model_champion", STATE_TABLE, LABELS_TABLE, EMBEDDINGS_TABLE],
+ deps=["inbox_ranking_model_champion", STATE_TABLE, LABELS_TABLE, EMBEDDINGS_TABLE, TITLE_EMBEDDINGS_TABLE],
**COMMON_ASSET_KWARGS,
)
def inbox_ranking_unseen_scores(context: dagster.AssetExecutionContext) -> None:
@@ -851,8 +918,19 @@ 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]}"
)
- 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)
+ loaded = load_unseen_models(context, client, bucket, prefix, partition_key)
+ # Only the side inputs the day's models read, and only the pool's rows: a snapshot holds a
+ # vector per live report, while the scored population is one day's newborns.
+ extras = embeddings_extras(
+ context,
+ client,
+ bucket,
+ prefix,
+ partition_key,
+ tuple(dict.fromkeys(key for model in loaded for key in model.feature_set.extras_keys)),
+ report_ids=pool.index,
+ )
+ models = models_with_extras(context, loaded, 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:
@@ -866,6 +944,16 @@ def inbox_ranking_unseen_scores(context: dagster.AssetExecutionContext) -> None:
)
context.log.warning(f"nothing scored for dt={partition_key}: {len(pool)} newborn reports, {len(models)} models")
+ # One object holds every family, so what it already holds decides whether this run may replace it.
+ existing = read_parquet_if_exists(client, bucket, key)
+ lost = families_lost_by_rewrite(existing.to_pandas(), scores) if existing is not None else []
+ if lost:
+ raise dagster.Failure(
+ f"{UNSEEN_SCORES_TABLE} dt={partition_key} already holds rows for {', '.join(lost)} and this run scored "
+ f"none of them, so writing would destroy the scores the dt=D+horizon grade reads. A family is skipped "
+ f"for the day when its models or its set's side input are missing for the partition. Repair the missing "
+ f"input and re-run, or delete the object by hand to replace it deliberately."
+ )
write_parquet(client, bucket, key, scores_table(scores), snapshot_date=partition_key)
context.add_output_metadata(
{
@@ -986,10 +1074,12 @@ inbox_ranking_training_job = dagster.define_asset_job(
# 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, 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.
+ # plus labels per day) before the per-head builders run, plus one rendering's vectors as
+ # the side input the embedding set being built reads, so the peak grows with the lookback
+ # and the inventory. It is one rendering at a time rather than one per family, so a further
+ # embedding family costs runtime and not peak. 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": {
diff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.py
index db2c17e5ccc5..1f3ae26f113d 100644
--- a/products/signals/dags/inbox_ranking/training/unseen.py
+++ b/products/signals/dags/inbox_ranking/training/unseen.py
@@ -27,6 +27,7 @@ from products.signals.backend.ranking.features import (
NO_EXTRAS,
REPORT_EMBEDDINGS_FEATURE_SET,
TABULAR_FEATURE_SET,
+ TITLE_EMBEDDINGS_FEATURE_SET,
Extras,
FeatureSet,
feature_set_by_name,
@@ -57,6 +58,7 @@ CHAMPION_ROLE = "champion"
# it was fit on. Both are in the identity, so two families trained on one day stay apart.
TABULAR_MODEL_NAME = "tabular_xgb"
REPORT_EMBEDDINGS_MODEL_NAME = "report_embeddings"
+TITLE_EMBEDDINGS_MODEL_NAME = "title_embeddings"
# A shuffle plus one AUC rather than a refit, so this sits far above the trainer's NULL_PERMUTATIONS.
NULL_PERMUTATIONS = 25
@@ -112,7 +114,7 @@ class UnseenModel:
@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
+ its trainer fits. Every family is 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
@@ -122,9 +124,14 @@ class ModelFamily:
# 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.
+# The two embedding families read one `ReportEmbeddingsFeatureSet` instance each and fit with the
+# same module-level `XGB_PARAMS`, so their width, grain, row budget, sampling, split and booster
+# settings match by construction. Keep it that way: the pair is a measurement of the text choice,
+# and a recipe that differed between them would answer a question nobody asked.
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),
+ ModelFamily(name=TITLE_EMBEDDINGS_MODEL_NAME, feature_set=TITLE_EMBEDDINGS_FEATURE_SET),
)
@@ -335,6 +342,19 @@ def with_model_names(scores: pd.DataFrame) -> pd.DataFrame:
return scores.assign(model_name=scores["model_name"].fillna(TABULAR_MODEL_NAME))
+def families_lost_by_rewrite(existing: pd.DataFrame, scores: pd.DataFrame) -> list[str]:
+ """The families whose rows a rewrite of a partition's scores object would delete.
+
+ One object holds every family, and the write replaces it in full, so a run that scored fewer
+ families than the object already holds removes the rest. That is the loss
+ `empty_scores_write_allowed` refuses for a run that scored nothing, and a family is skipped
+ whenever its models or its set's side input are missing for the partition, so the partial case
+ is as ordinary as the empty one. Reading the object settles what it holds, which the row-count
+ stamp alone cannot.
+ """
+ return sorted(set(with_model_names(existing)["model_name"].unique()) - set(scores["model_name"].unique()))
+
+
def score_pool(
pool: pd.DataFrame,
labels: pd.DataFrame,