: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(warehouse-sources): stop S3 JSON inference dropping keys (#94289)
posthog[bot]c86529d9ac79
diff --git a/products/data_warehouse/backend/models/test/test_table.py b/products/data_warehouse/backend/models/test/test_table.pyindex 897811226707..0fbb447716e7 100644--- a/products/data_warehouse/backend/models/test/test_table.py+++ b/products/data_warehouse/backend/models/test/test_table.py@@ -987,12 +987,32 @@ class TestTable(BaseTest):result = remove_named_tuples("Array(Tuple(`1` String, `2` String, `3` Nullable(String)))")assert result == "Array(Tuple( String, String, Nullable(String)))"- def test_hogql_definition_tuple_with_backtick_positional_names(self):+ @parameterized.expand(+ [+ # A parquet reader given element names matches the nested fields by name, so a renamed+ # nested field comes back as an empty array. Positional matching still returns the data.+ (+ "parquet_stays_positional",+ DataWarehouseTable.TableFormat.Parquet,+ "`id` String, `deal_details` Array(Tuple( String, String, Nullable(String)))",+ ),+ # JSONEachRow has no positional reading of a nested object: without the names ClickHouse+ # expects an array and every read of the table raises code 27.+ (+ "json_keeps_names",+ DataWarehouseTable.TableFormat.JSON,+ "`id` String, `deal_details` Array(Tuple(`1` String, `2` String, `3` Nullable(String)))",+ ),+ ]+ )+ def test_hogql_definition_tuple_element_names_follow_the_format(+ self, _name: str, table_format: str, expected_structure: str+ ):credential = DataWarehouseCredential.objects.create(access_key="test", access_secret="test", team=self.team)table = DataWarehouseTable.objects.create(name="test_table",url_pattern="https://example.com",- format=DataWarehouseTable.TableFormat.Parquet,+ format=table_format,team=self.team,columns={"id": "String",@@ -1006,7 +1026,7 @@ class TestTable(BaseTest):)definition = table.hogql_definition()assert isinstance(definition, HogQLDataWarehouseTable)- assert definition.structure == "`id` String, `deal_details` Array(Tuple( String, String, Nullable(String)))"+ assert definition.structure == expected_structuredef assert_raises_with_invalid_hog_column_type(self, column_type):credential = DataWarehouseCredential.objects.create(access_key="test", access_secret="test", team=self.team)diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex 229ca047348b..d925e2a76317 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -140,6 +140,50 @@ CHDB_QUERY_TIMEOUT_SECONDS = 30.0# raw ClickHouse queries below bypass that path and must opt out the same way.DISABLE_HIVE_PARTITIONING_SETTINGS: dict[str, int] = {"use_hive_partitioning": 0}+# Formats whose structure carries the element names of a nested Tuple. JSONEachRow matches a nested+# object's keys to those names, so a nameless Tuple inside an Array makes ClickHouse expect a+# positional array instead, and every read of the table raises code 27 even when the query never+# mentions that column.+#+# Parquet-backed formats keep the nameless Tuple on purpose, which is what the names were stripped+# for in the first place (ClickHouse/ClickHouse#37594, still open). Their reader looks the nested+# fields up by name once the structure names them, so a nested field that the files renamed, or a+# glob over files whose nested schemas disagree, returns an empty array for every row that carries+# the other name. A nameless Tuple matches by position and still returns that data. Every synced+# source writes Delta, and its files keep the field names they had when they were written, so that+# drift is normal there and unreachable for JSON.+STRUCTURE_KEEPS_TUPLE_ELEMENT_NAMES: frozenset[str] = frozenset({DataWarehouseTableFormat.JSON})++# ClickHouse infers a schema from a bounded sample of the files, by default as little as the first+# one. Each nested JSON object becomes a named Tuple of exactly the keys that sample held, and+# `hogql_definition` pins that Tuple as the `structure` of every read, so a key the sample missed is+# unreadable at query time and not merely absent from the catalog. The `union` mode reads the head of+# every file and merges the result, which recovers the keys that only later files carry. ClickHouse+# rejects the mode for a format that cannot read a subset of its columns, which rules out headerless+# CSV but not CSVWithNames.+UNION_SCHEMA_INFERENCE_FORMATS: frozenset[str] = frozenset(+ {DataWarehouseTableFormat.JSON, DataWarehouseTableFormat.CSVWithNames}+)++# `union` adds a read per file, and introspection runs inside the POST that creates or refreshes a+# table, so an unbounded read outlives the gateway and returns a 504 that records nothing anywhere.+DESCRIBE_MAX_EXECUTION_TIME_SECONDS = 30+DESCRIBE_RETRY_BUDGET_SECONDS = 90+++def chdb_set_statements(describe_settings: dict[str, str | int]) -> str:+ """Render settings as SET statements to prefix a chdb query with.++ chdb does not honour the CSV double-quote setting in any other form. The upstream fix+ (https://github.com/chdb-io/chdb/pull/374) is merged but is not in the pinned 3.3.0, so these+ SET statements stay until chdb is upgraded past that release.+ """+ return "".join(+ f"SET {name} = {escape_param_clickhouse(value) if isinstance(value, str) else int(value)}; "+ for name, value in describe_settings.items()+ )++_CHDB_SUBPROCESS_SCRIPT = """import sys@@ -245,6 +289,7 @@ def hogql_fields_and_structure_for_columns(columns: dict[str, Any],modifiers: Optional["HogQLQueryModifiers"] = None,column_order: list[str] | None = None,+ keep_tuple_element_names: bool = False,) -> tuple[dict[str, FieldOrTable], list[str]]:"""Shared columns → HogQL fields mapping for warehouse and direct virtual tables.@@ -252,6 +297,10 @@ def hogql_fields_and_structure_for_columns(tables; direct virtual tables ignore them. ``column_order`` restores the SELECT order thejsonb column store drops (see ``reconstruct_ordered_columns``); omit it for column dictswhose insertion order is already meaningful.++ ``keep_tuple_element_names`` decides how a nested ``Tuple`` reaches the structure, and only+ ``STRUCTURE_KEEPS_TUPLE_ELEMENT_NAMES`` formats may set it. See that constant for why the two+ answers differ by format."""fields: dict[str, FieldOrTable] = {}structure = []@@ -268,8 +317,7 @@ def hogql_fields_and_structure_for_columns(clickhouse_type = clickhouse_type.replace("Nullable(", "")[:-1]is_nullable = True- # TODO: remove when addressed https://github.com/ClickHouse/ClickHouse/issues/37594- if clickhouse_type.startswith("Array("):+ if not keep_tuple_element_names and clickhouse_type.startswith("Array("):clickhouse_type = remove_named_tuples(clickhouse_type)if isinstance(type, dict):@@ -517,11 +565,21 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletself.columns = columnsself.column_order = list(columns.keys())+ def _describe_settings(self) -> dict[str, str | int]:+ settings: dict[str, str | int] = {**DISABLE_HIVE_PARTITIONING_SETTINGS}+ if self._is_csv_format() and self.csv_allow_double_quotes is not None:+ settings["format_csv_allow_double_quotes"] = 1 if self.csv_allow_double_quotes else 0+ if self.format in UNION_SCHEMA_INFERENCE_FORMATS:+ settings["schema_inference_mode"] = "union"+ settings["max_execution_time"] = DESCRIBE_MAX_EXECUTION_TIME_SECONDS+ return settings+def get_columns(self,safe_expose_ch_error: bool = True,) -> DataWarehouseTableIntrospectedColumns:result: list[tuple[str, ...]] | None = None+ describe_settings = self._describe_settings()placeholder_context = HogQLContext(team_id=self.team.pk)s3_table_func = build_function_call(url=self.url_pattern,@@ -542,15 +600,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletquoted_placeholders = {k: escape_param_clickhouse(v) for k, v in placeholder_context.values.items()}# chdb doesn't support parameterized queries- chdb_query = f"SET use_hive_partitioning = 0; DESCRIBE TABLE {s3_table_func}" % quoted_placeholders-- # Workaround for chdb not honouring the CSV double-quote setting. The upstream fix- # (https://github.com/chdb-io/chdb/pull/374) is merged but is not in the pinned 3.3.0,- # so this SET stays until chdb is upgraded past that release.- if self._is_csv_format() and self.csv_allow_double_quotes is not None:- chdb_query = (- f"SET format_csv_allow_double_quotes = {1 if self.csv_allow_double_quotes else 0}; {chdb_query}"- )+ chdb_query = f"{chdb_set_statements(describe_settings)}DESCRIBE TABLE {s3_table_func}" % quoted_placeholderschdb_result = run_chdb_query(chdb_query)reader = csv.reader(StringIO(chdb_result))result = [tuple(row) for row in reader]@@ -572,21 +622,21 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet# The cluster is a little broken right now, and so this can intermittently fail.# See https://posthog.slack.com/archives/C076R4753Q8/p1756901693184169 for contextattempts = 5+ # Only a bounded DESCRIBE gets a retry deadline, so the widened pass stays inside the+ # budget of the request that runs it and every other format keeps its retry behavior.+ retry_deadline = (+ time.monotonic() + DESCRIBE_RETRY_BUDGET_SECONDS if "max_execution_time" in describe_settings else None+ )for i in range(attempts):try:- get_columns_settings: dict[str, int] = dict(DISABLE_HIVE_PARTITIONING_SETTINGS)- if self._is_csv_format() and self.csv_allow_double_quotes is not None:- get_columns_settings["format_csv_allow_double_quotes"] = (- 1 if self.csv_allow_double_quotes else 0- )result = sync_execute(f"""DESCRIBE TABLE {s3_table_func}""",args=placeholder_context.values,- settings=get_columns_settings,+ settings=describe_settings,)breakexcept Exception as err:- if i >= attempts - 1:+ if i >= attempts - 1 or (retry_deadline is not None and time.monotonic() >= retry_deadline):capture_exception(err)if safe_expose_ch_error:self._safe_expose_ch_error(err)@@ -775,7 +825,12 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletcolumns = self.columns or {}- fields, structure = hogql_fields_and_structure_for_columns(columns, modifiers, column_order=self.column_order)+ fields, structure = hogql_fields_and_structure_for_columns(+ columns,+ modifiers,+ column_order=self.column_order,+ keep_tuple_element_names=self.format in STRUCTURE_KEEPS_TUPLE_ELEMENT_NAMES,+ )if self.external_data_source and self.external_data_source.is_direct_postgres:postgres_catalog = (diff --git a/products/warehouse_sources/backend/tests/test_table.py b/products/warehouse_sources/backend/tests/test_table.pyindex 0ec42666d7fe..0ce93d363748 100644--- a/products/warehouse_sources/backend/tests/test_table.py+++ b/products/warehouse_sources/backend/tests/test_table.py@@ -1,4 +1,6 @@+import tempfileimport subprocess+from pathlib import Pathfrom typing import Anyimport pytest@@ -14,6 +16,7 @@ from parameterized import parameterizedfrom posthog.hogql.database.direct_clickhouse_table import DirectClickHouseTablefrom posthog.hogql.database.models import DatabaseField, StringDatabaseField, UUIDDatabaseFieldfrom posthog.hogql.database.s3_table import DataWarehouseTable as HogQLDataWarehouseTable+from posthog.hogql.escape_sql import escape_param_clickhousefrom posthog.exceptions import ClickHouseAtCapacity@@ -21,6 +24,7 @@ from products.warehouse_sources.backend.models.credential import DataWarehouseCrfrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import (DataWarehouseTable,+ chdb_set_statements,get_hogql_field_for_column,run_chdb_query,)@@ -240,6 +244,118 @@ class TestRunChdbQuery:assert not DataWarehouseTable()._is_suppressed_chdb_error(exc_info.value)+class TestStructureAgainstTheEngine(BaseTest):+ # chdb embeds the same ClickHouse engine that introspects a table and that every warehouse read+ # runs against, over local files instead of S3. These cases therefore prove what the engine does+ # with a structure we built, which no mock-based test can. They go through run_chdb_query so that+ # a hung embedded query fails the test instead of wedging the job, and the timeout is generous+ # because importing chdb alone costs seconds.+ CHDB_TIMEOUT_SECONDS = 120.0++ def _json_file(self, lines: list[str], name: str = "rows.json", directory: Path | None = None) -> Path:+ path = (directory or Path(tempfile.mkdtemp())) / name+ path.write_text("".join(f"{line}\n" for line in lines))+ return path++ def test_optional_nested_key_from_a_later_file_is_inferred(self) -> None:+ # The whole point of the widened settings: a nested key that only later files carry has to+ # reach the schema, because the schema is also what every read of the table is parsed with.+ directory = Path(tempfile.mkdtemp())+ self._json_file(['{"id": 1, "usage": {"input_tokens": 10}}'], name="a.json", directory=directory)+ self._json_file(+ ['{"id": 2, "usage": {"input_tokens": 20, "cache_write_tokens": 5}}'], name="b.json", directory=directory+ )+ table = DataWarehouseTable(+ name="runs",+ format=DataWarehouseTable.TableFormat.JSON,+ team=self.team,+ url_pattern="s3://bucket/team_1/runs/*",+ )++ glob = escape_param_clickhouse(str(directory / "*.json"))+ described = run_chdb_query(+ f"{chdb_set_statements(table._describe_settings())}DESCRIBE TABLE file({glob}, JSONEachRow)",+ timeout=self.CHDB_TIMEOUT_SECONDS,+ )++ assert "cache_write_tokens" in described++ def test_array_of_objects_is_readable_through_the_stored_structure(self) -> None:+ # The element names are what makes the column parseable. Without them ClickHouse reads+ # `items` as a positional array, so every query over the table raises code 27, including+ # queries that never mention the column.+ table = DataWarehouseTable(+ name="orders",+ format=DataWarehouseTable.TableFormat.JSON,+ team=self.team,+ url_pattern="s3://bucket/team_1/orders/*",+ columns={+ "id": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField", "valid": True},+ "items": {+ "clickhouse": "Array(Tuple(sku Nullable(String), qty Nullable(Int64)))",+ "hogql": "StringArrayDatabaseField",+ "valid": True,+ },+ },+ )+ path = self._json_file(['{"id": 1, "items": [{"sku": "widget", "qty": 2}]}'])++ definition = table.hogql_definition()+ assert isinstance(definition, HogQLDataWarehouseTable)+ assert definition.structure is not None+ result = run_chdb_query(+ f"SELECT items.sku FROM file({escape_param_clickhouse(str(path))}, JSONEachRow, "+ f"{escape_param_clickhouse(definition.structure)})",+ timeout=self.CHDB_TIMEOUT_SECONDS,+ )++ assert "widget" in result+++class TestSchemaInferenceMode(BaseTest):+ def _table(self, table_format: str) -> DataWarehouseTable:+ return DataWarehouseTable(name="t", format=table_format, team=self.team, url_pattern="s3://bucket/team_1/t/*")++ @parameterized.expand(+ [+ ("json", DataWarehouseTable.TableFormat.JSON, True),+ ("csv_with_names", DataWarehouseTable.TableFormat.CSVWithNames, True),+ # ClickHouse refuses `union` for a format that cannot read a subset of its columns:+ # headerless CSV raises BAD_ARGUMENTS, which would leave those tables undescribable.+ ("csv", DataWarehouseTable.TableFormat.CSV, False),+ ("delta", DataWarehouseTable.TableFormat.Delta, False),+ ]+ )+ def test_union_inference_is_scoped_to_formats_that_accept_it(+ self, _name: str, table_format: str, expects_union: bool+ ) -> None:+ with patch(+ "products.warehouse_sources.backend.models.table.sync_execute",+ return_value=[("id", "Int64")],+ ) as mock_sync_execute:+ self._table(table_format).get_columns()++ settings = mock_sync_execute.call_args.kwargs["settings"]+ assert (settings.get("schema_inference_mode") == "union") is expects_union+ # Reading the head of every file is unbounded work inside a synchronous request, so the+ # widened pass carries a server-side time limit and the narrow pass keeps its old behavior.+ assert ("max_execution_time" in settings) is expects_union++ def test_a_failed_describe_raises_instead_of_storing_a_narrower_schema(self) -> None:+ # A degraded schema that persists silently is indistinguishable from the bug being fixed:+ # the person refreshes, nothing changes, and no signal exists anywhere. The retries belong+ # on this pass, because the cluster fails intermittently.+ with patch("products.warehouse_sources.backend.models.table.time.sleep"):+ with patch(+ "products.warehouse_sources.backend.models.table.sync_execute",+ side_effect=ServerException("DB::Exception: Unexpected", code=1002),+ ) as mock_sync_execute:+ with pytest.raises(Exception):+ self._table(DataWarehouseTable.TableFormat.JSON).get_columns()++ assert mock_sync_execute.call_count == 5++class TestGetHogqlFieldForColumn(SimpleTestCase):@parameterized.expand([