Skip to content

: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.

feat(warehouse-sources): read an evolving JSON object as the JSON type (#99549)

Daniel RCc0e49235e7d5
diff --git a/products/data_warehouse/backend/models/test/test_table.py b/products/data_warehouse/backend/models/test/test_table.py
index bbfffee39cd8..22eb3c025aa2 100644
--- a/products/data_warehouse/backend/models/test/test_table.py
+++ b/products/data_warehouse/backend/models/test/test_table.py
@@ -500,6 +500,31 @@ class TestTable(BaseTest):
}
}
+ @parameterized.expand(
+ [
+ # A JSON file's object keys vary per row, so the described key list is only a sample.
+ ("json", DataWarehouseTable.TableFormat.JSON, "JSON", "StringJSONDatabaseField"),
+ # A Parquet file declares its struct fields, so the Tuple is accurate.
+ ("parquet", DataWarehouseTable.TableFormat.Parquet, None, "StringJSONDatabaseField"),
+ ]
+ )
+ def test_get_columns_stores_a_json_object_as_the_json_type(
+ self, _name: str, table_format: str, expected_clickhouse: str | None, expected_hogql: str
+ ):
+ described = "Tuple(inputContentType Nullable(String), inputTokenCount Nullable(Int64))"
+ credential = DataWarehouseCredential.objects.create(access_key="key", access_secret="secret", team=self.team)
+ table = DataWarehouseTable.objects.create(
+ name="test_table", url_pattern="", credential=credential, format=table_format, team=self.team
+ )
+
+ with patch("products.warehouse_sources.backend.models.table.sync_execute") as sync_execute_results:
+ sync_execute_results.return_value = [["input", described]]
+ columns = table.get_columns()
+
+ assert columns == {
+ "input": {"clickhouse": expected_clickhouse or described, "hogql": expected_hogql, "valid": True}
+ }
+
def test_get_columns_with_hyphened_names(self):
credential = DataWarehouseCredential.objects.create(access_key="key", access_secret="secret", team=self.team)
table = DataWarehouseTable.objects.create(
@@ -1043,6 +1068,21 @@ class TestTable(BaseTest):
assert definition.top_level_settings is not None
assert definition.top_level_settings.format_csv_allow_double_quotes is False
+ def test_hogql_definition_reads_a_json_column_as_the_json_type(self):
+ credential = DataWarehouseCredential.objects.create(access_key="test", access_secret="test", team=self.team)
+ table = DataWarehouseTable.objects.create(
+ name="runs",
+ url_pattern="https://example.com/runs/*.json",
+ format=DataWarehouseTable.TableFormat.JSON,
+ team=self.team,
+ columns={"usage": {"clickhouse": "JSON", "hogql": "StringJSONDatabaseField"}},
+ credential=credential,
+ )
+
+ definition = table.hogql_definition()
+ assert isinstance(definition, HogQLDataWarehouseTable)
+ assert definition.structure == "`usage` JSON"
+
def test_hogql_definition_no_raw_settings_for_parquet(self):
credential = DataWarehouseCredential.objects.create(access_key="test", access_secret="test", team=self.team)
table = DataWarehouseTable.objects.create(
diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.py
index 53d89a827447..74aff5043c1b 100644
--- a/products/warehouse_sources/backend/models/table.py
+++ b/products/warehouse_sources/backend/models/table.py
@@ -561,6 +561,17 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
self.columns = columns
self.column_order = list(columns.keys())
+ def _nested_object_column_type(self, described_type: str) -> str:
+ """The type to store for a described column, as JSON where a key list would go stale.
+
+ Inference describes a JSON object as a named Tuple of the keys its sample held, and that Tuple becomes the
+ `structure` of every read, so a key outside the sample is unreadable. The JSON type carries no key list.
+ An array of objects and a Parquet-backed format keep the Tuple, which reads correctly and types each field.
+ """
+ if self.format != DataWarehouseTableFormat.JSON or clean_type(described_type) != "Tuple":
+ return described_type
+ return "JSON"
+
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:
@@ -645,9 +656,10 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
f"PostHog can't use the column name {column_name!r}. Column names can't contain "
"backticks, backslashes, line breaks, or null bytes. Rename the column, then try again."
)
+ clickhouse_type = self._nested_object_column_type(str(item[1]))
columns[column_name] = DataWarehouseTableIntrospectedColumn(
- hogql=CLICKHOUSE_HOGQL_MAPPING[clean_type(str(item[1]))].__name__,
- clickhouse=item[1],
+ hogql=CLICKHOUSE_HOGQL_MAPPING[clean_type(clickhouse_type)].__name__,
+ clickhouse=clickhouse_type,
valid=True,
)
diff --git a/products/warehouse_sources/backend/tests/test_table.py b/products/warehouse_sources/backend/tests/test_table.py
index 271c0ddace96..df8f7f65374e 100644
--- a/products/warehouse_sources/backend/tests/test_table.py
+++ b/products/warehouse_sources/backend/tests/test_table.py
@@ -1,10 +1,8 @@
-import tempfile
import subprocess
-from pathlib import Path
from typing import Any
import pytest
-from posthog.test.base import BaseTest
+from posthog.test.base import BaseTest, ClickhouseTestMixin
from unittest.mock import patch
from django.core.exceptions import ValidationError
@@ -18,6 +16,7 @@ from posthog.hogql.database.models import DatabaseField, StringDatabaseField, UU
from posthog.hogql.database.s3_table import DataWarehouseTable as HogQLDataWarehouseTable
from posthog.hogql.escape_sql import escape_param_clickhouse
+from posthog.clickhouse.client import sync_execute
from posthog.exceptions import ClickHouseAtCapacity
from products.warehouse_sources.backend.models.credential import DataWarehouseCredential
@@ -259,18 +258,22 @@ class TestRunChdbQuery:
assert DataWarehouseTable()._is_suppressed_chdb_error(exc_info.value) is suppressed
-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
+class TestStructureAgainstTheEngine(ClickhouseTestMixin, BaseTest):
+ # A warehouse read pins the stored structure as the `structure` argument of s3(), so what the engine
+ # does with that string decides whether a column is readable. These cases send the structure the model
+ # builds to ClickHouse and read rows back through it, which no mock-based test can do. They run on the
+ # cluster because that is where a read runs, and they send no settings for the same reason.
+ # `format()` stands in for s3() so the case needs no bucket: both take the same format and structure,
+ # and the parsing under test is the format reader's.
+ def _read_through_structure(self, table: DataWarehouseTable, select: str, rows: list[str]) -> list[tuple[Any, ...]]:
+ definition = table.hogql_definition()
+ assert isinstance(definition, HogQLDataWarehouseTable)
+ assert definition.structure is not None
+ return sync_execute(
+ f"SELECT {select} FROM format(JSONEachRow, "
+ f"{escape_param_clickhouse(definition.structure)}, "
+ f"{escape_param_clickhouse(''.join(f'{row}\n' for row in rows))}) ORDER BY id"
+ )
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
@@ -290,18 +293,36 @@ class TestStructureAgainstTheEngine(BaseTest):
},
},
)
- 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,
+ result = self._read_through_structure(table, "items.sku", ['{"id": 1, "items": [{"sku": "widget", "qty": 2}]}'])
+
+ assert result == [(["widget"],)]
+
+ def test_a_key_outside_the_schema_reads_through_a_json_column(self) -> None:
+ # Introspection samples part of the data, so the second row's key is absent from the stored schema
+ # and still reads. A Tuple of the sampled keys drops it at parse time instead.
+ table = DataWarehouseTable(
+ name="runs",
+ format=DataWarehouseTable.TableFormat.JSON,
+ team=self.team,
+ url_pattern="s3://bucket/team_1/runs/*",
+ columns={
+ "id": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField", "valid": True},
+ "usage": {"clickhouse": "JSON", "hogql": "StringJSONDatabaseField", "valid": True},
+ },
+ )
+
+ result = self._read_through_structure(
+ table,
+ "id, toString(usage.cacheWriteInputTokenCount) AS written",
+ [
+ '{"id": 1, "usage": {"inputTokens": 10}}',
+ '{"id": 2, "usage": {"inputTokens": 20, "cacheWriteInputTokenCount": 5}}',
+ ],
)
- assert "widget" in result
+ # The row that carries the key reads it; the row that does not reads empty rather than failing.
+ assert result == [(1, ""), (2, "5")]
class TestSchemaInferenceMode(BaseTest):