diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index 82eaeb747..f47e2ac92 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -4,6 +4,11 @@ on: pull_request: branches: [ "master" ] +permissions: + contents: read + # Allows the lint job's only-new-issues option to read the PR diff. + pull-requests: read + jobs: build: @@ -25,5 +30,44 @@ jobs: CGO_ENABLED=0 go build -ldflags="-extldflags=-static" -o gigapipe cmd/gigapipe/main.go - name: Unit tests - run: go test ./... + run: go test -race ./... + + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: golangci-lint + uses: golangci/golangci-lint-action@v9 + with: + # Must be built with a Go toolchain >= go.mod's `go` directive, or + # golangci-lint refuses to run at all. + version: v2.13.1 + # Grandfather in pre-existing findings; gate only newly introduced + # ones so adoption doesn't require cleaning up the whole repo first. + only-new-issues: true + + arch-lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: '1.26' + + - name: Install go-arch-lint + run: go install github.com/fe3dback/go-arch-lint@v1.15.0 + # Report-only: baselines current package coupling against + # .go-arch-lint.yml without gating the merge. continue-on-error keeps + # this from blocking a PR while still surfacing the report. + - name: go-arch-lint check (report-only) + continue-on-error: true + run: go-arch-lint check diff --git a/.gitignore b/.gitignore index 9741e638b..7a31e4e04 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ *.idx /docker /deps +/.claude/ diff --git a/.go-arch-lint.yml b/.go-arch-lint.yml new file mode 100644 index 000000000..93108965b --- /dev/null +++ b/.go-arch-lint.yml @@ -0,0 +1,52 @@ +# go-arch-lint configuration, report-only baseline (schema v3). +# +# This describes the current *rough* top-level layering of the repo +# (reader/, writer/, ruler/, shared/, ctrl/, cmd/, view/) so that +# `go-arch-lint check` runs cleanly today and can be tightened later. +# Dependency rules are deliberately permissive (anyProjectDeps/anyVendorDeps) +# — the point of this pass is to baseline current package coupling, not to +# enforce boundaries that don't exist yet. Run "go-arch-lint check" locally +# to see the current dependency graph; this is not wired as a CI gate. +version: 3 + +allow: + depOnAnyVendor: true + +components: + cmd: + in: cmd/** + ctrl: + in: ctrl/** + reader: + in: reader/** + writer: + in: writer/** + ruler: + in: ruler/** + shared: + in: shared/** + view: + in: view/** + test: + in: test/** + +deps: + cmd: + anyProjectDeps: true + ctrl: + anyProjectDeps: true + reader: + anyProjectDeps: true + writer: + anyProjectDeps: true + ruler: + anyProjectDeps: true + shared: + # shared already imports from reader/ and writer/ today (e.g. + # shared/commonroutes/controller.go); left permissive rather than + # inventing a boundary that doesn't exist yet. + anyProjectDeps: true + view: + anyProjectDeps: true + test: + anyProjectDeps: true diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..3d86fb433 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,62 @@ +# golangci-lint configuration (schema v2). +# +# Goal for this pass: a reasonable, not-overly-strict baseline appropriate for +# a mid-size *existing* codebase, not a from-scratch project. Linter choice +# and tuning below were derived by actually running golangci-lint against +# this repo and looking at what fired: +# +# - errcheck is intentionally NOT enabled. This codebase idiomatically +# ignores errors from things like http.ResponseWriter.Write and +# rows/conn.Close() in defers; enabling it flags ~170 pre-existing call +# sites that are not bugs, just this codebase's style. +# - govet's "structtag" and "composites" checks are disabled. Both parsers +# built on github.com/alecthomas/participle encode grammar rules as +# struct tags (e.g. `@@`, `"(" @@ ")"`) that are not real reflect +# struct tags, and lexer rule tables use unkeyed composite literals by +# participle's own convention. These would fire on every new grammar +# rule added to the PromQL/LogQL/TraceQL parsers, which is exactly the +# code this milestone's corpus work touches most. +# - staticcheck is restricted to the SA* (actual bug/deprecation) checks. +# The ST*/S*/QF* style and quickfix checks bundled into staticcheck by +# default add ~90 pre-existing stylistic findings (e.g. "could use +# strings.ReplaceAll", implicit type on declaration) that are not worth +# a hard gate right now. +# +# ineffassign, unused, misspell, unconvert, gofmt and goimports are enabled +# as-is; the CI job runs golangci-lint-action with only-new-issues so this +# initial adoption gates new/changed code without requiring a full +# pre-existing-debt cleanup as a prerequisite. +version: "2" + +linters: + default: none + enable: + - govet + - ineffassign + - unused + - staticcheck + - misspell + - unconvert + settings: + govet: + disable: + - structtag + - composites + staticcheck: + checks: + - "SA*" + exclusions: + paths: + # Ported/vendored-style algorithm implementations (two independent + # copies pre-date this config); not code we want a style gate on. + - reader/utils/cityhash102 + - writer/utils/helputils/cityhash102 + +formatters: + enable: + - gofmt + - goimports + exclusions: + paths: + - reader/utils/cityhash102 + - writer/utils/helputils/cityhash102 diff --git a/Makefile b/Makefile index 6e365abde..f213801d8 100644 --- a/Makefile +++ b/Makefile @@ -4,9 +4,47 @@ docker-compose ?= docker-compose # server (via compose interpolation) and the test runner see the same value. export QRYN_RULER_ENABLED ?= true +# Query heads with a parser fuzz target. +heads := promql logql traceql + +# HEAD/DURATION are set on the command line, e.g. `make fuzz HEAD=promql`. +HEAD ?= +DURATION ?= 60s + +.PHONY: docker e2e-deps e2e-build e2e-test e2e-cleanup e2e-full e2e-ci \ + build test-unit lint arch-lint fuzz + docker: docker build -f scripts/deploy/docker/Dockerfile -t gigapipe . +# Build the gigapipe binary the same way CI does. +build: + go mod tidy + CGO_ENABLED=0 go build -ldflags="-extldflags=-static" -o gigapipe cmd/gigapipe/main.go + +# Run the full unit-test suite with the race detector, matching CI. +test-unit: + go test -race ./... + +# Run golangci-lint with the repo's committed config, gating only issues +# introduced since origin/master (mirrors CI's only-new-issues option) so +# this doesn't fail locally on pre-existing repo-wide debt. +lint: + golangci-lint run --new-from-rev=origin/master + +# Run go-arch-lint in report-only mode against the baseline layering config. +arch-lint: + go-arch-lint check + +# Run the native Go parser fuzz target for one query head: +# make fuzz HEAD=promql|logql|traceql [DURATION=60s] +fuzz: + @case " $(heads) " in \ + *" $(HEAD) "*) ;; \ + *) echo "fuzz: unknown or missing HEAD '$(HEAD)' (expected one of: $(heads)); usage: make fuzz HEAD=promql [DURATION=60s]" >&2; exit 1 ;; \ + esac + go test "./reader/$(HEAD)/$(HEAD)_parser" -run '^$$' -fuzz "FuzzParse" -fuzztime "$(DURATION)" + e2e-deps: if [ ! -d ./deps/qryn-test ]; then git clone https://github.com/metrico/qryn-test.git ./deps/qryn-test; fi cd deps/qryn-test && git pull && git checkout main && git pull; diff --git a/docs/contributing.md b/docs/contributing.md index 09d9b904c..1d2714baf 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -69,6 +69,17 @@ For end-to-end tests: make e2e-full ``` +The Makefile also wraps the same build/test/lint lanes CI runs, plus +parser-fuzz helpers for the query transpilers: + +```bash +make build # build the gigapipe binary the way CI does +make test-unit # go test -race ./..., matching CI +make lint # golangci-lint, gated to issues new since origin/master +make arch-lint # go-arch-lint report against .go-arch-lint.yml +make fuzz HEAD=promql DURATION=60s # run the native Go parser fuzz target for a query head +``` + ## Submitting a Pull Request 1. Create a branch: diff --git a/reader/internal/parserpin/parserpin.go b/reader/internal/parserpin/parserpin.go new file mode 100644 index 000000000..40aebb497 --- /dev/null +++ b/reader/internal/parserpin/parserpin.go @@ -0,0 +1,70 @@ +package parserpin + +import ( + "reflect" + "testing" +) + +// ParserPinCase is one table-driven "valid query -> expected AST shape" or +// "invalid query -> expected error class" pin for a single query head's +// parser. +// +// Deep AST-shape assertions are genuinely different per head (PromQL, +// LogQL and TraceQL parsers produce unrelated types with no common +// interface worth inventing), so this helper only guarantees the shallow, +// generic assertion that is easy to make generic: a valid query parses to a +// non-nil root with no error, and an invalid query returns a non-nil error. +// A case that wants a deeper shape pin supplies Check, run only when parsing +// itself succeeds as expected. +type ParserPinCase[T any] struct { + // Name is the subtest name (t.Run). + Name string + // Query is the raw text handed to the parser. + Query string + // WantErr marks this as an invalid-query case: Parse must return a + // non-nil error, and Check (if set) is not run. + WantErr bool + // Check, if set, receives the parsed AST for a valid-query case for a + // head to assert deeper shape beyond "non-nil root". + Check func(t *testing.T, ast T) +} + +// RunParserPins runs every case in cases as a subtest, calling parse and +// asserting either a non-nil root with no error (WantErr == false) or a +// non-nil error (WantErr == true). +func RunParserPins[T any](t *testing.T, parse func(query string) (T, error), cases []ParserPinCase[T]) { + t.Helper() + for _, c := range cases { + c := c + t.Run(c.Name, func(t *testing.T) { + ast, err := parse(c.Query) + if c.WantErr { + if err == nil { + t.Fatalf("Parse(%q): expected an error, got none", c.Query) + } + return + } + if err != nil { + t.Fatalf("Parse(%q): unexpected error: %v", c.Query, err) + } + if isNilAST(ast) { + t.Fatalf("Parse(%q): expected a non-nil AST root", c.Query) + } + if c.Check != nil { + c.Check(t, ast) + } + }) + } +} + +// isNilAST reports whether a generic AST root (typically a pointer) is nil, +// without requiring T to satisfy any particular interface. +func isNilAST(ast any) bool { + v := reflect.ValueOf(ast) + switch v.Kind() { + case reflect.Pointer, reflect.Interface, reflect.Slice, reflect.Map, reflect.Chan, reflect.Func: + return v.IsNil() + default: + return false + } +} diff --git a/reader/logql/logql_parser/fuzz_test.go b/reader/logql/logql_parser/fuzz_test.go new file mode 100644 index 000000000..dd3bdbe42 --- /dev/null +++ b/reader/logql/logql_parser/fuzz_test.go @@ -0,0 +1,137 @@ +package logql_parser + +import "testing" + +// FuzzParse asserts that Parse never panics on arbitrary input. It makes no +// claim about output shape or correctness. +// +// Not part of the default test/CI lane: native Go fuzz targets only run +// their seed corpus under plain `go test`, and are otherwise driven locally +// via `make fuzz HEAD=logql DURATION=` (or `go test -fuzz=FuzzParse`). +func FuzzParse(f *testing.F) { + for _, seed := range []string{ + `{app="x"}`, + `{app="x", env="prod"}`, + `{app="x"} |= "GET"`, + `{app="x"} |~ "2[0-9]$"`, + `{app="x"} != "error" != "debug"`, + `{app="x"} | json`, + `{app="x"} | json field="value"`, + `{app="x"} | logfmt`, + `{app="x"} | regexp "^(?[^0-9]+)[0-9]+$"`, + `rate({app="x"} |= "GET" [5m])`, + `sum by (app) (rate({app="x"} [1m]))`, + `sum_over_time({app="x"} | json | unwrap value [1m]) by (app)`, + `{app="x"} | line_format "{{.field}}"`, + `{app="x"} | freq > 4 and (status="4" or status==2)`, + + // The rest of this seed corpus is drawn from grafana/loki's + // pkg/logql/bench query registry — a broader spread of LogQL grammar + // (drop/unwrap-conversion-function/detected_level, empty by()/ + // without(), chained label filters) than the hand-written seeds + // above cover alone. Several exercise constructs this parser + // currently rejects (see the invalid_* parser pins) — useful fuzz + // input either way, since FuzzParse only asserts no panic. + `{app="x"} | detected_level="error"`, + `{app="x"} | logfmt | detected_level="error"`, + `{app="x"} | detected_level="error" | logfmt`, + `{app="x"} | json | detected_level="error"`, + `{app="x"} | detected_level="error" | json`, + `{app="x"} |= "level"`, + `{app="x"} |~ "(?i)error"`, + `{app="x"} !~ "(?i)debug"`, + `{app="x"} | field = "value"`, + `{app="x"} |= "this will not hit any line"`, + `sum(count_over_time({app="x"}[5m]))`, + `sum(count_over_time({app="x"} | detected_level=~"error|warn" [5m]))`, + `sum(rate({app="x"} | detected_level=~"error|warn" [5m]))`, + `sum(count_over_time({app="x"} |= "level" [5m]))`, + `sum(avg_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `sum(avg_over_time({app="x"} |= "level" | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `sum(min_over_time({app="x"} |= "level" | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `sum(max_over_time({app="x"} |= "level" | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `sum by (pod) (count_over_time({app="x"}[5m]))`, + `sum by (namespace) (count_over_time({app="x"}[5m]))`, + `sum by (service_name) (count_over_time({app="x"}[5m]))`, + `sum by (detected_level) (count_over_time({app="x"}[5m]))`, + `sum by (cluster, namespace) (count_over_time({app="x"}[5m]))`, + `sum by (service_name, container) (count_over_time({app="x"}[5m]))`, + `sum by (level) (sum_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `sum by (level) (sum_over_time({app="x"} | logfmt | duration != "" | unwrap duration_seconds(duration) [5m]))`, + `max by (level) (min_over_time({app="x"} | logfmt | duration != "" | unwrap duration_seconds(duration) [5m]))`, + `avg by (level) (avg_over_time({app="x"} | logfmt | duration != "" | unwrap duration_seconds(duration) [5m]))`, + `max by () (avg_over_time({app="x"} | logfmt | duration != "" | unwrap duration_seconds(duration) [5m]))`, + `max by (level) (avg_over_time({app="x"} | logfmt | duration != "" | unwrap duration_seconds(duration) [5m]) without (service_name))`, + `max without () (sum_over_time({app="x"} | logfmt | duration != "" | unwrap duration_seconds(duration) [5m]))`, + `avg_over_time({app="x"} | logfmt | duration != "" | unwrap duration_seconds(duration) [5m])`, + `sum_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m])`, + `rate({app="x"} | json | unwrap duration_ms [5m])`, + `sum by (level) (rate({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `rate({app="x"} | logfmt | duration != "" | unwrap duration_seconds(duration) [5m])`, + `sum_over_time({app="x"} | json | unwrap duration_ms [5m])`, + `sum(sum_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `sum by (level, namespace) (sum_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `sum without (namespace) (sum_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `sum by (level) (sum_over_time({app="x"} | logfmt | unwrap bytes [5m]))`, + `avg_over_time({app="x"} | json | unwrap duration_ms [5m])`, + `avg(avg_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `avg by (level) (avg_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `max_over_time({app="x"} | json | unwrap duration_ms [5m])`, + `max(max_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `max by (level) (max_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `max by (level) (max_over_time({app="x"} | logfmt | duration != "" | unwrap duration_seconds(duration) [5m]))`, + `min_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m])`, + `min(min_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `min by (level) (min_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `min by (level) (min_over_time({app="x"} | logfmt | duration != "" | unwrap duration_seconds(duration) [5m]))`, + `sum by (detected_level) (sum_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `stdvar_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m])`, + `avg by (level) (stdvar_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `stddev_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m])`, + `avg by (level) (stddev_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `quantile_over_time(0.5, {app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m])`, + `quantile_over_time(0.90, {app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m])`, + `quantile_over_time(0.95, {app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m])`, + `quantile_over_time(0.99, {app="x"} | json | unwrap duration_ms [5m])`, + `avg by (level) (quantile_over_time(0.99, {app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `quantile_over_time(0.99, {app="x"} | logfmt | duration != "" | unwrap duration_seconds(duration) [5m])`, + `sum_over_time({app="x"} | logfmt | size != "" | unwrap size [5m])`, + `max by () (max_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `sum without (namespace, cluster) (sum_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `max(avg by (level) (avg_over_time({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m])))`, + `sum(sum_over_time({app="x"} |= "level" | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `avg(avg_over_time({app="x"} |~ "(?i)error|warn" | logfmt | duration != "" | unwrap duration(duration) [5m]))`, + `sum by (level) (sum_over_time({app="x"} | logfmt | level != "" | duration != "" | unwrap duration(duration) [5m]))`, + `{app="x"} |~ "error|exception" | detected_level="error"`, + `{app="x"} | json | duration_seconds > 0.1 | detected_level!="debug"`, + `{app="x"} | logfmt | level="error" | detected_level="error"`, + `{app="x"} |~ "(?i)error" | json | logfmt | drop __error__, __error_details__ | status_code >= 500`, + `{app="x"} | detected_level="error" |~ "(?i)failed"`, + `{app="x"} | detected_level=~"error|warn" |~ "(?i)refused"`, + `{app="x"} | json | logfmt | drop __error__, __error_details__`, + `{app="x"} | json | logfmt | drop __error__, __error_details__ | level="error"`, + `{app="x"} | json | logfmt | drop __error__, __error_details__ | level="error" or level="warn"`, + `sum by (detected_level) (avg_over_time({app="x"} | json | logfmt | duration != "" | drop __error__, __error_details__ | unwrap duration_seconds(duration) [5m]))`, + `sum by (detected_level) (count_over_time({app="x"} | detected_level="debug" or detected_level="info" or detected_level="warn" |~ "(?i)(?i)duration" | json | logfmt | drop __error__, __error_details__ | level=~"(?i)INFO" [5m]))`, + `rate({app="x"} | logfmt | duration != "" | unwrap duration(duration) [5m])`, + `sum by (level) (avg_over_time({app="x"} | logfmt | duration != "" | unwrap duration_seconds(duration) [5m]))`, + `sum(sum_over_time({app="x"} | logfmt | duration != "" | unwrap duration_seconds(duration) [5m]))`, + `avg(avg_over_time({app="x"} | logfmt | duration != "" | unwrap duration_seconds(duration) [5m]))`, + `sum(sum_over_time({app="x"} | logfmt | unwrap bytes [5m]))`, + `sum(sum_over_time({app="x"} | logfmt | size != "" | unwrap size [5m]))`, + `avg(avg_over_time({app="x"} | logfmt | size != "" | unwrap size [5m]))`, + `avg(avg_over_time({app="x"} | logfmt | unwrap status [5m]))`, + `sum by (level) (count_over_time({app="x"} | json [5m]))`, + } { + f.Add(seed) + } + + f.Fuzz(func(t *testing.T, query string) { + defer func() { + if r := recover(); r != nil { + t.Fatalf("Parse panicked on %q: %v", query, r) + } + }() + _, _ = Parse(query) + }) +} diff --git a/reader/logql/logql_parser/parserpin_test.go b/reader/logql/logql_parser/parserpin_test.go new file mode 100644 index 000000000..2f230c910 --- /dev/null +++ b/reader/logql/logql_parser/parserpin_test.go @@ -0,0 +1,271 @@ +package logql_parser + +import ( + "testing" + + "github.com/metrico/qryn/v5/reader/internal/parserpin" +) + +// TestParserPins pins the LogQL parser's AST shape for a representative +// spread of valid query shapes, and its error behavior for a representative +// spread of invalid ones. See reader/internal/parserpin/parserpin.go for +// what RunParserPins asserts generically (non-nil root / non-nil error); the +// Check callbacks here go further for the cases where a deeper shape pin is +// worth the assertion. +func TestParserPins(t *testing.T) { + parserpin.RunParserPins(t, Parse, []parserpin.ParserPinCase[*LogQLScript]{ + { + Name: "bare_stream_selector", + Query: `{app="x"}`, + Check: func(t *testing.T, ast *LogQLScript) { + sel := ast.Head.StrSelector + if sel == nil { + t.Fatalf("expected a non-nil StrSelector head, got %+v", ast.Head) + } + if len(sel.StrSelCmds) != 1 || sel.StrSelCmds[0].Label.Name != "app" || sel.StrSelCmds[0].Op != "=" { + t.Errorf("expected a single app= matcher, got %+v", sel.StrSelCmds) + } + }, + }, + { + Name: "multi_matcher_selector", + Query: `{app="x", env=~"prod.*"}`, + Check: func(t *testing.T, ast *LogQLScript) { + sel := ast.Head.StrSelector + if sel == nil || len(sel.StrSelCmds) != 2 { + t.Fatalf("expected 2 matchers, got %+v", ast.Head) + } + if sel.StrSelCmds[1].Op != "=~" { + t.Errorf("expected second matcher op =~, got %q", sel.StrSelCmds[1].Op) + } + }, + }, + { + Name: "line_filter_contains", + Query: `{app="x"} |= "error"`, + Check: func(t *testing.T, ast *LogQLScript) { + sel := ast.Head.StrSelector + if sel == nil || len(sel.Pipelines) != 1 || sel.Pipelines[0].LineFilter == nil { + t.Fatalf("expected a single LineFilter pipeline stage, got %+v", ast.Head) + } + if sel.Pipelines[0].LineFilter.Fn != "|=" { + t.Errorf("expected line filter fn |=, got %q", sel.Pipelines[0].LineFilter.Fn) + } + }, + }, + { + Name: "label_filter_numeric", + Query: `{app="x"} | freq >= 4`, + Check: func(t *testing.T, ast *LogQLScript) { + sel := ast.Head.StrSelector + if sel == nil || len(sel.Pipelines) != 1 || sel.Pipelines[0].LabelFilter == nil { + t.Fatalf("expected a single LabelFilter pipeline stage, got %+v", ast.Head) + } + head := sel.Pipelines[0].LabelFilter.Head.SimpleHead + if head == nil || head.Fn != ">=" || head.NumVal != "4" { + t.Errorf("expected a numeric >= 4 filter, got %+v", head) + } + }, + }, + { + Name: "parser_json_with_params", + Query: `{app="x"} | json field="path"`, + Check: func(t *testing.T, ast *LogQLScript) { + sel := ast.Head.StrSelector + if sel == nil || len(sel.Pipelines) != 1 || sel.Pipelines[0].Parser == nil { + t.Fatalf("expected a single Parser pipeline stage, got %+v", ast.Head) + } + p := sel.Pipelines[0].Parser + if p.Fn != "json" || len(p.ParserParams) != 1 || p.ParserParams[0].Label.Name != "field" { + t.Errorf("expected json parser with 1 param named field, got %+v", p) + } + }, + }, + { + Name: "parser_logfmt_bare", + Query: `{app="x"} | logfmt`, + Check: func(t *testing.T, ast *LogQLScript) { + sel := ast.Head.StrSelector + if sel == nil || len(sel.Pipelines) != 1 || sel.Pipelines[0].Parser == nil { + t.Fatalf("expected a single Parser pipeline stage, got %+v", ast.Head) + } + if sel.Pipelines[0].Parser.Fn != "logfmt" { + t.Errorf("expected logfmt parser, got %q", sel.Pipelines[0].Parser.Fn) + } + }, + }, + { + Name: "line_format", + Query: "{app=\"x\"} | line_format `{{.path}}`", + Check: func(t *testing.T, ast *LogQLScript) { + sel := ast.Head.StrSelector + if sel == nil || len(sel.Pipelines) != 1 || sel.Pipelines[0].LineFormat == nil { + t.Fatalf("expected a single LineFormat pipeline stage, got %+v", ast.Head) + } + }, + }, + { + Name: "unwrap_both_spellings_equivalent", + Query: `sum_over_time({app="x"} | unwrap bytes [5m])`, + Check: func(t *testing.T, ast *LogQLScript) { + lra := ast.Head.LRAOrUnwrap + if lra == nil || lra.Fn != "sum_over_time" { + t.Fatalf("expected an LRAOrUnwrap head with fn sum_over_time, got %+v", ast.Head) + } + pipelines := lra.StrSel.Pipelines + if len(pipelines) != 1 || pipelines[0].Unwrap == nil { + t.Fatalf("expected a single Unwrap pipeline stage, got %+v", pipelines) + } + if pipelines[0].Unwrap.Fn != "unwrap" || pipelines[0].Unwrap.Label.Name != "bytes" { + t.Errorf("expected unwrap bytes, got %+v", pipelines[0].Unwrap) + } + }, + }, + { + Name: "range_aggregation_with_by", + Query: `rate({app="x"}[5m]) by (path)`, + Check: func(t *testing.T, ast *LogQLScript) { + lra := ast.Head.LRAOrUnwrap + if lra == nil || lra.Fn != "rate" { + t.Fatalf("expected an LRAOrUnwrap head with fn rate, got %+v", ast.Head) + } + if lra.ByOrWithoutSuffix == nil || lra.ByOrWithoutSuffix.Fn != "by" { + t.Fatalf("expected a by(...) suffix, got %+v", lra.ByOrWithoutSuffix) + } + if len(lra.ByOrWithoutSuffix.Labels) != 1 || lra.ByOrWithoutSuffix.Labels[0].Name != "path" { + t.Errorf("expected by(path), got %+v", lra.ByOrWithoutSuffix.Labels) + } + }, + }, + { + Name: "aggregation_sum_by", + Query: `sum by (path) (rate({app="x"}[1m]))`, + Check: func(t *testing.T, ast *LogQLScript) { + agg := ast.Head.AggOperator + if agg == nil || agg.Fn != "sum" { + t.Fatalf("expected an AggOperator head with fn sum, got %+v", ast.Head) + } + if agg.ByOrWithoutPrefix == nil || agg.ByOrWithoutPrefix.Fn != "by" { + t.Errorf("expected a by(...) prefix, got %+v", agg.ByOrWithoutPrefix) + } + }, + }, + { + Name: "aggregation_without", + Query: `sum without (instance) (rate({app="x"}[1m]))`, + Check: func(t *testing.T, ast *LogQLScript) { + agg := ast.Head.AggOperator + if agg == nil || agg.ByOrWithoutPrefix == nil || agg.ByOrWithoutPrefix.Fn != "without" { + t.Fatalf("expected a without(...) prefix, got %+v", ast.Head) + } + }, + }, + { + Name: "topk", + Query: `topk(5, sum by (path) (rate({app="x"}[5m])))`, + Check: func(t *testing.T, ast *LogQLScript) { + topK := ast.Head.TopK + if topK == nil || topK.Fn != "topk" || topK.Param != "5" { + t.Fatalf("expected a topk(5, ...) head, got %+v", ast.Head) + } + if topK.AggOperator == nil { + t.Errorf("expected the topk argument to be an AggOperator, got %+v", topK) + } + }, + }, + { + Name: "binary_expression", + Query: `rate({app="a"}[1m]) / rate({app="b"}[1m])`, + Check: func(t *testing.T, ast *LogQLScript) { + if !ast.IsBinary() { + t.Fatalf("expected IsBinary()==true, got BinOps=%+v", ast.BinOps) + } + if len(ast.BinOps) != 1 || ast.BinOps[0].Op != "/" { + t.Errorf("expected a single '/' binary op, got %+v", ast.BinOps) + } + }, + }, + { + Name: "line_filter_negative_regex", + Query: `{app="x"} !~ "(?i)debug"`, + Check: func(t *testing.T, ast *LogQLScript) { + sel := ast.Head.StrSelector + if sel == nil || len(sel.Pipelines) != 1 || sel.Pipelines[0].LineFilter == nil { + t.Fatalf("expected a single LineFilter pipeline stage, got %+v", ast.Head) + } + if sel.Pipelines[0].LineFilter.Fn != "!~" { + t.Errorf("expected line filter fn !~, got %q", sel.Pipelines[0].LineFilter.Fn) + } + }, + }, + { + Name: "drop_stage_multiple_labels", + Query: `{app="x"} | json | logfmt | drop __error__, __error_details__`, + Check: func(t *testing.T, ast *LogQLScript) { + sel := ast.Head.StrSelector + if sel == nil || len(sel.Pipelines) != 3 { + t.Fatalf("expected 3 pipeline stages (json, logfmt, drop), got %+v", ast.Head) + } + drop := sel.Pipelines[2].Drop + if drop == nil || len(drop.Params) != 2 { + t.Fatalf("expected a drop stage with 2 params, got %+v", sel.Pipelines[2]) + } + }, + }, + { + Name: "label_filter_or_chain", + Query: `{app="x"} | json | level="error" or level="warn"`, + Check: func(t *testing.T, ast *LogQLScript) { + sel := ast.Head.StrSelector + if sel == nil || len(sel.Pipelines) != 2 || sel.Pipelines[1].LabelFilter == nil { + t.Fatalf("expected a single LabelFilter pipeline stage after json, got %+v", ast.Head) + } + lf := sel.Pipelines[1].LabelFilter + if lf.Op != "or" || lf.Tail == nil { + t.Errorf("expected an 'or'-chained label filter with a Tail, got op=%q tail=%+v", lf.Op, lf.Tail) + } + }, + }, + { + Name: "quantile_over_time_call", + Query: `quantile_over_time(0.99, {app="x"} | json | unwrap duration_ms [5m])`, + Check: func(t *testing.T, ast *LogQLScript) { + qot := ast.Head.QuantileOverTime + if qot == nil || qot.Fn != "quantile_over_time" { + t.Fatalf("expected a QuantileOverTime head, got %+v", ast.Head) + } + }, + }, + { + Name: "rate_over_unwrap_after_parser", + Query: `rate({app="x"} | json | unwrap duration_ms [5m])`, + Check: func(t *testing.T, ast *LogQLScript) { + lra := ast.Head.LRAOrUnwrap + if lra == nil || lra.Fn != "rate" { + t.Fatalf("expected an LRAOrUnwrap head with fn rate, got %+v", ast.Head) + } + pipelines := lra.StrSel.Pipelines + if len(pipelines) != 2 || pipelines[0].Parser == nil || pipelines[1].Unwrap == nil { + t.Fatalf("expected a Parser stage followed by an Unwrap stage, got %+v", pipelines) + } + }, + }, + + // Invalid queries: only a non-nil parse error is asserted (see + // RunParserPins), spread across a representative range of syntax + // error classes. + {Name: "invalid_unclosed_brace", Query: `{app="x"`, WantErr: true}, + {Name: "invalid_trailing_operator", Query: `rate({app="x"}[1m]) /`, WantErr: true}, + {Name: "invalid_unterminated_string", Query: `{app="x} |= "error"`, WantErr: true}, + {Name: "invalid_range_duration_unit", Query: `rate({app="x"}[5x])`, WantErr: true}, + {Name: "invalid_missing_matcher_op", Query: `{app "x"}`, WantErr: true}, + {Name: "invalid_unclosed_range_call", Query: `rate({app="x"}[5m]`, WantErr: true}, + // Empty by()/without() grouping is accepted for AggOperator (see + // aggregation_sum_by/aggregation_without) but not here: LRAOrUnwrap's + // ByOrWithoutPrefix production requires a non-empty label list. + {Name: "invalid_empty_by_prefix", Query: `max by () (count_over_time({app="x"}[5m]))`, WantErr: true}, + // unwrap only accepts a bare label, never a conversion-function call + // wrapping one (contrast unwrap_both_spellings_equivalent's `unwrap bytes`). + {Name: "invalid_unwrap_conversion_func_call", Query: `rate({app="x"} | logfmt | unwrap duration(duration) [5m])`, WantErr: true}, + }) +} diff --git a/reader/promql/promql_parser/fuzz_test.go b/reader/promql/promql_parser/fuzz_test.go new file mode 100644 index 000000000..b541324f5 --- /dev/null +++ b/reader/promql/promql_parser/fuzz_test.go @@ -0,0 +1,159 @@ +package promql_parser + +import "testing" + +// FuzzParse asserts that Parse never panics on arbitrary input. It makes no +// claim about output shape or correctness. +// +// Not part of the default test/CI lane: native Go fuzz targets only run +// their seed corpus under plain `go test`, and are otherwise driven locally +// via `make fuzz HEAD=promql DURATION=` (or `go test -fuzz=FuzzParse`). +func FuzzParse(f *testing.F) { + for _, seed := range []string{ + `http_requests_total`, + `http_requests_total{status="5xx"}`, + `rate(http_requests_total{status="5xx"}[5m])`, + `increase(http_requests_total[1h])`, + `sum(rate(http_requests_total[5m])) by (status)`, + `sum without (instance) (rate(http_requests_total[5m]))`, + `avg(node_cpu_seconds_total) by (cpu) > 0.5`, + `topk(5, sum(rate(http_requests_total[5m])) by (path))`, + `histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))`, + `(node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes) / node_memory_MemTotal_bytes`, + + // The rest of this seed corpus is drawn from the prometheus/compliance + // project's query set (github.com/prometheus/compliance, promql + // subdirectory) — a broader spread of PromQL grammar (vector-matching + // modifiers, date/math functions, label_replace/label_join, special + // values, subqueries) than the hand-written seeds above cover alone. + `42`, + `1.234`, + `.123`, + `1.23e-3`, + `0x3d`, + `Inf`, + `+Inf`, + `-Inf`, + `NaN`, + `demo_memory_usage_bytes`, + `{__name__="demo_memory_usage_bytes"}`, + `demo_memory_usage_bytes{type="free"}`, + `demo_memory_usage_bytes{type!="free"}`, + `demo_memory_usage_bytes{instance=~"demo.promlabs.com:.*"}`, + `demo_memory_usage_bytes{instance=~"host"}`, + `demo_memory_usage_bytes{instance!~".*:10000"}`, + `demo_memory_usage_bytes{type="free", instance!="demo.promlabs.com:10000"}`, + `{type="free", instance!="demo.promlabs.com:10000"}`, + `{__name__=~".*"}`, + `nonexistent_metric_name`, + `demo_memory_usage_bytes offset 1m`, + `demo_memory_usage_bytes offset -5m`, + `demo_intermittent_metric`, + `sum(demo_memory_usage_bytes)`, + `avg(nonexistent_metric_name)`, + `max by() (demo_memory_usage_bytes)`, + `min by(instance) (demo_memory_usage_bytes)`, + `count by(instance, type) (demo_memory_usage_bytes)`, + `stddev by(nonexistent) (demo_memory_usage_bytes)`, + `stdvar without() (demo_memory_usage_bytes)`, + `sum without(instance) (demo_memory_usage_bytes)`, + `avg without(instance, type) (demo_memory_usage_bytes)`, + `max without(nonexistent) (demo_memory_usage_bytes)`, + `topk (3, demo_memory_usage_bytes)`, + `bottomk by(instance) (2, demo_memory_usage_bytes)`, + `topk without(instance) (2, demo_memory_usage_bytes)`, + `bottomk without() (2, demo_memory_usage_bytes)`, + `quantile(-0.5, demo_memory_usage_bytes)`, + `avg(max by(type) (demo_memory_usage_bytes))`, + `1 * 2 + 4 / 6 - 10 % 2 ^ 2`, + `demo_num_cpus + (1 == bool 2)`, + `demo_memory_usage_bytes + 1.2345`, + `demo_memory_usage_bytes != bool 1.2345`, + `1.2345 < bool demo_memory_usage_bytes`, + `0.12345 - demo_memory_usage_bytes`, + `(1 * 2 + 4 / 6 - (10%7)^2) * demo_memory_usage_bytes`, + `demo_memory_usage_bytes / (1 * 2 + 4 / 6 - 10)`, + `timestamp(demo_memory_usage_bytes * 1)`, + `timestamp(-demo_memory_usage_bytes)`, + `demo_memory_usage_bytes % on(instance, job, type) demo_memory_usage_bytes`, + `sum by(instance, type) (demo_memory_usage_bytes) ^ on(instance, type) group_left(job) demo_memory_usage_bytes`, + `demo_memory_usage_bytes > bool on(instance, job, type) demo_memory_usage_bytes`, + `demo_memory_usage_bytes / on(instance, job, type, __name__) demo_memory_usage_bytes`, + `sum without(job) (demo_memory_usage_bytes) / on(instance, type) demo_memory_usage_bytes`, + `sum without(job) (demo_memory_usage_bytes) / on(instance, type) group_left demo_memory_usage_bytes`, + `sum without(job) (demo_memory_usage_bytes) / on(instance, type) group_left(job) demo_memory_usage_bytes`, + `demo_memory_usage_bytes / on(instance, job) group_left demo_num_cpus`, + `demo_memory_usage_bytes / on(instance, type, job, non_existent) demo_memory_usage_bytes`, + `demo_num_cpus * Inf`, + `demo_num_cpus * -Inf`, + `demo_num_cpus * NaN`, + `demo_memory_usage_bytes + -(1)`, + `-demo_memory_usage_bytes`, + `-1 ^ 2`, + `1 + time()`, + `time() - 1`, + `time() <= bool 1`, + `1 >= bool time()`, + `time() * time()`, + `time() == bool time()`, + `time() == demo_memory_usage_bytes`, + `demo_memory_usage_bytes != time()`, + `sum_over_time(demo_memory_usage_bytes[1s])`, + `quantile_over_time(0.1, demo_memory_usage_bytes[15s])`, + `timestamp(demo_num_cpus)`, + `timestamp(timestamp(demo_num_cpus))`, + `abs(demo_memory_usage_bytes)`, + `ceil(-demo_memory_usage_bytes)`, + `delta(nonexistent_metric[5m])`, + `rate(demo_cpu_usage_seconds_total[1m])`, + `deriv(demo_disk_usage_bytes[5m])`, + `predict_linear(demo_disk_usage_bytes[15m], 600)`, + `time()`, + `label_replace(demo_num_cpus, "job", "destination-value-$1", "instance", "demo.promlabs.com:(.*)")`, + `label_replace(demo_num_cpus, "job", "destination-value-$1", "instance", "host:(.*)")`, + `label_replace(demo_num_cpus, "job", "$1-$2", "instance", "local(.*):(.*)")`, + `label_replace(demo_num_cpus, "job", "value-$1", "nonexistent-src", "source-value-(.*)")`, + `label_replace(demo_num_cpus, "job", "value-$1", "nonexistent-src", "(.*)")`, + `label_replace(demo_num_cpus, "job", "value-$1", "instance", "non-matching-regex")`, + `label_replace(demo_num_cpus, "job", "", "dst", ".*")`, + `label_replace(demo_num_cpus, "job", "value-$1", "src", "(.*")`, + `label_replace(demo_num_cpus, "~invalid", "", "src", "(.*)")`, + `label_replace(demo_num_cpus, "instance", "", "", "")`, + `label_join(demo_num_cpus, "new_label", "-", "instance", "job")`, + `label_join(demo_num_cpus, "job", "-", "instance", "job")`, + `label_join(demo_num_cpus, "job", "-", "instance")`, + `label_join(demo_num_cpus, "~invalid", "-", "instance")`, + `day_of_month()`, + `day_of_week(demo_batch_last_success_timestamp_seconds offset 10m)`, + `idelta(demo_cpu_usage_seconds_total[1h])`, + `clamp_min(demo_memory_usage_bytes, 2)`, + `clamp(demo_memory_usage_bytes, 0, 1)`, + `clamp(demo_memory_usage_bytes, 0, 1000000000000)`, + `clamp(demo_memory_usage_bytes, 1000000000000, 0)`, + `clamp(demo_memory_usage_bytes, 1000000000000, 1000000000000)`, + `resets(demo_cpu_usage_seconds_total[1s])`, + `changes(demo_batch_last_success_timestamp_seconds[15s])`, + `vector(1.23)`, + `vector(time())`, + `histogram_quantile(0.5, rate(demo_api_request_duration_seconds_bucket[1m]))`, + `histogram_quantile(0.9, nonexistent_metric)`, + `histogram_quantile(0.9, demo_memory_usage_bytes)`, + `histogram_quantile(0.9, {__name__=~"demo_api_request_duration_seconds_.+"})`, + `count_values("value", demo_api_request_duration_seconds_bucket)`, + `absent(demo_memory_usage_bytes)`, + `absent(nonexistent_metric_name)`, + `max_over_time((time() - max(demo_batch_last_success_timestamp_seconds) < 1000)[5m:10s] offset 5m)`, + `avg_over_time(rate(demo_cpu_usage_seconds_total[1m])[2m:10s])`, + } { + f.Add(seed) + } + + f.Fuzz(func(t *testing.T, query string) { + defer func() { + if r := recover(); r != nil { + t.Fatalf("Parse panicked on %q: %v", query, r) + } + }() + _, _ = Parse(query) + }) +} diff --git a/reader/promql/promql_parser/nodes.go b/reader/promql/promql_parser/nodes.go index c32f1357a..bb9710a12 100644 --- a/reader/promql/promql_parser/nodes.go +++ b/reader/promql/promql_parser/nodes.go @@ -1,14 +1,25 @@ package promql_parser import ( + "fmt" + "github.com/metrico/qryn/v5/reader/logql/logql_transpiler/shared" "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/promql/parser" ) type Expr struct { - Expr parser.Expr - Substitutes map[string]*Substitute + Expr parser.Expr + Substitutes map[string]*Substitute + substCounter int64 +} + +// NextSubstituteName returns a fresh, deterministic pushdown-substitute metric +// name for this transpile. It replaces a random suffix so the SQL a query +// lowers to is reproducible across runs (see TestTranspileIsDeterministic). +func (e *Expr) NextSubstituteName() string { + e.substCounter++ + return fmt.Sprintf("__metric_subst__%d", e.substCounter) } type Substitute struct { diff --git a/reader/promql/promql_parser/parserpin_test.go b/reader/promql/promql_parser/parserpin_test.go new file mode 100644 index 000000000..4468618a1 --- /dev/null +++ b/reader/promql/promql_parser/parserpin_test.go @@ -0,0 +1,425 @@ +package promql_parser + +import ( + "testing" + + "github.com/metrico/qryn/v5/reader/internal/parserpin" + "github.com/prometheus/prometheus/model/labels" + "github.com/prometheus/prometheus/promql/parser" +) + +// TestParserPins pins the PromQL parser's AST shape for a representative +// spread of valid query shapes, and its error behavior for a representative +// spread of invalid ones. See reader/internal/parserpin/parserpin.go for +// what RunParserPins asserts generically (non-nil root / non-nil error); the +// Check callbacks here go further for the cases where a deeper shape pin is +// worth the assertion. +func TestParserPins(t *testing.T) { + parserpin.RunParserPins(t, Parse, []parserpin.ParserPinCase[*Expr]{ + { + Name: "bare_selector", + Query: `http_requests_total`, + Check: func(t *testing.T, ast *Expr) { + vs, ok := ast.Expr.(*parser.VectorSelector) + if !ok { + t.Fatalf("expected *parser.VectorSelector, got %T", ast.Expr) + } + if vs.Name != "http_requests_total" { + t.Errorf("expected metric name %q, got %q", "http_requests_total", vs.Name) + } + }, + }, + { + Name: "selector_with_matchers", + Query: `http_requests_total{job="api",method!="GET"}`, + Check: func(t *testing.T, ast *Expr) { + vs, ok := ast.Expr.(*parser.VectorSelector) + if !ok { + t.Fatalf("expected *parser.VectorSelector, got %T", ast.Expr) + } + // __name__ plus the two explicit matchers. + if len(vs.LabelMatchers) != 3 { + t.Errorf("expected 3 label matchers (incl. __name__), got %d", len(vs.LabelMatchers)) + } + }, + }, + { + Name: "selector_with_regex_matcher", + Query: `http_requests_total{job=~"api.*"}`, + Check: func(t *testing.T, ast *Expr) { + vs, ok := ast.Expr.(*parser.VectorSelector) + if !ok { + t.Fatalf("expected *parser.VectorSelector, got %T", ast.Expr) + } + found := false + for _, m := range vs.LabelMatchers { + if m.Name == "job" && m.Type == labels.MatchRegexp { + found = true + } + } + if !found { + t.Errorf("expected a regex matcher on job, got %v", vs.LabelMatchers) + } + }, + }, + { + Name: "range_vector_selector", + Query: `http_requests_total[5m]`, + Check: func(t *testing.T, ast *Expr) { + ms, ok := ast.Expr.(*parser.MatrixSelector) + if !ok { + t.Fatalf("expected *parser.MatrixSelector, got %T", ast.Expr) + } + if ms.Range.String() != "5m0s" { + t.Errorf("expected range 5m0s, got %s", ms.Range) + } + }, + }, + { + Name: "range_function_call", + Query: `rate(http_requests_total[5m])`, + Check: func(t *testing.T, ast *Expr) { + call, ok := ast.Expr.(*parser.Call) + if !ok { + t.Fatalf("expected *parser.Call, got %T", ast.Expr) + } + if call.Func.Name != "rate" { + t.Errorf("expected func name rate, got %s", call.Func.Name) + } + }, + }, + { + Name: "nested_function_calls", + Query: `histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))`, + Check: func(t *testing.T, ast *Expr) { + call, ok := ast.Expr.(*parser.Call) + if !ok { + t.Fatalf("expected *parser.Call, got %T", ast.Expr) + } + if call.Func.Name != "histogram_quantile" { + t.Errorf("expected func name histogram_quantile, got %s", call.Func.Name) + } + if len(call.Args) != 2 { + t.Fatalf("expected 2 args, got %d", len(call.Args)) + } + if _, ok := call.Args[1].(*parser.Call); !ok { + t.Errorf("expected second arg to be a nested *parser.Call, got %T", call.Args[1]) + } + }, + }, + { + Name: "aggregation_by", + Query: `sum by (job) (http_requests_total)`, + Check: func(t *testing.T, ast *Expr) { + agg, ok := ast.Expr.(*parser.AggregateExpr) + if !ok { + t.Fatalf("expected *parser.AggregateExpr, got %T", ast.Expr) + } + if agg.Without { + t.Errorf("expected 'by' grouping, got 'without'") + } + if len(agg.Grouping) != 1 || agg.Grouping[0] != "job" { + t.Errorf("expected grouping [job], got %v", agg.Grouping) + } + }, + }, + { + Name: "aggregation_without", + Query: `sum without (instance) (http_requests_total)`, + Check: func(t *testing.T, ast *Expr) { + agg, ok := ast.Expr.(*parser.AggregateExpr) + if !ok { + t.Fatalf("expected *parser.AggregateExpr, got %T", ast.Expr) + } + if !agg.Without { + t.Errorf("expected 'without' grouping, got 'by'") + } + }, + }, + { + Name: "aggregation_with_param", + Query: `topk(5, http_requests_total)`, + Check: func(t *testing.T, ast *Expr) { + agg, ok := ast.Expr.(*parser.AggregateExpr) + if !ok { + t.Fatalf("expected *parser.AggregateExpr, got %T", ast.Expr) + } + if agg.Op != parser.TOPK { + t.Errorf("expected op TOPK, got %s", agg.Op) + } + if agg.Param == nil { + t.Errorf("expected a non-nil Param (k)") + } + }, + }, + { + Name: "binary_expression", + Query: `http_requests_total{job="a"} / http_requests_total{job="b"}`, + Check: func(t *testing.T, ast *Expr) { + bin, ok := ast.Expr.(*parser.BinaryExpr) + if !ok { + t.Fatalf("expected *parser.BinaryExpr, got %T", ast.Expr) + } + if bin.Op != parser.DIV { + t.Errorf("expected op DIV, got %s", bin.Op) + } + }, + }, + { + Name: "binary_bool_comparison", + Query: `up{job="api"} == bool 1`, + Check: func(t *testing.T, ast *Expr) { + bin, ok := ast.Expr.(*parser.BinaryExpr) + if !ok { + t.Fatalf("expected *parser.BinaryExpr, got %T", ast.Expr) + } + if bin.ReturnBool != true { + t.Errorf("expected ReturnBool=true for 'bool' modifier") + } + }, + }, + { + Name: "offset_modifier", + Query: `http_requests_total offset 5m`, + Check: func(t *testing.T, ast *Expr) { + vs, ok := ast.Expr.(*parser.VectorSelector) + if !ok { + t.Fatalf("expected *parser.VectorSelector, got %T", ast.Expr) + } + if vs.OriginalOffset.String() != "5m0s" { + t.Errorf("expected offset 5m0s, got %s", vs.OriginalOffset) + } + }, + }, + { + Name: "subquery", + Query: `rate(http_requests_total[5m])[30m:1m]`, + Check: func(t *testing.T, ast *Expr) { + sq, ok := ast.Expr.(*parser.SubqueryExpr) + if !ok { + t.Fatalf("expected *parser.SubqueryExpr, got %T", ast.Expr) + } + if sq.Range.String() != "30m0s" { + t.Errorf("expected subquery range 30m0s, got %s", sq.Range) + } + }, + }, + { + Name: "unary_expression", + Query: `-(http_requests_total)`, + Check: func(t *testing.T, ast *Expr) { + if _, ok := ast.Expr.(*parser.UnaryExpr); !ok { + t.Fatalf("expected *parser.UnaryExpr, got %T", ast.Expr) + } + }, + }, + { + Name: "label_replace_call", + Query: `label_replace(http_requests_total, "job", "$1-$2", "instance", "local(.*):(.*)")`, + Check: func(t *testing.T, ast *Expr) { + call, ok := ast.Expr.(*parser.Call) + if !ok { + t.Fatalf("expected *parser.Call, got %T", ast.Expr) + } + if call.Func.Name != "label_replace" { + t.Errorf("expected func name label_replace, got %s", call.Func.Name) + } + if len(call.Args) != 5 { + t.Fatalf("expected 5 args, got %d", len(call.Args)) + } + }, + }, + { + Name: "label_join_call", + Query: `label_join(http_requests_total, "job", "-", "instance")`, + Check: func(t *testing.T, ast *Expr) { + call, ok := ast.Expr.(*parser.Call) + if !ok { + t.Fatalf("expected *parser.Call, got %T", ast.Expr) + } + if call.Func.Name != "label_join" { + t.Errorf("expected func name label_join, got %s", call.Func.Name) + } + }, + }, + { + // Distinct from "nested_function_calls": the second arg is a bare + // selector, not a nested Call, so histogram_quantile's arg shape + // isn't always "instant-vector-producing function call". + Name: "histogram_quantile_over_bare_selector", + Query: `histogram_quantile(0.9, http_requests_total)`, + Check: func(t *testing.T, ast *Expr) { + call, ok := ast.Expr.(*parser.Call) + if !ok { + t.Fatalf("expected *parser.Call, got %T", ast.Expr) + } + if _, ok := call.Args[0].(*parser.NumberLiteral); !ok { + t.Errorf("expected first arg to be a *parser.NumberLiteral, got %T", call.Args[0]) + } + if _, ok := call.Args[1].(*parser.VectorSelector); !ok { + t.Errorf("expected second arg to be a *parser.VectorSelector, got %T", call.Args[1]) + } + }, + }, + { + Name: "zero_arg_call", + Query: `time()`, + Check: func(t *testing.T, ast *Expr) { + call, ok := ast.Expr.(*parser.Call) + if !ok { + t.Fatalf("expected *parser.Call, got %T", ast.Expr) + } + if call.Func.Name != "time" { + t.Errorf("expected func name time, got %s", call.Func.Name) + } + if len(call.Args) != 0 { + t.Errorf("expected 0 args, got %d", len(call.Args)) + } + }, + }, + { + Name: "scalar_bool_comparison_against_call", + Query: `1 >= bool time()`, + Check: func(t *testing.T, ast *Expr) { + bin, ok := ast.Expr.(*parser.BinaryExpr) + if !ok { + t.Fatalf("expected *parser.BinaryExpr, got %T", ast.Expr) + } + if bin.Op != parser.GTE { + t.Errorf("expected op GTE, got %s", bin.Op) + } + if !bin.ReturnBool { + t.Errorf("expected ReturnBool=true for 'bool' modifier") + } + if _, ok := bin.LHS.(*parser.NumberLiteral); !ok { + t.Errorf("expected LHS to be a *parser.NumberLiteral, got %T", bin.LHS) + } + }, + }, + { + // Power binds tighter than unary minus: the top node is the + // negation, wrapping the exponentiation, not the reverse. + Name: "unary_minus_binds_looser_than_power", + Query: `-1 ^ 2`, + Check: func(t *testing.T, ast *Expr) { + un, ok := ast.Expr.(*parser.UnaryExpr) + if !ok { + t.Fatalf("expected *parser.UnaryExpr, got %T", ast.Expr) + } + if _, ok := un.Expr.(*parser.BinaryExpr); !ok { + t.Errorf("expected the unary's inner expr to be a *parser.BinaryExpr (the ^), got %T", un.Expr) + } + }, + }, + { + Name: "aggregation_without_multiple_labels", + Query: `avg without (instance, type) (http_requests_total)`, + Check: func(t *testing.T, ast *Expr) { + agg, ok := ast.Expr.(*parser.AggregateExpr) + if !ok { + t.Fatalf("expected *parser.AggregateExpr, got %T", ast.Expr) + } + if len(agg.Grouping) != 2 { + t.Errorf("expected 2 grouping labels, got %v", agg.Grouping) + } + }, + }, + { + Name: "topk_bottomk_empty_without", + Query: `bottomk without () (2, http_requests_total)`, + Check: func(t *testing.T, ast *Expr) { + agg, ok := ast.Expr.(*parser.AggregateExpr) + if !ok { + t.Fatalf("expected *parser.AggregateExpr, got %T", ast.Expr) + } + if agg.Op != parser.BOTTOMK { + t.Errorf("expected op BOTTOMK, got %s", agg.Op) + } + if !agg.Without || len(agg.Grouping) != 0 { + t.Errorf("expected empty 'without' grouping, got without=%v grouping=%v", agg.Without, agg.Grouping) + } + if agg.Param == nil { + t.Errorf("expected a non-nil Param (k)") + } + }, + }, + { + Name: "quantile_aggregation", + Query: `quantile(0.9, http_requests_total)`, + Check: func(t *testing.T, ast *Expr) { + agg, ok := ast.Expr.(*parser.AggregateExpr) + if !ok { + t.Fatalf("expected *parser.AggregateExpr, got %T", ast.Expr) + } + if agg.Op != parser.QUANTILE { + t.Errorf("expected op QUANTILE, got %s", agg.Op) + } + if agg.Param == nil { + t.Errorf("expected a non-nil Param (the quantile)") + } + }, + }, + { + Name: "unary_expr_as_call_arg", + Query: `ceil(-http_requests_total)`, + Check: func(t *testing.T, ast *Expr) { + call, ok := ast.Expr.(*parser.Call) + if !ok { + t.Fatalf("expected *parser.Call, got %T", ast.Expr) + } + if _, ok := call.Args[0].(*parser.UnaryExpr); !ok { + t.Errorf("expected the arg to be a *parser.UnaryExpr, got %T", call.Args[0]) + } + }, + }, + { + Name: "vector_not_equal_call", + Query: `http_requests_total != time()`, + Check: func(t *testing.T, ast *Expr) { + bin, ok := ast.Expr.(*parser.BinaryExpr) + if !ok { + t.Fatalf("expected *parser.BinaryExpr, got %T", ast.Expr) + } + if bin.Op != parser.NEQ { + t.Errorf("expected op NEQ, got %s", bin.Op) + } + if _, ok := bin.RHS.(*parser.Call); !ok { + t.Errorf("expected RHS to be a *parser.Call, got %T", bin.RHS) + } + }, + }, + { + // The RHS is parenthesized, so the binary's RHS operand is the + // *parser.ParenExpr itself, not the bool-comparison it wraps. + Name: "binary_with_parenthesized_bool_comparison_operand", + Query: `http_requests_total + (1 == bool 2)`, + Check: func(t *testing.T, ast *Expr) { + bin, ok := ast.Expr.(*parser.BinaryExpr) + if !ok { + t.Fatalf("expected *parser.BinaryExpr, got %T", ast.Expr) + } + paren, ok := bin.RHS.(*parser.ParenExpr) + if !ok { + t.Fatalf("expected RHS to be a *parser.ParenExpr, got %T", bin.RHS) + } + if _, ok := paren.Expr.(*parser.BinaryExpr); !ok { + t.Errorf("expected the paren's inner expr to be a *parser.BinaryExpr, got %T", paren.Expr) + } + }, + }, + + // Invalid queries: only a non-nil parse error is asserted (see + // RunParserPins), spread across a representative range of syntax + // error classes. + {Name: "invalid_unclosed_brace", Query: `http_requests_total{job="api"`, WantErr: true}, + {Name: "invalid_trailing_operator", Query: `http_requests_total +`, WantErr: true}, + {Name: "invalid_unterminated_string", Query: `http_requests_total{job="api}`, WantErr: true}, + {Name: "invalid_range_duration", Query: `rate(http_requests_total[5x])`, WantErr: true}, + {Name: "invalid_aggregation_syntax", Query: `sum(by (job) http_requests_total)`, WantErr: true}, + {Name: "invalid_unclosed_call", Query: `rate(http_requests_total[5m]`, WantErr: true}, + // A selector where every matcher (here the only one, __name__) can + // match the empty string is rejected: PromQL requires at least one + // non-empty-matching matcher, or the selector would match everything. + {Name: "invalid_selector_all_matchers_match_empty", Query: `{__name__=~".*"}`, WantErr: true}, + }) +} diff --git a/reader/promql/promql_transpiler/determinism_test.go b/reader/promql/promql_transpiler/determinism_test.go new file mode 100644 index 000000000..cda5d0bbb --- /dev/null +++ b/reader/promql/promql_transpiler/determinism_test.go @@ -0,0 +1,36 @@ +package promql_transpiler + +import ( + "testing" + + "github.com/metrico/qryn/v5/reader/promql/promql_parser" +) + +// TestTranspileIsDeterministic guards the rand.Int63() -> per-transpile-counter +// fix for pushdown-substitute naming: two independent Parse+TranspileExpressionV2 +// passes over the same query must assign identical substitute names, so the +// residual expression handed to the embedded engine is byte-identical across +// runs. Before the fix, each pass drew a fresh random name, so this failed +// intermittently. +func TestTranspileIsDeterministic(t *testing.T) { + const query = `sum by (job) (rate(http_requests_total{job="myjob"}[5m]))` + + transpile := func() string { + t.Helper() + expr, err := promql_parser.Parse(query) + if err != nil { + t.Fatal(err) + } + expr, err = TranspileExpressionV2(expr) + if err != nil { + t.Fatal(err) + } + return expr.Expr.String() + } + + first := transpile() + second := transpile() + if first != second { + t.Fatalf("transpile is not deterministic:\n first: %s\nsecond: %s", first, second) + } +} diff --git a/reader/promql/promql_transpiler/optimizer/vector_agg.go b/reader/promql/promql_transpiler/optimizer/vector_agg.go index d10b2487d..e45b93d7e 100644 --- a/reader/promql/promql_transpiler/optimizer/vector_agg.go +++ b/reader/promql/promql_transpiler/optimizer/vector_agg.go @@ -1,9 +1,6 @@ package optimizer import ( - "fmt" - "math/rand/v2" - "github.com/metrico/qryn/v5/reader/promql/promql_parser" "github.com/metrico/qryn/v5/reader/promql/promql_transpiler/planner" prom_parser "github.com/prometheus/prometheus/promql/parser" @@ -82,7 +79,7 @@ func (v *Aggregate) aggregate(fn string) prom_parser.Expr { p.Main = planner.NewInstantVectorPlanner(&fp) } - metricName := fmt.Sprintf("__metric_subst__%d", rand.Int64()) + metricName := v.gExpr.NextSubstituteName() v.gExpr.Substitutes[metricName] = &promql_parser.Substitute{ MetricName: metricName, Node: v.expr, diff --git a/reader/promql/promql_transpiler/optimizer/vector_range.go b/reader/promql/promql_transpiler/optimizer/vector_range.go index b1bbe5c57..67bfd2820 100644 --- a/reader/promql/promql_transpiler/optimizer/vector_range.go +++ b/reader/promql/promql_transpiler/optimizer/vector_range.go @@ -1,8 +1,6 @@ package optimizer import ( - "fmt" - "math/rand/v2" "time" "github.com/metrico/qryn/v5/reader/logql/logql_transpiler/clickhouse_planner" @@ -104,7 +102,7 @@ func (v *VectorRange) fpPlanner() shared.SQLRequestPlanner { // substitute swaps the call out for a synthetic vector selector and registers // the planner that produces it. func (v *VectorRange) substitute(p shared.SQLRequestPlanner) prom_parser.Expr { - metricName := fmt.Sprintf("__metric_subst__%d", rand.Int64()) + metricName := v.gExpr.NextSubstituteName() v.gExpr.Substitutes[metricName] = &promql_parser.Substitute{ MetricName: metricName, Node: v.expr, diff --git a/reader/traceql/traceql_parser/fuzz_test.go b/reader/traceql/traceql_parser/fuzz_test.go new file mode 100644 index 000000000..ba23db420 --- /dev/null +++ b/reader/traceql/traceql_parser/fuzz_test.go @@ -0,0 +1,106 @@ +package traceql_parser + +import "testing" + +// FuzzParse asserts that Parse never panics on arbitrary input. It makes no +// claim about output shape or correctness. +// +// Not part of the default test/CI lane: native Go fuzz targets only run +// their seed corpus under plain `go test`, and are otherwise driven locally +// via `make fuzz HEAD=traceql DURATION=` (or `go test -fuzz=FuzzParse`). +func FuzzParse(f *testing.F) { + for _, seed := range []string{ + `{.service.name="test"}`, + `{.randomContainer=~"admiring" && .randomFloat > 10}`, + `{.randomContainer=~"admiring" && .randomFloat > 10} | count() > 2 || {.randomContainer=~"boring" && .randomFloat < 10}`, + `{duration > 100ms}`, + `{name="GET /api"}`, + `{status = error}`, + `{span.http.method="GET" && resource.service.name="frontend"}`, + `{} >> {name="child"}`, + `{.foo="bar"} | avg(duration) > 100ms`, + `{.foo=~"bar.*"}`, + + // The rest of this seed corpus is adapted from a TraceQL compatibility + // smoke suite (query strings only, no fixture/expectation metadata) — + // a broader spread of TraceQL grammar (structural operators, metrics + // pipelines with by(), nil comparisons, colon-form intrinsics, + // attribute-to-attribute comparisons) than the hand-written seeds + // above cover alone. Several exercise constructs this parser + // currently rejects (see the *_not_supported parser pins) — useful + // fuzz input either way, since FuzzParse only asserts no panic. + `{ resource.service.name = "checkout" }`, + `{ resource.service.name != "checkout" }`, + `{ resource.service.name =~ "ship.*" }`, + `{ resource.service.name =~ "check" }`, + `{ resource.deployment.env = "compat-test" }`, + `{ span.http.method = "GET" }`, + `{ .name = "attr-name-collision-sentinel" }`, + `{ duration > 100ms }`, + `{ duration < 300ms }`, + `{ kind = server }`, + `{ status = error }`, + `{ resource.service.name = "payments" } > { kind = consumer }`, + `{ kind = consumer } < { resource.service.name = "payments" }`, + `{ resource.service.name = "checkout" } >> { kind = client }`, + `{ kind = client } << { resource.service.name = "checkout" }`, + `{ resource.service.name = "checkout" && status = error }`, + `{ resource.service.name = "checkout" } || { resource.service.name = "payments" }`, + `{ kind = server } || { kind = internal }`, + `{ resource.service.name =~ ".+" } | count() > 0`, + `{ status = ok } | avg(duration) > 0`, + `{ status = error } | count() > 0`, + `{ resource.service.name = "checkout" && span.http.method = "GET" } && { span.child.index = "0" }`, + `{ resource.service.name = "payments" }`, + `{ resource.service.name = "checkout" } | select(nestedSetParent, nestedSetLeft, nestedSetRight)`, + `({ nestedSetParent < 0 } &>> { kind = server }) || ({ nestedSetParent < 0 }) | select(status, resource.service.name, name, nestedSetParent, nestedSetLeft, nestedSetRight)`, + `{ } | rate()`, + `{ } | count_over_time() by (resource.service.name)`, + `{ } | compare({ status = error }, 500)`, + `{ } | quantile_over_time(duration, 0.95)`, + `{ } | histogram_over_time(duration)`, + `{ } | count_over_time()`, + `{ } | avg_over_time(duration)`, + `{ }`, + `{{{`, + `{ span.http.method = "GET" && resource.cluster = }`, + `{ span.child.index = "0" }`, + `{ resource.service.name = "checkout" && resource.cluster = }`, + `{ kind != nil }`, + `{ kind != nil && span.child.index = "0" && span.kind = "SPAN_KIND_UNSPECIFIED" }`, + `{ status != nil }`, + `{ name != nil }`, + `{ span.http.method = nil }`, + `{ resource.deployment.env != nil }`, + `{nestedSetParent<0 && true && kind != nil} | rate() by(kind)`, + `{ kind != nil } | rate() by(kind)`, + `{ trace:rootService = "checkout" }`, + `{ trace:rootName =~ "GET /api/.*" }`, + `{ trace:duration > 100ms }`, + `{ !(kind = client) }`, + `{ span:kind = server }`, + `{ span:name =~ "GET /api/.*" }`, + `{ span:duration > 100ms }`, + `{ span:status = error }`, + `{ span:id != nil }`, + `{ span:parentID != nil }`, + `{ instrumentation:version = "1" }`, + `{ event:name = "whatever" }`, + `{ link:traceID != nil }`, + `{ ("foo" != "bar") && !("foo" = "bar") }`, + `{ span.child.index = resource.deployment.env }`, + `{ duration > span.budget_ns }`, + `{ name > 3 }`, + } { + f.Add(seed) + } + + f.Fuzz(func(t *testing.T, query string) { + defer func() { + if r := recover(); r != nil { + t.Fatalf("Parse panicked on %q: %v", query, r) + } + }() + _, _ = Parse(query) + }) +} diff --git a/reader/traceql/traceql_parser/parserpin_test.go b/reader/traceql/traceql_parser/parserpin_test.go new file mode 100644 index 000000000..8c7344dbb --- /dev/null +++ b/reader/traceql/traceql_parser/parserpin_test.go @@ -0,0 +1,320 @@ +package traceql_parser + +import ( + "testing" + + "github.com/metrico/qryn/v5/reader/internal/parserpin" +) + +// TestParserPins pins the TraceQL parser's AST shape for representative +// valid queries, and pins that a representative set of malformed queries +// fail to parse. See reader/traceql/traceql_parser/fuzz_test.go for the +// complementary "never panics" fuzz target. +func TestParserPins(t *testing.T) { + parserpin.RunParserPins(t, Parse, []parserpin.ParserPinCase[*TraceQLScript]{ + { + Name: "dot_attribute_selector", + Query: `{.http.method="GET"}`, + Check: func(t *testing.T, ast *TraceQLScript) { + head := ast.Head.AttrSelector.Head + if head == nil { + t.Fatalf("expected a non-nil attribute selector head") + } + if head.Label != ".http.method" { + t.Errorf("Label = %q, want %q", head.Label, ".http.method") + } + if head.Op != "=" { + t.Errorf("Op = %q, want %q", head.Op, "=") + } + if head.Val.StrVal == nil || head.Val.StrVal.Str != `"GET"` { + t.Errorf("Val.StrVal = %+v, want \"GET\"", head.Val.StrVal) + } + }, + }, + { + Name: "span_prefixed_numeric", + Query: `{span.http.status_code=200}`, + Check: func(t *testing.T, ast *TraceQLScript) { + head := ast.Head.AttrSelector.Head + if head == nil { + t.Fatalf("expected a non-nil attribute selector head") + } + if head.Label != "span.http.status_code" { + t.Errorf("Label = %q, want %q", head.Label, "span.http.status_code") + } + if head.Val.FVal != "200" { + t.Errorf("Val.FVal = %q, want %q", head.Val.FVal, "200") + } + }, + }, + { + Name: "intrinsic_duration_comparison", + Query: `{duration>100ms}`, + Check: func(t *testing.T, ast *TraceQLScript) { + head := ast.Head.AttrSelector.Head + if head == nil { + t.Fatalf("expected a non-nil attribute selector head") + } + if head.Label != "duration" { + t.Errorf("Label = %q, want %q", head.Label, "duration") + } + if head.Op != ">" { + t.Errorf("Op = %q, want %q", head.Op, ">") + } + if head.Val.TimeVal != "100ms" { + t.Errorf("Val.TimeVal = %q, want %q", head.Val.TimeVal, "100ms") + } + }, + }, + { + Name: "conjunction_inside_selector", + Query: `{.a="x" && .b="y"}`, + Check: func(t *testing.T, ast *TraceQLScript) { + exp := ast.Head.AttrSelector + if exp.AndOr != "&&" { + t.Errorf("AndOr = %q, want %q", exp.AndOr, "&&") + } + if exp.Tail == nil || exp.Tail.Head == nil || exp.Tail.Head.Label != ".b" { + t.Errorf("Tail head label = %+v, want .b", exp.Tail) + } + }, + }, + { + Name: "disjunction_inside_selector", + Query: `{.a="x" || .b="y"}`, + Check: func(t *testing.T, ast *TraceQLScript) { + exp := ast.Head.AttrSelector + if exp.AndOr != "||" { + t.Errorf("AndOr = %q, want %q", exp.AndOr, "||") + } + }, + }, + { + Name: "pipeline_aggregator", + Query: `{.a="x"} | count() > 2`, + Check: func(t *testing.T, ast *TraceQLScript) { + agg := ast.Head.Aggregator + if agg == nil { + t.Fatalf("expected a non-nil aggregator") + } + if agg.Fn != "count" { + t.Errorf("Fn = %q, want %q", agg.Fn, "count") + } + if agg.Cmp != ">" { + t.Errorf("Cmp = %q, want %q", agg.Cmp, ">") + } + if agg.Num != "2" { + t.Errorf("Num = %q, want %q", agg.Num, "2") + } + }, + }, + { + Name: "script_level_and", + Query: `{.a="x"} && {.b="y"}`, + Check: func(t *testing.T, ast *TraceQLScript) { + if ast.Op != "&&" { + t.Errorf("Op = %q, want %q", ast.Op, "&&") + } + if ast.Tail == nil { + t.Fatalf("expected a non-nil Tail") + } + }, + }, + { + Name: "script_level_or", + Query: `{.a="x"} || {.b="y"}`, + Check: func(t *testing.T, ast *TraceQLScript) { + if ast.Op != "||" { + t.Errorf("Op = %q, want %q", ast.Op, "||") + } + }, + }, + { + Name: "structural_descendant", + Query: `{.a="x"} &>> {.b="y"}`, + Check: func(t *testing.T, ast *TraceQLScript) { + if ast.Op != "&>>" { + t.Errorf("Op = %q, want %q", ast.Op, "&>>") + } + }, + }, + { + Name: "structural_sibling", + Query: `{.a="x"} ~ {.b="y"}`, + Check: func(t *testing.T, ast *TraceQLScript) { + if ast.Op != "~" { + t.Errorf("Op = %q, want %q", ast.Op, "~") + } + }, + }, + { + Name: "paren_wrapped", + Query: `({.a="x"})`, + Check: func(t *testing.T, ast *TraceQLScript) { + if ast.ParenExpr == nil { + t.Fatalf("expected a non-nil ParenExpr") + } + }, + }, + { + // AttrSelectorExp's grammar offers a dedicated BoolLiteral + // alternative for "true"/"false", but it is never actually + // reached for a bare `{true}`: AttrSelector.Head is tried first + // in the alternation, and "true" already matches its Label + // field (Label_name matches any identifier, participle-keyword + // or not), so parsing commits to the Head branch first. This + // pin intentionally captures that real AST shape rather than + // the grammar's aspirational BoolLiteral field. + Name: "bool_literal", + Query: `{true}`, + Check: func(t *testing.T, ast *TraceQLScript) { + if ast.Head.AttrSelector.BoolLiteral != "" { + t.Errorf("BoolLiteral = %q, want empty (Head branch wins)", ast.Head.AttrSelector.BoolLiteral) + } + head := ast.Head.AttrSelector.Head + if head == nil || head.Label != "true" { + t.Errorf("Head = %+v, want Label \"true\"", head) + } + }, + }, + + { + Name: "resource_prefixed_regex_matcher", + Query: `{ resource.service.name =~ "ship.*" }`, + Check: func(t *testing.T, ast *TraceQLScript) { + head := ast.Head.AttrSelector.Head + if head == nil || head.Op != "=~" { + t.Fatalf("expected a =~ matcher, got %+v", head) + } + }, + }, + { + Name: "mixed_attr_and_intrinsic_conjunction", + Query: `{ resource.service.name = "checkout" && status = error }`, + Check: func(t *testing.T, ast *TraceQLScript) { + exp := ast.Head.AttrSelector + if exp.AndOr != "&&" || exp.Tail == nil || exp.Tail.Head == nil { + t.Fatalf("expected an &&-chained tail, got %+v", exp) + } + if exp.Tail.Head.Label != "status" { + t.Errorf("expected the tail's label to be the intrinsic 'status', got %q", exp.Tail.Head.Label) + } + }, + }, + { + Name: "aggregator_with_attr_arg", + Query: `{ status = ok } | avg(duration) > 0`, + Check: func(t *testing.T, ast *TraceQLScript) { + agg := ast.Head.Aggregator + if agg == nil || agg.Fn != "avg" { + t.Fatalf("expected an avg aggregator, got %+v", agg) + } + if agg.Attr != "duration" { + t.Errorf("expected Attr=duration, got %q", agg.Attr) + } + }, + }, + { + Name: "metrics_pipeline_with_by_grouping", + Query: `{ } | count_over_time() by (resource.service.name)`, + Check: func(t *testing.T, ast *TraceQLScript) { + mf := ast.Head.MetricsFn + if mf == nil || mf.Fn != "count_over_time" { + t.Fatalf("expected a count_over_time MetricsFn, got %+v", ast.Head) + } + if mf.By == nil { + t.Errorf("expected a non-nil by(...) clause") + } + }, + }, + { + Name: "nil_comparison", + Query: `{ kind != nil }`, + Check: func(t *testing.T, ast *TraceQLScript) { + head := ast.Head.AttrSelector.Head + if head == nil || head.Op != "!=" { + t.Fatalf("expected a != matcher, got %+v", head) + } + if head.Val.NilVal == "" { + t.Errorf("expected Val.NilVal to be set, got %+v", head.Val) + } + }, + }, + { + Name: "attribute_to_attribute_comparison", + Query: `{ span.child.index = resource.deployment.env }`, + Check: func(t *testing.T, ast *TraceQLScript) { + head := ast.Head.AttrSelector.Head + if head == nil { + t.Fatalf("expected a non-nil attribute selector head") + } + if head.Val.UnquotVal != "resource.deployment.env" { + t.Errorf("expected the RHS to be the unquoted attribute path, got %+v", head.Val) + } + }, + }, + { + Name: "numeric_intrinsic_comparison", + Query: `{ name > 3 }`, + Check: func(t *testing.T, ast *TraceQLScript) { + head := ast.Head.AttrSelector.Head + if head == nil || head.Op != ">" { + t.Fatalf("expected a > matcher, got %+v", head) + } + if head.Val.FVal != "3" { + t.Errorf("expected Val.FVal=3, got %+v", head.Val) + } + }, + }, + + // --- invalid queries: expected to fail to parse --- + { + Name: "unclosed_brace", + Query: `{.a="x"`, + WantErr: true, + }, + { + Name: "unterminated_string", + Query: `{.a="x}`, + WantErr: true, + }, + { + // Plain ">>" is not a valid script-level structural operator token in + // this grammar — only "&>>" (Descendant) is. See lexer_rules v2.go + // and TraceQLScript.Op's token alternation in model_v2.go. + Name: "bare_descendant_token_not_supported", + Query: `{.a="x"} >> {.b="y"}`, + WantErr: true, + }, + { + // A single "&" is not a defined lexer token (only "&&", "&>>" + // are) so this fails at the lexer, before grammar matching even + // starts. + Name: "lone_ampersand_not_a_token", + Query: `{.a="x" & .b="y"}`, + WantErr: true, + }, + { + Name: "unclosed_aggregator_call", + Query: `{.a="x"} | count(`, + WantErr: true, + }, + { + // Distinct failure class from "bare_descendant_token_not_supported" + // (">>"): a single ">" isn't a script-level structural operator + // either — only Descendant/NotDescendant/Ancestor/NotAncestor/ + // Sibling/And/Or are (see TraceQLScript.Op's alternation). + Name: "bare_gt_not_a_structural_operator", + Query: `{.a="x"} > {.b="y"}`, + WantErr: true, + }, + { + // "!(" immediately preceding an expression fails at the lexer, + // same failure layer as "lone_ampersand_not_a_token" but a + // different offending token. + Name: "boolean_negation_not_supported", + Query: `{ !(kind = client) }`, + WantErr: true, + }, + }) +}