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): fit the ranking heads on one birth-day row per report (#101685)

Andrew Maguire7d8e024a95e6
diff --git a/docs/internal/inbox-ranking-training.md b/docs/internal/inbox-ranking-training.md
new file mode 100644
index 000000000000..10896ae8b5e5
--- /dev/null
+++ b/docs/internal/inbox-ranking-training.md
@@ -0,0 +1,20 @@
+# Inbox ranking training examples
+
+The tabular and report-embedding ranking families use one example per report per head, from the report's birth-day snapshot.
+This prevents long-lived reports from receiving more weight in training because they appear in more daily snapshots.
+Birth days use the UTC interval returned by `snapshot_bounds`, including the start and excluding the end.
+The label comes from the snapshot `horizon_days` later, including outcomes already present on the birth day.
+
+The `pr_merged` head includes every report and reads merges within 14 days.
+The `dismiss_wrong` head includes impressed reports and reads wrong-dismissal outcomes within 14 days.
+
+The examples asset records `reports_missing_birth_snapshot` for observed reports born inside the lookback whose birth-day partition is missing.
+These reports produce no birth-grain example; reports born before the lookback do not contribute to this count.
+A missing horizon snapshot also prevents an example because its label is unknown.
+Point-in-time state, label provenance, and embedding availability checks still apply.
+
+Every training series resets on the first partition after deploy.
+Before and after holdout numbers are not comparable because the example population changes.
+The daily snapshots and selectable scoring-moment and report grains remain available for future models.
+
+See the [ranking DAG README](../../products/signals/dags/inbox_ranking/README.md) for the feature-set contract and operating instructions.
diff --git a/products/signals/backend/ranking/features.py b/products/signals/backend/ranking/features.py
index 2f69dea2b6f3..d342190cc28f 100644
--- a/products/signals/backend/ranking/features.py
+++ b/products/signals/backend/ranking/features.py
@@ -79,11 +79,11 @@ EMBEDDING_INSERTED_AT_COLUMN = "embedding_inserted_at"
# row whose vector is a different length is not this model's, so it is treated as missing.
EMBEDDING_DIMENSIONS = 1536
-# How many rows one report contributes to a head's examples.
-# `scoring_moment` is one row per (report, snapshot): the serving situation replayed over the
-# snapshots of the lookback. `report` is one row per report, at the first snapshot of the window
-# where it is a usable scoring moment, which is the grain of the newborn pool the unseen read
-# grades.
+# How many rows one report contributes to a head's examples. The default is `birth`, one row per
+# report at the snapshot of the day it was created; `examples.py` holds the reasoning.
+# `scoring_moment` is one row per (report, snapshot), and `report` is the first snapshot of the
+# window where the report is a usable moment. Both stay selectable for the re-scoring families.
+BIRTH_GRAIN = "birth"
SCORING_MOMENT_GRAIN = "scoring_moment"
REPORT_GRAIN = "report"
@@ -143,8 +143,9 @@ class FeatureSet(abc.ABC):
`state_columns` are the report-state columns `build_matrix` reads, and `extras_keys` the side
inputs it needs next to them. The caller always adds `age_hours`, so a set may read that
- without declaring it. `example_grain` and `max_examples_per_head` size the set's example
- population: a set 1536 columns wide cannot afford the row count a set 15 columns wide can.
+ without declaring it. `example_grain` defaults to one birth-day row per report so the fit does
+ not weight reports by their lifetime. Daily snapshots remain available for the scoring-moment
+ and report grains. `max_examples_per_head` bounds the population for wide sets.
"""
name: str
@@ -152,7 +153,7 @@ class FeatureSet(abc.ABC):
feature_names: tuple[str, ...]
state_columns: tuple[str, ...]
extras_keys: tuple[str, ...] = ()
- example_grain: str = SCORING_MOMENT_GRAIN
+ example_grain: str = BIRTH_GRAIN
# Rows one head's examples may keep, or None for every row the grain produces.
max_examples_per_head: int | None = None
@@ -215,19 +216,19 @@ class ReportEmbeddingsFeatureSet(FeatureSet):
One example per report, not one per scoring moment. A day's newborns over the whole lookback,
times 1536 floats, is gigabytes of Parquet per partition and more than the training pod holds,
- which is what rules the moment grain out at this width. The first snapshot where a report is a
- usable scoring moment is also the grain of the newborn pool the unseen read grades, so the
- training population matches the graded one. `max_examples_per_head` bounds what is left; the
- lookback stays the tabular set's, so positives still accrue over the whole window.
+ which is what rules the moment grain out at this width. The default birth grain gives that.
+ `max_examples_per_head` bounds what is left; the lookback stays the tabular set's, so positives
+ still accrue over the whole window.
Vectors arrive through `extras`, from the dt=D `inbox_report_embeddings` snapshot, which holds
the latest vector per report. A report is re-embedded whenever its text changes, and the
summary workflow and each re-research run rewrite it, so the latest vector can postdate the
moment being built. `as_of` is therefore load-bearing rather than a nicety: a moment takes the
- vector only when that vector had already landed, and at the report grain the example moves to
- the first snapshot where it had. Without the check the family would train on text that did not
- exist when the report was supposedly scored, which is the one thing that would invalidate the
- comparison this family exists for.
+ vector only when that vector had already landed, so a report whose birth-day snapshot holds
+ only a later vector is no example at all, and at the report grain it moves to the first
+ snapshot where the vector was its own. Without the check the family would train on text that
+ did not exist when the report was supposedly scored, which is the one thing that would
+ invalidate the comparison this family exists for.
A report the snapshot has no vector for at all is not buildable either: the source table's TTL
runs from report creation, so a long-lived report loses its vector while still live, and an
@@ -240,7 +241,6 @@ class ReportEmbeddingsFeatureSet(FeatureSet):
feature_names = tuple(f"emb_{index}" for index in range(EMBEDDING_DIMENSIONS))
state_columns = ()
extras_keys = (REPORT_EMBEDDINGS_EXTRA,)
- example_grain = REPORT_GRAIN
# 1536 float32 columns, so a head's Parquet slice and its training matrix both scale with this.
# Sized so every head of this family fits one partition's examples object and the fits stay
# inside the training job's runtime budget, with the budget spent on positives first.
diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.md
index 74c2fd44bb5f..1b9625723aa2 100644
--- a/products/signals/dags/inbox_ranking/AGENTS.md
+++ b/products/signals/dags/inbox_ranking/AGENTS.md
@@ -13,9 +13,9 @@ Read `README.md` first for what the dataset is and how partitions behave. This f
- A model declares its feature set in `metadata.json` and is checked against that set, not against one global contract. Adding a set means an entry in `FEATURE_SETS`; the examples asset then writes its Parquet under `inbox_ranking_training_examples/v1/<feature_set>/dt=D/`, and the unseen scorer builds one matrix per set and shares it across the families that read it. Do not reintroduce a module-global feature list into the training path: two sets live side by side. A partition whose examples were written before the per-set layout has nothing under `<feature_set>/`, so re-run the examples asset for that day before re-running the candidate or the unseen scores on it.
- A set that reads a side input declares it in `extras_keys`, and reports per-row availability through `buildable`. The example builder drops the rows `buildable` returns False for. The scorer deliberately does not drop rows: every family scores the whole newborn pool, or the AUCs stop being paired and the uplift read the families exist for is unmeasurable. Watch `<set>_pool_coverage` on the scores asset instead.
- Both `buildable` and `build_matrix` take the moment being built as `as_of`, and a side input that changes over a report's life must honor it. The report vector does: reports are re-embedded when their text changes, so the snapshot's latest vector often postdates the moment, and taking it would train on text that did not exist yet. Never widen a set's side input to the latest value for convenience.
-- `example_grain` and `max_examples_per_head` are per set, because the examples object is. Keep the tabular set at the scoring-moment grain with no budget: `report_embeddings` is the reason both knobs exist (1536 columns per row), and a budget on the tabular set would thin the family the other lines are measured against. A budget keeps every positive, so it moves the base rate its scores calibrate to and not the ranking.
+- `example_grain` and `max_examples_per_head` are per set, because the examples object is. Both sets default to the birth grain so both families target the same scoring moment; side-input availability and row budgets can still change their training populations. Keep the tabular set with no budget: `report_embeddings` is the reason the budget exists (1536 columns per row), and a budget on the tabular set would thin the family the other lines are measured against. A budget keeps every positive, so it moves the base rate its scores calibrate to and not the ranking.
- `feature_vector` (one row, serving) and `feature_frame` (vectorized, training) must agree row for row; a test pins it. Change both together.
-- Examples are scoring moments (every report × every snapshot) unless the set asks for the report grain, labeled from the snapshot `horizon_days` later. Keep the holdout cut by report; a row-level split leaks near-duplicate snapshots of the same report. 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.
+- 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.
- `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.
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.md
index e39f1385976a..431481661d59 100644
--- a/products/signals/dags/inbox_ranking/README.md
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -10,7 +10,7 @@ inbox_ranking/
│ └── queries.py # HogQL label SQL, embeddings SQL, stream merging
├── training/
│ ├── dag.py # examples → candidate → champion assets + job + schedule
-│ ├── examples.py # scoring-moment training examples over the snapshots
+│ ├── examples.py # birth-grain training examples over the snapshots
│ ├── heads.py # the v0 outcome heads
│ ├── train.py # per-head XGBoost fit + holdout/null metrics
│ └── promotion.py # the champion promotion rule
@@ -63,7 +63,7 @@ The first four are report grain and land in one table. `inbox_signal_embeddings`
```text
s3://<bucket>/<prefix>/
-├── inbox_ranking_training_examples/v1/<feature_set>/dt=YYYY-MM-DD/ # scoring-moment examples, all heads, one parquet per feature set
+├── inbox_ranking_training_examples/v1/<feature_set>/dt=YYYY-MM-DD/ # one row per report at its birth, all heads, one parquet per feature set
├── inbox_ranking_models/v1/<model_name>/
│ ├── 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)
@@ -73,18 +73,34 @@ s3://<bucket>/<prefix>/
- **A model is a `(model_name, model_version, model_role)`.** `model_name` is the family: which features and which learner, `tabular_xgb` for the per-head XGBoost trained here. `model_version` is the partition day it was fit on, and `model_role` is `candidate` or `champion`. Each family owns a prefix under the models path and its own `champion.json`, so two families trained on the same day cannot collide, and promotion stays inside a family. A richer family is a second candidate graded on the same unseen rows, not a competitor for the tabular family's pointer.
- **A feature set is one feature universe.** `products/signals/backend/ranking/features.py` holds a `FeatureSet` per universe: its name, its schema version, its ordered feature names, the report-state columns it reads, `build_matrix`, and how many rows it wants per report and per head. `tabular` and `report_embeddings` are the two today. A candidate records the set it was fit on in its `metadata.json`, so the grader checks a model against its own set rather than one global contract, the examples asset writes one Parquet per set, and the unseen scorer builds one matrix per set and shares it across the families that read it. Adding a set means an entry in `FEATURE_SETS`; a model naming a set this build cannot produce is logged and left unscored.
-- **Examples are scoring moments by default.** For partition `dt=D` the examples asset reads the report-state and labels snapshots `dt=D-lookback..D` and emits one row per (report, snapshot) whose head label is still 0 on that snapshot, labeled from the snapshot `horizon_days` later (3 for open, 7 for action / dismiss_wrong / pr_created / discuss, 14 for pr_merged / refund). Features are built by the feature set from that snapshot's state columns plus `age_hours`, the report's age at the snapshot. Labels are aligned to the state spine, so a report with no label event is a negative (all-zero labels), not absent. Label-only rows (no Postgres state) are skipped, as are state rows read long after their snapshot day (backfills carry current Postgres state; see `features_observed_at`) and, for the `dismiss_wrong` head, rows whose status telemetry fails the dataset's `label_provenance_ok` check. This is the serving situation replayed over history; it measured better than one row per report on the engagement heads.
-- **The report's birth day is the exception to "still 0 on that snapshot".** A report born on day D has no scoring moment before D, so an outcome already visible at D is a future positive for that moment, not an outcome of an earlier one; the labels of D therefore read as their defaults for a report born on D. Most outcomes land on the birth day, so this is where the positives are: censoring on them costs the `pr_created` head most of its training signal. `<set>_<head>_birth_day_positives` on the examples asset, and `birth_day_positives` on the `inbox_ranking_examples_built` event, say how many positives the rule keeps. These rows carry a hindsight the other rows do not: the state snapshot reads `signal_count`, `total_weight`, `run_count` and the text sizes live from Postgres a few hours after day D ends, so a birth-day outcome happened before its own feature read. Both the holdout AUC and the newborn unseen grade therefore read optimistically on these rows, until the scoring sweep's timestamped score log replaces the daily snapshot as this table's source.
-- **Serving population caveat.** Past the birth day, training keeps only moments where the head's outcome has not happened yet, but the scoring sweep cannot see outcome state, so it also scores reports that were already opened or acted on. `p_open` on an already-opened report is undefined; the shadow eval joins scores as of impression time, which keeps the read honest. Stopping a head once its outcome is observed is a sweep-side change.
-- **A set may ask for the report grain instead**, one example per report at its first usable scoring moment of the window, and cap the rows one head keeps (`max_examples_per_head`, all positives first, then a seeded sample of the negatives). Both knobs exist for `report_embeddings`: at 1536 columns the moment grain is gigabytes of Parquet per partition and more than the training pod holds. The row budget changes the base rate its scores are calibrated to, not the ranking the unseen AUC reads. The lookback is the tabular set's either way, so positives accrue over the whole window.
+- **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.
+- **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.
- **`tabular` is the serving set** (the state counters, title/summary length, age, one-hot priority/actionability). No embedding, no impression-derived columns, so the scoring sweep needs only the `SignalReport` row and its judgment artefacts. The sweep must build features through the same module; the booster's `feature_names` are checked against it at load.
- **`report_embeddings` is the report's own vector and nothing else**, read from the dt=D `inbox_report_embeddings` snapshot as a side input. Age is deliberately left out: it is the whole signal of the `recency_auc` line the unseen read already reports, so a gap to that line is content rather than recency. The scoring sweep does not serve this set: it is an offline candidate, and serving it needs the report vector at scoring time.
-- **A moment only takes a vector that already existed for it.** The snapshot holds the latest vector per report, and a report is re-embedded whenever its text changes (the summary workflow and every re-research run rewrite it), so the latest vector often postdates an earlier moment. Each row carries `embedding_inserted_at`, and a moment keeps the vector only when it landed at or before that snapshot's end; at the report grain the example then moves to the first snapshot where the vector was already the report's own. Without that check the family would train on text that did not exist when the report was supposedly scored. A report the snapshot has no vector for at all is not an example either, because the source table's TTL runs from report creation and a long-lived report loses its vector while still live. The scores asset records each set's coverage of the newborn pool, so a thin side input is visible rather than silent.
+- **A moment only takes a vector that already existed for it.** The snapshot holds the latest vector per report, and a report is re-embedded whenever its text changes (the summary workflow and every re-research run rewrite it), so the latest vector often postdates an earlier moment. Each row carries `embedding_inserted_at`, and a moment keeps the vector only when it landed at or before that snapshot's end; at the birth grain a report whose birth-day snapshot holds only a later vector is no example, and at the report grain it moves to the first snapshot where the vector was already its own. Without that check the family would train on text that did not exist when the report was supposedly scored. A report the snapshot has no vector for at all is not an example either, because the source table's TTL runs from report creation and a long-lived report loses its vector while still live. The scores asset records each set's coverage of the newborn pool, so a thin side input is visible rather than silent.
- **A set whose side input is unavailable is skipped, not rebuilt from nothing.** The examples asset writes no object for it, the candidate asset leaves that family's partition as it stands, and the unseen scorer drops its models for the day. Rebuilding would write an empty examples object, then an empty candidate, and the candidate's prefix cleanup would delete boosters a champion pointer can name.
- **Candidate**: one per family, per-head XGBoost with fixed params, holdout = the last `holdout_days` of reports (cut by report, never by row), AUC + a label-permutation null. Each family trains on the examples of the feature set its registry entry names, and a family whose examples or metadata are missing that day is logged and skipped rather than failing the asset. A head is _readable_ when it has enough holdout positives and clears its null by 0.05. The shipped booster (`<head>.ubj`) is refit on everything; the train-only fit is kept as `<head>.holdout.ubj` so a later candidate can grade this model on its own holdout.
- **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` once per head and feature set, `inbox_ranking_candidate_trained` once per head (`head`, `model_role` always `candidate`, holdout / train AUC, average precision, logloss, positive rate, mean predicted score, the row-weighted decile calibration error, the permutation-null mean and spread, counts, `readable`), `inbox_ranking_holdout_calibration` once per head and holdout score decile and `inbox_ranking_promotion_decided` once per run, all carrying `model_name` and `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**: one decision per family against that family's own pointer. `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`.
+### Outcome heads
+
+| Head | Cohort at the horizon | Horizon (days) |
+| --------------- | --------------------- | -------------- |
+| `open` | Impressed reports | 3 |
+| `action` | Impressed reports | 7 |
+| `dismiss_wrong` | Impressed reports | 14 |
+| `pr_created` | Every report | 7 |
+| `pr_merged` | Every report | 14 |
+| `discuss` | Impressed reports | 7 |
+| `refund` | Every report | 14 |
+
+Every training series resets on the first partition after deploy.
+Before and after holdout numbers are not comparable because the example population changes.
+See [training example semantics](../../../../docs/internal/inbox-ranking-training.md) for gap handling and snapshot boundaries.
+
### 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.
diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.py
index 17e915e73c80..1621dc20fdbc 100644
--- a/products/signals/dags/inbox_ranking/tests/test_training.py
+++ b/products/signals/dags/inbox_ranking/tests/test_training.py
@@ -1,4 +1,5 @@
import io
+import copy
import json
import math
import datetime
@@ -17,6 +18,7 @@ from botocore.exceptions import ClientError
from posthog import settings
from products.signals.backend.ranking.features import (
+ BIRTH_GRAIN,
EMBEDDING_COLUMN,
EMBEDDING_DIMENSIONS,
EMBEDDING_INSERTED_AT_COLUMN,
@@ -25,6 +27,8 @@ from products.signals.backend.ranking.features import (
NO_EXTRAS,
REPORT_EMBEDDINGS_EXTRA,
REPORT_EMBEDDINGS_FEATURE_SET,
+ REPORT_GRAIN,
+ SCORING_MOMENT_GRAIN,
TABULAR_FEATURE_SET,
Extras,
FeatureSet,
@@ -63,8 +67,9 @@ from products.signals.dags.inbox_ranking.training.examples import (
cap_examples,
example_columns,
holdout_mask,
+ reports_missing_birth_snapshot,
)
-from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, dismissed_as_wrong
+from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, Head, dismissed_as_wrong
from products.signals.dags.inbox_ranking.training.promotion import AUC_TOLERANCE, PromotionDecision, decide_promotion
from products.signals.dags.inbox_ranking.training.telemetry import (
DISTINCT_ID,
@@ -114,10 +119,16 @@ D0 = datetime.date(2026, 8, 10)
NOW = datetime.datetime(2026, 8, 20, tzinfo=datetime.UTC)
+# Midday on D0, so a default report is born on the first snapshot day the tests build and the
+# birth grain keeps it. A test about any other grain passes its own `report_created_at`.
+BIRTH = pd.Timestamp("2026-08-10T12:00:00Z")
+BEFORE_THE_WINDOW = pd.Timestamp("2026-07-01T00:00:00Z")
+
+
def _state(report_ids: list[str], **overrides) -> pd.DataFrame:
n = len(report_ids)
base = {
- "report_created_at": [pd.Timestamp("2026-08-09T12:00:00Z")] * n,
+ "report_created_at": [BIRTH] * n,
"report_age_hours": [12.0] * n,
"signal_count": [3] * n,
"total_weight": [1.5] * n,
@@ -145,6 +156,26 @@ def _labels(report_ids: list[str], **overrides) -> pd.DataFrame:
return pd.DataFrame(base, index=pd.Index(report_ids, name="report_id"))
+def _at_grain(feature_set: FeatureSet, grain: str) -> FeatureSet:
+ """`feature_set` with a different example grain, so a test can pin one grain's rows."""
+ variant = copy.copy(feature_set)
+ variant.example_grain = grain
+ return variant
+
+
+def _daily_snapshots(
+ ids: list[str], head: Head, created: list[pd.Timestamp], *, days: int = 2
+) -> dict[datetime.date, Snapshot]:
+ snapshots: dict[datetime.date, Snapshot] = {}
+ for offset in range(days):
+ day = D0 + datetime.timedelta(days=offset)
+ state = _state(ids, report_created_at=created)
+ snapshots[day] = Snapshot(date=day, state=state, labels=_labels(ids, open_count=[0] * len(ids)))
+ partner = day + datetime.timedelta(days=head.horizon_days)
+ snapshots[partner] = Snapshot(date=partner, state=state, labels=_labels(ids, open_count=[1] * len(ids)))
+ return snapshots
+
+
@pytest.mark.parametrize(
"row",
[
@@ -182,27 +213,30 @@ def test_feature_vector_matches_feature_frame(row):
def test_build_examples_is_a_scoring_moment_with_a_future_label():
+ # The grain a re-scoring family would ask for: a row per snapshot, censored once the outcome is
+ # visible. Every report here is older than D0, so no birth-day exemption applies.
open_head = HEADS_BY_NAME["open"]
later = D0 + datetime.timedelta(days=open_head.horizon_days)
ids = ["a", "b", "c", "d"]
+ state = _state(ids, report_created_at=[BEFORE_THE_WINDOW] * 4)
snapshots = {
# a: not yet impressed or opened at D0, impressed and opened by D0+3 -> positive;
# b: already opened at D0 -> excluded; c: never opened -> negative;
# d: never impressed -> outside the cohort.
D0: Snapshot(
date=D0,
- state=_state(ids),
+ state=state,
labels=_labels(ids, open_count=[0, 1, 0, 0], impression_unit_count=[0, 1, 1, 0]),
),
later: Snapshot(
date=later,
- state=_state(ids),
+ state=state,
labels=_labels(ids, open_count=[2, 3, 0, 0], impression_unit_count=[1, 1, 1, 0]),
),
# A snapshot with no horizon partner contributes nothing.
- later + datetime.timedelta(days=1): Snapshot(date=later, state=_state(ids), labels=_labels(ids)),
+ later + datetime.timedelta(days=1): Snapshot(date=later, state=state, labels=_labels(ids)),
}
- examples = build_examples(snapshots, open_head, TABULAR_FEATURE_SET)
+ examples = build_examples(snapshots, open_head, _at_grain(TABULAR_FEATURE_SET, SCORING_MOMENT_GRAIN))
assert list(examples.columns) == list(example_columns(TABULAR_FEATURE_SET))
assert examples.set_index("report_id")["label"].to_dict() == {"a": 1, "c": 0}
assert (examples["snapshot_date"] == D0).all()
@@ -211,6 +245,8 @@ def test_build_examples_is_a_scoring_moment_with_a_future_label():
def test_assemble_snapshot_makes_never_labeled_reports_negatives_and_drops_untrusted_status_rows():
head = HEADS_BY_NAME["pr_created"]
+ wrong_head = HEADS_BY_NAME["dismiss_wrong"]
+ assert wrong_head.horizon_days == 14
later = D0 + datetime.timedelta(days=head.horizon_days)
ids = ["a", "b", "c", "gone"]
# a: status telemetry names another tenant -> provenance fails; b: no label row at all;
@@ -234,6 +270,10 @@ def test_assemble_snapshot_makes_never_labeled_reports_negatives_and_drops_untru
snapshots = {
D0: assemble_snapshot(D0, state, labels_now),
later: assemble_snapshot(later, state_later, labels_later),
+ # The two heads read different horizons off the same day.
+ D0 + datetime.timedelta(days=wrong_head.horizon_days): assemble_snapshot(
+ D0 + datetime.timedelta(days=wrong_head.horizon_days), state_later, labels_later
+ ),
}
assert snapshots[D0].labels.loc["b", "impression_unit_count"] == 0
@@ -243,11 +283,7 @@ def test_assemble_snapshot_makes_never_labeled_reports_negatives_and_drops_untru
pr = build_examples(snapshots, head, TABULAR_FEATURE_SET).set_index("report_id")["label"].to_dict()
assert pr == {"a": 0, "b": 0, "c": 1, "gone": 1}
# dismiss_wrong reads the status stream: a is dropped, b was never impressed, c is a positive.
- wrong = (
- build_examples(snapshots, HEADS_BY_NAME["dismiss_wrong"], TABULAR_FEATURE_SET)
- .set_index("report_id")["label"]
- .to_dict()
- )
+ wrong = build_examples(snapshots, wrong_head, TABULAR_FEATURE_SET).set_index("report_id")["label"].to_dict()
assert wrong == {"c": 1}
@@ -283,12 +319,13 @@ def test_dismissed_as_wrong_prefers_the_cumulative_count(frame, expected):
@pytest.mark.parametrize(
"head_name,frame,expected_cohort,expected_label",
[
- # pr_merged: cohort is reports with a PR, label is the merge within the horizon.
+ # pr_merged: cohort is everyone, label is the merge within the horizon, whether or not the
+ # report already had a PR at the scoring moment.
(
"pr_merged",
- pd.DataFrame({"pr_created_count": [1, 1, 0], "pr_merged_count": [1, 0, 0]}),
- [True, True, False],
- [True, False, False],
+ pd.DataFrame({"pr_created_count": [1, 1, 0], "pr_merged_count": [1, 0, 1]}),
+ [True, True, True],
+ [True, False, True],
),
# discuss: cohort is impressed reports, label is a discuss action.
(
@@ -561,22 +598,109 @@ def test_unseen_pool_is_the_reports_born_on_the_partition_day():
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.
[email protected]("grain", [BIRTH_GRAIN, SCORING_MOMENT_GRAIN, REPORT_GRAIN])
+def test_build_examples_never_covers_a_report_born_on_the_partition_day(grain):
+ # What the newborn pool rests on: a builder change that reached the partition day would leak,
+ # and every grain a set can select has to keep that property.
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")
+ newborn = 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])
+ scoring_day,
+ _state(["old"], report_created_at=[pd.Timestamp(scoring_day, tz="UTC")]),
+ _labels(["old"], open_count=[0]),
),
D0: assemble_snapshot(
D0,
- _state(["old", "newborn"], report_created_at=[old, newborn]),
+ _state(["old", "newborn"], report_created_at=[pd.Timestamp(scoring_day, tz="UTC"), newborn]),
_labels(["old", "newborn"], open_count=[1, 1]),
),
}
- assert set(build_examples(snapshots, head, TABULAR_FEATURE_SET)["report_id"]) == {"old"}
+ examples = build_examples(snapshots, head, _at_grain(TABULAR_FEATURE_SET, grain))
+ assert set(examples["report_id"]) == {"old"}
+
+
[email protected]("feature_set", [TABULAR_FEATURE_SET, REPORT_EMBEDDINGS_FEATURE_SET])
+def test_birth_grain_keeps_one_row_per_report_on_the_day_it_was_created(feature_set):
+ head = HEADS_BY_NAME["open"]
+ ids = ["newborn", "older", "utc_start", "utc_end"]
+ created = [
+ BIRTH,
+ BEFORE_THE_WINDOW,
+ pd.Timestamp("2026-08-09T20:00:00-04:00"),
+ pd.Timestamp("2026-08-10T20:00:00-04:00"),
+ ]
+ snapshots = _daily_snapshots(ids, head, created, days=3)
+ snapshots[D0 + datetime.timedelta(days=head.horizon_days)].labels.loc[:, "open_count"] = 0
+ extras = _report_vectors({report_id: _embedding() for report_id in ids})
+
+ examples = build_examples(snapshots, head, feature_set, extras)
+
+ assert feature_set.example_grain == BIRTH_GRAIN
+ assert examples["report_id"].is_unique
+ assert examples.set_index("report_id")[["snapshot_date", "label"]].to_dict("index") == {
+ "newborn": {"snapshot_date": D0, "label": 0},
+ "utc_start": {"snapshot_date": D0, "label": 0},
+ "utc_end": {"snapshot_date": D0 + datetime.timedelta(days=1), "label": 1},
+ }
+ moments = build_examples(snapshots, head, _at_grain(feature_set, SCORING_MOMENT_GRAIN), extras)
+ assert moments[moments["report_id"] == "newborn"]["label"].tolist() == [0, 1, 1]
+
+
+def test_pr_merged_is_a_merge_from_birth_rather_than_a_merge_given_a_pr():
+ head = HEADS_BY_NAME["pr_merged"]
+ assert head.horizon_days == 14
+ later = D0 + datetime.timedelta(days=14)
+ merged_day = D0 + datetime.timedelta(days=10)
+ ids = ["merged", "unmerged", "nothing"]
+ snapshots = {
+ D0: assemble_snapshot(D0, _state(ids), _labels(ids, pr_created_count=[0, 1, 0], pr_merged_count=[0, 0, 0])),
+ **{
+ date: assemble_snapshot(
+ date, _state(ids), _labels(ids, pr_created_count=[1, 1, 0], pr_merged_count=[1, 0, 0])
+ )
+ for date in (merged_day, later)
+ },
+ }
+
+ examples = build_examples(snapshots, head, TABULAR_FEATURE_SET)
+
+ assert examples.set_index("report_id")["label"].to_dict() == {"merged": 1, "unmerged": 0, "nothing": 0}
+
+
+def test_reports_missing_birth_snapshot_counts_only_the_ones_a_partition_gap_costs(monkeypatch):
+ gap = D0 + datetime.timedelta(days=1)
+ dates = [D0 + datetime.timedelta(days=offset) for offset in range(6)]
+ ids = ["born_in_the_gap", "older", "utc_start", "utc_end", "label_only"]
+ created = [
+ pd.Timestamp(gap, tz="UTC") + pd.Timedelta(hours=9),
+ BEFORE_THE_WINDOW,
+ pd.Timestamp("2026-08-10T20:00:00-04:00"),
+ pd.Timestamp("2026-08-11T20:00:00-04:00"),
+ pd.NaT,
+ ]
+ snapshots = {
+ date: Snapshot(date=date, state=_state(ids, report_created_at=created), labels=_labels(ids))
+ for date in dates
+ if date != gap
+ }
+
+ assert reports_missing_birth_snapshot(snapshots, dates) == 2
+ assert reports_missing_birth_snapshot({}, dates) == 0
+ examples = build_examples(snapshots, HEADS_BY_NAME["open"], TABULAR_FEATURE_SET)
+ assert examples["report_id"].tolist() == ["utc_end"]
+
+ module = "products.signals.dags.inbox_ranking.training.dag"
+ monkeypatch.setattr(f"{module}.skip_unconfigured", lambda context: False)
+ monkeypatch.setattr(f"{module}.s3_client", lambda: None)
+ monkeypatch.setattr(f"{module}.snapshot_dates", lambda *args: dates)
+ monkeypatch.setattr(f"{module}.load_snapshots", lambda *args, **kwargs: snapshots)
+ monkeypatch.setattr(f"{module}.report_embeddings_extras", lambda *args: NO_EXTRAS)
+ monkeypatch.setattr(f"{module}._write_examples", lambda *args: {})
+ with dagster.build_asset_context(partition_key=dates[-1].isoformat()) as context:
+ inbox_ranking_training_examples(context)
+ assert context.get_output_metadata("result")["reports_missing_birth_snapshot"].value == 2
def test_build_examples_keeps_an_outcome_that_landed_on_the_reports_birth_day():
@@ -1428,24 +1552,19 @@ def test_a_report_without_this_models_vector_is_not_an_embeddings_example(extras
def test_report_grain_keeps_one_example_per_report_and_needs_a_vector():
# The scoring-moment grain emits a near-duplicate row per snapshot, which is what 1536 columns
- # cannot afford; the first usable moment is also the grain of the pool the unseen read grades.
+ # cannot afford; the report grain keeps the first snapshot a report is usable on.
head = HEADS_BY_NAME["open"]
- ids = ["a", "b"]
- snapshots: dict[datetime.date, Snapshot] = {}
- for offset in (0, 1):
- day = D0 + datetime.timedelta(days=offset)
- later = day + datetime.timedelta(days=head.horizon_days)
- snapshots[day] = Snapshot(date=day, state=_state(ids), labels=_labels(ids, open_count=[0, 0]))
- snapshots[later] = Snapshot(date=later, state=_state(ids), labels=_labels(ids, open_count=[1, 1]))
+ snapshots = _daily_snapshots(["a", "b"], head, [BIRTH, BIRTH])
extras = _report_vectors({"a": _embedding()})
- examples = build_examples(snapshots, head, REPORT_EMBEDDINGS_FEATURE_SET, extras)
+ examples = build_examples(snapshots, head, _at_grain(REPORT_EMBEDDINGS_FEATURE_SET, REPORT_GRAIN), extras)
assert examples["report_id"].tolist() == ["a"]
assert examples["snapshot_date"].tolist() == [D0]
assert examples["emb_0"].tolist() == [0.0]
- # The tabular set reads the same snapshots at the moment grain, both reports, both days.
- assert build_examples(snapshots, head, TABULAR_FEATURE_SET)["report_id"].tolist() == ["a", "b", "a", "b"]
+ # The same snapshots at the moment grain: both reports, both days.
+ moments = build_examples(snapshots, head, _at_grain(TABULAR_FEATURE_SET, SCORING_MOMENT_GRAIN))
+ assert moments["report_id"].tolist() == ["a", "b", "a", "b"]
def test_cap_examples_keeps_every_positive_and_a_seeded_sample_of_the_negatives():
@@ -1495,19 +1614,15 @@ def test_report_grain_moves_the_example_to_the_first_moment_its_vector_existed_f
# A report whose vector landed after its first snapshot must not be dropped outright: its
# example belongs on the first snapshot where that vector was already the report's own.
head = HEADS_BY_NAME["open"]
- ids = ["a"]
- snapshots: dict[datetime.date, Snapshot] = {}
- for offset in (0, 1):
- day = D0 + datetime.timedelta(days=offset)
- later = day + datetime.timedelta(days=head.horizon_days)
- snapshots[day] = Snapshot(date=day, state=_state(ids), labels=_labels(ids, open_count=[0]))
- snapshots[later] = Snapshot(date=later, state=_state(ids), labels=_labels(ids, open_count=[1]))
+ snapshots = _daily_snapshots(["a"], head, [BIRTH])
# Landed during D0 + 1, so D0 cannot have it and D0 + 1 can.
extras = _report_vectors({"a": _embedding()}, landed=SNAPSHOT_END + datetime.timedelta(hours=6))
- examples = build_examples(snapshots, head, REPORT_EMBEDDINGS_FEATURE_SET, extras)
+ examples = build_examples(snapshots, head, _at_grain(REPORT_EMBEDDINGS_FEATURE_SET, REPORT_GRAIN), extras)
assert examples["snapshot_date"].tolist() == [D0 + datetime.timedelta(days=1)]
+ # At the birth grain there is no later moment to move to, so the report is no example at all.
+ assert build_examples(snapshots, head, REPORT_EMBEDDINGS_FEATURE_SET, extras).empty
def test_reading_a_moment_needs_the_vectors_landing_time():
diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.py
index 73a660b6e4fc..da6cee8458f3 100644
--- a/products/signals/dags/inbox_ranking/training/dag.py
+++ b/products/signals/dags/inbox_ranking/training/dag.py
@@ -81,6 +81,7 @@ from products.signals.dags.inbox_ranking.training.examples import (
build_examples,
example_columns,
point_in_time_mask,
+ reports_missing_birth_snapshot,
state_rows,
)
from products.signals.dags.inbox_ranking.training.heads import HEADS, HEADS_BY_HORIZON, HEADS_BY_NAME
@@ -314,10 +315,17 @@ def inbox_ranking_training_examples(context: dagster.AssetExecutionContext) -> N
if backfilled_rows:
context.log.warning(f"{backfilled_rows} state rows read after the snapshot window are excluded (backfill)")
+ # A gap in the partitions is silent at the birth grain: it removes every report born that day
+ # from every head, rather than thinning the rows of a report that survives.
+ unreachable_reports = reports_missing_birth_snapshot(snapshots, dates)
+ if unreachable_reports:
+ context.log.warning(f"{unreachable_reports} reports born inside the window have no birth-day snapshot")
+
extras = report_embeddings_extras(context, client, bucket, prefix, partition_key)
metadata: dict[str, dagster.MetadataValue] = {
"snapshots": dagster.MetadataValue.int(len(snapshots)),
"backfilled_state_rows_excluded": dagster.MetadataValue.int(backfilled_rows),
+ "reports_missing_birth_snapshot": dagster.MetadataValue.int(unreachable_reports),
}
for feature_set in FEATURE_SETS.values():
missing = feature_set.missing_extras(extras)
diff --git a/products/signals/dags/inbox_ranking/training/examples.py b/products/signals/dags/inbox_ranking/training/examples.py
index 35a825888ffd..400f2c6fe7d7 100644
--- a/products/signals/dags/inbox_ranking/training/examples.py
+++ b/products/signals/dags/inbox_ranking/training/examples.py
@@ -1,18 +1,16 @@
"""Training examples at the grain the feature set asks for.
-The default grain is a scoring moment: one example = one report as one daily snapshot saw it.
-Its features are that snapshot's report-state columns (plus `age_hours`, the report's age at the
-snapshot), and its label is whether the head's outcome happened within the head's horizon: the
-label is 0 on the snapshot row and read from the snapshot `horizon_days` later. That is the serving
-situation — a report gets scored, then users see it — replayed over the daily snapshots, and it
-measured better than one row per report on the engagement heads (skill issue 13). Once the scoring
-sweep's append-only score log has accrued it becomes this table's source; the snapshots are the
-bootstrap.
-
-The report's birth day is the exception to "0 on the snapshot row": a report born on day D has no
-scoring moment before D, so an outcome already visible at D is a future positive for the moment
-being built, not a past one. The labels of day D are therefore read as the defaults for a report
-born on D. Most outcomes land on the birth day, so this is where the positives are.
+The default grain is the report's birth: one example = one report as the snapshot of the day it
+was created saw it. Its features are that snapshot's report-state columns (plus `age_hours`, the
+report's age at the snapshot), and its label is whether the head's outcome happened within the
+head's horizon, read from the snapshot `horizon_days` later. That is the moment serving scores a
+report, and the label is a per-report probability, which is what the inbox ordering asks of it.
+Once the scoring sweep's append-only score log has accrued it becomes this table's source; the
+snapshots are the bootstrap.
+
+A report born on day D has no scoring moment before D, so an outcome already visible at D is a
+future positive for the moment being built, not a past one. Birth-day outcomes therefore do not
+censor the moment; its label still comes from the horizon snapshot.
These birth-day rows carry a hindsight the other rows do not. The state snapshot reads
`signal_count`, `total_weight`, `run_count` and the text sizes live from Postgres a few hours
@@ -21,24 +19,25 @@ outcome therefore happened before its own feature read, so both the holdout AUC
unseen grade read optimistically on these rows. What removes it is the scoring sweep's timestamped
score log becoming this table's source, not censoring the positives again.
-Rows of one report are near-duplicates, so the holdout is cut BY REPORT (report_created_at),
-never by row. Label-only rows (EU reports, hard-deleted rows) carry no state and are skipped.
-A snapshot is assembled over the state spine (`assemble_snapshot`): a report with no label event
-gets LABEL_DEFAULTS, so never-engaged reports are negatives rather than absent.
+The holdout is cut BY REPORT (report_created_at), never by row, so a grain that emits several rows
+of one report cannot straddle the cut. Label-only rows (EU reports, hard-deleted rows) carry no
+state and are skipped. A snapshot is assembled over the state spine (`assemble_snapshot`): a report
+with no label event gets LABEL_DEFAULTS, so never-engaged reports are negatives rather than absent.
-A wide set cannot afford that many rows, so a set may ask for the report grain instead (one
-example per report, at its first usable scoring moment of the window) and cap the rows one head
-keeps. Both knobs live on the `FeatureSet`, because the examples object is per set.
+A set may ask for the scoring-moment grain instead (one row per report per snapshot, whose label is
+a hazard conditional on the report still being live) or the report grain (the first snapshot of the
+window where the report is a usable moment), and cap the rows one head keeps. Both knobs live on
+the `FeatureSet`, because the examples object is per set.
"""
import datetime
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
import pandas as pd
from posthog.dataclasses import frozen
-from products.signals.backend.ranking.features import NO_EXTRAS, REPORT_GRAIN, Extras, FeatureSet
+from products.signals.backend.ranking.features import BIRTH_GRAIN, NO_EXTRAS, REPORT_GRAIN, Extras, FeatureSet
from products.signals.dags.inbox_ranking.common import snapshot_bounds
from products.signals.dags.inbox_ranking.dataset.dag import label_provenance_ok
from products.signals.dags.inbox_ranking.dataset.queries import LABEL_DEFAULTS
@@ -191,8 +190,9 @@ def example_moments(
extras: Extras,
) -> pd.DataFrame:
"""The (report, snapshot) moments that are examples for `head`, with their labels and no
- features. One row per moment at the scoring-moment grain; at the report grain, only the first
- snapshot of the window where a report is a usable moment."""
+ features. One row per report at the birth grain, on the snapshot of the day it was created; one
+ row per moment at the scoring-moment grain; at the report grain, the first snapshot of the
+ window where a report is a usable moment."""
frames: list[pd.DataFrame] = []
covered: set[object] = set()
for date in sorted(snapshots):
@@ -216,7 +216,8 @@ def example_moments(
# read at `now` would drop those pre-impression scoring moments, which are the serving case.
# An outcome already observed at `now` belongs to an earlier moment, so it censors this
# one. A report born on this day has no earlier moment to own it.
- censored = head.label(labels_now) & ~birth_day_mask(state, date)
+ born_today = birth_day_mask(state, date)
+ censored = head.label(labels_now) & ~born_today
keep = head.cohort(labels_later) & ~censored & state["signal_count"].notna()
keep &= point_in_time_mask(state, date)
if head.status_labels:
@@ -227,12 +228,15 @@ def example_moments(
# snapshot, cannot build the vector this moment had, so the report is not a moment here. At
# the report grain the report then takes its example on the first snapshot where it can.
keep &= feature_set.buildable(state, extras, as_of=snapshot_end)
- if feature_set.example_grain == REPORT_GRAIN:
+ if feature_set.example_grain == BIRTH_GRAIN:
+ keep &= born_today
+ elif feature_set.example_grain == REPORT_GRAIN:
keep &= ~state.index.isin(covered)
if not keep.any():
continue
kept_ids = state.index[keep.to_numpy()]
- covered.update(kept_ids)
+ if feature_set.example_grain == REPORT_GRAIN:
+ covered.update(kept_ids)
frames.append(
pd.DataFrame(
{
@@ -262,6 +266,21 @@ def birth_day_positives(examples: pd.DataFrame) -> int:
)
+def reports_missing_birth_snapshot(snapshots: Mapping[datetime.date, Snapshot], dates: Sequence[datetime.date]) -> int:
+ """How many reports born on a day of `dates` can be no example at the birth grain, because the
+ snapshot of that day is missing from `snapshots`.
+
+ A report born before the window is not counted: it has no birth-day snapshot by construction,
+ and the birth grain drops it deliberately rather than through a gap. The same snapshot bounds
+ define the birth day here and in the example filter.
+ """
+ if not snapshots:
+ return 0
+ created = pd.concat([snapshot.state["report_created_at"] for snapshot in snapshots.values()])
+ reports = created.dropna().loc[lambda rows: ~rows.index.duplicated()].to_frame()
+ return sum(int(birth_day_mask(reports, date).sum()) for date in set(dates).difference(snapshots))
+
+
def cap_examples(moments: pd.DataFrame, limit: int | None) -> pd.DataFrame:
"""`moments` within `limit` rows, keeping every positive and a seeded sample of the negatives.
diff --git a/products/signals/dags/inbox_ranking/training/heads.py b/products/signals/dags/inbox_ranking/training/heads.py
index e7f489037a3a..f2e28b53061e 100644
--- a/products/signals/dags/inbox_ranking/training/heads.py
+++ b/products/signals/dags/inbox_ranking/training/heads.py
@@ -95,17 +95,17 @@ HEADS: tuple[Head, ...] = (
name="dismiss_wrong",
cohort=impressed,
label=dismissed_as_wrong,
- horizon_days=7,
+ horizon_days=14,
min_holdout_positives=30,
status_labels=True,
),
# Which reports get a PR at all? Cohort is every report the sweep would score.
Head(name="pr_created", cohort=everyone, label=pr_created, horizon_days=7, min_holdout_positives=30),
- # Of the reports that got a PR, which got it merged? Completes the open -> pr_created -> pr_merged
- # funnel; the negative is "pr_created, no merge within the horizon".
+ # Which reports end up with a merged PR? The cohort is everyone, so the label carries the whole
+ # report-to-merge path rather than conditioning on a PR that does not exist yet at birth.
Head(
name="pr_merged",
- cohort=pr_created,
+ cohort=everyone,
label=pr_merged,
horizon_days=14,
min_holdout_positives=30,