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): shadow-evaluate the inbox ranking model against the served order (#101550)

posthog[bot]970512ca2732
diff --git a/docs/internal/inbox-ranking-shadow-evaluation.md b/docs/internal/inbox-ranking-shadow-evaluation.md
new file mode 100644
index 000000000000..9c1e53988c9f
--- /dev/null
+++ b/docs/internal/inbox-ranking-shadow-evaluation.md
@@ -0,0 +1,20 @@
+# Inbox ranking shadow evaluation
+
+The shadow job compares model, served and seeded random orders without changing what the inbox serves.
+The served baseline pools all selected sorts because impression events do not record the sort.
+Logged outcomes have position bias, so the comparison is not a causal estimate of a model rollout.
+
+The read reconstructs complete lists from newly shown impression rows in five-second UTC windows.
+It groups by viewer, session, scope and normalized tab, combines merged state sections and pagination by absolute rank, and requires every rank through the maximum list size.
+Incomplete or conflicting windows are excluded; window boundaries can lose valid observations, and nearby visits can combine without a render ID.
+Later visits outside the window remain separate.
+
+Scores become available at the S3 object's `LastModified`, read with the score bytes.
+Unscored reports retain their outcomes and go last in the model order.
+Coverage is computed separately for each family, role and head.
+A missing champion partition uses candidate scores as an explicit fallback, not as evidence of the historical champion pointer.
+
+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`.
+See the [ranking DAG README](../../products/signals/dags/inbox_ranking/README.md) for configuration and metric definitions.
diff --git a/posthog/dags/locations/signals.py b/posthog/dags/locations/signals.py
index 0112e3d4f9cf..11f78abdd8c7 100644
--- a/posthog/dags/locations/signals.py
+++ b/posthog/dags/locations/signals.py
@@ -2,6 +2,7 @@ import dagster
from products.signals.dags.inbox_ranking.common import is_inbox_ranking_registered
from products.signals.dags.inbox_ranking.dataset import dag as inbox_ranking_dataset
+from products.signals.dags.inbox_ranking.shadow import dag as inbox_ranking_shadow
from products.signals.dags.inbox_ranking.training import dag as inbox_ranking_training
from . import loggers, resources
@@ -21,11 +22,17 @@ if is_inbox_ranking_registered():
inbox_ranking_training.inbox_ranking_model_champion,
inbox_ranking_training.inbox_ranking_unseen_scores,
inbox_ranking_training.inbox_ranking_unseen_graded,
+ inbox_ranking_shadow.inbox_ranking_shadow_eval,
+ ],
+ jobs=[
+ inbox_ranking_dataset.inbox_ranking_dataset_job,
+ inbox_ranking_training.inbox_ranking_training_job,
+ inbox_ranking_shadow.inbox_ranking_shadow_job,
],
- jobs=[inbox_ranking_dataset.inbox_ranking_dataset_job, inbox_ranking_training.inbox_ranking_training_job],
schedules=[
inbox_ranking_dataset.inbox_ranking_dataset_schedule,
inbox_ranking_training.inbox_ranking_training_schedule,
+ inbox_ranking_shadow.inbox_ranking_shadow_schedule,
],
loggers=loggers,
resources=resources,
diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.py
index 2279f2f078ce..c77078287bd5 100644
--- a/posthog/settings/object_storage.py
+++ b/posthog/settings/object_storage.py
@@ -107,6 +107,10 @@ INBOX_RANKING_TRAINING_LOOKBACK_DAYS = get_from_env("INBOX_RANKING_TRAINING_LOOK
INBOX_RANKING_TRAINING_HOLDOUT_DAYS = get_from_env("INBOX_RANKING_TRAINING_HOLDOUT_DAYS", 7, type_cast=int)
INBOX_RANKING_AUTO_PROMOTE = get_from_env("INBOX_RANKING_AUTO_PROMOTE", False, type_cast=str_to_bool)
INBOX_RANKING_PROMOTION_MIN_DAYS = get_from_env("INBOX_RANKING_PROMOTION_MIN_DAYS", 3, type_cast=int)
+# Shadow dag (products/signals/dags/inbox_ranking/shadow): how many daily scores partitions back
+# the read looks for a score that already existed when a list was served. A report is scored on
+# the day it is born, so this bounds how old a report can be and still be graded.
+INBOX_RANKING_SHADOW_SCORE_LOOKBACK_DAYS = get_from_env("INBOX_RANKING_SHADOW_SCORE_LOOKBACK_DAYS", 60, type_cast=int)
# Identity matching scratch storage (products/growth `identity_matching_job`). The job writes
# per-run Parquet objects via ClickHouse `INSERT INTO FUNCTION s3(...)` and the read API globs
diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.md
index 1b9625723aa2..5fa9a2d7ac91 100644
--- a/products/signals/dags/inbox_ranking/AGENTS.md
+++ b/products/signals/dags/inbox_ranking/AGENTS.md
@@ -24,6 +24,17 @@ Read `README.md` first for what the dataset is and how partitions behave. This f
- The champion is compared to a candidate on the candidate's holdout, through the champion's `<head>.holdout.ubj` (the train-only fit). Keep writing that file: without it the gate falls back to the champion's stored AUC, which was measured on a different set of reports.
- The example builder reads labels aligned to the state spine (`assemble_snapshot`): no label row means all-zero labels, not "absent". It drops rows whose `features_observed_at` is a backfill (`STATE_LAG_LIMIT`) and, for status-derived heads, rows that fail `label_provenance_ok`.
+## Shadow dag specifics
+
+- 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.
+- **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.
+- 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
- `dt=` partitions are **immutable snapshots** with deterministic object keys; the only mutation ever applied is an idempotent re-run of the same partition. The exception is `inbox_signal_embeddings`, an emission log whose partition holds only that day's inserts — see the README's signal-grain section before touching it. Its re-run must stay **additive** (union with the existing object): the source drops rows it already archived, so a plain overwrite destroys history that exists nowhere else.
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.md
index 431481661d59..f5836d11f109 100644
--- a/products/signals/dags/inbox_ranking/README.md
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -1,6 +1,6 @@
# Inbox ranking Dagster dags
-Dagster jobs for the Self-driving Inbox report-ranking model: the **dataset** dag (daily snapshots) and the **training** dag (daily per-head XGBoost candidates + champion pointer), sibling subpackages sharing `common.py`.
+Dagster jobs for the Self-driving Inbox report-ranking model: the **dataset** dag (daily snapshots), the **training** dag (daily per-head XGBoost candidates + champion pointer) and the **shadow** dag (the model's order against the order the inbox serves), sibling subpackages sharing `common.py`.
```text
inbox_ranking/
@@ -14,6 +14,11 @@ inbox_ranking/
│ ├── heads.py # the v0 outcome heads
│ ├── train.py # per-head XGBoost fit + holdout/null metrics
│ └── promotion.py # the champion promotion rule
+├── shadow/
+│ ├── dag.py # the shadow eval asset + job + schedule
+│ ├── metrics.py # served lists, outcome attribution, NDCG/MRR over three orders
+│ ├── queries.py # HogQL for the served lists and the engagements that followed
+│ └── telemetry.py # the shadow grade as an event
└── tests/
```
@@ -148,30 +153,54 @@ The training job is S3-only, so it can run on a laptop against copies of the pro
Nothing here touches the prod bucket: the reader credential is read-only and the dag writes only to the local bucket.
-### Configuration
+## The shadow dag
-| Setting | Default | Meaning |
-| -------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `INBOX_RANKING_DATASET_S3_BUCKET` | unset | Destination bucket. Unset on Cloud makes every asset log and skip, so the dag can deploy before the bucket exists. Unset elsewhere falls back to the deployment's object-storage service (SeaweedFS in dev and CI). |
-| `INBOX_RANKING_DATASET_S3_PREFIX` | `inbox_ranking` | Key prefix under the bucket. |
-| `INBOX_RANKING_TRAINING_LOOKBACK_DAYS` | `60` | How many daily snapshots back the training examples reach. |
-| `INBOX_RANKING_TRAINING_HOLDOUT_DAYS` | `7` | Trailing days of reports that grade a candidate. |
-| `INBOX_RANKING_AUTO_PROMOTE` | `false` | Whether a winning candidate rewrites `champion.json`; off, the decision is only logged. |
-| `INBOX_RANKING_PROMOTION_MIN_DAYS` | `3` | Minimum age of the champion before another promotion. |
+`inbox_ranking_shadow_job` runs daily at 09:30 UTC on the same partition definition (gated like the other two) and writes one object:
+
+```text
+s3://<bucket>/<prefix>/
+└── inbox_ranking_shadow_eval/v1/dt=YYYY-MM-DD/ one row per (model, outcome, order)
+```
+
+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.
+
+- **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.
+- **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.
+
+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.
+
+## Configuration
+
+| Setting | Default | Meaning |
+| ------------------------------------------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `INBOX_RANKING_DATASET_S3_BUCKET` | unset | Destination bucket. Unset on Cloud makes every asset log and skip, so the dag can deploy before the bucket exists. Unset elsewhere falls back to the deployment's object-storage service (SeaweedFS in dev and CI). |
+| `INBOX_RANKING_DATASET_S3_PREFIX` | `inbox_ranking` | Key prefix under the bucket. |
+| `INBOX_RANKING_TRAINING_LOOKBACK_DAYS` | `60` | How many daily snapshots back the training examples reach. |
+| `INBOX_RANKING_TRAINING_HOLDOUT_DAYS` | `7` | Trailing days of reports that grade a candidate. |
+| `INBOX_RANKING_AUTO_PROMOTE` | `false` | Whether a winning candidate rewrites `champion.json`; off, the decision is only logged. |
+| `INBOX_RANKING_PROMOTION_MIN_DAYS` | `3` | Minimum age of the champion before another promotion. |
+| `INBOX_RANKING_SHADOW_SCORE_LOOKBACK_DAYS` | `60` | How many scores partitions back the shadow read looks for a score that already existed when a list was served. |
Writes use boto3: ambient AWS config (the node role) when the dedicated bucket is set, the `OBJECT_STORAGE_*` endpoint and credentials otherwise. Readers (project-level warehouse tables, model training) use a separate read-only credential provisioned with the bucket.
-### ClickHouse posture
+## ClickHouse posture
All reads route to the offline cluster replicas on Cloud (`etl_workload()`), carry the dagster run in `log_comment`, and the cross-team embeddings scan runs under explicit time/memory/spill guards (see `queries.py` for why that scan has no `team_id` sort-key prefix and why that is acceptable).
-### Operating it
+## Operating it
- Backfill any day range from the Dagster UI; partitions start 2026-04-01 (the label epoch). Every asset sits in the `inbox_ranking_etl` pool so concurrent partitions don't each start their own fleet-wide embeddings scan — the pool's limit is a Dagster deployment setting, provisioned with the bucket.
- Failures alert `#alerts-self-driving` (owner `team-self-driving`); assets retry twice with a 60s delay before failing a run. A UI-launched materialization runs under Dagster's implicit `__ASSET_JOB`, which carries no owner tag, so alert routing falls back to matching the `inbox_report_`, `inbox_signal_`, and `inbox_ranking_` asset-name prefixes.
-- The job is capped at 3h via `dagster/max_runtime` — the seven label streams run sequentially, each allowed up to 600s, and the join and S3 writes come after them.
+- Runtime budgets are per job (`dagster/max_runtime`): 3h for the dataset and training jobs, 1h for the shadow job. The 3h figure is what the dataset needs — its seven label streams run sequentially, each allowed up to 600s, and the join and S3 writes come after them. The shadow read is one day of two event families plus the scores objects in its lookback, so it gets an hour.
-### Deletion and retention
+## Deletion and retention
Partitions are immutable history, so a report deleted later keeps its rows (and vector) in partitions written before the deletion.
The embedding tombstone nulls the vector in every partition built after it, and `status='deleted'` flows through state from then on.
diff --git a/products/signals/dags/inbox_ranking/dataset/queries.py b/products/signals/dags/inbox_ranking/dataset/queries.py
index 721be0d41971..fee2dc89e11b 100644
--- a/products/signals/dags/inbox_ranking/dataset/queries.py
+++ b/products/signals/dags/inbox_ranking/dataset/queries.py
@@ -254,7 +254,7 @@ IMPRESSIONS_COLUMNS = (
# is 1-based, so anything below 1 is malformed; anything above int32 would raise on the Parquet
# conversion and fail the whole fleet-wide labels asset. Both are nulled out, and the impression
# still counts toward the impression/user counts.
-_IMPRESSION_RANK = (
+IMPRESSION_RANK_SQL = (
"if(JSONExtractInt(imp, 'rank') >= 1 AND JSONExtractInt(imp, 'rank') <= 2147483647, "
"JSONExtractInt(imp, 'rank'), NULL)"
)
@@ -264,8 +264,8 @@ SELECT
min(timestamp) AS first_impressed_at,
count() AS impression_unit_count,
uniq(distinct_id) AS impressed_user_count,
- argMinIf({_IMPRESSION_RANK}, timestamp, {_IMPRESSION_RANK} IS NOT NULL) AS first_impression_rank,
- min({_IMPRESSION_RANK}) AS best_impression_rank,
+ argMinIf({IMPRESSION_RANK_SQL}, timestamp, {IMPRESSION_RANK_SQL} IS NOT NULL) AS first_impression_rank,
+ min({IMPRESSION_RANK_SQL}) AS best_impression_rank,
argMax(JSONExtract(imp, 'source_products', 'Array(String)'), timestamp) AS source_products
FROM events
ARRAY JOIN JSONExtractArrayRaw(properties, 'impressions') AS imp
diff --git a/products/signals/dags/inbox_ranking/shadow/dag.py b/products/signals/dags/inbox_ranking/shadow/dag.py
new file mode 100644
index 000000000000..930cc12d1012
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/shadow/dag.py
@@ -0,0 +1,331 @@
+"""Shadow evaluation of the ranking model against the order the inbox serves.
+
+One asset on the daily partition:
+
+ inbox_ranking_shadow_eval/v1/dt=D/ one row per (model, outcome, order) graded 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.
+
+The read grades a model that is not serving, so nothing here changes what anyone sees.
+"""
+
+import datetime
+
+import pandas as pd
+import dagster
+import pyarrow as pa
+import pyarrow.parquet as pq
+from botocore.exceptions import ClientError
+
+from posthog import settings
+from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tag_queries
+from posthog.dags.common import dagster_tags
+
+from products.signals.dags.inbox_ranking.common import (
+ S3_BUCKET_ENV,
+ dataset_bucket,
+ dataset_unconfigured,
+ owner_tags,
+ partition_def,
+ partition_object_key,
+ s3_client,
+ skip_unconfigured,
+ snapshot_bounds,
+ write_parquet,
+)
+from products.signals.dags.inbox_ranking.dataset.queries import LABELS_TEAM_ID, labels_team
+from products.signals.dags.inbox_ranking.shadow.metrics import (
+ ATTRIBUTION_WINDOW,
+ OUTCOMES,
+ SCORE_JOIN_COLUMNS,
+ RankingGrade,
+ deduplicate_lists,
+ grade_lists,
+ join_scores,
+ score_coverage,
+ with_outcomes,
+)
+from products.signals.dags.inbox_ranking.shadow.queries import (
+ IMPRESSION_COLUMNS,
+ IMPRESSION_LISTS_SQL,
+ OUTCOME_COLUMNS,
+ OUTCOMES_SQL,
+ hogql_rows,
+)
+from products.signals.dags.inbox_ranking.shadow.telemetry import shadow_grade_events
+from products.signals.dags.inbox_ranking.training.telemetry import capture_training_events
+from products.signals.dags.inbox_ranking.training.unseen import UNSEEN_SCORES_TABLE, with_model_names
+
+SHADOW_TABLE = "inbox_ranking_shadow_eval"
+
+_GRADE_FIELDS: list[tuple[str, pa.DataType]] = [
+ ("snapshot_date", pa.date32()),
+ ("model_name", pa.string()),
+ ("model_role", pa.string()),
+ ("model_versions", pa.int32()),
+ ("outcome", pa.string()),
+ ("ranking_order", pa.string()),
+ ("lists", pa.int64()),
+ ("reports", pa.int64()),
+ ("mean_list_size", pa.float64()),
+ ("ndcg_5", pa.float64()),
+ ("ndcg_10", pa.float64()),
+ ("mrr", pa.float64()),
+ ("ndcg_5_std", pa.float64()),
+ ("ndcg_10_std", pa.float64()),
+ ("mrr_std", pa.float64()),
+ ("positive_served_rank_mean", pa.float64()),
+ # This grade's own coverage; `run_score_coverage` is the same share over every grade of the day.
+ ("score_coverage", pa.float64()),
+ ("positive_coverage", pa.float64()),
+ ("full_list_coverage", pa.float64()),
+ ("served_rows", pa.int64()),
+ ("served_lists", pa.int64()),
+ ("run_score_coverage", pa.float64()),
+]
+GRADE_SCHEMA = pa.schema(_GRADE_FIELDS)
+
+# The lists of dt=D are served by scores written on earlier partitions, back to the oldest report
+# still being impressed. The default same-partition mapping would run this before any of them
+# 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,
+ allow_nonexistent_upstream_partitions=True,
+)
+
+
+def _tag_dagster_queries(context: dagster.AssetExecutionContext) -> None:
+ """Attribute every ClickHouse query this asset issues in system.query_log. The dogfood project
+ owns the telemetry being read, so it is the team the queries are tagged with."""
+ tag_queries(
+ product=Product.SIGNALS,
+ feature=Feature.DATA_MODELING,
+ team_id=LABELS_TEAM_ID,
+ query_type="inbox_ranking_shadow_eval",
+ )
+ get_query_tags().with_dagster(dagster_tags(context))
+
+
+def impression_frame(rows: list[tuple[object, ...]]) -> pd.DataFrame:
+ frame = pd.DataFrame(rows, columns=list(IMPRESSION_COLUMNS))
+ frame["impressed_at"] = pd.to_datetime(frame["impressed_at"], utc=True)
+ frame["served_rank"] = pd.to_numeric(frame["served_rank"])
+ return frame
+
+
+def outcome_frame(rows: list[tuple[object, ...]]) -> pd.DataFrame:
+ frame = pd.DataFrame(rows, columns=list(OUTCOME_COLUMNS))
+ frame["timestamp"] = pd.to_datetime(frame["timestamp"], utc=True)
+ return frame
+
+
+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.
+ Missing partitions are ordinary: a day the training job did not run scored nobody."""
+ frames: list[pd.DataFrame] = []
+ for date in dates:
+ key = date.isoformat()
+ # Read whole rather than by column list: an object written before `model_name` existed
+ # has no such column, and `with_model_names` is what fills it in.
+ try:
+ response = client.get_object(Bucket=bucket, Key=partition_object_key(prefix, UNSEEN_SCORES_TABLE, key))
+ except ClientError as error:
+ if error.response.get("Error", {}).get("Code") in ("404", "NoSuchKey", "NotFound"):
+ continue
+ raise
+ with response["Body"] as body:
+ table = pq.read_table(pa.BufferReader(body.read()))
+ if table.num_rows == 0:
+ continue
+ # Down to the graded heads before the frame is kept: a partition holds a row per readable
+ # 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)
+ )
+ partition_columns = ["snapshot_date", "model_name", "head"]
+ champions = frame.loc[frame["model_role"] == "champion", partition_columns].drop_duplicates()
+ candidates = frame.loc[frame["model_role"] == "candidate"].merge(
+ champions, on=partition_columns, how="left", indicator=True
+ )
+ fallback = (
+ candidates.loc[candidates["_merge"] == "left_only"].drop(columns="_merge").assign(model_role="champion")
+ )
+ frames.extend([frame, fallback])
+ if not frames:
+ return pd.DataFrame(columns=[*SCORE_JOIN_COLUMNS, "available_at"])
+ return pd.concat(frames, ignore_index=True)
+
+
+def grade_rows(
+ grades: list[RankingGrade],
+ *,
+ partition_key: str,
+ served_rows: int,
+ served_lists: int,
+ run_coverage: float | None,
+) -> list[dict[str, object]]:
+ return [
+ {
+ **grade.as_dict(),
+ "snapshot_date": datetime.date.fromisoformat(partition_key),
+ "served_rows": served_rows,
+ "served_lists": served_lists,
+ "run_score_coverage": run_coverage,
+ }
+ for grade in grades
+ ]
+
+
+def grade_metadata(grades: list[RankingGrade]) -> dict[str, dagster.MetadataValue]:
+ """One entry per (model, outcome, order, metric), so the three orders of a day are readable
+ side by side on the materialization."""
+ metadata: dict[str, dagster.MetadataValue] = {}
+ for grade in grades:
+ 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}"
+ metadata[key] = (
+ dagster.MetadataValue.int(value) if isinstance(value, int) else dagster.MetadataValue.float(value)
+ )
+ return metadata
+
+
+ name=SHADOW_TABLE,
+ deps=[dagster.AssetDep(UNSEEN_SCORES_TABLE, partition_mapping=_SCORE_LOOKBACK_MAPPING)],
+ group_name="inbox_ranking_shadow",
+ partitions_def=partition_def,
+ tags=owner_tags,
+ retry_policy=dagster.RetryPolicy(max_retries=2, delay=60),
+ pool="inbox_ranking_etl",
+)
+def inbox_ranking_shadow_eval(context: dagster.AssetExecutionContext) -> None:
+ if skip_unconfigured(context):
+ return
+ partition_key = context.partition_key
+ bucket, prefix, client = dataset_bucket(), settings.INBOX_RANKING_DATASET_S3_PREFIX, s3_client()
+ day = datetime.date.fromisoformat(partition_key)
+ window_start, window_end = snapshot_bounds(partition_key)
+
+ _tag_dagster_queries(context)
+ team = labels_team()
+ impressions = impression_frame(
+ hogql_rows(
+ IMPRESSION_LISTS_SQL,
+ team=team,
+ query_type="inbox_ranking_shadow_impressions",
+ window_start=window_start,
+ window_end=window_end,
+ )
+ )
+ outcomes = outcome_frame(
+ hogql_rows(
+ OUTCOMES_SQL,
+ team=team,
+ query_type="inbox_ranking_shadow_outcomes",
+ window_start=window_start,
+ # An engagement with a list served just before midnight lands on the next day, so the
+ # outcome window runs one attribution window past the impression window.
+ window_end=window_end + ATTRIBUTION_WINDOW,
+ )
+ )
+
+ 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)
+ ],
+ )
+ joined = join_scores(lists, scores)
+ served_rows = len(lists)
+ coverage = score_coverage(served_rows, joined)
+ grades = grade_lists(joined, served=lists)
+ served_lists = int(lists["impression_id"].nunique()) if not lists.empty else 0
+
+ rows = grade_rows(
+ grades,
+ partition_key=partition_key,
+ served_rows=served_rows,
+ served_lists=served_lists,
+ run_coverage=coverage,
+ )
+ key = partition_object_key(prefix, SHADOW_TABLE, partition_key)
+ write_parquet(client, bucket, key, pa.Table.from_pylist(rows, schema=GRADE_SCHEMA), snapshot_date=partition_key)
+
+ for grade in grades:
+ context.log.info(f"shadow grade: {grade.as_dict()}")
+ if not grades:
+ context.log.warning(
+ f"dt={partition_key} graded nothing: {served_lists} lists, {served_rows} served rows, "
+ f"{len(scores)} scores in the lookback window"
+ )
+ context.add_output_metadata(
+ {
+ "served_lists": dagster.MetadataValue.int(served_lists),
+ "served_rows": dagster.MetadataValue.int(served_rows),
+ # The number the read rests on. A day whose lists were mostly unscored says little
+ # about either order; the residual is reports impressed on their birth day, which the
+ # daily job cannot have scored yet. `grade_metadata` carries each grade's own share.
+ "run_score_coverage": dagster.MetadataValue.float(coverage if coverage is not None else 0.0),
+ **grade_metadata(grades),
+ "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),
+ }
+ )
+ capture_training_events(
+ context,
+ partition_key,
+ shadow_grade_events(
+ run_id=context.run.run_id,
+ served_rows=served_rows,
+ served_lists=served_lists,
+ run_score_coverage=coverage,
+ grades=grades,
+ ),
+ )
+
+
+inbox_ranking_shadow_job = dagster.define_asset_job(
+ name="inbox_ranking_shadow_job",
+ selection=[SHADOW_TABLE],
+ partitions_def=partition_def,
+ tags={**owner_tags, "dagster/max_runtime": str(60 * 60)},
+)
+
+
+# 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.
+ cron_schedule="30 9 * * *",
+ job=inbox_ranking_shadow_job,
+ execution_timezone="UTC",
+ default_status=dagster.DefaultScheduleStatus.RUNNING
+ if settings.CLOUD_DEPLOYMENT == "US"
+ else dagster.DefaultScheduleStatus.STOPPED,
+ tags=owner_tags,
+)
+def inbox_ranking_shadow_schedule(
+ context: dagster.ScheduleEvaluationContext,
+) -> dagster.RunRequest | dagster.SkipReason:
+ if dataset_unconfigured():
+ return dagster.SkipReason(f"{S3_BUCKET_ENV} is not set; skipping until the dedicated bucket is provisioned")
+ previous_day = context.scheduled_execution_time.date() - datetime.timedelta(days=1)
+ return dagster.RunRequest(partition_key=previous_day.isoformat(), run_key=f"shadow-{previous_day.isoformat()}")
diff --git a/products/signals/dags/inbox_ranking/shadow/metrics.py b/products/signals/dags/inbox_ranking/shadow/metrics.py
new file mode 100644
index 000000000000..2b605dd085d3
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/shadow/metrics.py
@@ -0,0 +1,434 @@
+"""Shadow evaluation: the model's order against the order the inbox served.
+
+Every read the ranking model has today is offline. The holdout grades the recipe, the unseen read
+grades the model on reports it never saw, and neither one compares the model against the list
+people actually get, which is still a fixed sort. This module builds that comparison from data
+already flowing: an `Inbox reports impressed` event carries a set of rows at the ranks the list
+served them, the unseen scores say how the model would have ordered them, and the opens and
+actions that follow the impression say which rows were worth the top.
+
+Three orders are graded on each list, on exactly the same rows:
+
+- `model`, descending score of the head whose outcome is being graded, with unscored rows last;
+- `heuristic`, every row at the rank the list served, pooling all served sorts;
+- `random`, seeded permutations, the chance line a gap has to clear.
+
+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
+report the heuristic put first had more chance to be opened than one it put twentieth, whatever
+either order thinks of it. That flatters the heuristic line and no re-ranking of logged clicks can
+remove it. `positive_served_rank_mean` reports how concentrated the outcomes were at the top of
+the served list, so the size of the effect is visible next to the numbers it distorts.
+
+**Only complete reconstructed lists are graded.** Events are unioned by absolute rank inside a
+five-second UTC bucket for the same viewer, session, scope and normalized tab. State-section
+tabs normalize to `reports` so merged sections meet. The maximum list_size must equal the row
+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.
+
+**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
+attribution window", which is what an order can be held responsible for. The `open` head predicts
+"anyone opened this report within three days" and `action` the same over seven, both counted per
+report rather than per viewer. The scores being ranked are the head's, so a head is graded against
+the outcome it was fit toward, but a shadow NDCG and an unseen AUC of the same name answer
+different questions and are not one number.
+"""
+
+import datetime
+from collections.abc import Iterator, Mapping, Sequence
+from typing import Any
+
+import numpy as np
+import pandas as pd
+
+from posthog.dataclasses import frozen
+
+# The outcomes graded, each named after the head whose scores order it. Not that head's label: the
+# module docstring has the horizon and grain the proxy does not carry.
+OPEN_OUTCOME = "open"
+ACTION_OUTCOME = "action"
+OUTCOMES: tuple[str, ...] = (OPEN_OUTCOME, ACTION_OUTCOME)
+
+MODEL_ORDER = "model"
+HEURISTIC_ORDER = "heuristic"
+RANDOM_ORDER = "random"
+
+NDCG_CUTOFFS: tuple[int, ...] = (5, 10)
+
+# Seeded and fixed, so re-grading the same day reports the same chance line.
+RANDOM_PERMUTATIONS = 25
+RANDOM_SEED = 0
+
+# How long after seeing a list an engagement still counts as that list's. Opens land within
+# minutes of the impression; a window of hours would credit a list for a report the person came
+# back to from a link or a notification.
+ATTRIBUTION_WINDOW = datetime.timedelta(minutes=30)
+
+RENDER_WINDOW = "5s"
+SECTION_TABS = ("monitoring", "needs-decision", "resolved", "dismissed", "not-actionable")
+
+# A list of one is ranked identically by every order, so it separates nothing and only adds weight
+# to the average.
+MIN_LIST_SIZE = 2
+
+SCORE_JOIN_COLUMNS = ("report_id", "snapshot_date", "model_name", "model_version", "model_role", "head", "score")
+
+
+def outcome_column(outcome: str) -> str:
+ return f"outcome_{outcome}"
+
+
+@frozen
+class RankingGrade:
+ """One model, one outcome, one order, 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
+ reports appeared. That is the serving situation, not a mixing bug — the champion pointer a
+ sweep would load moves the same way.
+ """
+
+ model_name: str
+ model_role: str
+ model_versions: int
+ outcome: str
+ ranking_order: 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
+ reports: int
+ mean_list_size: float
+ ndcg_5: float | None
+ ndcg_10: float | None
+ mrr: float | None
+ # Spread across the seeded draws, so the random line carries its own noise band. None for the
+ # two deterministic orders.
+ ndcg_5_std: float | None
+ ndcg_10_std: float | None
+ mrr_std: float | None
+ # Mean served rank of the rows that drew the outcome: how much of the outcome the top of the
+ # served list already collected, which is the size of the position bias in these numbers.
+ positive_served_rank_mean: float | None
+ # This group's own coverage, not the run's. A head is only scored on a partition where the
+ # training job found it readable, and a family is skipped on a partition it has no metadata
+ # for, so one grade can rest on far fewer of the served rows than another one of the same day.
+ score_coverage: float | None
+ # The same share over the served rows that drew this outcome. The join drops unscored rows,
+ # and those are the reports born on the day they were impressed, which is where an open lands
+ # most often. Below 1 these lists are conditioned on the outcome falling on an older report.
+ positive_coverage: float | None
+ # Share of this group's lists that kept every row the person saw. Below 1 the rest were graded
+ # 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
+
+ def metrics(self) -> dict[str, int | float | None]:
+ return {
+ "lists": self.lists,
+ "reports": self.reports,
+ "mean_list_size": self.mean_list_size,
+ "ndcg_5": self.ndcg_5,
+ "ndcg_10": self.ndcg_10,
+ "mrr": self.mrr,
+ "ndcg_5_std": self.ndcg_5_std,
+ "ndcg_10_std": self.ndcg_10_std,
+ "mrr_std": self.mrr_std,
+ "positive_served_rank_mean": self.positive_served_rank_mean,
+ "score_coverage": self.score_coverage,
+ "positive_coverage": self.positive_coverage,
+ "full_list_coverage": self.full_list_coverage,
+ }
+
+ def as_dict(self) -> dict[str, object]:
+ return {
+ "model_name": self.model_name,
+ "model_role": self.model_role,
+ "model_versions": self.model_versions,
+ "outcome": self.outcome,
+ "ranking_order": self.ranking_order,
+ **self.metrics(),
+ }
+
+
+@frozen
+class ServedList:
+ """One impression's rows, as three aligned arrays: was it engaged with, what the model scored
+ it, and where the list put it."""
+
+ relevance: np.ndarray
+ score: np.ndarray
+ served_rank: np.ndarray
+
+
+def deduplicate_lists(impressions: pd.DataFrame) -> pd.DataFrame:
+ """Reassemble complete render windows after per-event outcome attribution.
+
+ Attribute first so a later incomplete impression cannot credit an earlier complete list.
+ Duplicate rows retain any outcome attributed to their latest event in the render window.
+ """
+ if impressions.empty:
+ return impressions
+ rows = impressions.assign(
+ render_window=impressions["impressed_at"].dt.floor(RENDER_WINDOW),
+ tab=impressions["tab"].replace(dict.fromkeys(SECTION_TABS, "reports")),
+ )
+ complete: list[pd.DataFrame] = []
+ for _, render in rows.groupby(["distinct_id", "session_id", "scope", "tab", "render_window"], sort=True):
+ size = render["list_size"].max()
+ if pd.isna(size) or size < 1 or not render["session_id"].iloc[0]:
+ continue
+ if (render.groupby("served_rank")["report_id"].nunique() > 1).any():
+ continue
+ ranked = render.sort_values(["impressed_at", "impression_id"]).drop_duplicates("served_rank")
+ if (
+ len(ranked) != size
+ or ranked["report_id"].nunique() != size
+ or set(ranked["served_rank"]) != set(range(1, int(size) + 1))
+ ):
+ continue
+ ranked = ranked.assign(
+ **{
+ column: ranked["served_rank"].map(render.groupby("served_rank")[column].max())
+ for outcome in OUTCOMES
+ if (column := outcome_column(outcome)) in render
+ }
+ )
+ complete.append(
+ ranked.assign(impression_id=render["impression_id"].min(), list_size=size).drop(columns="render_window")
+ )
+ return pd.concat(complete, ignore_index=True) if complete else impressions.head(0)
+
+
+def with_outcomes(impressions: pd.DataFrame, outcomes: pd.DataFrame) -> pd.DataFrame:
+ """`impressions` with one boolean column per outcome: did this person engage with this report
+ within the attribution window of seeing it in this list."""
+ engaged = impressions.copy()
+ for outcome in OUTCOMES:
+ engaged[outcome_column(outcome)] = False
+ if impressions.empty or outcomes.empty:
+ return engaged
+ pairs = impressions[["impression_id", "distinct_id", "report_id", "impressed_at"]].merge(
+ outcomes, on=["distinct_id", "report_id"], how="inner"
+ )
+ within = (pairs["timestamp"] >= pairs["impressed_at"]) & (
+ pairs["timestamp"] < pairs["impressed_at"] + ATTRIBUTION_WINDOW
+ )
+ # One engagement belongs to one list: the last one the person saw the report in before they
+ # engaged. A filter or sort change re-impresses the same rows at new ranks, so an open inside
+ # the window of several renders would otherwise mark every one of them relevant. The
+ # `impression_id` tie-break keeps a re-run of the partition on the same choice.
+ attributed = (
+ pairs.loc[within]
+ .sort_values(["impressed_at", "impression_id"])
+ .drop_duplicates(subset=["distinct_id", "report_id", "timestamp", "outcome"], keep="last")
+ )
+ keys = list(zip(engaged["impression_id"], engaged["report_id"], strict=True))
+ for outcome in OUTCOMES:
+ hits = set(
+ map(tuple, attributed.loc[attributed["outcome"] == outcome, ["impression_id", "report_id"]].to_numpy())
+ )
+ engaged[outcome_column(outcome)] = [key in hits for key in keys]
+ return engaged
+
+
+def join_scores(lists: pd.DataFrame, scores: pd.DataFrame) -> pd.DataFrame:
+ """One row per (list, report, model, head), carrying the newest score that existed when the
+ list was served.
+
+ 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.
+ """
+ if lists.empty or scores.empty:
+ return lists.head(0).merge(scores.head(0), on="report_id", how="inner")
+ 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"
+ )
+ 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",
+ )
+
+
+def score_coverage(served_rows: int, joined: pd.DataFrame) -> float | None:
+ """Share of served rows a model score was available for. The number the whole read rests on:
+ before this asset it was zero, because no scoring moment was ever paired with a served list.
+
+ Over the whole join it is the run's coverage; over one grade's rows it is that grade's. They
+ part whenever a head or a family scored fewer of the days the lists came from, so the run
+ figure alone would let a thin grade read as a well-covered one.
+ """
+ if not served_rows:
+ return None
+ covered = joined.loc[joined["score"].notna()].drop_duplicates(subset=["impression_id", "report_id"])
+ return float(len(covered) / served_rows)
+
+
+def served_lists(rows: pd.DataFrame, outcome: str) -> list[ServedList]:
+ """The gradeable lists of one (model, head) group.
+
+ 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.
+
+ 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
+ array as it stands. The impression query has no `ORDER BY`, so without this a re-run of the
+ partition could hand the same rows over differently and publish a different chance line.
+ """
+ column = outcome_column(outcome)
+ lists: list[ServedList] = []
+ for _, group in rows.groupby("impression_id", sort=True):
+ ordered = 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
+ lists.append(
+ ServedList(
+ relevance=relevance,
+ score=ordered["score"].fillna(-np.inf).to_numpy(dtype=float),
+ served_rank=ordered["served_rank"].to_numpy(dtype=float),
+ )
+ )
+ return lists
+
+
+def _dcg(relevance: np.ndarray, k: int) -> float:
+ top = relevance[:k]
+ return float((top / np.log2(np.arange(2, len(top) + 2))).sum())
+
+
+def ndcg_at_k(relevance_in_order: np.ndarray, k: int) -> float:
+ """Binary-relevance NDCG at `k`, normalized by the best this list could have done."""
+ ideal = _dcg(np.sort(relevance_in_order)[::-1], k)
+ return _dcg(relevance_in_order, k) / ideal if ideal else 0.0
+
+
+def reciprocal_rank(relevance_in_order: np.ndarray) -> float:
+ hits = np.flatnonzero(relevance_in_order)
+ return float(1.0 / (hits[0] + 1)) if len(hits) else 0.0
+
+
+def _order_metrics(ordered: Sequence[np.ndarray]) -> dict[str, float]:
+ """Mean of each metric over the lists, each already in the order being graded."""
+ return {
+ **{f"ndcg_{k}": float(np.mean([ndcg_at_k(relevance, k) for relevance in ordered])) for k in NDCG_CUTOFFS},
+ "mrr": float(np.mean([reciprocal_rank(relevance) for relevance in ordered])),
+ }
+
+
+def _model_ordered(lists: Sequence[ServedList]) -> list[np.ndarray]:
+ # Ties break on the served rank, so a model that scores a whole list alike neither gains nor
+ # loses against the heuristic on it.
+ return [entry.relevance[np.lexsort((entry.served_rank, -entry.score))] for entry in lists]
+
+
+def _heuristic_ordered(lists: Sequence[ServedList]) -> list[np.ndarray]:
+ return [entry.relevance[np.argsort(entry.served_rank, kind="stable")] for entry in lists]
+
+
+def _random_draws(lists: Sequence[ServedList]) -> Iterator[list[np.ndarray]]:
+ rng = np.random.default_rng(RANDOM_SEED)
+ for _ in range(RANDOM_PERMUTATIONS):
+ yield [rng.permutation(entry.relevance) for entry in lists]
+
+
+def _random_metrics(lists: Sequence[ServedList]) -> dict[str, float | None]:
+ """Mean and spread of each metric across the seeded draws."""
+ draws = [_order_metrics(ordered) for ordered in _random_draws(lists)]
+ metrics: dict[str, float | None] = {}
+ for name in draws[0]:
+ values = [draw[name] for draw in draws]
+ metrics[name] = float(np.mean(values))
+ metrics[f"{name}_std"] = float(np.std(values))
+ return metrics
+
+
+def _positive_served_rank_mean(lists: Sequence[ServedList]) -> float | None:
+ ranks = np.concatenate([entry.served_rank[entry.relevance > 0] for entry in lists])
+ return float(ranks.mean()) if len(ranks) else None
+
+
+def _positive_coverage(rows: pd.DataFrame, outcome: str, served_positives: int) -> float | None:
+ """Share of the served rows that drew `outcome` which this group had a score for."""
+ if not served_positives:
+ return None
+ 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."""
+ 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())
+
+
+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.
+
+ 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.
+ """
+ grades: list[RankingGrade] = []
+ if joined.empty:
+ return grades
+ served_rows = len(served)
+ served_per_list = served.groupby("impression_id").size()
+ served_positives = {outcome: int(served[outcome_column(outcome)].sum()) for outcome in OUTCOMES}
+ 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:
+ continue
+ shared: 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),
+ }
+ 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
+
+
+def _grade(shared: Mapping[str, Any], *, ranking_order: str, metrics: Mapping[str, float | None]) -> RankingGrade:
+ return RankingGrade(
+ ranking_order=ranking_order,
+ ndcg_5=metrics.get("ndcg_5"),
+ ndcg_10=metrics.get("ndcg_10"),
+ mrr=metrics.get("mrr"),
+ ndcg_5_std=metrics.get("ndcg_5_std"),
+ ndcg_10_std=metrics.get("ndcg_10_std"),
+ mrr_std=metrics.get("mrr_std"),
+ **shared,
+ )
diff --git a/products/signals/dags/inbox_ranking/shadow/queries.py b/products/signals/dags/inbox_ranking/shadow/queries.py
new file mode 100644
index 000000000000..653c48e9894f
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/shadow/queries.py
@@ -0,0 +1,124 @@
+"""SQL for the shadow evaluation: the lists the inbox served, and what people did with them.
+
+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
+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.
+Only reconstructions containing every rank from 1 through the maximum list_size are graded.
+Conflicting rank assignments are excluded. Buckets are an approximation without a render ID:
+pagination crossing a bucket boundary is excluded rather than graded as a separate partial list.
+"""
+
+import datetime
+from typing import Any
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
+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
+
+# 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
+# horizon and its per-report grain are deliberately not carried over; `shadow/metrics.py` says why.
+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
+# same event can land twice and would then put a report into its own list twice. `rank` is read
+# through the same 1-based contract guard the labels asset applies, and a report whose rank is
+# missing or malformed cannot be placed in the served order at all, so it is dropped here.
+IMPRESSION_COLUMNS = (
+ "impression_id",
+ "distinct_id",
+ "impressed_at",
+ "tab",
+ "scope",
+ "report_id",
+ "served_rank",
+ "session_id",
+ "list_size",
+)
+IMPRESSION_LISTS_SQL = f"""
+SELECT
+ impression_id,
+ any(distinct_id) AS distinct_id,
+ min(timestamp) AS impressed_at,
+ any(tab) AS tab,
+ any(scope) AS scope,
+ report_id,
+ any(rank_value) AS served_rank,
+ any(session_id) AS session_id,
+ max(list_size) AS list_size
+FROM (
+ SELECT
+ toString(uuid) AS impression_id,
+ distinct_id,
+ timestamp,
+ toString(properties.tab) AS tab,
+ toString(properties.scope) AS scope,
+ toString(properties.$session_id) AS session_id,
+ toInt(properties.list_size) AS list_size,
+ JSONExtractString(imp, 'report_id') AS report_id,
+ {IMPRESSION_RANK_SQL} AS rank_value
+ FROM events
+ ARRAY JOIN JSONExtractArrayRaw(properties, 'impressions') AS imp
+ WHERE event = 'Inbox reports impressed'
+ AND timestamp >= toDateTime({{window_start}}) AND timestamp < toDateTime({{window_end}})
+)
+GROUP BY impression_id, report_id
+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.
+OUTCOME_COLUMNS = ("report_id", "distinct_id", "timestamp", "outcome")
+OUTCOMES_SQL = f"""
+SELECT
+ toString(properties.report_id) AS report_id,
+ distinct_id,
+ timestamp,
+ if(event = 'Inbox report opened', 'open', 'action') AS outcome
+FROM events
+WHERE (
+ event = 'Inbox report opened'
+ OR (event = 'Inbox report action' AND toString(properties.action_type) IN ({_ACTION_TYPES_SQL}))
+ )
+ AND timestamp >= toDateTime({{window_start}}) AND timestamp < toDateTime({{window_end}})
+ AND toString(properties.report_id) != ''
+"""
+
+
+def hogql_rows(
+ sql: str,
+ *,
+ team: Team,
+ query_type: str,
+ window_start: datetime.datetime,
+ window_end: datetime.datetime,
+) -> list[tuple[Any, ...]]:
+ """Both queries scan one day of one event family, so they keep the HogQL default timeout
+ rather than the cumulative label windows' 600s."""
+ response = execute_hogql_query(
+ query=sql,
+ team=team,
+ query_type=query_type,
+ placeholders={
+ "window_start": ast.Constant(value=utc_bound(window_start)),
+ "window_end": ast.Constant(value=utc_bound(window_end)),
+ },
+ limit_context=LimitContext.SAVED_QUERY,
+ workload=etl_workload(),
+ settings=HogQLGlobalSettings(max_execution_time=600),
+ # The dag runs without a user; the read is a trusted internal ETL over the dogfood project.
+ bypass_warehouse_access_control=True,
+ )
+ return [tuple(row) for row in response.results or []]
diff --git a/products/signals/dags/inbox_ranking/shadow/telemetry.py b/products/signals/dags/inbox_ranking/shadow/telemetry.py
new file mode 100644
index 000000000000..0cf5aca56c25
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/shadow/telemetry.py
@@ -0,0 +1,57 @@
+"""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.
+"""
+
+from collections.abc import Sequence
+
+from products.signals.dags.inbox_ranking.shadow.metrics import RankingGrade
+from products.signals.dags.inbox_ranking.training.telemetry import TrainingEvent
+
+SHADOW_RANKING_GRADED_EVENT = "inbox_ranking_shadow_ranking_graded"
+SHADOW_RUN_COMPLETED_EVENT = "inbox_ranking_shadow_run_completed"
+
+
+def shadow_grade_events(
+ *,
+ run_id: str,
+ served_rows: int,
+ served_lists: int,
+ run_score_coverage: float | None,
+ grades: Sequence[RankingGrade],
+) -> list[TrainingEvent]:
+ """One run event, then one event per grade.
+
+ The run event is unconditional, for the reason `candidate_events` reports a head it could not
+ fit: a day that graded nothing is a day with a zero on it, not a gap, and a gap is what a
+ crashed run looks like on the same chart. Lists with no score available at impression time
+ grade nothing, which is every partition before the first usable scores object.
+
+ 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.
+ """
+ reason = None
+ if not grades:
+ reason = (
+ "no_complete_lists"
+ if not served_lists
+ else "no_available_scores"
+ if not run_score_coverage
+ else "no_gradeable_outcomes"
+ )
+ run: dict[str, object] = {
+ "run_id": run_id,
+ "served_rows": served_rows,
+ "served_lists": served_lists,
+ "run_score_coverage": run_score_coverage,
+ }
+ 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),
+ ]
diff --git a/products/signals/dags/inbox_ranking/tests/test_shadow.py b/products/signals/dags/inbox_ranking/tests/test_shadow.py
new file mode 100644
index 000000000000..df2a255eedb1
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/tests/test_shadow.py
@@ -0,0 +1,547 @@
+import io
+import datetime
+
+import pytest
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event
+
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+import pyarrow.parquet as pq
+from botocore.exceptions import ClientError
+
+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.shadow.metrics import (
+ ATTRIBUTION_WINDOW,
+ HEURISTIC_ORDER,
+ MODEL_ORDER,
+ RANDOM_ORDER,
+ deduplicate_lists,
+ grade_lists,
+ join_scores,
+ ndcg_at_k,
+ reciprocal_rank,
+ score_coverage,
+ served_lists,
+ with_outcomes,
+)
+from products.signals.dags.inbox_ranking.shadow.queries import IMPRESSION_LISTS_SQL, OUTCOMES_SQL, hogql_rows
+from products.signals.dags.inbox_ranking.shadow.telemetry import (
+ SHADOW_RANKING_GRADED_EVENT,
+ SHADOW_RUN_COMPLETED_EVENT,
+ shadow_grade_events,
+)
+from products.signals.dags.inbox_ranking.training.unseen import UNSEEN_SCORES_TABLE
+
+DAY = datetime.date(2026, 9, 10)
+SERVED_AT = datetime.datetime(2026, 9, 10, 12, 0, tzinfo=datetime.UTC)
+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"
+
+
+def _lists(rows: list[dict[str, object]]) -> pd.DataFrame:
+ frame = pd.DataFrame(rows)
+ frame["impressed_at"] = pd.to_datetime(frame["impressed_at"], utc=True)
+ return frame
+
+
+def _served(impression_id: str, report_ids: list[str], *, at: datetime.datetime = SERVED_AT) -> list[dict]:
+ return [
+ {
+ "impression_id": impression_id,
+ "distinct_id": "user-1",
+ "impressed_at": at,
+ "tab": "all",
+ "scope": "project",
+ "report_id": report_id,
+ "served_rank": rank,
+ "session_id": "session-1",
+ "list_size": len(report_ids),
+ }
+ for rank, report_id in enumerate(report_ids, start=1)
+ ]
+
+
+def _scores(report_ids: list[str], scores: list[float], *, snapshot_date: datetime.date, head: str = "open"):
+ frame = pd.DataFrame(
+ {
+ "report_id": report_ids,
+ "snapshot_date": snapshot_date,
+ "model_name": "tabular_xgb",
+ "model_version": snapshot_date.isoformat(),
+ "model_role": "champion",
+ "head": head,
+ "score": scores,
+ }
+ )
+ return frame.assign(available_at=pd.Timestamp(snapshot_date, tz="UTC") + datetime.timedelta(days=1, hours=7))
+
+
+def test_ndcg_rewards_putting_the_engaged_report_first():
+ assert ndcg_at_k(np.array([1.0, 0.0, 0.0]), 5) == 1.0
+ # Second place pays log2(3) of the ideal.
+ assert ndcg_at_k(np.array([0.0, 1.0, 0.0]), 5) == pytest.approx(1 / np.log2(3))
+ # A cutoff that excludes the only engaged row scores nothing, which is the point of @k.
+ assert ndcg_at_k(np.array([0.0] * 5 + [1.0]), 5) == 0.0
+ assert ndcg_at_k(np.array([0.0, 0.0]), 5) == 0.0
+
+
+def test_reciprocal_rank_is_one_over_the_first_hit():
+ assert reciprocal_rank(np.array([0.0, 1.0, 1.0])) == 0.5
+ assert reciprocal_rank(np.array([0.0, 0.0])) == 0.0
+
+
+def test_repeated_renders_only_collapse_inside_the_same_render_window():
+ rows = _lists(
+ [
+ *_served("first", [UUID_A, UUID_B]),
+ *_served("duplicate", [UUID_A, UUID_B], at=SERVED_AT + datetime.timedelta(seconds=1)),
+ *_served("second", [UUID_A, UUID_B], at=SERVED_AT + datetime.timedelta(minutes=1)),
+ *_served("reordered", [UUID_B, UUID_A], at=SERVED_AT + datetime.timedelta(minutes=2)),
+ # Hours later the same order is a second visit, not a repeat: an open that follows it
+ # lands outside the morning render's attribution window and would be lost with it.
+ *_served("revisit", [UUID_A, UUID_B], at=SERVED_AT + datetime.timedelta(hours=5)),
+ ]
+ )
+
+ outcomes = pd.DataFrame(
+ [{"report_id": UUID_A, "distinct_id": "user-1", "timestamp": SERVED_AT + datetime.timedelta(seconds=2)}]
+ ).assign(outcome="open")
+ kept = deduplicate_lists(with_outcomes(rows, outcomes))
+
+ assert sorted(kept["impression_id"].unique()) == ["duplicate", "reordered", "revisit", "second"]
+ assert len(kept) == 8
+ assert kept.loc[kept["outcome_open"], "report_id"].tolist() == [UUID_A]
+
+
[email protected]("section_tabs", [("all", "all"), ("monitoring", "needs-decision")])
+def test_section_and_pagination_events_reassemble_one_complete_list(section_tabs: tuple[str, str]) -> None:
+ rows = _lists(_served("first", [UUID_A, UUID_B]))
+ rows["impression_id"] = ["first", "second"]
+ rows["tab"] = list(section_tabs)
+ rows.loc[1, "impressed_at"] += datetime.timedelta(seconds=2)
+ if section_tabs == ("all", "all"):
+ rows.loc[0, "list_size"] = 1
+
+ assembled = deduplicate_lists(rows)
+
+ assert assembled["impression_id"].nunique() == 1
+ assert assembled["report_id"].tolist() == [UUID_A, UUID_B]
+ assert assembled["served_rank"].tolist() == [1, 2]
+ assert assembled["list_size"].tolist() == [2, 2]
+
+
+ "variation", ["missing_row", "next_bucket", "different_session", "rank_conflict", "missing_session"]
+)
+def test_incomplete_or_conflicting_render_windows_are_excluded(variation: str) -> None:
+ rows = _lists(_served("first", [UUID_A, UUID_B]))
+ if variation == "missing_row":
+ rows = rows.head(1)
+ elif variation == "next_bucket":
+ rows.loc[1, "impressed_at"] += datetime.timedelta(seconds=5)
+ elif variation == "different_session":
+ rows.loc[1, "session_id"] = "session-2"
+ elif variation == "missing_session":
+ rows["session_id"] = ""
+ else:
+ rows.loc[1, "served_rank"] = 1
+
+ assert deduplicate_lists(rows).empty
+
+
+def test_an_engagement_counts_for_the_list_that_preceded_it():
+ rows = _lists(_served("first", [UUID_A, UUID_B]))
+ outcomes = pd.DataFrame(
+ [
+ {"report_id": UUID_A, "distinct_id": "user-1", "timestamp": SERVED_AT + datetime.timedelta(minutes=2)},
+ # Too late to be this list's doing, and a different person's open is never this one's.
+ {"report_id": UUID_B, "distinct_id": "user-1", "timestamp": SERVED_AT + ATTRIBUTION_WINDOW},
+ {"report_id": UUID_B, "distinct_id": "user-2", "timestamp": SERVED_AT + datetime.timedelta(minutes=2)},
+ ]
+ ).assign(outcome="open")
+
+ engaged = with_outcomes(rows, outcomes)
+
+ assert engaged.set_index("report_id")["outcome_open"].to_dict() == {UUID_A: True, UUID_B: False}
+ assert not engaged["outcome_action"].any()
+
+
+def test_an_engagement_is_credited_to_one_list_only():
+ # 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. Only the last one they saw it in caused the open.
+ rows = _lists(
+ [
+ *_served("first", [UUID_A, UUID_B]),
+ *_served("reordered", [UUID_B, UUID_A], at=SERVED_AT + datetime.timedelta(minutes=1)),
+ ]
+ )
+ outcomes = pd.DataFrame(
+ [{"report_id": UUID_A, "distinct_id": "user-1", "timestamp": SERVED_AT + datetime.timedelta(minutes=2)}]
+ ).assign(outcome="open")
+
+ engaged = with_outcomes(rows, outcomes)
+
+ credited = engaged.loc[engaged["outcome_open"], ["impression_id", "report_id"]]
+ assert credited.to_numpy().tolist() == [["reordered", UUID_A]]
+
+ incomplete = rows.loc[~((rows["impression_id"] == "reordered") & (rows["report_id"] == UUID_B))]
+ complete = deduplicate_lists(with_outcomes(incomplete, outcomes))
+ assert complete["impression_id"].unique().tolist() == ["first"]
+ assert not complete["outcome_open"].any()
+
+
+def test_a_list_only_uses_scores_that_already_existed_when_it_was_served():
+ rows = _lists(_served("first", [UUID_A, UUID_B]))
+ scores = pd.concat(
+ [
+ _scores([UUID_A], [0.9], snapshot_date=DAY - datetime.timedelta(days=3)).assign(
+ available_at=SERVED_AT - datetime.timedelta(hours=1)
+ ),
+ _scores([UUID_A], [0.4], snapshot_date=DAY - datetime.timedelta(days=1)),
+ # A report born on the day it was impressed: the daily job that scores it has not run.
+ _scores([UUID_B], [0.8], snapshot_date=DAY),
+ ],
+ ignore_index=True,
+ )
+
+ joined = join_scores(rows, scores)
+
+ assert joined["report_id"].tolist() == [UUID_A, UUID_B]
+ assert joined["score"].iloc[0] == 0.4
+ assert pd.isna(joined["score"].iloc[1])
+ 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")
+
+ assert served_lists(graded, "open") == []
+
+
+def test_the_model_order_is_graded_against_the_served_order_and_chance():
+ # The served order buries the only report anyone opened; the model scores it highest.
+ 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],
+ )
+
+ grades = {grade.ranking_order: grade for grade in 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
+ assert grades[HEURISTIC_ORDER].mrr == 0.25
+ assert ndcg_5[MODEL_ORDER] == 1.0
+ assert ndcg_5[MODEL_ORDER] > ndcg_5[RANDOM_ORDER] > ndcg_5[HEURISTIC_ORDER]
+ # Only the random line carries a spread: the other two are one deterministic ordering.
+ assert (grades[RANDOM_ORDER].mrr_std or 0.0) > 0
+ assert grades[MODEL_ORDER].mrr_std is None
+ # 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"}
+
+
+def test_a_grade_carries_its_own_score_coverage_not_the_run_s():
+ # A head is scored only on the partitions the training job found it readable on, so one head
+ # can rest on far fewer of a day's served rows than another. The run figure hides that.
+ 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}
+ joined = pd.concat(
+ [served.assign(head="open", **scored), served.head(2).assign(head="action", **scored)],
+ ignore_index=True,
+ )
+
+ coverage = {
+ (grade.outcome, grade.ranking_order): grade.score_coverage for grade in grade_lists(joined, served=served)
+ }
+
+ assert score_coverage(len(served), joined) == 1.0
+ assert coverage[("open", MODEL_ORDER)] == 1.0
+ assert coverage[("action", MODEL_ORDER)] == 0.5
+
+
+def test_the_chance_line_does_not_move_when_the_rows_arrive_in_another_order():
+ # The impression query has no ORDER BY, so a re-run can hand the same rows over differently.
+ # The seeded permutations are applied to the array as it stands, and the partition is history.
+ 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],
+ )
+
+ def chance(frame: pd.DataFrame) -> tuple:
+ grade = next(g for g in grade_lists(frame, served=served) if g.ranking_order == 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():
+ 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)),
+ ]
+ ).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)
+
+ assert grade.lists == 2
+ assert grade.reports == 5
+ assert grade.positive_coverage == 0.5
+ assert grade.full_list_coverage == 0.0
+ assert grade.score_coverage == 0.4
+ 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_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(
+ 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,
+ )
+
+ assert {grade.model_versions for grade in grade_lists(joined, served=served)} == {2}
+
+
+class TestShadowQueries(ClickhouseTestMixin, BaseTest):
+ def _impress(
+ self,
+ impressions: list[dict],
+ *,
+ distinct_id: str = "user-1",
+ at=SERVED_AT,
+ tab: str = "all",
+ list_size: int | None = None,
+ ) -> None:
+ _create_event(
+ team=self.team,
+ event="Inbox reports impressed",
+ distinct_id=distinct_id,
+ timestamp=at,
+ properties={
+ "tab": tab,
+ "scope": "project",
+ "impressions": impressions,
+ "$session_id": "0198c0e8-93c8-7000-8000-a934eeb1b940",
+ "list_size": len(impressions) if list_size is None else list_size,
+ },
+ )
+
+ def _rows(self, sql: str) -> list[tuple]:
+ return hogql_rows(
+ sql,
+ team=self.team,
+ query_type="test",
+ window_start=WINDOW_START,
+ window_end=WINDOW_END + ATTRIBUTION_WINDOW,
+ )
+
+ 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")
+
+ rows = deduplicate_lists(impression_frame(self._rows(IMPRESSION_LISTS_SQL))).to_numpy().tolist()
+
+ lists = {row[0] for row in rows}
+ assert len(lists) == 2
+ by_report = {(row[0], row[5]): row[6] for row in rows}
+ assert sorted(by_report.values()) == [1, 1, 2]
+
+ 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)
+ self._impress(
+ [{"report_id": UUID_B, "rank": 2}],
+ tab="needs-decision",
+ list_size=2,
+ at=SERVED_AT + datetime.timedelta(seconds=1),
+ )
+ self._impress([{"report_id": UUID_A, "rank": 1}], distinct_id="user-2", list_size=2)
+
+ rows = deduplicate_lists(impression_frame(self._rows(IMPRESSION_LISTS_SQL)))
+
+ assert rows["impression_id"].nunique() == 1
+ assert rows.sort_values("served_rank")["report_id"].tolist() == [UUID_A, UUID_B]
+ assert rows["list_size"].tolist() == [2, 2]
+
+ def test_a_report_with_no_usable_rank_cannot_be_placed_in_the_served_order(self):
+ # Ranks are client-supplied; the producer contract is 1-based, so 0 is malformed.
+ self._impress([{"report_id": UUID_A, "rank": 0}, {"report_id": UUID_B, "rank": 1}])
+
+ assert [row[5] for row in self._rows(IMPRESSION_LISTS_SQL)] == [UUID_B]
+
+ def test_opens_and_the_action_head_are_the_only_outcomes_read(self):
+ for action_type in ("create_pr", "discuss", "snooze"):
+ _create_event(
+ team=self.team,
+ event="Inbox report action",
+ distinct_id="user-1",
+ timestamp=SERVED_AT,
+ properties={"report_id": UUID_A, "action_type": action_type},
+ )
+ _create_event(
+ team=self.team,
+ event="Inbox report opened",
+ distinct_id="user-1",
+ timestamp=SERVED_AT,
+ properties={"report_id": UUID_A},
+ )
+
+ outcomes = sorted(row[3] for row in self._rows(OUTCOMES_SQL))
+
+ assert outcomes == ["action", "action", "open"]
+
+
+class _FakeS3:
+ """The scores objects of a lookback window, keyed by their S3 key."""
+
+ def __init__(self, objects: dict[str, bytes]) -> None:
+ self.objects = objects
+
+ def get_object(self, Bucket: str, Key: str) -> dict:
+ if Key not in self.objects:
+ raise ClientError({"Error": {"Code": "NoSuchKey"}}, "GetObject")
+ return {"Body": io.BytesIO(self.objects[Key]), "LastModified": SERVED_AT + datetime.timedelta(hours=1)}
+
+
+def _scores_object(frame: pd.DataFrame) -> bytes:
+ sink = io.BytesIO()
+ pq.write_table(pa.Table.from_pandas(frame, preserve_index=False), sink)
+ return sink.getvalue()
+
+
+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.
+ legacy = _scores([UUID_A], [0.3], snapshot_date=old_day).drop(columns=["model_name", "available_at"])
+ recent = pd.concat(
+ [
+ _scores([UUID_B], [0.7], snapshot_date=new_day).drop(columns=["available_at"]),
+ _scores([UUID_B], [0.2], snapshot_date=new_day, head="pr_merged").drop(columns=["available_at"]),
+ ],
+ ignore_index=True,
+ )
+ client = _FakeS3(
+ {
+ partition_object_key("inbox_ranking", UNSEEN_SCORES_TABLE, old_day.isoformat()): _scores_object(legacy),
+ partition_object_key("inbox_ranking", UNSEEN_SCORES_TABLE, new_day.isoformat()): _scores_object(recent),
+ }
+ )
+
+ scores = load_scores(client, "bucket", "inbox_ranking", [old_day, new_day, DAY])
+
+ assert scores["model_name"].tolist() == ["tabular_xgb", "tabular_xgb"]
+ # Only the heads this read grades, and each one stamped with when it became servable.
+ assert scores["head"].tolist() == ["open", "open"]
+ assert scores["available_at"].tolist() == [SERVED_AT + datetime.timedelta(hours=1)] * 2
+ joined = join_scores(_lists(_served("first", [UUID_A, UUID_B])), scores)
+ assert joined["score"].isna().all()
+
+
+def test_missing_champion_partition_uses_candidate_without_replacing_existing_champion() -> None:
+ old_day, new_day = DAY - datetime.timedelta(days=2), DAY - datetime.timedelta(days=1)
+ shared = _scores([UUID_A], [0.3], snapshot_date=old_day).assign(model_role="candidate")
+ separate = pd.concat(
+ [
+ _scores([UUID_B], [0.7], snapshot_date=new_day),
+ _scores([UUID_B], [0.2], snapshot_date=new_day).assign(model_role="candidate"),
+ ]
+ )
+ client = _FakeS3(
+ {
+ partition_object_key("inbox_ranking", UNSEEN_SCORES_TABLE, old_day.isoformat()): _scores_object(shared),
+ partition_object_key("inbox_ranking", UNSEEN_SCORES_TABLE, new_day.isoformat()): _scores_object(separate),
+ }
+ )
+
+ scores = load_scores(client, "bucket", "inbox_ranking", [old_day, new_day])
+
+ champion = scores.loc[scores["model_role"] == "champion"]
+ assert champion["report_id"].tolist() == [UUID_A, UUID_B]
+ assert champion["score"].tolist() == [0.3, 0.7]
+
+
+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],
+ )
+
+ empty = shadow_grade_events(run_id="run-1", served_rows=12, served_lists=3, run_score_coverage=0.0, grades=[])
+ graded = shadow_grade_events(
+ run_id="run-1",
+ served_rows=2,
+ served_lists=1,
+ run_score_coverage=1.0,
+ grades=grade_lists(joined, served=served),
+ )
+
+ assert [event.event for event in empty] == [SHADOW_RUN_COMPLETED_EVENT]
+ assert empty[0].properties == {
+ "run_id": "run-1",
+ "served_rows": 12,
+ "served_lists": 3,
+ "run_score_coverage": 0.0,
+ "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]
+
+
+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],
+ )
+ graded = grade_rows(
+ grade_lists(joined, served=served),
+ partition_key=DAY.isoformat(),
+ served_rows=2,
+ served_lists=1,
+ run_coverage=1.0,
+ )
+
+ assert set(graded[0]) == set(GRADE_SCHEMA.names)
+ assert pa.Table.from_pylist(graded, schema=GRADE_SCHEMA).num_rows == 3
diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.py
index da6cee8458f3..17c56ff5f3cd 100644
--- a/products/signals/dags/inbox_ranking/training/dag.py
+++ b/products/signals/dags/inbox_ranking/training/dag.py
@@ -109,6 +109,7 @@ from products.signals.dags.inbox_ranking.training.unseen import (
CANDIDATE_ROLE,
CHAMPION_ROLE,
MODEL_FAMILIES,
+ UNSEEN_SCORES_TABLE,
HeadGrade,
ModelFamily,
UnseenModel,
@@ -131,7 +132,6 @@ from products.signals.dags.inbox_ranking.training.unseen import (
)
EXAMPLES_TABLE = "inbox_ranking_training_examples"
-UNSEEN_SCORES_TABLE = "inbox_ranking_unseen_scores"
MODELS_TABLE = "inbox_ranking_models"
CHAMPION_FILE = "champion.json"
METADATA_FILE = "metadata.json"
diff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.py
index 3ddb587120d7..db2c17e5ccc5 100644
--- a/products/signals/dags/inbox_ranking/training/unseen.py
+++ b/products/signals/dags/inbox_ranking/training/unseen.py
@@ -48,6 +48,8 @@ POOL_NAME = "newborn"
# definition puts two populations in one AUC series unless the older one keeps its own name.
LEGACY_POOL_NAME = "sampled"
+UNSEEN_SCORES_TABLE = "inbox_ranking_unseen_scores"
+
CANDIDATE_ROLE = "candidate"
CHAMPION_ROLE = "champion"