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): grade the served inbox ranking model's own scores (#107857)

posthog[bot]d8add8add312
diff --git a/docs/internal/inbox-ranking-training.md b/docs/internal/inbox-ranking-training.md
index e5d85f88dc20..b26186a8f0e6 100644
--- a/docs/internal/inbox-ranking-training.md
+++ b/docs/internal/inbox-ranking-training.md
@@ -113,3 +113,44 @@ A pooled line over several versions uses the frozen threshold of each version, s
After deployment and a new training and scoring run, check that the candidate events carry numeric `holdout_` fields and `refit_classification_threshold`, and that the unseen events carry `classification_threshold`.
Check the mature grades as each head's horizon becomes available.
+
+## Served-model classification metrics
+
+The unseen grades rescore the newborn pool with the day's candidate and champion.
+They are not the scores the inbox served.
+The served grade closes that gap.
+
+### Score events
+
+Each `inbox_ranking_report_scored` event carries the served threshold of its model:
+
+- `threshold_<head>`: the head's `refit_classification_threshold` from the serving copy's metadata. A serving copy is immutable per model key, so this is the threshold that scored the report.
+- `predicted_<head>`: `p_<head> >= threshold_<head>`. A score equal to the threshold is a positive prediction.
+- `readable_heads`: the heads whose holdout was readable.
+
+A head without a saved threshold has no `threshold_` or `predicted_` property.
+Models trained before thresholds existed have none, and no other value stands in for one.
+
+### The served grade
+
+`inbox_ranking_served_scores` writes `inbox_ranking_served_scores/v1/dt=D/` in the unseen scores schema.
+
+- Population: D's newborn pool, the same reports the unseen grade covers.
+- Score: the earliest scored event in D with the `served` role and this deployment's `environment`.
+- `classification_threshold` comes from `threshold_<head>`, and is null when the event has none.
+- Asset metadata: `served_pool_coverage`, rows per model version, and the heads without a threshold.
+
+`inbox_ranking_unseen_graded` reads the served object next to the unseen object for each scoring partition.
+Its events then carry `model_role = 'served'`, with no new event type.
+A missing served object is a skip in the asset metadata, not a failure.
+
+Caveats:
+
+- The daily promotion can change the served model part of the way through D, so one day's cohort can split across two versions. Grades stay per `(model_name, model_version, model_role)`. Never pool them across versions.
+- A report first scored after D ends, for example when its vector arrived late, is not in D's served rows. `served_pool_coverage` shows this. A later score never fills it in.
+- The sweep scores with the vector current at scoring time. The unseen grade uses the end-of-day vector. Served and candidate grades of one day are two reads, not one paired number.
+- A deployment where the sweep is off writes an empty object with coverage 0 and grades nothing.
+
+After deployment, check the new properties on a live sweep's events.
+Check the first `model_role = 'served'` early grades the next day, and the mature grades as each head's horizon passes.
+Until a model trained with thresholds is served, the events have no threshold properties and the served grades have null classification fields.
diff --git a/posthog/dags/locations/signals.py b/posthog/dags/locations/signals.py
index 685c1a27d0db..07c386865bb9 100644
--- a/posthog/dags/locations/signals.py
+++ b/posthog/dags/locations/signals.py
@@ -3,7 +3,10 @@ import dagster
from products.signals.dags.inbox_ranking.common import is_inbox_ranking_registered
from products.signals.dags.inbox_ranking.dataset import dag as inbox_ranking_dataset
from products.signals.dags.inbox_ranking.shadow import dag as inbox_ranking_shadow
-from products.signals.dags.inbox_ranking.training import dag as inbox_ranking_training
+from products.signals.dags.inbox_ranking.training import (
+ dag as inbox_ranking_training,
+ served as inbox_ranking_served,
+)
from . import loggers, resources
@@ -23,6 +26,7 @@ if is_inbox_ranking_registered():
inbox_ranking_training.inbox_ranking_model_champion,
inbox_ranking_training.inbox_ranking_serving_manifest,
inbox_ranking_training.inbox_ranking_unseen_scores,
+ inbox_ranking_served.inbox_ranking_served_scores,
inbox_ranking_training.inbox_ranking_unseen_graded,
inbox_ranking_shadow.inbox_ranking_shadow_eval,
],
diff --git a/products/signals/backend/ranking/model_contract.py b/products/signals/backend/ranking/model_contract.py
index da42b0297c41..c9f4d0f690d0 100644
--- a/products/signals/backend/ranking/model_contract.py
+++ b/products/signals/backend/ranking/model_contract.py
@@ -51,6 +51,16 @@ def readable_head_names(metadata: Mapping[str, Any]) -> frozenset[str]:
return frozenset(entry["head"] for entry in metadata.get("heads", []) if entry.get("readable"))
+def classification_thresholds(metadata: Mapping[str, Any]) -> dict[str, float]:
+ """The saved refit threshold per head. A model saved before thresholds existed has none, and its
+ grades then report null classification fields rather than a threshold read from the graded rows."""
+ return {
+ entry["head"]: float(entry["refit_classification_threshold"])
+ for entry in metadata.get("heads", [])
+ if entry.get("refit_classification_threshold") is not None
+ }
+
+
def trained_head_files(metadata: Mapping[str, Any], known_heads: Collection[str]) -> dict[str, str]:
"""The `<head>.ubj` object name per head the candidate fit, of the heads in `known_heads`.
diff --git a/products/signals/backend/ranking/sinks.py b/products/signals/backend/ranking/sinks.py
index 9538c4904591..59cb632983c0 100644
--- a/products/signals/backend/ranking/sinks.py
+++ b/products/signals/backend/ranking/sinks.py
@@ -12,8 +12,9 @@ from django.conf import settings
from posthog.ph_client import ScopedCapture, ph_scoped_capture
-from products.signals.backend.artefact_schemas import RankingScore
+from products.signals.backend.artefact_schemas import RankingModelResult, RankingScore
from products.signals.backend.models import SignalActorKind, SignalReport, SignalReportArtefact
+from products.signals.backend.ranking.model_contract import classification_thresholds, readable_head_names
REPORT_SCORED_EVENT = "inbox_ranking_report_scored"
DISTINCT_ID = "inbox_ranking_scoring"
@@ -68,6 +69,27 @@ def persist_scores(
if score.embedding_inserted_at
else None,
**{f"p_{head}": probability for head, probability in result.scores.items()},
+ **classification_properties(result),
},
)
return len(kept)
+
+
+def classification_properties(result: RankingModelResult) -> dict[str, object]:
+ """The served threshold and the flag it gives, per head, read from the result's copied metadata.
+
+ A serving copy is immutable per model key, so its metadata holds the threshold that scored the
+ report. A head without a saved threshold gets neither property: a model trained before
+ thresholds existed has none, and no other value may stand in for it. A tie is a positive, as in
+ the dag's grade.
+ """
+ thresholds = classification_thresholds(result.metadata)
+ return {
+ "readable_heads": sorted(readable_head_names(result.metadata)),
+ **{f"threshold_{head}": threshold for head, threshold in thresholds.items()},
+ **{
+ f"predicted_{head}": probability >= thresholds[head]
+ for head, probability in result.scores.items()
+ if head in thresholds
+ },
+ }
diff --git a/products/signals/backend/test/test_ranking_scoring.py b/products/signals/backend/test/test_ranking_scoring.py
index 258df5368527..5d55d29206ac 100644
--- a/products/signals/backend/test/test_ranking_scoring.py
+++ b/products/signals/backend/test/test_ranking_scoring.py
@@ -17,7 +17,7 @@ from parameterized import parameterized
from posthog.clickhouse.client import sync_execute
from posthog.models import Team
-from products.signals.backend.artefact_schemas import RankingScore
+from products.signals.backend.artefact_schemas import RankingModelResult, RankingScore
from products.signals.backend.models import SignalReport, SignalReportArtefact
from products.signals.backend.ranking import model_store, scorer
from products.signals.backend.ranking.features import (
@@ -41,7 +41,7 @@ from products.signals.backend.ranking.serving_manifest import (
serving_manifest_key,
serving_model_prefix,
)
-from products.signals.backend.ranking.sinks import REPORT_SCORED_EVENT
+from products.signals.backend.ranking.sinks import REPORT_SCORED_EVENT, classification_properties
from products.signals.backend.report_embedding_reader import (
REPORT_EMBEDDINGS_TABLE,
ReportVector,
@@ -98,6 +98,7 @@ class FakeObjectStore:
model_kind: str = "xgboost",
booster_feature_names: tuple[str, ...] | None = None,
missing_heads: Sequence[str] = (),
+ thresholds: Mapping[str, float] | None = None,
) -> ServingManifestEntry:
key = model_key(model_name, version)
prefix = serving_model_prefix(PREFIX, key)
@@ -108,7 +109,19 @@ class FakeObjectStore:
"feature_set": feature_set.name,
"feature_schema_version": feature_set.schema_version,
"feature_names": list(feature_set.feature_names),
- "heads": [{"head": head, "file": f"{head}.ubj", "readable": head == "open"} for head in HEADS],
+ "heads": [
+ {
+ "head": head,
+ "file": f"{head}.ubj",
+ "readable": head == "open",
+ **(
+ {"refit_classification_threshold": thresholds[head]}
+ if thresholds and head in thresholds
+ else {}
+ ),
+ }
+ for head in HEADS
+ ],
}
self.objects[f"{prefix}/{METADATA_FILE}"] = json.dumps(metadata).encode()
booster = _booster_ubj(booster_feature_names or feature_set.feature_names)
@@ -341,6 +354,33 @@ class TestScorer(_ScorerTestMixin, SimpleTestCase):
assert captured.events == []
+class TestClassificationProperties(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("tie_is_a_positive", 0.3, True),
+ ("above", 0.31, True),
+ ("below", 0.29, False),
+ ]
+ )
+ def test_predicted_reads_the_served_threshold(self, _name: str, score: float, predicted: bool) -> None:
+ result = RankingModelResult(
+ model_name="report_embeddings",
+ model_version=VERSION,
+ model_kind="xgboost",
+ roles=[SERVED_ROLE],
+ feature_schema_version=1,
+ status="scored",
+ scores={"open": score},
+ metadata={"heads": [{"head": "open", "readable": True, "refit_classification_threshold": 0.3}]},
+ )
+
+ assert classification_properties(result) == {
+ "readable_heads": ["open"],
+ "threshold_open": 0.3,
+ "predicted_open": predicted,
+ }
+
+
class TestScorerPersists(_ScorerTestMixin, BaseTest):
def _report(self, team_id: int) -> str:
return str(SignalReport.objects.create(team_id=team_id, status=SignalReport.Status.READY, title="A").id)
@@ -348,7 +388,7 @@ class TestScorerPersists(_ScorerTestMixin, BaseTest):
@parameterized.expand([("own_scope", False), ("shared_pass", True)])
def test_persist_writes_one_valid_row_per_scored_report_of_the_team(self, _name: str, shared_pass: bool) -> None:
self.team_id = self.team.id
- served = self._served()
+ served = self._served(thresholds={"open": 0.0})
title = self._challenger("title_embeddings", TITLE_EMBEDDINGS_FEATURE_SET)
manifest = self.store.publish_manifest([served, title])
scored, unscored = self._report(self.team.id), self._report(self.team.id)
@@ -380,6 +420,19 @@ class TestScorerPersists(_ScorerTestMixin, BaseTest):
(event["event"], event["properties"]["report_id"], event["properties"]["model_key"])
for event in captured.events
) == sorted([(REPORT_SCORED_EVENT, scored, served.key), (REPORT_SCORED_EVENT, scored, title.key)])
+ classification = {
+ event["properties"]["model_key"]: {
+ key: value
+ for key, value in event["properties"].items()
+ if key.startswith(("threshold_", "predicted_", "readable_heads"))
+ }
+ for event in captured.events
+ }
+ # thumbs_up saved no threshold, and a model without one gets no stand-in.
+ assert classification == {
+ served.key: {"readable_heads": ["open"], "threshold_open": 0.0, "predicted_open": True},
+ title.key: {"readable_heads": ["open"]},
+ }
assert self.store.reads.count(serving_manifest_key(PREFIX)) == 1
assert captured.scopes == (0 if shared_pass else 1)
diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.py
index 9055bb7d07da..bb892ea83432 100644
--- a/products/signals/dags/inbox_ranking/tests/test_training.py
+++ b/products/signals/dags/inbox_ranking/tests/test_training.py
@@ -6,6 +6,7 @@ import datetime
from typing import Any
import pytest
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event
import numpy as np
import pandas as pd
@@ -40,7 +41,12 @@ from products.signals.backend.ranking.features import (
feature_set_by_name,
feature_vector,
)
-from products.signals.backend.ranking.model_contract import model_mismatch, readable_head_names, trained_head_files
+from products.signals.backend.ranking.model_contract import (
+ classification_thresholds,
+ model_mismatch,
+ readable_head_names,
+ trained_head_files,
+)
from products.signals.backend.ranking.serving_manifest import (
CROSS_FAMILY_ROLE,
DAILY_CANDIDATE_ROLE,
@@ -52,6 +58,7 @@ from products.signals.backend.ranking.serving_manifest import (
serving_manifest_key,
serving_model_prefix,
)
+from products.signals.backend.ranking.sinks import REPORT_SCORED_EVENT
from products.signals.dags.inbox_ranking.common import partition_object_key
from products.signals.dags.inbox_ranking.dataset.dag import (
EMBEDDINGS_TABLE,
@@ -73,7 +80,6 @@ from products.signals.dags.inbox_ranking.training.dag import (
_train_candidate,
candidate_metadata,
champion_object_key,
- classification_thresholds,
embeddings_extras,
examples_object_key,
grade_metadata,
@@ -100,6 +106,7 @@ from products.signals.dags.inbox_ranking.training.examples import (
)
from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, Head, dismissed_as_wrong
from products.signals.dags.inbox_ranking.training.promotion import AUC_TOLERANCE, PromotionDecision, decide_promotion
+from products.signals.dags.inbox_ranking.training.served import served_events, served_metadata, served_score_rows
from products.signals.dags.inbox_ranking.training.serving import FamilyModels, compose_manifest
from products.signals.dags.inbox_ranking.training.telemetry import (
DISTINCT_ID,
@@ -125,6 +132,7 @@ from products.signals.dags.inbox_ranking.training.unseen import (
POOL_NAME,
REPORT_EMBEDDINGS_MODEL_NAME,
SCORE_COLUMNS,
+ SERVED_SCORES_TABLE,
TABULAR_MODEL_NAME,
TITLE_EMBEDDINGS_MODEL_NAME,
UNSEEN_SCORES_TABLE,
@@ -2584,3 +2592,150 @@ def test_the_serving_prefix_layout_is_stable():
serving_model_prefix("inbox_ranking", model_key(EMBEDDINGS_MODEL_NAME, "2026-08-19"))
== "inbox_ranking/serving/models/report_embeddings@2026-08-19"
)
+
+
+def _served_event(report_id: str, at: str, **properties: Any) -> tuple[pd.Timestamp, dict[str, Any]]:
+ timestamp = pd.Timestamp(at)
+ assert isinstance(timestamp, pd.Timestamp)
+ return (
+ timestamp,
+ {"report_id": report_id, "team_id": 2, "status": "scored", "roles": [SERVED_ROLE], **properties},
+ )
+
+
+def _served_events(*events: tuple[pd.Timestamp, dict[str, Any]]) -> pd.DataFrame:
+ return pd.DataFrame(list(events), columns=["scored_at", "properties"])
+
+
+V1, V2 = "2026-08-08", "2026-08-09"
+_V1_EVENT = {"model_name": REPORT_EMBEDDINGS_MODEL_NAME, "model_version": V1, "readable_heads": ["open"]}
+_V2_EVENT = {"model_name": REPORT_EMBEDDINGS_MODEL_NAME, "model_version": V2}
+_SERVED_POOL = ["tie", "low", "legacy_low", "legacy_high", "challenger_only", "late"]
+
+
+def _served_rows() -> pd.DataFrame:
+ events = _served_events(
+ # The promotion lands part of the way through D, so the day's cohort splits across V1 and V2.
+ _served_event("tie", "2026-08-10T13:00:00Z", p_open=0.4, threshold_open=0.4, **_V1_EVENT),
+ _served_event("tie", "2026-08-10T20:00:00Z", p_open=0.9, **_V2_EVENT),
+ _served_event("low", "2026-08-10T13:00:00Z", p_open=0.1, threshold_open=0.4, **_V1_EVENT),
+ # V2 predates thresholds, so its events carry no threshold and no readable heads.
+ _served_event("legacy_low", "2026-08-10T21:00:00Z", p_open=0.2, **_V2_EVENT),
+ _served_event("legacy_high", "2026-08-10T21:00:00Z", p_open=0.6, **_V2_EVENT),
+ _served_event("challenger_only", "2026-08-10T13:00:00Z", p_open=0.5, roles=[CROSS_FAMILY_ROLE], **_V1_EVENT),
+ _served_event("challenger_only", "2026-08-10T14:00:00Z", p_open=0.5, status="skipped", **_V1_EVENT),
+ # Born before D, so not a newborn of the pool.
+ _served_event("older", "2026-08-10T13:00:00Z", p_open=0.5, **_V1_EVENT),
+ )
+ # "late" has no event inside D: its first score came after D ended, so it stays uncovered.
+ pool = _state(_SERVED_POOL)
+ return served_score_rows(events, pool, _labels(_SERVED_POOL), snapshot_date=D0)
+
+
+def test_served_score_rows_keep_the_earliest_served_score_of_each_newborn():
+ rows = _served_rows().set_index("report_id")
+
+ assert sorted(rows.index) == ["legacy_high", "legacy_low", "low", "tie"]
+ assert rows.loc["tie", "model_version"] == V1
+ assert rows.loc["tie", "score"] == 0.4
+ assert rows.loc["tie", "age_hours"] == 1.0
+ assert set(rows["model_role"]) == {SERVED_ROLE}
+ assert rows["classification_threshold"].to_dict() == pytest.approx(
+ {"tie": 0.4, "low": 0.4, "legacy_low": np.nan, "legacy_high": np.nan}, nan_ok=True
+ )
+ # An event without `readable_heads` is unknown, which the grader reads as readable.
+ assert {
+ report_id: None if pd.isna(value) else bool(value) for report_id, value in rows["head_readable"].items()
+ } == {
+ "tie": True,
+ "low": True,
+ "legacy_low": None,
+ "legacy_high": None,
+ }
+ assert served_metadata(_state(_SERVED_POOL), rows.reset_index())["served_pool_coverage"] == (
+ dagster.MetadataValue.float(4 / 6)
+ )
+
+
+def test_served_scores_grade_per_version_at_the_threshold_that_was_served(monkeypatch):
+ graded_day = D0 + datetime.timedelta(days=HEADS_BY_NAME["open"].horizon_days)
+ ids = _SERVED_POOL
+ labels = _labels(ids, open_count=[1, 0, 0, 1, 0, 0])
+ prefix = settings.INBOX_RANKING_DATASET_S3_PREFIX
+ served_table = scores_table(_served_rows())
+ buffer = io.BytesIO()
+ pq.write_table(served_table, buffer)
+ # No unseen object and no older served object: both are skips, never a failure.
+ storage = _ParquetS3(
+ {
+ partition_object_key(prefix, STATE_TABLE, graded_day.isoformat()): _parquet(_state(ids)),
+ partition_object_key(prefix, LABELS_TABLE, graded_day.isoformat()): _parquet(labels),
+ partition_object_key(prefix, SERVED_SCORES_TABLE, D0.isoformat()): buffer.getvalue(),
+ }
+ )
+ monkeypatch.setattr(settings, "INBOX_RANKING_DATASET_S3_BUCKET", "test-bucket")
+ monkeypatch.setattr("products.signals.dags.inbox_ranking.training.dag.s3_client", lambda: storage)
+ client = _patch_capture(monkeypatch, cloud=True, debug=False)
+
+ with dagster.build_asset_context(partition_key=graded_day.isoformat()) as context:
+ inbox_ranking_unseen_graded(context)
+
+ graded = {
+ call["properties"]["model_version"]: call["properties"]
+ for call in client.calls
+ if call["event"] == "inbox_ranking_unseen_head_graded" and call["properties"]["head"] == "open"
+ }
+ assert set(graded) == {V1, V2}
+ assert {row["model_role"] for row in graded.values()} == {SERVED_ROLE}
+ # The tie is a positive, at the threshold V1 saved at birth.
+ assert {
+ "rows": 2,
+ "auc": 1.0,
+ "classification_threshold": 0.4,
+ "true_positives": 1,
+ "true_negatives": 1,
+ "false_positives": 0,
+ }.items() <= graded[V1].items()
+ # V2 saved no threshold: its classification fields are null, and AUC and calibration stay.
+ assert graded[V2]["auc"] == 1.0
+ assert graded[V2]["expected_calibration_error"] is not None
+ assert (graded[V2]["classification_threshold"], graded[V2]["true_positives"]) == (None, None)
+
+
+class TestServedEventsQuery(ClickhouseTestMixin, BaseTest):
+ def _scored(self, report_id: str, at: datetime.datetime, **properties: Any) -> None:
+ _create_event(
+ team=self.team,
+ event=REPORT_SCORED_EVENT,
+ distinct_id="inbox_ranking_scoring",
+ timestamp=at,
+ properties={
+ "environment": "US",
+ "report_id": report_id,
+ "status": "scored",
+ "roles": [SERVED_ROLE],
+ "p_open": 0.5,
+ **properties,
+ },
+ )
+
+ def test_reads_only_this_deployments_scores_of_the_pool_inside_the_day(self) -> None:
+ start = datetime.datetime(2026, 8, 10, tzinfo=datetime.UTC)
+ end = start + datetime.timedelta(days=1)
+ self._scored("in_day", start + datetime.timedelta(hours=3), threshold_open=0.4)
+ self._scored("late", end + datetime.timedelta(hours=1))
+ self._scored("other_region", start + datetime.timedelta(hours=3), environment="EU")
+ self._scored("skipped", start + datetime.timedelta(hours=3), status="skipped")
+ self._scored("not_in_pool", start + datetime.timedelta(hours=3))
+
+ events = served_events(
+ self.team,
+ ["in_day", "late", "other_region", "skipped"],
+ window_start=start,
+ window_end=end,
+ environment="US",
+ )
+
+ assert [properties["report_id"] for properties in events["properties"]] == ["in_day"]
+ (properties,) = events["properties"]
+ assert (properties["roles"], properties["threshold_open"]) == ([SERVED_ROLE], 0.4)
diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.py
index 945de629622a..7a89b49515c7 100644
--- a/products/signals/dags/inbox_ranking/training/dag.py
+++ b/products/signals/dags/inbox_ranking/training/dag.py
@@ -6,6 +6,7 @@ Three assets on the same daily partition as the dataset dag, each writing under
inbox_ranking_models/v1/<name>/dt=D/<head>.ubj one booster per head + metadata.json (the candidate)
inbox_ranking_models/v1/<name>/champion.json pointer to the version the scoring sweep loads
inbox_ranking_unseen_scores/v1/dt=D/ the day's models on the reports born that day
+ inbox_ranking_served_scores/v1/dt=D/ the served model's own scores of those reports
A fifth asset publishes what the scoring sweep serves. The dataset bucket holds the training
history and the Temporal workers cannot reach it, so `inbox_ranking_serving_manifest` copies the
@@ -38,7 +39,9 @@ scores every report born on D (`unseen_pool` explains why no example can cover o
head's horizon, keeping provisional evaluations separate from mature grades. The holdout AUC
grades the recipe, because the shipped booster is refit on train plus holdout; the baked unseen
AUC grades the model on reports it never saw. The two are comparable because both apply the
-same `Head` cohort, label and horizon.
+same `Head` cohort, label and horizon. `inbox_ranking_served_scores` (`training/served.py`) reads
+the scoring sweep's own birth-day scores of the same pool, and the grader grades them as the
+`served` role.
"""
import json
@@ -67,6 +70,7 @@ from products.signals.backend.ranking.features import (
FeatureSet,
)
from products.signals.backend.ranking.model_contract import (
+ classification_thresholds,
model_feature_set,
model_mismatch,
readable_head_names,
@@ -136,6 +140,7 @@ from products.signals.dags.inbox_ranking.training.unseen import (
CANDIDATE_ROLE,
CHAMPION_ROLE,
MODEL_FAMILIES,
+ SERVED_SCORES_TABLE,
UNSEEN_SCORES_TABLE,
HeadGrade,
ModelFamily,
@@ -950,16 +955,6 @@ _HORIZON_MAPPING = dagster.TimeWindowPartitionMapping(
)
-def classification_thresholds(metadata: Mapping[str, Any]) -> dict[str, float]:
- """The saved refit threshold per head. A model saved before thresholds existed has none, and its
- grades then report null classification fields rather than a threshold read from the graded rows."""
- return {
- entry["head"]: float(entry["refit_classification_threshold"])
- for entry in metadata.get("heads", [])
- if entry.get("refit_classification_threshold") is not None
- }
-
-
def load_family_models(
context: dagster.AssetExecutionContext, client, bucket: str, prefix: str, partition_key: str, model_name: str
) -> list[UnseenModel]:
@@ -1168,6 +1163,7 @@ def grade_metadata(grades: Sequence[HeadGrade]) -> dict[str, dagster.MetadataVal
name="inbox_ranking_unseen_graded",
deps=[
dagster.AssetDep(UNSEEN_SCORES_TABLE, partition_mapping=_HORIZON_MAPPING),
+ dagster.AssetDep(SERVED_SCORES_TABLE, partition_mapping=_HORIZON_MAPPING),
LABELS_TABLE,
],
**COMMON_ASSET_KWARGS,
@@ -1188,35 +1184,43 @@ def inbox_ranking_unseen_graded(context: dagster.AssetExecutionContext) -> None:
for observed_days in range(max(HEADS_BY_HORIZON) + 1):
heads = [head for head in HEADS if observed_days <= head.horizon_days]
scoring_partition = (day - datetime.timedelta(days=observed_days)).isoformat()
- table = read_parquet_if_exists(
- client, bucket, partition_object_key(prefix, UNSEEN_SCORES_TABLE, scoring_partition)
- )
- if table is None:
- skipped[scoring_partition] = "no unseen scores"
- continue
- scores = with_model_names(table.to_pandas())
- pool = scored_pool(scores)
- graded_by_head: dict[str, pd.DataFrame] = {}
- for head in heads:
- missing = missing_label_columns(labels, head)
- if missing:
- skipped[f"{scoring_partition}/{head.name}"] = f"dt={partition_key} labels lack {', '.join(missing)}"
- continue
- head_scores = scores[scores["head"] == head.name]
- if head_scores.empty:
- skipped[f"{scoring_partition}/{head.name}"] = "head was not scored"
+ # The served object is graded through the same path, apart from the unseen one, and its
+ # rows carry `model_role = 'served'`. A missing one is a logged skip, as a missing unseen
+ # object is: partitions before the served asset existed have none.
+ for scores_name, skip_prefix, kind in (
+ (UNSEEN_SCORES_TABLE, "", "unseen"),
+ (SERVED_SCORES_TABLE, "served/", "served"),
+ ):
+ table = read_parquet_if_exists(client, bucket, partition_object_key(prefix, scores_name, scoring_partition))
+ if table is None:
+ skipped[f"{skip_prefix}{scoring_partition}"] = f"no {kind} scores"
continue
- graded = graded_rows(head_scores, labels, head, pool=pool)
- evaluated = head_grades(graded, head, pool=pool, scoring_partition=scoring_partition, include_empty=True)
- evaluations.extend(evaluated)
- if observed_days == head.horizon_days:
- graded_by_head[head.name] = graded
- grades.extend(grade for grade in evaluated if grade.rows)
- report_rows.extend(
- report_grade_rows(
- graded_by_head, pool=pool, horizon_days=observed_days, scoring_partition=scoring_partition
+ scores = with_model_names(table.to_pandas())
+ pool = scored_pool(scores)
+ graded_by_head: dict[str, pd.DataFrame] = {}
+ for head in heads:
+ head_key = f"{skip_prefix}{scoring_partition}/{head.name}"
+ missing = missing_label_columns(labels, head)
+ if missing:
+ skipped[head_key] = f"dt={partition_key} labels lack {', '.join(missing)}"
+ continue
+ head_scores = scores[scores["head"] == head.name]
+ if head_scores.empty:
+ skipped[head_key] = "head was not scored"
+ continue
+ graded = graded_rows(head_scores, labels, head, pool=pool)
+ evaluated = head_grades(
+ graded, head, pool=pool, scoring_partition=scoring_partition, include_empty=True
+ )
+ evaluations.extend(evaluated)
+ if observed_days == head.horizon_days:
+ graded_by_head[head.name] = graded
+ grades.extend(grade for grade in evaluated if grade.rows)
+ report_rows.extend(
+ report_grade_rows(
+ graded_by_head, pool=pool, horizon_days=observed_days, scoring_partition=scoring_partition
+ )
)
- )
for grade in grades:
context.log.info(f"unseen grade: {grade.as_dict()}")
@@ -1255,6 +1259,7 @@ inbox_ranking_training_job = dagster.define_asset_job(
"inbox_ranking_model_champion",
SERVING_MANIFEST_ASSET,
UNSEEN_SCORES_TABLE,
+ SERVED_SCORES_TABLE,
"inbox_ranking_unseen_graded",
],
tags={
diff --git a/products/signals/dags/inbox_ranking/training/served.py b/products/signals/dags/inbox_ranking/training/served.py
new file mode 100644
index 000000000000..ff2693d00d17
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/training/served.py
@@ -0,0 +1,246 @@
+"""The served model's own birth-day scores, graded like the unseen ones.
+
+The unseen grade rescores the newborn pool inside the dag with the day's candidate and champion. It
+is not the score the inbox served. This module reads the scoring sweep's `inbox_ranking_report_scored`
+events for D's newborn pool and writes them in `SCORES_SCHEMA`, so `inbox_ranking_unseen_graded`
+grades them through the same path under `model_role = 'served'`.
+
+Caveats:
+
+- The daily promotion can change the served model part of the way through D, so one day's cohort
+ can split across two versions. Grades stay per `(model_name, model_version, model_role)` and are
+ never pooled across versions.
+- A report first scored after D ends, for example when its vector arrived late, is not in D's rows.
+ `served_pool_coverage` makes that visible. A later score never fills it in.
+- The sweep scores with the vector current at scoring time. The unseen grade uses the end-of-day
+ vector. Served and candidate grades of one day are two reads, not one paired number.
+- A deployment where the sweep is off writes an empty object with coverage 0 and grades nothing.
+"""
+
+import json
+import datetime
+from collections.abc import Collection, Mapping, Sequence
+from typing import Any
+
+import numpy as np
+import pandas as pd
+import dagster
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
+from posthog.hogql.query import execute_hogql_query
+
+from posthog import settings
+from posthog.models import Team
+
+from products.signals.backend.ranking.serving_manifest import SERVED_ROLE
+from products.signals.backend.ranking.sinks import REPORT_SCORED_EVENT
+from products.signals.dags.inbox_ranking.common import (
+ dataset_bucket,
+ object_row_count,
+ partition_object_key,
+ read_parquet_if_exists,
+ s3_client,
+ skip_unconfigured,
+ snapshot_bounds,
+ write_parquet,
+)
+from products.signals.dags.inbox_ranking.dataset.dag import LABELS_TABLE, STATE_TABLE
+from products.signals.dags.inbox_ranking.dataset.queries import etl_workload, labels_team, utc_bound
+from products.signals.dags.inbox_ranking.training.dag import COMMON_ASSET_KWARGS, load_snapshots
+from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME
+from products.signals.dags.inbox_ranking.training.unseen import (
+ POOL_NAME,
+ SCORE_COLUMNS,
+ SERVED_SCORES_TABLE,
+ empty_scores_write_allowed,
+ families_lost_by_rewrite,
+ scores_table,
+ unseen_pool,
+)
+
+# The status filter is repeated in `served_score_rows`, which also keeps only the served role: the
+# role list is a JSON array, and the row builder is where a test can pin both rules.
+SERVED_EVENTS_SQL = f"""
+SELECT timestamp, properties
+FROM events
+WHERE event = '{REPORT_SCORED_EVENT}'
+ AND timestamp >= toDateTime({{window_start}}) AND timestamp < toDateTime({{window_end}})
+ AND ifNull(toString(properties.environment), '') = {{environment}}
+ AND toString(properties.status) = 'scored'
+ AND toString(properties.report_id) IN {{report_ids}}
+"""
+
+
+def served_events(
+ team: Team,
+ report_ids: Collection[str],
+ *,
+ window_start: datetime.datetime,
+ window_end: datetime.datetime,
+ environment: str,
+) -> pd.DataFrame:
+ """Every scored event of this deployment for `report_ids` inside the window, as
+ `(scored_at, properties)` rows."""
+ if not report_ids:
+ return pd.DataFrame(columns=["scored_at", "properties"])
+ response = execute_hogql_query(
+ query=SERVED_EVENTS_SQL,
+ team=team,
+ query_type="inbox_ranking_served_scores",
+ placeholders={
+ "window_start": ast.Constant(value=utc_bound(window_start)),
+ "window_end": ast.Constant(value=utc_bound(window_end)),
+ "environment": ast.Constant(value=environment),
+ "report_ids": ast.Tuple(exprs=[ast.Constant(value=report_id) for report_id in sorted(report_ids)]),
+ },
+ limit_context=LimitContext.SAVED_QUERY,
+ workload=etl_workload(),
+ settings=HogQLGlobalSettings(max_execution_time=600),
+ # The dag runs without a user; the read is a trusted internal ETL over the dogfood project.
+ bypass_warehouse_access_control=True,
+ )
+ return pd.DataFrame(
+ [(scored_at, _properties(properties)) for scored_at, properties in response.results or []],
+ columns=["scored_at", "properties"],
+ )
+
+
+def _properties(value: Any) -> dict[str, Any]:
+ return json.loads(value) if isinstance(value, str) else dict(value or {})
+
+
+def served_score_rows(
+ events: pd.DataFrame, pool: pd.DataFrame, labels: pd.DataFrame, *, snapshot_date: datetime.date
+) -> pd.DataFrame:
+ """One row per (newborn report, head) in SCORE_COLUMNS order, from the report's earliest served
+ score in `events`.
+
+ `classification_threshold` is the served model's own `threshold_<head>`, null when the event
+ carries none, so every later grade of the row uses the cut that was served. `label_at_scoring`
+ reads D's snapshot labels, as `score_pool` does.
+ """
+ records = [
+ (scored_at, properties)
+ for scored_at, properties in zip(events["scored_at"], events["properties"])
+ if properties.get("status") == "scored"
+ and SERVED_ROLE in (properties.get("roles") or ())
+ and str(properties.get("report_id")) in pool.index
+ ]
+ earliest: dict[str, tuple[pd.Timestamp, Mapping[str, Any]]] = {}
+ for scored_at, properties in sorted(records, key=lambda record: pd.Timestamp(record[0])):
+ earliest.setdefault(str(properties["report_id"]), (pd.Timestamp(scored_at), properties))
+
+ aligned = labels.reindex(pool.index)
+ labels_by_head = {name: head.label(aligned) for name, head in HEADS_BY_NAME.items()}
+ rows: list[dict[str, object]] = []
+ for report_id, (scored_at, properties) in earliest.items():
+ created_at = pd.Timestamp(pool.at[report_id, "report_created_at"])
+ readable = properties.get("readable_heads")
+ for head_name in sorted(HEADS_BY_NAME):
+ score = properties.get(f"p_{head_name}")
+ if score is None:
+ continue
+ threshold = properties.get(f"threshold_{head_name}")
+ rows.append(
+ {
+ "report_id": report_id,
+ "team_id": properties.get("team_id"),
+ "report_created_at": created_at,
+ "snapshot_date": snapshot_date,
+ "pool": POOL_NAME,
+ "model_name": properties.get("model_name"),
+ "model_version": properties.get("model_version"),
+ "model_role": SERVED_ROLE,
+ # The event does not carry the feature contract version.
+ "feature_schema_version": None,
+ "head": head_name,
+ "score": float(score),
+ "age_hours": (_utc(scored_at) - _utc(created_at)).total_seconds() / 3600,
+ "label_at_scoring": bool(labels_by_head[head_name].at[report_id]),
+ # An event written before the property existed reads as unknown.
+ "head_readable": None if readable is None else head_name in readable,
+ "classification_threshold": np.nan if threshold is None else float(threshold),
+ }
+ )
+ if not rows:
+ return pd.DataFrame(columns=list(SCORE_COLUMNS))
+ frame = pd.DataFrame(rows)[list(SCORE_COLUMNS)]
+ frame["team_id"] = pd.to_numeric(frame["team_id"], errors="coerce").astype("Int64")
+ frame["feature_schema_version"] = frame["feature_schema_version"].astype("Int64")
+ frame["head_readable"] = frame["head_readable"].astype("boolean")
+ return frame
+
+
+def _utc(value: pd.Timestamp) -> pd.Timestamp:
+ return value.tz_localize("UTC") if value.tzinfo is None else value.tz_convert("UTC")
+
+
+def served_metadata(pool: pd.DataFrame, scores: pd.DataFrame) -> dict[str, dagster.MetadataValue]:
+ """Coverage of the pool, rows per model version, and the heads whose served model saved no
+ threshold."""
+ covered = scores["report_id"].nunique() if not scores.empty else 0
+ versions: Sequence[tuple[Any, int]] = (
+ [(key, len(group)) for key, group in scores.groupby(["model_name", "model_version"])]
+ if not scores.empty
+ else []
+ )
+ missing = scores[scores["classification_threshold"].isna()] if not scores.empty else scores
+ return {
+ "unseen_pool": dagster.MetadataValue.int(len(pool)),
+ "served_reports": dagster.MetadataValue.int(int(covered)),
+ "served_pool_coverage": dagster.MetadataValue.float(covered / len(pool) if len(pool) else 0.0),
+ "rows_by_model_version": dagster.MetadataValue.json(
+ {f"{name}@{version}": int(count) for (name, version), count in versions}
+ ),
+ "heads_without_threshold": dagster.MetadataValue.json(
+ sorted(missing["head"].unique().tolist()) if not missing.empty else []
+ ),
+ }
+
+
[email protected](name=SERVED_SCORES_TABLE, deps=[STATE_TABLE, LABELS_TABLE], **COMMON_ASSET_KWARGS)
+def inbox_ranking_served_scores(context: dagster.AssetExecutionContext) -> None:
+ """D's newborn pool with each report's earliest served score of D. See the module docstring for
+ the caveats every reader of these grades must keep."""
+ if skip_unconfigured(context):
+ return
+ partition_key = context.partition_key
+ bucket, prefix, client = dataset_bucket(), settings.INBOX_RANKING_DATASET_S3_PREFIX, s3_client()
+ day = datetime.date.fromisoformat(partition_key)
+ window_start, window_end = snapshot_bounds(partition_key)
+
+ snapshot = load_snapshots(client, bucket, prefix, [day], required=day)[day]
+ pool = unseen_pool(snapshot.state, day)
+ events = served_events(
+ labels_team(),
+ [str(report_id) for report_id in pool.index],
+ window_start=window_start,
+ window_end=window_end,
+ environment=settings.CLOUD_DEPLOYMENT or "",
+ )
+ scores = served_score_rows(events, pool, snapshot.labels, snapshot_date=day)
+
+ key = partition_object_key(prefix, SERVED_SCORES_TABLE, partition_key)
+ # The dt=D+horizon grade reads these rows. The events can be read again, but D's labels cannot.
+ if scores.empty:
+ existing_rows = object_row_count(client, bucket, key)
+ if not empty_scores_write_allowed(existing_rows):
+ raise dagster.Failure(
+ f"{SERVED_SCORES_TABLE} dt={partition_key} already holds {existing_rows} rows and this run read "
+ f"none, so writing would destroy the scores the dt=D+horizon grade reads. To replace the object "
+ f"deliberately, delete it by hand first."
+ )
+ context.log.warning(f"no served score for dt={partition_key}: {len(pool)} newborn reports")
+ existing = read_parquet_if_exists(client, bucket, key)
+ lost = families_lost_by_rewrite(existing.to_pandas(), scores) if existing is not None else []
+ if lost:
+ raise dagster.Failure(
+ f"{SERVED_SCORES_TABLE} dt={partition_key} already holds rows for {', '.join(lost)} and this run read "
+ f"none of them, so writing would destroy the scores the dt=D+horizon grade reads. Delete the object "
+ f"by hand to replace it deliberately."
+ )
+ write_parquet(client, bucket, key, scores_table(scores), snapshot_date=partition_key)
+ context.add_output_metadata(
+ {**served_metadata(pool, scores), "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}")}
+ )
diff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.py
index 4dd90b0fb7bb..90a9facf8499 100644
--- a/products/signals/dags/inbox_ranking/training/unseen.py
+++ b/products/signals/dags/inbox_ranking/training/unseen.py
@@ -55,6 +55,8 @@ POOL_NAME = "newborn"
LEGACY_POOL_NAME = "sampled"
UNSEEN_SCORES_TABLE = "inbox_ranking_unseen_scores"
+# The scoring sweep's own birth-day scores of the same pool, in the same schema (`training/served.py`).
+SERVED_SCORES_TABLE = "inbox_ranking_served_scores"
CANDIDATE_ROLE = "candidate"
CHAMPION_ROLE = "champion"