: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): promote inbox ranking models by hand through one served pointer (#118966)
posthog[bot]f7222f31bbab
diff --git a/docs/internal/inbox-ranking-training.md b/docs/internal/inbox-ranking-training.mdindex cbcef09d6a9f..90f972023026 100644--- a/docs/internal/inbox-ranking-training.md+++ b/docs/internal/inbox-ranking-training.md@@ -59,14 +59,19 @@ Each head in `metadata.json` records `example_window_start`, the earliest report## Promotion-A candidate replaces its family's champion only when, on every head the champion could read:+Promotion is manual.+A person runs `inbox_ranking_promote_job` with a `model_key` and a `reason`, and the job writes `inbox_ranking_models/v1/served.json` and publishes the serving manifest.+Training never moves that pointer.-- its holdout AUC is at most `AUC_TOLERANCE` below the champion's, and-- its holdout calibration error (ECE) is at most `ECE_TOLERANCE` above the champion's.+Each run still grades every candidate against the served model of its own `model_name`.+The decision says the candidate would promote only when, on every head the served model could read:-Both champion numbers come from the champion's `<head>.holdout.ubj` scored on the candidate's holdout.-A head without a paired champion ECE skips the calibration check.-`inbox_ranking_promotion_decided` carries the paired values as `champion_<head>_auc_on_this_holdout` and `champion_<head>_ece_on_this_holdout`.+- its holdout AUC is at most `AUC_TOLERANCE` below the served model's, and+- its holdout calibration error (ECE) is at most `ECE_TOLERANCE` above the served model's.++Both incumbent numbers come from the served model's `<head>.holdout.ubj` scored on the candidate's holdout.+A head without a paired incumbent ECE skips the calibration check.+`inbox_ranking_promotion_decided` carries the decision as `would_promote` and `gates_passed`, with `promoted` always false, and the paired values as `champion_<head>_auc_on_this_holdout` and `champion_<head>_ece_on_this_holdout`.## Baked and unbaked unseen metrics@@ -194,7 +199,7 @@ A missing object is a skip in the asset metadata, not a failure.Caveats:-- The daily promotion can change the served model part of the way through D, so one day's cohort can split across two versions, and one report can hold a row for each. Grades stay per `(model_name, model_version, model_role)`. Never pool them across versions.+- A manual promotion can change the served model part of the way through D, so one day's cohort can split across two versions, and one report can hold a row for each. Grades stay per `(model_name, model_version, model_role)`. Never pool them across versions.- The sweep scores a candidate only after a manifest names it, so a candidate's online cohort starts the day after it was trained. `pool_coverage_by_model` shows how much of the pool each key covered.- A report first scored after D ends, for example when its vector arrived late, is not in D's rows. `served_pool_coverage` shows this for the served model. A later score never fills it in.- The sweep scores with the vector current at scoring time, so two keys that scored one report at different times did not always read the same vector.diff --git a/posthog/dags/locations/signals.py b/posthog/dags/locations/signals.pyindex 74a1f2804390..26a106e47fc1 100644--- a/posthog/dags/locations/signals.py+++ b/posthog/dags/locations/signals.py@@ -4,6 +4,7 @@ from products.signals.dags.inbox_ranking.common import is_inbox_ranking_registerfrom products.signals.dags.inbox_ranking.dataset import dag as inbox_ranking_datasetfrom products.signals.dags.inbox_ranking.training import (dag as inbox_ranking_training,+ promote as inbox_ranking_promote,served as inbox_ranking_served,)@@ -34,6 +35,7 @@ if is_inbox_ranking_registered():inbox_ranking_dataset.inbox_ranking_dataset_job,inbox_ranking_dataset.inbox_ranking_labels_refresh_job,inbox_ranking_training.inbox_ranking_training_job,+ inbox_ranking_promote.inbox_ranking_promote_job,],schedules=[inbox_ranking_dataset.inbox_ranking_dataset_schedule,diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.pyindex 336dfa8fbbd6..a6df872cb704 100644--- a/posthog/settings/object_storage.py+++ b/posthog/settings/object_storage.py@@ -1,7 +1,7 @@import osfrom typing import Optional-from posthog.settings.base_variables import CLOUD_DEPLOYMENT, DEBUG, TEST+from posthog.settings.base_variables import DEBUG, TESTfrom posthog.settings.utils import get_from_envfrom posthog.utils import str_to_bool@@ -103,22 +103,13 @@ AI_BLOB_S3_PREFIX = os.getenv("AI_BLOB_S3_PREFIX", "aio/")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 by default; the-# candidate is still trained and graded daily.+# examples reach, and how many trailing days of reports grade a candidate. Promotion is manual: a+# person runs `inbox_ranking_promote_job`, which writes the served pointer.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", 0, type_cast=int)# Labels refresh sensor (products/signals/dags/inbox_ranking/dataset): how many stale labels# partitions one hourly tick rewrites after a FEATURE_SCHEMA_VERSION bump, newest first.INBOX_RANKING_LABELS_REFRESH_MAX_RUNS = get_from_env("INBOX_RANKING_LABELS_REFRESH_MAX_RUNS", 6, type_cast=int)-# The family whose champion the serving manifest serves. The scoring sweep reads the manifest-# from the deployment's own object store, so this is the only place the served family is chosen.-# Only US Cloud trains `nn`: local dev and tests have no nn champion, and EU does not train.-INBOX_RANKING_SERVED_FAMILY = os.getenv(- "INBOX_RANKING_SERVED_FAMILY", "nn" if (CLOUD_DEPLOYMENT or "").upper() == "US" else "report_embeddings"-)# A second deployment's object store that receives a copy of every serving publish, so a region# that does not train still serves the trained models. Reached via ambient AWS config. Unset means# no mirror.diff --git a/products/signals/backend/ranking/overrides.py b/products/signals/backend/ranking/overrides.pyindex cce5ba1b040a..e5a1ad492af4 100644--- a/products/signals/backend/ranking/overrides.py+++ b/products/signals/backend/ranking/overrides.py@@ -1,8 +1,9 @@-"""Temporary owner overrides of ranking serving and promotion, read from one feature flag payload.+"""Temporary owner overrides of ranking serving, read from one feature flag payload.An owner sets the `inbox-ranking-overrides` payload only to intervene, and every payload expires on-its own. The scoring sweep reads `served`, and the training dag reads `pin` and `promotion`. Both-parse the payload here, so the two cannot disagree about what a payload means.+its own. The scoring sweep reads `served`, and the training dag reads `pin`. Both parse the payload+here, so the two cannot disagree about what a payload means. Promotion is not an override: the+`inbox_ranking_promote_job` writes the served pointer.The parser is fail-safe. An absent, expired or invalid payload, or a failed flag lookup, gives`NO_OVERRIDES`, and the sweep and the dag then run as they do with no flag. An invalid payload is@@ -13,8 +14,7 @@ import reimport jsonimport datetimefrom collections.abc import Mapping-from dataclasses import field-from typing import Any, Literal+from typing import Anyimport pydanticimport structlog@@ -28,39 +28,28 @@ RANKING_OVERRIDES_FLAG = "inbox-ranking-overrides"# The flag is evaluated once per pass or run for this id, so an override applies to every report.RANKING_OVERRIDES_DISTINCT_ID = "internal_inbox_ranking_overrides"-# A forgotten override must not change serving or promotion for longer than this.+# A forgotten override must not change serving for longer than this.MAX_OVERRIDE_LIFETIME = datetime.timedelta(days=14)-PromotionGate = Literal["min_days", "ece", "min_holdout_positives"]-# A model key is also a path segment in the dataset bucket, so the format is strict.-_MODEL_KEY_PATTERN = re.compile(r"^[a-z0-9_]+@\d{4}-\d{2}-\d{2}$")+MODEL_KEY_PATTERN = re.compile(r"^[a-z0-9_]+@\d{4}-\d{2}-\d{2}$")class InvalidOverrides(ValueError):pass-class _PromotionPayload(pydantic.BaseModel):- model_config = pydantic.ConfigDict(extra="forbid")-- freeze: list[str] = []- force: list[str] = []- skip_gates: dict[str, list[PromotionGate]] = {}--class _OverridesPayload(pydantic.BaseModel):model_config = pydantic.ConfigDict(extra="forbid")expires_at: pydantic.AwareDatetimeserved: str | None = Nonepin: list[str] = []- promotion: _PromotionPayload = _PromotionPayload()@pydantic.field_validator("served")@classmethoddef served_is_a_model_key(cls, v: str | None) -> str | None:- if v is not None and not _MODEL_KEY_PATTERN.match(v):+ if v is not None and not MODEL_KEY_PATTERN.match(v):raise ValueError(f"{v!r} is not a `<model_name>@<YYYY-MM-DD>` model key")return v@@ -68,34 +57,17 @@ class _OverridesPayload(pydantic.BaseModel):@classmethoddef pins_are_model_keys(cls, v: list[str]) -> list[str]:for key in v:- if not _MODEL_KEY_PATTERN.match(key):+ if not MODEL_KEY_PATTERN.match(key):raise ValueError(f"{key!r} is not a `<model_name>@<YYYY-MM-DD>` model key")return v-@frozen-class PromotionOverride:- """One family's promotion override. `freeze` wins, so a frozen family has no force and no waived gate."""-- freeze: bool = False- force: bool = False- skip_gates: frozenset[str] = frozenset()--@frozenclass RankingOverrides:# None only on `NO_OVERRIDES`.expires_at: datetime.datetime | None = Noneserved: str | None = Nonepin: tuple[str, ...] = ()- freeze: frozenset[str] = frozenset()- force: frozenset[str] = frozenset()- skip_gates: Mapping[str, frozenset[str]] = field(default_factory=dict)-- def promotion_for(self, family: str) -> PromotionOverride:- if family in self.freeze:- return PromotionOverride(freeze=True)- return PromotionOverride(force=family in self.force, skip_gates=self.skip_gates.get(family, frozenset()))NO_OVERRIDES = RankingOverrides()@@ -112,9 +84,6 @@ def _validated(payload: Mapping[str, Any], now: datetime.datetime) -> RankingOveexpires_at=parsed.expires_at,served=parsed.served,pin=tuple(dict.fromkeys(parsed.pin)),- freeze=frozenset(parsed.promotion.freeze),- force=frozenset(parsed.promotion.force),- skip_gates={family: frozenset(gates) for family, gates in parsed.promotion.skip_gates.items()},)diff --git a/products/signals/backend/test/test_ranking_sweep.py b/products/signals/backend/test/test_ranking_sweep.pyindex d9dd322214e7..25edf3601436 100644--- a/products/signals/backend/test/test_ranking_sweep.py+++ b/products/signals/backend/test/test_ranking_sweep.py@@ -418,8 +418,12 @@ class TestParseOverrides(SimpleTestCase):"inbox_ranking_override_invalid",),(- "unknown_gate",- {"expires_at": EXPIRES, "promotion": {"skip_gates": {"report_embeddings": ["auc"]}}},+ "retired_promotion_block",+ {+ "expires_at": EXPIRES,+ "served": "report_embeddings@2026-10-03",+ "promotion": {"force": ["report_embeddings"]},+ },NO_OVERRIDES,"inbox_ranking_override_invalid",),@@ -441,19 +445,11 @@ class TestParseOverrides(SimpleTestCase):"expires_at": EXPIRES,"served": "report_embeddings@2026-10-03","pin": ["report_embeddings@2026-09-26"],- "promotion": {- "freeze": ["tabular_xgb"],- "force": ["report_embeddings"],- "skip_gates": {"report_embeddings": ["min_days", "ece"]},- },},RankingOverrides(expires_at=datetime.datetime(2026, 10, 11, tzinfo=datetime.UTC),served="report_embeddings@2026-10-03",pin=("report_embeddings@2026-09-26",),- freeze=frozenset({"tabular_xgb"}),- force=frozenset({"report_embeddings"}),- skip_gates={"report_embeddings": frozenset({"min_days", "ece"})},),None,),@@ -463,18 +459,3 @@ class TestParseOverrides(SimpleTestCase):with patch("products.signals.backend.ranking.overrides.logger") as logger:assert parse_overrides(payload, now=NOW) == expectedassert [call.args[0] for call in logger.warning.call_args_list] == ([warning] if warning else [])-- def test_freeze_wins_over_force_and_skip_gates(self) -> None:- overrides = parse_overrides(- {- "expires_at": EXPIRES,- "promotion": {- "freeze": ["report_embeddings"],- "force": ["report_embeddings"],- "skip_gates": {"report_embeddings": ["ece"]},- },- },- now=NOW,- )- promotion = overrides.promotion_for("report_embeddings")- assert (promotion.freeze, promotion.force, promotion.skip_gates) == (True, False, frozenset())diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.mdindex 9af48fffaf45..0711c7068364 100644--- a/products/signals/dags/inbox_ranking/AGENTS.md+++ b/products/signals/dags/inbox_ranking/AGENTS.md@@ -21,22 +21,22 @@ Read `README.md` first for what the dataset is and how partitions behave. This f- `example_grain` and `max_examples_per_head` are per set, because the examples object is. Every set defaults to the birth grain so the families target the same scoring moment; side-input availability and row budgets can still change their training populations. `report_embeddings` is the reason the budget exists (1536 columns per row). A budget limits history and never samples inside a day: `cap_examples` keeps whole report-creation days, newest first, so the kept label rate stays the population rate and the scores stay calibrated. Never reintroduce a positive-keeping sample: it raises the base rate the booster fits, and a holdout cut from the same sample hides it.- `feature_vector` (one row, serving) and `feature_frame` (vectorized, training) must agree row for row; a test pins it. Change both together.- Examples are one row per report, on the snapshot of the day it was created, labeled from the snapshot `horizon_days` later. The scoring-moment and report grains stay selectable for re-scoring families, so keep the holdout cut by report: a row-level split leaks near-duplicate snapshots of the same report the moment a set asks for one of them. The moments are chosen before the features are built, so a set under a row budget never builds columns for rows it then drops; keep that order.-- `inbox_ranking_models/v1/<model_name>/dt=D/` is history like the dataset partitions: the only mutation is a re-run of the same partition, which replaces the prefix in full (stale head files are deleted). `<model_name>/champion.json` is the only object written outside its partition, and only the champion asset (or a human, deliberately) writes it; it carries the candidate's `run_id`, so a loader can detect a re-run behind a pinned version.+- `inbox_ranking_models/v1/<model_name>/dt=D/` is history like the dataset partitions: the only mutation is a re-run of the same partition, which replaces the prefix in full (stale head files are deleted). `inbox_ranking_models/v1/served.json` is the only object written outside a partition, and only `inbox_ranking_promote_job` writes it, when a person runs it. No asset may write `served.json` or a `<model_name>/champion.json`: the champion assets record a decision and nothing else. The old `champion.json` files stay as the cross-family role's input.- The model is read in three layers: **training** (train metrics), **test** (the random-by-report holdout, which drives promotion) and **online** (`inbox_ranking_served_scores`, the scoring sweep's live scores of each day's newborns, graded by `inbox_ranking_unseen_graded` at each head's horizon). Do not add an offline rescoring of the newborn pool beside the online layer: the sweep already scores it with every model key the manifest names.- `served_score_rows` keeps the earliest scored event per (report, model key) and takes `model_role` from the event's roles. Grades stay per `(model_name, model_version, model_role)` and are never pooled across versions. A re-run that reads no event is refused when the partition already holds rows, and so is one that reads fewer families than the object holds, because the newborn state snapshot behind those rows ages out and the dt=D+horizon grade reads them.- Every scored row carries `head_readable`, and an unreadable head is still graded: a head that misses `min_holdout_positives` on one day's holdout still gets a number from the pooled online grade. Keep the promotion gate reading `readable` from the candidate metadata: an unreadable head must not decide a promotion.-- `model_name` is the model family, and every model object, scored row, grade and event carries it. A family is an entry in `MODEL_FAMILIES` (`training/unseen.py`) naming the feature set it is fit on, its `learner` and the `location` that trains it; each location's candidate and champion assets walk `families_trained_in(<location>)`, and the grader and the events need no change to gain a family. Promotion stays inside a family, so a family never takes another family's `champion.json`. Do not fold the family into `model_version`, which the dashboard filters as a date.+- `model_name` is the model family, and every model object, scored row, grade and event carries it. A family is an entry in `MODEL_FAMILIES` (`training/unseen.py`) naming the feature set it is fit on, its `learner` and the `location` that trains it; each location's candidate and champion assets walk `families_trained_in(<location>)`, and the grader and the events need no change to gain a family. A candidate is graded only against the served model of its own `model_name`; the served pointer itself can name any family. Do not fold the family into `model_version`, which the dashboard filters as a date.- A family whose `metadata.json`, examples object or side input is missing for a partition is logged and skipped, so one family does not cost every family's series. The champion asset raises only when no family has a candidate at all.-- Skipping is not the same as rebuilding from nothing, and the difference is destructive. An empty examples object produces an empty candidate, and the candidate's prefix cleanup then deletes the boosters that partition already holds, which a `champion.json` can be pointing at. So when a side input is unavailable, leave the partition's objects alone rather than writing empty ones over them.+- Skipping is not the same as rebuilding from nothing, and the difference is destructive. An empty examples object produces an empty candidate, and the candidate's prefix cleanup then deletes the boosters that partition already holds, which `served.json` or a pin can be pointing at. So when a side input is unavailable, leave the partition's objects alone rather than writing empty ones over them.- 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`.- The serving path reads the deployment's own object store, never the dataset bucket: the Temporal workers have no credential for that bucket, and keeping it that way is why the manifest asset copies what the sweep needs. `serving/models/<key>/` holds a version's `metadata.json` and its model files, `serving/manifest.json` names the models one pass scores. The holdout boosters grade a promotion and must stay behind.- An entry's files come from `ServingManifestEntry.files`: one `<head>.ubj` per head for `xgboost`, and the one `model.onnx` that `model_file` names for `onnx`. The copy step and the model store read that property, and the pin check reads the same names from each head's `file` in `metadata.json`, so a new model kind with another file layout keeps the two in step. Keep `onnxruntime` and `xgboost` imports inside the handlers' `load`: a test pins that importing the sweep loads neither.- The manifest schema and the object keys live in `products/signals/backend/ranking/serving_manifest.py`, next to the feature contract, because the dag writes them and the sweep reads them. Its validators run at write time, so the dag refuses a manifest the sweep could not act on; the entry cap is the `ranking_score` artefact's, so a manifest can never produce a row the artefact refuses.-- Publishing order is load-bearing. Every model copy finishes before `manifest.json` is written, so a failed copy leaves the previous manifest and the previous models serving. A model version is immutable, so a version whose `metadata.json` is already at the target is not copied again. A run with nothing to publish, such as a run before the served family has a champion, writes nothing rather than an empty manifest.+- Publishing order is load-bearing. Every model copy finishes before `manifest.json` is written, so a failed copy leaves the previous manifest and the previous models serving. A model version is immutable, so a version whose `metadata.json` is already at the target is not copied again. A run with nothing to publish, such as a run without `served.json`, writes nothing rather than an empty manifest. The served model passes the same check as a pin (`_pin_metadata`) before composition.- When a manifest entry has `reads_project_vectors`, the dt=D `inbox_project_vectors` day is copied to `serving/project_vectors/<D>/` before `manifest.json`, and the manifest names it in `project_vectors`. A missing day fails the publish, like a missing model file. Never copy project vectors to the mirror: they are per-team data of this deployment, so the mirror's manifest names none. Training and serving build the `project` and `has_history` inputs through the one `project_inputs` in `features.py`; keep `PROJECT_VECTOR_KINDS` and `MIN_PROJECT_HISTORY_REPORTS` there.- `HEADS` holds only the heads the inbox reads (`HeadRanker` in `backend/ranking/inbox_sort.py`). Add a head there only together with a surface that reads it. The promotion gate skips a champion head that is not in `HEADS`, so a trim does not block promotion.-- `nn` is trained by the `signals_ml` location (`nn/dag.py`), never by the main one. torch is imported only inside the candidate asset's body (through `nn/train.py` and `multihead/network.py`). `signals_ml` must import without torch, and `test_multihead_network.py` pins that. Its champion goes through `decide_family_champion`, the same rule and gate as the boosters, graded through the incumbent's `model.holdout.onnx`. Keep `signals_ml` commented out in `.dagster_home/workspace.yaml`, and keep its schedule (04:30 UTC) running by default on prod US only. `INBOX_RANKING_SERVED_FAMILY` defaults to `nn` on US Cloud only, because no other deployment has an `nn` champion.+- `nn` is trained by the `signals_ml` location (`nn/dag.py`), never by the main one. torch is imported only inside the candidate asset's body (through `nn/train.py` and `multihead/network.py`). `signals_ml` must import without torch, and `test_multihead_network.py` pins that. Its decision goes through `decide_family_champion`, the same rule as the boosters, graded through the incumbent's `model.holdout.onnx`. Keep `signals_ml` commented out in `.dagster_home/workspace.yaml`, and keep its schedule (04:30 UTC) running by default on prod US only.## Invariants — do not breakdiff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex 311d025f8990..bf9012ca8054 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -11,10 +11,11 @@ inbox_ranking/│ └── project_vectors.py # per-team context vectors (pure function)├── training/│ ├── dag.py # examples → candidate → champion assets + job + schedule+│ ├── promote.py # the manual promote job that writes served.json│ ├── examples.py # birth-grain training examples over the snapshots│ ├── heads.py # the v0 outcome heads│ ├── train.py # per-head XGBoost fit + holdout/null metrics-│ └── promotion.py # the champion promotion rule+│ └── promotion.py # the candidate grading rule├── multihead/ # the multi-head network, its ONNX export, and the offline prototype├── nn/ # the `nn` family: examples → candidate → champion assets, on the `signals_ml` location└── tests/@@ -139,14 +140,16 @@ Point-in-time caveats, per source:```texts3://<bucket>/<prefix>/├── inbox_ranking_training_examples/v1/<feature_set>/dt=YYYY-MM-DD/ # one row per report at its birth, all heads, one parquet per feature set-├── inbox_ranking_models/v1/<model_name>/-│ ├── dt=YYYY-MM-DD/<head>.ubj + <head>.holdout.ubj # the day's candidate: serving fit + train-only fit-│ │ + metadata.json # (a re-run replaces this prefix in full)-│ └── champion.json # pointer the scoring sweep loads (the only object written across partitions)+├── inbox_ranking_models/v1/+│ ├── served.json # the model key the scoring sweep serves; only the promote job writes it+│ └── <model_name>/+│ ├── dt=YYYY-MM-DD/<head>.ubj + <head>.holdout.ubj # the day's candidate: serving fit + train-only fit+│ │ + metadata.json # (a re-run replaces this prefix in full)+│ └── champion.json # retired automatic pointer; read only for the cross-family role└── inbox_ranking_served_scores/v1/dt=YYYY-MM-DD/ # the scoring sweep's scores of the reports born that day, per model key```-- **A model is a `(model_name, model_version, model_role)`.** `model_name` is the family: which features and which learner: `report_embeddings`, per-head XGBoost, is the one trained here. `nn`, one ONNX network, is trained by the `signals_ml` location, and each `MODEL_FAMILIES` entry names its `learner` and the `location` that trains it. `model_version` is the partition day it was fit on, and `model_role` is the role it was scored or trained under (`candidate` on the training events; `served`, `daily_candidate` or `cross_family` on the online grade). Each family owns a prefix under the models path and its own `champion.json`, so two families trained on the same day cannot collide, and promotion stays inside a family. A second family is a second model graded on the same online rows, not a competitor for another family's pointer.+- **A model is a `(model_name, model_version, model_role)`.** `model_name` is the family: which features and which learner: `report_embeddings`, per-head XGBoost, is the one trained here. `nn`, one ONNX network, is trained by the `signals_ml` location, and each `MODEL_FAMILIES` entry names its `learner` and the `location` that trains it. `model_version` is the partition day it was fit on, and `model_role` is the role it was scored or trained under (`candidate` on the training events; `served`, `daily_candidate` or `cross_family` on the online grade). Each family owns a prefix under the models path, so two families trained on the same day cannot collide. A candidate is graded only against the served model of its own name. The served pointer can name any family, so a rollback can cross families.- **A feature set is one feature universe.** `products/signals/backend/ranking/features.py` holds a `FeatureSet` per universe: its name, its schema version, its ordered feature names, the report-state columns it reads, `build_matrix`, and how many rows it wants per report and per head. `report_embeddings` is the one today. A candidate records the set it was fit on in its `metadata.json`, so the grader checks a model against its own set rather than one global contract, the examples asset writes one Parquet per set, and the unseen scorer builds one matrix per set and shares it across the families that read it. Adding a set means an entry in `FEATURE_SETS`; a model naming a set this build cannot produce is logged and left unscored.- **Examples are one row per report at its birth, by default.** For partition `dt=D` the examples asset reads the report-state and labels snapshots `dt=D-lookback..D` and emits one row per report, on the snapshot of the day it was created, labeled from the snapshot `horizon_days` later (7 for open, 14 for action, 30 for fixed). Features are built by the feature set from that snapshot's state columns plus `age_hours`, the report's age at the snapshot. Labels are aligned to the state spine, so a report with no label event is a negative (all-zero labels), not absent. Label-only rows (no Postgres state) are skipped, as are state rows read long after their snapshot day (backfills carry current Postgres state; see `features_observed_at`) and, for the heads that read the status stream (`action` and `fixed`), rows whose status telemetry fails the dataset's `label_provenance_ok` check. Birth is the moment serving scores a report, and the label that comes out is a per-report probability, which is what the inbox ordering needs. A report born before the window, or one whose birth-day snapshot is missing from it, is no example; `reports_missing_birth_snapshot` on the asset counts the second case, which is a gap in the partitions.- **An outcome already visible on the birth day is a future positive.** A report born on day D has no scoring moment before D, so an outcome visible at D belongs to the moment being built rather than to an earlier one; the labels of D therefore read as their defaults for a report born on D. Most outcomes land on the birth day, so this is where the positives are: censoring on them costs the `pr_created` head most of its training signal. `<set>_<head>_birth_day_positives` on the examples asset, and `birth_day_positives` on the `inbox_ranking_examples_built` event, say how many positives the rule keeps. These rows carry a hindsight the other rows do not: the state snapshot reads `signal_count`, `total_weight`, `run_count` and the text sizes live from Postgres a few hours after day D ends, so a birth-day outcome happened before its own feature read. Both the holdout AUC and the newborn unseen grade therefore read optimistically on these rows, until the scoring sweep's timestamped score log replaces the daily snapshot as this table's source.@@ -160,7 +163,13 @@ s3://<bucket>/<prefix>/- **One rendering's vectors are held at a time.** The examples asset loads a set's side inputs, builds that set's object, and releases them before the next set. Each snapshot carries a vector per live report, so a further embedding family costs runtime rather than peak memory. The scores asset narrows each snapshot to the newborn pool it scores for the same reason. Raising the pod memory limit is not the first move here.- **Candidate**: one per family, per-head XGBoost with fixed params, holdout = the last `holdout_days` of reports (cut by report, never by row), AUC + a label-permutation null. Each family trains on the examples of the feature set its registry entry names, and a family whose examples or metadata are missing that day is logged and skipped rather than failing the asset. A head is _readable_ when it has enough holdout positives and clears its null by 0.05. The shipped booster (`<head>.ubj`) is refit on everything; the train-only fit is kept as `<head>.holdout.ubj` so a later candidate can grade this model on its own holdout.- **Metrics telemetry**: each asset also captures its metrics as events into the dogfood project (the same project the label events land in), through `training/telemetry.py`: `inbox_ranking_examples_built` once per head and feature set, `inbox_ranking_candidate_trained` once per head (`head`, `model_role` always `candidate`, holdout / train AUC, average precision, logloss, positive rate, mean predicted score, the row-weighted decile calibration error, the permutation-null mean and spread, counts, `readable`), `inbox_ranking_holdout_calibration` once per head and holdout score decile `inbox_ranking_promotion_decided` once per run and `inbox_ranking_serving_manifest_published` once per run, all carrying `model_name` and `model_version` and stamped midday UTC on the partition day so re-runs and backfills chart on the day they describe. Per-head stability is a trends insight with a `head` breakdown; a readability drop is an insight alert. `metadata.json` stays the durable record. Capture is best-effort. Local dev runs (`DEBUG`) emit too, under `distinct_id` `inbox_ranking_training_local` with `environment=local`, so filter or break down on `environment` when reading the prod series; any other non-Cloud deployment emits nothing.-- **Champion**: one decision per family against that family's own pointer. `promotion.decide_promotion` — promote when the candidate has a readable head, is within 0.02 AUC and 0.02 holdout ECE of the champion on every head the champion could read, and the champion is at least `INBOX_RANKING_PROMOTION_MIN_DAYS` old. The quality gates run before the wait: `gates_passed` on the decision event and the `<family>_gates_passed` asset metadata say whether the candidate passed them, also on a day the wait blocks it, and `would_promote` stays the final decision. The champion's AUCs and ECEs come from its `<head>.holdout.ubj` scored on the candidate's holdout (`paired_champion_grades`), so both models are compared on one set of reports; a champion without that file falls back to its stored AUC and skips the calibration check. A head whose shared holdout has fewer than its `min_holdout_positives` is skipped rather than blocking, and is listed in `skipped_heads` on the decision event and the asset metadata; a head the candidate did not train still blocks. 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. To promote by hand, copy a candidate's `metadata.json` to `champion.json` with a `promoted_at`.+- **Champion**: one decision per family, recorded and never written to a pointer. The incumbent is the model `served.json` names when it has the candidate's `model_name`; otherwise there is no paired comparison, and the reason says so. `promotion.decide_promotion` says the candidate would promote when it has a readable head and is within 0.02 AUC and 0.02 holdout ECE of the incumbent on every head the incumbent could read. `would_promote` and `gates_passed` on the `inbox_ranking_promotion_decided` event and the asset metadata carry the decision, and `promoted` is always false. The incumbent's AUCs and ECEs come from its `<head>.holdout.ubj` scored on the candidate's holdout (`paired_champion_grades`), so both models are compared on one set of reports; an incumbent without that file falls back to its stored AUC and skips the calibration check. A head whose shared holdout has fewer than its `min_holdout_positives` is skipped rather than blocking, and is listed in `skipped_heads`; a head the candidate did not train still blocks.+- **Promotion is manual.** `inbox_ranking_promote_job` (`training/promote.py`, `signals` location) takes a `model_key` and a `reason`. It refuses a malformed key, a model this build cannot serve, a missing model file, and a model without every head in `HEADS`, and then writes nothing. Otherwise it writes `served.json` (`model_key`, `promoted_at`, `reason`, `previous_key`, `run_id`), captures `inbox_ranking_model_promoted`, and publishes the serving manifest for the newest partition with project vectors, so the sweep serves the model without waiting for the 05:00 UTC run. Rollback is the same job with an older key, of any family. Launch it from the Dagster UI, or:++```bash+dagster job launch -w .dagster_home/workspace.yaml --location posthog.dags.locations.signals -j inbox_ranking_promote_job \+ --config-json '{"ops": {"inbox_ranking_promote": {"config": {"model_key": "nn@2026-10-16", "reason": "seed the pointer"}}}}'+```- **Serving manifest**: the dag's decision about what the scoring sweep runs, published where the sweep can read it. The Temporal workers have no credential for the dataset bucket, so `inbox_ranking_serving_manifest` copies the models the sweep needs into the deployment's own object store and writes a manifest naming them:@@ -176,7 +185,7 @@ Each entry names its `model_kind`, and the sweep loads it through that kind's ha- `xgboost`, the default for a model without the field: one booster per head, `<head>.ubj`. The entry's `heads` list names the files.- `onnx`: one `model.onnx` for every head. The entry names it in `model_file`, and `heads` still lists the heads it scores. The graph takes one float32 input, `report`, of shape (batch, feature-set width), and gives one output, `probabilities`, of shape (batch, heads). The column order of that output is `output_heads` in the model's `metadata.json`, and each head entry in `heads` there names `model.onnx` as its `file`. At load, the handler checks the input names and widths against what the model's feature set builds, and a mismatch skips the model like an unloadable booster. The session runs on CPU with a bounded thread count, and `onnxruntime` is imported only when a model loads. The project-vector inputs are not served yet, so the sweep skips an `nn` model, whose graph also takes `project` and `has_history`, until it feeds them.-The manifest holds one entry per model with its `roles`: `served` for the champion of `INBOX_RANKING_SERVED_FAMILY`, `daily_candidate` for that family's candidate on this partition when it is a different, readable model, `pinned` for each model the `pin` override keeps (see [Overrides](#overrides)), and `cross_family` for every other family's champion that has a readable head. A pass scores all of them, so an online paired read and a later interleaving need no rescoring; the entry count is capped at the `ranking_score` artefact's own limit, dropping `cross_family` entries first and `pinned` entries next. The schema, the role names and the object keys live in `products/signals/backend/ranking/serving_manifest.py`, and its validators run at write time, so the dag refuses a manifest the sweep could not act on. A model version is immutable, so a version already in the store is not copied again, and `manifest.json` is written last: a failed copy leaves the previous manifest and the previous models serving. No family has a champion until the first promotion, so until then the asset writes nothing and says why.+The manifest holds one entry per model with its `roles`: `served` for the model `served.json` names, `daily_candidate` for the candidate of the same `model_name` on this partition when it is a different, readable model, `pinned` for each model the `pin` override keeps (see [Overrides](#overrides)), and `cross_family` for every other family's `champion.json` that has a readable head. Nothing writes those files anymore, so they name the last version the retired automatic promotion chose. A pass scores all of them, so an online paired read and a later interleaving need no rescoring; the entry count is capped at the `ranking_score` artefact's own limit, dropping `cross_family` entries first and `pinned` entries next. The schema, the role names and the object keys live in `products/signals/backend/ranking/serving_manifest.py`, and its validators run at write time, so the dag refuses a manifest the sweep could not act on. A model version is immutable, so a version already in the store is not copied again, and `manifest.json` is written last: a failed copy leaves the previous manifest and the previous models serving. When `served.json` is missing, or names a model that fails the pin check, the asset writes nothing and says why, and the previous manifest keeps serving.A region that does not train serves the same models through a mirror. When `INBOX_RANKING_SERVING_MIRROR_BUCKET` is set, the asset repeats the publish into that bucket after the primary publish succeeds, in the same order and with the same skip of versions already there. A mirror failure does not fail the asset: it logs, and the `inbox_ranking_serving_manifest_published` event carries `mirror_published=false`. The property is absent when no mirror is set.@@ -184,7 +193,7 @@ The reader is `score_reports` in `products/signals/backend/ranking/scorer.py`. I### Overrides-An owner can change serving and promotion without a training run, through the payload of the `inbox-ranking-overrides` feature flag in the internal PostHog project. The flag is inert by default. When the flag is off, the payload is empty, or the lookup fails, the sweep and the dag run as they do without the flag. The parser is `products/signals/backend/ranking/overrides.py`, and the sweep and the dag share it.+An owner can change serving without a training run or a Dagster launch, through the payload of the `inbox-ranking-overrides` feature flag in the internal PostHog project. The flag is inert by default. When the flag is off, the payload is empty, or the lookup fails, the sweep and the dag run as they do without the flag. The parser is `products/signals/backend/ranking/overrides.py`, and the sweep and the dag share it.Every key is optional, but no key applies without `expires_at`:@@ -192,39 +201,29 @@ Every key is optional, but no key applies without `expires_at`:{"expires_at": "2026-10-11T00:00:00Z","served": "report_embeddings@2026-10-03",- "pin": ["report_embeddings@2026-09-26"],- "promotion": {- "freeze": ["report_embeddings"],- "force": ["report_embeddings"],- "skip_gates": { "report_embeddings": ["min_days", "ece", "min_holdout_positives"] }- }+ "pin": ["report_embeddings@2026-09-26"]}```-| Key | Read by | Effect |-| ---------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `expires_at` | sweep and dag | Required. After this time the sweep and the dag ignore the payload and log `inbox_ranking_override_expired`. A payload with no `expires_at`, or one more than 14 days ahead, is invalid. |-| `served` | sweep, once per pass | Gives this model key the `served` role for the pass. The key must name a model in the current manifest, a pinned one included. No `champion.json` changes, and removing the key reverts on the next tick. |-| `pin` | dag (`inbox_ranking_serving_manifest`) | Keeps these model keys in the manifest with the `pinned` role, so a `served` override survives the next manifest rewrite and can roll back to an older model. |-| `promotion.freeze` | dag (`inbox_ranking_model_champion`) | For these families, the run trains, grades and records the decision, but never writes `champion.json`. |-| `promotion.force` | dag (`inbox_ranking_model_champion`) | For these families, the run promotes the day's candidate when `decide_promotion` refuses it. The candidate must still be newer than the champion and have a readable head. This is a lasting champion change. |-| `promotion.skip_gates` | dag (`inbox_ranking_model_champion`) | Waives named checks of `decide_promotion` for one family: `min_days` (the `INBOX_RANKING_PROMOTION_MIN_DAYS` wait), `ece` (`ECE_TOLERANCE`), `min_holdout_positives` (a head whose candidate holdout is too thin to read does not block). |+| Key | Read by | Effect |+| ------------ | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `expires_at` | sweep and dag | Required. After this time the sweep and the dag ignore the payload and log `inbox_ranking_override_expired`. A payload with no `expires_at`, or one more than 14 days ahead, is invalid. |+| `served` | sweep, once per pass | Gives this model key the `served` role for the pass. The key must name a model in the current manifest, a pinned one included. `served.json` does not change, and removing the key reverts on the next tick. |+| `pin` | dag (`inbox_ranking_serving_manifest`) | Keeps these model keys in the manifest with the `pinned` role, so a `served` override survives the next manifest rewrite and can roll back to an older model. |-`freeze` wins over `force` and `skip_gates` for the same family. `force` and `skip_gates` still need `INBOX_RANKING_AUTO_PROMOTE` on, so the flag cannot promote where promotion is off. An unknown key, an unknown gate, or a model key that is not `<model_name>@<YYYY-MM-DD>` makes the whole payload invalid: it is never partly applied, and `inbox_ranking_override_invalid` logs the reason.+Promotion is not an override: use `inbox_ranking_promote_job`. A payload that still carries the retired `promotion` key is invalid. An unknown key, or a model key that is not `<model_name>@<YYYY-MM-DD>`, makes the whole payload invalid: it is never partly applied, and `inbox_ranking_override_invalid` logs the reason.The worst result of a bad payload is a warning, never a stopped pass or an unpublished manifest:- A `served` key that is not in the manifest, that did not load (missing files, a feature contract mismatch, an untrained head), that has fewer heads than the manifest's served model is rejected. The sweep logs `inbox_ranking_override_rejected` and scores with the manifest's served model. The override only moves the `served` role among models the pods already load, so it never adds memory.- A pinned key whose `metadata.json` or boosters are missing in the dataset bucket, or that fails `model_mismatch`, is dropped before composition. The manifest still publishes, and the asset metadata lists `pinned_keys` and `dropped_pins` with reasons.-During a `served` override, the override model carries the roles `served` and `served_override`, and the manifest's served model carries `manifest_served` in place of `served`. The sweep compares the served key on the latest `ranking_score` with the effective one, so setting or removing an override rescores every report in the window. The `inbox_ranking_sweep_finished` log and each `inbox_ranking_report_scored` event carry `override_served` and `override_expires_at`. The `inbox_ranking_promotion_decided` event carries `override` (`frozen`, `forced`, `skipped_gates` or null) and `override_skipped_gates`, next to the `reason` the rule gave, so a forced promotion still records why the rule refused it.+During a `served` override, the override model carries the roles `served` and `served_override`, and the manifest's served model carries `manifest_served` in place of `served`. The sweep compares the served key on the latest `ranking_score` with the effective one, so setting or removing an override rescores every report in the window. The `inbox_ranking_sweep_finished` log and each `inbox_ranking_report_scored` event carry `override_served` and `override_expires_at`.Examples, each with an `expires_at` at most 14 days ahead:- Serve today's candidate now: set `served` to the `daily_candidate` key of the current manifest.-- Roll back to an older champion: add its key to `pin`, wait for the next manifest run (or rematerialize `inbox_ranking_serving_manifest`), then set `served` to the same key.-- Pause promotion while a regression is investigated: `"promotion": {"freeze": ["report_embeddings"]}`.-- Promote a candidate the rule refused for a harmless reason: `"promotion": {"force": ["report_embeddings"]}`, or the narrower `skip_gates` with the gate that refused it.+- Roll back to an older model without a Dagster launch: add its key to `pin`, wait for the next manifest run (or rematerialize `inbox_ranking_serving_manifest`), then set `served` to the same key. For a lasting rollback, run `inbox_ranking_promote_job` with the key.Both regions read the same flag, so one override applies everywhere, if the region's `posthoganalytics` client evaluates flags in the internal project. A region that cannot read the flag runs with no override. Nothing deletes old model prefixes in the dataset bucket or old `serving/models/<key>/` copies. If the bucket has a lifecycle rule, a rollback through `pin` works only while the model files are still there.@@ -238,7 +237,7 @@ Both regions read the same flag, so one override applies everywhere, if the regiThe families train only these three heads, because the inbox reads only these three.The dataset still snapshots the label columns of other outcomes, so a head can come back without a labels backfill.-The promotion gate compares only the heads in `HEADS`, so a champion that carries a retired head does not block a candidate without it.+The promotion rule compares only the heads in `HEADS`, so an incumbent that carries a retired head does not block a candidate without it.`action` counts intent from every surface, not only the cloud inbox list.A report is a positive when someone clicked an intent action in the inbox UI (create PR, implement, copy the prompt, discuss, open or view a PR, edit the reviewers, restore), or when a person or an external agent claimed it, linked a PR, left a note, discussed it in Slack, or resolved it.@@ -344,7 +343,7 @@ The network leaves out every report that is in any head's holdout, so the compar### The nn family-`nn` is one multi-head network (`multihead/network.py`) over the report vector and the team's `typical`, `open`, `action` and `dismiss` project vectors, with the heads `open`, `action` and `fixed`. It is a model family like the per-head ones: it has its own prefix and its own `champion.json`, the main job's serving manifest names its champion as an `onnx` entry, and the online grader grades it. The main location's candidate and champion assets never fit it.+`nn` is one multi-head network (`multihead/network.py`) over the report vector and the team's `typical`, `open`, `action` and `dismiss` project vectors, with the heads `open`, `action` and `fixed`. It is a model family like the per-head ones: it has its own prefix, the main job's serving manifest names a served or cross-family `nn` model as an `onnx` entry, and the online grader grades it. The main location's candidate and champion assets never fit it.`inbox_ranking_nn_training_job` lives on its own code location, `posthog/dags/locations/signals_ml.py`, which runs on an image with the `inbox-ranking` group. torch is imported only inside the candidate asset's body, so the location module imports on the main image too, and `test_multihead_network.py` fails if torch reaches it. The job writes:@@ -353,14 +352,14 @@ s3://<bucket>/<prefix>/├── inbox_ranking_nn_examples/v1/dt=YYYY-MM-DD/ # rows, a label and a holdout flag per head; no vectors└── inbox_ranking_models/v1/nn/├── dt=YYYY-MM-DD/model.onnx + model.holdout.onnx + metadata.json- └── champion.json+ └── champion.json # retired; nothing writes it```- **Examples** are the prototype's: each head's `example_moments` over the `report_embeddings` set, capped by `cap_examples` and split by `holdout_mask`, so every head's rows and holdout are the ones its `report_embeddings` champion is graded on. The object holds no vector. The candidate and champion assets rebuild the report vectors and the project vectors from the dt=D embeddings and labels snapshots.- **Candidate**: the network trains on the rows in no head's holdout and is graded on each head's own holdout through the same `head_metrics` the boosters use, so `metadata.json` carries the same per-head fields (pooled and within-team AUC, average precision, ECE, readability, row counts, example window). Readability uses the boosters' permutation null: three networks fit on permuted labels. `model.onnx` is a refit on every labeled row, and `model.holdout.onnx` is the train-only fit. `metadata.json` has `model_kind: onnx`, `feature_set: report_embeddings`, and `output_heads`, the graph's column order.-- **Champion**: the same rule, overrides and `INBOX_RANKING_AUTO_PROMOTE` gate as the other families (`decide_family_champion`). The incumbent is graded through its `model.holdout.onnx` on the candidate's holdout, with `onnxruntime`.+- **Champion**: the same rule as the other families (`decide_family_champion`), recorded and never written to a pointer. The incumbent is the served model when it is an `nn` model, graded through its `model.holdout.onnx` on the candidate's holdout, with `onnxruntime`.- **A missing partition is a skip.** If the dt=D state, labels or embeddings snapshot is missing, each asset logs and writes nothing, so the partition keeps the objects it holds.-- **Schedule**: 04:30 UTC, after the dataset job's 2h budget (02:30 UTC start) and before the 05:00 UTC training job when the run is short enough. A champion that lands after that day's manifest is published by the next day's manifest. The schedule runs by default on prod US and is stopped everywhere else.+- **Schedule**: 04:30 UTC, after the dataset job's 2h budget (02:30 UTC start) and before the 05:00 UTC training job when the run is short enough. A candidate that lands after that day's manifest is paired by the next day's manifest. The schedule runs by default on prod US and is stopped everywhere else.To run it locally, install the group (`uv sync --group inbox-ranking`), sync the snapshots with `INBOX_RANKING_SYNC_EMBEDDINGS=1` as in [Running the training job locally](#running-the-training-job-locally), and uncomment `posthog.dags.locations.signals_ml` in `.dagster_home/workspace.yaml`. The entry is commented out because most developers do not have torch installed. Then launch the job:@@ -371,18 +370,15 @@ dagster job launch -w .dagster_home/workspace.yaml --location posthog.dags.locat## 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` | `0` | Minimum age of the champion before another promotion. The scoring sweep stamps each score with its model key, so no wait is needed for a clean read. |-| `INBOX_RANKING_SERVED_FAMILY` | `report_embeddings` | Family whose champion the serving manifest serves. US Cloud defaults to `nn`. Local dev, tests and EU have no `nn` champion, so they default to `report_embeddings`. |-| `INBOX_RANKING_SERVING_MIRROR_BUCKET` | unset | A second deployment's object-storage bucket that receives a copy of every serving publish, through ambient AWS config. Unset means no mirror. |-| `INBOX_RANKING_SERVING_MIRROR_REGION` | unset | AWS region of the mirror bucket. |-| `INBOX_RANKING_SCORING_BATCH_SIZE` | `500` | Report ids per ClickHouse vector read in the scorer. A larger call is paged at this size. |+| 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_SERVING_MIRROR_BUCKET` | unset | A second deployment's object-storage bucket that receives a copy of every serving publish, through ambient AWS config. Unset means no mirror. |+| `INBOX_RANKING_SERVING_MIRROR_REGION` | unset | AWS region of the mirror bucket. |+| `INBOX_RANKING_SCORING_BATCH_SIZE` | `500` | Report ids per ClickHouse vector read in the scorer. A larger call is paged at this size. |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.diff --git a/products/signals/dags/inbox_ranking/common.py b/products/signals/dags/inbox_ranking/common.pyindex f5ed0a3c1f8f..87dfbdee6ac9 100644--- a/products/signals/dags/inbox_ranking/common.py+++ b/products/signals/dags/inbox_ranking/common.py@@ -62,6 +62,9 @@ partition_def = dagster.DailyPartitionsDefinition(start_date="2026-04-01")owner_tags: dict[str, str] = {"owner": JobOwners.TEAM_SELF_DRIVING.value}+# The serving publish runs inside the manifest asset and inside the manual promote job.+RunContext = dagster.AssetExecutionContext | dagster.OpExecutionContext+def is_inbox_ranking_registered() -> bool:"""EU report rows and embeddings are unreachable from a US dag, and labels from every regiondiff --git a/products/signals/dags/inbox_ranking/nn/dag.py b/products/signals/dags/inbox_ranking/nn/dag.pyindex 904b2ef76cac..c043db695ba0 100644--- a/products/signals/dags/inbox_ranking/nn/dag.py+++ b/products/signals/dags/inbox_ranking/nn/dag.py@@ -6,12 +6,12 @@ which runs on the image that carries torch:inbox_ranking_nn_examples/v1/dt=D/ rows, labels and holdout flags (`nn/examples.py`)inbox_ranking_models/v1/nn/dt=D/model.onnx the refit that serves, + model.holdout.onnx and metadata.json- inbox_ranking_models/v1/nn/champion.json pointer to the version the scoring sweep loads+ (no object) the champion asset grades the candidate and records the decisionThe main location's training job never fits `nn`, and this job never writes another family's-objects. The main job's serving manifest and online grader walk every family in `MODEL_FAMILIES`,-so they publish and grade an `nn` champion as an `onnx` entry with no change here. A champion that-lands after that day's manifest is published by the next day's manifest.+objects or any pointer. A person serves an `nn` version with `inbox_ranking_promote_job`. The main+job's serving manifest and online grader then publish and grade it as an `onnx` entry with no+change here. A candidate that lands after that day's manifest is paired by the next day's manifest.All three assets read the dt=D dataset partitions from the dataset bucket, as the main training jobdoes. A partition whose snapshots are missing is logged and skipped, and the objects already under@@ -30,7 +30,6 @@ from posthog import settingsfrom posthog.dataclasses import frozenfrom products.signals.backend.ranking.features import Extras-from products.signals.backend.ranking.overrides import read_ranking_overridesfrom products.signals.backend.ranking.serving_manifest import ONNX_MODEL_FILE, ONNX_MODEL_KINDfrom products.signals.dags.inbox_ranking.common import (S3_BUCKET_ENV,@@ -181,7 +180,7 @@ def train_candidate() -> dict[str, dagster.MetadataValue]:"""Fit the day's network, write its graphs and `metadata.json` under `nn/dt=D/`, and return theasset metadata. A partition without examples or snapshots keeps the objects it already holds,- because a `champion.json` can name them."""+ because the served pointer can name them."""prefix = settings.INBOX_RANKING_DATASET_S3_PREFIXarrow = read_parquet_if_exists(client, bucket, partition_object_key(prefix, NN_EXAMPLES_TABLE, partition_key))if arrow is None:@@ -274,14 +273,16 @@ def inbox_ranking_nn_model_champion(context: dagster.AssetExecutionContext) -> Ndef decide_champion(context: dagster.AssetExecutionContext, client, bucket: str, partition_key: str) -> dict[str, dagster.MetadataValue] | None:- """The `nn` promotion decision, through the rule, the overrides and the- `INBOX_RANKING_AUTO_PROMOTE` gate every family shares. Only `nn/champion.json` is ever written."""+ """The `nn` promotion decision, through the rule every family shares. Nothing is written: the+ decision is recorded for the person who runs `inbox_ranking_promote_job`."""prefix = settings.INBOX_RANKING_DATASET_S3_PREFIXdef grade_champion(champion: Mapping[str, Any]) -> dict[str, HoldoutGrade]:version = champion.get("model_version")if champion.get("model_kind") != ONNX_MODEL_KIND:- context.log.warning(f"nn champion {version} is not an {ONNX_MODEL_KIND} model; compared on its stored AUC")+ context.log.warning(+ f"served nn model {version} is not an {ONNX_MODEL_KIND} model; compared on its stored AUC"+ )return {}holdout_model = _read_bytes_if_exists(client, bucket, model_object_key(prefix, NN_FAMILY.name, str(version), HOLDOUT_MODEL_FILE)@@ -289,8 +290,8 @@ def decide_champion(arrow = read_parquet_if_exists(client, bucket, partition_object_key(prefix, NN_EXAMPLES_TABLE, partition_key))if holdout_model is None or arrow is None:context.log.warning(- f"no nn champion {HOLDOUT_MODEL_FILE} or no examples for dt={partition_key}; "- "the nn champion is compared on its stored AUC"+ f"no served nn {HOLDOUT_MODEL_FILE} or no examples for dt={partition_key}; "+ "the served nn model is compared on its stored AUC")return {}day = _day_inputs(context, client, bucket, prefix, partition_key)@@ -303,14 +304,7 @@ def decide_champion()return decide_family_champion(- context,- client,- bucket,- prefix,- partition_key,- NN_FAMILY,- read_ranking_overrides(datetime.datetime.now(datetime.UTC)),- grade_champion=grade_champion,+ context, client, bucket, prefix, partition_key, NN_FAMILY, grade_champion=grade_champion)@@ -339,8 +333,8 @@ inbox_ranking_nn_training_job = dagster.define_asset_job(# After the dataset job's 2h budget (02:30 UTC start), so the dt=D-1 snapshots exist, and before the-# main training job (05:00 UTC) where the run is short enough. A champion that lands after that-# job's manifest is published by the next day's manifest.+# main training job (05:00 UTC) where the run is short enough. A candidate that lands after that+# job's manifest is paired by the next day's manifest.@dagster.schedule(cron_schedule="30 4 * * *",job=inbox_ranking_nn_training_job,diff --git a/products/signals/dags/inbox_ranking/tests/test_nn.py b/products/signals/dags/inbox_ranking/tests/test_nn.pyindex 64fbae1aa5ca..9e5a7ca6f9de 100644--- a/products/signals/dags/inbox_ranking/tests/test_nn.py+++ b/products/signals/dags/inbox_ranking/tests/test_nn.py@@ -47,10 +47,11 @@ from products.signals.dags.inbox_ranking.tests.test_multihead import D0, DAYS, Hfrom products.signals.dags.inbox_ranking.training.dag import (CHAMPION_FILE,METADATA_FILE,- champion_object_key,+ SERVED_FILE,inbox_ranking_model_candidate,inbox_ranking_model_champion,model_object_key,+ served_object_key,)from products.signals.dags.inbox_ranking.training.serving import FamilyModels, compose_manifestfrom products.signals.dags.inbox_ranking.training.train import HeadMetrics@@ -140,12 +141,11 @@ def no_side_effects(monkeypatch: pytest.MonkeyPatch) -> None:for module in ("products.signals.dags.inbox_ranking.training.dag", "products.signals.dags.inbox_ranking.nn.dag"):monkeypatch.setattr(f"{module}.capture_training_events", lambda *args, **kwargs: None)monkeypatch.setattr(f"{module}.read_ranking_overrides", lambda now: NO_OVERRIDES, raising=False)- monkeypatch.setattr(settings, "INBOX_RANKING_AUTO_PROMOTE", True)-def test_the_main_location_never_fits_or_promotes_nn(monkeypatch, no_side_effects):- # Every family has a candidate and no champion, so the main champion asset promotes each family- # it walks. An `nn` pointer written here would name XGBoost files the sweep loads as ONNX.+def test_the_main_location_never_fits_nn_or_writes_a_pointer(monkeypatch, no_side_effects):+ # Every family has a candidate and nothing is served, so each decision would promote. Training+ # still writes no pointer: only the promote job chooses what the sweep serves.client = _S3({model_object_key(PREFIX, name, PARTITION, METADATA_FILE): json.dumps(@@ -160,8 +160,7 @@ def test_the_main_location_never_fits_or_promotes_nn(monkeypatch, no_side_effectinbox_ranking_model_candidate(context)inbox_ranking_model_champion(context)- champions = {key.split("/")[-2] for key in client.objects if key.endswith(CHAMPION_FILE)}- assert champions == {REPORT_EMBEDDINGS_MODEL_NAME}+ assert not [key for key in client.objects if key.endswith((CHAMPION_FILE, SERVED_FILE))]assert not [key for key in client.objects if f"/{NN_MODEL_NAME}/" in key and not key.endswith(METADATA_FILE)]@@ -175,7 +174,7 @@ def test_the_manifest_carries_an_nn_champion_as_an_onnx_entry():),FamilyModels(name=NN_MODEL_NAME, candidate=None, champion=_nn_metadata("2026-08-16")),],- served_family=REPORT_EMBEDDINGS_MODEL_NAME,+ served=_xgboost_metadata(REPORT_EMBEDDINGS_MODEL_NAME, "2026-08-15"),prefix=PREFIX,now=NOW,)@@ -188,7 +187,7 @@ def test_the_manifest_carries_an_nn_champion_as_an_onnx_entry():assert entry.heads == ["open"]-def test_the_manifest_serves_an_nn_champion_with_the_xgboost_champion_as_a_challenger():+def test_the_manifest_serves_an_nn_model_with_the_xgboost_champion_as_a_challenger():decision = compose_manifest([FamilyModels(@@ -202,7 +201,7 @@ def test_the_manifest_serves_an_nn_champion_with_the_xgboost_champion_as_a_challchampion=_nn_metadata("2026-08-16", heads=NN_HEAD_NAMES),),],- served_family=NN_MODEL_NAME,+ served=_nn_metadata("2026-08-16", heads=NN_HEAD_NAMES),prefix=PREFIX,now=NOW,)@@ -219,24 +218,27 @@ def test_the_manifest_serves_an_nn_champion_with_the_xgboost_champion_as_a_challassert sorted(served.heads) == sorted(NN_HEAD_NAMES)-def test_nn_promotion_writes_only_its_own_pointer(no_side_effects):- other_champion = json.dumps(_xgboost_metadata(REPORT_EMBEDDINGS_MODEL_NAME, "2026-08-15")).encode()+def test_the_nn_decision_is_graded_against_the_served_nn_model_and_writes_nothing(no_side_effects):+ served = _nn_metadata("2026-08-16")client = _S3({model_object_key(PREFIX, NN_MODEL_NAME, PARTITION, METADATA_FILE): json.dumps(_nn_metadata(PARTITION)).encode(),- champion_object_key(PREFIX, REPORT_EMBEDDINGS_MODEL_NAME): other_champion,+ model_object_key(PREFIX, NN_MODEL_NAME, "2026-08-16", METADATA_FILE): json.dumps(served).encode(),+ served_object_key(PREFIX): json.dumps(+ {"model_key": f"{NN_MODEL_NAME}@2026-08-16", "model_name": NN_MODEL_NAME, "model_version": "2026-08-16"}+ ).encode(),})- before = set(client.objects)+ before = dict(client.objects)with dagster.build_asset_context(partition_key=PARTITION) as context:- nn_dag.decide_champion(context, client, "bucket", PARTITION)+ metadata = nn_dag.decide_champion(context, client, "bucket", PARTITION)- assert set(client.objects) - before == {champion_object_key(PREFIX, NN_MODEL_NAME)}- assert client.objects[champion_object_key(PREFIX, REPORT_EMBEDDINGS_MODEL_NAME)] == other_champion- assert json.loads(client.objects[champion_object_key(PREFIX, NN_MODEL_NAME)])["model_version"] == PARTITION+ assert metadata is not None+ assert metadata[f"{NN_MODEL_NAME}_incumbent_champion_version"].value == "2026-08-16"+ assert client.objects == beforedef test_the_nn_candidate_writes_a_graph_whose_columns_follow_its_recorded_head_order(monkeypatch, no_side_effects):diff --git a/products/signals/dags/inbox_ranking/tests/test_promote.py b/products/signals/dags/inbox_ranking/tests/test_promote.pynew file mode 100644index 000000000000..d1c9997abae5--- /dev/null+++ b/products/signals/dags/inbox_ranking/tests/test_promote.py@@ -0,0 +1,122 @@+import json+import datetime+from typing import Any++import pytest++import dagster++from posthog import settings++from products.signals.backend.ranking.features import REPORT_EMBEDDINGS_FEATURE_SET+from products.signals.backend.ranking.serving_manifest import ServingManifest, serving_manifest_key+from products.signals.dags.inbox_ranking.common import partition_object_key+from products.signals.dags.inbox_ranking.dataset.dag import PROJECT_VECTORS_TABLE+from products.signals.dags.inbox_ranking.tests.test_training import _AppObjectStore, _ModelStoreS3, _patch_capture+from products.signals.dags.inbox_ranking.training.dag import METADATA_FILE, model_object_key, served_object_key+from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME+from products.signals.dags.inbox_ranking.training.promote import PromoteConfig, inbox_ranking_promote+from products.signals.dags.inbox_ranking.training.telemetry import MODEL_PROMOTED_EVENT+from products.signals.dags.inbox_ranking.training.unseen import REPORT_EMBEDDINGS_MODEL_NAME, ModelFamily++PREFIX = settings.INBOX_RANKING_DATASET_S3_PREFIX+SERVED_VERSION = "2026-10-16"+OLDER_VERSION = "2026-10-01"+++class _WritableS3(_ModelStoreS3):+ def put_object(self, *, Bucket, Key, Body, ContentType=None):+ self.objects[Key] = Body+++def _metadata(version: str, heads: tuple[str, ...]) -> dict[str, Any]:+ return {+ "model_name": REPORT_EMBEDDINGS_MODEL_NAME,+ "model_version": version,+ "feature_set": REPORT_EMBEDDINGS_FEATURE_SET.name,+ "feature_schema_version": REPORT_EMBEDDINGS_FEATURE_SET.schema_version,+ "feature_names": list(REPORT_EMBEDDINGS_FEATURE_SET.feature_names),+ "heads": [{"head": head, "readable": True, "file": f"{head}.ubj"} for head in heads],+ }+++def _add_model(objects: dict[str, bytes], version: str, heads: tuple[str, ...], *, files: bool = True) -> None:+ folder = model_object_key(PREFIX, REPORT_EMBEDDINGS_MODEL_NAME, version, "")+ objects[folder + METADATA_FILE] = json.dumps(_metadata(version, heads)).encode()+ if files:+ for head in heads:+ objects[folder + f"{head}.ubj"] = b"booster"+++def _dataset() -> _WritableS3:+ all_heads = tuple(sorted(HEADS_BY_NAME))+ objects: dict[str, bytes] = {+ served_object_key(PREFIX): json.dumps(+ {+ "model_key": f"{REPORT_EMBEDDINGS_MODEL_NAME}@{SERVED_VERSION}",+ "model_name": REPORT_EMBEDDINGS_MODEL_NAME,+ "model_version": SERVED_VERSION,+ }+ ).encode(),+ }+ yesterday = (datetime.datetime.now(datetime.UTC).date() - datetime.timedelta(days=1)).isoformat()+ objects[partition_object_key(PREFIX, PROJECT_VECTORS_TABLE, yesterday)] = b"vectors"+ _add_model(objects, SERVED_VERSION, all_heads)+ _add_model(objects, OLDER_VERSION, all_heads)+ _add_model(objects, "2026-09-01", all_heads, files=False)+ _add_model(objects, "2026-09-02", all_heads[:1])+ return _WritableS3(objects)+++def _promote(monkeypatch: pytest.MonkeyPatch, client: _WritableS3, store: _AppObjectStore, model_key: str):+ capture = _patch_capture(monkeypatch, cloud=True, debug=False)+ monkeypatch.setattr(settings, "INBOX_RANKING_DATASET_S3_BUCKET", "test-bucket")+ monkeypatch.setattr(settings, "INBOX_RANKING_SERVING_MIRROR_BUCKET", "")+ monkeypatch.setattr(+ "products.signals.dags.inbox_ranking.training.dag.MODEL_FAMILIES",+ (ModelFamily(name=REPORT_EMBEDDINGS_MODEL_NAME, feature_set=REPORT_EMBEDDINGS_FEATURE_SET),),+ )+ for module in ("dag", "promote"):+ monkeypatch.setattr(f"products.signals.dags.inbox_ranking.training.{module}.s3_client", lambda: client)+ monkeypatch.setattr("posthog.storage.object_storage.object_storage_client", lambda: store)+ with dagster.build_op_context() as context:+ inbox_ranking_promote(context, PromoteConfig(model_key=model_key, reason="roll back"))+ return capture+++def test_a_rollback_to_an_older_version_rewrites_the_pointer_and_publishes_it(monkeypatch):+ client, store = _dataset(), _AppObjectStore()++ capture = _promote(monkeypatch, client, store, f"{REPORT_EMBEDDINGS_MODEL_NAME}@{OLDER_VERSION}")++ pointer = json.loads(client.objects[served_object_key(PREFIX)])+ assert (pointer["model_key"], pointer["previous_key"], pointer["reason"]) == (+ f"{REPORT_EMBEDDINGS_MODEL_NAME}@{OLDER_VERSION}",+ f"{REPORT_EMBEDDINGS_MODEL_NAME}@{SERVED_VERSION}",+ "roll back",+ )+ manifest = ServingManifest.model_validate_json(store.objects[serving_manifest_key(PREFIX)])+ assert manifest.served.key == pointer["model_key"]+ [event] = [call["properties"] for call in capture.calls if call["event"] == MODEL_PROMOTED_EVENT]+ assert event["model_key"] == pointer["model_key"]+ assert event["previous_key"] == pointer["previous_key"]+++ "model_key,message",+ [+ ("report_embeddings@latest", "not a `<model_name>@<YYYY-MM-DD>` model key"),+ (f"{REPORT_EMBEDDINGS_MODEL_NAME}@2026-09-01", "missing model files"),+ (f"{REPORT_EMBEDDINGS_MODEL_NAME}@2026-09-02", "has no model for the heads"),+ ],+ ids=["malformed_key", "missing_file", "missing_head"],+)+def test_a_model_the_sweep_could_not_serve_is_refused_and_nothing_is_written(monkeypatch, model_key, message):+ client, store = _dataset(), _AppObjectStore()+ before = dict(client.objects)++ with pytest.raises(dagster.Failure, match=message):+ _promote(monkeypatch, client, store, model_key)++ assert client.objects == before+ assert store.objects == {}diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.pyindex 92b011d04590..55b3f3feb20c 100644--- a/products/signals/dags/inbox_ranking/tests/test_training.py+++ b/products/signals/dags/inbox_ranking/tests/test_training.py@@ -35,7 +35,7 @@ from products.signals.backend.ranking.features import (feature_set_by_name,)from products.signals.backend.ranking.model_contract import classification_thresholds, model_mismatch-from products.signals.backend.ranking.overrides import PromotionOverride, RankingOverrides+from products.signals.backend.ranking.overrides import RankingOverridesfrom products.signals.backend.ranking.serving_manifest import (CROSS_FAMILY_ROLE,DAILY_CANDIDATE_ROLE,@@ -84,6 +84,7 @@ from products.signals.dags.inbox_ranking.training.dag import (inbox_ranking_unseen_graded,load_snapshots,model_object_key,+ served_object_key,snapshot_dates,)from products.signals.dags.inbox_ranking.training.examples import (@@ -104,8 +105,6 @@ from products.signals.dags.inbox_ranking.training.promotion import (AUC_TOLERANCE,ECE_TOLERANCE,PromotionDecision,- PromotionOutcome,- apply_promotion_override,decide_promotion,)from products.signals.dags.inbox_ranking.training.served import (@@ -1421,9 +1420,6 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):decision=PromotionDecision(promote=True, reason="no champion yet", gates_passed=True, skipped_heads=("discuss",)),- outcome=PromotionOutcome(promote=True, override=None),- promoted=False,- champion_version="none",incumbent_champion_version="none",champion_aucs={"open": 0.6},champion_eces={"open": 0.05},@@ -1580,7 +1576,7 @@ def _metadata(version: str, **aucs: float | None) -> dict:@pytest.mark.parametrize("candidate,champion,expected_promote,reason_fragment",[- (_metadata("d2", open=0.65), None, True, "no champion"),+ (_metadata("d2", open=0.65), None, True, "no served model"),(_metadata("d2", open=None), None, False, "no readable head"),(_metadata("d2", open=0.65),@@ -1624,38 +1620,17 @@ def _metadata(version: str, **aucs: float | None) -> dict:],)def test_decide_promotion(candidate, champion, expected_promote, reason_fragment):- decision = decide_promotion(candidate, champion, now=NOW, min_days_between=3)+ decision = decide_promotion(candidate, champion)assert decision.promote is expected_promoteassert reason_fragment in decision.reason- "candidate_auc,expected_gates_passed,reason_fragment",- [- (0.70, True, "candidate passed every gate but champion d1 promoted less than 3d ago"),- # The wait must not hide a regression: the reason names the failed gate.- (0.65 - AUC_TOLERANCE - 0.01, False, "open regressed"),- ],-)-def test_decide_promotion_runs_the_quality_gates_before_the_wait(candidate_auc, expected_gates_passed, reason_fragment):- candidate = _metadata("d2", open=candidate_auc)- champion = {**_metadata("d1", open=0.65), "promoted_at": "2026-08-19T00:00:00+00:00"}-- decision = decide_promotion(candidate, champion, now=NOW, min_days_between=3)-- assert not decision.promote- assert decision.gates_passed is expected_gates_passed- 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+ assert decide_promotion(candidate, champion).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_grades={"open": _grade(auc=0.75, positives=50)}- )+ paired = decide_promotion(candidate, champion, champion_grades={"open": _grade(auc=0.75, positives=50)})assert not paired.promote and "regressed" in paired.reason@@ -1707,8 +1682,6 @@ def test_decide_promotion_skips_heads_the_shared_holdout_cannot_read(decision = decide_promotion(candidate,champion,- now=NOW,- min_days_between=3,champion_grades={"open": _grade(auc=0.70, positives=60), "fixed": fixed_grade},min_holdout_positives={"open": 50, "fixed": 30},)@@ -1735,138 +1708,27 @@ def test_decide_promotion_refuses_a_worse_calibrated_candidate(candidate_ece, chchampion = {**_metadata("d1", open=0.66), "promoted_at": "2026-08-10T00:00:00+00:00"}grade = _grade(auc=0.66, ece=(champion_eces or {}).get("open"), positives=50)- decision = decide_promotion(candidate, champion, now=NOW, min_days_between=3, champion_grades={"open": grade})+ decision = decide_promotion(candidate, champion, champion_grades={"open": grade})assert decision.promote is expected_promoteassert expected_promote or "open calibration regressed" in decision.reason-_RECENT_CHAMPION = {**_metadata("d1", open=0.70), "promoted_at": "2026-08-19T00:00:00+00:00"}--- "gate,candidate,champion,grades,expected_reason",- [- ("min_days", _metadata("d2", open=0.70), _RECENT_CHAMPION, {}, "less than 3d ago"),- (- "ece",- {- "model_version": "d2",- "heads": [{**_head("open", 0.70, readable=True), "holdout_expected_calibration_error": 0.3}],- },- {**_metadata("d1", open=0.70), "promoted_at": "2026-08-10T00:00:00+00:00"},- {"open": _grade(auc=0.70, ece=0.05, positives=60)},- "open calibration regressed",- ),- (- "min_holdout_positives",- {- "model_version": "d2",- "heads": [- _head("open", 0.70, readable=True),- {**_head("fixed", 0.60, readable=False), "holdout_positives": 4},- ],- },- {**_metadata("d1", open=0.70, fixed=0.70), "promoted_at": "2026-08-10T00:00:00+00:00"},- {},- "fixed readable on champion but not on candidate",- ),- ],-)-def test_a_skipped_gate_waives_only_that_check(gate, candidate, champion, grades, expected_reason):- kwargs = {- "now": NOW,- "min_days_between": 3,- "champion_grades": grades,- "min_holdout_positives": {"open": 50, "fixed": 30},- }- refused = decide_promotion(candidate, champion, **kwargs)- assert not refused.promote and expected_reason in refused.reason-- assert decide_promotion(candidate, champion, **kwargs, skip_gates={gate}).promote- other_gates = {"min_days", "ece", "min_holdout_positives"} - {gate}- assert not decide_promotion(candidate, champion, **kwargs, skip_gates=other_gates).promote---def test_a_waived_holdout_floor_still_blocks_a_head_the_candidate_lost():- candidate = _metadata("d2", open=0.70)- champion = {**_metadata("d1", open=0.70, action=0.65), "promoted_at": "2026-08-10T00:00:00+00:00"}-- decision = decide_promotion(candidate, champion, now=NOW, min_days_between=3, skip_gates={"min_holdout_positives"})-- assert not decision.promote--_REFUSED = PromotionDecision(promote=False, reason="open regressed: 0.600 vs champion 0.700", gates_passed=False)-_PROMOTED = PromotionDecision(- promote=True, reason="candidate at or above champion on every readable head", gates_passed=True-)-_OLDER_CHAMPION = {**_metadata("2026-08-10", open=0.70), "promoted_at": "2026-08-10T00:00:00+00:00"}- "decision,candidate,override,expected",- [- (- _PROMOTED,- _metadata("2026-08-19", open=0.70),- PromotionOverride(),- PromotionOutcome(promote=True, override=None),- ),- (- _PROMOTED,- _metadata("2026-08-19", open=0.70),- PromotionOverride(freeze=True),- PromotionOutcome(promote=False, override="frozen"),- ),- (- _REFUSED,- _metadata("2026-08-19", open=0.60),- PromotionOverride(force=True),- PromotionOutcome(promote=True, override="forced"),- ),- # Force never moves the pointer backwards, or onto a model with nothing readable.- (- _REFUSED,- _metadata("2026-08-10", open=0.90),- PromotionOverride(force=True),- PromotionOutcome(promote=False, override=None),- ),- (- _REFUSED,- _metadata("2026-08-19", open=None),- PromotionOverride(force=True),- PromotionOutcome(promote=False, override=None),- ),- (- _REFUSED,- _metadata("2026-08-19", open=0.60),- PromotionOverride(skip_gates=frozenset({"ece"})),- PromotionOutcome(promote=False, override="skipped_gates"),- ),- ],- ids=["none", "freeze", "force", "force_not_newer", "force_unreadable", "skip_gates"],-)-def test_apply_promotion_override(decision, candidate, override, expected):- assert apply_promotion_override(decision, candidate, _OLDER_CHAMPION, override) == expected---def test_a_forced_promotion_records_the_reason_the_rule_refused_it():+def test_the_promotion_decided_event_never_reports_a_promotion():event = promotion_event(partition_key="2026-08-19",run_id="run-1",model_name=EMBEDDINGS_MODEL_NAME,- decision=_REFUSED,- outcome=PromotionOutcome(promote=True, override="forced"),- promoted=True,- champion_version="2026-08-19",+ decision=PromotionDecision(promote=True, reason="candidate at or above", gates_passed=True),incumbent_champion_version="2026-08-10",champion_aucs={},champion_eces={},)- assert {"would_promote": False, "promoted": True, "reason": _REFUSED.reason, "override": "forced"}.items() <= (- event.properties.items()- )+ assert {"would_promote": True, "gates_passed": True, "promoted": False}.items() <= event.properties.items()+ assert "override" not in event.propertiesclass _FakeS3:@@ -2457,35 +2319,52 @@ def test_a_manifest_entry_the_sweep_could_not_load_is_refused(overrides, message)-def _compose(families, served_family=EMBEDDINGS_MODEL_NAME):+def _compose(families, served):return compose_manifest(families,- served_family=served_family,+ served=served,prefix="inbox_ranking",now=datetime.datetime(2026, 8, 19, 6, tzinfo=datetime.UTC),)-def test_no_champion_for_the_served_family_publishes_nothing():- # Until the first promotion no family has a champion. Composing a manifest off the day's- # candidate instead would move the served model every day without a promotion.+def test_no_served_pointer_publishes_nothing():+ # Composing a manifest off a champion or the day's candidate instead would move the served+ # model without a person choosing it.decision = _compose([FamilyModels(name=EMBEDDINGS_MODEL_NAME,candidate=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-19"),- champion=None,+ champion=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15"),)- ]+ ],+ served=None,)assert decision.manifest is None- assert "no champion" in decision.reason+ assert "no served pointer" in decision.reason-def test_an_unregistered_served_family_publishes_nothing():- decision = _compose([], served_family="not_a_family")- assert decision.manifest is None- assert "not registered" in decision.reason+def test_the_served_pointer_wins_over_the_champion_of_its_own_family():+ # A rollback names an older version of a family whose champion.json still names a newer one.+ decision = _compose(+ [+ FamilyModels(+ name=EMBEDDINGS_MODEL_NAME,+ candidate=None,+ champion=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15"),+ ),+ FamilyModels(+ name=STATE_MODEL_NAME, candidate=None, champion=_serving_metadata(STATE_MODEL_NAME, "2026-08-10")+ ),+ ],+ served=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-01"),+ )+ assert decision.manifest is not None+ assert [(entry.key, entry.roles) for entry in decision.manifest.models] == [+ (model_key(EMBEDDINGS_MODEL_NAME, "2026-08-01"), [SERVED_ROLE]),+ (model_key(STATE_MODEL_NAME, "2026-08-10"), [CROSS_FAMILY_ROLE]),+ ]@pytest.mark.parametrize(@@ -2508,9 +2387,10 @@ def test_the_served_family_candidate_is_paired_only_when_it_is_a_second_model(FamilyModels(name=EMBEDDINGS_MODEL_NAME,candidate=_serving_metadata(EMBEDDINGS_MODEL_NAME, candidate_version, readable=candidate_readable),- champion=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15"),+ champion=None,)- ]+ ],+ served=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15"),)assert decision.manifest is not Noneassert {entry.roles[0]: entry.model_version for entry in decision.manifest.models} == expected_roles@@ -2533,7 +2413,8 @@ def test_a_family_with_no_readable_head_is_left_out():candidate=None,champion=_serving_metadata(NN_MODEL_NAME, "2026-08-12", readable=False),),- ]+ ],+ served=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15"),)assert decision.manifest is not Noneassert [entry.model_name for entry in decision.manifest.models] == [EMBEDDINGS_MODEL_NAME, STATE_MODEL_NAME]@@ -2555,7 +2436,7 @@ def test_the_cap_drops_cross_family_entries_before_the_paired_read():for index in range(5)),]- decision = _compose(families)+ decision = _compose(families, served=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15"))assert decision.manifest is not Noneassert [entry.roles[0] for entry in decision.manifest.models] == [SERVED_ROLE,@@ -2579,7 +2460,7 @@ def test_a_pinned_model_is_kept_and_capped_before_the_paired_read():decision = compose_manifest(families,- served_family=EMBEDDINGS_MODEL_NAME,+ served=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15"),prefix="inbox_ranking",now=datetime.datetime(2026, 8, 19, 6, tzinfo=datetime.UTC),pinned=pinned,@@ -2596,17 +2477,9 @@ def test_a_pinned_model_is_kept_and_capped_before_the_paired_read():def test_a_model_published_before_model_kind_existed_reads_as_xgboost():- # Every champion promoted so far was written without the field; reading it as missing would- # leave the model store with nothing to dispatch on.- decision = _compose(- [- FamilyModels(- name=EMBEDDINGS_MODEL_NAME,- candidate=None,- champion=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15"),- )- ]- )+ # The early models were written without the field; reading it as missing would leave the+ # model store with nothing to dispatch on.+ decision = _compose([], served=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15"))assert decision.manifest is not Noneassert decision.manifest.served.model_kind == DEFAULT_MODEL_KIND@@ -2631,10 +2504,25 @@ class _AppObjectStore:self.extras[key] = extras+_FEATURE_FIELDS: dict[str, Any] = {+ "feature_set": REPORT_EMBEDDINGS_FEATURE_SET.name,+ "feature_schema_version": REPORT_EMBEDDINGS_FEATURE_SET.schema_version,+ "feature_names": list(REPORT_EMBEDDINGS_FEATURE_SET.feature_names),+}+++def _served_pointer(model_name: str, version: str) -> bytes:+ return json.dumps(+ {"model_key": model_key(model_name, version), "model_name": model_name, "model_version": version}+ ).encode()++def _serving_dataset_s3(prefix: str, partition_key: str, model_kind: str = DEFAULT_MODEL_KIND, project_vector_kinds: tuple[str, ...] = ()):- """The dataset bucket holding one champion and one candidate of the served family."""+ """The dataset bucket holding the served model, the pointer that names it, and one candidate of+ the same family. The family's `champion.json` names the candidate, so a publish that read it+ instead of the pointer would serve the wrong version."""onnx = model_kind == ONNX_MODEL_KINDmodel_file = ONNX_MODEL_FILE if onnx else "open.ubj"@@ -2642,14 +2530,15 @@ def _serving_dataset_s3(kind: dict[str, Any] = {"model_kind": model_kind, "model_file": ONNX_MODEL_FILE} if onnx else {}if project_vector_kinds:kind["project_vector_kinds"] = list(project_vector_kinds)- return _serving_metadata(EMBEDDINGS_MODEL_NAME, version, heads=("open",), **kind)+ return _serving_metadata(EMBEDDINGS_MODEL_NAME, version, heads=("open",), **_FEATURE_FIELDS, **kind)objects: dict[str, bytes] = {}for version in ("2026-08-15", partition_key):folder = model_object_key(prefix, EMBEDDINGS_MODEL_NAME, version, "")objects[folder + METADATA_FILE] = json.dumps(metadata(version)).encode()objects[folder + model_file] = f"booster-{version}".encode()- objects[champion_object_key(prefix, EMBEDDINGS_MODEL_NAME)] = json.dumps(metadata("2026-08-15")).encode()+ objects[champion_object_key(prefix, EMBEDDINGS_MODEL_NAME)] = json.dumps(metadata(partition_key)).encode()+ objects[served_object_key(prefix)] = _served_pointer(EMBEDDINGS_MODEL_NAME, "2026-08-15")return _ModelStoreS3(objects)@@ -2663,7 +2552,6 @@ def _run_serving_manifest(partition_key = "2026-08-19"prefix = settings.INBOX_RANKING_DATASET_S3_PREFIXcapture = _patch_capture(monkeypatch, cloud=True, debug=False)- monkeypatch.setattr(settings, "INBOX_RANKING_SERVED_FAMILY", EMBEDDINGS_MODEL_NAME)monkeypatch.setattr("products.signals.dags.inbox_ranking.training.dag.MODEL_FAMILIES",(ModelFamily(name=EMBEDDINGS_MODEL_NAME, feature_set=REPORT_EMBEDDINGS_FEATURE_SET),),@@ -2795,23 +2683,27 @@ def test_a_version_already_in_the_store_is_not_copied_again(monkeypatch):assert len(manifest.models) == 2[email protected]("fail_on,source_present", [("open.ubj", True), (None, False)])-def test_a_failed_copy_leaves_the_previous_manifest_serving(monkeypatch, fail_on, source_present):[email protected]("source_present", [True, False])+def test_a_failed_copy_leaves_the_previous_manifest_serving(monkeypatch, source_present):# Writing the manifest before the copies finished would point the sweep at a model whose# booster never arrived, which fails every report rather than leaving yesterday's order.prefix = settings.INBOX_RANKING_DATASET_S3_PREFIXprevious = b'{"manifest_version": "2026-08-18T06:00:00+00:00"}'- store = _AppObjectStore({serving_manifest_key(prefix): previous}, fail_on=fail_on)- # Without the source objects the champion pointer still composes a manifest, and the copy then- # has nothing to read.- champion_only = {- champion_object_key(prefix, EMBEDDINGS_MODEL_NAME): json.dumps(- _serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15", heads=("open",))- ).encode()+ store = _AppObjectStore({serving_manifest_key(prefix): previous}, fail_on="open.ubj" if source_present else None)+ # Without its booster the served model fails the pin check, so nothing is composed or copied.+ pointer_only = {+ served_object_key(prefix): _served_pointer(EMBEDDINGS_MODEL_NAME, "2026-08-15"),+ model_object_key(prefix, EMBEDDINGS_MODEL_NAME, "2026-08-15", METADATA_FILE): json.dumps(+ _serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15", heads=("open",), **_FEATURE_FIELDS)+ ).encode(),}- with pytest.raises((dagster.Failure, RuntimeError)):- _run_serving_manifest(monkeypatch, store, dataset_objects=None if source_present else champion_only)+ if source_present:+ with pytest.raises(RuntimeError):+ _run_serving_manifest(monkeypatch, store)+ else:+ capture = _run_serving_manifest(monkeypatch, store, dataset_objects=pointer_only)+ assert "missing model files" in _manifest_event(capture)["reason"]assert store.objects[serving_manifest_key(prefix)] == previous@@ -2822,7 +2714,7 @@ def test_a_failed_copy_leaves_the_previous_manifest_serving(monkeypatch, fail_onassert store.objects[f"{entry.prefix}/open.ubj"] == f"booster-{entry.model_version}".encode()-def test_no_manifest_is_written_when_the_served_family_has_no_champion(monkeypatch):+def test_no_manifest_is_written_without_a_served_pointer(monkeypatch):prefix = settings.INBOX_RANKING_DATASET_S3_PREFIXfolder = model_object_key(prefix, EMBEDDINGS_MODEL_NAME, "2026-08-19", "")store = _AppObjectStore()@@ -2840,12 +2732,7 @@ def test_a_missing_pin_is_dropped_and_the_manifest_still_publishes(monkeypatch):prefix = settings.INBOX_RANKING_DATASET_S3_PREFIXclient = _serving_dataset_s3(prefix, "2026-08-19")pin_version = "2026-08-01"- pin_metadata = {- **_serving_metadata(EMBEDDINGS_MODEL_NAME, pin_version, heads=("open",)),- "feature_set": REPORT_EMBEDDINGS_FEATURE_SET.name,- "feature_schema_version": REPORT_EMBEDDINGS_FEATURE_SET.schema_version,- "feature_names": list(REPORT_EMBEDDINGS_FEATURE_SET.feature_names),- }+ pin_metadata = _serving_metadata(EMBEDDINGS_MODEL_NAME, pin_version, heads=("open",), **_FEATURE_FIELDS)# The metadata is there, but the booster is not, so a copy of this pin would fail the publish.client.objects[model_object_key(prefix, EMBEDDINGS_MODEL_NAME, pin_version, METADATA_FILE)] = json.dumps(pin_metadatadiff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pyindex 6106ccd1ffbf..fbf0262ec79b 100644--- a/products/signals/dags/inbox_ranking/training/dag.py+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -4,7 +4,7 @@ Three assets on the same daily partition as the dataset dag, each writing underinbox_ranking_training_examples/v1/<set>/dt=D/ examples over the trailing snapshots, per feature setinbox_ranking_models/v1/<name>/dt=D/<head>.ubj one booster per head + metadata.json (the candidate)- inbox_ranking_models/v1/<name>/champion.json pointer to the version the scoring sweep loads+ inbox_ranking_models/v1/served.json pointer to the model key the scoring sweep servesinbox_ranking_served_scores/v1/dt=D/ the scoring sweep's scores of the reports born that dayA fifth asset publishes what the scoring sweep serves. The dataset bucket holds the training@@ -15,20 +15,20 @@ which models a pass scores, and which of them the inbox would order on.Partition dt=D trains on the report-state/labels snapshots dt=D-lookback..D (issue 13'sscoring-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. Every candidate is kept under `models/v1/<model_name>/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. Every model object sits under its-family's `model_name`, and promotion stays inside a family: a richer family is a second candidate-graded on the same rows, not a competitor for another family's pointer.+reports, and refits on everything. The champion asset applies `promotion.decide_promotion` and+records the decision, so the daily candidate series doubles as monitoring. It never moves a+pointer: only `inbox_ranking_promote_job` (`training/promote.py`) writes `served.json`, and a+person runs it. Every candidate is kept under `models/v1/<model_name>/dt=D/`; a re-run of a+partition replaces that prefix in full (stale head files are removed). The incumbent is the served+model when it has the candidate's `model_name`, and it is graded on the candidate's holdout through+its `<head>.holdout.ubj` (the train-only fit), so the rule compares both models on one set of+reports. The `<name>/champion.json` objects that the retired automatic promotion wrote stay in+place, and the manifest still reads them for the cross-family role.Both the candidate and the champion asset walk `families_trained_in(MAIN_LOCATION)`, so each family trains on the-examples of the feature set it declares and decides against its own pointer. A family whose+examples of the feature set it declares and is graded against the served model of its own name. A family whoseexamples or metadata are missing that day is logged and skipped: its own series has a gap, and-every other family still trains, promotes and gets graded.+every other family still trains and gets graded.The `nn` family is trained by the `signals_ml` location (`nn/dag.py`) and never here.Two further assets grade the served models on data no example covers. `inbox_ranking_served_scores`@@ -65,7 +65,7 @@ from products.signals.backend.ranking.features import (FeatureSet,)from products.signals.backend.ranking.model_contract import model_feature_set, model_mismatch, trained_head_files-from products.signals.backend.ranking.overrides import RankingOverrides, read_ranking_overrides+from products.signals.backend.ranking.overrides import read_ranking_overridesfrom products.signals.backend.ranking.serving_manifest import (DEFAULT_MODEL_KIND,ServingManifest,@@ -76,6 +76,7 @@ from products.signals.dags.inbox_ranking.common import (DATASET_VERSION,PARQUET_PART_NAME,S3_BUCKET_ENV,+ RunContext,dataset_bucket,dataset_unconfigured,owner_tags,@@ -115,8 +116,8 @@ from products.signals.dags.inbox_ranking.training.heads import (HEADS_BY_HORIZON,HEADS_BY_NAME,)-from products.signals.dags.inbox_ranking.training.promotion import apply_promotion_override, decide_promotion-from products.signals.dags.inbox_ranking.training.serving import FamilyModels, compose_manifest+from products.signals.dags.inbox_ranking.training.promotion import decide_promotion+from products.signals.dags.inbox_ranking.training.serving import FamilyModels, ManifestDecision, compose_manifestfrom products.signals.dags.inbox_ranking.training.telemetry import (HeadExampleCounts,candidate_events,@@ -160,6 +161,7 @@ if TYPE_CHECKING:EXAMPLES_TABLE = "inbox_ranking_training_examples"MODELS_TABLE = "inbox_ranking_models"CHAMPION_FILE = "champion.json"+SERVED_FILE = "served.json"METADATA_FILE = "metadata.json"# Label columns the heads read (plus the provenance inputs); everything else stays on disk.@@ -213,6 +215,11 @@ def champion_object_key(prefix: str, model_name: str) -> str:return f"{prefix}/{MODELS_TABLE}/{DATASET_VERSION}/{model_name}/{CHAMPION_FILE}"+def served_object_key(prefix: str) -> str:+ """The one served pointer. It sits above the family folders because it can name any family."""+ return f"{prefix}/{MODELS_TABLE}/{DATASET_VERSION}/{SERVED_FILE}"++def _read_bytes_if_exists(client, bucket: str, key: str) -> bytes | None:try:return client.get_object(Bucket=bucket, Key=key)["Body"].read()@@ -246,6 +253,11 @@ def _put_json(client, bucket: str, key: str, payload: dict[str, Any]) -> None:)+def read_served_pointer(client, bucket: str, prefix: str) -> dict[str, Any] | None:+ """The `served.json` record, or None before the first promotion."""+ return _read_json_if_exists(client, bucket, served_object_key(prefix))++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)]@@ -721,11 +733,10 @@ def inbox_ranking_model_champion(context: dagster.AssetExecutionContext) -> Nonepartition_key = context.partition_keybucket, prefix, client = dataset_bucket(), settings.INBOX_RANKING_DATASET_S3_PREFIX, s3_client()- overrides = read_ranking_overrides(datetime.datetime.now(datetime.UTC))metadata: dict[str, dagster.MetadataValue] = {}decided = 0for family in families_trained_in(MAIN_LOCATION):- family_metadata = _decide_champion(context, client, bucket, prefix, partition_key, family, overrides)+ family_metadata = _decide_champion(context, client, bucket, prefix, partition_key, family)if family_metadata is None:continuedecided += 1@@ -744,10 +755,9 @@ def _decide_champion(prefix: str,partition_key: str,family: ModelFamily,- overrides: RankingOverrides,) -> dict[str, dagster.MetadataValue] | None:- """One per-head XGBoost family's promotion decision against its own pointer, or None when the- family has no candidate for the partition."""+ """One per-head XGBoost family's promotion decision against the served model of its name, or+ None when the family has no candidate for the partition."""def grade_champion(champion: Mapping[str, Any]) -> dict[str, HoldoutGrade]:champion_feature_set = model_feature_set(champion)@@ -778,8 +788,18 @@ def _decide_champion(holdout_days=settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS,)- return decide_family_champion(- context, client, bucket, prefix, partition_key, family, overrides, grade_champion=grade_champion+ return decide_family_champion(context, client, bucket, prefix, partition_key, family, grade_champion=grade_champion)+++def served_incumbent(client, bucket: str, prefix: str, model_name: str) -> dict[str, Any] | None:+ """The metadata of the served model when it has `model_name`, else None. A candidate is graded+ only against a model of its own name: two names read different features, so a paired grade+ across them means nothing."""+ pointer = read_served_pointer(client, bucket, prefix)+ if pointer is None or pointer.get("model_name") != model_name:+ return None+ return _read_json_if_exists(+ client, bucket, model_object_key(prefix, model_name, pointer["model_version"], METADATA_FILE))@@ -790,16 +810,15 @@ def decide_family_champion(prefix: str,partition_key: str,family: ModelFamily,- overrides: RankingOverrides,*,grade_champion: Callable[[Mapping[str, Any]], dict[str, HoldoutGrade]],) -> dict[str, dagster.MetadataValue] | None:- """One family's promotion decision against its own pointer, or None when the family has no- candidate for the partition.+ """One family's promotion decision against the served model of its name, or None when the+ family has no candidate for the partition. The decision is recorded and never written to a+ pointer.`grade_champion` grades the incumbent's train-only fit on the candidate's holdout, in the- family's own learner. Every family shares the rest, so one rule, one override and one- `INBOX_RANKING_AUTO_PROMOTE` gate decide every pointer.+ family's own learner. Every family shares the rest, so one rule decides every family."""candidate = _read_json_if_exists(client, bucket, model_object_key(prefix, family.name, partition_key, METADATA_FILE)@@ -807,8 +826,7 @@ def decide_family_champion(if candidate is None:context.log.warning(f"no {family.name} candidate metadata for dt={partition_key}; nothing to decide")return None- champion_key = champion_object_key(prefix, family.name)- champion = _read_json_if_exists(client, bucket, champion_key)+ champion = served_incumbent(client, bucket, prefix, family.name)champion_grades: dict[str, HoldoutGrade] = {}champion_aucs: dict[str, float] = {}champion_eces: dict[str, float] = {}@@ -822,45 +840,21 @@ def decide_family_champion(}if champion_grades:context.log.info(- f"{family.name} champion {champion['model_version']} on this holdout: "+ f"{family.name} served model {champion['model_version']} on this holdout: "f"AUC {champion_aucs}, ECE {champion_eces}")- promotion_override = overrides.promotion_for(family.name)decision = decide_promotion(candidate,champion,- now=datetime.datetime.now(datetime.UTC),- min_days_between=settings.INBOX_RANKING_PROMOTION_MIN_DAYS,champion_grades=champion_grades,min_holdout_positives={name: head.min_holdout_positives for name, head in HEADS_BY_NAME.items()},- skip_gates=promotion_override.skip_gates,)- outcome = apply_promotion_override(decision, candidate, champion, promotion_override)context.log.info(- f"{family.name} promotion decision for dt={partition_key}: promote={decision.promote} ({decision.reason}), "- f"override={outcome.override}, outcome promote={outcome.promote}"+ f"{family.name} promotion decision for dt={partition_key}: would promote={decision.promote} "+ f"({decision.reason}); run inbox_ranking_promote_job to serve it")- promoted = False- if outcome.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, family.name, partition_key, METADATA_FILE),- },- )- promoted = True- elif outcome.promote:- context.log.info(f"INBOX_RANKING_AUTO_PROMOTE is off; the {family.name} candidate would have been promoted")-- # The paired AUCs belong to the incumbent: after a promotion `champion_version` names the- # candidate, so the incumbent is recorded alongside to keep the scores attributable.incumbent_champion_version = (champion or {}).get("model_version", "none")- champion_version = partition_key if promoted else incumbent_champion_versioncapture_training_events(context,partition_key,@@ -870,22 +864,16 @@ def decide_family_champion(run_id=context.run_id,model_name=family.name,decision=decision,- outcome=outcome,- promoted=promoted,- champion_version=champion_version,incumbent_champion_version=incumbent_champion_version,champion_aucs=champion_aucs,champion_eces=champion_eces,- skipped_gates=promotion_override.skip_gates,)],)return {f"{family.name}_would_promote": dagster.MetadataValue.bool(decision.promote),f"{family.name}_gates_passed": dagster.MetadataValue.bool(decision.gates_passed),- f"{family.name}_promoted": dagster.MetadataValue.bool(promoted),f"{family.name}_reason": dagster.MetadataValue.text(decision.reason),- f"{family.name}_override": dagster.MetadataValue.text(outcome.override or "none"),f"{family.name}_skipped_heads": dagster.MetadataValue.json(list(decision.skipped_heads)),**{f"{family.name}_champion_{head}_auc_on_this_holdout": dagster.MetadataValue.float(auc)@@ -896,7 +884,6 @@ def decide_family_champion(for head, ece in champion_eces.items()},f"{family.name}_incumbent_champion_version": dagster.MetadataValue.text(incumbent_champion_version),- f"{family.name}_champion_version": dagster.MetadataValue.text(champion_version),}@@ -938,11 +925,10 @@ def inbox_ranking_serving_manifest(context: dagster.AssetExecutionContext) -> Nocontext.add_output_metadata(_publish_manifest(context, context.partition_key, context.run.run_id))-def _publish_manifest(- context: dagster.AssetExecutionContext, partition_key: str, run_id: str-) -> dict[str, dagster.MetadataValue]:+def _publish_manifest(context: RunContext, partition_key: str, run_id: str) -> dict[str, dagster.MetadataValue]:bucket, prefix, client = dataset_bucket(), settings.INBOX_RANKING_DATASET_S3_PREFIX, s3_client()- served_family = settings.INBOX_RANKING_SERVED_FAMILY+ served, served_reason = _served_model(client, bucket, prefix)+ served_family = served["model_name"] if served is not None else "none"overrides = read_ranking_overrides(datetime.datetime.now(datetime.UTC))pinned, dropped_pins = _pinned_models(client, bucket, prefix, overrides.pin)for key, reason in dropped_pins.items():@@ -958,8 +944,10 @@ def _publish_manifest()for family in MODEL_FAMILIES]- decision = compose_manifest(- families, served_family=served_family, prefix=prefix, now=datetime.datetime.now(datetime.UTC), pinned=pinned+ decision = (+ compose_manifest(families, served=served, prefix=prefix, now=datetime.datetime.now(datetime.UTC), pinned=pinned)+ if served_reason is None+ else ManifestDecision(manifest=None, reason=served_reason))manifest_keys = {entry.key for entry in decision.manifest.models} if decision.manifest else set()if decision.manifest is not None:@@ -1046,6 +1034,25 @@ def _object_exists(client, bucket: str, key: str) -> bool:return True+def _served_model(client, bucket: str, prefix: str) -> tuple[dict[str, Any] | None, str | None]:+ """The metadata of the model `served.json` names, or None and the reason nothing is published.++ The served model passes the same check as a pin. A pointer to a model that cannot be served+ publishes nothing, so the previous manifest keeps serving.+ """+ pointer = read_served_pointer(client, bucket, prefix)+ if pointer is None:+ return None, f"no {SERVED_FILE}; run inbox_ranking_promote_job to choose the served model"+ key = str(pointer.get("model_key"))+ try:+ metadata, reason = _pin_metadata(client, bucket, prefix, key)+ except (ClientError, ValueError) as error:+ metadata, reason = None, f"could not read the model: {error!r}"+ if metadata is None:+ return None, f"served model {key} cannot be served: {reason}"+ return metadata, None++def _pinned_models(client, bucket: str, prefix: str, keys: Sequence[str]) -> tuple[list[dict[str, Any]], dict[str, str]]:@@ -1092,9 +1099,7 @@ def _pin_metadata(client, bucket: str, prefix: str, key: str) -> tuple[dict[str,return metadata, None-def _publish_mirror(- context: dagster.AssetExecutionContext, client, bucket: str, prefix: str, manifest: ServingManifest-) -> bool | None:+def _publish_mirror(context: RunContext, client, bucket: str, prefix: str, manifest: ServingManifest) -> bool | None:"""Copy the same publish into the mirror store, if one is set. Returns None when no mirror isset, otherwise whether the mirror now serves this manifest.@@ -1136,7 +1141,7 @@ class _ModelPublication:def publish_serving_models(- context: dagster.AssetExecutionContext,+ context: RunContext,client,bucket: str,prefix: str,@@ -1182,7 +1187,7 @@ def publish_serving_models(def _publish_project_vectors(- context: dagster.AssetExecutionContext,+ context: RunContext,client,bucket: str,source: str | None,diff --git a/products/signals/dags/inbox_ranking/training/promote.py b/products/signals/dags/inbox_ranking/training/promote.pynew file mode 100644index 000000000000..66537e767877--- /dev/null+++ b/products/signals/dags/inbox_ranking/training/promote.py@@ -0,0 +1,149 @@+"""Manual promotion: a person chooses the model key the scoring sweep serves.++`inbox_ranking_promote_job` writes `inbox_ranking_models/v1/served.json`, then publishes the serving+manifest for the newest dataset partition, so the change reaches the sweep without waiting for the+daily training run. Rollback is the same job with an older key, of any `model_name`: a person's+choice has no "newer than the incumbent" rule.++The job checks the model before it writes anything. A malformed key, a model that this build cannot+serve, a missing model file, or a model without every head in `HEADS` fails the run, and the+pointer and the manifest stay as they are.+"""++import datetime+from collections.abc import Mapping+from typing import Any++import dagster+import pydantic+from botocore.exceptions import ClientError++from posthog import settings++from products.signals.backend.ranking.model_contract import trained_head_files+from products.signals.backend.ranking.overrides import MODEL_KEY_PATTERN+from products.signals.dags.inbox_ranking.common import (+ S3_BUCKET_ENV,+ dataset_bucket,+ dataset_unconfigured,+ owner_tags,+ partition_object_key,+ s3_client,+)+from products.signals.dags.inbox_ranking.dataset.dag import PROJECT_VECTORS_TABLE+from products.signals.dags.inbox_ranking.training.dag import (+ _object_exists,+ _pin_metadata,+ _publish_manifest,+ _put_json,+ read_served_pointer,+ served_object_key,+)+from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME+from products.signals.dags.inbox_ranking.training.telemetry import capture_training_events, model_promoted_event++# The dataset job writes a day's partitions the next morning, so the newest one is at least a day+# old. A gap longer than this means the dataset job is broken, and the publish waits for it.+MAX_PARTITION_AGE_DAYS = 7+++class PromotionRefused(ValueError):+ pass+++class PromoteConfig(dagster.Config):+ model_key: str = pydantic.Field(description="The model key to serve, as `<model_name>@<YYYY-MM-DD>`.")+ reason: str = pydantic.Field(description="Why this model is served. Recorded in `served.json` and the event.")+++def promotable_model(client, bucket: str, prefix: str, model_key: str) -> dict[str, Any]:+ """The metadata of the model `model_key` names. Raises `PromotionRefused` when the sweep could+ not serve it with every head the inbox reads."""+ if not MODEL_KEY_PATTERN.match(model_key):+ raise PromotionRefused(f"{model_key!r} is not a `<model_name>@<YYYY-MM-DD>` model key")+ try:+ metadata, reason = _pin_metadata(client, bucket, prefix, model_key)+ except ClientError as error:+ raise PromotionRefused(f"could not read {model_key}: {error!r}") from error+ if metadata is None:+ raise PromotionRefused(f"{model_key} cannot be served: {reason}")+ missing_heads = sorted(set(HEADS_BY_NAME) - set(trained_head_files(metadata, HEADS_BY_NAME)))+ if missing_heads:+ raise PromotionRefused(f"{model_key} has no model for the heads {', '.join(missing_heads)}")+ return metadata+++def newest_partition(client, bucket: str, prefix: str, today: datetime.date) -> str:+ """The newest day whose project vectors exist. A served `nn` model reads that day, so the+ publish needs it, as the daily manifest does."""+ for offset in range(1, MAX_PARTITION_AGE_DAYS + 1):+ day = (today - datetime.timedelta(days=offset)).isoformat()+ if _object_exists(client, bucket, partition_object_key(prefix, PROJECT_VECTORS_TABLE, day)):+ return day+ raise PromotionRefused(f"no {PROJECT_VECTORS_TABLE} partition in the last {MAX_PARTITION_AGE_DAYS} days")+++def served_pointer(+ metadata: Mapping[str, Any],+ *,+ reason: str,+ previous: Mapping[str, Any] | None,+ run_id: str,+ promoted_at: datetime.datetime,+) -> dict[str, Any]:+ return {+ "model_key": f"{metadata['model_name']}@{metadata['model_version']}",+ "model_name": metadata["model_name"],+ "model_version": metadata["model_version"],+ "promoted_at": promoted_at.isoformat(),+ "reason": reason,+ "previous_key": (previous or {}).get("model_key"),+ "run_id": run_id,+ }++[email protected](tags=owner_tags)+def inbox_ranking_promote(context: dagster.OpExecutionContext, config: PromoteConfig) -> None:+ if dataset_unconfigured():+ raise dagster.Failure(f"{S3_BUCKET_ENV} is not set on this Cloud deployment; nothing to promote")+ reason = config.reason.strip()+ if not reason:+ raise dagster.Failure("reason is empty; say why this model is served")+ bucket, prefix, client = dataset_bucket(), settings.INBOX_RANKING_DATASET_S3_PREFIX, s3_client()+ now = datetime.datetime.now(datetime.UTC)+ try:+ metadata = promotable_model(client, bucket, prefix, config.model_key)+ partition_key = newest_partition(client, bucket, prefix, now.date())+ except PromotionRefused as error:+ raise dagster.Failure(f"not promoted: {error}") from error++ previous = read_served_pointer(client, bucket, prefix)+ pointer = served_pointer(metadata, reason=reason, previous=previous, run_id=context.run_id, promoted_at=now)+ _put_json(client, bucket, served_object_key(prefix), pointer)+ context.log.info(f"served.json now names {pointer['model_key']} (was {pointer['previous_key']})")+ capture_training_events(+ context,+ partition_key,+ [+ model_promoted_event(+ model_key=pointer["model_key"],+ previous_key=pointer["previous_key"],+ reason=reason,+ run_id=context.run_id,+ )+ ],+ timestamp=now,+ )++ published = _publish_manifest(context, partition_key, context.run_id)+ if not published["published"].value:+ raise dagster.Failure(+ f"served.json names {pointer['model_key']}, but no manifest was published for dt={partition_key}; "+ "the previous manifest keeps serving until the next training run publishes one"+ )+ context.log.info(f"published the serving manifest for dt={partition_key}: {published['served_key'].value}")++[email protected](name="inbox_ranking_promote_job", tags=owner_tags)+def inbox_ranking_promote_job() -> None:+ inbox_ranking_promote()diff --git a/products/signals/dags/inbox_ranking/training/promotion.py b/products/signals/dags/inbox_ranking/training/promotion.pyindex ddcf986dabd8..a7418c39a134 100644--- a/products/signals/dags/inbox_ranking/training/promotion.py+++ b/products/signals/dags/inbox_ranking/training/promotion.py@@ -1,10 +1,10 @@-"""Champion promotion rule.+"""Candidate grading 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.-The quality gates run before the wait, so `gates_passed` says whether the candidate is good enough-even on a day the wait blocks it. Pure function over the two metadata records so the rule is-testable without S3.+The rule says whether a candidate would replace the incumbent: it is at least as good on every head+the incumbent could read, and it has at least one readable head itself. The incumbent is the served+model when it has the candidate's `model_name`. The rule never moves the served pointer: a person+does that with `inbox_ranking_promote_job`, and reads this decision to choose. Pure function over+the two metadata records so the rule is testable without S3.`champion_grades` holds the champion's holdout booster graded on the candidate's holdout, so bothmodels are compared on one set of reports; the stored AUCs are the fallback for a head without one.@@ -19,19 +19,13 @@ A paired grade also says how many positives the shared holdout holds. Below theregression. A head the candidate did not train still blocks: a candidate must not replace a championby losing a head the champion serves. A champion head that is no longer in `HEADS` is not compared:it was retired, so no candidate trains it.--An owner can change one family's outcome through the `promotion` override (see-`products/signals/backend/ranking/overrides.py`). `skip_gates` waives named checks inside the rule,-and `apply_promotion_override` applies `freeze` and `force` to the rule's decision."""-import datetime-from collections.abc import Collection, Mapping+from collections.abc import Mappingfrom typing import Anyfrom posthog.dataclasses import frozen-from products.signals.backend.ranking.overrides import PromotionOverridefrom products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAMEfrom products.signals.dags.inbox_ranking.training.train import HoldoutGrade@@ -48,19 +42,12 @@ ECE_TOLERANCE = 0.02class PromotionDecision:promote: boolreason: str- # True when the candidate passed every quality gate, whether or not the wait blocked it.+ # True when the candidate passed every quality gate.gates_passed: bool# Champion-readable heads whose shared holdout had too few positives to compare.skipped_heads: tuple[str, ...] = ()-@frozen-class PromotionOutcome:- promote: bool- # "frozen", "forced" or "skipped_gates" when an override applied, else None.- override: str | None--def _readable_aucs(metadata: Mapping[str, Any]) -> dict[str, float]:return {head["head"]: float(head["holdout_auc"])@@ -73,19 +60,15 @@ def decide_promotion(candidate: Mapping[str, Any],champion: Mapping[str, Any] | None,*,- now: datetime.datetime,- min_days_between: int,champion_grades: Mapping[str, HoldoutGrade] | None = None,min_holdout_positives: Mapping[str, int] | None = None,- skip_gates: Collection[str] = (),) -> PromotionDecision:- """`skip_gates` waives `min_days` (the wait since the last promotion), `ece` (the calibration- check) and `min_holdout_positives` (a head whose candidate holdout has fewer positives than its- minimum is skipped rather than blocking)."""if not _readable_aucs(candidate):return PromotionDecision(promote=False, reason="candidate has no readable head", gates_passed=False)if champion is None:- return PromotionDecision(promote=True, reason="no champion yet", gates_passed=True)+ return PromotionDecision(+ promote=True, reason="no served model of this model_name to compare against", gates_passed=True+ )# 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@@ -97,20 +80,7 @@ def decide_promotion(gates_passed=False,)- decision = _compare_to_champion(candidate, champion, champion_grades or {}, min_holdout_positives or {}, skip_gates)- promoted_at = datetime.datetime.fromisoformat(champion["promoted_at"])- if (- decision.promote- and "min_days" not in skip_gates- and now - promoted_at < datetime.timedelta(days=min_days_between)- ):- return PromotionDecision(- promote=False,- reason=f"candidate passed every gate but champion {champion['model_version']} promoted less than {min_days_between}d ago",- gates_passed=True,- skipped_heads=decision.skipped_heads,- )- return decision+ return _compare_to_champion(candidate, champion, champion_grades or {}, min_holdout_positives or {})def _compare_to_champion(@@ -118,7 +88,6 @@ def _compare_to_champion(champion: Mapping[str, Any],champion_grades: Mapping[str, HoldoutGrade],min_holdout_positives: Mapping[str, int],- skip_gates: Collection[str],) -> PromotionDecision:candidate_aucs = _readable_aucs(candidate)candidate_heads = {head["head"]: head for head in candidate.get("heads", [])}@@ -126,14 +95,6 @@ def _compare_to_champion(for head, stored_auc in _readable_aucs(champion).items():if head not in HEADS_BY_NAME:continue- candidate_positives = candidate_heads.get(head, {}).get("holdout_positives")- if (- "min_holdout_positives" in skip_gates- and candidate_positives is not None- and candidate_positives < min_holdout_positives.get(head, 0)- ):- skipped.append(head)- continuegrade = champion_grades.get(head)if grade is None:# No shared holdout: readability was read on two different holdouts, so compare it as stored.@@ -166,12 +127,7 @@ def _compare_to_champion(champion_ece = grade.expected_calibration_error if grade is not None else Noneraw_ece = candidate_heads.get(head, {}).get("holdout_expected_calibration_error")candidate_ece = float(raw_ece) if raw_ece is not None else None- if (- "ece" not in skip_gates- and champion_ece is not None- and candidate_ece is not None- and candidate_ece > champion_ece + ECE_TOLERANCE- ):+ if champion_ece is not None and candidate_ece is not None and candidate_ece > champion_ece + ECE_TOLERANCE:return PromotionDecision(promote=False,reason=f"{head} calibration regressed: ECE {candidate_ece:.3f} vs champion {champion_ece:.3f}",@@ -187,26 +143,3 @@ def _compare_to_champion(return PromotionDecision(promote=True, reason="candidate at or above champion on every readable head", gates_passed=True)---def apply_promotion_override(- decision: PromotionDecision,- candidate: Mapping[str, Any],- champion: Mapping[str, Any] | None,- override: PromotionOverride,-) -> PromotionOutcome:- """The rule's decision with `freeze` or `force` applied.-- `force` still needs a readable head on a candidate newer than the champion, so it can never- move the pointer backwards or onto a model with nothing to read.- """- if override.freeze:- return PromotionOutcome(promote=False, override="frozen")- if (- override.force- and not decision.promote- and _readable_aucs(candidate)- and (champion is None or candidate["model_version"] > champion["model_version"])- ):- return PromotionOutcome(promote=True, override="forced")- return PromotionOutcome(promote=decision.promote, override="skipped_gates" if override.skip_gates else None)diff --git a/products/signals/dags/inbox_ranking/training/served.py b/products/signals/dags/inbox_ranking/training/served.pyindex 768db63cef11..672170d45f15 100644--- a/products/signals/dags/inbox_ranking/training/served.py+++ b/products/signals/dags/inbox_ranking/training/served.py@@ -1,13 +1,13 @@"""The scoring sweep's own birth-day scores, graded per model key.-The sweep scores each report with every model the serving manifest names: the served champion, the-served family's daily candidate, and the other families' champions. This module reads the sweep's+The sweep scores each report with every model the serving manifest names: the served model, the+daily candidate of its `model_name`, and the other families' champions. This module reads the sweep's`inbox_ranking_report_scored` events for D's newborn pool and writes them in `SCORES_SCHEMA`, so`inbox_ranking_unseen_graded` grades every model key on live scores through one path.Caveats:-- The daily promotion can change the served model part of the way through D, so one day's cohort+- A manual promotion can change the served model part of the way through D, so one day's cohortcan split across two versions, and one key can carry two roles. Grades stay per`(model_name, model_version, model_role)` and are never pooled across versions.- The sweep scores a candidate only after a manifest names it, so a candidate's cohort starts thediff --git a/products/signals/dags/inbox_ranking/training/serving.py b/products/signals/dags/inbox_ranking/training/serving.pyindex d83d5fda8d71..d3d30218ae51 100644--- a/products/signals/dags/inbox_ranking/training/serving.py+++ b/products/signals/dags/inbox_ranking/training/serving.py@@ -4,8 +4,8 @@ The training dag is the only place that knows every family's candidate and champpicks the set the scoring sweep runs. This module is that choice as pure functions over the`metadata.json` records; `training/dag.py` owns the S3 reads, the publishing and the telemetry.-The served entry is the champion of one family, so the served model only ever changes through a-promotion. The other entries are there so one pass produces several scores: an online paired read+The served entry is the model the `served.json` pointer names, so the served model changes only+when a person runs `inbox_ranking_promote_job`. The other entries are there so one pass produces several scores: an online paired readand a later interleaving then need no rescoring of the same reports. A pinned entry is there so anowner's `served` override can name it."""@@ -37,9 +37,10 @@ from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME@frozenclass FamilyModels:- """One family's two records for the partition: the candidate fit that day, and the pointer the- sweep would serve. Either can be absent — a family can be registered before its first candidate,- and no family has a champion until the first promotion."""+ """One family's two records for the partition: the candidate fit that day, and the family's+ `champion.json`. Either can be absent. Nothing writes `champion.json` anymore, so a champion is+ the last version the retired automatic promotion chose, and it serves only as a cross-family+ read."""name: strcandidate: Mapping[str, Any] | None@@ -88,39 +89,42 @@ def _entry(def compose_manifest(families: Sequence[FamilyModels],*,- served_family: str,+ served: Mapping[str, Any] | None,prefix: str,now: datetime.datetime,pinned: Sequence[Mapping[str, Any]] = (),) -> ManifestDecision:- """`pinned` holds the metadata of the models the `pin` override keeps. The caller checks that- their files exist, because a manifest that names a missing file is never published."""- by_name = {family.name: family for family in families}- served_models = by_name.get(served_family)- if served_models is None:- return ManifestDecision(manifest=None, reason=f"served family {served_family} is not registered")- if served_models.champion is None:- return ManifestDecision(manifest=None, reason=f"served family {served_family} has no champion yet")- served = _entry(- served_models.champion,+ """`served` holds the metadata of the model the `served.json` pointer names, and `pinned` the+ metadata of the models the `pin` override keeps. The caller checks that their files exist,+ because a manifest that names a missing file is never published."""+ if served is None:+ return ManifestDecision(manifest=None, reason="no served pointer")+ served_family = served["model_name"]+ served_entry = _entry(+ served,roles=[SERVED_ROLE],- labels={"reason": f"champion of the served family {served_family}"},+ labels={"reason": "named by the served pointer"},prefix=prefix,)- if served is None:+ if served_entry is None:return ManifestDecision(- manifest=None, reason=f"served family {served_family} champion has no head booster to load"+ manifest=None, reason=f"served model {served_family}@{served['model_version']} has no head to load")- entries = [served]- candidate = served_models.candidate+ entries = [served_entry]+ served_models = next((family for family in families if family.name == served_family), None)+ candidate = served_models.candidate if served_models is not None else None# A candidate at the champion's own version is the champion, so scoring it twice would only# spend the artefact's result budget on a duplicate.- if candidate is not None and candidate["model_version"] != served.model_version and readable_head_names(candidate):+ if (+ candidate is not None+ and candidate["model_version"] != served_entry.model_version+ and readable_head_names(candidate)+ ):daily = _entry(candidate,roles=[DAILY_CANDIDATE_ROLE],- labels={"reason": f"today's {served_family} candidate, paired against the served champion"},+ labels={"reason": f"today's {served_family} candidate, paired against the served model"},prefix=prefix,)if daily is not None:diff --git a/products/signals/dags/inbox_ranking/training/telemetry.py b/products/signals/dags/inbox_ranking/training/telemetry.pyindex c76377534845..e8590b91168f 100644--- a/products/signals/dags/inbox_ranking/training/telemetry.py+++ b/products/signals/dags/inbox_ranking/training/telemetry.py@@ -9,20 +9,18 @@ fails an asset."""import datetime-from collections.abc import Collection, Mapping, Sequence+from collections.abc import Mapping, Sequencefrom typing import Any-import dagster-from posthog import settingsfrom posthog.cloud_utils import is_cloudfrom posthog.dataclasses import frozenfrom posthog.ph_client import get_clientfrom products.signals.backend.ranking.serving_manifest import ServingManifest-from products.signals.dags.inbox_ranking.common import snapshot_bounds+from products.signals.dags.inbox_ranking.common import RunContext, snapshot_boundsfrom products.signals.dags.inbox_ranking.training.examples import ConsentExclusion-from products.signals.dags.inbox_ranking.training.promotion import PromotionDecision, PromotionOutcome+from products.signals.dags.inbox_ranking.training.promotion import PromotionDecisionfrom products.signals.dags.inbox_ranking.training.unseen import CANDIDATE_ROLE, HeadGrade# Not a person: one fixed id for the whole dag, and no person profile is created for it. Local dev@@ -33,6 +31,7 @@ LOCAL_ENVIRONMENT = "local"CANDIDATE_TRAINED_EVENT = "inbox_ranking_candidate_trained"EXAMPLES_BUILT_EVENT = "inbox_ranking_examples_built"PROMOTION_DECIDED_EVENT = "inbox_ranking_promotion_decided"+MODEL_PROMOTED_EVENT = "inbox_ranking_model_promoted"UNSEEN_HEAD_GRADED_EVENT = "inbox_ranking_unseen_head_graded"UNSEEN_HEAD_EVALUATED_EVENT = "inbox_ranking_unseen_head_evaluated"UNSEEN_REPORT_GRADED_EVENT = "inbox_ranking_unseen_report_graded"@@ -149,19 +148,15 @@ def promotion_event(run_id: str,model_name: str,decision: PromotionDecision,- outcome: PromotionOutcome,- promoted: bool,- champion_version: str,incumbent_champion_version: str,champion_aucs: Mapping[str, float],champion_eces: Mapping[str, float],- skipped_gates: Collection[str] = (),) -> TrainingEvent:- """`champion_aucs` and `champion_eces` were scored by the incumbent on this candidate's holdout; after a promotion- `champion_version` is the candidate, so the incumbent is carried separately. Every version here- belongs to `model_name`: promotion compares a candidate to the champion of its own family.+ """`champion_aucs` and `champion_eces` were scored by the incumbent on this candidate's holdout.+ The incumbent is the served model when it has `model_name`, else `none`.- `reason` is always the rule's reason, so a forced promotion still records why the rule refused it."""+ Training never moves the served pointer, so `promoted` is always false. A person promotes+ through `inbox_ranking_promote_job`, which captures `MODEL_PROMOTED_EVENT`."""return TrainingEvent(event=PROMOTION_DECIDED_EVENT,properties={@@ -170,12 +165,10 @@ def promotion_event("run_id": run_id,"would_promote": decision.promote,"gates_passed": decision.gates_passed,- "promoted": promoted,+ "promoted": False,"reason": decision.reason,- "override": outcome.override,- "override_skipped_gates": sorted(skipped_gates),"skipped_heads": list(decision.skipped_heads),- "champion_version": champion_version,+ "champion_version": incumbent_champion_version,"incumbent_champion_version": incumbent_champion_version,**{f"champion_{head}_auc_on_this_holdout": auc for head, auc in champion_aucs.items()},**{f"champion_{head}_ece_on_this_holdout": ece for head, ece in champion_eces.items()},@@ -183,6 +176,13 @@ def promotion_event()+def model_promoted_event(*, model_key: str, previous_key: str | None, reason: str, run_id: str) -> TrainingEvent:+ return TrainingEvent(+ event=MODEL_PROMOTED_EVENT,+ properties={"model_key": model_key, "previous_key": previous_key, "reason": reason, "run_id": run_id},+ )++def serving_manifest_event(*,partition_key: str,@@ -311,16 +311,21 @@ def capture_allowed() -> bool:def capture_training_events(- context: dagster.AssetExecutionContext, partition_key: str, events: list[TrainingEvent]+ context: RunContext,+ partition_key: str,+ events: list[TrainingEvent],+ *,+ timestamp: datetime.datetime | None = None,) -> None:"""Best-effort: a failed capture is logged, never raised, so telemetry cannot fail a trainingrun. Local runs are marked twice, by `environment` and by their own distinct id, so a chart- that forgets to filter still shows them as a separate series."""+ that forgets to filter still shows them as a separate series. `timestamp` defaults to the+ partition's midday; an event about a person's action passes the moment it happened."""if not capture_allowed():returnenvironment = settings.CLOUD_DEPLOYMENT or LOCAL_ENVIRONMENTdistinct_id = DISTINCT_ID if environment != LOCAL_ENVIRONMENT else LOCAL_DISTINCT_ID- timestamp = event_timestamp(partition_key)+ timestamp = timestamp or event_timestamp(partition_key)base = {"$process_person_profile": False, "partition": partition_key, "environment": environment}# A fresh client per call, flushed on shutdown, for the same reason `ph_scoped_capture` builds# one: the step process exits right after the asset, before a shared client's background