: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
fix(hogql): add language service regression guards (#100902)
Paweł Szczur6075e6df872d
diff --git a/.github/workflows/ci-hogql-language-service.yml b/.github/workflows/ci-hogql-language-service.ymlindex b6048de9bfc0..3e5d3396aa02 100644--- a/.github/workflows/ci-hogql-language-service.yml+++ b/.github/workflows/ci-hogql-language-service.yml@@ -42,3 +42,9 @@ jobs:- name: Run testsworking-directory: services/hogql-language-servicerun: go test -race ./...++ - name: Enforce autocomplete latency budget+ working-directory: services/hogql-language-service+ env:+ HOGQL_LANGUAGE_SERVICE_ENFORCE_LATENCY_BUDGET: '1'+ run: go test ./internal/completion -run '^TestCompleteContextualCatalogStaysWithinLatencyBudget$' -count=1diff --git a/services/hogql-language-service/internal/completion/completion.go b/services/hogql-language-service/internal/completion/completion.goindex 61c1d29ab9c0..7a9c5475a91c 100644--- a/services/hogql-language-service/internal/completion/completion.go+++ b/services/hogql-language-service/internal/completion/completion.go@@ -41,6 +41,7 @@ const ()var keywords = []string{"SELECT", "FROM", "WHERE", "GROUP BY", "ORDER BY", "LIMIT", "JOIN", "AS", "CASE", "NULL", "TRUE", "FALSE", "NOT"}+var betweenSeparator = []string{"AND"}var predicateContinuations = []string{"AND", "OR", "GROUP BY", "ORDER BY", "LIMIT"}var comparisonOperators = []string{"=", "!=", "<", "<=", ">", ">=", "LIKE", "ILIKE", "IN", "NOT IN", "IS NULL", "IS NOT NULL", "BETWEEN", "NOT BETWEEN"}var commonFunctions = []string{"avg", "coalesce", "count", "countDistinct", "countIf", "if", "max", "min", "now", "sum", "sumIf", "toDate", "toDateTime", "uniq", "uniqExact"}@@ -105,6 +106,8 @@ func Complete(schema *catalog.Catalog, query string, position int, positionEncod}} else if mode == completionModeComparison {suggestions = appendNamed(suggestions, comparisonOperators, lowerPrefix, "operator", "")+ } else if mode == completionModeBetweenSeparator {+ suggestions = appendNamed(suggestions, betweenSeparator, lowerPrefix, "keyword", "")} else if mode == completionModePredicateContinuation {suggestions = appendNamed(suggestions, predicateContinuations, lowerPrefix, "keyword", "")} else if mode == completionModePostExpression {diff --git a/services/hogql-language-service/internal/completion/completion_test.go b/services/hogql-language-service/internal/completion/completion_test.goindex ecb7a8b0096c..ac9f0a91e6a3 100644--- a/services/hogql-language-service/internal/completion/completion_test.go+++ b/services/hogql-language-service/internal/completion/completion_test.go@@ -3,8 +3,11 @@ package completionimport ("encoding/json""fmt"+ "math"+ "os""strings""testing"+ "time""github.com/PostHog/posthog/services/hogql-language-service/internal/catalog")@@ -127,15 +130,29 @@ func TestCompletesSQLSyntaxForCursorContext(t *testing.T) {label stringkind stringinsertText string- excluded string+ excluded []string+ total int}{{name: "function in select", query: "SELECT cou FROM orders", position: len("SELECT cou"), label: "count", kind: "function", insertText: "count()"},{name: "embedded function in select", query: "SELECT geoD FROM orders", position: len("SELECT geoD"), label: "geoDistance", kind: "function", insertText: "geoDistance()"},{name: "function in where", query: "SELECT * FROM orders WHERE coa", position: len("SELECT * FROM orders WHERE coa"), label: "coalesce", kind: "function", insertText: "coalesce()"},- {name: "operator after field", query: "SELECT * FROM orders WHERE amount ", position: len("SELECT * FROM orders WHERE amount "), label: "=", kind: "operator", insertText: "=", excluded: "AND"},- {name: "boolean after predicate", query: "SELECT * FROM orders WHERE amount > 0 ", position: len("SELECT * FROM orders WHERE amount > 0 "), label: "AND", kind: "keyword", insertText: "AND", excluded: "="},+ {name: "operator after field", query: "SELECT * FROM orders WHERE amount ", position: len("SELECT * FROM orders WHERE amount "), label: "=", kind: "operator", insertText: "=", excluded: []string{"AND"}},+ {name: "boolean after predicate", query: "SELECT * FROM orders WHERE amount > 0 ", position: len("SELECT * FROM orders WHERE amount > 0 "), label: "AND", kind: "keyword", insertText: "AND", excluded: []string{"="}},+ {name: "between separator", query: "SELECT * FROM orders WHERE amount BETWEEN 1 ", position: len("SELECT * FROM orders WHERE amount BETWEEN 1 "), label: "AND", kind: "keyword", insertText: "AND", excluded: []string{"OR", "GROUP BY", "ORDER BY", "LIMIT"}, total: 1},+ {name: "between unfinished arithmetic expression", query: "SELECT * FROM orders WHERE amount BETWEEN 1 + cou", position: len("SELECT * FROM orders WHERE amount BETWEEN 1 + cou"), label: "count", kind: "function", insertText: "count()", excluded: []string{"AND"}},+ {name: "between unfinished function call", query: "SELECT * FROM orders WHERE amount BETWEEN toDate(amo", position: len("SELECT * FROM orders WHERE amount BETWEEN toDate(amo"), label: "amount", kind: "field", excluded: []string{"AND"}},+ {name: "between unfinished interval", query: "SELECT * FROM orders WHERE amount BETWEEN INTERVAL ", position: len("SELECT * FROM orders WHERE amount BETWEEN INTERVAL "), label: "amount", kind: "field", excluded: []string{"AND"}},+ {name: "between interval missing unit", query: "SELECT * FROM orders WHERE amount BETWEEN INTERVAL 1 ", position: len("SELECT * FROM orders WHERE amount BETWEEN INTERVAL 1 "), label: "amount", kind: "field", excluded: []string{"AND"}},+ {name: "between complete interval", query: "SELECT * FROM orders WHERE amount BETWEEN INTERVAL 1 DAY ", position: len("SELECT * FROM orders WHERE amount BETWEEN INTERVAL 1 DAY "), label: "AND", kind: "keyword", insertText: "AND", total: 1},+ {name: "between nested interval missing unit", query: "SELECT * FROM orders WHERE amount BETWEEN toDate(INTERVAL 1) ", position: len("SELECT * FROM orders WHERE amount BETWEEN toDate(INTERVAL 1) "), label: "amount", kind: "field", excluded: []string{"AND"}},+ {name: "between complete nested interval", query: "SELECT * FROM orders WHERE amount BETWEEN toDate(INTERVAL 1 DAY) ", position: len("SELECT * FROM orders WHERE amount BETWEEN toDate(INTERVAL 1 DAY) "), label: "AND", kind: "keyword", insertText: "AND", total: 1},+ {name: "between unfinished case", query: "SELECT * FROM orders WHERE amount BETWEEN CASE ", position: len("SELECT * FROM orders WHERE amount BETWEEN CASE "), label: "amount", kind: "field", excluded: []string{"AND"}},+ {name: "between unfinished case conjunction", query: "SELECT * FROM orders WHERE amount BETWEEN CASE WHEN amount > 0 AND amo", position: len("SELECT * FROM orders WHERE amount BETWEEN CASE WHEN amount > 0 AND amo"), label: "amount", kind: "field", excluded: []string{"AND"}},+ {name: "between complete case", query: "SELECT * FROM orders WHERE amount BETWEEN CASE WHEN amount > 0 THEN 1 ELSE 0 END ", position: len("SELECT * FROM orders WHERE amount BETWEEN CASE WHEN amount > 0 THEN 1 ELSE 0 END "), label: "AND", kind: "keyword", insertText: "AND", total: 1},{name: "field after boolean", query: "SELECT * FROM orders WHERE amount > 0 AND ", position: len("SELECT * FROM orders WHERE amount > 0 AND "), label: "amount", kind: "field"},- {name: "field after select comma", query: "SELECT amount, FROM orders", position: len("SELECT amount, "), label: "amount", kind: "field", excluded: "orders"},+ {name: "field after select comma", query: "SELECT amount, FROM orders", position: len("SELECT amount, "), label: "amount", kind: "field", excluded: []string{"orders"}},+ {name: "double-quoted clause identifier", query: `SELECT "FROM" FROM orders`, position: len(`SELECT "FROM" `), label: "count", kind: "function", insertText: "count()", excluded: []string{"orders"}},+ {name: "backtick-quoted clause identifier", query: "SELECT `JOIN` FROM orders", position: len("SELECT `JOIN` "), label: "count", kind: "function", insertText: "count()", excluded: []string{"orders"}},}for _, test := range tests {t.Run(test.name, func(t *testing.T) {@@ -143,12 +160,17 @@ func TestCompletesSQLSyntaxForCursorContext(t *testing.T) {if err != nil {t.Fatal(err)}+ if test.total > 0 && result.Total != test.total {+ t.Fatalf("suggestion total = %d, want %d; suggestions = %#v", result.Total, test.total, result.Suggestions)+ }suggestion, ok := findSuggestion(result.Suggestions, test.label)if !ok || suggestion.Kind != test.kind || suggestion.InsertText != test.insertText {t.Fatalf("suggestion %q = %#v; all suggestions = %#v; parse error = %q", test.label, suggestion, result.Suggestions, result.ParseError)}- if test.excluded != "" && hasSuggestion(result.Suggestions, test.excluded) {- t.Fatalf("unexpected suggestion %q in %#v", test.excluded, result.Suggestions)+ for _, excluded := range test.excluded {+ if hasSuggestion(result.Suggestions, excluded) {+ t.Fatalf("unexpected suggestion %q in %#v", excluded, result.Suggestions)+ }}})}@@ -220,7 +242,7 @@ func findSuggestion(suggestions []Suggestion, label string) (Suggestion, bool) {return Suggestion{}, false}-func BenchmarkCompleteContextualCatalog(b *testing.B) {+func largeContextualCatalog() *catalog.Catalog {schema := &catalog.Catalog{Tables: make(map[string]catalog.Table, 1024)}for tableIndex := 0; tableIndex < 1024; tableIndex++ {fields := make(map[string]catalog.Field, 25)@@ -231,6 +253,73 @@ func BenchmarkCompleteContextualCatalog(b *testing.B) {name := fmt.Sprintf("table_%04d", tableIndex)schema.Tables[name] = catalog.Table{Name: name, Type: "data_warehouse", Fields: fields}}+ return schema+}++func TestCompleteContextualCatalogStaysWithinLatencyBudget(t *testing.T) {+ if os.Getenv("HOGQL_LANGUAGE_SERVICE_ENFORCE_LATENCY_BUDGET") != "1" {+ t.Skip("latency budget requires the dedicated non-race test environment")+ }++ const sampleCount = 20+ const maxAverage = 5 * time.Millisecond+ const maxStandardDeviation = 5 * time.Millisecond++ schema := largeContextualCatalog()+ intervalPrefix := "SELECT * FROM table_0500 WHERE column_10 BETWEEN "+ intervalQuery := intervalPrefix + strings.Repeat("INTERVAL ", ((16<<10)-len(intervalPrefix)-len("1 DAY "))/len("INTERVAL ")) + "1 DAY "+ for _, test := range []struct {+ name string+ query string+ position int+ callsPerSample int+ }{+ {name: "contextual catalog", query: "SELECT countD FROM table_0500", position: len("SELECT countD"), callsPerSample: 100},+ {name: "adversarial interval expression", query: intervalQuery, position: len(intervalQuery), callsPerSample: 20},+ } {+ t.Run(test.name, func(t *testing.T) {+ for range test.callsPerSample {+ if _, err := Complete(schema, test.query, test.position, PositionEncodingUTF8, ""); err != nil {+ t.Fatal(err)+ }+ }+ durations := make([]float64, sampleCount)+ for sample := range sampleCount {+ startedAt := time.Now()+ for range test.callsPerSample {+ if _, err := Complete(schema, test.query, test.position, PositionEncodingUTF8, ""); err != nil {+ t.Fatal(err)+ }+ }+ durations[sample] = float64(time.Since(startedAt)) / float64(test.callsPerSample)+ }++ var total float64+ for _, duration := range durations {+ total += duration+ }+ average := total / sampleCount+ var squaredDifferences float64+ for _, duration := range durations {+ difference := duration - average+ squaredDifferences += difference * difference+ }+ standardDeviation := math.Sqrt(squaredDifferences / sampleCount)+ if time.Duration(average) > maxAverage || time.Duration(standardDeviation) > maxStandardDeviation {+ t.Fatalf(+ "completion latency average = %s (max %s), standard deviation = %s (max %s)",+ time.Duration(average),+ maxAverage,+ time.Duration(standardDeviation),+ maxStandardDeviation,+ )+ }+ })+ }+}++func BenchmarkCompleteContextualCatalog(b *testing.B) {+ schema := largeContextualCatalog()for _, benchmark := range []struct {name stringquery string@@ -238,6 +327,7 @@ func BenchmarkCompleteContextualCatalog(b *testing.B) {}{{name: "operator", query: "SELECT * FROM table_0500 WHERE column_10 ", position: len("SELECT * FROM table_0500 WHERE column_10 ")},{name: "function prefix", query: "SELECT countD FROM table_0500", position: len("SELECT countD")},+ {name: "repeated interval", query: "SELECT * FROM table_0500 WHERE column_10 BETWEEN " + strings.Repeat("INTERVAL ", 1000) + "1 DAY ", position: len("SELECT * FROM table_0500 WHERE column_10 BETWEEN ") + len("INTERVAL ")*1000 + len("1 DAY ")},} {b.Run(benchmark.name, func(b *testing.B) {result, err := Complete(schema, benchmark.query, benchmark.position, PositionEncodingUTF8, "")diff --git a/services/hogql-language-service/internal/completion/context.go b/services/hogql-language-service/internal/completion/context.goindex abae63b9fe2b..c264ba346f87 100644--- a/services/hogql-language-service/internal/completion/context.go+++ b/services/hogql-language-service/internal/completion/context.go@@ -14,6 +14,7 @@ const (completionModeTablecompletionModeExpressioncompletionModeComparison+ completionModeBetweenSeparatorcompletionModePredicateContinuationcompletionModePostExpression)@@ -75,26 +76,42 @@ func activeClause(tokens []sqlToken, depth int) (int, string) {func predicateMode(tokens []sqlToken, depth int) completionMode {start := 0betweenPending := false+ caseDepth := 0for index, token := range tokens {if token.kind == sqlTokenLeftParen && token.depth == depth-1 {start = index + 1betweenPending = false+ caseDepth = 0continue}if token.depth != depth || token.kind != sqlTokenWord {continue}- if token.text == "BETWEEN" {- betweenPending = true- continue- }- if token.text == "AND" && betweenPending {- betweenPending = false- continue- }- if token.text == "AND" || token.text == "OR" {+ switch token.text {+ case "CASE":+ caseDepth+++ case "END":+ if caseDepth > 0 {+ caseDepth--+ }+ case "BETWEEN":+ if caseDepth == 0 {+ betweenPending = true+ }+ case "AND":+ if caseDepth > 0 {+ continue+ }+ if betweenPending {+ betweenPending = false+ continue+ }start = index + 1- betweenPending = false+ case "OR":+ if caseDepth == 0 {+ start = index + 1+ betweenPending = false+ }}}segment := tokens[start:]@@ -113,6 +130,12 @@ func predicateMode(tokens []sqlToken, depth int) completionMode {}}if comparisonIndex >= 0 {+ if betweenPending && segment[comparisonIndex].text == "BETWEEN" {+ if betweenLowerBoundComplete(segment[comparisonIndex+1:], depth) {+ return completionModeBetweenSeparator+ }+ return completionModeExpression+ }for _, token := range segment[comparisonIndex+1:] {if token.depth <= depth && token.text != "NOT" {return completionModePredicateContinuation@@ -126,6 +149,66 @@ func predicateMode(tokens []sqlToken, depth int) completionMode {return completionModeComparison}+func betweenLowerBoundComplete(tokens []sqlToken, depth int) bool {+ hasExpressionToken := false+ openCases := 0+ lastExpressionIndex := -1+ pendingIntervals := make([]int, depth+1)+ for index := range pendingIntervals {+ pendingIntervals[index] = -1+ }+ for index, token := range tokens {+ if token.depth < depth {+ break+ }+ for len(pendingIntervals) > token.depth+1 {+ if pendingIntervals[len(pendingIntervals)-1] >= 0 {+ return false+ }+ pendingIntervals = pendingIntervals[:len(pendingIntervals)-1]+ }+ for len(pendingIntervals) <= token.depth {+ pendingIntervals = append(pendingIntervals, -1)+ }+ if token.kind == sqlTokenWord {+ switch token.text {+ case "CASE":+ openCases+++ case "END":+ if openCases > 0 {+ openCases--+ }+ case "INTERVAL":+ pendingIntervals[token.depth] = index+ default:+ if isIntervalUnit(token.text) && lastExpressionIndex > pendingIntervals[token.depth] {+ pendingIntervals[token.depth] = -1+ }+ }+ }+ if token.text != "NOT" {+ hasExpressionToken = true+ }+ if token.kind == sqlTokenWord || token.kind == sqlTokenValue {+ lastExpressionIndex = index+ }+ }+ for _, intervalIndex := range pendingIntervals {+ if intervalIndex >= 0 {+ return false+ }+ }+ return hasExpressionToken && openCases == 0+}++func isIntervalUnit(value string) bool {+ switch value {+ case "MILLISECOND", "SECOND", "MINUTE", "HOUR", "DAY", "WEEK", "MONTH", "QUARTER", "YEAR":+ return true+ }+ return false+}+func lastTokenAtDepth(tokens []sqlToken, depth int) sqlToken {for index := len(tokens) - 1; index >= 0; index-- {if tokens[index].depth <= depth {diff --git a/services/hogql-language-service/internal/validation/validation.go b/services/hogql-language-service/internal/validation/validation.goindex 250c2dc5f60b..85585b31fce3 100644--- a/services/hogql-language-service/internal/validation/validation.go+++ b/services/hogql-language-service/internal/validation/validation.go@@ -110,6 +110,10 @@ func Validate(schema *catalog.Catalog, query string) Result {ignoredIdents[typed.Table] = truecase *clickhouse.FunctionExpr:ignoredIdents[typed.Name] = true+ case *clickhouse.IntervalExpr:+ ignoredIdents[typed.Unit] = true+ case *clickhouse.IntervalFrom:+ ignoredIdents[typed.Interval] = truecase *clickhouse.SelectItem:ignoredIdents[typed.Alias] = truecase *clickhouse.AliasExpr:diff --git a/services/hogql-language-service/internal/validation/validation_test.go b/services/hogql-language-service/internal/validation/validation_test.goindex d12d3c8b04cd..3fd66dfdfddd 100644--- a/services/hogql-language-service/internal/validation/validation_test.go+++ b/services/hogql-language-service/internal/validation/validation_test.go@@ -19,7 +19,12 @@ func schema() *catalog.Catalog {"postgres.synced.orders": {Name: "postgres.synced.orders", Type: "data_warehouse", Fields: map[string]catalog.Field{"synced_id": {Name: "synced_id", Type: "string"},}},- "events": {Name: "events", Type: "posthog", Fields: map[string]catalog.Field{"properties": {Name: "properties", Type: "json"}}},+ "events": {Name: "events", Type: "posthog", Fields: map[string]catalog.Field{+ "event": {Name: "event", Type: "string"},+ "properties": {Name: "properties", Type: "json"},+ "timestamp": {Name: "timestamp", Type: "datetime"},+ "uuid": {Name: "uuid", Type: "uuid"},+ }},"persons": {Name: "persons", Type: "posthog", Fields: map[string]catalog.Field{"properties": {Name: "properties", Type: "json"}}},}, Properties: map[string][]catalog.Property{"event": {{Name: "$geo_city", ValueType: "String"}},@@ -98,12 +103,21 @@ func TestValidateUnknownAliasedFieldSuggestsVisibleMatch(t *testing.T) {}func TestValidateAcceptsKnownFieldsAndFunctions(t *testing.T) {- result := Validate(schema(), "SELECT sum(o.amount), o.order_id FROM warehouse_orders AS o WHERE o.amount > 0")- if !result.Valid || len(result.Diagnostics) != 0 {- t.Fatalf("result = %#v", result)- }- if len(result.TableNames) != 1 || result.TableNames[0] != "warehouse_orders" {- t.Fatalf("table names = %#v", result.TableNames)+ for _, test := range []struct {+ query string+ tableName string+ }{+ {query: "SELECT sum(o.amount), o.order_id FROM warehouse_orders AS o WHERE o.amount > 0", tableName: "warehouse_orders"},+ {query: "SELECT uuid FROM events WHERE event = '$pageview' AND timestamp > now() - interval 1 month", tableName: "events"},+ {query: "SELECT extract(month FROM timestamp) FROM events", tableName: "events"},+ } {+ result := Validate(schema(), test.query)+ if !result.Valid || len(result.Diagnostics) != 0 {+ t.Fatalf("query %q returned %#v", test.query, result)+ }+ if len(result.TableNames) != 1 || result.TableNames[0] != test.tableName {+ t.Fatalf("query %q returned table names %#v", test.query, result.TableNames)+ }}}