: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(hogai): render SQL NULL as (null) instead of "None" for LLMs (#76854)
Lucas Faria9d09f9bdbc84
diff --git a/ee/hogai/context/insight/format/__init__.py b/ee/hogai/context/insight/format/__init__.pyindex 0e55ae15eda9..a9c3d5daf899 100644--- a/ee/hogai/context/insight/format/__init__.py+++ b/ee/hogai/context/insight/format/__init__.py@@ -29,7 +29,7 @@ from .funnel import FunnelResultsFormatterfrom .lifecycle import LifecycleResultsFormatterfrom .paths import PathsResultsFormatterfrom .retention import RetentionResultsFormatter-from .sql import TRUNCATED_MARKER, SQLResultsFormatter+from .sql import NULL_MARKER, TRUNCATED_MARKER, SQLResultsFormatterfrom .stickiness import StickinessResultsFormatterfrom .trends import TrendsResultsFormatter@@ -129,6 +129,7 @@ __all__ = ["StickinessResultsFormatter","TrendsResultsFormatter","TRUNCATED_MARKER",+ "NULL_MARKER","format_access_control_warnings","format_query_results_for_llm","format_warehouse_sync_warnings",diff --git a/ee/hogai/context/insight/format/sql.py b/ee/hogai/context/insight/format/sql.pyindex ceef0f0cb450..2c7a7ebac3b1 100644--- a/ee/hogai/context/insight/format/sql.py+++ b/ee/hogai/context/insight/format/sql.py@@ -3,6 +3,9 @@ from typing import Anyfrom posthog.schema import AssistantHogQLQuery, HogQLQueryTRUNCATED_MARKER = "...truncated"+# Must stay distinctive: query_executor detects it with a substring check over the whole formatted+# table (same way it detects TRUNCATED_MARKER), and an LLM must not mistake it for a data value.+NULL_MARKER = "(null)"class SQLResultsFormatter:@@ -31,8 +34,17 @@ class SQLResultsFormatter:def _format_cell(self, cell: Any) -> str:"""Format a single cell value, truncating large dicts/arrays or stringified JSON."""+ if cell is None:+ # Bare str(None) yields "None", which LLMs read as a value rather than as missing data.+ return NULL_MARKER+cell_str = str(cell)+ if cell_str == NULL_MARKER:+ # A real value that renders exactly like the marker would otherwise be indistinguishable+ # from SQL NULL, so the LLM would report present data as missing. Quote it instead.+ return f'"{NULL_MARKER}"'+# Check if it's a dict/list or a stringified JSON (starts with { or [)is_json_like = isinstance(cell, dict | list) or (isinstance(cell, str) and cell_str and cell_str[0] in ("{", "[")diff --git a/ee/hogai/context/insight/format/test/test_sql.py b/ee/hogai/context/insight/format/test/test_sql.pyindex 382074c31157..d23f818f3503 100644--- a/ee/hogai/context/insight/format/test/test_sql.py+++ b/ee/hogai/context/insight/format/test/test_sql.py@@ -4,7 +4,7 @@ from posthog.test.base import BaseTestfrom posthog.schema import AssistantHogQLQuery-from .. import TRUNCATED_MARKER, SQLResultsFormatter+from .. import NULL_MARKER, TRUNCATED_MARKER, SQLResultsFormatterclass TestSQLResultsFormatter(BaseTest):@@ -47,7 +47,31 @@ class TestSQLResultsFormatter(BaseTest):columns = ["id", "name"]formatter = SQLResultsFormatter(query, results, columns)- expected = "id|name\n1|test\n2|None"+ expected = f"id|name\n1|test\n2|{NULL_MARKER}"+ self.assertEqual(formatter.format(), expected)++ def test_format_none_is_distinguishable_from_the_string_none(self):+ query = AssistantHogQLQuery(query="SELECT id, name")+ results: list[Any] = [+ {"id": 1, "name": None},+ {"id": 2, "name": "None"},+ ]+ columns = ["id", "name"]++ formatter = SQLResultsFormatter(query, results, columns)+ expected = f"id|name\n1|{NULL_MARKER}\n2|None"+ self.assertEqual(formatter.format(), expected)++ def test_format_none_is_distinguishable_from_a_literal_marker_value(self):+ query = AssistantHogQLQuery(query="SELECT id, name")+ results: list[Any] = [+ {"id": 1, "name": None},+ {"id": 2, "name": NULL_MARKER},+ ]+ columns = ["id", "name"]++ formatter = SQLResultsFormatter(query, results, columns)+ expected = f'id|name\n1|{NULL_MARKER}\n2|"{NULL_MARKER}"'self.assertEqual(formatter.format(), expected)def test_format_with_numeric_values(self):diff --git a/ee/hogai/context/insight/prompts.py b/ee/hogai/context/insight/prompts.pyindex fc3c59abda36..d91c1d465202 100644--- a/ee/hogai/context/insight/prompts.py+++ b/ee/hogai/context/insight/prompts.py@@ -51,6 +51,9 @@ Do not copy the results table as the user sees it in the UI.{{#include_url_remin{{#has_truncated_values}}Some JSON/array values were truncated. You can write a more specific SQL query to explore individual properties or array elements if needed.{{/has_truncated_values}}+{{#has_null_values}}+Cells shown as `(null)` are SQL NULL: the column had no value for those rows, usually because the property is absent on that event. Treat them as missing data. Never report `(null)` as a value, and never conclude a property is set to "null" or "None" from them.+{{/has_null_values}}</system_reminder>""".strip()diff --git a/ee/hogai/context/insight/query_executor.py b/ee/hogai/context/insight/query_executor.pyindex 3760759e1c6e..5e32b6cafcda 100644--- a/ee/hogai/context/insight/query_executor.py+++ b/ee/hogai/context/insight/query_executor.py@@ -51,6 +51,7 @@ from posthog.rbac.user_access_control import UserAccessControlErrorfrom posthog.sync import database_sync_to_asyncfrom ee.hogai.context.insight.format import (+ NULL_MARKER,TRUNCATED_MARKER,BoxPlotResultsFormatter,FunnelResultsFormatter,@@ -630,6 +631,10 @@ async def execute_and_format_query(has_truncated_values = isinstance(query, AssistantHogQLQuery | HogQLQuery | DataVisualizationNode) and (TRUNCATED_MARKER in results and not used_fallback)+ # Check if SQL results contain null values+ has_null_values = isinstance(query, AssistantHogQLQuery | HogQLQuery | DataVisualizationNode) and (+ NULL_MARKER in results and not used_fallback+ )query_result = format_prompt_string(QUERY_RESULTS_PROMPT,@@ -640,6 +645,7 @@ async def execute_and_format_query(project_datetime_display=utc_now_datetime.astimezone(team.timezone_info).strftime("%Y-%m-%d %H:%M:%S"),project_timezone=team.timezone_info.tzname(utc_now_datetime),has_truncated_values=has_truncated_values,+ has_null_values=has_null_values,sql_query=True if isinstance(query, AssistantHogQLQuery | HogQLQuery | DataVisualizationNode) else None,)