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(replay): export raw ids from the score export sweep (#117639)

Nicholas Waltz903b32f5eaa4
diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/activities.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/activities.py
index d5319c8cc779..8f790eb750f9 100644
--- a/posthog/temporal/session_replay/surfacing_score_export_sweep/activities.py
+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/activities.py
@@ -1,9 +1,7 @@
-"""Activities: plan the (day × hash bucket) fan-out, then per partition fetch → pseudonymize → Parquet → S3 put.
+"""Activities: plan the (day × hash bucket) fan-out, then per partition fetch → Parquet → S3 put.
-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.
+Every scored session is exported with raw team and session ids, as the ML mirror's metadata
+carries them, so rows join onto `block-metadata` wherever the mirror wrote the session.
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.
@@ -22,7 +20,6 @@ from asgiref.sync import sync_to_async
from boto3 import client as boto3_client
from botocore.client import Config
from temporalio import activity
-from temporalio.exceptions import ApplicationError
from posthog.clickhouse.client import sync_execute
from posthog.temporal.session_replay.surfacing_score_export_sweep import sql as export_sql
@@ -34,15 +31,6 @@ from posthog.temporal.session_replay.surfacing_score_export_sweep.constants impo
EXPORT_PAGE_MAX_ROWS,
REEXPORT_WINDOW_DAYS,
)
-from posthog.temporal.session_replay.surfacing_score_export_sweep.pseudonymize import (
- PSEUDONYM_SESSION,
- PSEUDONYM_TEAM,
- PseudonymKeyFingerprintMismatchError,
- PseudonymKeyNotConfiguredError,
- is_pseudonym_key_configured,
- pseudonymize,
- resolve_pseudonym_key,
-)
from posthog.temporal.session_replay.surfacing_score_export_sweep.s3 import (
score_export_destination,
score_export_object_key,
@@ -59,8 +47,6 @@ logger = structlog.get_logger(__name__)
def _disabled_reason() -> str | None:
- if not is_pseudonym_key_configured():
- return "pseudonym key not configured"
if score_export_destination() is None:
return "score export S3 destination not configured"
return None
@@ -132,15 +118,15 @@ def _fetch_page(spec: ExportPartitionSpec, cursor: _Cursor) -> list[_ScoredRow]:
)
-def _page_table(rows: list[_ScoredRow], secret: bytes) -> pa.Table:
+def _page_table(rows: list[_ScoredRow]) -> pa.Table:
records: list[dict[str, Any]] = []
for team_id, session_id, started_at, score in rows:
if started_at.tzinfo is None:
started_at = started_at.replace(tzinfo=UTC)
records.append(
{
- "session_id": pseudonymize(secret, PSEUDONYM_SESSION, session_id),
- "team_id": pseudonymize(secret, PSEUDONYM_TEAM, str(team_id)),
+ "session_id": session_id,
+ "team_id": str(team_id),
"started_at": started_at,
"surfacing_score": float(score),
}
@@ -165,11 +151,6 @@ def _upload(key: str, body: bytes) -> None:
@activity.defn
async def export_scores_partition_activity(spec: ExportPartitionSpec) -> ExportPartitionResult:
- try:
- secret = await sync_to_async(resolve_pseudonym_key, thread_sensitive=False)()
- except (PseudonymKeyNotConfiguredError, PseudonymKeyFingerprintMismatchError) as e:
- raise ApplicationError(str(e), type=type(e).__name__, non_retryable=True) from e
-
activity.heartbeat({"phase": "fetch", "day": spec.day, "chunk_id": spec.chunk_id})
sink = io.BytesIO()
@@ -180,9 +161,9 @@ async def export_scores_partition_activity(spec: ExportPartitionSpec) -> ExportP
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)
+ table = await sync_to_async(_page_table, thread_sensitive=False)(rows)
await sync_to_async(writer.write_table, thread_sensitive=False)(table)
- rows_total += len(rows)
+ rows_total += table.num_rows
cursor = (rows[-1][1], rows[-1][0])
if len(rows) < EXPORT_PAGE_MAX_ROWS:
break
diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/constants.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/constants.py
index c4dd6bb78cde..3e14a7ef353f 100644
--- a/posthog/temporal/session_replay/surfacing_score_export_sweep/constants.py
+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/constants.py
@@ -1,6 +1,6 @@
"""Static config for the surfacing-score export sweep: daily export of scored
sessions from `session_replay_events` to the ML-account S3 bucket as
-dt-partitioned Parquet, keyed by the ML mirror's pseudonymous ids."""
+dt-partitioned Parquet, keyed by raw team and session ids like the ML mirror's metadata."""
from datetime import date, timedelta
diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/pseudonymize.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/pseudonymize.py
deleted file mode 100644
index ac52dbe787d6..000000000000
--- a/posthog/temporal/session_replay/surfacing_score_export_sweep/pseudonymize.py
+++ /dev/null
@@ -1,96 +0,0 @@
-"""Python port of the ML mirror's pseudonymization (`nodejs/.../ml-mirror/pseudonymize.ts`
-+ `pseudonym-key.ts`). Must stay byte-identical, same key and env vars, or exported
-scores stop joining onto the mirrored dataset."""
-
-from __future__ import annotations
-
-import os
-import hmac
-import hashlib
-import threading
-from base64 import b64decode
-
-import structlog
-from boto3 import client as boto3_client
-
-logger = structlog.get_logger(__name__)
-
-PSEUDONYM_TEAM = "team"
-PSEUDONYM_SESSION = "session"
-
-WRAPPED_KEY_ENV_VAR = "SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY"
-PLAINTEXT_SECRET_ENV_VAR = "SESSION_RECORDING_ML_PSEUDONYM_SECRET"
-KMS_REGION_ENV_VAR = "SESSION_RECORDING_ML_PSEUDONYM_KMS_REGION"
-KEY_FINGERPRINT_ENV_VAR = "SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT"
-
-
-class PseudonymKeyNotConfiguredError(RuntimeError):
- pass
-
-
-class PseudonymKeyFingerprintMismatchError(RuntimeError):
- pass
-
-
-def pseudonymize(secret: bytes, namespace: str, value: str) -> str:
- message = f"{len(namespace)}:{namespace}:{value}".encode()
- return hmac.new(secret, message, hashlib.sha256).hexdigest()[:32]
-
-
-def pseudonym_key_fingerprint(secret: bytes) -> str:
- return hmac.new(secret, b"pseudonym-key-fingerprint:v1", hashlib.sha256).hexdigest()[:16]
-
-
-def is_pseudonym_key_configured() -> bool:
- return bool(os.environ.get(WRAPPED_KEY_ENV_VAR) or os.environ.get(PLAINTEXT_SECRET_ENV_VAR))
-
-
-_SECRET: bytes | None = None
-_SECRET_LOCK = threading.Lock()
-
-
-def _kms_decrypt(ciphertext_base64: str, region: str) -> bytes:
- kms = boto3_client("kms", region_name=region or None)
- result = kms.decrypt(CiphertextBlob=b64decode(ciphertext_base64))
- plaintext = result.get("Plaintext")
- if not plaintext:
- raise PseudonymKeyNotConfiguredError("KMS Decrypt returned no plaintext for the pseudonym key")
- return bytes(plaintext)
-
-
-def resolve_pseudonym_key() -> bytes:
- """KMS-wrapped key preferred, plaintext env for dev. Fails closed on a missing key
- or a pinned-fingerprint mismatch — a rotated key would re-map the id space."""
- global _SECRET
- with _SECRET_LOCK:
- if _SECRET is not None:
- return _SECRET
-
- wrapped = os.environ.get(WRAPPED_KEY_ENV_VAR)
- plaintext_secret = os.environ.get(PLAINTEXT_SECRET_ENV_VAR)
- if wrapped:
- secret = _kms_decrypt(wrapped, os.environ.get(KMS_REGION_ENV_VAR, ""))
- source = "kms"
- elif plaintext_secret:
- secret = plaintext_secret.encode()
- source = "env"
- else:
- raise PseudonymKeyNotConfiguredError(
- f"{WRAPPED_KEY_ENV_VAR} or {PLAINTEXT_SECRET_ENV_VAR} must be set for the score export sweep"
- )
-
- fingerprint = pseudonym_key_fingerprint(secret)
- expected = os.environ.get(KEY_FINGERPRINT_ENV_VAR)
- if expected and expected != fingerprint:
- raise PseudonymKeyFingerprintMismatchError(
- f"pseudonym key fingerprint mismatch (resolved {fingerprint}, expected {expected})"
- )
-
- logger.info(
- "surfacing_score_export_sweep.pseudonym_key_loaded",
- source=source,
- fingerprint=fingerprint,
- pinned=bool(expected),
- )
- _SECRET = secret
- return secret
diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/sql.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/sql.py
index 8411bbfb768d..a0d72112df07 100644
--- a/posthog/temporal/session_replay/surfacing_score_export_sweep/sql.py
+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/sql.py
@@ -9,11 +9,8 @@ def fetch_scored_sessions_page_sql(replay_events_table: str = SESSION_REPLAY_EVE
%(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.
+ There is deliberately no opted-in-team filter: scores carry no session
+ content, and rows from teams the mirror does not cover join to nothing.
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 means
diff --git a/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/test_export.py b/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/test_export.py
index 42e498e13889..91d55b56a38f 100644
--- a/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/test_export.py
+++ b/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/test_export.py
@@ -1,12 +1,9 @@
-# Golden vectors generated from the Node source of truth (nodejs/.../ml-mirror/pseudonymize.ts).
-
import io
from datetime import UTC, date, datetime
import pytest
import pyarrow.parquet as pq
-from parameterized import parameterized
from posthog.temporal.session_replay.surfacing_score_export_sweep.activities import (
_PARQUET_SCHEMA,
@@ -17,28 +14,6 @@ from posthog.temporal.session_replay.surfacing_score_export_sweep.constants impo
EXPORT_FLOOR_DAY,
REEXPORT_WINDOW_DAYS,
)
-from posthog.temporal.session_replay.surfacing_score_export_sweep.pseudonymize import (
- PSEUDONYM_SESSION,
- PSEUDONYM_TEAM,
- pseudonym_key_fingerprint,
- pseudonymize,
-)
-
-SECRET = b"super-secret"
-
-
-class TestPseudonymizeNodeParity:
- @parameterized.expand(
- [
- (PSEUDONYM_SESSION, "0197d1cf-13d0-7c07-a301-d2e19a7c2a55", "5f004a2baeeb5c761c6ba2c70730961c"),
- (PSEUDONYM_TEAM, "42", "a424b2c7c7d5b495e6479d058e5f751c"),
- ]
- )
- def test_matches_node_golden_vector(self, namespace: str, value: str, expected: str) -> None:
- assert pseudonymize(SECRET, namespace, value) == expected
-
- def test_fingerprint_matches_node_golden_vector(self) -> None:
- assert pseudonym_key_fingerprint(SECRET) == "db7dc188104c2bae"
class TestExportDays:
@@ -61,25 +36,24 @@ def _write_pages(pages: list[list[tuple[int, str, datetime, float]]]) -> bytes:
sink = io.BytesIO()
writer = pq.ParquetWriter(sink, _PARQUET_SCHEMA, compression="snappy")
for page in pages:
- writer.write_table(_page_table(page, SECRET))
+ writer.write_table(_page_table(page))
writer.close()
return sink.getvalue()
class TestPartitionParquet:
- def test_pseudonymizes_ids_and_round_trips_across_pages(self) -> None:
- started_at = datetime(2026, 7, 4, 12, 30, tzinfo=UTC)
- session_id = "0197d1cf-13d0-7c07-a301-d2e19a7c2a55"
+ def test_exports_raw_ids_and_round_trips_across_pages(self) -> None:
+ started_at = datetime(2026, 10, 14, 12, 30, tzinfo=UTC)
+ session_id = "019a1f2e-13d0-7c07-a301-d2e19a7c2a55"
body = _write_pages([[(42, session_id, started_at, 0.75)], [(43, "another-session", started_at, 0.25)]])
table = pq.read_table(io.BytesIO(body))
assert table.num_rows == 2
row = table.to_pylist()[0]
- assert row["session_id"] == "5f004a2baeeb5c761c6ba2c70730961c"
- assert row["team_id"] == "a424b2c7c7d5b495e6479d058e5f751c"
+ assert row["session_id"] == session_id
+ assert row["team_id"] == "42"
assert row["started_at"] == started_at
assert row["surfacing_score"] == pytest.approx(0.75)
- assert session_id not in body.decode("latin-1")
def test_no_pages_still_writes_a_readable_object_with_the_schema(self) -> None:
table = pq.read_table(io.BytesIO(_write_pages([])))