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): add multitenant language service (#96266)

Paweł Szczuref48428aa044
diff --git a/.github/workflows/ci-security.yaml b/.github/workflows/ci-security.yaml
index 066ff2ac979c..dc7e0f3935b8 100644
--- a/.github/workflows/ci-security.yaml
+++ b/.github/workflows/ci-security.yaml
@@ -76,6 +76,7 @@ jobs:
- '.github/workflows/ci-security.yaml'
go:
- 'livestream/**'
+ - 'services/hogql-language-service/**'
- '.github/workflows/ci-security.yaml'
rust:
- 'cli/**'
@@ -218,6 +219,7 @@ jobs:
--config r/go.lang.security
--exclude-rule go.lang.security.audit.xss.no-fprintf-to-responsewriter.no-fprintf-to-responsewriter
--include /livestream
+ --include /services/hogql-language-service
semgrep-rust:
needs: changes
diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.md
new file mode 100644
index 000000000000..ced092aa3ab2
--- /dev/null
+++ b/docs/internal/hogql-language-service.md
@@ -0,0 +1,113 @@
+# HogQL language service
+
+## Goal
+
+The HogQL language service moves latency-sensitive SQL editor operations into a long-lived Go process. Its resident
+catalog avoids rebuilding tables, views, and property metadata for every keystroke.
+
+The service targets:
+
+- low-single-digit-millisecond autocomplete on a warm catalog;
+- a stable internal API for HogQL validation and, later, translation; and
+- low PostHog overhead above ClickHouse execution time.
+
+## Architecture
+
+```text
+Browser
+ | authenticated PostHog request
+ v
+Django
+ | resolves team membership and user permissions
+ | publishes visible catalog with a scoped service JWT
+ v
+HogQL language service
+ | selects the exact team and user catalog
+ | parses and resolves entirely in memory
+ v
+Autocomplete or validation response
+```
+
+Django remains authoritative for authentication, team membership, entitlements, feature flags, and access-control
+resolution. The Go service does not read PostHog permission tables or accept browser-selected identity without an
+authenticated internal request.
+
+## Isolation boundary
+
+Every protected route requires both `team_id` and `user_id` in its path. Shared middleware converts those values into
+one authorization struct used by JWT verification, rate limiting, catalog lookup, and request handlers.
+
+The service keys its current catalog cache by that pair because the published snapshot contains user-filtered tables
+and properties.
+
+The transport JWT also binds the request to:
+
+- one positive team ID;
+- one positive user ID;
+- one service audience;
+- an explicit operation; and
+- a short validity window.
+
+An absent, invalid, expired, or evicted catalog fails closed. The service never falls back to another team or user's
+catalog.
+
+Before reading a request body, a bounded token bucket limits the direct peer address. After JWT verification, another
+bounded bucket limits the authenticated team and user pair. The service ignores forwarded-IP headers because only
+deployment infrastructure can define a trustworthy proxy chain.
+
+A later implementation may store structural schema once per team and apply smaller user authorization overlays. The
+team remains the primary isolation boundary in that model.
+
+## Resident state
+
+Catalog publication replaces the catalog and revision atomically. Readers observe either the previous complete
+revision or the next complete revision.
+
+The in-memory registry has two bounds:
+
+- an idle TTL removes unused entries; and
+- least-recently-used eviction caps the number of entries.
+
+Warm autocomplete and validation perform no synchronous metadata requests. Catalog refresh remains outside the
+keystroke path.
+
+## API direction
+
+The initial internal API supports:
+
+- publishing and deleting a catalog for one team and user;
+- contextual autocomplete with at most 25 results and cursor pagination; and
+- syntax and catalog-backed semantic validation.
+
+Responses return the catalog revision used for computation. Callers can discard results produced from a stale
+revision.
+
+HogQL translation is the next service capability. Its stable response should contain parameterized ClickHouse SQL,
+bound values, referenced resources, output schema, warnings, and catalog revisions. The internal parser AST is not an
+API contract.
+
+## Deployment and rollout
+
+The production container builds a static binary with Go 1.27.1 and runs as a non-root user. A non-loopback listener
+fails startup unless dedicated signing keys are configured.
+
+Local and debug environments may use the service directly. Production integration remains behind a server-side
+feature flag and should progress through shadow comparison before serving editor results.
+
+The initial rollout keeps ClickHouse execution in Django:
+
+```text
+Django -> language service translation -> Django -> ClickHouse
+```
+
+Measurements must separate catalog lookup, parsing, translation, network transit, ClickHouse duration, result
+decoding, and serialization. A combined translation and execution path is justified only if the extra service hop
+prevents the overhead target.
+
+## Non-goals
+
+- Reimplementing PostHog membership or permission resolution in Go.
+- Exposing the language service directly to browsers.
+- Treating feature flags as an authorization boundary.
+- Moving ClickHouse execution before latency measurements justify it.
+- Making the parser's internal AST a compatibility contract.
diff --git a/services/hogql-language-service/.dockerignore b/services/hogql-language-service/.dockerignore
new file mode 100644
index 000000000000..99c0979fea15
--- /dev/null
+++ b/services/hogql-language-service/.dockerignore
@@ -0,0 +1,4 @@
+.git
+Dockerfile
+README.md
+**/*_test.go
diff --git a/services/hogql-language-service/Dockerfile b/services/hogql-language-service/Dockerfile
new file mode 100644
index 000000000000..f70fb1a52fd0
--- /dev/null
+++ b/services/hogql-language-service/Dockerfile
@@ -0,0 +1,36 @@
+FROM golang:1.27.1-bookworm@sha256:648f440f42a0958804efb24df176f806f9d353b41f1c0627f666428e40310f6b AS build
+
+WORKDIR /src
+
+COPY go.mod go.sum ./
+RUN --mount=type=cache,target=/go/pkg/mod go mod download
+
+COPY . ./
+
+ARG COMMIT_HASH=unknown
+ARG TARGETOS=linux
+ARG TARGETARCH
+RUN --mount=type=cache,target=/go/pkg/mod \
+ --mount=type=cache,target=/root/.cache/go-build \
+ CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build \
+ -trimpath \
+ -ldflags="-s -w" \
+ -o /out/hogql-language-service \
+ ./cmd/server && \
+ printf '%s' "${COMMIT_HASH}" > /out/commit.txt
+
+FROM scratch
+
+WORKDIR /app
+
+COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
+COPY --from=build --chown=65532:65532 /out/hogql-language-service /app/hogql-language-service
+COPY --from=build --chown=65532:65532 /out/commit.txt /app/commit.txt
+
+ENV LISTEN_ADDR=0.0.0.0:8091
+
+EXPOSE 8091
+
+USER 65532:65532
+
+ENTRYPOINT ["/app/hogql-language-service"]
diff --git a/services/hogql-language-service/README.md b/services/hogql-language-service/README.md
new file mode 100644
index 000000000000..4847d25b187a
--- /dev/null
+++ b/services/hogql-language-service/README.md
@@ -0,0 +1,147 @@
+# HogQL language service prototype
+
+This prototype keeps multiple immutable, permission-filtered catalogs in memory and provides local SQL completion.
+It uses `github.com/orian/clickhouse-sql-parser` to recover table and alias context from the query. Django remains the
+authority for deciding which schema and properties belong in each catalog.
+
+For local development, start the service on its loopback listener:
+
+```bash
+HOGQL_LANGUAGE_SERVICE_ALLOW_INSECURE=1 .codex/with-flox go -C services/hogql-language-service run ./cmd/server
+```
+
+Publish a permission-filtered catalog through the multitenant endpoint below before making language requests. The Go
+service does not hold a personal API key or fetch schema from PostHog directly.
+
+```bash
+curl -sS http://localhost:8091/health
+curl -sS -X POST http://localhost:8091/teams/2/users/1/autocomplete \
+ -H 'Content-Type: application/json' \
+ -d '{"query":"SELECT o. FROM orders AS o","position":9}'
+```
+
+Validate syntax and catalog-backed table and field references:
+
+```bash
+curl -sS -X POST http://localhost:8091/teams/2/users/1/validate \
+ -H 'Content-Type: application/json' \
+ -d '{"query":"SELECT amuont FROM warehouse_0420"}'
+```
+
+Diagnostics contain byte offsets and up to five visible typo suggestions ranked by case-insensitive Levenshtein
+distance. Dynamic properties use the same cached namespaces as autocomplete.
+
+```bash
+curl -sS -X POST http://localhost:8091/teams/2/users/1/autocomplete \
+ -H 'Content-Type: application/json' \
+ -d '{"query":"SELECT events.properties.$geo"}'
+
+curl -sS -X POST http://localhost:8091/teams/2/users/1/validate \
+ -H 'Content-Type: application/json' \
+ -d '{"query":"SELECT events.properties.$geo_cty FROM events"}'
+```
+
+`position` is an optional UTF-8 byte offset and defaults to the end of the query. `durationMicros` covers only the
+in-memory completion path; network and JSON decoding are intentionally excluded. Responses contain at most 25
+suggestions, the total match count, and an opaque `nextCursor` when another page exists. Send the same query and
+position with `"cursor":"<nextCursor>"` to retrieve it. The HTTP `Content-Length` is the encoded response size.
+
+The parser currently accepts ClickHouse's `database.table` identifiers but not HogQL's three-part synced-table names.
+Completion retains the parser error for diagnostics and uses a catalog-aware table-reference fallback for those names.
+Validation normalizes those table references before parsing while preserving byte offsets.
+
+## Multitenant catalogs
+
+Django can publish a complete catalog for one team and user without restarting the service:
+
+```bash
+curl -sS -X PUT http://localhost:8091/teams/2/users/17/catalog \
+ -H 'Content-Type: application/json' \
+ -d '{
+ "revision": "schema-42:permissions-9",
+ "catalog": {
+ "tables": {
+ "events": {"name": "events", "type": "posthog", "fields": {}}
+ },
+ "properties": {"event": [{"name": "$geo_city", "property_type": "String"}]}
+ }
+ }'
+```
+
+Every protected route requires positive `teamId` and `userId` path parameters. The response includes
+`catalogRevision`, allowing Django and the editor to detect a stale response. An unknown, expired, or evicted pair
+returns `404`; the service never falls back to another team or user.
+
+`DELETE /teams/{teamId}/users/{userId}/catalog` removes that entry.
+
+Catalogs expire `CATALOG_TTL` (default `30m`) after publication so active projects periodically refresh their schema.
+When `MAX_CATALOGS` (default `1024`) or `CATALOG_CACHE_MAX_BYTES` (default `8 GiB`) is reached, the least recently used
+catalog is evicted. A catalog request is limited to `64 MiB`. Publishing a new revision replaces the old immutable
+catalog atomically.
+
+Authentication is required unless `HOGQL_LANGUAGE_SERVICE_ALLOW_INSECURE=1` explicitly disables it on a loopback
+listener for local development. Insecure mode logs a startup warning and is rejected on non-loopback listeners.
+`HOGQL_LANGUAGE_SERVICE_SIGNING_KEYS` contains one or more comma-separated HMAC keys. Django sends a short-lived
+HS256 JWT as `Authorization: Bearer …` with these claims:
+
+```json
+{
+ "aud": "hogql-language-service",
+ "team_id": 2,
+ "user_id": 17,
+ "operations": ["publish", "complete", "validate", "delete"],
+ "nbf": 1788750000,
+ "exp": 1788750060
+}
+```
+
+Tokens are valid only for the exact team, user, and operation. List the current signing key first and old keys
+afterward during rotation. Do not expose the service directly to browsers; Django should mint tokens and proxy
+requests after resolving the user's membership and permissions for that team.
+
+## Rate limiting
+
+Protected requests pass through two bounded in-memory token buckets before the handler reads JSON:
+
+1. The pre-authentication bucket keys requests by the direct peer IP address.
+2. The principal bucket keys authenticated requests by `teamId:userId`.
+
+The JWT must match the path before a request consumes principal capacity. The service does not trust forwarded-IP
+headers. Deployments should configure the pre-authentication allowance for the expected number of Django callers.
+
+| Setting | Default |
+| ---------------------------------------- | ------- |
+| `PRE_AUTH_RATE_LIMIT_CAPACITY` | `300` |
+| `PRE_AUTH_RATE_LIMIT_REFILL_PER_SECOND` | `100` |
+| `PRINCIPAL_RATE_LIMIT_CAPACITY` | `120` |
+| `PRINCIPAL_RATE_LIMIT_REFILL_PER_SECOND` | `60` |
+| `RATE_LIMIT_MAX_KEYS` | `10000` |
+| `RATE_LIMIT_IDLE_TTL` | `10m` |
+
+Limited requests return `429` and a `Retry-After` header. The entry bound prevents attacker-controlled path values
+from growing limiter memory without limit.
+
+## Container image
+
+Build the image from the service directory:
+
+```bash
+docker build \
+ --build-arg COMMIT_HASH="$(git rev-parse HEAD)" \
+ --tag hogql-language-service:local \
+ services/hogql-language-service
+```
+
+The image runs as a non-root user and listens on port `8091`. Because the container binds to all interfaces, it
+requires `HOGQL_LANGUAGE_SERVICE_SIGNING_KEYS`:
+
+```bash
+docker run --rm \
+ --publish 127.0.0.1:8091:8091 \
+ --env HOGQL_LANGUAGE_SERVICE_SIGNING_KEYS=local-development-key \
+ hogql-language-service:local
+```
+
+The production binary is compiled with Go 1.27.1 and `go build -trimpath`. The runtime image contains only the static
+service binary, the commit identifier, and CA certificates. BuildKit's `TARGETOS` and `TARGETARCH` arguments allow
+native `linux/amd64` and `linux/arm64` builds.
diff --git a/services/hogql-language-service/cmd/server/main.go b/services/hogql-language-service/cmd/server/main.go
new file mode 100644
index 000000000000..aa694a14ceef
--- /dev/null
+++ b/services/hogql-language-service/cmd/server/main.go
@@ -0,0 +1,364 @@
+package main
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "math"
+ "net"
+ "net/http"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/completion"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/ratelimit"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/serviceauth"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/validation"
+)
+
+type server struct {
+ catalogs *catalog.Registry
+ auth *serviceauth.Authenticator
+ preAuthLimiter *ratelimit.Limiter
+ principalLimiter *ratelimit.Limiter
+}
+
+type completionRequest struct {
+ Query string `json:"query"`
+ Position *int `json:"position,omitempty"`
+ Cursor string `json:"cursor,omitempty"`
+}
+
+type completionResponse struct {
+ completion.Result
+ CatalogRevision string `json:"catalogRevision"`
+ DurationMicros int64 `json:"durationMicros"`
+}
+
+type validationRequest struct {
+ Query string `json:"query"`
+}
+
+type validationResponse struct {
+ validation.Result
+ CatalogRevision string `json:"catalogRevision"`
+}
+
+type catalogUpdate struct {
+ Revision string `json:"revision"`
+ Catalog catalog.Catalog `json:"catalog"`
+}
+
+func main() {
+ listenAddress := env("LISTEN_ADDR", "127.0.0.1:8091")
+ maxCatalogs, err := positiveIntEnv("MAX_CATALOGS", 1024)
+ if err != nil {
+ fatalConfiguration(err)
+ }
+ catalogTTL, err := positiveDurationEnv("CATALOG_TTL", 30*time.Minute)
+ if err != nil {
+ fatalConfiguration(err)
+ }
+ maxCatalogBytes, err := positiveIntEnv("CATALOG_CACHE_MAX_BYTES", 8<<30)
+ if err != nil {
+ fatalConfiguration(err)
+ }
+ keys := splitNonEmpty(os.Getenv("HOGQL_LANGUAGE_SERVICE_SIGNING_KEYS"))
+ allowInsecure, err := allowInsecureAuthentication(listenAddress, os.Getenv("HOGQL_LANGUAGE_SERVICE_ALLOW_INSECURE"))
+ if err != nil {
+ fatalConfiguration(err)
+ }
+ if len(keys) == 0 && !allowInsecure {
+ fatalConfiguration(errors.New("HOGQL_LANGUAGE_SERVICE_SIGNING_KEYS is required"))
+ }
+ if allowInsecure {
+ slog.Warn("authentication disabled for local development", "address", listenAddress)
+ }
+ maxRateLimitKeys, err := positiveIntEnv("RATE_LIMIT_MAX_KEYS", 10000)
+ if err != nil {
+ fatalConfiguration(err)
+ }
+ rateLimitIdleTTL, err := positiveDurationEnv("RATE_LIMIT_IDLE_TTL", 10*time.Minute)
+ if err != nil {
+ fatalConfiguration(err)
+ }
+
+ s := &server{
+ catalogs: catalog.NewRegistry(maxCatalogs, int64(maxCatalogBytes), catalogTTL),
+ auth: serviceauth.New(keys, allowInsecure),
+ preAuthLimiter: configuredLimiter("PRE_AUTH_RATE_LIMIT", 300, 100, maxRateLimitKeys, rateLimitIdleTTL),
+ principalLimiter: configuredLimiter("PRINCIPAL_RATE_LIMIT", 120, 60, maxRateLimitKeys, rateLimitIdleTTL),
+ }
+ httpServer := &http.Server{
+ Addr: listenAddress,
+ Handler: s.handler(),
+ ReadHeaderTimeout: 5 * time.Second,
+ ReadTimeout: 30 * time.Second,
+ WriteTimeout: 30 * time.Second,
+ IdleTimeout: 60 * time.Second,
+ }
+ stats := s.catalogs.Stats()
+ slog.Info("HogQL language service listening", "address", listenAddress, "catalogs", stats.Catalogs, "tables", stats.Tables, "properties", stats.Properties)
+ if err := httpServer.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
+ slog.Error("server stopped", "error", err)
+ os.Exit(1)
+ }
+}
+
+func (s *server) handler() http.Handler {
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /health", s.health)
+ mux.Handle("PUT /teams/{teamID}/users/{userID}/catalog", s.authorized(serviceauth.OperationPublish, s.putCatalog))
+ mux.Handle("DELETE /teams/{teamID}/users/{userID}/catalog", s.authorized(serviceauth.OperationDelete, s.deleteCatalog))
+ mux.Handle("POST /teams/{teamID}/users/{userID}/autocomplete", s.authorized(serviceauth.OperationComplete, s.autocomplete))
+ mux.Handle("POST /teams/{teamID}/users/{userID}/validate", s.authorized(serviceauth.OperationValidate, s.validate))
+ return securityHeaders(mux)
+}
+
+func securityHeaders(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ next.ServeHTTP(w, r)
+ })
+}
+
+type authorizedHandler func(http.ResponseWriter, *http.Request, serviceauth.Authorization)
+
+func (s *server) authorized(operation serviceauth.Operation, next authorizedHandler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ preAuthAllowed, retryAfter := s.preAuthLimiter.Allow(remoteAddress(r))
+ authorization, err := authorizationFromPath(r)
+ if err != nil {
+ if !preAuthAllowed {
+ writeRateLimitResponse(w, retryAfter)
+ } else {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ }
+ return
+ }
+ if err := s.auth.Verify(r.Header.Get("Authorization"), authorization, operation); err != nil {
+ if !preAuthAllowed {
+ writeRateLimitResponse(w, retryAfter)
+ } else {
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ }
+ return
+ }
+ if allowed, retryAfter := s.principalLimiter.Allow(authorizationKey(authorization)); !allowed {
+ writeRateLimitResponse(w, retryAfter)
+ return
+ }
+ next(w, r, authorization)
+ })
+}
+
+func (s *server) putCatalog(w http.ResponseWriter, r *http.Request, authorization serviceauth.Authorization) {
+ var input catalogUpdate
+ if !decodeJSON(w, r, 64<<20, &input) {
+ return
+ }
+ if err := s.catalogs.Put(authorization, input.Revision, &input.Catalog); err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"teamId": authorization.TeamID, "userId": authorization.UserID, "revision": input.Revision})
+}
+
+func (s *server) deleteCatalog(w http.ResponseWriter, _ *http.Request, authorization serviceauth.Authorization) {
+ if !s.catalogs.Delete(authorization) {
+ http.Error(w, "catalog not found", http.StatusNotFound)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
+func (s *server) autocomplete(w http.ResponseWriter, r *http.Request, authorization serviceauth.Authorization) {
+ var input completionRequest
+ if !decodeJSON(w, r, 128<<10, &input) {
+ return
+ }
+ current, revision, ok := s.catalogs.Get(authorization)
+ if !ok {
+ http.Error(w, "catalog not found", http.StatusNotFound)
+ return
+ }
+ position := len(input.Query)
+ if input.Position != nil {
+ position = *input.Position
+ }
+ started := time.Now()
+ result, err := completion.Complete(current, input.Query, position, input.Cursor)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ writeJSON(w, http.StatusOK, completionResponse{Result: result, CatalogRevision: revision, DurationMicros: time.Since(started).Microseconds()})
+}
+
+func (s *server) validate(w http.ResponseWriter, r *http.Request, authorization serviceauth.Authorization) {
+ var input validationRequest
+ if !decodeJSON(w, r, 128<<10, &input) {
+ return
+ }
+ current, revision, ok := s.catalogs.Get(authorization)
+ if !ok {
+ http.Error(w, "catalog not found", http.StatusNotFound)
+ return
+ }
+ writeJSON(w, http.StatusOK, validationResponse{Result: validation.Validate(current, input.Query), CatalogRevision: revision})
+}
+
+func (s *server) health(w http.ResponseWriter, _ *http.Request) {
+ writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
+}
+
+func decodeJSON(w http.ResponseWriter, r *http.Request, maxBytes int64, target any) bool {
+ decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBytes))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(target); err != nil {
+ http.Error(w, "invalid request: "+err.Error(), http.StatusBadRequest)
+ return false
+ }
+ return true
+}
+
+func authorizationFromPath(r *http.Request) (serviceauth.Authorization, error) {
+ teamID, err := strconv.ParseInt(r.PathValue("teamID"), 10, 64)
+ if err != nil {
+ return serviceauth.Authorization{}, errors.New("teamID and userID must be positive integers")
+ }
+ userID, err := strconv.ParseInt(r.PathValue("userID"), 10, 64)
+ if err != nil || teamID <= 0 || userID <= 0 {
+ return serviceauth.Authorization{}, errors.New("teamID and userID must be positive integers")
+ }
+ return serviceauth.Authorization{TeamID: teamID, UserID: userID}, nil
+}
+
+func remoteAddress(r *http.Request) string {
+ host, _, err := net.SplitHostPort(r.RemoteAddr)
+ if err != nil {
+ return r.RemoteAddr
+ }
+ return host
+}
+
+func authorizationKey(authorization serviceauth.Authorization) string {
+ return strconv.FormatInt(authorization.TeamID, 10) + ":" + strconv.FormatInt(authorization.UserID, 10)
+}
+
+func writeRateLimitResponse(w http.ResponseWriter, retryAfter time.Duration) {
+ seconds := max(int64(1), int64((retryAfter+time.Second-1)/time.Second))
+ w.Header().Set("Retry-After", strconv.FormatInt(seconds, 10))
+ http.Error(w, "rate limit exceeded", http.StatusTooManyRequests)
+}
+
+func isLoopbackAddress(address string) bool {
+ host, _, err := net.SplitHostPort(address)
+ if err != nil {
+ return false
+ }
+ return host == "localhost" || net.ParseIP(host).IsLoopback()
+}
+
+func splitNonEmpty(value string) []string {
+ var values []string
+ for _, item := range strings.Split(value, ",") {
+ if item = strings.TrimSpace(item); item != "" {
+ values = append(values, item)
+ }
+ }
+ return values
+}
+
+func positiveIntEnv(name string, fallback int) (int, error) {
+ value := os.Getenv(name)
+ if value == "" {
+ return fallback, nil
+ }
+ parsed, err := strconv.Atoi(value)
+ if err != nil || parsed <= 0 {
+ return 0, fmt.Errorf("%s must be a positive integer", name)
+ }
+ return parsed, nil
+}
+
+func positiveDurationEnv(name string, fallback time.Duration) (time.Duration, error) {
+ value := os.Getenv(name)
+ if value == "" {
+ return fallback, nil
+ }
+ parsed, err := time.ParseDuration(value)
+ if err != nil || parsed <= 0 {
+ return 0, fmt.Errorf("%s must be a positive duration", name)
+ }
+ return parsed, nil
+}
+
+func configuredLimiter(prefix string, defaultCapacity, defaultRefill float64, maxEntries int, idleTTL time.Duration) *ratelimit.Limiter {
+ capacity, err := positiveFloatEnv(prefix+"_CAPACITY", defaultCapacity)
+ if err != nil {
+ fatalConfiguration(err)
+ }
+ refill, err := positiveFloatEnv(prefix+"_REFILL_PER_SECOND", defaultRefill)
+ if err != nil {
+ fatalConfiguration(err)
+ }
+ limiter, err := ratelimit.New(ratelimit.Config{Capacity: capacity, RefillPerSec: refill, MaxEntries: maxEntries, IdleTTL: idleTTL})
+ if err != nil {
+ fatalConfiguration(err)
+ }
+ return limiter
+}
+
+func positiveFloatEnv(name string, fallback float64) (float64, error) {
+ value := os.Getenv(name)
+ if value == "" {
+ return fallback, nil
+ }
+ parsed, err := strconv.ParseFloat(value, 64)
+ if err != nil || parsed <= 0 || math.IsNaN(parsed) || math.IsInf(parsed, 0) {
+ return 0, fmt.Errorf("%s must be a positive number", name)
+ }
+ return parsed, nil
+}
+
+func writeJSON(w http.ResponseWriter, status int, value any) {
+ body, err := json.Marshal(value)
+ if err != nil {
+ http.Error(w, "encode response", http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json; charset=utf-8")
+ w.Header().Set("Content-Length", strconv.Itoa(len(body)))
+ w.WriteHeader(status)
+ // nosemgrep: go.lang.security.audit.xss.no-direct-write-to-responsewriter.no-direct-write-to-responsewriter -- json.Marshal escapes strings and this response has an application/json content type.
+ if _, err := w.Write(body); err != nil {
+ slog.Warn("write response", "error", err)
+ }
+}
+
+func allowInsecureAuthentication(listenAddress, configured string) (bool, error) {
+ if configured != "1" {
+ return false, nil
+ }
+ if !isLoopbackAddress(listenAddress) {
+ return false, errors.New("HOGQL_LANGUAGE_SERVICE_ALLOW_INSECURE requires a loopback LISTEN_ADDR")
+ }
+ return true, nil
+}
+
+func fatalConfiguration(err error) {
+ slog.Error("invalid configuration", "error", err)
+ os.Exit(1)
+}
+
+func env(name, fallback string) string {
+ if value := os.Getenv(name); value != "" {
+ return value
+ }
+ return fallback
+}
diff --git a/services/hogql-language-service/cmd/server/main_test.go b/services/hogql-language-service/cmd/server/main_test.go
new file mode 100644
index 000000000000..e53f7d857e5a
--- /dev/null
+++ b/services/hogql-language-service/cmd/server/main_test.go
@@ -0,0 +1,195 @@
+package main
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/completion"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/ratelimit"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/serviceauth"
+)
+
+func TestAutocompleteUsesOnlyRequestedTeamAndUserCatalog(t *testing.T) {
+ s := newTestServer(t)
+ handler := s.handler()
+ putCatalogForTest(t, handler, 1, 10, "revision-one", "orders")
+ putCatalogForTest(t, handler, 1, 20, "revision-two", "accounts")
+ putCatalogForTest(t, handler, 2, 10, "revision-three", "invoices")
+
+ for _, test := range []struct {
+ teamID int64
+ userID int64
+ revision string
+ table string
+ }{
+ {teamID: 1, userID: 10, revision: "revision-one", table: "orders"},
+ {teamID: 1, userID: 20, revision: "revision-two", table: "accounts"},
+ {teamID: 2, userID: 10, revision: "revision-three", table: "invoices"},
+ } {
+ body := `{"query":"SELECT * FROM "}`
+ path := scopePath(test.teamID, test.userID) + "/autocomplete"
+ request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
+ request.Header.Set("Content-Type", "application/json")
+ response := httptest.NewRecorder()
+ handler.ServeHTTP(response, request)
+ if response.Code != http.StatusOK {
+ t.Fatalf("autocomplete returned %d: %s", response.Code, response.Body.String())
+ }
+ if contentType := response.Header().Get("Content-Type"); contentType != "application/json; charset=utf-8" {
+ t.Fatalf("unexpected Content-Type: %q", contentType)
+ }
+ if response.Header().Get("X-Content-Type-Options") != "nosniff" {
+ t.Fatal("response is missing X-Content-Type-Options: nosniff")
+ }
+ if contentLength := response.Header().Get("Content-Length"); contentLength != strconv.Itoa(response.Body.Len()) {
+ t.Fatalf("Content-Length = %q, response size = %d", contentLength, response.Body.Len())
+ }
+ var result completionResponse
+ if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
+ t.Fatal(err)
+ }
+ if result.CatalogRevision != test.revision || !hasSuggestion(result.Suggestions, test.table) {
+ t.Fatalf("unexpected response for team %d user %d: %#v", test.teamID, test.userID, result)
+ }
+ for _, otherTable := range []string{"orders", "accounts", "invoices"} {
+ if otherTable != test.table && hasSuggestion(result.Suggestions, otherTable) {
+ t.Fatalf("%s leaked into team %d user %d", otherTable, test.teamID, test.userID)
+ }
+ }
+ }
+}
+
+func TestInsecureAuthenticationRequiresExplicitLoopbackOptIn(t *testing.T) {
+ for _, test := range []struct {
+ address string
+ configured string
+ allowed bool
+ wantError bool
+ }{
+ {address: "127.0.0.1:8091", configured: "", allowed: false},
+ {address: "127.0.0.1:8091", configured: "1", allowed: true},
+ {address: "0.0.0.0:8091", configured: "1", allowed: false, wantError: true},
+ } {
+ allowed, err := allowInsecureAuthentication(test.address, test.configured)
+ if allowed != test.allowed || (err != nil) != test.wantError {
+ t.Fatalf("address %q configured %q returned allowed=%t error=%v", test.address, test.configured, allowed, err)
+ }
+ }
+}
+
+func TestAutocompleteRequiresKnownTeamAndUser(t *testing.T) {
+ s := newTestServer(t)
+ for _, test := range []struct {
+ path string
+ body string
+ status int
+ }{
+ {path: "/teams/1/users/invalid/autocomplete", body: `{"query":"SELECT "}`, status: http.StatusBadRequest},
+ {path: "/teams/invalid/users/10/validate", body: `{"query":"SELECT 1"}`, status: http.StatusBadRequest},
+ {path: scopePath(1, 10) + "/autocomplete", body: `{"query":"SELECT "}`, status: http.StatusNotFound},
+ } {
+ request := httptest.NewRequest(http.MethodPost, test.path, strings.NewReader(test.body))
+ response := httptest.NewRecorder()
+ s.handler().ServeHTTP(response, request)
+ if response.Code != test.status {
+ t.Fatalf("expected %d, got %d: %s", test.status, response.Code, response.Body.String())
+ }
+ if response.Header().Get("X-Content-Type-Options") != "nosniff" {
+ t.Fatal("error response is missing X-Content-Type-Options: nosniff")
+ }
+ }
+}
+
+func TestPrincipalRateLimitRunsBeforeBodyDecodeAndDoesNotCrossScopes(t *testing.T) {
+ preAuthLimiter, err := ratelimit.New(ratelimit.Config{Capacity: 1, RefillPerSec: 0.001, MaxEntries: 10, IdleTTL: time.Hour})
+ if err != nil {
+ t.Fatal(err)
+ }
+ principalLimiter, err := ratelimit.New(ratelimit.Config{Capacity: 1, RefillPerSec: 0.001, MaxEntries: 10, IdleTTL: time.Hour})
+ if err != nil {
+ t.Fatal(err)
+ }
+ s := &server{
+ catalogs: catalog.NewRegistry(10, 1<<20, time.Hour),
+ auth: serviceauth.New(nil, true),
+ preAuthLimiter: preAuthLimiter,
+ principalLimiter: principalLimiter,
+ }
+ value := &catalog.Catalog{Tables: map[string]catalog.Table{}, Properties: map[string][]catalog.Property{}}
+ for _, authorization := range []serviceauth.Authorization{{TeamID: 1, UserID: 10}, {TeamID: 1, UserID: 20}} {
+ if err := s.catalogs.Put(authorization, "1", value); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ request := httptest.NewRequest(http.MethodPost, scopePath(1, 10)+"/autocomplete", strings.NewReader(`{"query":"SELECT "}`))
+ response := httptest.NewRecorder()
+ s.handler().ServeHTTP(response, request)
+ if response.Code != http.StatusOK {
+ t.Fatalf("first request returned %d: %s", response.Code, response.Body.String())
+ }
+
+ request = httptest.NewRequest(http.MethodPost, scopePath(1, 10)+"/autocomplete", strings.NewReader(`{`))
+ response = httptest.NewRecorder()
+ s.handler().ServeHTTP(response, request)
+ if response.Code != http.StatusTooManyRequests || response.Header().Get("Retry-After") == "" {
+ t.Fatalf("limited request returned %d without Retry-After: %s", response.Code, response.Body.String())
+ }
+
+ request = httptest.NewRequest(http.MethodPost, scopePath(1, 20)+"/autocomplete", strings.NewReader(`{"query":"SELECT "}`))
+ response = httptest.NewRecorder()
+ s.handler().ServeHTTP(response, request)
+ if response.Code != http.StatusOK {
+ t.Fatalf("another user inherited the rate limit: %d: %s", response.Code, response.Body.String())
+ }
+}
+
+func putCatalogForTest(t *testing.T, handler http.Handler, teamID, userID int64, revision, table string) {
+ t.Helper()
+ body := `{"revision":"` + revision + `","catalog":{"tables":{"` + table + `":{"name":"` + table + `","type":"warehouse","fields":{}}},"properties":{}}}`
+ path := scopePath(teamID, userID) + "/catalog"
+ request := httptest.NewRequest(http.MethodPut, path, 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())
+ }
+}
+
+func newTestServer(t *testing.T) *server {
+ t.Helper()
+ config := ratelimit.Config{Capacity: 1000, RefillPerSec: 1000, MaxEntries: 100, IdleTTL: time.Hour}
+ preAuthLimiter, err := ratelimit.New(config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ principalLimiter, err := ratelimit.New(config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return &server{
+ catalogs: catalog.NewRegistry(10, 1<<20, time.Hour),
+ auth: serviceauth.New(nil, true),
+ preAuthLimiter: preAuthLimiter,
+ principalLimiter: principalLimiter,
+ }
+}
+
+func scopePath(teamID, userID int64) string {
+ return "/teams/" + strconv.FormatInt(teamID, 10) + "/users/" + strconv.FormatInt(userID, 10)
+}
+
+func hasSuggestion(suggestions []completion.Suggestion, label string) bool {
+ for _, suggestion := range suggestions {
+ if suggestion.Label == label {
+ return true
+ }
+ }
+ return false
+}
diff --git a/services/hogql-language-service/go.mod b/services/hogql-language-service/go.mod
new file mode 100644
index 000000000000..f0d1c212c6e3
--- /dev/null
+++ b/services/hogql-language-service/go.mod
@@ -0,0 +1,5 @@
+module github.com/PostHog/posthog/services/hogql-language-service
+
+go 1.27.1
+
+require github.com/orian/clickhouse-sql-parser v0.0.0-20260813141301-768a69c3d95a
diff --git a/services/hogql-language-service/go.sum b/services/hogql-language-service/go.sum
new file mode 100644
index 000000000000..3572070010ce
--- /dev/null
+++ b/services/hogql-language-service/go.sum
@@ -0,0 +1,14 @@
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/orian/clickhouse-sql-parser v0.0.0-20260813141301-768a69c3d95a h1:pEpE55SB1MrdR7O8Vow1zDmUeAJxKQ1PeRVNyXS5L4g=
+github.com/orian/clickhouse-sql-parser v0.0.0-20260813141301-768a69c3d95a/go.mod h1:22D/qoWV/Ipbn5Gcub+0ttta1wgzSDaJMprQRZWghoE=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/sebdah/goldie/v2 v2.5.3 h1:9ES/mNN+HNUbNWpVAlrzuZ7jE+Nrczbj8uFRjM7624Y=
+github.com/sebdah/goldie/v2 v2.5.3/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI=
+github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ=
+github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
+github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
+github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/services/hogql-language-service/internal/catalog/catalog.go b/services/hogql-language-service/internal/catalog/catalog.go
new file mode 100644
index 000000000000..e68cc0ab25d2
--- /dev/null
+++ b/services/hogql-language-service/internal/catalog/catalog.go
@@ -0,0 +1,23 @@
+package catalog
+
+type Field struct {
+ Name string `json:"name"`
+ Type string `json:"type"`
+}
+
+type Table struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Fields map[string]Field `json:"fields"`
+}
+
+type Property struct {
+ Name string `json:"name"`
+ ValueType string `json:"property_type"`
+}
+
+type Catalog struct {
+ Tables map[string]Table `json:"tables"`
+ Properties map[string][]Property `json:"properties"`
+}
diff --git a/services/hogql-language-service/internal/catalog/registry.go b/services/hogql-language-service/internal/catalog/registry.go
new file mode 100644
index 000000000000..3672ae8aa47e
--- /dev/null
+++ b/services/hogql-language-service/internal/catalog/registry.go
@@ -0,0 +1,158 @@
+package catalog
+
+import (
+ "errors"
+ "sync"
+ "time"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/serviceauth"
+)
+
+var (
+ ErrInvalidScope = errors.New("team ID and user ID must be positive")
+ ErrInvalidRevision = errors.New("invalid catalog revision")
+ ErrCatalogTooLarge = errors.New("catalog exceeds cache capacity")
+)
+
+type Registry struct {
+ mu sync.Mutex
+ entries map[serviceauth.Authorization]registryEntry
+ maxEntries int
+ maxBytes int64
+ totalBytes int64
+ ttl time.Duration
+ now func() time.Time
+}
+
+type registryEntry struct {
+ catalog *Catalog
+ revision string
+ createdAt time.Time
+ lastAccess time.Time
+ sizeBytes int64
+}
+
+type RegistryStats struct {
+ Catalogs int `json:"catalogs"`
+ Tables int `json:"tables"`
+ Properties int `json:"properties"`
+}
+
+func NewRegistry(maxEntries int, maxBytes int64, ttl time.Duration) *Registry {
+ return newRegistry(maxEntries, maxBytes, ttl, time.Now)
+}
+
+func newRegistry(maxEntries int, maxBytes int64, ttl time.Duration, now func() time.Time) *Registry {
+ return &Registry{entries: map[serviceauth.Authorization]registryEntry{}, maxEntries: maxEntries, maxBytes: maxBytes, ttl: ttl, now: now}
+}
+
+func (r *Registry) Put(authorization serviceauth.Authorization, revision string, value *Catalog) error {
+ if !authorization.Valid() {
+ return ErrInvalidScope
+ }
+ if revision == "" || len(revision) > 128 {
+ return ErrInvalidRevision
+ }
+ if value == nil || value.Tables == nil || value.Properties == nil {
+ return errors.New("catalog must contain tables and properties")
+ }
+ sizeBytes := estimatedSize(value)
+ if sizeBytes > r.maxBytes {
+ return ErrCatalogTooLarge
+ }
+
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ now := r.now()
+ r.removeExpired(now)
+ if existing, exists := r.entries[authorization]; exists {
+ r.totalBytes -= existing.sizeBytes
+ delete(r.entries, authorization)
+ }
+ for len(r.entries) >= r.maxEntries || r.totalBytes+sizeBytes > r.maxBytes {
+ r.removeLeastRecentlyUsed()
+ }
+ r.entries[authorization] = registryEntry{catalog: value, revision: revision, createdAt: now, lastAccess: now, sizeBytes: sizeBytes}
+ r.totalBytes += sizeBytes
+ return nil
+}
+
+func (r *Registry) Get(authorization serviceauth.Authorization) (*Catalog, string, bool) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ now := r.now()
+ r.removeExpired(now)
+ entry, ok := r.entries[authorization]
+ if !ok {
+ return nil, "", false
+ }
+ entry.lastAccess = now
+ r.entries[authorization] = entry
+ return entry.catalog, entry.revision, true
+}
+
+func (r *Registry) Delete(authorization serviceauth.Authorization) bool {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if _, exists := r.entries[authorization]; !exists {
+ return false
+ }
+ r.totalBytes -= r.entries[authorization].sizeBytes
+ delete(r.entries, authorization)
+ return true
+}
+
+func (r *Registry) Stats() RegistryStats {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.removeExpired(r.now())
+ stats := RegistryStats{Catalogs: len(r.entries)}
+ for _, entry := range r.entries {
+ stats.Tables += len(entry.catalog.Tables)
+ for _, properties := range entry.catalog.Properties {
+ stats.Properties += len(properties)
+ }
+ }
+ return stats
+}
+
+func (r *Registry) removeExpired(now time.Time) {
+ for authorization, entry := range r.entries {
+ if now.Sub(entry.createdAt) >= r.ttl {
+ r.totalBytes -= entry.sizeBytes
+ delete(r.entries, authorization)
+ }
+ }
+}
+
+func (r *Registry) removeLeastRecentlyUsed() {
+ var oldestAuthorization serviceauth.Authorization
+ found := false
+ var oldest time.Time
+ for authorization, entry := range r.entries {
+ if !found || entry.lastAccess.Before(oldest) {
+ oldestAuthorization = authorization
+ oldest = entry.lastAccess
+ found = true
+ }
+ }
+ r.totalBytes -= r.entries[oldestAuthorization].sizeBytes
+ delete(r.entries, oldestAuthorization)
+}
+
+func estimatedSize(value *Catalog) int64 {
+ var size int64
+ for name, table := range value.Tables {
+ size += int64(len(name) + len(table.Name) + len(table.Type) + 64)
+ for fieldName, field := range table.Fields {
+ size += int64(len(fieldName) + len(field.Name) + len(field.Type) + 64)
+ }
+ }
+ for namespace, properties := range value.Properties {
+ size += int64(len(namespace) + 64)
+ for _, property := range properties {
+ size += int64(len(property.Name) + len(property.ValueType) + 32)
+ }
+ }
+ return size
+}
diff --git a/services/hogql-language-service/internal/catalog/registry_test.go b/services/hogql-language-service/internal/catalog/registry_test.go
new file mode 100644
index 000000000000..46e8acbe18b0
--- /dev/null
+++ b/services/hogql-language-service/internal/catalog/registry_test.go
@@ -0,0 +1,100 @@
+package catalog
+
+import (
+ "testing"
+ "time"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/serviceauth"
+)
+
+func TestRegistryIsolatesCatalogsAndReplacesRevisionAtomically(t *testing.T) {
+ now := time.Unix(100, 0)
+ registry := newRegistry(2, 1<<20, time.Hour, func() time.Time { return now })
+ first := &Catalog{Tables: map[string]Table{"events": {Name: "events"}}, Properties: map[string][]Property{}}
+ second := &Catalog{Tables: map[string]Table{"persons": {Name: "persons"}}, Properties: map[string][]Property{}}
+ if err := registry.Put(serviceauth.Authorization{TeamID: 1, UserID: 10}, "1", first); err != nil {
+ t.Fatal(err)
+ }
+ if err := registry.Put(serviceauth.Authorization{TeamID: 2, UserID: 20}, "7", second); err != nil {
+ t.Fatal(err)
+ }
+ loaded, revision, ok := registry.Get(serviceauth.Authorization{TeamID: 1, UserID: 10})
+ if !ok || revision != "1" || loaded.Tables["events"].Name != "events" {
+ t.Fatalf("unexpected first catalog: %#v, %q, %t", loaded, revision, ok)
+ }
+ if _, exists := loaded.Tables["persons"]; exists {
+ t.Fatal("one team and user scope received another scope's table")
+ }
+ if err := registry.Put(serviceauth.Authorization{TeamID: 1, UserID: 10}, "2", second); err != nil {
+ t.Fatal(err)
+ }
+ loaded, revision, ok = registry.Get(serviceauth.Authorization{TeamID: 1, UserID: 10})
+ if !ok || revision != "2" || loaded.Tables["persons"].Name != "persons" {
+ t.Fatalf("replacement was not visible: %#v, %q, %t", loaded, revision, ok)
+ }
+}
+
+func TestRegistryExpiresAndEvictsLeastRecentlyUsedCatalogs(t *testing.T) {
+ now := time.Unix(100, 0)
+ registry := newRegistry(2, 1<<20, time.Minute, func() time.Time { return now })
+ value := &Catalog{Tables: map[string]Table{}, Properties: map[string][]Property{}}
+ for _, scope := range []serviceauth.Authorization{{TeamID: 1, UserID: 10}, {TeamID: 2, UserID: 20}} {
+ if err := registry.Put(scope, "1", value); err != nil {
+ t.Fatal(err)
+ }
+ now = now.Add(time.Second)
+ }
+ if _, _, ok := registry.Get(serviceauth.Authorization{TeamID: 1, UserID: 10}); !ok {
+ t.Fatal("first team and user scope unexpectedly missing")
+ }
+ now = now.Add(time.Second)
+ if err := registry.Put(serviceauth.Authorization{TeamID: 3, UserID: 30}, "1", value); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, ok := registry.Get(serviceauth.Authorization{TeamID: 2, UserID: 20}); ok {
+ t.Fatal("least recently used catalog was not evicted")
+ }
+ now = now.Add(time.Minute)
+ if stats := registry.Stats(); stats.Catalogs != 0 {
+ t.Fatalf("expired catalogs remain: %#v", stats)
+ }
+}
+
+func TestRegistryExpiresActiveCatalogFromPublicationTime(t *testing.T) {
+ now := time.Unix(100, 0)
+ registry := newRegistry(1, 1<<20, time.Minute, func() time.Time { return now })
+ scope := serviceauth.Authorization{TeamID: 1, UserID: 10}
+ value := &Catalog{Tables: map[string]Table{}, Properties: map[string][]Property{}}
+ if err := registry.Put(scope, "1", value); err != nil {
+ t.Fatal(err)
+ }
+ now = now.Add(45 * time.Second)
+ if _, _, ok := registry.Get(scope); !ok {
+ t.Fatal("catalog expired before its publication TTL")
+ }
+ now = now.Add(16 * time.Second)
+ if _, _, ok := registry.Get(scope); ok {
+ t.Fatal("catalog access extended its publication TTL")
+ }
+}
+
+func TestRegistryEvictsCatalogsToStayWithinMemoryBudget(t *testing.T) {
+ now := time.Unix(100, 0)
+ value := &Catalog{Tables: map[string]Table{"events": {Name: "events", Fields: map[string]Field{"long_field_name": {Name: "long_field_name", Type: "String"}}}}, Properties: map[string][]Property{}}
+ size := estimatedSize(value)
+ registry := newRegistry(10, size, time.Hour, func() time.Time { return now })
+ first := serviceauth.Authorization{TeamID: 1, UserID: 10}
+ second := serviceauth.Authorization{TeamID: 2, UserID: 20}
+ if err := registry.Put(first, "1", value); err != nil {
+ t.Fatal(err)
+ }
+ if err := registry.Put(second, "1", value); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, ok := registry.Get(first); ok {
+ t.Fatal("oldest catalog was not evicted to meet the memory budget")
+ }
+ if _, _, ok := registry.Get(second); !ok {
+ t.Fatal("new catalog was not retained")
+ }
+}
diff --git a/services/hogql-language-service/internal/completion/completion.go b/services/hogql-language-service/internal/completion/completion.go
new file mode 100644
index 000000000000..dcf35df6d780
--- /dev/null
+++ b/services/hogql-language-service/internal/completion/completion.go
@@ -0,0 +1,259 @@
+package completion
+
+import (
+ "encoding/base64"
+ "fmt"
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+ "unicode"
+
+ 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 Suggestion struct {
+ Label string `json:"label"`
+ Kind string `json:"kind"`
+ Detail string `json:"detail,omitempty"`
+}
+
+type Result struct {
+ Suggestions []Suggestion `json:"suggestions"`
+ Total int `json:"total"`
+ NextCursor string `json:"nextCursor,omitempty"`
+ ParseError string `json:"parseError,omitempty"`
+}
+
+const PageSize = 25
+
+var keywords = []string{"SELECT", "FROM", "WHERE", "GROUP BY", "ORDER BY", "LIMIT", "JOIN", "AS"}
+var tableReference = regexp.MustCompile(`(?i)\b(?:FROM|JOIN)\s+([A-Za-z_][A-Za-z0-9_.$]*)(?:\s+(?:AS\s+)?([A-Za-z_][A-Za-z0-9_]*))?`)
+
+func Complete(schema *catalog.Catalog, query string, position int, cursor string) (Result, error) {
+ if err := querylimits.Validate(query); err != nil {
+ return Result{}, err
+ }
+ offset, err := decodeCursor(cursor)
+ if err != nil {
+ return Result{}, err
+ }
+ if position < 0 || position > len(query) {
+ position = len(query)
+ }
+ prefix, qualifier, start := cursorWord(query[:position])
+ if len(prefix) > querylimits.MaxSuggestionInputBytes {
+ return Result{Suggestions: []Suggestion{}}, nil
+ }
+ lowerPrefix := strings.ToLower(prefix)
+ repaired := query[:start] + "__posthog_cursor__" + query[position:]
+ bindings, parseErr := tableBindings(repaired)
+ tablesByLowerName := tableNamesByLowerName(schema)
+ for binding, tableName := range bindings {
+ if canonicalName, ok := tablesByLowerName[strings.ToLower(tableName)]; ok {
+ bindings[binding] = canonicalName
+ }
+ }
+ for binding, tableName := range fallbackBindings(repaired, tablesByLowerName) {
+ bindings[binding] = tableName
+ }
+
+ var suggestions []Suggestion
+ if namespace, propertyPrefix, ok := propertyContext(query[:position], bindings); ok {
+ lowerPropertyPrefix := strings.ToLower(propertyPrefix)
+ for _, property := range schema.Properties[namespace] {
+ if hasLowerPrefix(property.Name, lowerPropertyPrefix) {
+ suggestions = append(suggestions, Suggestion{Label: property.Name, Kind: "property", Detail: property.ValueType})
+ }
+ }
+ } else if qualifier != "" {
+ if tableName, ok := bindings[strings.ToLower(qualifier)]; ok {
+ suggestions = appendFields(suggestions, schema.Tables[tableName], lowerPrefix)
+ }
+ } else if expectsTable(query[:start]) {
+ for name, table := range schema.Tables {
+ if hasLowerPrefix(name, lowerPrefix) {
+ suggestions = append(suggestions, Suggestion{Label: name, Kind: "table", Detail: table.Type})
+ }
+ }
+ } else {
+ seen := map[string]bool{}
+ for _, tableName := range bindings {
+ if seen[tableName] {
+ continue
+ }
+ seen[tableName] = true
+ suggestions = appendFields(suggestions, schema.Tables[tableName], lowerPrefix)
+ }
+ for _, keyword := range keywords {
+ if hasLowerPrefix(keyword, lowerPrefix) {
+ suggestions = append(suggestions, Suggestion{Label: keyword, Kind: "keyword"})
+ }
+ }
+ }
+ sort.Slice(suggestions, func(i, j int) bool {
+ if suggestions[i].Kind != suggestions[j].Kind {
+ return suggestions[i].Kind < suggestions[j].Kind
+ }
+ return suggestions[i].Label < suggestions[j].Label
+ })
+ result := Result{Suggestions: suggestions, Total: len(suggestions)}
+ if offset > len(suggestions) {
+ offset = len(suggestions)
+ }
+ end := min(offset+PageSize, len(suggestions))
+ result.Suggestions = suggestions[offset:end]
+ if end < len(suggestions) {
+ result.NextCursor = encodeCursor(end)
+ }
+ if parseErr != nil {
+ result.ParseError = parseErr.Error()
+ }
+ return result, nil
+}
+
+func propertyContext(input string, bindings map[string]string) (string, string, bool) {
+ start := len(input)
+ for start > 0 {
+ character := input[start-1]
+ if character != '.' && character != '$' && !isIdentifier(rune(character)) {
+ break
+ }
+ start--
+ }
+ parts := strings.Split(input[start:], ".")
+ if len(parts) < 2 {
+ return "", "", false
+ }
+ namespace, ok := propertyresolver.Resolve(parts, bindings)
+ return namespace, parts[len(parts)-1], ok
+}
+
+func decodeCursor(cursor string) (int, error) {
+ if cursor == "" {
+ return 0, nil
+ }
+ decoded, err := base64.RawURLEncoding.DecodeString(cursor)
+ if err != nil {
+ return 0, fmt.Errorf("invalid cursor")
+ }
+ offset, err := strconv.Atoi(string(decoded))
+ if err != nil || offset < 0 {
+ return 0, fmt.Errorf("invalid cursor")
+ }
+ return offset, nil
+}
+
+func encodeCursor(offset int) string {
+ return base64.RawURLEncoding.EncodeToString([]byte(strconv.Itoa(offset)))
+}
+
+// The ClickHouse grammar accepts database.table while HogQL warehouse names may have more segments.
+// Keep parser-derived bindings as the primary path and fill that syntax gap until the grammar supports it.
+func fallbackBindings(query string, tablesByLowerName map[string]string) map[string]string {
+ bindings := map[string]string{}
+ for _, match := range tableReference.FindAllStringSubmatch(query, -1) {
+ tableName, ok := tablesByLowerName[strings.ToLower(match[1])]
+ if !ok {
+ continue
+ }
+ bindings[strings.ToLower(tableName)] = tableName
+ if match[2] != "" && !strings.EqualFold(match[2], "FINAL") {
+ bindings[strings.ToLower(match[2])] = tableName
+ }
+ }
+ return bindings
+}
+
+func tableNamesByLowerName(schema *catalog.Catalog) map[string]string {
+ tables := make(map[string]string, len(schema.Tables))
+ for name := range schema.Tables {
+ tables[strings.ToLower(name)] = name
+ }
+ return tables
+}
+
+func appendFields(out []Suggestion, table catalog.Table, lowerPrefix string) []Suggestion {
+ for name, field := range table.Fields {
+ if hasLowerPrefix(name, lowerPrefix) {
+ out = append(out, Suggestion{Label: name, Kind: "field", Detail: field.Type})
+ }
+ }
+ return out
+}
+
+func cursorWord(input string) (prefix, qualifier string, start int) {
+ start = len(input)
+ for start > 0 && isIdentifier(rune(input[start-1])) {
+ start--
+ }
+ prefix = input[start:]
+ if start > 0 && input[start-1] == '.' {
+ qualifierEnd := start - 1
+ qualifierStart := qualifierEnd
+ for qualifierStart > 0 && isIdentifier(rune(input[qualifierStart-1])) {
+ qualifierStart--
+ }
+ qualifier = input[qualifierStart:qualifierEnd]
+ }
+ return prefix, qualifier, start
+}
+
+func isIdentifier(r rune) bool {
+ return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' || r == '$'
+}
+
+func expectsTable(input string) bool {
+ words := strings.Fields(strings.ToUpper(input))
+ if len(words) == 0 {
+ return false
+ }
+ last := words[len(words)-1]
+ return last == "FROM" || last == "JOIN" || strings.HasSuffix(strings.TrimSpace(input), ",")
+}
+
+func hasLowerPrefix(value, lowerPrefix string) bool {
+ return strings.HasPrefix(strings.ToLower(value), lowerPrefix)
+}
+
+func tableBindings(query string) (map[string]string, error) {
+ statements, err := clickhouse.NewParser(query).ParseStmts()
+ if err != nil {
+ return map[string]string{}, fmt.Errorf("parse incomplete SQL: %w", err)
+ }
+ bindings := map[string]string{}
+ for _, statement := range statements {
+ clickhouse.Walk(statement, func(node clickhouse.Expr) bool {
+ tableExpr, ok := node.(*clickhouse.TableExpr)
+ if !ok {
+ return true
+ }
+ tableNode := tableExpr.Expr
+ var aliasName string
+ if aliased, ok := tableNode.(*clickhouse.AliasExpr); ok {
+ tableNode = aliased.Expr
+ if alias, ok := aliased.Alias.(*clickhouse.Ident); ok {
+ aliasName = alias.Name
+ }
+ }
+ identifier, ok := tableNode.(*clickhouse.TableIdentifier)
+ if !ok || identifier.Table == nil {
+ return true
+ }
+ name := identifier.Table.Name
+ if identifier.Database != nil {
+ name = identifier.Database.Name + "." + name
+ }
+ bindings[strings.ToLower(name)] = name
+ if aliasName != "" {
+ bindings[strings.ToLower(aliasName)] = name
+ }
+ return false
+ })
+ }
+ return bindings, nil
+}
diff --git a/services/hogql-language-service/internal/completion/completion_test.go b/services/hogql-language-service/internal/completion/completion_test.go
new file mode 100644
index 000000000000..57a5e8c908e8
--- /dev/null
+++ b/services/hogql-language-service/internal/completion/completion_test.go
@@ -0,0 +1,141 @@
+package completion
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+)
+
+func testCatalog() *catalog.Catalog {
+ return &catalog.Catalog{Tables: map[string]catalog.Table{
+ "orders": {Name: "orders", Type: "data_warehouse", Fields: map[string]catalog.Field{
+ "order_id": {Name: "order_id", Type: "string"},
+ "amount": {Name: "amount", Type: "float"},
+ }},
+ "organizations": {Name: "organizations", Type: "posthog", Fields: map[string]catalog.Field{}},
+ "postgres.synced.orders": {Name: "postgres.synced.orders", Type: "data_warehouse", Fields: map[string]catalog.Field{
+ "synced_id": {Name: "synced_id", Type: "string"},
+ }},
+ }, Properties: map[string][]catalog.Property{
+ "event": {{Name: "$geo_city", ValueType: "String"}, {Name: "$geo_country", ValueType: "String"}},
+ "person": {{Name: "$geo_city", ValueType: "String"}},
+ "session": {{Name: "$entry_current_url", ValueType: "String"}},
+ "group:0": {{Name: "industry", ValueType: "String"}},
+ }}
+}
+
+func TestCompletionRejectsQueriesOutsideResourceLimits(t *testing.T) {
+ _, err := Complete(testCatalog(), strings.Repeat("x", 64<<10+1), 0, "")
+ if err == nil {
+ t.Fatal("oversized query was accepted")
+ }
+}
+
+func TestCompletesPropertiesForGenericNamespaces(t *testing.T) {
+ tests := []struct {
+ query string
+ position int
+ expect string
+ }{
+ {query: "SELECT events.properties.$geo FROM events", position: len("SELECT events.properties.$geo"), expect: "$geo_city"},
+ {query: "SELECT e.properties.$geo FROM events AS e", position: len("SELECT e.properties.$geo"), expect: "$geo_city"},
+ {query: "SELECT properties.$geo FROM persons", position: len("SELECT properties.$geo"), expect: "$geo_city"},
+ {query: "SELECT session.properties.$entry FROM events", position: len("SELECT session.properties.$entry"), expect: "$entry_current_url"},
+ {query: "SELECT group_0.properties.ind FROM events", position: len("SELECT group_0.properties.ind"), expect: "industry"},
+ }
+ for _, test := range tests {
+ result, err := Complete(testCatalog(), test.query, test.position, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(result.Suggestions) == 0 || result.Suggestions[0].Label != test.expect || result.Suggestions[0].Kind != "property" {
+ t.Fatalf("query %q returned %#v", test.query, result)
+ }
+ }
+}
+
+func TestCompletesFieldsForHogQLQualifiedTable(t *testing.T) {
+ query := "SELECT s. FROM postgres.synced.orders AS s"
+ result, err := Complete(testCatalog(), query, len("SELECT s."), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(result.Suggestions) != 1 || result.Suggestions[0].Label != "synced_id" {
+ t.Fatalf("suggestions = %#v; parse error = %q", result.Suggestions, result.ParseError)
+ }
+}
+
+func TestCompletesTablesAfterFrom(t *testing.T) {
+ result, err := Complete(testCatalog(), "SELECT * FROM ord", len("SELECT * FROM ord"), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(result.Suggestions) != 1 || result.Suggestions[0].Label != "orders" {
+ t.Fatalf("suggestions = %#v; parse error = %q", result.Suggestions, result.ParseError)
+ }
+}
+
+func TestCompletesFieldsForAlias(t *testing.T) {
+ query := "SELECT o. FROM orders AS o"
+ result, err := Complete(testCatalog(), query, len("SELECT o."), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(result.Suggestions) != 2 {
+ t.Fatalf("suggestions = %#v; parse error = %q", result.Suggestions, result.ParseError)
+ }
+}
+
+func TestCompletesFieldsForMixedCaseTableReference(t *testing.T) {
+ query := "SELECT Orders. FROM Orders"
+ result, err := Complete(testCatalog(), query, len("SELECT Orders."), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !hasSuggestion(result.Suggestions, "order_id") {
+ t.Fatalf("suggestions = %#v; parse error = %q", result.Suggestions, result.ParseError)
+ }
+}
+
+func TestCompletionPagesWithoutSkippingOrRepeatingTables(t *testing.T) {
+ schema := &catalog.Catalog{Tables: map[string]catalog.Table{}}
+ for index := 0; index < 30; index++ {
+ name := fmt.Sprintf("table_%02d", index)
+ schema.Tables[name] = catalog.Table{Name: name, Type: "data_warehouse", Fields: map[string]catalog.Field{}}
+ }
+ query := "SELECT * FROM table_"
+ first, err := Complete(schema, query, len(query), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(first.Suggestions) != PageSize || first.NextCursor == "" {
+ t.Fatalf("first page has %d suggestions and cursor %q", len(first.Suggestions), first.NextCursor)
+ }
+ if first.Total != 30 {
+ t.Fatalf("total = %d", first.Total)
+ }
+ second, err := Complete(schema, query, len(query), first.NextCursor)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(second.Suggestions) != 5 || second.NextCursor != "" {
+ t.Fatalf("second page has %d suggestions and cursor %q", len(second.Suggestions), second.NextCursor)
+ }
+ if first.Suggestions[24].Label != "table_24" || second.Suggestions[0].Label != "table_25" {
+ t.Fatalf("page boundary is %q then %q", first.Suggestions[24].Label, second.Suggestions[0].Label)
+ }
+ if _, err := Complete(schema, query, len(query), "not-a-cursor"); err == nil {
+ t.Fatal("invalid cursor was accepted")
+ }
+}
+
+func hasSuggestion(suggestions []Suggestion, label string) bool {
+ for _, suggestion := range suggestions {
+ if suggestion.Label == label {
+ return true
+ }
+ }
+ return false
+}
diff --git a/services/hogql-language-service/internal/propertyresolver/resolver.go b/services/hogql-language-service/internal/propertyresolver/resolver.go
new file mode 100644
index 000000000000..2e9c947b6541
--- /dev/null
+++ b/services/hogql-language-service/internal/propertyresolver/resolver.go
@@ -0,0 +1,59 @@
+package propertyresolver
+
+import (
+ "regexp"
+ "strings"
+)
+
+var groupOwner = regexp.MustCompile(`^group_?([0-4])$`)
+
+func Resolve(parts []string, bindings map[string]string) (string, bool) {
+ propertyIndex := -1
+ for index, part := range parts {
+ if strings.EqualFold(part, "properties") {
+ propertyIndex = index
+ }
+ }
+ if propertyIndex == -1 || propertyIndex != len(parts)-2 {
+ return "", false
+ }
+ if propertyIndex > 0 {
+ owner := strings.ToLower(parts[propertyIndex-1])
+ if namespace, ok := namespaceForOwner(owner); ok {
+ return namespace, true
+ }
+ if tableName, ok := bindings[owner]; ok {
+ return namespaceForOwner(strings.ToLower(tableName))
+ }
+ return "", false
+ }
+
+ namespaces := map[string]bool{}
+ for _, tableName := range bindings {
+ if namespace, ok := namespaceForOwner(strings.ToLower(tableName)); ok {
+ namespaces[namespace] = true
+ }
+ }
+ if len(namespaces) != 1 {
+ return "", false
+ }
+ for namespace := range namespaces {
+ return namespace, true
+ }
+ return "", false
+}
+
+func namespaceForOwner(owner string) (string, bool) {
+ switch owner {
+ case "event", "events":
+ return "event", true
+ case "person", "persons":
+ return "person", true
+ case "session", "sessions":
+ return "session", true
+ }
+ if match := groupOwner.FindStringSubmatch(owner); match != nil {
+ return "group:" + match[1], true
+ }
+ return "", false
+}
diff --git a/services/hogql-language-service/internal/querylimits/limits.go b/services/hogql-language-service/internal/querylimits/limits.go
new file mode 100644
index 000000000000..609c3a75f557
--- /dev/null
+++ b/services/hogql-language-service/internal/querylimits/limits.go
@@ -0,0 +1,55 @@
+package querylimits
+
+import "errors"
+
+const MaxQueryBytes = 64 << 10
+const MaxNestingDepth = 128
+const MaxSuggestionInputBytes = 128
+const MaxDiagnostics = 25
+
+var ErrQueryTooLarge = errors.New("query exceeds maximum size")
+var ErrQueryTooDeep = errors.New("query exceeds maximum nesting depth")
+
+func Validate(query string) error {
+ if len(query) > MaxQueryBytes {
+ return ErrQueryTooLarge
+ }
+ depth := 0
+ var quote byte
+ escaped := false
+ for index := 0; index < len(query); index++ {
+ character := query[index]
+ if quote != 0 {
+ if escaped {
+ escaped = false
+ continue
+ }
+ if character == '\\' {
+ escaped = true
+ continue
+ }
+ if character == quote {
+ if index+1 < len(query) && query[index+1] == quote {
+ index++
+ continue
+ }
+ quote = 0
+ }
+ continue
+ }
+ switch character {
+ case '\'', '"', '`':
+ quote = character
+ case '(':
+ depth++
+ if depth > MaxNestingDepth {
+ return ErrQueryTooDeep
+ }
+ case ')':
+ if depth > 0 {
+ depth--
+ }
+ }
+ }
+ return nil
+}
diff --git a/services/hogql-language-service/internal/querylimits/limits_test.go b/services/hogql-language-service/internal/querylimits/limits_test.go
new file mode 100644
index 000000000000..adbce055be78
--- /dev/null
+++ b/services/hogql-language-service/internal/querylimits/limits_test.go
@@ -0,0 +1,23 @@
+package querylimits
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestValidateBoundsQuerySizeAndNesting(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ query string
+ err error
+ }{
+ {name: "ordinary", query: "SELECT sum(amount) FROM orders"},
+ {name: "parentheses in string", query: "SELECT '" + strings.Repeat("(", MaxNestingDepth+1) + "'"},
+ {name: "oversized", query: strings.Repeat("a", MaxQueryBytes+1), err: ErrQueryTooLarge},
+ {name: "deeply nested", query: "SELECT " + strings.Repeat("(", MaxNestingDepth+1) + "1" + strings.Repeat(")", MaxNestingDepth+1), err: ErrQueryTooDeep},
+ } {
+ if err := Validate(test.query); err != test.err {
+ t.Fatalf("%s: got %v, want %v", test.name, err, test.err)
+ }
+ }
+}
diff --git a/services/hogql-language-service/internal/ratelimit/limiter.go b/services/hogql-language-service/internal/ratelimit/limiter.go
new file mode 100644
index 000000000000..91a228494364
--- /dev/null
+++ b/services/hogql-language-service/internal/ratelimit/limiter.go
@@ -0,0 +1,85 @@
+package ratelimit
+
+import (
+ "container/list"
+ "errors"
+ "math"
+ "sync"
+ "time"
+)
+
+type Config struct {
+ Capacity float64
+ RefillPerSec float64
+ MaxEntries int
+ IdleTTL time.Duration
+}
+
+type Limiter struct {
+ mu sync.Mutex
+ config Config
+ entries map[string]*entry
+ recency *list.List
+ now func() time.Time
+}
+
+type entry struct {
+ tokens float64
+ updatedAt time.Time
+ lastAccess time.Time
+ element *list.Element
+}
+
+func New(config Config) (*Limiter, error) {
+ return newLimiter(config, time.Now)
+}
+
+func newLimiter(config Config, now func() time.Time) (*Limiter, error) {
+ if config.Capacity <= 0 || math.IsNaN(config.Capacity) || math.IsInf(config.Capacity, 0) ||
+ config.RefillPerSec <= 0 || math.IsNaN(config.RefillPerSec) || math.IsInf(config.RefillPerSec, 0) ||
+ config.MaxEntries <= 0 || config.IdleTTL <= 0 {
+ return nil, errors.New("rate limit values must be positive")
+ }
+ return &Limiter{config: config, entries: make(map[string]*entry), recency: list.New(), now: now}, nil
+}
+
+func (l *Limiter) Allow(key string) (bool, time.Duration) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ now := l.now()
+ current, exists := l.entries[key]
+ if !exists || now.Sub(current.lastAccess) >= l.config.IdleTTL {
+ if exists {
+ l.recency.Remove(current.element)
+ delete(l.entries, key)
+ }
+ if len(l.entries) >= l.config.MaxEntries {
+ l.removeLeastRecentlyUsed()
+ }
+ current = &entry{tokens: l.config.Capacity, updatedAt: now}
+ current.element = l.recency.PushBack(key)
+ l.entries[key] = current
+ } else {
+ l.recency.MoveToBack(current.element)
+ }
+ elapsed := now.Sub(current.updatedAt).Seconds()
+ current.tokens = math.Min(l.config.Capacity, current.tokens+elapsed*l.config.RefillPerSec)
+ current.updatedAt = now
+ current.lastAccess = now
+ if current.tokens >= 1 {
+ current.tokens--
+ return true, 0
+ }
+ retryAfter := time.Duration(math.Ceil((1-current.tokens)/l.config.RefillPerSec*float64(time.Second))) * time.Nanosecond
+ return false, retryAfter
+}
+
+func (l *Limiter) removeLeastRecentlyUsed() {
+ oldest := l.recency.Front()
+ if oldest == nil {
+ return
+ }
+ delete(l.entries, oldest.Value.(string))
+ l.recency.Remove(oldest)
+}
diff --git a/services/hogql-language-service/internal/ratelimit/limiter_test.go b/services/hogql-language-service/internal/ratelimit/limiter_test.go
new file mode 100644
index 000000000000..78f5946c47ae
--- /dev/null
+++ b/services/hogql-language-service/internal/ratelimit/limiter_test.go
@@ -0,0 +1,60 @@
+package ratelimit
+
+import (
+ "math"
+ "testing"
+ "time"
+)
+
+func TestLimiterRefillsTokens(t *testing.T) {
+ now := time.Unix(100, 0)
+ limiter, err := newLimiter(Config{Capacity: 2, RefillPerSec: 1, MaxEntries: 2, IdleTTL: time.Minute}, func() time.Time { return now })
+ if err != nil {
+ t.Fatal(err)
+ }
+ for range 2 {
+ if allowed, _ := limiter.Allow("scope"); !allowed {
+ t.Fatal("request was unexpectedly limited")
+ }
+ }
+ if allowed, retryAfter := limiter.Allow("scope"); allowed || retryAfter != time.Second {
+ t.Fatalf("expected one second retry, got allowed=%t retry=%s", allowed, retryAfter)
+ }
+ now = now.Add(time.Second)
+ if allowed, _ := limiter.Allow("scope"); !allowed {
+ t.Fatal("refilled request was limited")
+ }
+}
+
+func TestLimiterBoundsKeysAndEvictsLeastRecentlyUsed(t *testing.T) {
+ now := time.Unix(100, 0)
+ limiter, err := newLimiter(Config{Capacity: 2, RefillPerSec: 1, MaxEntries: 2, IdleTTL: time.Minute}, func() time.Time { return now })
+ if err != nil {
+ t.Fatal(err)
+ }
+ limiter.Allow("first")
+ now = now.Add(time.Second)
+ limiter.Allow("second")
+ now = now.Add(time.Second)
+ limiter.Allow("first")
+ now = now.Add(time.Second)
+ limiter.Allow("third")
+
+ if len(limiter.entries) != 2 || limiter.entries["first"] == nil || limiter.entries["third"] == nil {
+ t.Fatalf("unexpected bounded entries: %#v", limiter.entries)
+ }
+ if limiter.entries["second"] != nil {
+ t.Fatal("least recently used key was not evicted")
+ }
+}
+
+func TestLimiterRejectsNonFiniteValues(t *testing.T) {
+ for _, config := range []Config{
+ {Capacity: math.NaN(), RefillPerSec: 1, MaxEntries: 1, IdleTTL: time.Minute},
+ {Capacity: 1, RefillPerSec: math.Inf(1), MaxEntries: 1, IdleTTL: time.Minute},
+ } {
+ if _, err := New(config); err == nil {
+ t.Fatal("non-finite configuration was accepted")
+ }
+ }
+}
diff --git a/services/hogql-language-service/internal/serviceauth/auth.go b/services/hogql-language-service/internal/serviceauth/auth.go
new file mode 100644
index 000000000000..897797dd5947
--- /dev/null
+++ b/services/hogql-language-service/internal/serviceauth/auth.go
@@ -0,0 +1,121 @@
+package serviceauth
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "strings"
+ "time"
+)
+
+var ErrUnauthorized = errors.New("unauthorized")
+
+type Authorization struct {
+ TeamID int64
+ UserID int64
+}
+
+func (a Authorization) Valid() bool {
+ return a.TeamID > 0 && a.UserID > 0
+}
+
+type Operation string
+
+const (
+ OperationPublish Operation = "publish"
+ OperationDelete Operation = "delete"
+ OperationComplete Operation = "complete"
+ OperationValidate Operation = "validate"
+)
+
+type Authenticator struct {
+ keys [][]byte
+ allowInsecure bool
+ now func() time.Time
+}
+
+type header struct {
+ Algorithm string `json:"alg"`
+}
+
+type Claims struct {
+ Audience string `json:"aud"`
+ TeamID int64 `json:"team_id"`
+ UserID int64 `json:"user_id"`
+ Operations []string `json:"operations"`
+ ExpiresAt int64 `json:"exp"`
+ NotBefore int64 `json:"nbf,omitempty"`
+}
+
+func New(keys []string, allowInsecure bool) *Authenticator {
+ parsed := make([][]byte, 0, len(keys))
+ for _, key := range keys {
+ if key = strings.TrimSpace(key); key != "" {
+ parsed = append(parsed, []byte(key))
+ }
+ }
+ return &Authenticator{keys: parsed, allowInsecure: allowInsecure, now: time.Now}
+}
+
+func (a *Authenticator) Verify(headerValue string, authorization Authorization, operation Operation) error {
+ if !authorization.Valid() {
+ return ErrUnauthorized
+ }
+ if len(a.keys) == 0 {
+ if a.allowInsecure {
+ return nil
+ }
+ return ErrUnauthorized
+ }
+ if !strings.HasPrefix(headerValue, "Bearer ") {
+ return ErrUnauthorized
+ }
+ parts := strings.Split(strings.TrimPrefix(headerValue, "Bearer "), ".")
+ if len(parts) != 3 {
+ return ErrUnauthorized
+ }
+ signed := parts[0] + "." + parts[1]
+ signature, err := base64.RawURLEncoding.DecodeString(parts[2])
+ if err != nil || !validSignature([]byte(signed), signature, a.keys) {
+ return ErrUnauthorized
+ }
+
+ var tokenHeader header
+ if err := decodePart(parts[0], &tokenHeader); err != nil || tokenHeader.Algorithm != "HS256" {
+ return ErrUnauthorized
+ }
+ var claims Claims
+ if err := decodePart(parts[1], &claims); err != nil {
+ return ErrUnauthorized
+ }
+ now := a.now().Unix()
+ if claims.Audience != "hogql-language-service" || claims.ExpiresAt <= now || claims.NotBefore > now || claims.TeamID != authorization.TeamID || claims.UserID != authorization.UserID {
+ return ErrUnauthorized
+ }
+ for _, allowed := range claims.Operations {
+ if allowed == string(operation) {
+ return nil
+ }
+ }
+ return ErrUnauthorized
+}
+
+func decodePart(part string, target any) error {
+ decoded, err := base64.RawURLEncoding.DecodeString(part)
+ if err != nil {
+ return err
+ }
+ return json.Unmarshal(decoded, target)
+}
+
+func validSignature(message, signature []byte, keys [][]byte) bool {
+ valid := false
+ for _, key := range keys {
+ mac := hmac.New(sha256.New, key)
+ _, _ = mac.Write(message)
+ valid = hmac.Equal(signature, mac.Sum(nil)) || valid
+ }
+ return valid
+}
diff --git a/services/hogql-language-service/internal/serviceauth/auth_test.go b/services/hogql-language-service/internal/serviceauth/auth_test.go
new file mode 100644
index 000000000000..8abc51af51fe
--- /dev/null
+++ b/services/hogql-language-service/internal/serviceauth/auth_test.go
@@ -0,0 +1,73 @@
+package serviceauth
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "testing"
+ "time"
+)
+
+func TestVerifyScopesTokenToCatalogAndOperation(t *testing.T) {
+ authenticator := New([]string{"current-key", "previous-key"}, false)
+ authenticator.now = func() time.Time { return time.Unix(100, 0) }
+ token := signToken(t, "previous-key", Claims{
+ Audience: "hogql-language-service",
+ TeamID: 1,
+ UserID: 10,
+ Operations: []string{"complete"},
+ ExpiresAt: 200,
+ })
+
+ if err := authenticator.Verify("Bearer "+token, Authorization{TeamID: 1, UserID: 10}, OperationComplete); err != nil {
+ t.Fatalf("valid rotated key was rejected: %v", err)
+ }
+ for _, test := range []struct {
+ teamID int64
+ userID int64
+ operation Operation
+ }{
+ {teamID: 2, userID: 10, operation: OperationComplete},
+ {teamID: 1, userID: 20, operation: OperationComplete},
+ {teamID: 1, userID: 10, operation: OperationPublish},
+ } {
+ authorization := Authorization{TeamID: test.teamID, UserID: test.userID}
+ if err := authenticator.Verify("Bearer "+token, authorization, test.operation); err == nil {
+ t.Fatalf("token unexpectedly authorized %s for team %d user %d", test.operation, test.teamID, test.userID)
+ }
+ }
+}
+
+func TestVerifyRejectsExpiredAndUnsignedTokens(t *testing.T) {
+ authenticator := New([]string{"key"}, false)
+ authenticator.now = func() time.Time { return time.Unix(100, 0) }
+ expired := signToken(t, "key", Claims{Audience: "hogql-language-service", TeamID: 1, UserID: 10, Operations: []string{"complete"}, ExpiresAt: 100})
+
+ for _, authorization := range []string{"", "Bearer unsigned", "Bearer " + expired} {
+ if err := authenticator.Verify(authorization, Authorization{TeamID: 1, UserID: 10}, OperationComplete); err == nil {
+ t.Fatalf("invalid token was accepted: %q", authorization)
+ }
+ }
+ if err := New(nil, true).Verify("", Authorization{}, OperationComplete); err == nil {
+ t.Fatal("insecure local mode accepted an empty authorization scope")
+ }
+}
+
+func signToken(t *testing.T, key string, claims Claims) string {
+ t.Helper()
+ headerJSON, err := json.Marshal(header{Algorithm: "HS256"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ claimsJSON, err := json.Marshal(claims)
+ if err != nil {
+ t.Fatal(err)
+ }
+ encodedHeader := base64.RawURLEncoding.EncodeToString(headerJSON)
+ encodedClaims := base64.RawURLEncoding.EncodeToString(claimsJSON)
+ message := encodedHeader + "." + encodedClaims
+ mac := hmac.New(sha256.New, []byte(key))
+ _, _ = mac.Write([]byte(message))
+ return message + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
+}
diff --git a/services/hogql-language-service/internal/validation/validation.go b/services/hogql-language-service/internal/validation/validation.go
new file mode 100644
index 000000000000..250c2dc5f60b
--- /dev/null
+++ b/services/hogql-language-service/internal/validation/validation.go
@@ -0,0 +1,424 @@
+package validation
+
+import (
+ "fmt"
+ "regexp"
+ "sort"
+ "strings"
+ "time"
+
+ 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 Suggestion struct {
+ Label string `json:"label"`
+ Distance int `json:"distance"`
+}
+
+type Diagnostic struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+ Start int `json:"start"`
+ End int `json:"end"`
+ Suggestions []Suggestion `json:"suggestions,omitempty"`
+}
+
+type Result struct {
+ Valid bool `json:"valid"`
+ Diagnostics []Diagnostic `json:"diagnostics"`
+ TableNames []string `json:"tableNames"`
+ DurationMicros int64 `json:"durationMicros"`
+}
+
+type tableBinding struct {
+ name string
+ table catalog.Table
+}
+
+type queryScope struct {
+ query *clickhouse.SelectQuery
+ parent *queryScope
+ bindings map[string]tableBinding
+}
+
+var tableReferencePattern = regexp.MustCompile(`(?i)\b(?:FROM|JOIN)\s+([A-Za-z_][A-Za-z0-9_.$]*)`)
+
+func Validate(schema *catalog.Catalog, query string) Result {
+ started := time.Now()
+ if err := querylimits.Validate(query); err != nil {
+ return result([]Diagnostic{{Code: "query_limit", Message: err.Error(), Start: 0, End: len(query)}}, nil, started)
+ }
+ parserQuery, originalTableNames := normalizeHogQLTableReferences(query)
+ statements, err := clickhouse.NewParser(parserQuery).ParseStmts()
+ if err != nil {
+ return result([]Diagnostic{{
+ Code: "syntax_error", Message: err.Error(), Start: 0, End: len(query),
+ }}, nil, started)
+ }
+
+ tablesByName := make(map[string]catalog.Table, len(schema.Tables))
+ for name, table := range schema.Tables {
+ tablesByName[strings.ToLower(name)] = table
+ }
+
+ var diagnostics []Diagnostic
+ var referencedTableNames []string
+ seenTableNames := map[string]bool{}
+ for _, statement := range statements {
+ scopes := queryScopes(statement)
+ ignoredIdents := map[*clickhouse.Ident]bool{}
+ clickhouse.Walk(statement, func(node clickhouse.Expr) bool {
+ switch typed := node.(type) {
+ case *clickhouse.TableExpr:
+ name, alias, start, end, ok := tableReference(typed)
+ if !ok {
+ return true
+ }
+ if original, exists := originalTableNames[strings.ToLower(name)]; exists {
+ name = original
+ }
+ lowerName := strings.ToLower(name)
+ if !seenTableNames[lowerName] {
+ referencedTableNames = append(referencedTableNames, name)
+ seenTableNames[lowerName] = true
+ }
+ table, exists := tablesByName[strings.ToLower(name)]
+ if !exists {
+ if len(diagnostics) < querylimits.MaxDiagnostics {
+ diagnostics = append(diagnostics, Diagnostic{
+ Code: "unknown_table", Message: fmt.Sprintf("Unknown table %q", name), Start: start, End: end,
+ Suggestions: closest(name, tableNames(schema), 5),
+ })
+ }
+ return true
+ }
+ binding := tableBinding{name: name, table: table}
+ scope := innermostScope(scopes, start, end)
+ if scope == nil {
+ return true
+ }
+ scope.bindings[strings.ToLower(name)] = binding
+ if alias != "" {
+ scope.bindings[strings.ToLower(alias)] = binding
+ }
+ case *clickhouse.TableIdentifier:
+ ignoredIdents[typed.Database] = true
+ ignoredIdents[typed.Table] = true
+ case *clickhouse.FunctionExpr:
+ ignoredIdents[typed.Name] = true
+ case *clickhouse.SelectItem:
+ ignoredIdents[typed.Alias] = true
+ case *clickhouse.AliasExpr:
+ if alias, ok := typed.Alias.(*clickhouse.Ident); ok {
+ ignoredIdents[alias] = true
+ }
+ }
+ return true
+ })
+ seen := map[string]bool{}
+ clickhouse.Walk(statement, func(node clickhouse.Expr) bool {
+ switch typed := node.(type) {
+ case *clickhouse.Path:
+ for _, field := range typed.Fields {
+ ignoredIdents[field] = true
+ }
+ if len(typed.Fields) < 2 {
+ return true
+ }
+ bindings := visibleBindings(innermostScope(scopes, int(node.Pos()), int(node.End())))
+ if len(bindings) == 0 {
+ return true
+ }
+ parts := make([]string, len(typed.Fields))
+ for index, field := range typed.Fields {
+ parts[index] = field.Name
+ }
+ bindingNames := make(map[string]string, len(bindings))
+ for name, binding := range bindings {
+ bindingNames[name] = binding.name
+ }
+ if namespace, ok := propertyresolver.Resolve(parts, bindingNames); ok {
+ validateProperty(&diagnostics, seen, schema.Properties[namespace], typed.Fields[len(typed.Fields)-1])
+ return true
+ }
+ if binding, ok := bindings[strings.ToLower(typed.Fields[0].Name)]; ok {
+ validateField(&diagnostics, seen, binding.table, typed.Fields[1])
+ }
+ case *clickhouse.Ident:
+ if ignoredIdents[typed] {
+ return true
+ }
+ bindings := visibleBindings(innermostScope(scopes, int(node.Pos()), int(node.End())))
+ if len(bindings) > 0 {
+ validateUnqualifiedField(&diagnostics, seen, bindings, typed)
+ }
+ }
+ return true
+ })
+ }
+ return result(diagnostics, referencedTableNames, started)
+}
+
+func queryScopes(statement clickhouse.Expr) []*queryScope {
+ var scopes []*queryScope
+ clickhouse.Walk(statement, func(node clickhouse.Expr) bool {
+ if query, ok := node.(*clickhouse.SelectQuery); ok {
+ scopes = append(scopes, &queryScope{query: query, bindings: map[string]tableBinding{}})
+ }
+ return true
+ })
+ for _, scope := range scopes {
+ for _, candidate := range scopes {
+ if scope == candidate || span(candidate.query) <= span(scope.query) || !contains(candidate.query, int(scope.query.Pos()), int(scope.query.End())) {
+ continue
+ }
+ if scope.parent == nil || span(candidate.query) < span(scope.parent.query) {
+ scope.parent = candidate
+ }
+ }
+ }
+ return scopes
+}
+
+func innermostScope(scopes []*queryScope, start, end int) *queryScope {
+ var found *queryScope
+ for _, scope := range scopes {
+ if contains(scope.query, start, end) && (found == nil || span(scope.query) < span(found.query)) {
+ found = scope
+ }
+ }
+ return found
+}
+
+func contains(query *clickhouse.SelectQuery, start, end int) bool {
+ return int(query.Pos()) <= start && end <= int(query.End())
+}
+
+func span(query *clickhouse.SelectQuery) int {
+ return int(query.End() - query.Pos())
+}
+
+func visibleBindings(scope *queryScope) map[string]tableBinding {
+ bindings := map[string]tableBinding{}
+ for current := scope; current != nil; current = current.parent {
+ for name, binding := range current.bindings {
+ if _, exists := bindings[name]; !exists {
+ bindings[name] = binding
+ }
+ }
+ }
+ return bindings
+}
+
+func validateProperty(diagnostics *[]Diagnostic, seen map[string]bool, properties []catalog.Property, ident *clickhouse.Ident) {
+ if len(*diagnostics) >= querylimits.MaxDiagnostics {
+ return
+ }
+ for _, property := range properties {
+ if strings.EqualFold(property.Name, ident.Name) {
+ return
+ }
+ }
+ key := fmt.Sprintf("%d:%d", ident.Pos(), ident.End())
+ if seen[key] {
+ return
+ }
+ seen[key] = true
+ names := make([]string, len(properties))
+ for index, property := range properties {
+ names[index] = property.Name
+ }
+ *diagnostics = append(*diagnostics, Diagnostic{
+ Code: "unknown_property", Message: fmt.Sprintf("Unknown property %q", ident.Name), Start: int(ident.Pos()), End: int(ident.End()),
+ Suggestions: closest(ident.Name, names, 5),
+ })
+}
+
+func normalizeHogQLTableReferences(query string) (string, map[string]string) {
+ normalized := []byte(query)
+ originalNames := map[string]string{}
+ for _, indexes := range tableReferencePattern.FindAllStringSubmatchIndex(query, -1) {
+ start, end := indexes[2], indexes[3]
+ name := query[start:end]
+ firstDot := strings.IndexByte(name, '.')
+ if firstDot == -1 || !strings.Contains(name[firstDot+1:], ".") {
+ continue
+ }
+ for index := start + firstDot + 1; index < end; index++ {
+ if normalized[index] == '.' {
+ normalized[index] = '_'
+ }
+ }
+ originalNames[strings.ToLower(string(normalized[start:end]))] = name
+ }
+ return string(normalized), originalNames
+}
+
+func tableReference(expr *clickhouse.TableExpr) (name, alias string, start, end int, ok bool) {
+ node := expr.Expr
+ if aliased, isAlias := node.(*clickhouse.AliasExpr); isAlias {
+ node = aliased.Expr
+ if ident, isIdent := aliased.Alias.(*clickhouse.Ident); isIdent {
+ alias = ident.Name
+ }
+ }
+ identifier, isTable := node.(*clickhouse.TableIdentifier)
+ if !isTable || identifier.Table == nil {
+ return "", "", 0, 0, false
+ }
+ name = identifier.Table.Name
+ if identifier.Database != nil {
+ name = identifier.Database.Name + "." + name
+ }
+ return name, alias, int(identifier.Pos()), int(identifier.End()), true
+}
+
+func validateField(diagnostics *[]Diagnostic, seen map[string]bool, table catalog.Table, ident *clickhouse.Ident) {
+ if len(*diagnostics) >= querylimits.MaxDiagnostics {
+ return
+ }
+ if hasField(table, ident.Name) {
+ return
+ }
+ key := fmt.Sprintf("%d:%d", ident.Pos(), ident.End())
+ if seen[key] {
+ return
+ }
+ seen[key] = true
+ *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, fieldNames(table), 5),
+ })
+}
+
+func validateUnqualifiedField(diagnostics *[]Diagnostic, seen map[string]bool, bindings map[string]tableBinding, ident *clickhouse.Ident) {
+ if len(*diagnostics) >= querylimits.MaxDiagnostics {
+ return
+ }
+ uniqueTables := map[string]catalog.Table{}
+ for _, binding := range bindings {
+ uniqueTables[binding.name] = binding.table
+ if hasField(binding.table, ident.Name) {
+ return
+ }
+ }
+ candidates := make([]string, 0)
+ for _, table := range uniqueTables {
+ candidates = append(candidates, fieldNames(table)...)
+ }
+ key := fmt.Sprintf("%d:%d", ident.Pos(), ident.End())
+ if seen[key] {
+ return
+ }
+ seen[key] = true
+ *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, candidates, 5),
+ })
+}
+
+func hasField(table catalog.Table, name string) bool {
+ for fieldName := range table.Fields {
+ if strings.EqualFold(fieldName, name) {
+ return true
+ }
+ }
+ return false
+}
+
+func tableNames(schema *catalog.Catalog) []string {
+ names := make([]string, 0, len(schema.Tables))
+ for name := range schema.Tables {
+ names = append(names, name)
+ }
+ return names
+}
+
+func fieldNames(table catalog.Table) []string {
+ names := make([]string, 0, len(table.Fields))
+ for name := range table.Fields {
+ names = append(names, name)
+ }
+ return names
+}
+
+func closest(input string, candidates []string, limit int) []Suggestion {
+ if len(input) > querylimits.MaxSuggestionInputBytes {
+ return nil
+ }
+ lowerInput := strings.ToLower(input)
+ leftRunes := []rune(lowerInput)
+ threshold := min(4, max(2, len(leftRunes)/3))
+ unique := map[string]Suggestion{}
+ for _, candidate := range candidates {
+ if len(candidate) > querylimits.MaxSuggestionInputBytes {
+ continue
+ }
+ lowerCandidate := strings.ToLower(candidate)
+ rightRunes := []rune(lowerCandidate)
+ lengthDifference := max(len(leftRunes), len(rightRunes)) - min(len(leftRunes), len(rightRunes))
+ prefix := strings.HasPrefix(lowerCandidate, lowerInput)
+ if lengthDifference > threshold && !prefix {
+ continue
+ }
+ distance := lengthDifference
+ if !prefix {
+ distance = levenshtein(leftRunes, rightRunes)
+ }
+ if distance > threshold {
+ continue
+ }
+ key := lowerCandidate
+ if existing, ok := unique[key]; !ok || distance < existing.Distance {
+ unique[key] = Suggestion{Label: candidate, Distance: distance}
+ }
+ }
+ result := make([]Suggestion, 0, len(unique))
+ for _, suggestion := range unique {
+ result = append(result, suggestion)
+ }
+ sort.Slice(result, func(i, j int) bool {
+ if result[i].Distance != result[j].Distance {
+ return result[i].Distance < result[j].Distance
+ }
+ return result[i].Label < result[j].Label
+ })
+ return result[:min(limit, len(result))]
+}
+
+func levenshtein(leftRunes, rightRunes []rune) int {
+ previous := make([]int, len(rightRunes)+1)
+ current := make([]int, len(rightRunes)+1)
+ for index := range previous {
+ previous[index] = index
+ }
+ for leftIndex, leftRune := range leftRunes {
+ current[0] = leftIndex + 1
+ for rightIndex, rightRune := range rightRunes {
+ cost := 1
+ if leftRune == rightRune {
+ cost = 0
+ }
+ current[rightIndex+1] = min(current[rightIndex]+1, previous[rightIndex+1]+1, previous[rightIndex]+cost)
+ }
+ previous, current = current, previous
+ }
+ return previous[len(rightRunes)]
+}
+
+func result(diagnostics []Diagnostic, tableNames []string, started time.Time) Result {
+ if diagnostics == nil {
+ diagnostics = []Diagnostic{}
+ }
+ if tableNames == nil {
+ tableNames = []string{}
+ }
+ return Result{
+ Valid: len(diagnostics) == 0, Diagnostics: diagnostics, TableNames: tableNames,
+ DurationMicros: time.Since(started).Microseconds(),
+ }
+}
diff --git a/services/hogql-language-service/internal/validation/validation_test.go b/services/hogql-language-service/internal/validation/validation_test.go
new file mode 100644
index 000000000000..d12d3c8b04cd
--- /dev/null
+++ b/services/hogql-language-service/internal/validation/validation_test.go
@@ -0,0 +1,137 @@
+package validation
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+)
+
+func schema() *catalog.Catalog {
+ return &catalog.Catalog{Tables: map[string]catalog.Table{
+ "warehouse_orders": {Name: "warehouse_orders", Type: "data_warehouse", Fields: map[string]catalog.Field{
+ "order_id": {Name: "order_id", Type: "string"},
+ "amount": {Name: "amount", Type: "float"},
+ }},
+ "warehouse_people": {Name: "warehouse_people", Type: "data_warehouse", Fields: map[string]catalog.Field{
+ "person_id": {Name: "person_id", Type: "string"},
+ }},
+ "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"}}},
+ "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"}},
+ "person": {{Name: "$geo_country", ValueType: "String"}},
+ "session": {{Name: "$entry_current_url", ValueType: "String"}},
+ "group:0": {{Name: "industry", ValueType: "String"}},
+ }}
+}
+
+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" {
+ t.Fatalf("result = %#v", result)
+ }
+}
+
+func TestValidateDoesNotShareBindingsAcrossNestedQueries(t *testing.T) {
+ result := Validate(schema(), "SELECT person_id FROM warehouse_orders WHERE order_id IN (SELECT person_id FROM warehouse_people)")
+ if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "unknown_field" {
+ t.Fatalf("result = %#v", result)
+ }
+}
+
+func TestValidateNestedAliasShadowsOuterAlias(t *testing.T) {
+ result := Validate(schema(), "SELECT o.person_id FROM warehouse_orders AS o WHERE order_id IN (SELECT o.person_id FROM warehouse_people AS o)")
+ if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "unknown_field" {
+ t.Fatalf("result = %#v", result)
+ }
+}
+
+func TestValidateAllJoinedTables(t *testing.T) {
+ result := Validate(schema(), "SELECT o.order_id, p.person_id FROM warehouse_orders AS o JOIN warehouse_people AS p ON o.order_id = p.person_id")
+ if !result.Valid {
+ t.Fatalf("result = %#v", result)
+ }
+}
+
+func TestValidateRejectsQueriesOutsideResourceLimits(t *testing.T) {
+ result := Validate(schema(), strings.Repeat("x", 64<<10+1))
+ if result.Valid || len(result.Diagnostics) != 1 || result.Diagnostics[0].Code != "query_limit" {
+ t.Fatalf("result = %#v", result)
+ }
+}
+
+func TestValidateCapsDiagnostics(t *testing.T) {
+ fields := make([]string, 150)
+ for index := range fields {
+ fields[index] = "missing_" + strings.Repeat("x", index%10) + string(rune('a'+index%26))
+ }
+ result := Validate(schema(), "SELECT "+strings.Join(fields, ", ")+" FROM warehouse_orders")
+ if len(result.Diagnostics) != 25 {
+ t.Fatalf("diagnostics = %d", len(result.Diagnostics))
+ }
+}
+
+func TestValidateUnknownTableSuggestsVisibleMatch(t *testing.T) {
+ result := Validate(schema(), "SELECT order_id FROM warehose_orders")
+ if result.Valid || len(result.Diagnostics) != 1 {
+ t.Fatalf("result = %#v", result)
+ }
+ diagnostic := result.Diagnostics[0]
+ if diagnostic.Code != "unknown_table" || len(diagnostic.Suggestions) == 0 || diagnostic.Suggestions[0].Label != "warehouse_orders" {
+ t.Fatalf("diagnostic = %#v", diagnostic)
+ }
+}
+
+func TestValidateUnknownAliasedFieldSuggestsVisibleMatch(t *testing.T) {
+ result := Validate(schema(), "SELECT o.amuont FROM warehouse_orders AS o")
+ if result.Valid || len(result.Diagnostics) != 1 {
+ t.Fatalf("result = %#v", result)
+ }
+ diagnostic := result.Diagnostics[0]
+ if diagnostic.Code != "unknown_field" || len(diagnostic.Suggestions) == 0 || diagnostic.Suggestions[0].Label != "amount" || diagnostic.Suggestions[0].Distance != 2 {
+ t.Fatalf("diagnostic = %#v", diagnostic)
+ }
+}
+
+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)
+ }
+}
+
+func TestValidateAcceptsHogQLQualifiedTable(t *testing.T) {
+ result := Validate(schema(), "SELECT o.synced_id FROM postgres.synced.orders AS o")
+ if !result.Valid || len(result.Diagnostics) != 0 {
+ t.Fatalf("result = %#v", result)
+ }
+}
+
+func TestValidatePropertiesAcrossGenericNamespaces(t *testing.T) {
+ tests := []struct {
+ query string
+ suggestion string
+ }{
+ {query: "SELECT e.properties.$geo_cty FROM events AS e", suggestion: "$geo_city"},
+ {query: "SELECT persons.properties.$geo_contry FROM persons", suggestion: "$geo_country"},
+ {query: "SELECT session.properties.$entry_curent_url FROM events", suggestion: "$entry_current_url"},
+ {query: "SELECT group_0.properties.indstry FROM events", suggestion: "industry"},
+ }
+ for _, test := range tests {
+ result := Validate(schema(), test.query)
+ if result.Valid || len(result.Diagnostics) != 1 {
+ t.Fatalf("query %q returned %#v", test.query, result)
+ }
+ diagnostic := result.Diagnostics[0]
+ if diagnostic.Code != "unknown_property" || len(diagnostic.Suggestions) == 0 || diagnostic.Suggestions[0].Label != test.suggestion {
+ t.Fatalf("query %q returned %#v", test.query, diagnostic)
+ }
+ }
+}
diff --git a/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py b/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py
index 9b1f93b66179..e7394e53e69f 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py
@@ -701,9 +701,12 @@ class TestSemgrepServicesCoverageCheck:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- - run: |
- semgrep scan services/api/
- semgrep scan services/worker/
+ - run: semgrep scan services/api/
+ semgrep-go:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - run: semgrep scan services/worker/
semgrep-js:
runs-on: ubuntu-latest
timeout-minutes: 5
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/semgrep_services_coverage.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/semgrep_services_coverage.py
index 2a314d99c357..95f253acaa20 100644
--- a/tools/hogli-commands/hogli_commands/workflow_lint/checks/semgrep_services_coverage.py
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/semgrep_services_coverage.py
@@ -1,7 +1,7 @@
"""Every ``services/<name>/`` is covered by a language-specific Semgrep job.
The repo-wide ``semgrep-general`` job excludes ``services/``, so a new
-service added without updating ``semgrep-python`` or ``semgrep-js`` silently
+service added without updating a language-specific scan silently
drops out of SAST.
Unlike the other checks, this one needs filesystem context (``services/``)
@@ -25,7 +25,7 @@ from hogli.manifest import REPO_ROOT
from ..check import CheckResult, Issue, WorkflowCheck
from ..model import Workflow
-COVERING_JOBS = ("semgrep-python", "semgrep-js")
+COVERING_JOBS = ("semgrep-python", "semgrep-go", "semgrep-js")
SECURITY_WORKFLOW_NAME = "ci-security.yaml"