Skip to content

: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.

feat(signals): mirror the inbox ranking serving publish to a second store (#108576)

posthog[bot]9a8862006673
diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.py
index f441cfac7b49..a5605f2c0ca4 100644
--- a/posthog/settings/object_storage.py
+++ b/posthog/settings/object_storage.py
@@ -110,6 +110,11 @@ INBOX_RANKING_PROMOTION_MIN_DAYS = get_from_env("INBOX_RANKING_PROMOTION_MIN_DAY
# The family whose champion the serving manifest serves. The scoring sweep reads the manifest
# from the deployment's own object store, so this is the only place the served family is chosen.
INBOX_RANKING_SERVED_FAMILY = os.getenv("INBOX_RANKING_SERVED_FAMILY", "report_embeddings")
+# 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.
+INBOX_RANKING_SERVING_MIRROR_BUCKET = os.getenv("INBOX_RANKING_SERVING_MIRROR_BUCKET", "")
+INBOX_RANKING_SERVING_MIRROR_REGION = os.getenv("INBOX_RANKING_SERVING_MIRROR_REGION", "")
# Scorer (products/signals/backend/ranking/scorer.py): report ids per ClickHouse vector read. A
# larger call is paged at this size. The sweep also gives one scorer call at most this many ids, which
# bounds the vectors and matrices one call holds.
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.md
index fee4259d0d7e..fc31ab256701 100644
--- a/products/signals/dags/inbox_ranking/README.md
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -107,6 +107,8 @@ s3://<object-storage bucket>/<prefix>/serving/
The manifest holds one entry per model with its `roles`: `served` for the champion of `INBOX_RANKING_SERVED_FAMILY`, `daily_candidate` for that family's candidate on this partition when it is a different, readable model, and `cross_family` for every other family's champion that has a readable head. A pass scores all of them, so an online paired read and a later interleaving need no rescoring; the entry count is capped at the `ranking_score` artefact's own limit, dropping `cross_family` entries first. The schema, the role names and the object keys live in `products/signals/backend/ranking/serving_manifest.py`, and its validators run at write time, so the dag refuses a manifest the sweep could not act on. A model version is immutable, so a version already in the store is not copied again, and `manifest.json` is written last: a failed copy leaves the previous manifest and the previous models serving. No family has a champion until the first promotion, so until then the asset writes nothing and says why.
+A region that does not train serves the same models through a mirror. When `INBOX_RANKING_SERVING_MIRROR_BUCKET` is set, the asset repeats the publish into that bucket after the primary publish succeeds, in the same order and with the same skip of versions already there. A mirror failure does not fail the asset: it logs, and the `inbox_ranking_serving_manifest_published` event carries `mirror_published=false`. The property is absent when no mirror is set.
+
The reader is `score_reports` in `products/signals/backend/ranking/scorer.py`. It loads every model the manifest names through `model_store.py`, reads each report's latest vector once per rendering, builds each model's matrix with its own `FeatureSet.build_matrix`, and writes one `ranking_score` artefact per report plus one `inbox_ranking_report_scored` event per report and model. The dag and the reader decide whether a model can be scored with the same functions, in `products/signals/backend/ranking/model_contract.py`. A served model that cannot load stops the pass. Any other model that cannot load, or has no vector for a report, is a `skipped` result. The embedding families are the only ones served, so a tabular entry is a `skipped` result too. No scheduled caller runs the reader yet.
### Outcome heads
@@ -238,6 +240,8 @@ Like the dataset job, this one reads the dogfood project's ClickHouse, so it can
| `INBOX_RANKING_AUTO_PROMOTE` | `false` | Whether a winning candidate rewrites `champion.json`; off, the decision is only logged. |
| `INBOX_RANKING_PROMOTION_MIN_DAYS` | `3` | Minimum age of the champion before another promotion. |
| `INBOX_RANKING_SERVED_FAMILY` | `report_embeddings` | Family whose champion the serving manifest serves. |
+| `INBOX_RANKING_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_SHADOW_SCORE_LOOKBACK_DAYS` | `60` | How many scores partitions back the shadow read looks for a score that already existed when a list was served. |
| `INBOX_RANKING_SCORING_BATCH_SIZE` | `500` | Report ids per ClickHouse vector read in the scorer. A larger call is paged at this size. |
diff --git a/products/signals/dags/inbox_ranking/common.py b/products/signals/dags/inbox_ranking/common.py
index 9fc2ed92482d..137293e85bc2 100644
--- a/products/signals/dags/inbox_ranking/common.py
+++ b/products/signals/dags/inbox_ranking/common.py
@@ -17,6 +17,7 @@ from botocore.exceptions import ClientError
from posthog import settings
from posthog.dags.common import JobOwners
+from posthog.storage.object_storage import ObjectStorage
DATASET_VERSION = "v1"
@@ -105,6 +106,11 @@ def s3_client(): # noqa: ANN201
)
+def serving_mirror_storage() -> ObjectStorage:
+ # The mirror is another deployment's store, so ambient AWS config must grant the write there.
+ return ObjectStorage(boto3.client("s3", region_name=settings.INBOX_RANKING_SERVING_MIRROR_REGION or None))
+
+
SNAPSHOT_DATE_METADATA_KEY = "snapshot-date"
ROW_COUNT_METADATA_KEY = "row-count"
diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.py
index bb892ea83432..2a6254711b64 100644
--- a/products/signals/dags/inbox_ranking/tests/test_training.py
+++ b/products/signals/dags/inbox_ranking/tests/test_training.py
@@ -111,6 +111,7 @@ from products.signals.dags.inbox_ranking.training.serving import FamilyModels, c
from products.signals.dags.inbox_ranking.training.telemetry import (
DISTINCT_ID,
LOCAL_DISTINCT_ID,
+ SERVING_MANIFEST_PUBLISHED_EVENT,
HeadExampleCounts,
TrainingEvent,
candidate_events,
@@ -2471,14 +2472,16 @@ class _AppObjectStore:
def __init__(self, existing: dict[str, bytes] | None = None, fail_on: str | None = None):
self.objects = dict(existing or {})
self.fail_on = fail_on
+ self.written: list[str] = []
- def head_object(self, file_key: str, bucket: str | None = None):
+ def head_object(self, bucket: str, file_key: str) -> dict[str, int] | None:
return {"ContentLength": len(self.objects[file_key])} if file_key in self.objects else None
- def write(self, file_name: str, content, extras: dict | None = None, bucket: str | None = None) -> None:
- if self.fail_on is not None and self.fail_on in file_name:
+ def write(self, bucket: str, key: str, content: str | bytes, extras: dict[str, str] | None) -> None:
+ if self.fail_on is not None and self.fail_on in key:
raise RuntimeError("object store write failed")
- self.objects[file_name] = content if isinstance(content, bytes) else content.encode()
+ self.objects[key] = content if isinstance(content, bytes) else content.encode()
+ self.written.append(key)
def _serving_dataset_s3(prefix: str, partition_key: str):
@@ -2497,10 +2500,15 @@ def _serving_dataset_s3(prefix: str, partition_key: str):
return _ModelStoreS3(objects)
-def _run_serving_manifest(monkeypatch, store: _AppObjectStore, dataset_objects=None):
+def _run_serving_manifest(
+ monkeypatch: pytest.MonkeyPatch,
+ store: _AppObjectStore,
+ dataset_objects: dict[str, bytes] | None = None,
+ mirror: _AppObjectStore | None = None,
+) -> _FakeClient:
partition_key = "2026-08-19"
prefix = settings.INBOX_RANKING_DATASET_S3_PREFIX
- _patch_capture(monkeypatch, cloud=False, debug=False)
+ capture = _patch_capture(monkeypatch, cloud=True, debug=False)
monkeypatch.setattr(settings, "INBOX_RANKING_SERVED_FAMILY", EMBEDDINGS_MODEL_NAME)
monkeypatch.setattr(
"products.signals.dags.inbox_ranking.training.dag.MODEL_FAMILIES",
@@ -2510,15 +2518,32 @@ def _run_serving_manifest(monkeypatch, store: _AppObjectStore, dataset_objects=N
_ModelStoreS3(dataset_objects) if dataset_objects is not None else _serving_dataset_s3(prefix, partition_key)
)
monkeypatch.setattr("products.signals.dags.inbox_ranking.training.dag.s3_client", lambda: client)
- monkeypatch.setattr("posthog.storage.object_storage.head_object", store.head_object)
- monkeypatch.setattr("posthog.storage.object_storage.write", store.write)
+ monkeypatch.setattr("posthog.storage.object_storage.object_storage_client", lambda: store)
+ monkeypatch.setattr(settings, "INBOX_RANKING_SERVING_MIRROR_BUCKET", "mirror-bucket" if mirror else "")
+
+ def mirror_storage() -> _AppObjectStore:
+ assert mirror is not None, "no mirror is set, so nothing may reach a second store"
+ return mirror
+
+ monkeypatch.setattr("products.signals.dags.inbox_ranking.training.dag.serving_mirror_storage", mirror_storage)
_publish_manifest(dagster.build_asset_context(partition_key=partition_key), partition_key, "run-1")
- return prefix
+ return capture
+
+def _manifest_event(capture: _FakeClient) -> dict[str, Any]:
+ [event] = [call["properties"] for call in capture.calls if call["event"] == SERVING_MANIFEST_PUBLISHED_EVENT]
+ return event
-def test_publishing_copies_every_model_the_manifest_names_and_writes_the_manifest_last(monkeypatch):
+
[email protected]("mirrored", [False, True])
+def test_publishing_copies_every_model_the_manifest_names_and_writes_the_manifest_last(
+ monkeypatch: pytest.MonkeyPatch, mirrored: bool
+) -> None:
+ # The EU sweep reads the mirror, so it needs the same files, in the same order, as the primary.
+ prefix = settings.INBOX_RANKING_DATASET_S3_PREFIX
store = _AppObjectStore()
- prefix = _run_serving_manifest(monkeypatch, store)
+ mirror = _AppObjectStore() if mirrored else None
+ capture = _run_serving_manifest(monkeypatch, store, mirror=mirror)
manifest = ServingManifest.model_validate_json(store.objects[serving_manifest_key(prefix)])
assert manifest.served.key == model_key(EMBEDDINGS_MODEL_NAME, "2026-08-15")
@@ -2526,6 +2551,24 @@ def test_publishing_copies_every_model_the_manifest_names_and_writes_the_manifes
for entry in manifest.models:
assert f"{entry.prefix}/{METADATA_FILE}" in store.objects
assert f"{entry.prefix}/open.ubj" in store.objects
+ assert store.written[-1] == serving_manifest_key(prefix)
+ if mirror is not None:
+ assert mirror.objects == store.objects
+ assert mirror.written[-1] == serving_manifest_key(prefix)
+ assert _manifest_event(capture).get("mirror_published") is (True if mirrored else None)
+
+
+def test_a_failed_mirror_leaves_the_primary_publish_intact(monkeypatch: pytest.MonkeyPatch) -> None:
+ prefix = settings.INBOX_RANKING_DATASET_S3_PREFIX
+ store = _AppObjectStore()
+ mirror = _AppObjectStore(fail_on="open.ubj")
+ capture = _run_serving_manifest(monkeypatch, store, mirror=mirror)
+
+ assert serving_manifest_key(prefix) in store.objects
+ assert serving_manifest_key(prefix) not in mirror.objects
+ event = _manifest_event(capture)
+ assert event["published"] is True
+ assert event["mirror_published"] is False
def test_a_version_already_in_the_store_is_not_copied_again(monkeypatch):
@@ -2535,7 +2578,8 @@ def test_a_version_already_in_the_store_is_not_copied_again(monkeypatch):
settings.INBOX_RANKING_DATASET_S3_PREFIX, model_key(EMBEDDINGS_MODEL_NAME, "2026-08-15")
)
store = _AppObjectStore({f"{champion_prefix}/{METADATA_FILE}": b"already here"})
- prefix = _run_serving_manifest(monkeypatch, store)
+ _run_serving_manifest(monkeypatch, store)
+ prefix = settings.INBOX_RANKING_DATASET_S3_PREFIX
assert store.objects[f"{champion_prefix}/{METADATA_FILE}"] == b"already here"
assert f"{champion_prefix}/open.ubj" not in store.objects
diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.py
index 7a89b49515c7..e668bbe72ac9 100644
--- a/products/signals/dags/inbox_ranking/training/dag.py
+++ b/products/signals/dags/inbox_ranking/training/dag.py
@@ -48,7 +48,7 @@ import json
import datetime
from collections.abc import Mapping, Sequence
from types import MappingProxyType
-from typing import Any
+from typing import TYPE_CHECKING, Any
import pandas as pd
import dagster
@@ -89,6 +89,7 @@ from products.signals.dags.inbox_ranking.common import (
partition_object_key,
read_parquet_if_exists,
s3_client,
+ serving_mirror_storage,
skip_unconfigured,
snapshot_bounds,
write_parquet,
@@ -161,6 +162,9 @@ from products.signals.dags.inbox_ranking.training.unseen import (
with_model_names,
)
+if TYPE_CHECKING:
+ from posthog.storage.object_storage import ObjectStorageClient
+
EXAMPLES_TABLE = "inbox_ranking_training_examples"
MODELS_TABLE = "inbox_ranking_models"
CHAMPION_FILE = "champion.json"
@@ -812,6 +816,12 @@ def _decide_champion(
SERVING_MANIFEST_ASSET = "inbox_ranking_serving_manifest"
+@frozen
+class _ServingStore:
+ storage: "ObjectStorageClient"
+ bucket: str
+
+
@dagster.asset(name=SERVING_MANIFEST_ASSET, deps=["inbox_ranking_model_champion"], **COMMON_ASSET_KWARGS)
def inbox_ranking_serving_manifest(context: dagster.AssetExecutionContext) -> None:
"""Publish the models the scoring sweep serves, and the manifest naming them.
@@ -865,13 +875,10 @@ def _publish_manifest(
manifest = decision.manifest
manifest_key = serving_manifest_key(prefix)
- publication = publish_serving_models(context, client, bucket, prefix, manifest)
- object_storage.write(
- manifest_key,
- manifest.model_dump_json(indent=2),
- extras={"ContentType": "application/json"},
- )
+ primary = _ServingStore(storage=object_storage.object_storage_client(), bucket=settings.OBJECT_STORAGE_BUCKET)
+ publication = publish_serving_models(context, client, bucket, prefix, manifest, primary)
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(
context,
partition_key,
@@ -885,9 +892,13 @@ def _publish_manifest(
copied_keys=publication.copied,
present_keys=publication.present,
bytes_copied=publication.bytes_copied,
+ mirror_published=mirror_published,
)
],
)
+ mirror_metadata = (
+ {} if mirror_published is None else {"mirror_published": dagster.MetadataValue.bool(mirror_published)}
+ )
return {
"published": dagster.MetadataValue.bool(True),
"manifest_key": dagster.MetadataValue.text(manifest_key),
@@ -899,9 +910,31 @@ 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),
+ **mirror_metadata,
}
+def _publish_mirror(
+ context: dagster.AssetExecutionContext, client, bucket: str, prefix: str, manifest: ServingManifest
+) -> bool | None:
+ """Copy the same publish into the mirror store, if one is set. Returns None when no mirror is
+ set, otherwise whether the mirror now serves this manifest.
+
+ The primary publish has already succeeded, so a mirror failure only logs: the region that
+ trains keeps serving, and the mirror keeps its previous manifest and models.
+ """
+ if not settings.INBOX_RANKING_SERVING_MIRROR_BUCKET:
+ return None
+ try:
+ mirror = _ServingStore(storage=serving_mirror_storage(), bucket=settings.INBOX_RANKING_SERVING_MIRROR_BUCKET)
+ publish_serving_models(context, client, bucket, prefix, manifest, mirror)
+ except Exception as error:
+ context.log.exception(f"serving manifest {manifest.manifest_version} not mirrored: {error!r}")
+ return False
+ context.log.info(f"mirrored serving manifest {manifest.manifest_version} to {mirror.bucket}")
+ return True
+
+
@frozen
class _ModelPublication:
copied: list[str]
@@ -915,12 +948,14 @@ def publish_serving_models(
bucket: str,
prefix: str,
manifest: ServingManifest,
+ target: _ServingStore,
) -> _ModelPublication:
- """Copy every model the manifest names from the dataset bucket into the app object store.
+ """Copy every model the manifest names from the dataset bucket into `target`, then write the
+ manifest there.
Returns the keys copied, the keys already there, and the bytes moved. A missing source object
- fails the asset before the manifest is written, so the manifest can never name a model the
- sweep cannot load.
+ fails before the manifest is written, so the manifest can never name a model the sweep cannot
+ load.
"""
copied: list[str] = []
present: list[str] = []
@@ -929,7 +964,7 @@ def publish_serving_models(
target_metadata = f"{entry.prefix}/{METADATA_FILE}"
# A version is immutable, so its metadata record standing in for the whole prefix is safe
# and saves re-reading a 1536-column booster every day.
- if object_storage.head_object(target_metadata) is not None:
+ if target.storage.head_object(bucket=target.bucket, file_key=target_metadata) is not None:
present.append(entry.key)
continue
# Metadata marks a complete copy, so write it after every booster to make retries safe.
@@ -939,10 +974,16 @@ def publish_serving_models(
)
if body is None:
raise dagster.Failure(f"{entry.key} is missing {name} in the dataset bucket; manifest not written")
- object_storage.write(f"{entry.prefix}/{name}", body)
+ target.storage.write(bucket=target.bucket, key=f"{entry.prefix}/{name}", content=body, extras=None)
bytes_copied += len(body)
copied.append(entry.key)
- context.log.info(f"copied {entry.key} to {entry.prefix}")
+ context.log.info(f"copied {entry.key} to {target.bucket}/{entry.prefix}")
+ target.storage.write(
+ bucket=target.bucket,
+ key=serving_manifest_key(prefix),
+ content=manifest.model_dump_json(indent=2),
+ extras={"ContentType": "application/json"},
+ )
return _ModelPublication(copied=copied, present=present, bytes_copied=bytes_copied)
diff --git a/products/signals/dags/inbox_ranking/training/telemetry.py b/products/signals/dags/inbox_ranking/training/telemetry.py
index 6b2533ec3507..584d63599552 100644
--- a/products/signals/dags/inbox_ranking/training/telemetry.py
+++ b/products/signals/dags/inbox_ranking/training/telemetry.py
@@ -170,6 +170,7 @@ def serving_manifest_event(
copied_keys: Sequence[str] = (),
present_keys: Sequence[str] = (),
bytes_copied: int = 0,
+ mirror_published: bool | None = None,
) -> TrainingEvent:
"""What the day's manifest published. A run that wrote nothing still reports, with `reason`:
the manifest is what makes the sweep serve anything, so a silent gap in this series would read
@@ -191,6 +192,8 @@ def serving_manifest_event(
"model_keys": [entry.key for entry in manifest.models],
"model_roles": {entry.key: entry.roles for entry in manifest.models},
}
+ if mirror_published is not None:
+ properties["mirror_published"] = mirror_published
return TrainingEvent(event=SERVING_MANIFEST_PUBLISHED_EVENT, properties=properties)
diff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.py
index 89d082580f88..908cfa84302d 100644
--- a/products/warehouse_sources/backend/models/util.py
+++ b/products/warehouse_sources/backend/models/util.py
@@ -782,6 +782,8 @@ _POSTHOG_OWNED_BUCKET_SETTING_NAMES = (
"DATAWAREHOUSE_BUCKET",
"DICTIONARY_STAGING_S3_BUCKET",
"IDENTITY_MATCHING_S3_BUCKET",
+ # Another region's app object store, so it holds that region's team data. Deny it even without a known node-role path.
+ "INBOX_RANKING_SERVING_MIRROR_BUCKET",
"NOTEBOOKS_FRAME_STORE_S3_BUCKET",
"OBJECT_STORAGE_BUCKET",
"OBJECT_STORAGE_EXTERNAL_WEB_ANALYTICS_BUCKET",