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(clickhouse): classify query-log errors like errors returned over HTTP (#83259)

Rossac631c02f5ab
diff --git a/posthog/temporal/common/clickhouse.py b/posthog/temporal/common/clickhouse.py
index d37a33b6b593..a00353749e4f 100644
--- a/posthog/temporal/common/clickhouse.py
+++ b/posthog/temporal/common/clickhouse.py
@@ -386,7 +386,9 @@ class ClickHouseClient:
return request_data
@staticmethod
- def raise_clickhouse_error(error_message: str, query: str | None = None) -> typing.NoReturn:
+ def raise_clickhouse_error(
+ error_message: str, query: str | None = None, query_id: str | None = None
+ ) -> typing.NoReturn:
"""Raise the appropriate ClickHouseError subclass based on the error message."""
ERROR_CODE_TO_EXCEPTION: dict[str, type[ClickHouseError]] = {
"ALL_REPLICAS_ARE_STALE": ClickHouseAllReplicasAreStaleError,
@@ -398,8 +400,8 @@ class ClickHouseClient:
}
for error_code, exc_class in ERROR_CODE_TO_EXCEPTION.items():
if error_code in error_message:
- raise exc_class(error_message, query=query)
- raise ClickHouseError(error_message, query=query)
+ raise exc_class(error_message, query=query, query_id=query_id)
+ raise ClickHouseError(error_message, query=query, query_id=query_id)
async def acheck_response(self, response, query) -> None:
"""Asynchronously check the HTTP response received from ClickHouse."""
@@ -764,8 +766,11 @@ class ClickHouseClient:
elif "ExceptionWhileProcessing" in events or "ExceptionBeforeStart" in events:
if raise_on_error:
error_message = error or f"Unknown query error in query with ID: {query_id}"
- # we don't have the original query here so just use the query id
- raise ClickHouseError(error_message, query_id=query_id)
+ # The query log's `exception` column holds the same text ClickHouse returns over
+ # HTTP, so classify it the same way for consistency. Otherwise, the exception a
+ # caller sees for a query result we fetch from the query log would differ from that
+ # they would get running the query and waiting for the result.
+ self.raise_clickhouse_error(error_message, query_id=query_id)
return ClickHouseQueryStatus.ERROR
elif "QueryStart" in events:
diff --git a/posthog/temporal/tests/test_clickhouse.py b/posthog/temporal/tests/test_clickhouse.py
index 2e3d10f1549c..c4ff40671d58 100644
--- a/posthog/temporal/tests/test_clickhouse.py
+++ b/posthog/temporal/tests/test_clickhouse.py
@@ -340,6 +340,31 @@ async def test_acheck_query_in_query_log_cancelled(clickhouse_client, django_db_
await _wait_for_query_status(clickhouse_client, query_id, ClickHouseQueryStatus.ERROR, raise_on_error=True)
+async def test_acheck_query_in_query_log_classifies_the_error(clickhouse_client, django_db_setup):
+ """A failure recovered from the query log is classified like one returned over HTTP.
+
+ A caller that waits out a query which outlived its client timeout reads the failure from the
+ query log instead of the response. Both carry the same error text, so both must yield the same
+ exception class: otherwise whether a caller sees `ClickHouseMemoryLimitExceededError` or a bare
+ `ClickHouseError` depends on how long the query happened to take.
+ """
+ query_id = f"test-memory-limit-query-{uuid.uuid4()}"
+
+ with pytest.raises(ClickHouseMemoryLimitExceededError) as direct:
+ await clickhouse_client.execute_query_with_summary(
+ "SELECT groupArray(toString(number)) FROM numbers(10000000)",
+ query_id=query_id,
+ settings={"max_memory_usage": "1000000"},
+ )
+
+ with pytest.raises(ClickHouseMemoryLimitExceededError) as from_query_log:
+ await _wait_for_query_status(clickhouse_client, query_id, ClickHouseQueryStatus.ERROR)
+
+ assert "MEMORY_LIMIT_EXCEEDED" in str(direct.value)
+ assert "MEMORY_LIMIT_EXCEEDED" in str(from_query_log.value)
+ assert from_query_log.value.query_id == query_id
+
+
async def test_acheck_query_in_query_log_not_found(clickhouse_client, django_db_setup):
"""Test that acheck_query_in_query_log raises ClickHouseQueryNotFound for non-existent queries."""
non_existent_query_id = f"test-non-existent-query-{uuid.uuid4()}"