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.

chore(clickhouse): standardize run-mode detection in migrations (#85233)

Paweł Szczur8681dcea27fe
diff --git a/.agents/skills/clickhouse-migrations/SKILL.md b/.agents/skills/clickhouse-migrations/SKILL.md
index d8022de6d934..0ec874a8a882 100644
--- a/.agents/skills/clickhouse-migrations/SKILL.md
+++ b/.agents/skills/clickhouse-migrations/SKILL.md
@@ -80,16 +80,28 @@ If you need both a schema change and application code that uses the new schema,
**No table should exist only in the cloud.** Every table created via migration must also exist in a local dev environment.
-Some migrations are cloud-guarded and skipped in local/hobby dev:
+Some migrations are cloud-guarded and skipped in local/hobby dev. Gate on `posthog.run_mode`, never on `settings.CLOUD_DEPLOYMENT` directly, because the `clickhouse-migrations-use-run-mode` semgrep rule blocks raw comparisons:
```python
+from posthog.run_mode import RunMode, run_mode
+
operations = (
[]
- if settings.CLOUD_DEPLOYMENT not in ("US", "EU", "DEV")
+ if not run_mode().is_deployed_cloud # US/EU/DEV
else [...]
)
```
+| Predicate | True for |
+| -------------------------------- | --------------------------------------------- |
+| `run_mode().is_deployed_cloud` | US, EU, DEV (the usual migration gate) |
+| `run_mode().is_prod_cloud` | US, EU (excludes staging) |
+| `run_mode() is RunMode.CLOUD_US` | one region (`CLOUD_EU`, `CLOUD_DEV` likewise) |
+
+`run_mode().is_cloud` also counts E2E, so it is wrong for a migration. That one matches `posthog.cloud_utils.is_cloud`.
+
+Call `run_mode()` where you need it rather than assigning a module-level constant. `posthog/clickhouse/test/test_migrations.py` re-imports every migration under a patched `posthog.settings.CLOUD_DEPLOYMENT` to check each deployment's branch for stray `ON CLUSTER`, and a cached value would silently skip that coverage.
+
If you create a new table inside such a guard, you must also add its SQL function to `posthog/clickhouse/schema.py` in the appropriate tuple so the table gets created locally:
| Table type | Tuple in `schema.py` |
diff --git a/.semgrep/rules/devex/clickhouse-migrations-use-run-mode.py b/.semgrep/rules/devex/clickhouse-migrations-use-run-mode.py
new file mode 100644
index 000000000000..8caa6f10471c
--- /dev/null
+++ b/.semgrep/rules/devex/clickhouse-migrations-use-run-mode.py
@@ -0,0 +1,19 @@
+# Test cases for clickhouse-migrations-use-run-mode rule.
+# ruff: noqa: F821, E501
+from posthog import settings
+from posthog.run_mode import RunMode, run_mode
+
+# ruleid: clickhouse-migrations-use-run-mode
+_gate = settings.CLOUD_DEPLOYMENT not in ("US", "EU", "DEV")
+
+# ruleid: clickhouse-migrations-use-run-mode
+_region_is_us = settings.CLOUD_DEPLOYMENT == "US"
+
+# ok: clickhouse-migrations-use-run-mode
+_ok_gate = run_mode().is_deployed_cloud
+
+# ok: clickhouse-migrations-use-run-mode
+_ok_prod = run_mode().is_prod_cloud
+
+# ok: clickhouse-migrations-use-run-mode
+_ok_region = run_mode() is RunMode.CLOUD_US
diff --git a/.semgrep/rules/devex/clickhouse-migrations-use-run-mode.yaml b/.semgrep/rules/devex/clickhouse-migrations-use-run-mode.yaml
new file mode 100644
index 000000000000..4d99c2a4bfc7
--- /dev/null
+++ b/.semgrep/rules/devex/clickhouse-migrations-use-run-mode.yaml
@@ -0,0 +1,38 @@
+rules:
+ - id: clickhouse-migrations-use-run-mode
+ message: |
+ ClickHouse migration compares `settings.CLOUD_DEPLOYMENT` directly.
+
+ Use `posthog.run_mode` so every migration spells the same environment the same way:
+
+ from posthog.run_mode import RunMode, run_mode
+
+ # skip off deployed cloud (US/EU/DEV), the usual gate
+ operations = [...] if run_mode().is_deployed_cloud else []
+
+ # customer-facing cloud only, excluding staging
+ if run_mode().is_prod_cloud: ...
+
+ # a single region
+ if run_mode() is RunMode.CLOUD_US: ...
+
+ Note `run_mode().is_deployed_cloud` excludes E2E, matching what the raw
+ `("US", "EU", "DEV")` tuple meant. `run_mode().is_cloud` includes it, which is
+ `posthog.cloud_utils.is_cloud`, which is not what a migration wants.
+
+ Resolve the mode inside the call, never into a module-level constant:
+ `posthog/clickhouse/test/test_migrations.py` re-imports each migration under a
+ patched `posthog.settings.CLOUD_DEPLOYMENT` to check every deployment's branch.
+
+ For a genuine exception, add
+ `# nosemgrep: clickhouse-migrations-use-run-mode -- <reason>` at the call site.
+ severity: ERROR
+ languages: [python]
+ paths:
+ include:
+ - 'posthog/clickhouse/migrations/**/*.py'
+ pattern: $S.CLOUD_DEPLOYMENT
+ metadata:
+ category: best-practice
+ subcategory:
+ - audit
diff --git a/posthog/clickhouse/client/migration_tools.py b/posthog/clickhouse/client/migration_tools.py
index 0f0d8072883f..4a0c0373ef3b 100644
--- a/posthog/clickhouse/client/migration_tools.py
+++ b/posthog/clickhouse/client/migration_tools.py
@@ -7,6 +7,7 @@ from infi.clickhouse_orm import migrations
from posthog import settings
from posthog.clickhouse.client.connection import DATA_NODE_ROLES, SINGLE_SHARD_DATA_NODE_ROLES, NodeRole
from posthog.clickhouse.cluster import ClickhouseCluster, Query, get_cluster
+from posthog.run_mode import run_mode
from posthog.settings.data_stores import (
CLICKHOUSE_CLUSTER,
CLICKHOUSE_MIGRATIONS_CLUSTER,
@@ -27,6 +28,10 @@ def get_migrations_cluster() -> ClickhouseCluster:
)
+def _collapses_to_all_nodes() -> bool:
+ return (settings.E2E_TESTING or not run_mode().is_deployed_cloud) and not settings.MULTINODE_CLICKHOUSE
+
+
def run_sql_with_exceptions(
sql: str,
node_roles: list[NodeRole] | NodeRole | None = None,
@@ -72,7 +77,7 @@ def run_sql_with_exceptions(
# Store original node_roles for validation purposes before debug override
original_node_roles = node_roles_list
- if (settings.E2E_TESTING or settings.DEBUG or not settings.CLOUD_DEPLOYMENT) and not settings.MULTINODE_CLICKHOUSE:
+ if _collapses_to_all_nodes():
# 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.
# MULTINODE_CLICKHOUSE opts back into role-based routing so the smoke-test
@@ -85,9 +90,7 @@ 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
- ) and not settings.MULTINODE_CLICKHOUSE
+ is_local_or_test = _collapses_to_all_nodes()
single_role = node_roles_list[0] if len(node_roles_list) == 1 else None
assert 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/migrations/0232_warpstream_ingestion_kafka_engines.py b/posthog/clickhouse/migrations/0232_warpstream_ingestion_kafka_engines.py
index 1afeeaf0003a..8b62a2cd678a 100644
--- a/posthog/clickhouse/migrations/0232_warpstream_ingestion_kafka_engines.py
+++ b/posthog/clickhouse/migrations/0232_warpstream_ingestion_kafka_engines.py
@@ -1,4 +1,3 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
from posthog.heatmaps.sql import HEATMAPS_WS_TABLE_MV_SQL, KAFKA_HEATMAPS_WS_TABLE_SQL
@@ -20,6 +19,7 @@ from posthog.models.person.sql import (
PERSON_DISTINCT_ID2_WS_MV_SQL,
PERSONS_WS_TABLE_MV_SQL,
)
+from posthog.run_mode import run_mode
# Migration to create WarpStream Kafka engine tables for core ingestion topics.
#
@@ -56,7 +56,7 @@ ALTER TABLE writable_events
operations = (
[]
- if settings.CLOUD_DEPLOYMENT not in ("US", "EU", "DEV")
+ if not run_mode().is_deployed_cloud
else [
# events_json (INGESTION_EVENTS — WS tables go to events ingestion nodes)
#
diff --git a/posthog/clickhouse/migrations/0234_warpstream_ingestion_warnings_kafka_engine.py b/posthog/clickhouse/migrations/0234_warpstream_ingestion_warnings_kafka_engine.py
index 4c1fc1382a77..72a7dcad8ca1 100644
--- a/posthog/clickhouse/migrations/0234_warpstream_ingestion_warnings_kafka_engine.py
+++ b/posthog/clickhouse/migrations/0234_warpstream_ingestion_warnings_kafka_engine.py
@@ -1,7 +1,7 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
from posthog.models.ingestion_warnings.sql import INGESTION_WARNINGS_WS_MV_SQL, KAFKA_INGESTION_WARNINGS_WS_TABLE_SQL
+from posthog.run_mode import run_mode
# Migration to create a WarpStream Kafka engine table for clickhouse_ingestion_warnings.
#
@@ -18,7 +18,7 @@ from posthog.models.ingestion_warnings.sql import INGESTION_WARNINGS_WS_MV_SQL,
operations = (
[]
- if settings.CLOUD_DEPLOYMENT not in ("US", "EU", "DEV")
+ if not run_mode().is_deployed_cloud
else [
run_sql_with_exceptions(
KAFKA_INGESTION_WARNINGS_WS_TABLE_SQL(),
diff --git a/posthog/clickhouse/migrations/0238_align_ws_events_kafka_mv_with_msk.py b/posthog/clickhouse/migrations/0238_align_ws_events_kafka_mv_with_msk.py
index f76c52bb0061..a74149dabc80 100644
--- a/posthog/clickhouse/migrations/0238_align_ws_events_kafka_mv_with_msk.py
+++ b/posthog/clickhouse/migrations/0238_align_ws_events_kafka_mv_with_msk.py
@@ -1,6 +1,5 @@
from pathlib import Path
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
from posthog.models.event.sql import (
@@ -9,6 +8,7 @@ from posthog.models.event.sql import (
EVENTS_TABLE_JSON_WS_MV_SQL,
KAFKA_EVENTS_TABLE_JSON_WS_SQL,
)
+from posthog.run_mode import RunMode, run_mode
# Align the WarpStream events pipeline (kafka_events_json_ws + events_json_ws_mv)
# with the MSK events pipeline (kafka_events_json + events_json_mv) on
@@ -27,10 +27,10 @@ from posthog.models.event.sql import (
# used them.
_SQL_DIR = Path(__file__).parent / "sql" / "0238"
-if settings.CLOUD_DEPLOYMENT == "US":
+if run_mode() is RunMode.CLOUD_US:
_kafka_ddl = (_SQL_DIR / "us_kafka.sql").read_text()
_mv_ddl = (_SQL_DIR / "us_mv.sql").read_text()
-elif settings.CLOUD_DEPLOYMENT == "EU":
+elif run_mode() is RunMode.CLOUD_EU:
_kafka_ddl = (_SQL_DIR / "eu_kafka.sql").read_text()
_mv_ddl = (_SQL_DIR / "eu_mv.sql").read_text()
else:
@@ -39,7 +39,7 @@ else:
operations = (
[]
- if settings.CLOUD_DEPLOYMENT not in ("US", "EU", "DEV")
+ if not run_mode().is_deployed_cloud
else [
# Order matters: drop the MV first so it stops consuming from the
# kafka engine, then drop the kafka engine, then recreate both.
diff --git a/posthog/clickhouse/migrations/0241_warpstream_ingestion_warnings_kafka_engine.py b/posthog/clickhouse/migrations/0241_warpstream_ingestion_warnings_kafka_engine.py
index 36f07e3b8c7a..9f528f651a43 100644
--- a/posthog/clickhouse/migrations/0241_warpstream_ingestion_warnings_kafka_engine.py
+++ b/posthog/clickhouse/migrations/0241_warpstream_ingestion_warnings_kafka_engine.py
@@ -1,7 +1,7 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
from posthog.models.ingestion_warnings.sql import INGESTION_WARNINGS_WS_MV_SQL, KAFKA_INGESTION_WARNINGS_WS_TABLE_SQL
+from posthog.run_mode import run_mode
# Re-apply of migration 0234, which did not get applied in cloud environments.
# Creates the WarpStream Kafka engine table and MV for clickhouse_ingestion_warnings.
@@ -19,7 +19,7 @@ from posthog.models.ingestion_warnings.sql import INGESTION_WARNINGS_WS_MV_SQL,
operations = (
[]
- if settings.CLOUD_DEPLOYMENT not in ("US", "EU", "DEV")
+ if not run_mode().is_deployed_cloud
else [
run_sql_with_exceptions(
KAFKA_INGESTION_WARNINGS_WS_TABLE_SQL(),
diff --git a/posthog/clickhouse/migrations/0242_warpstream_person_distinct_id_overrides_kafka_engine.py b/posthog/clickhouse/migrations/0242_warpstream_person_distinct_id_overrides_kafka_engine.py
index 52a7b882eba9..0bda7e27575c 100644
--- a/posthog/clickhouse/migrations/0242_warpstream_person_distinct_id_overrides_kafka_engine.py
+++ b/posthog/clickhouse/migrations/0242_warpstream_person_distinct_id_overrides_kafka_engine.py
@@ -1,10 +1,10 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
from posthog.models.person.sql import (
KAFKA_PERSON_DISTINCT_ID_OVERRIDES_WS_TABLE_SQL,
PERSON_DISTINCT_ID_OVERRIDES_WS_MV_SQL,
)
+from posthog.run_mode import run_mode
# Migration to create a WarpStream Kafka engine table for person_distinct_id_overrides.
#
@@ -25,7 +25,7 @@ from posthog.models.person.sql import (
operations = (
[]
- if settings.CLOUD_DEPLOYMENT not in ("US", "EU", "DEV")
+ if not run_mode().is_deployed_cloud
else [
run_sql_with_exceptions(
KAFKA_PERSON_DISTINCT_ID_OVERRIDES_WS_TABLE_SQL(),
diff --git a/posthog/clickhouse/migrations/0243_fix_precalculated_events_date.py b/posthog/clickhouse/migrations/0243_fix_precalculated_events_date.py
index 69331fc40586..c54e5f115962 100644
--- a/posthog/clickhouse/migrations/0243_fix_precalculated_events_date.py
+++ b/posthog/clickhouse/migrations/0243_fix_precalculated_events_date.py
@@ -1,4 +1,3 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
from posthog.models.precalculated_events.sql import (
@@ -11,6 +10,7 @@ from posthog.models.precalculated_events.sql import (
PRECALCULATED_EVENTS_WS_MV,
PRECALCULATED_EVENTS_WS_MV_SQL,
)
+from posthog.run_mode import run_mode
# The precalculated_events materialized view was deriving `date` from `toDate(_timestamp)`,
# where `_timestamp` is the Kafka ingestion time. That broke backfills: events inserted by the
@@ -28,8 +28,6 @@ from posthog.models.precalculated_events.sql import (
# target, causing double-ingest. WS objects are only recreated in cloud; in non-cloud they are
# dropped (if present) and not recreated.
-_is_cloud = settings.CLOUD_DEPLOYMENT in ("US", "EU", "DEV")
-
operations = [
# Drop MVs first so the Kafka tables can be recreated without a brief double-write window.
run_sql_with_exceptions(
@@ -70,6 +68,6 @@ operations = [
node_roles=[NodeRole.INGESTION_MEDIUM],
),
]
- if _is_cloud
+ if run_mode().is_deployed_cloud
else []
)
diff --git a/posthog/clickhouse/migrations/0245_warpstream_cohort_membership_kafka_engine.py b/posthog/clickhouse/migrations/0245_warpstream_cohort_membership_kafka_engine.py
index 2a0922d1a01d..d69be4ef26a4 100644
--- a/posthog/clickhouse/migrations/0245_warpstream_cohort_membership_kafka_engine.py
+++ b/posthog/clickhouse/migrations/0245_warpstream_cohort_membership_kafka_engine.py
@@ -1,7 +1,7 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
from posthog.models.cohortmembership.sql import COHORT_MEMBERSHIP_WS_MV_SQL, KAFKA_COHORT_MEMBERSHIP_WS_TABLE_SQL
+from posthog.run_mode import run_mode
# Migration to create a WarpStream Kafka engine table for cohort_membership_changed.
#
@@ -18,7 +18,7 @@ from posthog.models.cohortmembership.sql import COHORT_MEMBERSHIP_WS_MV_SQL, KAF
operations = (
[]
- if settings.CLOUD_DEPLOYMENT not in ("US", "EU", "DEV")
+ if not run_mode().is_deployed_cloud
else [
run_sql_with_exceptions(
KAFKA_COHORT_MEMBERSHIP_WS_TABLE_SQL(),
diff --git a/posthog/clickhouse/migrations/0246_warpstream_replay_kafka_engines.py b/posthog/clickhouse/migrations/0246_warpstream_replay_kafka_engines.py
index 5b8fadc07152..4c5c234cf32c 100644
--- a/posthog/clickhouse/migrations/0246_warpstream_replay_kafka_engines.py
+++ b/posthog/clickhouse/migrations/0246_warpstream_replay_kafka_engines.py
@@ -1,6 +1,6 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.run_mode import run_mode
from posthog.session_recordings.sql.session_replay_event_sql import (
KAFKA_SESSION_REPLAY_EVENTS_WS_TABLE_SQL,
SESSION_REPLAY_EVENTS_WS_MV_SQL,
@@ -27,7 +27,7 @@ from posthog.session_recordings.sql.session_replay_feature_sql import (
operations = (
[]
- if settings.CLOUD_DEPLOYMENT not in ("US", "EU", "DEV")
+ if not run_mode().is_deployed_cloud
else [
# session_replay_events (INGESTION_SMALL, matching existing MSK table)
run_sql_with_exceptions(
diff --git a/posthog/clickhouse/migrations/0247_warpstream_shared_kafka_engines.py b/posthog/clickhouse/migrations/0247_warpstream_shared_kafka_engines.py
index d9af6edbcf07..ca1dbededb48 100644
--- a/posthog/clickhouse/migrations/0247_warpstream_shared_kafka_engines.py
+++ b/posthog/clickhouse/migrations/0247_warpstream_shared_kafka_engines.py
@@ -1,6 +1,6 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.run_mode import run_mode
from products.error_tracking.backend.embedding import (
DOCUMENT_EMBEDDINGS_WRITABLE_TABLE_SQL,
@@ -36,7 +36,7 @@ from products.error_tracking.backend.sql import (
operations = (
[]
- if settings.CLOUD_DEPLOYMENT not in ("US", "EU", "DEV")
+ if not run_mode().is_deployed_cloud
else [
# document_embeddings
run_sql_with_exceptions(
diff --git a/posthog/clickhouse/migrations/0248_drop_msk_kafka_engines_with_ws_equivalents.py b/posthog/clickhouse/migrations/0248_drop_msk_kafka_engines_with_ws_equivalents.py
index de4cdb062dc5..42bb29c1db56 100644
--- a/posthog/clickhouse/migrations/0248_drop_msk_kafka_engines_with_ws_equivalents.py
+++ b/posthog/clickhouse/migrations/0248_drop_msk_kafka_engines_with_ws_equivalents.py
@@ -1,6 +1,6 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.run_mode import run_mode
# Drop MSK Kafka engine tables and their materialized views for every topic that
# already has a WarpStream (`_ws`) consumer in place. Each pair listed here was
@@ -30,7 +30,7 @@ from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
operations = (
[]
- if settings.CLOUD_DEPLOYMENT not in ("US", "EU", "DEV")
+ if not run_mode().is_deployed_cloud
else [
# log_entries (INGESTION_SMALL — `_v3` is the live MSK consumer)
run_sql_with_exceptions(
diff --git a/posthog/clickhouse/migrations/0249_property_values_kafka_named_collection.py b/posthog/clickhouse/migrations/0249_property_values_kafka_named_collection.py
index 76af4718161f..f0f6e8c59469 100644
--- a/posthog/clickhouse/migrations/0249_property_values_kafka_named_collection.py
+++ b/posthog/clickhouse/migrations/0249_property_values_kafka_named_collection.py
@@ -1,4 +1,3 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
from posthog.clickhouse.property_values import (
@@ -8,6 +7,7 @@ from posthog.clickhouse.property_values import (
PROPERTY_VALUES_MV_SQL,
PROPERTY_VALUES_TABLE_SQL,
)
+from posthog.run_mode import run_mode
# Fix to 0244: kafka_property_values used the default msk_cluster named
# collection, but the topic is produced to warpstream_ingestion. Drop the MV
@@ -15,7 +15,7 @@ from posthog.clickhouse.property_values import (
# collection. Storage table is untouched. The property_values pipeline lives
# on AUX in every cloud env.
-if settings.CLOUD_DEPLOYMENT in ("US", "EU", "DEV"):
+if run_mode().is_deployed_cloud:
operations = [
run_sql_with_exceptions(PROPERTY_VALUES_TABLE_SQL(), node_roles=[NodeRole.AUX]),
run_sql_with_exceptions(DROP_PROPERTY_VALUES_MV_SQL(), node_roles=[NodeRole.AUX]),
diff --git a/posthog/clickhouse/migrations/0250_property_values_lowercase_text_index.py b/posthog/clickhouse/migrations/0250_property_values_lowercase_text_index.py
index b46e9c5d24ef..b0c6bf603904 100644
--- a/posthog/clickhouse/migrations/0250_property_values_lowercase_text_index.py
+++ b/posthog/clickhouse/migrations/0250_property_values_lowercase_text_index.py
@@ -1,8 +1,8 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.run_mode import run_mode
-if settings.CLOUD_DEPLOYMENT in ("US", "EU", "DEV"):
+if run_mode().is_deployed_cloud:
_ROLES = [NodeRole.AUX]
else:
_ROLES = []
diff --git a/posthog/clickhouse/migrations/0252_extend_session_replay_features.py b/posthog/clickhouse/migrations/0252_extend_session_replay_features.py
index ca2d9cbf78ef..9e34d771aefd 100644
--- a/posthog/clickhouse/migrations/0252_extend_session_replay_features.py
+++ b/posthog/clickhouse/migrations/0252_extend_session_replay_features.py
@@ -1,6 +1,6 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.run_mode import run_mode
from posthog.session_recordings.sql.session_replay_feature_sql import (
DISTRIBUTED_SESSION_REPLAY_FEATURES_TABLE_SQL,
DROP_KAFKA_SESSION_REPLAY_FEATURES_TABLE_SQL,
@@ -62,8 +62,6 @@ def _alter_sharded() -> str:
)
-_is_cloud = settings.CLOUD_DEPLOYMENT in ("US", "EU", "DEV")
-
operations = [
# 1. Drop all materialized views and Kafka tables (MSK + WarpStream) before
run_sql_with_exceptions(DROP_SESSION_REPLAY_FEATURES_TABLE_MV_SQL(), node_roles=[NodeRole.INGESTION_MEDIUM]),
@@ -107,7 +105,7 @@ operations = [
),
run_sql_with_exceptions(SESSION_REPLAY_FEATURES_WS_MV_SQL(), node_roles=[NodeRole.INGESTION_MEDIUM]),
]
- if _is_cloud
+ if run_mode().is_deployed_cloud
# Non-cloud: MSK pair only.
else [
run_sql_with_exceptions(
diff --git a/posthog/clickhouse/migrations/0253_drop_dead_msk_kafka_tables.py b/posthog/clickhouse/migrations/0253_drop_dead_msk_kafka_tables.py
index 0db63fb0a058..2206cf427772 100644
--- a/posthog/clickhouse/migrations/0253_drop_dead_msk_kafka_tables.py
+++ b/posthog/clickhouse/migrations/0253_drop_dead_msk_kafka_tables.py
@@ -1,6 +1,6 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.run_mode import run_mode
# Drop MSK Kafka engine tables and their materialized views for topics that are
# no longer actively produced to, or whose functionality has been superseded.
@@ -25,7 +25,7 @@ from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
operations = (
[]
- if settings.CLOUD_DEPLOYMENT not in ("US", "EU", "DEV")
+ if not run_mode().is_deployed_cloud
else [
# plugin_log_entries (INGESTION_SMALL — moved here by migration 0152)
run_sql_with_exceptions(
diff --git a/posthog/clickhouse/migrations/0257_property_values_count_column.py b/posthog/clickhouse/migrations/0257_property_values_count_column.py
index 88b63d019f7d..cec90251d98f 100644
--- a/posthog/clickhouse/migrations/0257_property_values_count_column.py
+++ b/posthog/clickhouse/migrations/0257_property_values_count_column.py
@@ -1,4 +1,3 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
from posthog.clickhouse.property_values import (
@@ -7,11 +6,12 @@ from posthog.clickhouse.property_values import (
KAFKA_PROPERTY_VALUES_TABLE_SQL_FN,
PROPERTY_VALUES_MV_SQL,
)
+from posthog.run_mode import run_mode
# Kafka engine tables don't support ALTER ADD COLUMN, so we drop and recreate
# the MV + Kafka engine table together.
-if settings.CLOUD_DEPLOYMENT in ("US", "EU", "DEV"):
+if run_mode().is_deployed_cloud:
_ROLES = [NodeRole.AUX]
else:
_ROLES = []
diff --git a/posthog/clickhouse/migrations/0265_add_surfacing_score_to_session_replay_events.py b/posthog/clickhouse/migrations/0265_add_surfacing_score_to_session_replay_events.py
index 2cc4dd7437f5..6f3650b4893b 100644
--- a/posthog/clickhouse/migrations/0265_add_surfacing_score_to_session_replay_events.py
+++ b/posthog/clickhouse/migrations/0265_add_surfacing_score_to_session_replay_events.py
@@ -1,6 +1,6 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.run_mode import run_mode
from posthog.session_recordings.sql.session_replay_event_migrations_sql import (
ADD_SURFACING_SCORE_DISTRIBUTED_SESSION_REPLAY_EVENTS_TABLE_SQL,
ADD_SURFACING_SCORE_SESSION_REPLAY_EVENTS_TABLE_SQL,
@@ -20,8 +20,6 @@ from posthog.session_recordings.sql.session_replay_event_sql import (
# Add surfacing_score to session_replay_events. Cloud uses WarpStream and is dropping MSK;
# non-cloud only has MSK.
-_IS_CLOUD = settings.CLOUD_DEPLOYMENT in ("US", "EU", "DEV")
-
operations = [
# Drop MV + Kafka tables (DROP IF EXISTS, so WS drops no-op in non-cloud).
run_sql_with_exceptions(
@@ -57,7 +55,7 @@ operations = [
run_sql_with_exceptions(KAFKA_SESSION_REPLAY_EVENTS_WS_TABLE_SQL(), node_roles=[NodeRole.INGESTION_SMALL]),
run_sql_with_exceptions(SESSION_REPLAY_EVENTS_WS_MV_SQL(), node_roles=[NodeRole.INGESTION_SMALL]),
]
- if _IS_CLOUD
+ if run_mode().is_deployed_cloud
else [
run_sql_with_exceptions(
KAFKA_SESSION_REPLAY_EVENTS_TABLE_SQL(on_cluster=False), node_roles=[NodeRole.INGESTION_SMALL]
diff --git a/posthog/clickhouse/migrations/0266_recreate_session_replay_features.py b/posthog/clickhouse/migrations/0266_recreate_session_replay_features.py
index b7a39455d682..c11e36b8be23 100644
--- a/posthog/clickhouse/migrations/0266_recreate_session_replay_features.py
+++ b/posthog/clickhouse/migrations/0266_recreate_session_replay_features.py
@@ -1,6 +1,7 @@
from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.run_mode import run_mode
from posthog.session_recordings.sql.session_replay_feature_sql import (
DISTRIBUTED_SESSION_REPLAY_FEATURES_TABLE_SQL,
KAFKA_SESSION_REPLAY_FEATURES_TABLE_SQL,
@@ -13,8 +14,6 @@ from posthog.session_recordings.sql.session_replay_feature_sql import (
# Recreate session_replay_features from scratch.
-_is_cloud = settings.CLOUD_DEPLOYMENT in ("US", "EU", "DEV")
-
operations = [
# 1. Sharded storage on AUX.
run_sql_with_exceptions(
@@ -49,7 +48,7 @@ operations = [
node_roles=[NodeRole.INGESTION_MEDIUM],
),
]
- if _is_cloud
+ if run_mode().is_deployed_cloud
else [
run_sql_with_exceptions(
KAFKA_SESSION_REPLAY_FEATURES_TABLE_SQL(on_cluster=False),
diff --git a/posthog/clickhouse/migrations/0268_property_values_kafka_num_consumers.py b/posthog/clickhouse/migrations/0268_property_values_kafka_num_consumers.py
index bc52c95c6b41..012629658cd8 100644
--- a/posthog/clickhouse/migrations/0268_property_values_kafka_num_consumers.py
+++ b/posthog/clickhouse/migrations/0268_property_values_kafka_num_consumers.py
@@ -1,4 +1,3 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
from posthog.clickhouse.property_values import (
@@ -7,8 +6,9 @@ from posthog.clickhouse.property_values import (
KAFKA_PROPERTY_VALUES_TABLE_SQL_FN,
PROPERTY_VALUES_MV_SQL,
)
+from posthog.run_mode import run_mode
-if settings.CLOUD_DEPLOYMENT in ("US", "EU", "DEV"):
+if run_mode().is_deployed_cloud:
_ROLES = [NodeRole.AUX]
else:
_ROLES = []
diff --git a/posthog/clickhouse/migrations/0270_property_values_drop_mv_length_filter.py b/posthog/clickhouse/migrations/0270_property_values_drop_mv_length_filter.py
index d5f0ab4e32de..7de3751a3358 100644
--- a/posthog/clickhouse/migrations/0270_property_values_drop_mv_length_filter.py
+++ b/posthog/clickhouse/migrations/0270_property_values_drop_mv_length_filter.py
@@ -1,7 +1,7 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
from posthog.clickhouse.property_values import DROP_PROPERTY_VALUES_MV_SQL, PROPERTY_VALUES_MV_SQL
+from posthog.run_mode import run_mode
# Length and empty-value filtering now lives in the property-vals service, so the
# MV passes everything from the Kafka table straight through. property_values lives
@@ -14,6 +14,6 @@ operations = (
run_sql_with_exceptions(DROP_PROPERTY_VALUES_MV_SQL(), node_roles=_ROLES),
run_sql_with_exceptions(PROPERTY_VALUES_MV_SQL(), node_roles=_ROLES),
]
- if settings.CLOUD_DEPLOYMENT in ("US", "EU", "DEV")
+ if run_mode().is_deployed_cloud
else []
)
diff --git a/posthog/clickhouse/migrations/0273_query_log_archive_ops_json.py b/posthog/clickhouse/migrations/0273_query_log_archive_ops_json.py
index babd0d3b0143..a546d4c821ca 100644
--- a/posthog/clickhouse/migrations/0273_query_log_archive_ops_json.py
+++ b/posthog/clickhouse/migrations/0273_query_log_archive_ops_json.py
@@ -1,4 +1,3 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
from posthog.clickhouse.query_log_archive import (
@@ -12,6 +11,7 @@ from posthog.clickhouse.query_log_archive import (
WRITABLE_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL,
WRITABLE_QUERY_LOG_ARCHIVE_TABLE,
)
+from posthog.run_mode import run_mode
# Rebuild query_log_archive as a JSON-backed data table living on the OPS cluster:
# - sharded_query_log_archive : OPS data table, stores log_comment as a curated JSON column and
@@ -66,7 +66,7 @@ operations = [
# node, it catches the DATA-side table and leaves an empty copy behind — so drop it.
*(
[]
- if settings.CLOUD_DEPLOYMENT in ("US", "EU", "DEV")
+ if run_mode().is_deployed_cloud
else [
run_sql_with_exceptions(
f"DROP TABLE IF EXISTS {QUERY_LOG_ARCHIVE_OLD_TABLE}",
diff --git a/posthog/clickhouse/migrations/0276_query_log_archive_buffer.py b/posthog/clickhouse/migrations/0276_query_log_archive_buffer.py
index 937a2efc9e74..0b7fae61df71 100644
--- a/posthog/clickhouse/migrations/0276_query_log_archive_buffer.py
+++ b/posthog/clickhouse/migrations/0276_query_log_archive_buffer.py
@@ -1,4 +1,3 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
from posthog.clickhouse.query_log_archive import (
@@ -6,6 +5,7 @@ from posthog.clickhouse.query_log_archive import (
WRITABLE_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL,
WRITABLE_QUERY_LOG_ARCHIVE_TABLE,
)
+from posthog.run_mode import run_mode
# Insert a Buffer table (query_log_archive_buffer) in front of sharded_query_log_archive on the
# OPS cluster and route writable_query_log_archive through it, so the many small per-cluster MV
@@ -26,8 +26,6 @@ ALL_ROLES = [
NodeRole.OPS,
]
-_IS_CLOUD = settings.CLOUD_DEPLOYMENT in ("US", "EU", "DEV")
-
operations = [
# Buffer table on OPS, flushing to sharded_query_log_archive. Owned by this migration
# (not posthog-cloud-infra), so created everywhere — cloud and local.
@@ -36,7 +34,7 @@ operations = [
# posthog-cloud-infra. Drop + recreate is safe (Distributed holds no data, not replicated).
*(
[]
- if _IS_CLOUD
+ if run_mode().is_deployed_cloud
else [
run_sql_with_exceptions(f"DROP TABLE IF EXISTS {WRITABLE_QUERY_LOG_ARCHIVE_TABLE}", node_roles=ALL_ROLES),
run_sql_with_exceptions(WRITABLE_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL(), node_roles=ALL_ROLES),
diff --git a/posthog/clickhouse/migrations/0289_events_json_schema.py b/posthog/clickhouse/migrations/0289_events_json_schema.py
index e91939848038..46b33298df38 100644
--- a/posthog/clickhouse/migrations/0289_events_json_schema.py
+++ b/posthog/clickhouse/migrations/0289_events_json_schema.py
@@ -1,4 +1,3 @@
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
from posthog.models.event.sql import (
@@ -8,14 +7,13 @@ from posthog.models.event.sql import (
KAFKA_EVENTS_NATIVE_JSON_TABLE_SQL,
WRITABLE_EVENTS_JSON_TABLE_SQL,
)
-
-_IS_CLOUD = settings.CLOUD_DEPLOYMENT in ("US", "EU", "DEV")
+from posthog.run_mode import run_mode
# Cloud clusters get this schema rolled out separately. Keep this migration empty there so
# merging the application code does not change production ClickHouse schema.
operations = (
[]
- if _IS_CLOUD
+ if run_mode().is_deployed_cloud
else [
run_sql_with_exceptions(
EVENTS_JSON_TABLE_SQL(),
diff --git a/posthog/clickhouse/migrations/0291_add_ai_channel_type.py b/posthog/clickhouse/migrations/0291_add_ai_channel_type.py
index a478ae2066bc..3c25944778a4 100644
--- a/posthog/clickhouse/migrations/0291_add_ai_channel_type.py
+++ b/posthog/clickhouse/migrations/0291_add_ai_channel_type.py
@@ -1,5 +1,3 @@
-from django.conf import settings
-
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
from posthog.models.channel_type.sql import (
@@ -7,7 +5,13 @@ from posthog.models.channel_type.sql import (
CHANNEL_DEFINITION_DICTIONARY_NAME,
CHANNEL_DEFINITION_TABLE_NAME,
)
+from posthog.run_mode import RunMode, run_mode
+# Refreshes channel_definition with the AI channel type sources (chatgpt, claude, gemini, etc.), including
+# the perplexity/phind/you.com/andisearch/komo.ai rows reclassified from Search to AI. Nothing reads the
+# table at query time (all reads go through channel_definition_dict), so truncate + full reinsert is safe:
+# the dictionary serves its cached snapshot until the explicit reload. Writes run on one host
+# (is_alter_on_replicated_table) and replication fans out.
# Refreshes channel_definition with the AI channel type sources (chatgpt, claude, gemini, etc.), including
# the perplexity/phind/you.com/andisearch/komo.ai rows reclassified from Search to AI. Nothing reads the
# table at query time (all reads go through channel_definition_dict), so truncate + full reinsert is safe:
@@ -35,7 +39,12 @@ operations = [
# independent replica set (own zookeeper path) that the main-cluster write never reaches, so it needs its
# own truncate + reinsert; EU only has a Distributed wrapper over the main-cluster table (never TRUNCATE
# that), so a dictionary reload suffices. Local/hobby/dev sessions nodes carry neither (prod-only tables).
-if settings.CLOUD_DEPLOYMENT == "US":
+# The sessions satellite serves channel classification for session queries via its own per-node dictionary,
+# but its channel_definition differs per region (see posthog/clickhouse/hcl/roles/sessions/): US keeps an
+# independent replica set (own zookeeper path) that the main-cluster write never reaches, so it needs its
+# own truncate + reinsert; EU only has a Distributed wrapper over the main-cluster table (never TRUNCATE
+# that), so a dictionary reload suffices. Local/hobby/dev sessions nodes carry neither (prod-only tables).
+if run_mode() is RunMode.CLOUD_US:
operations += [
run_sql_with_exceptions(
f"TRUNCATE TABLE IF EXISTS {CHANNEL_DEFINITION_TABLE_NAME}",
@@ -48,7 +57,7 @@ if settings.CLOUD_DEPLOYMENT == "US":
is_alter_on_replicated_table=True,
),
]
-if settings.CLOUD_DEPLOYMENT in ("US", "EU"):
+if run_mode().is_prod_cloud:
operations.append(
run_sql_with_exceptions(
f"SYSTEM RELOAD DICTIONARY {CHANNEL_DEFINITION_DICTIONARY_NAME}",
diff --git a/posthog/clickhouse/migrations/0295_add_error_tracking_issue_severity.py b/posthog/clickhouse/migrations/0295_add_error_tracking_issue_severity.py
index 7e16fdeacea7..e21a09386677 100644
--- a/posthog/clickhouse/migrations/0295_add_error_tracking_issue_severity.py
+++ b/posthog/clickhouse/migrations/0295_add_error_tracking_issue_severity.py
@@ -2,9 +2,9 @@
Placement (node_roles) is derived from the node composition manifest; review before committing.
"""
-from posthog import settings
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.run_mode import run_mode
from products.error_tracking.backend.sql import (
ERROR_TRACKING_FINGERPRINT_ISSUE_STATE_KAFKA_TABLE,
@@ -17,8 +17,6 @@ from products.error_tracking.backend.sql import (
KAFKA_ERROR_TRACKING_FINGERPRINT_ISSUE_STATE_WS_TABLE_SQL,
)
-_is_cloud = settings.CLOUD_DEPLOYMENT in ("US", "EU", "DEV")
-
operations = [
run_sql_with_exceptions(
"ALTER TABLE raw_error_tracking_fingerprint_issue_state "
@@ -67,7 +65,7 @@ operations = [
node_roles=[NodeRole.INGESTION_SMALL],
),
]
- if _is_cloud
+ if run_mode().is_deployed_cloud
else [
run_sql_with_exceptions(
f"DROP TABLE IF EXISTS {ERROR_TRACKING_FINGERPRINT_ISSUE_STATE_MV}",
diff --git a/posthog/clickhouse/migrations/AGENTS.md b/posthog/clickhouse/migrations/AGENTS.md
index de440106a0a2..d60dc60b66f7 100644
--- a/posthog/clickhouse/migrations/AGENTS.md
+++ b/posthog/clickhouse/migrations/AGENTS.md
@@ -62,13 +62,16 @@ in a local dev environment.
Some migrations are cloud-guarded and skipped in local/hobby dev:
```python
-operations = (
- []
- if settings.CLOUD_DEPLOYMENT not in ("US", "EU", "DEV")
- else [...]
-)
+from posthog.run_mode import run_mode
+
+operations = [...] if run_mode().is_deployed_cloud else []
```
+Spell the gate with `posthog.run_mode`, never a raw `settings.CLOUD_DEPLOYMENT` comparison.
+A semgrep rule blocks the latter. Resolve the mode inside the call rather than into a
+module-level constant, so `test_migrations.py` can re-import the module under a patched
+`posthog.settings.CLOUD_DEPLOYMENT`.
+
If you create a new table inside such a guard, also add its SQL function to
`posthog/clickhouse/schema.py` in the appropriate tuple so the table is created locally:
diff --git a/posthog/cloud_utils.py b/posthog/cloud_utils.py
index e5521ac5a46c..24bf38161634 100644
--- a/posthog/cloud_utils.py
+++ b/posthog/cloud_utils.py
@@ -7,6 +7,7 @@ from django.db.utils import ProgrammingError
from django.utils import timezone
from posthog.exceptions_capture import capture_exception
+from posthog.run_mode import RunMode, derive_run_mode
if TYPE_CHECKING:
from ee.models.license import License
@@ -16,16 +17,31 @@ is_instance_licensed_cached: Optional[bool] = None
instance_license_cached: Optional["License"] = None
+def _run_mode() -> RunMode:
+ """Resolve the run mode from `django.conf.settings`, so `override_settings` applies.
+
+ `posthog.run_mode.run_mode` reads the `posthog.settings` module instead, which is what
+ ClickHouse migrations and their `mock.patch`-based tests need. Both spell the mapping
+ with `derive_run_mode`; only the settings object they read differs.
+ """
+ return derive_run_mode(settings.CLOUD_DEPLOYMENT, settings.DEBUG)
+
+
# Keep this in sync with isCloud() in nodejs/src/utils/env-utils.ts.
# "dev" refers to the hosted development environment, not local development (which is "local").
def is_cloud() -> bool:
- return (settings.CLOUD_DEPLOYMENT or "").upper() in ("EU", "US", "DEV", "E2E")
+ return _run_mode().is_cloud
def is_dev_mode() -> bool:
return bool(settings.DEBUG)
+def is_hobby() -> bool:
+ """Self-hosted install: neither cloud nor local dev. Mirrors `isHobby` in preflightLogic."""
+ return _run_mode().is_hobby
+
+
def is_ci() -> bool:
return os.environ.get("GITHUB_ACTIONS") is not None
diff --git a/posthog/run_mode.py b/posthog/run_mode.py
new file mode 100644
index 000000000000..0c74f76a2b60
--- /dev/null
+++ b/posthog/run_mode.py
@@ -0,0 +1,79 @@
+from enum import StrEnum
+
+__all__ = ["RunMode", "derive_run_mode", "run_mode"]
+
+
+class RunMode(StrEnum):
+ """How this PostHog process is deployed."""
+
+ CLOUD_US = "US"
+ CLOUD_EU = "EU"
+ CLOUD_DEV = "DEV"
+ E2E = "E2E"
+ LOCAL = "LOCAL"
+ HOBBY = "HOBBY"
+
+ @property
+ def is_prod_cloud(self) -> bool:
+ """Customer-facing PostHog Cloud: US or EU, excluding staging."""
+ return self is RunMode.CLOUD_US or self is RunMode.CLOUD_EU
+
+ @property
+ def is_deployed_cloud(self) -> bool:
+ """A cloud environment backed by deployed infrastructure: US, EU, or staging.
+
+ Excludes E2E, which runs against a local single-node stack. This is the
+ distinction ClickHouse migrations gate on.
+ """
+ return self.is_prod_cloud or self is RunMode.CLOUD_DEV
+
+ @property
+ def is_cloud(self) -> bool:
+ """Any cloud mode, E2E included. Matches `posthog.cloud_utils.is_cloud`."""
+ return self.is_deployed_cloud or self is RunMode.E2E
+
+ @property
+ def is_hobby(self) -> bool:
+ """Self-hosted: no cloud deployment and not local dev."""
+ return self is RunMode.HOBBY
+
+ @property
+ def region(self) -> str | None:
+ """`US`, `EU` or `DEV` on a deployed cloud env, else None."""
+ return self.value if self.is_deployed_cloud else None
+
+
+def derive_run_mode(cloud_deployment: str | None, debug: bool) -> RunMode:
+ """Resolve a run mode from the two settings that define it.
+
+ An unrecognized `cloud_deployment` resolves to LOCAL or HOBBY rather than raising,
+ so a typo'd value silently disables every cloud-gated code path instead of failing
+ the process.
+ """
+ match (cloud_deployment or "").upper():
+ case "US":
+ return RunMode.CLOUD_US
+ case "EU":
+ return RunMode.CLOUD_EU
+ case "DEV":
+ return RunMode.CLOUD_DEV
+ case "E2E":
+ return RunMode.E2E
+ case "LOCAL":
+ return RunMode.LOCAL
+ case _:
+ return RunMode.LOCAL if debug else RunMode.HOBBY
+
+
+def run_mode() -> RunMode:
+ """The current run mode, read from `posthog.settings` on every call.
+
+ Deliberately not cached: ClickHouse migrations resolve their `operations` at
+ module scope, and their tests re-import those modules under a patched
+ `posthog.settings.CLOUD_DEPLOYMENT` to check each deployment's branch.
+ """
+ # Module-level import would cycle: posthog.settings -> posthog.settings.utils ->
+ # posthog.utils -> posthog.cloud_utils, and cloud_utils imports this module.
+ from posthog import settings # noqa: PLC0415
+
+ return derive_run_mode(settings.CLOUD_DEPLOYMENT, settings.DEBUG)
diff --git a/posthog/test/test_run_mode.py b/posthog/test/test_run_mode.py
new file mode 100644
index 000000000000..e81770a6a5c4
--- /dev/null
+++ b/posthog/test/test_run_mode.py
@@ -0,0 +1,78 @@
+import unittest
+from unittest import mock
+
+from django.test import SimpleTestCase, override_settings
+
+from parameterized import parameterized
+
+from posthog.cloud_utils import is_cloud, is_hobby
+from posthog.run_mode import RunMode, derive_run_mode, run_mode
+
+
+class TestDeriveRunMode(unittest.TestCase):
+ @parameterized.expand(
+ [
+ ("US", False, RunMode.CLOUD_US),
+ ("EU", False, RunMode.CLOUD_EU),
+ ("DEV", False, RunMode.CLOUD_DEV),
+ ("E2E", True, RunMode.E2E),
+ ("LOCAL", False, RunMode.LOCAL),
+ ("us", False, RunMode.CLOUD_US),
+ (None, True, RunMode.LOCAL),
+ (None, False, RunMode.HOBBY),
+ ("", False, RunMode.HOBBY),
+ ("PROD", False, RunMode.HOBBY),
+ ]
+ )
+ def test_derives_mode(self, cloud_deployment: str | None, debug: bool, expected: RunMode) -> None:
+ self.assertIs(derive_run_mode(cloud_deployment, debug), expected)
+
+ @parameterized.expand(
+ [
+ (RunMode.CLOUD_US, True, True, True, False, "US"),
+ (RunMode.CLOUD_EU, True, True, True, False, "EU"),
+ (RunMode.CLOUD_DEV, False, True, True, False, "DEV"),
+ (RunMode.E2E, False, False, True, False, None),
+ (RunMode.LOCAL, False, False, False, False, None),
+ (RunMode.HOBBY, False, False, False, True, None),
+ ]
+ )
+ def test_predicates(
+ self,
+ mode: RunMode,
+ is_prod_cloud: bool,
+ is_deployed_cloud: bool,
+ is_cloud: bool,
+ is_hobby: bool,
+ region: str | None,
+ ) -> None:
+ self.assertEqual(mode.is_prod_cloud, is_prod_cloud)
+ self.assertEqual(mode.is_deployed_cloud, is_deployed_cloud)
+ self.assertEqual(mode.is_cloud, is_cloud)
+ self.assertEqual(mode.is_hobby, is_hobby)
+ self.assertEqual(mode.region, region)
+
+ def test_reads_settings_on_every_call(self) -> None:
+ with mock.patch("posthog.settings.CLOUD_DEPLOYMENT", "EU"):
+ self.assertIs(run_mode(), RunMode.CLOUD_EU)
+ with mock.patch("posthog.settings.CLOUD_DEPLOYMENT", "US"):
+ self.assertIs(run_mode(), RunMode.CLOUD_US)
+
+
+class TestCloudUtilsRunMode(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("US", False, True, False),
+ ("EU", False, True, False),
+ ("DEV", False, True, False),
+ ("E2E", False, True, False),
+ (None, True, False, False),
+ (None, False, False, True),
+ ]
+ )
+ def test_honors_override_settings(
+ self, cloud_deployment: str | None, debug: bool, cloud: bool, hobby: bool
+ ) -> None:
+ with override_settings(CLOUD_DEPLOYMENT=cloud_deployment, DEBUG=debug):
+ self.assertEqual(is_cloud(), cloud)
+ self.assertEqual(is_hobby(), hobby)