: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): publish the inbox ranking serving manifest (#106460)
posthog[bot]c2703de1e5d8
diff --git a/posthog/dags/locations/signals.py b/posthog/dags/locations/signals.pyindex d64d1b660043..685c1a27d0db 100644--- a/posthog/dags/locations/signals.py+++ b/posthog/dags/locations/signals.py@@ -21,6 +21,7 @@ if is_inbox_ranking_registered():inbox_ranking_training.inbox_ranking_training_examples,inbox_ranking_training.inbox_ranking_model_candidate,inbox_ranking_training.inbox_ranking_model_champion,+ inbox_ranking_training.inbox_ranking_serving_manifest,inbox_ranking_training.inbox_ranking_unseen_scores,inbox_ranking_training.inbox_ranking_unseen_graded,inbox_ranking_shadow.inbox_ranking_shadow_eval,diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.pyindex c77078287bd5..4f085f794712 100644--- a/posthog/settings/object_storage.py+++ b/posthog/settings/object_storage.py@@ -107,6 +107,9 @@ INBOX_RANKING_TRAINING_LOOKBACK_DAYS = get_from_env("INBOX_RANKING_TRAINING_LOOKINBOX_RANKING_TRAINING_HOLDOUT_DAYS = get_from_env("INBOX_RANKING_TRAINING_HOLDOUT_DAYS", 7, type_cast=int)INBOX_RANKING_AUTO_PROMOTE = get_from_env("INBOX_RANKING_AUTO_PROMOTE", False, type_cast=str_to_bool)INBOX_RANKING_PROMOTION_MIN_DAYS = get_from_env("INBOX_RANKING_PROMOTION_MIN_DAYS", 3, type_cast=int)+# 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.+INBOX_RANKING_SERVED_FAMILY = os.getenv("INBOX_RANKING_SERVED_FAMILY", "report_embeddings")# Shadow dag (products/signals/dags/inbox_ranking/shadow): how many daily scores partitions back# the read looks for a score that already existed when a list was served. A report is scored on# the day it is born, so this bounds how old a report can be and still be graded.diff --git a/products/signals/backend/ranking/serving_manifest.py b/products/signals/backend/ranking/serving_manifest.pynew file mode 100644index 000000000000..d93fcf2f62b0--- /dev/null+++ b/products/signals/backend/ranking/serving_manifest.py@@ -0,0 +1,118 @@+"""The serving manifest: which ranking models the scoring sweep runs, and which one is served.++The training dag decides the set. It knows every candidate's version, the heads each candidate+could fit, and each family's champion, so the choice belongs there rather than in the sweep. The+dag writes the decision as one small JSON object in the deployment's own object store, next to the+model files it also publishes, and the sweep reads both from there. The dataset bucket the training+dag writes its history to stays out of the serving path.++This module is the contract between the two. The schema, the role vocabulary and the object keys+live here, in the backend package that already holds the feature contract, so the writer and the+reader cannot disagree about them. The validators run at write time, so a manifest the sweep could+not act on is refused by the dag that composed it.+"""++from __future__ import annotations++from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator++from products.signals.backend.artefact_schemas import MAX_RANKING_MODEL_RESULTS, RANKING_SERVED_ROLE++# The one role a reader acts on, taken from the artefact schema so the manifest and the+# `ranking_score` rows it produces name the served model the same way.+SERVED_ROLE = RANKING_SERVED_ROLE+# The served family's model for the partition being trained, carried so a paired read compares the+# champion against the day's fit without a second scoring pass.+DAILY_CANDIDATE_ROLE = "daily_candidate"+# Another family's champion, scored alongside so a later interleaving needs no rescoring.+CROSS_FAMILY_ROLE = "cross_family"++# The learner a model store loads the booster with. Every family is per-head XGBoost today, and a+# model published before the field existed is one of those, so this is also the read fallback.+DEFAULT_MODEL_KIND = "xgboost"++MANIFEST_FILE = "manifest.json"+METADATA_FILE = "metadata.json"++_SERVING_SEGMENT = "serving"+++def serving_manifest_key(prefix: str) -> str:+ return f"{prefix}/{_SERVING_SEGMENT}/{MANIFEST_FILE}"+++def serving_model_prefix(prefix: str, key: str) -> str:+ """Where one model's `metadata.json` and head boosters sit. Keyed by `<name>@<version>`, so a+ version is published once however many manifests name it."""+ return f"{prefix}/{_SERVING_SEGMENT}/models/{key}"+++def model_key(model_name: str, model_version: str) -> str:+ return f"{model_name}@{model_version}"+++class ServingManifestEntry(BaseModel):+ """One model the sweep runs, and where to load it from."""++ # Pydantic reserves the `model_` prefix for its own API. The fields mirror the training dag's+ # own columns and `RankingModelResult`, which is the reason they carry these names.+ model_config = ConfigDict(protected_namespaces=())++ key: str = Field(description="`<model_name>@<model_version>`, the identity every consumer uses.")+ model_name: str = Field(description="Feature family the model belongs to, e.g. `report_embeddings`.")+ model_version: str = Field(description="Training partition the model was fit on, as `YYYY-MM-DD`.")+ model_kind: str = Field(description="Learner the model store loads the booster with, e.g. `xgboost`.")+ roles: list[str] = Field(+ min_length=1,+ description=f"Why this model is in the manifest. Exactly one entry carries `{SERVED_ROLE}`.",+ )+ labels: dict[str, str] = Field(default_factory=dict, description="Free text about the entry, for a reader.")+ prefix: str = Field(description="Object-store prefix holding this model's `metadata.json` and head boosters.")+ heads: list[str] = Field(min_length=1, description="Outcome heads with a booster under `prefix`.")++ @field_validator("key", "model_name", "model_version", "model_kind", "prefix")+ @classmethod+ def must_not_be_empty(cls, v: str) -> str:+ if not v.strip():+ raise ValueError("must not be empty or whitespace-only")+ return v++ @model_validator(mode="after")+ def key_matches_the_identity(self) -> ServingManifestEntry:+ expected = model_key(self.model_name, self.model_version)+ if self.key != expected:+ raise ValueError(f"key {self.key!r} does not match its model {expected!r}")+ return self+++class ServingManifest(BaseModel):+ """The models one scoring pass runs. A pass writes one `ranking_score` row naming all of them."""++ manifest_version: str = Field(description="ISO timestamp of the write, stamped onto every score it produces.")+ models: list[ServingManifestEntry] = Field(+ min_length=1,+ # The cap is the artefact's, so a manifest can never produce a row `RankingScore` refuses.+ max_length=MAX_RANKING_MODEL_RESULTS,+ description="Every model the pass runs, served first.",+ )++ @field_validator("manifest_version")+ @classmethod+ def must_not_be_empty(cls, v: str) -> str:+ if not v.strip():+ raise ValueError("must not be empty or whitespace-only")+ return v++ @model_validator(mode="after")+ def one_served_model_under_unique_keys(self) -> ServingManifest:+ keys = [entry.key for entry in self.models]+ if len(set(keys)) != len(keys):+ raise ValueError(f"model keys must be unique, got {keys}")+ served = [entry.key for entry in self.models if SERVED_ROLE in entry.roles]+ if len(served) != 1:+ raise ValueError(f"exactly one model must carry the {SERVED_ROLE!r} role, got {served}")+ return self++ @property+ def served(self) -> ServingManifestEntry:+ return next(entry for entry in self.models if SERVED_ROLE in entry.roles)diff --git a/products/signals/backend/test/conftest.py b/products/signals/backend/test/conftest.pyindex f3920521feb5..b7a83f3be36d 100644--- a/products/signals/backend/test/conftest.py+++ b/products/signals/backend/test/conftest.py@@ -31,7 +31,13 @@ from posthog.models.scoping import team_scope@pytest.fixture(autouse=True)def _scout_team_scope(request: pytest.FixtureRequest):instance = getattr(request, "instance", None)- if instance is None or not hasattr(instance, "team") or instance.team is None:+ # Per-test setup creates the team later; an inherited class team can refer to a rolled-back row.+ if (+ instance is None+ or not getattr(instance, "CLASS_DATA_LEVEL_SETUP", True)+ or not hasattr(instance, "team")+ or instance.team is None+ ):yieldreturnwith team_scope(instance.team.id):diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.mdindex ba1819315a00..21eb4f0a5a34 100644--- a/products/signals/dags/inbox_ranking/AGENTS.md+++ b/products/signals/dags/inbox_ranking/AGENTS.md@@ -27,6 +27,9 @@ Read `README.md` first for what the dataset is and how partitions behave. This f- 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.- 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 refit boosters, `serving/manifest.json` names the models one pass scores. The holdout boosters grade a promotion and must stay behind.+- 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, and no champion for the served family is the case today, writes nothing rather than an empty manifest.## Shadow dag specificsdiff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex 368ffe8ce44f..8c0a825d2a6e 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -94,9 +94,19 @@ s3://<bucket>/<prefix>/- **Missing and empty are different inputs.** The case above is a snapshot object that is absent. A snapshot that exists and carries no usable vector keeps its key, so the family builds no row and the ordinary thin-input path applies. Each rendering is a separate dependency of the examples and scores assets, so a failed title snapshot costs the title family's day and nothing else.- **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 and `inbox_ranking_promotion_decided` once per run, all carrying `model_name` and `model_version` and stamped midday UTC on the partition day so re-runs and backfills chart on the day they describe. Per-head stability is a trends insight with a `head` breakdown; a readability drop is an insight alert. `metadata.json` stays the durable record. Capture is best-effort. Local dev runs (`DEBUG`) emit too, under `distinct_id` `inbox_ranking_training_local` with `environment=local`, so filter or break down on `environment` when reading the prod series; any other non-Cloud deployment emits nothing.+- **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 of the champion on every head the champion could read, and the champion is at least `INBOX_RANKING_PROMOTION_MIN_DAYS` old. The champion's AUCs come from its `<head>.holdout.ubj` scored on the candidate's holdout (`paired_champion_aucs`), so both models are compared on one set of reports; a champion without that file falls back to its stored AUC. The pointer is rewritten only when `INBOX_RANKING_AUTO_PROMOTE` is on; otherwise the decision is logged and surfaced as asset metadata, so the daily candidate series is monitoring while the first shadow read runs on a frozen champion. To promote by hand, copy a candidate's `metadata.json` to `champion.json` with a `promoted_at`.+- **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:++```text+s3://<object-storage bucket>/<prefix>/serving/+├── models/<model_name>@<model_version>/metadata.json + <head>.ubj # the refit boosters only+└── manifest.json # the models one scoring pass runs+```++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, 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. 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.+### Outcome heads| Head | Cohort at the horizon | Horizon (days) |@@ -217,15 +227,16 @@ Like the dataset job, this one reads the dogfood project's ClickHouse, so it can## Configuration-| Setting | Default | Meaning |-| ------------------------------------------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `INBOX_RANKING_DATASET_S3_BUCKET` | unset | Destination bucket. Unset on Cloud makes every asset log and skip, so the dag can deploy before the bucket exists. Unset elsewhere falls back to the deployment's object-storage service (SeaweedFS in dev and CI). |-| `INBOX_RANKING_DATASET_S3_PREFIX` | `inbox_ranking` | Key prefix under the bucket. |-| `INBOX_RANKING_TRAINING_LOOKBACK_DAYS` | `60` | How many daily snapshots back the training examples reach. |-| `INBOX_RANKING_TRAINING_HOLDOUT_DAYS` | `7` | Trailing days of reports that grade a candidate. |-| `INBOX_RANKING_AUTO_PROMOTE` | `false` | Whether a winning candidate rewrites `champion.json`; off, the decision is only logged. |-| `INBOX_RANKING_PROMOTION_MIN_DAYS` | `3` | Minimum age of the champion before another promotion. |-| `INBOX_RANKING_SHADOW_SCORE_LOOKBACK_DAYS` | `60` | How many scores partitions back the shadow read looks for a score that already existed when a list was served. |+| Setting | Default | Meaning |+| ------------------------------------------ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `INBOX_RANKING_DATASET_S3_BUCKET` | unset | Destination bucket. Unset on Cloud makes every asset log and skip, so the dag can deploy before the bucket exists. Unset elsewhere falls back to the deployment's object-storage service (SeaweedFS in dev and CI). |+| `INBOX_RANKING_DATASET_S3_PREFIX` | `inbox_ranking` | Key prefix under the bucket. |+| `INBOX_RANKING_TRAINING_LOOKBACK_DAYS` | `60` | How many daily snapshots back the training examples reach. |+| `INBOX_RANKING_TRAINING_HOLDOUT_DAYS` | `7` | Trailing days of reports that grade a candidate. |+| `INBOX_RANKING_AUTO_PROMOTE` | `false` | Whether a winning candidate rewrites `champion.json`; off, the decision is only logged. |+| `INBOX_RANKING_PROMOTION_MIN_DAYS` | `3` | Minimum age of the champion before another promotion. |+| `INBOX_RANKING_SERVED_FAMILY` | `report_embeddings` | Family whose champion the serving manifest serves. |+| `INBOX_RANKING_SHADOW_SCORE_LOOKBACK_DAYS` | `60` | How many scores partitions back the shadow read looks for a score that already existed when a list was served. |Writes use boto3: ambient AWS config (the node role) when the dedicated bucket is set, the `OBJECT_STORAGE_*` endpoint and credentials otherwise. Readers (project-level warehouse tables, model training) use a separate read-only credential provisioned with the bucket.diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.pyindex 484de67323ec..c4e213057579 100644--- a/products/signals/dags/inbox_ranking/tests/test_training.py+++ b/products/signals/dags/inbox_ranking/tests/test_training.py@@ -14,9 +14,11 @@ import pyarrow as paimport xgboost as xgbimport pyarrow.parquet as pqfrom botocore.exceptions import ClientError+from pydantic import ValidationErrorfrom posthog import settings+from products.signals.backend.artefact_schemas import MAX_RANKING_MODEL_RESULTSfrom products.signals.backend.ranking.features import (BIRTH_GRAIN,EMBEDDING_COLUMN,@@ -38,6 +40,17 @@ from products.signals.backend.ranking.features import (feature_set_by_name,feature_vector,)+from products.signals.backend.ranking.serving_manifest import (+ CROSS_FAMILY_ROLE,+ DAILY_CANDIDATE_ROLE,+ DEFAULT_MODEL_KIND,+ SERVED_ROLE,+ ServingManifest,+ ServingManifestEntry,+ model_key,+ serving_manifest_key,+ serving_model_prefix,+)from products.signals.dags.inbox_ranking.common import partition_object_keyfrom products.signals.dags.inbox_ranking.dataset.dag import (EMBEDDINGS_TABLE,@@ -54,6 +67,7 @@ from products.signals.dags.inbox_ranking.training.dag import (_EXTRA_SNAPSHOT_TABLES,METADATA_FILE,_delete_other_objects,+ _publish_manifest,_train_candidate,candidate_metadata,champion_object_key,@@ -82,6 +96,7 @@ from products.signals.dags.inbox_ranking.training.examples import ()from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, Head, dismissed_as_wrongfrom products.signals.dags.inbox_ranking.training.promotion import AUC_TOLERANCE, PromotionDecision, decide_promotion+from products.signals.dags.inbox_ranking.training.serving import FamilyModels, compose_manifestfrom products.signals.dags.inbox_ranking.training.telemetry import (DISTINCT_ID,LOCAL_DISTINCT_ID,@@ -2019,3 +2034,331 @@ def test_a_model_is_not_scored_without_the_side_input_its_set_reads():kept = models_with_extras(dagster.build_asset_context(), [tabular, embeddings], NO_EXTRAS)assert [model.model_name for model in kept] == [TABULAR_MODEL_NAME]+++def _serving_metadata(model_name: str, version: str, *, heads=("open", "action"), readable=True, **overrides):+ return {+ "model_name": model_name,+ "model_version": version,+ "heads": [{"head": head, "readable": readable, "file": f"{head}.ubj"} for head in heads],+ **overrides,+ }+++def _manifest_entry(model_name: str, version: str, *, roles, heads=("open",)):+ key = model_key(model_name, version)+ return ServingManifestEntry(+ key=key,+ model_name=model_name,+ model_version=version,+ model_kind=DEFAULT_MODEL_KIND,+ roles=list(roles),+ prefix=serving_model_prefix("inbox_ranking", key),+ heads=list(heads),+ )+++ "models,message",+ [+ # The sweep reads the served score as `results[served_key]`, so each of these makes that+ # expression ambiguous, empty or unresolvable at scoring time instead of at write time.+ (+ [+ _manifest_entry(TABULAR_MODEL_NAME, "2026-08-19", roles=[SERVED_ROLE]),+ _manifest_entry(EMBEDDINGS_MODEL_NAME, "2026-08-19", roles=[SERVED_ROLE]),+ ],+ "exactly one model",+ ),+ ([_manifest_entry(TABULAR_MODEL_NAME, "2026-08-19", roles=[CROSS_FAMILY_ROLE])], "exactly one model"),+ (+ [+ _manifest_entry(TABULAR_MODEL_NAME, "2026-08-19", roles=[SERVED_ROLE]),+ _manifest_entry(TABULAR_MODEL_NAME, "2026-08-19", roles=[CROSS_FAMILY_ROLE]),+ ],+ "must be unique",+ ),+ ([], "at least 1 item"),+ (+ [+ _manifest_entry(TABULAR_MODEL_NAME, "2026-08-19", roles=[SERVED_ROLE]),+ *(+ _manifest_entry(EMBEDDINGS_MODEL_NAME, f"2026-08-{day:02d}", roles=[CROSS_FAMILY_ROLE])+ for day in range(1, MAX_RANKING_MODEL_RESULTS + 1)+ ),+ ],+ f"at most {MAX_RANKING_MODEL_RESULTS} items",+ ),+ ],+)+def test_a_manifest_the_sweep_could_not_act_on_is_refused(models, message):+ with pytest.raises(ValidationError, match=message):+ ServingManifest(manifest_version="2026-08-19T06:00:00+00:00", models=models)+++def test_a_manifest_entry_key_must_match_its_model():+ # The key is the join between a manifest entry, a stored score and a model prefix. A key that+ # names a different version sends the sweep to the wrong prefix and stores the wrong identity.+ with pytest.raises(ValidationError, match="does not match its model"):+ ServingManifestEntry(+ key="tabular_xgb@2026-08-18",+ model_name=TABULAR_MODEL_NAME,+ model_version="2026-08-19",+ model_kind=DEFAULT_MODEL_KIND,+ roles=[SERVED_ROLE],+ prefix="inbox_ranking/serving/models/tabular_xgb@2026-08-19",+ heads=["open"],+ )+++def _compose(families, served_family=EMBEDDINGS_MODEL_NAME):+ return compose_manifest(+ families,+ served_family=served_family,+ 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.+ decision = _compose(+ [+ FamilyModels(+ name=EMBEDDINGS_MODEL_NAME,+ candidate=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-19"),+ champion=None,+ )+ ]+ )+ assert decision.manifest is None+ assert "no champion" 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+++ "candidate_version,candidate_readable,expected_roles",+ [+ # A distinct, readable candidate is the paired read the sweep exists for.+ ("2026-08-19", True, {SERVED_ROLE: "2026-08-15", DAILY_CANDIDATE_ROLE: "2026-08-19"}),+ # The candidate at the champion's own version is the champion: a second entry for it would+ # spend a result slot on a duplicate score.+ ("2026-08-15", True, {SERVED_ROLE: "2026-08-15"}),+ # An unreadable candidate has no holdout number to pair the champion against.+ ("2026-08-19", False, {SERVED_ROLE: "2026-08-15"}),+ ],+)+def test_the_served_family_candidate_is_paired_only_when_it_is_a_second_model(+ candidate_version, candidate_readable, expected_roles+):+ decision = _compose(+ [+ 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"),+ )+ ]+ )+ assert decision.manifest is not None+ assert {entry.roles[0]: entry.model_version for entry in decision.manifest.models} == expected_roles+++def test_a_family_with_no_readable_head_is_left_out():+ # The title family has no readable head today. A manifest lists only models a store can load+ # and a reader can judge, so it must not gain an entry the sweep would score blind.+ decision = _compose(+ [+ FamilyModels(+ name=EMBEDDINGS_MODEL_NAME,+ candidate=None,+ champion=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15"),+ ),+ FamilyModels(+ name=TABULAR_MODEL_NAME, candidate=None, champion=_serving_metadata(TABULAR_MODEL_NAME, "2026-08-10")+ ),+ FamilyModels(+ name=TITLE_EMBEDDINGS_MODEL_NAME,+ candidate=None,+ champion=_serving_metadata(TITLE_EMBEDDINGS_MODEL_NAME, "2026-08-12", readable=False),+ ),+ ]+ )+ assert decision.manifest is not None+ assert [entry.model_name for entry in decision.manifest.models] == [EMBEDDINGS_MODEL_NAME, TABULAR_MODEL_NAME]+++def test_the_cap_drops_cross_family_entries_before_the_paired_read():+ # `RankingScore` refuses a row over the cap, so the manifest is capped at the same number. The+ # served entry and its paired candidate are the reads the sweep exists for.+ families = [+ FamilyModels(+ name=EMBEDDINGS_MODEL_NAME,+ candidate=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-19"),+ champion=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15"),+ ),+ *(+ FamilyModels(+ name=f"family_{index}", candidate=None, champion=_serving_metadata(f"family_{index}", "2026-08-10")+ )+ for index in range(5)+ ),+ ]+ decision = _compose(families)+ assert decision.manifest is not None+ assert [entry.roles[0] for entry in decision.manifest.models] == [+ SERVED_ROLE,+ DAILY_CANDIDATE_ROLE,+ *[CROSS_FAMILY_ROLE] * (MAX_RANKING_MODEL_RESULTS - 2),+ ]+++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"),+ )+ ]+ )+ assert decision.manifest is not None+ assert decision.manifest.served.model_kind == DEFAULT_MODEL_KIND+++class _AppObjectStore:+ """The deployment's object store, the one the Temporal workers can reach."""++ def __init__(self, existing: dict[str, bytes] | None = None, fail_on: str | None = None):+ self.objects = dict(existing or {})+ self.fail_on = fail_on++ def head_object(self, file_key: str, bucket: str | None = None):+ return {"ContentLength": len(self.objects[file_key])} if file_key in self.objects else None++ def write(self, file_name: str, content, extras: dict | None = None, bucket: str | None = None) -> None:+ if self.fail_on is not None and self.fail_on in file_name:+ raise RuntimeError("object store write failed")+ self.objects[file_name] = content if isinstance(content, bytes) else content.encode()+++def _serving_dataset_s3(prefix: str, partition_key: str):+ """The dataset bucket holding one champion and one candidate of the served family."""+ objects: dict[str, bytes] = {}+ for version, metadata in (+ ("2026-08-15", _serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15", heads=("open",))),+ (partition_key, _serving_metadata(EMBEDDINGS_MODEL_NAME, partition_key, heads=("open",))),+ ):+ folder = model_object_key(prefix, EMBEDDINGS_MODEL_NAME, version, "")+ objects[folder + METADATA_FILE] = json.dumps(metadata).encode()+ objects[folder + "open.ubj"] = f"booster-{version}".encode()+ objects[champion_object_key(prefix, EMBEDDINGS_MODEL_NAME)] = json.dumps(+ _serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15", heads=("open",))+ ).encode()+ return _ModelStoreS3(objects)+++def _run_serving_manifest(monkeypatch, store: _AppObjectStore, dataset_objects=None):+ partition_key = "2026-08-19"+ prefix = settings.INBOX_RANKING_DATASET_S3_PREFIX+ _patch_capture(monkeypatch, cloud=False, 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),),+ )+ client = (+ _ModelStoreS3(dataset_objects) if dataset_objects is not None else _serving_dataset_s3(prefix, partition_key)+ )+ monkeypatch.setattr("products.signals.dags.inbox_ranking.training.dag.s3_client", lambda: client)+ monkeypatch.setattr("posthog.storage.object_storage.head_object", store.head_object)+ monkeypatch.setattr("posthog.storage.object_storage.write", store.write)+ _publish_manifest(dagster.build_asset_context(partition_key=partition_key), partition_key, "run-1")+ return prefix+++def test_publishing_copies_every_model_the_manifest_names_and_writes_the_manifest_last(monkeypatch):+ store = _AppObjectStore()+ prefix = _run_serving_manifest(monkeypatch, store)++ manifest = ServingManifest.model_validate_json(store.objects[serving_manifest_key(prefix)])+ assert manifest.served.key == model_key(EMBEDDINGS_MODEL_NAME, "2026-08-15")+ # Every entry the manifest names has its record and its booster in the store the sweep reads.+ for entry in manifest.models:+ assert f"{entry.prefix}/{METADATA_FILE}" in store.objects+ assert f"{entry.prefix}/open.ubj" in store.objects+++def test_a_version_already_in_the_store_is_not_copied_again(monkeypatch):+ # A model version is immutable, so re-copying it every day would move the boosters of every+ # entry, one of which is 1536 columns wide, for no change.+ champion_prefix = serving_model_prefix(+ settings.INBOX_RANKING_DATASET_S3_PREFIX, model_key(EMBEDDINGS_MODEL_NAME, "2026-08-15")+ )+ store = _AppObjectStore({f"{champion_prefix}/{METADATA_FILE}": b"already here"})+ prefix = _run_serving_manifest(monkeypatch, store)++ assert store.objects[f"{champion_prefix}/{METADATA_FILE}"] == b"already here"+ assert f"{champion_prefix}/open.ubj" not in store.objects+ # The day's candidate was not there, so it was copied and the manifest still names both.+ manifest = ServingManifest.model_validate_json(store.objects[serving_manifest_key(prefix)])+ 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):+ # 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_PREFIX+ previous = 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()+ }++ with pytest.raises((dagster.Failure, RuntimeError)):+ _run_serving_manifest(monkeypatch, store, dataset_objects=None if source_present else champion_only)++ assert store.objects[serving_manifest_key(prefix)] == previous++ store.fail_on = None+ _run_serving_manifest(monkeypatch, store)+ manifest = ServingManifest.model_validate_json(store.objects[serving_manifest_key(prefix)])+ for entry in manifest.models:+ assert 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):+ prefix = settings.INBOX_RANKING_DATASET_S3_PREFIX+ folder = model_object_key(prefix, EMBEDDINGS_MODEL_NAME, "2026-08-19", "")+ store = _AppObjectStore()+ _run_serving_manifest(+ monkeypatch,+ store,+ dataset_objects={+ folder + METADATA_FILE: json.dumps(_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-19")).encode()+ },+ )+ assert store.objects == {}+++def test_the_serving_prefix_layout_is_stable():+ # The scoring sweep resolves these keys, so a change here is a change to the serving contract.+ assert serving_manifest_key("inbox_ranking") == "inbox_ranking/serving/manifest.json"+ assert (+ serving_model_prefix("inbox_ranking", model_key(EMBEDDINGS_MODEL_NAME, "2026-08-19"))+ == "inbox_ranking/serving/models/report_embeddings@2026-08-19"+ )diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pyindex 5fb0b102e710..4ae378810752 100644--- a/products/signals/dags/inbox_ranking/training/dag.py+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -7,6 +7,12 @@ Three assets on the same daily partition as the dataset dag, each writing underinbox_ranking_models/v1/<name>/champion.json pointer to the version the scoring sweep loadsinbox_ranking_unseen_scores/v1/dt=D/ the day's models on the reports born that day+A fifth asset publishes what the scoring sweep serves. The dataset bucket holds the training+history and the Temporal workers cannot reach it, so `inbox_ranking_serving_manifest` copies the+models the sweep needs into the deployment's own object store and writes a manifest naming them+(`serving/manifest.json`, `serving/models/<key>/`). The manifest is the dag's serving decision:+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` ofreports, and refits on everything. The champion asset applies `promotion.decide_promotion`; it@@ -47,6 +53,8 @@ import pyarrow.compute as pcfrom botocore.exceptions import ClientErrorfrom posthog import settings+from posthog.dataclasses import frozen+from posthog.storage import object_storagefrom products.signals.backend.ranking.features import (EMBEDDING_COLUMN,@@ -57,6 +65,7 @@ from products.signals.backend.ranking.features import (Extras,FeatureSet,)+from products.signals.backend.ranking.serving_manifest import DEFAULT_MODEL_KIND, ServingManifest, serving_manifest_keyfrom products.signals.dags.inbox_ranking.common import (DATASET_VERSION,PARQUET_PART_NAME,@@ -94,6 +103,7 @@ from products.signals.dags.inbox_ranking.training.examples import ()from products.signals.dags.inbox_ranking.training.heads import HEADS, HEADS_BY_HORIZON, HEADS_BY_NAMEfrom products.signals.dags.inbox_ranking.training.promotion import decide_promotion+from products.signals.dags.inbox_ranking.training.serving import FamilyModels, compose_manifestfrom products.signals.dags.inbox_ranking.training.telemetry import (HeadExampleCounts,candidate_events,@@ -101,6 +111,7 @@ from products.signals.dags.inbox_ranking.training.telemetry import (examples_events,holdout_calibration_events,promotion_event,+ serving_manifest_event,unseen_calibration_events,unseen_head_graded_events,unseen_report_graded_events,@@ -491,6 +502,9 @@ def candidate_metadata("model_name": model_name,"model_version": partition_key,"dataset_version": DATASET_VERSION,+ # The learner a model store loads the booster with. Every family is per-head XGBoost today;+ # the field exists so the serving manifest reads it from the source rather than assuming it.+ "model_kind": DEFAULT_MODEL_KIND,# The feature universe this model was fit on. The grader checks the model against this set# rather than against one global contract, so a second family is not rejected for reading# different features.@@ -786,6 +800,143 @@ def _decide_champion(}+SERVING_MANIFEST_ASSET = "inbox_ranking_serving_manifest"++[email protected](name=SERVING_MANIFEST_ASSET, deps=["inbox_ranking_model_champion"], **COMMON_ASSET_KWARGS)+def inbox_ranking_serving_manifest(context: dagster.AssetExecutionContext) -> None:+ """Publish the models the scoring sweep serves, and the manifest naming them.++ The training history stays in the dataset bucket, which the Temporal workers cannot reach. What+ the sweep needs is copied into the deployment's own object store instead, so the serving path+ needs no credential for the dataset bucket. A model version is immutable, so a version already+ at the target is left alone, and the manifest is written last: a failed copy leaves the previous+ manifest, and the models it names, serving.+ """+ if skip_unconfigured(context):+ return+ context.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]:+ bucket, prefix, client = dataset_bucket(), settings.INBOX_RANKING_DATASET_S3_PREFIX, s3_client()+ served_family = settings.INBOX_RANKING_SERVED_FAMILY++ families = [+ FamilyModels(+ name=family.name,+ candidate=_read_json_if_exists(+ client, bucket, model_object_key(prefix, family.name, partition_key, METADATA_FILE)+ ),+ champion=_read_json_if_exists(client, bucket, champion_object_key(prefix, family.name)),+ )+ for family in MODEL_FAMILIES+ ]+ decision = compose_manifest(+ families, served_family=served_family, prefix=prefix, now=datetime.datetime.now(datetime.UTC)+ )+ if decision.manifest is None:+ context.log.warning(f"no serving manifest for dt={partition_key}: {decision.reason}")+ capture_training_events(+ context,+ partition_key,+ [+ serving_manifest_event(+ partition_key=partition_key,+ run_id=run_id,+ served_family=served_family,+ manifest=None,+ reason=decision.reason,+ )+ ],+ )+ return {"published": dagster.MetadataValue.bool(False)}++ manifest = decision.manifest+ manifest_key = serving_manifest_key(prefix)+ publication = publish_serving_models(context, client, bucket, prefix, manifest)+ object_storage.write(+ manifest_key,+ manifest.model_dump_json(indent=2),+ extras={"ContentType": "application/json"},+ )+ context.log.info(f"published serving manifest {manifest.manifest_version} serving {manifest.served.key}")+ capture_training_events(+ context,+ partition_key,+ [+ serving_manifest_event(+ partition_key=partition_key,+ run_id=run_id,+ served_family=served_family,+ manifest=manifest,+ reason=decision.reason,+ copied_keys=publication.copied,+ present_keys=publication.present,+ bytes_copied=publication.bytes_copied,+ )+ ],+ )+ return {+ "published": dagster.MetadataValue.bool(True),+ "manifest_key": dagster.MetadataValue.text(manifest_key),+ "manifest_version": dagster.MetadataValue.text(manifest.manifest_version),+ "served_key": dagster.MetadataValue.text(manifest.served.key),+ "models": dagster.MetadataValue.json(+ [{"key": entry.key, "roles": entry.roles, "heads": entry.heads} for entry in manifest.models]+ ),+ "entries_copied": dagster.MetadataValue.int(len(publication.copied)),+ "entries_already_present": dagster.MetadataValue.int(len(publication.present)),+ "bytes_copied": dagster.MetadataValue.int(publication.bytes_copied),+ }+++@frozen+class _ModelPublication:+ copied: list[str]+ present: list[str]+ bytes_copied: int+++def publish_serving_models(+ context: dagster.AssetExecutionContext,+ client,+ bucket: str,+ prefix: str,+ manifest: ServingManifest,+) -> _ModelPublication:+ """Copy every model the manifest names from the dataset bucket into the app object store.++ Returns the keys copied, the keys already there, and the bytes moved. A missing source object+ fails the asset before the manifest is written, so the manifest can never name a model the+ sweep cannot load.+ """+ copied: list[str] = []+ present: list[str] = []+ bytes_copied = 0+ for entry in manifest.models:+ target_metadata = f"{entry.prefix}/{METADATA_FILE}"+ # A version is immutable, so its metadata record standing in for the whole prefix is safe+ # and saves re-reading a 1536-column booster every day.+ if object_storage.head_object(target_metadata) is not None:+ present.append(entry.key)+ continue+ # Metadata marks a complete copy, so write it after every booster to make retries safe.+ for name in (*(f"{head}.ubj" for head in entry.heads), METADATA_FILE):+ body = _read_bytes_if_exists(+ client, bucket, model_object_key(prefix, entry.model_name, entry.model_version, name)+ )+ if body is None:+ raise dagster.Failure(f"{entry.key} is missing {name} in the dataset bucket; manifest not written")+ object_storage.write(f"{entry.prefix}/{name}", body)+ bytes_copied += len(body)+ copied.append(entry.key)+ context.log.info(f"copied {entry.key} to {entry.prefix}")+ return _ModelPublication(copied=copied, present=present, bytes_copied=bytes_copied)++# dt=D grades the scores written on D - horizon_days, so the mapping reaches back as far as the# longest head horizon. Partitions before the scores asset existed have no upstream to map to._HORIZON_MAPPING = dagster.TimeWindowPartitionMapping(@@ -1068,6 +1219,7 @@ inbox_ranking_training_job = dagster.define_asset_job(EXAMPLES_TABLE,"inbox_ranking_model_candidate","inbox_ranking_model_champion",+ SERVING_MANIFEST_ASSET,UNSEEN_SCORES_TABLE,"inbox_ranking_unseen_graded",],diff --git a/products/signals/dags/inbox_ranking/training/serving.py b/products/signals/dags/inbox_ranking/training/serving.pynew file mode 100644index 000000000000..2141f8bfa1aa--- /dev/null+++ b/products/signals/dags/inbox_ranking/training/serving.py@@ -0,0 +1,134 @@+"""Composing the serving manifest from the day's models.++The training dag is the only place that knows every family's candidate and champion at once, so it+picks 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+and a later interleaving then need no rescoring of the same reports.+"""++import datetime+from collections.abc import Mapping, Sequence+from typing import Any++from posthog.dataclasses import frozen++from products.signals.backend.artefact_schemas import MAX_RANKING_MODEL_RESULTS+from products.signals.backend.ranking.serving_manifest import (+ CROSS_FAMILY_ROLE,+ DAILY_CANDIDATE_ROLE,+ DEFAULT_MODEL_KIND,+ SERVED_ROLE,+ ServingManifest,+ ServingManifestEntry,+ model_key,+ serving_model_prefix,+)+from products.signals.dags.inbox_ranking.training.unseen import readable_head_names, trained_head_files+++@frozen+class 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."""++ name: str+ candidate: Mapping[str, Any] | None+ champion: Mapping[str, Any] | None+++@frozen+class ManifestDecision:+ """The manifest to publish, or None with the reason nothing is published. A run that writes+ nothing leaves the previous manifest, and the models it names, in place."""++ manifest: ServingManifest | None+ reason: str+++def _entry(+ metadata: Mapping[str, Any],+ *,+ roles: Sequence[str],+ labels: Mapping[str, str],+ prefix: str,+) -> ServingManifestEntry | None:+ """One manifest entry, or None when the model has no head a store could load. Only the refit+ boosters are named: the holdout fits grade a promotion and never serve."""+ heads = sorted(trained_head_files(metadata))+ if not heads:+ return None+ key = model_key(metadata["model_name"], metadata["model_version"])+ return ServingManifestEntry(+ key=key,+ model_name=metadata["model_name"],+ model_version=metadata["model_version"],+ # A model published before the field existed is per-head XGBoost, so the old default reads+ # as what it is rather than as missing.+ model_kind=metadata.get("model_kind") or DEFAULT_MODEL_KIND,+ roles=list(roles),+ labels=dict(labels),+ prefix=serving_model_prefix(prefix, key),+ heads=heads,+ )+++def compose_manifest(+ families: Sequence[FamilyModels],+ *,+ served_family: str,+ prefix: str,+ now: datetime.datetime,+) -> ManifestDecision:+ 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,+ roles=[SERVED_ROLE],+ labels={"reason": f"champion of the served family {served_family}"},+ prefix=prefix,+ )+ if served is None:+ return ManifestDecision(+ manifest=None, reason=f"served family {served_family} champion has no head booster to load"+ )++ entries = [served]+ candidate = served_models.candidate+ # 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):+ daily = _entry(+ candidate,+ roles=[DAILY_CANDIDATE_ROLE],+ labels={"reason": f"today's {served_family} candidate, paired against the served champion"},+ prefix=prefix,+ )+ if daily is not None:+ entries.append(daily)++ for family in families:+ if family.name == served_family or family.champion is None or not readable_head_names(family.champion):+ continue+ cross = _entry(+ family.champion,+ roles=[CROSS_FAMILY_ROLE],+ labels={"reason": f"champion of {family.name}"},+ prefix=prefix,+ )+ if cross is not None:+ entries.append(cross)++ # The served entry and the paired candidate are the reads the sweep exists for, so the cap+ # falls on the cross-family entries. They are last in `entries`, in family registration order.+ return ManifestDecision(+ manifest=ServingManifest(manifest_version=now.isoformat(), models=entries[:MAX_RANKING_MODEL_RESULTS]),+ reason="composed",+ )diff --git a/products/signals/dags/inbox_ranking/training/telemetry.py b/products/signals/dags/inbox_ranking/training/telemetry.pyindex 0856a048d99d..30b9de34c5ef 100644--- a/products/signals/dags/inbox_ranking/training/telemetry.py+++ b/products/signals/dags/inbox_ranking/training/telemetry.py@@ -19,6 +19,7 @@ from posthog.cloud_utils import is_cloudfrom posthog.dataclasses import frozenfrom posthog.ph_client import get_client+from products.signals.backend.ranking.serving_manifest import ServingManifestfrom products.signals.dags.inbox_ranking.common import snapshot_boundsfrom products.signals.dags.inbox_ranking.training.promotion import PromotionDecisionfrom products.signals.dags.inbox_ranking.training.unseen import CANDIDATE_ROLE, HeadGrade@@ -36,6 +37,7 @@ UNSEEN_HEAD_GRADED_EVENT = "inbox_ranking_unseen_head_graded"UNSEEN_REPORT_GRADED_EVENT = "inbox_ranking_unseen_report_graded"UNSEEN_CALIBRATION_EVENT = "inbox_ranking_unseen_calibration"HOLDOUT_CALIBRATION_EVENT = "inbox_ranking_holdout_calibration"+SERVING_MANIFEST_PUBLISHED_EVENT = "inbox_ranking_serving_manifest_published"# Candidate metadata copied onto every per-head event so a chart can filter or break down on it._CANDIDATE_CONTEXT_KEYS = (@@ -157,6 +159,40 @@ def promotion_event()+def serving_manifest_event(+ *,+ partition_key: str,+ run_id: str,+ served_family: str,+ manifest: ServingManifest | None,+ reason: str,+ copied_keys: Sequence[str] = (),+ present_keys: Sequence[str] = (),+ bytes_copied: int = 0,+) -> TrainingEvent:+ """What the day's manifest published. A run that wrote nothing still reports, with `reason`:+ the manifest is what makes the sweep serve anything, so a silent gap in this series would read+ the same as a day of ordinary publishing."""+ properties: dict[str, object] = {+ "model_version": partition_key,+ "run_id": run_id,+ "served_family": served_family,+ "published": manifest is not None,+ "reason": reason,+ "entries_copied": len(copied_keys),+ "entries_already_present": len(present_keys),+ "bytes_copied": bytes_copied,+ }+ if manifest is not None:+ properties |= {+ "manifest_version": manifest.manifest_version,+ "served_key": manifest.served.key,+ "model_keys": [entry.key for entry in manifest.models],+ "model_roles": {entry.key: entry.roles for entry in manifest.models},+ }+ return TrainingEvent(event=SERVING_MANIFEST_PUBLISHED_EVENT, properties=properties)++def unseen_score_events(*, run_id: str, rows: Sequence[Mapping[str, Any]]) -> list[TrainingEvent]:"""One event per (report, model) for the day's unseen pool. Every property is flat andnumeric where it is a number, so a trends insight can aggregate a head's scores directly."""