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): capture inbox ranking training metrics as events (#91321)

Andrew Maguireae11e8471450
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.yml
index b37a80f2eabb..34e1985e6dd5 100644
--- a/.github/workflows/ci-dagster.yml
+++ b/.github/workflows/ci-dagster.yml
@@ -147,6 +147,7 @@ jobs:
- 'posthog/event_usage.py'
- 'posthog/products.py'
- 'posthog/cloud_utils.py'
+ - 'posthog/ph_client.py'
- 'products/managed_warehouse/backend/**'
# Backward compatibility for unrebased PRs; remove after August 14, 2026.
- 'posthog/ducklake/**'
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.md
index a52fcbc4623a..c42fa5f4637f 100644
--- a/products/signals/dags/inbox_ranking/README.md
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -74,6 +74,7 @@ s3://<bucket>/<prefix>/
- **Serving population caveat.** Training keeps only moments where the head's outcome has not happened yet, but the scoring sweep cannot see outcome state, so it also scores reports that were already opened or acted on. `p_open` on an already-opened report is undefined; the shadow eval joins scores as of impression time, which keeps the read honest. Stopping a head once its outcome is observed is a sweep-side change.
- **Features are tabular only in v0** (`products/signals/backend/ranking/features.py`: the state counters, title/summary length, age, one-hot priority/actionability). No embedding, no impression-derived columns, so the scoring sweep needs only the `SignalReport` row and its judgment artefacts. The sweep must build features through the same module; the booster's `feature_names` are checked against it at load.
- **Candidate**: per-head XGBoost with fixed params, holdout = the last `holdout_days` of reports (cut by report, never by row), AUC + a label-permutation null. A head is _readable_ when it has enough holdout positives and clears its null by 0.05. The shipped booster (`<head>.ubj`) is refit on everything; the train-only fit is kept as `<head>.holdout.ubj` so a later candidate can grade this model on its own holdout.
+- **Metrics telemetry**: each asset also captures its metrics as events into the dogfood project (the same project the label events land in), through `training/telemetry.py`: `inbox_ranking_examples_built` and `inbox_ranking_candidate_trained` once per head (`head`, holdout / train AUC, average precision, logloss, positive rate, the permutation-null mean and spread, counts, `readable`) and `inbox_ranking_promotion_decided` once per run, all carrying `model_version` and stamped midday UTC on the partition day so re-runs and backfills chart on the day they describe. Per-head stability is a trends insight with a `head` breakdown; a readability drop is an insight alert. `metadata.json` stays the durable record. Capture is best-effort. Local dev runs (`DEBUG`) emit too, under `distinct_id` `inbox_ranking_training_local` with `environment=local`, so filter or break down on `environment` when reading the prod series; any other non-Cloud deployment emits nothing.
- **Champion**: `promotion.decide_promotion` — promote when the candidate has a readable head, is within 0.02 AUC of the champion on every head the champion could read, and the champion is at least `INBOX_RANKING_PROMOTION_MIN_DAYS` old. The champion's AUCs come from its `<head>.holdout.ubj` scored on the candidate's holdout (`paired_champion_aucs`), so both models are compared on one set of reports; a champion without that file falls back to its stored AUC. The pointer is rewritten only when `INBOX_RANKING_AUTO_PROMOTE` is on; otherwise the decision is logged and surfaced as asset metadata, so the daily candidate series is monitoring while the first shadow read runs on a frozen champion. To promote by hand, copy a candidate's `metadata.json` to `champion.json` with a `promoted_at`.
### Configuration
diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.py
index c41fd94dfc7a..ef966abd0a3e 100644
--- a/products/signals/dags/inbox_ranking/tests/test_training.py
+++ b/products/signals/dags/inbox_ranking/tests/test_training.py
@@ -1,5 +1,6 @@
import math
import datetime
+from typing import Any
import pytest
@@ -30,7 +31,17 @@ from products.signals.dags.inbox_ranking.training.examples import (
holdout_mask,
)
from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, dismissed_as_wrong
-from products.signals.dags.inbox_ranking.training.promotion import AUC_TOLERANCE, decide_promotion
+from products.signals.dags.inbox_ranking.training.promotion import AUC_TOLERANCE, PromotionDecision, decide_promotion
+from products.signals.dags.inbox_ranking.training.telemetry import (
+ DISTINCT_ID,
+ LOCAL_DISTINCT_ID,
+ HeadExampleCounts,
+ TrainingEvent,
+ candidate_events,
+ capture_training_events,
+ examples_events,
+ promotion_event,
+)
from products.signals.dags.inbox_ranking.training.train import _head_readable, booster_holdout_auc, train_head
D0 = datetime.date(2026, 8, 10)
@@ -250,6 +261,13 @@ def test_train_head_learns_a_separable_signal_and_names_its_features():
assert trained.metrics.readable
assert trained.metrics.holdout_auc is not None and trained.metrics.holdout_auc > 0.9
assert trained.metrics.null_auc is not None and abs(trained.metrics.null_auc - 0.5) < 0.15
+ assert trained.metrics.null_auc_std is not None and trained.metrics.null_auc_std < 0.15
+ assert trained.metrics.train_auc is not None and trained.metrics.train_auc > 0.9
+ assert trained.metrics.holdout_average_precision is not None and trained.metrics.holdout_average_precision > 0.9
+ assert trained.metrics.holdout_logloss is not None and trained.metrics.holdout_logloss < 0.5
+ assert trained.metrics.holdout_positive_rate == pytest.approx(
+ trained.metrics.holdout_positives / trained.metrics.holdout_rows
+ )
booster = xgb.Booster()
booster.load_model(bytearray(trained.booster_ubj))
assert booster.feature_names == list(FEATURE_NAMES)
@@ -265,6 +283,43 @@ def test_train_head_learns_a_separable_signal_and_names_its_features():
assert booster_holdout_auc(other_ubj, examples, head, holdout_days=7) is None
+def test_train_head_keeps_logloss_on_a_single_class_holdout():
+ # Only the newest reports fall in the holdout, and they are all negatives: AUC is undefined
+ # there but logloss is not, and the head must still train and ship.
+ head = HEADS_BY_NAME["open"]
+ rng = np.random.default_rng(1)
+ n = 400
+ created = pd.to_datetime("2026-07-01", utc=True) + pd.to_timedelta(rng.integers(0, 40, n), unit="D")
+ signal_count = rng.integers(1, 50, n)
+ rows = pd.DataFrame(
+ {
+ "signal_count": signal_count,
+ "total_weight": rng.random(n),
+ "run_count": 1,
+ "title_chars": 40,
+ "summary_chars": 400,
+ "priority": "P2",
+ "actionability": None,
+ "age_hours": 12.0,
+ }
+ )
+ examples = feature_frame(rows)
+ examples.insert(0, "head", head.name)
+ examples.insert(1, "report_id", [f"r{i}" for i in range(n)])
+ examples.insert(2, "snapshot_date", D0)
+ examples.insert(3, "report_created_at", created)
+ in_holdout = holdout_mask(examples, 7).to_numpy()
+ examples["label"] = ((signal_count > 25) & ~in_holdout).astype(int)
+
+ trained = train_head(examples, head, holdout_days=7)
+ assert trained is not None
+ assert trained.metrics.holdout_positives == 0
+ assert trained.metrics.holdout_auc is None
+ assert trained.metrics.holdout_average_precision is None
+ assert trained.metrics.holdout_logloss is not None and trained.metrics.holdout_logloss > 0
+ assert not trained.metrics.readable
+
+
def test_train_head_returns_none_without_both_classes():
head = HEADS_BY_NAME["open"]
examples = pd.DataFrame(
@@ -281,6 +336,114 @@ def test_train_head_returns_none_without_both_classes():
assert train_head(examples, head, holdout_days=7) is None
+class _FakeClient:
+ def __init__(self) -> None:
+ self.calls: list[dict[str, Any]] = []
+ self.shutdowns = 0
+
+ def capture(self, **kwargs: Any) -> None:
+ self.calls.append(kwargs)
+
+ def shutdown(self) -> None:
+ self.shutdowns += 1
+
+
+def _patch_capture(monkeypatch, *, cloud: bool, debug: bool) -> _FakeClient:
+ client = _FakeClient()
+ monkeypatch.setattr("products.signals.dags.inbox_ranking.training.telemetry.get_client", lambda region: client)
+ monkeypatch.setattr("products.signals.dags.inbox_ranking.training.telemetry.is_cloud", lambda: cloud)
+ monkeypatch.setattr(settings, "DEBUG", debug)
+ monkeypatch.setattr(settings, "CLOUD_DEPLOYMENT", "US" if cloud else None)
+ return client
+
+
+ "cloud,debug,expected_distinct_id,expected_environment",
+ [
+ (True, False, DISTINCT_ID, "US"),
+ (False, True, LOCAL_DISTINCT_ID, "local"), # a laptop run lands on the dashboard, marked
+ (False, False, None, None), # a self-hosted instance never reports into PostHog's project
+ ],
+)
+def test_training_events_capture_gate_and_local_marking(
+ monkeypatch, cloud, debug, expected_distinct_id, expected_environment
+):
+ client = _patch_capture(monkeypatch, cloud=cloud, debug=debug)
+ events = [TrainingEvent(event="inbox_ranking_examples_built", properties={"head": "open"})]
+ capture_training_events(dagster.build_asset_context(), "2026-08-25", events)
+ if expected_distinct_id is None:
+ assert client.calls == []
+ return
+ assert client.shutdowns == 1
+ (call,) = client.calls
+ assert call["distinct_id"] == expected_distinct_id
+ assert call["properties"]["environment"] == expected_environment
+
+
+def test_training_events_carry_the_dashboard_contract(monkeypatch):
+ # The per-head events are what the project-2 insights break down on; dropping the head
+ # property, the partition-day timestamp, or the person-profile opt-out breaks every chart.
+ metadata = {
+ "model_version": "2026-08-25",
+ "run_id": "run-1",
+ "dataset_version": "v1",
+ "feature_schema_version": 1,
+ "lookback_days": 60,
+ "holdout_days": 7,
+ "heads": [
+ {"head": "open", "holdout_auc": 0.67, "readable": True, "file": "open.ubj", "holdout_file": None},
+ {"head": "action", "holdout_auc": None, "readable": False, "file": "action.ubj", "holdout_file": None},
+ ],
+ "skipped_heads": ["dismiss_wrong"],
+ }
+ events = [
+ *candidate_events(metadata),
+ *examples_events(
+ partition_key="2026-08-25",
+ run_id="run-1",
+ snapshots=20,
+ backfilled_rows=0,
+ per_head={"open": HeadExampleCounts(rows=10, positives=2)},
+ ),
+ promotion_event(
+ partition_key="2026-08-25",
+ run_id="run-1",
+ decision=PromotionDecision(promote=True, reason="no champion yet"),
+ promoted=False,
+ champion_version="none",
+ incumbent_champion_version="none",
+ champion_aucs={"open": 0.6},
+ ),
+ ]
+ client = _patch_capture(monkeypatch, cloud=True, debug=False)
+ capture_training_events(dagster.build_asset_context(), "2026-08-25", events)
+
+ by_event: dict[str, list[dict]] = {}
+ for call in client.calls:
+ by_event.setdefault(call["event"], []).append(call)
+ assert call["distinct_id"] == DISTINCT_ID
+ assert call["timestamp"] == datetime.datetime(2026, 8, 25, 12, tzinfo=datetime.UTC)
+ assert call["properties"]["$process_person_profile"] is False
+ assert call["properties"]["model_version"] == "2026-08-25"
+ candidates = by_event["inbox_ranking_candidate_trained"]
+ assert [c["properties"]["head"] for c in candidates] == ["open", "action", "dismiss_wrong"]
+ assert candidates[0]["properties"]["holdout_auc"] == 0.67
+ assert candidates[0]["properties"]["lookback_days"] == 60
+ assert candidates[0]["properties"]["trained"] is True
+ assert "file" not in candidates[0]["properties"]
+ # A head with nothing to fit still reports, so the readability alert sees a bad day, not a gap.
+ assert {"trained": False, "readable": False}.items() <= candidates[2]["properties"].items()
+ examples_props = by_event["inbox_ranking_examples_built"][0]["properties"]
+ assert {"head": "open", "rows": 10, "positives": 2}.items() <= examples_props.items()
+ promotion_props = by_event["inbox_ranking_promotion_decided"][0]["properties"]
+ assert {
+ "would_promote": True,
+ "promoted": False,
+ "incumbent_champion_version": "none",
+ "champion_open_auc_on_this_holdout": 0.6,
+ }.items() <= promotion_props.items()
+
+
@pytest.mark.parametrize(
"holdout_auc,null_auc,holdout_positives,expected",
[
diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.py
index bbc30a90a909..018e35c3e4fe 100644
--- a/products/signals/dags/inbox_ranking/training/dag.py
+++ b/products/signals/dags/inbox_ranking/training/dag.py
@@ -57,6 +57,13 @@ from products.signals.dags.inbox_ranking.training.examples import (
)
from products.signals.dags.inbox_ranking.training.heads import HEADS, HEADS_BY_NAME
from products.signals.dags.inbox_ranking.training.promotion import decide_promotion
+from products.signals.dags.inbox_ranking.training.telemetry import (
+ HeadExampleCounts,
+ candidate_events,
+ capture_training_events,
+ examples_events,
+ promotion_event,
+)
from products.signals.dags.inbox_ranking.training.train import XGB_PARAMS, TrainedHead, booster_holdout_auc, train_head
EXAMPLES_TABLE = "inbox_ranking_training_examples"
@@ -199,23 +206,43 @@ def inbox_ranking_training_examples(context: dagster.AssetExecutionContext) -> N
key = partition_object_key(prefix, EXAMPLES_TABLE, partition_key)
write_parquet(client, bucket, key, examples_table(examples), snapshot_date=partition_key)
+ counts = {
+ name: HeadExampleCounts(rows=len(frame), positives=int(frame["label"].sum()))
+ for name, frame in per_head.items()
+ }
context.add_output_metadata(
{
"rows": dagster.MetadataValue.int(len(examples)),
"snapshots": dagster.MetadataValue.int(len(snapshots)),
"backfilled_state_rows_excluded": dagster.MetadataValue.int(backfilled_rows),
- **{f"{name}_rows": dagster.MetadataValue.int(len(frame)) for name, frame in per_head.items()},
+ **{f"{name}_rows": dagster.MetadataValue.int(head_counts.rows) for name, head_counts in counts.items()},
**{
- f"{name}_positives": dagster.MetadataValue.int(int(frame["label"].sum()))
- for name, frame in per_head.items()
+ f"{name}_positives": dagster.MetadataValue.int(head_counts.positives)
+ for name, head_counts in counts.items()
},
"s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),
}
)
+ capture_training_events(
+ context,
+ partition_key,
+ examples_events(
+ partition_key=partition_key,
+ run_id=context.run.run_id,
+ snapshots=len(snapshots),
+ backfilled_rows=backfilled_rows,
+ per_head=counts,
+ ),
+ )
def candidate_metadata(
- partition_key: str, trained: list[TrainedHead], *, trained_at: datetime.datetime, run_id: str
+ partition_key: str,
+ trained: list[TrainedHead],
+ *,
+ skipped: list[str],
+ trained_at: datetime.datetime,
+ run_id: str,
) -> dict[str, Any]:
return {
"model_version": partition_key,
@@ -235,6 +262,8 @@ def candidate_metadata(
}
for head in trained
],
+ # Heads with nothing to fit on this partition; recorded so the per-head series has no gap.
+ "skipped_heads": skipped,
}
@@ -269,10 +298,12 @@ def inbox_ranking_model_candidate(context: dagster.AssetExecutionContext) -> Non
examples = read_parquet(client, bucket, partition_object_key(prefix, EXAMPLES_TABLE, partition_key)).to_pandas()
trained: list[TrainedHead] = []
+ skipped: list[str] = []
for head in HEADS:
result = train_head(examples, head, holdout_days=settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS)
if result is None:
context.log.warning(f"{head.name}: nothing to fit, skipped")
+ skipped.append(head.name)
continue
context.log.info(f"{head.name}: {result.metrics.as_dict()}")
trained.append(result)
@@ -287,7 +318,11 @@ def inbox_ranking_model_candidate(context: dagster.AssetExecutionContext) -> Non
client.put_object(Bucket=bucket, Key=key, Body=body, ContentType="application/octet-stream")
written.add(key)
metadata = candidate_metadata(
- partition_key, trained, trained_at=datetime.datetime.now(datetime.UTC), run_id=context.run.run_id
+ partition_key,
+ trained,
+ skipped=skipped,
+ trained_at=datetime.datetime.now(datetime.UTC),
+ run_id=context.run.run_id,
)
metadata_key = model_object_key(prefix, partition_key, METADATA_FILE)
_put_json(client, bucket, metadata_key, metadata)
@@ -296,6 +331,7 @@ def inbox_ranking_model_candidate(context: dagster.AssetExecutionContext) -> Non
stale = _delete_other_objects(client, bucket, model_object_key(prefix, partition_key, ""), written)
if stale:
context.log.warning(f"removed {len(stale)} stale objects from a previous run of dt={partition_key}")
+ capture_training_events(context, partition_key, candidate_events(metadata))
context.add_output_metadata(
{
"stale_objects_removed": dagster.MetadataValue.int(len(stale)),
@@ -355,6 +391,10 @@ def inbox_ranking_model_champion(context: dagster.AssetExecutionContext) -> None
elif decision.promote:
context.log.info("INBOX_RANKING_AUTO_PROMOTE is off; candidate would have been promoted")
+ # The paired AUCs belong to the incumbent: after a promotion `champion_version` names the
+ # candidate, so the incumbent is recorded alongside to keep the scores attributable.
+ incumbent_champion_version = (champion or {}).get("model_version", "none")
+ champion_version = partition_key if promoted else incumbent_champion_version
context.add_output_metadata(
{
"would_promote": dagster.MetadataValue.bool(decision.promote),
@@ -364,11 +404,25 @@ def inbox_ranking_model_champion(context: dagster.AssetExecutionContext) -> None
f"champion_{head}_auc_on_this_holdout": dagster.MetadataValue.float(auc)
for head, auc in champion_aucs.items()
},
- "champion_version": dagster.MetadataValue.text(
- partition_key if promoted else (champion or {}).get("model_version", "none")
- ),
+ "incumbent_champion_version": dagster.MetadataValue.text(incumbent_champion_version),
+ "champion_version": dagster.MetadataValue.text(champion_version),
}
)
+ capture_training_events(
+ context,
+ partition_key,
+ [
+ promotion_event(
+ partition_key=partition_key,
+ run_id=context.run.run_id,
+ decision=decision,
+ promoted=promoted,
+ champion_version=champion_version,
+ incumbent_champion_version=incumbent_champion_version,
+ champion_aucs=champion_aucs,
+ )
+ ],
+ )
inbox_ranking_training_job = dagster.define_asset_job(
diff --git a/products/signals/dags/inbox_ranking/training/telemetry.py b/products/signals/dags/inbox_ranking/training/telemetry.py
new file mode 100644
index 000000000000..9be66c7cdf49
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/training/telemetry.py
@@ -0,0 +1,181 @@
+"""Training metrics as events in the internal analytics project.
+
+`metadata.json` is the durable record of a candidate, but one JSON object per day in S3 cannot be
+charted. Every training run also captures its metrics as events into the dogfood project, the
+same project the label events land in, keyed by `model_version` and stamped with the partition
+day. Per-head stability is then a trends insight with a `head` breakdown, and a drop in
+readability is an insight alert. Delivery is best-effort and never fails an asset.
+"""
+
+import datetime
+from collections.abc import Mapping
+from typing import Any
+
+import dagster
+
+from posthog import settings
+from posthog.cloud_utils import is_cloud
+from posthog.dataclasses import frozen
+from posthog.ph_client import get_client
+
+from products.signals.dags.inbox_ranking.common import snapshot_bounds
+from products.signals.dags.inbox_ranking.training.promotion import PromotionDecision
+
+# Not a person: one fixed id for the whole dag, and no person profile is created for it. Local dev
+# runs get their own id so they never blend into the prod series.
+DISTINCT_ID = "inbox_ranking_training"
+LOCAL_DISTINCT_ID = "inbox_ranking_training_local"
+LOCAL_ENVIRONMENT = "local"
+CANDIDATE_TRAINED_EVENT = "inbox_ranking_candidate_trained"
+EXAMPLES_BUILT_EVENT = "inbox_ranking_examples_built"
+PROMOTION_DECIDED_EVENT = "inbox_ranking_promotion_decided"
+
+# Candidate metadata copied onto every per-head event so a chart can filter or break down on it.
+_CANDIDATE_CONTEXT_KEYS = (
+ "model_version",
+ "run_id",
+ "dataset_version",
+ "feature_schema_version",
+ "lookback_days",
+ "holdout_days",
+)
+# Object names inside the models prefix; meaningless on a chart.
+_HEAD_FILE_KEYS = ("file", "holdout_file")
+
+
+@frozen
+class TrainingEvent:
+ event: str
+ properties: dict[str, object]
+
+
+@frozen
+class HeadExampleCounts:
+ rows: int
+ positives: int
+
+
+def candidate_events(metadata: Mapping[str, Any]) -> list[TrainingEvent]:
+ """One event per head: the head's metrics plus the candidate context. A head the candidate
+ could not fit still gets an event (`trained` false, `readable` false), so a per-head alert sees
+ a bad day instead of a missing one."""
+ context = {key: metadata.get(key) for key in _CANDIDATE_CONTEXT_KEYS}
+ trained = [
+ TrainingEvent(
+ event=CANDIDATE_TRAINED_EVENT,
+ properties={
+ **context,
+ "trained": True,
+ **{key: value for key, value in head.items() if key not in _HEAD_FILE_KEYS},
+ },
+ )
+ for head in metadata.get("heads", [])
+ ]
+ skipped = [
+ TrainingEvent(
+ event=CANDIDATE_TRAINED_EVENT,
+ properties={**context, "head": head, "trained": False, "readable": False, "skip_reason": "nothing to fit"},
+ )
+ for head in metadata.get("skipped_heads", [])
+ ]
+ return [*trained, *skipped]
+
+
+def examples_events(
+ *,
+ partition_key: str,
+ run_id: str,
+ snapshots: int,
+ backfilled_rows: int,
+ per_head: Mapping[str, HeadExampleCounts],
+) -> list[TrainingEvent]:
+ """One event per head with its example and positive counts; the run-level counts repeat on each."""
+ return [
+ TrainingEvent(
+ event=EXAMPLES_BUILT_EVENT,
+ properties={
+ "model_version": partition_key,
+ "run_id": run_id,
+ "snapshots": snapshots,
+ "backfilled_state_rows_excluded": backfilled_rows,
+ "head": head,
+ "rows": counts.rows,
+ "positives": counts.positives,
+ },
+ )
+ for head, counts in per_head.items()
+ ]
+
+
+def promotion_event(
+ *,
+ partition_key: str,
+ run_id: str,
+ decision: PromotionDecision,
+ promoted: bool,
+ champion_version: str,
+ incumbent_champion_version: str,
+ champion_aucs: Mapping[str, float],
+) -> TrainingEvent:
+ """`champion_aucs` were scored by the incumbent on this candidate's holdout; after a promotion
+ `champion_version` is the candidate, so the incumbent is carried separately."""
+ return TrainingEvent(
+ event=PROMOTION_DECIDED_EVENT,
+ properties={
+ "model_version": partition_key,
+ "run_id": run_id,
+ "would_promote": decision.promote,
+ "promoted": promoted,
+ "reason": decision.reason,
+ "champion_version": champion_version,
+ "incumbent_champion_version": incumbent_champion_version,
+ **{f"champion_{head}_auc_on_this_holdout": auc for head, auc in champion_aucs.items()},
+ },
+ )
+
+
+def event_timestamp(partition_key: str) -> datetime.datetime:
+ """Midday UTC of the partition day. The run happens the next morning, so wall-clock time would
+ chart a candidate one day late, and midnight UTC falls on the previous day in the dogfood
+ project's US/Pacific timezone."""
+ start, _ = snapshot_bounds(partition_key)
+ return start + datetime.timedelta(hours=12)
+
+
+def capture_allowed() -> bool:
+ """Cloud, or a developer's DEBUG stack. A self-hosted instance running this dag must not
+ report into PostHog's own project, which is the gate `ph_client.ScopedCapture` applies; local
+ dev runs are let through on purpose so laptop experiments land on the same dashboard."""
+ return is_cloud() or bool(settings.DEBUG)
+
+
+def capture_training_events(
+ context: dagster.AssetExecutionContext, partition_key: str, events: list[TrainingEvent]
+) -> None:
+ """Best-effort: a failed capture is logged, never raised, so telemetry cannot fail a training
+ run. Local runs are marked twice, by `environment` and by their own distinct id, so a chart
+ that forgets to filter still shows them as a separate series."""
+ if not capture_allowed():
+ return
+ environment = settings.CLOUD_DEPLOYMENT or LOCAL_ENVIRONMENT
+ distinct_id = DISTINCT_ID if environment != LOCAL_ENVIRONMENT else LOCAL_DISTINCT_ID
+ timestamp = event_timestamp(partition_key)
+ base = {"$process_person_profile": False, "partition": partition_key, "environment": environment}
+ # A fresh client per call, flushed on shutdown, for the same reason `ph_scoped_capture` builds
+ # one: the step process exits right after the asset, before a shared client's background
+ # thread would deliver.
+ client = get_client("US")
+ if client is None:
+ return
+ try:
+ for event in events:
+ client.capture(
+ distinct_id=distinct_id,
+ event=event.event,
+ properties={**base, **event.properties},
+ timestamp=timestamp,
+ )
+ except Exception:
+ context.log.warning(f"training telemetry capture failed for dt={partition_key}", exc_info=True)
+ finally:
+ client.shutdown()
diff --git a/products/signals/dags/inbox_ranking/training/train.py b/products/signals/dags/inbox_ranking/training/train.py
index e04500ee1fc4..8e4edd52526f 100644
--- a/products/signals/dags/inbox_ranking/training/train.py
+++ b/products/signals/dags/inbox_ranking/training/train.py
@@ -8,7 +8,7 @@ the serving side can assert `booster.feature_names == FEATURE_NAMES` at load.
import numpy as np
import pandas as pd
import xgboost as xgb
-from sklearn.metrics import roc_auc_score
+from sklearn.metrics import average_precision_score, log_loss, roc_auc_score
from posthog.dataclasses import frozen
@@ -29,6 +29,11 @@ XGB_PARAMS: dict[str, object] = {
# A readable head must also clear its own permutation null by this much; below it the AUC is
# within the noise of this many positives.
NULL_MARGIN = 0.05
+# Each null is a full fit on permuted labels, so this multiplies the training cost per head. One
+# draw swings with whichever feature the permuted fit happened to lean on (age_hours dominates),
+# which put single-draw nulls at 0.38 on a 35k-row holdout; the mean of a few draws is the number
+# the margin is compared against, and the spread is reported so a wide band is visible.
+NULL_PERMUTATIONS = 3
@frozen
@@ -39,8 +44,17 @@ class HeadMetrics:
holdout_rows: int
holdout_positives: int
holdout_auc: float | None
+ # Mean and spread over NULL_PERMUTATIONS label-permutation fits scored on the holdout.
null_auc: float | None
+ null_auc_std: float | None
readable: bool
+ # Metrics for the dashboard, not the gate: the train-fit AUC on its own rows (the gap to
+ # holdout_auc is the overfit signal), and holdout metrics that read better than AUC when
+ # positives are rare.
+ train_auc: float | None = None
+ holdout_average_precision: float | None = None
+ holdout_logloss: float | None = None
+ holdout_positive_rate: float | None = None
def as_dict(self) -> dict[str, object]:
return {
@@ -51,7 +65,13 @@ class HeadMetrics:
"holdout_positives": self.holdout_positives,
"holdout_auc": self.holdout_auc,
"null_auc": self.null_auc,
+ "null_auc_std": self.null_auc_std,
+ "null_permutations": NULL_PERMUTATIONS,
"readable": self.readable,
+ "train_auc": self.train_auc,
+ "holdout_average_precision": self.holdout_average_precision,
+ "holdout_logloss": self.holdout_logloss,
+ "holdout_positive_rate": self.holdout_positive_rate,
}
@@ -86,8 +106,8 @@ def _head_readable(
) -> bool:
"""Readable = enough holdout positives, an above-chance holdout AUC, and clearing the head's own
permutation null by NULL_MARGIN. The absolute 0.5 floor is load-bearing on top of the null
- margin because the null is a single noisy draw: an inversely predictive head (AUC below chance)
- can still beat one low null draw by the margin, and must not be graded readable."""
+ margin because the null is a mean of a few noisy draws: an inversely predictive head (AUC below
+ chance) can still beat a low null mean by the margin, and must not be graded readable."""
if holdout_auc is None or null_auc is None:
return False
return holdout_positives >= min_positives and holdout_auc > 0.5 and holdout_auc - null_auc >= NULL_MARGIN
@@ -106,13 +126,23 @@ def train_head(examples: pd.DataFrame, head: Head, *, holdout_days: int, seed: i
return None
model = _fit(x_train, y_train, seed)
- holdout_auc = _auc(y_test, model.predict_proba(x_test)[:, 1]) if len(y_test) else None
+ train_auc = _auc(y_train, model.predict_proba(x_train)[:, 1])
+ holdout_scores = model.predict_proba(x_test)[:, 1] if len(y_test) else np.array([])
+ holdout_auc = _auc(y_test, holdout_scores) if len(y_test) else None
null_auc: float | None = None
+ null_auc_std: float | None = None
if holdout_auc is not None:
rng = np.random.default_rng(seed)
- null_model = _fit(x_train, rng.permutation(y_train), seed)
- null_auc = _auc(y_test, null_model.predict_proba(x_test)[:, 1])
+ null_aucs = [
+ auc
+ for draw in range(NULL_PERMUTATIONS)
+ if (auc := _auc(y_test, _fit(x_train, rng.permutation(y_train), seed + draw).predict_proba(x_test)[:, 1]))
+ is not None
+ ]
+ if null_aucs:
+ null_auc = float(np.mean(null_aucs))
+ null_auc_std = float(np.std(null_aucs))
readable = _head_readable(holdout_auc, null_auc, int(y_test.sum()), min_positives=head.min_holdout_positives)
metrics = HeadMetrics(
@@ -123,7 +153,15 @@ def train_head(examples: pd.DataFrame, head: Head, *, holdout_days: int, seed: i
holdout_positives=int(y_test.sum()),
holdout_auc=holdout_auc,
null_auc=null_auc,
+ null_auc_std=null_auc_std,
readable=readable,
+ train_auc=train_auc,
+ holdout_average_precision=(
+ float(average_precision_score(y_test, holdout_scores)) if holdout_auc is not None else None
+ ),
+ # Logloss is defined on a single-class holdout, unlike AUC and average precision.
+ holdout_logloss=float(log_loss(y_test, holdout_scores, labels=[0, 1])) if len(y_test) else None,
+ holdout_positive_rate=float(y_test.mean()) if len(y_test) else None,
)
# Refit on everything before shipping: the holdout only exists to grade the recipe.
final = _fit(x, y, seed)