: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): count report intent from every surface in the action head (#110865)
posthog[bot]c3bd9605588b
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex d002886f103c..97fc0ec19667 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -50,9 +50,10 @@ The first four are report grain and land in one table. `inbox_signal_embeddings`- Label columns are **cumulative**: later partitions strictly dominate earlier ones, so training reads features from `dt=D` and labels from any later partition, choosing the label-maturity window at read time. Late labels are never backfilled into old partitions.- `latest/` advances **monotonically**: each write stamps a `snapshot-date` in S3 object metadata, and a partition rewrites `latest/` only when it is at or ahead of what `latest/` holds. Delayed retries of the newest day repair it; backfills of older days never clobber it.- Rows for reports **outside this dag's region** are label-only: no Postgres state, no embedding, and `report_team_id` null (a US team id and an EU team id of the same number are different teams, so the label stream's id can't be merged in). `status_event_team_id` carries the team the transition itself reported, which is the tenant attribution those rows do have.-- **Backfills are not fully point-in-time**: labels are exact for any past day, embeddings are exact within the source table's 3-month TTL, but report state is read from Postgres as of the run (`features_observed_at` flags this per row). The title snapshot has the same guarantee and the same limit as the report snapshot, through the same `inserted_at < snapshot_end` bound.+- **Backfills are not fully point-in-time**: labels are exact for any past day apart from the server-side action counts (see below), embeddings are exact within the source table's 3-month TTL, but report state is read from Postgres as of the run (`features_observed_at` flags this per row). The title snapshot has the same guarantee and the same limit as the report snapshot, through the same `inserted_at < snapshot_end` bound.- **The `inserted_at` bound does not cover a re-embedded rendering.** The source replaces on a key that includes the rendering and the document id, so a partition rebuilt _later_ for an earlier day finds only the newer row, whose `inserted_at` is past the cutoff, and the report reads as having no vector that day. That loses coverage and never leaks a future vector. A forward run carries the same loss over a shorter window: the schedule fires at 02:30 UTC for the previous day, so the query starts at least 2.5 hours after the cutoff, and the title snapshot runs after the join, which makes its window the wider of the two. A partition before `title_v1` emission shipped holds zero rows, which is written as an empty Parquet with the full schema rather than skipped.- Report-state mutability reaches **inclusion**, not just feature values: `promoted_at` is cleared on suppression and snooze, so a report promoted before the cutoff and suppressed after it leaves the spine unless a label event referenced it before the cutoff. Forward runs see this only for the 2.5 hours between the cutoff and the schedule; backfills see the full accumulated effect. Deriving the spine from immutable promotion history (`signal_report_status_changed` carries `promoted_at`) is the v2 fix.+- **The server-side action counts read current artefact rows**, bounded by `created_at < snapshot_end`. A report merge moves the source's notes and linked PRs to the survivor and keeps their `created_at`, and a note can be deleted. A partition rebuilt after either change gives that action to the survivor, or loses it. Claims and Slack discussions stay on the source report. Forward runs see this only for the 2.5 hours between the cutoff and the schedule.### Signal-grain partitions@@ -82,7 +83,7 @@ s3://<bucket>/<prefix>/- **A model is a `(model_name, model_version, model_role)`.** `model_name` is the family: which features and which learner, `tabular_xgb` for the per-head XGBoost trained here. `model_version` is the partition day it was fit on, and `model_role` is `candidate` or `champion`. Each family owns a prefix under the models path and its own `champion.json`, so two families trained on the same day cannot collide, and promotion stays inside a family. A richer family is a second candidate graded on the same unseen rows, not a competitor for the tabular family's pointer.- **A feature set is one feature universe.** `products/signals/backend/ranking/features.py` holds a `FeatureSet` per universe: its name, its schema version, its ordered feature names, the report-state columns it reads, `build_matrix`, and how many rows it wants per report and per head. `tabular`, `report_embeddings` and `title_embeddings` are the three today. A candidate records the set it was fit on in its `metadata.json`, so the grader checks a model against its own set rather than one global contract, the examples asset writes one Parquet per set, and the unseen scorer builds one matrix per set and shares it across the families that read it. Adding a set means an entry in `FEATURE_SETS`; a model naming a set this build cannot produce is logged and left unscored.-- **Examples are one row per report at its birth, by default.** For partition `dt=D` the examples asset reads the report-state and labels snapshots `dt=D-lookback..D` and emits one row per report, on the snapshot of the day it was created, labeled from the snapshot `horizon_days` later (3 for open, 7 for action / pr_created / discuss / thumbs_up, 14 for dismiss_wrong / pr_merged / refund / reviewer_fix). Features are built by the feature set from 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. Birth is the moment serving scores a report, and the label that comes out is a per-report probability, which is what the inbox ordering needs. A report born before the window, or one whose birth-day snapshot is missing from it, is no example; `reports_missing_birth_snapshot` on the asset counts the second case, which is a gap in the partitions.+- **Examples are one row per report at its birth, by default.** For partition `dt=D` the examples asset reads the report-state and labels snapshots `dt=D-lookback..D` and emits one row per report, on the snapshot of the day it was created, labeled from the snapshot `horizon_days` later (3 for open, 7 for action / pr_created / discuss / thumbs_up, 14 for dismiss_wrong / pr_merged / refund / reviewer_fix). Features are built by the feature set from 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 heads that read the status stream (`dismiss_wrong` and `action`), rows whose status telemetry fails the dataset's `label_provenance_ok` check. Birth is the moment serving scores a report, and the label that comes out is a per-report probability, which is what the inbox ordering needs. A report born before the window, or one whose birth-day snapshot is missing from it, is no example; `reports_missing_birth_snapshot` on the asset counts the second case, which is a gap in the partitions.- **An outcome already visible on the birth day is a future positive.** A report born on day D has no scoring moment before D, so an outcome visible at D belongs to the moment being built rather than to an earlier one; the labels of D therefore read as their defaults for a report born on D. Most outcomes land on the birth day, so this is where the positives are: censoring on them costs the `pr_created` head most of its training signal. `<set>_<head>_birth_day_positives` on the examples asset, and `birth_day_positives` on the `inbox_ranking_examples_built` event, say how many positives the rule keeps. These rows carry a hindsight the other rows do not: the state snapshot reads `signal_count`, `total_weight`, `run_count` and the text sizes live from Postgres a few hours after day D ends, so a birth-day outcome happened before its own feature read. Both the holdout AUC and the newborn unseen grade therefore read optimistically on these rows, until the scoring sweep's timestamped score log replaces the daily snapshot as this table's source.- **Every head asks whether the outcome happened within N days of the scoring moment.** `pr_merged` includes every report, so the label covers the whole report-to-merge path without requiring a PR at birth or at the horizon.- **A set may ask for another grain**, and cap the rows one head keeps (`max_examples_per_head`, whole report-creation days, newest first). The scoring-moment grain is one row per (report, snapshot) whose head label is still 0 on that snapshot: the serving situation replayed over history, but its label is a hazard conditional on the report still being live, and one long-lived report contributes dozens of near-duplicate rows. The report grain is the first snapshot of the window where the report is a usable moment, which is later than birth only when a side input landed late. Both stay selectable for re-scoring families; nothing ships on them today. The row budget shortens the history a head is fit on and keeps each kept day whole, so the scores stay calibrated to the population of that window. The lookback is the tabular set's whatever the grain, so positives accrue over the whole window until the budget binds.@@ -116,7 +117,7 @@ The reader is `score_reports` in `products/signals/backend/ranking/scorer.py`. I| Head | Cohort at the horizon | Horizon (days) || --------------- | --------------------- | -------------- || `open` | Every report | 3 |-| `action` | Impressed reports | 7 |+| `action` | Every report | 7 || `dismiss_wrong` | Impressed reports | 14 || `pr_created` | Every report | 7 || `pr_merged` | Every report | 14 |@@ -125,6 +126,11 @@ The reader is `score_reports` in `products/signals/backend/ranking/scorer.py`. I| `thumbs_up` | Opened reports | 7 || `reviewer_fix` | Impressed reports | 14 |+`action` counts intent from every surface, not only the cloud inbox list.+A report is a positive when someone clicked an intent action in the inbox UI (create PR, implement, copy the prompt, discuss, open or view a PR, edit the reviewers, restore), or when a person or an external agent claimed it, linked a PR, left a note, discussed it in Slack, or resolved it with a reason.+Self-driving's own `task` and `system` writes do not count: they are internal operational work.+A resolve without a reason is the automatic resolve after a tracked PR merges, so it does not count either.+`thumbs_up` (a positive rating on the report body) and `reviewer_fix` (a suggested reviewer added or removed) are the explicit human-feedback pair.Both are rare — about 1% of opened reports and 1.5% of impressed reports — so neither clears its holdout bar on a single day.They are carried for the pooled newborn grade and as scorer inputs, not for a holdout AUC, and the promotion gate keeps ignoring an unreadable head.diff --git a/products/signals/dags/inbox_ranking/common.py b/products/signals/dags/inbox_ranking/common.pyindex 137293e85bc2..fa55b6a10227 100644--- a/products/signals/dags/inbox_ranking/common.py+++ b/products/signals/dags/inbox_ranking/common.py@@ -19,6 +19,8 @@ from posthog import settingsfrom posthog.dags.common import JobOwnersfrom posthog.storage.object_storage import ObjectStorage+from products.signals.backend.models import SignalActorKind+DATASET_VERSION = "v1"S3_BUCKET_ENV = "INBOX_RANKING_DATASET_S3_BUCKET"@@ -37,6 +39,13 @@ LABELS_EPOCH = "2026-04-01T00:00:00+00:00"# labels SQL (cumulative count) and the head definition.WRONG_DISMISSAL_REASONS = ("analysis_wrong", "report_unclear", "wontfix_intentional")+# Artefact actors whose writes count as a person acting on a report. `agent` is an external MCP+# client that authenticates as a real user, so a person drove it. `task` is a self-driving sandbox+# (scouts, implementation runs) and `system` is the pipeline: their claims, notes and PRs are+# internal operational writes, far more frequent than the human ones, and say nothing about intent.+# A null actor is a legacy or system write, so it is also excluded.+HUMAN_ACTOR_KINDS = (SignalActorKind.USER, SignalActorKind.AGENT)+partition_def = dagster.DailyPartitionsDefinition(start_date="2026-04-01")owner_tags: dict[str, str] = {"owner": JobOwners.TEAM_SELF_DRIVING.value}diff --git a/products/signals/dags/inbox_ranking/dataset/dag.py b/products/signals/dags/inbox_ranking/dataset/dag.pyindex 75e88cab7055..1332dc6d5c75 100644--- a/products/signals/dags/inbox_ranking/dataset/dag.py+++ b/products/signals/dags/inbox_ranking/dataset/dag.py@@ -21,7 +21,11 @@ from any later partition, choosing the label-maturity window at read time. Late-are never backfilled into old partitions.Point-in-time caveats, per source:-- labels are fully point-in-time for any past day (explicit event-time bound);+- labels are fully point-in-time for any past day (explicit event-time bound), except the+ server-side action counts. Those read current artefact rows bounded by created_at. A report+ merge moves the source's notes and linked PRs to the survivor and keeps their created_at, and a+ note can be deleted. A partition rebuilt after either change gives the action to the survivor+ or loses it;- embeddings are point-in-time within the underlying table's 3-month TTL (inserted_at bound), andthe title snapshot carries the same guarantee and the same limit. The bound does not cover are-embedded rendering: the source replaces on a key that includes the rendering and the document@@ -47,6 +51,8 @@ import datetimefrom collections.abc import Iteratorfrom typing import Any, cast+from django.db.models import Count, Min+import dagsterimport pyarrow as pa@@ -55,7 +61,7 @@ from posthog.clickhouse.client import sync_executefrom posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tag_queriesfrom posthog.dags.common import dagster_tags-from products.signals.backend.models import SignalReport, SignalReportArtefact+from products.signals.backend.models import SignalReport, SignalReportAction, SignalReportArtefactfrom products.signals.backend.ranking.inventory import spine_report_filterfrom products.signals.backend.report_embeddings import (EMBEDDING_DOCUMENT_TYPE,@@ -70,6 +76,7 @@ from products.signals.backend.signal_metadata import ()from products.signals.dags.inbox_ranking.common import (DATASET_VERSION,+ HUMAN_ACTOR_KINDS,S3_BUCKET_ENV,dataset_bucket,dataset_unconfigured,@@ -98,6 +105,8 @@ from products.signals.dags.inbox_ranking.dataset.queries import (LABELS_TEAM_ID,REPORT_EMBEDDINGS_QUERY_SETTINGS,REPORT_EMBEDDINGS_SQL,+ SERVER_ACTIONS_COLUMNS,+ SERVER_ACTIONS_STREAM,SIGNAL_EMBEDDINGS_QUERY_SETTINGS,SIGNAL_EMBEDDINGS_SQL,etl_workload,@@ -107,7 +116,7 @@ from products.signals.dags.inbox_ranking.dataset.queries import (valid_report_uuids,)-FEATURE_SCHEMA_VERSION = 6+FEATURE_SCHEMA_VERSION = 7STATE_TABLE = "inbox_report_state"EMBEDDINGS_TABLE = "inbox_report_embeddings"@@ -257,6 +266,26 @@ LABEL_FIELDS: list[tuple[str, pa.DataType]] = [("first_reviewer_removed_at", _TIMESTAMP),("resolve_click_count", pa.int32()),("first_resolve_clicked_at", _TIMESTAMP),+ ("copy_prompt_count", pa.int32()),+ ("first_prompt_copied_at", _TIMESTAMP),+ ("implement_click_count", pa.int32()),+ ("first_implement_clicked_at", _TIMESTAMP),+ ("open_pr_click_count", pa.int32()),+ ("first_open_pr_clicked_at", _TIMESTAMP),+ ("view_diff_count", pa.int32()),+ ("first_diff_viewed_at", _TIMESTAMP),+ ("restore_count", pa.int32()),+ ("first_restored_at", _TIMESTAMP),+ ("reasoned_resolution_count", pa.int32()),+ ("first_reasoned_resolved_at", _TIMESTAMP),+ ("claim_count", pa.int32()),+ ("first_claimed_at", _TIMESTAMP),+ ("linked_pr_count", pa.int32()),+ ("first_pr_linked_at", _TIMESTAMP),+ ("note_count", pa.int32()),+ ("first_noted_at", _TIMESTAMP),+ ("slack_discussion_count", pa.int32()),+ ("first_slack_discussed_at", _TIMESTAMP),]_LABELS_FIELDS: list[tuple[str, pa.DataType]] = [@@ -384,6 +413,58 @@ def _artefact_judgments(report_ids: list[str], snapshot_end: datetime.datetime)return judgments+# The artefact types that count as a server-side action, with the label columns each one fills.+_ACTION_ARTEFACT_COLUMNS: dict[str, tuple[str, str]] = {+ SignalReportArtefact.ArtefactType.WORK_CLAIM: ("claim_count", "first_claimed_at"),+ SignalReportArtefact.ArtefactType.PULL_REQUEST: ("linked_pr_count", "first_pr_linked_at"),+ SignalReportArtefact.ArtefactType.NOTE: ("note_count", "first_noted_at"),+}+++def server_action_rows(report_ids: list[str], snapshot_end: datetime.datetime) -> list[tuple[Any, ...]]:+ """One `(report_id, *SERVER_ACTIONS_COLUMNS)` row per report with a server-side action before+ the cutoff. Rows are counted, not the action row's own `count`, because that counter keeps+ moving after the cutoff."""+ entries: dict[str, dict[str, Any]] = {}++ def entry(report_id: Any) -> dict[str, Any]:+ return entries.setdefault(str(report_id), {column: LABEL_DEFAULTS[column] for column in SERVER_ACTIONS_COLUMNS})++ for chunk in _chunked(report_ids):+ artefacts = (+ SignalReportArtefact.objects.filter(+ report_id__in=chunk,+ type__in=list(_ACTION_ARTEFACT_COLUMNS),+ actor_kind__in=HUMAN_ACTOR_KINDS,+ created_at__lt=snapshot_end,+ )+ .values("report_id", "type")+ .annotate(row_count=Count("id"), earliest_at=Min("created_at"))+ )+ for row in artefacts.iterator(chunk_size=2000):+ count_column, first_column = _ACTION_ARTEFACT_COLUMNS[row["type"]]+ values = entry(row["report_id"])+ values[count_column] = row["row_count"]+ values[first_column] = row["earliest_at"]+ # One row per (report, user), so the count is the number of people who discussed it.+ discussions = (+ SignalReportAction.all_teams.filter(+ report_id__in=chunk,+ type=SignalReportAction.ActionType.SLACK_DISCUSSION,+ first_at__lt=snapshot_end,+ )+ .values("report_id")+ .annotate(row_count=Count("id"), earliest_at=Min("first_at"))+ )+ for row in discussions.iterator(chunk_size=2000):+ values = entry(row["report_id"])+ values["slack_discussion_count"] = row["row_count"]+ values["first_slack_discussed_at"] = row["earliest_at"]+ return [+ (report_id, *(values[column] for column in SERVER_ACTIONS_COLUMNS)) for report_id, values in entries.items()+ ]++@dagster.asset(name=STATE_TABLE, **COMMON_ASSET_KWARGS)def inbox_report_state(context: dagster.AssetExecutionContext) -> None:if skip_unconfigured(context):@@ -770,6 +851,15 @@ def inbox_report_labels(context: dagster.AssetExecutionContext) -> None:)context.log.info(f"{stream_name}: {len(stream_rows[stream_name])} reports")+ # The server-side actions are read for every report in the inbox before the cutoff, plus every+ # report an event stream named, so an action from a surface that emits no event still lands.+ action_report_ids = {+ str(report_id)+ for report_id in SignalReport.objects.filter(spine_report_filter(snapshot_end)).values_list("id", flat=True)+ } | valid_report_uuids({row[0] for rows in stream_rows.values() for row in rows})+ stream_rows[SERVER_ACTIONS_STREAM] = server_action_rows(sorted(action_report_ids), snapshot_end)+ context.log.info(f"{SERVER_ACTIONS_STREAM}: {len(stream_rows[SERVER_ACTIONS_STREAM])} reports")+rows = merge_label_streams(stream_rows, datetime.date.fromisoformat(partition_key))bucket = dataset_bucket()key = partition_object_key(settings.INBOX_RANKING_DATASET_S3_PREFIX, LABELS_TABLE, partition_key)@@ -778,8 +868,8 @@ def inbox_report_labels(context: dagster.AssetExecutionContext) -> None:{"rows": dagster.MetadataValue.int(len(rows)),**{- f"{stream_name}_reports": dagster.MetadataValue.int(len(stream_rows[stream_name]))- for stream_name, _, _ in LABEL_STREAMS+ f"{stream_name}_reports": dagster.MetadataValue.int(len(stream))+ for stream_name, stream in stream_rows.items()},"s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),}diff --git a/products/signals/dags/inbox_ranking/dataset/queries.py b/products/signals/dags/inbox_ranking/dataset/queries.pyindex 2dec3276fb8b..d45087f0075c 100644--- a/products/signals/dags/inbox_ranking/dataset/queries.py+++ b/products/signals/dags/inbox_ranking/dataset/queries.py@@ -328,6 +328,16 @@ ACTIONS_COLUMNS = ("first_reviewer_removed_at","resolve_click_count","first_resolve_clicked_at",+ "copy_prompt_count",+ "first_prompt_copied_at",+ "implement_click_count",+ "first_implement_clicked_at",+ "open_pr_click_count",+ "first_open_pr_clicked_at",+ "view_diff_count",+ "first_diff_viewed_at",+ "restore_count",+ "first_restored_at",)# Bulk action rows carry no report_id and are excluded; bulk dismissals are recovered from the# server-side status stream instead. minIf misses fill non-nullable datetimes with epoch 0, hence@@ -340,8 +350,10 @@ ACTIONS_COLUMNS = (## `resolve` marks a report done without an inbox PR, so it is a distinct positive outcome the# `create_pr` click does not cover. The `*_click*` names keep it apart from the status stream's-# `first_resolved_at`, which conflates every path a report reaches `resolved`. `restore`-# (un-dismissing a report) shares this aggregation shape and is a follow-up.+# `first_resolved_at`, which conflates every path a report reaches `resolved`.+#+# `copy_implementation_prompt`, `implement`, `open_pr`, `view_diff` and `restore` (un-dismissing a+# report) are the other intent actions the `action` head counts.## Blind spot: a bulk-bar resolve fires one report_id-less event and drops here like every bulk# action. Bulk dismissals are recovered from the status stream; bulk resolves are not, because the@@ -363,7 +375,17 @@ SELECTcountIf(toString(properties.action_type) = 'remove_suggested_reviewer') AS reviewer_remove_count,nullIf(minIf(timestamp, toString(properties.action_type) = 'remove_suggested_reviewer'), fromUnixTimestamp(0)) AS first_reviewer_removed_at,countIf(toString(properties.action_type) = 'resolve') AS resolve_click_count,- nullIf(minIf(timestamp, toString(properties.action_type) = 'resolve'), fromUnixTimestamp(0)) AS first_resolve_clicked_at+ nullIf(minIf(timestamp, toString(properties.action_type) = 'resolve'), fromUnixTimestamp(0)) AS first_resolve_clicked_at,+ countIf(toString(properties.action_type) = 'copy_implementation_prompt') AS copy_prompt_count,+ nullIf(minIf(timestamp, toString(properties.action_type) = 'copy_implementation_prompt'), fromUnixTimestamp(0)) AS first_prompt_copied_at,+ countIf(toString(properties.action_type) = 'implement') AS implement_click_count,+ nullIf(minIf(timestamp, toString(properties.action_type) = 'implement'), fromUnixTimestamp(0)) AS first_implement_clicked_at,+ countIf(toString(properties.action_type) = 'open_pr') AS open_pr_click_count,+ nullIf(minIf(timestamp, toString(properties.action_type) = 'open_pr'), fromUnixTimestamp(0)) AS first_open_pr_clicked_at,+ countIf(toString(properties.action_type) = 'view_diff') AS view_diff_count,+ nullIf(minIf(timestamp, toString(properties.action_type) = 'view_diff'), fromUnixTimestamp(0)) AS first_diff_viewed_at,+ countIf(toString(properties.action_type) = 'restore') AS restore_count,+ nullIf(minIf(timestamp, toString(properties.action_type) = 'restore'), fromUnixTimestamp(0)) AS first_restored_atFROM eventsWHERE event = 'Inbox report action'AND timestamp >= toDateTime({labels_epoch}) AND timestamp < toDateTime({snapshot_end})@@ -384,6 +406,8 @@ STATUS_COLUMNS = ("first_dismissal_reason","wrong_dismissal_count","first_wrong_dismissed_at",+ "reasoned_resolution_count",+ "first_reasoned_resolved_at","status_event_priority","status_event_actionability","status_event_team_id",@@ -455,6 +479,17 @@ SELECTbucket_first_wrong_dismissed_at,outcome = 'dismissed' AND event_team_id = latest_event_team_id) AS first_wrong_dismissed_at,+ -- A resolve that carries a reason is a person or an agent marking the report done, from any+ -- surface. A reason-less resolve is the automatic resolve after a tracked PR merges, so it is+ -- not counted. Counted per bucket and dated by the bucket's first reasoned event, under the+ -- same tenant restriction as the wrong-dismissal pair above. The action head reads this pair.+ countIf(+ outcome = 'resolved' AND bucket_reasoned = 1 AND event_team_id = latest_event_team_id+ ) AS reasoned_resolution_count,+ minIf(+ bucket_first_reasoned_at,+ outcome = 'resolved' AND event_team_id = latest_event_team_id+ ) AS first_reasoned_resolved_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@@ -511,6 +546,12 @@ FROM (nullIf(minIf(events.timestamp, toString(properties.dismissal_reason) IN ("""+ _WRONG_DISMISSAL_REASONS_SQL+ """)), fromUnixTimestamp(0)) AS bucket_first_wrong_dismissed_at,+ -- coalesce is load-bearing: HogQL evaluates NULL != '' to true, so a reason-less event+ -- would otherwise count as reasoned.+ max(coalesce(toString(properties.dismissal_reason), '') != '') AS bucket_reasoned,+ nullIf(+ minIf(events.timestamp, coalesce(toString(properties.dismissal_reason), '') != ''), fromUnixTimestamp(0)+ ) AS bucket_first_reasoned_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@@ -614,6 +655,24 @@ WHERE event = 'signals_pr_refund_created'GROUP BY report_id"""+# Server-side actions, read from Postgres rather than from analytics events: the claims, linked+# PRs and notes a person or an external agent wrote (`HUMAN_ACTOR_KINDS`), and Slack discussions.+# These reach a report from surfaces that emit no `Inbox report action` event (coding agents over+# MCP, the CLI, Slack, the desktop app). Each row is counted by its creation time only: artefact+# content can be edited in place, but these labels only need the row to exist before the cutoff.+# Postgres holds this region's reports only, so another region's report gets no server action.+SERVER_ACTIONS_STREAM = "server_actions"+SERVER_ACTIONS_COLUMNS = (+ "claim_count",+ "first_claimed_at",+ "linked_pr_count",+ "first_pr_linked_at",+ "note_count",+ "first_noted_at",+ "slack_discussion_count",+ "first_slack_discussed_at",+)+LABEL_STREAMS: tuple[tuple[str, str, tuple[str, ...]], ...] = (("impressions", IMPRESSIONS_SQL, IMPRESSIONS_COLUMNS),("opens", OPENS_SQL, OPENS_COLUMNS),@@ -624,6 +683,12 @@ LABEL_STREAMS: tuple[tuple[str, str, tuple[str, ...]], ...] = (("refunds", REFUNDS_SQL, REFUNDS_COLUMNS),)+# The label columns each stream fills, the SQL streams and the Postgres one alike.+LABEL_STREAM_COLUMNS: dict[str, tuple[str, ...]] = {+ **{name: columns for name, _, columns in LABEL_STREAMS},+ SERVER_ACTIONS_STREAM: SERVER_ACTIONS_COLUMNS,+}+# Every label column a report can have, with its no-events default. Streams overwrite their own# columns; the merge keeps counts at 0 (not null) so head derivations need no null handling.LABEL_DEFAULTS: dict[str, Any] = {@@ -680,6 +745,26 @@ LABEL_DEFAULTS: dict[str, Any] = {"first_reviewer_removed_at": None,"resolve_click_count": 0,"first_resolve_clicked_at": None,+ "copy_prompt_count": 0,+ "first_prompt_copied_at": None,+ "implement_click_count": 0,+ "first_implement_clicked_at": None,+ "open_pr_click_count": 0,+ "first_open_pr_clicked_at": None,+ "view_diff_count": 0,+ "first_diff_viewed_at": None,+ "restore_count": 0,+ "first_restored_at": None,+ "reasoned_resolution_count": 0,+ "first_reasoned_resolved_at": None,+ "claim_count": 0,+ "first_claimed_at": None,+ "linked_pr_count": 0,+ "first_pr_linked_at": None,+ "note_count": 0,+ "first_noted_at": None,+ "slack_discussion_count": 0,+ "first_slack_discussed_at": None,}_TIMESTAMP_LABEL_COLUMNS = frozenset(name for name in LABEL_DEFAULTS if name.endswith("_at"))@@ -699,6 +784,16 @@ OUTCOME_FIRST_EVENT_COLUMNS: dict[str, str] = {"reviewer_add_count": "first_reviewer_added_at","reviewer_remove_count": "first_reviewer_removed_at","resolve_click_count": "first_resolve_clicked_at",+ "copy_prompt_count": "first_prompt_copied_at",+ "implement_click_count": "first_implement_clicked_at",+ "open_pr_click_count": "first_open_pr_clicked_at",+ "view_diff_count": "first_diff_viewed_at",+ "restore_count": "first_restored_at",+ "reasoned_resolution_count": "first_reasoned_resolved_at",+ "claim_count": "first_claimed_at",+ "linked_pr_count": "first_pr_linked_at",+ "note_count": "first_noted_at",+ "slack_discussion_count": "first_slack_discussed_at","feedback_positive_count": "first_positive_feedback_at","feedback_negative_count": "first_negative_feedback_at","wrong_dismissal_count": "first_wrong_dismissed_at",@@ -737,9 +832,8 @@ def merge_label_streams(rows with impossible ids dropped, so forged or malformed client events cannot mint label-onlytraining rows."""merged: dict[str, dict[str, Any]] = {}- columns_by_stream = {name: columns for name, _, columns in LABEL_STREAMS}for stream_name, rows in stream_rows.items():- columns = columns_by_stream[stream_name]+ columns = LABEL_STREAM_COLUMNS[stream_name]for report_id, row in canonical_stream_rows(rows).items():entry = merged.setdefault(report_id,diff --git a/products/signals/dags/inbox_ranking/shadow/queries.py b/products/signals/dags/inbox_ranking/shadow/queries.pyindex a3a1bcda2931..551894f56b99 100644--- a/products/signals/dags/inbox_ranking/shadow/queries.py+++ b/products/signals/dags/inbox_ranking/shadow/queries.py@@ -30,10 +30,21 @@ from products.signals.dags.inbox_ranking.dataset.queries import (utc_bound,)-# The action types the `action` head counts as a positive (products/signals/dags/inbox_ranking/+# The UI action types the `action` head counts as a positive (products/signals/dags/inbox_ranking/# training/heads.py). Kept identical so both reads count the same event family. The head's seven-day# horizon and its per-report grain are deliberately not carried over; `shadow/metrics.py` says why.-ACTION_TYPES = ("create_pr", "discuss")+# The head's server-side sources stay out: this grade needs a per-viewer event after an impression.+ACTION_TYPES = (+ "create_pr",+ "implement",+ "copy_implementation_prompt",+ "discuss",+ "open_pr",+ "view_diff",+ "add_suggested_reviewer",+ "remove_suggested_reviewer",+ "restore",+)_ACTION_TYPES_SQL = ", ".join(f"'{action_type}'" for action_type in ACTION_TYPES)diff --git a/products/signals/dags/inbox_ranking/tests/test_dataset.py b/products/signals/dags/inbox_ranking/tests/test_dataset.pyindex cc432fcbc748..ac65c0af1074 100644--- a/products/signals/dags/inbox_ranking/tests/test_dataset.py+++ b/products/signals/dags/inbox_ranking/tests/test_dataset.py@@ -12,7 +12,7 @@ from parameterized import parameterizedfrom posthog.models import Organization, Teamfrom products.event_definitions.backend.models.property_definition import PropertyDefinition-from products.signals.backend.models import SignalReport+from products.signals.backend.models import SignalReport, SignalReportAction, SignalReportArtefactfrom products.signals.backend.ranking.inventory import spine_report_filterfrom products.signals.backend.report_embeddings import EMBEDDING_RENDERING_TITLE, EMBEDDING_RENDERING_TITLE_SUMMARYfrom products.signals.dags.inbox_ranking import common@@ -27,9 +27,10 @@ from products.signals.dags.inbox_ranking.dataset.dag import (from products.signals.dags.inbox_ranking.dataset.queries import (IMPRESSIONS_SQL,LABEL_DEFAULTS,- LABEL_STREAMS,+ LABEL_STREAM_COLUMNS,LABELED_REPORT_IDS_SQL,OUTCOME_FIRST_EVENT_COLUMNS,+ SERVER_ACTIONS_COLUMNS,STATUS_COLUMNS,STATUS_SQL,hogql_rows,@@ -189,14 +190,15 @@ 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, T1, 1, T1, 1, T1, 1, T1, 1, T1),+ ("bogus-id", *([1, T1] * 12)),# 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, 6, T2, 7, T1, 2, T1, 3, T2, 4, T1),+ (UUID_B, 5, T1, 0, None, 6, T2, 7, T1, 2, T1, 3, T2, 4, T1, 8, T2, 9, T1, 10, T2, 11, T1, 12, T2),],"feedback": [(UUID_B, 2, T1, 1, T2, T1, "negative")],"status_changes": [],"pr_events": [(UUID_B, 1, T1, 1, T2, 1, T2)],+ "server_actions": [(UUID_B, 13, T1, 14, T2, 15, T1, 16, T2)],}rows = {row["report_id"]: row for row in merge_label_streams(stream_rows, SNAPSHOT_DATE)}@@ -231,6 +233,19 @@ def test_merge_label_streams_fills_defaults_and_maps_columns():assert r2["first_reviewer_removed_at"] == T2assert r2["resolve_click_count"] == 4assert r2["first_resolve_clicked_at"] == T1+ assert r2["copy_prompt_count"] == 8+ assert r2["first_prompt_copied_at"] == T2+ assert r2["implement_click_count"] == 9+ assert r2["open_pr_click_count"] == 10+ assert r2["view_diff_count"] == 11+ assert r2["restore_count"] == 12+ assert r2["first_restored_at"] == T2+ assert r2["claim_count"] == 13+ assert r2["first_claimed_at"] == T1+ assert r2["linked_pr_count"] == 14+ assert r2["note_count"] == 15+ assert r2["slack_discussion_count"] == 16+ assert r2["first_slack_discussed_at"] == T2@pytest.mark.parametrize("alias_first", [True, False])@@ -255,7 +270,7 @@ def test_stream_row_width_mismatch_fails_loudly():def test_label_stream_columns_all_exist_in_defaults():- for _name, _sql, columns in LABEL_STREAMS:+ for columns in LABEL_STREAM_COLUMNS.values():assert set(columns) <= set(LABEL_DEFAULTS)@@ -439,6 +454,56 @@ class TestSpineInclusion(BaseTest):assert metadata["excluded_no_training_consent_teams"].value == 2+class TestServerActions(BaseTest):+ def test_only_actions_a_person_or_an_external_agent_wrote_before_the_cutoff_count(self):+ snapshot_end = datetime.datetime.now(datetime.UTC) + datetime.timedelta(hours=1)+ report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY, title="t", summary="s")+ claims = {+ kind: SignalReportArtefact.objects.create(+ team=self.team,+ report=report,+ type=SignalReportArtefact.ArtefactType.WORK_CLAIM,+ content="{}",+ actor_kind=kind,+ )+ for kind in ("user", "agent", "task", "system", None)+ }+ for kind in ("task", "user"):+ SignalReportArtefact.objects.create(+ team=self.team,+ report=report,+ type=SignalReportArtefact.ArtefactType.NOTE,+ content="{}",+ actor_kind=kind,+ )+ late_note = SignalReportArtefact.objects.create(+ team=self.team, report=report, type=SignalReportArtefact.ArtefactType.NOTE, content="{}", actor_kind="user"+ )+ SignalReportArtefact.objects.filter(id=late_note.id).update(+ created_at=snapshot_end + datetime.timedelta(hours=1)+ )+ SignalReportAction.all_teams.create(+ team=self.team,+ report=report,+ user=self.user,+ type=SignalReportAction.ActionType.SLACK_DISCUSSION,+ count=5,+ last_at=snapshot_end,+ )++ rows = dag.server_action_rows([str(report.id)], snapshot_end)++ assert len(rows) == 1+ row = dict(zip(("report_id", *SERVER_ACTIONS_COLUMNS), rows[0], strict=True))+ assert row["report_id"] == str(report.id)+ assert row["claim_count"] == 2+ assert row["first_claimed_at"] == claims["user"].created_at+ assert row["note_count"] == 1+ assert row["linked_pr_count"] == 0+ assert row["first_pr_linked_at"] is None+ assert row["slack_discussion_count"] == 1++class TestImpressionsStream(ClickhouseTestMixin, BaseTest):@parameterized.expand([("labeled_ids", LABELED_REPORT_IDS_SQL), ("impressions", IMPRESSIONS_SQL)])def test_impressions_survive_a_numeric_property_definition(self, _name, sql):@@ -560,6 +625,17 @@ class TestStatusStream(ClickhouseTestMixin, BaseTest):# a dismissal the report's tenant never made.assert row["first_dismissed_server_at"] != T1+ @parameterized.expand([("reasoned", "fixed_outside_posthog", 1), ("reasonless", None, 0), ("empty", "", 0)])+ def test_only_a_reasoned_resolve_counts_as_a_reasoned_resolution(self, _name, reason, expected_count):+ # A reason-less resolve is the automatic resolve after a tracked PR merges, not a person+ # acting on the report.+ self._transition(T1, "ready", "resolved", reason)++ row = self._status_row()+ assert row["first_resolved_at"] == T1+ assert row["reasoned_resolution_count"] == expected_count+ assert row["first_reasoned_resolved_at"] == (T1 if expected_count else None)+def test_no_status_column_reads_an_event_from_another_tenant(self):# Forged-event invariance: transitions naming another team, all earlier than the genuine# ones, must leave every status column exactly as the genuine transitions alone produce it.diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.pyindex 85f8dc673e0e..545a4fc307c8 100644--- a/products/signals/dags/inbox_ranking/tests/test_training.py+++ b/products/signals/dags/inbox_ranking/tests/test_training.py@@ -108,7 +108,12 @@ from products.signals.dags.inbox_ranking.training.examples import (holdout_mask,reports_missing_birth_snapshot,)-from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME, Head, dismissed_as_wrong+from products.signals.dags.inbox_ranking.training.heads import (+ ACTION_LABEL_COLUMNS,+ HEADS_BY_NAME,+ Head,+ dismissed_as_wrong,+)from products.signals.dags.inbox_ranking.training.promotion import (AUC_TOLERANCE,ECE_TOLERANCE,@@ -383,6 +388,21 @@ def test_dismissed_as_wrong_prefers_the_cumulative_count(frame, expected):[True, True, True],[True, False, True],),+ # action: cohort is everyone, so a never-impressed report an agent claimed is a positive.+ # A server-side action and a UI action are the same label.+ (+ "action",+ pd.DataFrame(+ {+ "impression_unit_count": [0, 1, 1, 1],+ "claim_count": [1, 0, 0, 0],+ "reasoned_resolution_count": [0, 1, 0, 0],+ "view_diff_count": [0, 0, 2, 0],+ }+ ),+ [True, True, True, True],+ [True, True, True, False],+ ),# discuss: cohort is impressed reports, label is a discuss action.("discuss",@@ -443,34 +463,35 @@ class _ParquetS3:return {"Body": io.BytesIO(self._objects[Key])}[email protected]("head_name", ["pr_merged", "refund", "thumbs_up", "reviewer_fix"])-def test_new_head_label_columns_survive_the_load_snapshots_projection(head_name):+ "head_name,positive_column",+ [+ ("pr_merged", "pr_merged_count"),+ ("refund", "refund_count"),+ ("thumbs_up", "feedback_positive_count"),+ ("reviewer_fix", "reviewer_add_count"),+ *(("action", column) for column in ACTION_LABEL_COLUMNS),+ ],+)+def test_new_head_label_columns_survive_the_load_snapshots_projection(head_name, positive_column):# 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"],- open_count=[1],- pr_created_count=[0],- pr_merged_count=[0],- refund_count=[0],- feedback_positive_count=[0],- reviewer_add_count=[0],- reviewer_remove_count=[0],- )- labels_later = _labels(- ["a"],- open_count=[1],- pr_created_count=[1],- pr_merged_count=[1],- refund_count=[1],- feedback_positive_count=[1],- reviewer_add_count=[1],- reviewer_remove_count=[0],- )+ zeros = {+ column: [0]+ for column in (+ "pr_merged_count",+ "refund_count",+ "feedback_positive_count",+ "reviewer_add_count",+ *ACTION_LABEL_COLUMNS,+ )+ }+ labels_now = _labels(["a"], open_count=[1], **zeros)+ labels_later = _labels(["a"], open_count=[1], **{**zeros, positive_column: [1]})objects: dict[str, bytes] = {}for date, labels in ((D0, labels_now), (later, labels_later)):key = date.isoformat()@@ -1047,7 +1068,7 @@ def test_unseen_daily_evaluations_keep_baked_events_at_each_heads_horizon(@pytest.mark.parametrize("impressions", [0, 1])def test_daily_evaluation_keeps_empty_and_single_class_cohorts_explicit(impressions):- head = HEADS_BY_NAME["action"]+ head = HEADS_BY_NAME["discuss"]graded = graded_rows(_scores(["pending"], head_readable=[False], classification_threshold=[0.2]),_labels(["pending"], impression_unit_count=[impressions]),diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pyindex 76f1a7b413b6..bb77a3d3e93c 100644--- a/products/signals/dags/inbox_ranking/training/dag.py+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -117,7 +117,12 @@ from products.signals.dags.inbox_ranking.training.examples import (reports_missing_birth_snapshot,state_rows,)-from products.signals.dags.inbox_ranking.training.heads import HEADS, HEADS_BY_HORIZON, HEADS_BY_NAME+from products.signals.dags.inbox_ranking.training.heads import (+ ACTION_LABEL_COLUMNS,+ HEADS,+ HEADS_BY_HORIZON,+ HEADS_BY_NAME,+)from products.signals.dags.inbox_ranking.training.promotion import decide_promotionfrom products.signals.dags.inbox_ranking.training.serving import FamilyModels, compose_manifestfrom products.signals.dags.inbox_ranking.training.telemetry import (@@ -179,16 +184,13 @@ METADATA_FILE = "metadata.json"_LABEL_COLUMNS = ("impression_unit_count","open_count",- "create_pr_click_count",- "discuss_count","dismissal_reason","wrong_dismissal_count","pr_created_count","pr_merged_count","refund_count","feedback_positive_count",- "reviewer_add_count",- "reviewer_remove_count",+ *ACTION_LABEL_COLUMNS,*PROVENANCE_LABEL_COLUMNS,)# Every registered feature set's columns in one read: the state snapshot is loaded once and everydiff --git a/products/signals/dags/inbox_ranking/training/heads.py b/products/signals/dags/inbox_ranking/training/heads.pyindex 77a27226a90a..401509766e29 100644--- a/products/signals/dags/inbox_ranking/training/heads.py+++ b/products/signals/dags/inbox_ranking/training/heads.py@@ -8,6 +8,10 @@ must still be 0) and the snapshot `horizon_days` later (the label). The report'sexception: it has no earlier scoring moment, so an outcome already visible there is a futurepositive for that moment rather than an outcome of an earlier one, and the label may already be 1.+`action` counts intent from any surface: the inbox UI, external coding agents over MCP, the CLI,+Slack and the desktop app. Self-driving's own `task` and `system` writes are excluded, because+they are internal operational work and not a person acting on the report.+Mirrors the workspace `heads.py` (random-dev-internal, `inbox-ranking/`). Seven heads are denseenough to read on the holdout. `thumbs_up` and `reviewer_fix` are the explicit human-feedback pair:they are rare, so they are carried for the pooled newborn grade and as scorer inputs rather than@@ -39,8 +43,35 @@ def opened(frame: pd.DataFrame) -> pd.Series:return _count(frame, "open_count") > 0+# Intent actions from the inbox UI (`Inbox report action` events).+UI_ACTION_COLUMNS = (+ "create_pr_click_count",+ "implement_click_count",+ "copy_prompt_count",+ "discuss_count",+ "open_pr_click_count",+ "view_diff_count",+ "reviewer_add_count",+ "reviewer_remove_count",+ "restore_count",+)+# Intent actions recorded server-side, so they also cover the surfaces that emit no UI event. The+# artefact counts already exclude `task` and `system` writes (`HUMAN_ACTOR_KINDS`).+SERVER_ACTION_COLUMNS = (+ "claim_count",+ "linked_pr_count",+ "note_count",+ "slack_discussion_count",+ "reasoned_resolution_count",+)+ACTION_LABEL_COLUMNS = UI_ACTION_COLUMNS + SERVER_ACTION_COLUMNS++def acted(frame: pd.DataFrame) -> pd.Series:- return (_count(frame, "create_pr_click_count") + _count(frame, "discuss_count")) > 0+ any_action = pd.Series(False, index=frame.index)+ for column in ACTION_LABEL_COLUMNS:+ any_action |= _count(frame, column) > 0+ return any_actiondef dismissed_as_wrong(frame: pd.DataFrame) -> pd.Series:@@ -98,8 +129,18 @@ HEADS: tuple[Head, ...] = (# Which reports got opened by anyone? Cohort is every report: opens from a deeplink, the desktop# app or any other surface count, and those often have no list impression.Head(name="open", cohort=everyone, label=opened, horizon_days=3, min_holdout_positives=50),- # Of the reports users saw, which drew a create-PR click or a discuss?- Head(name="action", cohort=impressed, label=acted, horizon_days=7, min_holdout_positives=30),+ # Which reports did someone act on, from any surface? The cohort is everyone, because a report+ # worked from Slack, the desktop app or an agent was often never impressed in the cloud list.+ # The label reads the status stream (a reasoned resolve), so it needs the provenance check.+ Head(+ name="action",+ cohort=everyone,+ label=acted,+ horizon_days=7,+ min_holdout_positives=30,+ label_columns=ACTION_LABEL_COLUMNS,+ status_labels=True,+ ),# Of the reports users saw, which were dismissed as wrong / unclear / intentional - the# precision-failure negative. already_fixed and wontfix_irrelevant are deliberately not here.Head(@@ -122,7 +163,7 @@ HEADS: tuple[Head, ...] = (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+ # Of the reports users saw, which drew a discuss? A subset of the action head, which is fine - each# head trains independently.Head(name="discuss",