: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): keep source column order in synced tables (#112362)
Daniel RCd158507f8ecb
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.pyindex 84dd16ac8d74..7d07c877fe0b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py@@ -1450,8 +1450,9 @@ def _process_batch(# Support both given schemas and inferred schemasif schema is None or len(schema.names) == 0:try:- # Gather all unique keys from all items, not just the first- all_keys = set().union(*(d.keys() for d in table_data))+ # Gather all unique keys from all items, not just the first. Use a dict, not a set, so+ # that the columns keep the order the source gave them.+ all_keys = dict.fromkeys(key for d in table_data for key in d)first_item = table_data[0]first_item = {key: first_item.get(key, None) for key in all_keys}table_data[0] = first_item@@ -1463,7 +1464,7 @@ def _process_batch(drop_column_names: set[str] = set()- column_names = set(table_data[0].keys())+ column_names = list(table_data[0].keys())columnar_table_data: dict[str, pa.Array | np.ndarray[Any, np.dtype[Any]]] = {}for col in column_names:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.pyindex 2bffcf766b9e..8bec8de4fefb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py@@ -104,6 +104,17 @@ def test_table_from_py_list_inconsistent_other_types():)+def test_table_from_py_list_keeps_the_key_order_of_the_rows():+ table = table_from_py_list(+ [+ {"zeta": 1, "alpha": "a", "mid": None, "beta": 2.5, "omega": "o", "gamma": True, "delta": 3},+ {"zeta": 2, "alpha": "b", "mid": "m", "beta": 3.5, "omega": "p", "gamma": False, "delta": 4, "late": "x"},+ ]+ )++ assert table.column_names == ["zeta", "alpha", "mid", "beta", "omega", "gamma", "delta", "late"]++def test_table_from_py_list_numeric_column_with_non_numeric_value_raises_named_error():with pytest.raises(TypeError) as exc_info:table_from_py_list([{"revenue": 1.5}, {"revenue": "N/A"}, {"revenue": ""}])diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.pyindex 7af00cea767f..9d92e7a127d8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py@@ -469,10 +469,10 @@ async def validate_schema_and_update_table(effective_primary_keys,external_data_schema.incremental_field,)- table_for_update.columns = columns- table_for_update.save(update_fields=["columns"])+ table_for_update.set_columns(columns)+ table_for_update.save(update_fields=["columns", "column_order"])# Keep local reference in sync- table_created.columns = columns+ table_created.set_columns(columns)# schema could have been deleted by this pointschema_model = (@@ -611,8 +611,8 @@ async def register_cdc_companion_table(def _persist_columns() -> None:with transaction.atomic():- companion_table.columns = columns- companion_table.save(update_fields=["columns"])+ companion_table.set_columns(columns)+ companion_table.save(update_fields=["columns", "column_order"])if set_as_schema_table:ExternalDataSchema.objects.filter(id=schema_id, team_id=team_id).update(table=companion_table)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.pyindex 6184385b5be3..9c2afcbfc543 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py@@ -645,6 +645,25 @@ class TestValidateSchemaAndUpdateTable:schema.refresh_from_db()assert schema.sync_type_config[REGISTERED_SCHEMA_FINGERPRINT_KEY]+ def test_records_the_introspected_column_order(self, team):+ schema, job = self._schema_and_job(team)+ table = self._linked_table(team, schema, job, queryable_folder="orders__query_a")+ introspected = {+ "customer_name": {"clickhouse": "String", "hogql": "x"},+ "id": {"clickhouse": "Int64", "hogql": "x"},+ "total": {"clickhouse": "Float64", "hogql": "x"},+ }++ with (+ patch.object(DataWarehouseTable, "get_columns", return_value=introspected),+ patch.object(DataWarehouseTable, "get_count", return_value=150),+ ):+ self._register(team, schema, job, queryable_folder="orders__query_a", delta_schema_json="{}")++ table.refresh_from_db()+ assert table.column_order == ["customer_name", "id", "total"]+ assert [name for name, _ in table.hogql_definition().fields.items()][:3] == ["customer_name", "id", "total"]+def test_a_failed_introspection_leaves_no_fingerprint_behind(self, team):# get_columns() can fail on a table with no committed files (tolerated, see above). The next# sync must introspect again rather than trust a fingerprint for columns that were never written.