:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): keep birth-day outcomes in ranking labels and the newborn grade (#101503)
posthog[bot]c8e082d2fed0
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex bb45a8e8b688..66e551cfb064 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -74,7 +74,8 @@ 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.- **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 report's birth day is the exception to "still 0 on that snapshot".** A report born on day D has no scoring moment before D, so an outcome already visible at D is a future positive for that moment, not an outcome of 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.+- **Serving population caveat.** Past the birth day, 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.- **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.@@ -89,12 +90,12 @@ s3://<bucket>/<prefix>/The holdout grades the recipe, not the model that ships: the shipped booster is refit on train plus holdout, and every holdout row comes from the same snapshots the trainer saw.Two assets add the missing number, an offline batch proxy for performance on reports the model never saw.-- **`inbox_ranking_unseen_scores` (dt=D)** takes the dt=D state rows of the reports **created on D**, the pool the events tag `pool=newborn`. A newborn has no scoring moment before D, and the dt=D examples stop at D minus the head's horizon (3 days at the shortest), so no example can cover it: leakage-freedom is structural, not a property of what the example builder did that day. The set difference against the examples Parquet stays as a runtime guard — a non-empty overlap fails the asset instead of publishing the number. Every newborn is scored, not a sample, with the day's candidate and, when the pointer names a different version, the champion. Only readable heads are scored, and a model whose feature contract has moved on is logged and left out. 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.+- **`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_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.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.-Three 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`, `base_rate`, `auc` and `recency_auc`, and `inbox_ranking_unseen_report_graded` per (report, model, horizon) with `p_<head>`, `in_cohort_<head>` and `outcome_<head>` for calibration reads. 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.+Three 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`, `auc` and `recency_auc`, and `inbox_ranking_unseen_report_graded` per (report, model, horizon) with `p_<head>`, `in_cohort_<head>` and `outcome_<head>` for calibration reads. 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.### Running the training job locallydiff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.pyindex 6acd550fc1de..29fdec9bf528 100644--- a/products/signals/dags/inbox_ranking/tests/test_training.py+++ b/products/signals/dags/inbox_ranking/tests/test_training.py@@ -53,6 +53,7 @@ from products.signals.dags.inbox_ranking.training.examples import (STATE_LAG_LIMIT,Snapshot,assemble_snapshot,+ birth_day_positives,build_examples,cap_examples,example_columns,@@ -515,7 +516,8 @@ def _scores(report_ids: list[str], **overrides) -> pd.DataFrame:base = {"report_id": report_ids,"team_id": [2] * n,- "report_created_at": [pd.Timestamp("2026-08-09T12:00:00Z")] * n,+ # The default pool is the newborn one, so the default row was born on the day it was scored.+ "report_created_at": [pd.Timestamp("2026-08-10T09:00:00Z")] * n,"snapshot_date": [D0] * n,"pool": [POOL_NAME] * n,"model_name": [TABULAR_MODEL_NAME] * n,@@ -565,6 +567,23 @@ def test_build_examples_never_covers_a_report_born_on_the_partition_day():assert set(build_examples(snapshots, head, TABULAR_FEATURE_SET)["report_id"]) == {"old"}+def test_build_examples_keeps_an_outcome_that_landed_on_the_reports_birth_day():+ # Most PRs land the day the report is born. Censoring on the labels of the birth day would+ # drop those positives from the head that predicts them.+ head = HEADS_BY_NAME["pr_created"]+ later = D0 + datetime.timedelta(days=head.horizon_days)+ ids = ["newborn", "old"]+ created = [pd.Timestamp("2026-08-10T09:00:00Z"), pd.Timestamp("2026-07-01T00:00:00Z")]+ snapshots = {+ date: assemble_snapshot(date, _state(ids, report_created_at=created), _labels(ids, pr_created_count=[1, 1]))+ for date in (D0, later)+ }+ examples = build_examples(snapshots, head, TABULAR_FEATURE_SET)+ # The old report's PR predates D0, so it belongs to a moment before D0 and stays censored.+ assert examples.set_index("report_id")["label"].to_dict() == {"newborn": 1}+ assert birth_day_positives(examples) == 1++def test_leaked_report_ids_flags_a_pool_report_an_example_already_covers():# The guard must fail the asset rather than publish an AUC measured on training data.pool = _state(["a", "b"])@@ -574,29 +593,64 @@ def test_leaked_report_ids_flags_a_pool_report_an_example_already_covers():def test_grading_keeps_the_scoring_moment_rows_and_reads_the_outcome_later():# Same rule build_examples applies, so the unseen AUC is comparable to the holdout AUC: the- # outcome must not have happened at scoring time, and the cohort is read at the later snapshot.+ # cohort is read at the later snapshot, and a newborn keeps the outcome that landed on its+ # own birth day, which is where most outcomes land.head = HEADS_BY_NAME["open"]scores = _scores(["a", "b", "c", "d", "e"], label_at_scoring=[False, True, False, False, False])labels = _labels(["a", "b", "c", "e"], open_count=[1, 1, 1, 0], impression_unit_count=[1, 1, 0, 1])- graded = graded_rows(scores, labels, head).set_index("report_id")- # b was already opened when it was scored, c was never impressed, d has no labels row at all.- assert graded["in_cohort"].to_dict() == {"a": True, "b": False, "c": False, "d": False, "e": True}- assert (graded.loc["a", "outcome"], graded.loc["e", "outcome"]) == (True, False)+ graded = graded_rows(scores, labels, head, pool=POOL_NAME).set_index("report_id")+ # c was never impressed and d has no labels row at all; b was opened on its birth day, which+ # the newborn pool grades rather than drops.+ assert graded["in_cohort"].to_dict() == {"a": True, "b": True, "c": False, "d": False, "e": True}+ assert (graded.loc["a", "outcome"], graded.loc["b", "outcome"], graded.loc["e", "outcome"]) == (True, True, False)# An excluded row keeps its score with no outcome, so a calibration read can filter on the flag.- assert graded.loc[["b", "c", "d"], "outcome"].isna().all()+ assert graded.loc[["c", "d"], "outcome"].isna().all()+++def test_grading_an_older_pool_still_drops_an_outcome_that_predates_the_score():+ # The legacy sampled pool held reports of any age, so an outcome already observed at scoring+ # time belongs to an earlier moment there and must stay out of the grade.+ head = HEADS_BY_NAME["open"]+ scores = _scores(+ ["a", "b"],+ pool=[LEGACY_POOL_NAME] * 2,+ report_created_at=[pd.Timestamp("2026-07-01T00:00:00Z")] * 2,+ label_at_scoring=[False, True],+ )+ labels = _labels(["a", "b"], open_count=[1, 1], impression_unit_count=[1, 1])+ graded = graded_rows(scores, labels, head, pool=LEGACY_POOL_NAME).set_index("report_id")+ assert graded["in_cohort"].to_dict() == {"a": True, "b": False}+++def test_grading_a_status_label_head_drops_a_newborn_outcome_from_the_scoring_day():+ # build_examples reads label_provenance_ok on the scoring snapshot too, and no scores column+ # carries that verdict, so grading the row would accept a label the builder can still refuse.+ head = HEADS_BY_NAME["dismiss_wrong"]+ scores = _scores(["a", "b"], label_at_scoring=[False, True])+ labels = _labels(+ ["a", "b"],+ wrong_dismissal_count=[1, 1],+ impression_unit_count=[1, 1],+ label_provenance_ok=[True, True],+ )+ graded = graded_rows(scores, labels, head, pool=POOL_NAME).set_index("report_id")+ assert graded["in_cohort"].to_dict() == {"a": True, "b": False}def test_head_grades_report_counts_and_an_undefined_auc_on_a_single_class():head = HEADS_BY_NAME["open"]labels = _labels(["a", "e"], open_count=[1, 0])- two_classes = graded_rows(_scores(["a", "e"], score=[0.9, 0.1]), labels, head)+ scores = _scores(["a", "e"], score=[0.9, 0.1], label_at_scoring=[True, False])+ two_classes = graded_rows(scores, labels, head, pool=POOL_NAME)(grade,) = head_grades(two_classes, head, pool=POOL_NAME, scoring_partition="2026-08-10")assert (grade.rows, grade.positives, grade.auc, grade.base_rate) == (2, 1, 1.0, 0.5)+ # a was opened on its birth day, so the grade says how much of its signal that day carries.+ assert grade.birth_day_positives == 1assert grade.recency_auc == 0.5 # both reports are the same age, so newest-first cannot rank themassert grade.null_auc is not None# A head with rows but one outcome class still reports, so the daily series has no gap.(single_class,) = head_grades(- graded_rows(_scores(["e"]), _labels(["e"], open_count=[0]), head),+ graded_rows(_scores(["e"]), _labels(["e"], open_count=[0]), head, pool=POOL_NAME),head,pool=POOL_NAME,scoring_partition="2026-08-10",@@ -644,7 +698,10 @@ def test_head_grades_keep_two_families_apart_on_the_same_rows():labels = _labels(["a", "e"], open_count=[1, 0])tabular = _scores(["a", "e"], score=[0.9, 0.1])embeddings = _scores(["a", "e"], score=[0.1, 0.9], model_name=[EMBEDDINGS_MODEL_NAME] * 2)- graded = pd.concat([graded_rows(tabular, labels, head), graded_rows(embeddings, labels, head)], ignore_index=True)+ graded = pd.concat(+ [graded_rows(tabular, labels, head, pool=POOL_NAME), graded_rows(embeddings, labels, head, pool=POOL_NAME)],+ 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),@@ -785,8 +842,8 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):],"skipped_heads": ["dismiss_wrong"],}- scores = _scores(["a"], model_version=["2026-08-25"], score=[0.8])- graded = graded_rows(scores, _labels(["a"], open_count=[1]), HEADS_BY_NAME["open"])+ scores = _scores(["a"], model_version=["2026-08-25"], score=[0.8], label_at_scoring=[True])+ graded = graded_rows(scores, _labels(["a"], open_count=[1]), HEADS_BY_NAME["open"], pool=POOL_NAME)grades = head_grades(graded, HEADS_BY_NAME["open"], pool=POOL_NAME, scoring_partition="2026-08-22")events = [*candidate_events(metadata),@@ -796,7 +853,7 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):feature_set=TABULAR_FEATURE_SET.name,snapshots=20,backfilled_rows=0,- per_head={"open": HeadExampleCounts(rows=10, positives=2)},+ per_head={"open": HeadExampleCounts(rows=10, positives=2, birth_day_positives=1)},),promotion_event(partition_key="2026-08-25",@@ -848,6 +905,7 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):"head": "open","rows": 10,"positives": 2,+ "birth_day_positives": 1,"feature_set": TABULAR_FEATURE_SET.name,}.items() <= examples_props.items()promotion_props = by_event["inbox_ranking_promotion_decided"][0]["properties"]@@ -877,6 +935,7 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):"horizon_days": 3,"rows": 1,"positives": 1,+ "birth_day_positives": 1,"auc": None,}.items() <= head_graded_props.items()report_graded_props = by_event["inbox_ranking_unseen_report_graded"][0]["properties"]diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pyindex e5d528f33830..7ec700e95af1 100644--- a/products/signals/dags/inbox_ranking/training/dag.py+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -77,6 +77,7 @@ from products.signals.dags.inbox_ranking.training.examples import (PROVENANCE_STATE_COLUMNS,Snapshot,assemble_snapshot,+ birth_day_positives,build_examples,example_columns,point_in_time_mask,@@ -350,7 +351,11 @@ def _write_examples(key = examples_object_key(prefix, feature_set.name, partition_key)write_parquet(client, bucket, key, examples_table(examples, feature_set), snapshot_date=partition_key)counts = {- name: HeadExampleCounts(rows=len(frame), positives=int(frame["label"].sum()))+ name: HeadExampleCounts(+ rows=len(frame),+ positives=int(frame["label"].sum()),+ birth_day_positives=birth_day_positives(frame),+ )for name, frame in per_head.items()}metadata: dict[str, dagster.MetadataValue] = {@@ -363,6 +368,10 @@ def _write_examples(f"{feature_set.name}_{name}_positives": dagster.MetadataValue.int(head_counts.positives)for name, head_counts in counts.items()},+ **{+ f"{feature_set.name}_{name}_birth_day_positives": dagster.MetadataValue.int(head_counts.birth_day_positives)+ for name, head_counts in counts.items()+ },f"{feature_set.name}_s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),}capture_training_events(@@ -907,7 +916,7 @@ def inbox_ranking_unseen_graded(context: dagster.AssetExecutionContext) -> None:if head_scores.empty:skipped[head.name] = f"dt={scoring_partition} scored no {head.name} row"continue- graded = graded_rows(head_scores, labels, head)+ graded = graded_rows(head_scores, labels, head, pool=pool)graded_by_head[head.name] = gradedgrades.extend(head_grades(graded, head, pool=pool, scoring_partition=scoring_partition))report_rows.extend(diff --git a/products/signals/dags/inbox_ranking/training/examples.py b/products/signals/dags/inbox_ranking/training/examples.pyindex 11d7431c94e9..35a825888ffd 100644--- a/products/signals/dags/inbox_ranking/training/examples.py+++ b/products/signals/dags/inbox_ranking/training/examples.py@@ -9,6 +9,18 @@ measured better than one row per report on the engagement heads (skill issue 13)sweep's append-only score log has accrued it becomes this table's source; the snapshots are thebootstrap.+The report's birth day is the exception to "0 on the snapshot row": a report born on day D has no+scoring moment before D, so an outcome already visible at D is a future positive for the moment+being built, not a past one. The labels of day D are therefore read as the defaults for a report+born on D. Most outcomes land on the birth day, so this is where the positives are.++These birth-day 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, and only `priority` and `actionability` are cut at the snapshot. A birth-day+outcome therefore happened before its own feature read, so both the holdout AUC and the newborn+unseen grade read optimistically on these rows. What removes it is the scoring sweep's timestamped+score log becoming this table's source, not censoring the positives again.+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 event@@ -126,6 +138,20 @@ def assemble_snapshot(date: datetime.date, state: pd.DataFrame, labels: pd.DataFreturn Snapshot(date=date, state=state, labels=aligned)+def birth_day_mask(state: pd.DataFrame, date: datetime.date) -> pd.Series:+ """True for rows of the reports created on snapshot day `date`.++ Creation day stands in for the report's first scoring moment. The two differ when a report+ stays `potential` past midnight, because the state spine admits a report only once it promotes+ or is born visible, so the report's first moment is its promotion day. Such a report is still+ censored on that day, and the newborn pool never grades it. Closing that gap needs+ `first_visible_at` carried in the state schema, which no partition has today.+ """+ start, end = snapshot_bounds(date.isoformat())+ created = pd.to_datetime(state["report_created_at"], utc=True)+ return (created >= start) & (created < end)++def point_in_time_mask(state: pd.DataFrame, date: datetime.date) -> pd.Series:"""True for rows whose Postgres state was read close enough to the snapshot day to stand forthe state as of that day. Rows without the stamp are kept."""@@ -188,7 +214,10 @@ def example_moments(# 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.- keep = head.cohort(labels_later) & ~head.label(labels_now) & state["signal_count"].notna()+ # An outcome already observed at `now` belongs to an earlier moment, so it censors this+ # one. A report born on this day has no earlier moment to own it.+ censored = head.label(labels_now) & ~birth_day_mask(state, date)+ keep = head.cohort(labels_later) & ~censored & state["signal_count"].notna()keep &= point_in_time_mask(state, date)if head.status_labels:keep &= _flag_or_true(labels_now, "label_provenance_ok") & _flag_or_true(@@ -220,6 +249,19 @@ def example_moments(return pd.concat(frames, ignore_index=True)+def birth_day_positives(examples: pd.DataFrame) -> int:+ """How many of `examples`' positives sit on their report's birth day: the size of what the+ birth-day rule keeps. Read off the moment columns, so a wide set does not copy its feature+ columns to count them."""+ if examples.empty:+ return 0+ moments = examples[["report_created_at", "snapshot_date", "label"]]+ return sum(+ int((birth_day_mask(group, date) & (group["label"] == 1)).sum())+ for date, group in moments.groupby("snapshot_date", sort=False)+ )++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.diff --git a/products/signals/dags/inbox_ranking/training/heads.py b/products/signals/dags/inbox_ranking/training/heads.pyindex 9aa7f2c0daf9..e7f489037a3a 100644--- a/products/signals/dags/inbox_ranking/training/heads.py+++ b/products/signals/dags/inbox_ranking/training/heads.py@@ -4,7 +4,9 @@ Each head is a cohort (which reports are scoreable examples), a binary label, anlabel is "the outcome happened within `horizon_days` of the scoring moment", evaluated from thecumulative label columns the dataset dag snapshots. Cohort and label are vectorized over a frameof `inbox_report_labels` columns, so the same definitions read the snapshot at scoring time (label-must still be 0) and the snapshot `horizon_days` later (the label).+must still be 0) and the snapshot `horizon_days` later (the label). The report's birth day is the+exception: it has no earlier scoring moment, so an outcome already visible there is a future+positive for that moment rather than an outcome of an earlier one, and the label may already be 1.Mirrors the workspace `heads.py` (random-dev-internal, `inbox-ranking/`) for the seven heads withenough positives to ship; the other seven stay workspace-only until they are readable.diff --git a/products/signals/dags/inbox_ranking/training/telemetry.py b/products/signals/dags/inbox_ranking/training/telemetry.pyindex 09b7081ac845..6024bb360be3 100644--- a/products/signals/dags/inbox_ranking/training/telemetry.py+++ b/products/signals/dags/inbox_ranking/training/telemetry.py@@ -59,6 +59,9 @@ class TrainingEvent:class HeadExampleCounts:rows: intpositives: int+ # Of the positives, how many sit on their report's birth day: most outcomes land there, so a+ # drop in this share is the first sign the birth-day rule stopped keeping them.+ birth_day_positives: intdef candidate_events(metadata: Mapping[str, Any]) -> list[TrainingEvent]:@@ -113,6 +116,7 @@ def examples_events("head": head,"rows": counts.rows,"positives": counts.positives,+ "birth_day_positives": counts.birth_day_positives,},)for head, counts in per_head.items()diff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.pyindex a88cea4088f0..02bd60939984 100644--- a/products/signals/dags/inbox_ranking/training/unseen.py+++ b/products/signals/dags/inbox_ranking/training/unseen.py@@ -32,7 +32,7 @@ from products.signals.backend.ranking.features import (feature_set_by_name,)from products.signals.dags.inbox_ranking.common import snapshot_bounds-from products.signals.dags.inbox_ranking.training.examples import point_in_time_mask, state_rows+from products.signals.dags.inbox_ranking.training.examples import birth_day_mask, point_in_time_mask, state_rowsfrom products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, Head# Stamped on every scored event, so a chart can tell this pool definition from a later one.@@ -134,6 +134,9 @@ class HeadGrade:model_role: strrows: intpositives: int+ # Of the positives, how many had already happened when the report was scored: on this pool the+ # outcome landed on the report's own birth day, which is where most outcomes land.+ birth_day_positives: intbase_rate: float | Noneauc: float | None# AUC of "newest first" on the same outcomes. A model that does not beat it has learned@@ -147,6 +150,7 @@ class HeadGrade:return {"rows": self.rows,"positives": self.positives,+ "birth_day_positives": self.birth_day_positives,"base_rate": self.base_rate,"auc": self.auc,"recency_auc": self.recency_auc,@@ -256,10 +260,8 @@ def unseen_pool(state: pd.DataFrame, snapshot_date: datetime.date) -> pd.DataFrabackfilled state row carries current Postgres state rather than the state as of the day, and arow without `signal_count` has no features to score."""- start, end = snapshot_bounds(snapshot_date.isoformat())- created = pd.to_datetime(state["report_created_at"], utc=True)# Newborns first: the remaining filters then run over the slice, not every live report.- newborn = state.loc[((created >= start) & (created < end)).to_numpy()]+ newborn = state.loc[birth_day_mask(state, snapshot_date).to_numpy()]keep = newborn["signal_count"].notna().to_numpy()keep &= point_in_time_mask(newborn, snapshot_date).to_numpy()return newborn.loc[keep]@@ -327,8 +329,8 @@ def score_pool(Features are built exactly as `build_examples` builds them, as of the end of the pool's day, soa 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` records- whether the head's outcome had already happened on the scoring day; the grader drops those- rows, the same way the example builder drops a scoring moment whose label is already 1.+ whether the head's outcome had already happened on the scoring day. Every pool row is a+ newborn, so the grader keeps those rows rather than dropping them."""_, as_of = snapshot_bounds(snapshot_date.isoformat())aligned_labels = labels.reindex(pool.index)@@ -422,23 +424,32 @@ def missing_label_columns(labels: pd.DataFrame, head: Head) -> list[str]:return [column for column in head.label_columns if column not in labels]-def graded_rows(head_scores: pd.DataFrame, labels: pd.DataFrame, head: Head) -> pd.DataFrame:+def graded_rows(head_scores: pd.DataFrame, labels: pd.DataFrame, head: Head, *, pool: str) -> pd.DataFrame:"""`head_scores` with `in_cohort` and `outcome` read from the later snapshot's labels.- A row is in cohort when the head's outcome had not already happened on the scoring day, the- report still has a labels row, and the head's cohort holds at the grading day. The cohort is- read at the later snapshot for the same reason `build_examples` reads it there: the impression- that puts a report in the cohort usually lands after the report is scored. An out-of-cohort row- keeps its score with `outcome` null, so a calibration read can filter on the flag.+ A row is in cohort when the report still has a labels row and the head's cohort holds at the+ grading day. The cohort is read at the later snapshot for the same reason `build_examples`+ reads it there: the impression that puts a report in the cohort usually lands after the report+ is scored. An out-of-cohort row keeps its score with `outcome` null, so a calibration read can+ filter on the flag.++ Outside the newborn pool a row whose outcome had already happened on the scoring day is out of+ cohort too, because that outcome belongs to an earlier scoring moment. A newborn was scored on+ its own birth day, which has no earlier moment, so that row is graded. Same rule as+ `build_examples`.++ A status-label head is the exception, and keeps the exclusion in every pool. `build_examples`+ reads `label_provenance_ok` on the scoring snapshot as well as on the grading one, while a+ scores row carries no scoring-day verdict for this side to read. Grading a birth-day outcome+ here would therefore accept a label the builder can still refuse. Carrying that verdict on the+ score row is what lifts the exception."""ids = pd.Index(head_scores["report_id"])aligned = labels.reindex(ids)aligned.index = head_scores.index- in_cohort = (- ids.isin(labels.index)- & ~head_scores["label_at_scoring"].fillna(False).to_numpy(dtype=bool)- & head.cohort(aligned).to_numpy()- )+ in_cohort = ids.isin(labels.index) & head.cohort(aligned).to_numpy()+ if pool != POOL_NAME or head.status_labels:+ in_cohort &= ~head_scores["label_at_scoring"].fillna(False).to_numpy(dtype=bool)if head.status_labels and "label_provenance_ok" in aligned:in_cohort &= aligned["label_provenance_ok"].fillna(False).to_numpy(dtype=bool)graded = head_scores.copy()@@ -457,6 +468,7 @@ def head_grades(graded: pd.DataFrame, head: Head, *, pool: str, scoring_partitio):outcomes = rows["outcome"].to_numpy(dtype=bool)scores = rows["score"].to_numpy(dtype=float)+ at_scoring = rows["label_at_scoring"].fillna(False).to_numpy(dtype=bool)band = chance_band(outcomes, scores)grades.append(HeadGrade(@@ -469,6 +481,7 @@ def head_grades(graded: pd.DataFrame, head: Head, *, pool: str, scoring_partitiomodel_role=str(model_role),rows=len(rows),positives=int(outcomes.sum()),+ birth_day_positives=int((outcomes & at_scoring).sum()),base_rate=float(outcomes.mean()) if len(rows) else None,auc=_auc(outcomes, scores),recency_auc=_auc(outcomes, -rows["age_hours"].to_numpy(dtype=float)),