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.

fix(data-modeling): reuse initial Arrow schema for empty results (#71578)

Thiago Salvatoredf919f8a84ba
diff --git a/posthog/temporal/common/asyncpa.py b/posthog/temporal/common/asyncpa.py
index 5a20e5fa86db..a0c2d7af9dcb 100644
--- a/posthog/temporal/common/asyncpa.py
+++ b/posthog/temporal/common/asyncpa.py
@@ -121,16 +121,16 @@ class AsyncRecordBatchReader:
return await self.read_next_record_batch()
async def read_next_record_batch(self) -> pa.RecordBatch:
- if self._schema is None:
- schema = await self.read_schema()
- self._schema = schema
- else:
- schema = self._schema
-
+ schema = await self.get_schema()
message = await anext(self._reader)
return pa.ipc.read_record_batch(message, schema)
+ async def get_schema(self) -> pa.Schema:
+ if self._schema is None:
+ self._schema = await self.read_schema()
+ return self._schema
+
async def read_schema(self) -> pa.Schema:
"""Read the schema, which should be the first message."""
message = await anext(self._reader)
diff --git a/posthog/temporal/common/clickhouse.py b/posthog/temporal/common/clickhouse.py
index 8d3a55fa9af7..f96d69b1a777 100644
--- a/posthog/temporal/common/clickhouse.py
+++ b/posthog/temporal/common/clickhouse.py
@@ -892,6 +892,7 @@ class ClickHouseClient:
*data,
query_parameters=None,
query_id: str | None = None,
+ on_schema: collections.abc.Callable[[pa.Schema], None] | None = None,
) -> typing.AsyncGenerator[pa.RecordBatch]:
"""Execute the given query in ClickHouse and stream back the response as Arrow record batches.
@@ -899,6 +900,8 @@ class ClickHouseClient:
"""
async with self.apost_query(query, *data, query_parameters=query_parameters, query_id=query_id) as response:
reader = asyncpa.AsyncRecordBatchReader(ChunkBytesAsyncStreamIterator(response.content))
+ if on_schema is not None:
+ on_schema(await reader.get_schema())
async for batch in reader:
yield batch
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.py
index 4e2517eda2cb..e168ea95d531 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view.py
@@ -273,20 +273,6 @@ async def _write_empty_parquet_for_zero_rows(table_uri: str, schema: pa.Schema,
return file_uri
-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)
@@ -412,8 +398,18 @@ async def hogql_table(query: str, team: Team, logger: FilteringBoundLogger, view
batches = []
batches_size = 0
yielded_results = False
+ arrow_schema: pa.Schema | None = None
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):
+
+ def capture_arrow_schema(schema: pa.Schema) -> None:
+ nonlocal arrow_schema
+ arrow_schema = schema
+
+ async for batch in client.astream_query_as_arrow(
+ arrow_printed,
+ query_parameters=context.values,
+ on_schema=capture_arrow_schema,
+ ):
batches_size = batches_size + batch.nbytes
batches.append(batch)
@@ -436,8 +432,11 @@ async def hogql_table(query: str, team: Team, logger: FilteringBoundLogger, view
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)
+ if arrow_schema is None:
+ raise EmptyHogQLResponseColumnsError()
+ empty_batch = pa.RecordBatch.from_arrays(
+ [pa.array([], type=field.type) for field in arrow_schema], schema=arrow_schema
+ )
yield (empty_batch, ch_typings_pairs)
diff --git a/posthog/temporal/tests/common/test_asyncpa.py b/posthog/temporal/tests/common/test_asyncpa.py
index 332332add267..d21590de4279 100644
--- a/posthog/temporal/tests/common/test_asyncpa.py
+++ b/posthog/temporal/tests/common/test_asyncpa.py
@@ -86,6 +86,7 @@ async def test_record_batch_reader_reads_record_batches(record_batches: collecti
_ = buffer.seek(0)
+ assert await reader.get_schema() == first_batch.schema
read_batch = await anext(reader)
assert first_batch == read_batch
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
index f48c5b02287d..dc62464e2337 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -1,3 +1,4 @@
+import contextlib
from collections.abc import Collection, Iterable
from typing import Any, cast
@@ -25,8 +26,10 @@ from posthog.temporal.data_modeling.activities import (
succeed_materialization_activity,
)
from posthog.temporal.data_modeling.activities.materialize_view import (
+ LOGGER,
InvalidNodeTypeException,
_get_aws_storage_options,
+ hogql_table,
)
from products.data_modeling.backend.facade.api import compute_enrichment_hash
@@ -1052,3 +1055,57 @@ class TestMaterializeViewActivity:
)
with pytest.raises(RuntimeError, match="boom"):
await activity_environment.run(materialize_view_activity, inputs)
+
+
+class _EmptyArrowClient:
+ def __init__(self, schema: pa.Schema):
+ self.schema = schema
+ self.arrow_query_calls = 0
+ self.schema_query_calls = 0
+
+ async def astream_query_as_arrow(self, query, *data, query_parameters=None, query_id=None, on_schema=None):
+ self.arrow_query_calls += 1
+ if on_schema is not None:
+ on_schema(self.schema)
+ return
+ yield # type: ignore[unreachable] # makes this an async generator that yields no batches
+
+ @contextlib.asynccontextmanager
+ async def apost_query(self, query, *data, query_parameters=None, query_id=None):
+ if query.startswith("DESCRIBE TABLE"):
+ body = b"id\tInt64\n"
+ else:
+ self.schema_query_calls += 1
+ buffer = pa.BufferOutputStream()
+ with pa.ipc.new_stream(buffer, self.schema):
+ pass
+ body = buffer.getvalue().to_pybytes()
+
+ class _Response:
+ def __init__(self, response_body: bytes):
+ self.content = self
+ self.body = response_body
+
+ async def read(self) -> bytes:
+ return self.body
+
+ yield _Response(body)
+
+
+class TestHogqlTableEmptyResults:
+ async def test_zero_row_query_uses_the_initial_stream_schema(self, ateam):
+ client = _EmptyArrowClient(pa.schema([pa.field("id", pa.int64())]))
+
+ @contextlib.asynccontextmanager
+ async def fake_get_client(**kwargs):
+ yield client
+
+ with unittest.mock.patch(
+ "posthog.temporal.data_modeling.activities.materialize_view.get_clickhouse_client", fake_get_client
+ ):
+ batches = [batch async for batch in hogql_table("SELECT 1", ateam, LOGGER.bind())]
+
+ assert len(batches) == 1
+ assert batches[0][0].num_rows == 0
+ assert client.arrow_query_calls == 1
+ assert client.schema_query_calls == 0