diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml new file mode 100644 index 000000000..7fb14a3da --- /dev/null +++ b/.github/workflows/fuzz.yml @@ -0,0 +1,53 @@ +name: Parser fuzz + +# Exploratory only: started by hand from the Actions tab, never a merge gate. +# A crasher fails the run and is uploaded as an artifact; commit it under the +# target's testdata/fuzz/FuzzParse directory so it replays as a plain test. +on: + workflow_dispatch: + inputs: + head: + description: Query head to fuzz + type: choice + options: + - promql + - logql + - traceql + duration: + description: How long to fuzz, as a Go duration (e.g. 60s, 10m) + type: string + default: 60s + +permissions: + contents: read + +jobs: + fuzz: + 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: Fuzz + env: + FUZZ_HEAD: ${{ inputs.head }} + FUZZ_DURATION: ${{ inputs.duration }} + run: | + # -fuzztime takes a duration such as 60s or 10m, or an iteration count such as 1000x. + if ! [[ "$FUZZ_DURATION" =~ ^[0-9]+(ns|us|ms|s|m|h|x)$ ]]; then + echo "invalid duration: $FUZZ_DURATION" >&2 + exit 1 + fi + make fuzz HEAD="$FUZZ_HEAD" DURATION="$FUZZ_DURATION" + + - name: Upload crashers + if: failure() + uses: actions/upload-artifact@v4 + with: + name: fuzz-crashers-${{ inputs.head }} + path: reader/${{ inputs.head }}/${{ inputs.head }}_parser/testdata/fuzz/ + if-no-files-found: ignore diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index 82eaeb747..8fa8ccc6c 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -4,6 +4,11 @@ on: pull_request: branches: [ "master" ] +permissions: + contents: read + +# Every lane runs through a Makefile recipe, so CI and local runs are the same +# commands. jobs: build: @@ -17,13 +22,29 @@ jobs: go-version-file: go.mod - name: gofmt - run: test -z "$(gofmt -l .)" || { gofmt -l .; exit 1; } + run: make fmt-check - name: Build Gigapipe - run: | - go mod tidy - CGO_ENABLED=0 go build -ldflags="-extldflags=-static" -o gigapipe cmd/gigapipe/main.go + run: make build - name: Unit tests - run: go test ./... + run: make test-unit + + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + # --new-from-rev needs the commit it compares against in the history. + fetch-depth: 0 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + # Only new issues fail the job (since the pull request's base commit, or + # since the previous commit on a push), so adoption doesn't require + # cleaning up pre-existing findings first. + - name: golangci-lint + run: make lint LINT_NEW_FROM_REV=${{ github.event.pull_request.base.sha || github.event.before }} diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..12cd2168f --- /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. +# - 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. CI runs `make lint`, which reports only issues new since the pull +# request's base commit (--new-from-rev), 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 7f0c1f0c3..bdb7ff6bb 100644 --- a/Makefile +++ b/Makefile @@ -10,9 +10,53 @@ E2E_TESTS_DIR ?= ./deps/gigapipe-tests # 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 + +# Only issues introduced since this revision are reported. CI passes the pull +# request's base commit. +LINT_NEW_FROM_REV ?= origin/master + +.PHONY: docker e2e-deps e2e-build e2e-test e2e-cleanup e2e-full e2e-ci \ + fmt-check build test-unit lint fuzz + docker: docker build -f scripts/deploy/docker/Dockerfile -t gigapipe . +# Fail if any Go file is not gofmt-formatted, listing the offending files. +fmt-check: + @test -z "$$(gofmt -l .)" || { gofmt -l .; exit 1; } + +# 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 LINT_NEW_FROM_REV so this doesn't fail on pre-existing +# repo-wide debt. golangci-lint is deliberately unpinned: @latest keeps up with +# new Go releases without a version to bump by hand, and the linters it runs +# are listed explicitly in .golangci.yml. +lint: + go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest run --new-from-rev=$(LINT_NEW_FROM_REV) + +# 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 $(E2E_TESTS_DIR) ]; then git clone $(E2E_TESTS_REPO) $(E2E_TESTS_DIR); fi cd $(E2E_TESTS_DIR) && git pull && git checkout main && git pull; diff --git a/docs/contributing.md b/docs/contributing.md index 09d9b904c..87631bbbb 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -69,6 +69,22 @@ For end-to-end tests: make e2e-full ``` +The Makefile is the entry point for every lane CI runs (CI calls these same +recipes), plus parser-fuzz helpers for the query transpilers: + +```bash +make fmt-check # fail if any Go file is not gofmt-formatted +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 fuzz HEAD=promql DURATION=60s # run the native Go parser fuzz target for a query head +``` + +`make lint` builds the latest golangci-lint release, so nothing needs to be +installed first. If your fork's `origin/master` is behind, +compare against another revision with `make lint LINT_NEW_FROM_REV=upstream/master`. +Fuzzing can also be started from the "Parser fuzz" workflow in the Actions tab. + ## Submitting a Pull Request 1. Create a branch: diff --git a/reader/logql/logql_parser/fuzz_test.go b/reader/logql/logql_parser/fuzz_test.go new file mode 100644 index 000000000..f1b139d46 --- /dev/null +++ b/reader/logql/logql_parser/fuzz_test.go @@ -0,0 +1,152 @@ +package logql_parser + +import "testing" + +// FuzzParse asserts that Parse never panics on arbitrary input, and that any +// query it accepts round-trips: rendering it, parsing the rendering and +// rendering that again gives the same text. It makes no claim about which +// queries should be accepted. +// +// The seed corpus below (and any inputs under testdata/fuzz/FuzzParse) runs +// as an ordinary test under `go test ./...`, so CI checks it on every change. +// Fuzzing beyond the seeds is not part of CI: it runs with +// `make fuzz HEAD=logql DURATION=`, locally or from the manually +// dispatched "Parser fuzz" workflow. +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 — useful fuzz input either way, since rejected + // input must still not 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("panicked on %q: %v", query, r) + } + }() + script, err := Parse(query) + if err != nil { + return + } + rendered := script.String() + again, err := Parse(rendered) + if err != nil { + t.Fatalf("%q renders as %q, which does not parse: %v", query, rendered, err) + } + if got := again.String(); got != rendered { + t.Fatalf("%q renders as %q, which renders as %q", query, rendered, got) + } + }) +} diff --git a/reader/logql/logql_parser/testdata/fuzz/FuzzParse/2fc52079c62c4c93 b/reader/logql/logql_parser/testdata/fuzz/FuzzParse/2fc52079c62c4c93 new file mode 100644 index 000000000..f483a8431 --- /dev/null +++ b/reader/logql/logql_parser/testdata/fuzz/FuzzParse/2fc52079c62c4c93 @@ -0,0 +1,2 @@ +go test fuzz v1 +string("{A=\"\"}|json|logfmt|drop A000|A=\"\"or") diff --git a/reader/promql/promql_parser/fuzz_test.go b/reader/promql/promql_parser/fuzz_test.go new file mode 100644 index 000000000..86ba56442 --- /dev/null +++ b/reader/promql/promql_parser/fuzz_test.go @@ -0,0 +1,174 @@ +package promql_parser + +import "testing" + +// FuzzParse asserts that Parse never panics on arbitrary input, and that any +// query it accepts round-trips: rendering it, parsing the rendering and +// rendering that again gives the same text. It makes no claim about which +// queries should be accepted. +// +// The seed corpus below (and any inputs under testdata/fuzz/FuzzParse) runs +// as an ordinary test under `go test ./...`, so CI checks it on every change. +// Fuzzing beyond the seeds is not part of CI: it runs with +// `make fuzz HEAD=promql DURATION=`, locally or from the manually +// dispatched "Parser fuzz" workflow. +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("panicked on %q: %v", query, r) + } + }() + script, err := Parse(query) + if err != nil { + return + } + rendered := script.Expr.String() + again, err := Parse(rendered) + if err != nil { + t.Fatalf("%q renders as %q, which does not parse: %v", query, rendered, err) + } + if got := again.Expr.String(); got != rendered { + t.Fatalf("%q renders as %q, which renders as %q", query, rendered, got) + } + }) +} 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_transpiler/determinism_test.go b/reader/promql/promql_transpiler/determinism_test.go new file mode 100644 index 000000000..16bcf629f --- /dev/null +++ b/reader/promql/promql_transpiler/determinism_test.go @@ -0,0 +1,81 @@ +package promql_transpiler + +import ( + "sort" + "strings" + "testing" + "time" + + "github.com/metrico/qryn/v5/reader/logql/logql_transpiler/shared" + "github.com/metrico/qryn/v5/reader/promql/promql_parser" + sql "github.com/metrico/qryn/v5/reader/utils/sql_select" +) + +// TestTranspileIsDeterministic guards the rand.Int64() -> per-transpile-counter +// fix for pushdown-substitute naming: two independent Parse+TranspileExpressionV2 +// passes over the same query must produce a byte-identical residual expression +// and byte-identical SQL for every substitute. Before the fix, each pass drew a +// fresh random name, so this failed intermittently. +func TestTranspileIsDeterministic(t *testing.T) { + queries := []string{ + `sum by (job) (rate(http_requests_total{job="myjob"}[5m]))`, + `sum(rate(a[5m])) / sum(rate(b[5m]))`, + } + for _, query := range queries { + t.Run(query, func(t *testing.T) { + first := transpileForDeterminism(t, query) + second := transpileForDeterminism(t, query) + if first != second { + t.Fatalf("transpile is not deterministic:\n first: %s\nsecond: %s", first, second) + } + }) + } +} + +// transpileForDeterminism returns the residual expression followed by each +// substitute's name and SQL, in name order. +func transpileForDeterminism(t *testing.T, query string) 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) + } + if len(expr.Substitutes) == 0 { + t.Fatalf("%s: no substitutes, so the test would not exercise substitute naming", query) + } + + from := time.Unix(1700000000, 0) + names := make([]string, 0, len(expr.Substitutes)) + for name := range expr.Substitutes { + names = append(names, name) + } + sort.Strings(names) + + var out strings.Builder + out.WriteString(expr.Expr.String()) + for _, name := range names { + req, err := expr.Substitutes[name].Request.Process(&shared.PlannerContext{ + From: from, + To: from.Add(time.Hour), + Step: 15 * time.Second, + TimeSeriesGinTableName: "time_series_gin", + SamplesTableName: "samples_v3", + TimeSeriesTableName: "time_series", + TimeSeriesDistTableName: "time_series", + Metrics15sTableName: "metrics_15s", + }) + if err != nil { + t.Fatal(err) + } + str, err := req.String(sql.DefaultCtx()) + if err != nil { + t.Fatal(err) + } + out.WriteString("\n" + name + ": " + str) + } + return out.String() +} diff --git a/reader/promql/promql_transpiler/optimizer/vector_agg.go b/reader/promql/promql_transpiler/optimizer/vector_agg.go index 6c3ad7ffa..be33ff457 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" @@ -77,7 +74,7 @@ func (v *Aggregate) aggregate(fn string) prom_parser.Expr { p.Main = planner.NewInstantVectorPlanner(streamSelect(v.selector), taggedGrid(v.selector)) } - 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 60bb9f436..11518b6cb 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/shared" @@ -96,7 +94,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..5c47c54a6 --- /dev/null +++ b/reader/traceql/traceql_parser/fuzz_test.go @@ -0,0 +1,121 @@ +package traceql_parser + +import "testing" + +// FuzzParse asserts that Parse never panics on arbitrary input, and that any +// query it accepts round-trips: rendering it, parsing the rendering and +// rendering that again gives the same text. It makes no claim about which +// queries should be accepted. +// +// The seed corpus below (and any inputs under testdata/fuzz/FuzzParse) runs +// as an ordinary test under `go test ./...`, so CI checks it on every change. +// Fuzzing beyond the seeds is not part of CI: it runs with +// `make fuzz HEAD=traceql DURATION=`, locally or from the manually +// dispatched "Parser fuzz" workflow. +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 — useful fuzz input either way, since rejected + // input must still not 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("panicked on %q: %v", query, r) + } + }() + script, err := Parse(query) + if err != nil { + return + } + rendered := script.String() + again, err := Parse(rendered) + if err != nil { + t.Fatalf("%q renders as %q, which does not parse: %v", query, rendered, err) + } + if got := again.String(); got != rendered { + t.Fatalf("%q renders as %q, which renders as %q", query, rendered, got) + } + }) +}