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): drop schema guard blocking migration 0322 (#100938)

Arno Hillen7d152d865743
diff --git a/docs/internal/mobile-replay-capture-mode.md b/docs/internal/mobile-replay-capture-mode.md
index 2d2514da9d20..a9a5626bc0e1 100644
--- a/docs/internal/mobile-replay-capture-mode.md
+++ b/docs/internal/mobile-replay-capture-mode.md
@@ -70,9 +70,8 @@ Keep the `unknown` count visible to distinguish missing classifications from wir
Existing installations need schema cleanup before deploying this change.
Coordinate with the ClickHouse team to remove the old stored `snapshot_mode` column and align `snapshot_source` to `AggregateFunction(argMin, Nullable(String), DateTime64(6, 'UTC'))` on the sharded, writable, and read tables.
-Migration `0322` checks these prerequisites on every target node before adding columns or replacing the materialized views.
-If a check fails, the migration stops without changing tables or views.
-Complete the coordinated cleanup, then retry the migration.
+Migration `0322` adds `snapshot_mode_v2` with `ADD COLUMN IF NOT EXISTS` and does not check these prerequisites.
+Run the coordinated cleanup separately; the migration does not block on it.
Changes to historical migrations apply to fresh installations and do not repair tables on installations that already ran them.
The replacement-column migration does not perform this cleanup or convert existing source aggregate states.
diff --git a/posthog/clickhouse/migrations/0322_add_snapshot_mode_v2_to_session_replay_events.py b/posthog/clickhouse/migrations/0322_add_snapshot_mode_v2_to_session_replay_events.py
index f20e9d72024d..f9b02338deda 100644
--- a/posthog/clickhouse/migrations/0322_add_snapshot_mode_v2_to_session_replay_events.py
+++ b/posthog/clickhouse/migrations/0322_add_snapshot_mode_v2_to_session_replay_events.py
@@ -8,41 +8,12 @@ from posthog.session_recordings.sql.session_replay_event_sql import (
SESSION_REPLAY_EVENTS_WS_MV_SQL,
)
-CHECK_REPLAY_SCHEMA = """
-SELECT throwIf(
- countIf(name = 'snapshot_mode') > 0
- OR countIf(
- name = 'snapshot_source'
- AND type = 'AggregateFunction(argMin, Nullable(String), DateTime64(6, ''UTC''))'
- ) != 1,
- 'Replay metadata schema is not ready on {table_name}. Complete the ClickHouse cleanup in docs/internal/mobile-replay-capture-mode.md before retrying migration 0322.'
-)
-FROM system.columns
-WHERE database = currentDatabase() AND table = '{table_name}'
-"""
-
ADD_SNAPSHOT_MODE_V2 = """
ALTER TABLE {table_name}
ADD COLUMN IF NOT EXISTS snapshot_mode_v2 AggregateFunction(argMin, Nullable(String), DateTime64(6, 'UTC'))
"""
operations = [
- # Validate every replica before DDL; replicated ALTERs only run on one host per shard.
- run_sql_with_exceptions(
- CHECK_REPLAY_SCHEMA.format(table_name="sharded_session_replay_events"),
- node_roles=[NodeRole.DATA],
- require_hosts=True,
- ),
- run_sql_with_exceptions(
- CHECK_REPLAY_SCHEMA.format(table_name="writable_session_replay_events"),
- node_roles=[NodeRole.DATA, NodeRole.INGESTION_SMALL],
- require_hosts=True,
- ),
- run_sql_with_exceptions(
- CHECK_REPLAY_SCHEMA.format(table_name="session_replay_events"),
- node_roles=[NodeRole.DATA],
- require_hosts=True,
- ),
run_sql_with_exceptions(
ADD_SNAPSHOT_MODE_V2.format(table_name="sharded_session_replay_events"),
node_roles=[NodeRole.DATA],
diff --git a/posthog/clickhouse/test/test_session_replay_mode.py b/posthog/clickhouse/test/test_session_replay_mode.py
index c23d65f7ceb3..ea76e5c1240f 100644
--- a/posthog/clickhouse/test/test_session_replay_mode.py
+++ b/posthog/clickhouse/test/test_session_replay_mode.py
@@ -1,4 +1,3 @@
-import re
from collections.abc import Callable
from importlib import import_module
from uuid import uuid4
@@ -7,8 +6,6 @@ import pytest
from django.conf import settings
-from clickhouse_driver.errors import ServerException
-
from posthog.clickhouse.client import sync_execute
from posthog.session_recordings.sql.session_replay_event_sql import (
KAFKA_SESSION_REPLAY_EVENTS_TABLE_BASE_SQL,
@@ -91,78 +88,3 @@ def test_replay_metadata_reads_old_parts_and_classified_blocks(mv_sql: Callable[
sync_execute(f"DROP VIEW IF EXISTS {database}.{view}")
sync_execute(f"DROP TABLE IF EXISTS {database}.{source}")
sync_execute(f"DROP TABLE IF EXISTS {database}.{target}")
-
-
- "unprepared_table", ["sharded_session_replay_events", "writable_session_replay_events", "session_replay_events"]
-)
[email protected]("problem", ["source_type", "legacy_mode"])
-def test_mode_migration_rejects_unprepared_schema_before_changing_tables(unprepared_table: str, problem: str) -> None:
- migration = import_module("posthog.clickhouse.migrations.0322_add_snapshot_mode_v2_to_session_replay_events")
- suffix = uuid4().hex
- tables = ["sharded_session_replay_events", "writable_session_replay_events", "session_replay_events"]
- views = ["session_replay_events_mv", "session_replay_events_ws_mv"]
- source = "kafka_session_replay_events"
- names = {name: f"{name}_{suffix}" for name in [*tables, *views, source]}
- name_pattern = re.compile(r"\b(" + "|".join(names) + r")\b")
- source_column = " snapshot_source AggregateFunction(argMin, Nullable(String), DateTime64(6, 'UTC')),\n"
- mode_column = " snapshot_mode_v2 AggregateFunction(argMin, Nullable(String), DateTime64(6, 'UTC')),\n"
- prepared_schema = SESSION_REPLAY_EVENTS_TABLE_BASE_SQL.replace(mode_column, "")
-
- def create_target(table: str, *, prepared: bool) -> None:
- schema = prepared_schema
- if not prepared:
- if problem == "source_type":
- schema = schema.replace(
- source_column, source_column.replace("Nullable(String)", "LowCardinality(Nullable(String))")
- )
- else:
- schema = schema.replace(
- source_column, source_column + mode_column.replace("snapshot_mode_v2", "snapshot_mode")
- )
- sync_execute(schema.format(table_name=names[table], on_cluster_clause="", engine="Memory"))
-
- def run_migration() -> None:
- for operation in migration.operations:
- sync_execute(name_pattern.sub(lambda match: names[match[0]], operation._sql))
-
- try:
- for table in tables:
- create_target(table, prepared=table != unprepared_table)
- sync_execute(
- KAFKA_SESSION_REPLAY_EVENTS_TABLE_BASE_SQL.replace(
- ") ENGINE = {engine}", "_timestamp DateTime\n) ENGINE = {engine}"
- ).format(table_name=names[source], on_cluster_clause="", engine="Memory")
- )
- for view in views:
- sync_execute(f"CREATE VIEW {names[view]} AS SELECT 1")
-
- with pytest.raises(ServerException, match="Replay metadata schema is not ready"):
- run_migration()
-
- assert sync_execute(
- "SELECT count() FROM system.columns WHERE database = currentDatabase() "
- "AND table IN %(tables)s AND name = 'snapshot_mode_v2'",
- {"tables": tuple(names[table] for table in tables)},
- ) == [(0,)]
- assert sync_execute(
- "SELECT count() FROM system.tables WHERE database = currentDatabase() "
- "AND name IN %(views)s AND engine = 'View'",
- {"views": tuple(names[view] for view in views)},
- ) == [(2,)]
-
- sync_execute(f"DROP TABLE {names[unprepared_table]}")
- create_target(unprepared_table, prepared=True)
- run_migration()
- assert sync_execute(
- "SELECT count() FROM system.columns WHERE database = currentDatabase() "
- "AND table IN %(tables)s AND name = 'snapshot_mode_v2'",
- {"tables": tuple(names[table] for table in tables)},
- ) == [(3,)]
- assert sync_execute(
- "SELECT engine FROM system.tables WHERE database = currentDatabase() AND name = %(view)s",
- {"view": names[views[0]]},
- ) == [("MaterializedView",)]
- finally:
- for name in [*views, source, *tables]:
- sync_execute(f"DROP TABLE IF EXISTS {names[name]}")