: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): score newborn reports in the inbox ranking unseen read (#96408)
posthog[bot]df9262dd9824
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex de38ad410c91..f483698a818e 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -68,7 +68,7 @@ s3://<bucket>/<prefix>/│ ├── dt=YYYY-MM-DD/<head>.ubj + <head>.holdout.ubj # the day's candidate: serving fit + train-only fit│ │ + metadata.json # (a re-run replaces this prefix in full)│ └── champion.json # pointer the scoring sweep loads (the only object written across partitions)-└── inbox_ranking_unseen_scores/v1/dt=YYYY-MM-DD/ # the day's models on reports no example covers+└── inbox_ranking_unseen_scores/v1/dt=YYYY-MM-DD/ # the day's models on the reports born that day```- **Examples are scoring moments, not reports.** For partition `dt=D` the examples asset reads the report-state and labels snapshots `dt=D-lookback..D` and emits one row per (report, snapshot) whose head label is still 0 on that snapshot, labeled from the snapshot `horizon_days` later (3 for open, 7 for action / dismiss_wrong / pr_created / discuss, 14 for pr_merged / refund). Features are that snapshot's state columns plus `age_hours`, the report's age at the snapshot. Labels are aligned to the state spine, so a report with no label event is a negative (all-zero labels), not absent. Label-only rows (no Postgres state) are skipped, as are state rows read long after their snapshot day (backfills carry current Postgres state; see `features_observed_at`) and, for the `dismiss_wrong` head, rows whose status telemetry fails the dataset's `label_provenance_ok` check. This is the serving situation replayed over history; it measured better than one row per report on the engagement heads.@@ -83,12 +83,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 that appear in **no** dt=D example, for any head, in train or in holdout. That is a set difference against the examples Parquet, not a date rule, so it stays correct if the example builder changes; in practice it is the reports too recent to pair with a horizon snapshot. It samples `UNSEEN_SAMPLE_SIZE` of them, seeded from the partition day so a re-run reproduces the sample, and scores each sampled report with the day's candidate and, when the pointer names a different version, the champion. Only readable heads are scored, and a model whose feature contract has moved on is logged and left out. One Parquet row per (report, model, head) carries the score, `age_hours`, and `label_at_scoring`, the head outcome that had already happened when the report was scored.+- **`inbox_ranking_unseen_scores` (dt=D)** takes the dt=D state rows of the reports **created on D**, the pool the events tag `pool=newborn`. A newborn has no scoring moment before D, and the dt=D examples stop at D minus the head's horizon (3 days at the shortest), so no example can cover it: leakage-freedom is structural, not a property of what the example builder did that day. The set difference against the examples Parquet stays as a runtime guard — a non-empty overlap fails the asset instead of publishing the number. Every newborn is scored, not a sample, with the day's candidate and, when the pointer names a different version, the champion. Only readable heads are scored, and a model whose feature contract has moved on is logged and left out. One Parquet row per (report, model, head) carries the score, `age_hours`, `label_at_scoring` (the head outcome that had already happened when the report was scored), and `pool`, the pool definition that produced the row.- **`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 `recency_auc`, the AUC of ranking newest first on the same outcomes.-Because the pool, 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.+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>` and the raw feature inputs, `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.+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.### Running the training job locallydiff --git a/products/signals/dags/inbox_ranking/common.py b/products/signals/dags/inbox_ranking/common.pyindex 0762a2372f0e..203f16508f03 100644--- a/products/signals/dags/inbox_ranking/common.py+++ b/products/signals/dags/inbox_ranking/common.py@@ -179,9 +179,9 @@ def merge_emission_rows(existing: pa.Table, fresh: pa.Table, key_columns: tuple[return pa.concat_tables([existing, fresh.filter(mask)])-def read_parquet(client, bucket: str, key: str) -> pa.Table:+def read_parquet(client, bucket: str, key: str, columns: list[str] | None = None) -> pa.Table:body = client.get_object(Bucket=bucket, Key=key)["Body"].read()- return pq.read_table(pa.BufferReader(body))+ return pq.read_table(pa.BufferReader(body), columns=columns)def read_parquet_if_exists(client, bucket: str, key: str) -> pa.Table | None:diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.pyindex 832d4bd92847..f2bb8f4ae14e 100644--- a/products/signals/dags/inbox_ranking/tests/test_training.py+++ b/products/signals/dags/inbox_ranking/tests/test_training.py@@ -53,11 +53,14 @@ from products.signals.dags.inbox_ranking.training.telemetry import (from products.signals.dags.inbox_ranking.training.train import _head_readable, booster_holdout_auc, train_headfrom products.signals.dags.inbox_ranking.training.unseen import (CANDIDATE_ROLE,+ LEGACY_POOL_NAME,+ POOL_NAME,graded_rows,head_grades,+ leaked_report_ids,report_grade_rows,- sample_unseen,score_event_rows,+ scored_pool,unseen_pool,)@@ -440,6 +443,7 @@ def test_train_head_returns_none_without_both_classes():class _FakeClient:def __init__(self) -> None:self.calls: list[dict[str, Any]] = []+ self.client_kwargs: dict[str, Any] = {}self.shutdowns = 0def capture(self, **kwargs: Any) -> None:@@ -451,7 +455,12 @@ class _FakeClient:def _patch_capture(monkeypatch, *, cloud: bool, debug: bool) -> _FakeClient:client = _FakeClient()- monkeypatch.setattr("products.signals.dags.inbox_ranking.training.telemetry.get_client", lambda region: client)++ def build(region: str, **kwargs: Any) -> _FakeClient:+ client.client_kwargs = kwargs+ return client++ monkeypatch.setattr("products.signals.dags.inbox_ranking.training.telemetry.get_client", build)monkeypatch.setattr("products.signals.dags.inbox_ranking.training.telemetry.is_cloud", lambda: cloud)monkeypatch.setattr(settings, "DEBUG", debug)monkeypatch.setattr(settings, "CLOUD_DEPLOYMENT", "US" if cloud else None)@@ -465,6 +474,7 @@ def _scores(report_ids: list[str], **overrides) -> pd.DataFrame:"team_id": [2] * n,"report_created_at": [pd.Timestamp("2026-08-09T12:00:00Z")] * n,"snapshot_date": [D0] * n,+ "pool": [POOL_NAME] * n,"model_version": ["2026-08-10"] * n,"model_role": [CANDIDATE_ROLE] * n,"feature_schema_version": [1] * n,@@ -477,26 +487,45 @@ def _scores(report_ids: list[str], **overrides) -> pd.DataFrame:return pd.DataFrame(base)-def test_unseen_pool_excludes_every_report_the_examples_cover():- # The pool is the whole point of the unseen read: a report that appears in any example, for any- # head, in train or in holdout, is a report the shipped booster was refit on.- ids = ["a", "b", "c", "d", "e"]- state = _state(ids, signal_count=[3, 3, 3, None, 3])- examples = pd.DataFrame({"head": ["open", "action"], "report_id": ["a", "b"]})- pool = unseen_pool(state, D0, examples["report_id"])- # d carries no signal_count, so build_examples would have skipped it too.- assert pool.index.tolist() == ["c", "e"]+def test_unseen_pool_is_the_reports_born_on_the_partition_day():+ # A report born before D can already be a training example on D, so the pool must exclude it.+ born_on_d0 = pd.Timestamp("2026-08-10T09:00:00Z")+ pool = unseen_pool(+ _state(+ ["a", "b", "c", "d"],+ report_created_at=[born_on_d0, pd.Timestamp("2026-08-09T23:59:59Z"), born_on_d0, born_on_d0],+ signal_count=[3, 3, None, 3],+ features_observed_at=[pd.Timestamp("2026-08-11T04:00:00Z")] * 3 + [pd.Timestamp("2026-08-20T04:00:00Z")],+ ),+ D0,+ )+ # b was born the day before; c has no signal_count and d is a backfill, which build_examples drops too.+ assert pool.index.tolist() == ["a"]+++def test_build_examples_never_covers_a_report_born_on_the_partition_day():+ # What the newborn pool rests on: a builder change that reached the partition day would leak.+ head = HEADS_BY_NAME["open"]+ scoring_day = D0 - datetime.timedelta(days=head.horizon_days)+ old, newborn = pd.Timestamp("2026-07-01T00:00:00Z"), pd.Timestamp("2026-08-10T09:00:00Z")+ snapshots = {+ scoring_day: assemble_snapshot(+ scoring_day, _state(["old"], report_created_at=[old]), _labels(["old"], open_count=[0])+ ),+ D0: assemble_snapshot(+ D0,+ _state(["old", "newborn"], report_created_at=[old, newborn]),+ _labels(["old", "newborn"], open_count=[1, 1]),+ ),+ }+ assert set(build_examples(snapshots, head)["report_id"]) == {"old"}-def test_unseen_sample_is_reproducible_for_a_partition():- # A re-run of the partition rewrites the scores object, so the sample must not move: a second- # sample would score reports whose outcomes are never graded, and drop ones already promised.- pool = _state([f"r{index}" for index in range(50)])- first = sample_unseen(pool, "2026-08-10", size=10)- second = sample_unseen(pool, "2026-08-10", size=10)- assert first.index.tolist() == second.index.tolist()- assert len(first) == 10- assert sample_unseen(pool, "2026-08-11", size=10).index.tolist() != first.index.tolist()+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"])+ assert leaked_report_ids(pool, ["c"]) == []+ assert leaked_report_ids(pool, ["b", "c"]) == ["b"]def test_grading_keeps_the_scoring_moment_rows_and_reads_the_outcome_later():@@ -517,12 +546,15 @@ def test_head_grades_report_counts_and_a_null_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)- (grade,) = head_grades(two_classes, head, scoring_partition="2026-08-10")+ (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)assert grade.recency_auc == 0.5 # both reports are the same age, so newest-first cannot rank them# 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), head, scoring_partition="2026-08-10"+ graded_rows(_scores(["e"]), _labels(["e"], open_count=[0]), head),+ head,+ pool=POOL_NAME,+ scoring_partition="2026-08-10",)assert (single_class.rows, single_class.positives, single_class.auc) == (1, 0, None)# Counts are ints and the null AUC is dropped: the graded asset writes these as Dagster metadata.@@ -532,6 +564,19 @@ def test_head_grades_report_counts_and_a_null_auc_on_a_single_class():assert "open_candidate_auc" not in grade_metadata([single_class])+ "scores,expected",+ [+ (_scores(["a"]), POOL_NAME),+ # The grader reads scores up to 14 days old, so it still meets objects written before the+ # column existed. Reading one as the current pool would mix two populations in one AUC.+ (_scores(["a"]).drop(columns=["pool"]), LEGACY_POOL_NAME),+ ],+)+def test_scored_pool_names_the_definition_a_scores_object_was_written_under(scores, expected):+ assert scored_pool(scores) == expected++@pytest.mark.parametrize("cloud,debug,expected_distinct_id,expected_environment",[@@ -555,6 +600,19 @@ def test_training_events_capture_gate_and_local_marking(assert call["properties"]["environment"] == expected_environment+def test_capture_sizes_the_client_queue_to_the_batch(monkeypatch):+ # The SDK drops an event that meets a full queue and reports it only on its own logger. A+ # grading run enqueues one event per report, model and horizon, so a queue left at the+ # 10,000-slot default would lose the tail of the per-report events with nothing in the log.+ client = _patch_capture(monkeypatch, cloud=True, debug=False)+ events = [+ TrainingEvent(event="inbox_ranking_unseen_report_graded", properties={"report_id": str(index)})+ for index in range(10_001)+ ]+ capture_training_events(dagster.build_asset_context(), "2026-08-25", events)+ assert client.client_kwargs["max_queue_size"] >= len(events)++def test_training_events_carry_the_dashboard_contract(monkeypatch):# The per-head events are what the project-2 insights break down on; dropping the head# property, the partition-day timestamp, or the person-profile opt-out breaks every chart.@@ -573,7 +631,7 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):}scores = _scores(["a"], model_version=["2026-08-25"], score=[0.8])graded = graded_rows(scores, _labels(["a"], open_count=[1]), HEADS_BY_NAME["open"])- grades = head_grades(graded, HEADS_BY_NAME["open"], scoring_partition="2026-08-22")+ grades = head_grades(graded, HEADS_BY_NAME["open"], pool=POOL_NAME, scoring_partition="2026-08-22")events = [*candidate_events(metadata),*examples_events(@@ -592,11 +650,11 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):incumbent_champion_version="none",champion_aucs={"open": 0.6},),- *unseen_score_events(run_id="run-1", rows=score_event_rows(scores, _state(["a"]), unseen_pool_size=40)),+ *unseen_score_events(run_id="run-1", rows=score_event_rows(scores, _state(["a"]))),*unseen_head_graded_events(run_id="run-1", grades=grades),*unseen_report_graded_events(run_id="run-1",- rows=report_grade_rows({"open": graded}, horizon_days=3, scoring_partition="2026-08-22"),+ rows=report_grade_rows({"open": graded}, pool=POOL_NAME, horizon_days=3, scoring_partition="2026-08-22"),),]client = _patch_capture(monkeypatch, cloud=True, debug=False)@@ -633,8 +691,8 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):"report_id": "a","model_role": CANDIDATE_ROLE,"p_open": 0.8,- "unseen_pool": 40,- "sample_size": 1,+ "pool": POOL_NAME,+ "unseen_pool": 1,"signal_count": 3,}.items() <= scored_props.items()head_graded_props = by_event["inbox_ranking_unseen_head_graded"][0]["properties"]@@ -642,6 +700,7 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):"head": "open","model_role": CANDIDATE_ROLE,"scoring_partition": "2026-08-22",+ "pool": POOL_NAME,"horizon_days": 3,"rows": 1,"positives": 1,@@ -652,6 +711,7 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):"report_id": "a","model_role": CANDIDATE_ROLE,"scoring_partition": "2026-08-22",+ "pool": POOL_NAME,"horizon_days": 3,"in_cohort_open": True,"outcome_open": True,diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pyindex 05b0876f0764..4f973299a3e5 100644--- a/products/signals/dags/inbox_ranking/training/dag.py+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -5,7 +5,7 @@ Three assets on the same daily partition as the dataset dag, each writing underinbox_ranking_training_examples/v1/dt=D/ scoring-moment examples over the trailing snapshotsinbox_ranking_models/v1/dt=D/<head>.ubj one booster per head + metadata.json (the candidate)inbox_ranking_models/v1/champion.json pointer to the model version the scoring sweep loads- inbox_ranking_unseen_scores/v1/dt=D/ the day's models on reports no example covers+ inbox_ranking_unseen_scores/v1/dt=D/ the day's models on the reports born that dayPartition dt=D trains on the report-state/labels snapshots dt=D-lookback..D (issue 13'sscoring-moment join, `training/examples.py`), grades each head on the last `holdout_days` of@@ -19,11 +19,11 @@ graded on the candidate's holdout through its `<head>.holdout.ubj` (the train-onpromotion rule compares both models on one set of reports.Two further assets grade the day's models on data no example covers. `inbox_ranking_unseen_scores`-samples reports absent from the dt=D examples and scores them; `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.+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."""import json@@ -84,13 +84,14 @@ from products.signals.dags.inbox_ranking.training.unseen import (UnseenModel,graded_rows,head_grades,+ leaked_report_ids,missing_label_columns,model_mismatch,readable_head_files,report_grade_rows,- sample_unseen,score_event_rows,- score_sample,+ score_pool,+ scored_pool,scores_table,unseen_pool,)@@ -481,7 +482,7 @@ def load_unseen_models(models: list[UnseenModel] = []for role, metadata in records:if metadata is None:- context.log.warning(f"no {role} metadata to score the unseen sample with")+ context.log.warning(f"no {role} metadata to score the unseen pool with")continuemismatch = model_mismatch(metadata)if mismatch is not None:@@ -519,20 +520,27 @@ def inbox_ranking_unseen_scores(context: dagster.AssetExecutionContext) -> None:day = datetime.date.fromisoformat(partition_key)snapshot = load_snapshots(client, bucket, prefix, [day], required=day)[day]- examples = read_parquet(client, bucket, partition_object_key(prefix, EXAMPLES_TABLE, partition_key))- pool = unseen_pool(snapshot.state, day, examples.column("report_id").to_pylist())- sample = sample_unseen(pool, partition_key)+ # Only the ids: the examples table is one row per (report, snapshot, head) over the lookback.+ example_ids = read_parquet(+ client, bucket, partition_object_key(prefix, EXAMPLES_TABLE, partition_key), columns=["report_id"]+ )+ pool = unseen_pool(snapshot.state, day)+ leaked = leaked_report_ids(pool, example_ids.column("report_id").unique().to_pylist())+ if leaked:+ raise dagster.Failure(+ f"{len(leaked)} reports created on {partition_key} already appear in that day's training examples, "+ f"so the unseen read would grade a model on its own data: {leaked[:10]}"+ )models = load_unseen_models(context, client, bucket, prefix, partition_key)- scores = score_sample(sample, snapshot.labels, models, snapshot_date=day)+ scores = score_pool(pool, snapshot.labels, models, snapshot_date=day)if scores.empty:- context.log.warning(f"nothing scored for dt={partition_key}: {len(pool)} unseen reports, {len(models)} models")+ context.log.warning(f"nothing scored for dt={partition_key}: {len(pool)} newborn reports, {len(models)} models")key = partition_object_key(prefix, UNSEEN_SCORES_TABLE, partition_key)write_parquet(client, bucket, key, scores_table(scores), snapshot_date=partition_key)context.add_output_metadata({"unseen_pool": dagster.MetadataValue.int(len(pool)),- "sample_size": dagster.MetadataValue.int(len(sample)),"models_scored": dagster.MetadataValue.int(len(models)),**{f"{model.model_role}_heads_scored": dagster.MetadataValue.int(len(model.boosters)) for model in models},"s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),@@ -541,9 +549,7 @@ def inbox_ranking_unseen_scores(context: dagster.AssetExecutionContext) -> None:capture_training_events(context,partition_key,- unseen_score_events(- run_id=context.run.run_id, rows=score_event_rows(scores, sample, unseen_pool_size=len(pool))- ),+ unseen_score_events(run_id=context.run.run_id, rows=score_event_rows(scores, pool)),)@@ -590,6 +596,7 @@ def inbox_ranking_unseen_graded(context: dagster.AssetExecutionContext) -> None:skipped.update({head.name: f"no unseen scores for dt={scoring_partition}" for head in heads})continuescores = table.to_pandas()+ pool = scored_pool(scores)graded_by_head: dict[str, pd.DataFrame] = {}for head in heads:missing = missing_label_columns(labels, head)@@ -602,9 +609,9 @@ def inbox_ranking_unseen_graded(context: dagster.AssetExecutionContext) -> None:continuegraded = graded_rows(head_scores, labels, head)graded_by_head[head.name] = graded- grades.extend(head_grades(graded, head, scoring_partition=scoring_partition))+ grades.extend(head_grades(graded, head, pool=pool, scoring_partition=scoring_partition))report_rows.extend(- report_grade_rows(graded_by_head, horizon_days=horizon_days, scoring_partition=scoring_partition)+ report_grade_rows(graded_by_head, pool=pool, horizon_days=horizon_days, scoring_partition=scoring_partition))for grade in grades:diff --git a/products/signals/dags/inbox_ranking/training/telemetry.py b/products/signals/dags/inbox_ranking/training/telemetry.pyindex ea8ddda9a3a2..2d4c27df3d81 100644--- a/products/signals/dags/inbox_ranking/training/telemetry.py+++ b/products/signals/dags/inbox_ranking/training/telemetry.py@@ -139,7 +139,7 @@ def promotion_event(def unseen_score_events(*, run_id: str, rows: Sequence[Mapping[str, Any]]) -> list[TrainingEvent]:- """One event per (report, model) for the day's unseen sample. Every property is flat and+ """One event per (report, model) for the day's unseen pool. Every property is flat andnumeric where it is a number, so a trends insight can aggregate a head's scores directly."""return [TrainingEvent(event=UNSEEN_REPORT_SCORED_EVENT, properties={**row, "run_id": run_id}) for row in rows]@@ -189,8 +189,10 @@ def capture_training_events(base = {"$process_person_profile": False, "partition": partition_key, "environment": environment}# A fresh client per call, flushed on shutdown, for the same reason `ph_scoped_capture` builds# one: the step process exits right after the asset, before a shared client's background- # thread would deliver.- client = get_client("US")+ # thread would deliver. Its queue holds the whole batch, because the SDK drops an event that+ # meets a full queue and reports it only on its own logger: the grading asset enqueues one row+ # per report, model and horizon, which is more than the default 10,000 slots.+ client = get_client("US", max_queue_size=max(len(events), 1))if client is None:returntry:diff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.pyindex cfd1abc4925a..dcbb9659bc2c 100644--- a/products/signals/dags/inbox_ranking/training/unseen.py+++ b/products/signals/dags/inbox_ranking/training/unseen.py@@ -3,12 +3,12 @@The trainer grades a candidate on a holdout cut from the same example set and then refits theshipped booster on train plus holdout, so `holdout_auc` grades the recipe rather than the modelthat ships. This module is the offline batch proxy for the number that is missing: each day it-samples reports that appear in no training example, scores them with the day's models, and grades-those scores at each head's horizon against a snapshot the model could not have seen.+scores the reports born that day with the day's models, and grades those scores at each head's+horizon against a snapshot the model could not have seen.-The pool, the cohort, the label and the horizon come from the same `Head` definitions the trainer-uses, so the unseen AUC is directly comparable to the holdout AUC of the same head and model-version. Pure functions over frames; `training/dag.py` owns the S3 and telemetry plumbing.+The cohort, the label and the horizon come from the same `Head` definitions the trainer uses, so+the unseen AUC is directly comparable to the holdout AUC of the same head and model version. Pure+functions over frames; `training/dag.py` owns the S3 and telemetry plumbing."""import datetime@@ -24,13 +24,16 @@ from sklearn.metrics import roc_auc_scorefrom posthog.dataclasses import frozenfrom products.signals.backend.ranking.features import FEATURE_NAMES, FEATURE_SCHEMA_VERSION, feature_frame+from products.signals.dags.inbox_ranking.common import snapshot_boundsfrom products.signals.dags.inbox_ranking.training.examples import STATE_COLUMNS, point_in_time_maskfrom products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, Head-# How many unseen reports one day's read scores. Large enough that a head with a low base rate-# still collects positives over a few days, small enough that the event volume stays under the-# label streams this project already carries.-UNSEEN_SAMPLE_SIZE = 1000+# Stamped on every scored event, so a chart can tell this pool definition from a later one.+POOL_NAME = "newborn"+# The pool of a scores object written before the column existed: a seeded sample of the state rows+# the day's examples did not cover. The grader reads objects up to 14 days old, so a change of pool+# definition puts two populations in one AUC series unless the older one keeps its own name.+LEGACY_POOL_NAME = "sampled"CANDIDATE_ROLE = "candidate"CHAMPION_ROLE = "champion"@@ -43,6 +46,7 @@ _SCORE_TYPES: dict[str, pa.DataType] = {"team_id": pa.int64(),"report_created_at": pa.timestamp("us", tz="UTC"),"snapshot_date": pa.date32(),+ "pool": pa.string(),"model_version": pa.string(),"model_role": pa.string(),"feature_schema_version": pa.int64(),@@ -69,7 +73,7 @@ FEATURE_INPUT_COLUMNS = (@frozenclass UnseenModel:- """One model to score the sample with, and the readable heads it can score."""+ """One model to score the pool with, and the readable heads it can score."""model_version: strmodel_role: str@@ -83,6 +87,9 @@ class HeadGrade:horizon_days: int# The partition the scores were written on, which is `horizon_days` before the grading day.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.+ pool: strmodel_version: strmodel_role: strrows: int@@ -107,6 +114,7 @@ class HeadGrade:"head": self.head,"horizon_days": self.horizon_days,"scoring_partition": self.scoring_partition,+ "pool": self.pool,"model_version": self.model_version,"model_role": self.model_role,**self.metrics(),@@ -143,33 +151,51 @@ def readable_head_files(metadata: Mapping[str, Any]) -> dict[str, str]:}-def unseen_pool(- state: pd.DataFrame, snapshot_date: datetime.date, example_report_ids: Collection[object]-) -> pd.DataFrame:- """The dt=D state rows no training example covers.+def unseen_pool(state: pd.DataFrame, snapshot_date: datetime.date) -> pd.DataFrame:+ """The dt=D state rows of the reports created on D.- A set difference against the example ids rather than a date rule, so the pool stays correct if- the example builder changes. The two extra filters mirror `build_examples`: a backfilled state- row carries current Postgres state rather than the state as of the day, and a row without- `signal_count` has no features to score.+ A newborn has no scoring moment before D, and the dt=D examples reach no later than D minus the+ head's horizon, so no training example can cover it. Leakage-freedom is therefore structural+ rather than a set difference over whatever the example builder did that day, and the read stays+ on the fresh reports the inbox actually ranks. The two extra filters mirror `build_examples`: a+ backfilled state row carries current Postgres state rather than the state as of the day, and a+ row without `signal_count` has no features to score."""- keep = ~state.index.isin(set(example_report_ids))- keep &= state["signal_count"].notna().to_numpy()- keep &= point_in_time_mask(state, snapshot_date).to_numpy()- return state.loc[keep]+ 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()]+ keep = newborn["signal_count"].notna().to_numpy()+ keep &= point_in_time_mask(newborn, snapshot_date).to_numpy()+ return newborn.loc[keep]++def leaked_report_ids(pool: pd.DataFrame, example_report_ids: Collection[object]) -> list[str]:+ """Pool reports a training example already covers.++ Empty while every head horizon stays above zero. A non-empty result means the example builder+ now reaches the partition day, so the read would grade a model on its own training data; the+ caller fails the asset instead of publishing that number.+ """+ covered = set(example_report_ids)+ return sorted(str(report_id) for report_id in pool.index if report_id in covered)-def sample_unseen(pool: pd.DataFrame, partition_key: str, *, size: int = UNSEEN_SAMPLE_SIZE) -> pd.DataFrame:- """A uniform sample of the pool without replacement, seeded from the partition day so a re-run- of the partition reproduces it. A pool at or below `size` is scored in full."""- if len(pool) <= size:- return pool- rng = np.random.default_rng(int(partition_key.replace("-", "")))- return pool.iloc[np.sort(rng.choice(len(pool), size=size, replace=False))]++def scored_pool(scores: pd.DataFrame) -> str:+ """The pool definition a scores object was written under.++ One partition is written by one run, so the column holds a single value. An object written+ before the column existed is a sample of the old pool, and must not be graded as the current+ one.+ """+ if "pool" not in scores:+ return LEGACY_POOL_NAME+ values = scores["pool"].dropna().unique()+ return str(values[0]) if len(values) else LEGACY_POOL_NAME-def score_sample(- sample: pd.DataFrame, labels: pd.DataFrame, models: Sequence[UnseenModel], *, snapshot_date: datetime.date+def score_pool(+ pool: pd.DataFrame, labels: pd.DataFrame, models: Sequence[UnseenModel], *, snapshot_date: datetime.date) -> pd.DataFrame:"""One row per (report, model, head) in SCORE_COLUMNS order.@@ -178,26 +204,29 @@ def score_sample(head's outcome had already happened on the scoring day; the grader drops those rows, the sameway the example builder drops a scoring moment whose label is already 1."""- rows = sample[list(STATE_COLUMNS)].copy()+ rows = pool[list(STATE_COLUMNS)].copy()rows["age_hours"] = rows.pop("report_age_hours").astype(float)matrix = xgb.DMatrix(feature_frame(rows), feature_names=list(FEATURE_NAMES))- aligned_labels = labels.reindex(sample.index)- team_id = (- sample["report_team_id"] if "report_team_id" in sample else pd.Series(None, index=sample.index, dtype=object)- )+ aligned_labels = labels.reindex(pool.index)+ team_id = pool["report_team_id"] if "report_team_id" in pool else pd.Series(None, index=pool.index, dtype=object)+ report_ids = pool.index.to_numpy()+ team_ids = pd.to_numeric(team_id, errors="coerce").astype("Int64").to_numpy()+ created_at = pd.to_datetime(rows["report_created_at"], utc=True).to_numpy()+ age_hours = rows["age_hours"].to_numpy()frames = [pd.DataFrame({- "report_id": sample.index.to_numpy(),- "team_id": pd.to_numeric(team_id, errors="coerce").astype("Int64").to_numpy(),- "report_created_at": pd.to_datetime(rows["report_created_at"], utc=True).to_numpy(),+ "report_id": report_ids,+ "team_id": team_ids,+ "report_created_at": created_at,"snapshot_date": snapshot_date,+ "pool": POOL_NAME,"model_version": model.model_version,"model_role": model.model_role,"feature_schema_version": model.feature_schema_version,"head": head_name,"score": _predict(booster_ubj, matrix),- "age_hours": rows["age_hours"].to_numpy(),+ "age_hours": age_hours,"label_at_scoring": HEADS_BY_NAME[head_name].label(aligned_labels).to_numpy(),})@@ -221,35 +250,34 @@ def scores_table(scores: pd.DataFrame) -> pa.Table:return pa.Table.from_pandas(scores[list(SCORE_COLUMNS)], schema=SCORES_SCHEMA, preserve_index=False)-def score_event_rows(scores: pd.DataFrame, sample: pd.DataFrame, *, unseen_pool_size: int) -> list[dict[str, object]]:+def score_event_rows(scores: pd.DataFrame, pool: pd.DataFrame) -> list[dict[str, object]]:"""One dict per (report, model): every head's score as `p_<head>`, plus the raw feature inputs.The Parquet is long so that a head can be added without a schema change; an event is wide so atrends insight can aggregate a head's scores without a join."""+ columns = [column for column in FEATURE_INPUT_COLUMNS if column in pool]+ inputs = {+ report_id: {column: _plain(value) for column, value in row.items()}+ for report_id, row in pool[columns].to_dict("index").items()+ }rows: dict[tuple[str, str], dict[str, object]] = {}for record in scores.to_dict("records"):key = (str(record["report_id"]), str(record["model_role"]))- entry = rows.setdefault(- key,- {+ if key not in rows:+ rows[key] = {"report_id": record["report_id"],"team_id": _int_or_none(record["team_id"]),"report_created_at": _isoformat_or_none(record["report_created_at"]),"model_version": record["model_version"],"model_role": record["model_role"],"feature_schema_version": record["feature_schema_version"],- "unseen_pool": unseen_pool_size,- "sample_size": len(sample),+ "pool": POOL_NAME,+ "unseen_pool": len(pool),"age_hours": float(record["age_hours"]),- **{- column: _plain(sample[column].get(record["report_id"]))- for column in FEATURE_INPUT_COLUMNS- if column in sample- },- },- )- entry[f"p_{record['head']}"] = float(record["score"])+ **inputs.get(record["report_id"], {}),+ }+ rows[key][f"p_{record['head']}"] = float(record["score"])return list(rows.values())@@ -285,7 +313,7 @@ def graded_rows(head_scores: pd.DataFrame, labels: pd.DataFrame, head: Head) ->return graded-def head_grades(graded: pd.DataFrame, head: Head, *, scoring_partition: str) -> list[HeadGrade]:+def head_grades(graded: pd.DataFrame, head: Head, *, pool: str, scoring_partition: str) -> list[HeadGrade]:"""The unseen read per model that scored this head, over the in-cohort rows."""grades: list[HeadGrade] = []kept = graded[graded["in_cohort"]]@@ -296,6 +324,7 @@ def head_grades(graded: pd.DataFrame, head: Head, *, scoring_partition: str) ->head=head.name,horizon_days=head.horizon_days,scoring_partition=scoring_partition,+ pool=pool,model_version=str(model_version),model_role=str(model_role),rows=len(rows),@@ -309,7 +338,7 @@ def head_grades(graded: pd.DataFrame, head: Head, *, scoring_partition: str) ->def report_grade_rows(- graded_by_head: Mapping[str, pd.DataFrame], *, horizon_days: int, scoring_partition: str+ graded_by_head: Mapping[str, pd.DataFrame], *, pool: str, horizon_days: int, scoring_partition: str) -> list[dict[str, object]]:"""One dict per (report, model) carrying every head graded at this horizon.@@ -326,6 +355,7 @@ def report_grade_rows("report_id": record["report_id"],"team_id": _int_or_none(record["team_id"]),"scoring_partition": scoring_partition,+ "pool": pool,"model_version": record["model_version"],"model_role": record["model_role"],"horizon_days": horizon_days,