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.

feat(hogql): forward language service metadata notices (#105069)

Paweł Szczur5dcd570a316c
diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.md
index 9054bb05c864..d48784ea5e1a 100644
--- a/docs/internal/hogql-language-service.md
+++ b/docs/internal/hogql-language-service.md
@@ -415,10 +415,13 @@ Metadata also uses Python when `variables` is not null or `debug` is true.
Expression languages and non-`HogQLQuery` source contexts remain on Python because they can require surrounding query resolution.
Service failures preserve the original request, including its source context, for Python fallback.
-Go metadata returns diagnostics and logical table names, not the full Python compiler metadata.
+Go metadata returns diagnostics, logical table names, and source-positioned notices for resolved table and field references, not the full Python compiler metadata.
`indexUsage: true` does not force Python fallback or enable index analysis in Go.
-Go-backed Django responses leave `index_usage`, `isUsingIndices`, and `ch_table_names` unset, and return an empty `notices` list until the adapter forwards service notices.
-Python-only heuristic warnings, type notices, and actionable index warnings are not added to a successful Go response.
+Go responses leave `index_usage`, `isUsingIndices`, and `ch_table_names` unset.
+The Django adapter maps Go notices into the existing metadata `notices` list, which the editor displays as hints.
+Older service responses without a `notices` field remain valid and produce an empty list.
+Malformed notices use the same Python fallback and sanitized error reporting as malformed diagnostics.
+Python-only heuristic warnings and actionable index warnings are not added to a successful Go response.
Index analysis and compiler metadata parity remain separate follow-up work; this routing change does not add a second Python validation pass.
### Table and field notices
diff --git a/posthog/api/services/query.py b/posthog/api/services/query.py
index bf3c88e54262..69a8bf286a19 100644
--- a/posthog/api/services/query.py
+++ b/posthog/api/services/query.py
@@ -280,6 +280,10 @@ def _metadata_response_from_language_service(
body = language_result.body
if not isinstance(body.get("diagnostics"), list):
raise TypeError("diagnostics must be a list")
+ raw_notices = body.get("notices", [])
+ if not isinstance(raw_notices, list):
+ raise TypeError("notices must be a list")
+ query_length_utf16 = len(query.query.encode("utf-16-le", errors="surrogatepass")) // 2
errors: list[HogQLNotice] = []
warnings: list[HogQLNotice] = []
for diagnostic in body["diagnostics"]:
@@ -293,12 +297,33 @@ def _metadata_response_from_language_service(
warnings.append(notice)
else:
errors.append(notice)
+ notices: list[HogQLNotice] = []
+ for raw_notice in raw_notices:
+ if not isinstance(raw_notice, dict):
+ raise TypeError("notice must be an object")
+ message = raw_notice["message"]
+ start = raw_notice["start"]
+ end = raw_notice["end"]
+ fix = raw_notice.get("fix")
+ if (
+ not isinstance(message, str)
+ or not isinstance(start, int)
+ or isinstance(start, bool)
+ or not isinstance(end, int)
+ or isinstance(end, bool)
+ or start < 0
+ or end <= start
+ or end > query_length_utf16
+ or (fix is not None and not isinstance(fix, str))
+ ):
+ raise TypeError("invalid notice")
+ notices.append(HogQLNotice(message=message, start=start, end=end, fix=fix))
return HogQLMetadataResponse(
isValid=not errors,
query=query.query,
errors=errors,
warnings=warnings,
- notices=[],
+ notices=notices,
table_names=body.get("tableNames", []),
)
diff --git a/posthog/api/test/test_query_service.py b/posthog/api/test/test_query_service.py
index 41f3d4b8f8a5..049b2db3fb37 100644
--- a/posthog/api/test/test_query_service.py
+++ b/posthog/api/test/test_query_service.py
@@ -53,6 +53,7 @@ from posthog.api.services.query import (
_DatabaseSchemaCatalog,
_EditorAssistRoute,
_language_service_call,
+ _metadata_response_from_language_service,
_record_editor_assist_backend,
process_query_model,
)
@@ -72,6 +73,56 @@ from products.warehouse_sources.backend.facade.types import ExternalDataSourceTy
class TestLanguageServiceRouting(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "new_payload",
+ "SELECT '😀', event FROM events",
+ [
+ {"message": "Field 'event' is of type 'String'", "start": 13, "end": 18},
+ {"message": "Table 'events'", "start": 24, "end": 30},
+ ],
+ (13, 18),
+ (24, 30),
+ ),
+ (
+ "lone_surrogate",
+ "SELECT '\ud800', event FROM events",
+ [
+ {"message": "Field 'event' is of type 'String'", "start": 12, "end": 17},
+ {"message": "Table 'events'", "start": 23, "end": 29},
+ ],
+ (12, 17),
+ (23, 29),
+ ),
+ ("old_payload", "SELECT '😀', event FROM events", None, None, None),
+ ]
+ )
+ def test_metadata_maps_optional_notices_with_utf16_positions(
+ self,
+ _name: str,
+ query_text: str,
+ raw_notices: list[dict[str, object]] | None,
+ expected_field_span: tuple[int, int] | None,
+ expected_table_span: tuple[int, int] | None,
+ ) -> None:
+ query = HogQLMetadata(query=query_text, language=HogLanguage.HOG_QL)
+ body: dict[str, object] = {"valid": True, "diagnostics": [], "tableNames": ["events"]}
+ if raw_notices is not None:
+ body["notices"] = raw_notices
+ response = _metadata_response_from_language_service(
+ query, LanguageServiceResult(body=body, duration_seconds=0, response_size_bytes=0)
+ )
+
+ assert response.isValid is True
+ assert len(response.notices or []) == len(raw_notices or [])
+ if expected_field_span is not None:
+ assert response.notices[0].message == "Field 'event' is of type 'String'"
+ assert (response.notices[0].start, response.notices[0].end) == expected_field_span
+ assert response.notices[0].fix is None
+ assert response.notices[1].message == "Table 'events'"
+ assert (response.notices[1].start, response.notices[1].end) == expected_table_span
+
def test_served_backend_counter_is_exported_for_prometheus(self) -> None:
labels = {"operation": "metadata", "backend": "python", "reason": "service_error"}
before = REGISTRY.get_sample_value("hogql_editor_assist_responses_total", labels) or 0
@@ -351,7 +402,7 @@ class TestLanguageServiceRouting(SimpleTestCase):
@patch("posthog.api.services.query.EDITOR_ASSIST_RESPONSES_TOTAL")
@patch("posthog.api.services.query.is_language_service_enabled", return_value=True)
@patch("posthog.api.services.query.LanguageServiceClient")
- def test_hogql_metadata_with_source_context_uses_language_service_diagnostics(
+ def test_hogql_metadata_with_source_context_uses_language_service_result(
self,
_name: str,
source_query: HogQLQuery | None,
@@ -368,19 +419,23 @@ class TestLanguageServiceRouting(SimpleTestCase):
{
"code": "unknown_table",
"message": 'Unknown table "evnts"',
- "start": 14,
- "end": 19,
+ "start": 30,
+ "end": 35,
"suggestions": [{"label": "events", "distance": 1}],
}
],
- "tableNames": ["evnts"],
+ "notices": [
+ {"message": "Field 'event' is of type 'String'", "start": 7, "end": 12},
+ {"message": "Table 'events'", "start": 18, "end": 24},
+ ],
+ "tableNames": ["events", "evnts"],
},
duration_seconds=0.001,
response_size_bytes=128,
)
query = HogQLMetadata(
- query="SELECT * FROM evnts",
+ query="SELECT event FROM events JOIN evnts ON 1 = 1",
language=HogLanguage.HOG_QL,
sourceQuery=source_query,
indexUsage=index_usage,
@@ -398,8 +453,12 @@ class TestLanguageServiceRouting(SimpleTestCase):
assert response.isValid is False
assert response.errors[0].message == 'Unknown table "evnts"'
assert response.errors[0].fix == "events"
+ assert [(notice.message, notice.start, notice.end) for notice in response.notices] == [
+ ("Field 'event' is of type 'String'", 7, 12),
+ ("Table 'events'", 18, 24),
+ ]
assert response.query == query.query
- assert response.table_names == ["evnts"]
+ assert response.table_names == ["events", "evnts"]
assert response.index_usage is None
assert response.isUsingIndices is None
assert "timings" not in response.model_dump()
@@ -471,7 +530,22 @@ class TestLanguageServiceRouting(SimpleTestCase):
else:
capture_malformed.assert_called_once_with("metadata", malformed_stage)
- @parameterized.expand([("collection", {}), ("nested", [None])])
+ @parameterized.expand(
+ [
+ ("diagnostics_collection", {"diagnostics": {}}, "SELECT event FROM events"),
+ ("diagnostics_nested", {"diagnostics": [None]}, "SELECT event FROM events"),
+ ("notices_collection", {"notices": {}}, "SELECT event FROM events"),
+ ("notices_nested", {"notices": [None]}, "SELECT event FROM events"),
+ ("notices_missing_message", {"notices": [{"start": 7, "end": 12}]}, "SELECT event FROM events"),
+ ("notices_missing_start", {"notices": [{"message": "field", "end": 12}]}, "SELECT event FROM events"),
+ ("notices_missing_end", {"notices": [{"message": "field", "start": 7}]}, "SELECT event FROM events"),
+ (
+ "notices_out_of_range",
+ {"notices": [{"message": "field", "start": 7, "end": 999}]},
+ "SELECT event FROM events",
+ ),
+ ]
+ )
@patch("posthog.api.services.query._capture_malformed_language_service_response")
@patch("posthog.api.services.query.EDITOR_ASSIST_RESPONSES_TOTAL")
@patch("posthog.api.services.query.get_hogql_metadata")
@@ -480,7 +554,8 @@ class TestLanguageServiceRouting(SimpleTestCase):
def test_malformed_metadata_mapping_falls_back(
self,
_name: str,
- diagnostics: object,
+ payload: dict[str, object],
+ query_text: str,
client_class: MagicMock,
enabled: MagicMock,
python_metadata: MagicMock,
@@ -488,13 +563,13 @@ class TestLanguageServiceRouting(SimpleTestCase):
capture_malformed: MagicMock,
) -> None:
client_class.return_value.validate.return_value = LanguageServiceResult(
- body={"catalogRevision": "warehouse-aliases-v1:cached", "diagnostics": diagnostics},
+ body={"catalogRevision": "warehouse-aliases-v1:cached", "diagnostics": [], **payload},
duration_seconds=0,
response_size_bytes=0,
)
python_metadata.return_value = HogQLMetadataResponse(
isValid=True,
- query="SELECT event FROM events",
+ query=query_text,
errors=[],
warnings=[],
notices=[],
@@ -503,7 +578,7 @@ class TestLanguageServiceRouting(SimpleTestCase):
response = process_query_model(
cast(Team, SimpleNamespace(pk=12)),
- HogQLMetadata(query="SELECT event FROM events", language=HogLanguage.HOG_QL),
+ HogQLMetadata(query=query_text, language=HogLanguage.HOG_QL),
user=cast(User, SimpleNamespace(pk=34)),
)