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.

fix(signals): grade the inbox shadow eval on rows the model can score (#102885)

posthog[bot]5e24cabb8b4e
diff --git a/docs/internal/inbox-ranking-shadow-evaluation.md b/docs/internal/inbox-ranking-shadow-evaluation.md
index 9c1e53988c9f..46257db37271 100644
--- a/docs/internal/inbox-ranking-shadow-evaluation.md
+++ b/docs/internal/inbox-ranking-shadow-evaluation.md
@@ -16,5 +16,7 @@ A missing champion partition uses candidate scores as an explicit fallback, not
The daily job has a one-hour timeout.
Every completed evaluation emits `inbox_ranking_shadow_run_completed`, including runs with zero grades and a `reason`: `no_complete_lists`, `no_available_scores`, or `no_gradeable_outcomes`.
-Per-order metrics remain on `inbox_ranking_shadow_ranking_graded`.
+Per-order metrics for `all_rows` remain on `inbox_ranking_shadow_ranking_graded`.
+Metrics for `scored_rows` use `inbox_ranking_shadow_scored_ranking_graded`, so existing charts do not mix the two scopes.
+Use the scored event to compare orders on the same scored reports.
See the [ranking DAG README](../../products/signals/dags/inbox_ranking/README.md) for configuration and metric definitions.
diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.md
index 731e74e1476a..6f191df783de 100644
--- a/products/signals/dags/inbox_ranking/AGENTS.md
+++ b/products/signals/dags/inbox_ranking/AGENTS.md
@@ -32,10 +32,12 @@ Read `README.md` first for what the dataset is and how partitions behave. This f
- The shadow read grades a model that is not serving. It must stay read-only: nothing here writes a rank into a list response, and the serving decision is Part B.
- The grading unit is a complete reconstructed render window, not an event. Union absolute ranks inside a five-second bucket for the same viewer, session, scope and normalized tab, and require every rank through the maximum list size. State-section tabs normalize to `reports`. Reject missing sessions, incomplete windows and rank conflicts. This is an approximation without a render ID; keep the boundary and nearby-visit caveats in the README.
- A row may only use a score whose S3 `LastModified` predates its impression. Read the timestamp and bytes from the same GET response. Rewrites conservatively reduce historical coverage; never substitute the nominal training start time.
-- Grade every order on every reconstructed row, including unscored reports and their outcomes. The model ranks unscored rows last, tied on served rank. Coverage counts non-null scores; `positive_coverage` and `full_list_coverage` keep the limits visible. A group with no available scores is not graded.
+- The impression read is scoped to this deployment's app host. The dogfood project holds every region's telemetry, and the scoring pool needs this region's Postgres state, so an unscoped read grades lists whose rows can never hold a score. Keep the outcome read unscoped: a tenth of engagements carry no host, and attribution already requires a list that was kept.
+- Every grade is computed under both `GRADING_SCOPES`. `all_rows` keeps every reconstructed row with the unscored ones last in the model order; `scored_rows` narrows each list to the rows the group scored, so neither order is graded on a row the model could not place. Never fold the two into one line: the difference between them is the size of the coverage handicap. A list with no scored row is graded under neither, because every score there ties at minus infinity and the two orders draw level for free.
+- Coverage counts non-null scores; `positive_coverage`, `full_list_coverage` and `scored_list_share` keep the limits visible, and `score_coverage`, `score_pending_share` and `never_scored_share` sum to 1 so a thin read says whether it is waiting for the next training run. A group with no available scores is not graded.
- **Never present the heuristic line without the position-bias caveat.** Every logged outcome happened under the served order, so the heuristic is being graded on the clicks it caused. No re-ranking of logged clicks removes that; `positive_served_rank_mean` is how the effect stays visible. That line also pools every sort the inbox served, because the impression event carries the ranks but not the sort behind them, so never read the gap as a verdict on the inbox default.
- `open` and `action` are the outcomes because they name the heads whose scores order them. They are not those heads' labels: the graded relevance is list-scoped, the same viewer engaging inside the attribution window, while a head predicts a per-report outcome over days. Never present a shadow metric and an unseen AUC of the same name as one number. A new outcome means a head that predicts it, not a new relevance rule bolted onto the grader.
-- A missing champion partition/family/head falls back to its candidate rows, including shared-version days. Never replace existing champion rows. This convention is not a historical policy identity: missing champion metadata can also trigger it, so retain that caveat.
+- A missing champion partition/family/head falls back to its candidate rows, including shared-version days. Never replace existing champion rows, and keep `score_is_fallback` on the substituted rows so `champion_is_fallback` can say the line is not a pure champion read. This convention is not a historical policy identity: missing champion metadata can also trigger it, so retain that caveat.
- Coverage says whether a grade means anything. Every grade carries its own `score_coverage` over the rows that grade had, next to the run-wide `run_score_coverage`. Keep the two apart: per-head readability and per-family skips make one grade's coverage differ from the day's, so one number for both lets a thin grade read as a well-covered one. A day of unscored lists is not a day the model did badly.
## Invariants — do not break
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.md
index 2480ab1ce615..b62ab8853132 100644
--- a/products/signals/dags/inbox_ranking/README.md
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -179,20 +179,33 @@ Nothing here touches the prod bucket: the reader credential is read-only and the
```text
s3://<bucket>/<prefix>/
-└── inbox_ranking_shadow_eval/v1/dt=YYYY-MM-DD/ one row per (model, outcome, order)
+└── inbox_ranking_shadow_eval/v1/dt=YYYY-MM-DD/ one row per (model, outcome, order, scope)
```
Every other read of this model is offline. The holdout grades the recipe, the unseen read grades the model on reports it never saw, and neither compares the model against the list people actually get. That list is sorted without a model: the inbox asks for `priority,status,-updated_at` by default, a person can change the field and the direction, and the flat view re-sorts the merged per-state responses on the client with the same keys. (`-is_suggested_reviewer,status,-updated_at` in `products/signals/backend/views.py` is only the fallback for a caller that sends no ordering. The inbox always sends one, and reviewer scope is deliberately not a tiebreak there.) Nothing serves a model rank, so the model cannot be measured by what people clicked on it. What can be measured is the counterfactual, from data already flowing.
+- **Only this region's lists are read.** The dogfood project collects the inbox telemetry of every region, but the scoring pool reads report state from this region's Postgres, so a report another region served can never hold a score. The impression query is bounded to `properties.$host` = this deployment's app host (`urlparse(settings.SITE_URL).netloc`), which is the only thing on the event that says which app rendered the list. An impression with no host is dropped rather than assumed local. The outcome query is deliberately not scoped: about one engagement in ten carries no host, and attribution already requires the same person and report as a list that was kept.
- **Grade only complete reconstructed render windows.** An `Inbox reports impressed` event holds only newly shown rows. Union events by absolute rank for the same `distinct_id`, `$session_id`, `scope`, normalized `tab` and five-second UTC bucket, keeping the maximum `list_size`. State-section tabs normalize to `reports`, because the merged Reports view emits a different tab per section. Grade only windows with every rank from 1 through `list_size` and one distinct report per rank. Exclude missing sessions and conflicting assignments. Pagination inside a bucket extends the earlier list; an incomplete page in a later bucket is excluded. Exact repeats collapse only inside the bucket, so later visits remain separate. Without a render ID this is an approximation: a boundary can split one render, and nearby visits can combine. It does not recover every served list.
- **A report is relevant to a list when the same person opened it or acted on it within 30 minutes of seeing it there.** `open` and `action` name the heads whose scores order them, so a head is graded against the outcome it was fit toward. The relevance is a list-scoped proxy for that head's label, not the label itself: the `open` head predicts that anyone opens the report within three days, and `action` the same over seven, both counted per report rather than per viewer. A shadow NDCG and an unseen AUC of the same name therefore answer different questions. A window of hours would credit a list for a report the person came back to from a link. One engagement counts for one list, the last one the person saw the report in before it: changing a filter or a sort re-impresses the same rows at new ranks, so one person can hold several live lists holding the same report, and only one of them can have caused the open.
- **A list uses only scores available when each row was impressed.** Availability comes from S3 `LastModified` on the same GET response as the score data, not the training schedule. Delayed writes and backfills cannot backdate scores; a rewrite conservatively loses coverage before its new write time. Unscored reports keep their outcomes and rank last in the model order, tied on served rank. `score_coverage` is the scored share for each family, role and head; `positive_coverage` is the scored share of its engaged rows, and `full_list_coverage` is the share of served lists with every row scored. A group with no available scores is not graded.
- **Three orders are graded on exactly the same rows**: `model` (descending score of the head, ties broken on the served rank), `heuristic` (the rank the list served), and `random` (seeded permutations, reported with their spread — the chance line a gap has to clear). Each gets NDCG@5, NDCG@10 and MRR, averaged over the lists that had the outcome. A list with no outcome has no ideal ranking to normalize against, and a list of one is ordered identically by everything, so neither is graded.
+- **Each set of three is graded under two scopes, and a list with no scored row is graded under neither.** `grading_scope` is `all_rows` (every reconstructed row, unscored ones last in the model order) or `scored_rows` (the same lists narrowed to the rows the group scored). An unscored row sinks to the bottom of the model order while the served order keeps it where it was, so an outcome landing on one costs the model line and costs the heuristic line nothing — a coverage effect reading as a ranking one. `scored_rows` removes it by grading both orders on the rows the model could place, at the price of a shorter list under the NDCG cutoffs; `all_rows` keeps the older series. A list with no scored row at all ties every score at minus infinity, which hands the two lines a free draw, so it is excluded from both. **Read a promotion gate off `scored_rows`.**
+- **Coverage says what a line rests on and why the rest is missing.** `score_coverage`, `score_pending_share` (a score exists but arrived after the list was served — the birth-day residual) and `never_scored_share` (no score anywhere in the lookback) sum to 1 over the served rows. `scored_list_share` is the share of lists either scope can grade, and `full_list_coverage` the stricter share scored right through. `champion_is_fallback` is true when the group's scored rows include candidate rows standing in for a missing champion partition. It is group-level like the shares beside it, so it can warn on a line whose own graded rows are all real champion scores, and it never stays false on one that rests on a fallback.
- **Position bias is not corrected for, and cannot be.** Every recorded open happened under the served order, so a report the heuristic put first had more chance of being opened than one it put twentieth, whatever either order thinks of it. That flatters the heuristic line. `positive_served_rank_mean` reports how concentrated the outcomes were at the top of the served list, so the size of the effect sits next to the numbers it distorts. A gap that survives it is real; a narrow one is not evidence of anything.
- **The heuristic line pools every order that was served.** The impression event records the ranks a list showed but not the sort that produced them, so the default order, a person's chosen order and each client's own all average into one line. The gap therefore answers "would one global order beat the mix of orders people get", not "would it beat the inbox default". Nothing recovers the split later: with no sort on the event, a past partition cannot be separated after the fact.
- **A grade groups by family and role, not by version.** `model_versions` counts the score versions mixed across a day's lists. When a partition has no champion rows for a family and head, the read uses that partition's candidate rows as the champion fallback. This includes days when both share a version and preserves existing champion rows. Missing rows can also mean unreadable champion metadata, so the fallback is an evaluation convention, not proof of the historical champion pointer.
-`inbox_ranking_shadow_ranking_graded` carries each grade to the dashboard: `model_name`, `model_role`, `outcome`, `ranking_order`, the three metrics (plus `_std` on the random line), `positive_served_rank_mean`, the grade's own `score_coverage`, `positive_coverage` and `full_list_coverage`, and the run-level `served_lists`, `served_rows` and `run_score_coverage` on every row, so a thin line can be filtered out without a join. **Filter a single line on `score_coverage`, not on `run_score_coverage`**: a head is scored only on the partitions the training job found it readable on, and a family is skipped on a partition it has no metadata for, so the run figure is a union that a thin grade hides behind. The chart is a trends insight broken down on `ranking_order`. `inbox_ranking_shadow_run_completed` lands once per partition whether or not anything was graded, carrying the same run-level fields plus `grades`, so a day that graded nothing reads as a zero rather than the gap a failed run leaves.
+`inbox_ranking_shadow_ranking_graded` carries only `all_rows` grades, so existing charts do not mix scopes.
+`inbox_ranking_shadow_scored_ranking_graded` carries only `scored_rows` grades.
+Use the scored event for a promotion gate and break down the trends insight by `ranking_order`.
+Both events carry `model_name`, `model_role`, `outcome`, `ranking_order`, `grading_scope`, and the three metrics, plus `_std` for the random order.
+They also carry `positive_served_rank_mean`, `score_coverage`, `positive_coverage`, `full_list_coverage`, `scored_list_share`, `score_pending_share`, `never_scored_share`, and `champion_is_fallback`.
+Each event includes the run-level `served_lists`, `served_rows`, and `run_score_coverage` for filtering without a join.
+**Filter a single line on `score_coverage`, not on `run_score_coverage`.**
+Different heads and families can have different coverage, which the run-level union does not show.
+`inbox_ranking_shadow_run_completed` occurs once per partition, even if no grades exist.
+It carries the same run-level fields and `grades`, the total across both scopes.
+Thus, a completed run with no grades remains distinct from a failed run.
Like the dataset job, this one reads the dogfood project's ClickHouse, so it cannot run on a laptop against S3 copies the way the training job can. It reads; it changes nothing anyone sees. Whether a model rank is stamped onto the list response, behind a flag, is the serving decision this read exists to inform.
diff --git a/products/signals/dags/inbox_ranking/dataset/queries.py b/products/signals/dags/inbox_ranking/dataset/queries.py
index 737f09f670aa..204f1afb7b0d 100644
--- a/products/signals/dags/inbox_ranking/dataset/queries.py
+++ b/products/signals/dags/inbox_ranking/dataset/queries.py
@@ -10,6 +10,7 @@ day.
import uuid
import datetime
from typing import Any
+from urllib.parse import urlparse
import dagster
@@ -17,6 +18,7 @@ from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
from posthog.hogql.query import execute_hogql_query
+from posthog import settings
from posthog.clickhouse.client.connection import Workload
from posthog.cloud_utils import is_cloud
from posthog.models import Team
@@ -41,6 +43,18 @@ def labels_team() -> Team:
)
+def region_app_host() -> str:
+ """The app host this deployment serves the inbox on.
+
+ Team 2 collects the inbox telemetry of every region, and the label streams keep the other
+ regions' rows on purpose (label-only rows, README.md). A read that needs report state cannot:
+ the scoring pool (`training/unseen.py`) builds it from this region's Postgres, so a report
+ another region served can never hold a score. `$host` is the only property on those events
+ that says which app rendered the page.
+ """
+ return urlparse(settings.SITE_URL).netloc
+
+
def etl_workload() -> Workload:
"""Route ETL reads to the offline cluster replicas on Cloud so they never compete with
customer-facing queries; local and self-hosted deployments have no offline cluster."""
diff --git a/products/signals/dags/inbox_ranking/shadow/dag.py b/products/signals/dags/inbox_ranking/shadow/dag.py
index 930cc12d1012..5c574885c4a1 100644
--- a/products/signals/dags/inbox_ranking/shadow/dag.py
+++ b/products/signals/dags/inbox_ranking/shadow/dag.py
@@ -2,15 +2,18 @@
One asset on the daily partition:
- inbox_ranking_shadow_eval/v1/dt=D/ one row per (model, outcome, order) graded on D's lists
+ inbox_ranking_shadow_eval/v1/dt=D/ one row per (model, outcome, order, scope) on D's lists
The inbox still serves a fixed sort, and no list response carries a model rank, so the model
cannot be measured by what people clicked on it. What can be measured is the counterfactual: take
the lists that were actually served on D, take the score each report already had when its list was
served, and ask whether the model's order would have put the opened and acted-on reports higher
-than the served order did. `shadow/metrics.py` holds the ranking metrics and the position-bias
-caveat; this module reads the lists from the dogfood project, the scores from S3, and writes the
-grades back.
+than the served order did. `shadow/metrics.py` holds the ranking metrics, the grading scopes and
+the position-bias caveat; this module reads the lists from the dogfood project, the scores from
+S3, and writes the grades back.
+
+The impression read is scoped to this deployment's app host, for the reason `region_app_host`
+gives.
The read grades a model that is not serving, so nothing here changes what anyone sees.
"""
@@ -71,6 +74,7 @@ _GRADE_FIELDS: list[tuple[str, pa.DataType]] = [
("model_versions", pa.int32()),
("outcome", pa.string()),
("ranking_order", pa.string()),
+ ("grading_scope", pa.string()),
("lists", pa.int64()),
("reports", pa.int64()),
("mean_list_size", pa.float64()),
@@ -85,6 +89,10 @@ _GRADE_FIELDS: list[tuple[str, pa.DataType]] = [
("score_coverage", pa.float64()),
("positive_coverage", pa.float64()),
("full_list_coverage", pa.float64()),
+ ("scored_list_share", pa.float64()),
+ ("score_pending_share", pa.float64()),
+ ("never_scored_share", pa.float64()),
+ ("champion_is_fallback", pa.bool_()),
("served_rows", pa.int64()),
("served_lists", pa.int64()),
("run_score_coverage", pa.float64()),
@@ -96,9 +104,9 @@ GRADE_SCHEMA = pa.schema(_GRADE_FIELDS)
# exist. Partitions before the label epoch have no upstream to map to.
_SCORE_LOOKBACK_MAPPING = dagster.TimeWindowPartitionMapping(
start_offset=-settings.INBOX_RANKING_SHADOW_SCORE_LOOKBACK_DAYS,
- # dt=D's own scores are written the next morning, after every list of D was served, so they can
- # never be part of this read.
- end_offset=-1,
+ # dt=D's own scores are written the next morning, so they can never rank a list D served. The
+ # window still reaches them, for the reason `score_lookback_dates` gives.
+ end_offset=0,
allow_nonexistent_upstream_partitions=True,
)
@@ -128,12 +136,28 @@ def outcome_frame(rows: list[tuple[object, ...]]) -> pd.DataFrame:
return frame
+def score_lookback_dates(day: datetime.date) -> list[datetime.date]:
+ """The scores partitions a dt=`day` read covers, oldest first.
+
+ `day` itself is in the window although its scores are written the next morning and so can
+ never be available to a list it served. It is the only partition holding the score of a report
+ born on `day`, and `join_scores` needs that row to be present to call an impression of it
+ pending rather than never scored. The availability filter is what keeps the score itself out
+ of the ranking.
+ """
+ return [
+ day - datetime.timedelta(days=offset)
+ for offset in range(settings.INBOX_RANKING_SHADOW_SCORE_LOOKBACK_DAYS, -1, -1)
+ ]
+
+
def load_scores(client, bucket: str, prefix: str, dates: list[datetime.date]) -> pd.DataFrame:
"""Every graded head's scores from the partitions in `dates`, with the instant each one became
servable. Use LastModified from the same GET as the data, so rewrites and backfills cannot
backdate scores. A rewrite conservatively loses coverage before that write. Missing champion
rows for a partition/family/head fall back to its candidate, including shared-version days;
- this fallback does not establish which version historically held the champion pointer.
+ `score_is_fallback` marks those rows, and the fallback does not establish which version
+ historically held the champion pointer.
Missing partitions are ordinary: a day the training job did not run scored nobody."""
frames: list[pd.DataFrame] = []
for date in dates:
@@ -154,7 +178,7 @@ def load_scores(client, bucket: str, prefix: str, dates: list[datetime.date]) ->
# head, this read grades two of the seven, and the whole lookback window is held at once.
frame = with_model_names(table.to_pandas())[list(SCORE_JOIN_COLUMNS)]
frame = frame.loc[frame["head"].isin(OUTCOMES)].assign(
- available_at=pd.to_datetime(response["LastModified"], utc=True)
+ available_at=pd.to_datetime(response["LastModified"], utc=True), score_is_fallback=False
)
partition_columns = ["snapshot_date", "model_name", "head"]
champions = frame.loc[frame["model_role"] == "champion", partition_columns].drop_duplicates()
@@ -162,11 +186,13 @@ def load_scores(client, bucket: str, prefix: str, dates: list[datetime.date]) ->
champions, on=partition_columns, how="left", indicator=True
)
fallback = (
- candidates.loc[candidates["_merge"] == "left_only"].drop(columns="_merge").assign(model_role="champion")
+ candidates.loc[candidates["_merge"] == "left_only"]
+ .drop(columns="_merge")
+ .assign(model_role="champion", score_is_fallback=True)
)
frames.extend([frame, fallback])
if not frames:
- return pd.DataFrame(columns=[*SCORE_JOIN_COLUMNS, "available_at"])
+ return pd.DataFrame(columns=[*SCORE_JOIN_COLUMNS, "available_at", "score_is_fallback"])
return pd.concat(frames, ignore_index=True)
@@ -198,7 +224,10 @@ def grade_metadata(grades: list[RankingGrade]) -> dict[str, dagster.MetadataValu
for name, value in grade.metrics().items():
if value is None:
continue
- key = f"{grade.outcome}_{grade.model_name}_{grade.model_role}_{grade.ranking_order}_{name}"
+ key = (
+ f"{grade.outcome}_{grade.model_name}_{grade.model_role}_"
+ f"{grade.grading_scope}_{grade.ranking_order}_{name}"
+ )
metadata[key] = (
dagster.MetadataValue.int(value) if isinstance(value, int) else dagster.MetadataValue.float(value)
)
@@ -246,15 +275,7 @@ def inbox_ranking_shadow_eval(context: dagster.AssetExecutionContext) -> None:
)
lists = deduplicate_lists(with_outcomes(impressions, outcomes))
- scores = load_scores(
- client,
- bucket,
- prefix,
- [
- day - datetime.timedelta(days=offset)
- for offset in range(settings.INBOX_RANKING_SHADOW_SCORE_LOOKBACK_DAYS, 0, -1)
- ],
- )
+ scores = load_scores(client, bucket, prefix, score_lookback_dates(day))
joined = join_scores(lists, scores)
served_rows = len(lists)
coverage = score_coverage(served_rows, joined)
@@ -312,7 +333,8 @@ inbox_ranking_shadow_job = dagster.define_asset_job(
# Runs after the training job's own budget, so dt=D-1's scores are written before the day that
-# needs them next; this read itself only ever uses scores from before its own partition.
+# needs them next and dt=D's own object exists for the pending check; only the partitions before
+# dt=D can rank a list.
@dagster.schedule(
cron_schedule="30 9 * * *",
job=inbox_ranking_shadow_job,
diff --git a/products/signals/dags/inbox_ranking/shadow/metrics.py b/products/signals/dags/inbox_ranking/shadow/metrics.py
index 2b605dd085d3..fe2c1f452e35 100644
--- a/products/signals/dags/inbox_ranking/shadow/metrics.py
+++ b/products/signals/dags/inbox_ranking/shadow/metrics.py
@@ -13,6 +13,14 @@ Three orders are graded on each list, on exactly the same rows:
- `heuristic`, every row at the rank the list served, pooling all served sorts;
- `random`, seeded permutations, the chance line a gap has to clear.
+Each set of three is graded under two scopes, because a day's lists are mostly part-scored:
+
+- `all_rows`, every reconstructed row, with the unscored ones last in the model order;
+- `scored_rows`, the same lists narrowed to the rows the model had a score for.
+
+A list with no scored row at all is graded under neither. Every score there ties at minus
+infinity, the model order collapses onto the served order, and the two lines draw level for free.
+
Pure functions over frames; `shadow/dag.py` owns the ClickHouse, S3 and telemetry plumbing.
**Position bias is not corrected for.** Every recorded open happened under the served order, so a
@@ -27,8 +35,17 @@ tabs normalize to `reports` so merged sections meet. The maximum list_size must
count, ranks must be contiguous, and conflicting rank assignments are excluded. Pagination
inside the bucket extends the list; later incomplete pages are excluded. Without a render ID,
the bucket can split a render or combine nearby visits, so this is a conservative approximation.
-Repeat visits in different buckets stay separate. Unscored reports keep their outcomes and rank
-last in the model order, tied on served rank; a group with no available scores is not graded.
+Repeat visits in different buckets stay separate. Under `all_rows`, unscored reports keep their
+outcomes and rank last in the model order, tied on served rank; a group with no available scores
+is not graded.
+
+**A part-scored list handicaps the model order, and `scored_rows` is how that is read off.** An
+unscored row sinks to the bottom of the model order while the served order keeps it where it was,
+so an outcome that lands on one costs the model line and costs the heuristic line nothing. That is
+a coverage effect, not a ranking one. The `scored_rows` scope removes it by grading both orders on
+the rows the model could actually order, at the price of a shorter list under the NDCG cutoffs.
+`scored_list_share`, `score_pending_share` and `never_scored_share` say how much of the day each
+scope rests on.
**The graded outcome is a list-scoped proxy for the head it is named after, not that head's own
label.** Relevance here is "the person who saw this list engaged with this row inside the
@@ -58,6 +75,11 @@ MODEL_ORDER = "model"
HEURISTIC_ORDER = "heuristic"
RANDOM_ORDER = "random"
+# Which rows of a list a grade is computed over. Both require at least one scored row.
+ALL_ROWS_SCOPE = "all_rows"
+SCORED_ROWS_SCOPE = "scored_rows"
+GRADING_SCOPES: tuple[str, ...] = (ALL_ROWS_SCOPE, SCORED_ROWS_SCOPE)
+
NDCG_CUTOFFS: tuple[int, ...] = (5, 10)
# Seeded and fixed, so re-grading the same day reports the same chance line.
@@ -85,7 +107,7 @@ def outcome_column(outcome: str) -> str:
@frozen
class RankingGrade:
- """One model, one outcome, one order, over the lists that had that outcome.
+ """One model, one outcome, one order, one grading scope, over the lists that had that outcome.
`model_versions` counts the distinct model versions in the group: a report is scored on the day
it is born, so a day of lists is ranked by whichever version was current when each of its
@@ -98,6 +120,8 @@ class RankingGrade:
model_versions: int
outcome: str
ranking_order: str
+ # Which rows of each list the three orders were graded over; one of `GRADING_SCOPES`.
+ grading_scope: str
# Lists that had at least one of this outcome and at least MIN_LIST_SIZE scored rows. A list
# with no outcome has no ideal ranking to score against, so it is not graded.
lists: int
@@ -126,6 +150,19 @@ class RankingGrade:
# with their unscored rows removed, so the served ranks close up and the NDCG cutoffs bite on
# a shorter list than the one that was rendered.
full_list_coverage: float | None
+ # Share of served lists holding at least one scored row: the lists either scope can grade.
+ # `full_list_coverage` is the stricter share of those that were scored right through.
+ scored_list_share: float | None
+ # The two halves of what `score_coverage` is missing, so a thin read says which cause it has.
+ # Pending rows had a score written after the list was served, which is the birth-day residual
+ # the daily job cannot avoid. Never-scored rows had none anywhere in the lookback window: a
+ # report the pool never held. The three shares sum to 1.
+ score_pending_share: float | None
+ never_scored_share: float | None
+ # Whether any scored row the group held came from `load_scores` reading candidate rows in
+ # place of a missing champion. Group-level like the shares above, so it can warn on a line
+ # whose own graded rows are all real champion scores; it never stays False on one that is not.
+ champion_is_fallback: bool
def metrics(self) -> dict[str, int | float | None]:
return {
@@ -142,6 +179,9 @@ class RankingGrade:
"score_coverage": self.score_coverage,
"positive_coverage": self.positive_coverage,
"full_list_coverage": self.full_list_coverage,
+ "scored_list_share": self.scored_list_share,
+ "score_pending_share": self.score_pending_share,
+ "never_scored_share": self.never_scored_share,
}
def as_dict(self) -> dict[str, object]:
@@ -151,6 +191,8 @@ class RankingGrade:
"model_versions": self.model_versions,
"outcome": self.outcome,
"ranking_order": self.ranking_order,
+ "grading_scope": self.grading_scope,
+ "champion_is_fallback": self.champion_is_fallback,
**self.metrics(),
}
@@ -242,20 +284,26 @@ def join_scores(lists: pd.DataFrame, scores: pd.DataFrame) -> pd.DataFrame:
Unscored reports retain a null score and all their outcomes for each model group. The model
orders them last. A group with no score available for any served row produces no grades.
+
+ `score_pending` splits the unscored rows in two: True when a score for the row exists in the
+ lookback window but was written after the list was served, which is the birth-day residual the
+ daily job cannot avoid, and False when the window holds no score for the row at all.
"""
+ key = ["impression_id", "report_id", "model_name", "model_role", "head"]
if lists.empty or scores.empty:
- return lists.head(0).merge(scores.head(0), on="report_id", how="inner")
+ return lists.head(0).merge(scores.head(0), on="report_id", how="inner").assign(score_pending=False)
joined = lists.merge(scores, on="report_id", how="inner")
- joined = joined.loc[joined["available_at"] <= joined["impressed_at"]]
- matched = joined.sort_values(["snapshot_date", "available_at", "model_version"]).drop_duplicates(
- subset=["impression_id", "report_id", "model_name", "model_role", "head"], keep="last"
+ available = joined.loc[joined["available_at"] <= joined["impressed_at"]]
+ matched = available.sort_values(["snapshot_date", "available_at", "model_version"]).drop_duplicates(
+ subset=key, keep="last"
)
groups = scores[["model_name", "model_role", "head"]].drop_duplicates()
- return lists.merge(groups, how="cross").merge(
- matched.drop(columns=lists.columns.difference(["impression_id", "report_id"])),
- on=["impression_id", "report_id", "model_name", "model_role", "head"],
- how="left",
+ known = joined[key].drop_duplicates().assign(had_score=True)
+ side = known.merge(
+ matched.drop(columns=lists.columns.difference(["impression_id", "report_id"])), on=key, how="left"
)
+ rows = lists.merge(groups, how="cross").merge(side, on=key, how="left")
+ return rows.assign(score_pending=rows.pop("had_score").notna() & rows["score"].isna())
def score_coverage(served_rows: int, joined: pd.DataFrame) -> float | None:
@@ -272,11 +320,13 @@ def score_coverage(served_rows: int, joined: pd.DataFrame) -> float | None:
return float(len(covered) / served_rows)
-def served_lists(rows: pd.DataFrame, outcome: str) -> list[ServedList]:
- """The gradeable lists of one (model, head) group.
+def served_lists(rows: pd.DataFrame, outcome: str, *, scope: str = ALL_ROWS_SCOPE) -> list[ServedList]:
+ """The gradeable lists of one (model, head) group, under one grading scope.
A list with no outcome is dropped: NDCG has no ideal ranking to normalize against and the
- reciprocal rank has no hit, so every order would score the same nothing.
+ reciprocal rank has no hit, so every order would score the same nothing. A list with no scored
+ row is dropped under both scopes, and `scored_rows` keeps only the rows the group scored; the
+ module docstring says why.
Rows are put in served order first. Neither deterministic order cares which arrangement they
arrive in, because both sort on `served_rank`, but the seeded permutations are applied to the
@@ -286,7 +336,10 @@ def served_lists(rows: pd.DataFrame, outcome: str) -> list[ServedList]:
column = outcome_column(outcome)
lists: list[ServedList] = []
for _, group in rows.groupby("impression_id", sort=True):
- ordered = group.sort_values(["served_rank", "report_id"])
+ scored = group.loc[group["score"].notna()]
+ if scored.empty:
+ continue
+ ordered = (scored if scope == SCORED_ROWS_SCOPE else group).sort_values(["served_rank", "report_id"])
relevance = ordered[column].to_numpy(dtype=float)
if len(ordered) < MIN_LIST_SIZE or relevance.sum() == 0:
continue
@@ -363,25 +416,47 @@ def _positive_coverage(rows: pd.DataFrame, outcome: str, served_positives: int)
return float(rows.loc[rows["score"].notna(), outcome_column(outcome)].sum() / served_positives)
-def _full_list_coverage(rows: pd.DataFrame, served_per_list: pd.Series) -> float | None:
- """Share of served lists for which this group had a score for every row."""
+def _list_coverages(rows: pd.DataFrame, served_per_list: pd.Series) -> dict[str, float | None]:
+ """How much of each served list this group scored: the share it can grade at all, and the
+ stricter share it scored right through."""
per_list = (
rows.loc[rows["score"].notna()].groupby("impression_id").size().reindex(served_per_list.index, fill_value=0)
)
if per_list.empty:
- return None
- return float((per_list == served_per_list.reindex(per_list.index)).mean())
+ return {"scored_list_share": None, "full_list_coverage": None}
+ return {
+ "scored_list_share": float((per_list > 0).mean()),
+ "full_list_coverage": float((per_list == served_per_list.reindex(per_list.index)).mean()),
+ }
+
+
+def _unscored_shares(rows: pd.DataFrame, served_rows: int) -> dict[str, float | None]:
+ """The two reasons a served row carries no score, each as a share of the served rows.
+
+ With `score_coverage` these three sum to 1, so a thin read says whether it is waiting for the
+ next training run or looking at reports the pool never held.
+ """
+ if not served_rows:
+ return {"score_pending_share": None, "never_scored_share": None}
+ unscored = rows.loc[rows["score"].isna()].drop_duplicates(subset=["impression_id", "report_id"])
+ pending = int(unscored["score_pending"].sum())
+ return {
+ "score_pending_share": float(pending / served_rows),
+ "never_scored_share": float((len(unscored) - pending) / served_rows),
+ }
def grade_lists(joined: pd.DataFrame, *, served: pd.DataFrame) -> list[RankingGrade]:
- """Three grades per (model, outcome): the model's order, the served order, and chance.
+ """Three grades per (model, outcome, grading scope): the model's order, the served order, and
+ chance.
Grouping is by model family and role rather than version for the reason `RankingGrade` gives:
one day's lists are ranked by whichever version scored each report at its birth.
`model_role` is the snapshot role, not the current serving policy. Missing champion partitions
- use candidate scores as a fallback in `load_scores`. Coverage reports actual non-null scores
- per group. Unscored rows and their outcomes stay in every order; see the module docstring.
+ use candidate scores as a fallback in `load_scores`, and `champion_is_fallback` says when the
+ group holds one. Coverage reports actual non-null scores per group, and is a property of the
+ group rather than of the scope, so the same figures ride on both scopes of a group.
"""
grades: list[RankingGrade] = []
if joined.empty:
@@ -392,32 +467,40 @@ def grade_lists(joined: pd.DataFrame, *, served: pd.DataFrame) -> list[RankingGr
for (model_name, model_role, head), rows in joined.groupby(["model_name", "model_role", "head"], sort=True):
if head not in OUTCOMES:
continue
- if not rows["score"].notna().any():
- continue
- lists = served_lists(rows, str(head))
- if not lists:
+ scored = rows["score"].notna()
+ if not scored.any():
continue
- shared: dict[str, Any] = {
+ coverage: dict[str, Any] = {
"model_name": str(model_name),
"model_role": str(model_role),
"model_versions": int(rows["model_version"].nunique()),
"outcome": str(head),
- "lists": len(lists),
- "reports": sum(len(entry.relevance) for entry in lists),
- "mean_list_size": float(np.mean([len(entry.relevance) for entry in lists])),
- "positive_served_rank_mean": _positive_served_rank_mean(lists),
"score_coverage": score_coverage(served_rows, rows),
"positive_coverage": _positive_coverage(rows, str(head), served_positives[str(head)]),
- "full_list_coverage": _full_list_coverage(rows, served_per_list),
+ "champion_is_fallback": bool(rows.loc[scored, "score_is_fallback"].any()),
+ **_list_coverages(rows, served_per_list),
+ **_unscored_shares(rows, served_rows),
}
- grades.extend(
- _grade(shared, ranking_order=order, metrics=metrics)
- for order, metrics in (
- (MODEL_ORDER, _order_metrics(_model_ordered(lists))),
- (HEURISTIC_ORDER, _order_metrics(_heuristic_ordered(lists))),
- (RANDOM_ORDER, _random_metrics(lists)),
+ for scope in GRADING_SCOPES:
+ lists = served_lists(rows, str(head), scope=scope)
+ if not lists:
+ continue
+ shared: dict[str, Any] = {
+ **coverage,
+ "grading_scope": scope,
+ "lists": len(lists),
+ "reports": sum(len(entry.relevance) for entry in lists),
+ "mean_list_size": float(np.mean([len(entry.relevance) for entry in lists])),
+ "positive_served_rank_mean": _positive_served_rank_mean(lists),
+ }
+ grades.extend(
+ _grade(shared, ranking_order=order, metrics=metrics)
+ for order, metrics in (
+ (MODEL_ORDER, _order_metrics(_model_ordered(lists))),
+ (HEURISTIC_ORDER, _order_metrics(_heuristic_ordered(lists))),
+ (RANDOM_ORDER, _random_metrics(lists)),
+ )
)
- )
return grades
diff --git a/products/signals/dags/inbox_ranking/shadow/queries.py b/products/signals/dags/inbox_ranking/shadow/queries.py
index 653c48e9894f..a3a1bcda2931 100644
--- a/products/signals/dags/inbox_ranking/shadow/queries.py
+++ b/products/signals/dags/inbox_ranking/shadow/queries.py
@@ -2,7 +2,10 @@
Both queries read the dogfood project's client telemetry, the same stream the label assets read,
and both are bounded by explicit event-time windows so a partition is reproducible for any past
-day. An impression event contains only newly shown rows, not a complete ranked list. The query
+day. The impression query is also bounded to this deployment's app host, because the project holds
+every region's telemetry while only this region's reports can hold a score.
+
+An impression event contains only newly shown rows, not a complete ranked list. The query
retains session and list size so `deduplicate_lists` can union absolute ranks within each
(distinct_id, session_id, scope, normalized tab, five-second UTC bucket). State-section tabs
normalize to `reports`, because the merged Reports view emits a different tab per section.
@@ -20,7 +23,12 @@ from posthog.hogql.query import execute_hogql_query
from posthog.models import Team
-from products.signals.dags.inbox_ranking.dataset.queries import IMPRESSION_RANK_SQL, etl_workload, utc_bound
+from products.signals.dags.inbox_ranking.dataset.queries import (
+ IMPRESSION_RANK_SQL,
+ etl_workload,
+ region_app_host,
+ utc_bound,
+)
# The action types the `action` head counts as a positive (products/signals/dags/inbox_ranking/
# training/heads.py). Kept identical so both reads count the same event family. The head's seven-day
@@ -29,6 +37,7 @@ ACTION_TYPES = ("create_pr", "discuss")
_ACTION_TYPES_SQL = ", ".join(f"'{action_type}'" for action_type in ACTION_TYPES)
+
# One row per (impression event, report), before reconstruction in `deduplicate_lists`.
#
# The GROUP BY is a delivery guard, not an aggregate: analytics capture is at-least-once, so the
@@ -72,6 +81,10 @@ FROM (
ARRAY JOIN JSONExtractArrayRaw(properties, 'impressions') AS imp
WHERE event = 'Inbox reports impressed'
AND timestamp >= toDateTime({{window_start}}) AND timestamp < toDateTime({{window_end}})
+ -- Only this region's lists, for the reason `region_app_host` gives. An event without a host
+ -- is dropped rather than assumed local: either way the list cannot be graded, and the
+ -- conservative direction keeps the coverage figure honest.
+ AND toString(properties.$host) = {{app_host}}
)
GROUP BY impression_id, report_id
HAVING report_id != '' AND served_rank IS NOT NULL
@@ -80,6 +93,10 @@ HAVING report_id != '' AND served_rank IS NOT NULL
# One row per engagement, tagged with the head whose outcome it is. Attribution to a list happens
# in pandas: an engagement belongs to the impression of the same person and report that it follows
# inside the attribution window.
+#
+# Deliberately not scoped to the app host the impression query is scoped to. About one engagement
+# in ten carries no host, and attribution already requires the same person and report as a list
+# this read kept, so a host filter here would only drop outcomes of local lists.
OUTCOME_COLUMNS = ("report_id", "distinct_id", "timestamp", "outcome")
OUTCOMES_SQL = f"""
SELECT
@@ -114,6 +131,7 @@ def hogql_rows(
placeholders={
"window_start": ast.Constant(value=utc_bound(window_start)),
"window_end": ast.Constant(value=utc_bound(window_end)),
+ "app_host": ast.Constant(value=region_app_host()),
},
limit_context=LimitContext.SAVED_QUERY,
workload=etl_workload(),
diff --git a/products/signals/dags/inbox_ranking/shadow/telemetry.py b/products/signals/dags/inbox_ranking/shadow/telemetry.py
index 0cf5aca56c25..88eef7160827 100644
--- a/products/signals/dags/inbox_ranking/shadow/telemetry.py
+++ b/products/signals/dags/inbox_ranking/shadow/telemetry.py
@@ -1,19 +1,23 @@
"""The shadow read as events, next to the training and unseen series.
The Parquet is the durable record, but a daily object in S3 cannot be charted. One event per
-(model, outcome, order) makes the three lines a trends insight with a `ranking_order` breakdown,
-so "does the model order better than the list people get" is one chart. A run event rides
-alongside them, one per partition whether or not anything was graded, so an alert can tell a
-quiet day from a run that never finished. The capture plumbing is the training dag's, shared
-rather than duplicated.
+(model, outcome, order, grading scope) makes the three lines a trends insight with a
+`ranking_order` breakdown, so "does the model order better than the list people get" is one chart.
+The existing event contains only `all_rows` grades, so existing charts do not mix scopes.
+The scored event contains only `scored_rows` grades for comparisons on the same scored reports.
+
+A run event rides alongside them, one per partition whether or not anything was graded, so an
+alert can tell a quiet day from a run that never finished. The capture plumbing is the training
+dag's, shared rather than duplicated.
"""
from collections.abc import Sequence
-from products.signals.dags.inbox_ranking.shadow.metrics import RankingGrade
+from products.signals.dags.inbox_ranking.shadow.metrics import ALL_ROWS_SCOPE, RankingGrade
from products.signals.dags.inbox_ranking.training.telemetry import TrainingEvent
SHADOW_RANKING_GRADED_EVENT = "inbox_ranking_shadow_ranking_graded"
+SHADOW_SCORED_RANKING_GRADED_EVENT = "inbox_ranking_shadow_scored_ranking_graded"
SHADOW_RUN_COMPLETED_EVENT = "inbox_ranking_shadow_run_completed"
@@ -34,7 +38,8 @@ def shadow_grade_events(
The run-level counts ride on every grade event too, so a chart can filter on them without a
join. Each grade also carries its own `score_coverage`, which is the one to filter a single
- line on.
+ line on, and `scored_list_share`, `score_pending_share` and `never_scored_share` say how much
+ of the day that line rests on and why the rest is missing.
"""
reason = None
if not grades:
@@ -53,5 +58,13 @@ def shadow_grade_events(
}
return [
TrainingEvent(event=SHADOW_RUN_COMPLETED_EVENT, properties={**run, "grades": len(grades), "reason": reason}),
- *(TrainingEvent(event=SHADOW_RANKING_GRADED_EVENT, properties={**grade.as_dict(), **run}) for grade in grades),
+ *(
+ TrainingEvent(
+ event=SHADOW_RANKING_GRADED_EVENT
+ if grade.grading_scope == ALL_ROWS_SCOPE
+ else SHADOW_SCORED_RANKING_GRADED_EVENT,
+ properties={**grade.as_dict(), **run},
+ )
+ for grade in grades
+ ),
]
diff --git a/products/signals/dags/inbox_ranking/tests/test_shadow.py b/products/signals/dags/inbox_ranking/tests/test_shadow.py
index df2a255eedb1..1880a24291fb 100644
--- a/products/signals/dags/inbox_ranking/tests/test_shadow.py
+++ b/products/signals/dags/inbox_ranking/tests/test_shadow.py
@@ -10,13 +10,25 @@ import pyarrow as pa
import pyarrow.parquet as pq
from botocore.exceptions import ClientError
+from posthog import settings
+
from products.signals.dags.inbox_ranking.common import partition_object_key
-from products.signals.dags.inbox_ranking.shadow.dag import GRADE_SCHEMA, grade_rows, impression_frame, load_scores
+from products.signals.dags.inbox_ranking.dataset.queries import region_app_host
+from products.signals.dags.inbox_ranking.shadow.dag import (
+ GRADE_SCHEMA,
+ grade_rows,
+ impression_frame,
+ load_scores,
+ score_lookback_dates,
+)
from products.signals.dags.inbox_ranking.shadow.metrics import (
+ ALL_ROWS_SCOPE,
ATTRIBUTION_WINDOW,
HEURISTIC_ORDER,
MODEL_ORDER,
RANDOM_ORDER,
+ SCORED_ROWS_SCOPE,
+ RankingGrade,
deduplicate_lists,
grade_lists,
join_scores,
@@ -30,6 +42,7 @@ from products.signals.dags.inbox_ranking.shadow.queries import IMPRESSION_LISTS_
from products.signals.dags.inbox_ranking.shadow.telemetry import (
SHADOW_RANKING_GRADED_EVENT,
SHADOW_RUN_COMPLETED_EVENT,
+ SHADOW_SCORED_RANKING_GRADED_EVENT,
shadow_grade_events,
)
from products.signals.dags.inbox_ranking.training.unseen import UNSEEN_SCORES_TABLE
@@ -40,6 +53,11 @@ WINDOW_START = datetime.datetime(2026, 9, 10, tzinfo=datetime.UTC)
WINDOW_END = datetime.datetime(2026, 9, 11, tzinfo=datetime.UTC)
UUID_A = "0198c0e8-93c8-0000-38f5-a934eeb1b93e"
UUID_B = "0198c0e8-93c8-0000-38f5-a934eeb1b93f"
+UUID_C = "0198c0e8-93c8-0000-38f5-a934eeb1b940"
+
+
+def _by_order(grades: list[RankingGrade], *, scope: str = ALL_ROWS_SCOPE) -> dict[str, RankingGrade]:
+ return {grade.ranking_order: grade for grade in grades if grade.grading_scope == scope}
def _lists(rows: list[dict[str, object]]) -> pd.DataFrame:
@@ -65,6 +83,11 @@ def _served(impression_id: str, report_ids: list[str], *, at: datetime.datetime
]
+def _joined(served: pd.DataFrame, *, head: str = "open", **columns: object) -> pd.DataFrame:
+ """A frame shaped like `join_scores` output, for grades that need no availability logic."""
+ return served.assign(model_role="champion", head=head, score_pending=False, score_is_fallback=False, **columns)
+
+
def _scores(report_ids: list[str], scores: list[float], *, snapshot_date: datetime.date, head: str = "open"):
frame = pd.DataFrame(
{
@@ -77,7 +100,10 @@ def _scores(report_ids: list[str], scores: list[float], *, snapshot_date: dateti
"score": scores,
}
)
- return frame.assign(available_at=pd.Timestamp(snapshot_date, tz="UTC") + datetime.timedelta(days=1, hours=7))
+ return frame.assign(
+ available_at=pd.Timestamp(snapshot_date, tz="UTC") + datetime.timedelta(days=1, hours=7),
+ score_is_fallback=False,
+ )
def test_ndcg_rewards_putting_the_engaged_report_first():
@@ -213,12 +239,14 @@ def test_a_list_only_uses_scores_that_already_existed_when_it_was_served():
assert joined["report_id"].tolist() == [UUID_A, UUID_B]
assert joined["score"].iloc[0] == 0.4
assert pd.isna(joined["score"].iloc[1])
+ # The unscored row is pending, not unknown: its score exists and lands after the impression.
+ assert joined["score_pending"].tolist() == [False, True]
assert score_coverage(len(rows), joined) == 0.5
def test_lists_without_an_outcome_or_a_choice_to_make_are_not_graded():
rows = _lists([*_served("no_outcome", [UUID_A, UUID_B]), *_served("single", [UUID_A])])
- graded = rows.assign(outcome_open=[False, False, True], score=0.5, head="open")
+ graded = _joined(rows, outcome_open=[False, False, True], score=0.5)
assert served_lists(graded, "open") == []
@@ -228,15 +256,9 @@ def test_the_model_order_is_graded_against_the_served_order_and_chance():
served = _lists(_served("first", [UUID_A, UUID_B, UUID_B + "-c", UUID_B + "-d"])).assign(
outcome_open=[False, False, False, True], outcome_action=False
)
- joined = served.assign(
- model_name="tabular_xgb",
- model_version="2026-09-09",
- model_role="champion",
- head="open",
- score=[0.1, 0.2, 0.3, 0.9],
- )
+ joined = _joined(served, model_name="tabular_xgb", model_version="2026-09-09", score=[0.1, 0.2, 0.3, 0.9])
- grades = {grade.ranking_order: grade for grade in grade_lists(joined, served=served)}
+ grades = _by_order(grade_lists(joined, served=served))
ndcg_5 = {order: grade.ndcg_5 or 0.0 for order, grade in grades.items()}
assert grades[MODEL_ORDER].mrr == 1.0
@@ -249,6 +271,8 @@ def test_the_model_order_is_graded_against_the_served_order_and_chance():
# The served rank of the opened report, which is how much position bias these numbers carry.
assert grades[MODEL_ORDER].positive_served_rank_mean == 4.0
assert {grade.outcome for grade in grade_lists(joined, served=served)} == {"open"}
+ # Every row is scored, so the two scopes grade the same rows and report the same numbers.
+ assert _by_order(grade_lists(joined, served=served), scope=SCORED_ROWS_SCOPE)[MODEL_ORDER].mrr == 1.0
def test_a_grade_carries_its_own_score_coverage_not_the_run_s():
@@ -257,9 +281,9 @@ def test_a_grade_carries_its_own_score_coverage_not_the_run_s():
served = _lists(_served("first", [UUID_A, UUID_B, UUID_B + "-c", UUID_B + "-d"])).assign(
outcome_open=[True, False, False, False], outcome_action=[True, False, False, False]
)
- scored = {"model_name": "tabular_xgb", "model_version": "2026-09-09", "model_role": "champion", "score": 0.5}
+ scored = {"model_name": "tabular_xgb", "model_version": "2026-09-09", "score": 0.5}
joined = pd.concat(
- [served.assign(head="open", **scored), served.head(2).assign(head="action", **scored)],
+ [_joined(served, head="open", **scored), _joined(served.head(2), head="action", **scored)],
ignore_index=True,
)
@@ -278,55 +302,93 @@ def test_the_chance_line_does_not_move_when_the_rows_arrive_in_another_order():
served = _lists(_served("first", [UUID_A, UUID_B, UUID_B + "-c", UUID_B + "-d"])).assign(
outcome_open=[False, True, False, True], outcome_action=False
)
- joined = served.assign(
- model_name="tabular_xgb",
- model_version="2026-09-09",
- model_role="champion",
- head="open",
- score=[0.1, 0.2, 0.3, 0.9],
- )
+ joined = _joined(served, model_name="tabular_xgb", model_version="2026-09-09", score=[0.1, 0.2, 0.3, 0.9])
def chance(frame: pd.DataFrame) -> tuple:
- grade = next(g for g in grade_lists(frame, served=served) if g.ranking_order == RANDOM_ORDER)
+ grade = _by_order(grade_lists(frame, served=served))[RANDOM_ORDER]
return (grade.ndcg_5, grade.ndcg_10, grade.mrr)
assert chance(joined.iloc[[3, 0, 2, 1]]) == chance(joined)
-def test_a_grade_keeps_unscored_positives_and_ranks_them_last():
+def test_a_list_with_no_scored_row_is_not_graded_and_its_neighbour_keeps_its_unscored_rows():
+ # Every score in the second list ties at minus infinity, so the model order collapses onto the
+ # served one and the two lines would draw level there for free.
served = _lists(
[
- *_served("kept", [UUID_A, UUID_B, UUID_B + "-c"]),
- *_served("dropped", [UUID_B + "-d", UUID_B + "-e"], at=SERVED_AT + datetime.timedelta(hours=2)),
+ *_served("kept", [UUID_A, UUID_B, UUID_C]),
+ *_served("unscored", [UUID_C + "-d", UUID_C + "-e"], at=SERVED_AT + datetime.timedelta(hours=2)),
]
).assign(outcome_open=[True, False, False, True, False], outcome_action=False)
joined = join_scores(served, _scores([UUID_A, UUID_B], [0.9, 0.1], snapshot_date=DAY - datetime.timedelta(days=1)))
- grade = next(grade for grade in grade_lists(joined, served=served) if grade.ranking_order == MODEL_ORDER)
+ grade = _by_order(grade_lists(joined, served=served))[MODEL_ORDER]
- assert grade.lists == 2
- assert grade.reports == 5
+ assert grade.lists == 1
+ assert grade.reports == 3
assert grade.positive_coverage == 0.5
assert grade.full_list_coverage == 0.0
+ assert grade.scored_list_share == 0.5
assert grade.score_coverage == 0.4
+ assert grade.never_scored_share == pytest.approx(0.6)
assert grade.mrr == 1.0
- served["outcome_open"] = [False, False, True, True, False]
- joined = join_scores(served, _scores([UUID_A, UUID_B], [0.9, 0.1], snapshot_date=DAY - datetime.timedelta(days=1)))
- grade = next(grade for grade in grade_lists(joined, served=served) if grade.ranking_order == MODEL_ORDER)
- assert grade.mrr == pytest.approx((1 / 3 + 1) / 2)
- assert grade.positive_coverage == 0.0
+
+def test_a_part_scored_list_no_longer_costs_the_model_order_what_coverage_costs_it():
+ # The only opened report is one no score existed for. It sinks to the bottom of the model order
+ # and stays first in the served one, so a coverage gap reads as a ranking loss.
+ served = _lists(_served("first", [UUID_C, UUID_A, UUID_B])).assign(
+ outcome_open=[True, False, False], outcome_action=False
+ )
+ joined = join_scores(served, _scores([UUID_A, UUID_B], [0.1, 0.9], snapshot_date=DAY - datetime.timedelta(days=1)))
+
+ all_rows = _by_order(grade_lists(joined, served=served))
+ scored_rows = _by_order(grade_lists(joined, served=served), scope=SCORED_ROWS_SCOPE)
+
+ assert all_rows[MODEL_ORDER].mrr == pytest.approx(1 / 3)
+ assert all_rows[HEURISTIC_ORDER].mrr == 1.0
+ # On the rows the model could place there is no outcome left, so the list leaves the scored
+ # read instead of scoring the model down for a row it never saw.
+ assert scored_rows == {}
+ assert all_rows[MODEL_ORDER].never_scored_share == pytest.approx(1 / 3)
+
+
+def test_a_grade_says_why_the_rows_it_lacks_are_missing():
+ # score_coverage alone cannot separate "the training job has not scored it yet" from "the pool
+ # never held it", and only the first repairs itself overnight.
+ served = _lists(_served("first", [UUID_A, UUID_B, UUID_C])).assign(
+ outcome_open=[True, False, False], outcome_action=False
+ )
+ scores = pd.concat(
+ [
+ _scores([UUID_A], [0.9], snapshot_date=DAY - datetime.timedelta(days=1)).assign(score_is_fallback=True),
+ # Born on the day it was impressed: its score is written the next morning.
+ _scores([UUID_B], [0.4], snapshot_date=DAY),
+ ],
+ ignore_index=True,
+ )
+
+ grade = _by_order(grade_lists(join_scores(served, scores), served=served))[MODEL_ORDER]
+
+ assert grade.score_coverage == pytest.approx(1 / 3)
+ assert grade.score_pending_share == pytest.approx(1 / 3)
+ assert grade.never_scored_share == pytest.approx(1 / 3)
+ assert grade.scored_list_share == 1.0
+ assert grade.full_list_coverage == 0.0
+ # This champion line is candidate rows standing in for a missing champion partition.
+ assert grade.champion_is_fallback is True
+ # One scored row cannot separate two orders, so the scored read has nothing to say about it.
+ assert _by_order(grade_lists(join_scores(served, scores), served=served), scope=SCORED_ROWS_SCOPE) == {}
def test_a_grade_carries_the_versions_that_scored_the_day():
served = _lists([*_served("first", [UUID_A, UUID_B]), *_served("second", [UUID_A, UUID_B])]).assign(
outcome_open=[True, False, True, False], outcome_action=False
)
- joined = served.assign(
+ joined = _joined(
+ served,
model_name="tabular_xgb",
model_version=["2026-09-01", "2026-09-02", "2026-09-01", "2026-09-02"],
- model_role="champion",
- head="open",
score=0.5,
)
@@ -342,7 +404,9 @@ class TestShadowQueries(ClickhouseTestMixin, BaseTest):
at=SERVED_AT,
tab: str = "all",
list_size: int | None = None,
+ host: str | None = None,
) -> None:
+ host = region_app_host() if host is None else host
_create_event(
team=self.team,
event="Inbox reports impressed",
@@ -351,6 +415,7 @@ class TestShadowQueries(ClickhouseTestMixin, BaseTest):
properties={
"tab": tab,
"scope": "project",
+ "$host": host,
"impressions": impressions,
"$session_id": "0198c0e8-93c8-7000-8000-a934eeb1b940",
"list_size": len(impressions) if list_size is None else list_size,
@@ -369,6 +434,9 @@ class TestShadowQueries(ClickhouseTestMixin, BaseTest):
def test_one_impression_event_is_one_ranked_list(self):
self._impress([{"report_id": UUID_A, "rank": 1}, {"report_id": UUID_B, "rank": 2}])
self._impress([{"report_id": UUID_A, "rank": 1}], distinct_id="user-2")
+ # The dogfood project holds every region's telemetry, and no score can ever exist for a
+ # report another region served, so its lists would only be graded on missing scores.
+ self._impress([{"report_id": UUID_C, "rank": 1}], distinct_id="user-3", host="other.posthog.com")
rows = deduplicate_lists(impression_frame(self._rows(IMPRESSION_LISTS_SQL))).to_numpy().tolist()
@@ -376,6 +444,7 @@ class TestShadowQueries(ClickhouseTestMixin, BaseTest):
assert len(lists) == 2
by_report = {(row[0], row[5]): row[6] for row in rows}
assert sorted(by_report.values()) == [1, 1, 2]
+ assert UUID_C not in {row[5] for row in rows}
def test_merged_sections_reconstruct_the_render_and_exclude_an_incomplete_visit(self) -> None:
self._impress([{"report_id": UUID_A, "rank": 1}], tab="monitoring", list_size=2)
@@ -439,6 +508,16 @@ def _scores_object(frame: pd.DataFrame) -> bytes:
return sink.getvalue()
+def test_the_score_window_reaches_the_partition_day_a_birth_day_score_lands_in():
+ dates = score_lookback_dates(DAY)
+
+ # dt=D holds the scores of the reports born on D, so a window stopping at D-1 sees no score at
+ # all for a report impressed on its birth day and reads it as one the pool never held.
+ assert dates[-1] == DAY
+ assert dates[0] == DAY - datetime.timedelta(days=settings.INBOX_RANKING_SHADOW_SCORE_LOOKBACK_DAYS)
+ assert len(dates) == len(set(dates)) == settings.INBOX_RANKING_SHADOW_SCORE_LOOKBACK_DAYS + 1
+
+
def test_load_scores_reads_the_window_and_names_the_family_of_older_objects():
old_day, new_day = DAY - datetime.timedelta(days=2), DAY - datetime.timedelta(days=1)
# An object written before `model_name` existed holds tabular rows and must not read as null.
@@ -488,19 +567,15 @@ def test_missing_champion_partition_uses_candidate_without_replacing_existing_ch
champion = scores.loc[scores["model_role"] == "champion"]
assert champion["report_id"].tolist() == [UUID_A, UUID_B]
assert champion["score"].tolist() == [0.3, 0.7]
+ # Only the stand-in says so, so a grade can report that it is not a pure champion read.
+ assert champion["score_is_fallback"].tolist() == [True, False]
def test_a_day_that_graded_nothing_still_reports_a_run():
# A day whose lists had no score available at impression time grades nothing, and without a
# run event that is byte-identical to a run that crashed before capturing anything.
served = _lists(_served("first", [UUID_A, UUID_B])).assign(outcome_open=[True, False], outcome_action=False)
- joined = served.assign(
- model_name="tabular_xgb",
- model_version="2026-09-09",
- model_role="champion",
- head="open",
- score=[0.9, 0.1],
- )
+ joined = _joined(served, model_name="tabular_xgb", model_version="2026-09-09", score=[0.9, 0.1])
empty = shadow_grade_events(run_id="run-1", served_rows=12, served_lists=3, run_score_coverage=0.0, grades=[])
graded = shadow_grade_events(
@@ -520,21 +595,26 @@ def test_a_day_that_graded_nothing_still_reports_a_run():
"grades": 0,
"reason": "no_available_scores",
}
- # The run event rides alongside the three orders, never instead of them.
- assert [event.event for event in graded] == [SHADOW_RUN_COMPLETED_EVENT, *[SHADOW_RANKING_GRADED_EVENT] * 3]
+ assert [event.event for event in graded] == [
+ SHADOW_RUN_COMPLETED_EVENT,
+ *[SHADOW_RANKING_GRADED_EVENT] * 3,
+ *[SHADOW_SCORED_RANKING_GRADED_EVENT] * 3,
+ ]
+ assert graded[0].properties["grades"] == 6
+ for event_name, scope in (
+ (SHADOW_RANKING_GRADED_EVENT, ALL_ROWS_SCOPE),
+ (SHADOW_SCORED_RANKING_GRADED_EVENT, SCORED_ROWS_SCOPE),
+ ):
+ events = [event for event in graded if event.event == event_name]
+ assert {event.properties["grading_scope"] for event in events} == {scope}
+ assert {event.properties["ranking_order"] for event in events} == {MODEL_ORDER, HEURISTIC_ORDER, RANDOM_ORDER}
def test_grade_rows_match_the_parquet_schema_exactly():
# pa.Table.from_pylist drops keys the schema does not name, so a grade field added without a
# column would vanish from the object without failing anything.
served = _lists(_served("first", [UUID_A, UUID_B])).assign(outcome_open=[True, False], outcome_action=False)
- joined = served.assign(
- model_name="tabular_xgb",
- model_version="2026-09-09",
- model_role="champion",
- head="open",
- score=[0.9, 0.1],
- )
+ joined = _joined(served, model_name="tabular_xgb", model_version="2026-09-09", score=[0.9, 0.1])
graded = grade_rows(
grade_lists(joined, served=served),
partition_key=DAY.isoformat(),
@@ -544,4 +624,4 @@ def test_grade_rows_match_the_parquet_schema_exactly():
)
assert set(graded[0]) == set(GRADE_SCHEMA.names)
- assert pa.Table.from_pylist(graded, schema=GRADE_SCHEMA).num_rows == 3
+ assert pa.Table.from_pylist(graded, schema=GRADE_SCHEMA).num_rows == 6