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): record first-event timestamps for every ranking label (#101546)

posthog[bot]832be18d5ae3
diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.md
index 349a37b10b89..74c2fd44bb5f 100644
--- a/products/signals/dags/inbox_ranking/AGENTS.md
+++ b/products/signals/dags/inbox_ranking/AGENTS.md
@@ -28,6 +28,7 @@ Read `README.md` first for what the dataset is and how partitions behave. This f
- `dt=` partitions are **immutable snapshots** with deterministic object keys; the only mutation ever applied is an idempotent re-run of the same partition. The exception is `inbox_signal_embeddings`, an emission log whose partition holds only that day's inserts — see the README's signal-grain section before touching it. Its re-run must stay **additive** (union with the existing object): the source drops rows it already archived, so a plain overwrite destroys history that exists nowhere else.
- Label columns are **cumulative from `LABELS_EPOCH`**; never bake a maturity window or a rolling time bound into the SQL (the saved `inbox_ranking_*` views roll 90 days — that is exactly why their SQL is inlined here with explicit bounds instead of reused).
+- Every cumulative outcome count ships with the column holding the moment its first counted event arrived, declared as a pair in `OUTCOME_FIRST_EVENT_COLUMNS` (a test fails on an unpaired count). A count alone dates an outcome only to the whole cumulative window, so a horizon label or a time-to-outcome read has nothing but a proxy without that moment. The timestamp must use the same predicate as its count, or the pair describes different events.
- `latest/` must stay **monotonic** (snapshot-date metadata stamp); backfills must never overwrite it.
- Schema changes: additive nullable columns bump `FEATURE_SCHEMA_VERSION`; breaking changes bump the `v1` path segment. The parquet schemas and the row assemblers must stay in exact key agreement — `pa.Table.from_pylist` silently drops unknown keys, and a test guards this.
- Cross-team ClickHouse reads stay on the offline workload with explicit guards; team-2 label queries keep their event + timestamp bounds aligned with the events sort key.
diff --git a/products/signals/dags/inbox_ranking/dataset/dag.py b/products/signals/dags/inbox_ranking/dataset/dag.py
index 307903cdab4f..86ea6fe88005 100644
--- a/products/signals/dags/inbox_ranking/dataset/dag.py
+++ b/products/signals/dags/inbox_ranking/dataset/dag.py
@@ -96,7 +96,7 @@ from products.signals.dags.inbox_ranking.dataset.queries import (
valid_report_uuids,
)
-FEATURE_SCHEMA_VERSION = 5
+FEATURE_SCHEMA_VERSION = 6
# Statuses a report can be authored straight into and still be in the inbox (`create_scout_report`
# and `create_custom_agent_ready_report`), which is how a report reaches the spine without a
@@ -216,9 +216,13 @@ LABEL_FIELDS: list[tuple[str, pa.DataType]] = [
("create_pr_click_count", pa.int32()),
("first_create_pr_clicked_at", _TIMESTAMP),
("discuss_count", pa.int32()),
+ ("first_discussed_at", _TIMESTAMP),
("snooze_count", pa.int32()),
+ ("first_snooze_clicked_at", _TIMESTAMP),
("feedback_positive_count", pa.int32()),
+ ("first_positive_feedback_at", _TIMESTAMP),
("feedback_negative_count", pa.int32()),
+ ("first_negative_feedback_at", _TIMESTAMP),
("first_feedback_at", _TIMESTAMP),
("latest_feedback_sentiment", pa.string()),
("first_resolved_at", _TIMESTAMP),
@@ -228,7 +232,9 @@ LABEL_FIELDS: list[tuple[str, pa.DataType]] = [
("latest_status_event", pa.string()),
("latest_status_event_at", _TIMESTAMP),
("dismissal_reason", pa.string()),
+ ("first_dismissal_reason", pa.string()),
("wrong_dismissal_count", pa.int32()),
+ ("first_wrong_dismissed_at", _TIMESTAMP),
("status_event_priority", pa.string()),
("status_event_actionability", pa.string()),
("status_event_team_id", pa.int64()),
@@ -237,6 +243,7 @@ LABEL_FIELDS: list[tuple[str, pa.DataType]] = [
("pr_merged_count", pa.int32()),
("first_pr_merged_at", _TIMESTAMP),
("pr_closed_count", pa.int32()),
+ ("first_pr_closed_at", _TIMESTAMP),
("refund_count", pa.int32()),
("first_refunded_at", _TIMESTAMP),
("refund_reason", pa.string()),
diff --git a/products/signals/dags/inbox_ranking/dataset/queries.py b/products/signals/dags/inbox_ranking/dataset/queries.py
index 6a3c8495423e..721be0d41971 100644
--- a/products/signals/dags/inbox_ranking/dataset/queries.py
+++ b/products/signals/dags/inbox_ranking/dataset/queries.py
@@ -295,7 +295,9 @@ ACTIONS_COLUMNS = (
"create_pr_click_count",
"first_create_pr_clicked_at",
"discuss_count",
+ "first_discussed_at",
"snooze_count",
+ "first_snooze_clicked_at",
"reviewer_add_count",
"first_reviewer_added_at",
"reviewer_remove_count",
@@ -329,7 +331,9 @@ SELECT
countIf(toString(properties.action_type) = 'create_pr') AS create_pr_click_count,
nullIf(minIf(timestamp, toString(properties.action_type) = 'create_pr'), fromUnixTimestamp(0)) AS first_create_pr_clicked_at,
countIf(toString(properties.action_type) = 'discuss') AS discuss_count,
+ nullIf(minIf(timestamp, toString(properties.action_type) = 'discuss'), fromUnixTimestamp(0)) AS first_discussed_at,
countIf(toString(properties.action_type) = 'snooze') AS snooze_count,
+ nullIf(minIf(timestamp, toString(properties.action_type) = 'snooze'), fromUnixTimestamp(0)) AS first_snooze_clicked_at,
countIf(toString(properties.action_type) = 'add_suggested_reviewer') AS reviewer_add_count,
nullIf(minIf(timestamp, toString(properties.action_type) = 'add_suggested_reviewer'), fromUnixTimestamp(0)) AS first_reviewer_added_at,
countIf(toString(properties.action_type) = 'remove_suggested_reviewer') AS reviewer_remove_count,
@@ -353,7 +357,9 @@ STATUS_COLUMNS = (
"latest_status_event",
"latest_status_event_at",
"dismissal_reason",
+ "first_dismissal_reason",
"wrong_dismissal_count",
+ "first_wrong_dismissed_at",
"status_event_priority",
"status_event_actionability",
"status_event_team_id",
@@ -386,6 +392,26 @@ SELECT
-- below: a reason-less genuine transition must not let an older reason from another team
-- through.
argMaxIf(bucket_dismissal_reason, last_timestamp, event_team_id = latest_event_team_id) AS dismissal_reason,
+ -- The reason on the *earliest* reasoned dismissal, under the same tenant restriction. The
+ -- latest-wins reason above answers "how is this report classified now"; a horizon or
+ -- time-to-outcome read needs the reason that came with the dismissal it is dating.
+ -- The empty sentinel rides all the way to the end so a reason-less earliest dismissal reports
+ -- NULL rather than handing over the next dismissal's reason: a dismissal carries no reason
+ -- whenever no artefact accompanies the transition, and this column has to describe the earliest
+ -- dismissal itself.
+ --
+ -- Caveat until posthog#101565 lands: this reason is restricted to the latest transition's
+ -- tenant while first_dismissed_server_at above is not, so an earlier dismissal naming another
+ -- team can date that column while this one reads a later genuine dismissal. Treat the two as
+ -- separate reads, not as one event.
+ nullIf(
+ argMinIf(
+ bucket_first_dismissal_reason,
+ first_timestamp,
+ outcome = 'dismissed' AND event_team_id = latest_event_team_id
+ ),
+ ''
+ ) AS first_dismissal_reason,
-- Cumulative, unlike dismissal_reason above: a restore or a later dismissal with another reason
-- overwrites the latest-wins reason, and a label that can revert to 0 breaks the training
-- builder's assumption that labels only grow. Counted per bucket (a bucket that saw any wrong
@@ -397,6 +423,15 @@ SELECT
countIf(
outcome = 'dismissed' AND bucket_wrong_dismissal = 1 AND event_team_id = latest_event_team_id
) AS wrong_dismissal_count,
+ -- Restricted to the count's own tenant, so a time-to-outcome read never takes a moment from a
+ -- bucket the count itself excluded. Reads the bucket's first *wrong* dismissal, not its
+ -- first_timestamp: a bucket that collapses a plain dismissal, a restore and a wrong dismissal
+ -- starts with the plain one. Buckets holding no wrong reason carry NULL and min skips them.
+ -- Stable as the window grows: a min over a window that only extends forward cannot move.
+ minIf(
+ bucket_first_wrong_dismissed_at,
+ outcome = 'dismissed' AND event_team_id = latest_event_team_id
+ ) AS first_wrong_dismissed_at,
-- These two must stay paired with latest_status_event, so coalesce/nullIf keeps argMax from
-- skipping a null: a judgment artefact can be deleted, and then the latest transition
-- genuinely carries none. Plain argMax would reach back to an older transition and present
@@ -439,9 +474,20 @@ FROM (
-- Named apart from the outer alias: ClickHouse resolves a bare `dismissal_reason` in the outer
-- aggregates to the outer alias, which is itself an aggregate.
nullIf(argMax(toString(properties.dismissal_reason), events.timestamp), '') AS bucket_dismissal_reason,
+ -- The reason on the bucket's earliest event, the parallel of first_timestamp: a bucket can
+ -- collapse a dismiss, a restore and a second dismissal, and then its latest reason is not
+ -- the one the first dismissal carried. A reason-less event is kept as the empty string,
+ -- because argMin skips a null and would hand over a later event's reason, so the reason
+ -- always describes the event first_timestamp dates.
+ argMin(
+ coalesce(toString(properties.dismissal_reason), ''), events.timestamp
+ ) AS bucket_first_dismissal_reason,
max(toString(properties.dismissal_reason) IN ("""
+ _WRONG_DISMISSAL_REASONS_SQL
+ """)) AS bucket_wrong_dismissal,
+ nullIf(minIf(events.timestamp, toString(properties.dismissal_reason) IN ("""
+ + _WRONG_DISMISSAL_REASONS_SQL
+ + """)), fromUnixTimestamp(0)) AS bucket_first_wrong_dismissed_at,
nullIf(argMax(toString(properties.priority), events.timestamp), '') AS event_priority,
nullIf(argMax(toString(properties.actionability), events.timestamp), '') AS event_actionability,
nullIf(toString(properties.team_id), '') AS event_team_id
@@ -470,6 +516,7 @@ PR_COLUMNS = (
"pr_merged_count",
"first_pr_merged_at",
"pr_closed_count",
+ "first_pr_closed_at",
)
PR_EVENTS_SQL = """
SELECT
@@ -478,7 +525,8 @@ SELECT
nullIf(minIf(timestamp, event = 'pr_created'), fromUnixTimestamp(0)) AS first_pr_created_at,
countIf(event = 'pr_merged') AS pr_merged_count,
nullIf(minIf(timestamp, event = 'pr_merged'), fromUnixTimestamp(0)) AS first_pr_merged_at,
- countIf(event = 'pr_closed') AS pr_closed_count
+ countIf(event = 'pr_closed') AS pr_closed_count,
+ nullIf(minIf(timestamp, event = 'pr_closed'), fromUnixTimestamp(0)) AS first_pr_closed_at
FROM events
WHERE event IN ('pr_created', 'pr_merged', 'pr_closed')
AND timestamp >= toDateTime({labels_epoch}) AND timestamp < toDateTime({snapshot_end})
@@ -489,7 +537,9 @@ GROUP BY report_id
FEEDBACK_COLUMNS = (
"feedback_positive_count",
+ "first_positive_feedback_at",
"feedback_negative_count",
+ "first_negative_feedback_at",
"first_feedback_at",
"latest_feedback_sentiment",
)
@@ -500,7 +550,9 @@ FEEDBACK_SQL = f"""
SELECT
toString(properties.report_id) AS report_id,
countIf(toString(properties.sentiment) = 'positive') AS feedback_positive_count,
+ nullIf(minIf(timestamp, toString(properties.sentiment) = 'positive'), fromUnixTimestamp(0)) AS first_positive_feedback_at,
countIf(toString(properties.sentiment) = 'negative') AS feedback_negative_count,
+ nullIf(minIf(timestamp, toString(properties.sentiment) = 'negative'), fromUnixTimestamp(0)) AS first_negative_feedback_at,
min(timestamp) AS first_feedback_at,
argMax(toString(properties.sentiment), timestamp) AS latest_feedback_sentiment
FROM events
@@ -566,9 +618,13 @@ LABEL_DEFAULTS: dict[str, Any] = {
"create_pr_click_count": 0,
"first_create_pr_clicked_at": None,
"discuss_count": 0,
+ "first_discussed_at": None,
"snooze_count": 0,
+ "first_snooze_clicked_at": None,
"feedback_positive_count": 0,
+ "first_positive_feedback_at": None,
"feedback_negative_count": 0,
+ "first_negative_feedback_at": None,
"first_feedback_at": None,
"latest_feedback_sentiment": None,
"first_resolved_at": None,
@@ -578,7 +634,9 @@ LABEL_DEFAULTS: dict[str, Any] = {
"latest_status_event": None,
"latest_status_event_at": None,
"dismissal_reason": None,
+ "first_dismissal_reason": None,
"wrong_dismissal_count": 0,
+ "first_wrong_dismissed_at": None,
"status_event_priority": None,
"status_event_actionability": None,
"status_event_team_id": None,
@@ -587,6 +645,7 @@ LABEL_DEFAULTS: dict[str, Any] = {
"pr_merged_count": 0,
"first_pr_merged_at": None,
"pr_closed_count": 0,
+ "first_pr_closed_at": None,
"refund_count": 0,
"first_refunded_at": None,
"refund_reason": None,
@@ -602,6 +661,30 @@ LABEL_DEFAULTS: dict[str, Any] = {
_TIMESTAMP_LABEL_COLUMNS = frozenset(name for name in LABEL_DEFAULTS if name.endswith("_at"))
+# Every cumulative outcome count, paired with the column holding the moment its first counted event
+# arrived. A horizon read ("did the outcome happen within N days of this moment?") and a
+# time-to-outcome read both need that moment: the count dates the outcome only to the partition's
+# whole cumulative window. Each timestamp uses the same predicate as its count, and a min over a
+# window that only extends forward never moves, so the pair holds across partitions.
+OUTCOME_FIRST_EVENT_COLUMNS: dict[str, str] = {
+ "impression_unit_count": "first_impressed_at",
+ "open_count": "first_opened_at",
+ "ui_dismiss_count": "first_ui_dismissed_at",
+ "create_pr_click_count": "first_create_pr_clicked_at",
+ "discuss_count": "first_discussed_at",
+ "snooze_count": "first_snooze_clicked_at",
+ "reviewer_add_count": "first_reviewer_added_at",
+ "reviewer_remove_count": "first_reviewer_removed_at",
+ "resolve_click_count": "first_resolve_clicked_at",
+ "feedback_positive_count": "first_positive_feedback_at",
+ "feedback_negative_count": "first_negative_feedback_at",
+ "wrong_dismissal_count": "first_wrong_dismissed_at",
+ "pr_created_count": "first_pr_created_at",
+ "pr_merged_count": "first_pr_merged_at",
+ "pr_closed_count": "first_pr_closed_at",
+ "refund_count": "first_refunded_at",
+}
+
def canonical_stream_rows(rows: list[tuple[Any, ...]]) -> dict[str, tuple[Any, ...]]:
"""One row per canonical report id, dropping ids that cannot be report UUIDs.
diff --git a/products/signals/dags/inbox_ranking/tests/test_dataset.py b/products/signals/dags/inbox_ranking/tests/test_dataset.py
index 9687f57ec555..6daf625fa40b 100644
--- a/products/signals/dags/inbox_ranking/tests/test_dataset.py
+++ b/products/signals/dags/inbox_ranking/tests/test_dataset.py
@@ -11,6 +11,7 @@ from products.event_definitions.backend.models.property_definition import Proper
from products.signals.backend.models import SignalReport
from products.signals.dags.inbox_ranking import common
from products.signals.dags.inbox_ranking.dataset.dag import (
+ LABELS_SCHEMA,
MODEL_DATA_SCHEMA,
assemble_model_rows,
label_provenance_ok,
@@ -21,6 +22,7 @@ from products.signals.dags.inbox_ranking.dataset.queries import (
LABEL_DEFAULTS,
LABEL_STREAMS,
LABELED_REPORT_IDS_SQL,
+ OUTCOME_FIRST_EVENT_COLUMNS,
STATUS_COLUMNS,
STATUS_SQL,
hogql_rows,
@@ -163,13 +165,14 @@ def test_merge_label_streams_fills_defaults_and_maps_columns():
"impressions": [(UUID_A, T1.replace(tzinfo=None), 5, 2, 3, 1, ["error_tracking"])],
"opens": [(UUID_A.upper(), T2, 4, 2), (UUID_B, T2, 1, 1)],
"actions": [
- ("bogus-id", 1, T1, 1, T1, 1, 1, 1, T1, 1, T1, 1, T1),
+ ("bogus-id", 1, T1, 1, T1, 1, T1, 1, T1, 1, T1, 1, T1, 1, T1),
# Distinct values per column, so a shifted or swapped ACTIONS_SQL/ACTIONS_COLUMNS
# position lands a wrong value in some asserted field below.
- (UUID_B, 5, T1, 0, None, 0, 0, 2, T1, 3, T2, 4, T1),
+ (UUID_B, 5, T1, 0, None, 6, T2, 7, T1, 2, T1, 3, T2, 4, T1),
],
+ "feedback": [(UUID_B, 2, T1, 1, T2, T1, "negative")],
"status_changes": [],
- "pr_events": [],
+ "pr_events": [(UUID_B, 1, T1, 1, T2, 1, T2)],
}
rows = {row["report_id"]: row for row in merge_label_streams(stream_rows, SNAPSHOT_DATE)}
@@ -183,11 +186,21 @@ def test_merge_label_streams_fills_defaults_and_maps_columns():
assert r1["source_products"] == ["error_tracking"]
assert r1["first_impressed_at"] == T1
assert r1["open_count"] == 4
+ assert r1["pr_created_count"] == 0
r2 = rows[UUID_B]
assert r2["impression_unit_count"] == 0
assert r2["first_impressed_at"] is None
- assert r2["pr_created_count"] == 0
assert r2["ui_dismiss_count"] == 5
+ assert r2["discuss_count"] == 6
+ assert r2["first_discussed_at"] == T2
+ assert r2["snooze_count"] == 7
+ assert r2["first_snooze_clicked_at"] == T1
+ assert r2["feedback_positive_count"] == 2
+ assert r2["first_positive_feedback_at"] == T1
+ assert r2["feedback_negative_count"] == 1
+ assert r2["first_negative_feedback_at"] == T2
+ assert r2["pr_closed_count"] == 1
+ assert r2["first_pr_closed_at"] == T2
assert r2["reviewer_add_count"] == 2
assert r2["first_reviewer_added_at"] == T1
assert r2["reviewer_remove_count"] == 3
@@ -222,6 +235,22 @@ def test_label_stream_columns_all_exist_in_defaults():
assert set(columns) <= set(LABEL_DEFAULTS)
+def test_every_outcome_count_is_paired_with_a_first_event_timestamp():
+ # A horizon label ("did the outcome happen within N days of this moment?") and a time-to-outcome
+ # read both need the moment the outcome first arrived. The cumulative count only says it
+ # happened somewhere in the partition's whole window, so a new count column has to arrive with
+ # its paired timestamp or be named as a uniq over an outcome that already has one.
+ count_columns = {name for name in LABEL_DEFAULTS if name.endswith("_count")}
+ # The user counts are uniq aggregates over an outcome the map already pairs, not outcomes of
+ # their own.
+ assert count_columns == set(OUTCOME_FIRST_EVENT_COLUMNS) | {"impressed_user_count", "opened_user_count"}
+
+ for count_column, first_event_column in OUTCOME_FIRST_EVENT_COLUMNS.items():
+ assert first_event_column in LABEL_DEFAULTS, count_column
+ assert LABEL_DEFAULTS[first_event_column] is None, count_column
+ assert LABELS_SCHEMA.field(first_event_column).type == pa.timestamp("us", tz="UTC")
+
+
@pytest.mark.parametrize(
"pg_status,pg_updated_at,latest_event,event_team_id,expected",
[
@@ -417,8 +446,40 @@ class TestStatusStream(ClickhouseTestMixin, BaseTest):
row = self._status_row()
assert row["dismissal_reason"] == "already_fixed"
+ assert row["first_dismissal_reason"] == "analysis_wrong"
+ assert row["wrong_dismissal_count"] == 1
+ assert row["first_dismissed_server_at"] == T1
+ assert row["first_wrong_dismissed_at"] == T1
+
+ @parameterized.expand([(datetime.timedelta(hours=1),), (datetime.timedelta(minutes=1),)])
+ def test_a_reasonless_first_dismissal_carries_no_reason_forward(self, gap):
+ # A dismissal with no reason is normal: the PR-closed path suppresses a report with no
+ # artefact. The earliest dismissal must not borrow the reason of a later one, or a consumer
+ # pairs that reason with first_dismissed_server_at and misreads why the report was dismissed.
+ self._transition(T1, "ready", "suppressed", None)
+ self._transition(T1 + gap, "suppressed", "ready")
+ self._transition(T1 + 2 * gap, "ready", "suppressed", "analysis_wrong")
+
+ row = self._status_row()
+ assert row["first_dismissed_server_at"] == T1
+ assert row["first_dismissal_reason"] is None
+ assert row["dismissal_reason"] == "analysis_wrong"
+ assert row["first_wrong_dismissed_at"] == T1 + 2 * gap
+
+ @parameterized.expand([(datetime.timedelta(hours=1),), (datetime.timedelta(minutes=1),)])
+ def test_first_wrong_dismissed_at_skips_an_earlier_plain_dismissal(self, gap):
+ # dismissed as already_fixed, restored, then dismissed as analysis_wrong. The bucket's own
+ # first timestamp is the plain dismissal, so a time-to-outcome read would date the wrong
+ # dismissal to a moment it did not happen. The one-minute variant puts all three in one
+ # ten-minute dedupe bucket.
+ self._transition(T1, "ready", "suppressed", "already_fixed")
+ self._transition(T1 + gap, "suppressed", "ready")
+ self._transition(T1 + 2 * gap, "ready", "suppressed", "analysis_wrong")
+
+ row = self._status_row()
assert row["wrong_dismissal_count"] == 1
assert row["first_dismissed_server_at"] == T1
+ assert row["first_wrong_dismissed_at"] == T1 + 2 * gap
@parameterized.expand(
[
@@ -437,7 +498,10 @@ class TestStatusStream(ClickhouseTestMixin, BaseTest):
row = self._status_row()
assert row["status_event_team_id"] == self.team.id
assert row["dismissal_reason"] == reason
+ # The forged reason is also the earliest one, so it must not reach first_dismissal_reason.
+ assert row["first_dismissal_reason"] == reason
assert row["wrong_dismissal_count"] == 0
+ assert row["first_wrong_dismissed_at"] is None
def test_tied_tenants_count_and_report_the_same_team(self):
# Two tenants' buckets with the same last timestamp: whichever wins the tie, the count and