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): show real types and rank functions in SQL editor autocomplete (#79146)

George Munyoro657bddbf4e5c
diff --git a/frontend/src/lib/monaco/hogQLAutocompleteProvider.ts b/frontend/src/lib/monaco/hogQLAutocompleteProvider.ts
index e4f5567a7c4e..5ac0daf2da81 100644
--- a/frontend/src/lib/monaco/hogQLAutocompleteProvider.ts
+++ b/frontend/src/lib/monaco/hogQLAutocompleteProvider.ts
@@ -140,7 +140,9 @@ export const hogQLAutocompleteProvider = (type: HogLanguage): languages.Completi
const completionItems = response.suggestions
const suggestions = completionItems.map<languages.CompletionItem>((item) => {
const kind = convertCompletionItemKind(item.kind)
- const sortText = kindToSortText(item.kind, item.label)
+ // The backend sets sortText when it can rank a suggestion, for example a function
+ // whose return type fits the comparison being written. Otherwise fall back to kind order.
+ const sortText = item.sortText ?? kindToSortText(item.kind, item.label)
return {
label: {
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 83a2226b110a..23864cf4d6b4 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -5709,6 +5709,10 @@
"label": {
"description": "The label of this completion item. By default this is also the text that is inserted when selecting this completion.",
"type": "string"
+ },
+ "sortText": {
+ "description": "Overrides the editor's default ordering for this item. Set when the backend can rank a suggestion, for example a function whose return type fits the comparison being written.",
+ "type": "string"
}
},
"required": ["label", "insertText", "kind"],
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 03db1ac78fab..4e321374d480 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -821,6 +821,11 @@ export interface AutocompleteCompletionItem {
* an icon is chosen by the editor.
*/
kind: AutocompleteCompletionItemKind
+ /**
+ * Overrides the editor's default ordering for this item. Set when the backend can rank a
+ * suggestion, for example a function whose return type fits the comparison being written.
+ */
+ sortText?: string
}
export interface HogQLAutocompleteResponse {
diff --git a/hogli.yaml b/hogli.yaml
index ded8101527a4..cf68a656d4ad 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -816,8 +816,8 @@ quality:
"$@"
description: Format CSS/SCSS files
format:js:
- cmd: pnpm oxlint --fix --fix-suggestions --quiet --no-error-on-unmatched-pattern
- "$@" && pnpm exec oxfmt --no-error-on-unmatched-pattern "$@"
+ cmd: pnpm oxlint --fix --fix-suggestions --quiet "$@" && pnpm exec oxfmt
+ --no-error-on-unmatched-pattern "$@"
description: Format JavaScript/TypeScript files (frontend)
format:nodejs:
cmd: pnpm --dir nodejs exec eslint --fix "$@" && pnpm --dir nodejs exec prettier
diff --git a/posthog/hogql/autocomplete.py b/posthog/hogql/autocomplete.py
index 44fd0ae244c0..9ed7d5bef555 100644
--- a/posthog/hogql/autocomplete.py
+++ b/posthog/hogql/autocomplete.py
@@ -1,6 +1,7 @@
import json
from collections.abc import Callable
from copy import deepcopy
+from functools import lru_cache
from typing import Optional, cast
from django.db import models
@@ -31,18 +32,25 @@ from posthog.hogql.database.models import (
StringDatabaseField,
StringJSONDatabaseField,
Table,
- UUIDDatabaseField,
VirtualTable,
)
from posthog.hogql.database.schema.events import EventsGroupSubTable, EventsPersonSubTable, EventsTable
from posthog.hogql.database.schema.groups import GroupsTable
from posthog.hogql.database.schema.persons import PersonsTable
from posthog.hogql.filters import replace_filters
-from posthog.hogql.functions.mapping import ALL_EXPOSED_FUNCTION_NAMES
+from posthog.hogql.functions.mapping import ALL_EXPOSED_FUNCTION_NAMES, find_hogql_aggregation, find_hogql_function
from posthog.hogql.parser import parse_expr, parse_program, parse_select, parse_string_template
from posthog.hogql.resolver import resolve_types, resolve_types_from_table
from posthog.hogql.resolver_utils import extract_select_queries
from posthog.hogql.timings import HogQLTimings
+from posthog.hogql.type_system import (
+ ComparisonCompatibility,
+ RuntimeType,
+ comparison_compatibility,
+ infer_function_return_type,
+ runtime_type_from_constant_type,
+ runtime_type_from_database_field,
+)
from posthog.hogql.visitor import TraversingVisitor, clone_expr
from posthog.exceptions_capture import capture_exception
@@ -100,8 +108,81 @@ def get_direct_table_function_names(context: HogQLContext) -> list[str]:
return sorted({name for name in available_table_functions if isinstance(name, str)})
+# The editor groups by kind first: variables and fields sort under "1", functions under "2". Ranking
+# has to stay inside the function group, so a ranked function keeps that prefix and adds its bucket
+# after it ("2-0-now"). Sorting a function above the table's own columns is not the trade here.
+_FUNCTION_KIND_SORT_PREFIX = "2"
+
+# Ranking buckets for function suggestions, lowest sorts first. Monaco orders by `sortText`, so the
+# bucket decides position within the group and the name breaks ties inside a bucket.
+_FUNCTION_RANK_BY_COMPATIBILITY: dict[ComparisonCompatibility, str] = {
+ ComparisonCompatibility.DEFINITELY_COMPATIBLE: "0",
+ ComparisonCompatibility.CHEAP_CAST: "1",
+ ComparisonCompatibility.UNKNOWN: "2",
+ ComparisonCompatibility.EXPENSIVE_CAST: "3",
+ ComparisonCompatibility.INCOMPATIBLE: "4",
+}
+_UNRANKED_FUNCTION_PREFIX = "2"
+
+
+@lru_cache(maxsize=2048)
+def _declared_function_return_type(function_name: str) -> ast.ConstantType | None:
+ """The return type a function declares before its arguments are known.
+
+ Completion runs before the user types any arguments, so ask for inference over unknown
+ arguments. Functions whose return type depends on those arguments answer UnknownType, which
+ ranks in the middle rather than being pushed down.
+ """
+ meta = find_hogql_function(function_name) or find_hogql_aggregation(function_name)
+ if meta is None:
+ return None
+ arg_types: list[ast.ConstantType] = [ast.UnknownType(nullable=False) for _ in range(meta.min_args or 0)]
+ try:
+ return infer_function_return_type(function_name, arg_types, meta=meta).return_type
+ except Exception:
+ return None
+
+
+def expected_type_at_position(
+ node: Optional[AST], parent_node: Optional[AST], table: Table, context: HogQLContext
+) -> ast.ConstantType | None:
+ """The type the expression under the cursor is being compared against, when there is one.
+
+ Only handles a comparison with a resolvable other side, which is where a type expectation is
+ unambiguous. Everything else returns None and leaves suggestions unranked.
+ """
+ if not isinstance(parent_node, ast.CompareOperation):
+ return None
+ other_side = parent_node.left if parent_node.right is node else parent_node.right
+ if other_side is node:
+ return None
+ try:
+ table_chain = table.to_printed_hogql().replace("`", "").split(".")
+ resolved = resolve_types_from_table(other_side, table_chain, context, "hogql")
+ if resolved.type is None:
+ return None
+ return resolved.type.resolve_constant_type(context)
+ except Exception:
+ # A half-typed comparison often will not resolve. Ranking is an enhancement, so fall back
+ # to the unranked list rather than failing the completion request.
+ return None
+
+
+def _function_sort_text(function_name: str, expected_type: ast.ConstantType) -> str:
+ return_type = _declared_function_return_type(function_name)
+ if return_type is None:
+ bucket = _UNRANKED_FUNCTION_PREFIX
+ else:
+ bucket = _FUNCTION_RANK_BY_COMPATIBILITY[comparison_compatibility(expected_type, return_type)]
+ return f"{_FUNCTION_KIND_SORT_PREFIX}-{bucket}-{function_name}"
+
+
def append_function_suggestions(
- suggestions: list[AutocompleteCompletionItem], language: str, context: HogQLContext, prefix: str = ""
+ suggestions: list[AutocompleteCompletionItem],
+ language: str,
+ context: HogQLContext,
+ prefix: str = "",
+ expected_type: ast.ConstantType | None = None,
) -> None:
available_functions = get_available_functions(language, context)
if prefix:
@@ -112,11 +193,16 @@ def append_function_suggestions(
if function_name.lower().startswith(normalized_prefix)
]
+ sort_texts: Optional[list[str]] = None
+ if expected_type is not None:
+ sort_texts = [_function_sort_text(function_name, expected_type) for function_name in available_functions]
+
extend_responses(
available_functions,
suggestions,
AutocompleteCompletionItemKind.FUNCTION,
insert_text=lambda key: f"{key}()",
+ sort_texts=sort_texts,
)
@@ -182,25 +268,32 @@ def constant_type_to_database_field(constant_type: ConstantType, name: str) -> D
return DatabaseField(name=name)
+# Shown when the type system has no answer for a field. Deliberately visible rather than blank:
+# an unlabeled completion is indistinguishable from one we chose not to label, and the gap is the
+# thing worth seeing.
+UNKNOWN_TYPE_LABEL = "unknown"
+
+
+def _display_runtime_type(runtime_type: RuntimeType) -> str:
+ """Render a runtime type for a completion detail.
+
+ An unknown family renders as the unknown label rather than `Unknown`/`Nullable(Unknown)`. We do
+ not know the type, so we do not know its nullability either, and claiming it reads as a fact.
+ """
+ if runtime_type.family == "unknown":
+ return UNKNOWN_TYPE_LABEL
+ return runtime_type.display()
+
+
def convert_field_or_table_to_type_string(
field_or_table: FieldOrTable, parent_table: str, context: HogQLContext
) -> str | None:
- if isinstance(field_or_table, BooleanDatabaseField):
- return "Boolean"
- if isinstance(field_or_table, IntegerDatabaseField):
- return "Integer"
- if isinstance(field_or_table, FloatDatabaseField):
- return "Float"
- if isinstance(field_or_table, StringDatabaseField):
- return "String"
- if isinstance(field_or_table, UUIDDatabaseField):
- return "String"
- if isinstance(field_or_table, DateTimeDatabaseField):
- return "DateTime"
- if isinstance(field_or_table, DateDatabaseField):
- return "Date"
- if isinstance(field_or_table, StringJSONDatabaseField):
- return "Object"
+ """Render the type the resolver would give this field, in ClickHouse spelling.
+
+ Reads the structured runtime type rather than the DatabaseField subclass, so nullability and
+ parametric detail (`Nullable(Float64)`, `Array(String)`, `DateTime64(6, 'UTC')`) reach the
+ editor instead of being flattened to a family name.
+ """
if isinstance(field_or_table, ast.ExpressionField):
parent_table_chain = parent_table.replace("`", "").split(".")
try:
@@ -208,15 +301,20 @@ def convert_field_or_table_to_type_string(
assert field_expr.type is not None
constant_type = field_expr.type.resolve_constant_type(context)
- return constant_type.print_type()
+ return _display_runtime_type(runtime_type_from_constant_type(constant_type))
except Exception as e:
- tracking_error = Exception("Cant resolve expression field in autocomplete")
+ tracking_error = Exception("Can't resolve expression field in autocomplete")
tracking_error.__cause__ = e
capture_exception(tracking_error)
- return "Expression"
+ return UNKNOWN_TYPE_LABEL
if isinstance(field_or_table, ast.Table | ast.LazyJoin):
return "Table"
+ if isinstance(field_or_table, ast.DatabaseField):
+ try:
+ return _display_runtime_type(runtime_type_from_database_field(field_or_table))
+ except Exception:
+ return UNKNOWN_TYPE_LABEL
return None
@@ -354,7 +452,12 @@ def resolve_table_field_traversers(table: Table, context: HogQLContext) -> Table
def append_table_field_to_response(
- table: Table, suggestions: list[AutocompleteCompletionItem], language: str, context: HogQLContext
+ table: Table,
+ suggestions: list[AutocompleteCompletionItem],
+ language: str,
+ context: HogQLContext,
+ node: Optional[AST] = None,
+ parent_node: Optional[AST] = None,
) -> None:
keys: list[str] = []
details: list[str | None] = []
@@ -374,7 +477,12 @@ def append_table_field_to_response(
insert_text=lambda key: f"`{key}`" if any(n in key for n in HOGQL_CHARACTERS_TO_BE_WRAPPED) else key,
)
- append_function_suggestions(suggestions=suggestions, language=language, context=context)
+ append_function_suggestions(
+ suggestions=suggestions,
+ language=language,
+ context=context,
+ expected_type=expected_type_at_position(node, parent_node, table, context),
+ )
def extend_responses(
@@ -383,6 +491,7 @@ def extend_responses(
kind: AutocompleteCompletionItemKind = AutocompleteCompletionItemKind.VARIABLE,
insert_text: Optional[Callable[[str], str]] = None,
details: Optional[list[str | None]] = None,
+ sort_texts: Optional[list[str]] = None,
) -> None:
suggestions.extend(
[
@@ -391,6 +500,7 @@ def extend_responses(
label=key,
kind=kind,
detail=details[index] if details is not None else None,
+ sortText=sort_texts[index] if sort_texts is not None else None,
)
for index, key in enumerate(keys)
]
@@ -653,6 +763,8 @@ def get_hogql_autocomplete(
suggestions=response.suggestions,
language=query.language,
context=context,
+ node=node,
+ parent_node=parent_node,
)
break
diff --git a/posthog/hogql/test/test_autocomplete.py b/posthog/hogql/test/test_autocomplete.py
index ec5dbde913df..c4ed0f290b20 100644
--- a/posthog/hogql/test/test_autocomplete.py
+++ b/posthog/hogql/test/test_autocomplete.py
@@ -15,7 +15,7 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.autocomplete import get_hogql_autocomplete
from posthog.hogql.database.database import Database
-from posthog.hogql.database.models import StringDatabaseField
+from posthog.hogql.database.models import FloatDatabaseField, StringDatabaseField
from posthog.hogql.database.schema.events import EventsTable
from posthog.hogql.database.schema.persons import PERSONS_FIELDS
@@ -389,6 +389,66 @@ class TestAutocomplete(ClickhouseTestMixin, APIBaseTest):
assert suggestion.label == "created_at"
assert suggestion.insertText == "created_at"
+ def test_autocomplete_ranks_functions_by_comparison_fit(self):
+ # Without ranking the function list is alphabetical, so `xor` and `varSamp` sit alongside
+ # `now` when the user is completing the right side of a timestamp comparison.
+ query = "select * from events where timestamp > "
+ results = self._select(query=query, start=len(query), end=len(query))
+
+ sort_text = {
+ suggestion.label: suggestion.sortText
+ for suggestion in results.suggestions
+ if suggestion.kind == AutocompleteCompletionItemKind.FUNCTION
+ }
+
+ now_sort_text = sort_text["now"]
+ to_datetime_sort_text = sort_text["toDateTime"]
+ xor_sort_text = sort_text["xor"]
+ assert now_sort_text is not None
+ assert to_datetime_sort_text is not None
+ assert xor_sort_text is not None
+ assert now_sort_text < xor_sort_text
+ assert to_datetime_sort_text < xor_sort_text
+
+ # Ranking orders functions against each other, never against the table's own columns. The
+ # editor sorts variables under "1" and functions under "2", so a ranked function has to keep
+ # the function prefix or a well-fitting function jumps above every field.
+ field_sort_text = {
+ suggestion.label: suggestion.sortText
+ for suggestion in results.suggestions
+ if suggestion.kind == AutocompleteCompletionItemKind.VARIABLE
+ }
+ assert field_sort_text["event"] is None
+ assert now_sort_text.startswith("2-")
+
+ def test_autocomplete_leaves_functions_unranked_without_an_expected_type(self):
+ # No comparison means no expectation, so ranking stays off and the editor keeps its own
+ # ordering. Guards against emitting a confident order we cannot justify.
+ query = "select from events"
+ results = self._select(query=query, start=7, end=7)
+
+ functions = [
+ suggestion
+ for suggestion in results.suggestions
+ if suggestion.kind == AutocompleteCompletionItemKind.FUNCTION
+ ]
+
+ assert len(functions) > 0
+ assert all(suggestion.sortText is None for suggestion in functions)
+
+ def test_autocomplete_details_carry_nullability(self):
+ # Completions read the structured runtime type, so a nullable column is visibly nullable in
+ # the editor. Reverting to a DatabaseField isinstance ladder flattens `Nullable(Boolean)` to
+ # `Boolean`, which is exactly the distinction that makes a NULL guard look redundant.
+ database = Database.create_for(team=self.team)
+ database.get_table("events").fields["nullable_score"] = FloatDatabaseField(name="nullable_score", nullable=True)
+
+ results = self._select(query="select from events", start=7, end=7, database=database)
+ details = {suggestion.label: suggestion.detail for suggestion in results.suggestions}
+
+ assert details["nullable_score"] == "Nullable(Float64)"
+ assert details["event"] == "String"
+
def test_autocomplete_resolve_expression_type(self):
database = Database.create_for(team=self.team)
@@ -408,7 +468,9 @@ class TestAutocomplete(ClickhouseTestMixin, APIBaseTest):
assert suggestion is not None
assert suggestion.label == "expr_field"
assert suggestion.insertText == "expr_field"
- assert suggestion.detail == "DateTime"
+ # `toDateTime` on a string prints to `parseDateTime64BestEffortOrNull`, so the result really
+ # can be NULL. The detail flattened that away until completions started reading runtime types.
+ assert suggestion.detail == "Nullable(DateTime)"
def test_autocomplete_template_strings(self):
database = Database.create_for(team=self.team)
diff --git a/posthog/schema.py b/posthog/schema.py
index bc8443c5b1d4..984a5eed1f96 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -4475,6 +4475,14 @@ class AutocompleteCompletionItem(BaseModel):
" is inserted when selecting this completion."
),
)
+ sortText: str | None = Field(
+ default=None,
+ description=(
+ "Overrides the editor's default ordering for this item. Set when the"
+ " backend can rank a suggestion, for example a function whose return type"
+ " fits the comparison being written."
+ ),
+ )
class BoxPlotDatum(BaseModel):
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2c8ad0d2db72..986b308a9890 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -10376,6 +10376,8 @@ export namespace Schemas {
kind: AutocompleteCompletionItemKind;
/** The label of this completion item. By default this is also the text that is inserted when selecting this completion. */
label: string;
+ /** Overrides the editor's default ordering for this item. Set when the backend can rank a suggestion, for example a function whose return type fits the comparison being written. */
+ sortText?: string | null;
}
/**