: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(clickhouse): rich clickhouse test setup (#57981)
Paweł Szczur16b60ece678f
diff --git a/.github/workflows/ci-clickhouse-multinode-migrations.yml b/.github/workflows/ci-clickhouse-multinode-migrations.ymlnew file mode 100644index 000000000000..9d8e4da21dcb--- /dev/null+++ b/.github/workflows/ci-clickhouse-multinode-migrations.yml@@ -0,0 +1,83 @@+name: ClickHouse Multinode Migration Smoke++on:+ push:+ branches:+ - master+ pull_request:+ paths:+ - 'posthog/clickhouse/migrations/**'+ - 'posthog/models/**/sql.py'+ - 'posthog/settings/data_stores.py'+ - 'posthog/clickhouse/cluster.py'+ - 'posthog/clickhouse/client/migration_tools.py'+ - 'docker/clickhouse/config.d/multinode/**'+ - 'docker-compose.multinode-clickhouse.yml'+ - 'tools/infra-scripts/clickhouse-multinode/**'+ - '.github/workflows/ci-clickhouse-multinode-migrations.yml'+ merge_group:+ workflow_dispatch:++concurrency:+ group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++permissions:+ contents: read++jobs:+ multinode-migration-smoke:+ name: Run ClickHouse migrations against per-cluster topology+ runs-on: ubuntu-24.04+ timeout-minutes: 25+ env:+ DEBUG: '1'+ MULTINODE_CLICKHOUSE: '1'+ CLICKHOUSE_HOST: localhost+ CLICKHOUSE_MIGRATIONS_HOST: localhost+ CLICKHOUSE_DATABASE: posthog+ CLICKHOUSE_USER: default+ CLICKHOUSE_PASSWORD: ''+ CLICKHOUSE_SECURE: 'false'+ CLICKHOUSE_VERIFY: 'false'+ DATABASE_URL: 'postgres://posthog:posthog@localhost:5432/posthog'+ REDIS_URL: 'redis://localhost'+ # unsafe - for testing only+ SECRET_KEY: '6b01eee4f945ca25045b5aab440b953461faf08693a9abbf1166dc7c6b9772da'+ steps:+ - uses: actions/checkout@v6++ - name: Add multinode hostnames to /etc/hosts+ run: |+ echo "127.0.0.1 clickhouse-data clickhouse-ai-events clickhouse-aux clickhouse-ops clickhouse-sessions kafka zookeeper" | sudo tee -a /etc/hosts++ - name: Set up Python+ uses: actions/setup-python@v6+ with:+ python-version: 3.12.12++ - name: Install uv+ uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0+ with:+ version: '0.10.2'+ enable-cache: true+ cache-dependency-glob: uv.lock++ - name: Install Python dependencies+ run: UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev++ - name: Run smoke test+ run: tools/infra-scripts/clickhouse-multinode/multinode-migration-smoke++ - name: Dump compose logs on failure+ if: failure()+ run: |+ docker compose -f docker-compose.multinode-clickhouse.yml logs --no-color > multinode-compose.log || true++ - name: Upload compose logs on failure+ if: failure()+ uses: actions/upload-artifact@v4+ with:+ name: multinode-compose-logs+ path: multinode-compose.log+ if-no-files-found: ignorediff --git a/docker-compose.dev-coordinator.yml b/docker-compose.dev-coordinator.ymldeleted file mode 100644index 4be85df8f3b6..000000000000--- a/docker-compose.dev-coordinator.yml+++ /dev/null@@ -1,221 +0,0 @@-#-# docker-compose file used ONLY for local development using a coordinator topology in ClickHouse.-# For more info, see:-# https://posthog.com/handbook/engineering/developing-locally-#-# PostHog has sunset support for self-hosted K8s deployments.-# See: https://posthog.com/blog/sunsetting-helm-support-posthog-#--services:- proxy:- extends:- file: docker-compose.base.yml- service: proxy- ports:- - 8010:8000- depends_on:- - replay-capture- - capture- - feature-flags- extra_hosts:- - 'web:host-gateway'- db:- extends:- file: docker-compose.base.yml- service: db- ports:- - '5432:5432'- volumes:- - postgres-15-data:/var/lib/postgresql/data- # something in the django app when running in dev mode- # (maybe only in Pycharm) keeps many idle transactions open- # and eventually kills postgres, these settings aim to stop that happening.- # They are only for DEV and should not be used in production.- command: postgres -c max_connections=1000 -c idle_in_transaction_session_timeout=300000- redis7:- extends:- file: docker-compose.base.yml- service: redis7- ports:- - '6379:6379'-- flower:- extends:- file: docker-compose.base.yml- service: flower- ports:- - '5555:5555'-- clickhouse: &clickhouse- extends:- file: docker-compose.base.yml- service: clickhouse- hostname: clickhouse- ports:- - '8123:8123'- - '8443:8443'- - '9000:9000'- - '9440:9440'- - '9009:9009'- volumes:- # this new entrypoint file is to fix a bug detailed here https://github.com/ClickHouse/ClickHouse/pull/59991- # revert this when we upgrade clickhouse- - ./docker/clickhouse/entrypoint.sh:/entrypoint.sh- - ./posthog/idl:/idl- - ./docker/clickhouse/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d- - ./docker/clickhouse/config.xml:/etc/clickhouse-server/config.xml- - ./docker/clickhouse/config.d/data_node.xml:/etc/clickhouse-server/config.d/data_node.xml- - ./docker/clickhouse/users-dev.xml:/etc/clickhouse-server/users.xml- - ./docker/clickhouse/user_defined_function.xml:/etc/clickhouse-server/user_defined_function.xml- - ./posthog/user_scripts:/var/lib/clickhouse/user_scripts- extra_hosts:- - 'host.docker.internal:host-gateway'- depends_on:- - kafka- - zookeeper-- clickhouse-coordinator:- hostname: clickhouse-coordinator- <<: *clickhouse- volumes:- # this new entrypoint file is to fix a bug detailed here https://github.com/ClickHouse/ClickHouse/pull/59991- # revert this when we upgrade clickhouse- - ./docker/clickhouse/entrypoint.sh:/entrypoint.sh- - ./posthog/idl:/idl- - ./docker/clickhouse/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d- - ./docker/clickhouse/config.xml:/etc/clickhouse-server/config.xml- - ./docker/clickhouse/config.d/coordinator.xml:/etc/clickhouse-server/config.d/coordinator.xml- - ./docker/clickhouse/users-dev.xml:/etc/clickhouse-server/users.xml- - ./docker/clickhouse/user_defined_function.xml:/etc/clickhouse-server/user_defined_function.xml- - ./posthog/user_scripts:/var/lib/clickhouse/user_scripts- ports:- - '9001:9001'-- zookeeper:- extends:- file: docker-compose.base.yml- service: zookeeper- ports:- - '2181:2181'-- kafka:- extends:- file: docker-compose.base.yml- service: kafka- ports:- - '9092:9092'- depends_on:- - zookeeper-- kafka_ui:- extends:- file: docker-compose.base.yml- service: kafka_ui- ports:- - '9093:8080'- depends_on:- - kafka-- objectstorage:- extends:- file: docker-compose.base.yml- service: objectstorage- ports:- - '19000:19000'- - '19001:19001'-- maildev:- extends:- file: docker-compose.base.yml- service: maildev- ports:- - '1080:1080'- - '1025:1025'-- webhook-tester:- image: tarampampam/webhook-tester:2.2.6- restart: on-failure- ports:- - '2080:8080'- environment:- - AUTO_CREATE_SESSIONS=true-- # capture-rs- capture:- extends:- file: docker-compose.base.yml- service: capture- environment:- - DEBUG=1- depends_on:- - redis7- - kafka-- # replay capture-rs- replay-capture:- extends:- file: docker-compose.base.yml- service: replay-capture- depends_on:- - redis7- - kafka-- property-defs-rs:- extends:- file: docker-compose.base.yml- service: property-defs-rs- depends_on:- - kafka-- feature-flags:- extends:- file: docker-compose.base.yml- service: feature-flags- depends_on:- - redis7- - db-- # Temporal containers- elasticsearch:- extends:- file: docker-compose.base.yml- service: elasticsearch- expose:- - 9200-- temporal:- extends:- file: docker-compose.base.yml- service: temporal-- temporal-admin-tools:- extends:- file: docker-compose.base.yml- service: temporal-admin-tools- depends_on:- - temporal- temporal-ui:- extends:- file: docker-compose.base.yml- service: temporal-ui- depends_on:- temporal:- condition: service_started- db:- condition: service_healthy-- cyclotron-janitor:- extends:- file: docker-compose.base.yml- service: cyclotron-janitor- environment:- DATABASE_URL: 'postgres://posthog:posthog@db:5432/cyclotron'- RUST_LOG: 'info'- depends_on:- db:- condition: service_healthy--volumes:- postgres-15-data:- redpanda-data:diff --git a/docker-compose.multinode-clickhouse.yml b/docker-compose.multinode-clickhouse.ymlnew file mode 100644index 000000000000..a674e5d964e7--- /dev/null+++ b/docker-compose.multinode-clickhouse.yml@@ -0,0 +1,140 @@+#+# Multi-node ClickHouse smoke-test stack.+#+# Boots one ClickHouse server per logical cluster (data + ai_events + aux + ops + sessions)+# so migration runs can be verified against a topology that resembles production.+# Opt-in only: not used by `bin/start` or any of the default dev/CI flows.+# Driven by `tools/infra-scripts/clickhouse-multinode/multinode-migration-smoke`+# and `tools/infra-scripts/clickhouse-multinode/start-multinode-clickhouse`.+#+# Each ClickHouse extends the base service and mounts a per-role config file from+# docker/clickhouse/config.d/multinode/. Ports are offset to avoid clashing with a+# single-node `clickhouse` container that may be running on 9000/8123.+#+# A distinct compose project name keeps volumes / networks separate from+# `bin/start` (which uses the default `posthog` project), so Zookeeper/Kafka+# state from a previous dev run can't leak DDL queue entries that reference+# the old single-node `clickhouse:9000` host.+#++name: posthog-multinode-smoke++services:+ zookeeper:+ extends:+ file: docker-compose.base.yml+ service: zookeeper++ kafka:+ extends:+ file: docker-compose.base.yml+ service: kafka+ depends_on:+ - zookeeper++ db:+ extends:+ file: docker-compose.base.yml+ service: db+ ports:+ - '5432:5432'++ redis7:+ extends:+ file: docker-compose.base.yml+ service: redis7+ ports:+ - '6379:6379'++ clickhouse-data: &clickhouse-multinode+ extends:+ file: docker-compose.base.yml+ service: clickhouse+ hostname: clickhouse-data+ environment:+ CLICKHOUSE_SKIP_USER_SETUP: 1+ KAFKA_HOSTS: 'kafka:9092'+ volumes:+ - ./posthog/idl:/idl+ - ./docker/clickhouse/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d+ - ./docker/clickhouse/config.xml:/etc/clickhouse-server/config.xml+ - ./docker/clickhouse/config.d/multinode/data_node.xml:/etc/clickhouse-server/config.d/default.xml+ - ./docker/clickhouse/config.d/dev-memory.xml:/etc/clickhouse-server/config.d/dev-memory.xml+ - ./docker/clickhouse/users-dev.xml:/etc/clickhouse-server/users.xml+ - ./docker/clickhouse/user_defined_function.xml:/etc/clickhouse-server/user_defined_function.xml+ - ./posthog/user_scripts:/var/lib/clickhouse/user_scripts+ extra_hosts:+ - 'host.docker.internal:host-gateway'+ depends_on:+ - kafka+ - zookeeper+ ports:+ - '8123:8123'+ - '9000:9000'++ clickhouse-ai-events:+ <<: *clickhouse-multinode+ hostname: clickhouse-ai-events+ volumes:+ - ./posthog/idl:/idl+ - ./docker/clickhouse/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d+ - ./docker/clickhouse/config.xml:/etc/clickhouse-server/config.xml+ - ./docker/clickhouse/config.d/multinode/ai_events_node.xml:/etc/clickhouse-server/config.d/default.xml+ - ./docker/clickhouse/config.d/dev-memory.xml:/etc/clickhouse-server/config.d/dev-memory.xml+ - ./docker/clickhouse/users-dev.xml:/etc/clickhouse-server/users.xml+ - ./docker/clickhouse/user_defined_function.xml:/etc/clickhouse-server/user_defined_function.xml+ - ./posthog/user_scripts:/var/lib/clickhouse/user_scripts+ ports:+ - '8124:8123'+ - '9100:9000'++ clickhouse-aux:+ <<: *clickhouse-multinode+ hostname: clickhouse-aux+ volumes:+ - ./posthog/idl:/idl+ - ./docker/clickhouse/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d+ - ./docker/clickhouse/config.xml:/etc/clickhouse-server/config.xml+ - ./docker/clickhouse/config.d/multinode/aux_node.xml:/etc/clickhouse-server/config.d/default.xml+ - ./docker/clickhouse/config.d/dev-memory.xml:/etc/clickhouse-server/config.d/dev-memory.xml+ - ./docker/clickhouse/users-dev.xml:/etc/clickhouse-server/users.xml+ - ./docker/clickhouse/user_defined_function.xml:/etc/clickhouse-server/user_defined_function.xml+ - ./posthog/user_scripts:/var/lib/clickhouse/user_scripts+ ports:+ - '8125:8123'+ - '9200:9000'++ clickhouse-ops:+ <<: *clickhouse-multinode+ hostname: clickhouse-ops+ volumes:+ - ./posthog/idl:/idl+ - ./docker/clickhouse/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d+ - ./docker/clickhouse/config.xml:/etc/clickhouse-server/config.xml+ - ./docker/clickhouse/config.d/multinode/ops_node.xml:/etc/clickhouse-server/config.d/default.xml+ - ./docker/clickhouse/config.d/dev-memory.xml:/etc/clickhouse-server/config.d/dev-memory.xml+ - ./docker/clickhouse/users-dev.xml:/etc/clickhouse-server/users.xml+ - ./docker/clickhouse/user_defined_function.xml:/etc/clickhouse-server/user_defined_function.xml+ - ./posthog/user_scripts:/var/lib/clickhouse/user_scripts+ ports:+ - '8126:8123'+ - '9300:9000'++ clickhouse-sessions:+ <<: *clickhouse-multinode+ hostname: clickhouse-sessions+ volumes:+ - ./posthog/idl:/idl+ - ./docker/clickhouse/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d+ - ./docker/clickhouse/config.xml:/etc/clickhouse-server/config.xml+ - ./docker/clickhouse/config.d/multinode/sessions_node.xml:/etc/clickhouse-server/config.d/default.xml+ - ./docker/clickhouse/config.d/dev-memory.xml:/etc/clickhouse-server/config.d/dev-memory.xml+ - ./docker/clickhouse/users-dev.xml:/etc/clickhouse-server/users.xml+ - ./docker/clickhouse/user_defined_function.xml:/etc/clickhouse-server/user_defined_function.xml+ - ./posthog/user_scripts:/var/lib/clickhouse/user_scripts+ ports:+ - '8127:8123'+ - '9400:9000'++volumes:+ redpanda-data:diff --git a/docker/clickhouse/config.d/multinode/ai_events_node.xml b/docker/clickhouse/config.d/multinode/ai_events_node.xmlnew file mode 100644index 000000000000..1e7792fa2e9e--- /dev/null+++ b/docker/clickhouse/config.d/multinode/ai_events_node.xml@@ -0,0 +1,126 @@+<clickhouse>+ <tcp_port>9000</tcp_port>++ <remote_servers>+ <posthog>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog>+ <posthog_single_shard>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_single_shard>+ <posthog_writable>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_writable>+ <posthog_primary_replica>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_primary_replica>++ <posthog_migrations>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-ai-events</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-aux</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-ops</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-sessions</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_migrations>++ <ai_events>+ <shard>+ <replica>+ <host>clickhouse-ai-events</host>+ <port>9000</port>+ </replica>+ </shard>+ </ai_events>+ <aux>+ <shard>+ <replica>+ <host>clickhouse-aux</host>+ <port>9000</port>+ </replica>+ </shard>+ </aux>+ <ops>+ <shard>+ <replica>+ <host>clickhouse-ops</host>+ <port>9000</port>+ </replica>+ </shard>+ </ops>+ <sessions>+ <shard>+ <replica>+ <host>clickhouse-sessions</host>+ <port>9000</port>+ </replica>+ </shard>+ </sessions>+ </remote_servers>++ <named_collections>+ <msk_cluster>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </msk_cluster>+ <warpstream_ingestion>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </warpstream_ingestion>+ <warpstream_calculated_events>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </warpstream_calculated_events>+ <warpstream_replay>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </warpstream_replay>+ </named_collections>++ <macros>+ <shard>01</shard>+ <replica>ai</replica>+ <hostClusterType>online</hostClusterType>+ <hostClusterRole>ai_events</hostClusterRole>+ </macros>+</clickhouse>diff --git a/docker/clickhouse/config.d/multinode/aux_node.xml b/docker/clickhouse/config.d/multinode/aux_node.xmlnew file mode 100644index 000000000000..e81c680dfe7b--- /dev/null+++ b/docker/clickhouse/config.d/multinode/aux_node.xml@@ -0,0 +1,126 @@+<clickhouse>+ <tcp_port>9000</tcp_port>++ <remote_servers>+ <posthog>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog>+ <posthog_single_shard>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_single_shard>+ <posthog_writable>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_writable>+ <posthog_primary_replica>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_primary_replica>++ <posthog_migrations>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-ai-events</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-aux</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-ops</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-sessions</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_migrations>++ <ai_events>+ <shard>+ <replica>+ <host>clickhouse-ai-events</host>+ <port>9000</port>+ </replica>+ </shard>+ </ai_events>+ <aux>+ <shard>+ <replica>+ <host>clickhouse-aux</host>+ <port>9000</port>+ </replica>+ </shard>+ </aux>+ <ops>+ <shard>+ <replica>+ <host>clickhouse-ops</host>+ <port>9000</port>+ </replica>+ </shard>+ </ops>+ <sessions>+ <shard>+ <replica>+ <host>clickhouse-sessions</host>+ <port>9000</port>+ </replica>+ </shard>+ </sessions>+ </remote_servers>++ <named_collections>+ <msk_cluster>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </msk_cluster>+ <warpstream_ingestion>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </warpstream_ingestion>+ <warpstream_calculated_events>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </warpstream_calculated_events>+ <warpstream_replay>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </warpstream_replay>+ </named_collections>++ <macros>+ <shard>01</shard>+ <replica>aux</replica>+ <hostClusterType>online</hostClusterType>+ <hostClusterRole>aux</hostClusterRole>+ </macros>+</clickhouse>diff --git a/docker/clickhouse/config.d/multinode/data_node.xml b/docker/clickhouse/config.d/multinode/data_node.xmlnew file mode 100644index 000000000000..ee1a949e00ab--- /dev/null+++ b/docker/clickhouse/config.d/multinode/data_node.xml@@ -0,0 +1,126 @@+<clickhouse>+ <tcp_port>9000</tcp_port>++ <remote_servers>+ <posthog>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog>+ <posthog_single_shard>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_single_shard>+ <posthog_writable>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_writable>+ <posthog_primary_replica>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_primary_replica>++ <posthog_migrations>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-ai-events</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-aux</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-ops</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-sessions</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_migrations>++ <ai_events>+ <shard>+ <replica>+ <host>clickhouse-ai-events</host>+ <port>9000</port>+ </replica>+ </shard>+ </ai_events>+ <aux>+ <shard>+ <replica>+ <host>clickhouse-aux</host>+ <port>9000</port>+ </replica>+ </shard>+ </aux>+ <ops>+ <shard>+ <replica>+ <host>clickhouse-ops</host>+ <port>9000</port>+ </replica>+ </shard>+ </ops>+ <sessions>+ <shard>+ <replica>+ <host>clickhouse-sessions</host>+ <port>9000</port>+ </replica>+ </shard>+ </sessions>+ </remote_servers>++ <named_collections>+ <msk_cluster>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </msk_cluster>+ <warpstream_ingestion>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </warpstream_ingestion>+ <warpstream_calculated_events>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </warpstream_calculated_events>+ <warpstream_replay>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </warpstream_replay>+ </named_collections>++ <macros>+ <shard>01</shard>+ <replica>data</replica>+ <hostClusterType>online</hostClusterType>+ <hostClusterRole>data</hostClusterRole>+ </macros>+</clickhouse>diff --git a/docker/clickhouse/config.d/multinode/ops_node.xml b/docker/clickhouse/config.d/multinode/ops_node.xmlnew file mode 100644index 000000000000..4ee429f916eb--- /dev/null+++ b/docker/clickhouse/config.d/multinode/ops_node.xml@@ -0,0 +1,126 @@+<clickhouse>+ <tcp_port>9000</tcp_port>++ <remote_servers>+ <posthog>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog>+ <posthog_single_shard>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_single_shard>+ <posthog_writable>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_writable>+ <posthog_primary_replica>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_primary_replica>++ <posthog_migrations>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-ai-events</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-aux</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-ops</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-sessions</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_migrations>++ <ai_events>+ <shard>+ <replica>+ <host>clickhouse-ai-events</host>+ <port>9000</port>+ </replica>+ </shard>+ </ai_events>+ <aux>+ <shard>+ <replica>+ <host>clickhouse-aux</host>+ <port>9000</port>+ </replica>+ </shard>+ </aux>+ <ops>+ <shard>+ <replica>+ <host>clickhouse-ops</host>+ <port>9000</port>+ </replica>+ </shard>+ </ops>+ <sessions>+ <shard>+ <replica>+ <host>clickhouse-sessions</host>+ <port>9000</port>+ </replica>+ </shard>+ </sessions>+ </remote_servers>++ <named_collections>+ <msk_cluster>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </msk_cluster>+ <warpstream_ingestion>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </warpstream_ingestion>+ <warpstream_calculated_events>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </warpstream_calculated_events>+ <warpstream_replay>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </warpstream_replay>+ </named_collections>++ <macros>+ <shard>01</shard>+ <replica>ops</replica>+ <hostClusterType>online</hostClusterType>+ <hostClusterRole>ops</hostClusterRole>+ </macros>+</clickhouse>diff --git a/docker/clickhouse/config.d/multinode/sessions_node.xml b/docker/clickhouse/config.d/multinode/sessions_node.xmlnew file mode 100644index 000000000000..b216c7103614--- /dev/null+++ b/docker/clickhouse/config.d/multinode/sessions_node.xml@@ -0,0 +1,126 @@+<clickhouse>+ <tcp_port>9000</tcp_port>++ <remote_servers>+ <posthog>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog>+ <posthog_single_shard>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_single_shard>+ <posthog_writable>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_writable>+ <posthog_primary_replica>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_primary_replica>++ <posthog_migrations>+ <shard>+ <replica>+ <host>clickhouse-data</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-ai-events</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-aux</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-ops</host>+ <port>9000</port>+ </replica>+ </shard>+ <shard>+ <replica>+ <host>clickhouse-sessions</host>+ <port>9000</port>+ </replica>+ </shard>+ </posthog_migrations>++ <ai_events>+ <shard>+ <replica>+ <host>clickhouse-ai-events</host>+ <port>9000</port>+ </replica>+ </shard>+ </ai_events>+ <aux>+ <shard>+ <replica>+ <host>clickhouse-aux</host>+ <port>9000</port>+ </replica>+ </shard>+ </aux>+ <ops>+ <shard>+ <replica>+ <host>clickhouse-ops</host>+ <port>9000</port>+ </replica>+ </shard>+ </ops>+ <sessions>+ <shard>+ <replica>+ <host>clickhouse-sessions</host>+ <port>9000</port>+ </replica>+ </shard>+ </sessions>+ </remote_servers>++ <named_collections>+ <msk_cluster>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </msk_cluster>+ <warpstream_ingestion>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </warpstream_ingestion>+ <warpstream_calculated_events>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </warpstream_calculated_events>+ <warpstream_replay>+ <kafka_broker_list from_env="KAFKA_HOSTS"/>+ </warpstream_replay>+ </named_collections>++ <macros>+ <shard>01</shard>+ <replica>sess</replica>+ <hostClusterType>online</hostClusterType>+ <hostClusterRole>sessions</hostClusterRole>+ </macros>+</clickhouse>diff --git a/hogli.yaml b/hogli.yamlindex e5f3ab3528c7..948e0cf0e7f9 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -808,6 +808,18 @@ tools:bin_script: clickhouse-metrics-initdescription: Initialize ClickHouse metrics schema (temporary, pre-migration)hidden: true+ clickhouse:multinode:start:+ cmd: tools/infra-scripts/clickhouse-multinode/start-multinode-clickhouse+ description: Boot the multinode ClickHouse smoke-test stack (one server per logical cluster) for local migration verification+ hidden: true+ clickhouse:multinode:verify:+ cmd: python tools/infra-scripts/clickhouse-multinode/verify-multinode-clickhouse.py+ description: Assert that the multinode ClickHouse stack ended up with the expected per-node table layout+ hidden: true+ clickhouse:multinode:test:+ cmd: tools/infra-scripts/clickhouse-multinode/multinode-migration-smoke+ description: Boot a per-cluster ClickHouse stack and smoke-test migrations against it+ hidden: truecreate:notebook:node:bin_script: create-notebook-node.shdescription: Create a new NotebookNode file and update types and editor referencesdiff --git a/posthog/clickhouse/client/migration_tools.py b/posthog/clickhouse/client/migration_tools.pyindex df6b4095997b..244df1c27cf6 100644--- a/posthog/clickhouse/client/migration_tools.py+++ b/posthog/clickhouse/client/migration_tools.py@@ -72,9 +72,11 @@ def run_sql_with_exceptions(# Store original node_roles for validation purposes before debug overrideoriginal_node_roles = node_roles_list- if settings.E2E_TESTING or settings.DEBUG or not settings.CLOUD_DEPLOYMENT:+ if (settings.E2E_TESTING or settings.DEBUG or not settings.CLOUD_DEPLOYMENT) and not settings.MULTINODE_CLICKHOUSE:# In E2E tests, debug mode and hobby deployments, we run migrations on ALL nodes- # because we don't have different ClickHouse topologies yet in Docker+ # because we don't have different ClickHouse topologies yet in Docker.+ # MULTINODE_CLICKHOUSE opts back into role-based routing so the smoke-test+ # stack can verify migrations actually land on the correct cluster.node_roles_list = [NodeRole.ALL]def run_migration():@@ -83,7 +85,9 @@ def run_sql_with_exceptions(query = Query(sql)if sharded and is_alter_on_replicated_table:- is_local_or_test = settings.E2E_TESTING or settings.DEBUG or not settings.CLOUD_DEPLOYMENT+ is_local_or_test = (+ settings.E2E_TESTING or settings.DEBUG or not settings.CLOUD_DEPLOYMENT+ ) and not settings.MULTINODE_CLICKHOUSEsingle_role = node_roles_list[0] if len(node_roles_list) == 1 else Noneassert is_local_or_test or (single_role is not None and single_role in DATA_NODE_ROLES), ("When running migrations on sharded tables, node_roles must be exactly one of "diff --git a/posthog/clickhouse/cluster.py b/posthog/clickhouse/cluster.pyindex 231cb5876440..7de41a80fcba 100644--- a/posthog/clickhouse/cluster.py+++ b/posthog/clickhouse/cluster.py@@ -27,6 +27,32 @@ def ON_CLUSTER_CLAUSE(on_cluster=True):return f"ON CLUSTER '{CLICKHOUSE_CLUSTER}'" if on_cluster else ""+# Smoke-test only: when migrating against the multinode docker-compose stack+# from the host, every docker hostname (`clickhouse-aux`, …) is mapped to+# 127.0.0.1 via /etc/hosts, but only one container can publish on port 9000 —+# so without a per-host port override, every role-routed connection lands on+# whichever container holds 127.0.0.1:9000 (the data node). The compose file+# publishes each satellite on a distinct host port; this map mirrors that.+#+# Canonical source: `docker-compose.multinode-clickhouse.yml` (per-service+# `ports:` blocks). Keep this map in sync when adding or renumbering nodes.+_MULTINODE_HOST_PORT_OVERRIDES: dict[str, tuple[str, int]] = {+ "clickhouse-data": ("localhost", 9000),+ "clickhouse-ai-events": ("localhost", 9100),+ "clickhouse-aux": ("localhost", 9200),+ "clickhouse-ops": ("localhost", 9300),+ "clickhouse-sessions": ("localhost", 9400),+}+++def _resolve_connection_target(host_name: str, port: int | None) -> tuple[str, int | None]:+ if settings.MULTINODE_CLICKHOUSE:+ override = _MULTINODE_HOST_PORT_OVERRIDES.get(host_name)+ if override:+ return override+ return (host_name, port)++K = TypeVar("K")V = TypeVar("V")@@ -118,13 +144,12 @@ class ClickhouseCluster:for row in cluster_hosts:(host_name, port, shard_num, replica_num, host_cluster_type, host_cluster_role) = row+ # We only use the port from system.clusters if we're running in E2E tests or debug mode,+ # otherwise, we will use the default port.+ effective_port = port if (settings.E2E_TESTING or settings.DEBUG) else None+ resolved_host, resolved_port = _resolve_connection_target(host_name, effective_port)host_info = HostInfo(- ConnectionInfo(- host_name,- # We only use the port from system.clusters if we're running in E2E tests or debug mode,- # otherwise, we will use the default port.- port=port if (settings.E2E_TESTING or settings.DEBUG) else None,- ),+ ConnectionInfo(resolved_host, resolved_port),shard_num if host_cluster_role == NodeRole.DATA else None,replica_num if host_cluster_role == NodeRole.DATA else None,host_cluster_type,@@ -140,11 +165,10 @@ class ClickhouseCluster:for row in data_hosts:(host_name, port, shard_num, replica_num, host_cluster_type, host_cluster_role) = rowif host_cluster_role == NodeRole.DATA:+ effective_port = port if (settings.E2E_TESTING or settings.DEBUG) else None+ resolved_host, resolved_port = _resolve_connection_target(host_name, effective_port)host_info = HostInfo(- ConnectionInfo(- host_name,- port=port if (settings.E2E_TESTING or settings.DEBUG) else None,- ),+ ConnectionInfo(resolved_host, resolved_port),shard_num,replica_num,host_cluster_type,@@ -165,11 +189,10 @@ class ClickhouseCluster:logger.info("Discovered %d hosts from satellite cluster %r", len(satellite_hosts), satellite_name)for row in satellite_hosts:(host_name, port, _shard_num, _replica_num, host_cluster_type, host_cluster_role) = row+ effective_port = port if (settings.E2E_TESTING or settings.DEBUG) else None+ resolved_host, resolved_port = _resolve_connection_target(host_name, effective_port)host_info = HostInfo(- ConnectionInfo(- host_name,- port=port if (settings.E2E_TESTING or settings.DEBUG) else None,- ),+ ConnectionInfo(resolved_host, resolved_port),shard_num=None,replica_num=None,host_cluster_type=host_cluster_type,diff --git a/posthog/clickhouse/migrations/0001_initial.py b/posthog/clickhouse/migrations/0001_initial.pyindex 00479372f82f..9c7bb587ed03 100644--- a/posthog/clickhouse/migrations/0001_initial.py+++ b/posthog/clickhouse/migrations/0001_initial.py@@ -1,8 +1,12 @@+from posthog.clickhouse.client.connection import NodeRolefrom posthog.clickhouse.client.migration_tools import run_sql_with_exceptionsfrom posthog.models.event.sql import EVENTS_TABLE_SQL-from posthog.settings import CLICKHOUSE_CLUSTER, CLICKHOUSE_DATABASE+from posthog.settings import CLICKHOUSE_DATABASEoperations = [- run_sql_with_exceptions(f"CREATE DATABASE IF NOT EXISTS {CLICKHOUSE_DATABASE} ON CLUSTER '{CLICKHOUSE_CLUSTER}'"),+ run_sql_with_exceptions(+ f"CREATE DATABASE IF NOT EXISTS {CLICKHOUSE_DATABASE}",+ node_roles=[NodeRole.ALL],+ ),run_sql_with_exceptions(EVENTS_TABLE_SQL()),]diff --git a/posthog/clickhouse/migrations/0233_session_replay_features.py b/posthog/clickhouse/migrations/0233_session_replay_features.pyindex cd3d57b40982..9600459c72aa 100644--- a/posthog/clickhouse/migrations/0233_session_replay_features.py+++ b/posthog/clickhouse/migrations/0233_session_replay_features.py@@ -9,10 +9,10 @@ from posthog.session_recordings.sql.session_replay_feature_sql import ()operations = [- # Sharded data table on DATA nodes- run_sql_with_exceptions(SESSION_REPLAY_FEATURES_TABLE_SQL(on_cluster=False), node_roles=[NodeRole.DATA]),- # Distributed read table on DATA nodes- run_sql_with_exceptions(DISTRIBUTED_SESSION_REPLAY_FEATURES_TABLE_SQL(), node_roles=[NodeRole.DATA]),+ # Sharded data table on AUX nodes (single-shard satellite cluster)+ run_sql_with_exceptions(SESSION_REPLAY_FEATURES_TABLE_SQL(on_cluster=False), node_roles=[NodeRole.AUX]),+ # Distributed read table on AUX nodes (co-located with the source-of-truth table)+ run_sql_with_exceptions(DISTRIBUTED_SESSION_REPLAY_FEATURES_TABLE_SQL(), node_roles=[NodeRole.AUX]),# Writable distributed table on INGESTION_MEDIUM nodesrun_sql_with_exceptions(WRITABLE_SESSION_REPLAY_FEATURES_TABLE_SQL(), node_roles=[NodeRole.INGESTION_MEDIUM]),# Kafka table on INGESTION_MEDIUM nodes (requires msk_cluster named collection)diff --git a/posthog/management/commands/migrate_clickhouse.py b/posthog/management/commands/migrate_clickhouse.pyindex 4d545dcc88e6..e28bb382bd06 100644--- a/posthog/management/commands/migrate_clickhouse.py+++ b/posthog/management/commands/migrate_clickhouse.py@@ -55,6 +55,7 @@ class Command(BaseCommand):def migrate(self, host, options):# Infi only creates the DB in one node, but not the rest. Create it before running migrations.self._create_database_if_not_exists(CLICKHOUSE_DATABASE, CLICKHOUSE_MIGRATIONS_CLUSTER)+ self._create_migration_tracking_tables_if_not_exist(CLICKHOUSE_DATABASE, CLICKHOUSE_MIGRATIONS_CLUSTER)database = Database(CLICKHOUSE_DATABASE,db_url=host,@@ -120,8 +121,59 @@ class Command(BaseCommand):return database._get_applied_migrations(MIGRATIONS_PACKAGE_NAME, replicated=True)def _create_database_if_not_exists(self, database: str, cluster: str):- if settings.TEST or settings.E2E_TESTING:+ # MULTINODE_CLICKHOUSE: infi.clickhouse_orm creates the Distributed+ # migration-tracking table across the migrations cluster before the+ # first migration runs, so the database has to exist on every node up+ # front — otherwise the CREATE TABLE fans out to satellites that have+ # no `posthog` database yet and fails with UNKNOWN_DATABASE.+ if settings.TEST or settings.E2E_TESTING or settings.MULTINODE_CLICKHOUSE:with default_client() as client:client.execute(f"CREATE DATABASE IF NOT EXISTS {database} ON CLUSTER {cluster}",)++ def _create_migration_tracking_tables_if_not_exist(self, database: str, cluster: str):+ # MULTINODE_CLICKHOUSE only: infi.clickhouse_orm's auto-create path+ # issues `CREATE TABLE` without `ON CLUSTER`, so the underlying+ # ReplicatedMergeTree only lands on the migrations host. With a real+ # multi-node `posthog_migrations` cluster, the Distributed tracking+ # table fans out to every shard and trips UNKNOWN_TABLE on satellites+ # that never received the local replica. Pre-create both tables on+ # the cluster so the very first SELECT in infi's migrate() succeeds+ # and the auto-create branch never runs.+ #+ # Schema (`package_name String, module_name String, applied Date`) and+ # the ZK path mirror `infi.clickhouse_orm.migrations.MigrationHistory`+ # / `MigrationHistoryReplicated`. If `infi` ever changes those, this+ # pre-create will silently diverge — keep the two in sync.+ if not settings.MULTINODE_CLICKHOUSE:+ return+ with default_client() as client:+ client.execute(+ f"""+ CREATE TABLE IF NOT EXISTS {database}.infi_clickhouse_orm_migrations+ ON CLUSTER {cluster} (+ package_name String,+ module_name String,+ applied Date+ )+ ENGINE = ReplicatedMergeTree(+ '/clickhouse/prod/tables/noshard/{{database}}/{{table}}',+ '{{replica}}-{{shard}}'+ )+ PARTITION BY toYYYYMM(applied)+ ORDER BY (package_name, module_name)+ SETTINGS index_granularity = 8192+ """+ )+ client.execute(+ f"""+ CREATE TABLE IF NOT EXISTS {database}.infi_clickhouse_orm_migrations_distributed+ ON CLUSTER {cluster} (+ package_name String,+ module_name String,+ applied Date+ )+ ENGINE = Distributed({cluster}, {database}, infi_clickhouse_orm_migrations, rand())+ """+ )diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex 3199d23ada82..bac8082b3962 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -291,6 +291,10 @@ CLICKHOUSE_WRITABLE_CLUSTER: str = os.getenv("CLICKHOUSE_WRITABLE_CLUSTER", "posCLICKHOUSE_PRIMARY_REPLICA_CLUSTER: str = os.getenv("CLICKHOUSE_PRIMARY_REPLICA_CLUSTER", "posthog_primary_replica")CLICKHOUSE_AUX_CLUSTER: str = os.getenv("CLICKHOUSE_AUX_CLUSTER", "aux")CLICKHOUSE_AI_EVENTS_CLUSTER: str = os.getenv("CLICKHOUSE_AI_EVENTS_CLUSTER", "ai_events")+# Opt-in flag for the multinode ClickHouse smoke-test stack. When true, migrations+# respect their declared NodeRole(s) instead of being collapsed to NodeRole.ALL,+# so a per-cluster topology can actually exercise routing.+MULTINODE_CLICKHOUSE: bool = get_from_env("MULTINODE_CLICKHOUSE", False, type_cast=str_to_bool)CLICKHOUSE_FALLBACK_CANCEL_QUERY_ON_CLUSTER = get_from_env("CLICKHOUSE_FALLBACK_CANCEL_QUERY_ON_CLUSTER", default=False, type_cast=str_to_bool)diff --git a/tools/infra-scripts/clickhouse-multinode/multinode-migration-smoke b/tools/infra-scripts/clickhouse-multinode/multinode-migration-smokenew file mode 100755index 000000000000..5fe7b773276e--- /dev/null+++ b/tools/infra-scripts/clickhouse-multinode/multinode-migration-smoke@@ -0,0 +1,186 @@+#!/usr/bin/env bash+#+# End-to-end smoke test for ClickHouse migrations against a multi-node topology.+#+# Boots one ClickHouse server per logical cluster (data + ai_events + aux + ops + sessions),+# runs `manage.py migrate_clickhouse` with MULTINODE_CLICKHOUSE=1 (so migrations respect+# their declared NodeRole instead of being collapsed to NodeRole.ALL), then runs the+# verification script to assert each node ended up with the tables it should have.+#+# Env knobs:+# KEEP=1 Do not tear down the stack on success (useful for local debugging).+# SKIP_BOOT=1 Assume the stack is already running (useful when iterating on+# migrations against an already-booted stack).+# KEEP_POSTGRES=1 Preserve the postgres + redis containers across runs (skips the+# pre-boot teardown for those services and the `manage.py migrate`+# step). Speeds up iteration on ClickHouse migrations by avoiding+# a full Django schema rebuild every run.+#++set -euo pipefail++SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)+# Repo root is three levels up from tools/infra-scripts/clickhouse-multinode/.+cd "$SCRIPT_DIR/../../.."++COMPOSE_FILE="docker-compose.multinode-clickhouse.yml"+CH_SERVICES=(clickhouse-data clickhouse-ai-events clickhouse-aux clickhouse-ops clickhouse-sessions)+INFRA_SERVICES=(zookeeper kafka db redis7)+ALL_SERVICES=("${INFRA_SERVICES[@]}" "${CH_SERVICES[@]}")+HEALTH_TIMEOUT="${HEALTH_TIMEOUT:-180}"++# Tracks the failing step so the EXIT trap can print a precise banner.+SMOKE_STAGE="boot"+SMOKE_PASSED=0++dc() { docker compose -f "$COMPOSE_FILE" "$@"; }++report_result() {+ # Caller must pass the original failing exit code as $1. We can't read $?+ # ourselves because the log-dumping loops in dump_logs_on_failure end in+ # `|| true`, which would clobber $? to 0 before we observed it.+ local exit_code=$1+ echo+ echo "==========================================================================="+ if [ "$SMOKE_PASSED" = "1" ] && [ "$exit_code" -eq 0 ]; then+ echo " ✅ MULTINODE SMOKE PASSED"+ else+ echo " ❌ MULTINODE SMOKE FAILED (stage: ${SMOKE_STAGE}, exit code: ${exit_code})"+ fi+ echo "==========================================================================="+ return "$exit_code"+}++dump_logs_on_failure() {+ local exit_code=$?+ if [ "$exit_code" -ne 0 ] || [ "$SMOKE_PASSED" != "1" ]; then+ echo+ echo "===================== FAILURE: dumping container logs ====================="+ for svc in "${ALL_SERVICES[@]}"; do+ echo+ echo "----- $svc -----"+ dc logs --tail=200 "$svc" || true+ done+ echo+ echo "===================== ClickHouse system.errors per node ====================="+ for svc in "${CH_SERVICES[@]}"; do+ echo "----- $svc -----"+ dc exec -T "$svc" clickhouse-client --query \+ "SELECT name, value, last_error_message FROM system.errors WHERE value > 0 ORDER BY value DESC LIMIT 20" \+ || true+ done+ fi+ report_result "$exit_code"+ # Explicit exit so the script's final status doesn't depend on the EXIT+ # trap's return value semantics, which vary across bash versions.+ exit "$exit_code"+}+trap dump_logs_on_failure EXIT++check_hosts_mapping() {+ # The cluster topology lookup returns docker-internal hostnames+ # (clickhouse-data, clickhouse-aux, …). Migrations run from the host shell,+ # so those hostnames must resolve locally. CI handles this via /etc/hosts;+ # locally the user has to do the same. Bail out early with a precise hint+ # rather than failing deep inside infi.clickhouse_orm with `Code: 210`.+ local missing=()+ for svc in "${CH_SERVICES[@]}"; do+ if ! python3 -c "import socket; socket.gethostbyname('$svc')" >/dev/null 2>&1; then+ missing+=("$svc")+ fi+ done+ if [ ${#missing[@]} -gt 0 ]; then+ echo "ERROR: these docker hostnames don't resolve from the host:" >&2+ printf ' - %s\n' "${missing[@]}" >&2+ echo >&2+ echo "Add them to /etc/hosts, e.g.:" >&2+ echo " echo '127.0.0.1 ${CH_SERVICES[*]}' | sudo tee -a /etc/hosts" >&2+ exit 1+ fi+}++wait_for_healthy() {+ local svc="$1"+ local cid status+ local deadline=$(( SECONDS + HEALTH_TIMEOUT ))++ while [ "$SECONDS" -lt "$deadline" ]; do+ cid=$(dc ps -q "$svc" || true)+ if [ -n "$cid" ]; then+ status=$(docker inspect --format '{{.State.Health.Status}}' "$cid" 2>/dev/null || echo "missing")+ if [ "$status" = "healthy" ]; then+ echo " $svc -> healthy"+ return 0+ fi+ fi+ sleep 2+ done+ echo " $svc -> NOT healthy after ${HEALTH_TIMEOUT}s" >&2+ return 1+}++if [ "${SKIP_BOOT:-0}" != "1" ]; then+ SMOKE_STAGE="boot"+ if [ "${KEEP_POSTGRES:-0}" = "1" ]; then+ echo "==> KEEP_POSTGRES=1: tearing down ClickHouse + Kafka + Zookeeper only..."+ dc rm -fsv "${CH_SERVICES[@]}" zookeeper kafka >/dev/null 2>&1 || true+ else+ echo "==> Tearing down any previous multinode stack (clears Zookeeper state)..."+ dc down -v --remove-orphans >/dev/null 2>&1 || true+ fi++ echo "==> Booting multinode ClickHouse stack..."+ dc up -d "${ALL_SERVICES[@]}"++ echo "==> Waiting for Postgres + Redis + ClickHouse nodes to become healthy..."+ for svc in db redis7 "${CH_SERVICES[@]}"; do+ wait_for_healthy "$svc"+ done+fi++SMOKE_STAGE="hosts-resolution"+echo "==> Verifying docker hostnames resolve from this shell..."+check_hosts_mapping++export MULTINODE_CLICKHOUSE=1+export CLICKHOUSE_HOST="${CLICKHOUSE_HOST:-localhost}"+export CLICKHOUSE_MIGRATIONS_HOST="${CLICKHOUSE_MIGRATIONS_HOST:-localhost}"+export CLICKHOUSE_CLUSTER="${CLICKHOUSE_CLUSTER:-posthog}"+export CLICKHOUSE_MIGRATIONS_CLUSTER="${CLICKHOUSE_MIGRATIONS_CLUSTER:-posthog_migrations}"+export CLICKHOUSE_SATELLITE_CLUSTERS="${CLICKHOUSE_SATELLITE_CLUSTERS:-ai_events,aux,ops,sessions}"+export CLICKHOUSE_DATABASE="${CLICKHOUSE_DATABASE:-posthog}"+export CLICKHOUSE_USER="${CLICKHOUSE_USER:-default}"+export CLICKHOUSE_PASSWORD="${CLICKHOUSE_PASSWORD:-}"+export CLICKHOUSE_SECURE="${CLICKHOUSE_SECURE:-false}"+export CLICKHOUSE_VERIFY="${CLICKHOUSE_VERIFY:-false}"+export DATABASE_URL="${DATABASE_URL:-postgres://posthog:posthog@localhost:5432/posthog}"+export REDIS_URL="${REDIS_URL:-redis://localhost:6379}"+export SECRET_KEY="${SECRET_KEY:-multinode-smoke-not-a-real-secret}"++if [ "${KEEP_POSTGRES:-0}" = "1" ]; then+ echo "==> KEEP_POSTGRES=1: skipping Django (Postgres) migrations"+else+ SMOKE_STAGE="migrate_postgres"+ # migrate_clickhouse reads `posthog_instancesetting` from Postgres, so the+ # Django schema must exist before the ClickHouse step runs.+ echo "==> Running Django (Postgres) migrations..."+ python manage.py migrate --noinput+fi++SMOKE_STAGE="migrate_clickhouse"+echo "==> Running ClickHouse migrations against the data node..."+python manage.py migrate_clickhouse++SMOKE_STAGE="verify"+echo "==> Verifying per-node table layout..."+python tools/infra-scripts/clickhouse-multinode/verify-multinode-clickhouse.py++SMOKE_PASSED=1+SMOKE_STAGE="teardown"++if [ "${KEEP:-0}" = "1" ]; then+ echo "KEEP=1 set: leaving stack running. Tear down with: tools/infra-scripts/clickhouse-multinode/start-multinode-clickhouse down"+else+ echo "==> Tearing down stack..."+ dc down -v+fidiff --git a/tools/infra-scripts/clickhouse-multinode/start-multinode-clickhouse b/tools/infra-scripts/clickhouse-multinode/start-multinode-clickhousenew file mode 100755index 000000000000..ca04c7962535--- /dev/null+++ b/tools/infra-scripts/clickhouse-multinode/start-multinode-clickhouse@@ -0,0 +1,49 @@+#!/usr/bin/env bash+#+# Boot the multinode ClickHouse smoke-test stack in the background.+# One ClickHouse server per logical cluster (data + ai_events + aux + ops + sessions).+# This is opt-in tooling for verifying migration routing — `bin/start` is unaffected.+#++set -euo pipefail++SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)+# Repo root is three levels up from tools/infra-scripts/clickhouse-multinode/.+cd "$SCRIPT_DIR/../../.."++COMPOSE_FILE="docker-compose.multinode-clickhouse.yml"+SERVICES=(zookeeper kafka db redis7 clickhouse-data clickhouse-ai-events clickhouse-aux clickhouse-ops clickhouse-sessions)++case "${1:-up}" in+ up)+ docker compose -f "$COMPOSE_FILE" up -d "${SERVICES[@]}"+ echo+ echo "Multinode ClickHouse stack starting. Published ports:"+ echo " clickhouse-data localhost:9000 (HTTP 8123)"+ echo " clickhouse-ai-events localhost:9100 (HTTP 8124)"+ echo " clickhouse-aux localhost:9200 (HTTP 8125)"+ echo " clickhouse-ops localhost:9300 (HTTP 8126)"+ echo " clickhouse-sessions localhost:9400 (HTTP 8127)"+ echo+ echo "To run migrations against this stack, set:"+ echo " export MULTINODE_CLICKHOUSE=1"+ echo " export CLICKHOUSE_HOST=localhost"+ echo " export CLICKHOUSE_MIGRATIONS_HOST=localhost"+ echo "Then run: python manage.py migrate_clickhouse"+ echo+ echo "Or run the full smoke test: tools/infra-scripts/clickhouse-multinode/multinode-migration-smoke"+ ;;+ down)+ docker compose -f "$COMPOSE_FILE" down -v+ ;;+ logs)+ docker compose -f "$COMPOSE_FILE" logs -f "${@:2}"+ ;;+ ps)+ docker compose -f "$COMPOSE_FILE" ps+ ;;+ *)+ echo "Usage: $0 [up|down|logs|ps]" >&2+ exit 2+ ;;+esacdiff --git a/tools/infra-scripts/clickhouse-multinode/verify-multinode-clickhouse.py b/tools/infra-scripts/clickhouse-multinode/verify-multinode-clickhouse.pynew file mode 100755index 000000000000..dfc910d1b7b0--- /dev/null+++ b/tools/infra-scripts/clickhouse-multinode/verify-multinode-clickhouse.py@@ -0,0 +1,192 @@+#!/usr/bin/env python+# ruff: noqa: T201+"""+Verify that the multinode ClickHouse smoke-test stack ended up in the expected+shape after `manage.py migrate_clickhouse` ran.++Connects to each ClickHouse node directly (via its published port) and asserts:++1. `getMacro('hostClusterRole')` returns the expected role per node — confirms+ the per-node config files mounted correctly.+2. `system.clusters` is consistent across nodes and lists the expected logical+ clusters with the expected member hosts — confirms `<remote_servers>` is+ wired correctly.+3. Tables that production routes to a satellite cluster (ai_events / aux / ops+ / sessions) live on the matching node and **not** on the data node. Catches+ migrations that forgot `node_roles=[NodeRole.X]` and accidentally created a+ table everywhere.++Exits 0 on success, non-zero on the first failed assertion (with context).+"""++from __future__ import annotations++import sys+from dataclasses import dataclass++from clickhouse_driver import Client+++@dataclass(frozen=True)+class Node:+ name: str+ host: str+ port: int+ expected_role: str+++# Match the published ports in docker-compose.multinode-clickhouse.yml.+NODES: list[Node] = [+ Node("clickhouse-data", "localhost", 9000, "data"),+ Node("clickhouse-ai-events", "localhost", 9100, "ai_events"),+ Node("clickhouse-aux", "localhost", 9200, "aux"),+ Node("clickhouse-ops", "localhost", 9300, "ops"),+ Node("clickhouse-sessions", "localhost", 9400, "sessions"),+]++# Logical cluster -> expected member hosts (sorted). Each multinode XML file+# declares the same `<remote_servers>` block, so every node must agree.+EXPECTED_CLUSTERS: dict[str, list[str]] = {+ "posthog": ["clickhouse-data"],+ "posthog_single_shard": ["clickhouse-data"],+ "posthog_writable": ["clickhouse-data"],+ "posthog_primary_replica": ["clickhouse-data"],+ "posthog_migrations": [+ "clickhouse-ai-events",+ "clickhouse-aux",+ "clickhouse-data",+ "clickhouse-ops",+ "clickhouse-sessions",+ ],+ "ai_events": ["clickhouse-ai-events"],+ "aux": ["clickhouse-aux"],+ "ops": ["clickhouse-ops"],+ "sessions": ["clickhouse-sessions"],+}+++@dataclass(frozen=True)+class SatelliteTables:+ # Tables that must exist on the satellite node.+ on_satellite: list[str]+ # Tables that must NOT exist on the data node. Distributed wrappers are+ # routinely created on data too (so the data node can query the satellite+ # shard cross-cluster) — only the underlying sharded data table belongs+ # exclusively to the satellite.+ forbidden_on_data: list[str]+++# Manifest of tables (in CLICKHOUSE_DATABASE) per satellite role. Update when+# adding new per-cluster tables.+SATELLITE_TABLE_MANIFEST: dict[str, SatelliteTables] = {+ "ai_events": SatelliteTables(+ on_satellite=["ai_events", "sharded_ai_events"],+ forbidden_on_data=["sharded_ai_events"],+ ),+ "aux": SatelliteTables(on_satellite=[], forbidden_on_data=[]),+ "ops": SatelliteTables(on_satellite=[], forbidden_on_data=[]),+ "sessions": SatelliteTables(on_satellite=[], forbidden_on_data=[]),+}++DATABASE = "posthog"+++def client(node: Node) -> Client:+ return Client(host=node.host, port=node.port, database="default")+++def fail(msg: str) -> None:+ print(f"FAIL: {msg}", file=sys.stderr)+ sys.exit(1)+++def check_macros() -> None:+ print("==> Checking <macros> per node")+ for node in NODES:+ with client(node) as c:+ ((role,),) = c.execute("SELECT getMacro('hostClusterRole')")+ if role != node.expected_role:+ fail(f"{node.name}: hostClusterRole={role!r}, expected {node.expected_role!r}")+ print(f" {node.name}: hostClusterRole={role}")+++def fetch_clusters(node: Node) -> dict[str, list[str]]:+ with client(node) as c:+ rows = c.execute(+ "SELECT cluster, host_name FROM system.clusters WHERE cluster IN %(clusters)s ORDER BY cluster, host_name",+ {"clusters": tuple(EXPECTED_CLUSTERS.keys())},+ )+ layout: dict[str, list[str]] = {}+ for cluster, host in rows:+ layout.setdefault(cluster, []).append(host)+ return layout+++def check_cluster_topology() -> None:+ print("==> Checking system.clusters consistency across nodes")+ expected = {k: sorted(set(v)) for k, v in EXPECTED_CLUSTERS.items()}+ for node in NODES:+ layout = {k: sorted(set(v)) for k, v in fetch_clusters(node).items()}+ for cluster, hosts in expected.items():+ actual = layout.get(cluster)+ if actual != hosts:+ fail(f"{node.name}: cluster {cluster!r} hosts={actual}, expected {hosts}")+ print(f" {node.name}: {len(layout)} clusters match")+++def fetch_local_tables(node: Node) -> set[str]:+ with client(node) as c:+ rows = c.execute(+ "SELECT name FROM system.tables WHERE database = %(db)s",+ {"db": DATABASE},+ )+ return {name for (name,) in rows}+++def find_node(role: str) -> Node:+ for node in NODES:+ if node.expected_role == role:+ return node+ raise KeyError(role)+++def check_satellite_tables() -> None:+ print("==> Checking per-cluster table placement (manifest)")+ data_node = find_node("data")+ data_tables = fetch_local_tables(data_node)+ print(f" {data_node.name}: {len(data_tables)} tables in {DATABASE!r}")++ any_checked = False+ for role, manifest in SATELLITE_TABLE_MANIFEST.items():+ if not manifest.on_satellite and not manifest.forbidden_on_data:+ continue+ any_checked = True+ node = find_node(role)+ node_tables = fetch_local_tables(node)+ print(f" {node.name}: {len(node_tables)} tables in {DATABASE!r}")++ missing = [t for t in manifest.on_satellite if t not in node_tables]+ if missing:+ fail(f"{node.name}: missing expected tables {missing}")++ leaked = [t for t in manifest.forbidden_on_data if t in data_tables]+ if leaked:+ fail(+ f"{data_node.name} should not have satellite-only tables {leaked} "+ f"(they belong on {node.name}). Did a migration forget node_roles=?"+ )++ if not any_checked:+ print(" (no satellite manifests populated yet — skipping presence checks)")+++def main() -> int:+ check_macros()+ check_cluster_topology()+ check_satellite_tables()+ print("OK: multinode topology and table layout look correct.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())