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-warehouse): describe warehouse columns by hogql-visible name (#67417)

Tom Owersf64ce19d0ca4
diff --git a/products/warehouse_sources/backend/models/external_table_definitions.py b/products/warehouse_sources/backend/models/external_table_definitions.py
index a4c36e30fd5a..976faca9f896 100644
--- a/products/warehouse_sources/backend/models/external_table_definitions.py
+++ b/products/warehouse_sources/backend/models/external_table_definitions.py
@@ -10,6 +10,7 @@ from posthog.hogql.database.models import (
StringDatabaseField,
StringJSONDatabaseField,
)
+from posthog.hogql.visitor import TraversingVisitor
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEY
@@ -1464,3 +1465,57 @@ def get_dlt_mapping_for_external_table(table):
for _, field in external_tables[table].items()
if type(field) is not ast.ExpressionField
}
+
+
+class _SingleFieldChainCollector(TraversingVisitor):
+ """Collects the single-segment field references (e.g. `__created`) inside an expression."""
+
+ def __init__(self) -> None:
+ self.names: set[str] = set()
+
+ def visit_field(self, node: ast.Field) -> None:
+ if len(node.chain) == 1 and isinstance(node.chain[0], str):
+ self.names.add(node.chain[0])
+
+
+def get_hogql_column_name_mapping(table_name_without_prefix: str) -> dict[str, str]:
+ """Map each raw synced column name to the HogQL-visible field name it surfaces as.
+
+ Curated sources (Stripe, etc.) rename or wrap some raw columns when exposing them via HogQL — for
+ example Stripe's `customer` -> `customer_id` (a direct rename) and `created` -> `created_at` (a
+ computed `ExpressionField` over the hidden `__created` column). Anything downstream that keys off
+ column names — the user-facing column list, and semantic enrichment, which stores annotations that
+ users and the AI agent read back by the *visible* name — needs this raw -> visible mapping. Returns
+ `{}` for tables with no curated definition (arbitrary SQL sources), where raw columns are exposed
+ unchanged.
+ """
+ fields = external_tables.get(table_name_without_prefix)
+ if not fields:
+ return {}
+
+ # Hidden plain fields carry the raw column name (`__created` -> raw `created`) but are never
+ # surfaced directly; a visible ExpressionField wraps them.
+ hidden_raw_by_key = {
+ key: field.name
+ for key, field in fields.items()
+ if isinstance(field, DatabaseField) and not isinstance(field, ast.ExpressionField) and field.hidden
+ }
+
+ mapping: dict[str, str] = {}
+ # ExpressionFields first: attribute the raw column behind each referenced hidden field to the
+ # expression's visible name (`created` -> `created_at`).
+ for key, field in fields.items():
+ if isinstance(field, ast.ExpressionField):
+ collector = _SingleFieldChainCollector()
+ collector.visit(field.expr)
+ for referenced in collector.names:
+ raw = hidden_raw_by_key.get(referenced)
+ if raw is not None:
+ mapping[raw] = key
+ # Visible plain fields: direct renames (`customer` -> `customer_id`). Don't override an
+ # expression mapping already established for the same raw column.
+ for key, field in fields.items():
+ if isinstance(field, DatabaseField) and not isinstance(field, ast.ExpressionField) and not field.hidden:
+ mapping.setdefault(field.name, key)
+
+ return mapping
diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.py
index d8a417ff2eaf..e89a53333f4b 100644
--- a/products/warehouse_sources/backend/models/table.py
+++ b/products/warehouse_sources/backend/models/table.py
@@ -53,7 +53,7 @@ from products.warehouse_sources.backend.models.util import (
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEY
from .credential import DataWarehouseCredential
-from .external_table_definitions import external_tables
+from .external_table_definitions import external_tables, get_hogql_column_name_mapping
if TYPE_CHECKING:
from posthog.schema import HogQLQueryModifiers
@@ -208,7 +208,14 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
works for REST sources (Stripe, Hubspot, …) too — unlike the SQL-only
`ExternalDataSchema.schema_metadata`. Handles both the dict (`{"clickhouse": ...}`) and the
legacy plain-string column shapes.
+
+ Curated sources (Stripe, etc.) rename or wrap some raw columns when exposing them via HogQL
+ (`created` -> `created_at`, `customer` -> `customer_id`), so `name` is the HogQL-visible name
+ callers surface to users and the AI agent — not the raw synced column. To recover the raw ->
+ visible mapping (e.g. to match canonical descriptions keyed by raw name), call
+ `get_hogql_column_name_mapping(self.table_name_without_prefix())` directly.
"""
+ hogql_by_raw = get_hogql_column_name_mapping(self.table_name_without_prefix())
result: list[dict[str, Any]] = []
for name, definition in (self.columns or {}).items():
if name in HIDDEN_COLUMNS:
@@ -219,7 +226,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
clickhouse_type = definition or ""
result.append(
{
- "name": name,
+ "name": hogql_by_raw.get(name, name),
"data_type": clean_type(clickhouse_type) if clickhouse_type else "unknown",
"is_nullable": "Nullable(" in clickhouse_type,
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py
index efcea98533ec..797efd1b5270 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py
@@ -39,6 +39,7 @@ from posthog.temporal.common.logger import get_write_only_logger
from products.warehouse_sources.backend.models.column_annotation import WarehouseColumnAnnotation
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_table_definitions import get_hogql_column_name_mapping
from products.warehouse_sources.backend.models.table import DataWarehouseTable
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
get_canonical_descriptions_for_source,
@@ -434,11 +435,15 @@ def enrich_table_semantics_sync(team_id: int, schema_id: uuid.UUID) -> dict[str,
columns = columns[:MAX_COLUMNS_PER_TABLE]
foreign_keys = schema.foreign_keys or []
- # Curated, documentation-sourced descriptions the source ships for this endpoint, if any.
+ # Curated, documentation-sourced descriptions the source ships for this endpoint, if any. These are
+ # keyed by the raw source field name (`created`, `customer`); re-key them to the HogQL-visible name
+ # (`created_at`, `customer_id`) each column surfaces as, so the description lands on the column that
+ # `information_schema` and the AI agent actually see. Columns with no rename map to themselves.
+ hogql_name_by_raw = get_hogql_column_name_mapping(table.table_name_without_prefix())
canonical = get_canonical_descriptions_for_source(schema.source.source_type).get(schema.name, {})
canonical_columns = {
- name: description
- for name, description in (canonical.get("columns") or {}).items()
+ hogql_name_by_raw.get(raw_name, raw_name): description
+ for raw_name, description in (canonical.get("columns") or {}).items()
if isinstance(description, str) and description.strip()
}
canonical_table_description = canonical.get("description")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.py
index 96017f95e449..2db1155ecb6f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.py
@@ -481,6 +481,41 @@ class TestEnrichTableSemanticsSync:
assert annotations["amount"].description_source == WarehouseColumnAnnotation.DescriptionSource.CANONICAL
assert annotations["amount"].ai_model is None
+ def test_renamed_columns_are_annotated_under_hogql_visible_name(self):
+ # Stripe's HogQL layer renames some raw columns (`created` -> `created_at`, `customer` ->
+ # `customer_id`). Canonical descriptions are keyed by the raw name, but `information_schema`
+ # and the AI agent read annotations back by the visible name — so the annotation (and the LLM
+ # ask for whatever has no canonical entry) must land on the visible name, not the raw one.
+ team = _team()
+ schema, table = _make_schema(
+ team,
+ columns=[
+ {"name": "created", "data_type": "Int64", "is_nullable": False},
+ {"name": "customer", "data_type": "String", "is_nullable": True},
+ {"name": "payment_method", "data_type": "String", "is_nullable": True},
+ ],
+ )
+ canonical = {"Charge": {"columns": {"created": "Unix creation time.", "customer": "Customer ID."}}}
+ generated = {"columns": {"payment_method_id": "Payment method used."}}
+ with (
+ patch.object(enrich, "enrichment_enabled", return_value=True),
+ patch.object(enrich, "get_canonical_descriptions_for_source", return_value=canonical),
+ patch.object(enrich, "_get_business_context", return_value=""),
+ patch.object(enrich, "_generate_descriptions", return_value=(generated, _USAGE)) as mock_llm,
+ ):
+ result = enrich_table_semantics_sync(team.pk, schema.id)
+
+ assert result["status"] == "done"
+ annotations = _annotations(team, table)
+ # Canonical descriptions land on the HogQL-visible names, not the raw `created` / `customer`.
+ assert annotations["created_at"].description == "Unix creation time."
+ assert annotations["customer_id"].description == "Customer ID."
+ assert "created" not in annotations
+ assert "customer" not in annotations
+ # The un-canonical column is asked of the LLM — and stored — under its visible name too.
+ assert mock_llm.call_args.kwargs["columns_needing_description"] == ["payment_method_id"]
+ assert annotations["payment_method_id"].description == "Payment method used."
+
def test_ai_fills_columns_without_canonical_description(self):
team = _team()
schema, table = _make_schema(
diff --git a/products/warehouse_sources/backend/tests/test_external_table_definitions.py b/products/warehouse_sources/backend/tests/test_external_table_definitions.py
new file mode 100644
index 000000000000..0a6b7b21579e
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/test_external_table_definitions.py
@@ -0,0 +1,37 @@
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.models.external_table_definitions import get_hogql_column_name_mapping
+
+
+class TestGetHogqlColumnNameMapping:
+ @parameterized.expand(
+ [
+ # Direct renames (`StringDatabaseField(name="customer")` exposed as `customer_id`).
+ ("stripe_charge", "customer", "customer_id"),
+ ("stripe_charge", "invoice", "invoice_id"),
+ ("stripe_charge", "payment_intent", "payment_intent_id"),
+ ("stripe_charge", "balance_transaction", "balance_transaction_id"),
+ # Expression renames: raw column feeds a hidden `__created` field wrapped by a visible
+ # `created_at` ExpressionField — the mapping must resolve through the expression.
+ ("stripe_charge", "created", "created_at"),
+ ("stripe_invoice", "period_start", "period_start_at"),
+ ("stripe_invoice", "period_end", "period_end_at"),
+ ("stripe_creditnote", "voided_at", "voided_at"),
+ ("stripe_subscription", "latest_invoice", "latest_invoice_id"),
+ ]
+ )
+ def test_maps_raw_column_to_hogql_visible_name(self, table: str, raw: str, expected: str) -> None:
+ assert get_hogql_column_name_mapping(table)[raw] == expected
+
+ def test_non_renamed_columns_map_to_themselves(self) -> None:
+ mapping = get_hogql_column_name_mapping("stripe_charge")
+ assert mapping["amount"] == "amount"
+ assert mapping["currency"] == "currency"
+
+ def test_hidden_alias_field_is_never_a_target(self) -> None:
+ # Raw `created` must resolve to the visible `created_at`, never the hidden `__created` alias.
+ assert "__created" not in get_hogql_column_name_mapping("stripe_charge").values()
+
+ def test_unknown_table_returns_empty_mapping(self) -> None:
+ # Arbitrary SQL sources have no curated definition — raw names are exposed unchanged.
+ assert get_hogql_column_name_mapping("some_postgres_table") == {}