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(hogql): allow metadata with sql source context (#104263)

Paweł Szczur757c8eda67a5
diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.md
index 6c53782273e2..42df98535b1e 100644
--- a/docs/internal/hogql-language-service.md
+++ b/docs/internal/hogql-language-service.md
@@ -300,9 +300,20 @@ If publication fails or a catalog cannot represent the resolver result, Django u
Malformed HTTP payloads, incompatible revisions after refresh, and malformed autocomplete or validation mappings also use the Python path.
Malformed service responses produce a sanitized Error Tracking event without the SQL text, response body, user context, or original exception.
-Full-query HogQL autocomplete can use the language service when `sourceQuery` is absent or is a `HogQLQuery`; only the current editor SQL and cursor position are sent.
-Metadata requests still require `sourceQuery` to be absent.
+Full-query HogQL autocomplete and metadata can use the language service when `sourceQuery` is absent or is a `HogQLQuery`.
+Only the current editor SQL is sent, together with the cursor position for autocomplete.
+The editor can retain an older or incomplete `sourceQuery` while the current SQL changes; full-query metadata does not use that source text.
+For example, metadata for `SELECT distinct_id FROM events` can use Go even if `sourceQuery.query` is `SELECT event FROM events WHERE` and `indexUsage` is true.
Both operations continue to use Python when `connectionId`, `globals`, `filters`, or `modifiers` is not null.
+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.
+`indexUsage: true` does not force Python fallback or enable index analysis in Go.
+Go responses leave `index_usage`, `isUsingIndices`, and `ch_table_names` unset, and return an empty `notices` list.
+Python-only heuristic warnings, type notices, 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.
For authenticated requests that have the service configured and the feature flag enabled, the Prometheus counter `hogql_editor_assist_responses_total` counts the backend that produced the final successful editor response.
Its bounded attributes are the operation, backend, and routing reason.
diff --git a/posthog/api/services/query.py b/posthog/api/services/query.py
index 08e575404349..8401004bfc1a 100644
--- a/posthog/api/services/query.py
+++ b/posthog/api/services/query.py
@@ -108,7 +108,12 @@ def _language_service_eligible(query: HogQLAutocomplete | HogQLMetadata) -> bool
and query.modifiers is None
)
if isinstance(query, HogQLMetadata):
- return common and query.sourceQuery is None and query.variables is None and not query.debug
+ return (
+ common
+ and (query.sourceQuery is None or isinstance(query.sourceQuery, HogQLQuery))
+ and query.variables is None
+ and not query.debug
+ )
return common and (query.sourceQuery is None or isinstance(query.sourceQuery, HogQLQuery))
diff --git a/posthog/api/test/test_query_service.py b/posthog/api/test/test_query_service.py
index 89076d1df68c..babd1cb031a5 100644
--- a/posthog/api/test/test_query_service.py
+++ b/posthog/api/test/test_query_service.py
@@ -51,7 +51,6 @@ from posthog.api.services.query import (
_DatabaseSchemaCatalog,
_EditorAssistRoute,
_language_service_call,
- _language_service_eligible,
_record_editor_assist_backend,
process_query_model,
)
@@ -90,11 +89,6 @@ class TestLanguageServiceRouting(SimpleTestCase):
)
)
- def test_hogql_metadata_with_index_usage_is_language_service_eligible(self) -> None:
- query = HogQLMetadata(query="SELECT * FROM events", language=HogLanguage.HOG_QL, indexUsage=True)
-
- assert _language_service_eligible(query)
-
@patch("posthog.api.services.query._build_database_schema_query", side_effect=DatabaseSchemaUnavailable())
@patch("posthog.hogql.language_service.get_client")
@patch("posthog.api.services.query.LanguageServiceClient")
@@ -218,41 +212,71 @@ class TestLanguageServiceRouting(SimpleTestCase):
)
analytics_client.labels.return_value.inc.assert_called_once_with()
- @patch("posthog.api.services.query._route_editor_assist")
- def test_hogql_metadata_uses_language_service_diagnostics(self, mock_language_service_call: MagicMock):
- mock_language_service_call.return_value = _EditorAssistRoute(
- enabled=True,
- reason="served",
- result=LanguageServiceResult(
- body={
- "valid": False,
- "diagnostics": [
- {
- "code": "unknown_table",
- "message": 'Unknown table "evnts"',
- "start": 14,
- "end": 19,
- "suggestions": [{"label": "events", "distance": 1}],
- }
- ],
- "tableNames": ["evnts"],
- },
- duration_seconds=0.001,
- response_size_bytes=128,
- ),
+ @parameterized.expand(
+ [
+ ("without_source", None, False),
+ ("with_stale_source", HogQLQuery(query="SELECT event FROM events WHERE"), False),
+ ("with_stale_source_and_indexes", HogQLQuery(query="SELECT event FROM events WHERE"), True),
+ ]
+ )
+ @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(
+ self,
+ _name: str,
+ source_query: HogQLQuery | None,
+ index_usage: bool,
+ client_class: MagicMock,
+ _enabled: MagicMock,
+ responses_total: MagicMock,
+ ) -> None:
+ client_class.return_value.validate.return_value = LanguageServiceResult(
+ body={
+ "catalogRevision": "warehouse-aliases-v1:cached",
+ "valid": False,
+ "diagnostics": [
+ {
+ "code": "unknown_table",
+ "message": 'Unknown table "evnts"',
+ "start": 14,
+ "end": 19,
+ "suggestions": [{"label": "events", "distance": 1}],
+ }
+ ],
+ "tableNames": ["evnts"],
+ },
+ duration_seconds=0.001,
+ response_size_bytes=128,
)
+ query = HogQLMetadata(
+ query="SELECT * FROM evnts",
+ language=HogLanguage.HOG_QL,
+ sourceQuery=source_query,
+ indexUsage=index_usage,
+ )
+ original_query = query.model_dump()
response = process_query_model(
cast(Team, SimpleNamespace(pk=12)),
- HogQLMetadata(query="SELECT * FROM evnts", language=HogLanguage.HOG_QL),
+ query,
user=cast(User, SimpleNamespace(pk=34)),
)
+ client_class.return_value.validate.assert_called_once_with(12, 34, query.query)
+ assert query.model_dump() == original_query
assert isinstance(response, HogQLMetadataResponse)
assert response.isValid is False
assert response.errors[0].message == 'Unknown table "evnts"'
assert response.errors[0].fix == "events"
+ assert response.query == query.query
assert response.table_names == ["evnts"]
+ assert response.index_usage is None
+ assert response.isUsingIndices is None
+ responses_total.labels.assert_called_once_with(
+ operation="metadata", backend="language_service", reason="served"
+ )
+ responses_total.labels.return_value.inc.assert_called_once_with()
@parameterized.expand(
[
@@ -292,13 +316,23 @@ class TestLanguageServiceRouting(SimpleTestCase):
table_names=["events"],
)
+ query = HogQLMetadata(
+ query="SELECT event FROM events",
+ language=HogLanguage.HOG_QL,
+ sourceQuery=HogQLQuery(query="SELECT distinct_id FROM events"),
+ indexUsage=True,
+ )
+ original_query = query.model_dump()
response = process_query_model(
cast(Team, SimpleNamespace(pk=12)),
- HogQLMetadata(query="SELECT event FROM events", language=HogLanguage.HOG_QL),
+ query,
user=cast(User, SimpleNamespace(pk=34)),
)
assert response is python_metadata.return_value
+ assert python_metadata.call_args.kwargs["query"] is query
+ assert query.model_dump() == original_query
+ client_class.return_value.validate.assert_called_once_with(12, 34, query.query)
analytics_client.labels.assert_called_once_with(operation="metadata", backend="python", reason=reason)
analytics_client.labels.return_value.inc.assert_called_once_with()
enabled.assert_called_once()
@@ -533,7 +567,18 @@ class TestLanguageServiceRouting(SimpleTestCase):
enabled.assert_called_once()
@parameterized.expand(
- [("debug", {"debug": True}), ("source", {"sourceQuery": {"kind": "HogQLQuery", "query": "SELECT 1"}})]
+ [
+ ("debug", {"debug": True}),
+ (
+ "expression",
+ {
+ "language": "hogQLExpr",
+ "sourceQuery": {"kind": "HogQLQuery", "query": "SELECT event FROM events"},
+ },
+ ),
+ ("non_sql_source", {"sourceQuery": {"kind": "EventsNode"}}),
+ ("variables", {"variables": {}}),
+ ]
)
@patch("posthog.api.services.query.LanguageServiceClient")
@patch("posthog.api.services.query.EDITOR_ASSIST_RESPONSES_TOTAL")