: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(sessions): recreate the sessions v3 ingestion pipeline as a migration (#104026)
Andy Zhao854a4262ec8b
diff --git a/posthog/clickhouse/kafka_engine.py b/posthog/clickhouse/kafka_engine.pyindex 6c8fd27f5419..92fceb8e4eab 100644--- a/posthog/clickhouse/kafka_engine.py+++ b/posthog/clickhouse/kafka_engine.py@@ -52,6 +52,8 @@ CONSUMER_GROUP_INGESTION_WARNINGS_WS = "clickhouse_ingestion_warnings_ws"CONSUMER_GROUP_INGESTION_WARNINGS_V2 = "clickhouse_ingestion_warnings_v2"CONSUMER_GROUP_SESSION_REPLAY_EVENTS_WS = "clickhouse_session_replay_events_ws"CONSUMER_GROUP_SESSION_REPLAY_FEATURES_WS = "clickhouse_session_replay_features_ws"+# The ws2 suffix keeps this group distinct from the retired hand-managed pipeline.+CONSUMER_GROUP_RAW_SESSIONS_V3_EVENTS_JSON_WS = "clickhouse_raw_sessions_v3_events_json_ws2"CONSUMER_GROUP_COHORT_MEMBERSHIP_WS = "clickhouse_cohort_membership_ws"# WarpStream-shared consumer groups (topics moved to warpstream-shared VC; coexist with MSKdiff --git a/posthog/clickhouse/migrations/0328_sessions_v3_ws_pipeline.py b/posthog/clickhouse/migrations/0328_sessions_v3_ws_pipeline.pynew file mode 100644index 000000000000..2dbb1a3c0923--- /dev/null+++ b/posthog/clickhouse/migrations/0328_sessions_v3_ws_pipeline.py@@ -0,0 +1,47 @@+from posthog.clickhouse.client.connection import NodeRole+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions+from posthog.models.raw_sessions.migrations_v3 import ADD_EMAILS, ADD_FLAG_KEY_VALUES, ADD_HOSTS+from posthog.models.raw_sessions.sessions_v3 import (+ KAFKA_RAW_SESSIONS_V3_TABLE_SQL,+ RAW_SESSIONS_V3_EVENTS_WS_MV_SQL,+ WRITABLE_RAW_SESSIONS_INGESTION_TABLE_SQL_V3,+ WRITABLE_RAW_SESSIONS_TABLE_V3,+)+from posthog.run_mode import run_mode++operations = (+ []+ if not run_mode().is_deployed_cloud+ else [+ run_sql_with_exceptions(+ WRITABLE_RAW_SESSIONS_INGESTION_TABLE_SQL_V3(),+ node_roles=[NodeRole.INGESTION_EVENTS],+ ),+ run_sql_with_exceptions(+ ADD_FLAG_KEY_VALUES.format(table_name=WRITABLE_RAW_SESSIONS_TABLE_V3()),+ node_roles=[NodeRole.INGESTION_EVENTS],+ sharded=False,+ is_alter_on_replicated_table=False,+ ),+ run_sql_with_exceptions(+ ADD_HOSTS.format(table_name=WRITABLE_RAW_SESSIONS_TABLE_V3()),+ node_roles=[NodeRole.INGESTION_EVENTS],+ sharded=False,+ is_alter_on_replicated_table=False,+ ),+ run_sql_with_exceptions(+ ADD_EMAILS.format(table_name=WRITABLE_RAW_SESSIONS_TABLE_V3()),+ node_roles=[NodeRole.INGESTION_EVENTS],+ sharded=False,+ is_alter_on_replicated_table=False,+ ),+ run_sql_with_exceptions(+ KAFKA_RAW_SESSIONS_V3_TABLE_SQL(),+ node_roles=[NodeRole.INGESTION_EVENTS],+ ),+ run_sql_with_exceptions(+ RAW_SESSIONS_V3_EVENTS_WS_MV_SQL(),+ node_roles=[NodeRole.INGESTION_EVENTS],+ ),+ ]+)diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txtindex 77f13daaf2cc..6e9eaef8f55b 100644--- a/posthog/clickhouse/migrations/max_migration.txt+++ b/posthog/clickhouse/migrations/max_migration.txt@@ -1 +1 @@-0327_metrics4+0328_sessions_v3_ws_pipelinediff --git a/posthog/models/raw_sessions/sessions_v3.py b/posthog/models/raw_sessions/sessions_v3.pyindex 7fddd6eeaf89..265348911e71 100644--- a/posthog/models/raw_sessions/sessions_v3.py+++ b/posthog/models/raw_sessions/sessions_v3.py@@ -2,7 +2,15 @@ from typing import Optionalfrom django.conf import settings+from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE+from posthog.clickhouse.kafka_engine import (+ CONSUMER_GROUP_RAW_SESSIONS_V3_EVENTS_JSON_WS,+ kafka_engine,+ kafka_num_consumers,+)from posthog.clickhouse.table_engines import AggregatingMergeTree, Distributed, ReplicationScheme+from posthog.kafka_client.topics import KAFKA_EVENTS_JSON+from posthog.models.event.sql import EVENTS_TABLE_BASE_SQL, EVENTS_TABLE_DYNAMICALLY_MATERIALIZED_COLUMNS"""Raw sessions table v3@@ -307,10 +315,10 @@ PROPERTIES = f"""tupleElement(p, '$host') as _host"""-def RAW_SESSION_TABLE_MV_SELECT_SQL_V3(source_table, where="TRUE", include_session_timestamp=False):+def RAW_SESSION_TABLE_MV_SELECT_SQL_V3(source_table, where="TRUE", include_session_timestamp=False, extra_ctes=""):return """WITH- {PROPERTIES},+ {extra_ctes}{PROPERTIES},-- attribution properties from non-pageview/screen events should be deprioritized, so make the timestamp +/- 1 year so they sort lastif (event = '$pageview' OR event = '$screen', timestamp, timestamp + toIntervalYear(1)) as pageview_prio_timestamp_min,if (event = '$pageview' OR event = '$screen', timestamp, timestamp - toIntervalYear(1)) as pageview_prio_timestamp_max@@ -401,6 +409,7 @@ AND {where}source_table=source_table,where=where,PROPERTIES=PROPERTIES,+ extra_ctes=extra_ctes,session_timestamp="fromUnixTimestamp64Milli(toUInt64(bitShiftRight(`$session_id_uuid`, 80))) AS session_timestamp,"if include_session_timestampelse "",@@ -438,6 +447,90 @@ MODIFY QUERY)+# WarpStream ingestion pipeline on the ingestion-events cluster: Kafka table -> MV -> writable.+# The ws2 names stay clear of the earlier hand-managed pipeline's objects, which hold the+# unsuffixed names outside repo control.++KAFKA_RAW_SESSIONS_V3_TABLE = "kafka_raw_sessions_v3_events_json_ws2"+RAW_SESSIONS_V3_EVENTS_WS_MV = "raw_sessions_v3_events_json_ws2_mv"++# The Kafka stream carries raw event JSON, so the columns the select reads from sharded_events+# as materialized columns are derived here instead. The flags map expression matches the+# properties_group_feature_flags materializer in posthog/clickhouse/property_groups.py.+KAFKA_SOURCE_COLUMN_CTES = """JSONExtractString(properties, '$session_id') AS `$session_id`,+ toUInt128(JSONExtract(properties, '$session_id', 'Nullable(UUID)')) AS `$session_id_uuid`,+ mapSort(mapFilter((key, _) -> key LIKE '$feature/%', CAST(JSONExtractKeysAndValues(properties, 'String'), 'Map(String, String)'))) AS properties_group_feature_flags,+ _timestamp AS inserted_at,+ """+++def KAFKA_RAW_SESSIONS_V3_TABLE_SQL():+ return (+ EVENTS_TABLE_BASE_SQL+ + """+ SETTINGS kafka_skip_broken_messages = 100,+ kafka_num_consumers = {num_consumers},+ kafka_thread_per_consumer = 1,+ kafka_poll_timeout_ms = 10000,+ kafka_max_block_size = 100000+"""+ ).format(+ num_consumers=kafka_num_consumers(1),+ table_name=KAFKA_RAW_SESSIONS_V3_TABLE,+ on_cluster_clause=ON_CLUSTER_CLAUSE(False),+ engine=kafka_engine(+ topic=KAFKA_EVENTS_JSON,+ group=CONSUMER_GROUP_RAW_SESSIONS_V3_EVENTS_JSON_WS,+ named_collection=settings.CLICKHOUSE_KAFKA_WARPSTREAM_INGESTION_NAMED_COLLECTION,+ ),+ extra_fields="",+ dynamically_materialized_columns=EVENTS_TABLE_DYNAMICALLY_MATERIALIZED_COLUMNS(),+ materialized_columns="",+ indexes="",+ )+++def WRITABLE_RAW_SESSIONS_INGESTION_TABLE_SQL_V3():+ # On the ingestion layer the writable points at the sessions satellite cluster, where the+ # live raw_sessions_v3 MergeTree lives. Cloud-only, so the cluster name has no settings entry.+ return RAW_SESSIONS_TABLE_BASE_SQL_V3.format(+ table_name=WRITABLE_RAW_SESSIONS_TABLE_V3(),+ engine=Distributed(+ data_table=TABLE_BASE_NAME_V3,+ sharding_key="cityHash64(session_id_v7)",+ cluster="sessions",+ ),+ session_timestamp_modifier="DEFAULT",+ max_hosts=SESSION_V3_MAX_HOSTS_PER_SESSION,+ max_emails=SESSION_V3_MAX_EMAILS_PER_SESSION,+ )+++def RAW_SESSIONS_V3_EVENTS_WS_MV_SQL():+ return """+CREATE MATERIALIZED VIEW IF NOT EXISTS {mv_name}+TO {database}.{target_table}+AS+{select_sql}+""".format(+ mv_name=RAW_SESSIONS_V3_EVENTS_WS_MV,+ database=settings.CLICKHOUSE_DATABASE,+ target_table=WRITABLE_RAW_SESSIONS_TABLE_V3(),+ select_sql=RAW_SESSION_TABLE_MV_SELECT_SQL_V3(+ source_table=f"{settings.CLICKHOUSE_DATABASE}.{KAFKA_RAW_SESSIONS_V3_TABLE}",+ extra_ctes=KAFKA_SOURCE_COLUMN_CTES,+ ),+ )+++def DROP_RAW_SESSIONS_V3_EVENTS_WS_MV_SQL():+ return f"DROP TABLE IF EXISTS {RAW_SESSIONS_V3_EVENTS_WS_MV}"+++def DROP_KAFKA_RAW_SESSIONS_V3_TABLE_SQL():+ return f"DROP TABLE IF EXISTS {KAFKA_RAW_SESSIONS_V3_TABLE}"++def RAW_SESSION_TABLE_MV_RECORDINGS_SELECT_SQL_V3(source_table, where="TRUE", include_session_timestamp=False):return """WITH