:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): add baked and unbaked unseen ranking metrics (#107205)
posthog[bot]9050b690ea6d
diff --git a/docs/internal/inbox-ranking-training.md b/docs/internal/inbox-ranking-training.mdindex b7730f472871..fdf127f94a24 100644--- a/docs/internal/inbox-ranking-training.md+++ b/docs/internal/inbox-ranking-training.md@@ -19,3 +19,48 @@ Before and after holdout numbers are not comparable because the example populatiThe daily snapshots and selectable scoring-moment and report grains remain available for future models.See the [ranking DAG README](../../products/signals/dags/inbox_ranking/README.md) for the feature-set contract and operating instructions.++## Baked and unbaked unseen metrics++`inbox_ranking_unseen_graded` evaluates the saved predictions for each scoring cohort every day, from its birth-day snapshot through each head's horizon.+It reads each scores partition once per run and never re-scores an older cohort with a newer model.+The first read has `observed_days=0`; the unit is the difference between UTC snapshot dates, not a full day of observation for every report.++- **Baked:** `inbox_ranking_unseen_head_graded`, `inbox_ranking_unseen_calibration`, and `inbox_ranking_unseen_report_graded` retain their full-horizon semantics.+- **Daily evaluations:** `inbox_ranking_unseen_head_evaluated` carries the head metrics at each observation age, including the final baked evaluation. Filter `is_mature=false` for unbaked results and `is_mature=true` for baked results.++The daily event includes `scoring_partition`, `evaluation_partition`, `observed_days`, `horizon_days`, `is_mature`, and `evaluated_at`, alongside the model family, version, role and pool.+`rows` counts eligible reports, `scored_rows` counts the original scored reports, and `cohort_coverage` is their ratio.+Eligibility can grow as reports receive impressions or opens; label availability and provenance rules still apply.+Missing scores or required label columns produce an explicit skip in the asset metadata, not an all-negative grade.+An empty eligible cohort emits zero rows and null metrics; a cohort with only one outcome class emits counts and a null AUC.+`readable` continues to describe the model's holdout readability, independently of maturity or the evaluation's sample size.++### Reading the two versions++For a cohort-date time series, group by `(scoring_partition, pool, head, model_name, model_version, model_role)`.+Select the complete event with the greatest `(evaluation_partition, evaluated_at)` in each group, rather than averaging or summing daily revisions.+Use `run_id` as a tie-breaker for an identical evaluation timestamp.+Select the complete event even when its AUC is null, so a previously defined AUC does not hide an empty or single-class revision.+Plot `scoring_partition` on the x-axis and distinguish the unbaked tail with `is_mature`.+Keep cohort age, horizon, rows and positives visible in the tooltip.+The event timestamp remains the evaluation partition's midday UTC, so default event-time trends describe the evaluation day rather than the scoring cohort.++For a history at a fixed age, filter `observed_days` first and retain the newest `evaluated_at` for each group.+For example, compare day-one cohorts with other day-one cohorts, while keeping the baked series alongside them.+Model comparisons need the same reports, observation age and pool.+The daily stream contains aggregate metrics only; per-report and per-decile events remain baked-only to bound telemetry volume.++An unbaked negative means the outcome has not happened in the available snapshot.+Later outcomes can move AUC in either direction, and early evaluations can favor reports whose outcomes arrive quickly.+Early calibration error compares a full-horizon prediction with incomplete outcomes; use baked results for calibration decisions and definitive regression judgments.+Daily evaluations do not change training labels, champion promotion or serving.+They stop at the head's horizon; a retry evaluates the named snapshot rather than extending that horizon to the retry date.++### Verification after deployment++Check that the new event has an age-zero evaluation for each scored head and subsequent evaluations through its horizon.+For the final evaluation, compare counts and metrics with the matching baked event.+Check missing-partition metadata and grading runtime; the grader reads at most `max(horizon_days) + 1` scores objects per run.+Existing baked-only consumers need no filter changes.+New charts must opt into the daily event and select one revision per cohort as described above.diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex f5e7f2322bd2..fee4259d0d7e 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -137,11 +137,11 @@ The holdout grades the recipe, not the model that ships: the shipped booster isTwo 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. Every head the candidate fit is scored, readable or not, because the pooled grade over many days is the only read a rare head can ever get; each scored row carries `head_readable`, the readability of that head on the model that wrote it, so the grade can keep the two populations apart. 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.+- **`inbox_ranking_unseen_graded` (dt=D)** reads saved scores from D back through each head's horizon and evaluates them against the dt=D labels. Daily head evaluations include both unbaked and baked metrics, marked by `is_mature`; existing head, report and calibration grade events remain baked-only at `D - horizon_days`. See [baked and unbaked unseen metrics](../../../../docs/internal/inbox-ranking-training.md#baked-and-unbaked-unseen-metrics) for the event contract and chart revision rules. 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.+At the full horizon, the cohort, label and provenance rules are the trainer's own, so the baked 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 `readable` (whether the head's holdout could be read on the model that wrote the scores), `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.+Four events carry the scores and baked results 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 `readable` (whether the head's holdout could be read on the model that wrote the scores), `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 anotherdiff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.pyindex dde058174f34..27930f5b4739 100644--- a/products/signals/dags/inbox_ranking/tests/test_training.py+++ b/products/signals/dags/inbox_ranking/tests/test_training.py@@ -76,6 +76,7 @@ from products.signals.dags.inbox_ranking.training.dag import (examples_object_key,grade_metadata,inbox_ranking_training_examples,+ inbox_ranking_unseen_graded,inbox_ranking_unseen_scores,load_snapshots,load_unseen_models,@@ -124,6 +125,7 @@ from products.signals.dags.inbox_ranking.training.unseen import (SCORE_COLUMNS,TABULAR_MODEL_NAME,TITLE_EMBEDDINGS_MODEL_NAME,+ UNSEEN_SCORES_TABLE,ModelFamily,UnseenModel,calibration_rows,@@ -876,6 +878,107 @@ def test_head_grades_report_counts_and_an_undefined_auc_on_a_single_class():assert "open_tabular_xgb_candidate_auc" not in grade_metadata([single_class])+ "observed_days,missing_merge_column",+ [(0, False), (1, False), (2, False), (3, False), (7, False), (14, False), (15, False), (0, True), (14, True)],+)+def test_unseen_daily_evaluations_keep_baked_events_at_each_heads_horizon(+ monkeypatch, observed_days, missing_merge_column+):+ ids = ["fast", "slow", "pending"]+ head_names = ["open", "pr_created", "pr_merged"]+ families = [TABULAR_MODEL_NAME, EMBEDDINGS_MODEL_NAME]+ scores = pd.concat(+ [+ _scores(ids, head=[head] * 3, model_name=[family] * 3, score=[0.9, 0.1, 0.5])+ for head in head_names+ for family in families+ ],+ ignore_index=True,+ )+ day = D0 + datetime.timedelta(days=observed_days)+ partition = day.isoformat()+ outcomes = [1, int(observed_days >= 2), 0]+ labels = _labels(ids, open_count=outcomes, pr_created_count=outcomes, pr_merged_count=outcomes)+ if missing_merge_column:+ labels = labels.drop(columns=["pr_merged_count"])+ head_names.remove("pr_merged")+ prefix = settings.INBOX_RANKING_DATASET_S3_PREFIX+ storage = _ParquetS3(+ {+ partition_object_key(prefix, STATE_TABLE, partition): _parquet(_state(ids)),+ partition_object_key(prefix, LABELS_TABLE, partition): _parquet(labels),+ partition_object_key(prefix, UNSEEN_SCORES_TABLE, D0.isoformat()): _parquet(scores),+ }+ )+ monkeypatch.setattr(settings, "INBOX_RANKING_DATASET_S3_BUCKET", "test-bucket")+ monkeypatch.setattr("products.signals.dags.inbox_ranking.training.dag.s3_client", lambda: storage)+ client = _patch_capture(monkeypatch, cloud=True, debug=False)++ with dagster.build_asset_context(partition_key=partition) as context:+ inbox_ranking_unseen_graded(context)++ daily = [call["properties"] for call in client.calls if call["event"] == "inbox_ranking_unseen_head_evaluated"]+ expected_heads = {name for name in head_names if observed_days <= HEADS_BY_NAME[name].horizon_days}+ assert {(row["head"], row["model_name"]) for row in daily} == {+ (head, family) for head in expected_heads for family in families+ }+ for row in daily:+ assert {+ "scoring_partition": D0.isoformat(),+ "evaluation_partition": partition,+ "observed_days": observed_days,+ "is_mature": observed_days == HEADS_BY_NAME[row["head"]].horizon_days,+ "model_version": D0.isoformat(),+ "rows": 3,+ "scored_rows": 3,+ "positives": sum(outcomes),+ "cohort_coverage": 1.0,+ "mean_score": 0.5,+ "auc": 1.0 if observed_days < 2 else 0.5,+ }.items() <= row.items()+ assert datetime.datetime.fromisoformat(row["evaluated_at"]).tzinfo is not None++ baked_heads = {name for name in head_names if observed_days == HEADS_BY_NAME[name].horizon_days}+ baked = [call["properties"] for call in client.calls if call["event"] == "inbox_ranking_unseen_head_graded"]+ assert {(row["head"], row["model_name"]) for row in baked} == {+ (head, family) for head in baked_heads for family in families+ }+ for row in baked:+ daily_row = next(+ item for item in daily if (item["head"], item["model_name"]) == (row["head"], row["model_name"])+ )+ assert row.items() <= daily_row.items()++ report_events = [+ call["properties"] for call in client.calls if call["event"] == "inbox_ranking_unseen_report_graded"+ ]+ assert len(report_events) == (len(ids) * len(families) if baked_heads else 0)+ for row in report_events:+ assert row["horizon_days"] == observed_days+ assert {key.removeprefix("outcome_") for key in row if key.startswith("outcome_")} == baked_heads+ calibration = [call["properties"] for call in client.calls if call["event"] == "inbox_ranking_unseen_calibration"]+ assert {row["head"] for row in calibration} == baked_heads++[email protected]("impressions", [0, 1])+def test_daily_evaluation_keeps_empty_and_single_class_cohorts_explicit(impressions):+ head = HEADS_BY_NAME["open"]+ graded = graded_rows(+ _scores(["pending"], head_readable=[False]),+ _labels(["pending"], impression_unit_count=[impressions]),+ head,+ pool=POOL_NAME,+ )+ (grade,) = head_grades(graded, head, pool=POOL_NAME, scoring_partition=D0.isoformat(), include_empty=True)+ assert (grade.scored_rows, grade.rows, grade.positives) == (1, impressions, 0)+ assert (grade.auc, grade.recency_auc, grade.null_auc) == (None, None, None)+ assert grade.readable is False+ if not impressions:+ assert (grade.mean_score, grade.base_rate, grade.expected_calibration_error) == (None, None, None)+ assert head_grades(graded, head, pool=POOL_NAME, scoring_partition=D0.isoformat()) == []++def test_calibration_buckets_keep_a_run_of_tied_scores_in_one_bucket():# Splitting a run of equal scores would give each half a realized rate that depends on the# order the rows arrived in, and report a gap that is not there.diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pyindex c785d159da9d..4887d3dadab2 100644--- a/products/signals/dags/inbox_ranking/training/dag.py+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -34,10 +34,11 @@ rendering each, from separate snapshots, so a missing snapshot costs one familyTwo further assets grade the day's models on data no example covers. `inbox_ranking_unseen_scores`scores every report born on D (`unseen_pool` explains why no example can cover one);-`inbox_ranking_unseen_graded` reads each head's scores from `D - horizon_days` and grades them-against the dt=D labels. The holdout AUC grades the recipe, because the shipped booster is refit on-train plus holdout; the unseen AUC grades the model on reports it never saw, and the two are-comparable because both apply the same `Head` cohort, label and horizon.+`inbox_ranking_unseen_graded` evaluates saved scores daily against the dt=D labels until each+head's horizon, keeping provisional evaluations separate from mature grades. The holdout AUC+grades the recipe, because the shipped booster is refit on train plus holdout; the baked unseen+AUC grades the model on reports it never saw. The two are comparable because both apply the+same `Head` cohort, label and horizon."""import json@@ -119,6 +120,7 @@ from products.signals.dags.inbox_ranking.training.telemetry import (promotion_event,serving_manifest_event,unseen_calibration_events,+ unseen_head_evaluated_events,unseen_head_graded_events,unseen_report_graded_events,unseen_score_events,@@ -939,7 +941,7 @@ def publish_serving_models(return _ModelPublication(copied=copied, present=present, bytes_copied=bytes_copied)-# dt=D grades the scores written on D - horizon_days, so the mapping reaches back as far as the+# dt=D evaluates scores from birth through maturity, so the mapping reaches back as far as the# longest head horizon. Partitions before the scores asset existed have no upstream to map to._HORIZON_MAPPING = dagster.TimeWindowPartitionMapping(start_offset=-max(HEADS_BY_HORIZON),@@ -1168,16 +1170,18 @@ def inbox_ranking_unseen_graded(context: dagster.AssetExecutionContext) -> None:labels = load_snapshots(client, bucket, prefix, [day], required=day)[day].labelsgrades: list[HeadGrade] = []+ evaluations: list[HeadGrade] = []skipped: dict[str, str] = {}report_rows: list[dict[str, object]] = []- # Walk the horizons, not the heads: heads that share a horizon read the same scores object.- for horizon_days, heads in HEADS_BY_HORIZON.items():- scoring_partition = (day - datetime.timedelta(days=horizon_days)).isoformat()+ # Read each saved scores object once, even when several heads are still maturing.+ for observed_days in range(max(HEADS_BY_HORIZON) + 1):+ heads = [head for head in HEADS if observed_days <= head.horizon_days]+ scoring_partition = (day - datetime.timedelta(days=observed_days)).isoformat()table = read_parquet_if_exists(client, bucket, partition_object_key(prefix, UNSEEN_SCORES_TABLE, scoring_partition))if table is None:- skipped.update({head.name: f"no unseen scores for dt={scoring_partition}" for head in heads})+ skipped[scoring_partition] = "no unseen scores"continuescores = with_model_names(table.to_pandas())pool = scored_pool(scores)@@ -1185,17 +1189,22 @@ def inbox_ranking_unseen_graded(context: dagster.AssetExecutionContext) -> None:for head in heads:missing = missing_label_columns(labels, head)if missing:- skipped[head.name] = f"dt={partition_key} labels lack {', '.join(missing)}"+ skipped[f"{scoring_partition}/{head.name}"] = f"dt={partition_key} labels lack {', '.join(missing)}"continuehead_scores = scores[scores["head"] == head.name]if head_scores.empty:- skipped[head.name] = f"dt={scoring_partition} scored no {head.name} row"+ skipped[f"{scoring_partition}/{head.name}"] = "head was not scored"continuegraded = graded_rows(head_scores, labels, head, pool=pool)- graded_by_head[head.name] = graded- grades.extend(head_grades(graded, head, pool=pool, scoring_partition=scoring_partition))+ evaluated = head_grades(graded, head, pool=pool, scoring_partition=scoring_partition, include_empty=True)+ evaluations.extend(evaluated)+ if observed_days == head.horizon_days:+ graded_by_head[head.name] = graded+ grades.extend(grade for grade in evaluated if grade.rows)report_rows.extend(- report_grade_rows(graded_by_head, pool=pool, horizon_days=horizon_days, scoring_partition=scoring_partition)+ report_grade_rows(+ graded_by_head, pool=pool, horizon_days=observed_days, scoring_partition=scoring_partition+ ))for grade in grades:@@ -1203,14 +1212,26 @@ def inbox_ranking_unseen_graded(context: dagster.AssetExecutionContext) -> None:for head_name, reason in skipped.items():context.log.info(f"{head_name}: not graded, {reason}")- context.add_output_metadata({**grade_metadata(grades), "skipped_heads": dagster.MetadataValue.json(skipped)})+ context.add_output_metadata(+ {+ **grade_metadata(grades),+ "daily_evaluations": dagster.MetadataValue.int(len(evaluations)),+ "skipped_heads": dagster.MetadataValue.json(skipped),+ }+ )capture_training_events(context,partition_key,[- *unseen_head_graded_events(run_id=context.run.run_id, grades=grades),- *unseen_calibration_events(run_id=context.run.run_id, rows=calibration_rows(grades)),- *unseen_report_graded_events(run_id=context.run.run_id, rows=report_rows),+ *unseen_head_evaluated_events(+ run_id=context.run_id,+ grades=evaluations,+ evaluation_partition=partition_key,+ evaluated_at=datetime.datetime.now(datetime.UTC),+ ),+ *unseen_head_graded_events(run_id=context.run_id, grades=grades),+ *unseen_calibration_events(run_id=context.run_id, rows=calibration_rows(grades)),+ *unseen_report_graded_events(run_id=context.run_id, rows=report_rows),],)diff --git a/products/signals/dags/inbox_ranking/training/telemetry.py b/products/signals/dags/inbox_ranking/training/telemetry.pyindex 30b9de34c5ef..6b2533ec3507 100644--- a/products/signals/dags/inbox_ranking/training/telemetry.py+++ b/products/signals/dags/inbox_ranking/training/telemetry.py@@ -34,6 +34,7 @@ EXAMPLES_BUILT_EVENT = "inbox_ranking_examples_built"PROMOTION_DECIDED_EVENT = "inbox_ranking_promotion_decided"UNSEEN_REPORT_SCORED_EVENT = "inbox_ranking_unseen_report_scored"UNSEEN_HEAD_GRADED_EVENT = "inbox_ranking_unseen_head_graded"+UNSEEN_HEAD_EVALUATED_EVENT = "inbox_ranking_unseen_head_evaluated"UNSEEN_REPORT_GRADED_EVENT = "inbox_ranking_unseen_report_graded"UNSEEN_CALIBRATION_EVENT = "inbox_ranking_unseen_calibration"HOLDOUT_CALIBRATION_EVENT = "inbox_ranking_holdout_calibration"@@ -208,6 +209,35 @@ def unseen_head_graded_events(*, run_id: str, grades: Sequence[HeadGrade]) -> li]+def unseen_head_evaluated_events(+ *, run_id: str, grades: Sequence[HeadGrade], evaluation_partition: str, evaluated_at: datetime.datetime+) -> list[TrainingEvent]:+ # A separate stream keeps provisional negatives out of mature-only charts and alerts.+ events: list[TrainingEvent] = []+ for grade in grades:+ observed_days = (+ datetime.date.fromisoformat(evaluation_partition) - datetime.date.fromisoformat(grade.scoring_partition)+ ).days+ if not 0 <= observed_days <= grade.horizon_days:+ raise ValueError("Unseen evaluations must stay within the head's outcome horizon")+ events.append(+ TrainingEvent(+ event=UNSEEN_HEAD_EVALUATED_EVENT,+ properties={+ **grade.as_dict(),+ "run_id": run_id,+ "evaluation_partition": evaluation_partition,+ "evaluated_at": evaluated_at.isoformat(),+ "observed_days": observed_days,+ "is_mature": observed_days == grade.horizon_days,+ "scored_rows": grade.scored_rows,+ "cohort_coverage": grade.rows / grade.scored_rows if grade.scored_rows else None,+ },+ )+ )+ return events++def unseen_calibration_events(*, run_id: str, rows: Sequence[Mapping[str, Any]]) -> list[TrainingEvent]:"""One event per (model, head, score decile) of the unseen grade: how much the decile predictedagainst how often the outcome happened. One event per bucket because a decile table on the headdiff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.pyindex 1c2abe11f564..bf50b6c2bd52 100644--- a/products/signals/dags/inbox_ranking/training/unseen.py+++ b/products/signals/dags/inbox_ranking/training/unseen.py@@ -142,7 +142,7 @@ MODEL_FAMILIES: tuple[ModelFamily, ...] = (class HeadGrade:head: strhorizon_days: int- # The partition the scores were written on, which is `horizon_days` before the grading day.+ # The original scores stay fixed while daily evaluations observe more outcomes.scoring_partition: str# The pool definition the scored rows came from, carried so the AUC series can be read per pool# rather than split by hand on the day a definition changed.@@ -154,6 +154,7 @@ class HeadGrade:# scored and graded while unreadable, so the pooled grade over many days can give it a number# its one-day holdout never will; read the two populations apart.readable: bool+ scored_rows: introws: intpositives: int# Of the positives, how many had already happened when the report was scored: on this pool the@@ -479,7 +480,9 @@ def graded_rows(head_scores: pd.DataFrame, labels: pd.DataFrame, head: Head, *,return graded-def head_grades(graded: pd.DataFrame, head: Head, *, pool: str, scoring_partition: str) -> list[HeadGrade]:+def head_grades(+ graded: pd.DataFrame, head: Head, *, pool: str, scoring_partition: str, include_empty: bool = False+) -> list[HeadGrade]:"""The unseen read per model that scored this head, over the in-cohort rows.Every family scores the whole pool, so a set whose side input covers few of the day's newborns@@ -488,10 +491,12 @@ def head_grades(graded: pd.DataFrame, head: Head, *, pool: str, scoring_partitio`model_name`, with `<set>_pool_coverage` on the scores asset for how thin the day was."""grades: list[HeadGrade] = []- kept = graded[graded["in_cohort"]]- for (model_name, model_version, model_role), rows in kept.groupby(+ for (model_name, model_version, model_role), scored in graded.groupby(["model_name", "model_version", "model_role"], sort=True):+ rows = scored[scored["in_cohort"]]+ if rows.empty and not include_empty:+ continueoutcomes = 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)@@ -506,7 +511,8 @@ def head_grades(graded: pd.DataFrame, head: Head, *, pool: str, scoring_partitiomodel_name=str(model_name),model_version=str(model_version),model_role=str(model_role),- readable=bool(rows["head_readable"].all()),+ readable=bool((scored if rows.empty else rows)["head_readable"].all()),+ scored_rows=len(scored),rows=len(rows),positives=int(outcomes.sum()),birth_day_positives=int((outcomes & at_scoring).sum()),