: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 fixed project vectors in both regions (#126359)
posthog[bot]99f793c94d93
diff --git a/products/signals/backend/ranking/features.py b/products/signals/backend/ranking/features.pyindex f0aafb7a8da1..9d3d1090e2ad 100644--- a/products/signals/backend/ranking/features.py+++ b/products/signals/backend/ranking/features.py@@ -83,13 +83,13 @@ SOURCE_PRODUCTS = ()SOURCE_FEATURE_NAMES = (*(f"source_{product}" for product in SOURCE_PRODUCTS), "source_other")-# 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.+# The default project-vector kinds of a family, in the order a network that reads them takes them.+# The training and serving inputs both read these names, so the two sides cannot order the kinds+# differently. The pair lane and `user_offsets` read only these kinds.PROJECT_VECTOR_KINDS = ("typical", "open", "action", "dismiss")-# Every kind `project_vectors()` can build. An experiment family can read a kind the stored table-# and the serving path do not carry, such as `fixed`, which comes from the status stream.-TRAINING_PROJECT_VECTOR_KINDS = (*PROJECT_VECTOR_KINDS, "fixed")+# Every kind `project_vectors()` can build. The dataset dag's `inbox_project_vectors` writes one row+# per (team, kind) of these, and serving gives each model the kinds it reads, in its own order.+ALL_PROJECT_VECTOR_KINDS = (*PROJECT_VECTOR_KINDS, "fixed")# 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 = 5diff --git a/products/signals/backend/ranking/model_store.py b/products/signals/backend/ranking/model_store.pyindex 6c4932745e94..127eee67f47d 100644--- a/products/signals/backend/ranking/model_store.py+++ b/products/signals/backend/ranking/model_store.py@@ -36,6 +36,7 @@ from posthog.storage import object_storagefrom products.signals.backend.artefact_schemas import MAX_RANKING_MODEL_RESULTSfrom products.signals.backend.ranking.features import (+ ALL_PROJECT_VECTOR_KINDS,EMBEDDING_DIMENSIONS,PROJECT_VECTOR_KINDS,FeatureSet,@@ -71,9 +72,9 @@ 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.+# The inputs that take the team's project vectors and their history flags, in the order of the kinds+# the graph's `metadata.json` lists under `ONNX_PROJECT_VECTOR_KINDS_KEY`. Only a graph that lists+# kinds takes them.ONNX_PROJECT_INPUT = "project"ONNX_HAS_HISTORY_INPUT = "has_history"ONNX_PROJECT_VECTOR_KINDS_KEY = "project_vector_kinds"@@ -105,8 +106,13 @@ class LoadedModel:metadata: Mapping[str, Any]# A matrix in `feature_set.feature_names` order to the probabilities of each head.predict: Predict- # True when `predict` also needs the team's project vectors.- reads_project_vectors: bool = False+ # The project vector kinds `predict` also needs, in the graph's input order. Empty when the+ # model reads no project vectors.+ project_vector_kinds: tuple[str, ...] = ()++ @property+ def reads_project_vectors(self) -> bool:+ return bool(self.project_vector_kinds)@frozen@@ -188,14 +194,13 @@ class ONNXHandler:except Exception as error:raise ModelLoadError(f"{entry.key} {ONNX_MODEL_FILE} does not load: {error}") from errorkinds = tuple(metadata.get(ONNX_PROJECT_VECTOR_KINDS_KEY) or ())- if kinds and kinds != PROJECT_VECTOR_KINDS:+ if len(set(kinds)) != len(kinds) or not set(kinds) <= set(ALL_PROJECT_VECTOR_KINDS):raise ModelLoadError(- f"{entry.key} {METADATA_FILE} {ONNX_PROJECT_VECTOR_KINDS_KEY} {list(kinds)} are not {list(PROJECT_VECTOR_KINDS)}"+ f"{entry.key} {METADATA_FILE} {ONNX_PROJECT_VECTOR_KINDS_KEY} {list(kinds)} are not distinct "+ f"kinds of {list(ALL_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)- )+ mismatch = _onnx_input_mismatch(session.get_inputs(), _onnx_input_shapes(feature_set, kinds))if mismatch is not None:raise ModelLoadError(f"{entry.key} {mismatch}")output_heads = list(metadata.get(ONNX_OUTPUT_HEADS_KEY) or ())@@ -219,16 +224,16 @@ class ONNXHandler:feature_set=feature_set,metadata=metadata,predict=predict,- reads_project_vectors=reads_project_vectors,+ project_vector_kinds=kinds,)-def _onnx_input_shapes(feature_set: FeatureSet, *, reads_project_vectors: bool) -> dict[str, tuple[int, ...]]:+def _onnx_input_shapes(feature_set: FeatureSet, project_vector_kinds: Sequence[str]) -> 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),)+ if project_vector_kinds:+ shapes[ONNX_PROJECT_INPUT] = (len(project_vector_kinds), EMBEDDING_DIMENSIONS)+ shapes[ONNX_HAS_HISTORY_INPUT] = (len(project_vector_kinds),)return shapes@@ -368,14 +373,25 @@ class ProjectVectors:# False when the manifest names no object or the object is missing, so no team has vectors.available: bool+ # One row per team, in `ALL_PROJECT_VECTOR_KINDS` order.by_team: Mapping[int, ProjectInputs]+ # The kinds the day has rows for. A day written before `fixed` was stored has no `fixed` rows.+ kinds: frozenset[str] = frozenset()- 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."""+ def missing_kinds(self, kinds: Sequence[str]) -> list[str]:+ """The kinds of `kinds` the day has no rows for. A model must not read them as all-zero vectors."""+ return [kind for kind in kinds if kind not in self.kinds]++ def for_team(self, team_id: int, kinds: Sequence[str] = PROJECT_VECTOR_KINDS) -> ProjectInputs | None:+ """One row of the team's vectors in `kinds` order, 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])+ inputs = self.by_team.get(team_id) or project_inputs(+ pd.DataFrame(columns=PROJECT_VECTORS_COLUMNS), [team_id], ALL_PROJECT_VECTOR_KINDS+ )+ positions = [ALL_PROJECT_VECTOR_KINDS.index(kind) for kind in kinds]+ return ProjectInputs(vectors=inputs.vectors[:, positions], has_history=inputs.has_history[:, positions])def load_project_vectors(manifest: ServingManifest, team_ids: Collection[int]) -> ProjectVectors:@@ -392,15 +408,17 @@ def load_project_vectors(manifest: ServingManifest, team_ids: Collection[int]) -if key is not None and teams:logger.warning("inbox_ranking_project_vectors_missing", project_vectors_key=key)return ProjectVectors(available=False, by_team={})+ # The kinds come from every row, so a day without rows for these teams still says what it carries.+ kinds = frozenset(pd.read_parquet(io.BytesIO(body), columns=["kind"])["kind"].unique())rows = pd.read_parquet(io.BytesIO(body), columns=PROJECT_VECTORS_COLUMNS, filters=[("team_id", "in", teams)])- inputs = project_inputs(rows, teams)+ inputs = project_inputs(rows, teams, ALL_PROJECT_VECTOR_KINDS)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)+ return ProjectVectors(available=True, by_team=by_team, kinds=kinds)@frozendiff --git a/products/signals/backend/ranking/scorer.py b/products/signals/backend/ranking/scorer.pyindex 1b1ea8c7fc51..be3cffcb2570 100644--- a/products/signals/backend/ranking/scorer.py+++ b/products/signals/backend/ranking/scorer.py@@ -9,7 +9,9 @@ Nothing is written until every report of the call is scored, so a failure part oa 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.+repeated for each report, through the same `project_inputs` the training dag builds them with. Each+model gets its own kinds in its own order. A model that reads a kind the day has no rows for is+skipped, so it never scores on all-zero vectors.A model whose set declares the `priority` state column gets each report's latest priority judgment,read once per call and only when a model needs it. The sweep rescores a report when its vector or@@ -57,6 +59,7 @@ logger = structlog.get_logger(__name__)NO_VECTOR = "no_vector"NO_PROJECT_VECTORS = "no_project_vectors"+PROJECT_VECTOR_KINDS_MISSING = "project_vector_kinds_missing"# 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.@@ -159,7 +162,8 @@ def _score_model(report_ids: Sequence[str],rows: pd.DataFrame,vectors_by_extra: Mapping[str, Mapping[str, ReportVector]],- team_project: ProjectInputs | None,+ team_id: int,+ project_vectors: ProjectVectors | None,) -> _ModelScores:"""`rows` holds the report-state columns of the pass, one row per id of `report_ids`."""extra = _served_extra(model.feature_set)@@ -174,8 +178,13 @@ def _score_model(by_report={},skip_reason=f"state columns {unread} of {model.feature_set.name} are not served yet",)- if model.reads_project_vectors and team_project is None:- return _ModelScores(model=model, by_report={}, skip_reason=NO_PROJECT_VECTORS)+ team_project = None+ if model.reads_project_vectors:+ if project_vectors is None or not project_vectors.available:+ return _ModelScores(model=model, by_report={}, skip_reason=NO_PROJECT_VECTORS)+ if project_vectors.missing_kinds(model.project_vector_kinds):+ return _ModelScores(model=model, by_report={}, skip_reason=PROJECT_VECTOR_KINDS_MISSING)+ team_project = project_vectors.for_team(team_id, model.project_vector_kinds)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()@@ -183,7 +192,7 @@ def _score_model(return _ModelScores(model=model, by_report={}, skip_reason=None)matrix = model.feature_set.build_matrix(rows, extras, as_of=None).loc[buildable]project = None- if model.reads_project_vectors and team_project is not None:+ if 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),@@ -250,7 +259,8 @@ def score_reports(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 theproject 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.+ project vectors when the pass has none, or reads a kind the pass has no rows for, raises,+ because no report could get a served score."""if serving is None:serving = load_serving_set()@@ -266,16 +276,21 @@ def score_reports(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")+ if served.reads_project_vectors:+ if project_vectors is None or not project_vectors.available:+ raise ScoringError(f"served model {served.entry.key} reads project vectors and the pass has none")+ missing = project_vectors.missing_kinds(served.project_vector_kinds)+ if missing:+ raise ScoringError(+ f"served model {served.entry.key} reads project vector kinds {missing} the pass has no rows for"+ )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}rows = _state_rows(team_id, ids, {column for model in models for column in model.feature_set.state_columns})scored_models = {- model.entry.key: _score_model(model, ids, rows, vectors_by_extra, team_project) for model in models+ model.entry.key: _score_model(model, ids, rows, vectors_by_extra, team_id, project_vectors) for model in models}served_key = serving.manifest.served.keyserved_vectors = vectors_by_extra[served_extra]diff --git a/products/signals/backend/test/test_ranking_scoring.py b/products/signals/backend/test/test_ranking_scoring.pyindex 4286f5ab8fe0..e826a631c4c9 100644--- a/products/signals/backend/test/test_ranking_scoring.py+++ b/products/signals/backend/test/test_ranking_scoring.py@@ -29,6 +29,7 @@ from products.signals.backend.artefact_schemas import RankingModelResult, Rankinfrom products.signals.backend.models import SignalReport, SignalReportArtefactfrom products.signals.backend.ranking import model_store, scorerfrom products.signals.backend.ranking.features import (+ ALL_PROJECT_VECTOR_KINDS,EMBEDDING_DIMENSIONS,MIN_PROJECT_HISTORY_REPORTS,PROJECT_VECTOR_KINDS,@@ -38,7 +39,13 @@ from products.signals.backend.ranking.features import ()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_PROJECT_VECTORS, NO_VECTOR, ScoringError, score_reports+from products.signals.backend.ranking.scorer import (+ NO_PROJECT_VECTORS,+ NO_VECTOR,+ PROJECT_VECTOR_KINDS_MISSING,+ ScoringError,+ score_reports,+)from products.signals.backend.ranking.serving_manifest import (CROSS_FAMILY_ROLE,MANIFEST_SERVED_ROLE,@@ -258,13 +265,31 @@ class TestModelStore(_StoreTestMixin, SimpleTestCase):"inputs ['has_history', 'project', 'report'] are not ['report']",),(- "onnx_project_kinds_in_another_order",+ "onnx_project_kind_unknown",+ {+ "model_kind": ONNX_MODEL_KIND,+ "onnx_fixture": "project_report.onnx",+ "project_vector_kinds": ("typical", "open", "action", "closed"),+ },+ "project_vector_kinds ['typical', 'open', 'action', 'closed'] are not distinct",+ ),+ (+ "onnx_project_kind_repeated",{"model_kind": ONNX_MODEL_KIND,"onnx_fixture": "project_report.onnx",- "project_vector_kinds": ("open", "typical", "action", "dismiss"),+ "project_vector_kinds": ("typical", "open", "open", "dismiss"),},- "project_vector_kinds ['open', 'typical', 'action', 'dismiss']",+ "project_vector_kinds ['typical', 'open', 'open', 'dismiss'] are not distinct",+ ),+ (+ "onnx_project_kinds_wider_than_the_graph",+ {+ "model_kind": ONNX_MODEL_KIND,+ "onnx_fixture": "project_report.onnx",+ "project_vector_kinds": ALL_PROJECT_VECTOR_KINDS,+ },+ "input project is tensor(float)",),])@@ -441,14 +466,16 @@ 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:+ def _project_model(+ self, roles: Sequence[str], kinds: Sequence[str] = PROJECT_VECTOR_KINDS, name: str = "nn"+ ) -> ServingManifestEntry:return self.store.publish_model(- "nn",+ name,REPORT_EMBEDDINGS_FEATURE_SET,roles=roles,model_kind=ONNX_MODEL_KIND,onnx_fixture="project_report.onnx",- project_vector_kinds=PROJECT_VECTOR_KINDS,+ project_vector_kinds=kinds,)def test_an_onnx_model_reads_the_team_project_vectors(self) -> None:@@ -499,6 +526,35 @@ class TestScorer(_ScorerTestMixin, SimpleTestCase):with self.assertRaisesRegex(ScoringError, "reads project vectors"):self._score(["r1"], vectors, persist=False)+ def test_a_model_that_reads_a_kind_the_day_lacks_is_skipped_or_stops_the_served_score(self) -> None:+ expected = np.load(ONNX_FIXTURES / "project_report.expected.npz")+ # The published day carries the four default kinds only, like a day written before `fixed` was stored.+ key = self.store.publish_project_vectors(self.team_id, expected["project"], expected["has_history"])+ 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])+ fixed = self._project_model([CROSS_FAMILY_ROLE], kinds=("typical", "open", "action", "fixed"), name="nn_fixed")+ self.store.publish_manifest([served, nn, fixed], project_vectors=key)++ (outcome,), _, _ = self._score(["r1"], vectors, persist=False)++ assert outcome.score is not None+ results = outcome.score.results+ assert results[nn.key].status == "scored"+ assert (results[fixed.key].status, results[fixed.key].skip_reason) == (+ "skipped",+ PROJECT_VECTOR_KINDS_MISSING,+ )++ model_store.clear_model_cache()+ self.store.publish_manifest(+ [self._project_model([SERVED_ROLE], kinds=("typical", "open", "action", "fixed"), name="nn_fixed")],+ project_vectors=key,+ )+ with self.assertRaisesRegex(ScoringError, r"reads project vector kinds \['fixed'\]"):+ 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/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.mdindex 111a8ac77439..d02ef0a23bcf 100644--- a/products/signals/dags/inbox_ranking/AGENTS.md+++ b/products/signals/dags/inbox_ranking/AGENTS.md@@ -7,10 +7,10 @@ Read `README.md` first for what the dataset is and how partitions behave. This f- A new ranking dag (training, eval, ...) is a **sibling subpackage** (`inbox_ranking/<name>/dag.py`) importing shared plumbing from `common.py` — don't grow `dataset/` sideways and don't duplicate the S3/partition helpers.- `inbox_report_title_embeddings` is a **leaf**: never add it to `inbox_report_model_data`'s `deps` or give that join a title column, or a failure in the title snapshot fails the training table. Its own `deps=[MODEL_DATA_TABLE]` exists for memory, not data — two full sets of 1536-float vectors must not be held at once in the run pod. Raising the pod memory limit is not the first resort.- `inbox_user_report_interactions` is a **leaf** with its own `USER_INTERACTIONS_SCHEMA_VERSION`: keep it out of `inbox_report_model_data`'s `deps`, and never stamp it with `FEATURE_SCHEMA_VERSION`, or a user-grain change sets off the labels refresh sensor. It writes a row only for a report in this region's Postgres whose team is in `training_consent_team_ids()`.-- `inbox_project_vectors` is a **leaf** with its own `PROJECT_VECTORS_SCHEMA_VERSION`: keep it out of `inbox_report_model_data`'s `deps`. Its `deps=[EMBEDDINGS_TABLE, LABELS_TABLE]` keep it after the embeddings snapshot, so the two vector-heavy steps do not share the run pod's memory. `project_vectors` takes a report into a vector only when its vector landed and its engagement moment (a UI event, or `first_fixed_at` for `fixed`) happened strictly before `as_of`; never widen that to the latest snapshot value. A report born on day D reads the dt=D−1 vectors (see the README). Keep `first_fixed_at` out of `LABEL_COLUMNS`, because the engagement export carries exactly those columns; training readers load `CONTEXT_LABEL_COLUMNS`.+- `inbox_project_vectors` is a **leaf** with its own `PROJECT_VECTORS_SCHEMA_VERSION`: keep it out of `inbox_report_model_data`'s `deps`. Its `deps=[EMBEDDINGS_TABLE, LABELS_TABLE]` keep it after the embeddings snapshot, so the two vector-heavy steps do not share the run pod's memory. `project_vectors` takes a report into a vector only when its vector landed and its engagement moment (a UI event, or `first_fixed_at` for `fixed`) happened strictly before `as_of`; never widen that to the latest snapshot value. A report born on day D reads the dt=D−1 vectors (see the README). It writes every kind of `ALL_PROJECT_VECTOR_KINDS` from `CONTEXT_LABEL_COLUMNS`. `LABEL_COLUMNS` holds the UI engagement columns only, without `first_fixed_at`.- `inbox_user_vectors` is a **leaf** with its own `USER_VECTORS_SCHEMA_VERSION`: keep it out of `inbox_report_model_data`'s `deps`. Its `deps=[PROJECT_VECTORS_TABLE, USER_INTERACTIONS_TABLE]` keep it after the project vectors, so two reads of the embeddings snapshot do not share the run pod's memory. It builds its rows through `user_vectors()` with the same consent re-filter and `team_organizations` mapping as the pair lane, so its dt=D rows equal what `pair_user_vectors` rebuilds for a report born on D+1; a test pins that parity. `user_hash` covers each kind's name, `n_reports` and vector only, so a day that adds no report keeps a user's hash.-- `inbox_engagement_export` is a **leaf** with its own `ENGAGEMENT_EXPORT_SCHEMA_VERSION`, read by another region. It writes to the mirror store only under `serving_engagement_key`, because the mirror's write grant covers only `<prefix>/serving/`. Keep its columns exactly `LABEL_COLUMNS` and its rows limited to reports with no `SignalReport` in this region: no team ids, counts, text or vectors leave the region. A mirror failure logs and must not fail the asset. Keep the local-share guard before the write: when the local report lookup finds no local report (`no_local_reports`) or a share below `ENGAGEMENT_EXPORT_MIN_LOCAL_SHARE` (`local_share_collapsed`), the asset writes nothing and still succeeds. Its `inbox_ranking_engagement_export_published` event carries counts only, never a report id or a team id.-- `inbox_mirror_project_vectors` (`mirror/dag.py`) is the only inbox-ranking asset that registers on EU (`is_inbox_ranking_mirror_registered()`). It reads this region's report vectors through `report_embeddings_table` and the engagement export through `serving_engagement_key`, and writes only to this region's object store at `serving_project_vectors_key`. Keep it on the same `project_vectors()` and the same consent rule as `inbox_project_vectors`, so the two regions build their vectors the same way. A missing, too old or unknown-schema export fails the asset rather than writing vectors without engagement.+- `inbox_engagement_export` is a **leaf** with its own `ENGAGEMENT_EXPORT_SCHEMA_VERSION`, read by another region. It writes to the mirror store only under `serving_engagement_key`, because the mirror's write grant covers only `<prefix>/serving/`. Keep its columns exactly `ENGAGEMENT_EXPORT_COLUMNS` (report ids and engagement timestamps) and its rows limited to reports with no `SignalReport` in this region: no team ids, counts, text or vectors leave the region. A mirror failure logs and must not fail the asset. Keep the local-share guard before the write: when the local report lookup finds no local report (`no_local_reports`) or a share below `ENGAGEMENT_EXPORT_MIN_LOCAL_SHARE` (`local_share_collapsed`), the asset writes nothing and still succeeds. Its `inbox_ranking_engagement_export_published` event carries counts only, never a report id or a team id.+- `inbox_mirror_project_vectors` (`mirror/dag.py`) is the only inbox-ranking asset that registers on EU (`is_inbox_ranking_mirror_registered()`). It reads this region's report vectors through `report_embeddings_table` and the engagement export through `serving_engagement_key`, and writes only to this region's object store at `serving_project_vectors_key`. Keep it on the same `project_vectors()` and the same consent rule as `inbox_project_vectors`, so the two regions build their vectors the same way. A missing, too old or unknown-schema export fails the asset rather than writing vectors without engagement. The two regions deploy apart, so the reader takes the current export schema version and the one before it: a v1 export has no `first_fixed_at`, so its day carries four kinds and no `fixed` rows.- `inbox_activity_summary_vectors` is a **leaf** with its own `ACTIVITY_SUMMARY_VECTORS_SCHEMA_VERSION`: keep it out of `inbox_report_model_data`'s `deps`, and never select the summary text (`content`). It is the only durable copy of the activity summary vectors once the source TTL passes, so a re-run must keep the rows the source no longer returns (`merge_activity_summary_vectors`). Training reads a user's vector at a moment through `activity_vector_as_of`, never the newest vector of the user.- Register new jobs/schedules in `posthog/dags/locations/signals.py` (or `signals_ml.py` for a torch-dependent dag), keep the EU gate (`is_inbox_ranking_registered()`), and remember the ci-dagster paths filter must cover every module a dag file imports (`uv run .github/scripts/check-dagster-paths.py`).@@ -41,7 +41,7 @@ Read `README.md` first for what the dataset is and how partitions behave. This f- The `recent` role keeps the newest `INBOX_RANKING_SERVING_RECENT_VERSIONS` versions of the served `model_name`, read from the last 2N partitions, so each version gets several days of online scores. The `challenger` role keeps the newest readable version of each other serving family (`serving_families()`), read from its last 2 partitions. Each one passes the pin check before composition, because one missing file fails the publish. Keep the order under the cap as served, recent, challenger, pinned, cross-family. Each recent entry is one more model per sweep pass, so measure the sweep's duration, peak RSS and scored and deferred counts on the `inbox_ranking_sweep_finished` log before and after a change to N.- Publishing order is load-bearing. Every model copy finishes before `manifest.json` is written, so a failed copy leaves the previous manifest and the previous models serving. A model version is immutable, so a version whose `metadata.json` is already at the target is not copied again. A run with nothing to publish, such as a run without `served.json`, writes nothing rather than an empty manifest. The served model passes the same check as a pin (`_pin_metadata`) before composition.- The manifest asset copies the dt=D `inbox_user_vectors` day to `serving/user_vectors/<D>/` before `manifest.json` and names it in `user_vectors`. No model reads it yet, so a missing day or a failed copy only logs and leaves the key out; it never blocks a publish. Never copy user vectors to the mirror: the mirror's manifest always names none.-- 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, and never read the body of a mirror object: they are per-team data of the deployment that owns the teams. The mirror's manifest names the mirror region's own day only after `_mirror_project_vectors` checks its object metadata (`PROJECT_VECTORS_*_METADATA_KEY` in `serving_manifest.py`) within `MIRROR_PROJECT_VECTORS_MAX_LAG_DAYS`. Without such a day it names none, and a served model that reads them keeps the mirror on its previous manifest. 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. Only a report-grain experiment can set its family's `project_vector_kinds` to other kinds from `TRAINING_PROJECT_VECTOR_KINDS`; the stored table, serving and the pair lane stay on `PROJECT_VECTOR_KINDS`.+- 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, and never read the body of a mirror object: they are per-team data of the deployment that owns the teams. The mirror's manifest names the mirror region's own day only after `_mirror_project_vectors` checks its object metadata (`PROJECT_VECTORS_*_METADATA_KEY` in `serving_manifest.py`) within `MIRROR_PROJECT_VECTORS_MAX_LAG_DAYS`. Without such a day it names none, and a served model that reads them keeps the mirror on its previous manifest. `_project_vectors_refusal` takes the current project-vectors schema version and the one before it, so a mirror region that deploys later does not hold the mirror on an old manifest. 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. Only a report-grain experiment can set its family's `project_vector_kinds` to other kinds from `ALL_PROJECT_VECTOR_KINDS`; the pair lane and `user_offsets` stay on `PROJECT_VECTOR_KINDS`. Serving loads every kind of the day and gives each model its own kinds in its own order. A model that reads a kind the day has no rows for is skipped with `project_vector_kinds_missing`, and a served model that hits it fails the pass like `no_project_vectors`; never feed it all-zero vectors instead.- `HEADS` holds only the heads the inbox reads (`HeadRanker` in `backend/ranking/inbox_sort.py`). Add a head there only together with a surface that reads it. The promotion gate skips a champion head that is not in `HEADS`, so a trim does not block promotion.- `nn_v3` and `nn_with_prio_v2` are trained by the `signals_ml` location (`nn/dag.py`), never by the main one. They share one `inbox_ranking_nn_examples` object, and each has its own candidate and champion asset from `family_assets`. The `nn_v3` assets keep the names `inbox_ranking_nn_model_{candidate,champion}`, so their Dagster history continues. A later family's candidate depends on the previous family's champion, for memory and not for data: two candidates at once can exceed the job's memory limit. A family whose set reads a state column the examples object lacks skips with a warning rather than training on zeros. torch is imported only inside the candidate asset's body (through `nn/train.py` and `multihead/network.py`). `signals_ml` must import without torch, and `test_multihead_network.py` pins that. Its decision goes through `decide_family_champion` in `training/dag.py`, graded through the incumbent's `model.holdout.onnx`. Keep `signals_ml` commented out in `.dagster_home/workspace.yaml`, and keep its schedule (04:30 UTC) running by default on prod US only.diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex c2a9a4e8a0fe..d60dabea9372 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -67,9 +67,10 @@ The first four are report grain and land in one table. `inbox_signal_embeddings`| `open` | the last 50 reports anyone on the team opened before `as_of` || `action` | the last 50 reports anyone on the team acted on through a UI intent action (`UI_ACTION_COLUMNS`) || `dismiss` | the last 50 reports anyone on the team dismissed from the UI |+| `fixed` | the last 50 reports the team got fixed (`first_fixed_at`, from the status stream) |- The columns are `team_id`, `kind`, `vector` (small-1536), `n_reports` and `as_of`.-- The inputs are the dt=D `inbox_report_embeddings` and `inbox_report_labels` snapshots only. The engagement moments are the labels' first-event timestamps of the inbox app events, so MCP reads and agent actions never count. A project is a team, not an organization.+- The inputs are the dt=D `inbox_report_embeddings` and `inbox_report_labels` snapshots only. The `open`, `action` and `dismiss` moments are the labels' first-event timestamps of the inbox app events, so MCP reads and agent actions never count there. The `fixed` moment comes from the status stream, so a fix through an agent counts. A project is a team, not an organization.- A kind with fewer than `MIN_HISTORY_REPORTS` reports keeps its row, with its real `n_reports` and an all-zero vector. A team with no report vector before `as_of` has no rows.- The asset filters the embeddings snapshot through `training_consent_team_ids()` again, so an opt-out after the snapshot was written takes effect.- **It is a leaf.** Nothing joins it, it is not in `inbox_report_model_data`'s deps, and its object carries its own `PROJECT_VECTORS_SCHEMA_VERSION`, so a failure here does not fail the training table. Its deps on the embeddings and labels assets keep it after the embeddings snapshot, so the two vector-heavy steps do not share the run pod's memory.@@ -80,6 +81,7 @@ Point-in-time contract:- 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.+- Serving loads every kind of the day and gives each model the kinds its `metadata.json` lists, in that order. A day written before `PROJECT_VECTORS_SCHEMA_VERSION` 2, or a mirror day built from a v1 engagement export, has no `fixed` rows. A model that reads a kind the day has no rows for is skipped with `project_vector_kinds_missing`. When the served model hits it, the pass fails.### User vectors@@ -92,12 +94,12 @@ The asset calls it with `as_of` = the end of dt=D, on the dt=D interactions and### Engagement export-`inbox_engagement_export` sends the UI engagement moments of the other region's reports to the mirror store, so that region can build its own project vectors from its own report embeddings.-The inbox telemetry of every region lands in the US dogfood project, so the `open`, `action` and `dismiss` moments of an EU report exist only in the US labels snapshot.+`inbox_engagement_export` sends the engagement moments of the other region's reports to the mirror store, so that region can build its own project vectors from its own report embeddings.+The inbox telemetry of every region lands in the US dogfood project, so the `open`, `action`, `dismiss` and `fixed` moments of an EU report exist only in the US labels snapshot.- It runs only when `INBOX_RANKING_SERVING_MIRROR_BUCKET` is set. Otherwise it logs and writes nothing.- The rows are the dt=D labels rows whose `report_id` has no `SignalReport` in this region's Postgres before the cutoff. A row whose id is not a UUID is dropped.-- The columns are exactly `LABEL_COLUMNS` from `dataset/project_vectors.py`: `report_id` and the first opened, first UI dismissed and first UI action timestamps. There are no team ids, no counts, no text and no vectors, so the other region passes the file to `project_vectors()` unchanged.+- The columns are exactly `ENGAGEMENT_EXPORT_COLUMNS` from `dataset/project_vectors.py`: `report_id` and the first opened, first UI dismissed, first UI action and first fixed timestamps. There are no team ids, no counts, no text and no vectors, so the other region passes the file to `project_vectors()` unchanged.- The labels snapshot is cumulative, so each day is a full snapshot as of the end of dt=D.- The key is `serving_engagement_key(prefix, dt)`: `<prefix>/serving/engagement/<dt>/engagement.parquet`. The mirror's write grant covers only `<prefix>/serving/`. The write sets `ACL: bucket-owner-full-control` and stamps the row count, the snapshot date and `ENGAGEMENT_EXPORT_SCHEMA_VERSION` in the object metadata.- **It is a leaf.** Nothing joins it. A mirror write failure does not fail the asset: it logs, and the output metadata carries `written=false`. The metadata also carries `rows`, `excluded_rows` (the rows whose report is in this region), `local_share` (`excluded_rows` over all labels rows), `bytes` and `s3_key`.@@ -114,7 +116,7 @@ The report vectors of a region exist only in its own ClickHouse, so the training- It registers on EU only (`is_inbox_ranking_mirror_registered()`), in its own daily job `inbox_ranking_mirror_job` at 05:30 UTC, after the training region's dataset run.- The schedule skips its ticks until `INBOX_RANKING_MIRROR_PROJECT_VECTORS_ENABLED` is set. A run by hand works without it.- The report vectors come from `report_embeddings_table`, the same function the `inbox_report_embeddings` snapshot uses, for the teams in this region's `training_consent_team_ids()`.-- The engagement moments come from the dt=D engagement export at `serving_engagement_key`, in this region's object store. When dt=D is missing, it uses the newest export up to `ENGAGEMENT_EXPORT_MAX_AGE_DAYS` older and logs a warning. When none is in that window, or the export has another schema version, the asset fails.+- The engagement moments come from the dt=D engagement export at `serving_engagement_key`, in this region's object store. When dt=D is missing, it uses the newest export up to `ENGAGEMENT_EXPORT_MAX_AGE_DAYS` older and logs a warning. When none is in that window, or the export has a schema version the reader does not know, the asset fails. The reader takes `ENGAGEMENT_EXPORT_SCHEMA_VERSION` and the version before it, because the two regions deploy apart. A v1 export has no `first_fixed_at`, so the day gets four kinds and no `fixed` rows.- It calls `project_vectors()` in memory with `as_of` at the end of dt=D, and writes no dataset object.- The output is `serving_project_vectors_key(prefix, dt)` in this region's object store, stamped with the row count, the snapshot date, `PROJECT_VECTORS_SCHEMA_VERSION` and the export date it read.- The output metadata carries the rows, the teams, the teams with enough history for each kind, the export date and its age.diff --git a/products/signals/dags/inbox_ranking/dataset/dag.py b/products/signals/dags/inbox_ranking/dataset/dag.pyindex 44ff89985e08..0231c4ee8c32 100644--- a/products/signals/dags/inbox_ranking/dataset/dag.py+++ b/products/signals/dags/inbox_ranking/dataset/dag.py@@ -142,8 +142,10 @@ from products.signals.dags.inbox_ranking.common import ()from products.signals.dags.inbox_ranking.consent import training_consent_team_idsfrom products.signals.dags.inbox_ranking.dataset.project_vectors import (+ CONTEXT_KINDS,+ CONTEXT_LABEL_COLUMNS,EMBEDDING_COLUMNS,- LABEL_COLUMNS,+ ENGAGEMENT_EXPORT_COLUMNS,PROJECT_VECTORS_SCHEMA_VERSION,USER_INTERACTION_COLUMNS,USER_VECTORS_SCHEMA_VERSION,@@ -205,7 +207,7 @@ ACTIVITY_SUMMARY_VECTORS_TABLE = "inbox_activity_summary_vectors"REVIEWERS_SCHEMA_VERSION = 1# The engagement export is read in another region, so its shape moves apart from every local snapshot.-ENGAGEMENT_EXPORT_SCHEMA_VERSION = 1+ENGAGEMENT_EXPORT_SCHEMA_VERSION = 2# The activity summary vectors are a (team, user, day) leaf, so their shape moves apart too.ACTIVITY_SUMMARY_VECTORS_SCHEMA_VERSION = 1# Every document type that carries an activity summary vector. A backfilled type joins this tuple,@@ -1501,9 +1503,9 @@ def inbox_project_vectors(context: dagster.AssetExecutionContext) -> None:excluded_reports = embeddings.num_rows - consented.num_rowsdel embeddingslabels = read_parquet(- client, bucket, partition_object_key(prefix, LABELS_TABLE, partition_key), list(LABEL_COLUMNS)+ client, bucket, partition_object_key(prefix, LABELS_TABLE, partition_key), list(CONTEXT_LABEL_COLUMNS))- table = project_vectors(labels, consented, snapshot_end)+ table = project_vectors(labels, consented, snapshot_end, CONTEXT_KINDS)key = partition_object_key(prefix, PROJECT_VECTORS_TABLE, partition_key)write_parquet(client, bucket, key, table, schema_version=PROJECT_VECTORS_SCHEMA_VERSION)@@ -1513,7 +1515,7 @@ def inbox_project_vectors(context: dagster.AssetExecutionContext) -> None:"teams": dagster.MetadataValue.int(len(set(table.column("team_id").to_pylist()))),**{f"teams_with_{kind}_history": dagster.MetadataValue.int(count)- for kind, count in teams_with_history(table).items()+ for kind, count in teams_with_history(table, CONTEXT_KINDS).items()},"excluded_no_training_consent_reports": dagster.MetadataValue.int(excluded_reports),"s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),@@ -1751,11 +1753,11 @@ def engagement_export_refusal(label_rows: int, local_rows: int) -> str | None:**COMMON_ASSET_KWARGS,)def inbox_engagement_export(context: dagster.AssetExecutionContext) -> None:- """Export the UI engagement moments of the other region's reports to the mirror store.+ """Export the engagement moments of the other region's reports to the mirror store.The other region builds its project vectors from its own report embeddings, but the open,- action and dismiss moments exist only in this region's labels snapshot. The export carries- only `LABEL_COLUMNS`: report ids and timestamps, no team ids, no text and no vectors. The+ action, dismiss and fixed moments exist only in this region's labels snapshot. The export+ carries only `ENGAGEMENT_EXPORT_COLUMNS`: report ids and timestamps, no team ids, no text and no vectors. Thelabels snapshot is cumulative, so each day is a full snapshot as of the end of dt=D."""if skip_unconfigured(context):@@ -1769,7 +1771,10 @@ def inbox_engagement_export(context: dagster.AssetExecutionContext) -> None:prefix = settings.INBOX_RANKING_DATASET_S3_PREFIXlabels = read_parquet(- s3_client(), dataset_bucket(), partition_object_key(prefix, LABELS_TABLE, partition_key), list(LABEL_COLUMNS)+ s3_client(),+ dataset_bucket(),+ partition_object_key(prefix, LABELS_TABLE, partition_key),+ list(ENGAGEMENT_EXPORT_COLUMNS),)# telemetry imports the training modules, which import this module.from products.signals.dags.inbox_ranking.training.telemetry import ( # noqa: PLC0415diff --git a/products/signals/dags/inbox_ranking/dataset/project_vectors.py b/products/signals/dags/inbox_ranking/dataset/project_vectors.pyindex f6728f25f2a4..48a828e86892 100644--- a/products/signals/dags/inbox_ranking/dataset/project_vectors.py+++ b/products/signals/dags/inbox_ranking/dataset/project_vectors.py@@ -12,9 +12,9 @@ gets one vector per kind, as of a moment:The open, action and dismiss moments come from the inbox app events, so only human UI engagementcounts there, and MCP reads and agent actions never reach those vectors. The fixed moment comes from-the status stream, so a fix through an agent or a merged PR counts. The stored table and serving-carry the first four kinds only. `fixed` is built only for a family that asks for it in training,-from the labels snapshot's `first_fixed_at`. A project is a team, not an organization.+the status stream, so a fix through an agent or a merged PR counts. The stored table carries all five+kinds, and serving gives each model the kinds it reads. A family reads `PROJECT_VECTOR_KINDS` unless+it asks for others. A project is a team, not an organization.`user_vectors` builds the same kind of vector for one person in one organization, from the`inbox_user_report_interactions` rows of the reports that person viewed or dismissed:@@ -42,32 +42,34 @@ import pyarrow.compute as pcfrom posthog.dataclasses import frozenfrom products.signals.backend.ranking.features import (+ ALL_PROJECT_VECTOR_KINDS,EMBEDDING_DIMENSIONS,MIN_PROJECT_HISTORY_REPORTS,PROJECT_VECTOR_KINDS,- TRAINING_PROJECT_VECTOR_KINDS,USER_HISTORY_KINDS,)from products.signals.dags.inbox_ranking.dataset.queries import ACTION_TYPESfrom products.signals.dags.inbox_ranking.training.heads import UI_ACTION_COLUMNS# A leaf with its own columns, so its schema moves apart from FEATURE_SCHEMA_VERSION.-PROJECT_VECTORS_SCHEMA_VERSION = 1+PROJECT_VECTORS_SCHEMA_VERSION = 2HISTORY_LIMIT = 50# The backend owns the kinds and the threshold, because the scoring sweep builds the same inputs.MIN_HISTORY_REPORTS = MIN_PROJECT_HISTORY_REPORTSVECTOR_KINDS = PROJECT_VECTOR_KINDS-CONTEXT_KINDS = TRAINING_PROJECT_VECTOR_KINDS+CONTEXT_KINDS = ALL_PROJECT_VECTOR_KINDSTYPICAL, OPEN, ACTION, DISMISS, FIXED = CONTEXT_KINDSOPEN_COLUMN = "first_opened_at"DISMISS_COLUMN = "first_ui_dismissed_at"FIXED_COLUMN = "first_fixed_at"UI_ACTION_FIRST_COLUMNS = tuple(first for _, count, first in ACTION_TYPES if count in UI_ACTION_COLUMNS)-# The engagement export carries exactly these columns to the other region, so `fixed` stays out.+# The UI engagement columns of the labels snapshot. `fixed` comes from the status stream instead.LABEL_COLUMNS = ("report_id", OPEN_COLUMN, DISMISS_COLUMN, *UI_ACTION_FIRST_COLUMNS)CONTEXT_LABEL_COLUMNS = (*LABEL_COLUMNS, FIXED_COLUMN)+# The engagement export carries exactly these columns to the other region.+ENGAGEMENT_EXPORT_COLUMNS = CONTEXT_LABEL_COLUMNSEMBEDDING_COLUMNS = ("report_id", "report_team_id", "embedding_small", "embedding_inserted_at", "is_tombstone")_PROJECT_VECTORS_FIELDS: list[tuple[str, pa.DataType]] = [@@ -133,7 +135,7 @@ def project_vectors(A kind with fewer than `MIN_HISTORY_REPORTS` reports keeps its row, with its real `n_reports`and an all-zero vector, so a reader can tell a thin history from a missing team. `kinds` defaults- to the stored table's kinds. Asking for `fixed` needs the `first_fixed_at` column in `labels`.+ to `PROJECT_VECTOR_KINDS`. Asking for `fixed` needs the `first_fixed_at` column in `labels`."""unknown = [kind for kind in kinds if kind not in CONTEXT_KINDS]if unknown:diff --git a/products/signals/dags/inbox_ranking/mirror/dag.py b/products/signals/dags/inbox_ranking/mirror/dag.pyindex d447ec1fadf4..138f0a810448 100644--- a/products/signals/dags/inbox_ranking/mirror/dag.py+++ b/products/signals/dags/inbox_ranking/mirror/dag.py@@ -6,7 +6,7 @@ region's report vectors exist only in its own ClickHouse. So this region buildssame `project_vectors()` the training region uses:report vectors this region's ClickHouse, through `report_embeddings_table`- UI engagement the training region's `inbox_engagement_export` in this region's object store+ engagement the training region's `inbox_engagement_export` in this region's object storeThe output lands in this region's object store at `serving_project_vectors_key`, which the servedmanifest can name.@@ -46,8 +46,11 @@ from products.signals.dags.inbox_ranking.dataset.dag import (tag_dagster_queries,)from products.signals.dags.inbox_ranking.dataset.project_vectors import (+ CONTEXT_KINDS,+ ENGAGEMENT_EXPORT_COLUMNS,LABEL_COLUMNS,PROJECT_VECTORS_SCHEMA_VERSION,+ VECTOR_KINDS,project_vectors,teams_with_history,)@@ -59,11 +62,27 @@ MIRROR_PROJECT_VECTORS_ASSET = "inbox_mirror_project_vectors"ENGAGEMENT_EXPORT_MAX_AGE_DAYS = 2+@frozen+class _ExportShape:+ columns: tuple[str, ...]+ kinds: tuple[str, ...]+++# The two regions deploy apart, so this reader also takes the version before the current one. A v1+# export has no `first_fixed_at`, so its day has no `fixed` rows.+_EXPORT_SHAPES: dict[str, _ExportShape] = {+ "1": _ExportShape(columns=LABEL_COLUMNS, kinds=VECTOR_KINDS),+ str(ENGAGEMENT_EXPORT_SCHEMA_VERSION): _ExportShape(columns=ENGAGEMENT_EXPORT_COLUMNS, kinds=CONTEXT_KINDS),+}++@frozenclass EngagementExport:export_date: strage_days: intlabels: pa.Table+ # The project vector kinds the labels can build.+ kinds: tuple[str, ...]def read_engagement_export(@@ -81,16 +100,17 @@ def read_engagement_export(if head is None:continueschema_version = head.get("Metadata", {}).get(SCHEMA_VERSION_METADATA_KEY)- if schema_version != str(ENGAGEMENT_EXPORT_SCHEMA_VERSION):+ shape = _EXPORT_SHAPES.get(schema_version or "")+ if shape is None:raise dagster.Failure(f"engagement export {key} has schema version {schema_version}, "- f"this reader knows {ENGAGEMENT_EXPORT_SCHEMA_VERSION}"+ f"this reader knows {sorted(_EXPORT_SHAPES)}")body = storage.read_bytes(bucket, key)if body is None:continue- labels = pq.read_table(pa.BufferReader(body), columns=list(LABEL_COLUMNS))- return EngagementExport(export_date=export_date, age_days=age_days, labels=labels)+ labels = pq.read_table(pa.BufferReader(body), columns=list(shape.columns))+ return EngagementExport(export_date=export_date, age_days=age_days, labels=labels, kinds=shape.kinds)return None@@ -120,7 +140,7 @@ def inbox_mirror_project_vectors(context: dagster.AssetExecutionContext) -> Noneconsent_team_ids = training_consent_team_ids()embeddings = report_embeddings_table(partition_key, EMBEDDING_RENDERING_TITLE_SUMMARY, consent_team_ids)embedding_rows = embeddings.num_rows- table = project_vectors(export.labels, embeddings, snapshot_end)+ table = project_vectors(export.labels, embeddings, snapshot_end, export.kinds)del embeddingsbuffer = io.BytesIO()@@ -146,7 +166,7 @@ def inbox_mirror_project_vectors(context: dagster.AssetExecutionContext) -> None"teams": dagster.MetadataValue.int(len(set(table.column("team_id").to_pylist()))),**{f"teams_with_{kind}_history": dagster.MetadataValue.int(count)- for kind, count in teams_with_history(table).items()+ for kind, count in teams_with_history(table, export.kinds).items()},"embedding_rows": dagster.MetadataValue.int(embedding_rows),"engagement_rows": dagster.MetadataValue.int(export.labels.num_rows),diff --git a/products/signals/dags/inbox_ranking/tests/test_project_vectors.py b/products/signals/dags/inbox_ranking/tests/test_project_vectors.pyindex 7ec46008b049..2ed984e99212 100644--- a/products/signals/dags/inbox_ranking/tests/test_project_vectors.py+++ b/products/signals/dags/inbox_ranking/tests/test_project_vectors.py@@ -12,7 +12,7 @@ import pyarrow.parquet as pqfrom parameterized import parameterizedfrom products.signals.backend.ranking import model_store-from products.signals.backend.ranking.features import EMBEDDING_DIMENSIONS+from products.signals.backend.ranking.features import EMBEDDING_DIMENSIONS, PROJECT_VECTOR_KINDSfrom products.signals.backend.ranking.serving_manifest import (PROJECT_VECTORS_ENGAGEMENT_DATE_METADATA_KEY,SERVED_ROLE,@@ -27,6 +27,7 @@ from products.signals.dags.inbox_ranking.dataset import dagfrom products.signals.dags.inbox_ranking.dataset.dag import EMBEDDINGS_SCHEMA, LABELS_SCHEMA, USER_INTERACTIONS_SCHEMAfrom products.signals.dags.inbox_ranking.dataset.project_vectors import (CONTEXT_KINDS,+ ENGAGEMENT_EXPORT_COLUMNS,HISTORY_LIMIT,LABEL_COLUMNS,MIN_HISTORY_REPORTS,@@ -219,9 +220,12 @@ def test_user_vectors_average_the_last_reports_and_skip_a_user_without_history()def test_the_asset_writes_only_teams_opted_in_to_ai_training(monkeypatch) -> None:partition_key = (AS_OF.date() - datetime.timedelta(days=1)).isoformat()reports = [(team_id, index, 1.0, BEFORE) for team_id in (2, 7) for index in range(MIN_HISTORY_REPORTS)]+ # One fix lands at as_of, so it must stay out of the stored `fixed` vector.+ fixes = [(7, index, "first_fixed_at", BEFORE) for index in range(MIN_HISTORY_REPORTS - 1)]+ fixes.append((7, MIN_HISTORY_REPORTS - 1, "first_fixed_at", AS_OF))snapshots = {common.partition_object_key("inbox_ranking", dag.EMBEDDINGS_TABLE, partition_key): _embeddings(reports),- common.partition_object_key("inbox_ranking", dag.LABELS_TABLE, partition_key): _labels([]),+ common.partition_object_key("inbox_ranking", dag.LABELS_TABLE, partition_key): _labels(fixes),}captured: dict[str, Any] = {}@@ -242,6 +246,9 @@ 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}+ rows = _rows_by_key(captured["table"])+ assert {kind for _, kind in rows} == set(CONTEXT_KINDS)+ assert rows[(7, "fixed")]["n_reports"] == MIN_HISTORY_REPORTS - 1def _run_user_vectors_asset(monkeypatch, interactions: pa.Table, embeddings: pa.Table, consent: frozenset[int]):@@ -390,6 +397,7 @@ def test_serving_reads_the_published_day_as_training_builds_it(monkeypatch: pytereports = [(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)]+ engagements += [(2, index, "first_fixed_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]@@ -398,12 +406,16 @@ def test_serving_reads_the_published_day_as_training_builds_it(monkeypatch: pyte# 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)+ days: dict[str, bytes] = {}+ for kinds in (CONTEXT_KINDS, PROJECT_VECTOR_KINDS):+ buffer = io.BytesIO()+ pq.write_table(project_vectors(labels, embeddings, AS_OF, kinds), buffer)+ days[",".join(kinds)] = buffer.getvalue()+ published = [days[",".join(CONTEXT_KINDS)]]monkeypatch.setattr(model_store.object_storage,"read_bytes",- lambda name, bucket=None, *, missing_ok=False: buffer.getvalue() if name == key else None,+ lambda name, bucket=None, *, missing_ok=False: published[0] if name == key else None,)entry = ServingManifestEntry(key="nn@2026-07-29",@@ -416,18 +428,28 @@ def test_serving_reads_the_published_day_as_training_builds_it(monkeypatch: pytemodel_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- )+ manifest = ServingManifest(manifest_version=AS_OF.isoformat(), models=[entry], project_vectors=key)+ serving = model_store.load_project_vectors(manifest, teams)+ published[0] = days[",".join(PROJECT_VECTOR_KINDS)]+ four_kind_serving = model_store.load_project_vectors(manifest, teams)+ assert serving.kinds == set(CONTEXT_KINDS)+ assert four_kind_serving.missing_kinds(CONTEXT_KINDS) == ["fixed"]for position, team_id in enumerate(teams):served = serving.for_team(team_id)- assert served is not None+ four_kind_served = four_kind_serving.for_team(team_id)+ assert served is not None and four_kind_served is not Nonepair = 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])+ # A four-kind model gets the same bytes from a five-kind day as from a four-kind day.+ assert served.vectors.tobytes() == four_kind_served.vectors.tobytes()+ assert served.has_history.tobytes() == four_kind_served.has_history.tobytes()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()+ fixed_first = serving.for_team(2, ("fixed", "typical"))+ assert fixed_first is not None+ assert fixed_first.has_history.tolist() == [[1, 1]]LOCAL_REPORT_ID = "00000000-0000-4000-8000-000000000001"@@ -555,13 +577,13 @@ def test_the_engagement_export_sends_only_remote_reports_to_the_mirror(assert write["extras"]["ACL"] == "bucket-owner-full-control"assert write["extras"]["Metadata"][common.SCHEMA_VERSION_METADATA_KEY] == str(dag.ENGAGEMENT_EXPORT_SCHEMA_VERSION)exported = pq.read_table(io.BytesIO(write["content"]))- assert exported.column_names == list(LABEL_COLUMNS)+ assert exported.column_names == list(ENGAGEMENT_EXPORT_COLUMNS)if not label_ids:assert exported.num_rows == 0returnassert looked_up == [[LOCAL_REPORT_ID, REMOTE_REPORT_ID]]assert exported.to_pylist() == [- dict.fromkeys(LABEL_COLUMNS) | {"report_id": REMOTE_REPORT_ID, "first_opened_at": BEFORE}+ dict.fromkeys(ENGAGEMENT_EXPORT_COLUMNS) | {"report_id": REMOTE_REPORT_ID, "first_opened_at": BEFORE}]@@ -583,8 +605,9 @@ class _RegionStorage:def _export_object(engagements: list[tuple[int, int, str, datetime.datetime]], schema_version: int) -> tuple:+ columns = LABEL_COLUMNS if schema_version == 1 else ENGAGEMENT_EXPORT_COLUMNSbuffer = io.BytesIO()- pq.write_table(_labels(engagements).select(list(LABEL_COLUMNS)), buffer)+ pq.write_table(_labels(engagements).select(list(columns)), buffer)return buffer.getvalue(), {common.SCHEMA_VERSION_METADATA_KEY: str(schema_version)}@@ -593,10 +616,11 @@ def _export_object(engagements: list[tuple[int, int, str, datetime.datetime]], s[([0, 1], dag.ENGAGEMENT_EXPORT_SCHEMA_VERSION, 0),([1], dag.ENGAGEMENT_EXPORT_SCHEMA_VERSION, 1),+ ([0], 1, 0),([mirror_dag.ENGAGEMENT_EXPORT_MAX_AGE_DAYS + 1], dag.ENGAGEMENT_EXPORT_SCHEMA_VERSION, None),([0], dag.ENGAGEMENT_EXPORT_SCHEMA_VERSION + 1, None),],- ids=["fresh", "one_day_late", "too_stale", "unknown_schema"],+ ids=["fresh", "one_day_late", "previous_schema", "too_stale", "unknown_schema"],)def test_the_mirror_region_builds_its_vectors_from_its_embeddings_and_the_export(monkeypatch: pytest.MonkeyPatch, export_ages: list[int], schema_version: int, expected_export_age: int | None@@ -604,6 +628,7 @@ def test_the_mirror_region_builds_its_vectors_from_its_embeddings_and_the_exportpartition_day = AS_OF.date() - datetime.timedelta(days=1)reports = [(team_id, index, 1.0, BEFORE) for team_id in (5, 9) for index in range(MIN_HISTORY_REPORTS)]engagements = [(5, index, "first_opened_at", BEFORE) for index in range(MIN_HISTORY_REPORTS)]+ engagements += [(5, index, "first_fixed_at", BEFORE) for index in range(MIN_HISTORY_REPORTS)]storage = _RegionStorage({serving_engagement_key(@@ -651,6 +676,10 @@ def test_the_mirror_region_builds_its_vectors_from_its_embeddings_and_the_exportrows = _rows_by_key(written)assert {team_id for team_id, _ in rows} == {5}assert rows[(5, "open")]["n_reports"] == MIN_HISTORY_REPORTS+ if schema_version == 1:+ assert {kind for _, kind in rows} == set(PROJECT_VECTOR_KINDS)+ else:+ assert rows[(5, "fixed")]["n_reports"] == MIN_HISTORY_REPORTSassert set(written.column("as_of").to_pylist()) == {AS_OF}diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.pyindex 148368bc43f4..0084893b61bf 100644--- a/products/signals/dags/inbox_ranking/tests/test_training.py+++ b/products/signals/dags/inbox_ranking/tests/test_training.py@@ -2453,6 +2453,7 @@ def _mirror_vectors_metadata(engagement_offset: int, schema_version: int = PROJE"mirror_days,expected_offset,skip_reason",[({0: _mirror_vectors_metadata(1)}, 0, None),+ ({0: _mirror_vectors_metadata(1, schema_version=1)}, 0, None),({1: _mirror_vectors_metadata(2)}, 1, None),({diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pyindex 70c98a69471c..ef749344d7ad 100644--- a/products/signals/dags/inbox_ranking/training/dag.py+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -740,8 +740,13 @@ class _MirrorProjectVectors:refusal: str | None+# The mirror region deploys apart from this one, so its day can carry the version before the+# current one. The scorer skips a model that reads a kind the day has no rows for.+_NAMEABLE_PROJECT_VECTORS_SCHEMA_VERSIONS = frozenset({"1", str(PROJECT_VECTORS_SCHEMA_VERSION)})++def _project_vectors_refusal(metadata: Mapping[str, str], oldest: datetime.date) -> str | None:- if metadata.get(PROJECT_VECTORS_SCHEMA_VERSION_METADATA_KEY) != str(PROJECT_VECTORS_SCHEMA_VERSION):+ if metadata.get(PROJECT_VECTORS_SCHEMA_VERSION_METADATA_KEY) not in _NAMEABLE_PROJECT_VECTORS_SCHEMA_VERSIONS:return UNKNOWN_SCHEMA_VERSIONtry:engagement_date = datetime.date.fromisoformat(metadata.get(PROJECT_VECTORS_ENGAGEMENT_DATE_METADATA_KEY, ""))diff --git a/products/signals/dags/inbox_ranking/training/families.py b/products/signals/dags/inbox_ranking/training/families.pyindex fdc28089dfcc..fe0285a1e9ed 100644--- a/products/signals/dags/inbox_ranking/training/families.py+++ b/products/signals/dags/inbox_ranking/training/families.py@@ -21,13 +21,13 @@ from typing import Final, Literalfrom posthog.dataclasses import frozenfrom products.signals.backend.ranking.features import (+ ALL_PROJECT_VECTOR_KINDS,PAIR_BASE_FEATURE_SET,PAIR_USER_HISTORY_FEATURE_SET,PROJECT_VECTOR_KINDS,REPORT_EMBEDDINGS_FEATURE_SET,REPORT_EMBEDDINGS_PRIORITY_FEATURE_SET,REPORT_EMBEDDINGS_PRIORITY_SOURCES_FEATURE_SET,- TRAINING_PROJECT_VECTOR_KINDS,FeatureSet,)from products.signals.backend.ranking.serving_manifest import DEFAULT_MODEL_KIND, ONNX_MODEL_KIND@@ -65,8 +65,7 @@ class ModelFamily:partition day it trains in `expires`. A serving family has neither.`project_vector_kinds` are the team context kinds the network reads, in its input order. Only a- report-grain experiment can change them: the stored table, the serving path and the pair lane- read `PROJECT_VECTOR_KINDS` only.+ report-grain experiment can change them. The pair lane reads `PROJECT_VECTOR_KINDS` only.A pair-grain family is always an experiment and declares its `heads` from `PAIR_HEAD_NAMES`. Its`baseline` is another pair experiment, and it names a `baseline`, a `reference`, or both: the@@ -99,10 +98,10 @@ class ModelFamily:def _check_project_vector_kinds(self) -> None:kinds = self.project_vector_kinds- if not kinds or len(set(kinds)) != len(kinds) or not set(kinds) <= set(TRAINING_PROJECT_VECTOR_KINDS):+ if not kinds or len(set(kinds)) != len(kinds) or not set(kinds) <= set(ALL_PROJECT_VECTOR_KINDS):raise ValueError(f"family {self.name} declares project vector kinds {list(kinds)}; pick distinct kinds from "- f"{list(TRAINING_PROJECT_VECTOR_KINDS)}"+ f"{list(ALL_PROJECT_VECTOR_KINDS)}")if kinds != PROJECT_VECTOR_KINDS and (not self.experiment or self.grain == PAIR_GRAIN):raise ValueError(