: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 the nn inbox ranking model on US Cloud (#118587)
posthog[bot]629e4ae5da39
diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.pyindex 2d45fe8d9a5f..336dfa8fbbd6 100644--- a/posthog/settings/object_storage.py+++ b/posthog/settings/object_storage.py@@ -1,7 +1,7 @@import osfrom typing import Optional-from posthog.settings.base_variables import DEBUG, TEST+from posthog.settings.base_variables import CLOUD_DEPLOYMENT, DEBUG, TESTfrom posthog.settings.utils import get_from_envfrom posthog.utils import str_to_bool@@ -115,7 +115,10 @@ INBOX_RANKING_PROMOTION_MIN_DAYS = get_from_env("INBOX_RANKING_PROMOTION_MIN_DAYINBOX_RANKING_LABELS_REFRESH_MAX_RUNS = get_from_env("INBOX_RANKING_LABELS_REFRESH_MAX_RUNS", 6, type_cast=int)# The family whose champion the serving manifest serves. The scoring sweep reads the manifest# from the deployment's own object store, so this is the only place the served family is chosen.-INBOX_RANKING_SERVED_FAMILY = os.getenv("INBOX_RANKING_SERVED_FAMILY", "report_embeddings")+# Only US Cloud trains `nn`: local dev and tests have no nn champion, and EU does not train.+INBOX_RANKING_SERVED_FAMILY = os.getenv(+ "INBOX_RANKING_SERVED_FAMILY", "nn" if (CLOUD_DEPLOYMENT or "").upper() == "US" else "report_embeddings"+)# A second deployment's object store that receives a copy of every serving publish, so a region# that does not train still serves the trained models. Reached via ambient AWS config. Unset means# no mirror.diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.mdindex 9b16d37671f0..9af48fffaf45 100644--- a/products/signals/dags/inbox_ranking/AGENTS.md+++ b/products/signals/dags/inbox_ranking/AGENTS.md@@ -33,10 +33,10 @@ Read `README.md` first for what the dataset is and how partitions behave. This f- The serving path reads the deployment's own object store, never the dataset bucket: the Temporal workers have no credential for that bucket, and keeping it that way is why the manifest asset copies what the sweep needs. `serving/models/<key>/` holds a version's `metadata.json` and its model files, `serving/manifest.json` names the models one pass scores. The holdout boosters grade a promotion and must stay behind.- An entry's files come from `ServingManifestEntry.files`: one `<head>.ubj` per head for `xgboost`, and the one `model.onnx` that `model_file` names for `onnx`. The copy step and the model store read that property, and the pin check reads the same names from each head's `file` in `metadata.json`, so a new model kind with another file layout keeps the two in step. Keep `onnxruntime` and `xgboost` imports inside the handlers' `load`: a test pins that importing the sweep loads neither.- The manifest schema and the object keys live in `products/signals/backend/ranking/serving_manifest.py`, next to the feature contract, because the dag writes them and the sweep reads them. Its validators run at write time, so the dag refuses a manifest the sweep could not act on; the entry cap is the `ranking_score` artefact's, so a manifest can never produce a row the artefact refuses.-- Publishing order is load-bearing. Every model copy finishes before `manifest.json` is written, so a failed copy leaves the previous manifest and the previous models serving. A model version is immutable, so a version whose `metadata.json` is already at the target is not copied again. A run with nothing to publish, and no champion for the served family is the case today, writes nothing rather than an empty manifest.+- Publishing order is load-bearing. Every model copy finishes before `manifest.json` is written, so a failed copy leaves the previous manifest and the previous models serving. A model version is immutable, so a version whose `metadata.json` is already at the target is not copied again. A run with nothing to publish, such as a run before the served family has a champion, 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.- `HEADS` holds only the heads the inbox reads (`HeadRanker` in `backend/ranking/inbox_sort.py`). Add a head there only together with a surface that reads it. The promotion gate skips a champion head that is not in `HEADS`, so a trim does not block promotion.-- `nn` is trained by the `signals_ml` location (`nn/dag.py`), never by the main one. torch is imported only inside the candidate asset's body (through `nn/train.py` and `multihead/network.py`). `signals_ml` must import without torch, and `test_multihead_network.py` pins that. Its champion goes through `decide_family_champion`, the same rule and gate as the boosters, graded through the incumbent's `model.holdout.onnx`. Keep `signals_ml` commented out in `.dagster_home/workspace.yaml`, and keep its schedule (04:30 UTC) running by default on prod US only.+- `nn` is trained by the `signals_ml` location (`nn/dag.py`), never by the main one. torch is imported only inside the candidate asset's body (through `nn/train.py` and `multihead/network.py`). `signals_ml` must import without torch, and `test_multihead_network.py` pins that. Its champion goes through `decide_family_champion`, the same rule and gate as the boosters, graded through the incumbent's `model.holdout.onnx`. Keep `signals_ml` commented out in `.dagster_home/workspace.yaml`, and keep its schedule (04:30 UTC) running by default on prod US only. `INBOX_RANKING_SERVED_FAMILY` defaults to `nn` on US Cloud only, because no other deployment has an `nn` champion.## Invariants — do not breakdiff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex a5fde315e4b7..311d025f8990 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -379,7 +379,7 @@ dagster job launch -w .dagster_home/workspace.yaml --location posthog.dags.locat| `INBOX_RANKING_TRAINING_HOLDOUT_DAYS` | `7` | Trailing days of reports that grade a candidate. || `INBOX_RANKING_AUTO_PROMOTE` | `false` | Whether a winning candidate rewrites `champion.json`; off, the decision is only logged. || `INBOX_RANKING_PROMOTION_MIN_DAYS` | `0` | Minimum age of the champion before another promotion. The scoring sweep stamps each score with its model key, so no wait is needed for a clean read. |-| `INBOX_RANKING_SERVED_FAMILY` | `report_embeddings` | Family whose champion the serving manifest serves. |+| `INBOX_RANKING_SERVED_FAMILY` | `report_embeddings` | Family whose champion the serving manifest serves. US Cloud defaults to `nn`. Local dev, tests and EU have no `nn` champion, so they default to `report_embeddings`. || `INBOX_RANKING_SERVING_MIRROR_BUCKET` | unset | A second deployment's object-storage bucket that receives a copy of every serving publish, through ambient AWS config. Unset means no mirror. || `INBOX_RANKING_SERVING_MIRROR_REGION` | unset | AWS region of the mirror bucket. || `INBOX_RANKING_SCORING_BATCH_SIZE` | `500` | Report ids per ClickHouse vector read in the scorer. A larger call is paged at this size. |diff --git a/products/signals/dags/inbox_ranking/tests/test_nn.py b/products/signals/dags/inbox_ranking/tests/test_nn.pyindex 7629205549b5..64fbae1aa5ca 100644--- a/products/signals/dags/inbox_ranking/tests/test_nn.py+++ b/products/signals/dags/inbox_ranking/tests/test_nn.py@@ -17,7 +17,13 @@ from posthog import settingsfrom products.signals.backend.ranking.model_contract import model_mismatchfrom products.signals.backend.ranking.model_store import ONNX_OUTPUT_HEADS_KEYfrom products.signals.backend.ranking.overrides import NO_OVERRIDES-from products.signals.backend.ranking.serving_manifest import CROSS_FAMILY_ROLE, ONNX_MODEL_FILE, ONNX_MODEL_KIND+from products.signals.backend.ranking.serving_manifest import (+ CROSS_FAMILY_ROLE,+ DAILY_CANDIDATE_ROLE,+ ONNX_MODEL_FILE,+ ONNX_MODEL_KIND,+ SERVED_ROLE,+)from products.signals.dags.inbox_ranking.common import partition_object_keyfrom products.signals.dags.inbox_ranking.dataset.dag import EMBEDDINGS_TABLE, LABELS_TABLEfrom products.signals.dags.inbox_ranking.multihead.inputs import NetworkConfig@@ -87,23 +93,12 @@ def _parquet(table: pa.Table) -> bytes:return sink.getvalue()-def _trained_network() -> TrainedNetwork:- metrics = HeadMetrics(- head="open",- train_rows=400,- train_positives=120,- holdout_rows=200,- holdout_positives=60,- holdout_auc=0.8,- null_auc=0.5,- null_auc_std=0.01,- readable=True,- )+def _trained_network(heads: tuple[str, ...] = ("open",)) -> TrainedNetwork:return TrainedNetwork(output_heads=NN_HEAD_NAMES,model_onnx=b"graph",holdout_model_onnx=b"holdout-graph",- heads=(NetworkHead(metrics=metrics, calibration=()),),+ heads=tuple(NetworkHead(metrics=_head_metrics(head), calibration=()) for head in heads),skipped=(),network_train_rows=400,refit_rows=600,@@ -111,9 +106,23 @@ def _trained_network() -> TrainedNetwork:)-def _nn_metadata(version: str) -> dict[str, Any]:+def _head_metrics(head: str) -> HeadMetrics:+ return HeadMetrics(+ head=head,+ train_rows=400,+ train_positives=120,+ holdout_rows=200,+ holdout_positives=60,+ holdout_auc=0.8,+ null_auc=0.5,+ null_auc_std=0.01,+ readable=True,+ )+++def _nn_metadata(version: str, heads: tuple[str, ...] = ("open",)) -> dict[str, Any]:return candidate_metadata(- version, _trained_network(), config=NetworkConfig(), windows={}, trained_at=NOW, run_id="run-1"+ version, _trained_network(heads), config=NetworkConfig(), windows={}, trained_at=NOW, run_id="run-1")@@ -179,6 +188,37 @@ def test_the_manifest_carries_an_nn_champion_as_an_onnx_entry():assert entry.heads == ["open"]+def test_the_manifest_serves_an_nn_champion_with_the_xgboost_champion_as_a_challenger():+ decision = compose_manifest(+ [+ FamilyModels(+ name=REPORT_EMBEDDINGS_MODEL_NAME,+ candidate=None,+ champion=_xgboost_metadata(REPORT_EMBEDDINGS_MODEL_NAME, "2026-08-15"),+ ),+ FamilyModels(+ name=NN_MODEL_NAME,+ candidate=_nn_metadata(PARTITION, heads=NN_HEAD_NAMES),+ champion=_nn_metadata("2026-08-16", heads=NN_HEAD_NAMES),+ ),+ ],+ served_family=NN_MODEL_NAME,+ prefix=PREFIX,+ now=NOW,+ )++ assert decision.manifest is not None+ assert [(entry.model_name, entry.model_version, entry.roles) for entry in decision.manifest.models] == [+ (NN_MODEL_NAME, "2026-08-16", [SERVED_ROLE]),+ (NN_MODEL_NAME, PARTITION, [DAILY_CANDIDATE_ROLE]),+ (REPORT_EMBEDDINGS_MODEL_NAME, "2026-08-15", [CROSS_FAMILY_ROLE]),+ ]+ served = decision.manifest.served+ assert served.model_kind == ONNX_MODEL_KIND+ assert served.files == [ONNX_MODEL_FILE]+ assert sorted(served.heads) == sorted(NN_HEAD_NAMES)++def test_nn_promotion_writes_only_its_own_pointer(no_side_effects):other_champion = json.dumps(_xgboost_metadata(REPORT_EMBEDDINGS_MODEL_NAME, "2026-08-15")).encode()client = _S3(