: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): add pr_merged, discuss, and refund heads to inbox ranking (#92454)
posthog[bot]0a1dbb053a0f
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex 23efc2b0738f..52e84ae3f8b5 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -70,7 +70,7 @@ s3://<bucket>/<prefix>/└── champion.json # pointer the scoring sweep loads (the only object written across partitions)```-- **Examples are scoring moments, not reports.** For partition `dt=D` the examples asset reads the report-state and labels snapshots `dt=D-lookback..D` and emits one row per (report, snapshot) whose head label is still 0 on that snapshot, labeled from the snapshot `horizon_days` later (3 for open, 7 for action / dismiss_wrong / pr_created). Features are that snapshot's state columns plus `age_hours`, the report's age at the snapshot. Labels are aligned to the state spine, so a report with no label event is a negative (all-zero labels), not absent. Label-only rows (no Postgres state) are skipped, as are state rows read long after their snapshot day (backfills carry current Postgres state; see `features_observed_at`) and, for the `dismiss_wrong` head, rows whose status telemetry fails the dataset's `label_provenance_ok` check. This is the serving situation replayed over history; it measured better than one row per report on the engagement heads.+- **Examples are scoring moments, not reports.** For partition `dt=D` the examples asset reads the report-state and labels snapshots `dt=D-lookback..D` and emits one row per (report, snapshot) whose head label is still 0 on that snapshot, labeled from the snapshot `horizon_days` later (3 for open, 7 for action / dismiss_wrong / pr_created / discuss, 14 for pr_merged / refund). Features are that snapshot's state columns plus `age_hours`, the report's age at the snapshot. Labels are aligned to the state spine, so a report with no label event is a negative (all-zero labels), not absent. Label-only rows (no Postgres state) are skipped, as are state rows read long after their snapshot day (backfills carry current Postgres state; see `features_observed_at`) and, for the `dismiss_wrong` head, rows whose status telemetry fails the dataset's `label_provenance_ok` check. This is the serving situation replayed over history; it measured better than one row per report on the engagement heads.- **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.diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.pyindex ef966abd0a3e..e33bcdb303b6 100644--- a/products/signals/dags/inbox_ranking/tests/test_training.py+++ b/products/signals/dags/inbox_ranking/tests/test_training.py@@ -1,3 +1,4 @@+import ioimport mathimport datetimefrom typing import Any@@ -7,12 +8,15 @@ import pytestimport numpy as npimport pandas as pdimport dagster+import pyarrow as paimport xgboost as xgb+import pyarrow.parquet as pqfrom botocore.exceptions import ClientErrorfrom posthog import settingsfrom products.signals.backend.ranking.features import FEATURE_NAMES, feature_frame, feature_vector+from products.signals.dags.inbox_ranking.common import partition_object_keyfrom products.signals.dags.inbox_ranking.dataset.dag import LABELS_TABLE, STATE_TABLEfrom products.signals.dags.inbox_ranking.training.dag import (_delete_other_objects,@@ -210,6 +214,90 @@ def test_dismissed_as_wrong_prefers_the_cumulative_count(frame, expected):assert dismissed_as_wrong(frame).tolist() == expected+ "head_name,frame,expected_cohort,expected_label",+ [+ # pr_merged: cohort is reports with a PR, label is the merge within the horizon.+ (+ "pr_merged",+ pd.DataFrame({"pr_created_count": [1, 1, 0], "pr_merged_count": [1, 0, 0]}),+ [True, True, False],+ [True, False, False],+ ),+ # discuss: cohort is impressed reports, label is a discuss action.+ (+ "discuss",+ pd.DataFrame({"impression_unit_count": [1, 1, 0], "discuss_count": [2, 0, 0]}),+ [True, True, False],+ [True, False, False],+ ),+ # refund: cohort is everyone, label is a refund event.+ (+ "refund",+ pd.DataFrame({"refund_count": [1, 0, 0]}),+ [True, True, True],+ [True, False, False],+ ),+ ],+)+def test_new_heads_read_the_right_cohort_and_label_columns(head_name, frame, expected_cohort, expected_label):+ head = HEADS_BY_NAME[head_name]+ assert head.cohort(frame).tolist() == expected_cohort+ assert head.label(frame).tolist() == expected_label+++def _parquet(frame: pd.DataFrame) -> bytes:+ buffer = io.BytesIO()+ pq.write_table(pa.Table.from_pandas(frame.reset_index(), preserve_index=False), buffer)+ return buffer.getvalue()+++class _ParquetS3:+ """Serves the state and labels parquet objects load_snapshots reads, keyed by object key."""++ def __init__(self, objects: dict[str, bytes]) -> None:+ self._objects = objects++ def get_object(self, *, Bucket, Key):+ if Key not in self._objects:+ raise ClientError({"Error": {"Code": "NoSuchKey"}}, "GetObject")+ return {"Body": io.BytesIO(self._objects[Key])}++[email protected]("head_name", ["pr_merged", "refund"])+def test_new_head_label_columns_survive_the_load_snapshots_projection(head_name):+ # load_snapshots projects the labels parquet down to _LABEL_COLUMNS before any head sees it, so a+ # head whose label column is missing from that list trains on all-zero labels. The cohort/label+ # unit test hand-builds frames that already carry the columns, so it never crosses the projection.+ # Drive the real parquet -> projection -> build_examples path and assert a positive label survives.+ head = HEADS_BY_NAME[head_name]+ later = D0 + datetime.timedelta(days=head.horizon_days)+ labels_now = _labels(["a"], pr_created_count=[0], pr_merged_count=[0], refund_count=[0])+ labels_later = _labels(["a"], pr_created_count=[1], pr_merged_count=[1], refund_count=[1])+ objects: dict[str, bytes] = {}+ for date, labels in ((D0, labels_now), (later, labels_later)):+ key = date.isoformat()+ objects[partition_object_key("inbox_ranking", STATE_TABLE, key)] = _parquet(_state(["a"]))+ objects[partition_object_key("inbox_ranking", LABELS_TABLE, key)] = _parquet(labels)+ snapshots = load_snapshots(_ParquetS3(objects), "bucket", "inbox_ranking", [D0, later])+ examples = build_examples(snapshots, head)+ assert examples.set_index("report_id")["label"].to_dict() == {"a": 1}+++def test_build_examples_skips_refund_pairs_when_the_scoring_snapshot_lacks_the_column():+ # refund_count entered the labels schema after the epoch, so a partition written before it has no+ # such column. Without the guard _count reads the gap as zero, so the "not refunded yet" filter+ # passes for a report already refunded before D0, and its cumulative refund in the later snapshot+ # mints a stale future positive. The whole pair must be skipped, not scored.+ head = HEADS_BY_NAME["refund"]+ later = D0 + datetime.timedelta(days=head.horizon_days)+ snapshots = {+ D0: Snapshot(date=D0, state=_state(["a"]), labels=_labels(["a"])),+ later: Snapshot(date=later, state=_state(["a"]), labels=_labels(["a"], refund_count=[1])),+ }+ assert build_examples(snapshots, head).empty++def test_build_examples_skips_label_only_rows():head = HEADS_BY_NAME["pr_created"]later = D0 + datetime.timedelta(days=head.horizon_days)diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pyindex 018e35c3e4fe..45737354006b 100644--- a/products/signals/dags/inbox_ranking/training/dag.py+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -80,6 +80,8 @@ _LABEL_COLUMNS = ("dismissal_reason","wrong_dismissal_count","pr_created_count",+ "pr_merged_count",+ "refund_count",*PROVENANCE_LABEL_COLUMNS,)_STATE_READ_COLUMNS = (*STATE_COLUMNS, *PROVENANCE_STATE_COLUMNS, "features_observed_at")diff --git a/products/signals/dags/inbox_ranking/training/examples.py b/products/signals/dags/inbox_ranking/training/examples.pyindex 3384938a037e..cc3c8b1fc9b7 100644--- a/products/signals/dags/inbox_ranking/training/examples.py+++ b/products/signals/dags/inbox_ranking/training/examples.py@@ -124,6 +124,12 @@ def build_examples(snapshots: Mapping[datetime.date, Snapshot], head: Head) -> pif later is None:continuenow = snapshots[date]+ # A label column that is absent from a snapshot reads as zero, so a cumulative count present+ # only in the later snapshot (a column that entered the schema mid-window) would pass the+ # "not yet observed at now" guard below and mint an outcome from before `now` as a future+ # positive. Skip the pair when the head's label cannot be read from both snapshots.+ if any(column not in now.labels or column not in later.labels for column in head.label_columns):+ continueids = now.state.index.intersection(now.labels.index).intersection(later.labels.index)if len(ids) == 0:continuediff --git a/products/signals/dags/inbox_ranking/training/heads.py b/products/signals/dags/inbox_ranking/training/heads.pyindex 83124a17eea2..cf9c5d82d582 100644--- a/products/signals/dags/inbox_ranking/training/heads.py+++ b/products/signals/dags/inbox_ranking/training/heads.py@@ -6,8 +6,8 @@ cumulative label columns the dataset dag snapshots. Cohort and label are vectoriof `inbox_report_labels` columns, so the same definitions read the snapshot at scoring time (labelmust still be 0) and the snapshot `horizon_days` later (the label).-Mirrors the workspace `heads.py` (random-dev-internal, `inbox-ranking/`) for the four heads with-enough positives to ship; the other ten stay workspace-only until they are readable.+Mirrors the workspace `heads.py` (random-dev-internal, `inbox-ranking/`) for the seven heads with+enough positives to ship; the other seven stay workspace-only until they are readable."""from collections.abc import Callable@@ -53,6 +53,18 @@ def pr_created(frame: pd.DataFrame) -> pd.Series:return _count(frame, "pr_created_count") > 0+def pr_merged(frame: pd.DataFrame) -> pd.Series:+ return _count(frame, "pr_merged_count") > 0+++def discussed(frame: pd.DataFrame) -> pd.Series:+ return _count(frame, "discuss_count") > 0+++def refunded(frame: pd.DataFrame) -> pd.Series:+ return _count(frame, "refund_count") > 0++@frozenclass Head:name: str@@ -61,6 +73,10 @@ class Head:horizon_days: int# Below this many positives in the holdout the head's AUC is noise; the promotion gate ignores it.min_holdout_positives: int+ # Cumulative count columns the label reads. A scoring pair whose snapshot is missing one of these+ # cannot tell "outcome not yet observed" from "column absent", so the example builder skips it.+ # Empty when the label tolerates a missing column on its own (dismiss_wrong falls back to a reason).+ label_columns: tuple[str, ...] = ()# The label comes from the status-change stream, whose tenant provenance the dataset dag# cross-checks; rows that fail that check are unusable for this head.status_labels: bool = False@@ -83,6 +99,38 @@ HEADS: tuple[Head, ...] = (),# Which reports get a PR at all? Cohort is every report the sweep would score.Head(name="pr_created", cohort=everyone, label=pr_created, horizon_days=7, min_holdout_positives=30),+ # Of the reports that got a PR, which got it merged? Completes the open -> pr_created -> pr_merged+ # funnel; the negative is "pr_created, no merge within the horizon".+ Head(+ name="pr_merged",+ cohort=pr_created,+ label=pr_merged,+ horizon_days=14,+ min_holdout_positives=30,+ label_columns=("pr_merged_count",),+ ),+ # Of the reports users saw, which drew a discuss? Overlaps the action head, which is fine - each+ # head trains independently.+ Head(+ name="discuss",+ cohort=impressed,+ label=discussed,+ horizon_days=7,+ min_holdout_positives=30,+ label_columns=("discuss_count",),+ ),+ # Which reports led to a refund? Cohort is everyone, not pr_created: a minority of refunded reports+ # carry no pr_created event, since the refund stream is minted server-side on its own event.+ # refund_count entered the labels schema after the epoch, so pre-existing partitions lack it; the+ # label_columns guard keeps its cumulative count from leaking stale refunds as future positives.+ Head(+ name="refund",+ cohort=everyone,+ label=refunded,+ horizon_days=14,+ min_holdout_positives=20,+ label_columns=("refund_count",),+ ),)HEADS_BY_NAME: dict[str, Head] = {head.name: head for head in HEADS}