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): refuse duplicate output column names (#93036)

Jovan Sakovicfdf71fbfc99d
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.py
index 5480cca65d5a..bf3fbf10b155 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view.py
@@ -24,6 +24,7 @@ from posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast
from posthog.hogql.visitor import CloningVisitor
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.models import Team
from posthog.ph_client import feature_enabled_or_false
@@ -34,6 +35,7 @@ from posthog.temporal.common.clickhouse import (
ClickHouseError,
get_client as get_clickhouse_client,
)
+from posthog.temporal.common.errors import NonReportableError
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_logger
from posthog.temporal.data_modeling.activities.incremental_write import (
@@ -112,9 +114,17 @@ def _print_untouched(
return print_prepared_ast(prepared_query, context=context, dialect="clickhouse", settings=settings, stack=[])
+@frozen
+class _DescribedColumn:
+ name: str
+ ch_type: str
+
+
async def _describe_columns(
printed: str, query_parameters: dict[str, typing.Any], query_settings: dict[str, str] | None
-) -> dict[str, str]:
+) -> list[_DescribedColumn]:
+ """A select list is ordered and may repeat a name, so the probe returns a list, not a mapping.
+ `_reject_duplicate_output_columns` is what turns a repeat into a readable error."""
async with _clickhouse_query_semaphore, get_clickhouse_client() as client:
async with client.apost_query(
query=f"DESCRIBE TABLE ({printed}) FORMAT TabSeparatedRaw",
@@ -123,13 +133,32 @@ async def _describe_columns(
settings=query_settings,
) as ch_response:
table_describe_response = await ch_response.content.read()
- columns: dict[str, str] = {}
+ columns: list[_DescribedColumn] = []
for line in table_describe_response.decode("utf-8").splitlines():
column_name, ch_type = line.strip().split("\t")
- columns[column_name] = ch_type
+ columns.append(_DescribedColumn(name=column_name, ch_type=ch_type))
return columns
+def _reject_duplicate_output_columns(columns: list[_DescribedColumn]) -> None:
+ # Folded because Delta compares field names without case, so `userId` beside `userid` is as
+ # unwritable as a literal repeat. Left to the write, that pair costs a full scan first.
+ first_spelling: dict[str, str] = {}
+ duplicates: list[str] = []
+ seen_duplicates: set[str] = set()
+ for column in columns:
+ folded = column.name.lower()
+ if folded in first_spelling:
+ for spelling in (first_spelling[folded], column.name):
+ if spelling not in seen_duplicates:
+ seen_duplicates.add(spelling)
+ duplicates.append(spelling)
+ else:
+ first_spelling[folded] = column.name
+ if duplicates:
+ raise DuplicateOutputColumnError(duplicates)
+
+
CLICKHOUSE_MAX_BLOCK_SIZE_ROWS = 50 * 1000
DELTA_TABLE_RETENTION_HOURS = 24
@@ -157,6 +186,21 @@ class EmptyHogQLResponseColumnsError(Exception):
super().__init__("After running a HogQL query, no columns were returned")
+class DuplicateOutputColumnError(NonReportableError):
+ """Both consumers of the probe address a column by name: the type wrapper rebuilds the select
+ list from it, and the arrow transform looks it up on the batch. Neither can say which of two
+ same-named columns is meant, so the repeat is refused rather than resolved arbitrarily."""
+
+ def __init__(self, duplicates: list[str]) -> None:
+ names = ", ".join(f'"{name}"' for name in duplicates)
+ super().__init__(
+ f"The query returns more than one column named {names}. "
+ "Names that differ only by case count as duplicates. "
+ "Give each output column a unique name, for example with an alias."
+ )
+ self.duplicates = duplicates
+
+
def _incremental_enabled(team_id: int) -> bool:
"""Fails closed: a flag-service outage produces a full refresh, which costs money but is
never wrong."""
@@ -609,12 +653,14 @@ async def hogql_table(
untouched = await database_sync_to_async_pool(_print_untouched)(prepared_hogql_query, context, settings)
described_columns = await _describe_columns(untouched, context.values, None)
+ _reject_duplicate_output_columns(described_columns)
+
query_typings: list[tuple[str, str, tuple[str, tuple[ast.Constant, ...]] | None]] = []
- for column_name, ch_type in described_columns.items():
- if _needs_conversion(ch_type):
- query_typings.append((column_name, ch_type, get_call_tuple(ch_type)))
+ for column in described_columns:
+ if _needs_conversion(column.ch_type):
+ query_typings.append((column.name, column.ch_type, get_call_tuple(column.ch_type)))
else:
- query_typings.append((column_name, ch_type, None))
+ query_typings.append((column.name, column.ch_type, None))
has_type_to_convert = any(call_tuple is not None for _, _, call_tuple in query_typings)
if has_type_to_convert:
diff --git a/posthog/temporal/data_modeling/workflows/materialize_view.py b/posthog/temporal/data_modeling/workflows/materialize_view.py
index 15eb86720d8f..67964172ffb5 100644
--- a/posthog/temporal/data_modeling/workflows/materialize_view.py
+++ b/posthog/temporal/data_modeling/workflows/materialize_view.py
@@ -99,6 +99,7 @@ NON_RETRYABLE_ERRORS = [
"InvalidNodeTypeException",
"NodeNotFoundException",
"EmptyHogQLResponseColumnsError",
+ "DuplicateOutputColumnError",
]
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 24b3034474a0..5904cbefd0f7 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -22,6 +22,7 @@ from posthog.hogql.resolver import ResolverFactory
from posthog.models import Team, User
from posthog.sync import database_sync_to_async
from posthog.temporal.common.clickhouse import ClickHouseError
+from posthog.temporal.common.errors import NonReportableError
from posthog.temporal.data_modeling.activities import (
CreateDataModelingJobInputs,
FailMaterializationInputs,
@@ -38,6 +39,7 @@ from posthog.temporal.data_modeling.activities import (
)
from posthog.temporal.data_modeling.activities.materialize_view import (
LOGGER,
+ DuplicateOutputColumnError,
EmptyHogQLResponseColumnsError,
InvalidNodeTypeException,
get_aws_storage_options,
@@ -1723,6 +1725,44 @@ class TestHogqlTableDescribeSettings:
assert batches[0][1] == [("distinct_id", "String")]
+class TestHogqlTableDuplicateOutputColumns:
+ @pytest.mark.parametrize(
+ ("describe_body", "expected_duplicates"),
+ [
+ pytest.param(b"event\tDateTime\nevent\tDateTime\n", ["event"], id="type-the-wrapper-converts"),
+ pytest.param(b"event\tString\nevent\tString\n", ["event"], id="type-the-wrapper-leaves-alone"),
+ # Delta refuses these at the write, so the scan they would cost is wasted either way
+ pytest.param(b"event\tString\nEvent\tString\n", ["event", "Event"], id="names-differing-only-by-case"),
+ ],
+ )
+ async def test_a_repeated_output_name_is_refused_before_the_query_runs(
+ self, ateam: Team, describe_body: bytes, expected_duplicates: list[str]
+ ) -> None:
+ client = _EmptyArrowClient(pa.schema([pa.field("event", pa.string())]))
+ client.describe_body = describe_body
+
+ @contextlib.asynccontextmanager
+ async def fake_get_client(**kwargs: Any) -> AsyncIterator[_EmptyArrowClient]:
+ yield client
+
+ # selecting a column on top of an asterisk that already includes it, which the resolver
+ # allows through where an explicit `x AS a, y AS a` is refused as a redefined alias
+ with (
+ unittest.mock.patch(
+ "posthog.temporal.data_modeling.activities.materialize_view.get_clickhouse_client", fake_get_client
+ ),
+ pytest.raises(DuplicateOutputColumnError) as error,
+ ):
+ _ = [batch async for batch in hogql_table("SELECT *, event FROM events", ateam, LOGGER.bind())]
+
+ assert error.value.duplicates == expected_duplicates
+ for name in expected_duplicates:
+ assert f'"{name}"' in str(error.value)
+ assert client.arrow_query_calls == 0
+ # a broken saved query is the customer's to fix, so the refusal must not reach error tracking
+ assert isinstance(error.value, NonReportableError)
+
+
class _SlowDescribeClient(_EmptyArrowClient):
describe_body = b"ts\tDateTime\n"