Skip to content

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

feat(signals): grade the inbox ranking model on unseen reports (#95239)

posthog[bot]19147c91c1c9
diff --git a/posthog/dags/locations/signals.py b/posthog/dags/locations/signals.py
index 1bb4406ee289..0112e3d4f9cf 100644
--- a/posthog/dags/locations/signals.py
+++ b/posthog/dags/locations/signals.py
@@ -19,6 +19,8 @@ if is_inbox_ranking_registered():
inbox_ranking_training.inbox_ranking_training_examples,
inbox_ranking_training.inbox_ranking_model_candidate,
inbox_ranking_training.inbox_ranking_model_champion,
+ inbox_ranking_training.inbox_ranking_unseen_scores,
+ inbox_ranking_training.inbox_ranking_unseen_graded,
],
jobs=[inbox_ranking_dataset.inbox_ranking_dataset_job, inbox_ranking_training.inbox_ranking_training_job],
schedules=[
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.md
index 52e84ae3f8b5..de38ad410c91 100644
--- a/products/signals/dags/inbox_ranking/README.md
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -64,10 +64,11 @@ The first four are report grain and land in one table. `inbox_signal_embeddings`
```text
s3://<bucket>/<prefix>/
├── inbox_ranking_training_examples/v1/dt=YYYY-MM-DD/ # scoring-moment examples, all heads, one parquet
-└── inbox_ranking_models/v1/
- ├── 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_models/v1/
+│ ├── 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
```
- **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.
@@ -77,6 +78,18 @@ s3://<bucket>/<prefix>/
- **Metrics telemetry**: each asset also captures its metrics as events into the dogfood project (the same project the label events land in), through `training/telemetry.py`: `inbox_ranking_examples_built` and `inbox_ranking_candidate_trained` once per head (`head`, holdout / train AUC, average precision, logloss, positive rate, the permutation-null mean and spread, counts, `readable`) and `inbox_ranking_promotion_decided` once per run, all carrying `model_version` and stamped midday UTC on the partition day so re-runs and backfills chart on the day they describe. Per-head stability is a trends insight with a `head` breakdown; a readability drop is an insight alert. `metadata.json` stays the durable record. Capture is best-effort. Local dev runs (`DEBUG`) emit too, under `distinct_id` `inbox_ranking_training_local` with `environment=local`, so filter or break down on `environment` when reading the prod series; any other non-Cloud deployment emits nothing.
- **Champion**: `promotion.decide_promotion` — promote when the candidate has a readable head, is within 0.02 AUC of the champion on every head the champion could read, and the champion is at least `INBOX_RANKING_PROMOTION_MIN_DAYS` old. The champion's AUCs come from its `<head>.holdout.ubj` scored on the candidate's holdout (`paired_champion_aucs`), so both models are compared on one set of reports; a champion without that file falls back to its stored AUC. The pointer is rewritten only when `INBOX_RANKING_AUTO_PROMOTE` is on; otherwise the decision is logged and surfaced as asset metadata, so the daily candidate series is monitoring while the first shadow read runs on a frozen champion. To promote by hand, copy a candidate's `metadata.json` to `champion.json` with a `promoted_at`.
+### The unseen read
+
+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_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.
+
+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.
+
### Running the training job locally
The training job is S3-only, so it can run on a laptop against copies of the prod snapshots. The dataset job cannot: it needs the dogfood project's ClickHouse and cross-region Postgres.
diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.py
index e33bcdb303b6..5c7f9ab56ad4 100644
--- a/products/signals/dags/inbox_ranking/tests/test_training.py
+++ b/products/signals/dags/inbox_ranking/tests/test_training.py
@@ -45,8 +45,20 @@ from products.signals.dags.inbox_ranking.training.telemetry import (
capture_training_events,
examples_events,
promotion_event,
+ unseen_head_graded_events,
+ unseen_report_graded_events,
+ unseen_score_events,
)
from products.signals.dags.inbox_ranking.training.train import _head_readable, booster_holdout_auc, train_head
+from products.signals.dags.inbox_ranking.training.unseen import (
+ CANDIDATE_ROLE,
+ graded_rows,
+ head_grades,
+ report_grade_rows,
+ sample_unseen,
+ score_event_rows,
+ unseen_pool,
+)
D0 = datetime.date(2026, 8, 10)
NOW = datetime.datetime(2026, 8, 20, tzinfo=datetime.UTC)
@@ -445,6 +457,75 @@ def _patch_capture(monkeypatch, *, cloud: bool, debug: bool) -> _FakeClient:
return client
+def _scores(report_ids: list[str], **overrides) -> pd.DataFrame:
+ n = len(report_ids)
+ base = {
+ "report_id": report_ids,
+ "team_id": [2] * n,
+ "report_created_at": [pd.Timestamp("2026-08-09T12:00:00Z")] * n,
+ "snapshot_date": [D0] * n,
+ "model_version": ["2026-08-10"] * n,
+ "model_role": [CANDIDATE_ROLE] * n,
+ "feature_schema_version": [1] * n,
+ "head": ["open"] * n,
+ "score": [0.5] * n,
+ "age_hours": [12.0] * n,
+ "label_at_scoring": [False] * n,
+ }
+ base.update(overrides)
+ 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_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_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.
+ 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)
+ # 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()
+
+
+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")
+ 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"
+ )
+ assert (single_class.rows, single_class.positives, single_class.auc) == (1, 0, None)
+
+
@pytest.mark.parametrize(
"cloud,debug,expected_distinct_id,expected_environment",
[
@@ -484,6 +565,9 @@ 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"])
+ grades = head_grades(graded, HEADS_BY_NAME["open"], scoring_partition="2026-08-22")
events = [
*candidate_events(metadata),
*examples_events(
@@ -502,6 +586,12 @@ 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_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"),
+ ),
]
client = _patch_capture(monkeypatch, cloud=True, debug=False)
capture_training_events(dagster.build_asset_context(), "2026-08-25", events)
@@ -530,6 +620,37 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
"incumbent_champion_version": "none",
"champion_open_auc_on_this_holdout": 0.6,
}.items() <= promotion_props.items()
+ # The unseen series is charted next to the holdout series, so it breaks down on the same head
+ # property and carries the model it graded; the p_/outcome_ naming is what a calibration read joins on.
+ scored_props = by_event["inbox_ranking_unseen_report_scored"][0]["properties"]
+ assert {
+ "report_id": "a",
+ "model_role": CANDIDATE_ROLE,
+ "p_open": 0.8,
+ "unseen_pool": 40,
+ "sample_size": 1,
+ "signal_count": 3,
+ }.items() <= scored_props.items()
+ head_graded_props = by_event["inbox_ranking_unseen_head_graded"][0]["properties"]
+ assert {
+ "head": "open",
+ "model_role": CANDIDATE_ROLE,
+ "scoring_partition": "2026-08-22",
+ "horizon_days": 3,
+ "rows": 1,
+ "positives": 1,
+ "auc": None,
+ }.items() <= head_graded_props.items()
+ report_graded_props = by_event["inbox_ranking_unseen_report_graded"][0]["properties"]
+ assert {
+ "report_id": "a",
+ "model_role": CANDIDATE_ROLE,
+ "scoring_partition": "2026-08-22",
+ "horizon_days": 3,
+ "in_cohort_open": True,
+ "outcome_open": True,
+ "p_open": 0.8,
+ }.items() <= report_graded_props.items()
@pytest.mark.parametrize(
diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.py
index 45737354006b..0050777f618a 100644
--- a/products/signals/dags/inbox_ranking/training/dag.py
+++ b/products/signals/dags/inbox_ranking/training/dag.py
@@ -5,6 +5,7 @@ Three assets on the same daily partition as the dataset dag, each writing under
inbox_ranking_training_examples/v1/dt=D/ scoring-moment examples over the trailing snapshots
inbox_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
Partition dt=D trains on the report-state/labels snapshots dt=D-lookback..D (issue 13's
scoring-moment join, `training/examples.py`), grades each head on the last `holdout_days` of
@@ -16,6 +17,13 @@ that prefix in full (stale head files are removed), and `champion.json` carries
was promoted from so a loader can tell a re-run apart from the version it pinned. The champion is
graded on the candidate's holdout through its `<head>.holdout.ubj` (the train-only fit), so the
promotion 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.
"""
import json
@@ -55,7 +63,7 @@ from products.signals.dags.inbox_ranking.training.examples import (
build_examples,
point_in_time_mask,
)
-from products.signals.dags.inbox_ranking.training.heads import HEADS, HEADS_BY_NAME
+from products.signals.dags.inbox_ranking.training.heads import HEADS, HEADS_BY_HORIZON, HEADS_BY_NAME
from products.signals.dags.inbox_ranking.training.promotion import decide_promotion
from products.signals.dags.inbox_ranking.training.telemetry import (
HeadExampleCounts,
@@ -63,10 +71,31 @@ from products.signals.dags.inbox_ranking.training.telemetry import (
capture_training_events,
examples_events,
promotion_event,
+ unseen_head_graded_events,
+ unseen_report_graded_events,
+ unseen_score_events,
)
from products.signals.dags.inbox_ranking.training.train import XGB_PARAMS, TrainedHead, booster_holdout_auc, train_head
+from products.signals.dags.inbox_ranking.training.unseen import (
+ CANDIDATE_ROLE,
+ CHAMPION_ROLE,
+ HeadGrade,
+ UnseenModel,
+ graded_rows,
+ head_grades,
+ missing_label_columns,
+ model_mismatch,
+ readable_head_files,
+ report_grade_rows,
+ sample_unseen,
+ score_event_rows,
+ score_sample,
+ scores_table,
+ unseen_pool,
+)
EXAMPLES_TABLE = "inbox_ranking_training_examples"
+UNSEEN_SCORES_TABLE = "inbox_ranking_unseen_scores"
MODELS_TABLE = "inbox_ranking_models"
CHAMPION_FILE = "champion.json"
METADATA_FILE = "metadata.json"
@@ -427,9 +456,177 @@ def inbox_ranking_model_champion(context: dagster.AssetExecutionContext) -> None
)
+# dt=D grades the scores written on D - horizon_days, 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),
+ end_offset=0,
+ allow_nonexistent_upstream_partitions=True,
+)
+
+
+def load_unseen_models(
+ context: dagster.AssetExecutionContext, client, bucket: str, prefix: str, partition_key: str
+) -> list[UnseenModel]:
+ """The models worth an unseen read on dt=D: the day's candidate, plus the champion when the
+ pointer names a different version. A model whose feature contract has moved on is logged and
+ left out rather than failing the asset, because its boosters cannot take the current matrix."""
+ candidate = _read_json_if_exists(client, bucket, model_object_key(prefix, partition_key, METADATA_FILE))
+ champion = _read_json_if_exists(client, bucket, champion_object_key(prefix))
+ records = [(CANDIDATE_ROLE, candidate)]
+ if champion is not None and champion.get("model_version") != (candidate or {}).get("model_version"):
+ records.append((CHAMPION_ROLE, champion))
+
+ 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")
+ continue
+ mismatch = model_mismatch(metadata)
+ if mismatch is not None:
+ context.log.warning(f"{role} {metadata.get('model_version')} not scored: {mismatch}")
+ continue
+ boosters = {}
+ for head_name, filename in readable_head_files(metadata).items():
+ body = _read_bytes_if_exists(client, bucket, model_object_key(prefix, metadata["model_version"], filename))
+ if body is not None:
+ boosters[head_name] = body
+ if not boosters:
+ context.log.warning(f"{role} {metadata['model_version']} has no readable head to score")
+ continue
+ models.append(
+ UnseenModel(
+ model_version=metadata["model_version"],
+ model_role=role,
+ feature_schema_version=metadata["feature_schema_version"],
+ boosters=boosters,
+ )
+ )
+ return models
+
+
+ name=UNSEEN_SCORES_TABLE,
+ deps=["inbox_ranking_model_champion", STATE_TABLE, LABELS_TABLE],
+ **COMMON_ASSET_KWARGS,
+)
+def inbox_ranking_unseen_scores(context: dagster.AssetExecutionContext) -> None:
+ if skip_unconfigured(context):
+ return
+ partition_key = context.partition_key
+ bucket, prefix, client = dataset_bucket(), settings.INBOX_RANKING_DATASET_S3_PREFIX, s3_client()
+ 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)
+ models = load_unseen_models(context, client, bucket, prefix, partition_key)
+ scores = score_sample(sample, 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")
+
+ 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}"),
+ }
+ )
+ 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))
+ ),
+ )
+
+
+ name="inbox_ranking_unseen_graded",
+ deps=[
+ dagster.AssetDep(UNSEEN_SCORES_TABLE, partition_mapping=_HORIZON_MAPPING),
+ LABELS_TABLE,
+ ],
+ **COMMON_ASSET_KWARGS,
+)
+def inbox_ranking_unseen_graded(context: dagster.AssetExecutionContext) -> None:
+ if skip_unconfigured(context):
+ return
+ partition_key = context.partition_key
+ bucket, prefix, client = dataset_bucket(), settings.INBOX_RANKING_DATASET_S3_PREFIX, s3_client()
+ day = datetime.date.fromisoformat(partition_key)
+
+ labels = load_snapshots(client, bucket, prefix, [day], required=day)[day].labels
+ grades: 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()
+ 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})
+ continue
+ scores = table.to_pandas()
+ graded_by_head: dict[str, pd.DataFrame] = {}
+ for head in heads:
+ missing = missing_label_columns(labels, head)
+ if missing:
+ skipped[head.name] = f"dt={partition_key} labels lack {', '.join(missing)}"
+ continue
+ head_scores = scores[scores["head"] == head.name]
+ 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_by_head[head.name] = graded
+ grades.extend(head_grades(graded, head, scoring_partition=scoring_partition))
+ report_rows.extend(
+ report_grade_rows(graded_by_head, horizon_days=horizon_days, scoring_partition=scoring_partition)
+ )
+
+ for grade in grades:
+ context.log.info(f"unseen grade: {grade.as_dict()}")
+ for head_name, reason in skipped.items():
+ context.log.info(f"{head_name}: not graded, {reason}")
+
+ context.add_output_metadata(
+ {
+ **{
+ f"{grade.head}_{grade.model_role}_{name}": dagster.MetadataValue.float(value)
+ for grade in grades
+ for name, value in grade.metrics().items()
+ if value is not None
+ },
+ "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_report_graded_events(run_id=context.run.run_id, rows=report_rows),
+ ],
+ )
+
+
inbox_ranking_training_job = dagster.define_asset_job(
name="inbox_ranking_training_job",
- selection=[EXAMPLES_TABLE, "inbox_ranking_model_candidate", "inbox_ranking_model_champion"],
+ selection=[
+ EXAMPLES_TABLE,
+ "inbox_ranking_model_candidate",
+ "inbox_ranking_model_champion",
+ UNSEEN_SCORES_TABLE,
+ "inbox_ranking_unseen_graded",
+ ],
partitions_def=partition_def,
tags={
**owner_tags,
diff --git a/products/signals/dags/inbox_ranking/training/heads.py b/products/signals/dags/inbox_ranking/training/heads.py
index cf9c5d82d582..9aa7f2c0daf9 100644
--- a/products/signals/dags/inbox_ranking/training/heads.py
+++ b/products/signals/dags/inbox_ranking/training/heads.py
@@ -134,3 +134,9 @@ HEADS: tuple[Head, ...] = (
)
HEADS_BY_NAME: dict[str, Head] = {head.name: head for head in HEADS}
+# Heads that share a horizon are labeled from the same later snapshot, so a reader that walks the
+# horizons touches each snapshot once instead of once per head.
+HEADS_BY_HORIZON: dict[int, tuple[Head, ...]] = {
+ horizon: tuple(head for head in HEADS if head.horizon_days == horizon)
+ for horizon in sorted({head.horizon_days for head in HEADS})
+}
diff --git a/products/signals/dags/inbox_ranking/training/telemetry.py b/products/signals/dags/inbox_ranking/training/telemetry.py
index 9be66c7cdf49..ea8ddda9a3a2 100644
--- a/products/signals/dags/inbox_ranking/training/telemetry.py
+++ b/products/signals/dags/inbox_ranking/training/telemetry.py
@@ -8,7 +8,7 @@ readability is an insight alert. Delivery is best-effort and never fails an asse
"""
import datetime
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from typing import Any
import dagster
@@ -20,6 +20,7 @@ from posthog.ph_client import get_client
from products.signals.dags.inbox_ranking.common import snapshot_bounds
from products.signals.dags.inbox_ranking.training.promotion import PromotionDecision
+from products.signals.dags.inbox_ranking.training.unseen import HeadGrade
# Not a person: one fixed id for the whole dag, and no person profile is created for it. Local dev
# runs get their own id so they never blend into the prod series.
@@ -29,6 +30,9 @@ LOCAL_ENVIRONMENT = "local"
CANDIDATE_TRAINED_EVENT = "inbox_ranking_candidate_trained"
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_REPORT_GRADED_EVENT = "inbox_ranking_unseen_report_graded"
# Candidate metadata copied onto every per-head event so a chart can filter or break down on it.
_CANDIDATE_CONTEXT_KEYS = (
@@ -134,6 +138,28 @@ 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
+ numeric 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]
+
+
+def unseen_head_graded_events(*, run_id: str, grades: Sequence[HeadGrade]) -> list[TrainingEvent]:
+ """One event per (model, head): the unseen AUC that sits next to the head's holdout AUC. A head
+ with rows but a single outcome class still reports, with a null AUC, so the series has no gap."""
+ return [
+ TrainingEvent(event=UNSEEN_HEAD_GRADED_EVENT, properties={**grade.as_dict(), "run_id": run_id})
+ for grade in grades
+ ]
+
+
+def unseen_report_graded_events(*, run_id: str, rows: Sequence[Mapping[str, Any]]) -> list[TrainingEvent]:
+ """One event per (report, model, horizon): the scores and what actually happened, for
+ calibration reads. Stamped on the day the outcome was read; `scoring_partition` carries the day
+ the report was scored, so a chart can be built on either axis."""
+ return [TrainingEvent(event=UNSEEN_REPORT_GRADED_EVENT, properties={**row, "run_id": run_id}) for row in rows]
+
+
def event_timestamp(partition_key: str) -> datetime.datetime:
"""Midday UTC of the partition day. The run happens the next morning, so wall-clock time would
chart a candidate one day late, and midnight UTC falls on the previous day in the dogfood
diff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.py
new file mode 100644
index 000000000000..127432f1e3e1
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/training/unseen.py
@@ -0,0 +1,355 @@
+"""Unseen-performance read for the ranking model.
+
+The trainer grades a candidate on a holdout cut from the same example set and then refits the
+shipped booster on train plus holdout, so `holdout_auc` grades the recipe rather than the model
+that 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.
+
+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.
+"""
+
+import datetime
+from collections.abc import Collection, Mapping, Sequence
+from typing import Any
+
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+import xgboost as xgb
+from sklearn.metrics import roc_auc_score
+
+from posthog.dataclasses import frozen
+
+from products.signals.backend.ranking.features import FEATURE_NAMES, FEATURE_SCHEMA_VERSION, feature_frame
+from products.signals.dags.inbox_ranking.training.examples import STATE_COLUMNS, point_in_time_mask
+from 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
+
+CANDIDATE_ROLE = "candidate"
+CHAMPION_ROLE = "champion"
+
+# The scores Parquet is long (one row per report, model and head) so a head can be added without a
+# schema change. Declared explicitly, so a day with no unseen report writes an empty object a
+# reader can still open with the schema every other day has.
+_SCORE_TYPES: dict[str, pa.DataType] = {
+ "report_id": pa.string(),
+ "team_id": pa.int64(),
+ "report_created_at": pa.timestamp("us", tz="UTC"),
+ "snapshot_date": pa.date32(),
+ "model_version": pa.string(),
+ "model_role": pa.string(),
+ "feature_schema_version": pa.int64(),
+ "head": pa.string(),
+ "score": pa.float64(),
+ "age_hours": pa.float64(),
+ "label_at_scoring": pa.bool_(),
+}
+SCORES_SCHEMA = pa.schema(_SCORE_TYPES)
+SCORE_COLUMNS = tuple(_SCORE_TYPES)
+
+# Report-state columns copied onto a scored event next to the scores, so a calibration read can
+# group on the raw inputs without joining the Parquet.
+FEATURE_INPUT_COLUMNS = (
+ "signal_count",
+ "total_weight",
+ "run_count",
+ "title_chars",
+ "summary_chars",
+ "priority",
+ "actionability",
+)
+
+
+@frozen
+class UnseenModel:
+ """One model to score the sample with, and the readable heads it can score."""
+
+ model_version: str
+ model_role: str
+ feature_schema_version: int
+ boosters: Mapping[str, bytes]
+
+
+@frozen
+class HeadGrade:
+ head: str
+ horizon_days: int
+ # The partition the scores were written on, which is `horizon_days` before the grading day.
+ scoring_partition: str
+ model_version: str
+ model_role: str
+ rows: int
+ positives: int
+ base_rate: float | None
+ auc: float | None
+ # AUC of "newest first" on the same outcomes. A model that does not beat it has learned
+ # nothing the inbox could not do by sorting on age.
+ recency_auc: float | None
+
+ def metrics(self) -> dict[str, float | None]:
+ return {
+ "rows": self.rows,
+ "positives": self.positives,
+ "base_rate": self.base_rate,
+ "auc": self.auc,
+ "recency_auc": self.recency_auc,
+ }
+
+ def as_dict(self) -> dict[str, object]:
+ return {
+ "head": self.head,
+ "horizon_days": self.horizon_days,
+ "scoring_partition": self.scoring_partition,
+ "model_version": self.model_version,
+ "model_role": self.model_role,
+ **self.metrics(),
+ }
+
+
+def _auc(outcomes: np.ndarray, scores: np.ndarray) -> float | None:
+ """AUC, or None when it is undefined: a single outcome class, or a ranking column that carries
+ a non-finite value (a missing `age_hours` makes the recency baseline unrankable)."""
+ if len(outcomes) == 0 or outcomes.sum() == 0 or outcomes.sum() == len(outcomes):
+ return None
+ if not np.isfinite(scores).all():
+ return None
+ return float(roc_auc_score(outcomes, scores))
+
+
+def model_mismatch(metadata: Mapping[str, Any]) -> str | None:
+ """Why the model cannot be scored against the current feature contract, or None when it can."""
+ version = metadata.get("feature_schema_version")
+ if version != FEATURE_SCHEMA_VERSION:
+ return f"feature_schema_version {version} is not the serving contract's {FEATURE_SCHEMA_VERSION}"
+ if tuple(metadata.get("feature_names") or ()) != FEATURE_NAMES:
+ return "feature_names differ from the serving contract"
+ return None
+
+
+def readable_head_files(metadata: Mapping[str, Any]) -> dict[str, str]:
+ """The `<head>.ubj` object name per readable head. Only a readable head is worth an unseen
+ read; an unreadable one has no holdout AUC to compare the unseen AUC against."""
+ return {
+ entry["head"]: entry["file"]
+ for entry in metadata.get("heads", [])
+ if entry.get("readable") and entry.get("file") and entry.get("head") in HEADS_BY_NAME
+ }
+
+
+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.
+
+ 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.
+ """
+ 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]
+
+
+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 score_sample(
+ sample: pd.DataFrame, labels: pd.DataFrame, models: Sequence[UnseenModel], *, snapshot_date: datetime.date
+) -> pd.DataFrame:
+ """One row per (report, model, head) in SCORE_COLUMNS order.
+
+ Features are built exactly as `build_examples` builds them, so a report scored here sees the
+ same vector it would have seen as a training example. `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.
+ """
+ rows = sample[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)
+ )
+ 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(),
+ "snapshot_date": snapshot_date,
+ "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(),
+ "label_at_scoring": HEADS_BY_NAME[head_name].label(aligned_labels).to_numpy(),
+ }
+ )
+ for model in models
+ for head_name, booster_ubj in model.boosters.items()
+ ]
+ if not frames:
+ return pd.DataFrame(columns=list(SCORE_COLUMNS))
+ return pd.concat(frames, ignore_index=True)[list(SCORE_COLUMNS)]
+
+
+def _predict(booster_ubj: bytes, matrix: xgb.DMatrix) -> np.ndarray:
+ booster = xgb.Booster()
+ booster.load_model(bytearray(booster_ubj))
+ return booster.predict(matrix)
+
+
+def scores_table(scores: pd.DataFrame) -> pa.Table:
+ if scores.empty:
+ return SCORES_SCHEMA.empty_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]]:
+ """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 a
+ trends insight can aggregate a head's scores without a join.
+ """
+ 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,
+ {
+ "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),
+ "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"])
+ return list(rows.values())
+
+
+def missing_label_columns(labels: pd.DataFrame, head: Head) -> list[str]:
+ """The head's label columns the grading snapshot lacks. A missing cumulative count reads as
+ zero, which would grade every scored report a negative, so the head is skipped instead."""
+ 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:
+ """`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.
+ """
+ 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()
+ )
+ 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()
+ graded["in_cohort"] = in_cohort
+ graded["outcome"] = pd.array(head.label(aligned).to_numpy(dtype=bool), dtype="boolean")
+ graded.loc[~in_cohort, "outcome"] = pd.NA
+ return graded
+
+
+def head_grades(graded: pd.DataFrame, head: Head, *, 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"]]
+ for (model_version, model_role), rows in kept.groupby(["model_version", "model_role"], sort=True):
+ outcomes = rows["outcome"].to_numpy(dtype=bool)
+ grades.append(
+ HeadGrade(
+ head=head.name,
+ horizon_days=head.horizon_days,
+ scoring_partition=scoring_partition,
+ model_version=str(model_version),
+ model_role=str(model_role),
+ rows=len(rows),
+ positives=int(outcomes.sum()),
+ base_rate=float(outcomes.mean()) if len(rows) else None,
+ auc=_auc(outcomes, rows["score"].to_numpy(dtype=float)),
+ recency_auc=_auc(outcomes, -rows["age_hours"].to_numpy(dtype=float)),
+ )
+ )
+ return grades
+
+
+def report_grade_rows(
+ graded_by_head: Mapping[str, pd.DataFrame], *, horizon_days: int, scoring_partition: str
+) -> list[dict[str, object]]:
+ """One dict per (report, model) carrying every head graded at this horizon.
+
+ Heads are grouped by horizon because they were all scored on the same day, so one event holds a
+ report's whole outcome at that horizon.
+ """
+ rows: dict[tuple[str, str], dict[str, object]] = {}
+ for head_name, graded in sorted(graded_by_head.items()):
+ for record in graded.to_dict("records"):
+ key = (str(record["report_id"]), str(record["model_role"]))
+ entry = rows.setdefault(
+ key,
+ {
+ "report_id": record["report_id"],
+ "team_id": _int_or_none(record["team_id"]),
+ "scoring_partition": scoring_partition,
+ "model_version": record["model_version"],
+ "model_role": record["model_role"],
+ "horizon_days": horizon_days,
+ },
+ )
+ entry[f"in_cohort_{head_name}"] = bool(record["in_cohort"])
+ entry[f"p_{head_name}"] = float(record["score"])
+ if record["in_cohort"]:
+ entry[f"outcome_{head_name}"] = bool(record["outcome"])
+ return list(rows.values())
+
+
+def _plain(value: Any) -> Any:
+ """A numpy or pandas scalar as the plain Python value the capture client can serialize."""
+ if value is None or pd.isna(value):
+ return None
+ return value.item() if isinstance(value, np.generic) else value
+
+
+def _int_or_none(value: Any) -> int | None:
+ plain = _plain(value)
+ return None if plain is None else int(plain)
+
+
+def _isoformat_or_none(value: Any) -> str | None:
+ plain = _plain(value)
+ return None if plain is None else pd.Timestamp(plain).isoformat()