: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(modeling): fix column names lowercased by deltalake (#64066)
andrew j. mcgehee32e9fb0b8ab2
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.pyindex 2b563d223409..7cbd529fcc8c 100644--- a/posthog/temporal/data_modeling/activities/materialize_view.py+++ b/posthog/temporal/data_modeling/activities/materialize_view.py@@ -189,6 +189,25 @@ def _transform_date_and_datetimes(batch: pa.RecordBatch, types: list[tuple[str,return pa.RecordBatch.from_arrays(new_columns, schema=pa.schema(new_fields, metadata=new_metadata))+def _force_nullable(batch: pa.RecordBatch) -> pa.RecordBatch:+ """Mark every column nullable so batch schemas don't diverge across delta commits.++ ClickHouse emits non-nullable columns for expressions, constants, concat()/toString(),+ and non-Nullable source columns. When such a query spans more than one batch, the first+ batch's overwrite pins a non-nullable delta schema and the later append routes through+ delta-rs's DataFusion writer to reconcile schemas. DataFusion lowercases identifiers and+ then fails to resolve case-sensitive columns, e.g. "No field named userid. ... Did you+ mean 'userId'?" — breaking any column with uppercase characters. Pinning every column to+ nullable keeps each batch's schema identical to the first overwrite, so the append never+ triggers that path and camelCase column names survive.+ """+ nullable_schema = pa.schema(+ [pa.field(field.name, field.type, nullable=True, metadata=field.metadata) for field in batch.schema],+ metadata=typing.cast("dict[bytes | str, bytes | str] | None", batch.schema.metadata),+ )+ return batch.cast(nullable_schema)++def _transform_unsupported_decimals(batch: pa.RecordBatch) -> pa.RecordBatch:"""Transform high-precision decimal columns to types supported by Delta Lake."""schema = batch.schema@@ -550,6 +569,7 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializasync for batch, ch_types in hogql_table(hogql_query, team, logger):batch = _transform_unsupported_decimals(batch)batch = _transform_date_and_datetimes(batch, ch_types)+ batch = _force_nullable(batch)if delta_table is None:pa_schema = batch.schemaawait asyncio.to_thread(diff --git a/posthog/temporal/data_modeling/run_workflow.py b/posthog/temporal/data_modeling/run_workflow.pyindex 8c0d9993bc74..62ba13e853c1 100644--- a/posthog/temporal/data_modeling/run_workflow.py+++ b/posthog/temporal/data_modeling/run_workflow.py@@ -542,6 +542,7 @@ async def materialize_model(batch, ch_types = resbatch = _transform_unsupported_decimals(batch)batch = _transform_date_and_datetimes(batch, ch_types)+ batch = _force_nullable(batch)if index == 0:await logger.adebug(@@ -1178,6 +1179,25 @@ def _transform_unsupported_decimals(batch: pa.RecordBatch) -> pa.RecordBatch:return pa.RecordBatch.from_arrays(new_columns, schema=pa.schema(new_fields, metadata=new_metadata))+def _force_nullable(batch: pa.RecordBatch) -> pa.RecordBatch:+ """Mark every column nullable so batch schemas don't diverge across delta commits.++ ClickHouse emits non-nullable columns for expressions, constants, concat()/toString(),+ and non-Nullable source columns. When such a query spans more than one batch, the first+ batch's overwrite pins a non-nullable delta schema and the later append routes through+ delta-rs's DataFusion writer to reconcile schemas. DataFusion lowercases identifiers and+ then fails to resolve case-sensitive columns, e.g. "No field named userid. ... Did you+ mean 'userId'?" — breaking any column with uppercase characters. Pinning every column to+ nullable keeps each batch's schema identical to the first overwrite, so the append never+ triggers that path and camelCase column names survive.+ """+ nullable_schema = pa.schema(+ [pa.field(field.name, field.type, nullable=True, metadata=field.metadata) for field in batch.schema],+ metadata=typing.cast("dict[bytes | str, bytes | str] | None", batch.schema.metadata),+ )+ return batch.cast(nullable_schema)++def _get_credentials():if settings.USE_LOCAL_SETUP:ensure_bucket_exists(diff --git a/posthog/temporal/tests/data_modeling/conftest.py b/posthog/temporal/tests/data_modeling/conftest.pyindex 3e2b85001ef9..d8db08af9735 100644--- a/posthog/temporal/tests/data_modeling/conftest.py+++ b/posthog/temporal/tests/data_modeling/conftest.py@@ -8,6 +8,14 @@ from django.conf import settingsimport aioboto3import pytest_asyncio+# The activity-log post_save signal lazily imports posthog.api.advanced_activity_logs+# (-> posthog.tasks.usage_report) the first time an ActivityLog row is created. In these+# temporal tests the worker logger has already reconfigured structlog to a WrapperLogger,+# under which usage_report's module-level logger.setLevel() raises AttributeError and crashes+# fixture setup. Importing the chain here — while structlog is still the default config —+# runs that module-level code safely and caches it, so the signal's lazy import is a no-op.+import posthog.api.advanced_activity_logs # noqa: F401, E402 — warm import; see comment above+TEST_ROOT_BUCKET = "test-data-modeling"SESSION = aioboto3.Session()create_test_client = functools.partial(SESSION.client, endpoint_url=settings.OBJECT_STORAGE_ENDPOINT)diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex 527c2106b824..8b559edad4d6 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -651,6 +651,65 @@ class TestMaterializeViewActivity:assert materialized.column_names == camel_case_namesassert materialized.num_rows == 6+ async def test_preserves_column_casing_for_non_nullable_columns_across_batches(+ self, activity_environment, ateam, anode, ajob, bucket_name, adag+ ):+ # regression: ClickHouse emits NON-nullable columns for expressions, constants,+ # concat()/toString(), and non-Nullable source columns. When such a query spans more+ # than one batch, the first batch's overwrite pins a non-nullable delta schema and the+ # later append (schema_mode="merge") routes through delta-rs's DataFusion writer, which+ # lowercases identifiers and fails with:+ # "Schema error: No field named userid. ... Did you mean 'userId'?"+ # for any column containing uppercase characters. This mirrors the customer query whose+ # camelCase columns (userId, portfolioId, pHuniqueId, aumDKK, ...) are all non-nullable.+ camel_case_names = ["date", "userId", "portfolioId", "pHuniqueId", "aumDKK", "aum_ETF"]+ non_nullable_schema = pa.schema([pa.field(name, pa.string(), nullable=False) for name in camel_case_names])++ def mock_hogql_table(*args, **kwargs):+ del args, kwargs+ batches = [+ pa.RecordBatch.from_arrays(+ [pa.array([f"b{i}r0", f"b{i}r1"], type=pa.string()) for _ in camel_case_names],+ schema=non_nullable_schema,+ )+ for i in range(3)+ ]++ async def async_generator():+ for batch in batches:+ yield batch, [(name, "String") for name in camel_case_names]++ return async_generator()++ with (+ override_settings(+ BUCKET_URL=f"s3://{bucket_name}",+ DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,+ DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,+ DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",+ ),+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.materialize_view.hogql_table", mock_hogql_table+ ),+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.materialize_view.get_query_row_count",+ return_value=6,+ ),+ ):+ inputs = MaterializeViewInputs(+ team_id=ateam.pk,+ dag_id=str(adag.id),+ node_id=str(anode.id),+ job_id=str(ajob.id),+ )+ result = await activity_environment.run(materialize_view_activity, inputs)++ assert result.row_count == 6+ delta_table = deltalake.DeltaTable(result.table_uri, storage_options=_get_aws_storage_options())+ materialized = delta_table.to_pyarrow_table()+ assert materialized.column_names == camel_case_names+ assert materialized.num_rows == 6+async def test_zero_row_materialization_writes_empty_parquet(self, activity_environment, ateam, anode, asaved_query, ajob, bucket_name, adag):