: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(llma): keep AI string-ID properties as strings in property swapper (#66550)
posthog[bot]696cfe7ea297
diff --git a/posthog/hogql/context.py b/posthog/hogql/context.pyindex ae6a1e860286..b3e3e2c853b0 100644--- a/posthog/hogql/context.py+++ b/posthog/hogql/context.py@@ -80,6 +80,7 @@ class HogQLContext:output_format: str | None = None# Globals that will be resolved in the context of the queryglobals: Optional[dict] = None+ property_type_overrides: Optional[dict[str, str]] = None# Per-query data that query runners want to ingest into the HogQL resolution (e.g. pending updates# merged into a table via UNION ALL in error tracking).data_to_ingest: dict[str, Any] = field(default_factory=dict)diff --git a/posthog/hogql/transforms/property_types.py b/posthog/hogql/transforms/property_types.pyindex 169f92def992..c6c7431c0820 100644--- a/posthog/hogql/transforms/property_types.py+++ b/posthog/hogql/transforms/property_types.py@@ -84,12 +84,15 @@ def build_property_swapper(node: ast.AST, context: HogQLContext) -> None:else [])+ type_overrides = context.property_type_overrides or {}+event_properties: dict[str, dict[str, str | None]] = {}for prop_def in event_property_definitions:if not prop_def.property_type:continue- prop_info: dict[str, str | None] = {"type": prop_def.property_type}+ prop_type = type_overrides.get(prop_def.name, prop_def.property_type)+ prop_info: dict[str, str | None] = {"type": prop_type}slot = prop_def.materialized_column_slots.first()if slot:prop_info["dmat"] = f"{DMAT_STRING_COLUMN_NAME_PREFIX}{slot.slot_index}"diff --git a/posthog/hogql/transforms/test/test_property_types.py b/posthog/hogql/transforms/test/test_property_types.pyindex 179a26b8e79b..6b590d263c59 100644--- a/posthog/hogql/transforms/test/test_property_types.py+++ b/posthog/hogql/transforms/test/test_property_types.py@@ -538,6 +538,27 @@ class TestPropertyTypes(BaseTest):)assert printed == self._events_schema_snapshot()+ def test_property_type_override_beats_detected_type(self):+ PropertyDefinition.objects.get_or_create(+ team=self.team,+ type=PropertyDefinition.Type.EVENT,+ name="ts_like_id",+ defaults={"property_type": "DateTime"},+ )++ def _print(overrides: dict[str, str] | None) -> str:+ query, _ = prepare_and_print_ast(+ parse_select("select properties.ts_like_id from events"),+ HogQLContext(team_id=self.team.pk, enable_select_queries=True, property_type_overrides=overrides),+ "clickhouse",+ )+ return pretty_print_in_tests(query, self.team.pk)++ assert "parseDateTime64BestEffortOrNull" in _print(None)+ overridden = _print({"ts_like_id": "String"})+ assert "parseDateTime64BestEffortOrNull" not in overridden, overridden+ assert "toDateTime" not in overridden, overridden+@pytest.mark.usefixtures("unittest_snapshot")def test_resolve_property_types_person_raw(self):printed = self._print_select(diff --git a/posthog/hogql_queries/ai/ai_column_rewriter.py b/posthog/hogql_queries/ai/ai_column_rewriter.pyindex a13dfaddc64b..67724f79beef 100644--- a/posthog/hogql_queries/ai/ai_column_rewriter.py+++ b/posthog/hogql_queries/ai/ai_column_rewriter.py@@ -64,6 +64,22 @@ _RAW_JSON_COLUMNS: frozenset[str] = frozenset()_EVENTS_TABLE_ALIAS = "__ai_events_fallback"+# Forced String so detection can't coerce timestamp-/number-shaped IDs and break an exact match.+_STRING_ID_COLUMNS: frozenset[str] = frozenset(+ {+ "trace_id",+ "session_id",+ "parent_id",+ "span_id",+ "generation_id",+ "experiment_id",+ }+)++EVENTS_FALLBACK_PROPERTY_TYPE_OVERRIDES: dict[str, str] = {+ AI_COLUMN_TO_PROPERTY[col]: "String" for col in _STRING_ID_COLUMNS+}+class AiColumnToPropertyRewriter(CloningVisitor):"""Rewrites `ai_events` column references to `events` property references.diff --git a/posthog/hogql_queries/ai/ai_table_resolver.py b/posthog/hogql_queries/ai/ai_table_resolver.pyindex c0d7053f177d..7ecf4095d6ab 100644--- a/posthog/hogql_queries/ai/ai_table_resolver.py+++ b/posthog/hogql_queries/ai/ai_table_resolver.py@@ -9,7 +9,11 @@ from posthog.hogql.context import HogQLContextfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Product, tag_queries, tags_context-from posthog.hogql_queries.ai.ai_column_rewriter import rewrite_expr_for_events_table, rewrite_query_for_events_table+from posthog.hogql_queries.ai.ai_column_rewriter import (+ EVENTS_FALLBACK_PROPERTY_TYPE_OVERRIDES,+ rewrite_expr_for_events_table,+ rewrite_query_for_events_table,+)from posthog.hogql_queries.ai.ai_property_rewriter import rewrite_expr_for_ai_events_tablefrom posthog.models.event.new_events_schema import use_new_events_schemafrom posthog.ph_client import feature_enabled_or_false@@ -123,20 +127,26 @@ def query_ai_events(events_schema = use_new_events_schema(team.pk)events_query = rewrite_query_for_events_table(query)- events_placeholders = {key: rewrite_expr_for_events_table(value) for key, value in placeholders.items()}- kwargs["context"] = HogQLContext(team_id=team.pk, use_new_events_schema=events_schema)+ events_placeholders = {k: rewrite_expr_for_events_table(v) for k, v in placeholders.items()}+ events_kwargs = {+ **kwargs,+ "context": HogQLContext(+ team_id=team.pk,+ use_new_events_schema=events_schema,+ property_type_overrides=EVENTS_FALLBACK_PROPERTY_TYPE_OVERRIDES,+ ),+ }if fall_back_to_events:tag_queries(ai_query_source="shared_table_fallback")AI_EVENTS_QUERY_TOTAL.labels(source="shared_table_fallback").inc()with AI_EVENTS_QUERY_DURATION_SECONDS.labels(source="shared_table_fallback").time():- result = execute_hogql_query(query=events_query, placeholders=events_placeholders, **kwargs)- return result+ return execute_hogql_query(query=events_query, placeholders=events_placeholders, **events_kwargs)# The caller can't use heavy-column-stripped events rows, so probe events solely to# tell "aged past the TTL" apart from "never existed" and raise the matching error.with AI_EVENTS_QUERY_DURATION_SECONDS.labels(source="retention_probe").time():- probe = execute_hogql_query(query=events_query, placeholders=events_placeholders, **kwargs)+ probe = execute_hogql_query(query=events_query, placeholders=events_placeholders, **events_kwargs)if probe.results:tag_queries(ai_query_source="expired")AI_EVENTS_QUERY_TOTAL.labels(source="expired").inc()diff --git a/posthog/hogql_queries/ai/test/test_ai_property_rewriter.py b/posthog/hogql_queries/ai/test/test_ai_property_rewriter.pyindex b6a1f621aa07..b241bf3058f5 100644--- a/posthog/hogql_queries/ai/test/test_ai_property_rewriter.py+++ b/posthog/hogql_queries/ai/test/test_ai_property_rewriter.py@@ -3,9 +3,22 @@ import pytestfrom posthog.hogql import astfrom posthog.hogql.parser import parse_select+from posthog.hogql_queries.ai.ai_column_rewriter import (+ _STRING_ID_COLUMNS,+ AI_COLUMN_TO_PROPERTY,+ EVENTS_FALLBACK_PROPERTY_TYPE_OVERRIDES,+)from posthog.hogql_queries.ai.ai_property_rewriter import AiPropertyRewriter, _rewrite_property_field+class TestEventsFallbackPropertyTypeOverrides:+ def test_overrides_force_string_for_each_string_id_column(self):+ assert _STRING_ID_COLUMNS <= set(AI_COLUMN_TO_PROPERTY), _STRING_ID_COLUMNS - set(AI_COLUMN_TO_PROPERTY)+ assert EVENTS_FALLBACK_PROPERTY_TYPE_OVERRIDES == {+ AI_COLUMN_TO_PROPERTY[col]: "String" for col in _STRING_ID_COLUMNS+ }++class TestRewritePropertyField:def test_simple_ai_property(self):result = _rewrite_property_field(["properties", "$ai_trace_id"])