: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): daily training dag for the inbox report-ranking model (#85876)
Andrew Maguire5b820cacd18d
diff --git a/posthog/dags/locations/signals.py b/posthog/dags/locations/signals.pyindex ab6aeffc038d..1bb4406ee289 100644--- a/posthog/dags/locations/signals.py+++ b/posthog/dags/locations/signals.py@@ -2,6 +2,7 @@ import dagsterfrom products.signals.dags.inbox_ranking.common import is_inbox_ranking_registeredfrom products.signals.dags.inbox_ranking.dataset import dag as inbox_ranking_dataset+from products.signals.dags.inbox_ranking.training import dag as inbox_ranking_trainingfrom . import loggers, resources@@ -15,9 +16,15 @@ if is_inbox_ranking_registered():inbox_ranking_dataset.inbox_signal_embeddings,inbox_ranking_dataset.inbox_report_labels,inbox_ranking_dataset.inbox_report_model_data,+ inbox_ranking_training.inbox_ranking_training_examples,+ inbox_ranking_training.inbox_ranking_model_candidate,+ inbox_ranking_training.inbox_ranking_model_champion,+ ],+ 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,],- jobs=[inbox_ranking_dataset.inbox_ranking_dataset_job],- schedules=[inbox_ranking_dataset.inbox_ranking_dataset_schedule],loggers=loggers,resources=resources,)diff --git a/posthog/dags/slack_alerts.py b/posthog/dags/slack_alerts.pyindex dea1a689723f..9c050114e462 100644--- a/posthog/dags/slack_alerts.py+++ b/posthog/dags/slack_alerts.py@@ -106,6 +106,7 @@ ASSET_NAME_PREFIX_OWNERS: tuple[tuple[str, JobOwners], ...] = (("web_", JobOwners.TEAM_WEB_ANALYTICS),("inbox_report_", JobOwners.TEAM_SELF_DRIVING),("inbox_signal_", JobOwners.TEAM_SELF_DRIVING),+ ("inbox_ranking_", JobOwners.TEAM_SELF_DRIVING),)diff --git a/posthog/dags/tests/test_slack_alerts.py b/posthog/dags/tests/test_slack_alerts.pyindex 48e6e3b6e529..d4bc196c44dc 100644--- a/posthog/dags/tests/test_slack_alerts.py+++ b/posthog/dags/tests/test_slack_alerts.py@@ -70,6 +70,17 @@ class TestSlackAlertsRouting:assert result == JobOwners.TEAM_SELF_DRIVING.value+ def test_asset_job_with_inbox_ranking_steps_routes_to_self_driving(self):+ mock_run = mock.MagicMock(spec=dagster.DagsterRun)+ mock_run.job_name = "__ASSET_JOB"+ mock_run.tags = {}++ error_message = "Execution of run for \"__ASSET_JOB\" failed. Steps failed: ['inbox_ranking_model_candidate']."++ result = get_job_owner_for_alert(mock_run, error_message)++ assert result == JobOwners.TEAM_SELF_DRIVING.value+def test_asset_job_without_web_steps_uses_original_owner(self):mock_run = mock.MagicMock(spec=dagster.DagsterRun)mock_run.job_name = "__ASSET_JOB"diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.pyindex 5b3798881998..2cd73729dfc7 100644--- a/posthog/settings/object_storage.py+++ b/posthog/settings/object_storage.py@@ -99,6 +99,14 @@ AI_BLOB_S3_PREFIX = os.getenv("AI_BLOB_S3_PREFIX", "aio/")# tables and mlhog training via a separate read-only credential.INBOX_RANKING_DATASET_S3_BUCKET = os.getenv("INBOX_RANKING_DATASET_S3_BUCKET", "")INBOX_RANKING_DATASET_S3_PREFIX = os.getenv("INBOX_RANKING_DATASET_S3_PREFIX", "inbox_ranking")+# Training dag (products/signals/dags/inbox_ranking/training): how many daily snapshots back the+# examples reach, how many trailing days of reports grade a candidate, and whether a winning+# candidate rewrites the champion pointer on its own. Promotion stays manual until the first shadow+# read has a frozen champion to read against; the candidate is still trained and graded daily.+INBOX_RANKING_TRAINING_LOOKBACK_DAYS = get_from_env("INBOX_RANKING_TRAINING_LOOKBACK_DAYS", 60, type_cast=int)+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)# 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 globsdiff --git a/products/signals/backend/ranking/features.py b/products/signals/backend/ranking/features.pynew file mode 100644index 000000000000..82c1f91db299--- /dev/null+++ b/products/signals/backend/ranking/features.py@@ -0,0 +1,91 @@+"""Feature universe for the report-ranking model.++One ordered list of feature names, one function that turns a report-state row into that vector.+Training (`products/signals/dags/inbox_ranking/training/`) and serving (the scoring sweep in this+package) must build features through the same code, so the booster's `feature_names` match the+serving matrix by construction; the model's `metadata.json` records FEATURE_SCHEMA_VERSION and the+serving side refuses a booster whose version or feature names disagree with what it can produce.++v0 is tabular only: the report-state columns the dataset dag snapshots from Postgres plus the+report's age at the scoring moment. No report embedding and no impression-derived columns+(`source_products`), so the sweep needs nothing beyond the SignalReport row and its latest+judgment artefacts. Embeddings wait for the score log to accrue (skill issue 14).+"""++import math+from collections.abc import Mapping+from typing import Any++import pandas as pd++FEATURE_SCHEMA_VERSION = 1++PRIORITY_VALUES = ("P0", "P1", "P2", "P3", "P4")+ACTIONABILITY_VALUES = ("immediately_actionable", "requires_human_input", "not_actionable")++NUMERIC_FEATURES = (+ "signal_count",+ "total_weight",+ "run_count",+ "title_chars",+ "summary_chars",+ "age_hours",+)++FEATURE_NAMES: tuple[str, ...] = (+ *NUMERIC_FEATURES,+ "priority_known",+ *(f"priority_{value}" for value in PRIORITY_VALUES),+ "actionability_known",+ *(f"actionability_{value}" for value in ACTIONABILITY_VALUES),+)+++def _number(value: Any) -> float:+ if value is None:+ return math.nan+ try:+ number = float(value)+ except (TypeError, ValueError):+ return math.nan+ return number if math.isfinite(number) else math.nan+++def feature_vector(row: Mapping[str, Any]) -> list[float]:+ """The feature vector for one scoring moment, in FEATURE_NAMES order.++ `row` carries the report-state columns (`signal_count`, `total_weight`, `run_count`,+ `title_chars`, `summary_chars`, `priority`, `actionability`) and `age_hours`, the report's age+ at the moment being scored. Missing numerics become NaN (XGBoost learns a default direction);+ missing categoricals set the `*_known` flag to 0 with every one-hot at 0.+ """+ values = [_number(row.get(name)) for name in NUMERIC_FEATURES]+ priority = row.get("priority")+ values.append(1.0 if priority in PRIORITY_VALUES else 0.0)+ values.extend(1.0 if priority == value else 0.0 for value in PRIORITY_VALUES)+ actionability = row.get("actionability")+ values.append(1.0 if actionability in ACTIONABILITY_VALUES else 0.0)+ values.extend(1.0 if actionability == value else 0.0 for value in ACTIONABILITY_VALUES)+ return values+++def feature_frame(rows: pd.DataFrame) -> pd.DataFrame:+ """Vectorized `feature_vector` over a frame of report-state rows, columns in FEATURE_NAMES order.++ Must agree with `feature_vector` row for row (a test pins it): training builds matrices here,+ the sweep scores one report at a time through `feature_vector`.+ """+ out = pd.DataFrame(index=rows.index)+ for name in NUMERIC_FEATURES:+ out[name] = pd.to_numeric(rows[name], errors="coerce").astype(float) if name in rows else math.nan+ priority = rows["priority"] if "priority" in rows else pd.Series(None, index=rows.index, dtype=object)+ out["priority_known"] = priority.isin(PRIORITY_VALUES).astype(float)+ for value in PRIORITY_VALUES:+ out[f"priority_{value}"] = (priority == value).astype(float)+ actionability = (+ rows["actionability"] if "actionability" in rows else pd.Series(None, index=rows.index, dtype=object)+ )+ out["actionability_known"] = actionability.isin(ACTIONABILITY_VALUES).astype(float)+ for value in ACTIONABILITY_VALUES:+ out[f"actionability_{value}"] = (actionability == value).astype(float)+ return out[list(FEATURE_NAMES)]diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.mdindex 1b4623b8f2ec..a986bde3141b 100644--- a/products/signals/dags/inbox_ranking/AGENTS.md+++ b/products/signals/dags/inbox_ranking/AGENTS.md@@ -7,6 +7,15 @@ Read `README.md` first for what the dataset is and how partitions behave. This f- A new ranking dag (training, eval, ...) is a **sibling subpackage** (`inbox_ranking/<name>/dag.py`) importing shared plumbing from `common.py` — don't grow `dataset/` sideways and don't duplicate the S3/partition helpers.- Register new jobs/schedules in `posthog/dags/locations/signals.py`, keep the EU gate (`is_inbox_ranking_registered()`), and remember the ci-dagster paths filter must cover every module a dag file imports (`uv run .github/scripts/check-dagster-paths.py`).+## Training dag specifics++- `products/signals/backend/ranking/features.py` is the serving contract (it lives in the backend so the scoring sweep owns it and the dag imports it): the training code and the sweep both import `FEATURE_NAMES` / `feature_vector`, and the sweep refuses a booster whose `feature_names` or `feature_schema_version` disagree. Adding a feature means bumping `FEATURE_SCHEMA_VERSION`, and the sweep must be able to compute it from the `SignalReport` row at scoring time — nothing impression-derived, nothing that needs the label streams.+- `feature_vector` (one row, serving) and `feature_frame` (vectorized, training) must agree row for row; a test pins it. Change both together.+- Examples are scoring moments (every report × every snapshot), labeled from the snapshot `horizon_days` later. Keep the holdout cut by report; a row-level split leaks near-duplicate snapshots of the same report.+- `inbox_ranking_models/v1/dt=D/` is history like the dataset partitions: the only mutation is a re-run of the same partition, which replaces the prefix in full (stale head files are deleted). `champion.json` is the only object written outside its partition, and only the champion asset (or a human, deliberately) writes it; it carries the candidate's `run_id`, so a loader can detect a re-run behind a pinned version.+- 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`.+## 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.mdindex 73ef49bd35db..a52fcbc4623a 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -1,7 +1,6 @@# Inbox ranking Dagster dags-Dagster jobs for the Self-driving Inbox report-ranking model.-The one dag today is the **dataset** dag; future ranking dags (training, eval) live as sibling subpackages sharing `common.py`.+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`.```textinbox_ranking/@@ -9,6 +8,12 @@ inbox_ranking/├── dataset/│ ├── dag.py # the five dataset assets + job + schedule│ └── queries.py # HogQL label SQL, embeddings SQL, stream merging+├── training/+│ ├── dag.py # examples → candidate → champion assets + job + schedule+│ ├── examples.py # scoring-moment training examples over the snapshots+│ ├── heads.py # the v0 outcome heads+│ ├── train.py # per-head XGBoost fit + holdout/null metrics+│ └── promotion.py # the champion promotion rule└── tests/```@@ -52,12 +57,35 @@ The first four are report grain and land in one table. `inbox_signal_embeddings`- The count check remains as a backstop: a union can only grow, so a smaller result means the merge itself is broken and the write is refused. Row counts are stamped in S3 object metadata at write time to make that check a `head_object`. A deliberate shrink still means deleting the object by hand.- Signal text never leaves ClickHouse: the query selects the vector and the structured metadata (weight, source, match graph), not `content` or the free-text metadata fields.+## The training dag++`inbox_ranking_training_job` runs daily at 06:00 UTC on the same partition definition (gated like the dataset job) and writes:++```text+s3://<bucket>/<prefix>/+├── inbox_ranking_training_examples/v1/dt=YYYY-MM-DD/ # scoring-moment examples, all heads, one parquet+└── inbox_ranking_models/v1/+ ├── dt=YYYY-MM-DD/<head>.ubj + <head>.holdout.ubj # the day's candidate: serving fit + train-only fit+ │ + metadata.json # (a re-run replaces this prefix in full)+ └── champion.json # pointer the scoring sweep loads (the only object written across partitions)+```++- **Examples are scoring moments, not reports.** For partition `dt=D` the examples asset reads the report-state and labels snapshots `dt=D-lookback..D` and emits one row per (report, snapshot) whose head label is still 0 on that snapshot, labeled from the snapshot `horizon_days` later (3 for open, 7 for action / dismiss_wrong / pr_created). Features are that snapshot's state columns plus `age_hours`, the report's age at the snapshot. Labels are aligned to the state spine, so a report with no label event is a negative (all-zero labels), not absent. Label-only rows (no Postgres state) are skipped, as are state rows read long after their snapshot day (backfills carry current Postgres state; see `features_observed_at`) and, for the `dismiss_wrong` head, rows whose status telemetry fails the dataset's `label_provenance_ok` check. This is the serving situation replayed over history; it measured better than one row per report on the engagement heads.+- **Serving population caveat.** Training keeps only moments where the head's outcome has not happened yet, but the scoring sweep cannot see outcome state, so it also scores reports that were already opened or acted on. `p_open` on an already-opened report is undefined; the shadow eval joins scores as of impression time, which keeps the read honest. Stopping a head once its outcome is observed is a sweep-side change.+- **Features are tabular only in v0** (`products/signals/backend/ranking/features.py`: the state counters, title/summary length, age, one-hot priority/actionability). No embedding, no impression-derived columns, so the scoring sweep needs only the `SignalReport` row and its judgment artefacts. The sweep must build features through the same module; the booster's `feature_names` are checked against it at load.+- **Candidate**: per-head XGBoost with fixed params, holdout = the last `holdout_days` of reports (cut by report, never by row), AUC + a label-permutation null. A head is _readable_ when it has enough holdout positives and clears its null by 0.05. The shipped booster (`<head>.ubj`) is refit on everything; the train-only fit is kept as `<head>.holdout.ubj` so a later candidate can grade this model on its own holdout.+- **Champion**: `promotion.decide_promotion` — promote when the candidate has a readable head, is within 0.02 AUC of the champion on every head the champion could read, and the champion is at least `INBOX_RANKING_PROMOTION_MIN_DAYS` old. The champion's AUCs come from its `<head>.holdout.ubj` scored on the candidate's holdout (`paired_champion_aucs`), so both models are compared on one set of reports; a champion without that file falls back to its stored AUC. The pointer is rewritten only when `INBOX_RANKING_AUTO_PROMOTE` is on; otherwise the decision is logged and surfaced as asset metadata, so the daily candidate series is monitoring while the first shadow read runs on a frozen champion. To promote by hand, copy a candidate's `metadata.json` to `champion.json` with a `promoted_at`.+### 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. |+| 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. |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.@@ -68,7 +96,7 @@ All reads route to the offline cluster replicas on Cloud (`etl_workload()`), car### 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_` and `inbox_signal_` asset-name prefixes.+- 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.### Deletion and retentiondiff --git a/products/signals/dags/inbox_ranking/common.py b/products/signals/dags/inbox_ranking/common.pyindex da93e27ab81b..0762a2372f0e 100644--- a/products/signals/dags/inbox_ranking/common.py+++ b/products/signals/dags/inbox_ranking/common.py@@ -31,6 +31,11 @@ PARQUET_PART_NAME = "part-00000.parquet"# label bound 7-8 hours off the UTC partition boundary. An embedded offset overrides that.LABELS_EPOCH = "2026-04-01T00:00:00+00:00"+# Dismissal reasons that mean the report itself was wrong (the precision failure the dismiss_wrong+# head predicts). already_fixed and wontfix_irrelevant are deliberately not here. Shared by the+# labels SQL (cumulative count) and the head definition.+WRONG_DISMISSAL_REASONS = ("analysis_wrong", "report_unclear", "wontfix_intentional")+partition_def = dagster.DailyPartitionsDefinition(start_date="2026-04-01")owner_tags: dict[str, str] = {"owner": JobOwners.TEAM_SELF_DRIVING.value}diff --git a/products/signals/dags/inbox_ranking/dataset/dag.py b/products/signals/dags/inbox_ranking/dataset/dag.pyindex fbe606dd11ac..78eaa1f4ccdd 100644--- a/products/signals/dags/inbox_ranking/dataset/dag.py+++ b/products/signals/dags/inbox_ranking/dataset/dag.py@@ -92,7 +92,7 @@ from products.signals.dags.inbox_ranking.dataset.queries import (valid_report_uuids,)-FEATURE_SCHEMA_VERSION = 3+FEATURE_SCHEMA_VERSION = 4# Statuses a report can be authored straight into and still be in the inbox (`create_scout_report`# and `create_custom_agent_ready_report`), which is how a report reaches the spine without a@@ -224,6 +224,7 @@ LABEL_FIELDS: list[tuple[str, pa.DataType]] = [("latest_status_event", pa.string()),("latest_status_event_at", _TIMESTAMP),("dismissal_reason", pa.string()),+ ("wrong_dismissal_count", pa.int32()),("status_event_priority", pa.string()),("status_event_actionability", pa.string()),("status_event_team_id", pa.int64()),diff --git a/products/signals/dags/inbox_ranking/dataset/queries.py b/products/signals/dags/inbox_ranking/dataset/queries.pyindex c9a643e3041e..b44d48099d54 100644--- a/products/signals/dags/inbox_ranking/dataset/queries.py+++ b/products/signals/dags/inbox_ranking/dataset/queries.py@@ -21,7 +21,7 @@ from posthog.clickhouse.client.connection import Workloadfrom posthog.cloud_utils import is_cloudfrom posthog.models import Team-from products.signals.dags.inbox_ranking.common import LABELS_EPOCH, ensure_utc+from products.signals.dags.inbox_ranking.common import LABELS_EPOCH, WRONG_DISMISSAL_REASONS, ensure_utc# All regions' label telemetry lands in the US dogfood project (PostHog internal, team 2).LABELS_TEAM_ID = 2@@ -324,6 +324,8 @@ WHERE event = 'Inbox report action'GROUP BY report_id"""+_WRONG_DISMISSAL_REASONS_SQL = ", ".join(f"'{reason}'" for reason in WRONG_DISMISSAL_REASONS)+STATUS_COLUMNS = ("first_resolved_at","first_dismissed_server_at",@@ -332,6 +334,7 @@ STATUS_COLUMNS = ("latest_status_event","latest_status_event_at","dismissal_reason",+ "wrong_dismissal_count","status_event_priority","status_event_actionability","status_event_team_id",@@ -348,7 +351,8 @@ STATUS_COLUMNS = (# capture_status_change_analytics snapshots them onto every transition: artefacts can be re-judged# or edited, so the state asset's cutoff-observed judgment is not necessarily what was true when# the outcome happened. Both are kept — state for features, these for label-time provenance.-STATUS_SQL = """+STATUS_SQL = (+ """SELECTreport_id,nullIf(minIf(first_timestamp, outcome = 'resolved'), fromUnixTimestamp(0)) AS first_resolved_at,@@ -359,8 +363,21 @@ SELECTmax(last_timestamp) AS latest_status_event_at,-- argMax skips NULL values, so this is the reason from the latest *reasoned* transition (the-- intended semantic: reasons only accompany dismissals/snoozes), not necessarily paired with- -- latest_status_event above.- argMax(dismissal_reason, last_timestamp) AS dismissal_reason,+ -- latest_status_event above. Restricted to the latest transition's tenant, like the count+ -- below: a reason-less genuine transition must not let an older reason from another team+ -- through.+ argMaxIf(bucket_dismissal_reason, last_timestamp, event_team_id = latest_event_team_id) AS dismissal_reason,+ -- Cumulative, unlike dismissal_reason above: a restore or a later dismissal with another reason+ -- overwrites the latest-wins reason, and a label that can revert to 0 breaks the training+ -- builder's assumption that labels only grow. Counted per bucket (a bucket that saw any wrong+ -- reason counts once, so a same-bucket re-dismissal cannot erase it) and only for buckets that+ -- name the same tenant as the latest transition, which is the event the provenance+ -- cross-check validates against Postgres. Buckets are split by tenant, so the flag and the+ -- team it is checked against always come from the same events. The dismiss_wrong head reads+ -- this column.+ countIf(+ outcome = 'dismissed' AND bucket_wrong_dismissal = 1 AND event_team_id = latest_event_team_id+ ) AS wrong_dismissal_count,-- These two must stay paired with latest_status_event, so coalesce/nullIf keeps argMax from-- skipping a null: a judgment artefact can be deleted, and then the latest transition-- genuinely carries none. Plain argMax would reach back to an older transition and present@@ -371,9 +388,20 @@ SELECT-- label-only row can have: reports outside this dag's region have no Postgres state and no-- embedding here. Deliberately *not* merged into report_team_id, which is a US team id by-- construction — team ids are per-region, so an EU 42 and a US 42 are different teams and- -- nothing on the event says which region emitted it.- toInt(argMax(coalesce(event_team_id, ''), last_timestamp)) AS status_event_team_id+ -- nothing on the event says which region emitted it. Read from the window column rather than+ -- selected again, so the tenant the provenance check sees is the one the aggregates above+ -- filtered on, even when two tenants' buckets tie on last_timestamp.+ toInt(any(latest_event_team_id)) AS status_event_team_idFROM (+ SELECT+ *,+ -- The team the latest transition reported, on every bucket row, so an aggregate above can+ -- filter on it (ClickHouse does not allow an aggregate inside another aggregate). The+ -- tenant is the tie-breaker so the selection is deterministic.+ argMax(+ coalesce(event_team_id, ''), tuple(last_timestamp, coalesce(event_team_id, ''))+ ) OVER (PARTITION BY report_id) AS latest_event_team_id+ FROM (SELECTmin(events.timestamp) AS first_timestamp,max(events.timestamp) AS last_timestamp,@@ -389,22 +417,33 @@ FROM () AS outcome,-- Latest event in the bucket rather than any(): identical for the duplicate deliveries this-- grouping targets, and the one that matches last_timestamp when it collapsed real repeats.- nullIf(argMax(toString(properties.dismissal_reason), events.timestamp), '') AS dismissal_reason,+ -- Named apart from the outer alias: ClickHouse resolves a bare `dismissal_reason` in the outer+ -- aggregates to the outer alias, which is itself an aggregate.+ nullIf(argMax(toString(properties.dismissal_reason), events.timestamp), '') AS bucket_dismissal_reason,+ max(toString(properties.dismissal_reason) IN ("""+ + _WRONG_DISMISSAL_REASONS_SQL+ + """)) AS bucket_wrong_dismissal,nullIf(argMax(toString(properties.priority), events.timestamp), '') AS event_priority,nullIf(argMax(toString(properties.actionability), events.timestamp), '') AS event_actionability,- nullIf(argMax(toString(properties.team_id), events.timestamp), '') AS event_team_id+ nullIf(toString(properties.team_id), '') AS event_team_idFROM eventsWHERE event = 'signal_report_status_changed'AND events.timestamp >= toDateTime({labels_epoch}) AND events.timestamp < toDateTime({snapshot_end})AND toString(properties.report_id) != ''+ -- The tenant is part of the bucket key: an event naming another team never shares a bucket+ -- with the genuine transition it collides with, so its reason cannot be counted under the+ -- genuine event's team.GROUP BYreport_id,previous_status,status,+ event_team_id,toStartOfInterval(events.timestamp, INTERVAL 10 MINUTE)+ ))GROUP BY report_id"""+)PR_COLUMNS = ("pr_created_count",@@ -520,6 +559,7 @@ LABEL_DEFAULTS: dict[str, Any] = {"latest_status_event": None,"latest_status_event_at": None,"dismissal_reason": None,+ "wrong_dismissal_count": 0,"status_event_priority": None,"status_event_actionability": None,"status_event_team_id": None,diff --git a/products/signals/dags/inbox_ranking/tests/test_dataset.py b/products/signals/dags/inbox_ranking/tests/test_dataset.pyindex e2ad635dc414..c703a690efb9 100644--- a/products/signals/dags/inbox_ranking/tests/test_dataset.py+++ b/products/signals/dags/inbox_ranking/tests/test_dataset.py@@ -2,9 +2,10 @@ import datetimefrom typing import Anyimport pytest-from posthog.test.base import BaseTest+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_eventimport pyarrow as pa+from parameterized import parameterizedfrom products.signals.backend.models import SignalReportfrom products.signals.dags.inbox_ranking import common@@ -17,6 +18,9 @@ from products.signals.dags.inbox_ranking.dataset.dag import (from products.signals.dags.inbox_ranking.dataset.queries import (LABEL_DEFAULTS,LABEL_STREAMS,+ STATUS_COLUMNS,+ STATUS_SQL,+ hogql_rows,merge_label_streams,utc_bound,valid_report_uuids,@@ -345,3 +349,76 @@ class TestSpineInclusion(BaseTest):assert in_spine == {promoted, born_visible}assert promoted_after_cutoff not in in_spineassert created_after_cutoff not in in_spine+++class TestStatusStream(ClickhouseTestMixin, BaseTest):+ def _transition(+ self,+ when: datetime.datetime,+ previous: str,+ status: str,+ reason: str | None = None,+ *,+ team_id: int | None = None,+ ) -> None:+ _create_event(+ team=self.team,+ event="signal_report_status_changed",+ distinct_id="team-2",+ timestamp=when,+ properties={+ "report_id": UUID_A,+ "previous_status": previous,+ "status": status,+ "dismissal_reason": reason,+ "team_id": str(team_id or self.team.id),+ },+ )++ def _status_row(self) -> dict[str, Any]:+ rows = hogql_rows(STATUS_SQL, team=self.team, query_type="test", snapshot_end=SNAPSHOT_END)+ assert len(rows) == 1+ return dict(zip(STATUS_COLUMNS, rows[0][1:], strict=True))++ @parameterized.expand([(datetime.timedelta(hours=1),), (datetime.timedelta(minutes=1),)])+ def test_wrong_dismissal_count_survives_a_restore_and_a_later_reason(self, gap):+ # dismissed as wrong, restored, then dismissed again as already_fixed: the latest-wins reason+ # forgets the wrong dismissal, the cumulative count must not, even when all three land in one+ # ten-minute dedupe bucket.+ self._transition(T1, "ready", "suppressed", "analysis_wrong")+ self._transition(T1 + gap, "suppressed", "ready")+ self._transition(T1 + 2 * gap, "ready", "suppressed", "already_fixed")++ row = self._status_row()+ assert row["dismissal_reason"] == "already_fixed"+ assert row["wrong_dismissal_count"] == 1+ assert row["first_dismissed_server_at"] == T1++ @parameterized.expand(+ [+ ("later_bucket", T2, "ready", "resolved", None),+ ("same_bucket", T1 + datetime.timedelta(minutes=1), "ready", "suppressed", "already_fixed"),+ ]+ )+ def test_wrong_dismissal_count_ignores_events_from_another_tenant(self, _name, when, previous, status, reason):+ # A forged wrong dismissal naming another team, followed by a genuine transition, must not+ # make the report a dismiss_wrong positive through the cumulative count. The same-bucket+ # case lands both in one ten-minute dedupe bucket, where the bucket's wrong flag and the+ # bucket's tenant would otherwise come from different events.+ self._transition(T1, "ready", "suppressed", "analysis_wrong", team_id=999)+ self._transition(when, previous, status, reason)++ row = self._status_row()+ assert row["status_event_team_id"] == self.team.id+ assert row["dismissal_reason"] == reason+ assert row["wrong_dismissal_count"] == 0++ def test_tied_tenants_count_and_report_the_same_team(self):+ # Two tenants' buckets with the same last timestamp: whichever wins the tie, the count and+ # the team the provenance check reads must come from the same selection, or a forged wrong+ # dismissal could be counted while the genuine tenant passes provenance.+ self._transition(T1, "ready", "suppressed", "analysis_wrong", team_id=999)+ self._transition(T1, "ready", "suppressed", "already_fixed")++ row = self._status_row()+ assert row["wrong_dismissal_count"] == (0 if row["status_event_team_id"] == self.team.id else 1)diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.pynew file mode 100644index 000000000000..c41fd94dfc7a--- /dev/null+++ b/products/signals/dags/inbox_ranking/tests/test_training.py@@ -0,0 +1,418 @@+import math+import datetime++import pytest++import numpy as np+import pandas as pd+import dagster+import xgboost as xgb+from botocore.exceptions import ClientError++from posthog import settings++from products.signals.backend.ranking.features import FEATURE_NAMES, feature_frame, feature_vector+from products.signals.dags.inbox_ranking.dataset.dag import LABELS_TABLE, STATE_TABLE+from products.signals.dags.inbox_ranking.training.dag import (+ _delete_other_objects,+ champion_object_key,+ inbox_ranking_training_examples,+ load_snapshots,+ model_object_key,+ snapshot_dates,+)+from products.signals.dags.inbox_ranking.training.examples import (+ EXAMPLE_COLUMNS,+ STATE_LAG_LIMIT,+ Snapshot,+ assemble_snapshot,+ build_examples,+ holdout_mask,+)+from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, dismissed_as_wrong+from products.signals.dags.inbox_ranking.training.promotion import AUC_TOLERANCE, decide_promotion+from products.signals.dags.inbox_ranking.training.train import _head_readable, booster_holdout_auc, train_head++D0 = datetime.date(2026, 8, 10)+NOW = datetime.datetime(2026, 8, 20, tzinfo=datetime.UTC)+++def _state(report_ids: list[str], **overrides) -> pd.DataFrame:+ n = len(report_ids)+ base = {+ "report_created_at": [pd.Timestamp("2026-08-09T12:00:00Z")] * n,+ "report_age_hours": [12.0] * n,+ "signal_count": [3] * n,+ "total_weight": [1.5] * n,+ "run_count": [1] * n,+ "title_chars": [40] * n,+ "summary_chars": [400] * n,+ "priority": ["P2"] * n,+ "actionability": ["immediately_actionable"] * n,+ }+ base.update(overrides)+ return pd.DataFrame(base, index=pd.Index(report_ids, name="report_id"))+++def _labels(report_ids: list[str], **overrides) -> pd.DataFrame:+ n = len(report_ids)+ base = {+ "impression_unit_count": [1] * n,+ "open_count": [0] * n,+ "create_pr_click_count": [0] * n,+ "discuss_count": [0] * n,+ "dismissal_reason": [None] * n,+ "pr_created_count": [0] * n,+ }+ base.update(overrides)+ return pd.DataFrame(base, index=pd.Index(report_ids, name="report_id"))+++ "row",+ [+ {+ "signal_count": 3,+ "total_weight": 1.5,+ "run_count": 1,+ "title_chars": 40,+ "summary_chars": 400,+ "priority": "P1",+ "actionability": "not_actionable",+ "age_hours": 5.0,+ },+ {+ "signal_count": None,+ "total_weight": float("nan"),+ "run_count": 2,+ "title_chars": 0,+ "summary_chars": 0,+ "priority": None,+ "actionability": "bogus",+ "age_hours": 100.0,+ },+ {},+ ],+)+def test_feature_vector_matches_feature_frame(row):+ # The sweep scores one report at a time through feature_vector; training builds matrices+ # through feature_frame. They must agree or the booster sees a different universe at serve time.+ vector = feature_vector(row)+ frame = feature_frame(pd.DataFrame([row]) if row else pd.DataFrame([{}]))+ assert len(vector) == len(FEATURE_NAMES) == frame.shape[1]+ for name, value, column_value in zip(FEATURE_NAMES, vector, frame.iloc[0].tolist(), strict=True):+ assert (math.isnan(value) and math.isnan(column_value)) or value == column_value, name+++def test_build_examples_is_a_scoring_moment_with_a_future_label():+ open_head = HEADS_BY_NAME["open"]+ later = D0 + datetime.timedelta(days=open_head.horizon_days)+ ids = ["a", "b", "c", "d"]+ snapshots = {+ # a: not yet impressed or opened at D0, impressed and opened by D0+3 -> positive;+ # b: already opened at D0 -> excluded; c: never opened -> negative;+ # d: never impressed -> outside the cohort.+ D0: Snapshot(+ date=D0,+ state=_state(ids),+ labels=_labels(ids, open_count=[0, 1, 0, 0], impression_unit_count=[0, 1, 1, 0]),+ ),+ later: Snapshot(+ date=later,+ state=_state(ids),+ labels=_labels(ids, open_count=[2, 3, 0, 0], impression_unit_count=[1, 1, 1, 0]),+ ),+ # A snapshot with no horizon partner contributes nothing.+ later + datetime.timedelta(days=1): Snapshot(date=later, state=_state(ids), labels=_labels(ids)),+ }+ examples = build_examples(snapshots, open_head)+ assert list(examples.columns) == list(EXAMPLE_COLUMNS)+ assert examples.set_index("report_id")["label"].to_dict() == {"a": 1, "c": 0}+ assert (examples["snapshot_date"] == D0).all()+ assert (examples["age_hours"] == 12.0).all()+++def test_assemble_snapshot_makes_never_labeled_reports_negatives_and_drops_untrusted_status_rows():+ head = HEADS_BY_NAME["pr_created"]+ later = D0 + datetime.timedelta(days=head.horizon_days)+ ids = ["a", "b", "c", "gone"]+ # a: status telemetry names another tenant -> provenance fails; b: no label row at all;+ # c: trusted, dismissed as wrong by the horizon; gone: hard-deleted before the horizon, so the+ # later snapshot has its label row but no state row.+ state = _state(+ ids,+ report_team_id=[1, 1, 1, 1],+ status=["ready"] * 4,+ pg_updated_at=[pd.Timestamp("2026-08-09T12:00:00Z")] * 4,+ )+ labels_now = _labels(["a", "c"], latest_status_event=["suppressed", None], status_event_team_id=[99, None])+ labels_later = _labels(+ ["a", "c", "gone"],+ latest_status_event=["suppressed", "suppressed", None],+ status_event_team_id=[99, 1, None],+ wrong_dismissal_count=[1, 1, 0],+ pr_created_count=[0, 1, 1],+ )+ state_later = state.drop("gone").assign(status=["ready", "ready", "suppressed"])+ snapshots = {+ D0: assemble_snapshot(D0, state, labels_now),+ later: assemble_snapshot(later, state_later, labels_later),+ }++ assert snapshots[D0].labels.loc["b", "impression_unit_count"] == 0+ assert snapshots[D0].labels["label_provenance_ok"].to_dict() == {"a": False, "b": True, "c": True, "gone": True}+ assert snapshots[later].labels["label_provenance_ok"].to_dict() == {"a": False, "b": True, "c": True, "gone": False}+ # pr_created reads the tasks webhook, so a's untrusted status telemetry does not exclude it there.+ pr = build_examples(snapshots, head).set_index("report_id")["label"].to_dict()+ assert pr == {"a": 0, "b": 0, "c": 1, "gone": 1}+ # dismiss_wrong reads the status stream: a is dropped, b was never impressed, c is a positive.+ wrong = build_examples(snapshots, HEADS_BY_NAME["dismiss_wrong"]).set_index("report_id")["label"].to_dict()+ assert wrong == {"c": 1}+++def test_build_examples_drops_state_rows_read_long_after_their_snapshot():+ head = HEADS_BY_NAME["pr_created"]+ later = D0 + datetime.timedelta(days=head.horizon_days)+ forward_run = pd.Timestamp(D0 + datetime.timedelta(days=1), tz="UTC") + pd.Timedelta(hours=3)+ backfill = pd.Timestamp(D0 + datetime.timedelta(days=1), tz="UTC") + STATE_LAG_LIMIT + pd.Timedelta(hours=1)+ state = _state(["a", "b"], features_observed_at=[forward_run, backfill])+ snapshots = {+ D0: Snapshot(date=D0, state=state, labels=_labels(["a", "b"])),+ later: Snapshot(date=later, state=state, labels=_labels(["a", "b"])),+ }+ assert build_examples(snapshots, head)["report_id"].tolist() == ["a"]+++ "frame,expected",+ [+ # The cumulative count wins: a wrong dismissal later overwritten by already_fixed stays positive.+ (+ pd.DataFrame({"wrong_dismissal_count": [1, 0], "dismissal_reason": ["already_fixed", "analysis_wrong"]}),+ [True, False],+ ),+ # Partitions written before the count existed fall back to the latest-wins reason.+ (pd.DataFrame({"dismissal_reason": ["already_fixed", "analysis_wrong"]}), [False, True]),+ ],+)+def test_dismissed_as_wrong_prefers_the_cumulative_count(frame, expected):+ assert dismissed_as_wrong(frame).tolist() == expected+++def test_build_examples_skips_label_only_rows():+ head = HEADS_BY_NAME["pr_created"]+ later = D0 + datetime.timedelta(days=head.horizon_days)+ state = _state(["a", "eu"], signal_count=[3, None])+ snapshots = {+ D0: Snapshot(date=D0, state=state, labels=_labels(["a", "eu"])),+ later: Snapshot(date=later, state=state, labels=_labels(["a", "eu"], pr_created_count=[1, 1])),+ }+ assert build_examples(snapshots, head)["report_id"].tolist() == ["a"]+++def test_holdout_mask_cuts_by_report_not_by_row():+ examples = pd.DataFrame(+ {+ "report_id": ["old", "old", "new", "new"],+ "report_created_at": pd.to_datetime(["2026-08-01", "2026-08-01", "2026-08-18", "2026-08-18"], utc=True),+ }+ )+ assert holdout_mask(examples, holdout_days=7).tolist() == [False, False, True, True]+++def test_train_head_learns_a_separable_signal_and_names_its_features():+ head = HEADS_BY_NAME["open"]+ rng = np.random.default_rng(0)+ n = 2000+ created = pd.to_datetime("2026-07-01", utc=True) + pd.to_timedelta(rng.integers(0, 40, n), unit="D")+ signal_count = rng.integers(1, 50, n)+ rows = pd.DataFrame(+ {+ "signal_count": signal_count,+ "total_weight": rng.random(n),+ "run_count": 1,+ "title_chars": 40,+ "summary_chars": 400,+ "priority": "P2",+ "actionability": None,+ "age_hours": 12.0,+ }+ )+ examples = feature_frame(rows)+ examples.insert(0, "head", head.name)+ examples.insert(1, "report_id", [f"r{i}" for i in range(n)])+ examples.insert(2, "snapshot_date", D0)+ examples.insert(3, "report_created_at", created)+ examples["label"] = (signal_count > 25).astype(int)++ trained = train_head(examples, head, holdout_days=7)+ assert trained is not None+ assert trained.metrics.readable+ assert trained.metrics.holdout_auc is not None and trained.metrics.holdout_auc > 0.9+ assert trained.metrics.null_auc is not None and abs(trained.metrics.null_auc - 0.5) < 0.15+ booster = xgb.Booster()+ booster.load_model(bytearray(trained.booster_ubj))+ assert booster.feature_names == list(FEATURE_NAMES)+ # The saved holdout fit graded on the same rows must reproduce the stored metric: this is the+ # path the champion gate uses to compare two models on one holdout.+ assert trained.holdout_booster_ubj is not None+ paired = booster_holdout_auc(trained.holdout_booster_ubj, examples, head, holdout_days=7)+ assert paired == pytest.approx(trained.metrics.holdout_auc, abs=1e-6)+ # A booster from another feature schema is not scorable on these examples: the gate must fall+ # back to the stored AUC instead of failing the champion asset every day.+ other_schema = xgb.XGBClassifier(n_estimators=2).fit(pd.DataFrame({"not_a_feature": [0, 1, 0, 1]}), [0, 1, 0, 1])+ other_ubj = bytes(other_schema.get_booster().save_raw("ubj"))+ assert booster_holdout_auc(other_ubj, examples, head, holdout_days=7) is None+++def test_train_head_returns_none_without_both_classes():+ head = HEADS_BY_NAME["open"]+ examples = pd.DataFrame(+ {+ "head": [head.name] * 3,+ "report_id": ["a", "b", "c"],+ "snapshot_date": D0,+ "report_created_at": pd.to_datetime(["2026-08-01"] * 3, utc=True),+ "label": [0, 0, 0],+ }+ )+ for name in FEATURE_NAMES:+ examples[name] = 1.0+ assert train_head(examples, head, holdout_days=7) is None+++ "holdout_auc,null_auc,holdout_positives,expected",+ [+ (0.46, 0.40, 50, False), # below chance, yet clears the null margin: the floor must reject it+ (0.70, 0.50, 50, True), # above chance, clears the margin, enough positives+ ],+)+def test_head_readable_requires_above_chance_auc(holdout_auc, null_auc, holdout_positives, expected):+ assert _head_readable(holdout_auc, null_auc, holdout_positives, min_positives=30) is expected+++def _metadata(version: str, **aucs: float | None) -> dict:+ return {+ "model_version": version,+ "heads": [{"head": head, "holdout_auc": auc, "readable": auc is not None} for head, auc in aucs.items()],+ }+++ "candidate,champion,expected_promote,reason_fragment",+ [+ (_metadata("d2", open=0.65), None, True, "no champion"),+ (_metadata("d2", open=None), None, False, "no readable head"),+ (+ _metadata("d2", open=0.65),+ {**_metadata("d1", open=0.64), "promoted_at": "2026-08-10T00:00:00+00:00"},+ True,+ "at or above",+ ),+ (+ _metadata("d2", open=0.65 - AUC_TOLERANCE - 0.01),+ {**_metadata("d1", open=0.65), "promoted_at": "2026-08-10T00:00:00+00:00"},+ False,+ "regressed",+ ),+ (+ _metadata("d2", open=0.70),+ {**_metadata("d1", open=0.65), "promoted_at": "2026-08-19T00:00:00+00:00"},+ False,+ "less than 3d ago",+ ),+ (+ _metadata("d2", open=0.70),+ {**_metadata("d1", open=0.65, action=0.6), "promoted_at": "2026-08-10T00:00:00+00:00"},+ False,+ "action readable on champion but not on candidate",+ ),+ # A backfilled older candidate, even a much better one, must not roll the champion backwards.+ (+ _metadata("2026-08-11", open=0.90),+ {**_metadata("2026-08-12", open=0.65), "promoted_at": "2026-08-10T00:00:00+00:00"},+ False,+ "not newer",+ ),+ # Re-running the champion's own partition must not re-promote it.+ (+ _metadata("2026-08-12", open=0.90),+ {**_metadata("2026-08-12", open=0.65), "promoted_at": "2026-08-10T00:00:00+00:00"},+ False,+ "not newer",+ ),+ ],+)+def test_decide_promotion(candidate, champion, expected_promote, reason_fragment):+ decision = decide_promotion(candidate, champion, now=NOW, min_days_between=3)+ assert decision.promote is expected_promote+ assert reason_fragment in decision.reason+++def test_decide_promotion_grades_the_champion_on_the_candidate_holdout():+ candidate = _metadata("d2", open=0.66)+ champion = {**_metadata("d1", open=0.60), "promoted_at": "2026-08-10T00:00:00+00:00"}+ assert decide_promotion(candidate, champion, now=NOW, min_days_between=3).promote+ # Paired on this holdout the champion is stronger than its stored number said.+ paired = decide_promotion(candidate, champion, now=NOW, min_days_between=3, champion_aucs={"open": 0.75})+ assert not paired.promote and "regressed" in paired.reason+++class _FakeS3:+ def __init__(self, keys: list[str]):+ self.keys = set(keys)+ self.deleted: list[str] = []++ def get_paginator(self, _name):+ return self++ def paginate(self, *, Bucket, Prefix):+ yield {"Contents": [{"Key": key} for key in sorted(self.keys) if key.startswith(Prefix)]}++ def delete_objects(self, *, Bucket, Delete):+ self.deleted = [obj["Key"] for obj in Delete["Objects"]]+ self.keys -= set(self.deleted)+++def test_rerun_removes_stale_head_files_but_keeps_what_it_just_wrote():+ folder = model_object_key("inbox_ranking", "2026-08-19", "")+ written = {folder + "open.ubj", folder + "open.holdout.ubj", folder + "metadata.json"}+ client = _FakeS3([*written, folder + "action.ubj", "inbox_ranking/inbox_ranking_models/v1/champion.json"])+ assert _delete_other_objects(client, "bucket", folder, written) == [folder + "action.ubj"]+ assert client.keys == written | {"inbox_ranking/inbox_ranking_models/v1/champion.json"}+++class _EmptyS3:+ def get_object(self, *, Bucket, Key):+ raise ClientError({"Error": {"Code": "NoSuchKey"}}, "GetObject")+++def test_load_snapshots_fails_without_the_requested_partition():+ dates = snapshot_dates("2026-08-19", 2)+ assert load_snapshots(_EmptyS3(), "bucket", "inbox_ranking", dates) == {}+ with pytest.raises(dagster.Failure, match="2026-08-19"):+ load_snapshots(_EmptyS3(), "bucket", "inbox_ranking", dates, required=dates[-1])+++def test_examples_depend_on_the_whole_lookback_window():+ # An asset backfill must not run examples(D) before the older state and labels days exist.+ for upstream in (STATE_TABLE, LABELS_TABLE):+ mapping = inbox_ranking_training_examples.get_partition_mapping(dagster.AssetKey(upstream))+ assert isinstance(mapping, dagster.TimeWindowPartitionMapping)+ assert mapping.start_offset == -settings.INBOX_RANKING_TRAINING_LOOKBACK_DAYS+ assert mapping.end_offset == 0+++def test_model_key_layout_is_stable():+ # The scoring sweep resolves the champion pointer and booster files by these keys.+ assert (+ model_object_key("inbox_ranking", "2026-08-19", "open.ubj")+ == "inbox_ranking/inbox_ranking_models/v1/dt=2026-08-19/open.ubj"+ )+ assert champion_object_key("inbox_ranking") == "inbox_ranking/inbox_ranking_models/v1/champion.json"+ assert snapshot_dates("2026-08-19", 2) == [+ datetime.date(2026, 8, 17),+ datetime.date(2026, 8, 18),+ datetime.date(2026, 8, 19),+ ]diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pynew file mode 100644index 000000000000..022b8e2eed66--- /dev/null+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -0,0 +1,398 @@+"""Daily training for the Self-driving Inbox report-ranking model (v0: per-head XGBoost).++Three assets on the same daily partition as the dataset dag, each writing under the dataset prefix:++ inbox_ranking_training_examples/v1/dt=D/ scoring-moment examples over the trailing snapshots+ inbox_ranking_models/v1/dt=D/<head>.ubj one booster per head + metadata.json (the candidate)+ inbox_ranking_models/v1/champion.json pointer to the model version the scoring sweep loads++Partition dt=D trains on the report-state/labels snapshots dt=D-lookback..D (issue 13's+scoring-moment join, `training/examples.py`), grades each head on the last `holdout_days` of+reports, and refits on everything. The champion asset applies `promotion.decide_promotion`; it+rewrites the pointer only when `INBOX_RANKING_AUTO_PROMOTE` is on, otherwise it logs the decision+so the daily candidate series doubles as monitoring while the first shadow read runs against a+frozen champion. Every candidate is kept under `models/v1/dt=D/`; a re-run of a partition replaces+that prefix in full (stale head files are removed), and `champion.json` carries the `run_id` it+was promoted from so a loader can tell a re-run apart from the version it pinned. The champion is+graded on the candidate's holdout through its `<head>.holdout.ubj` (the train-only fit), so the+promotion rule compares both models on one set of reports.+"""++import json+import datetime+from typing import Any++import pandas as pd+import dagster+import pyarrow as pa+from botocore.exceptions import ClientError++from posthog import settings++from products.signals.backend.ranking.features import FEATURE_NAMES, FEATURE_SCHEMA_VERSION+from products.signals.dags.inbox_ranking.common import (+ DATASET_VERSION,+ S3_BUCKET_ENV,+ dataset_bucket,+ dataset_unconfigured,+ owner_tags,+ partition_def,+ partition_object_key,+ read_parquet,+ read_parquet_if_exists,+ s3_client,+ skip_unconfigured,+ write_parquet,+)+from products.signals.dags.inbox_ranking.dataset.dag import LABELS_TABLE, STATE_TABLE+from products.signals.dags.inbox_ranking.training.examples import (+ EXAMPLE_COLUMNS,+ PROVENANCE_LABEL_COLUMNS,+ PROVENANCE_STATE_COLUMNS,+ STATE_COLUMNS,+ Snapshot,+ assemble_snapshot,+ build_examples,+ point_in_time_mask,+)+from products.signals.dags.inbox_ranking.training.heads import HEADS, HEADS_BY_NAME+from products.signals.dags.inbox_ranking.training.promotion import decide_promotion+from products.signals.dags.inbox_ranking.training.train import XGB_PARAMS, TrainedHead, booster_holdout_auc, train_head++EXAMPLES_TABLE = "inbox_ranking_training_examples"+MODELS_TABLE = "inbox_ranking_models"+CHAMPION_FILE = "champion.json"+METADATA_FILE = "metadata.json"++# Label columns the heads read (plus the provenance inputs); everything else stays on disk.+_LABEL_COLUMNS = (+ "impression_unit_count",+ "open_count",+ "create_pr_click_count",+ "discuss_count",+ "dismissal_reason",+ "wrong_dismissal_count",+ "pr_created_count",+ *PROVENANCE_LABEL_COLUMNS,+)+_STATE_READ_COLUMNS = (*STATE_COLUMNS, *PROVENANCE_STATE_COLUMNS, "features_observed_at")++COMMON_ASSET_KWARGS: dict[str, Any] = {+ "group_name": "inbox_ranking_training",+ "partitions_def": partition_def,+ "tags": owner_tags,+ "retry_policy": dagster.RetryPolicy(max_retries=1, delay=60),+ "pool": "inbox_ranking_etl",+}+++def model_object_key(prefix: str, partition_key: str, filename: str) -> str:+ return f"{prefix}/{MODELS_TABLE}/{DATASET_VERSION}/dt={partition_key}/{filename}"+++def champion_object_key(prefix: str) -> str:+ return f"{prefix}/{MODELS_TABLE}/{DATASET_VERSION}/{CHAMPION_FILE}"+++def _read_bytes_if_exists(client, bucket: str, key: str) -> bytes | None:+ try:+ return client.get_object(Bucket=bucket, Key=key)["Body"].read()+ except ClientError as error:+ if error.response.get("Error", {}).get("Code") in ("404", "NoSuchKey", "NotFound"):+ return None+ raise+++def _read_json_if_exists(client, bucket: str, key: str) -> dict[str, Any] | None:+ body = _read_bytes_if_exists(client, bucket, key)+ return None if body is None else json.loads(body)+++def _delete_other_objects(client, bucket: str, folder: str, keep: set[str]) -> list[str]:+ """Delete every object under `folder` whose key is not in `keep`; returns the deleted keys."""+ stale = [+ obj["Key"]+ for page in client.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=folder)+ for obj in page.get("Contents", [])+ if obj["Key"] not in keep+ ]+ if stale:+ client.delete_objects(Bucket=bucket, Delete={"Objects": [{"Key": key} for key in stale]})+ return stale+++def _put_json(client, bucket: str, key: str, payload: dict[str, Any]) -> None:+ client.put_object(+ Bucket=bucket, Key=key, Body=json.dumps(payload, indent=2).encode(), ContentType="application/json"+ )+++def snapshot_dates(partition_key: str, lookback_days: int) -> list[datetime.date]:+ end = datetime.date.fromisoformat(partition_key)+ return [end - datetime.timedelta(days=offset) for offset in range(lookback_days, -1, -1)]+++def load_snapshots(+ client, bucket: str, prefix: str, dates: list[datetime.date], *, required: datetime.date | None = None+) -> dict[datetime.date, Snapshot]:+ """The report-state and labels snapshots that exist for `dates`, indexed by report_id. Days+ missing either object are skipped: the example builder treats a gap as unknowable labels.+ `required` is the one day that must be present; the training job is scheduled independently+ of the dataset job, so without it a failed dataset run would yield a candidate named after a+ day it never saw."""+ snapshots: dict[datetime.date, Snapshot] = {}+ for date in dates:+ key = date.isoformat()+ state = read_parquet_if_exists(client, bucket, partition_object_key(prefix, STATE_TABLE, key))+ labels = read_parquet_if_exists(client, bucket, partition_object_key(prefix, LABELS_TABLE, key))+ if state is None or labels is None:+ continue+ state_columns = [column for column in _STATE_READ_COLUMNS if column in state.column_names]+ state_frame = state.select(["report_id", *state_columns]).to_pandas().set_index("report_id")+ label_columns = [column for column in _LABEL_COLUMNS if column in labels.column_names]+ labels_frame = labels.select(["report_id", *label_columns]).to_pandas().set_index("report_id")+ snapshots[date] = assemble_snapshot(date, state_frame, labels_frame)+ if required is not None and required not in snapshots:+ raise dagster.Failure(f"state and labels snapshots for {required.isoformat()} are required but missing")+ return snapshots+++def examples_table(examples: pd.DataFrame) -> pa.Table:+ return pa.Table.from_pandas(examples[list(EXAMPLE_COLUMNS)], preserve_index=False)+++# The examples for dt=D read every snapshot back to D-lookback. The default same-partition mapping+# would let an asset backfill run examples(D) as soon as state(D) and labels(D) exist, while the+# older days it needs are still pending. Partitions before the label epoch have no upstream to map to.+_LOOKBACK_MAPPING = dagster.TimeWindowPartitionMapping(+ start_offset=-settings.INBOX_RANKING_TRAINING_LOOKBACK_DAYS,+ end_offset=0,+ allow_nonexistent_upstream_partitions=True,+)+++ name=EXAMPLES_TABLE,+ deps=[+ dagster.AssetDep(STATE_TABLE, partition_mapping=_LOOKBACK_MAPPING),+ dagster.AssetDep(LABELS_TABLE, partition_mapping=_LOOKBACK_MAPPING),+ ],+ **COMMON_ASSET_KWARGS,+)+def inbox_ranking_training_examples(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()++ dates = snapshot_dates(partition_key, settings.INBOX_RANKING_TRAINING_LOOKBACK_DAYS)+ snapshots = load_snapshots(client, bucket, prefix, dates, required=dates[-1])+ context.log.info(f"{len(snapshots)} of {len(dates)} snapshots present")+ backfilled_rows = sum(int((~point_in_time_mask(snap.state, snap.date)).sum()) for snap in snapshots.values())+ if backfilled_rows:+ context.log.warning(f"{backfilled_rows} state rows read after the snapshot window are excluded (backfill)")++ per_head = {head.name: build_examples(snapshots, head) for head in HEADS}+ examples = (+ pd.concat(per_head.values(), ignore_index=True) if per_head else pd.DataFrame(columns=list(EXAMPLE_COLUMNS))+ )++ key = partition_object_key(prefix, EXAMPLES_TABLE, partition_key)+ write_parquet(client, bucket, key, examples_table(examples), snapshot_date=partition_key)+ context.add_output_metadata(+ {+ "rows": dagster.MetadataValue.int(len(examples)),+ "snapshots": dagster.MetadataValue.int(len(snapshots)),+ "backfilled_state_rows_excluded": dagster.MetadataValue.int(backfilled_rows),+ **{f"{name}_rows": dagster.MetadataValue.int(len(frame)) for name, frame in per_head.items()},+ **{+ f"{name}_positives": dagster.MetadataValue.int(int(frame["label"].sum()))+ for name, frame in per_head.items()+ },+ "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),+ }+ )+++def candidate_metadata(+ partition_key: str, trained: list[TrainedHead], *, trained_at: datetime.datetime, run_id: str+) -> dict[str, Any]:+ return {+ "model_version": partition_key,+ "dataset_version": DATASET_VERSION,+ "feature_schema_version": FEATURE_SCHEMA_VERSION,+ "feature_names": list(FEATURE_NAMES),+ "trained_at": trained_at.isoformat(),+ "run_id": run_id,+ "lookback_days": settings.INBOX_RANKING_TRAINING_LOOKBACK_DAYS,+ "holdout_days": settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS,+ "xgb_params": XGB_PARAMS,+ "heads": [+ head.metrics.as_dict()+ | {+ "file": f"{head.head}.ubj",+ "holdout_file": f"{head.head}.holdout.ubj" if head.holdout_booster_ubj is not None else None,+ }+ for head in trained+ ],+ }+++def paired_champion_aucs(+ client, bucket: str, prefix: str, champion: dict[str, Any], examples: pd.DataFrame, *, holdout_days: int+) -> dict[str, float]:+ """The champion's readable heads graded on the candidate's holdout, through the champion's saved+ holdout boosters. Heads without a saved holdout booster are left out and fall back to the+ champion's stored AUC in `decide_promotion`."""+ aucs: dict[str, float] = {}+ for entry in champion.get("heads", []):+ head = HEADS_BY_NAME.get(entry.get("head"))+ if head is None or not entry.get("readable") or not entry.get("holdout_file"):+ continue+ body = _read_bytes_if_exists(+ client, bucket, model_object_key(prefix, champion["model_version"], entry["holdout_file"])+ )+ if body is None:+ continue+ auc = booster_holdout_auc(body, examples, head, holdout_days=holdout_days)+ if auc is not None:+ aucs[head.name] = auc+ return aucs++[email protected](name="inbox_ranking_model_candidate", deps=[EXAMPLES_TABLE], **COMMON_ASSET_KWARGS)+def inbox_ranking_model_candidate(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()++ examples = read_parquet(client, bucket, partition_object_key(prefix, EXAMPLES_TABLE, partition_key)).to_pandas()+ trained: list[TrainedHead] = []+ for head in HEADS:+ result = train_head(examples, head, holdout_days=settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS)+ if result is None:+ context.log.warning(f"{head.name}: nothing to fit, skipped")+ continue+ context.log.info(f"{head.name}: {result.metrics.as_dict()}")+ trained.append(result)++ written: set[str] = set()+ for model in trained:+ files = {f"{model.head}.ubj": model.booster_ubj}+ if model.holdout_booster_ubj is not None:+ files[f"{model.head}.holdout.ubj"] = model.holdout_booster_ubj+ for filename, body in files.items():+ key = model_object_key(prefix, partition_key, filename)+ client.put_object(Bucket=bucket, Key=key, Body=body, ContentType="application/octet-stream")+ written.add(key)+ metadata = candidate_metadata(+ partition_key, trained, trained_at=datetime.datetime.now(datetime.UTC), run_id=context.run.run_id+ )+ metadata_key = model_object_key(prefix, partition_key, METADATA_FILE)+ _put_json(client, bucket, metadata_key, metadata)+ written.add(metadata_key)+ # A re-run that trains fewer heads must not leave the previous run's files behind.+ stale = _delete_other_objects(client, bucket, model_object_key(prefix, partition_key, ""), written)+ if stale:+ context.log.warning(f"removed {len(stale)} stale objects from a previous run of dt={partition_key}")+ context.add_output_metadata(+ {+ "stale_objects_removed": dagster.MetadataValue.int(len(stale)),+ "heads_trained": dagster.MetadataValue.int(len(trained)),+ "heads_readable": dagster.MetadataValue.int(sum(1 for head in trained if head.metrics.readable)),+ **{+ f"{head.head}_holdout_auc": dagster.MetadataValue.float(head.metrics.holdout_auc)+ for head in trained+ if head.metrics.holdout_auc is not None+ },+ "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{metadata_key}"),+ }+ )++[email protected](name="inbox_ranking_model_champion", deps=["inbox_ranking_model_candidate"], **COMMON_ASSET_KWARGS)+def inbox_ranking_model_champion(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()++ candidate = _read_json_if_exists(client, bucket, model_object_key(prefix, partition_key, METADATA_FILE))+ if candidate is None:+ raise dagster.Failure(f"candidate metadata for dt={partition_key} is missing")+ champion_key = champion_object_key(prefix)+ champion = _read_json_if_exists(client, bucket, champion_key)+ champion_aucs: dict[str, float] = {}+ if champion is not None:+ examples = read_parquet(client, bucket, partition_object_key(prefix, EXAMPLES_TABLE, partition_key)).to_pandas()+ champion_aucs = paired_champion_aucs(+ client, bucket, prefix, champion, examples, holdout_days=settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS+ )+ context.log.info(f"champion {champion['model_version']} on this holdout: {champion_aucs}")+ decision = decide_promotion(+ candidate,+ champion,+ now=datetime.datetime.now(datetime.UTC),+ min_days_between=settings.INBOX_RANKING_PROMOTION_MIN_DAYS,+ champion_aucs=champion_aucs,+ )+ context.log.info(f"promotion decision for dt={partition_key}: promote={decision.promote} ({decision.reason})")++ promoted = False+ if decision.promote and settings.INBOX_RANKING_AUTO_PROMOTE:+ _put_json(+ client,+ bucket,+ champion_key,+ {+ **candidate,+ "promoted_at": datetime.datetime.now(datetime.UTC).isoformat(),+ "metadata_key": model_object_key(prefix, partition_key, METADATA_FILE),+ },+ )+ promoted = True+ elif decision.promote:+ context.log.info("INBOX_RANKING_AUTO_PROMOTE is off; candidate would have been promoted")++ context.add_output_metadata(+ {+ "would_promote": dagster.MetadataValue.bool(decision.promote),+ "promoted": dagster.MetadataValue.bool(promoted),+ "reason": dagster.MetadataValue.text(decision.reason),+ **{+ f"champion_{head}_auc_on_this_holdout": dagster.MetadataValue.float(auc)+ for head, auc in champion_aucs.items()+ },+ "champion_version": dagster.MetadataValue.text(+ partition_key if promoted else (champion or {}).get("model_version", "none")+ ),+ }+ )+++inbox_ranking_training_job = dagster.define_asset_job(+ name="inbox_ranking_training_job",+ selection=[EXAMPLES_TABLE, "inbox_ranking_model_candidate", "inbox_ranking_model_champion"],+ partitions_def=partition_def,+ tags={**owner_tags, "dagster/max_runtime": str(2 * 60 * 60)},+)+++# Runs after the dataset job's 3h budget (02:30 UTC start) so dt=D-1's snapshots exist.+ cron_schedule="0 6 * * *",+ job=inbox_ranking_training_job,+ execution_timezone="UTC",+ default_status=dagster.DefaultScheduleStatus.RUNNING+ if settings.CLOUD_DEPLOYMENT == "US"+ else dagster.DefaultScheduleStatus.STOPPED,+ tags=owner_tags,+)+def inbox_ranking_training_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"training-{previous_day.isoformat()}")diff --git a/products/signals/dags/inbox_ranking/training/examples.py b/products/signals/dags/inbox_ranking/training/examples.pynew file mode 100644index 000000000000..3384938a037e--- /dev/null+++ b/products/signals/dags/inbox_ranking/training/examples.py@@ -0,0 +1,169 @@+"""Training examples at the scoring-moment grain.++One example = one report as one daily snapshot saw it. Its features are that snapshot's+report-state columns (plus `age_hours`, the report's age at the snapshot), and its label is+whether the head's outcome happened within the head's horizon: the label is 0 on the snapshot row+and read from the snapshot `horizon_days` later. That is the serving situation — a report gets+scored, then users see it — replayed over the daily snapshots, and it measured better than one+row per report on the engagement heads (skill issue 13). Once the scoring sweep's append-only+score log has accrued it becomes this table's source; the snapshots are the bootstrap.++Rows of one report are near-duplicates, so the holdout is cut BY REPORT (report_created_at),+never by row. Label-only rows (EU reports, hard-deleted rows) carry no state and are skipped.+A snapshot is assembled over the state spine (`assemble_snapshot`): a report with no label event+gets LABEL_DEFAULTS, so never-engaged reports are negatives rather than absent.+"""++import datetime+from collections.abc import Mapping++import pandas as pd++from posthog.dataclasses import frozen++from products.signals.backend.ranking.features import FEATURE_NAMES, feature_frame+from products.signals.dags.inbox_ranking.common import snapshot_bounds+from products.signals.dags.inbox_ranking.dataset.dag import label_provenance_ok+from products.signals.dags.inbox_ranking.dataset.queries import LABEL_DEFAULTS+from products.signals.dags.inbox_ranking.training.heads import Head++# Report-state columns an example carries, besides the features. `report_age_hours` is the+# snapshot's own clock and becomes the `age_hours` feature.+STATE_COLUMNS = (+ "report_created_at",+ "report_age_hours",+ "signal_count",+ "total_weight",+ "run_count",+ "title_chars",+ "summary_chars",+ "priority",+ "actionability",+)+# Inputs of the label provenance cross-check, read next to the features and labels.+PROVENANCE_STATE_COLUMNS = ("report_team_id", "status", "pg_updated_at")+PROVENANCE_LABEL_COLUMNS = ("latest_status_event", "status_event_team_id")+EXAMPLE_COLUMNS = ("head", "report_id", "snapshot_date", "report_created_at", *FEATURE_NAMES, "label")++# A forward run stamps features_observed_at a few hours after the snapshot end. Anything read later+# than this is a backfill that carries current Postgres state, not the state as of the snapshot.+STATE_LAG_LIMIT = datetime.timedelta(days=2)+++@frozen+class Snapshot:+ """One day's report-state and labels, both indexed by report_id."""++ date: datetime.date+ state: pd.DataFrame+ labels: pd.DataFrame+++def _none_if_missing(value: object) -> object:+ return None if value is None or value is pd.NaT or (isinstance(value, float) and pd.isna(value)) else value+++def assemble_snapshot(date: datetime.date, state: pd.DataFrame, labels: pd.DataFrame) -> Snapshot:+ """Align `labels` to the state spine: every state report gets a label row (LABEL_DEFAULTS for+ reports that had no event) and a `label_provenance_ok` column from the dataset dag's+ cross-check when the provenance inputs are present. Label-only rows stay: a report deleted+ before a later snapshot keeps its horizon label there, while `build_examples` skips them as+ scoring moments because they carry no state."""+ aligned = labels.reindex(state.index.union(labels.index))+ state = state.reindex(aligned.index)+ for column, default in LABEL_DEFAULTS.items():+ if column in aligned and default is not None:+ aligned[column] = aligned[column].fillna(default)+ has_inputs = all(column in state for column in PROVENANCE_STATE_COLUMNS) and all(+ column in aligned for column in PROVENANCE_LABEL_COLUMNS+ )+ if has_inputs:+ _, snapshot_end = snapshot_bounds(date.isoformat())+ aligned["label_provenance_ok"] = [+ label_provenance_ok(+ _none_if_missing(status), # type: ignore[arg-type]+ _none_if_missing(updated_at), # type: ignore[arg-type]+ _none_if_missing(latest_event), # type: ignore[arg-type]+ report_team_id=_none_if_missing(team_id), # type: ignore[arg-type]+ status_event_team_id=_none_if_missing(event_team_id), # type: ignore[arg-type]+ snapshot_end=snapshot_end,+ )+ for status, updated_at, latest_event, team_id, event_team_id in zip(+ state["status"],+ state["pg_updated_at"],+ aligned["latest_status_event"],+ state["report_team_id"],+ aligned["status_event_team_id"],+ strict=True,+ )+ ]+ return Snapshot(date=date, state=state, labels=aligned)+++def point_in_time_mask(state: pd.DataFrame, date: datetime.date) -> pd.Series:+ """True for rows whose Postgres state was read close enough to the snapshot day to stand for+ the state as of that day. Rows without the stamp are kept."""+ if "features_observed_at" not in state:+ return pd.Series(True, index=state.index)+ _, snapshot_end = snapshot_bounds(date.isoformat())+ observed = pd.to_datetime(state["features_observed_at"], utc=True)+ return observed.isna() | (observed <= snapshot_end + STATE_LAG_LIMIT)+++def _flag_or_true(labels: pd.DataFrame, column: str) -> pd.Series:+ return labels[column].fillna(False).astype(bool) if column in labels else pd.Series(True, index=labels.index)+++def build_examples(snapshots: Mapping[datetime.date, Snapshot], head: Head) -> pd.DataFrame:+ """Every (report, snapshot) scoring moment for `head` whose label can be read, as one frame+ with EXAMPLE_COLUMNS. Snapshots whose `horizon_days`-later snapshot is missing contribute no+ examples (the label is unknowable), so a gap in the partitions simply thins the data."""+ frames: list[pd.DataFrame] = []+ for date in sorted(snapshots):+ later = snapshots.get(date + datetime.timedelta(days=head.horizon_days))+ if later is None:+ continue+ now = snapshots[date]+ ids = now.state.index.intersection(now.labels.index).intersection(later.labels.index)+ if len(ids) == 0:+ continue+ state, labels_now, labels_later = now.state.loc[ids], now.labels.loc[ids], later.labels.loc[ids]+ # The cohort reads the later snapshot on purpose. The sweep scores a report before users see+ # it, so the impression that puts a report in the cohort usually lands after `now`. A cohort+ # read at `now` would drop those pre-impression scoring moments, which are the serving case.+ keep = head.cohort(labels_later) & ~head.label(labels_now) & state["signal_count"].notna()+ keep &= point_in_time_mask(state, date)+ if head.status_labels:+ keep &= _flag_or_true(labels_now, "label_provenance_ok") & _flag_or_true(+ labels_later, "label_provenance_ok"+ )+ if not keep.any():+ continue+ rows = state.loc[keep, list(STATE_COLUMNS)].copy()+ rows["age_hours"] = rows.pop("report_age_hours").astype(float)+ features = feature_frame(rows)+ examples = pd.DataFrame(+ {+ "head": head.name,+ "report_id": rows.index.to_numpy(),+ "snapshot_date": date,+ "report_created_at": pd.to_datetime(rows["report_created_at"], utc=True).to_numpy(),+ }+ )+ for name in FEATURE_NAMES:+ examples[name] = features[name].to_numpy()+ examples["label"] = head.label(labels_later.loc[keep]).astype(int).to_numpy()+ frames.append(examples)+ if not frames:+ return pd.DataFrame(columns=list(EXAMPLE_COLUMNS))+ return pd.concat(frames, ignore_index=True)[list(EXAMPLE_COLUMNS)]+++def holdout_mask(examples: pd.DataFrame, holdout_days: int) -> pd.Series:+ """True for every row of the reports created in the last `holdout_days` of the example set.+ Cut by report so a report's snapshot rows never straddle train and holdout."""+ created = pd.to_datetime(examples["report_created_at"], utc=True)+ if created.empty:+ return pd.Series(False, index=examples.index)+ cutoff = created.max() - pd.Timedelta(days=holdout_days)+ return created >= cutoffdiff --git a/products/signals/dags/inbox_ranking/training/heads.py b/products/signals/dags/inbox_ranking/training/heads.pynew file mode 100644index 000000000000..83124a17eea2--- /dev/null+++ b/products/signals/dags/inbox_ranking/training/heads.py@@ -0,0 +1,88 @@+"""The outcome heads the v0 ranking model predicts.++Each head is a cohort (which reports are scoreable examples), a binary label, and a horizon: the+label is "the outcome happened within `horizon_days` of the scoring moment", evaluated from the+cumulative label columns the dataset dag snapshots. Cohort and label are vectorized over a frame+of `inbox_report_labels` columns, so the same definitions read the snapshot at scoring time (label+must still be 0) and the snapshot `horizon_days` later (the label).++Mirrors the workspace `heads.py` (random-dev-internal, `inbox-ranking/`) for the four heads with+enough positives to ship; the other ten stay workspace-only until they are readable.+"""++from collections.abc import Callable++import pandas as pd++from posthog.dataclasses import frozen++from products.signals.dags.inbox_ranking.common import WRONG_DISMISSAL_REASONS+++def _count(frame: pd.DataFrame, column: str) -> pd.Series:+ return frame[column].fillna(0).astype(int) if column in frame else pd.Series(0, index=frame.index)+++def impressed(frame: pd.DataFrame) -> pd.Series:+ return _count(frame, "impression_unit_count") > 0+++def everyone(frame: pd.DataFrame) -> pd.Series:+ return pd.Series(True, index=frame.index)+++def opened(frame: pd.DataFrame) -> pd.Series:+ return _count(frame, "open_count") > 0+++def acted(frame: pd.DataFrame) -> pd.Series:+ return (_count(frame, "create_pr_click_count") + _count(frame, "discuss_count")) > 0+++def dismissed_as_wrong(frame: pd.DataFrame) -> pd.Series:+ if "wrong_dismissal_count" in frame:+ return _count(frame, "wrong_dismissal_count") > 0+ # Partitions written before the cumulative count existed carry only the latest-wins reason,+ # which a later restore or re-dismissal can overwrite.+ if "dismissal_reason" not in frame:+ return pd.Series(False, index=frame.index)+ return frame["dismissal_reason"].isin(WRONG_DISMISSAL_REASONS)+++def pr_created(frame: pd.DataFrame) -> pd.Series:+ return _count(frame, "pr_created_count") > 0+++@frozen+class Head:+ name: str+ cohort: Callable[[pd.DataFrame], pd.Series]+ label: Callable[[pd.DataFrame], pd.Series]+ horizon_days: int+ # Below this many positives in the holdout the head's AUC is noise; the promotion gate ignores it.+ min_holdout_positives: int+ # The label comes from the status-change stream, whose tenant provenance the dataset dag+ # cross-checks; rows that fail that check are unusable for this head.+ status_labels: bool = False+++HEADS: tuple[Head, ...] = (+ # Of the reports users saw, which got opened by anyone? Opens land within hours of impression.+ Head(name="open", cohort=impressed, label=opened, horizon_days=3, min_holdout_positives=50),+ # Of the reports users saw, which drew a create-PR click or a discuss?+ Head(name="action", cohort=impressed, label=acted, horizon_days=7, min_holdout_positives=30),+ # Of the reports users saw, which were dismissed as wrong / unclear / intentional - the+ # precision-failure negative. already_fixed and wontfix_irrelevant are deliberately not here.+ Head(+ name="dismiss_wrong",+ cohort=impressed,+ label=dismissed_as_wrong,+ horizon_days=7,+ min_holdout_positives=30,+ status_labels=True,+ ),+ # Which reports get a PR at all? Cohort is every report the sweep would score.+ Head(name="pr_created", cohort=everyone, label=pr_created, horizon_days=7, min_holdout_positives=30),+)++HEADS_BY_NAME: dict[str, Head] = {head.name: head for head in HEADS}diff --git a/products/signals/dags/inbox_ranking/training/promotion.py b/products/signals/dags/inbox_ranking/training/promotion.pynew file mode 100644index 000000000000..63be0f07585c--- /dev/null+++ b/products/signals/dags/inbox_ranking/training/promotion.py@@ -0,0 +1,73 @@+"""Champion promotion rule.++A candidate replaces the champion when it is at least as good on every head the champion could+read, has at least one readable head itself, and enough days have passed since the last promotion+(scores are consumed by an online shadow read, and a champion that changes every day muddies it).+Pure function over the two metadata records so the rule is testable without S3. The champion's+AUCs should be `champion_aucs`, its holdout booster graded on the candidate's holdout, so both+models are compared on one set of reports; the stored numbers are the fallback.+"""++import datetime+from collections.abc import Mapping+from typing import Any++from posthog.dataclasses import frozen++# A candidate may be this much worse than the champion on a readable head and still promote: at+# the readability floor the AUC's noise is about this size, so exact dominance would never trigger.+AUC_TOLERANCE = 0.02+++@frozen+class PromotionDecision:+ promote: bool+ reason: str+++def _readable_aucs(metadata: Mapping[str, Any]) -> dict[str, float]:+ return {+ head["head"]: float(head["holdout_auc"])+ for head in metadata.get("heads", [])+ if head.get("readable") and head.get("holdout_auc") is not None+ }+++def decide_promotion(+ candidate: Mapping[str, Any],+ champion: Mapping[str, Any] | None,+ *,+ now: datetime.datetime,+ min_days_between: int,+ champion_aucs: Mapping[str, float] | None = None,+) -> PromotionDecision:+ candidate_aucs = _readable_aucs(candidate)+ if not candidate_aucs:+ return PromotionDecision(promote=False, reason="candidate has no readable head")+ if champion is None:+ return PromotionDecision(promote=True, reason="no champion yet")++ # A backfill replays old partitions, so reject any candidate not newer than the champion to keep+ # the pointer from moving backwards to a stale model. model_version is the partition date, and+ # ISO date strings compare chronologically (same ordering the dataset dag's latest/ stamp relies on).+ if candidate["model_version"] <= champion["model_version"]:+ return PromotionDecision(+ promote=False,+ reason=f"candidate {candidate['model_version']} is not newer than champion {champion['model_version']}",+ )++ promoted_at = datetime.datetime.fromisoformat(champion["promoted_at"])+ if now - promoted_at < datetime.timedelta(days=min_days_between):+ return PromotionDecision(+ promote=False, reason=f"champion {champion['model_version']} promoted less than {min_days_between}d ago"+ )+ for head, stored_auc in _readable_aucs(champion).items():+ champion_auc = champion_aucs.get(head, stored_auc) if champion_aucs else stored_auc+ candidate_auc = candidate_aucs.get(head)+ if candidate_auc is None:+ return PromotionDecision(promote=False, reason=f"{head} readable on champion but not on candidate")+ if candidate_auc < champion_auc - AUC_TOLERANCE:+ return PromotionDecision(+ promote=False, reason=f"{head} regressed: {candidate_auc:.3f} vs champion {champion_auc:.3f}"+ )+ return PromotionDecision(promote=True, reason="candidate at or above champion on every readable head")diff --git a/products/signals/dags/inbox_ranking/training/train.py b/products/signals/dags/inbox_ranking/training/train.pynew file mode 100644index 000000000000..e04500ee1fc4--- /dev/null+++ b/products/signals/dags/inbox_ranking/training/train.py@@ -0,0 +1,157 @@+"""Per-head XGBoost training over the scoring-moment examples.++Deliberately plain: fixed hyperparameters, a time-based holdout by report, AUC plus a+label-permutation null per head. The booster is saved as UBJSON bytes with its feature names, so+the serving side can assert `booster.feature_names == FEATURE_NAMES` at load.+"""++import numpy as np+import pandas as pd+import xgboost as xgb+from sklearn.metrics import roc_auc_score++from posthog.dataclasses import frozen++from products.signals.backend.ranking.features import FEATURE_NAMES+from products.signals.dags.inbox_ranking.training.examples import holdout_mask+from products.signals.dags.inbox_ranking.training.heads import Head++XGB_PARAMS: dict[str, object] = {+ "n_estimators": 200,+ "max_depth": 4,+ "learning_rate": 0.05,+ "subsample": 0.8,+ "colsample_bytree": 0.8,+ "min_child_weight": 5,+ "eval_metric": "auc",+ "n_jobs": 2,+}+# A readable head must also clear its own permutation null by this much; below it the AUC is+# within the noise of this many positives.+NULL_MARGIN = 0.05+++@frozen+class HeadMetrics:+ head: str+ train_rows: int+ train_positives: int+ holdout_rows: int+ holdout_positives: int+ holdout_auc: float | None+ null_auc: float | None+ readable: bool++ def as_dict(self) -> dict[str, object]:+ return {+ "head": self.head,+ "train_rows": self.train_rows,+ "train_positives": self.train_positives,+ "holdout_rows": self.holdout_rows,+ "holdout_positives": self.holdout_positives,+ "holdout_auc": self.holdout_auc,+ "null_auc": self.null_auc,+ "readable": self.readable,+ }+++@frozen+class TrainedHead:+ head: str+ booster_ubj: bytes+ # The train-only fit that produced the holdout metrics, kept so a later candidate can grade this+ # model on its own holdout; None when there were no holdout rows.+ holdout_booster_ubj: bytes | None+ metrics: HeadMetrics+++def _ubj(model: xgb.XGBClassifier) -> bytes:+ return bytes(model.get_booster().save_raw("ubj"))+++def _fit(x: pd.DataFrame, y: np.ndarray, seed: int) -> xgb.XGBClassifier:+ model = xgb.XGBClassifier(**XGB_PARAMS, random_state=seed)+ model.fit(x, y, verbose=False)+ return model+++def _auc(y: np.ndarray, scores: np.ndarray) -> float | None:+ if y.sum() == 0 or y.sum() == len(y):+ return None+ return float(roc_auc_score(y, scores))+++def _head_readable(+ holdout_auc: float | None, null_auc: float | None, holdout_positives: int, *, min_positives: int+) -> bool:+ """Readable = enough holdout positives, an above-chance holdout AUC, and clearing the head's own+ permutation null by NULL_MARGIN. The absolute 0.5 floor is load-bearing on top of the null+ margin because the null is a single noisy draw: an inversely predictive head (AUC below chance)+ can still beat one low null draw by the margin, and must not be graded readable."""+ if holdout_auc is None or null_auc is None:+ return False+ return holdout_positives >= min_positives and holdout_auc > 0.5 and holdout_auc - null_auc >= NULL_MARGIN+++def train_head(examples: pd.DataFrame, head: Head, *, holdout_days: int, seed: int = 0) -> TrainedHead | None:+ """Fit one head; None when there is nothing to fit (no positive or no negative in train)."""+ rows = examples[examples["head"] == head.name]+ if rows.empty:+ return None+ test = holdout_mask(rows, holdout_days).to_numpy()+ x = rows[list(FEATURE_NAMES)].astype(float)+ y = rows["label"].to_numpy(dtype=int)+ x_train, y_train, x_test, y_test = x[~test], y[~test], x[test], y[test]+ if len(y_train) == 0 or y_train.sum() == 0 or y_train.sum() == len(y_train):+ return None++ model = _fit(x_train, y_train, seed)+ holdout_auc = _auc(y_test, model.predict_proba(x_test)[:, 1]) if len(y_test) else None++ null_auc: float | None = None+ if holdout_auc is not None:+ rng = np.random.default_rng(seed)+ null_model = _fit(x_train, rng.permutation(y_train), seed)+ null_auc = _auc(y_test, null_model.predict_proba(x_test)[:, 1])++ readable = _head_readable(holdout_auc, null_auc, int(y_test.sum()), min_positives=head.min_holdout_positives)+ metrics = HeadMetrics(+ head=head.name,+ train_rows=int(len(y_train)),+ train_positives=int(y_train.sum()),+ holdout_rows=int(len(y_test)),+ holdout_positives=int(y_test.sum()),+ holdout_auc=holdout_auc,+ null_auc=null_auc,+ readable=readable,+ )+ # Refit on everything before shipping: the holdout only exists to grade the recipe.+ final = _fit(x, y, seed)+ return TrainedHead(+ head=head.name,+ booster_ubj=_ubj(final),+ holdout_booster_ubj=_ubj(model) if len(y_test) else None,+ metrics=metrics,+ )+++def booster_holdout_auc(booster_ubj: bytes, examples: pd.DataFrame, head: Head, *, holdout_days: int) -> float | None:+ """AUC of a saved booster on `head`'s holdout rows of `examples`: the same rows `train_head`+ grades a candidate on, so a champion and a candidate can be compared on one set."""+ rows = examples[examples["head"] == head.name]+ if rows.empty:+ return None+ test = holdout_mask(rows, holdout_days).to_numpy()+ if not test.any():+ return None+ booster = xgb.Booster()+ booster.load_model(bytearray(booster_ubj))+ # The booster's own names, not the current contract: a champion trained before an additive+ # schema bump is still scorable on its subset. A name the examples lack means the schemas are+ # incompatible, and the caller falls back to the stored AUC.+ names = list(booster.feature_names or FEATURE_NAMES)+ if any(name not in rows for name in names):+ return None+ x = rows.loc[test, names].astype(float)+ y = rows.loc[test, "label"].to_numpy(dtype=int)+ return _auc(y, booster.predict(xgb.DMatrix(x, feature_names=names)))