: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
fix(replay): drop the opted-in team filter from the score export query (#71612)
Robbie15f350b73031
diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/activities.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/activities.pyindex 97ce91bdc7c5..d5db7fc134f8 100644--- a/posthog/temporal/session_replay/surfacing_score_export_sweep/activities.py+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/activities.py@@ -1,10 +1,12 @@"""Activities: plan the (day × hash bucket) fan-out, then per partition fetch → pseudonymize → Parquet → S3 put.-Only AI-training opted-in orgs are exported (the ML mirror's gate), with the-mirror's exact pseudonym scheme, so exported ids join onto `block-metadata`-and nothing else. Object keys are deterministic, so retries and the re-export-window overwrite; an empty partition still writes an empty object so deleted-sessions drop out rather than going stale.+All scored sessions are exported, pseudonymized with the ML mirror's exact+pseudonym scheme, so exported ids join onto `block-metadata` — which only+exists for AI-training opted-in orgs (the mirror's gate) — and nothing else.+Rows from non-opted-in teams are opaque pseudonyms that join to nothing.+Object keys are deterministic, so retries and the re-export window overwrite;+an empty partition still writes an empty object so deleted sessions drop out+rather than going stale."""from __future__ import annotations@@ -23,7 +25,6 @@ from temporalio import activityfrom temporalio.exceptions import ApplicationErrorfrom posthog.clickhouse.client import sync_execute-from posthog.models import Teamfrom posthog.temporal.session_replay.surfacing_score_export_sweep import sql as export_sqlfrom posthog.temporal.session_replay.surfacing_score_export_sweep.constants import (CH_EXPORT_QUERY_MAX_MEMORY_BYTES,@@ -102,10 +103,6 @@ _PARQUET_FIELDS: list[pa.Field[Any]] = [_PARQUET_SCHEMA = pa.schema(_PARQUET_FIELDS)-def _opted_in_team_ids() -> list[int]:- return list(Team.objects.filter(organization__is_ai_training_opted_in=True).values_list("id", flat=True))--# (team_id, session_id, started_at, score)_ScoredRow = tuple[int, str, datetime, float]@@ -114,7 +111,7 @@ _Cursor = tuple[str, int]_FIRST_PAGE: _Cursor = ("", 0)-def _fetch_page(spec: ExportPartitionSpec, team_ids: list[int], cursor: _Cursor) -> list[_ScoredRow]:+def _fetch_page(spec: ExportPartitionSpec, cursor: _Cursor) -> list[_ScoredRow]:return cast(list[_ScoredRow],sync_execute(@@ -122,7 +119,6 @@ def _fetch_page(spec: ExportPartitionSpec, team_ids: list[int], cursor: _Cursor){"of_chunks": spec.of_chunks,"chunk_id": spec.chunk_id,- "team_ids": team_ids,"day_start": f"{spec.day} 00:00:00","cursor_session_id": cursor[0],"cursor_team_id": cursor[1],@@ -175,15 +171,14 @@ async def export_scores_partition_activity(spec: ExportPartitionSpec) -> ExportPraise ApplicationError(str(e), type=type(e).__name__, non_retryable=True) from eactivity.heartbeat({"phase": "fetch", "day": spec.day, "chunk_id": spec.chunk_id})- team_ids = await sync_to_async(_opted_in_team_ids, thread_sensitive=False)()sink = io.BytesIO()writer = pq.ParquetWriter(sink, _PARQUET_SCHEMA, compression="snappy")cursor = _FIRST_PAGErows_total = 0try:- while team_ids:- rows = await sync_to_async(_fetch_page, thread_sensitive=False)(spec, team_ids, cursor)+ while True:+ rows = await sync_to_async(_fetch_page, thread_sensitive=False)(spec, cursor)if rows:table = await sync_to_async(_page_table, thread_sensitive=False)(rows, secret)await sync_to_async(writer.write_table, thread_sensitive=False)(table)diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/sql.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/sql.pyindex 2f63833d0070..8411bbfb768d 100644--- a/posthog/temporal/session_replay/surfacing_score_export_sweep/sql.py+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/sql.py@@ -5,10 +5,16 @@ SESSION_REPLAY_EVENTS_TABLE = "session_replay_events"def fetch_scored_sessions_page_sql(replay_events_table: str = SESSION_REPLAY_EVENTS_TABLE) -> str:"""One keyset-paginated page of a (day, hash bucket) export slice.- Bound parameters: %(of_chunks)s, %(chunk_id)s, %(team_ids)s,+ Bound parameters: %(of_chunks)s, %(chunk_id)s,%(day_start)s ('YYYY-MM-DD 00:00:00', UTC), %(cursor_session_id)s,%(cursor_team_id)s, %(page_size)s.+ There is deliberately no opted-in-team filter: exported rows are+ pseudonymized and only ever joined downstream against session data that+ exists solely for opted-in teams, so rows from other teams join to+ nothing. Inlining the opted-in id list here (twice) also blew past+ ClickHouse's 1 MiB max_query_size once enough teams opted in.+The cursor predicate and ORDER BY use the same (session_id, team_id) tuple,so pages tile the partition exactly; a page shorter than page_size meansthe slice is exhausted. The raw-row prefilter prunes on the@@ -31,7 +37,6 @@ SELECTmax(surfacing_score) AS scoreFROM {replay_events_table}WHERE cityHash64(session_id) %% %(of_chunks)s = %(chunk_id)s- AND team_id IN %(team_ids)sAND (session_id, team_id) > (%(cursor_session_id)s, %(cursor_team_id)s)AND min_first_timestamp >= toDateTime(%(day_start)s, 'UTC')AND min_first_timestamp < toDateTime(%(day_start)s, 'UTC') + toIntervalDay(2)@@ -39,7 +44,6 @@ WHERE cityHash64(session_id) %% %(of_chunks)s = %(chunk_id)sSELECT team_id, session_idFROM {replay_events_table}WHERE cityHash64(session_id) %% %(of_chunks)s = %(chunk_id)s- AND team_id IN %(team_ids)sAND min_first_timestamp >= toDateTime(%(day_start)s, 'UTC')AND is_deleted = 1)