Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): snapshot suggested reviewers per report in the inbox ranking dataset (#115079)

posthog[bot]237c688f3fc7
diff --git a/posthog/dags/locations/signals.py b/posthog/dags/locations/signals.py
index 785e4c5e7746..a59dec172d37 100644
--- a/posthog/dags/locations/signals.py
+++ b/posthog/dags/locations/signals.py
@@ -20,6 +20,7 @@ if is_inbox_ranking_registered():
inbox_ranking_dataset.inbox_report_labels,
inbox_ranking_dataset.inbox_report_model_data,
inbox_ranking_dataset.inbox_report_title_embeddings,
+ inbox_ranking_dataset.inbox_report_reviewers,
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/README.md b/products/signals/dags/inbox_ranking/README.md
index ee4960a52777..48dfddeefec7 100644
--- a/products/signals/dags/inbox_ranking/README.md
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -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 six 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 seven assets on one daily partition, each a Parquet object in S3:
```text
s3://<bucket>/<prefix>/
@@ -32,13 +32,20 @@ s3://<bucket>/<prefix>/
│ ├── dt=YYYY-MM-DD/ # materialized join of the three (the training table)
│ └── 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_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
```
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`.
`inbox_report_title_embeddings` is a report-grain leaf. It snapshots the `title_v1` rendering the same way `inbox_report_embeddings` snapshots `title_summary_v1`, and nothing joins it: the training side pairs the two by `report_id` when it measures one rendering against the other, and each carries its own `embedding_inserted_at`, because a summary-only edit re-emits only `title_summary_v1`. Its dependency on `inbox_report_model_data` is for ordering, not data — it holds a vector per live report, so it runs last and alone in the run pod. That edge has a cost: a failed join, or a run that hits the job's runtime cap, skips the title snapshot for the day, and the schedule never revisits a day. Repair such a gap with a single-asset backfill while the source rows are inside their 3-month TTL.
+`inbox_report_reviewers` is a (report, reviewer) leaf for user–report affinity modeling. It holds one row per entry of each spine report's current `SignalReportSuggestedReviewer` index, for teams that allow AI training. Nothing joins it, and its object carries its own schema version (`REVIEWERS_SCHEMA_VERSION`), so a failure here does not fail the training table.
+
+- `user_distinct_id` comes from `user_uuid` when that uuid names a member of the report team's organization. Otherwise it comes from `github_login`, through the same GitHub identity mapping the `pr_merged` and `pr_closed` attribution uses. `identity_resolution` says which one matched (`user_uuid`, `github_login` or `unresolved`).
+- An entry that maps to no member stays as a row with a null `user_distinct_id`, so a reviewer with no history is counted and not dropped.
+- **The asset is current-state-only.** The index is rebuilt in full on every reviewer change, and reviewer artefacts can be edited in place or deleted, so no earlier set can be rebuilt. A forward-run partition holds the set at run time (at most a few hours after the cutoff). A backfilled partition holds today's set, flagged by `features_observed_at`. History starts on the day the asset first ran.
+
### Partition semantics
- Partition `dt=D` snapshots the eligible report inventory (promoted before `D+1 00:00 UTC`, or referenced by any label event before it). Every label aggregate is bounded `event_time < D+1 00:00 UTC`.
diff --git a/products/signals/dags/inbox_ranking/dataset/dag.py b/products/signals/dags/inbox_ranking/dataset/dag.py
index 8fefae593e1a..104a705b36dd 100644
--- a/products/signals/dags/inbox_ranking/dataset/dag.py
+++ b/products/signals/dags/inbox_ranking/dataset/dag.py
@@ -1,6 +1,6 @@
"""Daily modeling dataset for the Self-driving Inbox report-ranking model.
-Six assets on one daily partition, each writing Parquet under the configured S3 prefix:
+Seven assets on one daily partition, each writing Parquet under the configured S3 prefix:
inbox_report_state/v1/dt=D/ Postgres spine + report-state columns
inbox_report_embeddings/v1/dt=D/ report_id -> small-1536 vector as of snapshot end
@@ -8,11 +8,14 @@ Six assets on one daily partition, each writing Parquet under the configured S3
inbox_report_model_data/v1/dt=D/ materialized join of the three, plus a rewritten latest/
inbox_signal_embeddings/v1/dt=D/ one row per signal emission during D, for the group-level model
inbox_report_title_embeddings/v1/dt=D/ the same shape, for the title-only rendering
+ inbox_report_reviewers/v1/dt=D/ one row per suggested reviewer of each spine report
The first four are report grain and feed one table. inbox_signal_embeddings is signal grain and is
read on its own, joined to the others by report_id at training time. inbox_report_title_embeddings
is a report-grain leaf: nothing joins it, and the training side pairs it to inbox_report_embeddings
-by report_id when it measures one rendering against the other.
+by 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.
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,
@@ -43,7 +46,11 @@ Point-in-time caveats, per source:
values: promoted_at is cleared on suppression and snooze, so a report promoted before the cutoff
and suppressed after it drops out of the spine unless a label event referenced it in time. A
spine derived from immutable promotion history (the status telemetry carries promoted_at) is the
- fix, and is a v2 change.
+ fix, and is a v2 change;
+- suggested reviewers are current-state-only too. The source index is rebuilt in full on every
+ reviewer change, and the reviewer artefacts can be edited in place or deleted, so no record of an
+ earlier set survives. A forward-run partition holds the set at run time, and a backfilled
+ partition holds today's set, flagged by features_observed_at.
"""
import json
@@ -60,8 +67,15 @@ from posthog import settings
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tag_queries
from posthog.dags.common import dagster_tags
-
-from products.signals.backend.models import SignalReport, SignalReportAction, SignalReportArtefact
+from posthog.dataclasses import frozen
+from posthog.models import OrganizationMembership, Team, User
+
+from products.signals.backend.models import (
+ SignalReport,
+ SignalReportAction,
+ SignalReportArtefact,
+ SignalReportSuggestedReviewer,
+)
from products.signals.backend.ranking.inventory import spine_report_filter
from products.signals.backend.report_embeddings import (
EMBEDDING_DOCUMENT_TYPE,
@@ -69,6 +83,7 @@ from products.signals.backend.report_embeddings import (
EMBEDDING_RENDERING_TITLE,
EMBEDDING_RENDERING_TITLE_SUMMARY,
)
+from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users
from products.signals.backend.signal_metadata import (
SIGNAL_DOCUMENT_PRODUCT,
SIGNAL_DOCUMENT_RENDERING,
@@ -126,6 +141,11 @@ TITLE_EMBEDDINGS_TABLE = "inbox_report_title_embeddings"
LABELS_TABLE = "inbox_report_labels"
MODEL_DATA_TABLE = "inbox_report_model_data"
SIGNAL_EMBEDDINGS_TABLE = "inbox_signal_embeddings"
+REVIEWERS_TABLE = "inbox_report_reviewers"
+
+# 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.
+REVIEWERS_SCHEMA_VERSION = 1
COMMON_ASSET_KWARGS: dict[str, Any] = {
"group_name": "inbox_ranking",
@@ -209,6 +229,21 @@ _SIGNAL_EMBEDDING_FIELDS: list[tuple[str, pa.DataType]] = [
]
SIGNAL_EMBEDDINGS_SCHEMA = pa.schema(_SIGNAL_EMBEDDING_FIELDS)
+_REVIEWER_FIELDS: list[tuple[str, pa.DataType]] = [
+ ("snapshot_date", pa.date32()),
+ ("features_observed_at", _TIMESTAMP),
+ ("report_id", pa.string()),
+ ("report_team_id", pa.int64()),
+ ("artefact_id", pa.string()),
+ ("artefact_created_at", _TIMESTAMP),
+ ("artefact_actor_kind", pa.string()),
+ ("github_login", pa.string()),
+ ("user_uuid", pa.string()),
+ ("user_distinct_id", pa.string()),
+ ("identity_resolution", pa.string()),
+]
+REVIEWERS_SCHEMA = pa.schema(_REVIEWER_FIELDS)
+
# What makes one emission distinct from another, so a re-run can tell a row it already archived from
# a genuinely new one. embedding_inserted_at is the version: the source keys a signal by
# (team_id, document_id) and distinguishes its versions by inserted_at.
@@ -581,6 +616,154 @@ def inbox_report_state(context: dagster.AssetExecutionContext) -> None:
)
+@frozen
+class MemberDistinctIds:
+ by_uuid: dict[str, str]
+ by_login: dict[str, str]
+
+
+def _member_distinct_ids(
+ team_id: int, user_uuids: Collection[str], github_logins: Collection[str]
+) -> MemberDistinctIds:
+ """Distinct ids of the team organization's members, keyed by uuid and by lowercased login.
+
+ A uuid that names no member of that organization does not resolve: an artefact can be edited
+ through the API, so its uuid is claimed and not proven.
+ """
+ by_uuid: dict[str, str] = {}
+ org_id = Team.objects.filter(id=team_id).values_list("organization_id", flat=True).first()
+ if user_uuids and org_id is not None:
+ by_uuid = {
+ str(user_uuid): str(distinct_id)
+ for user_uuid, distinct_id in User.objects.filter(
+ uuid__in=sorted(user_uuids),
+ id__in=OrganizationMembership.objects.filter(organization_id=org_id).values("user_id"),
+ ).values_list("uuid", "distinct_id")
+ }
+ by_login = {
+ login: str(user.distinct_id)
+ for login, user in resolve_org_github_login_to_users(team_id, github_logins).items()
+ }
+ return MemberDistinctIds(by_uuid=by_uuid, by_login=by_login)
+
+
+def reviewer_rows(
+ report_teams: Mapping[str, int],
+ *,
+ snapshot_date: datetime.date,
+ features_observed_at: datetime.datetime,
+) -> list[dict[str, Any]]:
+ """One row per entry of each report's current reviewer index, for the reports given.
+
+ `user_distinct_id` comes from the uuid when it names a member, and from the login otherwise.
+ An entry that maps to no member stays as a row with a null distinct id, so a reviewer with no
+ history is counted and not dropped.
+ """
+ entries_by_team: dict[int, list[dict[str, Any]]] = {}
+ for chunk in _chunked(sorted(report_teams)):
+ for entry in (
+ SignalReportSuggestedReviewer.all_teams.filter(report_id__in=chunk)
+ .values(
+ "report_id",
+ "team_id",
+ "artefact_id",
+ "artefact__created_at",
+ "artefact__actor_kind",
+ "github_login",
+ "user_uuid",
+ )
+ .iterator(chunk_size=2000)
+ ):
+ entries_by_team.setdefault(entry["team_id"], []).append(
+ {
+ "snapshot_date": snapshot_date,
+ "features_observed_at": features_observed_at,
+ "report_id": str(entry["report_id"]),
+ "report_team_id": entry["team_id"],
+ "artefact_id": str(entry["artefact_id"]),
+ "artefact_created_at": ensure_utc(entry["artefact__created_at"]),
+ "artefact_actor_kind": entry["artefact__actor_kind"],
+ "github_login": entry["github_login"].lower() if entry["github_login"] else None,
+ "user_uuid": str(entry["user_uuid"]) if entry["user_uuid"] else None,
+ }
+ )
+
+ rows: list[dict[str, Any]] = []
+ for team_id, team_rows in entries_by_team.items():
+ members = _member_distinct_ids(
+ team_id,
+ {row["user_uuid"] for row in team_rows if row["user_uuid"]},
+ {row["github_login"] for row in team_rows if row["github_login"]},
+ )
+ for row in team_rows:
+ if row["user_uuid"] in members.by_uuid:
+ row["user_distinct_id"], row["identity_resolution"] = members.by_uuid[row["user_uuid"]], "user_uuid"
+ elif row["github_login"] in members.by_login:
+ row["user_distinct_id"], row["identity_resolution"] = (
+ members.by_login[row["github_login"]],
+ "github_login",
+ )
+ else:
+ row["user_distinct_id"], row["identity_resolution"] = None, "unresolved"
+ rows.append(row)
+ rows.sort(
+ key=lambda row: (
+ row["report_id"],
+ row["artefact_created_at"],
+ row["github_login"] or "",
+ row["user_uuid"] or "",
+ )
+ )
+ return rows
+
+
[email protected](name=REVIEWERS_TABLE, **COMMON_ASSET_KWARGS)
+def inbox_report_reviewers(context: dagster.AssetExecutionContext) -> None:
+ """The suggested reviewers of every spine report, for the (report, reviewer) affinity model.
+
+ A leaf with its own schema version: nothing joins it, so a failure here leaves the training
+ table alone. The source is current-state-only, so a backfilled partition carries today's set,
+ flagged by features_observed_at. Only forward-run partitions record the set near the cutoff.
+ """
+ if skip_unconfigured(context):
+ return
+ partition_key = context.partition_key
+ _, snapshot_end = snapshot_bounds(partition_key)
+ snapshot_date = datetime.date.fromisoformat(partition_key)
+ features_observed_at = datetime.datetime.now(datetime.UTC)
+
+ consent_team_ids = training_consent_team_ids()
+ spine_teams = {
+ str(report_id): team_id
+ for report_id, team_id in SignalReport.objects.filter(spine_report_filter(snapshot_end)).values_list(
+ "id", "team_id"
+ )
+ }
+ report_teams = {report_id: team_id for report_id, team_id in spine_teams.items() if team_id in consent_team_ids}
+ rows = reviewer_rows(report_teams, snapshot_date=snapshot_date, features_observed_at=features_observed_at)
+
+ bucket = dataset_bucket()
+ key = partition_object_key(settings.INBOX_RANKING_DATASET_S3_PREFIX, REVIEWERS_TABLE, partition_key)
+ write_parquet(
+ s3_client(),
+ bucket,
+ key,
+ pa.Table.from_pylist(rows, schema=REVIEWERS_SCHEMA),
+ schema_version=REVIEWERS_SCHEMA_VERSION,
+ )
+ context.add_output_metadata(
+ {
+ "rows": dagster.MetadataValue.int(len(rows)),
+ "reports_with_reviewers": dagster.MetadataValue.int(len({row["report_id"] for row in rows})),
+ "unresolved_rows": dagster.MetadataValue.int(
+ sum(1 for row in rows if row["identity_resolution"] == "unresolved")
+ ),
+ "excluded_no_training_consent_reports": dagster.MetadataValue.int(len(spine_teams) - len(report_teams)),
+ "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),
+ }
+ )
+
+
def _snapshot_report_embeddings(
context: dagster.AssetExecutionContext, table: str, rendering: str, query_type: str
) -> None:
@@ -1052,6 +1235,7 @@ inbox_ranking_dataset_job = dagster.define_asset_job(
LABELS_TABLE,
MODEL_DATA_TABLE,
TITLE_EMBEDDINGS_TABLE,
+ REVIEWERS_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 — and
diff --git a/products/signals/dags/inbox_ranking/tests/test_dataset.py b/products/signals/dags/inbox_ranking/tests/test_dataset.py
index 1bedea0f6942..d3a3c98d5fef 100644
--- a/products/signals/dags/inbox_ranking/tests/test_dataset.py
+++ b/products/signals/dags/inbox_ranking/tests/test_dataset.py
@@ -8,11 +8,17 @@ from unittest.mock import patch
import dagster
import pyarrow as pa
from parameterized import parameterized
+from social_django.models import UserSocialAuth
-from posthog.models import Organization, Team
+from posthog.models import Organization, Team, User
from products.event_definitions.backend.models.property_definition import PropertyDefinition
-from products.signals.backend.models import SignalReport, SignalReportAction, SignalReportArtefact
+from products.signals.backend.models import (
+ SignalReport,
+ SignalReportAction,
+ SignalReportArtefact,
+ SignalReportSuggestedReviewer,
+)
from products.signals.backend.ranking.inventory import spine_report_filter
from products.signals.backend.report_embeddings import EMBEDDING_RENDERING_TITLE, EMBEDDING_RENDERING_TITLE_SUMMARY
from products.signals.dags.inbox_ranking import common
@@ -21,6 +27,7 @@ from products.signals.dags.inbox_ranking.dataset.dag import (
EMBEDDINGS_SCHEMA,
LABELS_SCHEMA,
MODEL_DATA_SCHEMA,
+ REVIEWERS_SCHEMA,
assemble_model_rows,
label_provenance_ok,
)
@@ -485,6 +492,88 @@ class TestSpineInclusion(BaseTest):
assert metadata["excluded_no_training_consent_teams"].value == 2
+class TestReviewerSnapshot(BaseTest):
+ def _report_with_reviewers(self, team: Team, entries: list[tuple[str | None, str | None]]) -> str:
+ report = SignalReport.objects.create(team=team, status=SignalReport.Status.READY, title="t", summary="s")
+ SignalReport.objects.filter(id=report.id).update(created_at=BEFORE_CUTOFF)
+ artefact = SignalReportArtefact.objects.create(
+ team=team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content="[]",
+ actor_kind="task",
+ )
+ for user_uuid, github_login in entries:
+ SignalReportSuggestedReviewer.all_teams.create(
+ team=team, report=report, artefact=artefact, user_uuid=user_uuid, github_login=github_login
+ )
+ return str(report.id)
+
+ def test_rows_resolve_members_by_uuid_or_login_and_keep_unresolved_reviewers(self):
+ by_login = User.objects.create_and_join(self.organization, "[email protected]", None)
+ UserSocialAuth.objects.create(user=by_login, provider="github", uid="gh-1", extra_data={"login": "Octo-Member"})
+ outsider = User.objects.create(email="[email protected]", distinct_id="outsider-distinct-id")
+ report_id = self._report_with_reviewers(
+ self.team,
+ [
+ (str(self.user.uuid), None),
+ (None, "octo-member"),
+ (None, "nobody-here"),
+ # A uuid outside the organization is claimed, not proven, so it must not resolve.
+ (str(outsider.uuid), None),
+ ],
+ )
+ self._report_with_reviewers(self.team, [(None, "not-in-the-snapshot")])
+
+ rows = dag.reviewer_rows(
+ {report_id: self.team.id}, snapshot_date=SNAPSHOT_DATE, features_observed_at=AFTER_SNAPSHOT_END
+ )
+
+ assert all(set(row) == set(REVIEWERS_SCHEMA.names) for row in rows)
+ resolved = {(row["user_uuid"] or row["github_login"]): row for row in rows}
+ assert set(resolved) == {str(self.user.uuid), "octo-member", "nobody-here", str(outsider.uuid)}
+ assert (
+ resolved[str(self.user.uuid)]["user_distinct_id"],
+ resolved[str(self.user.uuid)]["identity_resolution"],
+ ) == (
+ self.user.distinct_id,
+ "user_uuid",
+ )
+ assert (resolved["octo-member"]["user_distinct_id"], resolved["octo-member"]["identity_resolution"]) == (
+ by_login.distinct_id,
+ "github_login",
+ )
+ for unresolved in ("nobody-here", str(outsider.uuid)):
+ assert resolved[unresolved]["user_distinct_id"] is None
+ assert resolved[unresolved]["identity_resolution"] == "unresolved"
+ assert {row["artefact_actor_kind"] for row in rows} == {"task"}
+ assert {row["report_team_id"] for row in rows} == {self.team.id}
+
+ def test_snapshot_keeps_only_teams_opted_in_to_ai_training_and_stamps_the_run_time(self):
+ self.organization.is_ai_training_opted_in = True
+ self.organization.save()
+ consenting = self._report_with_reviewers(self.team, [(None, "someone")])
+ organization = Organization.objects.create(name="no-consent", is_ai_training_opted_in=False)
+ self._report_with_reviewers(Team.objects.create(organization=organization), [(None, "someone")])
+ written: dict[str, Any] = {}
+
+ with (
+ patch.object(dag, "skip_unconfigured", lambda context: False),
+ patch.object(dag, "s3_client", lambda: None),
+ patch.object(
+ dag, "write_parquet", lambda client, bucket, key, table, **kwargs: written.update(table=table, **kwargs)
+ ),
+ dagster.build_asset_context(partition_key=SNAPSHOT_DATE.isoformat()) as context,
+ ):
+ dag.inbox_report_reviewers(context)
+
+ table = written["table"]
+ assert table.column("report_id").to_pylist() == [consenting]
+ # A re-run of a past day carries the run time, which is how a reader tells a backfill apart.
+ assert table.column("features_observed_at").to_pylist()[0] > SNAPSHOT_END
+ assert written["schema_version"] == dag.REVIEWERS_SCHEMA_VERSION
+
+
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)
@@ -803,7 +892,7 @@ def test_embeddings_are_read_only_for_teams_opted_in_to_ai_training(monkeypatch,
assert written["table"].num_rows == 0
-def test_the_title_snapshot_is_a_leaf_ordered_after_the_join():
+def test_the_leaf_snapshots_run_in_the_job_without_feeding_the_join():
selection = dag.inbox_ranking_dataset_job.selection.resolve(
[
dag.inbox_report_state,
@@ -812,12 +901,13 @@ def test_the_title_snapshot_is_a_leaf_ordered_after_the_join():
dag.inbox_report_labels,
dag.inbox_report_model_data,
dag.inbox_report_title_embeddings,
+ dag.inbox_report_reviewers,
]
)
- assert dagster.AssetKey(dag.TITLE_EMBEDDINGS_TABLE) in selection
-
model_data_deps = {key.path[-1] for key in dag.inbox_report_model_data.keys_by_input_name.values()}
- assert dag.TITLE_EMBEDDINGS_TABLE not in model_data_deps
+ for leaf in (dag.TITLE_EMBEDDINGS_TABLE, dag.REVIEWERS_TABLE):
+ assert dagster.AssetKey(leaf) in selection
+ assert leaf not in model_data_deps
title_deps = {key.path[-1] for key in dag.inbox_report_title_embeddings.keys_by_input_name.values()}
assert title_deps == {dag.MODEL_DATA_TABLE}