Skip to content

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

feat(signals): train thumbs_up and reviewer_fix heads (#104410)

posthog[bot]a0f9df2578c5
diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.md
index 6f191df783de..ba1819315a00 100644
--- a/products/signals/dags/inbox_ranking/AGENTS.md
+++ b/products/signals/dags/inbox_ranking/AGENTS.md
@@ -21,6 +21,7 @@ Read `README.md` first for what the dataset is and how partitions behave. This f
- Examples are one row per report, on the snapshot of the day it was created, labeled from the snapshot `horizon_days` later. The scoring-moment and report grains stay selectable for re-scoring families, so keep the holdout cut by report: a row-level split leaks near-duplicate snapshots of the same report the moment a set asks for one of them. The moments are chosen before the features are built, so a set under a row budget never builds columns for rows it then drops; keep that order.
- `inbox_ranking_models/v1/<model_name>/dt=D/` is history like the dataset partitions: the only mutation is a re-run of the same partition, which replaces the prefix in full (stale head files are deleted). `<model_name>/champion.json` is the only object written outside its partition, and only the champion asset (or a human, deliberately) writes it; it carries the candidate's `run_id`, so a loader can detect a re-run behind a pinned version.
- A re-run of `inbox_ranking_unseen_scores` that scores nothing is refused when the partition already holds rows, because the newborn state snapshot behind those rows ages out and the dt=D+horizon grade reads them. A partition trained before the per-family models layout has no candidate to load, so it hits this; delete the object by hand to replace it deliberately. One object holds every family, so a re-run that scored some families and not every family the object already holds is refused for the same reason: skipping a family costs its own day, while rewriting the object without it deletes a day it already has.
+- The unseen scorer scores every head the candidate fit, not only the readable ones, and each scored row carries `head_readable`. A rare head (`thumbs_up`, `reviewer_fix`) never clears `min_holdout_positives` on one day's holdout, so gating the scoring on readability means the pooled newborn grade that could give it a number never starts. Keep the promotion gate reading `readable` from the candidate metadata: an unreadable head must not decide a promotion.
- `model_name` is the model family, and every model object, scored row, grade and event carries it. A family is an entry in `MODEL_FAMILIES` (`training/unseen.py`) naming the feature set it is fit on; the candidate and champion assets walk that registry, and the loader, the grader and the events need no change to gain a family. Promotion stays inside a family, so a family never takes another family's `champion.json`. Do not fold the family into `model_version`, which the dashboard filters as a date.
- A family whose `metadata.json`, examples object or side input is missing for a partition is logged and skipped, so one family does not cost every family's series. The champion asset raises only when no family has a candidate at all.
- Skipping is not the same as rebuilding from nothing, and the difference is destructive. An empty examples object produces an empty candidate, and the candidate's prefix cleanup then deletes the boosters that partition already holds, which a `champion.json` can be pointing at. So when a side input is unavailable, leave the partition's objects alone rather than writing empty ones over them.
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.md
index e31de12909db..368ffe8ce44f 100644
--- a/products/signals/dags/inbox_ranking/README.md
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -82,7 +82,7 @@ s3://<bucket>/<prefix>/
- **A model is a `(model_name, model_version, model_role)`.** `model_name` is the family: which features and which learner, `tabular_xgb` for the per-head XGBoost trained here. `model_version` is the partition day it was fit on, and `model_role` is `candidate` or `champion`. Each family owns a prefix under the models path and its own `champion.json`, so two families trained on the same day cannot collide, and promotion stays inside a family. A richer family is a second candidate graded on the same unseen rows, not a competitor for the tabular family's pointer.
- **A feature set is one feature universe.** `products/signals/backend/ranking/features.py` holds a `FeatureSet` per universe: its name, its schema version, its ordered feature names, the report-state columns it reads, `build_matrix`, and how many rows it wants per report and per head. `tabular`, `report_embeddings` and `title_embeddings` are the three today. A candidate records the set it was fit on in its `metadata.json`, so the grader checks a model against its own set rather than one global contract, the examples asset writes one Parquet per set, and the unseen scorer builds one matrix per set and shares it across the families that read it. Adding a set means an entry in `FEATURE_SETS`; a model naming a set this build cannot produce is logged and left unscored.
-- **Examples are one row per report at its birth, by default.** For partition `dt=D` the examples asset reads the report-state and labels snapshots `dt=D-lookback..D` and emits one row per report, on the snapshot of the day it was created, labeled from the snapshot `horizon_days` later (3 for open, 7 for action / pr_created / discuss, 14 for dismiss_wrong / pr_merged / refund). Features are built by the feature set from that snapshot's state columns plus `age_hours`, the report's age at the snapshot. Labels are aligned to the state spine, so a report with no label event is a negative (all-zero labels), not absent. Label-only rows (no Postgres state) are skipped, as are state rows read long after their snapshot day (backfills carry current Postgres state; see `features_observed_at`) and, for the `dismiss_wrong` head, rows whose status telemetry fails the dataset's `label_provenance_ok` check. Birth is the moment serving scores a report, and the label that comes out is a per-report probability, which is what the inbox ordering needs. A report born before the window, or one whose birth-day snapshot is missing from it, is no example; `reports_missing_birth_snapshot` on the asset counts the second case, which is a gap in the partitions.
+- **Examples are one row per report at its birth, by default.** For partition `dt=D` the examples asset reads the report-state and labels snapshots `dt=D-lookback..D` and emits one row per report, on the snapshot of the day it was created, labeled from the snapshot `horizon_days` later (3 for open, 7 for action / pr_created / discuss / thumbs_up, 14 for dismiss_wrong / pr_merged / refund / reviewer_fix). Features are built by the feature set from that snapshot's state columns plus `age_hours`, the report's age at the snapshot. Labels are aligned to the state spine, so a report with no label event is a negative (all-zero labels), not absent. Label-only rows (no Postgres state) are skipped, as are state rows read long after their snapshot day (backfills carry current Postgres state; see `features_observed_at`) and, for the `dismiss_wrong` head, rows whose status telemetry fails the dataset's `label_provenance_ok` check. Birth is the moment serving scores a report, and the label that comes out is a per-report probability, which is what the inbox ordering needs. A report born before the window, or one whose birth-day snapshot is missing from it, is no example; `reports_missing_birth_snapshot` on the asset counts the second case, which is a gap in the partitions.
- **An outcome already visible on the birth day is a future positive.** A report born on day D has no scoring moment before D, so an outcome visible at D belongs to the moment being built rather than to an earlier one; the labels of D therefore read as their defaults for a report born on D. Most outcomes land on the birth day, so this is where the positives are: censoring on them costs the `pr_created` head most of its training signal. `<set>_<head>_birth_day_positives` on the examples asset, and `birth_day_positives` on the `inbox_ranking_examples_built` event, say how many positives the rule keeps. These rows carry a hindsight the other rows do not: the state snapshot reads `signal_count`, `total_weight`, `run_count` and the text sizes live from Postgres a few hours after day D ends, so a birth-day outcome happened before its own feature read. Both the holdout AUC and the newborn unseen grade therefore read optimistically on these rows, until the scoring sweep's timestamped score log replaces the daily snapshot as this table's source.
- **Every head asks whether the outcome happened within N days of the scoring moment.** `pr_merged` includes every report, so the label covers the whole report-to-merge path without requiring a PR at birth or at the horizon.
- **A set may ask for another grain**, and cap the rows one head keeps (`max_examples_per_head`, all positives first, then a seeded sample of the negatives). The scoring-moment grain is one row per (report, snapshot) whose head label is still 0 on that snapshot: the serving situation replayed over history, but its label is a hazard conditional on the report still being live, and one long-lived report contributes dozens of near-duplicate rows. The report grain is the first snapshot of the window where the report is a usable moment, which is later than birth only when a side input landed late. Both stay selectable for re-scoring families; nothing ships on them today. The row budget changes the base rate a set's scores are calibrated to, not the ranking the unseen AUC reads. The lookback is the tabular set's whatever the grain, so positives accrue over the whole window.
@@ -108,6 +108,12 @@ s3://<bucket>/<prefix>/
| `pr_merged` | Every report | 14 |
| `discuss` | Impressed reports | 7 |
| `refund` | Every report | 14 |
+| `thumbs_up` | Opened reports | 7 |
+| `reviewer_fix` | Impressed reports | 14 |
+
+`thumbs_up` (a positive rating on the report body) and `reviewer_fix` (a suggested reviewer added or removed) are the explicit human-feedback pair.
+Both are rare — about 1% of opened reports and 1.5% of impressed reports — so neither clears its holdout bar on a single day.
+They are carried for the pooled newborn grade and as scorer inputs, not for a holdout AUC, and the promotion gate keeps ignoring an unreadable head.
Every training series resets on the first partition after deploy.
Before and after holdout numbers are not comparable because the example population changes.
@@ -118,12 +124,12 @@ See [training example semantics](../../../../docs/internal/inbox-ranking-trainin
The holdout grades the recipe, not the model that ships: the shipped booster is refit on train plus holdout, and every holdout row comes from the same snapshots the trainer saw.
Two assets add the missing number, an offline batch proxy for performance on reports the model never saw.
-- **`inbox_ranking_unseen_scores` (dt=D)** takes the dt=D state rows of the reports **created on D**, the pool the events tag `pool=newborn`. A newborn has no scoring moment before D, and the dt=D examples stop at D minus the head's horizon (3 days at the shortest), so no example can cover it: leakage-freedom is structural, not a property of what the example builder did that day. The set difference against the examples Parquet stays as a runtime guard — a non-empty overlap fails the asset instead of publishing the number. Every newborn is scored, not a sample, with the day's candidate and, when the pointer names a different version, the champion. Only readable heads are scored, and a model whose feature contract has moved on is logged and left out. Every family scores the whole pool, including reports whose side input has no row for them, because grades are only comparable on paired rows; the `<set>_pool_coverage` metadata says how much of the pool each set could build a real vector for. One Parquet row per (report, model, head) carries the score, `age_hours`, `label_at_scoring` (the head outcome that had already happened when the report was scored, which for a newborn is one that landed on its own birth day, so the grade keeps it; an older pool's rows are still dropped on it, and so are a status-label head's rows in every pool, because no scores column carries the scoring-day `label_provenance_ok` that the example builder checks), `model_name`, and `pool`, the pool definition that produced the row. A re-run that scores nothing is refused when the partition already holds rows, so a day with no loadable model cannot erase the scores a later grade reads; 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_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.
Because the cohort, the label, the horizon and the provenance rules are the trainer's own, the unseen AUC is directly comparable to the holdout AUC of the same head and model version. The gap between the two series is the overfitting read the promotion gate cannot see.
-Four events carry it to the dashboard, next to the training events: `inbox_ranking_unseen_report_scored` per (report, model) with `p_<head>`, the raw feature inputs, and `pool` (which pool definition produced the row), `inbox_ranking_unseen_head_graded` per (model, head) with `rows`, `positives`, `birth_day_positives` (of the positives, how many landed on the report's birth day), `base_rate`, `mean_score`, `expected_calibration_error`, `auc` and `recency_auc`, `inbox_ranking_unseen_calibration` per (model, head, decile) with `bucket`, `rows`, `positives`, `mean_score` and `realized_rate` (one event per decile, because a table on the head event would be an array no insight can break down), and `inbox_ranking_unseen_report_graded` per (report, model, horizon) with `p_<head>`, `in_cohort_<head>` and `outcome_<head>` for a calibration read on the raw rows. Both graded events are stamped on the day the outcome was read and carry `scoring_partition`, the day the report was scored, so a chart can be built on either axis. Both also carry `pool`, read back from the scores object, so an AUC series never mixes two pool definitions: the grader reads scores from up to 14 days earlier, so the days after a pool change grade both populations. A scores object written before the column existed reads as `sampled`, the pool the old seeded sample defined.
+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.
#### Reading one rendering against another
diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.py
index 81fbfa252392..484de67323ec 100644
--- a/products/signals/dags/inbox_ranking/tests/test_training.py
+++ b/products/signals/dags/inbox_ranking/tests/test_training.py
@@ -118,10 +118,12 @@ from products.signals.dags.inbox_ranking.training.unseen import (
head_grades,
leaked_report_ids,
model_mismatch,
+ readable_head_names,
report_grade_rows,
score_event_rows,
score_pool,
scored_pool,
+ trained_head_files,
unseen_pool,
with_model_names,
)
@@ -359,6 +361,26 @@ def test_dismissed_as_wrong_prefers_the_cumulative_count(frame, expected):
[True, True, True],
[True, False, False],
),
+ # thumbs_up: cohort is opened reports, label is a positive rating.
+ (
+ "thumbs_up",
+ pd.DataFrame({"open_count": [1, 1, 0], "feedback_positive_count": [1, 0, 0]}),
+ [True, True, False],
+ [True, False, False],
+ ),
+ # reviewer_fix: cohort is impressed reports, and an add or a remove is the same label.
+ (
+ "reviewer_fix",
+ pd.DataFrame(
+ {
+ "impression_unit_count": [1, 1, 1, 0],
+ "reviewer_add_count": [1, 0, 0, 0],
+ "reviewer_remove_count": [0, 2, 0, 0],
+ }
+ ),
+ [True, True, True, False],
+ [True, True, False, False],
+ ),
],
)
def test_new_heads_read_the_right_cohort_and_label_columns(head_name, frame, expected_cohort, expected_label):
@@ -385,7 +407,7 @@ class _ParquetS3:
return {"Body": io.BytesIO(self._objects[Key])}
[email protected]("head_name", ["pr_merged", "refund"])
[email protected]("head_name", ["pr_merged", "refund", "thumbs_up", "reviewer_fix"])
def test_new_head_label_columns_survive_the_load_snapshots_projection(head_name):
# load_snapshots projects the labels parquet down to _LABEL_COLUMNS before any head sees it, so a
# head whose label column is missing from that list trains on all-zero labels. The cohort/label
@@ -393,8 +415,26 @@ def test_new_head_label_columns_survive_the_load_snapshots_projection(head_name)
# Drive the real parquet -> projection -> build_examples path and assert a positive label survives.
head = HEADS_BY_NAME[head_name]
later = D0 + datetime.timedelta(days=head.horizon_days)
- labels_now = _labels(["a"], pr_created_count=[0], pr_merged_count=[0], refund_count=[0])
- labels_later = _labels(["a"], pr_created_count=[1], pr_merged_count=[1], refund_count=[1])
+ labels_now = _labels(
+ ["a"],
+ open_count=[1],
+ pr_created_count=[0],
+ pr_merged_count=[0],
+ refund_count=[0],
+ feedback_positive_count=[0],
+ reviewer_add_count=[0],
+ reviewer_remove_count=[0],
+ )
+ labels_later = _labels(
+ ["a"],
+ open_count=[1],
+ pr_created_count=[1],
+ pr_merged_count=[1],
+ refund_count=[1],
+ feedback_positive_count=[1],
+ reviewer_add_count=[1],
+ reviewer_remove_count=[0],
+ )
objects: dict[str, bytes] = {}
for date, labels in ((D0, labels_now), (later, labels_later)):
key = date.isoformat()
@@ -1229,6 +1269,7 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
"rows": 1,
"positives": 1,
"birth_day_positives": 1,
+ "readable": True,
"auc": None,
"mean_score": 0.8,
}.items() <= head_graded_props.items()
@@ -1248,6 +1289,8 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
"horizon_days",
"scoring_partition",
"pool",
+ # The holdout side reports readability on its own per-head event, not on every bucket.
+ "readable",
}
assert by_event["inbox_ranking_holdout_calibration"][0]["properties"]["model_role"] == CANDIDATE_ROLE
report_graded_props = by_event["inbox_ranking_unseen_report_graded"][0]["properties"]
@@ -1460,6 +1503,49 @@ def _unseen_model(model_name: str, feature_set: FeatureSet, role: str = CANDIDAT
)
+def test_an_unreadable_trained_head_is_still_scored_and_graded():
+ # A rare head never clears min_holdout_positives on one day's holdout, so gating the scoring on
+ # readability means the pooled newborn grade, the only read that can ever give it a number,
+ # never starts. The grade carries the flag instead, so the two populations stay apart.
+ metadata = {
+ "heads": [
+ {"head": "open", "file": "open.ubj", "readable": True},
+ {"head": "thumbs_up", "file": "thumbs_up.ubj", "readable": False},
+ ]
+ }
+ assert trained_head_files(metadata) == {"open": "open.ubj", "thumbs_up": "thumbs_up.ubj"}
+ assert readable_head_names(metadata) == frozenset({"open"})
+
+ booster = _booster_ubj(tuple(TABULAR_FEATURE_SET.feature_names))
+ model = UnseenModel(
+ model_name=TABULAR_MODEL_NAME,
+ model_version="2026-08-10",
+ model_role=CANDIDATE_ROLE,
+ feature_set=TABULAR_FEATURE_SET,
+ boosters={"open": booster, "thumbs_up": booster},
+ readable_heads=readable_head_names(metadata),
+ )
+ scores = score_pool(_state(["a", "b"]), _labels(["a", "b"]), [model], snapshot_date=D0)
+ assert scores.groupby("head")["head_readable"].all().to_dict() == {"open": True, "thumbs_up": False}
+
+ head = HEADS_BY_NAME["thumbs_up"]
+ labels = _labels(["a", "b"], open_count=[1, 1], feedback_positive_count=[1, 0])
+ graded = graded_rows(scores[scores["head"] == head.name], labels, head, pool=POOL_NAME)
+ (grade,) = head_grades(graded, head, pool=POOL_NAME, scoring_partition="2026-08-10")
+ assert (grade.rows, grade.positives, grade.readable) == (2, 1, False)
+
+
+def test_a_scores_object_written_before_the_readable_column_grades_as_readable():
+ # The grader reads objects up to 14 days old, and those runs scored a head only when it was
+ # readable, so a missing column must not turn a readable series unreadable overnight.
+ head = HEADS_BY_NAME["open"]
+ # _scores builds the pre-column row shape, so the frame reaching the grader carries no flag.
+ graded = graded_rows(_scores(["a", "b"]), _labels(["a", "b"], open_count=[1, 0]), head, pool=POOL_NAME)
+ assert graded["head_readable"].all()
+ (grade,) = head_grades(graded, head, pool=POOL_NAME, scoring_partition="2026-08-10")
+ assert grade.readable
+
+
def test_score_pool_builds_one_matrix_per_feature_set_and_shares_it():
# Two models on one set must reuse its matrix, and a model on another set must get its own.
# Scoring every model against a single matrix would feed the second set the wrong columns.
diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.py
index 72f058e1f479..5fb0b102e710 100644
--- a/products/signals/dags/inbox_ranking/training/dag.py
+++ b/products/signals/dags/inbox_ranking/training/dag.py
@@ -130,12 +130,13 @@ from products.signals.dags.inbox_ranking.training.unseen import (
missing_label_columns,
model_feature_set,
model_mismatch,
- readable_head_files,
+ readable_head_names,
report_grade_rows,
score_event_rows,
score_pool,
scored_pool,
scores_table,
+ trained_head_files,
unseen_pool,
with_model_names,
)
@@ -156,6 +157,9 @@ _LABEL_COLUMNS = (
"pr_created_count",
"pr_merged_count",
"refund_count",
+ "feedback_positive_count",
+ "reviewer_add_count",
+ "reviewer_remove_count",
*PROVENANCE_LABEL_COLUMNS,
)
# Every registered feature set's columns in one read: the state snapshot is loaded once and every
@@ -816,14 +820,14 @@ def load_family_models(
context.log.warning(f"{model_name} {role} {metadata.get('model_version')} not scored: {mismatch}")
continue
boosters = {}
- for head_name, filename in readable_head_files(metadata).items():
+ for head_name, filename in trained_head_files(metadata).items():
body = _read_bytes_if_exists(
client, bucket, model_object_key(prefix, model_name, metadata["model_version"], filename)
)
if body is not None:
boosters[head_name] = body
if not boosters:
- context.log.warning(f"{model_name} {role} {metadata['model_version']} has no readable head to score")
+ context.log.warning(f"{model_name} {role} {metadata['model_version']} has no trained head to score")
continue
models.append(
UnseenModel(
@@ -832,6 +836,7 @@ def load_family_models(
model_role=role,
feature_set=feature_set,
boosters=boosters,
+ readable_heads=readable_head_names(metadata),
)
)
return models
diff --git a/products/signals/dags/inbox_ranking/training/heads.py b/products/signals/dags/inbox_ranking/training/heads.py
index f2e28b53061e..084c186c1a79 100644
--- a/products/signals/dags/inbox_ranking/training/heads.py
+++ b/products/signals/dags/inbox_ranking/training/heads.py
@@ -8,8 +8,10 @@ must still be 0) and the snapshot `horizon_days` later (the label). The report's
exception: it has no earlier scoring moment, so an outcome already visible there is a future
positive for that moment rather than an outcome of an earlier one, and the label may already be 1.
-Mirrors the workspace `heads.py` (random-dev-internal, `inbox-ranking/`) for the seven heads with
-enough positives to ship; the other seven stay workspace-only until they are readable.
+Mirrors the workspace `heads.py` (random-dev-internal, `inbox-ranking/`). Seven heads are dense
+enough to read on the holdout. `thumbs_up` and `reviewer_fix` are the explicit human-feedback pair:
+they are rare, so they are carried for the pooled newborn grade and as scorer inputs rather than
+for a holdout AUC. The rest stay workspace-only.
"""
from collections.abc import Callable
@@ -67,6 +69,14 @@ def refunded(frame: pd.DataFrame) -> pd.Series:
return _count(frame, "refund_count") > 0
+def thumbed_up(frame: pd.DataFrame) -> pd.Series:
+ return _count(frame, "feedback_positive_count") > 0
+
+
+def reviewer_fixed(frame: pd.DataFrame) -> pd.Series:
+ return (_count(frame, "reviewer_add_count") + _count(frame, "reviewer_remove_count")) > 0
+
+
@frozen
class Head:
name: str
@@ -133,6 +143,28 @@ HEADS: tuple[Head, ...] = (
min_holdout_positives=20,
label_columns=("refund_count",),
),
+ # Of the reports someone opened, which drew a thumbs up at the end of the body? Every thumbed
+ # report was opened first, so the cohort loses nothing. About one opened report in a hundred
+ # gets one, so the holdout AUC stays noise for weeks and the pooled newborn grade is the read.
+ Head(
+ name="thumbs_up",
+ cohort=opened,
+ label=thumbed_up,
+ horizon_days=7,
+ min_holdout_positives=10,
+ label_columns=("feedback_positive_count",),
+ ),
+ # Of the reports users saw, which had their suggested reviewers corrected? An add and a remove
+ # are one label: a removal alone is housekeeping that usually follows a PR, while the pair reads
+ # as "a person corrected the reviewers". As slow to land as dismiss_wrong, hence the 14 days.
+ Head(
+ name="reviewer_fix",
+ cohort=impressed,
+ label=reviewer_fixed,
+ horizon_days=14,
+ min_holdout_positives=20,
+ label_columns=("reviewer_add_count", "reviewer_remove_count"),
+ ),
)
HEADS_BY_NAME: dict[str, Head] = {head.name: head for head in HEADS}
diff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.py
index 1f3ae26f113d..55bb4faa41a0 100644
--- a/products/signals/dags/inbox_ranking/training/unseen.py
+++ b/products/signals/dags/inbox_ranking/training/unseen.py
@@ -82,6 +82,7 @@ _SCORE_TYPES: dict[str, pa.DataType] = {
"score": pa.float64(),
"age_hours": pa.float64(),
"label_at_scoring": pa.bool_(),
+ "head_readable": pa.bool_(),
}
SCORES_SCHEMA = pa.schema(_SCORE_TYPES)
SCORE_COLUMNS = tuple(_SCORE_TYPES)
@@ -101,14 +102,17 @@ FEATURE_INPUT_COLUMNS = (
@frozen
class UnseenModel:
- """One model to score the pool with, the feature set it was fit on, and the readable heads it
- can score. Models that share a feature set share one matrix."""
+ """One model to score the pool with, the feature set it was fit on, and the heads it can score.
+ Models that share a feature set share one matrix."""
model_name: str
model_version: str
model_role: str
feature_set: FeatureSet
boosters: Mapping[str, bytes]
+ # Of those heads, the ones whose holdout could be read. Carried onto every scored row, because
+ # the grade runs `horizon_days` later and has no metadata of the model that wrote the row.
+ readable_heads: frozenset[str] = frozenset()
@frozen
@@ -147,6 +151,10 @@ class HeadGrade:
model_name: str
model_version: str
model_role: str
+ # Whether this head's holdout could be read on the model that wrote the scores. A rare head is
+ # 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
rows: int
positives: int
# Of the positives, how many had already happened when the report was scored: on this pool the
@@ -193,6 +201,7 @@ class HeadGrade:
"model_name": self.model_name,
"model_version": self.model_version,
"model_role": self.model_role,
+ "readable": self.readable,
}
def as_dict(self) -> dict[str, object]:
@@ -267,13 +276,24 @@ def model_mismatch(metadata: Mapping[str, Any]) -> str | None:
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."""
+def readable_head_names(metadata: Mapping[str, Any]) -> frozenset[str]:
+ """The heads of a model whose holdout AUC could be read."""
+ return frozenset(entry["head"] for entry in metadata.get("heads", []) if entry.get("readable"))
+
+
+def trained_head_files(metadata: Mapping[str, Any]) -> dict[str, str]:
+ """The `<head>.ubj` object name per head the candidate fit.
+
+ Every trained head is scored, readable or not. A rare head never clears `min_holdout_positives`
+ on one day's holdout, and the pooled newborn grade over many days is the only read that can
+ ever give it a number; gating the scoring on readability means that read never starts. An
+ unreadable head has no holdout AUC to compare against, so read its grade on its own, and the
+ promotion gate still ignores it.
+ """
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
+ if entry.get("file") and entry.get("head") in HEADS_BY_NAME
}
@@ -405,6 +425,7 @@ def score_pool(
"score": _predict(booster_ubj, matrix),
"age_hours": age_hours,
"label_at_scoring": HEADS_BY_NAME[head_name].label(aligned_labels).to_numpy(),
+ "head_readable": head_name in model.readable_heads,
}
)
for head_name, booster_ubj in model.boosters.items()
@@ -493,6 +514,10 @@ def graded_rows(head_scores: pd.DataFrame, labels: pd.DataFrame, head: Head, *,
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()
+ # An object written before the column existed scored a head only when it was readable.
+ graded["head_readable"] = (
+ head_scores["head_readable"].fillna(True).astype(bool) if "head_readable" in head_scores else True
+ )
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
@@ -526,6 +551,7 @@ def head_grades(graded: pd.DataFrame, head: Head, *, pool: str, scoring_partitio
model_name=str(model_name),
model_version=str(model_version),
model_role=str(model_role),
+ readable=bool(rows["head_readable"].all()),
rows=len(rows),
positives=int(outcomes.sum()),
birth_day_positives=int((outcomes & at_scoring).sum()),