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.

fix(signals): scope inbox user interactions to tenant and org members (#115390)

posthog[bot]3276320b7048
diff --git a/posthog/dags/slack_alerts.py b/posthog/dags/slack_alerts.py
index 7d3b1b9e8d94..d1025e6f42c7 100644
--- a/posthog/dags/slack_alerts.py
+++ b/posthog/dags/slack_alerts.py
@@ -114,6 +114,7 @@ ASSET_NAME_PREFIX_OWNERS: tuple[tuple[str, JobOwners], ...] = (
("inbox_report_", JobOwners.TEAM_SELF_DRIVING),
("inbox_signal_", JobOwners.TEAM_SELF_DRIVING),
("inbox_ranking_", JobOwners.TEAM_SELF_DRIVING),
+ ("inbox_user_", JobOwners.TEAM_SELF_DRIVING),
)
diff --git a/posthog/dags/tests/test_slack_alerts.py b/posthog/dags/tests/test_slack_alerts.py
index 4b3f020a388c..e3fd16958358 100644
--- a/posthog/dags/tests/test_slack_alerts.py
+++ b/posthog/dags/tests/test_slack_alerts.py
@@ -2,6 +2,7 @@ from unittest import mock
import dagster
from dagster import DagsterRunStatus
+from parameterized import parameterized
from slack_sdk.errors import SlackApiError
from posthog.dags.common import JobOwners
@@ -85,34 +86,20 @@ class TestSlackAlertsRouting:
assert result == JobOwners.TEAM_WEB_ANALYTICS.value
- def test_asset_job_with_inbox_report_steps_routes_to_self_driving(self):
- mock_run = mock.MagicMock(spec=dagster.DagsterRun)
- mock_run.job_name = "__ASSET_JOB"
- mock_run.tags = {}
-
- error_message = "Execution of run for \"__ASSET_JOB\" failed. Steps failed: ['inbox_report_labels']."
-
- result = get_job_owner_for_alert(mock_run, error_message)
-
- assert result == JobOwners.TEAM_SELF_DRIVING.value
-
- def test_asset_job_with_inbox_signal_steps_routes_to_self_driving(self):
- mock_run = mock.MagicMock(spec=dagster.DagsterRun)
- mock_run.job_name = "__ASSET_JOB"
- mock_run.tags = {}
-
- error_message = "Execution of run for \"__ASSET_JOB\" failed. Steps failed: ['inbox_signal_embeddings']."
-
- result = get_job_owner_for_alert(mock_run, error_message)
-
- assert result == JobOwners.TEAM_SELF_DRIVING.value
-
- def test_asset_job_with_inbox_ranking_steps_routes_to_self_driving(self):
+ @parameterized.expand(
+ [
+ ("inbox_report_labels",),
+ ("inbox_signal_embeddings",),
+ ("inbox_ranking_model_candidate",),
+ ("inbox_user_report_interactions",),
+ ]
+ )
+ def test_asset_job_with_inbox_steps_routes_to_self_driving(self, step):
mock_run = mock.MagicMock(spec=dagster.DagsterRun)
mock_run.job_name = "__ASSET_JOB"
mock_run.tags = {}
- error_message = "Execution of run for \"__ASSET_JOB\" failed. Steps failed: ['inbox_ranking_model_candidate']."
+ error_message = f"Execution of run for \"__ASSET_JOB\" failed. Steps failed: ['{step}']."
result = get_job_owner_for_alert(mock_run, error_message)
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.md
index 8951d8080c0b..9d6f2b2a0667 100644
--- a/products/signals/dags/inbox_ranking/README.md
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -93,6 +93,7 @@ Point-in-time contract:
- **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.
+- **Only members of the report's organization get rows.** The person lookups read every `User` in the region, so after the merge the asset drops each pair whose `user_distinct_id` is not a member of the report team's organization. The `non_member_pairs` metadata value counts these pairs.
| Columns | Source | Person key |
| -------------------------------------------------------------- | -------------------------------------------- | ---------------------------------------------------------- |
@@ -111,9 +112,9 @@ 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 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. When that tenant is missing or is not the report's team, the pair keeps its other streams and gets default status columns, as `label_provenance_ok` does for the report grain. The `status_tenant_mismatch_pairs` metadata value counts these pairs.
- **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.
+- **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, and the person must be a member of the report's organization, but nothing proves that the person saw the report.
- **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
diff --git a/products/signals/dags/inbox_ranking/dataset/dag.py b/products/signals/dags/inbox_ranking/dataset/dag.py
index 264e216e7436..e9dbfbd3802f 100644
--- a/products/signals/dags/inbox_ranking/dataset/dag.py
+++ b/products/signals/dags/inbox_ranking/dataset/dag.py
@@ -61,6 +61,7 @@ import json
import datetime
from collections.abc import Collection, Iterator, Mapping
from typing import Any, cast
+from uuid import UUID
from django.db.models import Count, Min
@@ -145,6 +146,8 @@ from products.signals.dags.inbox_ranking.dataset.queries import (
USER_LABEL_STREAMS,
USER_SERVER_ACTIONS_COLUMNS,
USER_SERVER_ACTIONS_STREAM,
+ USER_STATUS_STREAM,
+ canonical_report_uuid,
etl_workload,
hogql_rows,
labels_team,
@@ -685,21 +688,69 @@ def _report_teams(report_ids: list[str], snapshot_end: datetime.datetime) -> dic
return teams
+@frozen
+class ScopedRows:
+ rows: list[tuple[Any, ...]]
+ dropped: int
+
+
+def scoped_user_status_rows(rows: list[tuple[Any, ...]], report_teams: Mapping[str, int]) -> ScopedRows:
+ """Strip the trailing `status_event_team_id` from each `USER_STATUS_SQL` row, and drop the rows
+ whose tenant is missing or is not the report's team, as `label_provenance_ok` does for the report
+ grain. The pair keeps its other streams. A report outside this region's Postgres is not counted
+ here, because the assembler drops all of its pairs."""
+ kept: list[tuple[Any, ...]] = []
+ dropped = 0
+ for row in rows:
+ *values, status_event_team_id = row
+ report_id = canonical_report_uuid(str(row[0]))
+ team_id = report_teams.get(report_id) if report_id is not None else None
+ if team_id is not None and status_event_team_id != team_id:
+ dropped += 1
+ continue
+ kept.append(tuple(values))
+ return ScopedRows(rows=kept, dropped=dropped)
+
+
+def org_member_distinct_ids(team_ids: Collection[int], distinct_ids: list[str]) -> dict[int, set[str]]:
+ """The given distinct ids that name a member of each team's organization, keyed by team id. One
+ query per chunk of distinct ids covers every organization."""
+ team_orgs = dict(Team.objects.filter(id__in=sorted(team_ids)).values_list("id", "organization_id"))
+ by_org: dict[UUID, set[str]] = {}
+ for chunk in _chunked(distinct_ids):
+ for org_id, distinct_id in OrganizationMembership.objects.filter(
+ organization_id__in=set(team_orgs.values()), user__distinct_id__in=chunk
+ ).values_list("organization_id", "user__distinct_id"):
+ by_org.setdefault(org_id, set()).add(str(distinct_id))
+ return {team_id: by_org.get(org_id, set()) for team_id, org_id in team_orgs.items()}
+
+
+@frozen
+class UserInteractionRows:
+ rows: list[dict[str, Any]]
+ non_member_pairs: int
+
+
def assemble_user_interaction_rows(
merged_rows: list[dict[str, Any]],
report_teams: Mapping[str, int],
consent_team_ids: Collection[int],
+ team_members: Mapping[int, Collection[str]],
user_uuids: Mapping[str, str],
-) -> list[dict[str, Any]]:
+) -> UserInteractionRows:
"""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."""
+ training, and whose person is a member of that team's organization. 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]] = []
+ non_member_pairs = 0
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
+ if merged["user_distinct_id"] not in team_members.get(team_id, ()):
+ non_member_pairs += 1
+ continue
rows.append(
{
**merged,
@@ -707,7 +758,10 @@ def assemble_user_interaction_rows(
"user_uuid": user_uuids.get(merged["user_distinct_id"]),
}
)
- return sorted(rows, key=lambda row: (row["report_id"], row["user_distinct_id"]))
+ return UserInteractionRows(
+ rows=sorted(rows, key=lambda row: (row["report_id"], row["user_distinct_id"])),
+ non_member_pairs=non_member_pairs,
+ )
@dagster.asset(name=STATE_TABLE, **COMMON_ASSET_KWARGS)
@@ -1280,7 +1334,8 @@ def inbox_user_report_interactions(context: dagster.AssetExecutionContext) -> No
"""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.
+ is `User.distinct_id`, and a person who is not a member of the report team's organization gets
+ no row.
"""
if skip_unconfigured(context):
return
@@ -1309,6 +1364,8 @@ def inbox_user_report_interactions(context: dagster.AssetExecutionContext) -> No
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)
+ scoped_status = scoped_user_status_rows(stream_rows[USER_STATUS_STREAM], report_teams)
+ stream_rows[USER_STATUS_STREAM] = scoped_status.rows
merged = merge_label_streams(
stream_rows,
@@ -1318,10 +1375,12 @@ def inbox_user_report_interactions(context: dagster.AssetExecutionContext) -> No
defaults=USER_LABEL_DEFAULTS,
)
distinct_ids = sorted({row["user_distinct_id"] for row in merged})
+ team_members = org_member_distinct_ids(set(report_teams.values()) & set(consent_team_ids), distinct_ids)
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)
+ assembled = assemble_user_interaction_rows(merged, report_teams, consent_team_ids, team_members, user_uuids)
+ rows = assembled.rows
bucket = dataset_bucket()
key = partition_object_key(settings.INBOX_RANKING_DATASET_S3_PREFIX, USER_INTERACTIONS_TABLE, partition_key)
@@ -1338,6 +1397,8 @@ def inbox_user_report_interactions(context: dagster.AssetExecutionContext) -> No
"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)),
+ "non_member_pairs": dagster.MetadataValue.int(assembled.non_member_pairs),
+ "status_tenant_mismatch_pairs": dagster.MetadataValue.int(scoped_status.dropped),
**{
f"{stream_name}_pairs": dagster.MetadataValue.int(len(stream))
for stream_name, stream in stream_rows.items()
diff --git a/products/signals/dags/inbox_ranking/dataset/queries.py b/products/signals/dags/inbox_ranking/dataset/queries.py
index 8bfaf463d70e..b3f777ea6255 100644
--- a/products/signals/dags/inbox_ranking/dataset/queries.py
+++ b/products/signals/dags/inbox_ranking/dataset/queries.py
@@ -942,6 +942,7 @@ WHERE event = 'signals_pr_refund_created'
GROUP BY report_id, user_distinct_id
"""
+USER_STATUS_STREAM = "user_status_changes"
USER_STATUS_COLUMNS = (
"status_resolved_count",
"first_status_resolved_at",
@@ -959,7 +960,9 @@ USER_STATUS_COLUMNS = (
# 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.
+# actor, so one person's transition never dedupes into another's. A trailing `status_event_team_id`
+# column carries that tenant, and `scoped_user_status_rows` strips it after it checks it against the
+# report's team.
USER_STATUS_SQL = (
"""
SELECT
@@ -977,7 +980,8 @@ SELECT
) 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
+ ) AS first_dismissal_actor_kind,
+ toInt(any(latest_event_team_id)) AS status_event_team_id
FROM (
SELECT
*,
@@ -1067,7 +1071,7 @@ USER_LABEL_STREAMS: tuple[tuple[str, str, tuple[str, ...]], ...] = (
("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_STATUS_STREAM, USER_STATUS_SQL, USER_STATUS_COLUMNS),
("user_pr_events", USER_PR_SQL, USER_PR_COLUMNS),
)
diff --git a/products/signals/dags/inbox_ranking/tests/test_dataset.py b/products/signals/dags/inbox_ranking/tests/test_dataset.py
index f145b62c1d00..9a5196aa9f06 100644
--- a/products/signals/dags/inbox_ranking/tests/test_dataset.py
+++ b/products/signals/dags/inbox_ranking/tests/test_dataset.py
@@ -50,6 +50,7 @@ from products.signals.dags.inbox_ranking.dataset.queries import (
USER_SERVER_ACTIONS_COLUMNS,
USER_STATUS_COLUMNS,
USER_STATUS_SQL,
+ USER_STATUS_STREAM,
hogql_rows,
merge_label_streams,
region_app_host,
@@ -66,6 +67,7 @@ AFTER_SNAPSHOT_END = datetime.datetime(2026, 7, 30, 1, 0, tzinfo=datetime.UTC)
BEFORE_CUTOFF = datetime.datetime(2026, 7, 28, 9, 0, tzinfo=datetime.UTC)
UUID_A = "0198c0e8-93c8-0000-38f5-a934eeb1b93e"
UUID_B = "0198c0e8-93c8-0000-38f5-a934eeb1b93f"
+UUID_C = "0198c0e8-93c8-0000-38f5-a934eeb1b940"
def test_s3_key_layout_is_stable():
@@ -464,11 +466,22 @@ def test_user_grain_rows_match_the_parquet_schema_exactly():
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)
+ assembled = assemble_user_interaction_rows(merged, {UUID_A: 2}, {2}, {2: {"person-1"}}, {"person-1": "uuid-1"})
+ assert set(assembled.rows[0]) == set(USER_INTERACTIONS_SCHEMA.names)
def test_user_grain_keeps_one_row_per_person_and_only_consented_reports():
+ report_teams = {UUID_A: 2, UUID_B: 7, UUID_C: 2}
+ status = dag.scoped_user_status_rows(
+ [
+ (UUID_A, "person-1", 0, None, 1, T2, 0, None, "analysis_wrong", "agent", 2),
+ # The latest transition of UUID_C names another team, or no team.
+ (UUID_C, "person-1", 1, T2, 0, None, 0, None, None, None, 999),
+ (UUID_C, "person-2", 1, T2, 0, None, 0, None, None, None, None),
+ ],
+ report_teams,
+ )
+ assert status.dropped == 2
stream_rows: dict[str, list[tuple[Any, ...]]] = {
"user_opens": [
(UUID_A, "person-1", 2, T1, T2, "click"),
@@ -476,9 +489,11 @@ def test_user_grain_keeps_one_row_per_person_and_only_consented_reports():
(UUID_A.upper(), "person-1", 99, T2, T2, "deeplink"),
(UUID_A, "person-2", 1, T2, T2, "deeplink"),
(UUID_A, "", 1, T2, T2, "click"),
+ (UUID_A, "outsider", 3, T1, T1, "click"),
(UUID_B, "person-1", 1, T1, T1, "click"),
+ (UUID_C, "person-1", 1, T1, T1, "click"),
],
- "user_status_changes": [(UUID_A, "person-1", 0, None, 1, T2, 0, None, "analysis_wrong", "agent")],
+ "user_status_changes": status.rows,
}
merged = merge_label_streams(
stream_rows,
@@ -489,13 +504,18 @@ def test_user_grain_keeps_one_row_per_person_and_only_consented_reports():
)
# 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"})
+ assembled = assemble_user_interaction_rows(
+ merged, report_teams, {2}, {2: {"person-1", "person-2"}, 7: {"person-1"}}, {"person-1": "uuid-1"}
+ )
+ rows = assembled.rows
assert [(row["report_id"], row["user_distinct_id"]) for row in rows] == [
(UUID_A, "person-1"),
(UUID_A, "person-2"),
+ (UUID_C, "person-1"),
]
- person_1, person_2 = rows
+ assert assembled.non_member_pairs == 1
+ person_1, person_2, mismatched = rows
assert person_1["open_count"] == 2
assert person_1["first_open_method"] == "click"
assert person_1["status_dismissed_count"] == 1
@@ -504,6 +524,10 @@ def test_user_grain_keeps_one_row_per_person_and_only_consented_reports():
assert person_1["report_team_id"] == 2
assert person_2["status_dismissed_count"] == 0
assert person_2["user_uuid"] is None
+ assert mismatched["open_count"] == 1
+ assert {column: mismatched[column] for column in USER_STATUS_COLUMNS} == {
+ column: USER_LABEL_DEFAULTS[column] for column in USER_STATUS_COLUMNS
+ }
class TestSpineInclusion(BaseTest):
@@ -721,6 +745,17 @@ class TestServerActions(BaseTest):
assert row["first_viewed_at"] == view.first_at
assert row["first_read_at"] is None
+ def test_org_members_resolve_only_within_each_teams_organization(self):
+ other_org = Organization.objects.create(name="other")
+ other_team = Team.objects.create(organization=other_org, name="other")
+ outsider = User.objects.create_and_join(other_org, "[email protected]", "password")
+
+ member_id, outsider_id = str(self.user.distinct_id), str(outsider.distinct_id)
+
+ members = dag.org_member_distinct_ids({self.team.id, other_team.id}, [member_id, outsider_id, "unknown"])
+
+ assert members == {self.team.id: {member_id}, other_team.id: {outsider_id}}
+
class TestImpressionsStream(ClickhouseTestMixin, BaseTest):
@parameterized.expand([("labeled_ids", LABELED_REPORT_IDS_SQL), ("impressions", IMPRESSIONS_SQL)])
@@ -952,7 +987,7 @@ class TestUserGrainStreams(ClickhouseTestMixin, BaseTest):
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}
+ return {row[1]: dict(zip((*USER_STATUS_COLUMNS, "status_event_team_id"), 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]]] = [
@@ -993,7 +1028,8 @@ class TestUserGrainStreams(ClickhouseTestMixin, BaseTest):
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
+ # The status stream carries its tenant as one more column, which the asset strips.
+ assert len(rows[0]) == 2 + len(columns) + (stream_name == USER_STATUS_STREAM), 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")
@@ -1023,6 +1059,11 @@ class TestUserGrainStreams(ClickhouseTestMixin, BaseTest):
self._transition(T1, status, actor, "user", reason="analysis_wrong", team_id=999)
assert self._status_rows() == genuine_only
+ assert genuine_only["person-1"]["status_event_team_id"] == self.team.id
+
+ self._transition(T2 + datetime.timedelta(days=1), "resolved", "person-1", "user", team_id=999)
+
+ assert self._status_rows()["person-1"]["status_event_team_id"] == 999
def _run_embeddings_asset(monkeypatch, asset, rows, consent_team_ids=frozenset({2})):