: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): serve team project vectors to the inbox ranking sweep (#116641)
posthog[bot]e860edb4788e
diff --git a/products/signals/backend/ranking/features.py b/products/signals/backend/ranking/features.pyindex cd89f32ab8e4..cd549a6f61de 100644--- a/products/signals/backend/ranking/features.py+++ b/products/signals/backend/ranking/features.py@@ -15,12 +15,14 @@ vector at scoring time and needs nothing else from the report.import abcimport datetime-from collections.abc import Mapping+from collections.abc import Mapping, Sequencefrom types import MappingProxyTypeimport numpy as npimport pandas as pd+from posthog.dataclasses import frozen+# Side inputs a set may read next to the report-state rows, keyed by name and indexed by# report_id.Extras = Mapping[str, pd.DataFrame]@@ -41,6 +43,14 @@ EMBEDDING_INSERTED_AT_COLUMN = "embedding_inserted_at"# row whose vector is a different length is not this model's, so it is treated as missing.EMBEDDING_DIMENSIONS = 1536+# The team's project-vector kinds, in the order a network that reads them takes them. The dataset+# dag's `inbox_project_vectors` writes one row per (team, kind), and the training and serving+# inputs both read these names, so the two sides cannot order the kinds differently.+PROJECT_VECTOR_KINDS = ("typical", "open", "action", "dismiss")+# Below this many reports, a kind's mean is mostly one report's text, so the row keeps an all-zero+# vector and the kind has no history.+MIN_PROJECT_HISTORY_REPORTS = 5+# How many rows one report contributes to a head's examples. The default is `birth`, one row per# report at the snapshot of the day it was created; `examples.py` holds the reasoning.# `scoring_moment` is one row per (report, snapshot), and `report` is the first snapshot of the@@ -209,6 +219,43 @@ FEATURE_SETS: Mapping[str, FeatureSet] = MappingProxyType()+@frozen+class ProjectInputs:+ """The project vectors of some teams, one row per team in the order the caller asked for."""++ # (teams, kinds, EMBEDDING_DIMENSIONS) float32, in `PROJECT_VECTOR_KINDS` order. All zero where+ # the team has no row for the kind or its history is too thin.+ vectors: np.ndarray+ # (teams, kinds) float32, 1.0 where the kind had at least `MIN_PROJECT_HISTORY_REPORTS` reports.+ has_history: np.ndarray+++def project_inputs(project_vectors: pd.DataFrame, team_ids: Sequence[int]) -> ProjectInputs:+ """The project vectors of `team_ids` from one day of `inbox_project_vectors`.++ `project_vectors` carries the `team_id`, `kind`, `vector` and `n_reports` columns of that table.+ Training and serving both build the network's `project` and `has_history` inputs here, so a+ team without a row, a kind without a row and a thin kind read the same on both sides.+ """+ position = {int(team_id): index for index, team_id in enumerate(team_ids)}+ vectors = np.zeros((len(team_ids), len(PROJECT_VECTOR_KINDS), EMBEDDING_DIMENSIONS), dtype=np.float32)+ has_history = np.zeros((len(team_ids), len(PROJECT_VECTOR_KINDS)), dtype=np.float32)+ for team_id, kind, vector, n_reports in zip(+ project_vectors["team_id"],+ project_vectors["kind"],+ project_vectors["vector"],+ project_vectors["n_reports"],+ strict=True,+ ):+ team = position.get(int(team_id))+ if team is None or kind not in PROJECT_VECTOR_KINDS:+ continue+ kind_index = PROJECT_VECTOR_KINDS.index(kind)+ vectors[team, kind_index] = vector+ has_history[team, kind_index] = float(int(n_reports) >= MIN_PROJECT_HISTORY_REPORTS)+ return ProjectInputs(vectors=vectors, has_history=has_history)++def feature_set_by_name(name: str | None) -> FeatureSet | None:"""The named set, or None when the name is absent or this build cannot produce it."""return None if name is None else FEATURE_SETS.get(name)diff --git a/products/signals/backend/ranking/model_store.py b/products/signals/backend/ranking/model_store.pyindex 7e1e7211e895..5fede0dbe64b 100644--- a/products/signals/backend/ranking/model_store.py+++ b/products/signals/backend/ranking/model_store.py@@ -8,27 +8,38 @@ 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 loadedmodel is cached in the process by key with no invalidation. The manifest itself is read on everycall, because a promotion changes it in place.++A model that reads its team's project vectors reads them from the one day the manifest names+(`load_project_vectors`). The sweep reads that day once per pass, for the teams it scores."""from __future__ import annotations+import ioimport jsonimport threadingfrom collections import OrderedDict-from collections.abc import Callable, Mapping, Sequence+from collections.abc import Collection, Mapping, Sequencefrom dataclasses import replacefrom typing import Any, Protocolfrom django.conf import settingsimport numpy as np+import pandas as pdimport structlogfrom posthog.dataclasses import frozenfrom posthog.storage import object_storagefrom products.signals.backend.artefact_schemas import MAX_RANKING_MODEL_RESULTS-from products.signals.backend.ranking.features import FeatureSet+from products.signals.backend.ranking.features import (+ EMBEDDING_DIMENSIONS,+ PROJECT_VECTOR_KINDS,+ FeatureSet,+ ProjectInputs,+ project_inputs,+)from products.signals.backend.ranking.model_contract import (booster_mismatch,model_feature_set,@@ -58,6 +69,14 @@ ONNX_OUTPUT = "probabilities"ONNX_OUTPUT_HEADS_KEY = "output_heads"# The input that takes the feature set's matrix, the report vector.ONNX_REPORT_INPUT = "report"+# The inputs that take the team's project vectors and their history flags, in+# `PROJECT_VECTOR_KINDS` order. Only a graph whose `metadata.json` lists the kinds under+# `ONNX_PROJECT_VECTOR_KINDS_KEY` takes them.+ONNX_PROJECT_INPUT = "project"+ONNX_HAS_HISTORY_INPUT = "has_history"+ONNX_PROJECT_VECTOR_KINDS_KEY = "project_vector_kinds"+# The `inbox_project_vectors` columns `project_inputs` reads.+PROJECT_VECTORS_COLUMNS = ["team_id", "kind", "vector", "n_reports"]# Threads one ONNX session may use for one operator. The sweep shares the worker with other# activities, so a model must not take every core.ONNX_INTRA_OP_THREADS = 2@@ -67,6 +86,12 @@ class ModelLoadError(Exception):"""One manifest entry could not be loaded into a model this build can score."""+class Predict(Protocol):+ def __call__(self, matrix: np.ndarray, project: ProjectInputs | None = None) -> Mapping[str, np.ndarray]:+ """`project` holds one row per row of `matrix`, and only a model that reads project vectors needs it."""+ ...++@frozenclass LoadedModel:entry: ServingManifestEntry@@ -75,7 +100,9 @@ class LoadedModel:# 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]]+ predict: Predict+ # True when `predict` also needs the team's project vectors.+ reads_project_vectors: bool = False@frozen@@ -127,7 +154,7 @@ class XGBoostHandler:boosters[head] = boosterfeature_names = list(feature_set.feature_names)- def predict(matrix: np.ndarray) -> dict[str, np.ndarray]:+ def predict(matrix: np.ndarray, project: ProjectInputs | None = None) -> dict[str, np.ndarray]:dmatrix = xgb.DMatrix(matrix, feature_names=feature_names)return {head: booster.predict(dmatrix) for head, booster in boosters.items()}@@ -156,7 +183,15 @@ class ONNXHandler:# onnxruntime's errors share no base class below Exception.except Exception as error:raise ModelLoadError(f"{entry.key} {ONNX_MODEL_FILE} does not load: {error}") from error- mismatch = _onnx_input_mismatch(session.get_inputs(), _onnx_input_widths(feature_set))+ kinds = tuple(metadata.get(ONNX_PROJECT_VECTOR_KINDS_KEY) or ())+ if kinds and kinds != PROJECT_VECTOR_KINDS:+ raise ModelLoadError(+ f"{entry.key} {METADATA_FILE} {ONNX_PROJECT_VECTOR_KINDS_KEY} {list(kinds)} are not {list(PROJECT_VECTOR_KINDS)}"+ )+ reads_project_vectors = bool(kinds)+ mismatch = _onnx_input_mismatch(+ session.get_inputs(), _onnx_input_shapes(feature_set, reads_project_vectors=reads_project_vectors)+ )if mismatch is not None:raise ModelLoadError(f"{entry.key} {mismatch}")output_heads = list(metadata.get(ONNX_OUTPUT_HEADS_KEY) or ())@@ -165,35 +200,47 @@ class ONNXHandler:raise ModelLoadError(f"{entry.key} {mismatch}")columns = {head: output_heads.index(head) for head in entry.heads}- def predict(matrix: np.ndarray) -> dict[str, np.ndarray]:- (probabilities,) = session.run(- [ONNX_OUTPUT], {ONNX_REPORT_INPUT: np.ascontiguousarray(matrix, dtype=np.float32)}- )+ def predict(matrix: np.ndarray, project: ProjectInputs | None = None) -> dict[str, np.ndarray]:+ feeds = {ONNX_REPORT_INPUT: np.ascontiguousarray(matrix, dtype=np.float32)}+ if reads_project_vectors:+ if project is None:+ raise ValueError(f"{entry.key} reads project vectors and none were given")+ feeds[ONNX_PROJECT_INPUT] = np.ascontiguousarray(project.vectors, dtype=np.float32)+ feeds[ONNX_HAS_HISTORY_INPUT] = np.ascontiguousarray(project.has_history, dtype=np.float32)+ (probabilities,) = session.run([ONNX_OUTPUT], feeds)return {head: probabilities[:, column] for head, column in columns.items()}- return LoadedModel(entry=entry, feature_set=feature_set, metadata=metadata, predict=predict)-+ return LoadedModel(+ entry=entry,+ feature_set=feature_set,+ metadata=metadata,+ predict=predict,+ reads_project_vectors=reads_project_vectors,+ )-def _onnx_input_widths(feature_set: FeatureSet) -> dict[str, int]:- """The width of each ONNX input the scorer can feed for `feature_set`.- Only the report vector today. The project-vector inputs join here when the sweep can read- project vectors, and `predict` then feeds them too.- """- return {ONNX_REPORT_INPUT: len(feature_set.feature_names)}+def _onnx_input_shapes(feature_set: FeatureSet, *, reads_project_vectors: bool) -> dict[str, tuple[int, ...]]:+ """The shape after the batch axis of each ONNX input the scorer feeds for `feature_set`."""+ shapes: dict[str, tuple[int, ...]] = {ONNX_REPORT_INPUT: (len(feature_set.feature_names),)}+ if reads_project_vectors:+ shapes[ONNX_PROJECT_INPUT] = (len(PROJECT_VECTOR_KINDS), EMBEDDING_DIMENSIONS)+ shapes[ONNX_HAS_HISTORY_INPUT] = (len(PROJECT_VECTOR_KINDS),)+ return shapes-def _onnx_input_mismatch(inputs: Sequence[Any], widths: Mapping[str, int]) -> str | None:+def _onnx_input_mismatch(inputs: Sequence[Any], shapes: Mapping[str, tuple[int, ...]]) -> str | None:"""Why the graph's inputs differ from what the scorer feeds, or None when they agree.- Each input must be float32 with shape `(batch, width)`.+ Each input must be float32 with shape `(batch, *shape)`."""names = sorted(node.name for node in inputs)- if names != sorted(widths):- return f"{ONNX_MODEL_FILE} inputs {names} are not {sorted(widths)}"+ if names != sorted(shapes):+ return f"{ONNX_MODEL_FILE} inputs {names} are not {sorted(shapes)}"for node in inputs:- if node.type != "tensor(float)" or len(node.shape) != 2 or node.shape[1] != widths[node.name]:- return f"{ONNX_MODEL_FILE} input {node.name} is {node.type} {node.shape}, not float (batch, {widths[node.name]})"+ shape = shapes[node.name]+ if node.type != "tensor(float)" or tuple(node.shape[1:]) != shape or len(node.shape) != 1 + len(shape):+ expected = ", ".join(str(size) for size in shape)+ return f"{ONNX_MODEL_FILE} input {node.name} is {node.type} {node.shape}, not float (batch, {expected})"return None@@ -311,6 +358,47 @@ def load_serving_set(overrides: RankingOverrides | None = None) -> ServingSet |return _with_served_override(serving, overrides)+@frozen+class ProjectVectors:+ """The project vectors one pass reads, for the teams it scores."""++ # False when the manifest names no object or the object is missing, so no team has vectors.+ available: bool+ by_team: Mapping[int, ProjectInputs]++ def for_team(self, team_id: int) -> ProjectInputs | None:+ """One row of the team's vectors, all zero when the day has no row for the team, or None+ when the pass has no project vectors at all."""+ if not self.available:+ return None+ return self.by_team.get(team_id) or project_inputs(pd.DataFrame(columns=PROJECT_VECTORS_COLUMNS), [team_id])+++def load_project_vectors(manifest: ServingManifest, team_ids: Collection[int]) -> ProjectVectors:+ """The vectors of `team_ids` from the day the manifest names, read once.++ Only the rows of `team_ids` are kept, so the pass holds one vector per (team, kind) it scores.+ A missing object is no vectors at all rather than an empty day, so the models that read them+ are skipped instead of scoring every team as a team without history.+ """+ key = manifest.project_vectors+ teams = sorted({int(team_id) for team_id in team_ids})+ body = None if key is None or not teams else object_storage.read_bytes(key, missing_ok=True)+ if body is None:+ if key is not None and teams:+ logger.warning("inbox_ranking_project_vectors_missing", project_vectors_key=key)+ return ProjectVectors(available=False, by_team={})+ rows = pd.read_parquet(io.BytesIO(body), columns=PROJECT_VECTORS_COLUMNS, filters=[("team_id", "in", teams)])+ inputs = project_inputs(rows, teams)+ by_team = {+ team_id: ProjectInputs(+ vectors=inputs.vectors[index : index + 1], has_history=inputs.has_history[index : index + 1]+ )+ for index, team_id in enumerate(teams)+ }+ return ProjectVectors(available=True, by_team=by_team)++def served_override_rejection(serving: ServingSet, key: str) -> str | None:"""Why the model `key` cannot take the served role this pass, or None when it can.@@ -326,6 +414,8 @@ def served_override_rejection(serving: ServingSet, key: str) -> str | None:missing_heads = sorted(set(serving.served.entry.heads) - set(model.entry.heads))if missing_heads:return f"{key} has no head for {missing_heads}"+ if model.reads_project_vectors and serving.manifest.project_vectors is None:+ return f"{key} reads project vectors and the manifest names none"return Nonediff --git a/products/signals/backend/ranking/scorer.py b/products/signals/backend/ranking/scorer.pyindex 85cec399ec4f..0d538d3ed6d8 100644--- a/products/signals/backend/ranking/scorer.py+++ b/products/signals/backend/ranking/scorer.py@@ -7,12 +7,16 @@ with, so a served score is the value the dag would produce for the same model anNothing is written until every report of the call is scored, so a failure part of the way througha call writes nothing.++A model that reads its team's project vectors gets the team's row of the day the manifest names,+repeated for each report, through the same `project_inputs` the training dag builds them with."""from collections.abc import Mapping, Sequencefrom datetime import datetimefrom typing import Any+import numpy as npimport pandas as pdimport structlog@@ -26,10 +30,17 @@ from products.signals.backend.ranking.features import (REPORT_EMBEDDINGS_EXTRA,TITLE_EMBEDDINGS_EXTRA,FeatureSet,+ ProjectInputs,ReportEmbeddingsFeatureSet,)from products.signals.backend.ranking.model_contract import head_lifts-from products.signals.backend.ranking.model_store import LoadedModel, ServingSet, load_serving_set+from products.signals.backend.ranking.model_store import (+ LoadedModel,+ ProjectVectors,+ ServingSet,+ load_project_vectors,+ load_serving_set,+)from products.signals.backend.ranking.serving_manifest import ServingManifestEntryfrom products.signals.backend.ranking.sinks import persist_scoresfrom products.signals.backend.report_embedding_reader import ReportVector, latest_report_vectors@@ -38,6 +49,7 @@ from products.signals.backend.report_embeddings import EMBEDDING_RENDERING_TITLElogger = structlog.get_logger(__name__)NO_VECTOR = "no_vector"+NO_PROJECT_VECTORS = "no_project_vectors"# 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.@@ -99,6 +111,22 @@ def served_rendering(serving: ServingSet) -> str:return RENDERING_BY_EXTRA[_served_model_extra(serving.served)]+def pass_project_vectors(serving: ServingSet, team_ids: Sequence[int]) -> ProjectVectors | None:+ """The project vectors of `team_ids`, read once for a pass, or None when no model reads them.++ A failed read is no vectors at all, so it costs only the models that read them.+ """+ if not any(model.reads_project_vectors for model in (serving.served, *serving.others)):+ return None+ try:+ return load_project_vectors(serving.manifest, team_ids)+ except Exception:+ logger.exception(+ "inbox_ranking_project_vectors_unreadable", project_vectors_key=serving.manifest.project_vectors+ )+ return ProjectVectors(available=False, by_team={})++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(@@ -111,13 +139,18 @@ def _extras_frame(report_ids: Sequence[str], vectors: Mapping[str, ReportVector]def _score_model(- model: LoadedModel, report_ids: Sequence[str], vectors_by_extra: Mapping[str, Mapping[str, ReportVector]]+ model: LoadedModel,+ report_ids: Sequence[str],+ vectors_by_extra: Mapping[str, Mapping[str, ReportVector]],+ team_project: ProjectInputs | None,) -> _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")+ if model.reads_project_vectors and team_project is None:+ return _ModelScores(model=model, by_report={}, skip_reason=NO_PROJECT_VECTORS)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.@@ -125,7 +158,13 @@ def _score_model(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())+ project = None+ if model.reads_project_vectors and team_project is not None:+ project = ProjectInputs(+ vectors=np.repeat(team_project.vectors, len(matrix), axis=0),+ has_history=np.repeat(team_project.has_history, len(matrix), axis=0),+ )+ probabilities = model.predict(matrix.to_numpy(), project)by_report = {report_id: {head: float(values[index]) for head, values in probabilities.items()}for index, report_id in enumerate(matrix.index)@@ -176,6 +215,7 @@ def score_reports(now: datetime,serving: ServingSet | None = None,capture: ScopedCapture | None = None,+ project_vectors: ProjectVectors | None = None,) -> list[ReportScoringOutcome]:"""One outcome per distinct report id, in the order given.@@ -183,8 +223,10 @@ def score_reports(so the caller can try it again later. A challenger with no vector is a skipped result insidethe score. `persist=False` returns the scores and writes nothing.- A caller that scores many teams passes the `serving` set it loaded and one `capture`, so each- team does not read the manifest from object storage again or flush its own events.+ A caller that scores many teams passes the `serving` set it loaded, one `capture`, and the+ `project_vectors` of every team it scores, so each team does not read the manifest or the+ project vectors from object storage again or flush its own events. A served model that reads+ project vectors when the pass has none raises, because no report could get a served score."""if serving is None:serving = load_serving_set()@@ -198,11 +240,16 @@ def score_reports(served_extra = _served_model_extra(served)models = [served, *serving.others]+ if project_vectors is None:+ project_vectors = pass_project_vectors(serving, [team_id])+ team_project = project_vectors.for_team(team_id) if project_vectors is not None else None+ if served.reads_project_vectors and team_project is None:+ raise ScoringError(f"served model {served.entry.key} reads project vectors and the pass has none")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}+ scored_models = {model.entry.key: _score_model(model, ids, vectors_by_extra, team_project) for model in models}served_key = serving.manifest.served.keyserved_vectors = vectors_by_extra[served_extra]diff --git a/products/signals/backend/ranking/serving_manifest.py b/products/signals/backend/ranking/serving_manifest.pyindex 9c2f1d3915b5..481adfce6279 100644--- a/products/signals/backend/ranking/serving_manifest.py+++ b/products/signals/backend/ranking/serving_manifest.py@@ -46,6 +46,7 @@ HEAD_FILE_SUFFIX = ".ubj"MANIFEST_FILE = "manifest.json"METADATA_FILE = "metadata.json"+PROJECT_VECTORS_FILE = "project_vectors.parquet"_SERVING_SEGMENT = "serving"@@ -60,6 +61,12 @@ def serving_model_prefix(prefix: str, key: str) -> str:return f"{prefix}/{_SERVING_SEGMENT}/models/{key}"+def serving_project_vectors_key(prefix: str, partition_key: str) -> str:+ """Where one day of `inbox_project_vectors` sits. Keyed by its `dt`, so a day is published once+ however many manifests name it."""+ return f"{prefix}/{_SERVING_SEGMENT}/project_vectors/{partition_key}/{PROJECT_VECTORS_FILE}"++def model_key(model_name: str, model_version: str) -> str:return f"{model_name}@{model_version}"@@ -89,6 +96,10 @@ class ServingManifestEntry(BaseModel):f"Null when each head has its own `<head>{HEAD_FILE_SUFFIX}` booster."),)+ reads_project_vectors: bool = Field(+ default=False,+ description="True when the model also reads its team's project vectors, from the manifest's `project_vectors`.",+ )@field_validator("key", "model_name", "model_version", "model_kind", "prefix")@classmethod@@ -128,6 +139,13 @@ class ServingManifest(BaseModel):max_length=MAX_RANKING_MODEL_RESULTS,description="Every model the pass runs, served first.",)+ project_vectors: str | None = Field(+ default=None,+ description=(+ "Object key of the one `inbox_project_vectors` day that every entry with `reads_project_vectors` reads. "+ "Null when no entry reads them, or when this store has no copy, and then those entries score nothing."+ ),+ )@field_validator("manifest_version")@classmethoddiff --git a/products/signals/backend/ranking/sweep.py b/products/signals/backend/ranking/sweep.pyindex 1ec10f440408..6ca20488cfa5 100644--- a/products/signals/backend/ranking/sweep.py+++ b/products/signals/backend/ranking/sweep.py@@ -302,6 +302,7 @@ def score_inbox_reports(limit: int | None = None) -> ScoreInboxReportsResult:peak_rss_mb=_peak_rss_mb(),)+ project_vectors = scorer.pass_project_vectors(serving, list(ids_by_team))# A scorer call holds the vectors and matrices of all its reports, so one call scores at most one# vector read of one team. Each call persists its scores, so a pass that stops keeps its progress.chunks = [@@ -320,7 +321,13 @@ def score_inbox_reports(limit: int | None = None) -> ScoreInboxReportsResult:continuetry:outcomes = scorer.score_reports(- team_id, list(report_ids), persist=True, now=now, serving=serving, capture=capture+ team_id,+ list(report_ids),+ persist=True,+ now=now,+ serving=serving,+ capture=capture,+ project_vectors=project_vectors,)except (scorer.ScoringError, ModelLoadError):# A pass without a served score is worse than no pass.diff --git a/products/signals/backend/test/fixtures/onnx/build_onnx_fixtures.py b/products/signals/backend/test/fixtures/onnx/build_onnx_fixtures.pyindex 294169b45140..5a6b347b7773 100644--- a/products/signals/backend/test/fixtures/onnx/build_onnx_fixtures.py+++ b/products/signals/backend/test/fixtures/onnx/build_onnx_fixtures.py@@ -6,6 +6,8 @@ Run from the repository root:Each graph is `sigmoid(report @ weights + bias)`, the shape the inbox ranking network exports:an input `report` of shape (batch, width) and an output `probabilities` of shape (batch, heads).+`project_report.onnx` also takes `project` (batch, kinds, width) and `has_history` (batch, kinds),+the inputs of a network that reads the team's project vectors, and adds a term for each.The weights are seeded, so a rerun writes the same files."""@@ -20,6 +22,7 @@ FIXTURES = Path(__file__).parentOPSET = 17HEADS = 2SERVED_WIDTH = 1536+KINDS = 4EXPECTED_ROWS = 3@@ -44,6 +47,46 @@ def _graph(input_name: str, width: int, seed: int) -> tuple[onnx.ModelProto, np.return model, weights, bias+def _sigmoid(logits: np.ndarray) -> np.ndarray:+ return (1.0 / (1.0 + np.exp(-logits))).astype(np.float32)+++def _project_graph(seed: int) -> tuple[onnx.ModelProto, dict[str, np.ndarray]]:+ rng = np.random.default_rng(seed)+ weights = {+ "report_weights": (rng.normal(size=(SERVED_WIDTH, HEADS)) * 0.05).astype(np.float32),+ "project_weights": (rng.normal(size=(KINDS * SERVED_WIDTH, HEADS)) * 0.05).astype(np.float32),+ "history_weights": rng.normal(size=(KINDS, HEADS)).astype(np.float32),+ "bias": rng.normal(size=HEADS).astype(np.float32),+ }+ flat_shape = np.array([-1, KINDS * SERVED_WIDTH], dtype=np.int64)+ graph = helper.make_graph(+ nodes=[+ helper.make_node("MatMul", ["report", "report_weights"], ["report_logits"]),+ helper.make_node("Reshape", ["project", "flat_shape"], ["project_flat"]),+ helper.make_node("MatMul", ["project_flat", "project_weights"], ["project_logits"]),+ helper.make_node("MatMul", ["has_history", "history_weights"], ["history_logits"]),+ helper.make_node("Sum", ["report_logits", "project_logits", "history_logits", "bias"], ["logits"]),+ helper.make_node("Sigmoid", ["logits"], ["probabilities"]),+ ],+ name="inbox_ranking_project_fixture",+ inputs=[+ helper.make_tensor_value_info("report", TensorProto.FLOAT, ["batch", SERVED_WIDTH]),+ helper.make_tensor_value_info("project", TensorProto.FLOAT, ["batch", KINDS, SERVED_WIDTH]),+ helper.make_tensor_value_info("has_history", TensorProto.FLOAT, ["batch", KINDS]),+ ],+ outputs=[helper.make_tensor_value_info("probabilities", TensorProto.FLOAT, ["batch", HEADS])],+ initializer=[+ *(numpy_helper.from_array(value, name) for name, value in weights.items()),+ numpy_helper.from_array(flat_shape, "flat_shape"),+ ],+ )+ model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", OPSET)], producer_name="posthog-fixture")+ model.ir_version = 8+ onnx.checker.check_model(model)+ return model, weights++def main() -> None:served, weights, bias = _graph("report", SERVED_WIDTH, seed=0)onnx.save(served, FIXTURES / "report.onnx")@@ -57,6 +100,29 @@ def main() -> None:renamed, _, _ = _graph("vector", 8, seed=3)onnx.save(renamed, FIXTURES / "unknown_input.onnx")+ with_project, project_weights = _project_graph(seed=4)+ onnx.save(with_project, FIXTURES / "project_report.onnx")+ # One team's project vectors, so every row shares them, as in one scorer call.+ rng = np.random.default_rng(5)+ team_project = rng.normal(size=(KINDS, SERVED_WIDTH)).astype(np.float32)+ team_history = np.array([1.0, 1.0, 0.0, 1.0], dtype=np.float32)+ team_project[team_history == 0.0] = 0.0+ project = np.repeat(team_project[None], EXPECTED_ROWS, axis=0)+ has_history = np.repeat(team_history[None], EXPECTED_ROWS, axis=0)+ logits = (+ report.astype(np.float64) @ project_weights["report_weights"].astype(np.float64)+ + project.reshape(EXPECTED_ROWS, -1).astype(np.float64) @ project_weights["project_weights"].astype(np.float64)+ + has_history.astype(np.float64) @ project_weights["history_weights"].astype(np.float64)+ + project_weights["bias"].astype(np.float64)+ )+ np.savez(+ FIXTURES / "project_report.expected.npz",+ report=report,+ project=team_project,+ has_history=team_history,+ probabilities=_sigmoid(logits),+ )+if __name__ == "__main__":main()diff --git a/products/signals/backend/test/fixtures/onnx/project_report.expected.npz b/products/signals/backend/test/fixtures/onnx/project_report.expected.npznew file mode 100644index 000000000000..377613bb057dBinary files /dev/null and b/products/signals/backend/test/fixtures/onnx/project_report.expected.npz differdiff --git a/products/signals/backend/test/fixtures/onnx/project_report.onnx b/products/signals/backend/test/fixtures/onnx/project_report.onnxnew file mode 100644index 000000000000..a3b7f82793faBinary files /dev/null and b/products/signals/backend/test/fixtures/onnx/project_report.onnx differdiff --git a/products/signals/backend/test/test_ranking_scoring.py b/products/signals/backend/test/test_ranking_scoring.pyindex 71d1f18a7627..7277f60b7599 100644--- a/products/signals/backend/test/test_ranking_scoring.py+++ b/products/signals/backend/test/test_ranking_scoring.py@@ -1,3 +1,4 @@+import ioimport sysimport jsonimport datetime@@ -16,7 +17,9 @@ from django.test import SimpleTestCase, override_settingsimport numpy as npimport pandas as pd+import pyarrow as paimport xgboost as xgb+import pyarrow.parquet as pqfrom parameterized import parameterizedfrom posthog.clickhouse.client import sync_execute@@ -27,13 +30,15 @@ from products.signals.backend.models import SignalReport, SignalReportArtefactfrom products.signals.backend.ranking import model_store, scorerfrom products.signals.backend.ranking.features import (EMBEDDING_DIMENSIONS,+ MIN_PROJECT_HISTORY_REPORTS,+ PROJECT_VECTOR_KINDS,REPORT_EMBEDDINGS_FEATURE_SET,TITLE_EMBEDDINGS_FEATURE_SET,FeatureSet,)from products.signals.backend.ranking.model_store import ModelLoadError, load_serving_setfrom products.signals.backend.ranking.overrides import RankingOverrides-from products.signals.backend.ranking.scorer import NO_VECTOR, score_reports+from products.signals.backend.ranking.scorer import NO_PROJECT_VECTORS, NO_VECTOR, ScoringError, score_reportsfrom products.signals.backend.ranking.serving_manifest import (CROSS_FAMILY_ROLE,DAILY_CANDIDATE_ROLE,@@ -49,6 +54,7 @@ from products.signals.backend.ranking.serving_manifest import (model_key,serving_manifest_key,serving_model_prefix,+ serving_project_vectors_key,)from products.signals.backend.ranking.sinks import REPORT_SCORED_EVENT, classification_propertiesfrom products.signals.backend.report_embedding_reader import (@@ -112,6 +118,7 @@ class FakeObjectStore:missing_heads: Sequence[str] = (),thresholds: Mapping[str, float] | None = None,onnx_fixture: str = "report.onnx",+ project_vector_kinds: Sequence[str] = (),) -> ServingManifestEntry:key = model_key(model_name, version)prefix = serving_model_prefix(PREFIX, key)@@ -137,6 +144,8 @@ class FakeObjectStore:for head in HEADS],}+ if project_vector_kinds:+ metadata["project_vector_kinds"] = list(project_vector_kinds)if onnx:metadata["output_heads"] = list(ONNX_OUTPUT_HEADS)self.objects[f"{prefix}/{ONNX_MODEL_FILE}"] = (ONNX_FIXTURES / onnx_fixture).read_bytes()@@ -155,10 +164,33 @@ class FakeObjectStore:prefix=prefix,heads=list(HEADS),model_file=ONNX_MODEL_FILE if onnx else None,+ reads_project_vectors=bool(project_vector_kinds),)- def publish_manifest(self, entries: Sequence[ServingManifestEntry]) -> ServingManifest:- manifest = ServingManifest(manifest_version=NOW.isoformat(), models=list(entries))+ def publish_project_vectors(self, team_id: int, vectors: np.ndarray, has_history: np.ndarray) -> str:+ key = serving_project_vectors_key(PREFIX, VERSION)+ table = pa.Table.from_pylist(+ [+ {+ "team_id": team_id,+ "kind": kind,+ "vector": vectors[index].tolist(),+ "n_reports": MIN_PROJECT_HISTORY_REPORTS if has_history[index] else 1,+ }+ for index, kind in enumerate(PROJECT_VECTOR_KINDS)+ ]+ )+ buffer = io.BytesIO()+ pq.write_table(table, buffer)+ self.objects[key] = buffer.getvalue()+ return key++ def publish_manifest(+ self, entries: Sequence[ServingManifestEntry], project_vectors: str | None = None+ ) -> ServingManifest:+ manifest = ServingManifest(+ manifest_version=NOW.isoformat(), models=list(entries), project_vectors=project_vectors+ )self.objects[serving_manifest_key(PREFIX)] = manifest.model_dump_json().encode()return manifest@@ -215,6 +247,25 @@ class TestModelStore(_StoreTestMixin, SimpleTestCase):{"model_kind": ONNX_MODEL_KIND, "onnx_fixture": "unknown_input.onnx"},"inputs ['vector'] are not ['report']",),+ (+ "onnx_graph_without_project_inputs",+ {"model_kind": ONNX_MODEL_KIND, "project_vector_kinds": PROJECT_VECTOR_KINDS},+ "inputs ['report'] are not ['has_history', 'project', 'report']",+ ),+ (+ "onnx_project_inputs_without_kinds",+ {"model_kind": ONNX_MODEL_KIND, "onnx_fixture": "project_report.onnx"},+ "inputs ['has_history', 'project', 'report'] are not ['report']",+ ),+ (+ "onnx_project_kinds_in_another_order",+ {+ "model_kind": ONNX_MODEL_KIND,+ "onnx_fixture": "project_report.onnx",+ "project_vector_kinds": ("open", "typical", "action", "dismiss"),+ },+ "project_vector_kinds ['open', 'typical', 'action', 'dismiss']",+ ),])def test_a_challenger_that_cannot_load_is_skipped(self, _name: str, kwargs: dict, reason: str) -> None:@@ -413,6 +464,64 @@ class TestScorer(_ScorerTestMixin, SimpleTestCase):expected_scores = dict(zip(ONNX_OUTPUT_HEADS, probabilities.tolist()))assert results[onnx.key].scores == pytest.approx(expected_scores, abs=1e-6)+ def _project_model(self, roles: Sequence[str]) -> ServingManifestEntry:+ return self.store.publish_model(+ "nn",+ REPORT_EMBEDDINGS_FEATURE_SET,+ roles=roles,+ model_kind=ONNX_MODEL_KIND,+ onnx_fixture="project_report.onnx",+ project_vector_kinds=PROJECT_VECTOR_KINDS,+ )++ def test_an_onnx_model_reads_the_team_project_vectors(self) -> None:+ served = self._served()+ nn = self._project_model([CROSS_FAMILY_ROLE])+ expected = np.load(ONNX_FIXTURES / "project_report.expected.npz")+ key = self.store.publish_project_vectors(self.team_id, expected["project"], expected["has_history"])+ self.store.publish_manifest([served, nn], project_vectors=key)+ report_ids = [f"r{index}" for index in range(len(expected["report"]))]+ vectors = {+ EMBEDDING_RENDERING_TITLE_SUMMARY: {+ report_id: ReportVector(embedding=vector, inserted_at=LANDED)+ for report_id, vector in zip(report_ids, expected["report"])+ }+ }++ outcomes, _, _ = self._score(report_ids, vectors, persist=False)++ for outcome, probabilities in zip(outcomes, expected["probabilities"]):+ assert outcome.score is not None+ result = outcome.score.results[nn.key]+ assert result.status == "scored"+ assert result.scores == pytest.approx(dict(zip(ONNX_OUTPUT_HEADS, probabilities.tolist())), abs=1e-6)++ @parameterized.expand(+ [("manifest_names_none", False, None), ("object_missing", True, None), ("object_unreadable", True, b"oops")]+ )+ def test_a_model_without_project_vectors_is_skipped_or_stops_the_served_score(+ self, _name: str, names_a_key: bool, body: bytes | None+ ) -> None:+ key = serving_project_vectors_key(PREFIX, VERSION) if names_a_key else None+ if key is not None and body is not None:+ self.store.objects[key] = body+ report = ReportVector(embedding=_vector(1), inserted_at=LANDED)+ vectors = {EMBEDDING_RENDERING_TITLE_SUMMARY: {"r1": report}}+ served = self._served()+ nn = self._project_model([CROSS_FAMILY_ROLE])+ self.store.publish_manifest([served, nn], project_vectors=key)++ (outcome,), _, _ = self._score(["r1"], vectors, persist=False)++ assert outcome.score is not None+ result = outcome.score.results[nn.key]+ assert (result.status, result.skip_reason) == ("skipped", NO_PROJECT_VECTORS)++ model_store.clear_model_cache()+ self.store.publish_manifest([self._project_model([SERVED_ROLE])], project_vectors=key)+ with self.assertRaisesRegex(ScoringError, "reads project vectors"):+ self._score(["r1"], vectors, persist=False)+def test_importing_the_scoring_sweep_loads_no_model_runtime() -> None:result = subprocess.run(diff --git a/products/signals/backend/test/test_ranking_sweep.py b/products/signals/backend/test/test_ranking_sweep.pyindex dd41eec90f87..d9dd322214e7 100644--- a/products/signals/backend/test/test_ranking_sweep.py+++ b/products/signals/backend/test/test_ranking_sweep.py@@ -211,6 +211,8 @@ class TestScoreInboxReports(SimpleTestCase):self.served_rendering = self._patch(scorer, "served_rendering", return_value=EMBEDDING_RENDERING_TITLE_SUMMARY)self.due = self._patch(sweep, "reports_due_for_scoring", return_value=[])self.score_reports = self._patch(scorer, "score_reports", side_effect=self._outcomes)+ self.project_vectors = MagicMock()+ self.pass_project_vectors = self._patch(scorer, "pass_project_vectors", return_value=self.project_vectors)self.capture = MagicMock()self.capture_scopes = 0self._patch(sweep, "ph_scoped_capture", new=self._capture_scope)@@ -240,6 +242,7 @@ class TestScoreInboxReports(SimpleTestCase):now: datetime.datetime,serving: Any = None,capture: Any = None,+ project_vectors: Any = None,) -> list:if team_id in self.failing_teams:raise self.failing_teams[team_id]@@ -286,10 +289,13 @@ class TestScoreInboxReports(SimpleTestCase):(call.args[0], call.args[1], call.kwargs["persist"]) for call in self.score_reports.call_args_list) == [(1, ["a", "novec-c"], True), (2, ["b"], True)]assert all(- call.kwargs["serving"] is self.serving and call.kwargs["capture"] is self.capture+ call.kwargs["serving"] is self.serving+ and call.kwargs["capture"] is self.capture+ and call.kwargs["project_vectors"] is self.project_vectorsfor call in self.score_reports.call_args_list)assert (self.load_serving_set.call_count, self.capture_scopes, self.capture.flush.call_count) == (1, 1, 2)+ self.pass_project_vectors.assert_called_once_with(self.serving, [1, 2])self.logger.info.assert_any_call("inbox_ranking_sweep_started", candidates=3, teams=2, manifest_version=MANIFEST, peak_rss_mb=ANY)diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.mdindex 2c969929eb7e..5368ec8019e7 100644--- a/products/signals/dags/inbox_ranking/AGENTS.md+++ b/products/signals/dags/inbox_ranking/AGENTS.md@@ -34,6 +34,7 @@ Read `README.md` first for what the dataset is and how partitions behave. This f- An entry's files come from `ServingManifestEntry.files`: one `<head>.ubj` per head for `xgboost`, and the one `model.onnx` that `model_file` names for `onnx`. The copy step and the model store read that property, and the pin check reads the same names from each head's `file` in `metadata.json`, so a new model kind with another file layout keeps the two in step. Keep `onnxruntime` and `xgboost` imports inside the handlers' `load`: a test pins that importing the sweep loads neither.- The manifest schema and the object keys live in `products/signals/backend/ranking/serving_manifest.py`, next to the feature contract, because the dag writes them and the sweep reads them. Its validators run at write time, so the dag refuses a manifest the sweep could not act on; the entry cap is the `ranking_score` artefact's, so a manifest can never produce a row the artefact refuses.- Publishing order is load-bearing. Every model copy finishes before `manifest.json` is written, so a failed copy leaves the previous manifest and the previous models serving. A model version is immutable, so a version whose `metadata.json` is already at the target is not copied again. A run with nothing to publish, and no champion for the served family is the case today, writes nothing rather than an empty manifest.+- When a manifest entry has `reads_project_vectors`, the dt=D `inbox_project_vectors` day is copied to `serving/project_vectors/<D>/` before `manifest.json`, and the manifest names it in `project_vectors`. A missing day fails the publish, like a missing model file. Never copy project vectors to the mirror: they are per-team data of this deployment, so the mirror's manifest names none. Training and serving build the `project` and `has_history` inputs through the one `project_inputs` in `features.py`; keep `PROJECT_VECTOR_KINDS` and `MIN_PROJECT_HISTORY_REPORTS` there.## Invariants — do not breakdiff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex d80d0de85dd4..77f978631af8 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -73,6 +73,7 @@ Point-in-time contract:- A report born on day D uses the project vectors of dt=D−1. Their `as_of` is D 00:00 UTC, strictly before the birth, and that matches serving, where the sweep reads the newest snapshot.- A report enters a vector only when its vector landed and its engagement happened strictly before `as_of`. The snapshot holds only the latest vector per report, so a report re-embedded after `as_of` is left out rather than read with text it did not have yet.- The training side can rebuild any past day by calling the function on newer snapshots with an earlier `as_of`. No backfill is needed while the vectors are inside the embedding TTL.+- Serving: when any manifest entry reads project vectors, `inbox_ranking_serving_manifest` copies the dt=D day into the deployment's object store before it writes the manifest. The sweep reads that day once per pass, only for the teams it scores. Its `as_of` is the end of dt=D, so it is never newer than a report scored after the publish. Until the next publish, a report scored on day D+2 still reads dt=D, which is one day older than training reads.### Partition semanticsdiff --git a/products/signals/dags/inbox_ranking/dataset/project_vectors.py b/products/signals/dags/inbox_ranking/dataset/project_vectors.pyindex cdc2e71643d0..27f8e67a8ab0 100644--- a/products/signals/dags/inbox_ranking/dataset/project_vectors.py+++ b/products/signals/dags/inbox_ranking/dataset/project_vectors.py@@ -22,7 +22,11 @@ import numpy as npimport pyarrow as paimport pyarrow.compute as pc-from products.signals.backend.ranking.features import EMBEDDING_DIMENSIONS+from products.signals.backend.ranking.features import (+ EMBEDDING_DIMENSIONS,+ MIN_PROJECT_HISTORY_REPORTS,+ PROJECT_VECTOR_KINDS,+)from products.signals.dags.inbox_ranking.dataset.queries import ACTION_TYPESfrom products.signals.dags.inbox_ranking.training.heads import UI_ACTION_COLUMNS@@ -30,14 +34,10 @@ from products.signals.dags.inbox_ranking.training.heads import UI_ACTION_COLUMNSPROJECT_VECTORS_SCHEMA_VERSION = 1HISTORY_LIMIT = 50-# Below this many reports, a mean is mostly one report's text and says little about the team.-MIN_HISTORY_REPORTS = 5--TYPICAL = "typical"-OPEN = "open"-ACTION = "action"-DISMISS = "dismiss"-VECTOR_KINDS = (TYPICAL, OPEN, ACTION, DISMISS)+# The backend owns the kinds and the threshold, because the scoring sweep builds the same inputs.+MIN_HISTORY_REPORTS = MIN_PROJECT_HISTORY_REPORTS+VECTOR_KINDS = PROJECT_VECTOR_KINDS+TYPICAL, OPEN, ACTION, DISMISS = VECTOR_KINDSOPEN_COLUMN = "first_opened_at"DISMISS_COLUMN = "first_ui_dismissed_at"diff --git a/products/signals/dags/inbox_ranking/multihead/prototype.py b/products/signals/dags/inbox_ranking/multihead/prototype.pyindex e15733d1705a..a4de32b2ad54 100644--- a/products/signals/dags/inbox_ranking/multihead/prototype.py+++ b/products/signals/dags/inbox_ranking/multihead/prototype.py@@ -28,18 +28,18 @@ import numpy as npimport pandas as pdimport pyarrow as paimport xgboost as xgb-import pyarrow.compute as pcfrom sklearn.metrics import average_precision_score, roc_auc_scorefrom posthog.dataclasses import frozen-from products.signals.backend.ranking.features import EMBEDDING_DIMENSIONS, REPORT_EMBEDDINGS_FEATURE_SET, Extras-from products.signals.dags.inbox_ranking.common import snapshot_bounds-from products.signals.dags.inbox_ranking.dataset.project_vectors import (- MIN_HISTORY_REPORTS,- VECTOR_KINDS,- project_vectors,+from products.signals.backend.ranking.features import (+ EMBEDDING_DIMENSIONS,+ REPORT_EMBEDDINGS_FEATURE_SET,+ Extras,+ project_inputs,)+from products.signals.dags.inbox_ranking.common import snapshot_bounds+from products.signals.dags.inbox_ranking.dataset.project_vectors import VECTOR_KINDS, project_vectorsfrom products.signals.dags.inbox_ranking.multihead.inputs import NetworkConfig, NetworkInputs, ProjectContextfrom products.signals.dags.inbox_ranking.training.calibration import calibration_buckets, expected_calibration_errorfrom products.signals.dags.inbox_ranking.training.examples import Snapshot, cap_examples, example_moments, holdout_mask@@ -116,7 +116,8 @@ def project_context(rows: pd.DataFrame, labels: pa.Table, embeddings: pa.Table)"""The project vectors each row reads: its team's, as of the start of its snapshot day.One `project_vectors()` call per snapshot day, and only the needed teams' rows are kept from it,- so the context holds a vector per (team, day) rather than one per example row.+ so the context holds a vector per (team, day) rather than one per example row. `project_inputs`+ turns a day into vectors, the same function the scoring sweep reads the published day with."""kinds = len(VECTOR_KINDS)pair_keys = rows[["report_team_id", "snapshot_date"]].drop_duplicates().reset_index(drop=True)@@ -125,28 +126,12 @@ def project_context(rows: pd.DataFrame, labels: pa.Table, embeddings: pa.Table)pair_of: dict[tuple[int, datetime.date], int] = {}for date, group in pair_keys.groupby("snapshot_date", sort=True):as_of, _ = snapshot_bounds(date.isoformat())- teams = {int(team_id): int(pair) for pair, team_id in group["report_team_id"].items()}- pair_of.update({(team_id, date): pair for team_id, pair in teams.items()})- day = project_vectors(labels, embeddings, as_of)- day_vectors = (- pc.list_flatten(day.column("vector").combine_chunks())- .to_numpy(zero_copy_only=False)- .reshape(-1, EMBEDDING_DIMENSIONS)- )- for position, (team_id, kind, n_reports) in enumerate(- zip(- day.column("team_id").to_numpy(),- day.column("kind").to_pylist(),- day.column("n_reports").to_numpy(),- strict=True,- )- ):- pair = teams.get(int(team_id))- if pair is None:- continue- kind_index = VECTOR_KINDS.index(kind)- vectors[pair, kind_index] = day_vectors[position]- has_history[pair, kind_index] = float(int(n_reports) >= MIN_HISTORY_REPORTS)+ pairs = group.index.to_numpy()+ team_ids = [int(team_id) for team_id in group["report_team_id"]]+ pair_of.update({(team_id, date): int(pair) for team_id, pair in zip(team_ids, pairs, strict=True)})+ day = project_inputs(project_vectors(labels, embeddings, as_of).to_pandas(), team_ids)+ vectors[pairs] = day.vectors+ has_history[pairs] = day.has_historyindex = np.array([pair_of[(int(team_id), date)] for team_id, date in zip(rows["report_team_id"], rows["snapshot_date"])],dtype=np.int64,diff --git a/products/signals/dags/inbox_ranking/tests/test_project_vectors.py b/products/signals/dags/inbox_ranking/tests/test_project_vectors.pyindex c57ad31339aa..cd6291ec1c0f 100644--- a/products/signals/dags/inbox_ranking/tests/test_project_vectors.py+++ b/products/signals/dags/inbox_ranking/tests/test_project_vectors.py@@ -1,13 +1,24 @@+import ioimport datetimefrom typing import Anyimport pytest+import numpy as np+import pandas as pdimport dagsterimport pyarrow as pa+import pyarrow.parquet as pqfrom parameterized import parameterized+from products.signals.backend.ranking import model_storefrom products.signals.backend.ranking.features import EMBEDDING_DIMENSIONS+from products.signals.backend.ranking.serving_manifest import (+ SERVED_ROLE,+ ServingManifest,+ ServingManifestEntry,+ serving_project_vectors_key,+)from products.signals.dags.inbox_ranking import commonfrom products.signals.dags.inbox_ranking.dataset import dagfrom products.signals.dags.inbox_ranking.dataset.dag import EMBEDDINGS_SCHEMA, LABELS_SCHEMA@@ -18,6 +29,7 @@ from products.signals.dags.inbox_ranking.dataset.project_vectors import (PROJECT_VECTORS_SCHEMA_VERSION,project_vectors,)+from products.signals.dags.inbox_ranking.multihead.prototype import project_contextAS_OF = datetime.datetime(2026, 7, 30, tzinfo=datetime.UTC)BEFORE = AS_OF - datetime.timedelta(days=3)@@ -146,3 +158,47 @@ def test_the_asset_writes_only_teams_opted_in_to_ai_training(monkeypatch) -> Nonassert captured["schema_version"] == PROJECT_VECTORS_SCHEMA_VERSIONassert set(captured["table"].column("team_id").to_pylist()) == {7}assert set(captured["table"].column("as_of").to_pylist()) == {AS_OF}+++def test_serving_reads_the_published_day_as_training_builds_it(monkeypatch: pytest.MonkeyPatch) -> None:+ reports = [(2, index, float(index + 1), BEFORE) for index in range(MIN_HISTORY_REPORTS)]+ reports += [(3, 0, 7.0, BEFORE)]+ engagements = [(2, index, "first_opened_at", BEFORE) for index in range(MIN_HISTORY_REPORTS)]+ labels, embeddings = _labels(engagements), _embeddings(reports)+ # Team 4 has no report vector, so the day has no row for it.+ teams = [2, 3, 4]+ rows = pd.DataFrame({"report_team_id": teams, "snapshot_date": [AS_OF.date()] * len(teams)})+ training = project_context(rows, labels, embeddings)++ # A report born on AS_OF's day reads the day before it, whose as_of is AS_OF.+ key = serving_project_vectors_key("inbox_ranking", (AS_OF.date() - datetime.timedelta(days=1)).isoformat())+ buffer = io.BytesIO()+ pq.write_table(project_vectors(labels, embeddings, AS_OF), buffer)+ monkeypatch.setattr(+ model_store.object_storage,+ "read_bytes",+ lambda name, bucket=None, *, missing_ok=False: buffer.getvalue() if name == key else None,+ )+ entry = ServingManifestEntry(+ key="nn@2026-07-29",+ model_name="nn",+ model_version="2026-07-29",+ model_kind="onnx",+ roles=[SERVED_ROLE],+ prefix="inbox_ranking/serving/models/nn@2026-07-29",+ heads=["open"],+ model_file="model.onnx",+ reads_project_vectors=True,+ )+ serving = model_store.load_project_vectors(+ ServingManifest(manifest_version=AS_OF.isoformat(), models=[entry], project_vectors=key), teams+ )++ for position, team_id in enumerate(teams):+ served = serving.for_team(team_id)+ assert served is not None+ pair = training.index[position]+ np.testing.assert_array_equal(served.vectors[0], training.vectors[pair])+ np.testing.assert_array_equal(served.has_history[0], training.has_history[pair])+ assert training.has_history[training.index].tolist() == [[1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]+ assert not training.vectors[training.index[2]].any()diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.pyindex 866803744d63..dc94ac1cd87e 100644--- a/products/signals/dags/inbox_ranking/tests/test_training.py+++ b/products/signals/dags/inbox_ranking/tests/test_training.py@@ -51,12 +51,14 @@ from products.signals.backend.ranking.serving_manifest import (model_key,serving_manifest_key,serving_model_prefix,+ serving_project_vectors_key,)from products.signals.backend.ranking.sinks import REPORT_SCORED_EVENTfrom products.signals.dags.inbox_ranking.common import partition_object_keyfrom products.signals.dags.inbox_ranking.dataset.dag import (EMBEDDINGS_TABLE,LABELS_TABLE,+ PROJECT_VECTORS_TABLE,STATE_TABLE,TITLE_EMBEDDINGS_TABLE,)@@ -2798,13 +2800,17 @@ class _AppObjectStore:self.written.append(key)-def _serving_dataset_s3(prefix: str, partition_key: str, model_kind: str = DEFAULT_MODEL_KIND):+def _serving_dataset_s3(+ prefix: str, partition_key: str, model_kind: str = DEFAULT_MODEL_KIND, project_vector_kinds: tuple[str, ...] = ()+):"""The dataset bucket holding one champion and one candidate of the served family."""onnx = model_kind == ONNX_MODEL_KINDmodel_file = ONNX_MODEL_FILE if onnx else "open.ubj"def metadata(version: str) -> dict[str, Any]:- kind = {"model_kind": model_kind, "model_file": ONNX_MODEL_FILE} if onnx else {}+ kind: dict[str, Any] = {"model_kind": model_kind, "model_file": ONNX_MODEL_FILE} if onnx else {}+ if project_vector_kinds:+ kind["project_vector_kinds"] = list(project_vector_kinds)return _serving_metadata(EMBEDDINGS_MODEL_NAME, version, heads=("open",), **kind)objects: dict[str, bytes] = {}@@ -2897,6 +2903,47 @@ def test_a_failed_mirror_leaves_the_primary_publish_intact(monkeypatch: pytest.Massert event["mirror_published"] is False+ "source_present,already_published,mirrored",+ [(True, False, False), (True, True, False), (True, False, True), (False, False, False)],+)+def test_project_vectors_are_published_before_the_manifest_that_names_them(+ monkeypatch: pytest.MonkeyPatch, source_present: bool, already_published: bool, mirrored: bool+) -> None:+ prefix = settings.INBOX_RANKING_DATASET_S3_PREFIX+ partition_key = "2026-08-19"+ target = serving_project_vectors_key(prefix, partition_key)+ previous = b'{"manifest_version": "2026-08-18T06:00:00+00:00"}'+ existing = {serving_manifest_key(prefix): previous}+ if already_published:+ existing[target] = b"published before"+ store = _AppObjectStore(existing)+ mirror = _AppObjectStore() if mirrored else None+ dataset = _serving_dataset_s3(+ prefix, partition_key, model_kind=ONNX_MODEL_KIND, project_vector_kinds=("typical", "open", "action", "dismiss")+ )+ if source_present:+ dataset.objects[partition_object_key(prefix, PROJECT_VECTORS_TABLE, partition_key)] = b"vectors"++ if not source_present:+ with pytest.raises(dagster.Failure, match="project vectors"):+ _run_serving_manifest(monkeypatch, store, dataset_client=dataset)+ assert store.objects[serving_manifest_key(prefix)] == previous+ return+ _run_serving_manifest(monkeypatch, store, mirror=mirror, dataset_client=dataset)++ manifest = ServingManifest.model_validate_json(store.objects[serving_manifest_key(prefix)])+ assert manifest.project_vectors == target+ assert all(entry.reads_project_vectors for entry in manifest.models)+ assert store.objects[target] == (b"published before" if already_published else b"vectors")+ assert store.written[-1] == serving_manifest_key(prefix)+ assert (target in store.written) is not already_published+ if mirror is not None:+ # Team-level vectors stay in the deployment that owns the teams, and a served model that+ # reads them could not score there, so the mirror keeps its previous manifest.+ assert mirror.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.diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pyindex cb89f8b16008..cc3d6cac8b87 100644--- a/products/signals/dags/inbox_ranking/training/dag.py+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -67,7 +67,12 @@ from products.signals.backend.ranking.features import ()from products.signals.backend.ranking.model_contract import model_feature_set, model_mismatch, trained_head_filesfrom products.signals.backend.ranking.overrides import RankingOverrides, read_ranking_overrides-from products.signals.backend.ranking.serving_manifest import DEFAULT_MODEL_KIND, ServingManifest, serving_manifest_key+from products.signals.backend.ranking.serving_manifest import (+ DEFAULT_MODEL_KIND,+ ServingManifest,+ serving_manifest_key,+ serving_project_vectors_key,+)from products.signals.dags.inbox_ranking.common import (DATASET_VERSION,PARQUET_PART_NAME,@@ -87,6 +92,7 @@ from products.signals.dags.inbox_ranking.consent import training_consent_team_idfrom products.signals.dags.inbox_ranking.dataset.dag import (EMBEDDINGS_TABLE,LABELS_TABLE,+ PROJECT_VECTORS_TABLE,STATE_TABLE,TITLE_EMBEDDINGS_TABLE,)@@ -889,6 +895,10 @@ def inbox_ranking_serving_manifest(context: dagster.AssetExecutionContext) -> Noneeds no credential for the dataset bucket. A model version is immutable, so a version alreadyat the target is left alone, and the manifest is written last: a failed copy leaves the previousmanifest, and the models it names, serving.++ When an entry reads project vectors, the dt=D `inbox_project_vectors` day is copied the same+ way, and the manifest names it. Its `as_of` is the end of dt=D, so it is never newer than a+ report the sweep scores after this publish."""if skip_unconfigured(context):return@@ -945,9 +955,15 @@ def _publish_manifest(return {"published": dagster.MetadataValue.bool(False), **pin_metadata}manifest = decision.manifest+ project_vectors_source = None+ if any(entry.reads_project_vectors for entry in manifest.models):+ project_vectors_source = partition_object_key(prefix, PROJECT_VECTORS_TABLE, partition_key)+ manifest = manifest.model_copy(update={"project_vectors": serving_project_vectors_key(prefix, partition_key)})manifest_key = serving_manifest_key(prefix)primary = _ServingStore(storage=object_storage.object_storage_client(), bucket=settings.OBJECT_STORAGE_BUCKET)- publication = publish_serving_models(context, client, bucket, prefix, manifest, primary)+ publication = publish_serving_models(+ context, client, bucket, prefix, manifest, primary, project_vectors_source=project_vectors_source+ )context.log.info(f"published serving manifest {manifest.manifest_version} serving {manifest.served.key}")mirror_published = _publish_mirror(context, client, bucket, prefix, manifest)capture_training_events(@@ -981,6 +997,7 @@ def _publish_manifest("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),+ "project_vectors_key": dagster.MetadataValue.text(manifest.project_vectors or ""),**pin_metadata,**mirror_metadata,}@@ -1050,12 +1067,23 @@ def _publish_mirror(The primary publish has already succeeded, so a mirror failure only logs: the region thattrains keeps serving, and the mirror keeps its previous manifest and models.++ Project vectors are per-team data of this deployment's teams, so they never go to another+ deployment's store. The mirror's manifest names none, and its sweep skips the models that read them.+ A served model that reads them could not score there, so the mirror keeps its previous manifest."""if not settings.INBOX_RANKING_SERVING_MIRROR_BUCKET:return None+ if manifest.served.reads_project_vectors:+ context.log.warning(+ f"serving manifest {manifest.manifest_version} not mirrored: its served model reads project vectors"+ )+ return Falsetry:mirror = _ServingStore(storage=serving_mirror_storage(), bucket=settings.INBOX_RANKING_SERVING_MIRROR_BUCKET)- publish_serving_models(context, client, bucket, prefix, manifest, mirror)+ publish_serving_models(+ context, client, bucket, prefix, manifest.model_copy(update={"project_vectors": None}), mirror+ )except Exception as error:context.log.exception(f"serving manifest {manifest.manifest_version} not mirrored: {error!r}")return False@@ -1077,13 +1105,15 @@ def publish_serving_models(prefix: str,manifest: ServingManifest,target: _ServingStore,+ *,+ project_vectors_source: str | None = None,) -> _ModelPublication:- """Copy every model the manifest names from the dataset bucket into `target`, then write the- manifest there.+ """Copy every model the manifest names from the dataset bucket into `target`, then the project+ vectors the manifest names from `project_vectors_source`, then write the manifest there.Returns the keys copied, the keys already there, and the bytes moved. A missing source object- fails before the manifest is written, so the manifest can never name a model the sweep cannot- load.+ fails before the manifest is written, so the manifest can never name a model or a project+ vectors day the sweep cannot load."""copied: list[str] = []present: list[str] = []@@ -1106,6 +1136,10 @@ def publish_serving_models(bytes_copied += len(body)copied.append(entry.key)context.log.info(f"copied {entry.key} to {target.bucket}/{entry.prefix}")+ if manifest.project_vectors is not None:+ bytes_copied += _publish_project_vectors(+ context, client, bucket, project_vectors_source, manifest.project_vectors, target+ )target.storage.write(bucket=target.bucket,key=serving_manifest_key(prefix),@@ -1115,6 +1149,28 @@ def publish_serving_models(return _ModelPublication(copied=copied, present=present, bytes_copied=bytes_copied)+def _publish_project_vectors(+ context: dagster.AssetExecutionContext,+ client,+ bucket: str,+ source: str | None,+ target_key: str,+ target: _ServingStore,+) -> int:+ """Copy one day of project vectors to `target_key`, and return the bytes moved.++ A day is immutable once the manifest names it, so a copy already at the target is left alone.+ """+ if target.storage.head_object(bucket=target.bucket, file_key=target_key) is not None:+ return 0+ body = None if source is None else _read_bytes_if_exists(client, bucket, source)+ if body is None:+ raise dagster.Failure(f"project vectors {source} are missing in the dataset bucket; manifest not written")+ target.storage.write(bucket=target.bucket, key=target_key, content=body, extras=None)+ context.log.info(f"copied project vectors to {target.bucket}/{target_key}")+ return len(body)++# dt=D evaluates scores from birth through maturity, 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(diff --git a/products/signals/dags/inbox_ranking/training/serving.py b/products/signals/dags/inbox_ranking/training/serving.pyindex ea73357c465c..d83d5fda8d71 100644--- a/products/signals/dags/inbox_ranking/training/serving.py+++ b/products/signals/dags/inbox_ranking/training/serving.py@@ -18,6 +18,7 @@ from posthog.dataclasses import frozenfrom products.signals.backend.artefact_schemas import MAX_RANKING_MODEL_RESULTSfrom products.signals.backend.ranking.model_contract import readable_head_names, trained_head_files+from products.signals.backend.ranking.model_store import ONNX_PROJECT_VECTOR_KINDS_KEYfrom products.signals.backend.ranking.serving_manifest import (CROSS_FAMILY_ROLE,DAILY_CANDIDATE_ROLE,@@ -80,6 +81,7 @@ def _entry(prefix=serving_model_prefix(prefix, key),heads=heads,model_file=ONNX_MODEL_FILE if model_kind == ONNX_MODEL_KIND else None,+ reads_project_vectors=bool(metadata.get(ONNX_PROJECT_VECTOR_KINDS_KEY)),)