: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 generic delta errors and s3 fnf errors from empty queryable tables (#60688)
andrew j. mcgehee8d5cf28a63ba
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.pyindex 080052c4fc40..456e0f7cbdfc 100644--- a/posthog/temporal/data_modeling/activities/materialize_view.py+++ b/posthog/temporal/data_modeling/activities/materialize_view.py@@ -1,7 +1,8 @@-# TODO(andrew): add s3 cleanup on failureimport uuid+import queueimport typingimport asyncio+import threadingimport dataclassesfrom django.conf import settings@@ -10,6 +11,7 @@ import pyarrow as paimport deltalakeimport asyncstdlibimport pyarrow.compute as pc+import pyarrow.parquet as pqfrom structlog.contextvars import bind_contextvarsfrom structlog.types import FilteringBoundLoggerfrom temporalio import activity@@ -44,6 +46,10 @@ MB_100_IN_BYTES = 100 * 1000 * 1000CLICKHOUSE_MAX_BLOCK_SIZE_ROWS = 50 * 1000DELTA_TABLE_RETENTION_HOURS = 24+# how often the producer/consumer wake from a blocking queue op to re-check the+# stop flag+QUEUE_POLL_SECONDS = 1.0+# Limits concurrent ClickHouse queries per worker. Each worker pod runs a single# process with a single event loop — all async activities share it, so this# module-level semaphore gates every activity on the same worker.@@ -234,6 +240,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))+async def _write_empty_parquet_for_zero_rows(table_uri: str, schema: pa.Schema, logger: FilteringBoundLogger) -> str:+ """Write a single empty parquet file under ``table_uri`` so a zero-row materialization+ is still queryable.+ """+ buf = pa.BufferOutputStream()+ pq.write_table(schema.empty_table(), buf)+ parquet_bytes = buf.getvalue().to_pybytes()+ file_uri = f"{table_uri}/empty_{uuid.uuid4().hex}.parquet"+ s3 = get_s3_client()++ def _upload() -> None:+ with s3.open(file_uri, "wb") as f:+ f.write(parquet_bytes)++ await asyncio.to_thread(_upload)+ await logger.ainfo(f"Wrote empty parquet for zero-row materialization: uri={file_uri} bytes={len(parquet_bytes)}")+ return file_uri++async def get_query_row_count(query: str, team: Team, logger: FilteringBoundLogger, view_name: str | None = None) -> int:@@ -281,6 +306,20 @@ async def get_query_row_count(return count+async def _read_arrow_schema_from_query(client, query: str, query_parameters: dict) -> pa.Schema:+ """Fetch just the Arrow schema for a query that returned zero rows.++ The streaming reader hides the schema when there are no batches, so we re-issue the+ same query and read the schema message that ClickHouse always sends in ArrowStream+ format. The response for a zero-row result is just the schema + EOS, so reading the+ full body is cheap.+ """+ async with client.apost_query(query=query, query_parameters=query_parameters, query_id=str(uuid.uuid4())) as resp:+ data = await resp.content.read()+ reader = pa.ipc.open_stream(pa.BufferReader(data))+ return reader.schema++async def hogql_table(query: str, team: Team, logger: FilteringBoundLogger, view_name: str | None = None):"""Execute a HogQL query and yield batches of results."""query_node = parse_select(query)@@ -401,25 +440,34 @@ async def hogql_table(query: str, team: Team, logger: FilteringBoundLogger, view):batches = []batches_size = 0+ yielded_results = False+ ch_typings_pairs = [(column_name, column_type) for column_name, column_type, _ in query_typings]async for batch in client.astream_query_as_arrow(arrow_printed, query_parameters=context.values):batches_size = batches_size + batch.nbytesbatches.append(batch)if batches_size >= MB_100_IN_BYTES:await logger.adebug(f"Yielding {len(batches)} batches for total size of {batches_size / 1000 / 1000}MB")- yield (- _combine_batches(batches),- [(column_name, column_type) for column_name, column_type, _ in query_typings],- )+ yield (_combine_batches(batches), ch_typings_pairs)+ yielded_results = Truebatches_size = 0batches = []if len(batches) > 0:await logger.adebug(f"Yielding {len(batches)} batches for total size of {batches_size / 1000 / 1000}MB")- yield (- _combine_batches(batches),- [(column_name, column_type) for column_name, column_type, _ in query_typings],+ yield (_combine_batches(batches), ch_typings_pairs)+ yielded_results = True++ if not yielded_results:+ # zero-row result. yield a single empty batch carrying the query's schema so+ # downstream can still write a delta table (and an empty queryable parquet)+ # instead of leaving the model with no DataWarehouseTable at all.+ await logger.adebug(+ "Query returned zero batches; yielding empty batch with schema for queryable empty table")+ schema = await _read_arrow_schema_from_query(client, arrow_printed, context.values)+ empty_batch = pa.RecordBatch.from_arrays([pa.array([], type=field.type) for field in schema], schema=schema)+ yield (empty_batch, ch_typings_pairs)@database_sync_to_async@@ -485,41 +533,114 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializrow_count = 0storage_options = _get_aws_storage_options()delta_table: deltalake.DeltaTable | None = None- async for index, res in asyncstdlib.enumerate(- hogql_table(hogql_query, team, logger, view_name=saved_query.name)- ):- batch, ch_types = res- batch = _transform_unsupported_decimals(batch)- batch = _transform_date_and_datetimes(batch, ch_types)- if index == 0:+ # cache the schema of the first written batch so we can synthesize an empty+ # parquet for zero-row results without going through delta-rs (whose Schema+ # is arro3, not pyarrow).+ pa_schema: pa.Schema | None = None++ # we stream every batch through a single deltalake write transaction.+ # writing per-batch with mode="append" routes through delta-rs's+ # DataFusion-backed writer, which lowercases identifiers and breaks+ # columns with uppercase characters (`personId`, `Event`, ...) with+ # errors like "Generic DeltaTable error: Schema error: No field named+ # personid. ... Did you mean 'personId'?".+ SENTINEL: typing.Any = object()+ batch_queue: queue.Queue[pa.RecordBatch] = queue.Queue(maxsize=2)+ producer_error: list[BaseException] = []++ # the producer's queue ops run in a thread via asyncio.to_thread, which is not+ # cancellable: once a blocking queue.put/get is in flight, cancelling the+ # awaiting coroutine does nothing to the thread. a plain blocking put against a+ # full queue would therefore park its thread forever if the consumer stops+ # draining (e.g. the write aborts, or the activity is cancelled), orphaning the+ # thread and the producer task. so every blocking queue op below is a bounded+ # poll on stop_event instead — when stop is requested, the in-flight op returns+ # within QUEUE_POLL_SECONDS no matter what. safety is a property of the queue+ # primitives, not of how carefully cleanup is sequenced.+ stop_event = threading.Event()++ def _put(item: typing.Any) -> None:+ while not stop_event.is_set():+ try:+ batch_queue.put(item, timeout=QUEUE_POLL_SECONDS)+ return+ except queue.Full:+ continue++ def _get() -> typing.Any:+ while not stop_event.is_set():+ try:+ return batch_queue.get(timeout=QUEUE_POLL_SECONDS)+ except queue.Empty:+ continue+ return SENTINEL++ # a producer error is recorded in producer_error and then signalled to the+ # consumer as a SENTINEL — i.e. the same clean end-of-stream as success. the+ # consumer therefore commits whatever batches it received (a partial overwrite)+ # before we re-raise below. that partial commit is harmless: the activity raises,+ # Temporal retries, and the retry's delete-first wipes table_uri before rewriting.+ async def _produce_batches() -> None:+ nonlocal row_count+ try:+ async for _, res in asyncstdlib.enumerate(hogql_table(hogql_query, team, logger)):+ if stop_event.is_set():+ break+ batch, ch_types = res+ batch = _transform_unsupported_decimals(batch)+ batch = _transform_date_and_datetimes(batch, ch_types)+ num_rows = batch.num_rows+ await asyncio.to_thread(_put, batch)+ # local reference dropped immediately; the queue (and later+ # the consumer) holds the only remaining reference.+ del batch, ch_types+ row_count = row_count + num_rows+ job.rows_materialized = row_count+ await database_sync_to_async(job.save)()+ except BaseException as e:+ producer_error.append(e)+ finally:+ await asyncio.to_thread(_put, SENTINEL)++ producer_task = asyncio.create_task(_produce_batches())+ try:+ first_batch = await asyncio.to_thread(_get)+ if first_batch is not SENTINEL:+ pa_schema = first_batch.schema++ def _batch_iter() -> typing.Iterator[pa.RecordBatch]:+ yield first_batch+ while True:+ item = _get()+ if item is SENTINEL:+ return+ yield item++ reader = pa.RecordBatchReader.from_batches(pa_schema, _batch_iter())await logger.adebug(- f"Writing batch to delta table: index={index} mode=overwrite schema_mode=overwrite batch_row_count={batch.num_rows}"+ f"Writing batches to delta table in a single transaction: mode=overwrite schema_mode=overwrite first_batch_rows={first_batch.num_rows}")await asyncio.to_thread(deltalake.write_deltalake,table_or_uri=table_uri,- data=batch,+ data=reader,mode="overwrite",schema_mode="overwrite",storage_options=storage_options,)delta_table = deltalake.DeltaTable(table_uri, storage_options=storage_options)- else:- await logger.adebug(- f"Writing batch to delta table: index={index} mode=append batch_row_count={batch.num_rows}"- )- await asyncio.to_thread(- deltalake.write_deltalake, # type: ignore[arg-type]- table_or_uri=delta_table,- data=batch,- mode="append",- storage_options=storage_options,- )- row_count = row_count + batch.num_rows- job.rows_materialized = row_count- await database_sync_to_async(job.save)()- # explicitly delete batch to free memory after writing- del batch, ch_types+ finally:+ # request the producer stop and reap it. stop_event is set synchronously,+ # before any await, so even a cancellation delivered at the await below+ # cannot leave the producer parked on a queue op — its bounded _put/_get+ # observe the flag and return promptly, the producer breaks its loop, and+ # the task completes on its own. awaiting it here simply joins that exit.+ stop_event.set()+ await producer_task++ if producer_error:+ raise producer_error[0]+await logger.ainfo(f"Finished writing to delta table. row_count={row_count}")# row count validation warningif job.rows_expected is not None:@@ -541,6 +662,11 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializdry_run=False,)file_uris = delta_table.file_uris()+ if not file_uris and row_count == 0 and pa_schema is not None:+ # delta-rs writes no parquet for an empty batch. emit one so the+ # queryable folder has a file with a schema attached that's queryable+ empty_parquet_uri = await _write_empty_parquet_for_zero_rows(table_uri, pa_schema, logger)+ file_uris = [empty_parquet_uri]await logger.ainfo(f"Materialized node {node.name} with {row_count} rows")return MaterializeViewResult(node_id=node.id,diff --git a/posthog/temporal/data_modeling/workflows/materialize_view.py b/posthog/temporal/data_modeling/workflows/materialize_view.pyindex cae097661723..6726baf1055f 100644--- a/posthog/temporal/data_modeling/workflows/materialize_view.py+++ b/posthog/temporal/data_modeling/workflows/materialize_view.py@@ -202,7 +202,10 @@ class MaterializeViewWorkflow(PostHogWorkflow):cancellation_type=temporalio.workflow.ActivityCancellationType.TRY_CANCEL,)- # prepare files for querying and create DataWarehouseTable+ # prepare files for querying and create DataWarehouseTable.+ # materialize_view_activity guarantees file_uris is non-empty even for+ # zero-row results — it falls back to _write_empty_parquet_for_zero_rows+ # so prepare_s3_files_for_querying has something to list.storage_result = await temporalio.workflow.execute_activity(prepare_queryable_table_activity,PrepareQueryableTableInputs(diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex f8e4c73f30f4..24e1c76f77f9 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -1,5 +1,6 @@-from collections.abc import Collection-from typing import cast+import asyncio+from collections.abc import Collection, Iterable+from typing import Any, castimport pytestimport unittest.mock@@ -8,6 +9,7 @@ from django.conf import settingsfrom django.test import override_settingsimport pyarrow as pa+import deltalakeimport pytest_asynciofrom posthog.sync import database_sync_to_async@@ -23,7 +25,10 @@ from posthog.temporal.data_modeling.activities import (prepare_queryable_table_activity,succeed_materialization_activity,)-from posthog.temporal.data_modeling.activities.materialize_view import InvalidNodeTypeException+from posthog.temporal.data_modeling.activities.materialize_view import (+ InvalidNodeTypeException,+ _get_aws_storage_options,+)from products.data_modeling.backend.models import DAG, Node, NodeTypefrom products.data_modeling.backend.models.data_modeling_job import DataModelingJob, DataModelingJobStatus@@ -587,3 +592,180 @@ class TestMaterializeViewActivity:assert ajob.rows_expected == 5assert ajob.rows_materialized == 5assert result.row_count == 5++ async def test_preserves_column_casing_across_multiple_batches(+ self, activity_environment, ateam, anode, ajob, bucket_name, adag+ ):+ # regression: multiple batches with case-sensitive columns must materialize cleanly.+ #+ # per-batch mode="append" writes route through delta-rs's DataFusion-backed+ # writer, which lowercases identifiers and fails with+ # "Generic DeltaTable error: Schema error: No field named personid. ...+ # Did you mean 'personId'?" on tables whose column names contain uppercase+ # characters. the activity streams every batch through a single mode="overwrite"+ # transaction to take the case-safe create path; this test guards both invariants:+ # - all rows from every batch are written and column casing is preserved;+ # - the delta history contains a single version (i.e. one commit), which would+ # regress to N versions if someone reintroduced per-batch append.+ camel_case_names = ["Event", "DistinctId", "personId", "CamelCaseColumn"]++ 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],+ names=camel_case_names,+ )+ 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+ # one commit per materialization — guards against reintroducing per-batch+ # append, which would record N+ versions and route through the broken+ # DataFusion-backed writer.+ assert len(delta_table.history()) == 1++ async def test_zero_row_materialization_writes_empty_parquet(+ self, activity_environment, ateam, anode, asaved_query, ajob, bucket_name, adag+ ):+ # regression: a zero-row query must still produce a queryable empty table.+ #+ # delta-rs writes no parquet data file for an empty batch, so the activity+ # synthesizes one carrying the schema and returns it as file_uris. without+ # this, prepare_queryable_table_activity would later list a never-created+ # S3 folder and raise FileNotFoundError.+ fields: Iterable[pa.Field[Any]] = [pa.field("id", pa.int64()), pa.field("name", pa.string())]+ empty_schema = pa.schema(fields)++ def mock_hogql_table(*args, **kwargs):+ del args, kwargs+ empty_batch = pa.RecordBatch.from_arrays(+ [pa.array([], type=f.type) for f in empty_schema], schema=empty_schema+ )++ async def async_generator():+ yield empty_batch, [("id", "Int64"), ("name", "String")]++ 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=0,+ ),+ ):+ 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 == 0+ assert len(result.file_uris) == 1+ assert result.file_uris[0].endswith(".parquet")+ # delta log carries the schema so deltaLake() reads in get_columns succeed+ delta_table = deltalake.DeltaTable(result.table_uri, storage_options=_get_aws_storage_options())+ pyarrow_table = delta_table.to_pyarrow_table()+ assert pyarrow_table.num_rows == 0+ assert set(pyarrow_table.column_names) == {"id", "name"}++ async def test_aborted_write_releases_producer_parked_on_full_queue(+ self, activity_environment, ateam, anode, ajob, bucket_name, adag+ ):+ # regression: when the consumer (write) aborts while the producer is still+ # streaming, the producer must not be orphaned. its queue ops run in a thread+ # via asyncio.to_thread (not cancellable), so a plain blocking put against the+ # bounded queue would park that thread forever once the consumer stops draining,+ # and the cleanup join (await producer_task) would hang with it. the producer's+ # _put/_get poll a stop_event that cleanup sets, so the parked op returns and the+ # task is reaped. we yield far more batches than the queue holds (maxsize=2) and+ # make write_deltalake raise without draining, guaranteeing the producer parks;+ # the activity must surface the write error promptly instead of hanging.+ names = ["a", "b"]++ def mock_hogql_table(*args, **kwargs):+ del args, kwargs++ async def async_generator():+ for i in range(8):+ batch = pa.RecordBatch.from_arrays(+ [pa.array([f"b{i}r0", f"b{i}r1"], type=pa.string()) for _ in names],+ names=names,+ )+ yield batch, [(name, "String") for name in names]++ return async_generator()++ def raising_write(*args, **kwargs):+ del args, kwargs+ raise RuntimeError("boom")++ 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=16,+ ),+ unittest.mock.patch("deltalake.write_deltalake", side_effect=raising_write),+ ):+ inputs = MaterializeViewInputs(+ team_id=ateam.pk,+ dag_id=str(adag.id),+ node_id=str(anode.id),+ job_id=str(ajob.id),+ )+ # wait_for fails the test rather than hanging the suite if the producer is+ # orphaned and the cleanup join blocks forever.+ with pytest.raises(RuntimeError, match="boom"):+ await asyncio.wait_for(activity_environment.run(materialize_view_activity, inputs), timeout=10)