: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
fix(data-warehouse): populate s3_folder_name on schema create (#64144)
Daniel RC1519d00f66d3
diff --git a/posthog/temporal/data_imports/pipelines/helpers.py b/posthog/temporal/data_imports/pipelines/helpers.pyindex 1d093d88966e..3dc7c325b478 100644--- a/posthog/temporal/data_imports/pipelines/helpers.py+++ b/posthog/temporal/data_imports/pipelines/helpers.py@@ -64,6 +64,27 @@ def build_table_name(source: ExternalDataSource, schema_name: str):return f"{source.prefix or ''}{source.source_type}_{safe_schema_name}".lower()+def resolve_table_and_folder_names(schema_name: str, resolved_s3_folder_name: str | None) -> tuple[str, str]:+ """Return `(table_storage_name, folder_name)` for a schema row.++ These are intentionally different normalizations:+ - The S3 folder is the *snake_cased* identifier (`BalanceTransaction` -> `balance_transaction`).+ - `build_table_name` only lower-cases, so the HogQL table name must derive from the *raw* schema+ name (`BalanceTransaction` -> `stripe_balancetransaction`). Feeding it the folder would rename+ existing tables, e.g. `stripe_balancetransaction` -> `stripe_balance_transaction`.++ The exception is a row renamed during multi-schema migration: its folder is pinned to the+ original path, which differs from the row's own normalized name, so the table stays anchored+ there (e.g. `public.users` with folder `users` keeps `<prefix>_users`).+ """+ from posthog.temporal.data_imports.naming_convention import NamingConvention++ folder_name = NamingConvention.normalize_identifier(resolved_s3_folder_name or schema_name)+ is_folder_pinned = folder_name != NamingConvention.normalize_identifier(schema_name)+ table_storage_name = folder_name if is_folder_pinned else schema_name+ return table_storage_name, folder_name++def sync_revenue_analytics_views(schema: ExternalDataSchema, source: ExternalDataSource) -> None:"""Re-sync revenue analytics materialized views after a data load completes.diff --git a/posthog/temporal/data_imports/pipelines/pipeline_sync.py b/posthog/temporal/data_imports/pipelines/pipeline_sync.pyindex ee5ff1d97022..75fea10b928d 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_sync.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_sync.py@@ -21,7 +21,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.sync import database_sync_to_async_poolfrom posthog.temporal.common.logger import get_loggerfrom posthog.temporal.data_imports.naming_convention import NamingConvention-from posthog.temporal.data_imports.pipelines.helpers import build_table_name+from posthog.temporal.data_imports.pipelines.helpers import build_table_name, resolve_table_and_folder_namesfrom posthog.temporal.data_imports.sources.common.sql import filter_dwh_columns_by_enabled_columnsfrom products.data_warehouse.backend.types import ExternalDataSourceType@@ -178,12 +178,12 @@ async def validate_schema_and_update_table(_schema_name: str = external_data_schema.nameincremental_or_append = external_data_schema.should_use_incremental_field- # `s3_folder_name` pins the Delta path to the original unqualified name for legacy- # warehouse rows that got renamed to qualified form during multi-schema migration.- storage_schema_name = external_data_schema.resolved_s3_folder_name or _schema_name-- table_name = build_table_name(job.pipeline, storage_schema_name)- normalized_schema_name = NamingConvention.normalize_identifier(storage_schema_name)+ # The HogQL table name derives from the raw schema name (only lower-cased); the S3 folder is+ # the snake_cased `s3_folder_name`. They differ on purpose — see `resolve_table_and_folder_names`.+ table_storage_name, normalized_schema_name = resolve_table_and_folder_names(+ _schema_name, external_data_schema.resolved_s3_folder_name+ )+ table_name = build_table_name(job.pipeline, table_storage_name)new_url_pattern = job.url_pattern_by_schema(normalized_schema_name)# Checkdiff --git a/posthog/temporal/data_imports/pipelines/test_pipeline_sync.py b/posthog/temporal/data_imports/pipelines/test_pipeline_sync.pyindex 8e222d79827f..93d2dc54c29a 100644--- a/posthog/temporal/data_imports/pipelines/test_pipeline_sync.py+++ b/posthog/temporal/data_imports/pipelines/test_pipeline_sync.py@@ -3,8 +3,10 @@ import uuidfrom posthog.test.base import BaseTestfrom unittest.mock import patch+from parameterized import parameterized+from posthog.temporal.data_imports.naming_convention import NamingConvention-from posthog.temporal.data_imports.pipelines.helpers import build_table_name+from posthog.temporal.data_imports.pipelines.helpers import build_table_name, resolve_table_and_folder_namesfrom posthog.temporal.data_imports.pipelines.pipeline_sync import merge_columnsfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJob@@ -13,6 +15,49 @@ from products.warehouse_sources.backend.models.external_data_source import Exterfrom products.warehouse_sources.backend.models.table import DataWarehouseTable+class TestResolveTableAndFolderNames:+ @parameterized.expand(+ [+ # Stripe CamelCase: folder snake_cases, but the table keeps the only-lowercased raw name.+ (+ "stripe_camelcase",+ "BalanceTransaction",+ "balance_transaction",+ "BalanceTransaction",+ "balance_transaction",+ ),+ (+ "stripe_compound",+ "CustomerBalanceTransaction",+ "customer_balance_transaction",+ "CustomerBalanceTransaction",+ "customer_balance_transaction",+ ),+ # Already snake_case: table and folder match.+ ("plain_snake", "charge", "charge", "charge", "charge"),+ # Native multi-schema (never migrated): dotted name drives the table, folder snake_cases the dot.+ ("native_multi_schema", "public.orders", "public_orders", "public.orders", "public_orders"),+ # Legacy migrated row: folder is pinned to the original (differs from normalize(name)),+ # so the table anchors to the pinned folder, not the qualified name.+ ("legacy_pinned", "public.users", "users", "users", "users"),+ # No folder set: behaves like a plain row, table from the raw name.+ ("no_folder", "BalanceTransaction", None, "BalanceTransaction", "balance_transaction"),+ ]+ )+ def test_resolve(+ self, _name: str, schema_name: str, resolved_folder: str | None, exp_table: str, exp_folder: str+ ) -> None:+ table_storage_name, folder_name = resolve_table_and_folder_names(schema_name, resolved_folder)+ assert table_storage_name == exp_table+ assert folder_name == exp_folder++ def test_table_name_unchanged_for_camelcase_source(self) -> None:+ # The regression guard: a populated (snake_cased) folder must NOT rename the HogQL table.+ source = ExternalDataSource(source_type="Stripe", prefix="")+ table_storage_name, _ = resolve_table_and_folder_names("BalanceTransaction", "balance_transaction")+ assert build_table_name(source, table_storage_name) == "stripe_balancetransaction"++def _register_companion_sync(run_id: str,team_id: int,diff --git a/products/warehouse_sources/backend/migrations/0021_backfill_externaldataschema_s3_folder_name_gap.py b/products/warehouse_sources/backend/migrations/0021_backfill_externaldataschema_s3_folder_name_gap.pynew file mode 100644index 000000000000..1f87a56f2c02--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0021_backfill_externaldataschema_s3_folder_name_gap.py@@ -0,0 +1,39 @@+import time++from django.db import migrations++from posthog.temporal.data_imports.naming_convention import NamingConvention++BATCH_SIZE = 2000+++def forwards(apps, schema_editor):+ # Rows created after the column shipped but before `save()` started populating it have a NULL+ # `s3_folder_name`. Re-run the same backfill to fill them; the model's `save()` override prevents+ # any new NULLs going forward.+ ExternalDataSchema = apps.get_model("warehouse_sources", "ExternalDataSchema")++ while True:+ batch = list(+ ExternalDataSchema.objects.filter(s3_folder_name__isnull=True).only("id", "name", "sync_type_config")[+ :BATCH_SIZE+ ]+ )+ if not batch:+ break+ for schema in batch:+ legacy_key = (schema.sync_type_config or {}).get("dwh_storage_key")+ raw = legacy_key if isinstance(legacy_key, str) and legacy_key else schema.name+ schema.s3_folder_name = NamingConvention.normalize_identifier(raw)+ ExternalDataSchema.objects.bulk_update(batch, ["s3_folder_name"])+ time.sleep(0.1)+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources", "0020_alter_externaldatasource_source_type_and_more"),+ ]++ operations = [+ migrations.RunPython(forwards, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/warehouse_sources/backend/migrations/0022_repair_s3_folder_name_table_names.py b/products/warehouse_sources/backend/migrations/0022_repair_s3_folder_name_table_names.pynew file mode 100644index 000000000000..af4715b9b826--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0022_repair_s3_folder_name_table_names.py@@ -0,0 +1,59 @@+"""Rename DataWarehouseTables mis-named by feeding the snake_cased `s3_folder_name` into the table+name. `build_table_name` only lower-cases (`BalanceTransaction` -> `stripe_balancetransaction`),+but the buggy code lower-cased the *snake_cased* folder (`balance_transaction` ->+`stripe_balance_transaction`), breaking HogQL queries on the conventional name. The Delta data is+untouched (the S3 folder was always the snake_cased name) — this is a pure rename.++The match is deliberately exact: a table whose name IS what the bug produced+(`build_table_name(s3_folder_name)`) and that differs from the correct `build_table_name(name)`.+That excludes tables named by other code paths (direct-query / DuckLake tables are stored as the+raw schema name, not via build_table_name) and excludes multi-schema migration pins (dotted names,+where building from the folder is correct). A row that would collide with another live table of the+target name is left untouched.++The SQL mirrors `build_table_name`: lower(coalesce(prefix,'') || source_type || '_' || name).+Run the matching SELECT first (see the PR description) to preview the rows it will touch.+"""++from django.db import migrations++REPAIR_SQL = """+-- migration-analyzer: safe reason=Renames ~20 specific rows matched by an exact-name predicate (verified by a dry-run SELECT); brief lock, no batching needed.+UPDATE posthog_datawarehousetable AS t+SET name = lower(coalesce(src.prefix, '') || src.source_type || '_' || replace(s.name, '.', '__')),+ updated_at = now()+FROM posthog_externaldataschema AS s+JOIN posthog_externaldatasource AS src ON src.id = s.source_id+WHERE s.table_id = t.id+ AND s.deleted = false+ AND t.deleted = false+ AND strpos(s.name, '.') = 0 -- exclude multi-schema migration pins (dotted names)+ AND s.s3_folder_name IS NOT NULL+ -- the table name IS exactly the buggy output (built from the snake_cased folder)...+ AND t.name = lower(coalesce(src.prefix, '') || src.source_type || '_' || replace(s.s3_folder_name, '.', '__'))+ -- ...and that differs from the correct name (built from the raw schema name)...+ AND lower(coalesce(src.prefix, '') || src.source_type || '_' || replace(s.s3_folder_name, '.', '__'))+ <> lower(coalesce(src.prefix, '') || src.source_type || '_' || replace(s.name, '.', '__'))+ -- ...and nothing live already holds the target name for this source (avoid an ambiguous table).+ AND NOT EXISTS (+ SELECT 1+ FROM posthog_datawarehousetable AS t2+ WHERE t2.deleted = false+ AND t2.id <> t.id+ AND t2.team_id = t.team_id+ AND t2.external_data_source_id = t.external_data_source_id+ AND t2.name = lower(coalesce(src.prefix, '') || src.source_type || '_' || replace(s.name, '.', '__'))+ );+"""+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources", "0021_backfill_externaldataschema_s3_folder_name_gap"),+ ]++ operations = [+ # Irreversible: there is no meaningful way to re-apply the bug, and the rename restores the+ # conventional name the data was always queryable under.+ migrations.RunSQL(sql=REPAIR_SQL, reverse_sql=migrations.RunSQL.noop, elidable=True),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex a38e9e6bb5a8..868b49392f63 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0020_alter_externaldatasource_source_type_and_more+0022_repair_s3_folder_name_table_namesdiff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex 0e202af952ab..7d9da235bda2 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -88,6 +88,17 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldclass Meta:db_table = "posthog_externaldataschema"+ def save(self, *args: Any, **kwargs: Any) -> None:+ # Populate the S3 folder on first write so the column is always authoritative for new rows.+ # Legacy/qualified rows set it explicitly before renaming (see `_qualify_legacy_row`); this+ # only fills it when empty, so an existing folder is never overwritten by a later rename.+ if not self.s3_folder_name and self.name and self.name.strip():+ self.s3_folder_name = NamingConvention.normalize_identifier(self.resolved_s3_folder_name or self.name)+ update_fields = kwargs.get("update_fields")+ if update_fields is not None:+ kwargs["update_fields"] = {*update_fields, "s3_folder_name"}+ super().save(*args, **kwargs)+def folder_path(self) -> str:return f"team_{self.team_id}_{self.source.source_type}_{str(self.id)}".lower().replace("-", "_")diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.pyindex 73bfafea430b..6fc3bcbb0475 100644--- a/products/warehouse_sources/backend/tests/test_models.py+++ b/products/warehouse_sources/backend/tests/test_models.py@@ -1,4 +1,7 @@+import uuid+import pytest+from posthog.test.base import BaseTestfrom django.db.models import Model@@ -47,6 +50,47 @@ def test_resolved_s3_folder_name(assert schema.resolved_s3_folder_name == expected+class TestExternalDataSchemaSave(BaseTest):+ def _source(self) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ status="Completed",+ source_type="Postgres",+ )++ def _create(self, name: str, **kwargs) -> ExternalDataSchema:+ return ExternalDataSchema.objects.create(team_id=self.team.pk, source=self._source(), name=name, **kwargs)++ def test_save_populates_s3_folder_name_from_name(self) -> None:+ # The folder is the normalized name — never NULL for a new row.+ schema = self._create("My Table")+ assert schema.s3_folder_name == "my_table"+ schema.refresh_from_db()+ assert schema.s3_folder_name == "my_table"++ def test_save_uses_legacy_key_when_present(self) -> None:+ schema = self._create("public.users", sync_type_config={"dwh_storage_key": "users"})+ assert schema.s3_folder_name == "users"++ def test_save_does_not_overwrite_existing_folder(self) -> None:+ schema = self._create("My Table", s3_folder_name="pinned")+ assert schema.s3_folder_name == "pinned"++ def test_partial_update_backfills_null_folder(self) -> None:+ # A pre-existing NULL row heals on its next save, even a partial one.+ schema = self._create("orders")+ ExternalDataSchema.objects.filter(pk=schema.pk).update(s3_folder_name=None)+ schema.refresh_from_db()+ assert schema.s3_folder_name is None++ schema.status = "Completed"+ schema.save(update_fields=["status", "updated_at"])+ schema.refresh_from_db()+ assert schema.s3_folder_name == "orders"++@pytest.mark.parametrize("clickhouse_type,expected",[diff --git a/products/warehouse_sources/backend/tests/test_repair_s3_folder_name_table_names.py b/products/warehouse_sources/backend/tests/test_repair_s3_folder_name_table_names.pynew file mode 100644index 000000000000..9eb8a483105f--- /dev/null+++ b/products/warehouse_sources/backend/tests/test_repair_s3_folder_name_table_names.py@@ -0,0 +1,115 @@+import uuid+import importlib++from posthog.test.base import BaseTest++from django.db import connection++from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.models.table import DataWarehouseTable++# The migration module name starts with a digit, so import it dynamically to run its real SQL.+_migration = importlib.import_module(+ "products.warehouse_sources.backend.migrations.0022_repair_s3_folder_name_table_names"+)+REPAIR_SQL = _migration.REPAIR_SQL+++class TestRepairS3FolderNameTableNames(BaseTest):+ def _source(self, source_type: str, prefix: str = "") -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ status="Completed",+ source_type=source_type,+ prefix=prefix,+ )++ def _schema_with_table(+ self, source: ExternalDataSource, name: str, s3_folder_name: str | None, table_name: str+ ) -> tuple[ExternalDataSchema, DataWarehouseTable]:+ table = DataWarehouseTable.objects.create(+ team_id=self.team.pk,+ name=table_name,+ format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,+ url_pattern="https://bucket/x/*",+ external_data_source=source,+ )+ schema = ExternalDataSchema.objects.create(+ team_id=self.team.pk, source=source, name=name, s3_folder_name=s3_folder_name, table=table+ )+ return schema, table++ def _run(self) -> None:+ with connection.cursor() as cursor:+ cursor.execute(REPAIR_SQL)++ def test_renames_affected_camelcase_table(self) -> None:+ # Stripe CamelCase: table got the snake_cased folder name; should revert to the lower-cased raw name.+ _, table = self._schema_with_table(+ self._source("Stripe"),+ name="CustomerBalanceTransaction",+ s3_folder_name="customer_balance_transaction",+ table_name="stripe_customer_balance_transaction",+ )+ self._run()+ table.refresh_from_db()+ assert table.name == "stripe_customerbalancetransaction"++ def test_leaves_directquery_table_untouched(self) -> None:+ # DuckLake / direct-query tables are stored as the raw schema name (not via build_table_name),+ # so they must NOT match and must NOT be renamed.+ _, table = self._schema_with_table(+ self._source("Postgres", prefix="DuckConfig"),+ name="ducklake_column",+ s3_folder_name="ducklake_column",+ table_name="ducklake_column",+ )+ self._run()+ table.refresh_from_db()+ assert table.name == "ducklake_column"++ def test_leaves_multi_schema_pin_untouched(self) -> None:+ # Legacy multi-schema pin: dotted name, table pinned to the original folder — correct, skip.+ _, table = self._schema_with_table(+ self._source("Postgres"),+ name="public.users",+ s3_folder_name="users",+ table_name="postgres_users",+ )+ self._run()+ table.refresh_from_db()+ assert table.name == "postgres_users"++ def test_leaves_already_correct_table_untouched(self) -> None:+ _, table = self._schema_with_table(+ self._source("Stripe"),+ name="Charge",+ s3_folder_name="charge",+ table_name="stripe_charge",+ )+ self._run()+ table.refresh_from_db()+ assert table.name == "stripe_charge"++ def test_skips_when_target_name_collides_with_live_table(self) -> None:+ # If a live table already holds the correct name, leave the buggy one for manual resolution.+ source = self._source("Stripe")+ _, buggy = self._schema_with_table(+ source,+ name="CreditNote",+ s3_folder_name="credit_note",+ table_name="stripe_credit_note",+ )+ DataWarehouseTable.objects.create(+ team_id=self.team.pk,+ name="stripe_creditnote", # the target name, already taken by a live table+ format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,+ url_pattern="https://bucket/y/*",+ external_data_source=source,+ )+ self._run()+ buggy.refresh_from_db()+ assert buggy.name == "stripe_credit_note" # untouched