: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
feat(hogql): preserve property provenance through projections (#102170)
Paweł Szczurb6d97d38da35
diff --git a/docs/internal/hogql-language-service-demo.md b/docs/internal/hogql-language-service-demo.mdindex eba5b201132d..01a696ed71c3 100644--- a/docs/internal/hogql-language-service-demo.md+++ b/docs/internal/hogql-language-service-demo.md@@ -100,9 +100,9 @@ They are not evidence that a query would succeed or fail in the full PostHog com| Area | Current boundary and reason | Follow-up and acceptance check || -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || Full PostHog catalog parity | The fixture is a small, static subset so the demo runs without Django. Virtual joins and all product tables are not modeled completely. | Add an optional catalog generator using a synthetic local project. Compare its published schema with Django's catalog for that project and document required services. |-| Derived-relation completion | The page does not synthesize CTE or subquery fields when the service returns no suggestions. This keeps service gaps visible. | Implement the shared query analyzer, then use the CTE and subquery examples to verify projected fields, aliases, and types in both completion and validation. |+| Derived-relation completion | The service resolves CTE and aliased subquery fields through the shared analyzer. The page does not invent missing suggestions. | Use the examples to check projected fields, aliases, types, and direct property origins. Structured recovery for malformed queries remains separate work. || Identifier quoting | The page uses the service's quoted `insertText`. Completion inside an already quoted identifier is not supported by the textarea adapter. | Add quote-aware token replacement before supporting completion inside existing quotes. Check escaped backticks and mid-token edits. |-| Alias and property semantics | The demo does not correct select-alias visibility, property provenance through CTEs, or shadowing behavior. | Extend the analyzer with Python-resolver-backed scope rules. Check a CTE named `events` that projects person properties, and aliases used in `WHERE`, `GROUP BY`, `HAVING`, and `ORDER BY`. |+| Alias and property semantics | The service preserves direct property origins through derived fields and visible SELECT aliases. Computed or ambiguous origins do not produce property suggestions. | Check event/person separation, renamed containers, and aliases in supported clauses. Computed-expression and nested JSON provenance require separate design and tests. || Other HogQL constructs | Examples do not establish coverage for unions, scalar `WITH` aliases, CTE column-name lists, recursive CTEs, or every dialect. | Decide supported constructs explicitly in the analyzer design; add examples and observable regression coverage for each supported construct. Retain the service's exclusion of recursive CTE support unless that scope changes. || Query execution and compiler parity | No database or Python metadata endpoint is called; validation reflects only this Go service. | Add an opt-in comparison mode against a synthetic local Django project if compiler parity testing is needed. Keep execution separate and explicitly enabled. || Editor integration | A textarea keeps the page dependency-free. Optional debounced validation and completion run after edits. Monaco highlighting, squiggles, and completion inside already quoted identifiers are not provided. Insertion replaces an ordinary identifier around the captured cursor. | Add a locally bundled editor adapter when testing editor behavior, with cursor/range tests for quoted names, escaped characters, and mid-token edits. |diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.mdindex 88a09982bb52..badf8a263d46 100644--- a/docs/internal/hogql-language-service.md+++ b/docs/internal/hogql-language-service.md@@ -48,6 +48,11 @@ Direct field projections retain catalog types; expression types remain unknown.Qualified CTE completion also works before `FROM`, for example `WITH t AS (SELECT event FROM events) SELECT t.`.Inner bindings take precedence, and sibling queries and statements do not contribute suggestions.Validation checks aliased subquery output fields and continues to report only underlying catalog tables in `tableNames`.+Validation reports `duplicate_table` when a FROM or JOIN source reuses a table name or explicit alias in the same query scope.+Use distinct aliases for self-joins, for example `events AS e JOIN events AS other`.+This follows HogQL's resolver even when raw ClickHouse accepts an unaliased self-join.+The duplicate-name check is case-sensitive; separate nested queries and set-operation branches can reuse names.+Duplicate qualifiers do not establish property provenance, including inside CTE projections and qualified wildcards.FROM and JOIN completion includes visible table CTEs before catalog tables, with `CTE` in the suggestion detail.CTE names follow the same scope, definition-order, and shadowing rules as relation lookup; scalar WITH aliases are not tables.A visible CTE hides a catalog table with the same name, and pagination counts that name once.@@ -66,11 +71,18 @@ Select aliases follow the resolution order in `posthog/hogql/resolver.py` (`visiAn explicit alias becomes visible after its defining SELECT item, so later items can reference it.WHERE, PREWHERE, GROUP BY, HAVING, ORDER BY, named WINDOW definitions, and LIMIT expressions can reference all SELECT aliases in their query.FROM and JOIN expressions cannot reference them, and aliases do not cross nested queries, CTE definitions, UNION branches, or statements.+UNION ALL, UNION DISTINCT, and EXCEPT branches resolve property containers and aliases from their own sources without inheriting another branch's property catalog.Alias lookup is case-sensitive, as in the Python resolver; completion prefix matching remains case-insensitive.An alias named `UUID` does not hide a source field named `uuid`; they can refer to different values.An alias takes precedence over an unqualified field with the same name, while qualified field lookup still uses the relation.Direct alias chains retain catalog types, and validation typo suggestions include visible aliases.+Direct property-container projections retain their original catalog namespace through CTEs, aliased subqueries, renamed fields, wildcard expansion, and visible SELECT aliases.+Completion and property-name validation use that same origin, rather than guessing from the projected name.+For example, `WITH recent AS (SELECT properties FROM events) SELECT recent.properties.$br FROM recent` suggests `$browser`.+A CTE named `events` that projects `persons.properties` uses the person property catalog, not the event catalog.+Renaming a container to `props` preserves its origin; projecting an individual property value does not preserve the whole container's namespace.+Physical field completion borrows the catalog prefix index.Derived projections have a shared limit of 16,384 fields before deduplication.Field resolution also has a request-wide budget of 1,048,576 work units, counting relation visits and identifier bytes used for lookups and derived-field indexes.@@ -83,10 +95,11 @@ Derived qualified suggestions are sorted and deduplicated before pagination.- Cursor replacement must produce parseable SQL to resolve CTE and subquery fields. Recovery for missing parentheses or incomplete predicates in multi-scope queries remains follow-up work.- For an incomplete single `SELECT` without `WITH`, completion can recover a parseable `FROM` clause before an unfinished predicate. The response retains `parseError`. Recovery never overlays parsed bindings or scans aliases from sibling scopes.-- Property provenance through derived projections is not available. Completion suppresses property suggestions for derived owners, including CTEs that shadow built-in names such as `events`. Unqualified physical properties remain available when joined derived relations do not project `properties`; a derived `properties` field makes the namespace ambiguous. Add provenance before enabling those ambiguous suggestions.+- Property provenance covers direct containers only. Computed JSON expressions, nested JSON schemas, conflicting sources, and duplicate projected names do not establish a namespace. Completion suppresses property suggestions and validation skips property-name checks when the origin is unknown. Expression inference and ambiguous-column diagnostics remain follow-up work; duplicate source names produce `duplicate_table`.+- Projecting a nested virtual container such as `e.person.properties AS props` does not retain provenance. Model virtual-table traversal before enabling those projected namespaces; existing direct physical property paths remain available.- Select-alias recovery requires parseable cursor-replaced SQL. Single-SELECT recovery retains only FROM bindings and does not guess discarded aliases. Preserve SELECT items in a structured recovery pass before enabling those suggestions.-- Property provenance through select aliases is not available. A visible alias that shadows a property owner suppresses its property suggestions and property-name validation. Track the alias expression's owner before enabling property traversal; qualified physical properties remain available.-- Scalar WITH aliases, aliases inside expressions, ARRAY JOIN aliases, QUALIFY, and duplicate-alias diagnostics remain follow-up work. Model their resolver order and parser support before extending the top-level SELECT alias index. For duplicate declarations, the index retains the first declaration; it does not establish that the query is valid.+- SELECT-alias property provenance follows the existing visibility and case-sensitive precedence rules. An alias without a known container origin suppresses property-owner fallback; it does not inherit a namespace from a name such as `person` or `properties`.+- Scalar WITH aliases, aliases inside expressions, ARRAY JOIN aliases, QUALIFY, and duplicate SELECT-alias diagnostics remain follow-up work. Model their resolver order and parser support before extending the top-level SELECT alias index. For duplicate declarations, the index retains the first field and type, but property provenance becomes unknown once the duplicate declaration is visible; earlier references retain their original provenance.- Validation skips field checks when a query has no known FROM bindings, including SELECT without FROM. Completion can still suggest its aliases. Add explicit empty-source scopes and distinguish unknown relations before enabling strict validation there.- JOIN USING output coalescing and ambiguous unqualified-field diagnostics remain follow-up work. Completion offers each source's qualified field; it does not choose a join-wide value or change validation's ambiguity rules.- CTE table-name suggestions require cursor replacement to produce parseable SQL. Malformed WITH clauses fall back to catalog suggestions without guessing CTE scope. Structured recovery remains follow-up work.diff --git a/services/hogql-language-service/README.md b/services/hogql-language-service/README.mdindex 1f558d4cfa60..e993d7167e89 100644--- a/services/hogql-language-service/README.md+++ b/services/hogql-language-service/README.md@@ -44,6 +44,11 @@ Select fewer fields to stay within the limit.Field lookup work has a separate request-wide budget.Queries that exceed it return HTTP 400 for completion or a `query_limit` validation diagnostic; reduce the number of sources or qualify field names.Joining a CTE or subquery without a `properties` output does not suppress the physical table's property suggestions or validation.+Direct property containers retain their catalog namespace through CTEs, aliased subqueries, renamed projections, wildcards, and visible SELECT aliases.+For example, `WITH t AS (SELECT properties AS props FROM events) SELECT t.props.$br FROM t` suggests `$browser`.+Computed or ambiguous property origins remain unknown; the service does not guess a namespace from a projected name.+Validation reports `duplicate_table` for repeated table names or explicit aliases in one query scope and asks for distinct aliases.+Duplicate qualifiers do not supply property provenance, even when raw ClickHouse accepts the corresponding unaliased self-join.Validation diagnostic offsets use `positionEncoding`, which defaults to UTF-16. Diagnostics include up to five visibletypo suggestions ranked by case-insensitive Levenshtein distance. Dynamic properties use the same cached namespaces as@@ -75,7 +80,7 @@ For incomplete SQL, completion can recover a single query's `FROM` clause and keIt does not recover bindings from malformed CTEs or nested queries.Completion and validation recognize explicit SELECT aliases in later SELECT items and clauses resolved after SELECT, including WHERE, GROUP BY, HAVING, and ORDER BY.Aliases stay within their defining query and do not appear in JOIN conditions.-Derived-property provenance, additional alias forms, parser recovery, and other exclusions are tracked in [query analysis and remaining work](../../docs/internal/hogql-language-service.md#recovery-and-remaining-work).+Computed and nested property provenance, additional alias forms, parser recovery, and other exclusions are tracked in [query analysis and remaining work](../../docs/internal/hogql-language-service.md#recovery-and-remaining-work).## Multitenant catalogsdiff --git a/services/hogql-language-service/internal/analysis/aliases.go b/services/hogql-language-service/internal/analysis/aliases.goindex 8806531c34f2..1e3476bb54fb 100644--- a/services/hogql-language-service/internal/analysis/aliases.go+++ b/services/hogql-language-service/internal/analysis/aliases.go@@ -10,8 +10,10 @@ import ()type selectAlias struct {- field catalog.Entry- end int+ field catalog.Entry+ propertyNamespace string+ end int+ ambiguousAt int}func (s *queryScope) selectAliases() map[string]selectAlias {@@ -30,12 +32,17 @@ func (s *queryScope) selectAliases() map[string]selectAlias {if !s.budget.lookup(len(name) + 1) {break}- if _, exists := s.aliases[name]; exists {+ if existing, exists := s.aliases[name]; exists {+ if existing.ambiguousAt == 0 {+ existing.ambiguousAt = int(item.End())+ s.aliases[name] = existing+ }continue}// HogQL resolves each expression before registering its alias (Resolver.visit_alias).field := catalog.Entry{Name: name, Type: projectedType(s, item.Expr)}- s.aliases[name] = selectAlias{field: field, end: int(item.End())}+ namespace, _ := projectedPropertyNamespace(s, item.Expr, int(item.Expr.Pos()))+ s.aliases[name] = selectAlias{field: field, propertyNamespace: namespace, end: int(item.End())}}return s.aliases}@@ -67,12 +74,20 @@ func (b Bindings) aliasCutoff() int {}func (b Bindings) SelectAlias(name string) (catalog.Entry, bool) {+ alias, ok := b.selectAlias(name)+ return alias.field, ok+}++func (b Bindings) selectAlias(name string) (selectAlias, bool) {cutoff := b.aliasCutoff()if cutoff < 0 || !b.scope.budget.lookup(len(name)+1) {- return catalog.Entry{}, false+ return selectAlias{}, false}alias, ok := b.scope.selectAliases()[name]- return alias.field, ok && alias.end <= cutoff+ if ok && alias.ambiguousAt != 0 && alias.ambiguousAt <= cutoff {+ alias.propertyNamespace = ""+ }+ return alias, ok && alias.end <= cutoff}func (b Bindings) SelectAliases(prefix string) iter.Seq[catalog.Entry] {diff --git a/services/hogql-language-service/internal/analysis/document.go b/services/hogql-language-service/internal/analysis/document.goindex b7269a225047..27f5c258c8d7 100644--- a/services/hogql-language-service/internal/analysis/document.go+++ b/services/hogql-language-service/internal/analysis/document.go@@ -89,7 +89,7 @@ func (s *Statement) analyze() {}s.analyzed = trues.scopes = queryScopes(s.expr, s.budget)- clickhouse.Walk(s.expr, func(node clickhouse.Expr) bool {+ bindTables := func(node clickhouse.Expr) bool {expr, ok := node.(*clickhouse.TableExpr)if !ok {return true@@ -106,7 +106,7 @@ func (s *Statement) analyze() {return true}if cte := resolveCTE(scope, name, start); cte != nil {- addBinding(scope, name, alias, Relation{name: cte.name, cte: cte})+ addBinding(scope, name, alias, Relation{name: cte.name, cte: cte}, start, end)return true}if original, exists := s.originalTableNames[strings.ToLower(name)]; exists {@@ -120,23 +120,44 @@ func (s *Statement) analyze() {// HogQL registers multi-part table paths under a double-underscore alias.alias = implicitAlias}- addBinding(scope, name, alias, Relation{name: name, table: table})+ addBinding(scope, name, alias, Relation{name: name, table: table}, start, end)}return true- })+ }+ walkIncludingExcept(s.expr, bindTables)}// Walk borrows parser nodes for validation; callers must not mutate them or retain them across requests.func (s *Statement) Walk(visit func(clickhouse.Expr) bool) {- clickhouse.Walk(s.expr, visit)+ walkIncludingExcept(s.expr, visit)}func (s *Statement) Tables() iter.Seq[TableReference] {return slices.Values(s.tables)}+func (s *Statement) DuplicateSources() iter.Seq[Source] {+ return func(yield func(Source) bool) {+ for _, scope := range s.scopes {+ for _, source := range scope.duplicateSources {+ if !yield(source) {+ return+ }+ }+ }+ }+}+func (s *Statement) ContainsPosition(position int) bool {- return int(s.expr.Pos()) <= position && position <= int(s.expr.End())+ if int(s.expr.Pos()) <= position && position <= int(s.expr.End()) {+ return true+ }+ for _, scope := range s.scopes {+ if contains(scope.query, position, position) {+ return true+ }+ }+ return false}func (s *Statement) BindingsAt(start, end int) Bindings {@@ -212,6 +233,32 @@ func (b Bindings) UniqueRelations() iter.Seq[Relation] {}func (b Bindings) PropertyNamespace(parts []string) (string, bool) {+ if len(parts) > 2 && b.scope.hasDuplicateSource(parts[0]) {+ return "", false+ }+ if len(parts) >= 2 {+ ownerParts := parts[:len(parts)-1]+ if len(ownerParts) == 1 {+ if alias, ok := b.selectAlias(ownerParts[0]); ok {+ return alias.propertyNamespace, alias.propertyNamespace != ""+ }+ _, qualified := b.Relation(ownerParts[0])+ if !qualified && resolveCTE(b.scope, ownerParts[0], b.position) == nil {+ namespace, ok, matched := b.scope.unqualifiedPropertyNamespace(ownerParts[0])+ if ok {+ return namespace, true+ }+ if matched {+ return "", false+ }+ }+ }+ if len(ownerParts) == 2 {+ if relation, ok := b.Relation(ownerParts[0]); ok {+ return bindingPropertyNamespace(relation, ownerParts[1])+ }+ }+ }if len(parts) >= 2 {_, bound := b.Relation(parts[0])if _, shadowed := b.SelectAlias(parts[0]); shadowed {diff --git a/services/hogql-language-service/internal/analysis/scopes.go b/services/hogql-language-service/internal/analysis/scopes.goindex d7cb6352cbda..50af32d2a7d7 100644--- a/services/hogql-language-service/internal/analysis/scopes.go+++ b/services/hogql-language-service/internal/analysis/scopes.go@@ -8,6 +8,8 @@ import (clickhouse "github.com/orian/clickhouse-sql-parser/parser""github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"+ "github.com/PostHog/posthog/services/hogql-language-service/internal/propertyresolver"+ "github.com/PostHog/posthog/services/hogql-language-service/internal/querylimits")type Relation struct {@@ -21,12 +23,19 @@ type cteBinding struct {query *clickhouse.SelectQueryscope *queryScopebudget *projectionBudget- fields []catalog.Entry- fieldIndex map[string]catalog.Entry+ fields []projectedField+ entries []catalog.Entry+ fieldIndex map[string]projectedFieldfieldsDone boolresolving bool}+type projectedField struct {+ entry catalog.Entry+ propertyNamespace string+ ambiguous bool+}+type projectionBudget struct {remaining intexceeded bool@@ -35,16 +44,25 @@ type projectionBudget struct {}type queryScope struct {- query *clickhouse.SelectQuery- parent *queryScope- bindings map[string]Relation- sources []Source- visible map[string]Relation- unique []Relation- budget *projectionBudget- ctes []*cteBinding- cteRoot bool- aliases map[string]selectAlias+ query *clickhouse.SelectQuery+ parent *queryScope+ bindings map[string]Relation+ sources []Source+ visible map[string]Relation+ unique []Relation+ budget *projectionBudget+ ctes []*cteBinding+ cteRoot bool+ aliases map[string]selectAlias+ propertyNamespaces map[string]propertyNamespace+ sourceNames map[string]int+ duplicateSources []Source+}++type propertyNamespace struct {+ name string+ ok bool+ matched bool}var tableReferencePattern = regexp.MustCompile(`(?i)\b(?:FROM|JOIN)\s+([A-Za-z_][A-Za-z0-9_.$]*)`)@@ -52,7 +70,7 @@ var tableReferencePattern = regexp.MustCompile(`(?i)\b(?:FROM|JOIN)\s+([A-Za-z_]func queryScopes(statement clickhouse.Expr, budget *projectionBudget) []*queryScope {var scopes []*queryScopebyQuery := map[*clickhouse.SelectQuery]*queryScope{}- clickhouse.Walk(statement, func(node clickhouse.Expr) bool {+ walkIncludingExcept(statement, func(node clickhouse.Expr) bool {if query, ok := node.(*clickhouse.SelectQuery); ok {scope := &queryScope{query: query, bindings: map[string]Relation{}, budget: budget}scopes = append(scopes, scope)@@ -69,6 +87,9 @@ func queryScopes(statement clickhouse.Expr, budget *projectionBudget) []*queryScscope.parent = candidate}}+ if scope.parent != nil && (scope.parent.query.UnionAll == scope.query || scope.parent.query.UnionDistinct == scope.query || scope.parent.query.Except == scope.query) {+ scope.cteRoot = true+ }}for _, scope := range scopes {if scope.query.With == nil {@@ -90,14 +111,55 @@ func queryScopes(statement clickhouse.Expr, budget *projectionBudget) []*queryScreturn scopes}-func addBinding(scope *queryScope, name, alias string, binding Relation) {+func walkIncludingExcept(expr clickhouse.Expr, visit func(clickhouse.Expr) bool) {+ var exceptBranches []*clickhouse.SelectQuery+ seenExcept := map[*clickhouse.SelectQuery]bool{}+ wrapper := func(node clickhouse.Expr) bool {+ walkChildren := visit(node)+ if query, ok := node.(*clickhouse.SelectQuery); ok && walkChildren && query.Except != nil && !seenExcept[query.Except] {+ seenExcept[query.Except] = true+ exceptBranches = append(exceptBranches, query.Except)+ }+ return walkChildren+ }+ clickhouse.Walk(expr, wrapper)+ for len(exceptBranches) > 0 {+ branch := exceptBranches[0]+ exceptBranches = exceptBranches[1:]+ clickhouse.Walk(branch, wrapper)+ }+}++func addBinding(scope *queryScope, name, alias string, binding Relation, start, end int) {scope.bindings[strings.ToLower(name)] = binding- source := Source{name: name, relation: binding}+ source := Source{name: name, relation: binding, start: start, end: end}if alias != "" {scope.bindings[strings.ToLower(alias)] = bindingsource.name = alias}scope.sources = append(scope.sources, source)+ if scope.sourceNames == nil {+ scope.sourceNames = map[string]int{}+ }+ scope.sourceNames[source.name]+++ if scope.sourceNames[source.name] == 2 && len(scope.duplicateSources) < querylimits.MaxDiagnostics {+ scope.duplicateSources = append(scope.duplicateSources, source)+ }+}++func (s *queryScope) hasDuplicateSource(name string) bool {+ for current := s; current != nil; current = current.parent {+ if !s.budget.lookup(len(name) + 1) {+ return true+ }+ if count, visible := current.sourceNames[name]; visible {+ return count > 1+ }+ if current.cteRoot {+ break+ }+ }+ return false}func (s *queryScope) visibleCTEs(position int) []*cteBinding {@@ -176,6 +238,67 @@ func (s *queryScope) uniqueBindings() []Relation {return s.unique}+func (s *queryScope) provenanceSources(name string) []Relation {+ if s == nil {+ return nil+ }+ var sources []Relation+ seen := map[string]bool{}+ for current := s; current != nil; current = current.parent {+ currentNames := map[string]bool{}+ for _, source := range current.sources {+ if !s.budget.lookup(len(name) + 1) {+ return nil+ }+ key := strings.ToLower(source.name)+ if seen[key] {+ continue+ }+ currentNames[key] = true+ sources = append(sources, source.relation)+ }+ for key := range currentNames {+ seen[key] = true+ }+ if current.cteRoot {+ break+ }+ }+ return sources+}++func (s *queryScope) unqualifiedPropertyNamespace(name string) (string, bool, bool) {+ if s == nil {+ return "", false, false+ }+ key := foldedFieldName(name)+ if namespace, ok := s.propertyNamespaces[key]; ok {+ return namespace.name, namespace.ok, namespace.matched+ }+ if s.propertyNamespaces == nil {+ s.propertyNamespaces = map[string]propertyNamespace{}+ }+ resolved := propertyNamespace{}+ matches := 0+ for _, binding := range s.provenanceSources(name) {+ if _, ok := bindingField(binding, name); !ok {+ continue+ }+ matches+++ resolved.matched = true+ if matches > 1 {+ resolved = propertyNamespace{matched: true}+ break+ }+ resolved.name, resolved.ok = bindingPropertyNamespace(binding, name)+ }+ if matches != 1 {+ resolved = propertyNamespace{matched: matches > 0}+ }+ s.propertyNamespaces[key] = resolved+ return resolved.name, resolved.ok, resolved.matched+}+func normalizeHogQLTableReferences(query string) (string, map[string]string) {normalized := []byte(query)originalNames := map[string]string{}@@ -236,7 +359,7 @@ func bindSubquery(expr *clickhouse.TableExpr, scopes []*queryScope, budget *projinner.cteRoot = trueif alias != "" {derived := &cteBinding{name: alias, query: subquery.Select, scope: inner, budget: budget}- addBinding(inner.parent, alias, "", Relation{name: alias, cte: derived})+ addBinding(inner.parent, alias, "", Relation{name: alias, cte: derived}, int(expr.Pos()), int(expr.End()))}}return true@@ -265,19 +388,48 @@ func bindingField(binding Relation, name string) (catalog.Entry, bool) {return catalog.Entry{}, false}if c.fieldIndex == nil {- c.fieldIndex = make(map[string]catalog.Entry, len(fields))+ c.fieldIndex = make(map[string]projectedField, len(fields))for _, field := range fields {- if !c.budget.lookup(len(field.Name) + 1) {+ if !c.budget.lookup(len(field.entry.Name) + 1) {return catalog.Entry{}, false}- key := foldedFieldName(field.Name)- if _, exists := c.fieldIndex[key]; !exists {+ key := foldedFieldName(field.entry.Name)+ if existing, exists := c.fieldIndex[key]; !exists {c.fieldIndex[key] = field+ } else {+ existing.propertyNamespace = ""+ existing.ambiguous = true+ c.fieldIndex[key] = existing}}}field, ok := c.fieldIndex[foldedFieldName(name)]- return field, ok+ return field.entry, ok+}++func bindingPropertyNamespace(binding Relation, name string) (string, bool) {+ if binding.table != nil {+ if _, ok := binding.table.Fields.Exact(name); !ok {+ return "", false+ }+ return propertyresolver.Resolve([]string{binding.name, name, "property"}, map[string]string{strings.ToLower(binding.name): binding.name})+ }+ if binding.cte == nil {+ return "", false+ }+ c := binding.cte+ _ = c.projectedFields()+ if !c.fieldsDone || !c.budget.lookup(len(name)+1) {+ return "", false+ }+ if c.fieldIndex == nil {+ _, _ = bindingField(binding, name)+ }+ if c.budget.exceeded || c.budget.lookupExceeded {+ return "", false+ }+ field, ok := c.fieldIndex[foldedFieldName(name)]+ return field.propertyNamespace, ok && !field.ambiguous && field.propertyNamespace != ""}func bindingFields(binding Relation) []catalog.Entry {@@ -287,17 +439,25 @@ func bindingFields(binding Relation) []catalog.Entry {if binding.cte == nil {return nil}- return binding.cte.projectedFields()+ projected := binding.cte.projectedFields()+ if binding.cte.entries == nil && len(projected) > 0 {+ binding.cte.entries = make([]catalog.Entry, 0, len(projected))+ for _, field := range projected {+ binding.cte.entries = append(binding.cte.entries, field.entry)+ }+ }+ return binding.cte.entries}-func (c *cteBinding) projectedFields() []catalog.Entry {+func (c *cteBinding) projectedFields() []projectedField {if c.fieldsDone || c.resolving || c.scope == nil || c.budget.exceeded || c.budget.lookupExceeded {return c.fields}c.resolving = truefor _, item := range c.query.SelectItems {if item.Alias != nil {- c.appendField(catalog.Entry{Name: item.Alias.Name, Type: projectedType(c.scope, item.Expr)})+ namespace, _ := projectedPropertyNamespace(c.scope, item.Expr, int(item.Expr.Pos()))+ c.appendField(projectedField{entry: catalog.Entry{Name: item.Alias.Name, Type: projectedType(c.scope, item.Expr)}, propertyNamespace: namespace})if c.budget.exceeded || c.budget.lookupExceeded {break}@@ -308,22 +468,26 @@ func (c *cteBinding) projectedFields() []catalog.Entry {if expr.Name == "*" {c.appendWildcardFields(c.scope, "")} else {- c.appendField(catalog.Entry{Name: expr.Name, Type: projectedType(c.scope, expr)})+ namespace, _ := projectedPropertyNamespace(c.scope, expr, int(expr.Pos()))+ c.appendField(projectedField{entry: catalog.Entry{Name: expr.Name, Type: projectedType(c.scope, expr)}, propertyNamespace: namespace})}case *clickhouse.Path:if len(expr.Fields) > 0 {- c.appendField(catalog.Entry{Name: expr.Fields[len(expr.Fields)-1].Name, Type: projectedType(c.scope, expr)})+ namespace, _ := projectedPropertyNamespace(c.scope, expr, int(expr.Pos()))+ c.appendField(projectedField{entry: catalog.Entry{Name: expr.Fields[len(expr.Fields)-1].Name, Type: projectedType(c.scope, expr)}, propertyNamespace: namespace})}case *clickhouse.NestedIdentifier:if expr.DotIdent != nil && expr.DotIdent.Name == "*" {c.appendWildcardFields(c.scope, expr.Ident.Name)} else if expr.DotIdent != nil {- c.appendField(catalog.Entry{Name: expr.DotIdent.Name, Type: projectedType(c.scope, expr)})+ namespace, _ := projectedPropertyNamespace(c.scope, expr, int(expr.Pos()))+ c.appendField(projectedField{entry: catalog.Entry{Name: expr.DotIdent.Name, Type: projectedType(c.scope, expr)}, propertyNamespace: namespace})} else {- c.appendField(catalog.Entry{Name: expr.Ident.Name, Type: projectedType(c.scope, expr)})+ namespace, _ := projectedPropertyNamespace(c.scope, expr, int(expr.Pos()))+ c.appendField(projectedField{entry: catalog.Entry{Name: expr.Ident.Name, Type: projectedType(c.scope, expr)}, propertyNamespace: namespace})}default:- c.appendField(catalog.Entry{Name: item.Expr.String()})+ c.appendField(projectedField{entry: catalog.Entry{Name: item.Expr.String()}})}if c.budget.exceeded || c.budget.lookupExceeded {break@@ -334,13 +498,13 @@ func (c *cteBinding) projectedFields() []catalog.Entry {return c.fields}-func (c *cteBinding) appendField(field catalog.Entry) {+func (c *cteBinding) appendField(field projectedField) {if c.budget.take(1) == 1 {c.fields = append(c.fields, field)}}-func (c *cteBinding) appendFields(fields []catalog.Entry) {+func (c *cteBinding) appendFields(fields []projectedField) {count := c.budget.take(len(fields))c.fields = append(c.fields, fields[:count]...)}@@ -348,20 +512,84 @@ func (c *cteBinding) appendFields(fields []catalog.Entry) {func (c *cteBinding) appendWildcardFields(scope *queryScope, qualifier string) {bindings := visibleBindings(scope)if qualifier != "" {- c.appendFields(bindingFields(bindings[strings.ToLower(qualifier)]))+ c.appendBindingFields(bindings[strings.ToLower(qualifier)], scope.hasDuplicateSource(qualifier))return}seen := map[string]bool{}- for _, binding := range bindings {- if seen[binding.name] {- continue+ for current := scope; current != nil; current = current.parent {+ for _, source := range current.sources {+ key := strings.ToLower(source.name)+ if current != scope && seen[key] {+ continue+ }+ seen[key] = true+ c.appendBindingFields(source.relation, false)+ if c.budget.exceeded {+ return+ }+ }+ if current.cteRoot {+ break+ }+ }+}++func (c *cteBinding) appendBindingFields(binding Relation, suppressProvenance bool) {+ if binding.table != nil {+ fields := binding.table.Fields.Entries()+ count := c.budget.take(len(fields))+ for _, field := range fields[:count] {+ namespace, _ := bindingPropertyNamespace(binding, field.Name)+ if suppressProvenance {+ namespace = ""+ }+ c.fields = append(c.fields, projectedField{entry: field, propertyNamespace: namespace})}- seen[binding.name] = true- c.appendFields(bindingFields(binding))- if c.budget.exceeded {+ return+ }+ if binding.cte != nil {+ fields := binding.cte.projectedFields()+ if !suppressProvenance {+ c.appendFields(fields)return}+ count := c.budget.take(len(fields))+ for _, field := range fields[:count] {+ field.propertyNamespace = ""+ c.fields = append(c.fields, field)+ }+ }+}++func projectedPropertyNamespace(scope *queryScope, expr clickhouse.Expr, position int) (string, bool) {+ bindings := visibleBindings(scope)+ switch typed := expr.(type) {+ case *clickhouse.Ident:+ if alias, ok := (Bindings{scope: scope, position: position}).selectAlias(typed.Name); ok {+ return alias.propertyNamespace, alias.propertyNamespace != ""+ }+ namespace, ok, _ := scope.unqualifiedPropertyNamespace(typed.Name)+ return namespace, ok+ case *clickhouse.Path:+ if len(typed.Fields) == 2 {+ if scope.hasDuplicateSource(typed.Fields[0].Name) {+ return "", false+ }+ if binding, ok := bindings[strings.ToLower(typed.Fields[0].Name)]; ok {+ return bindingPropertyNamespace(binding, typed.Fields[1].Name)+ }+ }+ case *clickhouse.NestedIdentifier:+ if typed.DotIdent != nil {+ if scope.hasDuplicateSource(typed.Ident.Name) {+ return "", false+ }+ if binding, ok := bindings[strings.ToLower(typed.Ident.Name)]; ok {+ return bindingPropertyNamespace(binding, typed.DotIdent.Name)+ }+ }}+ return "", false}func (b *projectionBudget) take(count int) int {diff --git a/services/hogql-language-service/internal/analysis/sources.go b/services/hogql-language-service/internal/analysis/sources.goindex 281bfe3158d6..5b85007044a0 100644--- a/services/hogql-language-service/internal/analysis/sources.go+++ b/services/hogql-language-service/internal/analysis/sources.go@@ -10,12 +10,18 @@ import (type Source struct {name stringrelation Relation+ start int+ end int}func (s Source) Qualifier() string {return s.name}+func (s Source) Start() int { return s.start }++func (s Source) End() int { return s.end }+func (b Bindings) sources() iter.Seq[Source] {return func(yield func(Source) bool) {seen := map[string]bool{}diff --git a/services/hogql-language-service/internal/completion/completion_test.go b/services/hogql-language-service/internal/completion/completion_test.goindex 72cd05814e9c..fe2c7de953da 100644--- a/services/hogql-language-service/internal/completion/completion_test.go+++ b/services/hogql-language-service/internal/completion/completion_test.go@@ -278,6 +278,29 @@ func TestCompletesScopedProjections(t *testing.T) {{"renamed properties are unrelated", "WITH t AS (SELECT properties AS attrs FROM events) SELECT properties.$geo_ci| FROM events JOIN t ON 1 = 1", map[string]string{"$geo_city": "String"}},{"derived properties are ambiguous", "WITH t AS (SELECT properties FROM events) SELECT properties.$geo_ci| FROM events JOIN t ON 1 = 1", nil},{"qualified physical properties remain available", "WITH t AS (SELECT properties FROM events) SELECT e.properties.$geo_ci| FROM events AS e JOIN t ON 1 = 1", map[string]string{"$geo_city": "String"}},+ {"cte property provenance", "WITH recent AS (SELECT properties FROM events) SELECT recent.properties.$geo_co| FROM recent", map[string]string{"$geo_country": "String"}},+ {"unqualified cte property provenance", "WITH recent AS (SELECT properties FROM events) SELECT properties.$geo_co| FROM recent", map[string]string{"$geo_country": "String"}},+ {"subquery property provenance", "SELECT recent.properties.$geo_co| FROM (SELECT properties FROM events) AS recent", map[string]string{"$geo_country": "String"}},+ {"renamed property provenance", "WITH recent AS (SELECT properties AS props FROM events) SELECT recent.props.$geo_co| FROM recent", map[string]string{"$geo_country": "String"}},+ {"unqualified renamed property provenance", "WITH recent AS (SELECT properties AS props FROM events) SELECT props.$geo_co| FROM recent", map[string]string{"$geo_country": "String"}},+ {"chained property provenance", "WITH a AS (SELECT properties FROM events), b AS (SELECT properties FROM a) SELECT b.properties.$geo_co| FROM b", map[string]string{"$geo_country": "String"}},+ {"wildcard property provenance", "WITH a AS (SELECT * FROM events), b AS (SELECT * FROM a) SELECT b.properties.$geo_co| FROM b", map[string]string{"$geo_country": "String"}},+ {"qualified wildcard property provenance", "WITH a AS (SELECT e.* FROM events AS e JOIN events AS other ON 1 = 1) SELECT a.properties.$geo_co| FROM a", map[string]string{"$geo_country": "String"}},+ {"visible property alias", "SELECT properties AS props, props.$geo_co| FROM events", map[string]string{"$geo_country": "String"}},+ {"property alias chain", "SELECT properties AS props, props AS attrs, attrs.$geo_co| FROM events", map[string]string{"$geo_country": "String"}},+ {"property alias before duplicate", "SELECT properties AS props, props.$geo_co|, uuid AS props FROM events", map[string]string{"$geo_country": "String"}},+ {"property alias after duplicate", "SELECT properties AS props, uuid AS props, props.$geo| FROM events", nil},+ {"cte name does not determine provenance", "WITH events AS (SELECT properties FROM persons) SELECT events.properties.$geo| FROM events", map[string]string{"$geo_city": "String"}},+ {"ambiguous joined properties", "WITH t AS (SELECT properties FROM events JOIN persons ON 1 = 1) SELECT t.properties.$geo| FROM t", nil},+ {"self join properties are ambiguous", "WITH t AS (SELECT properties FROM events AS e JOIN events AS other ON 1 = 1) SELECT t.properties.$geo| FROM t", nil},+ {"unaliased self join properties are ambiguous", "WITH t AS (SELECT properties FROM events JOIN events ON 1 = 1) SELECT t.properties.$geo| FROM t", nil},+ {"qualified duplicate table name suppresses provenance", "WITH t AS (SELECT events.properties FROM events JOIN events ON 1 = 1) SELECT t.properties.$geo| FROM t", nil},+ {"qualified duplicate wildcard suppresses provenance", "WITH t AS (SELECT e.* FROM events AS e JOIN events AS e ON 1 = 1) SELECT t.properties.$geo| FROM t", nil},+ {"duplicate qualifier suppresses virtual properties", "SELECT e.person.properties.$geo| FROM events AS e JOIN events AS e ON 1 = 1", nil},+ {"self join wildcard properties are ambiguous", "WITH t AS (SELECT * FROM events AS e JOIN events AS other ON 1 = 1) SELECT t.properties.$geo| FROM t", nil},+ {"inner alias hides outer property source", "SELECT (SELECT properties.$geo| FROM persons AS e) FROM events AS e", map[string]string{"$geo_city": "String"}},+ {"duplicate projected properties", "WITH t AS (SELECT events.properties, events.properties FROM events) SELECT t.properties.$geo| FROM t", nil},+ {"scalar property leaf has no provenance", "WITH t AS (SELECT properties.$geo_city AS city FROM events) SELECT t.city.$geo| FROM t", nil},{"derived body isolation", "SELECT * FROM orders AS x JOIN (SELECT x.| FROM events) AS s ON 1 = 1", nil},{"joined derived sources", "WITH t AS (SELECT event FROM events) SELECT s.| FROM t JOIN (SELECT amount AS total FROM orders) AS s ON 1 = 1", map[string]string{"total": "float"}},{"unicode prefix", "WITH t AS (SELECT amount AS `数額` FROM orders) SELECT t.数| FROM t", map[string]string{"数額": "float"}},@@ -301,6 +324,11 @@ func TestCompletesScopedProjections(t *testing.T) {{"no inner select alias", "SELECT tot| FROM orders WHERE order_id IN (SELECT event AS total FROM events)", nil},{"no select alias across statements", "SELECT amount AS total FROM orders; SELECT tot| FROM events", nil},{"no select alias across union", "SELECT amount AS total FROM orders UNION ALL SELECT tot| FROM orders", nil},+ {"union all property isolation", "SELECT properties FROM events UNION ALL SELECT properties.$geo| FROM persons", map[string]string{"$geo_city": "String"}},+ {"union arm local property alias", "SELECT properties AS props FROM events UNION ALL SELECT properties AS props FROM persons WHERE props.$geo| = 'x'", map[string]string{"$geo_city": "String"}},+ {"union arm does not inherit property alias", "SELECT properties AS props FROM events UNION ALL SELECT props.$geo| FROM persons", nil},+ {"union distinct property isolation", "SELECT properties FROM events UNION DISTINCT SELECT properties.$geo| FROM persons", map[string]string{"$geo_city": "String"}},+ {"except property isolation", "SELECT properties FROM events EXCEPT SELECT properties.$geo| FROM persons", map[string]string{"$geo_city": "String"}},{"no select alias in cte", "WITH t AS (SELECT tot| FROM orders) SELECT amount AS total FROM orders", nil},{"alias property shadow", "SELECT uuid AS properties FROM events ORDER BY properties.$geo_ci|", nil},{"alias virtual property shadow", "SELECT uuid AS session FROM events ORDER BY session.properties.$entry|", nil},diff --git a/services/hogql-language-service/internal/validation/validation.go b/services/hogql-language-service/internal/validation/validation.goindex 088d4be7c79a..cdd725c7398d 100644--- a/services/hogql-language-service/internal/validation/validation.go+++ b/services/hogql-language-service/internal/validation/validation.go@@ -66,6 +66,17 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {})}}+ for source := range statement.DuplicateSources() {+ if len(diagnostics) >= querylimits.MaxDiagnostics {+ break+ }+ diagnostics = append(diagnostics, Diagnostic{+ Code: "duplicate_table",+ Message: fmt.Sprintf("Table name %q is used more than once. Use a distinct alias for each table.", source.Qualifier()),+ Start: source.Start(),+ End: source.End(),+ })+ }ignoredIdents := map[*clickhouse.Ident]bool{}statement.Walk(func(node clickhouse.Expr) bool {switch typed := node.(type) {diff --git a/services/hogql-language-service/internal/validation/validation_test.go b/services/hogql-language-service/internal/validation/validation_test.goindex 729c9866d299..55f9316a28f3 100644--- a/services/hogql-language-service/internal/validation/validation_test.go+++ b/services/hogql-language-service/internal/validation/validation_test.go@@ -143,6 +143,41 @@ func TestValidateAcceptsHogQLQualifiedTable(t *testing.T) {}}+func TestValidateDuplicateTableNames(t *testing.T) {+ for _, test := range []struct {+ name, query, qualifier string+ valid bool+ }{+ {name: "unaliased", query: "SELECT events.properties FROM events JOIN events ON 1 = 1", qualifier: "events"},+ {name: "duplicate alias", query: "SELECT e.properties FROM events AS e JOIN persons AS e ON 1 = 1", qualifier: "e"},+ {name: "derived property", query: "WITH t AS (SELECT events.properties FROM events JOIN events ON 1 = 1) SELECT t.properties.$geo_cty FROM t", qualifier: "events"},+ {name: "distinct aliases", query: "SELECT e.properties FROM events AS e JOIN events AS other ON 1 = 1", valid: true},+ {name: "case-sensitive aliases", query: "SELECT e.properties FROM events AS e JOIN events AS E ON 1 = 1", valid: true},+ {name: "nested reuse", query: "SELECT e.properties FROM events AS e WHERE uuid IN (SELECT properties FROM persons AS e)", valid: true},+ } {+ t.Run(test.name, func(t *testing.T) {+ result := Validate(schema(), test.query)+ if test.valid {+ if !result.Valid || len(result.Diagnostics) != 0 {+ t.Fatalf("result = %#v", result)+ }+ return+ }+ if result.Valid || len(result.Diagnostics) != 1 {+ t.Fatalf("result = %#v", result)+ }+ diagnostic := result.Diagnostics[0]+ if diagnostic.Code != "duplicate_table" || diagnostic.Message != fmt.Sprintf("Table name %q is used more than once. Use a distinct alias for each table.", test.qualifier) {+ t.Fatalf("diagnostic = %#v", diagnostic)+ }+ secondJoin := strings.Index(test.query, " JOIN ") + len(" JOIN ")+ if diagnostic.Start != secondJoin || diagnostic.End <= diagnostic.Start {+ t.Fatalf("diagnostic span = %d:%d, want start %d", diagnostic.Start, diagnostic.End, secondJoin)+ }+ })+ }+}+func TestValidateCommonTableExpressions(t *testing.T) {tests := []struct {name string@@ -305,9 +340,24 @@ func TestValidatePropertiesAcrossGenericNamespaces(t *testing.T) {{query: "WITH t AS (SELECT 1 AS x) SELECT properties.$geo_cty FROM events JOIN t ON 1 = 1", suggestion: "$geo_city"},{query: "SELECT properties.$geo_cty FROM events JOIN (SELECT 1 AS x) AS t ON 1 = 1", suggestion: "$geo_city"},{query: "WITH t AS (SELECT properties AS attrs FROM events) SELECT properties.$geo_cty FROM events JOIN t ON 1 = 1", suggestion: "$geo_city"},+ {query: "WITH recent AS (SELECT properties FROM events) SELECT recent.properties.$geo_cty FROM recent", suggestion: "$geo_city"},+ {query: "WITH recent AS (SELECT properties FROM events) SELECT properties.$geo_cty FROM recent", suggestion: "$geo_city"},+ {query: "SELECT recent.properties.$geo_cty FROM (SELECT properties FROM events) AS recent", suggestion: "$geo_city"},+ {query: "WITH recent AS (SELECT properties AS props FROM events) SELECT recent.props.$geo_cty FROM recent", suggestion: "$geo_city"},+ {query: "WITH recent AS (SELECT properties AS props FROM events) SELECT props.$geo_cty FROM recent", suggestion: "$geo_city"},+ {query: "WITH a AS (SELECT properties FROM persons), events AS (SELECT * FROM a) SELECT events.properties.$geo_contry FROM events", suggestion: "$geo_country"},+ {query: "SELECT properties AS props, props AS attrs, attrs.$geo_cty FROM events", suggestion: "$geo_city"},+ {query: "SELECT properties AS props, uuid AS props, props.$geo_cty FROM events", suggestion: ""},+ {query: "SELECT properties FROM events EXCEPT SELECT properties.$geo_contry FROM persons", suggestion: "$geo_country"},}for _, test := range tests {result := Validate(schema(), test.query)+ if test.suggestion == "" {+ if !result.Valid || len(result.Diagnostics) != 0 {+ t.Fatalf("query %q returned %#v", test.query, result)+ }+ continue+ }if result.Valid || len(result.Diagnostics) != 1 {t.Fatalf("query %q returned %#v", test.query, result)}