: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(session-replay): export surfacing scores to ML bucket as parquet (#68702)
Nicholas Waltz134dd72eba6d
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex 399c39144373..f313be38c2b5 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -141,6 +141,10 @@ from posthog.temporal.session_replay.summarization_sweep import (SUMMARIZATION_SWEEP_ACTIVITIES,SUMMARIZATION_SWEEP_WORKFLOWS,)+from posthog.temporal.session_replay.surfacing_score_export_sweep import (+ SURFACING_SCORE_EXPORT_SWEEP_ACTIVITIES,+ SURFACING_SCORE_EXPORT_SWEEP_WORKFLOWS,+)from posthog.temporal.session_replay.surfacing_scoring_sweep import (SURFACING_SCORING_SWEEP_ACTIVITIES,SURFACING_SCORING_SWEEP_WORKFLOWS,@@ -368,6 +372,7 @@ _task_queue_specs = [+ SESSION_SUMMARY_WORKFLOWS+ SESSION_SUMMARY_GROUP_WORKFLOWS+ SUMMARIZATION_SWEEP_WORKFLOWS+ + SURFACING_SCORE_EXPORT_SWEEP_WORKFLOWS+ SURFACING_SCORING_SWEEP_WORKFLOWS,GEMINI_CLEANUP_SWEEP_ACTIVITIES+ COUNT_PLAYLIST_ITEMS_ACTIVITIES@@ -378,6 +383,7 @@ _task_queue_specs = [+ SESSION_SUMMARY_ACTIVITIES+ SESSION_SUMMARY_GROUP_ACTIVITIES+ SUMMARIZATION_SWEEP_ACTIVITIES+ + SURFACING_SCORE_EXPORT_SWEEP_ACTIVITIES+ SURFACING_SCORING_SWEEP_ACTIVITIES,),(diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex c639649f1d7d..f2de97a6c9e2 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -66,6 +66,9 @@ from posthog.temporal.session_replay.replay_count_metrics.types import ReplayCoufrom posthog.temporal.session_replay.summarization_sweep.reconciler import (create_summarization_sweep_reconciler_schedule,)+from posthog.temporal.session_replay.surfacing_score_export_sweep.schedule import (+ create_surfacing_score_export_sweep_schedule,+)from posthog.temporal.session_replay.surfacing_scoring_sweep.schedule import create_surfacing_scoring_sweep_schedulefrom posthog.temporal.sync_events_retention.types import SyncEventsRetentionInputfrom posthog.temporal.usage_report.types import RunUsageReportsInputs@@ -799,6 +802,7 @@ schedules = [create_evaluation_clustering_schedule,cleanup_legacy_session_summarization_schedules,create_summarization_sweep_reconciler_schedule,+ create_surfacing_score_export_sweep_schedule,create_surfacing_scoring_sweep_schedule,create_ducklake_compaction_schedule,create_purge_deleted_recording_metadata_schedule,diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/__init__.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/__init__.pynew file mode 100644index 000000000000..a3c763fb5b34--- /dev/null+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/__init__.py@@ -0,0 +1,8 @@+from posthog.temporal.session_replay.surfacing_score_export_sweep.activities import (+ export_scores_partition_activity,+ list_export_partitions_activity,+)+from posthog.temporal.session_replay.surfacing_score_export_sweep.workflow import ExportSurfacingScoresWorkflow++SURFACING_SCORE_EXPORT_SWEEP_WORKFLOWS = [ExportSurfacingScoresWorkflow]+SURFACING_SCORE_EXPORT_SWEEP_ACTIVITIES = [list_export_partitions_activity, export_scores_partition_activity]diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/activities.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/activities.pynew file mode 100644index 000000000000..97ce91bdc7c5--- /dev/null+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/activities.py@@ -0,0 +1,213 @@+"""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.+"""++from __future__ import annotations++import io+from datetime import UTC, date, datetime, timedelta+from typing import Any, cast++import pyarrow as pa+import structlog+import pyarrow.parquet as pq+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.models import Team+from posthog.temporal.session_replay.surfacing_score_export_sweep import sql as export_sql+from posthog.temporal.session_replay.surfacing_score_export_sweep.constants import (+ CH_EXPORT_QUERY_MAX_MEMORY_BYTES,+ CH_EXPORT_QUERY_TIMEOUT_S,+ DEFAULT_OF_CHUNKS,+ EXPORT_FLOOR_DAY,+ 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,+ upload_parquet,+)+from posthog.temporal.session_replay.surfacing_score_export_sweep.types import (+ ExportPartitionResult,+ ExportPartitionSpec,+ ExportScoresSweepInputs,+ ListExportPartitionsResult,+)++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+++def export_days(today: date) -> list[str]:+ """Complete UTC days within the re-export window, never before the floor."""+ first_day = max(EXPORT_FLOOR_DAY, today - timedelta(days=REEXPORT_WINDOW_DAYS))+ days = []+ day = first_day+ while day < today:+ days.append(day.isoformat())+ day += timedelta(days=1)+ return days+++async def list_export_partitions_activity(_inputs: ExportScoresSweepInputs) -> ListExportPartitionsResult:+ reason = _disabled_reason()+ if reason is not None:+ logger.warning("surfacing_score_export_sweep.disabled", reason=reason)+ return ListExportPartitionsResult(disabled_reason=reason)++ days = export_days(datetime.now(UTC).date())+ partitions = [+ ExportPartitionSpec(day=d, chunk_id=chunk_id, of_chunks=DEFAULT_OF_CHUNKS)+ for d in days+ for chunk_id in range(DEFAULT_OF_CHUNKS)+ ]+ logger.info("surfacing_score_export_sweep.partitions_planned", days=len(days), partitions=len(partitions))+ return ListExportPartitionsResult(partitions=partitions)+++_PARQUET_FIELDS: list[pa.Field[Any]] = [+ pa.field("session_id", pa.string(), nullable=False),+ pa.field("team_id", pa.string(), nullable=False),+ pa.field("started_at", pa.timestamp("ms", tz="UTC"), nullable=False),+ pa.field("surfacing_score", pa.float32(), nullable=False),+]+_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]++# Keyset cursor over the (session_id, team_id) page ordering; ("", 0) sorts before every real row.+_Cursor = tuple[str, int]+_FIRST_PAGE: _Cursor = ("", 0)+++def _fetch_page(spec: ExportPartitionSpec, team_ids: list[int], cursor: _Cursor) -> list[_ScoredRow]:+ return cast(+ list[_ScoredRow],+ sync_execute(+ export_sql.fetch_scored_sessions_page_sql(),+ {+ "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],+ "page_size": EXPORT_PAGE_MAX_ROWS,+ },+ settings={+ "max_execution_time": CH_EXPORT_QUERY_TIMEOUT_S,+ "max_memory_usage": CH_EXPORT_QUERY_MAX_MEMORY_BYTES,+ },+ ),+ )+++def _page_table(rows: list[_ScoredRow], secret: bytes) -> 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)),+ "started_at": started_at,+ "surfacing_score": float(score),+ }+ )+ return pa.Table.from_pylist(records, schema=_PARQUET_SCHEMA)+++def _upload(key: str, body: bytes) -> None:+ dest = score_export_destination()+ if dest is None:+ raise RuntimeError("score export S3 destination not configured")+ s3 = boto3_client(+ "s3",+ endpoint_url=dest.endpoint,+ aws_access_key_id=dest.access_key_id,+ aws_secret_access_key=dest.secret_access_key,+ config=Config(signature_version="s3v4"),+ region_name=dest.region,+ )+ upload_parquet(s3, bucket=dest.bucket, key=key, body=body)+++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})+ 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_PAGE+ rows_total = 0+ try:+ while team_ids:+ rows = await sync_to_async(_fetch_page, thread_sensitive=False)(spec, team_ids, 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)+ rows_total += len(rows)+ cursor = (rows[-1][1], rows[-1][0])+ if len(rows) < EXPORT_PAGE_MAX_ROWS:+ break+ activity.heartbeat({"phase": "fetch", "day": spec.day, "chunk_id": spec.chunk_id, "rows": rows_total})+ finally:+ writer.close()+ body = sink.getvalue()++ activity.heartbeat({"phase": "upload", "day": spec.day, "chunk_id": spec.chunk_id, "rows": rows_total})+ key = score_export_object_key(spec.day, spec.chunk_id, spec.of_chunks)+ await sync_to_async(_upload, thread_sensitive=False)(key, body)++ activity.logger.info(+ "surfacing_score_export_sweep.partition_done",+ day=spec.day,+ chunk_id=spec.chunk_id,+ rows=rows_total,+ bytes=len(body),+ key=key,+ )+ return ExportPartitionResult(+ day=spec.day, chunk_id=spec.chunk_id, rows=rows_total, bytes_written=len(body), key=key+ )diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/constants.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/constants.pynew file mode 100644index 000000000000..27c807ed84e8--- /dev/null+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/constants.py@@ -0,0 +1,42 @@+"""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."""++from datetime import date, timedelta++from posthog.temporal.session_replay.surfacing_scoring_sweep.constants import SCORE_LOOKBACK_DAYS++WORKFLOW_NAME = "surfacing-score-export-sweep"+SCHEDULE_ID = "surfacing-score-export-sweep"+SCHEDULE_TYPE = "surfacing-score-export-sweep"++SCHEDULE_INTERVAL = timedelta(days=1)+# Offset from midnight UTC so near-boundary sessions are scored before their day is first exported.+SCHEDULE_OFFSET = timedelta(hours=2)++# First exported day partition — sessions started strictly after July 3rd, 2026 (UTC).+EXPORT_FLOOR_DAY = date(2026, 7, 4)++# Scores land up to SCORE_LOOKBACK_DAYS after session start, so re-export the trailing window each run.+REEXPORT_WINDOW_DAYS = SCORE_LOOKBACK_DAYS + 1++# `cityHash64(session_id) % OF_CHUNKS` partitioning, same scheme as the scoring sweep.+DEFAULT_OF_CHUNKS = 8++SCORE_EXPORT_PREFIX_ENV_VAR = "SESSION_RECORDING_ML_SCORE_EXPORT_PREFIX"+DEFAULT_SCORE_EXPORT_PREFIX = "score"++CH_EXPORT_QUERY_TIMEOUT_S = 120+CH_EXPORT_QUERY_MAX_MEMORY_BYTES = 10 * 1024 * 1024 * 1024 # 10 GiB++# Keyset-pagination page size — bounds worker memory and per-query result size per+# fetch (~100 B/row, so a full page is low hundreds of MB of Python objects).+# Sized so typical partitions are single-page and pagination only engages on outliers.+EXPORT_PAGE_MAX_ROWS = 500_000++LIST_PARTITIONS_ACTIVITY_TIMEOUT = timedelta(seconds=30)+EXPORT_PARTITION_ACTIVITY_TIMEOUT = timedelta(minutes=20)+# > CH_EXPORT_QUERY_TIMEOUT_S — heartbeats fire between page fetches, not during a SELECT.+EXPORT_PARTITION_HEARTBEAT_TIMEOUT = timedelta(minutes=3)++WORKFLOW_EXECUTION_TIMEOUT = timedelta(hours=1)diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/pseudonymize.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/pseudonymize.pynew file mode 100644index 000000000000..ac52dbe787d6--- /dev/null+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/pseudonymize.py@@ -0,0 +1,96 @@+"""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 secretdiff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/s3.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/s3.pynew file mode 100644index 000000000000..9a8e667ff09d--- /dev/null+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/s3.py@@ -0,0 +1,63 @@+"""Destination config, object-key layout, and upload helper — same+`{prefix}/dt=.../part-*.parquet` layout as the ML mirror's Parquet store, but+with deterministic part names so re-runs overwrite.++The destination is its own `SESSION_RECORDING_ML_SCORE_EXPORT_S3_*` config+with NO fallback to the `SESSION_RECORDING_V2_S3_*` replay-store settings: on+the shared Temporal worker those point at the production replay bucket, and+the mirror only reuses them safely because it runs as a dedicated deployment.+Unset bucket → the sweep is disabled."""++from __future__ import annotations++import os+from dataclasses import dataclass+from typing import Any++from posthog.temporal.session_replay.surfacing_score_export_sweep.constants import (+ DEFAULT_SCORE_EXPORT_PREFIX,+ SCORE_EXPORT_PREFIX_ENV_VAR,+)++S3_BUCKET_ENV_VAR = "SESSION_RECORDING_ML_SCORE_EXPORT_S3_BUCKET"+S3_REGION_ENV_VAR = "SESSION_RECORDING_ML_SCORE_EXPORT_S3_REGION"+S3_ENDPOINT_ENV_VAR = "SESSION_RECORDING_ML_SCORE_EXPORT_S3_ENDPOINT"+S3_ACCESS_KEY_ID_ENV_VAR = "SESSION_RECORDING_ML_SCORE_EXPORT_S3_ACCESS_KEY_ID"+S3_SECRET_ACCESS_KEY_ENV_VAR = "SESSION_RECORDING_ML_SCORE_EXPORT_S3_SECRET_ACCESS_KEY"++PARQUET_CONTENT_TYPE = "application/vnd.apache.parquet"+++@dataclass(frozen=True)+class ScoreExportDestination:+ bucket: str+ region: str+ # None → default AWS endpoint; keys None → ambient credential chain (IRSA/instance profile).+ endpoint: str | None+ access_key_id: str | None+ secret_access_key: str | None+++def score_export_destination() -> ScoreExportDestination | None:+ bucket = os.environ.get(S3_BUCKET_ENV_VAR, "")+ if not bucket:+ return None+ return ScoreExportDestination(+ bucket=bucket,+ region=os.environ.get(S3_REGION_ENV_VAR, "us-east-1"),+ endpoint=os.environ.get(S3_ENDPOINT_ENV_VAR) or None,+ access_key_id=os.environ.get(S3_ACCESS_KEY_ID_ENV_VAR) or None,+ secret_access_key=os.environ.get(S3_SECRET_ACCESS_KEY_ENV_VAR) or None,+ )+++def score_export_prefix() -> str:+ return os.environ.get(SCORE_EXPORT_PREFIX_ENV_VAR, DEFAULT_SCORE_EXPORT_PREFIX)+++def score_export_object_key(day: str, chunk_id: int, of_chunks: int) -> str:+ return f"{score_export_prefix()}/dt={day}/part-{chunk_id:04d}-of-{of_chunks:04d}.parquet"+++def upload_parquet(s3_client: Any, *, bucket: str, key: str, body: bytes) -> None:+ s3_client.put_object(Bucket=bucket, Key=key, Body=body, ContentType=PARQUET_CONTENT_TYPE)diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/schedule.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/schedule.pynew file mode 100644index 000000000000..3ed228192573--- /dev/null+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/schedule.py@@ -0,0 +1,66 @@+"""Singleton per-region Schedule for the daily score export tick."""++from __future__ import annotations++from django.conf import settings++import structlog+from temporalio import common+from temporalio.client import (+ Client,+ Schedule,+ ScheduleActionStartWorkflow,+ ScheduleIntervalSpec,+ ScheduleOverlapPolicy,+ SchedulePolicy,+ ScheduleSpec,+)+from temporalio.common import SearchAttributePair, TypedSearchAttributes++from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule+from posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_TYPE_KEY+from posthog.temporal.session_replay.surfacing_score_export_sweep.constants import (+ SCHEDULE_ID,+ SCHEDULE_INTERVAL,+ SCHEDULE_OFFSET,+ SCHEDULE_TYPE,+ WORKFLOW_EXECUTION_TIMEOUT,+ WORKFLOW_NAME,+)+from posthog.temporal.session_replay.surfacing_score_export_sweep.types import ExportScoresSweepInputs++logger = structlog.get_logger(__name__)+++def _build_schedule() -> Schedule:+ return Schedule(+ action=ScheduleActionStartWorkflow(+ WORKFLOW_NAME,+ ExportScoresSweepInputs(),+ id=WORKFLOW_NAME,+ task_queue=settings.SESSION_REPLAY_TASK_QUEUE,+ execution_timeout=WORKFLOW_EXECUTION_TIMEOUT,+ retry_policy=common.RetryPolicy(maximum_attempts=1),+ ),+ spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=SCHEDULE_INTERVAL, offset=SCHEDULE_OFFSET)]),+ policy=SchedulePolicy(+ overlap=ScheduleOverlapPolicy.SKIP,+ catchup_window=SCHEDULE_INTERVAL,+ ),+ )+++async def create_surfacing_score_export_sweep_schedule(client: Client) -> None:+ """Upserted on deploy via `posthog/temporal/schedule.py`'s `schedules` list."""+ schedule = _build_schedule()+ search_attributes = TypedSearchAttributes(+ search_attributes=[SearchAttributePair(key=POSTHOG_SCHEDULE_TYPE_KEY, value=SCHEDULE_TYPE)]+ )+ if await a_schedule_exists(client, SCHEDULE_ID):+ await a_update_schedule(client, SCHEDULE_ID, schedule, search_attributes=search_attributes)+ logger.info("surfacing_score_export_sweep.schedule_updated", schedule_id=SCHEDULE_ID)+ else:+ await a_create_schedule(+ client, SCHEDULE_ID, schedule, trigger_immediately=False, search_attributes=search_attributes+ )+ logger.info("surfacing_score_export_sweep.schedule_created", schedule_id=SCHEDULE_ID)diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/sql.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/sql.pynew file mode 100644index 000000000000..2f63833d0070--- /dev/null+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/sql.py@@ -0,0 +1,52 @@+"""ClickHouse statement for the surfacing-score export sweep."""++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,+ %(day_start)s ('YYYY-MM-DD 00:00:00', UTC), %(cursor_session_id)s,+ %(cursor_team_id)s, %(page_size)s.++ 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+ the slice is exhausted. The raw-row prefilter prunes on the+ `min_first_timestamp` ordering key; the +1 day buffer covers+ boundary-straddling rows, and the exact day cut is in HAVING on the+ aggregated min (the score writeback row sits at session start +1µs, so it+ is always in-window).++ Deletion markers are timestamped at deletion time, not session start, so+ the day-window scan can't see them; the GLOBAL NOT IN subquery matches+ them from the session's day onward with no upper bound. GLOBAL because+ markers are written with an empty distinct_id and can shard away from+ the session's rows.+ """+ return f"""+SELECT+ team_id,+ session_id,+ min(min_first_timestamp) AS started_at,+ max(surfacing_score) AS score+FROM {replay_events_table}+WHERE cityHash64(session_id) %% %(of_chunks)s = %(chunk_id)s+ AND team_id IN %(team_ids)s+ AND (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)+ AND (team_id, session_id) GLOBAL NOT IN (+ SELECT team_id, session_id+ FROM {replay_events_table}+ WHERE cityHash64(session_id) %% %(of_chunks)s = %(chunk_id)s+ AND team_id IN %(team_ids)s+ AND min_first_timestamp >= toDateTime(%(day_start)s, 'UTC')+ AND is_deleted = 1+ )+GROUP BY team_id, session_id+HAVING score IS NOT NULL+ AND started_at >= toDateTime(%(day_start)s, 'UTC')+ AND started_at < toDateTime(%(day_start)s, 'UTC') + toIntervalDay(1)+ORDER BY session_id, team_id+LIMIT %(page_size)s+""".strip()diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/types.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/types.pynew file mode 100644index 000000000000..af4a2e6b602a--- /dev/null+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/types.py@@ -0,0 +1,38 @@+"""Workflow inputs/outputs. Specs carry a day + hash bucket only — ids and scores never cross the workflow boundary."""++from dataclasses import dataclass, field+++@dataclass+class ExportScoresSweepInputs:+ pass+++@dataclass+class ExportPartitionSpec:+ day: str # YYYY-MM-DD (UTC)+ chunk_id: int+ of_chunks: int+++@dataclass+class ListExportPartitionsResult:+ partitions: list[ExportPartitionSpec] = field(default_factory=list)+ disabled_reason: str | None = None+++@dataclass+class ExportPartitionResult:+ day: str+ chunk_id: int+ rows: int = 0+ bytes_written: int = 0+ key: str = ""+++@dataclass+class ExportScoresSweepResult:+ partitions_dispatched: int = 0+ partitions_failed: int = 0+ total_rows: int = 0+ disabled_reason: str | None = Nonediff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.pynew file mode 100644index 000000000000..41ad60d17b6c--- /dev/null+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.py@@ -0,0 +1,96 @@+"""Daily tick: plan the (day × hash bucket) fan-out, export all partitions in parallel.+Failed partitions don't fail the tick — deterministic keys mean the next run rewrites them."""++from __future__ import annotations++import asyncio++from temporalio import workflow+from temporalio.common import RetryPolicy++from posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.session_replay.surfacing_score_export_sweep.constants import (+ EXPORT_PARTITION_ACTIVITY_TIMEOUT,+ EXPORT_PARTITION_HEARTBEAT_TIMEOUT,+ LIST_PARTITIONS_ACTIVITY_TIMEOUT,+ WORKFLOW_NAME,+)+from posthog.temporal.session_replay.surfacing_score_export_sweep.types import (+ ExportPartitionResult,+ ExportPartitionSpec,+ ExportScoresSweepInputs,+ ExportScoresSweepResult,+)++with workflow.unsafe.imports_passed_through():+ from posthog.temporal.session_replay.surfacing_score_export_sweep.activities import (+ export_scores_partition_activity,+ list_export_partitions_activity,+ )++[email protected](name=WORKFLOW_NAME)+class ExportSurfacingScoresWorkflow(PostHogWorkflow):+ inputs_cls = ExportScoresSweepInputs+ inputs_optional = True++ @workflow.run+ async def run(self, inputs: ExportScoresSweepInputs) -> ExportScoresSweepResult:+ plan = await workflow.execute_activity(+ list_export_partitions_activity,+ inputs,+ start_to_close_timeout=LIST_PARTITIONS_ACTIVITY_TIMEOUT,+ retry_policy=RetryPolicy(maximum_attempts=2),+ )++ if plan.disabled_reason is not None:+ workflow.logger.warning("surfacing_score_export_sweep.disabled", disabled_reason=plan.disabled_reason)+ return ExportScoresSweepResult(disabled_reason=plan.disabled_reason)++ if not plan.partitions:+ workflow.logger.info("surfacing_score_export_sweep.no_work")+ return ExportScoresSweepResult()++ results = await asyncio.gather(+ *(self._export_partition(spec) for spec in plan.partitions),+ return_exceptions=True,+ )+ return _summarize(plan.partitions, results)++ async def _export_partition(self, spec: ExportPartitionSpec) -> ExportPartitionResult:+ return await workflow.execute_activity(+ export_scores_partition_activity,+ spec,+ start_to_close_timeout=EXPORT_PARTITION_ACTIVITY_TIMEOUT,+ heartbeat_timeout=EXPORT_PARTITION_HEARTBEAT_TIMEOUT,+ retry_policy=RetryPolicy(+ maximum_attempts=3,+ non_retryable_error_types=[+ "PseudonymKeyNotConfiguredError",+ "PseudonymKeyFingerprintMismatchError",+ ],+ ),+ )+++def _summarize(+ partitions: list[ExportPartitionSpec], results: list[ExportPartitionResult | BaseException]+) -> ExportScoresSweepResult:+ summary = ExportScoresSweepResult(partitions_dispatched=len(partitions))+ for r in results:+ if isinstance(r, asyncio.CancelledError):+ raise r+ if isinstance(r, BaseException):+ summary.partitions_failed += 1+ workflow.logger.warning(+ "surfacing_score_export_sweep.partition_failed", error=str(r), error_type=type(r).__name__+ )+ continue+ summary.total_rows += r.rows+ workflow.logger.info(+ "surfacing_score_export_sweep.tick_done",+ partitions_dispatched=summary.partitions_dispatched,+ partitions_failed=summary.partitions_failed,+ total_rows=summary.total_rows,+ )+ return summarydiff --git a/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/__init__.py b/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --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.pynew file mode 100644index 000000000000..42e498e13889--- /dev/null+++ b/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/test_export.py@@ -0,0 +1,87 @@+# 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,+ _page_table,+ export_days,+)+from posthog.temporal.session_replay.surfacing_score_export_sweep.constants import (+ 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:+ def test_never_includes_days_before_the_floor(self) -> None:+ days = export_days(date(2026, 7, 6))+ assert days == [EXPORT_FLOOR_DAY.isoformat(), "2026-07-05"]++ def test_excludes_the_current_incomplete_day(self) -> None:+ today = date(2027, 1, 15)+ days = export_days(today)+ assert today.isoformat() not in days+ assert max(days) == "2027-01-14"+ assert len(days) == REEXPORT_WINDOW_DAYS++ def test_empty_before_any_complete_day_past_the_floor(self) -> None:+ assert export_days(EXPORT_FLOOR_DAY) == []+++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.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"+ 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["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([])))+ assert table.num_rows == 0+ assert table.schema.names == ["session_id", "team_id", "started_at", "surfacing_score"]