: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 widening S3 schema inference in a request (#99526)
Daniel RC4fd4181938b6
diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex cb645ec35d72..53d89a827447 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -154,23 +154,14 @@ DISABLE_HIVE_PARTITIONING_SETTINGS: dict[str, int] = {"use_hive_partitioning": 0# 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-+# Introspection keeps ClickHouse's default schema inference, which samples as little as the first+# file and therefore misses a nested key that only later files carry. The `union` mode finds those+# keys, but it reads the head of every object the pattern matches, and introspection runs inside the+# POST that creates or refreshes a table. A table whose pattern spans many objects cannot finish that+# in the time a request has, so the mode belongs on a path that is not a request. Until then the+# narrow sample stays, and a column the sample missed is reachable by retyping it to String and+# reading it with JSONExtract.def chdb_set_statements(describe_settings: dict[str, str | int]) -> str:"""Render settings as SET statements to prefix a chdb query with.@@ -574,9 +565,6 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletsettings: 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_SECONDSreturn settingsdef get_columns(@@ -627,11 +615,6 @@ 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:result = sync_execute(@@ -641,7 +624,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet)breakexcept Exception as err:- if i >= attempts - 1 or (retry_deadline is not None and time.monotonic() >= retry_deadline):+ if i >= attempts - 1:capture_exception(err)if safe_expose_ch_error:self._safe_expose_ch_error(err)diff --git a/products/warehouse_sources/backend/tests/test_table.py b/products/warehouse_sources/backend/tests/test_table.pyindex abc4df1ffa99..271c0ddace96 100644--- a/products/warehouse_sources/backend/tests/test_table.py+++ b/products/warehouse_sources/backend/tests/test_table.py@@ -24,7 +24,6 @@ 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,)@@ -273,29 +272,6 @@ class TestStructureAgainstTheEngine(BaseTest):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@@ -334,28 +310,23 @@ class TestSchemaInferenceMode(BaseTest):@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),+ ("json", DataWarehouseTable.TableFormat.JSON),+ ("csv_with_names", DataWarehouseTable.TableFormat.CSVWithNames),+ ("delta", DataWarehouseTable.TableFormat.Delta),])- def test_union_inference_is_scoped_to_formats_that_accept_it(- self, _name: str, table_format: str, expects_union: bool- ) -> None:+ def test_introspection_does_not_widen_the_file_sample(self, _name: str, table_format: str) -> None:+ # `union` reads the head of every object the pattern matches. A table whose pattern spans a+ # date-partitioned bucket cannot finish that inside a request, and the refresh fails instead+ # of returning the narrow schema. Widening belongs on an asynchronous path, so introspection+ # must keep the default sample until one exists.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+ assert "schema_inference_mode" not in mock_sync_execute.call_args.kwargs["settings"]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: