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): skip schema builds for template autocomplete (#104161)

Michael Reichenbach93a8d71090e6
diff --git a/posthog/api/services/query.py b/posthog/api/services/query.py
index d6878ba7d12b..bf3c88e54262 100644
--- a/posthog/api/services/query.py
+++ b/posthog/api/services/query.py
@@ -16,6 +16,7 @@ from posthog.schema import (
DatabaseSchemaQuery,
DatabaseSchemaQueryResponse,
DataWarehouseViewLink,
+ HogLanguage,
HogQLAutocomplete,
HogQLAutocompleteResponse,
HogQLMetadata,
@@ -584,16 +585,19 @@ def process_query_model(
with timings.measure("fallback_error_tracking"):
_capture_malformed_language_service_response("autocomplete", route.malformed_stage)
if autocomplete_response is None:
- with timings.measure("fallback_database"):
- _, database = resolve_database_for_connection(
- team,
- query.connectionId,
- user=user,
- error_factory=ValidationError,
- modifiers=create_default_modifiers_for_team(team),
- # Editor-assist only: query execution never reads cached sources.
- use_cached_sources=True,
- )
+ database: Database | None = None
+ # Hog and template languages answer from globals, so building the schema is wasted work.
+ if query.language in (HogLanguage.HOG_QL, HogLanguage.HOG_QL_EXPR):
+ with timings.measure("fallback_database"):
+ _, database = resolve_database_for_connection(
+ team,
+ query.connectionId,
+ user=user,
+ error_factory=ValidationError,
+ modifiers=create_default_modifiers_for_team(team),
+ # Editor-assist only: query execution never reads cached sources.
+ use_cached_sources=True,
+ )
with timings.measure("fallback_python_autocomplete"):
autocomplete_response = get_hogql_autocomplete(
query=query, team=team, database_arg=database, user=user
diff --git a/posthog/api/test/test_query_service.py b/posthog/api/test/test_query_service.py
index dd0a45a7c46e..41f3d4b8f8a5 100644
--- a/posthog/api/test/test_query_service.py
+++ b/posthog/api/test/test_query_service.py
@@ -622,12 +622,16 @@ class TestLanguageServiceRouting(SimpleTestCase):
@parameterized.expand(
[
- ("expression", {"language": "hogQLExpr"}),
- ("non_sql_source", {"sourceQuery": {"kind": "EventsNode"}}),
- ("connection", {"connectionId": "example-connection"}),
- ("globals", {"globals": {}}),
- ("filters", {"filters": {}}),
- ("modifiers", {"modifiers": {}}),
+ ("expression", {"language": "hogQLExpr"}, True),
+ ("non_sql_source", {"sourceQuery": {"kind": "EventsNode"}}, True),
+ ("connection", {"connectionId": "example-connection"}, True),
+ ("globals", {"globals": {}}, True),
+ ("filters", {"filters": {}}, True),
+ ("modifiers", {"modifiers": {}}, True),
+ ("hog", {"language": "hog", "globals": {"event": {}}}, False),
+ ("hog_template", {"language": "hogTemplate", "globals": {"event": {}}}, False),
+ ("liquid", {"language": "liquid", "globals": {"event": {}}}, False),
+ ("hog_json", {"language": "hogJson", "globals": {"event": {}}}, False),
]
)
@patch("posthog.api.services.query.create_default_modifiers_for_team")
@@ -639,10 +643,11 @@ class TestLanguageServiceRouting(SimpleTestCase):
self,
_name: str,
context: dict[str, object],
+ builds_database: bool,
client_class: MagicMock,
_enabled: MagicMock,
python_autocomplete: MagicMock,
- _resolve_database: MagicMock,
+ resolve_database: MagicMock,
_modifiers: MagicMock,
) -> None:
query = HogQLAutocomplete.model_validate(
@@ -668,7 +673,9 @@ class TestLanguageServiceRouting(SimpleTestCase):
client_class.assert_not_called()
timing_values = {timing.k: timing.t for timing in response.timings or []}
assert "./editor_assist/routing" in timing_values
- assert "./editor_assist/fallback_database" in timing_values
+ assert resolve_database.called is builds_database
+ assert (python_autocomplete.call_args.kwargs["database_arg"] is None) is not builds_database
+ assert ("./editor_assist/fallback_database" in timing_values) is builds_database
assert "./editor_assist/fallback_python_autocomplete" in timing_values
assert "./editor_assist" in timing_values
diff --git a/posthog/hogql/autocomplete.py b/posthog/hogql/autocomplete.py
index 71497af73e2d..6cc7f1f198ba 100644
--- a/posthog/hogql/autocomplete.py
+++ b/posthog/hogql/autocomplete.py
@@ -568,12 +568,20 @@ def get_hogql_autocomplete(
response = HogQLAutocompleteResponse(suggestions=[], incomplete_list=False)
timings = HogQLTimings()
- if database_arg is not None:
- database = database_arg
- else:
- database = Database.create_for(team=team, user=user, timings=timings)
+ built_database: Optional[Database] = database_arg
+ context = HogQLContext(team_id=team.pk, team=team, user=user, database=database_arg, timings=timings)
+
+ def get_database() -> Database:
+ """`Database.create_for` walks every warehouse table, join and view for the team, which
+ dominates the latency of an autocomplete request. Template languages (Hog, Hog templates,
+ Liquid) answer from `query.globals` and the STL alone, so they must never reach it.
+ """
+ nonlocal built_database
+ if built_database is None:
+ built_database = Database.create_for(team=team, user=user, timings=timings)
+ context.database = built_database
+ return built_database
- context = HogQLContext(team_id=team.pk, team=team, user=user, database=database, timings=timings)
if query.sourceQuery:
if query.sourceQuery.kind == "HogQLQuery" and (
query.sourceQuery.query is None or query.sourceQuery.query == ""
@@ -696,6 +704,10 @@ def get_hogql_autocomplete(
if select_ast is None:
break
+ # Everything below resolves against the team's schema, so this is the first point
+ # where the database has to exist.
+ database = get_database()
+
if query.filters:
try:
select_ast = cast(
diff --git a/posthog/hogql/test/test_autocomplete.py b/posthog/hogql/test/test_autocomplete.py
index bf60dfdbfdfd..c941212b1a88 100644
--- a/posthog/hogql/test/test_autocomplete.py
+++ b/posthog/hogql/test/test_autocomplete.py
@@ -1,6 +1,7 @@
from typing import Optional
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from unittest.mock import patch
from parameterized import parameterized
@@ -528,6 +529,15 @@ class TestAutocomplete(ClickhouseTestMixin, APIBaseTest):
results = self._template(query=query, start=5, end=6, database=database)
assert len(results.suggestions) == 0
+ def test_autocomplete_template_strings_skip_the_schema_build(self):
+ query = "this isn't a string {concat(eve)} <- this is"
+
+ with patch.object(Database, "create_for", wraps=Database.create_for) as create_for:
+ results = self._template(query=query, start=28, end=31)
+
+ create_for.assert_not_called()
+ assert "event" in [suggestion.label for suggestion in results.suggestions]
+
def test_autocomplete_template_json(self):
database = Database.create_for(team=self.team)