: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 a user-grain interactions table to the inbox ranking dataset (#115090)
posthog[bot]610e48dc48a1
diff --git a/posthog/dags/locations/signals.py b/posthog/dags/locations/signals.pyindex a59dec172d37..7b1794abba57 100644--- a/posthog/dags/locations/signals.py+++ b/posthog/dags/locations/signals.py@@ -21,6 +21,7 @@ if is_inbox_ranking_registered():inbox_ranking_dataset.inbox_report_model_data,inbox_ranking_dataset.inbox_report_title_embeddings,inbox_ranking_dataset.inbox_report_reviewers,+ inbox_ranking_dataset.inbox_user_report_interactions,inbox_ranking_training.inbox_ranking_training_examples,inbox_ranking_training.inbox_ranking_model_candidate,inbox_ranking_training.inbox_ranking_model_champion,diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.mdindex a226da0b371a..8300d4341bf2 100644--- a/products/signals/dags/inbox_ranking/AGENTS.md+++ b/products/signals/dags/inbox_ranking/AGENTS.md@@ -6,6 +6,7 @@ Read `README.md` first for what the dataset is and how partitions behave. This f- A new ranking dag (training, eval, ...) is a **sibling subpackage** (`inbox_ranking/<name>/dag.py`) importing shared plumbing from `common.py` — don't grow `dataset/` sideways and don't duplicate the S3/partition helpers.- `inbox_report_title_embeddings` is a **leaf**: never add it to `inbox_report_model_data`'s `deps` or give that join a title column, or a failure in the title snapshot fails the training table. Its own `deps=[MODEL_DATA_TABLE]` exists for memory, not data — two full sets of 1536-float vectors must not be held at once in the run pod. Raising the pod memory limit is not the first resort.+- `inbox_user_report_interactions` is a **leaf** with its own `USER_INTERACTIONS_SCHEMA_VERSION`: keep it out of `inbox_report_model_data`'s `deps`, and never stamp it with `FEATURE_SCHEMA_VERSION`, or a user-grain change sets off the labels refresh sensor. It writes a row only for a report in this region's Postgres whose team is in `training_consent_team_ids()`.- Register new jobs/schedules in `posthog/dags/locations/signals.py`, keep the EU gate (`is_inbox_ranking_registered()`), and remember the ci-dagster paths filter must cover every module a dag file imports (`uv run .github/scripts/check-dagster-paths.py`).## Training dag specificsdiff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex 48dfddeefec7..845b8525d897 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -6,7 +6,7 @@ Dagster jobs for the Self-driving Inbox report-ranking model: the **dataset** dainbox_ranking/├── common.py # shared: S3 destination config, daily partition def, gating, Parquet IO├── dataset/-│ ├── dag.py # the five dataset assets + job + schedule+│ ├── dag.py # the dataset assets + job + schedule│ └── queries.py # HogQL label SQL, embeddings SQL, stream merging├── training/│ ├── dag.py # examples → candidate → champion assets + job + schedule@@ -21,7 +21,7 @@ Registered via `posthog/dags/locations/signals.py` (US only) and loaded locally## The dataset dag-`inbox_ranking_dataset_job` runs daily at 02:30 UTC (schedule default: running on prod US, stopped everywhere else — including hosted DEV and E2E, which have no dogfood project to read labels from) and builds seven assets on one daily partition, each a Parquet object in S3:+`inbox_ranking_dataset_job` runs daily at 02:30 UTC (schedule default: running on prod US, stopped everywhere else — including hosted DEV and E2E, which have no dogfood project to read labels from) and builds eight assets on one daily partition, each a Parquet object in S3:```texts3://<bucket>/<prefix>/@@ -33,7 +33,8 @@ s3://<bucket>/<prefix>/│ └── latest/ # rewritten by the newest partition; warehouse tables point here├── inbox_signal_embeddings/v1/dt=YYYY-MM-DD/ # one row per signal emitted during the day (signal grain)├── inbox_report_title_embeddings/v1/dt=YYYY-MM-DD/ # the same shape, for the title-only rendering-└── inbox_report_reviewers/v1/dt=YYYY-MM-DD/ # one row per suggested reviewer of each spine report+├── inbox_report_reviewers/v1/dt=YYYY-MM-DD/ # one row per suggested reviewer of each spine report+└── inbox_user_report_interactions/v1/dt=YYYY-MM-DD/ # cumulative interactions per (report, person)```The first four are report grain and land in one table. `inbox_signal_embeddings` is signal grain, feeds the group-level model, and is read on its own — training joins it to `inbox_report_model_data` by `report_id`.@@ -58,6 +59,37 @@ The first four are report grain and land in one table. `inbox_signal_embeddings`- **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_report_status_changed` names the actor of each transition.** `actor_kind` is `user`, `agent`, `task` or `system`, and `actor_user_uuid`, `actor_distinct_id`, `actor_agent` and `actor_task_id` identify it. A transition no caller attributed (the pipeline, the PR-merge webhook, an unresolved Slack click) is `system`. The event `distinct_id` stays the team uuid. Events before this change carry no actor keys, so a per-user feature must treat a missing `actor_kind` as unknown, not as `system`.+### User grain++`inbox_user_report_interactions` has one row per `(report_id, user_distinct_id)`, for user–report affinity models. It has the labels asset's contract: `dt=D` is cumulative from `LABELS_EPOCH` to `D+1 00:00 UTC`, every source has an explicit time bound, and a re-run writes the same object (rows are sorted by key).++- **It is a leaf.** Nothing joins it, it is not in `inbox_report_model_data`'s deps, and it has no deps of its own, so it runs beside the labels asset. A failure here never fails the training table.+- **It has its own schema version**, `USER_INTERACTIONS_SCHEMA_VERSION`, stamped on the object. A change here does not set off `inbox_ranking_labels_refresh_sensor`. There is no refresh sensor for this table: after a schema change, backfill the training lookback by hand.+- **The person key is `User.distinct_id`.** The app's events and the status stream's `actor_distinct_id` already carry it. `user_uuid` is null when the distinct id is not a user in this region.+- **Only consented, local reports get rows.** A row is written only when its report exists in this region's Postgres before the cutoff and its team is in `training_consent_team_ids()`. This is stricter than the labels asset, which keeps label-only rows, because these rows describe a person.++| Columns | Source | Person key |+| -------------------------------------------------------------- | -------------------------------------------- | ---------------------------------------------------------- |+| impressions, suggested-reviewer impressions | `Inbox reports impressed` (per entry) | event `distinct_id` |+| opens, `first_open_method` | `Inbox report opened` | event `distinct_id` |+| closes, `total_time_spent_ms` | `Inbox report closed` | event `distinct_id` |+| UI actions (`ACTION_TYPES`) | `Inbox report action` | event `distinct_id` |+| feedback | `Inbox report feedback` | event `distinct_id` |+| refunds | `signals_pr_refund_created` | event `distinct_id` |+| `status_*`, `first_dismissal_actor_kind` | `signal_report_status_changed` | `actor_distinct_id` when `actor_kind` is `user` or `agent` |+| `pr_closed_by_*`, `pr_merged_by_*` | `pr_closed` / `pr_merged` | `pr_closed_by_distinct_id` / `pr_merged_by_distinct_id` |+| claims, linked PRs, notes | `SignalReportArtefact` (`HUMAN_ACTOR_KINDS`) | `created_by` |+| `first_viewed_at`, `first_read_at`, `first_slack_discussed_at` | `SignalReportAction.first_at` | `user` |++Point-in-time caveats, per source:++- **The status and PR columns start when the actor keys shipped (2026-10-09).** Earlier events carry no actor, so they reach no row. A backfill before that date fills only the app-event and Postgres columns. Most transitions are `system` and name no person, so most rows come from impressions and opens.+- **The PR closer and merger are set only when their GitHub login maps to an org member.**+- **The status columns follow the `STATUS_SQL` tenant rule.** Each aggregate reads only the tenant of the report's latest transition, taken over every transition of the report, not only this person's.+- **The Postgres columns read current rows**, with the report-grain caveats: a merge moves notes and linked PRs to the survivor, and a note can be deleted. Action rows give only `first_at`; their `count` and `last_at` keep moving after the cutoff. Bulk actions carry no `report_id` and stay out, and the desktop app sends no impressions.+- **The client streams are claimed, not proven.** A `report_id` and a `distinct_id` on an app event are client-supplied. The report must exist in this region, but nothing checks that the person is a member of the report's organization.+- **Staff impersonation.** posthog-js opts out of capture in an impersonated session, so the client streams hold no impersonated events. The refund event carries `was_impersonated`, and those refunds are excluded. The status event and the Postgres rows carry no impersonation flag, so a transition, artefact or action row a staff member made while impersonating counts for the impersonated person.+### Signal-grain partitions`inbox_signal_embeddings` is the one asset here whose partitions are **not** full snapshots. `dt=D` holds only the signal documents inserted during D — an emission log — because a cumulative copy at signal grain means a 1536-float vector per signal, fleet-wide, rewritten every day.diff --git a/products/signals/dags/inbox_ranking/dataset/dag.py b/products/signals/dags/inbox_ranking/dataset/dag.pyindex 104a705b36dd..d90e8e28a040 100644--- a/products/signals/dags/inbox_ranking/dataset/dag.py+++ b/products/signals/dags/inbox_ranking/dataset/dag.py@@ -9,13 +9,15 @@ Seven assets on one daily partition, each writing Parquet under the configured Sinbox_signal_embeddings/v1/dt=D/ one row per signal emission during D, for the group-level modelinbox_report_title_embeddings/v1/dt=D/ the same shape, for the title-only renderinginbox_report_reviewers/v1/dt=D/ one row per suggested reviewer of each spine report+ inbox_user_report_interactions/v1/dt=D/ cumulative interactions at (report, person) grainThe first four are report grain and feed one table. inbox_signal_embeddings is signal grain and isread on its own, joined to the others by report_id at training time. inbox_report_title_embeddingsis a report-grain leaf: nothing joins it, and the training side pairs it to inbox_report_embeddingsby report_id when it measures one rendering against the other. inbox_report_reviewers is a(report, reviewer) leaf with its own schema version: nothing joins it, and the training side pairs-it to the report tables by report_id.+it to the report tables by report_id. inbox_user_report_interactions is a (report, person) grain+leaf with its own schema version, so nothing joins it either.Partition dt=D is a full snapshot of the eligible report inventory (promoted or ever-labeled),with every label aggregate bounded `event_time < D+1 00:00 UTC`. Label columns are cumulative,@@ -126,6 +128,12 @@ from products.signals.dags.inbox_ranking.dataset.queries import (SERVER_ACTIONS_STREAM,SIGNAL_EMBEDDINGS_QUERY_SETTINGS,SIGNAL_EMBEDDINGS_SQL,+ USER_KEY_COLUMNS,+ USER_LABEL_DEFAULTS,+ USER_LABEL_STREAM_COLUMNS,+ USER_LABEL_STREAMS,+ USER_SERVER_ACTIONS_COLUMNS,+ USER_SERVER_ACTIONS_STREAM,etl_workload,hogql_rows,labels_team,@@ -134,6 +142,9 @@ from products.signals.dags.inbox_ranking.dataset.queries import ()FEATURE_SCHEMA_VERSION = 9+# Apart from FEATURE_SCHEMA_VERSION on purpose: the labels refresh sensor rewrites every labels+# partition whose stamp is older than that one, and a user-grain change must not set it off.+USER_INTERACTIONS_SCHEMA_VERSION = 1STATE_TABLE = "inbox_report_state"EMBEDDINGS_TABLE = "inbox_report_embeddings"@@ -142,6 +153,7 @@ LABELS_TABLE = "inbox_report_labels"MODEL_DATA_TABLE = "inbox_report_model_data"SIGNAL_EMBEDDINGS_TABLE = "inbox_signal_embeddings"REVIEWERS_TABLE = "inbox_report_reviewers"+USER_INTERACTIONS_TABLE = "inbox_user_report_interactions"# The reviewers asset is a leaf with its own columns, so its schema moves apart from# FEATURE_SCHEMA_VERSION. The same rule applies: additive nullable columns bump it.@@ -371,6 +383,78 @@ _MODEL_DATA_FIELDS: list[tuple[str, pa.DataType]] = []MODEL_DATA_SCHEMA = pa.schema(_MODEL_DATA_FIELDS)+_USER_INTERACTION_FIELDS: list[tuple[str, pa.DataType]] = [+ ("snapshot_date", pa.date32()),+ ("report_id", pa.string()),+ ("report_team_id", pa.int64()),+ ("user_distinct_id", pa.string()),+ ("user_uuid", pa.string()),+ ("impression_unit_count", pa.int32()),+ ("first_impressed_at", _TIMESTAMP),+ ("best_impression_rank", pa.int32()),+ ("impressed_as_suggested_reviewer_count", pa.int32()),+ ("first_impressed_as_suggested_reviewer_at", _TIMESTAMP),+ ("open_count", pa.int32()),+ ("first_opened_at", _TIMESTAMP),+ ("last_opened_at", _TIMESTAMP),+ ("first_open_method", pa.string()),+ ("close_count", pa.int32()),+ ("first_closed_at", _TIMESTAMP),+ ("total_time_spent_ms", pa.int64()),+ ("ui_dismiss_count", pa.int32()),+ ("first_ui_dismissed_at", _TIMESTAMP),+ ("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),+ ("reviewer_add_count", pa.int32()),+ ("first_reviewer_added_at", _TIMESTAMP),+ ("reviewer_remove_count", pa.int32()),+ ("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),+ ("feedback_positive_count", pa.int32()),+ ("first_positive_feedback_at", _TIMESTAMP),+ ("feedback_negative_count", pa.int32()),+ ("first_negative_feedback_at", _TIMESTAMP),+ ("refund_count", pa.int32()),+ ("first_refunded_at", _TIMESTAMP),+ ("status_resolved_count", pa.int32()),+ ("first_status_resolved_at", _TIMESTAMP),+ ("status_dismissed_count", pa.int32()),+ ("first_status_dismissed_at", _TIMESTAMP),+ ("status_snoozed_count", pa.int32()),+ ("first_status_snoozed_at", _TIMESTAMP),+ ("first_status_dismissal_reason", pa.string()),+ ("first_dismissal_actor_kind", pa.string()),+ ("pr_closed_by_count", pa.int32()),+ ("first_pr_closed_by_at", _TIMESTAMP),+ ("pr_merged_by_count", pa.int32()),+ ("first_pr_merged_by_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),+ ("first_viewed_at", _TIMESTAMP),+ ("first_read_at", _TIMESTAMP),+ ("first_slack_discussed_at", _TIMESTAMP),+]+USER_INTERACTIONS_SCHEMA = pa.schema(_USER_INTERACTION_FIELDS)+_STATE_PASSTHROUGH_COLUMNS = ("report_team_id","region",@@ -397,7 +481,7 @@ _STATE_PASSTHROUGH_COLUMNS = (_ORM_ID_CHUNK = 10_000-def _chunked(ids: list[str]) -> Iterator[list[str]]:+def _chunked[T](ids: list[T]) -> Iterator[list[T]]:for offset in range(0, len(ids), _ORM_ID_CHUNK):yield ids[offset : offset + _ORM_ID_CHUNK]@@ -506,6 +590,114 @@ def server_action_rows(report_ids: list[str], snapshot_end: datetime.datetime) -]+@frozen+class UserIdentity:+ distinct_id: str+ uuid: str+++def user_identities(field: str, values: list[Any]) -> dict[Any, UserIdentity]:+ """The identity of each user, keyed by `field` (`id` or `distinct_id`). A user with no+ distinct id is left out, because the user grain has no key for them."""+ identities: dict[Any, UserIdentity] = {}+ for chunk in _chunked(values):+ for key, distinct_id, user_uuid in (+ User.objects.filter(**{f"{field}__in": chunk}, distinct_id__isnull=False)+ .exclude(distinct_id="")+ .values_list(field, "distinct_id", "uuid")+ ):+ identities[key] = UserIdentity(distinct_id=distinct_id, uuid=str(user_uuid))+ return identities+++# The action types each user-grain Postgres column reads `first_at` from.+_USER_ACTION_FIRST_COLUMNS: dict[str, str] = {+ SignalReportAction.ActionType.VIEW: "first_viewed_at",+ SignalReportAction.ActionType.READ: "first_read_at",+ SignalReportAction.ActionType.SLACK_DISCUSSION: "first_slack_discussed_at",+}+++def user_server_action_rows(report_ids: list[str], snapshot_end: datetime.datetime) -> list[tuple[Any, ...]]:+ """One `(report_id, user_distinct_id, *USER_SERVER_ACTIONS_COLUMNS)` row per report and person+ with a server-side action before the cutoff. Artefacts count by their author and the same+ `HUMAN_ACTOR_KINDS` rule as `server_action_rows`; action rows give only `first_at`."""+ entries: dict[tuple[str, int], dict[str, Any]] = {}++ def entry(report_id: Any, user_id: int) -> dict[str, Any]:+ return entries.setdefault(+ (str(report_id), user_id), {column: USER_LABEL_DEFAULTS[column] for column in USER_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_by__isnull=False,+ created_at__lt=snapshot_end,+ )+ .values("report_id", "created_by_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"], row["created_by_id"])+ values[count_column] = row["row_count"]+ values[first_column] = row["earliest_at"]+ actions = SignalReportAction.all_teams.filter(+ report_id__in=chunk, type__in=list(_USER_ACTION_FIRST_COLUMNS), first_at__lt=snapshot_end+ ).values_list("report_id", "user_id", "type", "first_at")+ for report_id, user_id, action_type, first_at in actions.iterator(chunk_size=2000):+ entry(report_id, user_id)[_USER_ACTION_FIRST_COLUMNS[action_type]] = first_at++ identities = user_identities("id", sorted({user_id for _, user_id in entries}))+ return [+ (report_id, identities[user_id].distinct_id, *(values[column] for column in USER_SERVER_ACTIONS_COLUMNS))+ for (report_id, user_id), values in entries.items()+ if user_id in identities+ ]+++def _report_teams(report_ids: list[str], snapshot_end: datetime.datetime) -> dict[str, int]:+ """The owning team of each report that exists in this region's Postgres before the cutoff."""+ teams: dict[str, int] = {}+ for chunk in _chunked(report_ids):+ teams |= {+ str(report_id): team_id+ for report_id, team_id in SignalReport.objects.filter(+ id__in=chunk, created_at__lt=snapshot_end+ ).values_list("id", "team_id")+ }+ return teams+++def assemble_user_interaction_rows(+ merged_rows: list[dict[str, Any]],+ report_teams: Mapping[str, int],+ consent_team_ids: Collection[int],+ user_uuids: Mapping[str, str],+) -> list[dict[str, Any]]:+ """Keep the rows whose report exists in this region and belongs to a team opted in to AI+ training, and add the report's team and the person's uuid. Stricter than the labels asset, which+ keeps label-only rows, because these rows describe a person. Sorted, so a re-run writes the same+ object."""+ rows: list[dict[str, Any]] = []+ for merged in merged_rows:+ team_id = report_teams.get(merged["report_id"])+ if team_id is None or team_id not in consent_team_ids:+ continue+ rows.append(+ {+ **merged,+ "report_team_id": team_id,+ "user_uuid": user_uuids.get(merged["user_distinct_id"]),+ }+ )+ return sorted(rows, key=lambda row: (row["report_id"], row["user_distinct_id"]))++@dagster.asset(name=STATE_TABLE, **COMMON_ASSET_KWARGS)def inbox_report_state(context: dagster.AssetExecutionContext) -> None:if skip_unconfigured(context):@@ -1071,6 +1263,78 @@ def inbox_report_labels(context: dagster.AssetExecutionContext) -> None:)[email protected](name=USER_INTERACTIONS_TABLE, **COMMON_ASSET_KWARGS)+def inbox_user_report_interactions(context: dagster.AssetExecutionContext) -> None:+ """Cumulative interactions at (report, person) grain, for user-report affinity models.++ A leaf: nothing joins it, so a failure here never fails inbox_report_model_data. The person key+ is `User.distinct_id`; `user_uuid` is null when that distinct id is not a user in this region.+ """+ if skip_unconfigured(context):+ return+ _tag_dagster_queries(context, query_type="inbox_ranking_user_interactions")+ partition_key = context.partition_key+ _, snapshot_end = snapshot_bounds(partition_key)+ team = labels_team()++ stream_rows: dict[str, list[tuple[Any, ...]]] = {}+ for stream_name, sql, _columns in USER_LABEL_STREAMS:+ stream_rows[stream_name] = hogql_rows(+ sql,+ team=team,+ query_type=f"inbox_ranking_{stream_name}",+ snapshot_end=snapshot_end,+ )+ context.log.info(f"{stream_name}: {len(stream_rows[stream_name])} (report, person) pairs")++ # The same report set the labels asset reads server-side actions for, narrowed to the reports+ # whose rows can be written.+ candidate_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})+ report_teams = _report_teams(sorted(candidate_ids), snapshot_end)+ consent_team_ids = training_consent_team_ids()+ consented_ids = sorted(report_id for report_id, team_id in report_teams.items() if team_id in consent_team_ids)+ stream_rows[USER_SERVER_ACTIONS_STREAM] = user_server_action_rows(consented_ids, snapshot_end)++ merged = merge_label_streams(+ stream_rows,+ datetime.date.fromisoformat(partition_key),+ key_columns=USER_KEY_COLUMNS,+ stream_columns=USER_LABEL_STREAM_COLUMNS,+ defaults=USER_LABEL_DEFAULTS,+ )+ distinct_ids = sorted({row["user_distinct_id"] for row in merged})+ user_uuids = {+ distinct_id: identity.uuid for distinct_id, identity in user_identities("distinct_id", distinct_ids).items()+ }+ rows = assemble_user_interaction_rows(merged, report_teams, consent_team_ids, user_uuids)++ bucket = dataset_bucket()+ key = partition_object_key(settings.INBOX_RANKING_DATASET_S3_PREFIX, USER_INTERACTIONS_TABLE, partition_key)+ write_parquet(+ s3_client(),+ bucket,+ key,+ pa.Table.from_pylist(rows, schema=USER_INTERACTIONS_SCHEMA),+ schema_version=USER_INTERACTIONS_SCHEMA_VERSION,+ )+ context.add_output_metadata(+ {+ "rows": dagster.MetadataValue.int(len(rows)),+ "reports": dagster.MetadataValue.int(len({row["report_id"] for row in rows})),+ "users": dagster.MetadataValue.int(len({row["user_distinct_id"] for row in rows})),+ "excluded_pairs": dagster.MetadataValue.int(len(merged) - len(rows)),+ **{+ f"{stream_name}_pairs": dagster.MetadataValue.int(len(stream))+ for stream_name, stream in stream_rows.items()+ },+ "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),+ }+ )++def label_provenance_ok(pg_status: str | None,pg_updated_at: datetime.datetime | None,@@ -1236,6 +1500,7 @@ inbox_ranking_dataset_job = dagster.define_asset_job(MODEL_DATA_TABLE,TITLE_EMBEDDINGS_TABLE,REVIEWERS_TABLE,+ USER_INTERACTIONS_TABLE,],# The seven label streams run sequentially and each may take its full 600s query timeout, so an# hour left a slow-but-valid pass no room for the join, the S3 writes, or an asset retry — anddiff --git a/products/signals/dags/inbox_ranking/dataset/queries.py b/products/signals/dags/inbox_ranking/dataset/queries.pyindex 1b9270fbf02f..8bfaf463d70e 100644--- a/products/signals/dags/inbox_ranking/dataset/queries.py+++ b/products/signals/dags/inbox_ranking/dataset/queries.py@@ -9,6 +9,7 @@ day.import uuidimport datetime+from collections.abc import Mappingfrom typing import Anyfrom urllib.parse import urlparse@@ -320,32 +321,24 @@ WHERE event = 'Inbox report opened'GROUP BY report_id"""-ACTIONS_COLUMNS = (- "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",- "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",+# Every `Inbox report action` type the label streams aggregate, with its count and first-event+# columns. ACTIONS_COLUMNS, ACTIONS_SQL and the user-grain actions stream are all generated from this+# one tuple, so a new action type cannot land in one grain and not the other.+ACTION_TYPES: tuple[tuple[str, str, str], ...] = (+ ("dismiss", "ui_dismiss_count", "first_ui_dismissed_at"),+ ("create_pr", "create_pr_click_count", "first_create_pr_clicked_at"),+ ("discuss", "discuss_count", "first_discussed_at"),+ ("snooze", "snooze_count", "first_snooze_clicked_at"),+ ("add_suggested_reviewer", "reviewer_add_count", "first_reviewer_added_at"),+ ("remove_suggested_reviewer", "reviewer_remove_count", "first_reviewer_removed_at"),+ ("resolve", "resolve_click_count", "first_resolve_clicked_at"),+ ("copy_implementation_prompt", "copy_prompt_count", "first_prompt_copied_at"),+ ("implement", "implement_click_count", "first_implement_clicked_at"),+ ("open_pr", "open_pr_click_count", "first_open_pr_clicked_at"),+ ("view_diff", "view_diff_count", "first_diff_viewed_at"),+ ("restore", "restore_count", "first_restored_at"),)+ACTIONS_COLUMNS = tuple(column for _, count, first in ACTION_TYPES for column in (count, first))# 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# the nullIf(..., fromUnixTimestamp(0)) wraps here and below.@@ -366,36 +359,18 @@ ACTIONS_COLUMNS = (# action. Bulk dismissals are recovered from the status stream; bulk resolves are not, because the# same `first_resolved_at` conflation rules it out as a substitute. So a head must read# `resolve_click_count` = 0 as unknown, not as "the report was never resolved".-ACTIONS_SQL = """+_ACTION_AGGREGATES_SQL = ",\n".join(+ f" countIf(toString(properties.action_type) = '{action_type}') AS {count},\n"+ f" nullIf(minIf(timestamp, toString(properties.action_type) = '{action_type}'), fromUnixTimestamp(0)) AS {first}"+ for action_type, count, first in ACTION_TYPES+)+ACTIONS_SQL = f"""SELECTtoString(properties.report_id) AS report_id,- countIf(toString(properties.action_type) = 'dismiss') AS ui_dismiss_count,- nullIf(minIf(timestamp, toString(properties.action_type) = 'dismiss'), fromUnixTimestamp(0)) AS first_ui_dismissed_at,- 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,- 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,- 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_at+{_ACTION_AGGREGATES_SQL}FROM eventsWHERE event = 'Inbox report action'- AND timestamp >= toDateTime({labels_epoch}) AND timestamp < toDateTime({snapshot_end})+ AND timestamp >= toDateTime({{labels_epoch}}) AND timestamp < toDateTime({{snapshot_end}})AND toString(properties.report_id) != ''GROUP BY report_id"""@@ -414,6 +389,15 @@ _FIXED_TRANSITION_SQL = ()_LOW_VALUE_DISMISSAL_REASONS_SQL = ", ".join(f"'{reason}'" for reason in LOW_VALUE_DISMISSAL_REASONS)+# The outcome a transition reaches, shared by the report-grain and user-grain status streams.+_STATUS_OUTCOME_SQL = """multiIf(+ toString(properties.status) = 'suppressed', 'dismissed',+ toString(properties.status) = 'resolved', 'resolved',+ toString(properties.status) = 'failed', 'failed',+ toString(properties.previous_status) IN ('ready', 'resolved') AND toString(properties.status) = 'potential', 'snoozed',+ 'other'+ )"""+STATUS_COLUMNS = ("first_resolved_at","first_dismissed_server_at",@@ -556,13 +540,9 @@ FROM (toString(properties.report_id) AS report_id,toString(properties.previous_status) AS previous_status,toString(properties.status) AS status,- multiIf(- toString(properties.status) = 'suppressed', 'dismissed',- toString(properties.status) = 'resolved', 'resolved',- toString(properties.status) = 'failed', 'failed',- toString(properties.previous_status) IN ('ready', 'resolved') AND toString(properties.status) = 'potential', 'snoozed',- 'other'- ) AS outcome,+ """+ + _STATUS_OUTCOME_SQL+ + """ AS outcome,-- Latest event in the bucket rather than any(): identical for the duplicate deliveries this-- grouping targets, and the one that matches last_timestamp when it collapsed real repeats.-- Named apart from the outer alias: ClickHouse resolves a bare `dismissal_reason` in the outer@@ -819,8 +799,6 @@ LABEL_DEFAULTS: dict[str, Any] = {"first_slack_discussed_at": None,}-_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@@ -829,18 +807,7 @@ _TIMESTAMP_LABEL_COLUMNS = frozenset(name for name in LABEL_DEFAULTS if name.endOUTCOME_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",- "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",+ **{count: first for _, count, first in ACTION_TYPES},"reasoned_resolution_count": "first_reasoned_resolved_at","claim_count": "first_claimed_at","linked_pr_count": "first_pr_linked_at",@@ -858,41 +825,330 @@ OUTCOME_FIRST_EVENT_COLUMNS: dict[str, str] = {}-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.+# User grain: one row per (report, person). The person key is `User.distinct_id`: the app's own+# events and the status stream's `actor_distinct_id` already carry it, so no stream needs a person+# lookup. Each stream returns `(report_id, user_distinct_id, *columns)`.+USER_KEY_COLUMNS = ("report_id", "user_distinct_id")++USER_IMPRESSIONS_COLUMNS = (+ "impression_unit_count",+ "first_impressed_at",+ "best_impression_rank",+ "impressed_as_suggested_reviewer_count",+ "first_impressed_as_suggested_reviewer_at",+)+# `is_suggested_reviewer` is the flag the list rendered for this person on each entry.+USER_IMPRESSIONS_SQL = f"""+SELECT+ JSONExtractString(imp, 'report_id') AS report_id,+ distinct_id AS user_distinct_id,+ count() AS impression_unit_count,+ min(timestamp) AS first_impressed_at,+ min({IMPRESSION_RANK_SQL}) AS best_impression_rank,+ countIf(JSONExtractBool(imp, 'is_suggested_reviewer') = 1) AS impressed_as_suggested_reviewer_count,+ nullIf(+ minIf(timestamp, JSONExtractBool(imp, 'is_suggested_reviewer') = 1), fromUnixTimestamp(0)+ ) AS first_impressed_as_suggested_reviewer_at+FROM events+ARRAY JOIN JSONExtractArrayRaw(properties, 'impressions') AS imp+WHERE event = 'Inbox reports impressed'+ AND timestamp >= toDateTime({{labels_epoch}}) AND timestamp < toDateTime({{snapshot_end}})+GROUP BY report_id, user_distinct_id+HAVING report_id != ''+"""++USER_OPENS_COLUMNS = ("open_count", "first_opened_at", "last_opened_at", "first_open_method")+USER_OPENS_SQL = """+SELECT+ toString(properties.report_id) AS report_id,+ distinct_id AS user_distinct_id,+ count() AS open_count,+ min(timestamp) AS first_opened_at,+ max(timestamp) AS last_opened_at,+ nullIf(argMin(coalesce(toString(properties.open_method), ''), timestamp), '') AS first_open_method+FROM events+WHERE event = 'Inbox report opened'+ AND timestamp >= toDateTime({labels_epoch}) AND timestamp < toDateTime({snapshot_end})+ AND toString(properties.report_id) != ''+GROUP BY report_id, user_distinct_id+"""++USER_CLOSES_COLUMNS = ("close_count", "first_closed_at", "total_time_spent_ms")+# `time_spent_ms` is client-supplied. Each close counts between 0 and one day, so a malformed value+# cannot overflow the sum or make the dwell negative.+USER_CLOSES_SQL = """+SELECT+ toString(properties.report_id) AS report_id,+ distinct_id AS user_distinct_id,+ count() AS close_count,+ min(timestamp) AS first_closed_at,+ sum(least(greatest(coalesce(toInt(properties.time_spent_ms), 0), 0), 86400000)) AS total_time_spent_ms+FROM events+WHERE event = 'Inbox report closed'+ AND timestamp >= toDateTime({labels_epoch}) AND timestamp < toDateTime({snapshot_end})+ AND toString(properties.report_id) != ''+GROUP BY report_id, user_distinct_id+"""++USER_ACTIONS_SQL = f"""+SELECT+ toString(properties.report_id) AS report_id,+ distinct_id AS user_distinct_id,+{_ACTION_AGGREGATES_SQL}+FROM events+WHERE event = 'Inbox report action'+ AND timestamp >= toDateTime({{labels_epoch}}) AND timestamp < toDateTime({{snapshot_end}})+ AND toString(properties.report_id) != ''+GROUP BY report_id, user_distinct_id+"""++USER_FEEDBACK_COLUMNS = (+ "feedback_positive_count",+ "first_positive_feedback_at",+ "feedback_negative_count",+ "first_negative_feedback_at",+)+USER_FEEDBACK_SQL = f"""+SELECT+ toString(properties.report_id) AS report_id,+ distinct_id AS user_distinct_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+FROM events+WHERE event = 'Inbox report feedback'+ AND {FEEDBACK_SENTIMENTS_SQL}+ AND timestamp >= toDateTime({{labels_epoch}}) AND timestamp < toDateTime({{snapshot_end}})+ AND toString(properties.report_id) != ''+GROUP BY report_id, user_distinct_id+"""- ClickHouse groups on the raw client-supplied id, so spelling variants of one UUID arrive as- separate rows that canonicalize onto the same report. The canonically spelled row wins, so a- forged alias can never overwrite a real report's aggregates; between aliases the smallest raw- id wins, so the choice does not depend on ClickHouse's row order."""- best: dict[str, tuple[tuple[bool, str], tuple[Any, ...]]] = {}+USER_REFUNDS_COLUMNS = ("refund_count", "first_refunded_at")+# The refund endpoint stamps `was_impersonated` on its event, and a staff session acting as a+# customer would otherwise credit the customer with the refund. The client streams need no such+# filter: posthog-js opts out of capture in an impersonated session.+USER_REFUNDS_SQL = """+SELECT+ toString(properties.report_id) AS report_id,+ distinct_id AS user_distinct_id,+ uniq(toString(properties.refund_id)) AS refund_count,+ min(timestamp) AS first_refunded_at+FROM events+WHERE event = 'signals_pr_refund_created'+ AND timestamp >= toDateTime({labels_epoch}) AND timestamp < toDateTime({snapshot_end})+ AND toString(properties.report_id) != ''+ AND coalesce(toString(properties.was_impersonated), '') != 'true'+GROUP BY report_id, user_distinct_id+"""++USER_STATUS_COLUMNS = (+ "status_resolved_count",+ "first_status_resolved_at",+ "status_dismissed_count",+ "first_status_dismissed_at",+ "status_snoozed_count",+ "first_status_snoozed_at",+ "first_status_dismissal_reason",+ "first_dismissal_actor_kind",+)+# The transitions this person asked for, directly (`user`) or through an external agent acting for+# them (`agent`). `system` and `task` transitions name no person, and events from before the actor+# keys shipped carry none, so neither reaches this stream.+#+# The tenant rule is STATUS_SQL's: every aggregate reads only the tenant of the report's latest+# transition. The window runs over every transition of the report, before the actor filter, so the+# tenant is the one the report-grain stream and its provenance check use. Buckets also split by+# actor, so one person's transition never dedupes into another's.+USER_STATUS_SQL = (+ """+SELECT+ report_id,+ actor_distinct_id AS user_distinct_id,+ countIf(outcome = 'resolved' AND event_team_id = latest_event_team_id) AS status_resolved_count,+ nullIf(minIf(first_timestamp, outcome = 'resolved' AND event_team_id = latest_event_team_id), fromUnixTimestamp(0)) AS first_status_resolved_at,+ countIf(outcome = 'dismissed' AND event_team_id = latest_event_team_id) AS status_dismissed_count,+ nullIf(minIf(first_timestamp, outcome = 'dismissed' AND event_team_id = latest_event_team_id), fromUnixTimestamp(0)) AS first_status_dismissed_at,+ countIf(outcome = 'snoozed' AND event_team_id = latest_event_team_id) AS status_snoozed_count,+ nullIf(minIf(first_timestamp, outcome = 'snoozed' AND event_team_id = latest_event_team_id), fromUnixTimestamp(0)) AS first_status_snoozed_at,+ nullIf(+ argMinIf(bucket_first_dismissal_reason, first_timestamp, outcome = 'dismissed' AND event_team_id = latest_event_team_id),+ ''+ ) AS first_status_dismissal_reason,+ nullIf(+ argMinIf(actor_kind, first_timestamp, outcome = 'dismissed' AND event_team_id = latest_event_team_id), ''+ ) AS first_dismissal_actor_kind+FROM (+ SELECT+ *,+ argMax(+ coalesce(event_team_id, ''), tuple(last_timestamp, coalesce(event_team_id, ''))+ ) OVER (PARTITION BY report_id) AS latest_event_team_id+ FROM (+ SELECT+ min(events.timestamp) AS first_timestamp,+ max(events.timestamp) AS last_timestamp,+ toString(properties.report_id) AS report_id,+ toString(properties.previous_status) AS previous_status,+ toString(properties.status) AS status,+ """+ + _STATUS_OUTCOME_SQL+ + """ AS outcome,+ argMin(+ coalesce(toString(properties.dismissal_reason), ''), events.timestamp+ ) AS bucket_first_dismissal_reason,+ nullIf(toString(properties.team_id), '') AS event_team_id,+ coalesce(toString(properties.actor_distinct_id), '') AS actor_distinct_id,+ coalesce(toString(properties.actor_kind), '') AS actor_kind+ FROM events+ WHERE event = 'signal_report_status_changed'+ AND events.timestamp >= toDateTime({labels_epoch}) AND events.timestamp < toDateTime({snapshot_end})+ AND toString(properties.report_id) != ''+ GROUP BY+ report_id,+ previous_status,+ status,+ event_team_id,+ actor_distinct_id,+ actor_kind,+ toStartOfInterval(events.timestamp, INTERVAL 10 MINUTE)+ )+)+WHERE actor_distinct_id != '' AND actor_kind IN ('user', 'agent')+GROUP BY report_id, user_distinct_id+-- A person whose every transition names another tenant, or reaches no counted outcome, gets no row.+HAVING status_resolved_count + status_dismissed_count + status_snoozed_count > 0+"""+)++USER_PR_COLUMNS = ("pr_closed_by_count", "first_pr_closed_by_at", "pr_merged_by_count", "first_pr_merged_by_at")+# The closer and the merger are set only when their GitHub login maps to an org member.+USER_PR_SQL = """+SELECT+ toString(properties.signal_report_id) AS report_id,+ if(+ event = 'pr_merged',+ coalesce(toString(properties.pr_merged_by_distinct_id), ''),+ coalesce(toString(properties.pr_closed_by_distinct_id), '')+ ) AS user_distinct_id,+ countIf(event = 'pr_closed') AS pr_closed_by_count,+ nullIf(minIf(timestamp, event = 'pr_closed'), fromUnixTimestamp(0)) AS first_pr_closed_by_at,+ countIf(event = 'pr_merged') AS pr_merged_by_count,+ nullIf(minIf(timestamp, event = 'pr_merged'), fromUnixTimestamp(0)) AS first_pr_merged_by_at+FROM events+WHERE event IN ('pr_merged', 'pr_closed')+ AND timestamp >= toDateTime({labels_epoch}) AND timestamp < toDateTime({snapshot_end})+ AND properties.signal_report_id IS NOT NULL+ AND toString(properties.signal_report_id) != ''+GROUP BY report_id, user_distinct_id+HAVING user_distinct_id != ''+"""++# Postgres, this region only: the claims, linked PRs and notes a person wrote, and the moment each+# action row was first recorded. `first_at` is the only stable column of an action row: `count` and+# `last_at` keep moving after the cutoff.+USER_SERVER_ACTIONS_STREAM = "user_server_actions"+USER_SERVER_ACTIONS_COLUMNS = (+ "claim_count",+ "first_claimed_at",+ "linked_pr_count",+ "first_pr_linked_at",+ "note_count",+ "first_noted_at",+ "first_viewed_at",+ "first_read_at",+ "first_slack_discussed_at",+)++USER_LABEL_STREAMS: tuple[tuple[str, str, tuple[str, ...]], ...] = (+ ("user_impressions", USER_IMPRESSIONS_SQL, USER_IMPRESSIONS_COLUMNS),+ ("user_opens", USER_OPENS_SQL, USER_OPENS_COLUMNS),+ ("user_closes", USER_CLOSES_SQL, USER_CLOSES_COLUMNS),+ ("user_actions", USER_ACTIONS_SQL, ACTIONS_COLUMNS),+ ("user_feedback", USER_FEEDBACK_SQL, USER_FEEDBACK_COLUMNS),+ ("user_refunds", USER_REFUNDS_SQL, USER_REFUNDS_COLUMNS),+ ("user_status_changes", USER_STATUS_SQL, USER_STATUS_COLUMNS),+ ("user_pr_events", USER_PR_SQL, USER_PR_COLUMNS),+)++USER_LABEL_STREAM_COLUMNS: dict[str, tuple[str, ...]] = {+ **{name: columns for name, _, columns in USER_LABEL_STREAMS},+ USER_SERVER_ACTIONS_STREAM: USER_SERVER_ACTIONS_COLUMNS,+}++USER_LABEL_DEFAULTS: dict[str, Any] = {+ column: 0 if column.endswith("_count") or column == "total_time_spent_ms" else None+ for columns in USER_LABEL_STREAM_COLUMNS.values()+ for column in columns+}++# The user-grain counterpart of OUTCOME_FIRST_EVENT_COLUMNS, under the same rule.+USER_OUTCOME_FIRST_EVENT_COLUMNS: dict[str, str] = {+ "impression_unit_count": "first_impressed_at",+ "impressed_as_suggested_reviewer_count": "first_impressed_as_suggested_reviewer_at",+ "open_count": "first_opened_at",+ "close_count": "first_closed_at",+ **{count: first for _, count, first in ACTION_TYPES},+ "feedback_positive_count": "first_positive_feedback_at",+ "feedback_negative_count": "first_negative_feedback_at",+ "refund_count": "first_refunded_at",+ "status_resolved_count": "first_status_resolved_at",+ "status_dismissed_count": "first_status_dismissed_at",+ "status_snoozed_count": "first_status_snoozed_at",+ "pr_closed_by_count": "first_pr_closed_by_at",+ "pr_merged_by_count": "first_pr_merged_by_at",+ "claim_count": "first_claimed_at",+ "linked_pr_count": "first_pr_linked_at",+ "note_count": "first_noted_at",+}+++def canonical_stream_rows(rows: list[tuple[Any, ...]], key_width: int = 1) -> dict[tuple[str, ...], tuple[Any, ...]]:+ """One row per canonical key, dropping rows whose report id cannot be a report UUID.++ A row starts with its `key_width` key columns, the report id first. ClickHouse groups on the raw+ client-supplied id, so spelling variants of one UUID arrive as separate rows that canonicalize+ onto the same report. The canonically spelled row wins, so a forged alias can never overwrite a+ real report's aggregates; between aliases the smallest raw id wins, so the choice does not+ depend on ClickHouse's row order. A row with an empty further key (a person) is dropped too."""+ best: dict[tuple[str, ...], tuple[tuple[bool, str], tuple[Any, ...]]] = {}for row in rows:raw_id = str(row[0])report_id = canonical_report_uuid(raw_id)if report_id is None:continue+ other_keys = row[1:key_width]+ if any(value is None or value == "" for value in other_keys):+ continue+ key = (report_id, *(str(value) for value in other_keys))rank = (raw_id != report_id, raw_id)- current = best.get(report_id)+ current = best.get(key)if current is None or rank < current[0]:- best[report_id] = (rank, row)- return {report_id: row for report_id, (_rank, row) in best.items()}+ best[key] = (rank, row)+ return {key: row for key, (_rank, row) in best.items()}def merge_label_streams(- stream_rows: dict[str, list[tuple[Any, ...]]], snapshot_date: datetime.date+ stream_rows: dict[str, list[tuple[Any, ...]]],+ snapshot_date: datetime.date,+ *,+ key_columns: tuple[str, ...] = ("report_id",),+ stream_columns: Mapping[str, tuple[str, ...]] = LABEL_STREAM_COLUMNS,+ defaults: Mapping[str, Any] = LABEL_DEFAULTS,) -> list[dict[str, Any]]:- """Merge the per-stream aggregates (each row `(report_id, *stream_columns)`) into one labels- row per report, filling unseen streams with LABEL_DEFAULTS. Report ids are canonicalized and- rows with impossible ids dropped, so forged or malformed client events cannot mint label-only- training rows."""- merged: dict[str, dict[str, Any]] = {}+ """Merge the per-stream aggregates (each row `(*key_columns, *stream_columns)`) into one labels+ row per key, filling unseen streams with `defaults`. Report ids are canonicalized and rows with+ impossible ids dropped, so forged or malformed client events cannot mint label-only training+ rows. The defaults are the report grain's; the user grain passes its own."""+ key_width = len(key_columns)+ merged: dict[tuple[str, ...], dict[str, Any]] = {}for stream_name, rows in stream_rows.items():- columns = LABEL_STREAM_COLUMNS[stream_name]- for report_id, row in canonical_stream_rows(rows).items():+ columns = stream_columns[stream_name]+ for key, row in canonical_stream_rows(rows, key_width).items():entry = merged.setdefault(- report_id,- {"snapshot_date": snapshot_date, "report_id": report_id, **LABEL_DEFAULTS},+ key,+ {"snapshot_date": snapshot_date, **dict(zip(key_columns, key, strict=True)), **defaults},)- for column, value in zip(columns, row[1:], strict=True):- entry[column] = ensure_utc(value) if column in _TIMESTAMP_LABEL_COLUMNS else value+ for column, value in zip(columns, row[key_width:], strict=True):+ entry[column] = ensure_utc(value) if column.endswith("_at") else valuereturn list(merged.values())diff --git a/products/signals/dags/inbox_ranking/tests/test_dataset.py b/products/signals/dags/inbox_ranking/tests/test_dataset.pyindex d3a3c98d5fef..5b7cd7f10e36 100644--- a/products/signals/dags/inbox_ranking/tests/test_dataset.py+++ b/products/signals/dags/inbox_ranking/tests/test_dataset.py@@ -28,7 +28,9 @@ from products.signals.dags.inbox_ranking.dataset.dag import (LABELS_SCHEMA,MODEL_DATA_SCHEMA,REVIEWERS_SCHEMA,+ USER_INTERACTIONS_SCHEMA,assemble_model_rows,+ assemble_user_interaction_rows,label_provenance_ok,)from products.signals.dags.inbox_ranking.dataset.queries import (@@ -40,6 +42,14 @@ from products.signals.dags.inbox_ranking.dataset.queries import (SERVER_ACTIONS_COLUMNS,STATUS_COLUMNS,STATUS_SQL,+ USER_KEY_COLUMNS,+ USER_LABEL_DEFAULTS,+ USER_LABEL_STREAM_COLUMNS,+ USER_LABEL_STREAMS,+ USER_OUTCOME_FIRST_EVENT_COLUMNS,+ USER_SERVER_ACTIONS_COLUMNS,+ USER_STATUS_COLUMNS,+ USER_STATUS_SQL,hogql_rows,merge_label_streams,region_app_host,@@ -312,20 +322,28 @@ 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():+ "defaults,pairs,schema,uniq_counts",+ [+ # The user counts are uniq aggregates over an outcome the map already pairs, not outcomes of+ # their own.+ (LABEL_DEFAULTS, OUTCOME_FIRST_EVENT_COLUMNS, LABELS_SCHEMA, {"impressed_user_count", "opened_user_count"}),+ (USER_LABEL_DEFAULTS, USER_OUTCOME_FIRST_EVENT_COLUMNS, USER_INTERACTIONS_SCHEMA, set()),+ ],+ ids=["report_grain", "user_grain"],+)+def test_every_outcome_count_is_paired_with_a_first_event_timestamp(defaults, pairs, schema, uniq_counts):# 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"}+ count_columns = {name for name in defaults if name.endswith("_count")}+ assert count_columns == set(pairs) | uniq_counts- 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")+ for count_column, first_event_column in pairs.items():+ assert first_event_column in defaults, count_column+ assert defaults[first_event_column] is None, count_column+ assert schema.field(first_event_column).type == pa.timestamp("us", tz="UTC")@pytest.mark.parametrize(@@ -438,6 +456,56 @@ def test_assembled_rows_match_the_parquet_schema_exactly():assert set(rows[0]) == set(MODEL_DATA_SCHEMA.names)+def test_user_grain_rows_match_the_parquet_schema_exactly():+ merged = merge_label_streams(+ {"user_opens": [(UUID_A, "person-1", 1, T1, T1, "click")]},+ SNAPSHOT_DATE,+ key_columns=USER_KEY_COLUMNS,+ stream_columns=USER_LABEL_STREAM_COLUMNS,+ defaults=USER_LABEL_DEFAULTS,+ )+ rows = assemble_user_interaction_rows(merged, {UUID_A: 2}, {2}, {"person-1": "uuid-1"})+ assert set(rows[0]) == set(USER_INTERACTIONS_SCHEMA.names)+++def test_user_grain_keeps_one_row_per_person_and_only_consented_reports():+ stream_rows: dict[str, list[tuple[Any, ...]]] = {+ "user_opens": [+ (UUID_A, "person-1", 2, T1, T2, "click"),+ # A forged alias of the same report and person must not overwrite the canonical row.+ (UUID_A.upper(), "person-1", 99, T2, T2, "deeplink"),+ (UUID_A, "person-2", 1, T2, T2, "deeplink"),+ (UUID_A, "", 1, T2, T2, "click"),+ (UUID_B, "person-1", 1, T1, T1, "click"),+ ],+ "user_status_changes": [(UUID_A, "person-1", 0, None, 1, T2, 0, None, "analysis_wrong", "agent")],+ }+ merged = merge_label_streams(+ stream_rows,+ SNAPSHOT_DATE,+ key_columns=USER_KEY_COLUMNS,+ stream_columns=USER_LABEL_STREAM_COLUMNS,+ defaults=USER_LABEL_DEFAULTS,+ )++ # UUID_B belongs to a team that has not opted in to AI training, so its person gets no row.+ rows = assemble_user_interaction_rows(merged, {UUID_A: 2, UUID_B: 7}, {2}, {"person-1": "uuid-1"})++ assert [(row["report_id"], row["user_distinct_id"]) for row in rows] == [+ (UUID_A, "person-1"),+ (UUID_A, "person-2"),+ ]+ person_1, person_2 = rows+ assert person_1["open_count"] == 2+ assert person_1["first_open_method"] == "click"+ assert person_1["status_dismissed_count"] == 1+ assert person_1["first_dismissal_actor_kind"] == "agent"+ assert person_1["user_uuid"] == "uuid-1"+ assert person_1["report_team_id"] == 2+ assert person_2["status_dismissed_count"] == 0+ assert person_2["user_uuid"] is None++class TestSpineInclusion(BaseTest):def _report(self, status, *, promoted_at=None, created_at=BEFORE_CUTOFF):report = SignalReport.objects.create(team=self.team, status=status, title="t", summary="s")@@ -623,6 +691,36 @@ class TestServerActions(BaseTest):assert row["first_pr_linked_at"] is Noneassert row["slack_discussion_count"] == 1+ def test_user_actions_count_for_the_person_who_wrote_or_saw_them(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")+ for kind in ("user", "agent", "task"):+ SignalReportArtefact.objects.create(+ team=self.team,+ report=report,+ type=SignalReportArtefact.ArtefactType.NOTE,+ content="{}",+ actor_kind=kind,+ created_by=self.user,+ )+ view = SignalReportAction.all_teams.create(+ team=self.team,+ report=report,+ user=self.user,+ type=SignalReportAction.ActionType.VIEW,+ count=5,+ last_at=snapshot_end + datetime.timedelta(hours=1),+ )++ rows = dag.user_server_action_rows([str(report.id)], snapshot_end)++ assert len(rows) == 1+ row = dict(zip(("report_id", "user_distinct_id", *USER_SERVER_ACTIONS_COLUMNS), rows[0], strict=True))+ assert row["user_distinct_id"] == self.user.distinct_id+ assert row["note_count"] == 2+ assert row["first_viewed_at"] == view.first_at+ assert row["first_read_at"] is None+class TestImpressionsStream(ClickhouseTestMixin, BaseTest):@parameterized.expand([("labeled_ids", LABELED_REPORT_IDS_SQL), ("impressions", IMPRESSIONS_SQL)])@@ -824,6 +922,109 @@ class TestStatusStream(ClickhouseTestMixin, BaseTest):assert row["wrong_dismissal_count"] == (0 if row["status_event_team_id"] == self.team.id else 1)+class TestUserGrainStreams(ClickhouseTestMixin, BaseTest):+ def _transition(+ self,+ when: datetime.datetime,+ status: str,+ actor_distinct_id: str | None,+ actor_kind: str | None,+ *,+ reason: str | None = None,+ team_id: int | None = None,+ ) -> None:+ properties: dict[str, Any] = {+ "report_id": UUID_A,+ "previous_status": "ready",+ "status": status,+ "dismissal_reason": reason,+ "team_id": str(team_id or self.team.id),+ }+ if actor_kind is not None:+ properties |= {"actor_kind": actor_kind, "actor_distinct_id": actor_distinct_id}+ _create_event(+ team=self.team,+ event="signal_report_status_changed",+ distinct_id="team",+ timestamp=when,+ properties=properties,+ )++ def _status_rows(self) -> dict[str, dict[str, Any]]:+ rows = hogql_rows(USER_STATUS_SQL, team=self.team, query_type="test", snapshot_end=SNAPSHOT_END)+ return {row[1]: dict(zip(USER_STATUS_COLUMNS, row[2:], strict=True)) for row in rows}++ def test_every_user_stream_reads_its_person_from_its_source(self):+ events: list[tuple[str, str, dict[str, Any]]] = [+ (+ "Inbox reports impressed",+ "person-1",+ {"impressions": [{"report_id": UUID_A, "rank": 2, "is_suggested_reviewer": True}]},+ ),+ ("Inbox report opened", "person-1", {"report_id": UUID_A, "open_method": "click"}),+ ("Inbox report closed", "person-1", {"report_id": UUID_A, "time_spent_ms": 1500}),+ ("Inbox report action", "person-1", {"report_id": UUID_A, "action_type": "dismiss"}),+ ("Inbox report feedback", "person-1", {"report_id": UUID_A, "sentiment": "positive"}),+ ("signals_pr_refund_created", "person-1", {"report_id": UUID_A, "refund_id": "refund-1"}),+ (+ "signals_pr_refund_created",+ "person-2",+ {"report_id": UUID_A, "refund_id": "r2", "was_impersonated": True},+ ),+ (+ "signal_report_status_changed",+ "team",+ {+ "report_id": UUID_A,+ "previous_status": "ready",+ "status": "suppressed",+ "team_id": str(self.team.id),+ "actor_kind": "user",+ "actor_distinct_id": "person-1",+ },+ ),+ ("pr_closed", "team", {"signal_report_id": UUID_A, "pr_closed_by_distinct_id": "person-1"}),+ ("pr_merged", "team", {"signal_report_id": UUID_A}),+ ]+ for event, distinct_id, properties in events:+ _create_event(team=self.team, event=event, distinct_id=distinct_id, timestamp=T1, properties=properties)++ for stream_name, sql, columns in USER_LABEL_STREAMS:+ rows = hogql_rows(sql, team=self.team, query_type="test", snapshot_end=SNAPSHOT_END)+ # The impersonated refund and the merge with no mapped merger name nobody.+ assert [row[:2] for row in rows] == [(UUID_A, "person-1")], stream_name+ assert len(rows[0]) == 2 + len(columns), stream_name++ def test_a_person_gets_their_own_dismissal_and_an_agent_acting_for_them_is_named(self):+ self._transition(T1, "suppressed", "person-1", "user", reason="analysis_wrong")+ self._transition(T2, "suppressed", "person-2", "agent", reason="already_fixed")+ self._transition(T2 + datetime.timedelta(hours=1), "resolved", None, "system")+ # An event from before the actor keys shipped names nobody.+ self._transition(T2 + datetime.timedelta(hours=2), "resolved", None, None)++ rows = self._status_rows()++ assert set(rows) == {"person-1", "person-2"}+ assert rows["person-1"]["status_dismissed_count"] == 1+ assert rows["person-1"]["first_status_dismissed_at"] == T1+ assert rows["person-1"]["first_status_dismissal_reason"] == "analysis_wrong"+ assert rows["person-1"]["first_dismissal_actor_kind"] == "user"+ assert rows["person-1"]["status_resolved_count"] == 0+ assert rows["person-2"]["first_dismissal_actor_kind"] == "agent"++ def test_no_user_status_column_reads_an_event_from_another_tenant(self):+ statuses = ("resolved", "suppressed", "potential")+ for offset, status in enumerate(statuses):+ self._transition(T2 + datetime.timedelta(hours=offset), status, "person-1", "user")+ genuine_only = self._status_rows()++ for status in statuses:+ for actor in ("person-1", "person-2"):+ self._transition(T1, status, actor, "user", reason="analysis_wrong", team_id=999)++ assert self._status_rows() == genuine_only++def _run_embeddings_asset(monkeypatch, asset, rows, consent_team_ids=frozenset({2})):"""Run one embeddings asset against a stubbed ClickHouse and S3, and return what it wrote."""captured: dict[str, Any] = {}@@ -902,10 +1103,11 @@ def test_the_leaf_snapshots_run_in_the_job_without_feeding_the_join():dag.inbox_report_model_data,dag.inbox_report_title_embeddings,dag.inbox_report_reviewers,+ dag.inbox_user_report_interactions,])model_data_deps = {key.path[-1] for key in dag.inbox_report_model_data.keys_by_input_name.values()}- for leaf in (dag.TITLE_EMBEDDINGS_TABLE, dag.REVIEWERS_TABLE):+ for leaf in (dag.TITLE_EMBEDDINGS_TABLE, dag.REVIEWERS_TABLE, dag.USER_INTERACTIONS_TABLE):assert dagster.AssetKey(leaf) in selectionassert leaf not in model_data_deps