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): autocomplete catalog-backed lazy table fields (#104375)

Paweł Szczur21964c1cf1be
diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.md
index 92b877ba1687..33a9df5d1e7e 100644
--- a/docs/internal/hogql-language-service.md
+++ b/docs/internal/hogql-language-service.md
@@ -44,6 +44,112 @@ An alias candidate that resolves unambiguously to another visible canonical tabl
Nonrepresentable resolver collisions require a separate catalog contract before they can use the Go service.
Built-in `posthog.*` namespaces are outside this rollout.
+### Lazy-table traversal catalog
+
+The Go consumer accepts optional traversal metadata alongside the flat catalog.
+This is a consumer-first extension: existing Django snapshots do not publish these annotations yet.
+Deploy the Go consumer before enabling publication in Python, because older consumers reject unknown JSON fields.
+Snapshots without traversal metadata keep their existing completion and validation behavior.
+
+A field can carry one of two optional annotations:
+
+- `relation` points to an opaque key in the catalog's `relations` map.
+- `propertyNamespace` points to a key in the catalog's `properties` map.
+
+Each relation definition contains either a `table` reference to an exact canonical key in `tables`, or a `fields` map with the same field format as a top-level table.
+Use `table` when the target has the same permitted fields as an existing catalog table; the consumer reuses that table's prepared field index.
+Use `fields` for virtual targets or targets with a different schema.
+For example, HogQL can resolve `events.person` to a virtual person schema backed by event columns rather than the full `persons` schema.
+The publisher must resolve the effective target instead of inferring it from the field name.
+The relation key is not a SQL table name.
+Traversal definitions never appear in table suggestions, table aliases, or validation's `tableNames` output.
+They are reachable only through fields on a bound source.
+For example, this synthetic catalog exposes a person relation through events without adding another FROM table:
+
+```json
+{
+ "tables": {
+ "events": {
+ "name": "events",
+ "type": "posthog",
+ "fields": {
+ "person": { "name": "person", "type": "field_traverser", "relation": "event-person" }
+ }
+ }
+ },
+ "relations": {
+ "event-person": {
+ "fields": {
+ "id": { "name": "id", "type": "string" },
+ "properties": { "name": "properties", "type": "json", "propertyNamespace": "person" }
+ }
+ }
+ },
+ "properties": {
+ "person": [{ "name": "email", "property_type": "String" }]
+ }
+}
+```
+
+With that snapshot, completion at `|` supports:
+
+| SQL | Suggestions |
+| -------------------------------------------------------- | ------------------ |
+| `SELECT event.person.\| FROM events AS event` | `id`, `properties` |
+| `SELECT event.person.pro\| FROM events AS event` | `properties` |
+| `SELECT event.person.properties.\| FROM events AS event` | `email` |
+| `SELECT person.\| FROM events` | `id`, `properties` |
+
+The same graph format can describe session fields, group fields, custom lazy joins, and multi-hop relationships.
+For example, when `sessions` and `groups` are published canonical tables, these relation definitions reuse their fields:
+
+```json
+{
+ "event-session": { "table": "sessions" },
+ "event-group-0": {
+ "table": "groups",
+ "propertyNamespaces": { "properties": "group:0" }
+ },
+ "event-group-1": {
+ "table": "groups",
+ "propertyNamespaces": { "properties": "group:1" }
+ }
+}
+```
+
+Attach those relation IDs to the corresponding `events.session`, `events.group_0`, and `events.group_1` fields.
+Completion for `SELECT e.session.| FROM events AS e` then lists fields from the published `sessions` table.
+Completion for `SELECT e.group_0.properties.| FROM events AS e` uses the published `group:0` property list; `group_1` uses `group:1`.
+The optional `propertyNamespaces` map binds direct fields of a referenced table to published property lists.
+Each binding applies only inside that relation, not to the top-level table or another relation that references it.
+The consumer does not infer group indices or carry a binding through a further relation hop.
+
+Completion and validation use the same traversal resolver.
+Explicit traversal metadata takes precedence over built-in property-name heuristics; a missing field on a traversed relation does not inherit a namespace from its spelling.
+Existing source binding, alias visibility, and ambiguity rules still apply.
+
+Relation IDs and property namespaces must refer to published definitions, and a field cannot carry both annotations.
+Table references must use canonical keys, not aliases, and cannot also supply `fields`.
+Property-list bindings require a table reference and an exact target field that has no relation annotation.
+Admission allows at most 4,096 relation definitions and 120,000 inline fields and property-list bindings combined, in addition to existing top-level tables.
+Referenced table fields count once toward cache memory, regardless of how many relations reuse them.
+The cache budget includes the traversal graph and annotations; the catalog request remains bounded by 64 MiB.
+Cycles are allowed without recursive expansion.
+Each query path can follow at most 16 relation hops and also consumes the request's field-lookup work budget.
+
+This first consumer slice supports traversal from bound catalog sources, including sources inside CTE bodies.
+Direct top-level property containers retain their explicit namespace through the existing projected-field provenance rules.
+Projecting a relation or nested virtual property container through a CTE, subquery, or SELECT alias does not yet retain traversal provenance.
+Quoted path completion, nested JSON schemas, scalar traverser expression inference, and execution of lazy joins remain outside this slice.
+For deeper JSON paths under an explicit property namespace, validation checks the first property key but does not validate its descendants.
+
+The Python publisher follow-up must resolve `LazyJoin`, `VirtualTable`, and table-valued `FieldTraverser` targets using the same permission-filtered database as the snapshot.
+It must publish only permitted fields, reuse canonical table schemas when they match the resolved target, and deduplicate virtual relation definitions.
+It must bound traversal during publication and isolate unresolvable edges without exposing denied targets.
+It must also distinguish traversal-capable revisions so cached flat snapshots refresh instead of hiding the new suggestions until expiry.
+Scalar traversers need no relation annotation.
+No Python resolver chains, join SQL, credentials, or executable expressions belong in the graph.
+
## Query analysis
`internal/analysis` owns parsed statements, nested scopes, table and CTE bindings, and projected fields for validation and completion.
@@ -196,7 +302,7 @@ Closed block comments and line comments at end of input remain valid.
- Recovery does not target a cursor inside a CTE definition or FROM/JOIN source section. It also rejects queries with any nested SELECT in the outer query, including an intact FROM subquery or predicate subquery. Per-scope recovery must first preserve cursor ownership and alias visibility without importing sibling bindings.
- Set-operation and multi-statement recovery, scalar WITH declarations, and unterminated quoted tokens or comments remain excluded. These need separate statement/branch selection and lexical recovery rules before the service can infer bindings safely.
- 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.
+- Projecting a relation or nested virtual container such as `e.person.properties AS props` does not retain traversal provenance. Extend projected-field provenance before enabling those paths outside their source scope; direct source traversal requires explicit catalog annotations, and existing physical property paths remain available.
- Single-SELECT recovery without WITH retains only FROM bindings and does not guess discarded aliases. Extending SELECT-alias recovery there requires preserving its SELECT list and visibility positions as the CTE-aware path does.
- 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.
diff --git a/services/hogql-language-service/internal/analysis/document.go b/services/hogql-language-service/internal/analysis/document.go
index 06866efbb0bd..892e1e67e7a9 100644
--- a/services/hogql-language-service/internal/analysis/document.go
+++ b/services/hogql-language-service/internal/analysis/document.go
@@ -80,6 +80,9 @@ func (d *Document) LimitError() error {
if d.budget.lookupExceeded {
return querylimits.ErrFieldLookupTooLarge
}
+ if d.budget.relationExceeded {
+ return querylimits.ErrRelationTraversalTooDeep
+ }
return nil
}
@@ -232,6 +235,12 @@ func (b Bindings) UniqueRelations() iter.Seq[Relation] {
}
func (b Bindings) PropertyNamespace(parts []string) (string, bool) {
+ if len(parts) < 2 {
+ return "", false
+ }
+ if target := b.Traversal(parts[:len(parts)-1]); target.Explicit {
+ return target.PropertyNamespace, target.Valid && target.PropertyNamespace != "" && !target.HasProperty
+ }
if len(parts) > 2 && b.scope.hasDuplicateSource(parts[0]) {
return "", false
}
@@ -291,6 +300,113 @@ func (b Bindings) PropertyNamespace(parts []string) (string, bool) {
return propertyresolver.Resolve(parts, names)
}
+type TraversalTarget struct {
+ Fields *catalog.PreparedFields
+ PropertyNamespace string
+ Explicit bool
+ Valid bool
+ Failed bool
+ FailureAt int
+ HasProperty bool
+ PropertyAt int
+}
+
+func (b Bindings) Traversal(parts []string) TraversalTarget {
+ if len(parts) == 0 || b.scope == nil {
+ return TraversalTarget{}
+ }
+ var fields *catalog.PreparedFields
+ var relationView *catalog.PreparedRelation
+ index := 0
+ if relation, ok := b.Relation(parts[0]); ok {
+ if b.scope.hasDuplicateSource(parts[0]) {
+ return TraversalTarget{Explicit: true}
+ }
+ if relation.table == nil {
+ return TraversalTarget{}
+ }
+ fields = &relation.table.Fields
+ index = 1
+ } else {
+ matches := 0
+ annotated := 0
+ for source := range b.sources() {
+ if _, ok := source.relation.Field(parts[0]); !ok {
+ continue
+ }
+ matches++
+ if b.scope.hasDuplicateSource(source.name) {
+ return TraversalTarget{Explicit: true}
+ }
+ if source.relation.table != nil {
+ if _, ok := source.relation.table.Fields.Traversal(parts[0]); ok {
+ fields = &source.relation.table.Fields
+ annotated++
+ }
+ }
+ }
+ if annotated == 0 {
+ return TraversalTarget{}
+ }
+ if alias, ok := b.selectAlias(parts[0]); ok {
+ if len(parts) == 1 && alias.propertyNamespace != "" {
+ return TraversalTarget{PropertyNamespace: alias.propertyNamespace, Explicit: true, Valid: true}
+ }
+ return TraversalTarget{Explicit: true}
+ }
+ if matches != 1 || annotated != 1 {
+ return TraversalTarget{Explicit: true}
+ }
+ }
+ hops := 0
+ explicit := false
+ for ; index < len(parts); index++ {
+ if !b.scope.budget.lookup(len(parts[index]) + 1) {
+ return TraversalTarget{Explicit: explicit}
+ }
+ entry, ok := fields.Exact(parts[index])
+ if !ok {
+ return TraversalTarget{Fields: fields, Explicit: explicit, Failed: explicit, FailureAt: index}
+ }
+ var traversal catalog.FieldTraversal
+ if relationView != nil {
+ traversal, ok = relationView.Traversal(parts[index])
+ } else {
+ traversal, ok = fields.Traversal(parts[index])
+ }
+ if !ok {
+ if explicit && strings.EqualFold(entry.Type, "JSON") {
+ return TraversalTarget{Explicit: true}
+ }
+ return TraversalTarget{Fields: fields, Explicit: explicit, Failed: explicit, FailureAt: index + 1}
+ }
+ explicit = true
+ if traversal.PropertyNamespace != "" {
+ if index != len(parts)-1 {
+ return TraversalTarget{
+ PropertyNamespace: traversal.PropertyNamespace,
+ Explicit: true,
+ Valid: true,
+ HasProperty: true,
+ PropertyAt: index + 1,
+ }
+ }
+ return TraversalTarget{PropertyNamespace: traversal.PropertyNamespace, Explicit: true, Valid: true}
+ }
+ hops++
+ if hops > querylimits.MaxRelationTraversalHops {
+ b.scope.budget.relationExceeded = true
+ return TraversalTarget{Explicit: true}
+ }
+ if traversal.Relation == nil {
+ return TraversalTarget{Explicit: true}
+ }
+ relationView = traversal.Relation
+ fields = traversal.Relation.Fields
+ }
+ return TraversalTarget{Fields: fields, Explicit: explicit, Valid: fields != nil}
+}
+
func (r Relation) Name() string {
return r.name
}
diff --git a/services/hogql-language-service/internal/analysis/scopes.go b/services/hogql-language-service/internal/analysis/scopes.go
index 0465e308460e..a09275eefffd 100644
--- a/services/hogql-language-service/internal/analysis/scopes.go
+++ b/services/hogql-language-service/internal/analysis/scopes.go
@@ -37,10 +37,11 @@ type projectedField struct {
}
type projectionBudget struct {
- remaining int
- exceeded bool
- lookupRemaining int
- lookupExceeded bool
+ remaining int
+ exceeded bool
+ lookupRemaining int
+ lookupExceeded bool
+ relationExceeded bool
}
type queryScope struct {
@@ -412,6 +413,9 @@ func bindingPropertyNamespace(binding Relation, name string) (string, bool) {
if _, ok := binding.table.Fields.Exact(name); !ok {
return "", false
}
+ if traversal, ok := binding.table.Fields.Traversal(name); ok {
+ return traversal.PropertyNamespace, traversal.PropertyNamespace != ""
+ }
return propertyresolver.Resolve([]string{binding.table.Name, name, "property"}, nil)
}
if binding.cte == nil {
diff --git a/services/hogql-language-service/internal/catalog/catalog.go b/services/hogql-language-service/internal/catalog/catalog.go
index 0f78cd390bac..61657a7b9a9f 100644
--- a/services/hogql-language-service/internal/catalog/catalog.go
+++ b/services/hogql-language-service/internal/catalog/catalog.go
@@ -9,8 +9,16 @@ import (
)
type Field struct {
- Name string `json:"name"`
- Type string `json:"type"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Relation string `json:"relation,omitempty"`
+ PropertyNamespace string `json:"propertyNamespace,omitempty"`
+}
+
+type RelationDefinition struct {
+ Fields map[string]Field `json:"fields"`
+ Table string `json:"table,omitempty"`
+ PropertyNamespaces map[string]string `json:"propertyNamespaces,omitempty"`
}
type Table struct {
@@ -26,9 +34,10 @@ type Property struct {
}
type Catalog struct {
- Tables map[string]Table `json:"tables"`
- TableAliases map[string]string `json:"tableAliases,omitempty"`
- Properties map[string][]Property `json:"properties"`
+ Tables map[string]Table `json:"tables"`
+ TableAliases map[string]string `json:"tableAliases,omitempty"`
+ Properties map[string][]Property `json:"properties"`
+ Relations map[string]RelationDefinition `json:"relations,omitempty"`
}
type Entry struct {
@@ -43,7 +52,23 @@ type Index struct {
type PreparedTable struct {
Name string
Type string
- Fields Index
+ Fields PreparedFields
+}
+
+type PreparedRelation struct {
+ Fields *PreparedFields
+ propertyNamespaces map[string]string
+ ownedFields bool
+}
+
+type FieldTraversal struct {
+ Relation *PreparedRelation
+ PropertyNamespace string
+}
+
+type PreparedFields struct {
+ Index
+ traversals map[string]FieldTraversal
}
type PreparedCatalog struct {
@@ -52,6 +77,7 @@ type PreparedCatalog struct {
tablesByName map[string]int
tableValues []PreparedTable
properties map[string]*Index
+ relations map[string]*PreparedRelation
valid bool
tableCount int
propertyCount int
@@ -83,12 +109,57 @@ func Prepare(value *Catalog) *PreparedCatalog {
fieldEntries = append(fieldEntries, newEntry(fieldName, intern(types, field.Type)))
}
tableType := intern(types, table.Type)
- preparedTable := PreparedTable{Name: name, Type: tableType, Fields: newIndex(fieldEntries[fieldStart:])}
+ preparedTable := PreparedTable{Name: name, Type: tableType, Fields: PreparedFields{Index: newIndex(fieldEntries[fieldStart:])}}
prepared.tablesByName[name] = len(prepared.tableValues)
prepared.tableValues = append(prepared.tableValues, preparedTable)
tableEntries = append(tableEntries, newEntry(name, tableType))
}
prepared.tables = newIndex(tableEntries)
+ if len(value.Relations) > 0 {
+ prepared.relations = make(map[string]*PreparedRelation, len(value.Relations))
+ }
+ for name, relation := range value.Relations {
+ preparedRelation := &PreparedRelation{}
+ if relation.Fields != nil {
+ entries := make([]Entry, 0, len(relation.Fields))
+ for fieldName, field := range relation.Fields {
+ entries = append(entries, newEntry(fieldName, intern(types, field.Type)))
+ }
+ fields := PreparedFields{Index: newIndex(entries)}
+ preparedRelation.Fields = &fields
+ preparedRelation.ownedFields = true
+ } else if tableIndex, ok := prepared.tablesByName[relation.Table]; ok {
+ preparedRelation.Fields = &prepared.tableValues[tableIndex].Fields
+ }
+ if len(relation.PropertyNamespaces) > 0 {
+ preparedRelation.propertyNamespaces = make(map[string]string, len(relation.PropertyNamespaces))
+ for fieldName, namespace := range relation.PropertyNamespaces {
+ preparedRelation.propertyNamespaces[fieldName] = namespace
+ }
+ }
+ prepared.relations[name] = preparedRelation
+ }
+ prepareTraversals := func(fields map[string]Field, target *PreparedFields) {
+ for fieldName, field := range fields {
+ if field.Relation == "" && field.PropertyNamespace == "" {
+ continue
+ }
+ if target.traversals == nil {
+ target.traversals = make(map[string]FieldTraversal)
+ }
+ target.traversals[fieldName] = FieldTraversal{
+ Relation: prepared.relations[field.Relation], PropertyNamespace: field.PropertyNamespace,
+ }
+ }
+ }
+ for name, table := range value.Tables {
+ prepareTraversals(table.Fields, &prepared.tableValues[prepared.tablesByName[name]].Fields)
+ }
+ for name, relation := range value.Relations {
+ if relation.Fields != nil {
+ prepareTraversals(relation.Fields, prepared.relations[name].Fields)
+ }
+ }
prepared.tableSpellings = prepared.tables
if prepared.valid {
spellingEntries := slices.Clone(tableEntries)
@@ -117,6 +188,29 @@ func Prepare(value *Catalog) *PreparedCatalog {
return prepared
}
+func (f *PreparedFields) Traversal(name string) (FieldTraversal, bool) {
+ entry, ok := f.Exact(name)
+ if !ok || f.traversals == nil {
+ return FieldTraversal{}, false
+ }
+ traversal, ok := f.traversals[entry.Name]
+ return traversal, ok
+}
+
+func (r *PreparedRelation) Traversal(name string) (FieldTraversal, bool) {
+ if r == nil || r.Fields == nil {
+ return FieldTraversal{}, false
+ }
+ entry, ok := r.Fields.Exact(name)
+ if !ok {
+ return FieldTraversal{}, false
+ }
+ if namespace, ok := r.propertyNamespaces[entry.Name]; ok {
+ return FieldTraversal{PropertyNamespace: namespace}, true
+ }
+ return r.Fields.Traversal(entry.Name)
+}
+
func (c *PreparedCatalog) Table(name string) (*PreparedTable, bool) {
index, ok := c.tablesByName[name]
if !ok {
@@ -298,6 +392,34 @@ func (c *PreparedCatalog) estimateSize() int64 {
size += entrySize(property)
}
}
+ for name, relation := range c.relations {
+ size += int64(len(name) + 64)
+ if relation.ownedFields && relation.Fields != nil {
+ for _, field := range relation.Fields.entries {
+ size += entrySize(field)
+ if traversal, ok := relation.Fields.traversals[field.Name]; ok {
+ size += int64(len(traversal.PropertyNamespace) + 48)
+ }
+ }
+ if relation.Fields.traversals != nil {
+ size += 64
+ }
+ }
+ if relation.propertyNamespaces != nil {
+ size += 64
+ for fieldName, namespace := range relation.propertyNamespaces {
+ size += int64(len(fieldName) + len(namespace) + 48)
+ }
+ }
+ }
+ for _, table := range c.tableValues {
+ if table.Fields.traversals != nil {
+ size += 64
+ }
+ for _, traversal := range table.Fields.traversals {
+ size += int64(len(traversal.PropertyNamespace) + 48)
+ }
+ }
return size
}
diff --git a/services/hogql-language-service/internal/catalog/catalog_test.go b/services/hogql-language-service/internal/catalog/catalog_test.go
index 05927b07f6ff..0fb80b3f23a3 100644
--- a/services/hogql-language-service/internal/catalog/catalog_test.go
+++ b/services/hogql-language-service/internal/catalog/catalog_test.go
@@ -1,6 +1,11 @@
package catalog
-import "testing"
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "testing"
+)
func TestIndexExactUsesUnicodeCaseFolding(t *testing.T) {
index := newIndex([]Entry{newEntry("t", "String"), newEntry("ſ", "String")})
@@ -117,3 +122,135 @@ func TestValidateCatalogRejectsInvalidAliases(t *testing.T) {
t.Fatalf("canonical identity alias was rejected: %v", err)
}
}
+
+func TestPrepareCopiesAndValidatesTraversalRelations(t *testing.T) {
+ value := &Catalog{
+ Tables: map[string]Table{"events": {Fields: map[string]Field{"person": {Type: "lazy", Relation: "person"}}}},
+ Relations: map[string]RelationDefinition{"person": {Fields: map[string]Field{
+ "email": {Type: "String"}, "properties": {Type: "JSON", PropertyNamespace: "person"},
+ }}},
+ Properties: map[string][]Property{"person": {{Name: "plan", ValueType: "String"}}},
+ }
+ prepared := Prepare(value)
+ value.Relations["person"] = RelationDefinition{Fields: map[string]Field{"changed": {Type: "String"}}}
+ table, ok := prepared.Table("events")
+ if !ok {
+ t.Fatal("events table was not prepared")
+ }
+ traversal, ok := table.Fields.Traversal("person")
+ if !ok || traversal.Relation == nil {
+ t.Fatal("person traversal was not prepared")
+ }
+ if _, ok := traversal.Relation.Fields.Exact("email"); !ok {
+ t.Fatal("prepared relation changed with source catalog")
+ }
+ if _, ok := traversal.Relation.Fields.Exact("changed"); ok {
+ t.Fatal("prepared relation retained the source map")
+ }
+
+ for name, invalid := range map[string]*Catalog{
+ "dangling relation": {Tables: map[string]Table{"events": {Fields: map[string]Field{"person": {Relation: "missing"}}}}, Properties: map[string][]Property{}},
+ "dangling namespace": {Tables: map[string]Table{"events": {Fields: map[string]Field{"properties": {PropertyNamespace: "missing"}}}}, Properties: map[string][]Property{}},
+ "two targets": {Tables: map[string]Table{"events": {Fields: map[string]Field{"person": {Relation: "person", PropertyNamespace: "person"}}}}, Relations: map[string]RelationDefinition{"person": {Fields: map[string]Field{}}}, Properties: map[string][]Property{"person": {}}},
+ "relation union": {Tables: map[string]Table{"events": {Fields: map[string]Field{}}}, Relations: map[string]RelationDefinition{"person": {Fields: map[string]Field{}, Table: "events"}}, Properties: map[string][]Property{}},
+ "missing table": {Tables: map[string]Table{"events": {Fields: map[string]Field{}}}, Relations: map[string]RelationDefinition{"person": {Table: "missing"}}, Properties: map[string][]Property{}},
+ "table alias": {Tables: map[string]Table{"events": {Fields: map[string]Field{}}}, TableAliases: map[string]string{"legacy_events": "events"}, Relations: map[string]RelationDefinition{"person": {Table: "legacy_events"}}, Properties: map[string][]Property{}},
+ "bad override field": {Tables: map[string]Table{"events": {Fields: map[string]Field{}}}, Relations: map[string]RelationDefinition{"person": {Table: "events", PropertyNamespaces: map[string]string{"missing": "person"}}}, Properties: map[string][]Property{"person": {}}},
+ "neither target": {Tables: map[string]Table{"events": {Fields: map[string]Field{}}}, Relations: map[string]RelationDefinition{"person": {}}, Properties: map[string][]Property{}},
+ "virtual override": {Tables: map[string]Table{"events": {Fields: map[string]Field{}}}, Relations: map[string]RelationDefinition{"person": {Fields: map[string]Field{}, PropertyNamespaces: map[string]string{"properties": "person"}}}, Properties: map[string][]Property{"person": {}}},
+ "unknown override": {Tables: map[string]Table{"events": {Fields: map[string]Field{"properties": {Type: "JSON"}}}}, Relations: map[string]RelationDefinition{"person": {Table: "events", PropertyNamespaces: map[string]string{"properties": "missing"}}}, Properties: map[string][]Property{}},
+ "relation override": {Tables: map[string]Table{"events": {Fields: map[string]Field{"owner": {Relation: "person"}}}}, Relations: map[string]RelationDefinition{
+ "events": {Table: "events", PropertyNamespaces: map[string]string{"owner": "person"}}, "person": {Fields: map[string]Field{}},
+ }, Properties: map[string][]Property{"person": {}}},
+ } {
+ t.Run(name, func(t *testing.T) {
+ if ValidateCatalog(invalid) == nil {
+ t.Fatal("invalid traversal catalog was accepted")
+ }
+ })
+ }
+}
+
+func TestPrepareSharesTableRelationFieldsAndCopiesOverrides(t *testing.T) {
+ value := &Catalog{
+ Tables: map[string]Table{
+ "events": {Fields: map[string]Field{"person": {Type: "lazy", Relation: "person"}}},
+ "persons": {Fields: map[string]Field{"email": {Type: "String"}, "properties": {Type: "JSON"}}},
+ },
+ Relations: map[string]RelationDefinition{
+ "person": {Table: "persons", PropertyNamespaces: map[string]string{"properties": "person"}},
+ },
+ Properties: map[string][]Property{"person": {{Name: "plan", ValueType: "String"}}},
+ }
+ prepared := Prepare(value)
+ persons, _ := prepared.Table("persons")
+ events, _ := prepared.Table("events")
+ personTraversal, ok := events.Fields.Traversal("person")
+ if !ok || personTraversal.Relation.Fields != &persons.Fields {
+ t.Fatal("table-backed relation did not share canonical prepared fields")
+ }
+ value.Relations["person"].PropertyNamespaces["properties"] = "changed"
+ propertiesTraversal, ok := personTraversal.Relation.Traversal("PROPERTIES")
+ if !ok || propertiesTraversal.PropertyNamespace != "person" {
+ t.Fatalf("prepared override = %#v, %t", propertiesTraversal, ok)
+ }
+ if _, ok := persons.Fields.Traversal("properties"); ok {
+ t.Fatal("relation override mutated canonical table metadata")
+ }
+
+ invalid := &Catalog{
+ Tables: map[string]Table{"events": {Fields: map[string]Field{}}},
+ Relations: map[string]RelationDefinition{"missing": {Table: "missing"}},
+ Properties: map[string][]Property{},
+ }
+ if preparedInvalid := Prepare(invalid); preparedInvalid == nil || preparedInvalid.valid {
+ t.Fatalf("invalid table-backed relation prepared as valid: %#v", preparedInvalid)
+ }
+}
+
+func TestCatalogJSONPreservesEmptyVirtualRelation(t *testing.T) {
+ value := Catalog{
+ Tables: map[string]Table{"events": {Fields: map[string]Field{}}},
+ Relations: map[string]RelationDefinition{"empty": {Fields: map[string]Field{}}},
+ Properties: map[string][]Property{},
+ }
+ encoded, err := json.Marshal(value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var decoded Catalog
+ if err := json.Unmarshal(encoded, &decoded); err != nil {
+ t.Fatal(err)
+ }
+ if decoded.Relations["empty"].Fields == nil || ValidateCatalog(&decoded) != nil {
+ t.Fatalf("empty virtual relation did not round trip: %s", encoded)
+ }
+}
+
+func TestValidateCatalogRejectsTraversalLimits(t *testing.T) {
+ relations := make(map[string]RelationDefinition, MaxRelationDefinitions+1)
+ for index := 0; index <= MaxRelationDefinitions; index++ {
+ relations[fmt.Sprintf("relation_%d", index)] = RelationDefinition{Fields: map[string]Field{}}
+ }
+ if err := ValidateCatalog(&Catalog{Tables: map[string]Table{"events": {Fields: map[string]Field{}}}, Properties: map[string][]Property{}, Relations: relations}); !errors.Is(err, ErrInvalidRelations) {
+ t.Fatalf("relation definition limit error = %v", err)
+ }
+
+ fields := make(map[string]Field, MaxRelationFields/2+1)
+ for index := 0; index <= MaxRelationFields/2; index++ {
+ fields[fmt.Sprintf("field_%d", index)] = Field{Type: "String"}
+ }
+ overrides := make(map[string]string, len(fields))
+ for fieldName := range fields {
+ overrides[fieldName] = "shared"
+ }
+ if err := ValidateCatalog(&Catalog{
+ Tables: map[string]Table{"events": {Fields: fields}},
+ Properties: map[string][]Property{"shared": {}},
+ Relations: map[string]RelationDefinition{
+ "left": {Fields: fields}, "right": {Table: "events", PropertyNamespaces: overrides},
+ },
+ }); !errors.Is(err, ErrInvalidRelations) {
+ t.Fatalf("relation field limit error = %v", err)
+ }
+}
diff --git a/services/hogql-language-service/internal/catalog/registry.go b/services/hogql-language-service/internal/catalog/registry.go
index 16a3e4a8a0a2..d1d492f6b7d2 100644
--- a/services/hogql-language-service/internal/catalog/registry.go
+++ b/services/hogql-language-service/internal/catalog/registry.go
@@ -9,13 +9,17 @@ import (
)
var (
- ErrInvalidScope = errors.New("team ID and user ID must be positive")
- ErrInvalidRevision = errors.New("invalid catalog revision")
- ErrInvalidCatalog = errors.New("catalog must contain tables and properties")
- ErrInvalidAliases = errors.New("table aliases must map non-empty alternate names directly to canonical table keys")
- ErrCatalogTooLarge = errors.New("catalog exceeds cache capacity")
+ ErrInvalidScope = errors.New("team ID and user ID must be positive")
+ ErrInvalidRevision = errors.New("invalid catalog revision")
+ ErrInvalidCatalog = errors.New("catalog must contain tables and properties")
+ ErrInvalidAliases = errors.New("table aliases must map non-empty alternate names directly to canonical table keys")
+ ErrCatalogTooLarge = errors.New("catalog exceeds cache capacity")
+ ErrInvalidRelations = errors.New("catalog contains invalid traversal relations")
)
+const MaxRelationDefinitions = 4096
+const MaxRelationFields = 120000
+
type Registry struct {
mu sync.Mutex
entries map[serviceauth.Authorization]registryEntry
@@ -70,6 +74,61 @@ func ValidateCatalog(value *Catalog) error {
return ErrInvalidAliases
}
}
+ if len(value.Relations) > MaxRelationDefinitions {
+ return ErrInvalidRelations
+ }
+ relationFields := 0
+ validateFields := func(fields map[string]Field) error {
+ for _, field := range fields {
+ if field.Relation != "" && field.PropertyNamespace != "" {
+ return ErrInvalidRelations
+ }
+ if field.Relation != "" {
+ if _, ok := value.Relations[field.Relation]; !ok {
+ return ErrInvalidRelations
+ }
+ }
+ if field.PropertyNamespace != "" {
+ if _, ok := value.Properties[field.PropertyNamespace]; !ok {
+ return ErrInvalidRelations
+ }
+ }
+ }
+ return nil
+ }
+ for _, table := range value.Tables {
+ if err := validateFields(table.Fields); err != nil {
+ return err
+ }
+ }
+ for name, relation := range value.Relations {
+ ownsFields := relation.Fields != nil
+ referencesTable := relation.Table != ""
+ if name == "" || ownsFields == referencesTable || (!referencesTable && len(relation.PropertyNamespaces) > 0) {
+ return ErrInvalidRelations
+ }
+ relationFields += len(relation.Fields) + len(relation.PropertyNamespaces)
+ if relationFields > MaxRelationFields {
+ return ErrInvalidRelations
+ }
+ if ownsFields {
+ if err := validateFields(relation.Fields); err != nil {
+ return err
+ }
+ continue
+ }
+ table, ok := value.Tables[relation.Table]
+ if !ok {
+ return ErrInvalidRelations
+ }
+ for fieldName, namespace := range relation.PropertyNamespaces {
+ field, fieldExists := table.Fields[fieldName]
+ _, namespaceExists := value.Properties[namespace]
+ if fieldName == "" || !fieldExists || field.Relation != "" || namespace == "" || !namespaceExists {
+ return ErrInvalidRelations
+ }
+ }
+ }
return nil
}
diff --git a/services/hogql-language-service/internal/completion/completion.go b/services/hogql-language-service/internal/completion/completion.go
index 2907b50420d7..21427256f6ec 100644
--- a/services/hogql-language-service/internal/completion/completion.go
+++ b/services/hogql-language-service/internal/completion/completion.go
@@ -146,7 +146,18 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, posit
}
namespace, propertyPrefix, propertyOK := propertyContext(query[:position], bindings)
if propertyOK {
+ if document != nil && document.LimitError() != nil {
+ return Result{}, document.LimitError()
+ }
return indexedResult(slices.Values(schema.Properties(namespace).Prefix(propertyPrefix)), "property", offset, parseErr), nil
+ } else if target, fieldPrefix := traversalContext(query[:position], bindings); target.Explicit {
+ if document != nil && document.LimitError() != nil {
+ return Result{}, document.LimitError()
+ }
+ if !target.Valid || target.Fields == nil {
+ return Result{Suggestions: []Suggestion{}, ParseError: errorString(parseErr)}, nil
+ }
+ return indexedResult(slices.Values(target.Fields.Prefix(fieldPrefix)), "field", offset, parseErr), nil
} else if qualifier != "" {
entries := qualified.Prefix(lowerPrefix)
if document != nil && document.LimitError() != nil {
@@ -227,6 +238,13 @@ func Complete(schema *catalog.PreparedCatalog, query string, position int, posit
return result, nil
}
+func errorString(err error) string {
+ if err == nil {
+ return ""
+ }
+ return err.Error()
+}
+
func laterJoinAtCursor(query string, position int) bool {
_, cursorDepth, _ := scanSQLTokens(query[:position])
return hasLaterJoinAtDepth(query[position:], cursorDepth)
@@ -278,6 +296,22 @@ func propertyContext(input string, bindings analysis.Bindings) (string, string,
return namespace, parts[len(parts)-1], ok
}
+func traversalContext(input string, bindings analysis.Bindings) (analysis.TraversalTarget, string) {
+ start := len(input)
+ for start > 0 {
+ character, size := utf8.DecodeLastRuneInString(input[:start])
+ if character != '.' && !isIdentifier(character) {
+ break
+ }
+ start -= size
+ }
+ parts := strings.Split(input[start:], ".")
+ if len(parts) < 2 {
+ return analysis.TraversalTarget{}, ""
+ }
+ return bindings.Traversal(parts[:len(parts)-1]), parts[len(parts)-1]
+}
+
func decodeCursor(cursor string) (int, error) {
if cursor == "" {
return 0, nil
diff --git a/services/hogql-language-service/internal/completion/completion_test.go b/services/hogql-language-service/internal/completion/completion_test.go
index 559268e4dfa5..c1d247cc8906 100644
--- a/services/hogql-language-service/internal/completion/completion_test.go
+++ b/services/hogql-language-service/internal/completion/completion_test.go
@@ -6,6 +6,7 @@ import (
"fmt"
"math"
"os"
+ "slices"
"strings"
"testing"
"time"
@@ -44,6 +45,185 @@ func testCatalog() *catalog.PreparedCatalog {
}})
}
+func traversalCatalog() *catalog.PreparedCatalog {
+ return catalog.Prepare(&catalog.Catalog{
+ Tables: map[string]catalog.Table{
+ "events": {Type: "posthog", Fields: map[string]catalog.Field{
+ "event": {Type: "String"}, "person": {Type: "lazy", Relation: "person"},
+ "properties": {Type: "JSON", PropertyNamespace: "person"},
+ }},
+ },
+ Relations: map[string]catalog.RelationDefinition{
+ "person": {Fields: map[string]catalog.Field{
+ "email": {Type: "String"}, "properties": {Type: "JSON", PropertyNamespace: "person"},
+ "manager": {Type: "lazy", Relation: "person"}, "payload": {Type: "JSON"},
+ }},
+ },
+ Properties: map[string][]catalog.Property{"person": {{Name: "plan", ValueType: "String"}}},
+ })
+}
+
+func TestCompletesTraversalRelationsWithoutGlobalLeakage(t *testing.T) {
+ for _, test := range []struct {
+ query, expected, kind string
+ }{
+ {"SELECT e.person.em FROM events AS e", "email", "field"},
+ {"SELECT person.em FROM events", "email", "field"},
+ {"SELECT e.person.properties.pl FROM events AS e", "plan", "property"},
+ {"SELECT e.person.manager.em FROM events AS e", "email", "field"},
+ {"SELECT properties AS properties, properties.pl FROM events", "plan", "property"},
+ } {
+ result, err := Complete(traversalCatalog(), test.query, strings.Index(test.query, " FROM"), PositionEncodingUTF8, "")
+ if err != nil || len(result.Suggestions) != 1 || result.Suggestions[0].Label != test.expected || result.Suggestions[0].Kind != test.kind {
+ t.Fatalf("query %q returned %#v, %v", test.query, result, err)
+ }
+ }
+ for _, query := range []string{
+ "SELECT e.person. FROM events AS e",
+ "SELECT person. FROM events",
+ } {
+ result, err := Complete(traversalCatalog(), query, strings.Index(query, " FROM"), PositionEncodingUTF8, "")
+ if err != nil {
+ t.Fatalf("query %q returned %v", query, err)
+ }
+ labels := make([]string, len(result.Suggestions))
+ for index, suggestion := range result.Suggestions {
+ labels[index] = suggestion.Label
+ }
+ if got, want := strings.Join(labels, ","), "email,manager,payload,properties"; got != want {
+ t.Fatalf("query %q labels = %q, want %q", query, got, want)
+ }
+ }
+ result, err := Complete(traversalCatalog(), "SELECT * FROM per", len("SELECT * FROM per"), PositionEncodingUTF8, "")
+ if err != nil || len(result.Suggestions) != 0 {
+ t.Fatalf("traversal relation leaked into tables: %#v, %v", result, err)
+ }
+ query := "SELECT e.person.properties.plan. FROM events AS e"
+ result, err = Complete(traversalCatalog(), query, strings.Index(query, " FROM"), PositionEncodingUTF8, "")
+ if err != nil || len(result.Suggestions) != 0 {
+ t.Fatalf("nested property returned top-level suggestions: %#v, %v", result, err)
+ }
+}
+
+func TestExplicitTraversalDoesNotFallBackToLegacyPropertyNamespace(t *testing.T) {
+ schema := catalog.Prepare(&catalog.Catalog{
+ Tables: map[string]catalog.Table{"events": {Fields: map[string]catalog.Field{
+ "person": {Type: "lazy", Relation: "person"},
+ }}},
+ Relations: map[string]catalog.RelationDefinition{"person": {Fields: map[string]catalog.Field{
+ "email": {Type: "String"},
+ }}},
+ Properties: map[string][]catalog.Property{"person": {{Name: "plan", ValueType: "String"}}},
+ })
+ query := "SELECT e.person.properties. FROM events AS e"
+ result, err := Complete(schema, query, strings.Index(query, " FROM"), PositionEncodingUTF8, "")
+ if err != nil || len(result.Suggestions) != 0 {
+ t.Fatalf("explicit relation returned legacy properties: %#v, %v", result, err)
+ }
+}
+
+func TestTableBackedTraversalReusesFieldsAndScopesPropertyOverrides(t *testing.T) {
+ schema := catalog.Prepare(&catalog.Catalog{
+ Tables: map[string]catalog.Table{
+ "events": {Fields: map[string]catalog.Field{
+ "group": {Type: "lazy", Relation: "group_0"}, "other_group": {Type: "lazy", Relation: "group_1"},
+ }},
+ "groups": {Fields: map[string]catalog.Field{
+ "name": {Type: "String"}, "properties": {Type: "JSON", PropertyNamespace: "group"},
+ "owner": {Type: "lazy", Relation: "person"},
+ }},
+ },
+ Relations: map[string]catalog.RelationDefinition{
+ "group_0": {Table: "groups", PropertyNamespaces: map[string]string{"properties": "group:0"}},
+ "group_1": {Table: "groups", PropertyNamespaces: map[string]string{"properties": "group:1"}},
+ "person": {Fields: map[string]catalog.Field{
+ "properties": {Type: "JSON", PropertyNamespace: "person"}, "group": {Type: "lazy", Relation: "group_1"},
+ }},
+ },
+ Properties: map[string][]catalog.Property{
+ "group": {{Name: "base", ValueType: "String"}}, "group:0": {{Name: "zero", ValueType: "String"}},
+ "group:1": {{Name: "one", ValueType: "String"}},
+ "person": {{Name: "email", ValueType: "String"}},
+ },
+ })
+ for _, test := range []struct {
+ query string
+ expected []string
+ }{
+ {"SELECT e.group.na FROM events AS e", []string{"name"}},
+ {"SELECT e.group.properties. FROM events AS e", []string{"zero"}},
+ {"SELECT e.other_group.properties. FROM events AS e", []string{"one"}},
+ {"SELECT g.properties. FROM groups AS g", []string{"base"}},
+ {"SELECT e.group.owner.properties. FROM events AS e", []string{"email"}},
+ {"SELECT e.group.owner.group.properties. FROM events AS e", []string{"one"}},
+ } {
+ result, err := Complete(schema, test.query, strings.Index(test.query, " FROM"), PositionEncodingUTF8, "")
+ labels := make([]string, len(result.Suggestions))
+ for index, suggestion := range result.Suggestions {
+ labels[index] = suggestion.Label
+ }
+ if err != nil || !slices.Equal(labels, test.expected) {
+ t.Fatalf("query %q returned %#v, %v", test.query, result, err)
+ }
+ }
+ result := validation.Validate(schema, "SELECT e.group.properties.one FROM events AS e")
+ if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "unknown_property" {
+ t.Fatalf("group namespace isolation validation = %#v", result)
+ }
+ path := "e.group." + strings.Repeat("owner.group.", querylimits.MaxRelationTraversalHops/2)
+ query := "SELECT " + path + "properties. FROM events AS e"
+ completion, err := Complete(schema, query, strings.Index(query, " FROM"), PositionEncodingUTF8, "")
+ if !errors.Is(err, querylimits.ErrRelationTraversalTooDeep) || len(completion.Suggestions) != 0 {
+ t.Fatalf("overlong mixed traversal returned %#v, %v", completion, err)
+ }
+}
+
+func TestTraversalCompletionRespectsAmbiguityAndShadowing(t *testing.T) {
+ queries := []string{
+ "SELECT person.em FROM events AS left JOIN events AS right ON left.event = right.event",
+ "SELECT 1 AS person, person.em FROM events",
+ "SELECT E.person.em FROM events AS e",
+ }
+ for _, query := range queries {
+ result, err := Complete(traversalCatalog(), query, strings.Index(query, " FROM"), PositionEncodingUTF8, "")
+ if err != nil || len(result.Suggestions) != 0 {
+ t.Fatalf("query %q returned %#v, %v", query, result, err)
+ }
+ }
+}
+
+func TestTraversalCompletionRejectsDuplicateQualifiedSources(t *testing.T) {
+ schema := catalog.Prepare(&catalog.Catalog{
+ Tables: map[string]catalog.Table{
+ "events": {Fields: map[string]catalog.Field{"owner": {Type: "lazy", Relation: "person"}}},
+ "orders": {Fields: map[string]catalog.Field{"owner": {Type: "lazy", Relation: "account"}}},
+ },
+ Relations: map[string]catalog.RelationDefinition{
+ "person": {Fields: map[string]catalog.Field{"email": {Type: "String"}}},
+ "account": {Fields: map[string]catalog.Field{"external_id": {Type: "String"}}},
+ },
+ Properties: map[string][]catalog.Property{},
+ })
+ for _, query := range []string{
+ "SELECT source.owner.e FROM events AS source JOIN orders AS source ON 1 = 1",
+ "SELECT owner.e FROM events AS source JOIN orders AS source ON 1 = 1",
+ } {
+ result, err := Complete(schema, query, strings.Index(query, " FROM"), PositionEncodingUTF8, "")
+ if err != nil || len(result.Suggestions) != 0 {
+ t.Fatalf("duplicate source query %q returned %#v, %v", query, result, err)
+ }
+ }
+}
+
+func TestTraversalCompletionReportsHopLimit(t *testing.T) {
+ path := "e.person." + strings.Repeat("manager.", querylimits.MaxRelationTraversalHops)
+ query := "SELECT " + path + "em FROM events AS e"
+ result, err := Complete(traversalCatalog(), query, strings.Index(query, " FROM"), PositionEncodingUTF8, "")
+ if !errors.Is(err, querylimits.ErrRelationTraversalTooDeep) || len(result.Suggestions) != 0 {
+ t.Fatalf("overlong traversal returned %#v, %v", result, err)
+ }
+}
+
func TestCompletionRejectsQueriesOutsideResourceLimits(t *testing.T) {
_, err := Complete(testCatalog(), strings.Repeat("x", 64<<10+1), 0, PositionEncodingUTF8, "")
if err == nil {
diff --git a/services/hogql-language-service/internal/httpapi/handler_test.go b/services/hogql-language-service/internal/httpapi/handler_test.go
index 7873fca25ce3..813a56bfbfcc 100644
--- a/services/hogql-language-service/internal/httpapi/handler_test.go
+++ b/services/hogql-language-service/internal/httpapi/handler_test.go
@@ -130,6 +130,54 @@ func TestCatalogAliasesStayWithinPublishedTeamAndUser(t *testing.T) {
}
}
+func TestTraversalRelationsStayWithinPublishedTeamAndUser(t *testing.T) {
+ s := newTestServer(t)
+ handler := s.handler()
+ body := `{"revision":"traversal","catalog":{"tables":{"events":{"fields":{"person":{"type":"lazy","relation":"person"},"session":{"type":"lazy","relation":"session"}}},"sessions":{"fields":{"session_id":{"type":"String"}}}},"relations":{"empty":{"fields":{}},"person":{"fields":{"email":{"type":"String"},"properties":{"type":"JSON","propertyNamespace":"person"}}},"session":{"table":"sessions"}},"properties":{"person":[{"name":"plan","property_type":"String"}]}}}`
+ request := httptest.NewRequest(http.MethodPut, scopePath(1, 10)+"/catalog", strings.NewReader(body))
+ response := httptest.NewRecorder()
+ handler.ServeHTTP(response, request)
+ if response.Code != http.StatusOK {
+ t.Fatalf("catalog upload returned %d: %s", response.Code, response.Body.String())
+ }
+ putCatalogForTest(t, handler, 1, 20, "flat", "events")
+
+ for _, test := range []struct {
+ userID int64
+ valid bool
+ }{
+ {userID: 10, valid: true},
+ {userID: 20, valid: false},
+ } {
+ request = httptest.NewRequest(http.MethodPost, scopePath(1, test.userID)+"/validate", strings.NewReader(`{"query":"SELECT e.person.email FROM events AS e"}`))
+ response = httptest.NewRecorder()
+ handler.ServeHTTP(response, request)
+ if response.Code != http.StatusOK {
+ t.Fatalf("validate returned %d: %s", response.Code, response.Body.String())
+ }
+ var result validationResponse
+ if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
+ t.Fatal(err)
+ }
+ if result.Valid != test.valid {
+ t.Fatalf("user %d result = %#v", test.userID, result)
+ }
+ }
+ request = httptest.NewRequest(http.MethodPost, scopePath(1, 10)+"/validate", strings.NewReader(`{"query":"SELECT e.session.session_id FROM events AS e"}`))
+ response = httptest.NewRecorder()
+ handler.ServeHTTP(response, request)
+ if response.Code != http.StatusOK {
+ t.Fatalf("table-backed validate returned %d: %s", response.Code, response.Body.String())
+ }
+ var result validationResponse
+ if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
+ t.Fatal(err)
+ }
+ if !result.Valid {
+ t.Fatalf("table-backed traversal result = %#v", result)
+ }
+}
+
func TestCatalogRejectsInvalidAliasMaps(t *testing.T) {
handler := newTestServer(t).handler()
for name, aliases := range map[string]string{
diff --git a/services/hogql-language-service/internal/querylimits/limits.go b/services/hogql-language-service/internal/querylimits/limits.go
index 8c2b1afc4425..781eaef32dc4 100644
--- a/services/hogql-language-service/internal/querylimits/limits.go
+++ b/services/hogql-language-service/internal/querylimits/limits.go
@@ -8,11 +8,13 @@ const MaxSuggestionInputBytes = 128
const MaxDiagnostics = 25
const MaxCTEProjectedFields = 16 << 10
const MaxFieldLookupWork = 1 << 20
+const MaxRelationTraversalHops = 16
var ErrQueryTooLarge = errors.New("query exceeds maximum size")
var ErrQueryTooDeep = errors.New("query exceeds maximum nesting depth")
var ErrCTEProjectionTooLarge = errors.New("query expands too many CTE fields; select fewer fields in each CTE")
var ErrFieldLookupTooLarge = errors.New("query requires too much field lookup work; use fewer sources or qualify field names")
+var ErrRelationTraversalTooDeep = errors.New("query traverses too many lazy relations")
func Validate(query string) error {
if len(query) > MaxQueryBytes {
diff --git a/services/hogql-language-service/internal/validation/validation.go b/services/hogql-language-service/internal/validation/validation.go
index cf1097aca078..83540568b983 100644
--- a/services/hogql-language-service/internal/validation/validation.go
+++ b/services/hogql-language-service/internal/validation/validation.go
@@ -128,6 +128,25 @@ func Validate(schema *catalog.PreparedCatalog, query string) Result {
for index, field := range typed.Fields {
parts[index] = field.Name
}
+ target := bindings.Traversal(parts[:len(parts)-1])
+ if target.Explicit {
+ for _, field := range typed.Fields {
+ ignoredIdents[field] = true
+ }
+ if target.Failed {
+ failedAt := min(target.FailureAt, len(typed.Fields)-1)
+ validateUnknownIndexedField(&diagnostics, seen, target.Fields, typed.Fields[failedAt], document)
+ } else if target.Valid && target.PropertyNamespace != "" {
+ propertyAt := len(typed.Fields) - 1
+ if target.HasProperty {
+ propertyAt = target.PropertyAt
+ }
+ validateProperty(&diagnostics, seen, schema.Properties(target.PropertyNamespace), typed.Fields[propertyAt])
+ } else if target.Valid && target.Fields != nil {
+ validateIndexedField(&diagnostics, seen, target.Fields, typed.Fields[len(typed.Fields)-1], document)
+ }
+ return true
+ }
if namespace, ok := bindings.PropertyNamespace(parts); ok {
for _, field := range typed.Fields {
ignoredIdents[field] = true
@@ -227,6 +246,32 @@ func validateField(diagnostics *[]Diagnostic, seen map[string]bool, binding anal
})
}
+func validateIndexedField(diagnostics *[]Diagnostic, seen map[string]bool, fields *catalog.PreparedFields, ident *clickhouse.Ident, document *analysis.Document) {
+ if _, ok := fields.Exact(ident.Name); ok {
+ return
+ }
+ validateUnknownIndexedField(diagnostics, seen, fields, ident, document)
+}
+
+func validateUnknownIndexedField(diagnostics *[]Diagnostic, seen map[string]bool, fields *catalog.PreparedFields, ident *clickhouse.Ident, document *analysis.Document) {
+ if len(*diagnostics) >= querylimits.MaxDiagnostics || document.LimitError() != nil {
+ return
+ }
+ key := fmt.Sprintf("%d:%d", ident.Pos(), ident.End())
+ if seen[key] {
+ return
+ }
+ seen[key] = true
+ var entries []catalog.Entry
+ if fields != nil {
+ entries = fields.Entries()
+ }
+ *diagnostics = append(*diagnostics, Diagnostic{
+ Code: "unknown_field", Message: fmt.Sprintf("Unknown field %q", ident.Name), Start: int(ident.Pos()), End: int(ident.End()),
+ Suggestions: closest(ident.Name, slices.Values(entries), 5),
+ })
+}
+
func validateUnqualifiedField(diagnostics *[]Diagnostic, seen map[string]bool, bindings analysis.Bindings, ident *clickhouse.Ident, document *analysis.Document) {
if len(*diagnostics) >= querylimits.MaxDiagnostics || document.LimitError() != nil {
return
diff --git a/services/hogql-language-service/internal/validation/validation_test.go b/services/hogql-language-service/internal/validation/validation_test.go
index f1a2f3775a63..363f71665e62 100644
--- a/services/hogql-language-service/internal/validation/validation_test.go
+++ b/services/hogql-language-service/internal/validation/validation_test.go
@@ -36,6 +36,71 @@ func schema() *catalog.PreparedCatalog {
}})
}
+func traversalSchema() *catalog.PreparedCatalog {
+ return catalog.Prepare(&catalog.Catalog{
+ Tables: map[string]catalog.Table{
+ "events": {Fields: map[string]catalog.Field{
+ "event": {Type: "String"}, "person": {Type: "lazy", Relation: "person"},
+ "session": {Type: "lazy", Relation: "session"},
+ }},
+ "sessions": {Fields: map[string]catalog.Field{"session_id": {Type: "String"}}},
+ },
+ Relations: map[string]catalog.RelationDefinition{
+ "person": {Fields: map[string]catalog.Field{
+ "email": {Type: "String"}, "properties": {Type: "JSON", PropertyNamespace: "person"},
+ "manager": {Type: "lazy", Relation: "person"}, "payload": {Type: "JSON"},
+ }},
+ "session": {Table: "sessions"},
+ },
+ Properties: map[string][]catalog.Property{"person": {{Name: "plan", ValueType: "String"}}},
+ })
+}
+
+func TestValidateTraversalRelations(t *testing.T) {
+ for _, query := range []string{
+ "SELECT e.person.email FROM events AS e",
+ "SELECT person.email FROM events",
+ "SELECT e.person.properties.plan FROM events AS e",
+ "SELECT e.person.manager.email FROM events AS e",
+ "SELECT e.person.properties.plan.nested FROM events AS e",
+ "SELECT e.person.payload.unknown FROM events AS e",
+ "SELECT e.session.session_id FROM events AS e",
+ } {
+ result := Validate(traversalSchema(), query)
+ if !result.Valid || strings.Join(result.TableNames, ",") != "events" {
+ t.Fatalf("query %q returned %#v", query, result)
+ }
+ }
+ for _, test := range []struct {
+ query, code, value string
+ }{
+ {"SELECT e.person.emali FROM events AS e", "unknown_field", "emali"},
+ {"SELECT e.person.properties.paln FROM events AS e", "unknown_property", "paln"},
+ {"SELECT e.person.properties.paln.nested FROM events AS e", "unknown_property", "paln"},
+ {"SELECT e.person.missing.email FROM events AS e", "unknown_field", "missing"},
+ } {
+ result := Validate(traversalSchema(), test.query)
+ if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != test.code {
+ t.Fatalf("query %q returned %#v", test.query, result)
+ }
+ if got := test.query[result.Diagnostics[0].Start:result.Diagnostics[0].End]; got != test.value {
+ t.Fatalf("query %q diagnostic covered %q", test.query, got)
+ }
+ }
+}
+
+func TestTraversalRelationHopLimit(t *testing.T) {
+ parts := make([]string, querylimits.MaxRelationTraversalHops+1)
+ for index := range parts {
+ parts[index] = "manager"
+ }
+ query := "SELECT e.person." + strings.Join(parts, ".") + ".email FROM events AS e"
+ result := Validate(traversalSchema(), query)
+ if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "query_limit" || result.Diagnostics[0].Message != querylimits.ErrRelationTraversalTooDeep.Error() {
+ t.Fatalf("result = %#v", result)
+ }
+}
+
func TestValidateDoesNotShareBindingsAcrossStatements(t *testing.T) {
result := Validate(schema(), "SELECT person_id FROM warehouse_orders; SELECT person_id FROM warehouse_people")
if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "unknown_field" {