: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(data-warehouse): promote dwh_storage_key to s3_folder_path column (#63117)
Daniel RC039f5b7366a6
diff --git a/posthog/temporal/data_imports/pipelines/pipeline/typings.py b/posthog/temporal/data_imports/pipelines/pipeline/typings.pyindex 72711770818e..bb15c7781fa4 100644--- a/posthog/temporal/data_imports/pipelines/pipeline/typings.py+++ b/posthog/temporal/data_imports/pipelines/pipeline/typings.py@@ -74,7 +74,7 @@ class SourceInputs:enabled_columns: Optional[list[str]] = None# Multi-schema import context, read by `resolve_source_location`.schema_metadata: Optional[dict[str, Any]] = None- dwh_storage_key: Optional[str] = None+ s3_folder_name: Optional[str] = Noneclass PipelineResult(TypedDict):diff --git a/posthog/temporal/data_imports/pipelines/pipeline_sync.py b/posthog/temporal/data_imports/pipelines/pipeline_sync.pyindex 82bd76bc9589..ee5ff1d97022 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_sync.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_sync.py@@ -178,10 +178,9 @@ async def validate_schema_and_update_table(_schema_name: str = external_data_schema.nameincremental_or_append = external_data_schema.should_use_incremental_field- # `dwh_storage_key` pins the Delta path to the original unqualified name for legacy+ # `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_key = (external_data_schema.sync_type_config or {}).get("dwh_storage_key")- storage_schema_name = storage_key if isinstance(storage_key, str) and storage_key else _schema_name+ storage_schema_name = external_data_schema.resolved_s3_folder_name or _schema_nametable_name = build_table_name(job.pipeline, storage_schema_name)normalized_schema_name = NamingConvention.normalize_identifier(storage_schema_name)diff --git a/posthog/temporal/data_imports/sources/common/sql/location.py b/posthog/temporal/data_imports/sources/common/sql/location.pyindex 68431dc3c890..f2c65c29da91 100644--- a/posthog/temporal/data_imports/sources/common/sql/location.py+++ b/posthog/temporal/data_imports/sources/common/sql/location.py@@ -58,7 +58,7 @@ def resolve_source_location("""Resolve `(schema, table_name, response_name)` for one warehouse-import row.Namespace + table priority: per-schema `schema_metadata` → dotted `schema_name` self-heal →- `config_namespace` → `default`. `response_name` (the Delta subdir) uses `dwh_storage_key` when+ `config_namespace` → `default`. `response_name` (the Delta subdir) uses `s3_folder_name` whenpresent, so a migrated row keeps its legacy path — no S3 rewrite, no orphaned data."""metadata = inputs.schema_metadata if isinstance(inputs.schema_metadata, dict) else {}@@ -71,7 +71,7 @@ def resolve_source_location(schema = source_schema or normalize_namespace(config_namespace) or defaulttable_name = source_table_name or inputs.schema_name- storage_key = inputs.dwh_storage_key if isinstance(inputs.dwh_storage_key, str) and inputs.dwh_storage_key else None+ storage_key = inputs.s3_folder_name if isinstance(inputs.s3_folder_name, str) and inputs.s3_folder_name else Noneresponse_name = NamingConvention.normalize_identifier(storage_key or inputs.schema_name)return ResolvedSourceLocation(schema=schema, table_name=table_name, response_name=response_name)diff --git a/posthog/temporal/data_imports/sources/common/sql/tests/test_location.py b/posthog/temporal/data_imports/sources/common/sql/tests/test_location.pyindex 7de20879b1c4..91be68a18b81 100644--- a/posthog/temporal/data_imports/sources/common/sql/tests/test_location.py+++ b/posthog/temporal/data_imports/sources/common/sql/tests/test_location.py@@ -96,14 +96,14 @@ class TestResolveSourceLocation:def test_storage_key_preserves_legacy_delta_path(self) -> None:# Migrated row keeps the legacy Delta subdir (`users`, not `public_users`) or its data is orphaned.- inputs = _source_inputs(schema_name="public.users", dwh_storage_key="users")+ inputs = _source_inputs(schema_name="public.users", s3_folder_name="users")location = resolve_source_location(inputs, config_namespace=None)assert location.response_name == "users"assert location.schema == "public"assert location.table_name == "users"def test_storage_key_is_normalized(self) -> None:- inputs = _source_inputs(schema_name="public.My Table", dwh_storage_key="My Table")+ inputs = _source_inputs(schema_name="public.My Table", s3_folder_name="My Table")location = resolve_source_location(inputs, config_namespace=None)assert location.response_name == "my_table"diff --git a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql_multi_schema.py b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql_multi_schema.pyindex 15fc424387dd..498e86199dcc 100644--- a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql_multi_schema.py+++ b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql_multi_schema.py@@ -275,11 +275,11 @@ class TestBuildPipelineRouting:assert routing_mocks["metadata"] == ("analytics", "users")def test_preserves_legacy_storage_key(self, routing_mocks):- # A migrated single-schema row keeps its old Delta subdir via dwh_storage_key.+ # A migrated single-schema row keeps its old Delta subdir via s3_folder_name.inputs = _make_inputs(schema_name="analytics.users",schema_metadata={"source_schema": "analytics", "source_table_name": "users"},- dwh_storage_key="users",+ s3_folder_name="users",)response = MSSQLImplementation().build_pipeline(_make_config(schema=""), inputs)assert response.name == "users"diff --git a/posthog/temporal/data_imports/sources/postgres/source.py b/posthog/temporal/data_imports/sources/postgres/source.pyindex c316dc83b36a..d3bd5c18442f 100644--- a/posthog/temporal/data_imports/sources/postgres/source.py+++ b/posthog/temporal/data_imports/sources/postgres/source.py@@ -706,7 +706,6 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa)# `SourceResponse.name` must match `DataWarehouseTable.url_pattern` (both derived from the# storage key when present, otherwise the row name) so HogQL reads from where we wrote.- storage_key = (schema.sync_type_config or {}).get("dwh_storage_key")- storage_schema_name = storage_key if isinstance(storage_key, str) and storage_key else inputs.schema_name+ storage_schema_name = schema.resolved_s3_folder_name or inputs.schema_nameresponse.name = NamingConvention.normalize_identifier(storage_schema_name)return responsediff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.pyindex 5ba8c68999b4..6d6a4126bd73 100644--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py@@ -786,6 +786,7 @@ class TestPostgresSourceForPipelineSchemaResolution:schema_metadata: dict | None = None,source_model=None,sync_type_config: dict | None = None,+ s3_folder_name: str | None = None,):schema = mock.MagicMock()schema.name = name@@ -797,6 +798,10 @@ class TestPostgresSourceForPipelineSchemaResolution:schema.chunk_size_override = Noneschema.schema_metadata = schema_metadataschema.sync_type_config = sync_type_config or {}+ schema.s3_folder_name = s3_folder_name+ # MagicMock auto-attrs are truthy; pin the property to what the real model would resolve+ # (resolution itself is covered by warehouse_sources test_models).+ schema.resolved_s3_folder_name = s3_folder_nameschema.source = source_model or mock.MagicMock()return schema@@ -853,9 +858,9 @@ class TestPostgresSourceForPipelineSchemaResolution:assert kwargs["schema"] == "real_schema"assert kwargs["table_names"] == ["real_table"]- def test_dwh_storage_key_drives_response_name_so_delta_writes_to_legacy_path(self, source):+ def test_s3_folder_name_drives_response_name_so_delta_writes_to_legacy_path(self, source):# After `consolidate_postgres_legacy_rows` renames `example_table` → `public.example_table`,- # the row carries `dwh_storage_key="example_table"`. `validate_schema_and_update_table` uses+ # the row carries `s3_folder_name="example_table"`. `validate_schema_and_update_table` uses# that key for `url_pattern`, so `SourceResponse.name` MUST also derive from the storage key# — otherwise Delta files land at `.../public__example_table/` while `DataWarehouseTable.url_pattern`# points at `.../example_table/` and HogQL reads from an empty location.@@ -864,7 +869,7 @@ class TestPostgresSourceForPipelineSchemaResolution:schema_model = self._make_schema_model("public.example_table",schema_metadata={"source_schema": "public", "source_table_name": "example_table"},- sync_type_config={"dwh_storage_key": "example_table"},+ s3_folder_name="example_table",)inputs = self._make_inputs("public.example_table")config = self._make_config(schema=None)@@ -884,12 +889,12 @@ class TestPostgresSourceForPipelineSchemaResolution:source.source_for_pipeline(config, inputs)assert response.name == NamingConvention.normalize_identifier("example_table"), (- f"response.name must derive from dwh_storage_key to keep Delta writes anchored to the "+ f"response.name must derive from s3_folder_name to keep Delta writes anchored to the "f"legacy folder; got {response.name!r}")def test_response_name_uses_schema_name_when_no_storage_key(self, source):- # New (non-migrated) rows have no dwh_storage_key — response.name falls back to the row's+ # New (non-migrated) rows have no s3_folder_name — response.name falls back to the row's# current name so the Delta path matches `url_pattern` (also derived from the row's name).from posthog.temporal.data_imports.naming_convention import NamingConventiondiff --git a/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py b/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.pyindex 2a5c8e490929..f62b96a20742 100644--- a/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py+++ b/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py@@ -821,7 +821,7 @@ class TestBuildPipeline:assert get_meta.call_args.args[2] == "messages"assert response.name == "messages"- def test_dwh_storage_key_preserves_legacy_delta_path(self, build_pipeline_mocks, mocker):+ def test_s3_folder_name_preserves_legacy_delta_path(self, build_pipeline_mocks, mocker):mocker.patch.object(RedshiftImplementation,"get_table_metadata",@@ -836,7 +836,7 @@ class TestBuildPipeline:inputs = _make_inputs(schema_name="analytics.users",schema_metadata={"source_schema": "analytics", "source_table_name": "users"},- dwh_storage_key="users",+ s3_folder_name="users",)response = impl.build_pipeline(_make_config(schema=""), inputs)diff --git a/posthog/temporal/data_imports/workflow_activities/import_data_sync.py b/posthog/temporal/data_imports/workflow_activities/import_data_sync.pyindex a1252fa57619..00cd0b41413e 100644--- a/posthog/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/posthog/temporal/data_imports/workflow_activities/import_data_sync.py@@ -162,7 +162,7 @@ async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> Pipelinreset_pipeline=reset_pipeline,enabled_columns=schema.enabled_columns,schema_metadata=schema.schema_metadata,- dwh_storage_key=schema.dwh_storage_key,+ s3_folder_name=schema.resolved_s3_folder_name,)new_source = SourceRegistry.get_source(source_type)diff --git a/products/data_warehouse/backend/api/test/test_postgres_warehouse_migration.py b/products/data_warehouse/backend/api/test/test_postgres_warehouse_migration.pyindex 291eace25eed..42011b817907 100644--- a/products/data_warehouse/backend/api/test/test_postgres_warehouse_migration.py+++ b/products/data_warehouse/backend/api/test/test_postgres_warehouse_migration.py@@ -26,7 +26,7 @@ class TestPostgresWarehouseMigration(APIBaseTest):# A pre-PR warehouse Postgres source had `schema=public` on the source config and# `ExternalDataSchema.name="auth_group"` (no schema prefix). After this PR, discovery# returns the qualified `public.auth_group`. `consolidate_postgres_legacy_rows` qualifies- # the legacy row in place and stores `dwh_storage_key="auth_group"` so the next sync+ # the legacy row in place and stores `s3_folder_name="auth_group"` so the next sync# writes to the original Delta path — no orphaned data, but the row picks up the new# qualified naming so tables from other schemas can coexist without a name collision.mock_get_source.return_value.parse_config.return_value = None@@ -77,8 +77,8 @@ class TestPostgresWarehouseMigration(APIBaseTest):legacy_table.refresh_from_db()# Row gets the qualified name so multi-schema discovery doesn't collide later.assert legacy_schema.name == "public.auth_group"- # dwh_storage_key locks the Delta path to the legacy folder so existing data is preserved.- assert legacy_schema.sync_type_config.get("dwh_storage_key") == "auth_group"+ # s3_folder_name locks the Delta path to the legacy folder so existing data is preserved.+ assert legacy_schema.s3_folder_name == "auth_group"# schema_metadata pinned so source_for_pipeline knows the canonical (schema, table) tuple.metadata = legacy_schema.sync_type_config.get("schema_metadata") or {}assert metadata.get("source_schema") == "public"@@ -146,7 +146,7 @@ class TestPostgresWarehouseMigration(APIBaseTest):metadata = schema.sync_type_config.get("schema_metadata") or {}assert metadata.get("source_schema") == "public"assert metadata.get("source_table_name") == "auth_group"- assert schema.sync_type_config.get("dwh_storage_key") == "auth_group"+ assert schema.s3_folder_name == "auth_group"@patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")def test_refresh_schemas_refreshes_legacy_warehouse_metadata_when_columns_change(self, mock_get_source):@@ -270,13 +270,13 @@ class TestPostgresWarehouseMigration(APIBaseTest):# `rename_postgres_schemas_to_match_source_schemas` matches the legacy unqualified# row by location to the discovered `public.example_table` (legacy falls back to "public"# when no default schema is set), then `consolidate_postgres_legacy_rows` qualifies the- # legacy row in place using the pinned `source_schema`. `dwh_storage_key="example_table"`+ # legacy row in place using the pinned `source_schema`. `s3_folder_name="example_table"`# keeps the Delta path anchored to the legacy folder so no data is orphaned.legacy = ExternalDataSchema.objects.get(team_id=self.team.pk, source_id=source.pk, name="public.example_table")legacy_metadata = legacy.sync_type_config.get("schema_metadata") or {}assert legacy_metadata.get("source_schema") == "public"assert legacy_metadata.get("source_table_name") == "example_table"- assert legacy.sync_type_config.get("dwh_storage_key") == "example_table"+ assert legacy.s3_folder_name == "example_table"# The unqualified row is gone — it was renamed in place.assert not ExternalDataSchema.objects.filter(team_id=self.team.pk, source_id=source.pk, name="example_table", deleted=False@@ -365,9 +365,9 @@ class TestPostgresWarehouseMigration(APIBaseTest):f"legacy row pinned to wrong schema: {metadata.get('source_schema')!r}")assert metadata.get("source_table_name") == "example_table"- # dwh_storage_key pins the Delta path to the legacy "example_table" key so existing data+ # s3_folder_name pins the Delta path to the legacy "example_table" folder so existing data# stays in place — no rewrite, no orphan.- assert legacy.sync_type_config.get("dwh_storage_key") == "example_table"+ assert legacy.s3_folder_name == "example_table"# The original unqualified row is gone (it was renamed in place).assert not ExternalDataSchema.objects.filter(team_id=self.team.pk, source_id=source.pk, name="example_table", deleted=False@@ -457,7 +457,7 @@ class TestPostgresWarehouseMigration(APIBaseTest):live.refresh_from_db()assert live.name == "poblic.example_table"assert live.table_id == live_table.id- assert (live.sync_type_config or {}).get("dwh_storage_key") == "example_table"+ assert live.s3_folder_name == "example_table"# The orphan duplicate is soft-deleted.orphan.refresh_from_db()assert orphan.deleted is Truediff --git a/products/data_warehouse/backend/postgres_warehouse_migration.py b/products/data_warehouse/backend/postgres_warehouse_migration.pyindex 51307712df82..d0aeda6f0dfd 100644--- a/products/data_warehouse/backend/postgres_warehouse_migration.py+++ b/products/data_warehouse/backend/postgres_warehouse_migration.py@@ -29,7 +29,7 @@ def reconcile_refresh_name_substitutions(source_schemas=source_schemas,team_id=team_id,# Warehouse-mode rename would change the Delta path on the next sync; defer to consolidate- # below which preserves the path via `dwh_storage_key`.+ # below which preserves the path via `s3_folder_name`.allow_rename=source.is_direct_query,)diff --git a/products/data_warehouse/backend/sql_warehouse_migration.py b/products/data_warehouse/backend/sql_warehouse_migration.pyindex e91e8962a9d2..becbdd06b02d 100644--- a/products/data_warehouse/backend/sql_warehouse_migration.py+++ b/products/data_warehouse/backend/sql_warehouse_migration.py@@ -1,6 +1,6 @@"""Migrate pre-multi-schema SQL warehouse rows to qualified naming without re-syncing.-Legacy rows are renamed in place (`users` → `public.users`) and tagged `dwh_storage_key=<original>`+Legacy rows are renamed in place (`users` → `public.users`) and tagged `s3_folder_name=<original>`so sync keeps reading/writing the legacy Delta path. Source-agnostic — gated only by the namespacefield being blank-able; Postgres direct-query plumbing stays in `postgres_warehouse_migration.py`."""@@ -9,6 +9,7 @@ from __future__ import annotationsfrom typing import Any+from posthog.temporal.data_imports.naming_convention import NamingConventionfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistryfrom posthog.temporal.data_imports.sources.common.sql.base import SQLSourcefrom posthog.temporal.data_imports.sources.common.sql.location import fill_missing_from_dotted_name, normalize_namespace@@ -56,7 +57,7 @@ def _qualify_legacy_row(target_source_table_name: str | None = None,duplicate_to_drop: Any | None = None,) -> str | None:- """Rename `row` to qualified form, stash `dwh_storage_key`, optionally drop a duplicate.+ """Rename `row` to qualified form, stash `s3_folder_name`, optionally drop a duplicate.Returns the new name, or None if a duplicate with its own data blocked the rename."""sync_type_config = row.sync_type_config or {}@@ -81,12 +82,18 @@ def _qualify_legacy_row(merged_metadata.setdefault("foreign_keys", [])new_sync_type_config: dict[str, Any] = {**sync_type_config, "schema_metadata": merged_metadata}- if "dwh_storage_key" not in sync_type_config:- new_sync_type_config["dwh_storage_key"] = row.name++ update_fields = ["name", "sync_type_config", "updated_at"]+ if not row.s3_folder_name:+ # The S3 folder is the normalized identifier — store that, so the column holds the real+ # folder name (matching what the backfill writes and what readers compute). `resolved_*`+ # picks up any legacy `dwh_storage_key` so a previously-migrated row keeps its path.+ row.s3_folder_name = NamingConvention.normalize_identifier(row.resolved_s3_folder_name or row.name)+ update_fields.append("s3_folder_name")row.name = qualified_namerow.sync_type_config = new_sync_type_config- row.save(update_fields=["name", "sync_type_config", "updated_at"])+ row.save(update_fields=update_fields)return qualified_namediff --git a/products/data_warehouse/backend/test/test_sql_warehouse_migration.py b/products/data_warehouse/backend/test/test_sql_warehouse_migration.pyindex ee0575be5079..5fcfe3e68879 100644--- a/products/data_warehouse/backend/test/test_sql_warehouse_migration.py+++ b/products/data_warehouse/backend/test/test_sql_warehouse_migration.py@@ -141,8 +141,8 @@ class TestQualifyNonPostgresRows(BaseTest):row.refresh_from_db()assert row.name == "dbo.users"- # dwh_storage_key locks the Delta path to the legacy folder so existing data is preserved.- assert row.sync_type_config.get("dwh_storage_key") == "users"+ # s3_folder_name locks the Delta path to the legacy folder so existing data is preserved.+ assert row.s3_folder_name == "users"metadata = row.sync_type_config.get("schema_metadata") or {}assert metadata.get("source_schema") == "dbo"assert metadata.get("source_table_name") == "users"@@ -163,7 +163,7 @@ class TestQualifyNonPostgresRows(BaseTest):row.refresh_from_db()assert row.name == "sales.orders"assert substitutions == {"orders": "sales.orders"}- assert row.sync_type_config.get("dwh_storage_key") == "orders"+ assert row.s3_folder_name == "orders"def test_apply_on_refresh_is_noop_for_already_qualified_rows(self) -> None:source = self._source(schema="")diff --git a/products/warehouse_sources/backend/migrations/0013_externaldataschema_s3_folder_name.py b/products/warehouse_sources/backend/migrations/0013_externaldataschema_s3_folder_name.pynew file mode 100644index 000000000000..85dfcc4f6f7a--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0013_externaldataschema_s3_folder_name.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources", "0012_alter_externaldatasource_source_type_and_more"),+ ]++ operations = [+ migrations.AddField(+ model_name="externaldataschema",+ name="s3_folder_name",+ field=models.CharField(blank=True, max_length=400, null=True),+ ),+ ]diff --git a/products/warehouse_sources/backend/migrations/0014_backfill_externaldataschema_s3_folder_name.py b/products/warehouse_sources/backend/migrations/0014_backfill_externaldataschema_s3_folder_name.pynew file mode 100644index 000000000000..ee7490d9676e--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0014_backfill_externaldataschema_s3_folder_name.py@@ -0,0 +1,40 @@+import time++from django.db import migrations++from posthog.temporal.data_imports.naming_convention import NamingConvention++BATCH_SIZE = 2000+++def forwards(apps, schema_editor):+ ExternalDataSchema = apps.get_model("warehouse_sources", "ExternalDataSchema")++ # Updated rows fall out of the NULL filter, so refetching advances the backfill batch by batch.+ 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")+ # Legacy storage key when present, else the schema name. The S3 folder is the *normalized*+ # identifier (readers normalize before building the path), so store the normalized form —+ # not the raw name, which would point at a folder that doesn't exist for e.g. "My Table".+ 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", "0013_externaldataschema_s3_folder_name"),+ ]++ operations = [+ migrations.RunPython(forwards, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex c99bf40e22dc..c6f7dc40522f 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0012_alter_externaldatasource_source_type_and_more+0014_backfill_externaldataschema_s3_folder_namediff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex 0aac676fa43b..8d93edfeafaa 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -64,6 +64,11 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFielddefault=dict,blank=True,)+ # Normalized leaf subdir under the source's S3 folder that Delta data is written to (the actual+ # folder name, e.g. `my_table`, not `My Table`). Pins legacy rows (renamed to qualified form+ # during multi-schema migration) to their original path. Empty for rows written before this+ # column existed — readers fall back to the legacy JSON key, then the normalized schema `name`.+ s3_folder_name = models.CharField(max_length=400, null=True, blank=True)# Deprecated in favour of `sync_frequency_interval`sync_frequency = deprecate_field(models.CharField(max_length=128, choices=SyncFrequency, default=SyncFrequency.DAILY, blank=True)@@ -237,9 +242,13 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldreturn None@property- def dwh_storage_key(self) -> str | None:- if self.sync_type_config:- return self.sync_type_config.get("dwh_storage_key")+ def resolved_s3_folder_name(self) -> str | None:+ # JSON fallback covers rows written by old workers before the column rollout.+ if self.s3_folder_name:+ return self.s3_folder_name+ legacy_key = (self.sync_type_config or {}).get("dwh_storage_key")+ if isinstance(legacy_key, str) and legacy_key:+ return legacy_keyreturn None@propertydiff --git a/products/warehouse_sources/backend/tests/test_migration_0014.py b/products/warehouse_sources/backend/tests/test_migration_0014.pynew file mode 100644index 000000000000..2180c16f9f38--- /dev/null+++ b/products/warehouse_sources/backend/tests/test_migration_0014.py@@ -0,0 +1,94 @@+from typing import Any++from posthog.test.base import TestMigrations++from parameterized import parameterized++from posthog.temporal.data_imports.naming_convention import NamingConvention+++class BackfillS3FolderNameMigrationTest(TestMigrations):+ """The backfill must reproduce the exact folder the sync readers compute today, or existing+ Delta data is orphaned. Readers resolve `normalize_identifier(dwh_storage_key or name)`, so:+ - no legacy key (the vast majority of rows) -> the normalized schema name+ - a legacy key (rows migrated to multi-schema) -> the normalized key+ Every case below asserts the stored value equals that folder.+ """++ migrate_from = "0013_externaldataschema_s3_folder_name"+ migrate_to = "0014_backfill_externaldataschema_s3_folder_name"++ @property+ def app(self) -> str:+ return "warehouse_sources"++ def setUpBeforeMigration(self, apps: Any) -> None:+ Organization = apps.get_model("posthog", "Organization")+ Project = apps.get_model("posthog", "Project")+ Team = apps.get_model("posthog", "Team")+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")+ ExternalDataSchema = apps.get_model("warehouse_sources", "ExternalDataSchema")+ self.ExternalDataSchema = ExternalDataSchema++ org = Organization.objects.create(name="Org")+ project = Project.objects.create(id=999_999, organization=org, name="Proj")+ team = Team.objects.create(organization=org, project=project, name="Team")+ source = ExternalDataSource.objects.create(+ team=team, source_id="src", connection_id="conn", status="Completed", source_type="Postgres"+ )++ def make(name: str, **kwargs: Any) -> str:+ return ExternalDataSchema.objects.create(team=team, source=source, name=name, **kwargs).id++ # No legacy key → folder is the normalized name. This is the common path (almost all sources).+ self.no_key = {+ "already_normalized": make("users", sync_type_config={}),+ "needs_casefold": make("MyTable", sync_type_config={}),+ "needs_space_strip": make("My Table", sync_type_config={}),+ "qualified_dotted": make("analytics.Events", sync_type_config={}),+ "null_key": make("orders", sync_type_config={"dwh_storage_key": None}),+ "empty_key": make("invoices", sync_type_config={"dwh_storage_key": ""}),+ }+ # Legacy key present (multi-schema migrated rows) → folder is the normalized key, pinning the+ # original pre-qualification path even though `name` is now qualified.+ self.with_key = {+ "key_normalized": make("public.users", sync_type_config={"dwh_storage_key": "users"}),+ "key_needs_norm": make("public.My Table", sync_type_config={"dwh_storage_key": "My Table"}),+ }+ # Already populated before the backfill — the NULL filter must skip it.+ self.preset = make("anything", sync_type_config={}, s3_folder_name="preset_value")++ @parameterized.expand(+ [+ ("already_normalized", "users", "users"),+ ("needs_casefold", "MyTable", "my_table"),+ ("needs_space_strip", "My Table", "my_table"),+ ("qualified_dotted", "analytics.Events", "analytics_events"),+ ("null_key", "orders", "orders"),+ ("empty_key", "invoices", "invoices"),+ ]+ )+ def test_no_key_uses_normalized_name(self, key: str, name: str, expected: str) -> None:+ schema = self.ExternalDataSchema.objects.get(id=self.no_key[key])+ # Equals both the hand-computed folder and the readers' own normalization of the name.+ assert schema.s3_folder_name == expected+ assert schema.s3_folder_name == NamingConvention.normalize_identifier(name)++ @parameterized.expand(+ [+ ("key_normalized", "users", "users"),+ ("key_needs_norm", "My Table", "my_table"),+ ]+ )+ def test_legacy_key_uses_normalized_key(self, key: str, legacy_key: str, expected: str) -> None:+ schema = self.ExternalDataSchema.objects.get(id=self.with_key[key])+ assert schema.s3_folder_name == expected+ assert schema.s3_folder_name == NamingConvention.normalize_identifier(legacy_key)++ def test_existing_value_is_not_overwritten(self) -> None:+ schema = self.ExternalDataSchema.objects.get(id=self.preset)+ assert schema.s3_folder_name == "preset_value"++ def test_every_row_is_populated(self) -> None:+ # The migration edits every row; none may be left NULL or a sync would orphan its data.+ assert not self.ExternalDataSchema.objects.filter(s3_folder_name__isnull=True).exists()diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.pyindex bf4915942bc4..73bfafea430b 100644--- a/products/warehouse_sources/backend/tests/test_models.py+++ b/products/warehouse_sources/backend/tests/test_models.py@@ -26,6 +26,27 @@ def test_db_table_preserved_across_split(model: type[Model], expected_db_table:assert model._meta.db_table == expected_db_table+ "s3_folder_name,sync_type_config,expected",+ [+ ("legacy_users", {"dwh_storage_key": "ignored"}, "legacy_users"),+ (None, {"dwh_storage_key": "legacy_users"}, "legacy_users"),+ ("", {"dwh_storage_key": "legacy_users"}, "legacy_users"),+ (None, {"dwh_storage_key": ""}, None),+ (None, {"dwh_storage_key": 123}, None),+ (None, {}, None),+ (None, None, None),+ ],+)+def test_resolved_s3_folder_name(+ s3_folder_name: str | None, sync_type_config: dict | None, expected: str | None+) -> None:+ """Column wins; rows written by pre-column workers fall back to the JSON key; junk yields None+ so callers fall back to the schema name."""+ schema = ExternalDataSchema(s3_folder_name=s3_folder_name, sync_type_config=sync_type_config)+ assert schema.resolved_s3_folder_name == expected++@pytest.mark.parametrize("clickhouse_type,expected",[