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): surface the clickhouse error in a broken arrow stream (#109733)

posthog[bot]20ce07d22de8
diff --git a/posthog/temporal/common/asyncpa.py b/posthog/temporal/common/asyncpa.py
index 2a63eeda1f67..fe1856abb287 100644
--- a/posthog/temporal/common/asyncpa.py
+++ b/posthog/temporal/common/asyncpa.py
@@ -8,10 +8,16 @@ from posthog.temporal.common.logger import get_write_only_logger
logger = get_write_only_logger()
CONTINUATION_BYTES = b"\xff\xff\xff\xff"
+# A server that fails mid-stream appends its error text to the stream, so the tail is small.
+MAX_UNPARSED_BYTES = 1024 * 1024
+UNPARSED_READ_TIMEOUT_SECONDS = 10
+INVALID_MESSAGE_FORMAT_ERROR = "Arrow stream contains bytes that are not an IPC message"
class InvalidMessageFormat(Exception):
- pass
+ def __init__(self, message: str, unparsed: bytes = b"") -> None:
+ super().__init__(message)
+ self.unparsed = unparsed
class AsyncMessageReader:
@@ -45,9 +51,9 @@ class AsyncMessageReader:
await self.read_until(4)
if self._buffer[:4] != CONTINUATION_BYTES:
- raise InvalidMessageFormat(
- f"Encapsulated IPC message format must begin with continuation bytes, received: '{self._buffer[:4]}'"
- )
+ unparsed = await self.read_remaining()
+ preview = unparsed[:200].decode("utf-8", errors="replace")
+ raise InvalidMessageFormat(f"{INVALID_MESSAGE_FORMAT_ERROR}: {preview!r}", unparsed=unparsed)
await self.read_until(8)
@@ -83,6 +89,18 @@ class AsyncMessageReader:
bytes = await anext(self._bytes)
self._buffer.extend(bytes)
+ async def read_remaining(self) -> bytes:
+ """Read the rest of the stream, up to MAX_UNPARSED_BYTES, and return it with the buffer."""
+ try:
+ # Callers can read without a request timeout, so a stalled stream must not block here.
+ async with asyncio.timeout(UNPARSED_READ_TIMEOUT_SECONDS):
+ while len(self._buffer) < MAX_UNPARSED_BYTES:
+ self._buffer.extend(await anext(self._bytes))
+ except Exception:
+ # The stream ended, the server closed the connection, or the deadline passed.
+ pass
+ return bytes(self._buffer[:MAX_UNPARSED_BYTES])
+
def parse_body_size(self, metadata_flatbuffer: bytes | bytearray | memoryview) -> int:
"""Parse body size from metadata flatbuffer.
diff --git a/posthog/temporal/common/clickhouse.py b/posthog/temporal/common/clickhouse.py
index 7f9e515bfde2..37de0a5aa72c 100644
--- a/posthog/temporal/common/clickhouse.py
+++ b/posthog/temporal/common/clickhouse.py
@@ -170,6 +170,23 @@ class ClickHouseClientNotConnected(Exception):
super().__init__("ClickHouseClient is not connected. Are you running in a context manager?")
+_CLICKHOUSE_ERROR_START = re.compile(r"(?:(?:std::exception|Poco::Exception)\. )?Code: \d+[.,] ")
+# ClickHouse 25+ wraps the error in "__exception__" lines and closes it with "<size> <tag>".
+_CLICKHOUSE_ERROR_TRAILER = re.compile(r"(\r?\n\d+ \w+)?\r?\n__exception__\s*$")
+
+QUERY_LOG_LOOKUP_ATTEMPTS = 5
+QUERY_LOG_LOOKUP_INTERVAL_SECONDS = 3
+
+
+def extract_clickhouse_error(payload: bytes) -> str | None:
+ """Find a ClickHouse error message in bytes that ClickHouse appended to a response."""
+ text = payload.decode("utf-8", errors="replace")
+ match = _CLICKHOUSE_ERROR_START.search(text)
+ if match is None:
+ return None
+ return _CLICKHOUSE_ERROR_TRAILER.sub("", text[match.start() :]).strip()
+
+
class ClickHouseError(Exception):
"""Base Exception representing anything going wrong with ClickHouse."""
@@ -460,6 +477,42 @@ class ClickHouseClient:
raise exc_class(error_message, query=query, query_id=query_id)
raise ClickHouseError(error_message, query=query, query_id=query_id)
+ @classmethod
+ def raise_stream_error(
+ cls, error: asyncpa.InvalidMessageFormat, query: str | None = None, query_id: str | None = None
+ ) -> typing.NoReturn:
+ """Raise the ClickHouse error in the unparsed tail of an Arrow stream, or the original error.
+
+ ClickHouse sends the 200 status before the query ends. When the query fails after that,
+ ClickHouse appends the error text to the stream that it already sent.
+ """
+ error_message = extract_clickhouse_error(error.unparsed)
+ if error_message is None:
+ raise error
+ try:
+ cls.raise_clickhouse_error(error_message, query=query, query_id=query_id)
+ except ClickHouseError as clickhouse_error:
+ raise clickhouse_error from error
+
+ async def araise_cut_stream_error(
+ self, error: aiohttp.ClientPayloadError, query: str | None, query_id: str
+ ) -> typing.NoReturn:
+ """Raise the query's error from the query log when the response ended early, or the original error."""
+ for attempt in range(QUERY_LOG_LOOKUP_ATTEMPTS):
+ if attempt:
+ await asyncio.sleep(QUERY_LOG_LOOKUP_INTERVAL_SECONDS)
+ try:
+ status = await self.acheck_query_in_query_log(query_id)
+ except ClickHouseQueryNotFound:
+ continue
+ except ClickHouseCheckQueryStatusError:
+ break
+ except ClickHouseError as clickhouse_error:
+ raise clickhouse_error from error
+ if status != ClickHouseQueryStatus.RUNNING:
+ break
+ raise error
+
async def acheck_response(self, response, query) -> None:
"""Asynchronously check the HTTP response received from ClickHouse."""
if response.status != 200:
@@ -986,14 +1039,20 @@ class ClickHouseClient:
This method makes sense when running with FORMAT ArrowStream, although we currently do not enforce this.
"""
+ query_id = query_id or str(uuid.uuid4())
async with self.apost_query(
query, *data, query_parameters=query_parameters, query_id=query_id, external_tables=external_tables
) 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
+ try:
+ if on_schema is not None:
+ on_schema(await reader.get_schema())
+ async for batch in reader:
+ yield batch
+ except asyncpa.InvalidMessageFormat as error:
+ self.raise_stream_error(error, query=query, query_id=query_id)
+ except aiohttp.ClientPayloadError as error:
+ await self.araise_cut_stream_error(error, query=query, query_id=query_id)
async def aproduce_query_as_arrow_record_batches(
self,
@@ -1009,9 +1068,15 @@ class ClickHouseClient:
This method is intended to be ran as a background task, producing record batches continuously, while other
downstream consumer tasks process them from the queue.
"""
+ query_id = query_id or str(uuid.uuid4())
async with self.apost_query(query, *data, query_parameters=query_parameters, query_id=query_id) as response:
reader = asyncpa.AsyncRecordBatchProducer(ChunkBytesAsyncStreamIterator(response.content))
- await reader.produce(queue=queue)
+ try:
+ await reader.produce(queue=queue)
+ except asyncpa.InvalidMessageFormat as error:
+ self.raise_stream_error(error, query=query, query_id=query_id)
+ except aiohttp.ClientPayloadError as error:
+ await self.araise_cut_stream_error(error, query=query, query_id=query_id)
async def __aenter__(self):
"""Enter method part of the AsyncContextManager protocol."""
diff --git a/posthog/temporal/data_modeling/activities/utils.py b/posthog/temporal/data_modeling/activities/utils.py
index 8fd7dfb72821..606fd0067d56 100644
--- a/posthog/temporal/data_modeling/activities/utils.py
+++ b/posthog/temporal/data_modeling/activities/utils.py
@@ -8,6 +8,7 @@ from django.db import transaction
from structlog.contextvars import bind_contextvars
from posthog.sync import database_sync_to_async_pool
+from posthog.temporal.common.asyncpa import INVALID_MESSAGE_FORMAT_ERROR, InvalidMessageFormat
from posthog.temporal.common.logger import get_logger
from posthog.temporal.data_modeling.activities.preempt_dag_run import ABANDONED_ERROR
@@ -106,9 +107,23 @@ EXTERNALLY_ABORTED_MARKERS = (
QUALITY_BLOCKED_ERROR_PREFIX,
)
+STREAM_FAULT_ERROR_PREFIXES = (
+ # the Arrow stream broke and carried no ClickHouse error, so nothing says the query failed
+ f"{InvalidMessageFormat.__name__}: {INVALID_MESSAGE_FORMAT_ERROR}: ",
+ # older job rows record the same stream fault with this text
+ f"{InvalidMessageFormat.__name__}: Encapsulated IPC message format must begin with continuation bytes, received: ",
+)
+
+SUSPENDED_ERROR_PREFIX = (
+ f"This model has been suspended after {CONSECUTIVE_FAILURES_TO_SUSPEND} consecutive failed "
+ "materializations. Error: "
+)
+
def is_externally_aborted(error: str) -> bool:
- return any(marker in error for marker in EXTERNALLY_ABORTED_MARKERS)
+ return any(marker in error for marker in EXTERNALLY_ABORTED_MARKERS) or error.removeprefix(
+ SUSPENDED_ERROR_PREFIX
+ ).startswith(STREAM_FAULT_ERROR_PREFIXES)
def bind_data_modeling_log_context(team_id: int, saved_query_id: UUID | str) -> None:
@@ -218,10 +233,7 @@ def maybe_suspend_node_for_engine(
# not the model the customer reads.
if str(engine) == DataModelingJobEngine.CLICKHOUSE.value:
job = DataModelingJob.objects.get(id=job_id)
- job.error = (
- f"This model has been suspended after {CONSECUTIVE_FAILURES_TO_SUSPEND} consecutive failed "
- f"materializations. Error: {job.error}"
- )
+ job.error = f"{SUSPENDED_ERROR_PREFIX}{job.error}"
job.save(update_fields=["error"])
return True
diff --git a/posthog/temporal/tests/common/test_asyncpa.py b/posthog/temporal/tests/common/test_asyncpa.py
index 2a51e9b0d3ff..663db9f95a59 100644
--- a/posthog/temporal/tests/common/test_asyncpa.py
+++ b/posthog/temporal/tests/common/test_asyncpa.py
@@ -1,6 +1,7 @@
import io
import random
import string
+import asyncio
import collections.abc
import pytest
@@ -133,3 +134,18 @@ async def test_record_batch_reader_resumes_from_byte_offset(batches_before_resum
batches_resumed = [batch async for batch in resumed_reader]
assert batches_resumed == batches[batches_before_resume:]
+
+
+async def test_message_reader_stops_waiting_for_a_stalled_error_tail(monkeypatch):
+ async def stalled_stream():
+ yield b"Code: 241. DB::Exception: an error"
+ await asyncio.Event().wait()
+ yield b""
+
+ monkeypatch.setattr(asyncpa, "UNPARSED_READ_TIMEOUT_SECONDS", 0.1)
+ reader = asyncpa.AsyncMessageReader(stalled_stream())
+
+ with pytest.raises(asyncpa.InvalidMessageFormat) as exc_info:
+ await asyncio.wait_for(reader.read_next_message(), timeout=5)
+
+ assert exc_info.value.unparsed == b"Code: 241. DB::Exception: an error"
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 dbd1023048b9..17f867926037 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -808,6 +808,10 @@ class TestNodeSuspension:
"QueueEmpty: Application error",
"Preempted: a new DAG run started before this job completed",
"Not published: 2 data quality checks failed. The previous version keeps serving until the checks pass.",
+ "InvalidMessageFormat: Arrow stream contains bytes that are not an IPC message: 'garbage'",
+ "InvalidMessageFormat: Encapsulated IPC message format must begin with continuation bytes, received: 'b'",
+ "This model has been suspended after 5 consecutive failed materializations. "
+ "Error: InvalidMessageFormat: Arrow stream contains bytes that are not an IPC message: 'garbage'",
],
)
async def test_externally_aborted_failures_do_not_suspend(self, ateam, anode, asaved_query, adag, aborted_error):
@@ -840,7 +844,16 @@ class TestNodeSuspension:
for job in jobs:
await database_sync_to_async(job.delete)()
- @pytest.mark.parametrize("identifier", ["Preempted", "QueueEmpty", "ProxyConnectionError"])
+ @pytest.mark.parametrize(
+ "identifier",
+ [
+ "Preempted",
+ "QueueEmpty",
+ "ProxyConnectionError",
+ "InvalidMessageFormat: Arrow stream contains bytes that are not an IPC message: ",
+ "InvalidMessageFormat: Encapsulated IPC message format must begin with continuation bytes, received: ",
+ ],
+ )
async def test_suspends_when_a_customer_identifier_spells_an_abort_marker(
self, ateam, anode, asaved_query, adag, identifier
):
diff --git a/posthog/temporal/tests/test_clickhouse.py b/posthog/temporal/tests/test_clickhouse.py
index e7cdc3520532..c9c361d0d6f4 100644
--- a/posthog/temporal/tests/test_clickhouse.py
+++ b/posthog/temporal/tests/test_clickhouse.py
@@ -5,9 +5,13 @@ import datetime as dt
import contextlib
import pytest
-from unittest.mock import MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import aiohttp
+import pyarrow as pa
from posthog.clickhouse.query_tagging import QueryTags
+from posthog.temporal.common.asyncpa import InvalidMessageFormat
from posthog.temporal.common.clickhouse import (
ClickHouseAllReplicasAreStaleError,
ClickHouseCheckQueryStatusError,
@@ -560,6 +564,149 @@ async def test_stream_query_as_jsonl_handles_whitespace_only_lines(clickhouse_cl
assert results[2] == {"id": 3}
+class _FakeStreamReader:
+ def __init__(self, data: bytes, chunk_size: int = 64) -> None:
+ self._chunks = [data[i : i + chunk_size] for i in range(0, len(data), chunk_size)]
+
+ async def readchunk(self) -> tuple[bytes, bool]:
+ if self._chunks:
+ return self._chunks.pop(0), True
+ return b"", False
+
+ def at_eof(self) -> bool:
+ return not self._chunks
+
+
+_MEMORY_LIMIT_ERROR = (
+ "Code: 241. DB::Exception: Query memory limit exceeded: would use 10.00 GiB, maximum: 10.00 GiB. "
+ "(MEMORY_LIMIT_EXCEEDED) (version x.x.x.x (official build))"
+)
+_STD_EXCEPTION_ERROR = (
+ "std::exception. Code: 1001, type: std::bad_alloc, e.what() = std::bad_alloc (version x.x.x.x (official build))"
+)
+_POCO_EXCEPTION_ERROR = (
+ "Poco::Exception. Code: 1000, e.code() = 32, e.displayText() = Broken pipe (version x.x.x.x (official build))"
+)
+_MISSING_COLUMN_ERROR = (
+ "Code: 47. DB::Exception: Missing columns: '__exception__' while processing query. "
+ "(UNKNOWN_IDENTIFIER) (version x.x.x.x (official build))"
+)
+
+
+ "tail,expected_exception,expected_message",
+ [
+ (f"{_MEMORY_LIMIT_ERROR}\n".encode(), ClickHouseMemoryLimitExceededError, _MEMORY_LIMIT_ERROR),
+ (
+ f"\r\n__exception__\r\nabcdefgh\r\n{_MEMORY_LIMIT_ERROR}\r\n{len(_MEMORY_LIMIT_ERROR)} abcdefgh\r\n__exception__\r\n".encode(),
+ ClickHouseMemoryLimitExceededError,
+ _MEMORY_LIMIT_ERROR,
+ ),
+ (
+ f"{_MISSING_COLUMN_ERROR}\n".encode(),
+ ClickHouseError,
+ _MISSING_COLUMN_ERROR,
+ ),
+ (f"{_STD_EXCEPTION_ERROR}\n".encode(), ClickHouseError, _STD_EXCEPTION_ERROR),
+ (
+ f"\r\n__exception__\r\nabcdefgh\r\n{_STD_EXCEPTION_ERROR}\r\n{len(_STD_EXCEPTION_ERROR)} abcdefgh\r\n__exception__\r\n".encode(),
+ ClickHouseError,
+ _STD_EXCEPTION_ERROR,
+ ),
+ (f"{_POCO_EXCEPTION_ERROR}\n".encode(), ClickHouseError, _POCO_EXCEPTION_ERROR),
+ (b"not an arrow message and not an error", InvalidMessageFormat, None),
+ ],
+ ids=[
+ "plain_error_tail",
+ "wrapped_error_tail",
+ "error_names_the_wrapper_token",
+ "plain_std_exception_tail",
+ "wrapped_std_exception_tail",
+ "plain_poco_exception_tail",
+ "no_error_in_tail",
+ ],
+)
+async def test_astream_query_as_arrow_raises_error_appended_to_stream(
+ clickhouse_client, tail, expected_exception, expected_message
+):
+ batch = pa.RecordBatch.from_pylist([{"id": i} for i in range(10)])
+ sink = pa.BufferOutputStream()
+ writer = pa.ipc.new_stream(sink, batch.schema)
+ writer.write_batch(batch)
+ # A failed query never writes the end-of-stream marker, so the error follows the last batch.
+ data = sink.getvalue().to_pybytes() + tail
+
+ mock_response = MagicMock()
+ mock_response.content = _FakeStreamReader(data)
+
+ @contextlib.asynccontextmanager
+ async def mock_post(*args, **kwargs):
+ yield mock_response
+
+ batches = []
+ with patch.object(clickhouse_client, "apost_query", mock_post):
+ with pytest.raises(expected_exception) as exc_info:
+ async for record_batch in clickhouse_client.astream_query_as_arrow("SELECT 1", query_id="test-query"):
+ batches.append(record_batch)
+
+ assert batches == [batch]
+ if expected_message is not None:
+ assert str(exc_info.value) == expected_message
+ assert exc_info.value.query_id == "test-query"
+
+
+class _TruncatedStreamReader(_FakeStreamReader):
+ async def readchunk(self) -> tuple[bytes, bool]:
+ if self._chunks:
+ return await super().readchunk()
+ raise aiohttp.ClientPayloadError("Response payload is not completed")
+
+
+_TIMEOUT_ERROR = (
+ "Code: 159. DB::Exception: Timeout exceeded: elapsed 600001 ms, maximum: 600000 ms. "
+ "(TIMEOUT_EXCEEDED) (version x.x.x.x (official build))"
+)
+
+
+ "query_log_rows,expected_exception",
+ [
+ ([{"type": "ExceptionWhileProcessing", "exception": _TIMEOUT_ERROR}], ClickHouseQueryTimeoutError),
+ ([], aiohttp.ClientPayloadError),
+ ],
+ ids=["query_log_has_the_error", "query_log_has_no_row"],
+)
+async def test_astream_query_as_arrow_reads_query_log_when_the_response_is_cut(
+ clickhouse_client, query_log_rows, expected_exception
+):
+ batch = pa.RecordBatch.from_pylist([{"id": i} for i in range(10)])
+ sink = pa.BufferOutputStream()
+ writer = pa.ipc.new_stream(sink, batch.schema)
+ writer.write_batch(batch)
+
+ mock_response = MagicMock()
+ mock_response.content = _TruncatedStreamReader(sink.getvalue().to_pybytes())
+ posted_query_ids = []
+
+ @contextlib.asynccontextmanager
+ async def mock_post(*args, query_id=None, **kwargs):
+ posted_query_ids.append(query_id)
+ yield mock_response
+
+ read_query_log = AsyncMock(return_value=query_log_rows)
+ with (
+ patch.object(clickhouse_client, "apost_query", mock_post),
+ patch.object(clickhouse_client, "read_query_as_jsonl", read_query_log),
+ patch("posthog.temporal.common.clickhouse.QUERY_LOG_LOOKUP_INTERVAL_SECONDS", 0),
+ ):
+ with pytest.raises(expected_exception):
+ async for _ in clickhouse_client.astream_query_as_arrow("SELECT 1"):
+ pass
+
+ assert posted_query_ids[0] is not None
+ assert read_query_log.call_args.kwargs["query_parameters"]["query_id"] == posted_query_ids[0]
+
+
async def test_apost_query_sends_external_tables(clickhouse_client, django_db_setup):
table = {
"name": "_jev_result",