: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): score inbox reports with the models in the serving manifest (#106765)
posthog[bot]45654169840b
diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.pyindex 4f085f794712..a467f8a61818 100644--- a/posthog/settings/object_storage.py+++ b/posthog/settings/object_storage.py@@ -110,6 +110,9 @@ INBOX_RANKING_PROMOTION_MIN_DAYS = get_from_env("INBOX_RANKING_PROMOTION_MIN_DAY# 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")+# Scorer (products/signals/backend/ranking/scorer.py): report ids per ClickHouse vector read. A+# larger call is paged at this size.+INBOX_RANKING_SCORING_BATCH_SIZE = get_from_env("INBOX_RANKING_SCORING_BATCH_SIZE", 500, type_cast=int)# Shadow dag (products/signals/dags/inbox_ranking/shadow): how many daily scores partitions back# the read looks for a score that already existed when a list was served. A report is scored on# the day it is born, so this bounds how old a report can be and still be graded.diff --git a/products/signals/backend/ranking/model_contract.py b/products/signals/backend/ranking/model_contract.pynew file mode 100644index 000000000000..da42b0297c41--- /dev/null+++ b/products/signals/backend/ranking/model_contract.py@@ -0,0 +1,70 @@+"""Whether a published ranking model can be scored by this build.++The training dag and the serving store make the same decision about the same `metadata.json`, so+the rules live here, next to the feature sets they check against. The dag grades a model it can+score, and the server serves a model it can score; code copied between the two would let them+disagree about which models those are.+"""++from collections.abc import Collection, Mapping, Sequence+from typing import Any++from products.signals.backend.ranking.features import FeatureSet, feature_set_by_name+++def model_feature_set(metadata: Mapping[str, Any]) -> FeatureSet | None:+ """The feature set the model declares, or None when this build cannot produce it. Metadata+ written before the field existed declares nothing and reads as the tabular set."""+ return feature_set_by_name(metadata.get("feature_set"))+++def model_mismatch(metadata: Mapping[str, Any]) -> str | None:+ """Why the model cannot be scored, or None when it can.++ A model is checked against its own declared set rather than one global contract, so a family+ on a richer set is not rejected for disagreeing with the tabular one.+ """+ feature_set = model_feature_set(metadata)+ if feature_set is None:+ return f"feature set {metadata.get('feature_set')} is not one this build can produce"+ version = metadata.get("feature_schema_version")+ if version != feature_set.schema_version:+ return f"feature_schema_version {version} is not {feature_set.name}'s {feature_set.schema_version}"+ if tuple(metadata.get("feature_names") or ()) != feature_set.feature_names:+ return f"feature_names differ from the {feature_set.name} feature set"+ return None+++def booster_mismatch(head: str, booster_feature_names: Sequence[str] | None, feature_set: FeatureSet) -> str | None:+ """Why one loaded head booster cannot take the feature set's matrix, or None when it can.++ `model_mismatch` reads only the metadata record. A booster file replaced under an unchanged+ `metadata.json` passes that check, so a loader asks the booster itself as well.+ """+ if tuple(booster_feature_names or ()) != feature_set.feature_names:+ return f"{head} booster feature_names differ from the {feature_set.name} feature set"+ return None+++def readable_head_names(metadata: Mapping[str, Any]) -> frozenset[str]:+ """The heads of a model whose holdout AUC could be read."""+ return frozenset(entry["head"] for entry in metadata.get("heads", []) if entry.get("readable"))+++def trained_head_files(metadata: Mapping[str, Any], known_heads: Collection[str]) -> dict[str, str]:+ """The `<head>.ubj` object name per head the candidate fit, of the heads in `known_heads`.++ Every trained head is scored, readable or not. A rare head never clears `min_holdout_positives`+ on one day's holdout, and the pooled newborn grade over many days is the only read that can+ ever give it a number; gating the scoring on readability means that read never starts. An+ unreadable head has no holdout AUC to compare against, so read its grade on its own, and the+ promotion gate still ignores it.++ The dag passes the heads it defines. The server passes the heads its manifest entry names,+ because the dag already chose those with this same function.+ """+ return {+ entry["head"]: entry["file"]+ for entry in metadata.get("heads", [])+ if entry.get("file") and entry.get("head") in known_heads+ }diff --git a/products/signals/backend/ranking/model_store.py b/products/signals/backend/ranking/model_store.pynew file mode 100644index 000000000000..b7390dc34d19--- /dev/null+++ b/products/signals/backend/ranking/model_store.py@@ -0,0 +1,191 @@+"""Loads the models the serving manifest names, from the deployment's own object store.++The training dag publishes the manifest and every model it names under+`<INBOX_RANKING_DATASET_S3_PREFIX>/serving/` (see `serving_manifest.py`). This module is the reader.+It uses `posthog.storage.object_storage`, the client the dag publishes with, and never the dataset+bucket: the scoring workers hold no credential for that bucket.++A model key is `<name>@<version>`, and the dag never re-copies a published version, so a loaded+model is cached in the process by key with no invalidation. The manifest itself is read on every+call, because a promotion changes it in place.+"""++from __future__ import annotations++import json+import threading+from collections import OrderedDict+from collections.abc import Callable, Mapping, Sequence+from dataclasses import replace+from typing import Any, Protocol++from django.conf import settings++import numpy as np+import structlog++from posthog.dataclasses import frozen+from posthog.storage import object_storage++from products.signals.backend.artefact_schemas import MAX_RANKING_MODEL_RESULTS+from products.signals.backend.ranking.features import FeatureSet+from products.signals.backend.ranking.model_contract import (+ booster_mismatch,+ model_feature_set,+ model_mismatch,+ trained_head_files,+)+from products.signals.backend.ranking.serving_manifest import (+ DEFAULT_MODEL_KIND,+ METADATA_FILE,+ ServingManifest,+ ServingManifestEntry,+ serving_manifest_key,+)++logger = structlog.get_logger(__name__)++HEAD_FILE_SUFFIX = ".ubj"+++class ModelLoadError(Exception):+ """One manifest entry could not be loaded into a model this build can score."""+++@frozen+class LoadedModel:+ entry: ServingManifestEntry+ # From `feature_set_by_name(metadata["feature_set"])`, the set the model was fit on.+ feature_set: FeatureSet+ # The model's `metadata.json`, copied onto every result it produces.+ metadata: Mapping[str, Any]+ # A matrix in `feature_set.feature_names` order to the probabilities of each head.+ predict: Callable[[np.ndarray], Mapping[str, np.ndarray]]+++@frozen+class ServingSet:+ manifest: ServingManifest+ served: LoadedModel+ # The other entries that loaded, in manifest order.+ others: Sequence[LoadedModel]+ # Model key to the reason the entry could not be loaded.+ skipped: Mapping[str, str]+++class ModelKindHandler(Protocol):+ def load(+ self, entry: ServingManifestEntry, metadata: Mapping[str, Any], head_files: Mapping[str, bytes]+ ) -> LoadedModel: ...+++class XGBoostHandler:+ """One binary XGBoost booster per head, all fit on the same feature set."""++ def load(+ self, entry: ServingManifestEntry, metadata: Mapping[str, Any], head_files: Mapping[str, bytes]+ ) -> LoadedModel:+ import xgboost as xgb # noqa: PLC0415 — keeps xgboost's native OpenMP runtime off the Temporal worker import path++ feature_set = model_feature_set(metadata)+ if feature_set is None:+ raise ModelLoadError(f"{entry.key} declares a feature set this build cannot produce")+ boosters: dict[str, xgb.Booster] = {}+ for head, raw in head_files.items():+ booster = xgb.Booster()+ try:+ booster.load_model(bytearray(raw))+ except xgb.core.XGBoostError as error:+ raise ModelLoadError(f"{entry.key} {head} booster does not load: {error}") from error+ mismatch = booster_mismatch(head, booster.feature_names, feature_set)+ if mismatch is not None:+ raise ModelLoadError(f"{entry.key} {mismatch}")+ boosters[head] = booster+ feature_names = list(feature_set.feature_names)++ def predict(matrix: np.ndarray) -> dict[str, np.ndarray]:+ dmatrix = xgb.DMatrix(matrix, feature_names=feature_names)+ return {head: booster.predict(dmatrix) for head, booster in boosters.items()}++ return LoadedModel(entry=entry, feature_set=feature_set, metadata=metadata, predict=predict)+++# The place a new learner plugs in, e.g. a torch model with its own `predict`.+MODEL_KIND_HANDLERS: Mapping[str, ModelKindHandler] = {DEFAULT_MODEL_KIND: XGBoostHandler()}++_cache: OrderedDict[str, LoadedModel] = OrderedDict()+_cache_lock = threading.Lock()+++def _read_entry(entry: ServingManifestEntry) -> LoadedModel:+ handler = MODEL_KIND_HANDLERS.get(entry.model_kind)+ if handler is None:+ raise ModelLoadError(f"{entry.key} has model_kind {entry.model_kind}, which this build cannot load")+ raw_metadata = object_storage.read(f"{entry.prefix}/{METADATA_FILE}", missing_ok=True)+ if raw_metadata is None:+ raise ModelLoadError(f"{entry.key} has no {METADATA_FILE} under {entry.prefix}")+ metadata = json.loads(raw_metadata)+ if (metadata.get("model_name"), metadata.get("model_version")) != (entry.model_name, entry.model_version):+ raise ModelLoadError(f"{entry.key} {METADATA_FILE} describes another model")+ mismatch = model_mismatch(metadata)+ if mismatch is not None:+ raise ModelLoadError(f"{entry.key} {mismatch}")+ untrained = sorted(set(entry.heads) - set(trained_head_files(metadata, entry.heads)))+ if untrained:+ raise ModelLoadError(f"{entry.key} {METADATA_FILE} has no trained booster for {untrained}")+ head_files: dict[str, bytes] = {}+ for head in entry.heads:+ body = object_storage.read_bytes(f"{entry.prefix}/{head}{HEAD_FILE_SUFFIX}", missing_ok=True)+ if body is None:+ raise ModelLoadError(f"{entry.key} has no {head}{HEAD_FILE_SUFFIX} under {entry.prefix}")+ head_files[head] = body+ return handler.load(entry, metadata, head_files)+++def load_model(entry: ServingManifestEntry) -> LoadedModel:+ """The model one entry names, from the process cache when this key was loaded before.++ The cached model carries the entry it was first loaded under, and roles change between+ manifests, so the returned model carries the current entry instead.+ """+ with _cache_lock:+ cached = _cache.get(entry.key)+ if cached is not None:+ _cache.move_to_end(entry.key)+ if cached is None:+ cached = _read_entry(entry)+ with _cache_lock:+ _cache[entry.key] = cached+ while len(_cache) > MAX_RANKING_MODEL_RESULTS:+ _cache.popitem(last=False)+ return replace(cached, entry=entry)+++def clear_model_cache() -> None:+ with _cache_lock:+ _cache.clear()+++def load_serving_set() -> ServingSet | None:+ """Every model the manifest names, or None when no manifest is published yet.++ A served entry that fails to load raises, because a pass without a served score is worse than+ no pass. Any other entry that fails is recorded in `skipped`, and the scorer writes it as a+ skipped result, so the coverage of each model stays readable.+ """+ raw_manifest = object_storage.read(serving_manifest_key(settings.INBOX_RANKING_DATASET_S3_PREFIX), missing_ok=True)+ if raw_manifest is None:+ return None+ manifest = ServingManifest.model_validate_json(raw_manifest)+ served = load_model(manifest.served)+ others: list[LoadedModel] = []+ skipped: dict[str, str] = {}+ for entry in manifest.models:+ if entry.key == manifest.served.key:+ continue+ try:+ others.append(load_model(entry))+ except ModelLoadError as error:+ logger.warning("inbox_ranking_model_skipped", model_key=entry.key, reason=str(error))+ skipped[entry.key] = str(error)+ return ServingSet(manifest=manifest, served=served, others=others, skipped=skipped)diff --git a/products/signals/backend/ranking/scorer.py b/products/signals/backend/ranking/scorer.pynew file mode 100644index 000000000000..ea96727b3ed3--- /dev/null+++ b/products/signals/backend/ranking/scorer.py@@ -0,0 +1,208 @@+"""Scores inbox reports with every model the serving manifest names.++One pass loads the serving set, reads each report's current vector once per rendering the models+need, builds each model's matrix through its own `FeatureSet.build_matrix`, and produces one+validated `RankingScore` per report. `build_matrix` is the code the training dag fits and grades+with, so a served score is the value the dag would produce for the same model and vector.++Nothing is written until every report of the call is scored, so a failure part of the way through+a call writes nothing.+"""++from collections.abc import Mapping, Sequence+from datetime import datetime+from typing import Any++import pandas as pd+import structlog++from posthog.dataclasses import frozen++from products.signals.backend.artefact_schemas import RankingModelResult, RankingScore+from products.signals.backend.ranking.features import (+ EMBEDDING_COLUMN,+ EMBEDDING_INSERTED_AT_COLUMN,+ REPORT_EMBEDDINGS_EXTRA,+ TITLE_EMBEDDINGS_EXTRA,+ FeatureSet,+ ReportEmbeddingsFeatureSet,+)+from products.signals.backend.ranking.model_store import LoadedModel, load_serving_set+from products.signals.backend.ranking.serving_manifest import ServingManifestEntry+from products.signals.backend.ranking.sinks import persist_scores+from products.signals.backend.report_embedding_reader import ReportVector, latest_report_vectors+from products.signals.backend.report_embeddings import EMBEDDING_RENDERING_TITLE, EMBEDDING_RENDERING_TITLE_SUMMARY++logger = structlog.get_logger(__name__)++NO_VECTOR = "no_vector"++# The rendering each embedding side input is the vector of. The dataset dag snapshots the same+# renderings under the same keys, so a model reads the text it was fit on.+RENDERING_BY_EXTRA: Mapping[str, str] = {+ REPORT_EMBEDDINGS_EXTRA: EMBEDDING_RENDERING_TITLE_SUMMARY,+ TITLE_EMBEDDINGS_EXTRA: EMBEDDING_RENDERING_TITLE,+}++# A model that did not load has no feature contract this pass could read.+UNKNOWN_FEATURE_SCHEMA_VERSION = 0++# Left off the copied metadata: an embedding set names 1536 columns, and `feature_set` with+# `feature_schema_version` already identify them.+_METADATA_FIELDS_NOT_COPIED = frozenset({"feature_names"})+++class ScoringError(Exception):+ """The pass cannot produce a served score for any report."""+++@frozen+class ReportScoringOutcome:+ report_id: str+ # None when the report could not be scored this pass.+ score: RankingScore | None+ # Why the report has no score, e.g. "no_vector". None when scored.+ reason: str | None+++@frozen+class _ModelScores:+ """One model's pass over the call's reports: probabilities per report it could score, or the+ reason it scored none."""++ model: LoadedModel+ by_report: Mapping[str, Mapping[str, float]]+ skip_reason: str | None+++def _served_extra(feature_set: FeatureSet) -> str | None:+ """The side input a set is served from, or None when this build does not serve the set yet."""+ if not isinstance(feature_set, ReportEmbeddingsFeatureSet):+ return None+ (extra,) = feature_set.extras_keys+ return extra if extra in RENDERING_BY_EXTRA else None+++def _extras_frame(report_ids: Sequence[str], vectors: Mapping[str, ReportVector]) -> pd.DataFrame:+ present = [report_id for report_id in report_ids if report_id in vectors]+ return pd.DataFrame(+ {+ EMBEDDING_COLUMN: [vectors[report_id].embedding for report_id in present],+ EMBEDDING_INSERTED_AT_COLUMN: [vectors[report_id].inserted_at for report_id in present],+ },+ index=pd.Index(present, name="report_id"),+ )+++def _score_model(+ model: LoadedModel, report_ids: Sequence[str], vectors_by_extra: Mapping[str, Mapping[str, ReportVector]]+) -> _ModelScores:+ extra = _served_extra(model.feature_set)+ if extra is None:+ return _ModelScores(+ model=model, by_report={}, skip_reason=f"feature set {model.feature_set.name} is not served yet"+ )+ rows = pd.DataFrame(index=pd.Index(list(report_ids), name="report_id"))+ extras = {extra: _extras_frame(report_ids, vectors_by_extra[extra])}+ # `as_of=None`: serving scores the latest vector, where training reads the one of its moment.+ buildable = model.feature_set.buildable(rows, extras, as_of=None).to_numpy()+ if not buildable.any():+ return _ModelScores(model=model, by_report={}, skip_reason=None)+ matrix = model.feature_set.build_matrix(rows, extras, as_of=None).loc[buildable]+ probabilities = model.predict(matrix.to_numpy())+ by_report = {+ report_id: {head: float(values[index]) for head, values in probabilities.items()}+ for index, report_id in enumerate(matrix.index)+ }+ return _ModelScores(model=model, by_report=by_report, skip_reason=None)+++def _copied_metadata(metadata: Mapping[str, Any]) -> dict[str, Any]:+ return {key: value for key, value in metadata.items() if key not in _METADATA_FIELDS_NOT_COPIED}+++def _result(model_scores: _ModelScores, report_id: str) -> RankingModelResult:+ model = model_scores.model+ entry = model.entry+ scores = model_scores.by_report.get(report_id)+ skip_reason = model_scores.skip_reason or (NO_VECTOR if scores is None else None)+ return RankingModelResult(+ model_name=entry.model_name,+ model_version=entry.model_version,+ model_kind=entry.model_kind,+ roles=list(entry.roles),+ feature_schema_version=model.feature_set.schema_version,+ status="skipped" if skip_reason else "scored",+ skip_reason=skip_reason,+ scores=dict(scores or {}),+ metadata=_copied_metadata(model.metadata),+ )+++def _unloaded_result(entry: ServingManifestEntry, reason: str) -> RankingModelResult:+ return RankingModelResult(+ model_name=entry.model_name,+ model_version=entry.model_version,+ model_kind=entry.model_kind,+ roles=list(entry.roles),+ feature_schema_version=UNKNOWN_FEATURE_SCHEMA_VERSION,+ status="skipped",+ skip_reason=reason,+ )+++def score_reports(+ team_id: int, report_ids: Sequence[str], *, persist: bool, now: datetime+) -> list[ReportScoringOutcome]:+ """One outcome per distinct report id, in the order given.++ A report with no current vector for the served model gets no score and `reason="no_vector"`,+ so the caller can try it again later. A challenger with no vector is a skipped result inside+ the score. `persist=False` returns the scores and writes nothing.+ """+ serving = load_serving_set()+ if serving is None:+ logger.info("inbox_ranking_scoring_skipped", team_id=team_id, reason="no serving manifest is published")+ return []+ ids = list(dict.fromkeys(str(report_id) for report_id in report_ids))+ if not ids:+ return []+ served = serving.served+ served_extra = _served_extra(served.feature_set)+ if served_extra is None:+ raise ScoringError(+ f"served model {served.entry.key} is on feature set {served.feature_set.name}, not served yet"+ )++ models = [served, *serving.others]+ needed_extras = {extra for model in models if (extra := _served_extra(model.feature_set)) is not None}+ vectors_by_extra = {+ extra: latest_report_vectors(team_id, ids, rendering=RENDERING_BY_EXTRA[extra]) for extra in needed_extras+ }+ scored_models = {model.entry.key: _score_model(model, ids, vectors_by_extra) for model in models}+ served_key = serving.manifest.served.key+ served_vectors = vectors_by_extra[served_extra]++ outcomes: list[ReportScoringOutcome] = []+ for report_id in ids:+ if report_id not in scored_models[served_key].by_report:+ outcomes.append(ReportScoringOutcome(report_id=report_id, score=None, reason=NO_VECTOR))+ continue+ results: dict[str, RankingModelResult] = {}+ for entry in serving.manifest.models:+ if entry.key in scored_models:+ results[entry.key] = _result(scored_models[entry.key], report_id)+ else:+ results[entry.key] = _unloaded_result(entry, serving.skipped[entry.key])+ score = RankingScore(+ scored_at=now,+ embedding_inserted_at=served_vectors[report_id].inserted_at,+ manifest_version=serving.manifest.manifest_version,+ served_key=served_key,+ results=results,+ )+ outcomes.append(ReportScoringOutcome(report_id=report_id, score=score, reason=None))++ if persist:+ persist_scores(team_id, [(outcome.report_id, outcome.score) for outcome in outcomes if outcome.score])+ return outcomesdiff --git a/products/signals/backend/ranking/sinks.py b/products/signals/backend/ranking/sinks.pynew file mode 100644index 000000000000..9a060e2fcea3--- /dev/null+++ b/products/signals/backend/ranking/sinks.py@@ -0,0 +1,68 @@+"""Where a scoring pass writes: one `ranking_score` artefact per report, and one event per model.++`ranking_score` is in `NON_WRITABLE_ARTEFACT_TYPES`, so this system path is its only writer. The+events go to PostHog's own project, where the inbox label streams join them on `report_id` like+every other ranking event.+"""++from collections.abc import Sequence++from django.conf import settings++from posthog.ph_client import ph_scoped_capture++from products.signals.backend.artefact_schemas import RankingScore+from products.signals.backend.models import SignalActorKind, SignalReport, SignalReportArtefact++REPORT_SCORED_EVENT = "inbox_ranking_report_scored"+DISTINCT_ID = "inbox_ranking_scoring"+++def persist_scores(team_id: int, scores: Sequence[tuple[str, RankingScore]]) -> int:+ """Write one artefact per `(report_id, score)` of the team, then capture its events.++ A report id that is not one of the team's reports is dropped. Returns the rows written.+ """+ report_ids = [report_id for report_id, _ in scores]+ owned = {+ str(report_id)+ for report_id in SignalReport.objects.filter(team_id=team_id, id__in=report_ids).values_list("id", flat=True)+ }+ kept = [(report_id, score) for report_id, score in scores if report_id in owned]+ SignalReportArtefact.objects.bulk_create(+ [+ SignalReportArtefact(+ team_id=team_id,+ report_id=report_id,+ type=SignalReportArtefact.ArtefactType.RANKING_SCORE,+ content=score.model_dump_json(),+ actor_kind=SignalActorKind.SYSTEM,+ )+ for report_id, score in kept+ ]+ )+ with ph_scoped_capture() as capture:+ for report_id, score in kept:+ for model_key, result in score.results.items():+ capture(+ distinct_id=DISTINCT_ID,+ event=REPORT_SCORED_EVENT,+ properties={+ "$process_person_profile": False,+ "environment": settings.CLOUD_DEPLOYMENT,+ "team_id": team_id,+ "report_id": report_id,+ "model_key": model_key,+ "model_name": result.model_name,+ "model_version": result.model_version,+ "roles": result.roles,+ "status": result.status,+ "skip_reason": result.skip_reason,+ "manifest_version": score.manifest_version,+ "embedding_inserted_at": score.embedding_inserted_at.isoformat()+ if score.embedding_inserted_at+ else None,+ **{f"p_{head}": probability for head, probability in result.scores.items()},+ },+ )+ return len(kept)diff --git a/products/signals/backend/report_embedding_reader.py b/products/signals/backend/report_embedding_reader.pynew file mode 100644index 000000000000..27b4a62d5027--- /dev/null+++ b/products/signals/backend/report_embedding_reader.py@@ -0,0 +1,98 @@+"""Reads the current vector of each report, for the ranking scorer.++`report_embeddings.py` writes one `document_embeddings` row per rendering of a report. The dataset+dag snapshots every report's latest row fleet-wide with `REPORT_EMBEDDINGS_SQL`. The scorer needs+the same latest row for a few reports of one team, so this read is that query with the team and+the report ids added. The team id is the table's sort-key prefix, so the read is a point read and+not a full scan.+"""++import datetime+from collections.abc import Sequence+from typing import Any, cast++from django.conf import settings++import numpy as np++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.client.connection import Workload+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.dataclasses import frozen++from products.signals.backend.ranking.features import EMBEDDING_DIMENSIONS+from products.signals.backend.report_embeddings import EMBEDDING_DOCUMENT_TYPE, EMBEDDING_PRODUCT++# The text-embedding-3-small-1536 table, which is the model the report documents are embedded with.+REPORT_EMBEDDINGS_TABLE = "distributed_posthog_document_embeddings_text_embedding_3_small_1536"++LATEST_REPORT_VECTORS_SQL = f"""+SELECT+ document_id,+ argMax(embedding, inserted_at) AS embedding,+ argMax(JSONExtractBool(metadata, 'deleted'), inserted_at) AS is_tombstone,+ max(inserted_at) AS embedding_inserted_at+FROM {REPORT_EMBEDDINGS_TABLE}+WHERE team_id = %(team_id)s+ AND product = %(product)s+ AND document_type = %(document_type)s+ AND rendering = %(rendering)s+ AND document_id IN %(report_ids)s+GROUP BY document_id+"""+++@frozen+class ReportVector:+ # float32, EMBEDDING_DIMENSIONS wide.+ embedding: np.ndarray+ inserted_at: datetime.datetime+++def latest_report_vectors(team_id: int, report_ids: Sequence[str], *, rendering: str) -> dict[str, ReportVector]:+ """The newest vector of each report in `rendering`, keyed by report id.++ A report whose newest row is a tombstone is absent, and so is a report with no row. An older+ live row never stands in for a tombstone, because the aggregate takes the newest row only. A+ vector of another width is from another model, so it is absent too. One query per batch of+ `INBOX_RANKING_SCORING_BATCH_SIZE` ids.+ """+ ids = list(dict.fromkeys(str(report_id) for report_id in report_ids))+ batch_size = settings.INBOX_RANKING_SCORING_BATCH_SIZE+ vectors: dict[str, ReportVector] = {}+ for start in range(0, len(ids), batch_size):+ tag_queries(+ product=Product.SIGNALS,+ feature=Feature.ENRICHMENT,+ team_id=team_id,+ query_type="inbox_ranking_report_vectors",+ )+ rows = cast(+ list[tuple[Any, ...]],+ sync_execute(+ LATEST_REPORT_VECTORS_SQL,+ {+ "team_id": team_id,+ "product": EMBEDDING_PRODUCT,+ "document_type": EMBEDDING_DOCUMENT_TYPE,+ "rendering": rendering,+ "report_ids": ids[start : start + batch_size],+ },+ workload=Workload.OFFLINE,+ team_id=team_id,+ )+ or [],+ )+ for document_id, embedding, is_tombstone, inserted_at in rows:+ if is_tombstone or len(embedding) != EMBEDDING_DIMENSIONS:+ continue+ vectors[str(document_id)] = ReportVector(+ embedding=np.asarray(embedding, dtype=np.float32),+ inserted_at=_utc(inserted_at),+ )+ return vectors+++def _utc(value: datetime.datetime) -> datetime.datetime:+ # ClickHouse returns a naive DateTime in UTC.+ return value.replace(tzinfo=datetime.UTC) if value.tzinfo is None else value.astimezone(datetime.UTC)diff --git a/products/signals/backend/test/test_ranking_scoring.py b/products/signals/backend/test/test_ranking_scoring.pynew file mode 100644index 000000000000..6a94f2887521--- /dev/null+++ b/products/signals/backend/test/test_ranking_scoring.py@@ -0,0 +1,454 @@+import json+import datetime+from collections.abc import Iterator, Mapping, Sequence+from contextlib import contextmanager+from typing import Any++from posthog.test.base import BaseTest, ClickhouseTestMixin+from unittest.mock import patch++from django.test import SimpleTestCase, override_settings++import numpy as np+import pandas as pd+import xgboost as xgb+from parameterized import parameterized++from posthog.clickhouse.client import sync_execute+from posthog.models import Team++from products.signals.backend.artefact_schemas import RankingScore+from products.signals.backend.models import SignalReport, SignalReportArtefact+from products.signals.backend.ranking import model_store, scorer+from products.signals.backend.ranking.features import (+ EMBEDDING_DIMENSIONS,+ REPORT_EMBEDDINGS_EXTRA,+ REPORT_EMBEDDINGS_FEATURE_SET,+ TABULAR_FEATURE_SET,+ TITLE_EMBEDDINGS_FEATURE_SET,+ FeatureSet,+)+from products.signals.backend.ranking.model_store import ModelLoadError, load_serving_set+from products.signals.backend.ranking.scorer import NO_VECTOR, score_reports+from products.signals.backend.ranking.serving_manifest import (+ CROSS_FAMILY_ROLE,+ DAILY_CANDIDATE_ROLE,+ METADATA_FILE,+ SERVED_ROLE,+ ServingManifest,+ ServingManifestEntry,+ model_key,+ serving_manifest_key,+ serving_model_prefix,+)+from products.signals.backend.ranking.sinks import REPORT_SCORED_EVENT+from products.signals.backend.report_embedding_reader import (+ REPORT_EMBEDDINGS_TABLE,+ ReportVector,+ latest_report_vectors,+)+from products.signals.backend.report_embeddings import EMBEDDING_RENDERING_TITLE, EMBEDDING_RENDERING_TITLE_SUMMARY+from products.signals.dags.inbox_ranking.training.unseen import UnseenModel, score_pool++PREFIX = "inbox_ranking_test"+VERSION = "2026-09-01"+OLDER_VERSION = "2026-08-25"+NOW = datetime.datetime(2026, 9, 2, 12, 0, tzinfo=datetime.UTC)+LANDED = datetime.datetime(2026, 9, 2, 9, 0, tzinfo=datetime.UTC)+HEADS = ("open", "thumbs_up")++_BOOSTERS: dict[tuple[str, ...], bytes] = {}+++def _booster_ubj(feature_names: tuple[str, ...]) -> bytes:+ if feature_names not in _BOOSTERS:+ rows = 20+ rng = np.random.default_rng(0)+ x = pd.DataFrame(rng.normal(size=(rows, len(feature_names))), columns=list(feature_names))+ model = xgb.XGBClassifier(n_estimators=3, max_depth=2)+ model.fit(x, np.arange(rows) % 2)+ _BOOSTERS[feature_names] = bytes(model.get_booster().save_raw("ubj"))+ return _BOOSTERS[feature_names]+++def _vector(seed: int) -> np.ndarray:+ return np.random.default_rng(seed).normal(size=EMBEDDING_DIMENSIONS).astype(np.float32)+++class FakeObjectStore:+ def __init__(self) -> None:+ self.objects: dict[str, bytes] = {}+ self.reads: list[str] = []++ def read_bytes(self, file_name: str, bucket: str | None = None, *, missing_ok: bool = False) -> bytes | None:+ self.reads.append(file_name)+ return self.objects.get(file_name)++ def read(self, file_name: str, bucket: str | None = None, *, missing_ok: bool = False) -> str | None:+ body = self.read_bytes(file_name, bucket, missing_ok=missing_ok)+ return None if body is None else body.decode()++ def publish_model(+ self,+ model_name: str,+ feature_set: FeatureSet,+ *,+ version: str = VERSION,+ roles: Sequence[str] = (SERVED_ROLE,),+ model_kind: str = "xgboost",+ booster_feature_names: tuple[str, ...] | None = None,+ missing_heads: Sequence[str] = (),+ ) -> ServingManifestEntry:+ key = model_key(model_name, version)+ prefix = serving_model_prefix(PREFIX, key)+ metadata = {+ "model_name": model_name,+ "model_version": version,+ "model_kind": model_kind,+ "feature_set": feature_set.name,+ "feature_schema_version": feature_set.schema_version,+ "feature_names": list(feature_set.feature_names),+ "heads": [{"head": head, "file": f"{head}.ubj", "readable": head == "open"} for head in HEADS],+ }+ self.objects[f"{prefix}/{METADATA_FILE}"] = json.dumps(metadata).encode()+ booster = _booster_ubj(booster_feature_names or feature_set.feature_names)+ for head in HEADS:+ if head not in missing_heads:+ self.objects[f"{prefix}/{head}.ubj"] = booster+ return ServingManifestEntry(+ key=key,+ model_name=model_name,+ model_version=version,+ model_kind=model_kind,+ roles=list(roles),+ prefix=prefix,+ heads=list(HEADS),+ )++ def publish_manifest(self, entries: Sequence[ServingManifestEntry]) -> ServingManifest:+ manifest = ServingManifest(manifest_version=NOW.isoformat(), models=list(entries))+ self.objects[serving_manifest_key(PREFIX)] = manifest.model_dump_json().encode()+ return manifest+++class _StoreTestMixin:+ def setUp(self) -> None:+ super().setUp() # type: ignore[misc]+ model_store.clear_model_cache()+ self.store = FakeObjectStore()+ for name in ("read", "read_bytes"):+ patcher = patch.object(model_store.object_storage, name, getattr(self.store, name))+ patcher.start()+ self.addCleanup(patcher.stop) # type: ignore[attr-defined]+ settings_override = override_settings(INBOX_RANKING_DATASET_S3_PREFIX=PREFIX)+ settings_override.enable()+ self.addCleanup(settings_override.disable) # type: ignore[attr-defined]+ self.addCleanup(model_store.clear_model_cache) # type: ignore[attr-defined]++ def _served(self, **kwargs: Any) -> ServingManifestEntry:+ return self.store.publish_model("report_embeddings", REPORT_EMBEDDINGS_FEATURE_SET, **kwargs)++ def _challenger(self, model_name: str, feature_set: FeatureSet, **kwargs: Any) -> ServingManifestEntry:+ return self.store.publish_model(model_name, feature_set, roles=[CROSS_FAMILY_ROLE], **kwargs)+++class TestModelStore(_StoreTestMixin, SimpleTestCase):+ def test_no_manifest_is_no_serving_set(self) -> None:+ assert load_serving_set() is None++ @parameterized.expand(+ [+ ("booster_on_other_features", {"booster_feature_names": TABULAR_FEATURE_SET.feature_names}, "booster"),+ ("missing_head_file", {"missing_heads": ["thumbs_up"]}, "thumbs_up.ubj"),+ ("unknown_model_kind", {"model_kind": "torch"}, "torch"),+ ]+ )+ def test_a_served_entry_that_cannot_load_raises(self, _name: str, kwargs: dict, reason: str) -> None:+ self.store.publish_manifest([self._served(**kwargs)])+ with self.assertRaisesRegex(ModelLoadError, reason):+ load_serving_set()++ @parameterized.expand(+ [+ ("booster_on_other_features", {"booster_feature_names": TABULAR_FEATURE_SET.feature_names}, "booster"),+ ("missing_head_file", {"missing_heads": ["thumbs_up"]}, "thumbs_up.ubj"),+ ("unknown_model_kind", {"model_kind": "torch"}, "torch"),+ ]+ )+ def test_a_challenger_that_cannot_load_is_skipped(self, _name: str, kwargs: dict, reason: str) -> None:+ served = self._served()+ challenger = self._challenger("title_embeddings", TITLE_EMBEDDINGS_FEATURE_SET, **kwargs)+ self.store.publish_manifest([served, challenger])++ serving = load_serving_set()++ assert serving is not None+ assert serving.served.entry.key == served.key+ assert serving.others == []+ assert reason in serving.skipped[challenger.key]++ def test_a_loaded_key_is_not_read_again_but_takes_the_new_roles(self) -> None:+ served = self._served()+ self.store.publish_manifest([served])+ load_serving_set()+ model_reads = [key for key in self.store.reads if key != serving_manifest_key(PREFIX)]++ self.store.publish_manifest([served.model_copy(update={"roles": [SERVED_ROLE, DAILY_CANDIDATE_ROLE]})])+ serving = load_serving_set()++ assert serving is not None+ assert [key for key in self.store.reads if key != serving_manifest_key(PREFIX)] == model_reads+ assert serving.served.entry.roles == [SERVED_ROLE, DAILY_CANDIDATE_ROLE]+++class _FakeVectors:+ def __init__(self, vectors_by_rendering: Mapping[str, Mapping[str, ReportVector]]) -> None:+ self.vectors_by_rendering = vectors_by_rendering+ self.calls: list[str] = []++ def __call__(self, team_id: int, report_ids: Sequence[str], *, rendering: str) -> dict[str, ReportVector]:+ self.calls.append(rendering)+ vectors = self.vectors_by_rendering.get(rendering, {})+ return {report_id: vectors[report_id] for report_id in report_ids if report_id in vectors}+++class _Captured:+ def __init__(self) -> None:+ self.events: list[dict[str, Any]] = []++ @contextmanager+ def __call__(self) -> Iterator[Any]:+ yield lambda **kwargs: self.events.append(kwargs)+++class _ScorerTestMixin(_StoreTestMixin):+ def _score(+ self, report_ids: Sequence[str], vectors: Mapping[str, Mapping[str, ReportVector]], *, persist: bool+ ) -> tuple[list[scorer.ReportScoringOutcome], _FakeVectors, _Captured]:+ fake_vectors = _FakeVectors(vectors)+ captured = _Captured()+ with (+ patch.object(scorer, "latest_report_vectors", fake_vectors),+ patch("products.signals.backend.ranking.sinks.ph_scoped_capture", captured),+ ):+ outcomes = score_reports(self.team_id, report_ids, persist=persist, now=NOW)+ return outcomes, fake_vectors, captured++ team_id = 1+++class TestScorer(_ScorerTestMixin, SimpleTestCase):+ def test_a_served_score_equals_the_dags_unseen_score_for_the_same_model_and_vector(self) -> None:+ served = self._served()+ self.store.publish_manifest([served])+ vector = _vector(1)++ (outcome,), _, _ = self._score(+ ["r1"],+ {EMBEDDING_RENDERING_TITLE_SUMMARY: {"r1": ReportVector(embedding=vector, inserted_at=LANDED)}},+ persist=False,+ )++ pool = pd.DataFrame(+ {+ "report_created_at": [pd.Timestamp(LANDED)],+ "report_age_hours": [3.0],+ "signal_count": [2],+ },+ index=pd.Index(["r1"], name="report_id"),+ )+ extras = {+ REPORT_EMBEDDINGS_EXTRA: pd.DataFrame(+ {"embedding_small": [list(vector)], "embedding_inserted_at": [LANDED]},+ index=pd.Index(["r1"], name="report_id"),+ )+ }+ booster = self.store.objects[f"{served.prefix}/open.ubj"]+ dag_scores = score_pool(+ pool,+ pd.DataFrame({"open_count": [0], "impression_unit_count": [1]}, index=pool.index),+ [+ UnseenModel(+ model_name=served.model_name,+ model_version=served.model_version,+ model_role="champion",+ feature_set=REPORT_EMBEDDINGS_FEATURE_SET,+ boosters={"open": booster},+ )+ ],+ snapshot_date=LANDED.date(),+ extras=extras,+ )++ assert outcome.score is not None+ assert outcome.score.results[served.key].scores["open"] == float(dag_scores["score"].iloc[0])++ def test_a_missing_served_vector_is_no_score(self) -> None:+ self.store.publish_manifest([self._served()])++ outcomes, _, _ = self._score(["r1"], {}, persist=False)++ assert [(outcome.score, outcome.reason) for outcome in outcomes] == [(None, NO_VECTOR)]++ def test_one_vector_read_per_rendering_whatever_the_number_of_models(self) -> None:+ served = self._served()+ candidate = self.store.publish_model(+ "report_embeddings", REPORT_EMBEDDINGS_FEATURE_SET, version=OLDER_VERSION, roles=[DAILY_CANDIDATE_ROLE]+ )+ title = self._challenger("title_embeddings", TITLE_EMBEDDINGS_FEATURE_SET)+ self.store.publish_manifest([served, candidate, title])++ _, fake_vectors, _ = self._score(["r1", "r2"], {}, persist=False)++ assert sorted(fake_vectors.calls) == sorted([EMBEDDING_RENDERING_TITLE_SUMMARY, EMBEDDING_RENDERING_TITLE])++ def test_challengers_without_a_vector_or_a_served_feature_set_are_skipped_results(self) -> None:+ served = self._served()+ title = self._challenger("title_embeddings", TITLE_EMBEDDINGS_FEATURE_SET)+ tabular = self._challenger("tabular_xgb", TABULAR_FEATURE_SET)+ manifest = self.store.publish_manifest([served, title, tabular])++ (outcome,), _, captured = self._score(+ ["r1"],+ {EMBEDDING_RENDERING_TITLE_SUMMARY: {"r1": ReportVector(embedding=_vector(1), inserted_at=LANDED)}},+ persist=False,+ )++ assert outcome.score is not None+ results = outcome.score.results+ assert (results[served.key].status, set(results[served.key].scores)) == ("scored", set(HEADS))+ assert (results[title.key].status, results[title.key].skip_reason) == ("skipped", NO_VECTOR)+ assert (results[tabular.key].status, results[tabular.key].skip_reason) == (+ "skipped",+ "feature set tabular is not served yet",+ )+ assert outcome.score.served_key == manifest.served.key+ assert outcome.score.embedding_inserted_at == LANDED+ assert captured.events == []+++class TestScorerPersists(_ScorerTestMixin, BaseTest):+ def _report(self, team_id: int) -> str:+ return str(SignalReport.objects.create(team_id=team_id, status=SignalReport.Status.READY, title="A").id)++ def test_persist_writes_one_valid_row_per_scored_report_of_the_team(self) -> None:+ self.team_id = self.team.id+ served = self._served()+ title = self._challenger("title_embeddings", TITLE_EMBEDDINGS_FEATURE_SET)+ manifest = self.store.publish_manifest([served, title])+ scored, unscored = self._report(self.team.id), self._report(self.team.id)+ other_team = Team.objects.create(organization=self.organization)+ foreign = self._report(other_team.id)+ vector = ReportVector(embedding=_vector(1), inserted_at=LANDED)++ outcomes, _, captured = self._score(+ [scored, unscored, foreign],+ {+ EMBEDDING_RENDERING_TITLE_SUMMARY: {scored: vector, foreign: vector},+ EMBEDDING_RENDERING_TITLE: {scored: vector},+ },+ persist=True,+ )++ assert {outcome.report_id: outcome.reason for outcome in outcomes} == {+ scored: None,+ unscored: NO_VECTOR,+ foreign: None,+ }+ rows = list(SignalReportArtefact.objects.filter(type=SignalReportArtefact.ArtefactType.RANKING_SCORE))+ assert [(str(row.report_id), row.team_id) for row in rows] == [(scored, self.team.id)]+ score = RankingScore.model_validate_json(rows[0].content)+ assert score.served_key == manifest.served.key+ assert score.results[title.key].status == "scored"+ assert sorted(+ (event["event"], event["properties"]["report_id"], event["properties"]["model_key"])+ for event in captured.events+ ) == sorted([(REPORT_SCORED_EVENT, scored, served.key), (REPORT_SCORED_EVENT, scored, title.key)])++ def test_without_persist_nothing_is_written_or_captured(self) -> None:+ self.team_id = self.team.id+ self.store.publish_manifest([self._served()])+ report = self._report(self.team.id)++ (outcome,), _, captured = self._score(+ [report],+ {EMBEDDING_RENDERING_TITLE_SUMMARY: {report: ReportVector(embedding=_vector(1), inserted_at=LANDED)}},+ persist=False,+ )++ assert outcome.score is not None+ assert not SignalReportArtefact.objects.filter(type=SignalReportArtefact.ArtefactType.RANKING_SCORE).exists()+ assert captured.events == []+++class TestLatestReportVectors(ClickhouseTestMixin, BaseTest):+ def setUp(self) -> None:+ super().setUp()+ sync_execute(f"TRUNCATE TABLE {REPORT_EMBEDDINGS_TABLE}", flush=False, team_id=self.team.pk)+ self.base = (datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=2)).replace(microsecond=0)++ def _emit(+ self, *, team_id: int, report_id: str, hours: int, deleted: bool = False, rendering: str | None = None+ ) -> None:+ at = self.base + datetime.timedelta(hours=hours)+ sync_execute(+ f"""+ INSERT INTO {REPORT_EMBEDDINGS_TABLE} (+ team_id, product, document_type, rendering, document_id,+ timestamp, inserted_at, content, metadata, embedding,+ _timestamp, _offset, _partition+ ) VALUES+ """,+ [+ (+ team_id,+ "signals",+ "report",+ rendering or EMBEDDING_RENDERING_TITLE_SUMMARY,+ report_id,+ self.base,+ at,+ "a report",+ json.dumps({"deleted": deleted}),+ [float(hours)] * EMBEDDING_DIMENSIONS,+ at,+ 0,+ 0,+ )+ ],+ flush=False,+ team_id=team_id,+ )++ def test_reads_the_newest_live_row_of_the_team_only(self) -> None:+ self._emit(team_id=self.team.pk, report_id="live", hours=1)+ self._emit(team_id=self.team.pk, report_id="live", hours=2)+ self._emit(team_id=self.team.pk, report_id="retracted", hours=1)+ self._emit(team_id=self.team.pk, report_id="retracted", hours=2, deleted=True)+ self._emit(team_id=self.team.pk, report_id="title_only", hours=1, rendering=EMBEDDING_RENDERING_TITLE)+ self._emit(team_id=self.team.pk + 1, report_id="foreign", hours=1)++ vectors = latest_report_vectors(+ self.team.pk,+ ["live", "retracted", "title_only", "foreign", "absent"],+ rendering=EMBEDDING_RENDERING_TITLE_SUMMARY,+ )++ assert list(vectors) == ["live"]+ assert vectors["live"].embedding[0] == 2.0+ assert vectors["live"].inserted_at == self.base + datetime.timedelta(hours=2)++ @parameterized.expand([("one_batch", 500, 1), ("paged", 2, 2)])+ def test_reads_in_batches_of_the_configured_size(self, _name: str, batch_size: int, queries: int) -> None:+ for index in range(3):+ self._emit(team_id=self.team.pk, report_id=f"r{index}", hours=1)++ with (+ override_settings(INBOX_RANKING_SCORING_BATCH_SIZE=batch_size),+ patch("products.signals.backend.report_embedding_reader.sync_execute", wraps=sync_execute) as spy,+ ):+ vectors = latest_report_vectors(+ self.team.pk, ["r0", "r1", "r2"], rendering=EMBEDDING_RENDERING_TITLE_SUMMARY+ )++ assert (sorted(vectors), spy.call_count) == (["r0", "r1", "r2"], queries)diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex 8c0a825d2a6e..f5e7f2322bd2 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -107,6 +107,8 @@ s3://<object-storage bucket>/<prefix>/serving/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.+The reader is `score_reports` in `products/signals/backend/ranking/scorer.py`. It loads every model the manifest names through `model_store.py`, reads each report's latest vector once per rendering, builds each model's matrix with its own `FeatureSet.build_matrix`, and writes one `ranking_score` artefact per report plus one `inbox_ranking_report_scored` event per report and model. The dag and the reader decide whether a model can be scored with the same functions, in `products/signals/backend/ranking/model_contract.py`. A served model that cannot load stops the pass. Any other model that cannot load, or has no vector for a report, is a `skipped` result. The embedding families are the only ones served, so a tabular entry is a `skipped` result too. No scheduled caller runs the reader yet.+### Outcome heads| Head | Cohort at the horizon | Horizon (days) |@@ -237,6 +239,7 @@ Like the dataset job, this one reads the dogfood project's ClickHouse, so it can| `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. |+| `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/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.pyindex c4e213057579..dde058174f34 100644--- a/products/signals/dags/inbox_ranking/tests/test_training.py+++ b/products/signals/dags/inbox_ranking/tests/test_training.py@@ -40,6 +40,7 @@ from products.signals.backend.ranking.features import (feature_set_by_name,feature_vector,)+from products.signals.backend.ranking.model_contract import model_mismatch, readable_head_names, trained_head_filesfrom products.signals.backend.ranking.serving_manifest import (CROSS_FAMILY_ROLE,DAILY_CANDIDATE_ROLE,@@ -132,13 +133,10 @@ from products.signals.dags.inbox_ranking.training.unseen import (graded_rows,head_grades,leaked_report_ids,- model_mismatch,- readable_head_names,report_grade_rows,score_event_rows,score_pool,scored_pool,- trained_head_files,unseen_pool,with_model_names,)@@ -1528,7 +1526,7 @@ def test_an_unreadable_trained_head_is_still_scored_and_graded():{"head": "thumbs_up", "file": "thumbs_up.ubj", "readable": False},]}- assert trained_head_files(metadata) == {"open": "open.ubj", "thumbs_up": "thumbs_up.ubj"}+ assert trained_head_files(metadata, HEADS_BY_NAME) == {"open": "open.ubj", "thumbs_up": "thumbs_up.ubj"}assert readable_head_names(metadata) == frozenset({"open"})booster = _booster_ubj(tuple(TABULAR_FEATURE_SET.feature_names))diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pyindex 4ae378810752..c785d159da9d 100644--- a/products/signals/dags/inbox_ranking/training/dag.py+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -65,6 +65,12 @@ from products.signals.backend.ranking.features import (Extras,FeatureSet,)+from products.signals.backend.ranking.model_contract import (+ model_feature_set,+ model_mismatch,+ readable_head_names,+ trained_head_files,+)from products.signals.backend.ranking.serving_manifest import DEFAULT_MODEL_KIND, ServingManifest, serving_manifest_keyfrom products.signals.dags.inbox_ranking.common import (DATASET_VERSION,@@ -139,15 +145,11 @@ from products.signals.dags.inbox_ranking.training.unseen import (head_grades,leaked_report_ids,missing_label_columns,- model_feature_set,- model_mismatch,- readable_head_names,report_grade_rows,score_event_rows,score_pool,scored_pool,scores_table,- trained_head_files,unseen_pool,with_model_names,)@@ -971,7 +973,7 @@ def load_family_models(context.log.warning(f"{model_name} {role} {metadata.get('model_version')} not scored: {mismatch}")continueboosters = {}- for head_name, filename in trained_head_files(metadata).items():+ for head_name, filename in trained_head_files(metadata, HEADS_BY_NAME).items():body = _read_bytes_if_exists(client, bucket, model_object_key(prefix, model_name, metadata["model_version"], filename))diff --git a/products/signals/dags/inbox_ranking/training/serving.py b/products/signals/dags/inbox_ranking/training/serving.pyindex 2141f8bfa1aa..2c6f61cafddd 100644--- a/products/signals/dags/inbox_ranking/training/serving.py+++ b/products/signals/dags/inbox_ranking/training/serving.py@@ -16,6 +16,7 @@ from typing import Anyfrom posthog.dataclasses import frozenfrom products.signals.backend.artefact_schemas import MAX_RANKING_MODEL_RESULTS+from products.signals.backend.ranking.model_contract import readable_head_names, trained_head_filesfrom products.signals.backend.ranking.serving_manifest import (CROSS_FAMILY_ROLE,DAILY_CANDIDATE_ROLE,@@ -26,7 +27,7 @@ from products.signals.backend.ranking.serving_manifest import (model_key,serving_model_prefix,)-from products.signals.dags.inbox_ranking.training.unseen import readable_head_names, trained_head_files+from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME@frozen@@ -58,7 +59,7 @@ def _entry() -> ServingManifestEntry | None:"""One manifest entry, or None when the model has no head a store could load. Only the refitboosters are named: the holdout fits grade a promotion and never serve."""- heads = sorted(trained_head_files(metadata))+ heads = sorted(trained_head_files(metadata, HEADS_BY_NAME))if not heads:return Nonekey = model_key(metadata["model_name"], metadata["model_version"])diff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.pyindex 55bb4faa41a0..1c2abe11f564 100644--- a/products/signals/dags/inbox_ranking/training/unseen.py+++ b/products/signals/dags/inbox_ranking/training/unseen.py@@ -30,7 +30,6 @@ from products.signals.backend.ranking.features import (TITLE_EMBEDDINGS_FEATURE_SET,Extras,FeatureSet,- feature_set_by_name,)from products.signals.dags.inbox_ranking.common import snapshot_boundsfrom products.signals.dags.inbox_ranking.training.calibration import (@@ -253,50 +252,6 @@ def chance_band(outcomes: np.ndarray, scores: np.ndarray) -> ChanceBand:return ChanceBand(auc=float(np.mean(aucs)), auc_std=float(np.std(aucs)))-def model_feature_set(metadata: Mapping[str, Any]) -> FeatureSet | None:- """The feature set the model declares, or None when this build cannot produce it. Metadata- written before the field existed declares nothing and reads as the tabular set."""- return feature_set_by_name(metadata.get("feature_set"))---def model_mismatch(metadata: Mapping[str, Any]) -> str | None:- """Why the model cannot be scored, or None when it can.-- A model is checked against its own declared set rather than one global contract, so a family- on a richer set is not rejected for disagreeing with the tabular one.- """- feature_set = model_feature_set(metadata)- if feature_set is None:- return f"feature set {metadata.get('feature_set')} is not one this build can produce"- version = metadata.get("feature_schema_version")- if version != feature_set.schema_version:- return f"feature_schema_version {version} is not {feature_set.name}'s {feature_set.schema_version}"- if tuple(metadata.get("feature_names") or ()) != feature_set.feature_names:- return f"feature_names differ from the {feature_set.name} feature set"- return None---def readable_head_names(metadata: Mapping[str, Any]) -> frozenset[str]:- """The heads of a model whose holdout AUC could be read."""- return frozenset(entry["head"] for entry in metadata.get("heads", []) if entry.get("readable"))---def trained_head_files(metadata: Mapping[str, Any]) -> dict[str, str]:- """The `<head>.ubj` object name per head the candidate fit.-- Every trained head is scored, readable or not. A rare head never clears `min_holdout_positives`- on one day's holdout, and the pooled newborn grade over many days is the only read that can- ever give it a number; gating the scoring on readability means that read never starts. An- unreadable head has no holdout AUC to compare against, so read its grade on its own, and the- promotion gate still ignores it.- """- return {- entry["head"]: entry["file"]- for entry in metadata.get("heads", [])- if entry.get("file") and entry.get("head") in HEADS_BY_NAME- }--def unseen_pool(state: pd.DataFrame, snapshot_date: datetime.date) -> pd.DataFrame:"""The dt=D state rows of the reports created on D.